v4l2: Remove already included headers
[vlc.git] / modules / access / v4l2.c
1 /*****************************************************************************
2  * v4l2.c : Video4Linux2 input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2002-2007 the VideoLAN team
5  * $Id$
6  *
7  * Author: Benjamin Pracht <bigben at videolan dot org>
8  *         Richard Hosking <richard at hovis dot net>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /* 
26  * Sections based on the reference V4L2 capture example at
27  * http://v4l2spec.bytesex.org/spec/capture-example.html
28  */
29  
30 /*
31  * TODO: No mjpeg support yet. 
32  * TODO: mmap untested. 
33  * TODO: Tuner partial implementation.
34  * TODO: Alsa input support?
35  */
36
37 /*****************************************************************************
38  * Preamble
39  *****************************************************************************/
40
41 #include <vlc/vlc.h>
42 #include <vlc_access.h>
43 #include <vlc_demux.h>
44 #include <vlc_input.h>
45 #include <vlc_vout.h>
46
47 #include <fcntl.h>
48 #include <unistd.h>
49 #include <sys/ioctl.h>
50 #include <sys/mman.h>
51
52 #include <linux/videodev2.h>
53
54 #include <sys/soundcard.h>
55
56 /*****************************************************************************
57  * Module descriptior
58  *****************************************************************************/
59
60 static int  Open ( vlc_object_t * );
61 static void Close( vlc_object_t * );
62
63 #define DEV_TEXT N_("Device name")
64 #define DEV_LONGTEXT N_( \
65     "Name of the device to use. " \
66     "If you don't specify anything, /dev/video0 will be used.")
67 #define ADEV_TEXT N_("Audio device name")
68 #define ADEV_LONGTEXT N_( \
69     "Name of the audio device to use. " \
70     "If you don't specify anything, no audio device will be used.")
71 #define STANDARD_TEXT N_( "Standard" )
72 #define STANDARD_LONGTEXT N_( \
73     "Video standard (Default, SECAM, PAL, or NTSC)." )
74 #define CHROMA_TEXT N_("Video input chroma format")
75 #define CHROMA_LONGTEXT N_( \
76     "Force the Video4Linux2 video device to use a specific chroma format " \
77     "(eg. I420, RV24, etc.)")
78 #define INPUT_TEXT N_( "Input" )
79 #define INPUT_LONGTEXT N_( \
80     "Input of the card to use (Usually, 0 = tuner, " \
81     "1 = composite, 2 = svideo)." )
82 #define IOMETHOD_TEXT N_( "IO Method" )
83 #define IOMETHOD_LONGTEXT N_( \
84     "IO Method (READ, MMAP, USERPTR)." )
85 #define FPS_TEXT N_( "Framerate" )
86 #define FPS_LONGTEXT N_( "Framerate to capture, if applicable " \
87     "(-1 for autodetect)." )
88 #define STEREO_TEXT N_( "Stereo" )
89 #define STEREO_LONGTEXT N_( \
90     "Capture the audio stream in stereo." )
91 #define SAMPLERATE_TEXT N_( "Samplerate" )
92 #define SAMPLERATE_LONGTEXT N_( \
93     "Samplerate of the captured audio stream, in Hz (eg: 11025, 22050, 44100, 48000)" )    
94 #define CACHING_TEXT N_("Caching value in ms")
95 #define CACHING_LONGTEXT N_( \
96     "Caching value for V4L2 captures. This " \
97     "value should be set in milliseconds." )
98     
99 typedef enum {
100     IO_METHOD_READ,
101     IO_METHOD_MMAP,
102     IO_METHOD_USERPTR,
103 } io_method;
104
105 static int i_standards_list[] =
106     { V4L2_STD_UNKNOWN, V4L2_STD_SECAM, V4L2_STD_PAL, V4L2_STD_NTSC };
107 static const char *psz_standards_list_text[] =
108     { N_("Default"), N_("SECAM"), N_("PAL"),  N_("NTSC") };
109     
110 static int i_iomethod_list[] =
111     { IO_METHOD_READ, IO_METHOD_MMAP, IO_METHOD_USERPTR };
112 static const char *psz_iomethod_list_text[] =
113     { N_("READ"), N_("MMAP"),  N_("USERPTR") };
114
115 vlc_module_begin();
116     set_shortname( _("Video4Linux2") );
117     set_description( _("Video4Linux2 input") );
118     set_category( CAT_INPUT );
119     set_subcategory( SUBCAT_INPUT_ACCESS );
120
121     add_string( "v4l2-dev", "/dev/video0", 0, DEV_TEXT, DEV_LONGTEXT,
122                 VLC_FALSE );
123     add_string( "v4l2-adev", "/dev/dsp", 0, DEV_TEXT, DEV_LONGTEXT,
124                 VLC_FALSE );
125     add_integer( "v4l2-standard", 0, NULL, STANDARD_TEXT, STANDARD_LONGTEXT,
126                 VLC_FALSE );
127         change_integer_list( i_standards_list, psz_standards_list_text, 0 );
128     add_string( "v4l2-chroma", NULL, NULL, CHROMA_TEXT, CHROMA_LONGTEXT,
129                 VLC_TRUE );
130     add_integer( "v4l2-input", 0, NULL, INPUT_TEXT, INPUT_LONGTEXT,
131                 VLC_TRUE );
132     add_integer( "v4l2-io", IO_METHOD_MMAP, NULL, IOMETHOD_TEXT,
133                  IOMETHOD_LONGTEXT, VLC_FALSE );
134         change_integer_list( i_iomethod_list, psz_iomethod_list_text, 0 );
135     add_float( "v4l2-fps", 0, NULL, FPS_TEXT, FPS_LONGTEXT, VLC_TRUE );
136     add_bool( "v4l2-stereo", VLC_TRUE, NULL, STEREO_TEXT, STEREO_LONGTEXT,
137                 VLC_TRUE );
138     add_integer( "v4l2-samplerate", 48000, NULL, SAMPLERATE_TEXT,
139                 SAMPLERATE_LONGTEXT, VLC_TRUE );
140     add_integer( "v4l2-caching", DEFAULT_PTS_DELAY / 1000, NULL,
141                 CACHING_TEXT, CACHING_LONGTEXT, VLC_TRUE );
142
143     add_shortcut( "v4l2" );
144     set_capability( "access_demux", 10 );
145     set_callbacks( Open, Close );
146 vlc_module_end();
147
148 /*****************************************************************************
149  * Access: local prototypes
150  *****************************************************************************/
151
152 static void ParseMRL( demux_t * );
153
154 static int Control( demux_t *, int, va_list );
155
156 static int Demux( demux_t * );
157 static block_t* GrabVideo( demux_t *p_demux );
158 static block_t* ProcessVideoFrame( demux_t *p_demux, uint8_t *p_frame );
159 static block_t* GrabAudio( demux_t *p_demux );
160
161 vlc_bool_t IsChromaSupported( demux_t *p_demux, unsigned int i_v4l2 );
162 unsigned int GetChromaFromFourcc( char *psz_fourcc );
163
164 static int OpenVideoDev( demux_t *, char *psz_device );
165 static int OpenAudioDev( demux_t *, char *psz_device );
166 static vlc_bool_t ProbeVideoDev( demux_t *, char *psz_device );
167 static vlc_bool_t ProbeAudioDev( demux_t *, char *psz_device );
168
169 static struct
170 {
171     unsigned int i_v4l2;
172     int i_fourcc;
173 } v4l2chroma_to_fourcc[] =
174 {
175     { V4L2_PIX_FMT_GREY, VLC_FOURCC( 'G', 'R', 'E', 'Y' ) },
176     { V4L2_PIX_FMT_HI240, VLC_FOURCC( 'I', '2', '4', '0' ) },
177     { V4L2_PIX_FMT_RGB565, VLC_FOURCC( 'R', 'V', '1', '6' ) },
178     { V4L2_PIX_FMT_RGB555, VLC_FOURCC( 'R', 'V', '1', '5' ) },
179     { V4L2_PIX_FMT_BGR24, VLC_FOURCC( 'R', 'V', '2', '4' ) },
180     { V4L2_PIX_FMT_BGR32, VLC_FOURCC( 'R', 'V', '3', '2' ) },
181     { V4L2_PIX_FMT_YUYV, VLC_FOURCC( 'Y', 'U', 'Y', '2' ) },
182     { V4L2_PIX_FMT_YUYV, VLC_FOURCC( 'Y', 'U', 'Y', 'V' ) },
183     { V4L2_PIX_FMT_UYVY, VLC_FOURCC( 'U', 'Y', 'V', 'Y' ) },
184     { V4L2_PIX_FMT_Y41P, VLC_FOURCC( 'I', '4', '1', 'N' ) },
185     { V4L2_PIX_FMT_YUV422P, VLC_FOURCC( 'I', '4', '2', '2' ) },
186     { V4L2_PIX_FMT_YVU420, VLC_FOURCC( 'I', '4', '2', '0' ) },
187     { V4L2_PIX_FMT_YUV411P, VLC_FOURCC( 'I', '4', '1', '1' ) },
188     { V4L2_PIX_FMT_YUV410, VLC_FOURCC( 'I', '4', '1', '0' ) },
189     { 0, 0 }
190 };
191
192 struct buffer_t 
193 {
194     void *  start;
195     size_t  length;
196 };
197
198 struct demux_sys_t
199 {
200     char *psz_device;  /* Main device from MRL, can be video or audio */
201     
202     char *psz_vdev;
203     int  i_fd_video;
204
205     char *psz_adev;
206     int  i_fd_audio;
207     
208     /* Video */
209     io_method io;
210     
211     int i_pts;
212
213     struct v4l2_capability dev_cap;
214
215     int i_input;
216     struct v4l2_input *p_inputs;
217     int i_selected_input;
218     
219     int i_standard;
220     struct v4l2_standard *p_standards;
221     v4l2_std_id i_selected_standard_id;
222
223     int i_audio;
224     /* V4L2 devices cannot have more than 32 audio inputs */
225     struct v4l2_audio p_audios[32];
226
227     int i_tuner;
228     struct v4l2_tuner *p_tuners;
229
230     int i_codec;
231     struct v4l2_fmtdesc *p_codecs;
232     
233     struct buffer_t *p_buffers;
234     unsigned int i_nbuffers;
235     
236     int i_width;
237     int i_height;
238     float f_fps;            /* <= 0.0 mean to grab at full rate */
239     mtime_t i_video_pts;    /* only used when f_fps > 0 */
240     int i_fourcc;
241     
242     picture_t pic;
243     int i_video_frame_size;
244     
245     es_out_id_t *p_es_video;
246     
247     /* Audio */
248     int i_sample_rate;
249     vlc_bool_t b_stereo;
250     int i_audio_max_frame_size;
251     block_t *p_block_audio;
252     es_out_id_t *p_es_audio;
253 };
254
255 /*****************************************************************************
256  * Open: opens v4l2 device
257  *****************************************************************************
258  *
259  * url: <video device>::::
260  *
261  *****************************************************************************/
262 static int Open( vlc_object_t *p_this )
263 {
264     demux_t     *p_demux = (demux_t*)p_this;
265     demux_sys_t *p_sys;
266     vlc_value_t val;
267     char *psz;
268     
269     /* Only when selected */
270     if( *p_demux->psz_access == '\0' ) return VLC_EGENERIC;
271
272     /* Set up p_demux */
273     p_demux->pf_control = Control;
274     p_demux->pf_demux = Demux;
275     p_demux->info.i_update = 0;
276     p_demux->info.i_title = 0;
277     p_demux->info.i_seekpoint = 0;
278
279     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
280     if( p_sys == NULL ) return VLC_ENOMEM;
281     memset( p_sys, 0, sizeof( demux_sys_t ) );
282     
283     p_sys->i_video_pts = -1;
284     
285     var_Create( p_demux, "v4l2-standard", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
286     var_Get( p_demux, "v4l2-standard", &val );
287     p_sys->i_selected_standard_id = i_standards_list[val.i_int];
288     
289     p_sys->i_selected_input = var_CreateGetInteger( p_demux, "v4l2-input" );
290     
291     p_sys->io = var_CreateGetInteger( p_demux, "v4l2-io" );
292     
293     var_Create( p_demux, "v4l2-fps", VLC_VAR_FLOAT | VLC_VAR_DOINHERIT );
294     var_Get( p_demux, "v4l2-fps", &val );
295     p_sys->f_fps = val.f_float;
296               
297     var_Create( p_demux, "v4l2-samplerate", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
298     var_Get( p_demux, "v4l2-samplerate", &val );
299     p_sys->i_sample_rate = val.i_int;
300     
301     psz = var_CreateGetString( p_demux, "v4l2-chroma" );
302     p_sys->i_fourcc = GetChromaFromFourcc( psz );
303     free( psz );    
304     
305     var_Create( p_demux, "v4l2-stereo", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
306     var_Get( p_demux, "v4l2-stereo", &val );
307     p_sys->b_stereo = val.b_bool;
308
309     p_sys->i_pts = var_CreateGetInteger( p_demux, "v4l2-caching" );
310
311     p_sys->psz_device = p_sys->psz_vdev = p_sys->psz_adev = NULL;
312     p_sys->i_fd_video = -1;
313     p_sys->i_fd_audio = -1;
314     
315     p_sys->p_es_video = p_sys->p_es_audio = 0;
316     p_sys->p_block_audio = 0;
317
318     ParseMRL( p_demux );
319     
320     /* Find main device (video or audio) */
321     if( p_sys->psz_device && *p_sys->psz_device )
322     {
323         msg_Dbg( p_demux, "main device='%s'", p_sys->psz_device );
324
325         /* Try to open as video device */
326         msg_Dbg( p_demux, "trying device '%s' as video", p_sys->psz_device );
327         if( ProbeVideoDev( p_demux, p_sys->psz_device ) )
328         {
329             msg_Dbg( p_demux, "'%s' is a video device", p_sys->psz_device );
330             /* Device was a video device */            
331             if( p_sys->psz_vdev ) free( p_sys->psz_vdev );
332             p_sys->psz_vdev = p_sys->psz_device;
333             p_sys->psz_device = NULL;
334             p_sys->i_fd_video = OpenVideoDev( p_demux, p_sys->psz_vdev );
335             if( p_sys->i_fd_video < 0 )
336             {
337                 Close( p_this );
338                 return VLC_EGENERIC;            
339             }
340         }
341         else
342         {
343             /* Try to open as audio device */     
344             msg_Dbg( p_demux, "trying device '%s' as audio", p_sys->psz_device );
345             if( ProbeAudioDev( p_demux, p_sys->psz_device ) )
346             {
347                 msg_Dbg( p_demux, "'%s' is an audio device", p_sys->psz_device );
348                 /* Device was an audio device */
349                 if( p_sys->psz_adev ) free( p_sys->psz_adev );
350                 p_sys->psz_adev = p_sys->psz_device;
351                 p_sys->psz_device = NULL;
352                 p_sys->i_fd_audio = OpenAudioDev( p_demux, p_sys->psz_adev );
353                 if( p_sys->i_fd_audio < 0 )
354                 {
355                     Close( p_this );
356                     return VLC_EGENERIC;            
357                 }
358             }
359         }
360     }
361
362     /* If no device opened, only continue if the access was forced */
363     if( p_sys->i_fd_video < 0 && p_sys->i_fd_audio < 0 )
364     {
365         if( strcmp( p_demux->psz_access, "v4l2" ) )
366         {
367             Close( p_this );
368             return VLC_EGENERIC;
369         }
370     }
371
372     /* Find video device */
373     if( p_sys->i_fd_video < 0 )
374     {
375         if( !p_sys->psz_vdev || !*p_sys->psz_vdev )
376         {
377             if( p_sys->psz_vdev ) free( p_sys->psz_vdev );
378             p_sys->psz_vdev = var_CreateGetString( p_demux, "v4l2-dev" );;
379         }
380
381         if( p_sys->psz_vdev && *p_sys->psz_vdev && ProbeVideoDev( p_demux, p_sys->psz_vdev ) )
382         {
383             p_sys->i_fd_video = OpenVideoDev( p_demux, p_sys->psz_vdev );
384         }
385     }
386
387     /* Find audio device */
388     if( p_sys->i_fd_audio < 0 )
389     {
390         if( !p_sys->psz_adev || !*p_sys->psz_adev )
391         {
392             if( p_sys->psz_adev ) free( p_sys->psz_adev );
393             p_sys->psz_adev = var_CreateGetString( p_demux, "v4l2-adev" );;
394         }
395
396         if( p_sys->psz_adev && *p_sys->psz_adev && ProbeAudioDev( p_demux, p_sys->psz_adev ) )
397         {
398             p_sys->i_fd_audio = OpenAudioDev( p_demux, p_sys->psz_adev );
399         }
400     }
401
402     if( p_sys->i_fd_video < 0 && p_sys->i_fd_audio < 0 )
403     {
404         Close( p_this );
405         return VLC_EGENERIC;
406     }
407
408     return VLC_SUCCESS;
409 }
410
411 /*****************************************************************************
412  * ParseMRL: parse the options contained in the MRL
413  *****************************************************************************/
414 static void ParseMRL( demux_t *p_demux )
415 {
416     demux_sys_t *p_sys = p_demux->p_sys;
417
418     char *psz_dup = strdup( p_demux->psz_path );
419     char *psz_parser = psz_dup;
420
421     while( *psz_parser && *psz_parser != ':' )
422     {
423         psz_parser++;
424     }
425
426     if( *psz_parser == ':' )
427     {
428         /* read options */
429         for( ;; )
430         {
431             *psz_parser++ = '\0';
432             
433             if( !strncmp( psz_parser, "adev=", strlen( "adev=" ) ) )
434             {
435                 int  i_len;
436
437                 psz_parser += strlen( "adev=" );
438                 if( strchr( psz_parser, ':' ) )
439                 {
440                     i_len = strchr( psz_parser, ':' ) - psz_parser;
441                 }
442                 else
443                 {
444                     i_len = strlen( psz_parser );
445                 }
446
447                 p_sys->psz_adev = strndup( psz_parser, i_len );
448
449                 psz_parser += i_len; 
450             }
451             else if( !strncmp( psz_parser, "standard=", strlen( "standard=" ) ) )
452             {
453                 psz_parser += strlen( "standard=" );
454                 if( !strncmp( psz_parser, "pal", strlen( "pal" ) ) )
455                 {
456                     p_sys->i_selected_standard_id = V4L2_STD_PAL;
457                     psz_parser += strlen( "pal" );
458                 }
459                 else if( !strncmp( psz_parser, "ntsc", strlen( "ntsc" ) ) )
460                 {
461                     p_sys->i_selected_standard_id = V4L2_STD_NTSC;
462                     psz_parser += strlen( "ntsc" );
463                 }
464                 else if( !strncmp( psz_parser, "secam", strlen( "secam" ) ) )
465                 {
466                     p_sys->i_selected_standard_id = V4L2_STD_SECAM;
467                     psz_parser += strlen( "secam" );
468                 }
469                 else if( !strncmp( psz_parser, "default", strlen( "default" ) ) )
470                 {
471                     p_sys->i_selected_standard_id = V4L2_STD_UNKNOWN;
472                     psz_parser += strlen( "default" );
473                 }
474                 else
475                 {
476                     p_sys->i_selected_standard_id = i_standards_list[strtol( psz_parser, &psz_parser, 0 )];
477                 }
478             }
479             else if( !strncmp( psz_parser, "chroma=", strlen( "chroma=" ) ) )
480             {
481                 int  i_len;
482
483                 psz_parser += strlen( "chroma=" );
484                 if( strchr( psz_parser, ':' ) )
485                 {
486                     i_len = strchr( psz_parser, ':' ) - psz_parser;
487                 }
488                 else
489                 {
490                     i_len = strlen( psz_parser );
491                 }
492
493                 char* chroma = strndup( psz_parser, i_len );
494                 p_sys->i_fourcc = GetChromaFromFourcc( chroma );
495                 free( chroma );                
496
497                 psz_parser += i_len; 
498             }
499             else if( !strncmp( psz_parser, "input=", strlen( "input=" ) ) )
500             {
501                 p_sys->i_selected_input = strtol( psz_parser + strlen( "input=" ),
502                                        &psz_parser, 0 );
503             }            
504             else if( !strncmp( psz_parser, "fps=", strlen( "fps=" ) ) )
505             {
506                 p_sys->f_fps = strtof( psz_parser + strlen( "fps=" ),
507                                        &psz_parser );
508             }
509             else if( !strncmp( psz_parser, "io=", strlen( "io=" ) ) )
510             {
511                 psz_parser += strlen( "io=" );
512                 if( !strncmp( psz_parser, "read", strlen( "read" ) ) )
513                 {
514                     p_sys->io = IO_METHOD_READ;
515                     psz_parser += strlen( "read" );
516                 }
517                 else if( !strncmp( psz_parser, "mmap", strlen( "mmap" ) ) )
518                 {
519                     p_sys->io = IO_METHOD_MMAP;
520                     psz_parser += strlen( "mmap" );
521                 }
522                 else if( !strncmp( psz_parser, "userptr", strlen( "userptr" ) ) )
523                 {
524                     p_sys->io = IO_METHOD_USERPTR;
525                     psz_parser += strlen( "userptr" );
526                 }
527                 else
528                 {
529                     p_sys->io = strtol( psz_parser, &psz_parser, 0 );
530                 }
531             }
532             else if( !strncmp( psz_parser, "samplerate=",
533                                strlen( "samplerate=" ) ) )
534             {
535                 p_sys->i_sample_rate =
536                     strtol( psz_parser + strlen( "samplerate=" ),
537                             &psz_parser, 0 );
538             }
539             else if( !strncmp( psz_parser, "stereo", strlen( "stereo" ) ) )
540             {
541                 psz_parser += strlen( "stereo" );
542                 p_sys->b_stereo = VLC_TRUE;
543             }
544             else if( !strncmp( psz_parser, "mono", strlen( "mono" ) ) )
545             {
546                 psz_parser += strlen( "mono" );
547                 p_sys->b_stereo = VLC_FALSE;
548             }
549             else if( !strncmp( psz_parser, "caching=", strlen( "caching=" ) ) )
550             {
551                 p_sys->i_pts = strtol( psz_parser + strlen( "caching=" ),
552                                        &psz_parser, DEFAULT_PTS_DELAY / 1000 );
553             }
554             else
555             {
556                 msg_Warn( p_demux, "unknown option" );
557             }
558
559             while( *psz_parser && *psz_parser != ':' )
560             {
561                 psz_parser++;
562             }
563
564             if( *psz_parser == '\0' )
565             {
566                 break;
567             }
568         }
569     }
570
571     /* Main device */
572     if( *psz_dup )
573     {
574         p_sys->psz_device = strdup( psz_dup );
575     }
576     if( psz_dup ) free( psz_dup );
577 }
578
579 /*****************************************************************************
580  * Close: close device, free resources
581  *****************************************************************************/
582 static void Close( vlc_object_t *p_this )
583 {
584     demux_t     *p_demux = (demux_t *)p_this;
585     demux_sys_t *p_sys   = p_demux->p_sys;    
586     struct v4l2_buffer buf;
587     enum v4l2_buf_type buf_type;
588     unsigned int i;
589     
590     /* Stop video capture */
591     if( p_sys->i_fd_video >= 0 ) 
592     {
593         switch( p_sys->io )
594         {
595         case IO_METHOD_READ:
596             /* Nothing to do */
597             break;
598             
599         case IO_METHOD_MMAP:
600         case IO_METHOD_USERPTR:    
601             /* Some drivers 'hang' internally if this is not done before streamoff */               
602             for( unsigned int i = 0; i < p_sys->i_nbuffers; i++ )
603             {
604                 memset( &buf, 0, sizeof(buf) );
605                 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
606                 buf.memory = V4L2_MEMORY_USERPTR;
607                 ioctl( p_sys->i_fd_video, VIDIOC_DQBUF, &buf ); /* ignore result */
608             }
609                 
610             buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;                        
611             if( ioctl( p_sys->i_fd_video, VIDIOC_STREAMOFF, &buf_type ) < 0 ) {
612                 msg_Err( p_demux, "VIDIOC_STREAMOFF failed" );
613             }    
614             
615             break;        
616         }
617     }
618
619     /* Close */    
620     if( p_sys->i_fd_video >= 0 ) close( p_sys->i_fd_video );
621     if( p_sys->i_fd_audio >= 0 ) close( p_sys->i_fd_audio );
622
623     /* Free Video Buffers */
624     if( p_sys->p_buffers ) {
625         switch( p_sys->io )
626         {
627         case IO_METHOD_READ:
628             free( p_sys->p_buffers[0].start );
629             break;
630             
631         case IO_METHOD_MMAP:
632             for( i = 0; i < p_sys->i_nbuffers; ++i ) 
633             {
634                 if( munmap( p_sys->p_buffers[i].start, p_sys->p_buffers[i].length ) )
635                 {
636                     msg_Err( p_demux, "munmap failed" );
637                 }
638             }    
639             break;
640             
641         case IO_METHOD_USERPTR:        
642             for( i = 0; i < p_sys->i_nbuffers; ++i ) 
643             {
644                free( p_sys->p_buffers[i].start );
645             }        
646             break;        
647         }
648         free( p_sys->p_buffers );
649     }
650
651     if( p_sys->p_block_audio ) block_Release( p_sys->p_block_audio );
652     if( p_sys->psz_device ) free( p_sys->psz_device );
653     if( p_sys->psz_vdev ) free( p_sys->psz_vdev );
654     if( p_sys->psz_adev ) free( p_sys->psz_adev );
655     if( p_sys->p_standards ) free( p_sys->p_standards );
656     if( p_sys->p_inputs ) free( p_sys->p_inputs );
657     if( p_sys->p_tuners ) free( p_sys->p_tuners );
658     if( p_sys->p_codecs ) free( p_sys->p_codecs );
659
660     free( p_sys );
661 }
662
663 /*****************************************************************************
664  * Control:
665  *****************************************************************************/
666 static int Control( demux_t *p_demux, int i_query, va_list args )
667 {
668     demux_sys_t *p_sys = p_demux->p_sys;
669     vlc_bool_t *pb;
670     int64_t    *pi64;
671
672     switch( i_query )
673     {
674         /* Special for access_demux */
675         case DEMUX_CAN_PAUSE:
676         case DEMUX_SET_PAUSE_STATE:
677         case DEMUX_CAN_CONTROL_PACE:
678             pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
679             *pb = VLC_FALSE;
680             return VLC_SUCCESS;
681
682         case DEMUX_GET_PTS_DELAY:
683             pi64 = (int64_t*)va_arg( args, int64_t * );
684             *pi64 = (int64_t)p_sys->i_pts * 1000;
685             return VLC_SUCCESS;
686
687         case DEMUX_GET_TIME:
688             pi64 = (int64_t*)va_arg( args, int64_t * );
689             *pi64 = mdate();
690             return VLC_SUCCESS;
691
692         /* TODO implement others */
693         default:
694             return VLC_EGENERIC;
695     }
696
697     return VLC_EGENERIC;
698 }
699
700 /*****************************************************************************
701  * Demux: Processes the audio or video frame
702  *****************************************************************************/
703 static int Demux( demux_t *p_demux )
704 {
705     demux_sys_t *p_sys = p_demux->p_sys;
706         es_out_id_t *p_es = p_sys->p_es_audio;
707     block_t *p_block = NULL;
708       
709     /* Try grabbing audio frames first */
710     if( p_sys->i_fd_audio < 0 || !( p_block = GrabAudio( p_demux ) ) )
711     {
712         /* Try grabbing video frame */
713         p_es = p_sys->p_es_video;
714         if( p_sys->i_fd_video > 0 ) p_block = GrabVideo( p_demux );
715     }
716   
717     if( !p_block )
718     {
719         /* Sleep so we do not consume all the cpu, 10ms seems
720          * like a good value (100fps) */
721         msleep( 10 );
722         return 1;
723     }
724
725     es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_block->i_pts );
726     es_out_Send( p_demux->out, p_es, p_block );
727
728     return 1;
729 }
730
731 /*****************************************************************************
732  * GrabVideo: Grab a video frame
733  *****************************************************************************/
734 static block_t* GrabVideo( demux_t *p_demux )
735 {
736     demux_sys_t *p_sys = p_demux->p_sys;
737
738     block_t *p_block = NULL;
739     struct v4l2_buffer buf;
740
741     if( p_sys->f_fps >= 0.1 && p_sys->i_video_pts > 0 )
742     {
743         mtime_t i_dur = (mtime_t)((double)1000000 / (double)p_sys->f_fps);
744
745         /* Did we wait long enough ? (frame rate reduction) */
746         if( p_sys->i_video_pts + i_dur > mdate() ) return 0;
747     }
748     
749     /* Grab Video Frame */
750     switch( p_sys->io )
751     {
752     case IO_METHOD_READ:
753         if( read( p_sys->i_fd_video, p_sys->p_buffers[0].start, p_sys->p_buffers[0].length ) )
754         {
755             switch( errno ) 
756             {
757             case EAGAIN:
758                 return 0;
759             case EIO:
760                 /* Could ignore EIO, see spec. */
761                 /* fall through */
762             default:
763                 msg_Err( p_demux, "Failed to read frame" );
764                 return 0;
765                 }        
766         }
767         
768         p_block = ProcessVideoFrame( p_demux, (uint8_t*)p_sys->p_buffers[0].start );
769         if( !p_block ) return 0;
770         
771         break;
772         
773     case IO_METHOD_MMAP:
774         memset( &buf, 0, sizeof(buf) );
775         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
776         buf.memory = V4L2_MEMORY_MMAP;
777         
778         /* Wait for next frame */
779         if (ioctl( p_sys->i_fd_video, VIDIOC_DQBUF, &buf ) < 0 )
780         {
781             switch( errno ) 
782             {
783             case EAGAIN:
784                 return 0;
785             case EIO:
786                 /* Could ignore EIO, see spec. */
787                 /* fall through */
788             default:
789                 msg_Err( p_demux, "Failed to wait (VIDIOC_DQBUF)" );
790                 return 0;
791                 }
792         }
793
794         if( buf.index >= p_sys->i_nbuffers ) {
795             msg_Err( p_demux, "Failed capturing new frame as i>=nbuffers" );
796             return 0;
797         }
798         
799         p_block = ProcessVideoFrame( p_demux, p_sys->p_buffers[buf.index].start );
800         if( !p_block ) return 0;
801
802         /* Unlock */    
803         if( ioctl( p_sys->i_fd_video, VIDIOC_QBUF, &buf ) < 0 )
804         {
805             msg_Err (p_demux, "Failed to unlock (VIDIOC_QBUF)");
806                 return 0;
807         }
808     
809         break;
810         
811     case IO_METHOD_USERPTR:        
812         memset( &buf, 0, sizeof(buf) );
813         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
814         buf.memory = V4L2_MEMORY_USERPTR;
815         
816         /* Wait for next frame */
817         if (ioctl( p_sys->i_fd_video, VIDIOC_DQBUF, &buf ) < 0 )
818         {
819             switch( errno ) 
820             {
821             case EAGAIN:
822                 return 0;
823             case EIO:
824                 /* Could ignore EIO, see spec. */
825                 /* fall through */
826             default:
827                 msg_Err( p_demux, "Failed to wait (VIDIOC_DQBUF)" );
828                 return 0;
829                 }
830         }
831
832         /* Find frame? */
833         unsigned int i;
834         for( i = 0; i < p_sys->i_nbuffers; i++ )
835         {
836             if( buf.m.userptr == (unsigned long)p_sys->p_buffers[i].start && 
837                 buf.length == p_sys->p_buffers[i].length ) break;
838         }
839
840         if( i >= p_sys->i_nbuffers ) {
841             msg_Err( p_demux, "Failed capturing new frame as i>=nbuffers" );
842             return 0;
843         }
844         
845         p_block = ProcessVideoFrame( p_demux, (uint8_t*)buf.m.userptr );
846         if( !p_block ) return 0;
847
848         /* Unlock */    
849         if( ioctl( p_sys->i_fd_video, VIDIOC_QBUF, &buf ) < 0 )
850         {
851             msg_Err (p_demux, "Failed to unlock (VIDIOC_QBUF)");
852             return 0;
853         }
854         
855         break;
856        
857     }
858     
859     /* Timestamp */
860     p_sys->i_video_pts = p_block->i_pts = p_block->i_dts = mdate();
861     
862     return p_block;
863 }
864
865 /*****************************************************************************
866  * ProcessVideoFrame: Helper function to take a buffer and copy it into
867  * a new block
868  *****************************************************************************/
869 static block_t* ProcessVideoFrame( demux_t *p_demux, uint8_t *p_frame )
870 {
871     demux_sys_t *p_sys = p_demux->p_sys;
872     block_t *p_block;
873
874     if( !p_frame ) return 0;
875                 
876     /* New block */
877     if( !( p_block = block_New( p_demux, p_sys->i_video_frame_size ) ) )
878     {
879         msg_Warn( p_demux, "Cannot get new block" );
880         return 0;
881     }
882
883     /* Copy frame */
884     memcpy( p_block->p_buffer, p_frame, p_sys->i_video_frame_size );
885     
886     return p_block;
887 }
888
889 /*****************************************************************************
890  * GrabAudio: Grab an audio frame
891  *****************************************************************************/
892 static block_t* GrabAudio( demux_t *p_demux )
893 {
894     demux_sys_t *p_sys = p_demux->p_sys;
895     struct audio_buf_info buf_info;
896     int i_read, i_correct;
897     block_t *p_block;
898     
899     /* Copied from v4l.c */
900
901     if( p_sys->p_block_audio ) p_block = p_sys->p_block_audio;
902     else p_block = block_New( p_demux, p_sys->i_audio_max_frame_size );
903
904     if( !p_block )
905     {
906         msg_Warn( p_demux, "cannot get block" );
907         return 0;
908     }
909
910     p_sys->p_block_audio = p_block;
911
912     i_read = read( p_sys->i_fd_audio, p_block->p_buffer,
913                    p_sys->i_audio_max_frame_size );                  
914
915     if( i_read <= 0 ) return 0;
916
917     p_block->i_buffer = i_read;
918     p_sys->p_block_audio = 0;
919
920     /* Correct the date because of kernel buffering */
921     i_correct = i_read;
922     if( ioctl( p_sys->i_fd_audio, SNDCTL_DSP_GETISPACE, &buf_info ) == 0 )
923     {
924         i_correct += buf_info.bytes;
925     }
926
927     /* Timestamp */
928     p_block->i_pts = p_block->i_dts =
929         mdate() - I64C(1000000) * (mtime_t)i_correct /
930         2 / ( p_sys->b_stereo ? 2 : 1) / p_sys->i_sample_rate;
931
932     return p_block;
933 }
934
935 /*****************************************************************************
936  * Helper function to initalise video IO using the Read method
937  *****************************************************************************/
938 static int InitRead( demux_t *p_demux, int i_fd, unsigned int i_buffer_size ) 
939 {
940     demux_sys_t *p_sys = p_demux->p_sys;
941
942     p_sys->p_buffers = calloc( 1, sizeof( *p_sys->p_buffers ) );
943     if( !p_sys->p_buffers )
944     {
945         msg_Err( p_demux, "Out of memory" );
946         goto open_failed;
947     }
948     
949     p_sys->p_buffers[0].length = i_buffer_size;
950     p_sys->p_buffers[0].start = malloc( i_buffer_size );
951     if( !p_sys->p_buffers[0].start )
952     {
953         msg_Err( p_demux, "Out of memory" );
954         goto open_failed;
955     }    
956
957     return VLC_SUCCESS;
958     
959 open_failed:
960     return VLC_EGENERIC;
961     
962 }
963
964 /*****************************************************************************
965  * Helper function to initalise video IO using the mmap method
966  *****************************************************************************/
967 static int InitMmap( demux_t *p_demux, int i_fd ) 
968 {
969     demux_sys_t *p_sys = p_demux->p_sys;
970     struct v4l2_requestbuffers req;
971     
972     memset( &req, 0, sizeof(req) );
973     req.count = 4;
974     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
975     req.memory = V4L2_MEMORY_MMAP;
976     
977     if( ioctl( i_fd, VIDIOC_REQBUFS, &req ) < 0 )
978     {
979         msg_Err( p_demux, "device does not support mmap i/o" );
980         goto open_failed;
981     }
982                             
983     if( req.count < 2 )
984     {
985         msg_Err( p_demux, "Insufficient buffer memory" );
986         goto open_failed;
987     }
988     
989     p_sys->p_buffers = calloc( req.count, sizeof( *p_sys->p_buffers ) );
990     if( !p_sys->p_buffers )
991     {
992         msg_Err( p_demux, "Out of memory" );
993         goto open_failed;
994     }
995     
996     for( p_sys->i_nbuffers = 0; p_sys->i_nbuffers < req.count; ++p_sys->i_nbuffers )
997     {
998         struct v4l2_buffer buf;
999         
1000         memset( &buf, 0, sizeof(buf) );
1001         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1002         buf.memory = V4L2_MEMORY_MMAP;
1003         buf.index = p_sys->i_nbuffers;
1004         
1005         if( ioctl( i_fd, VIDIOC_QUERYBUF, &buf ) < 0 )
1006         {
1007             msg_Err( p_demux, "VIDIOC_QUERYBUF" );
1008             goto open_failed;
1009         }
1010         
1011         p_sys->p_buffers[p_sys->i_nbuffers].length = buf.length;
1012         p_sys->p_buffers[p_sys->i_nbuffers].start = 
1013             mmap( NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, p_sys->i_fd_video, buf.m.offset );
1014
1015         if( p_sys->p_buffers[p_sys->i_nbuffers].start == MAP_FAILED )
1016         {
1017             msg_Err( p_demux, "mmap failed" );
1018             goto open_failed;
1019         }
1020     }
1021  
1022     return VLC_SUCCESS;
1023     
1024 open_failed:
1025     return VLC_EGENERIC;
1026     
1027 }
1028
1029 /*****************************************************************************
1030  * Helper function to initalise video IO using the userbuf method
1031  *****************************************************************************/
1032 static int InitUserP( demux_t *p_demux, int i_fd, unsigned int i_buffer_size ) 
1033 {
1034     demux_sys_t *p_sys = p_demux->p_sys;
1035     struct v4l2_requestbuffers req;
1036     
1037     memset( &req, 0, sizeof(req) );
1038     req.count = 4;
1039     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1040     req.memory = V4L2_MEMORY_USERPTR;
1041     
1042     if( ioctl( i_fd, VIDIOC_REQBUFS, &req ) < 0 )
1043     {
1044         msg_Err( p_demux, "device does not support user pointer i/o" );
1045         goto open_failed;
1046     }
1047     
1048     p_sys->p_buffers = calloc( 4, sizeof( *p_sys->p_buffers ) );
1049     if( !p_sys->p_buffers )
1050     {
1051         msg_Err( p_demux, "Out of memory" );
1052         goto open_failed;
1053     }
1054     
1055     for( p_sys->i_nbuffers = 0; p_sys->i_nbuffers < 4; ++p_sys->i_nbuffers )
1056     {
1057         p_sys->p_buffers[p_sys->i_nbuffers].length = i_buffer_size;
1058         p_sys->p_buffers[p_sys->i_nbuffers].start = malloc( i_buffer_size );
1059
1060         if( !p_sys->p_buffers[p_sys->i_nbuffers].start )
1061         {
1062             msg_Err( p_demux, "out of memory" );
1063             goto open_failed;
1064         }
1065     }
1066
1067     return VLC_SUCCESS;
1068     
1069 open_failed:
1070     return VLC_EGENERIC;
1071     
1072 }
1073
1074 /*****************************************************************************
1075  * GetChromaFromFourcc: Returns the fourcc code from the given string
1076  *****************************************************************************/
1077 unsigned int GetChromaFromFourcc( char *psz_fourcc )
1078 {
1079     if( strlen( psz_fourcc ) >= 4 )
1080     {
1081         int i_chroma = VLC_FOURCC( psz_fourcc[0], psz_fourcc[1], psz_fourcc[2], psz_fourcc[3] );
1082
1083         /* Find out v4l2 chroma code */
1084         for( int i = 0; v4l2chroma_to_fourcc[i].i_fourcc != 0; i++ )
1085         {
1086             if( v4l2chroma_to_fourcc[i].i_fourcc == i_chroma )
1087             {
1088                 return v4l2chroma_to_fourcc[i].i_fourcc;
1089             }
1090         }
1091     }
1092     
1093     return 0;
1094 }
1095
1096 /*****************************************************************************
1097  * IsChromaSupported: returns true if the specified V4L2 chroma constant is 
1098  * in the array of supported chromas returned by the driver
1099  *****************************************************************************/
1100 vlc_bool_t IsChromaSupported( demux_t *p_demux, unsigned int i_chroma )
1101 {
1102     demux_sys_t *p_sys = p_demux->p_sys;
1103
1104     for( int i_index = 0; i_index < p_sys->i_codec; i_index++ )
1105     {
1106         if( p_sys->p_codecs[i_index].pixelformat == i_chroma ) return VLC_TRUE;
1107     }
1108     
1109     return VLC_FALSE;            
1110 }
1111
1112 /*****************************************************************************
1113  * OpenVideoDev: open and set up the video device and probe for capabilities
1114  *****************************************************************************/
1115 int OpenVideoDev( demux_t *p_demux, char *psz_device )
1116 {
1117     int i_fd;
1118     demux_sys_t *p_sys = p_demux->p_sys;
1119     struct v4l2_cropcap cropcap;
1120     struct v4l2_crop crop;
1121     struct v4l2_format fmt;
1122     unsigned int i_min;
1123     enum v4l2_buf_type buf_type;
1124     
1125     if( ( i_fd = open( psz_device, O_RDWR ) ) < 0 )
1126     {
1127         msg_Err( p_demux, "cannot open device (%m)" );
1128         goto open_failed;
1129     }
1130
1131     /* Select standard */
1132     
1133     if( p_sys->i_selected_standard_id != V4L2_STD_UNKNOWN )
1134     {
1135         if( ioctl( i_fd, VIDIOC_S_STD, &p_sys->i_selected_standard_id ) < 0 )
1136         {
1137            msg_Err( p_demux, "cannot set input (%m)" );
1138            goto open_failed;
1139         }
1140         msg_Dbg( p_demux, "Set standard" );
1141     }
1142
1143     /* Select input */
1144     
1145     if( p_sys->i_selected_input > p_sys->i_input )
1146     {
1147         msg_Warn( p_demux, "invalid input. Using the default one" );
1148         p_sys->i_selected_input = 0;
1149     }
1150
1151     if( ioctl( i_fd, VIDIOC_S_INPUT, &p_sys->i_selected_input ) < 0 )
1152     {
1153        msg_Err( p_demux, "cannot set input (%m)" );
1154        goto open_failed;
1155     }
1156
1157     /* Verify device support for the various IO methods */
1158     switch( p_sys->io )
1159     {
1160     case IO_METHOD_READ:
1161         if( !(p_sys->dev_cap.capabilities & V4L2_CAP_READWRITE) ) 
1162         {
1163             msg_Err( p_demux, "device does not support read i/o" );
1164             goto open_failed;            
1165         }    
1166         break;
1167         
1168     case IO_METHOD_MMAP:
1169     case IO_METHOD_USERPTR:
1170         if( !(p_sys->dev_cap.capabilities & V4L2_CAP_STREAMING) ) 
1171         {
1172             msg_Err( p_demux, "device does not support streaming i/o" );
1173             goto open_failed;            
1174         }
1175         break;
1176        
1177     default:
1178         msg_Err( p_demux, "io method not supported" );
1179         goto open_failed;
1180     }
1181         
1182     /* Reset Cropping */
1183     memset( &cropcap, 0, sizeof(cropcap) );
1184     cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1185     if( ioctl( i_fd, VIDIOC_CROPCAP, &cropcap ) >= 0 )
1186         {
1187         crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1188         crop.c = cropcap.defrect; /* reset to default */
1189         if( ioctl( i_fd, VIDIOC_S_CROP, &crop ) < 0 )
1190                 {
1191             switch( errno )
1192                         {
1193             case EINVAL:
1194                 /* Cropping not supported. */
1195                 break;
1196             default:
1197                 /* Errors ignored. */
1198                 break;
1199             }
1200         }
1201     }
1202   
1203     /* Try and find default resolution if not specified */
1204     if( !p_sys->i_width && !p_sys->i_height ) {        
1205         memset( &fmt, 0, sizeof(fmt) );
1206         fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1207         
1208         if ( ioctl( i_fd, VIDIOC_G_FMT, &fmt ) < 0 ) 
1209         {
1210             msg_Err( p_demux, "Cannot get default width and height." );
1211             goto open_failed;
1212         }    
1213         
1214         p_sys->i_width = fmt.fmt.pix.width;
1215         p_sys->i_height = fmt.fmt.pix.height;
1216         
1217         if( fmt.fmt.pix.field == V4L2_FIELD_ALTERNATE )
1218         {
1219             p_sys->i_height = p_sys->i_height * 2;
1220         }
1221     }
1222         
1223     fmt.fmt.pix.width = p_sys->i_width; 
1224     fmt.fmt.pix.height = p_sys->i_height;    
1225     fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
1226     
1227     /* Test and set Chroma */
1228     fmt.fmt.pix.pixelformat = 0;
1229     if( p_sys->i_fourcc ) 
1230     {
1231         /* User specified chroma */
1232         for( int i = 0; v4l2chroma_to_fourcc[i].i_v4l2 != 0; i++ )
1233         {
1234             if( v4l2chroma_to_fourcc[i].i_fourcc == p_sys->i_fourcc )
1235             {
1236                 fmt.fmt.pix.pixelformat = v4l2chroma_to_fourcc[i].i_v4l2;
1237                 break;
1238             }
1239         }
1240         /* Try and set user chroma */
1241         if( !IsChromaSupported( p_demux, fmt.fmt.pix.pixelformat ) || ( fmt.fmt.pix.pixelformat && ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 ) ) 
1242         {
1243             msg_Warn( p_demux, "Driver is unable to use specified chroma.  Using defaults." );
1244             fmt.fmt.pix.pixelformat = 0;
1245         }
1246     }
1247     
1248     /* If no user specified chroma, find best */
1249     if( !fmt.fmt.pix.pixelformat )
1250     {
1251         fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YVU420;
1252         if( !IsChromaSupported( p_demux, fmt.fmt.pix.pixelformat ) || ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 ) 
1253         {
1254             fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUV422P;
1255             if( !IsChromaSupported( p_demux, fmt.fmt.pix.pixelformat ) || ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 ) 
1256             {
1257                 fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
1258                 if( !IsChromaSupported( p_demux, fmt.fmt.pix.pixelformat ) || ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 ) 
1259                 {
1260                     msg_Err( p_demux, "Could not select any of the default chromas!" );
1261                     goto open_failed; 
1262                 }                  
1263             }              
1264         }    
1265     }   
1266
1267     /* Reassign width, height and chroma incase driver override */
1268     p_sys->i_width = fmt.fmt.pix.width;
1269     p_sys->i_height = fmt.fmt.pix.height;
1270
1271     /* Look up final fourcc */
1272     p_sys->i_fourcc = 0;
1273     for( int i = 0; v4l2chroma_to_fourcc[i].i_fourcc != 0; i++ )
1274     {
1275         if( v4l2chroma_to_fourcc[i].i_v4l2 == fmt.fmt.pix.pixelformat )
1276         {
1277             p_sys->i_fourcc = v4l2chroma_to_fourcc[i].i_fourcc;
1278             break;
1279         }
1280     }
1281     
1282     /* Buggy driver paranoia */
1283     i_min = fmt.fmt.pix.width * 2;
1284     if( fmt.fmt.pix.bytesperline < i_min )
1285         fmt.fmt.pix.bytesperline = i_min;
1286     i_min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
1287     if( fmt.fmt.pix.sizeimage < i_min )
1288         fmt.fmt.pix.sizeimage = i_min;        
1289        
1290     /* Init vout Picture */
1291     vout_InitPicture( VLC_OBJECT(p_demux), &p_sys->pic, p_sys->i_fourcc,
1292         p_sys->i_width, p_sys->i_height, p_sys->i_width *
1293         VOUT_ASPECT_FACTOR / p_sys->i_height );
1294     if( !p_sys->pic.i_planes )
1295     {
1296         msg_Err( p_demux, "unsupported chroma" );
1297         goto open_failed;
1298     }
1299     p_sys->i_video_frame_size = 0;
1300     for( int i = 0; i < p_sys->pic.i_planes; i++ )
1301     {
1302          p_sys->i_video_frame_size += p_sys->pic.p[i].i_visible_lines * p_sys->pic.p[i].i_visible_pitch;
1303     }       
1304        
1305     /* Init IO method */     
1306     switch( p_sys->io )
1307     {
1308     case IO_METHOD_READ:
1309         if( InitRead( p_demux, i_fd, fmt.fmt.pix.sizeimage ) != VLC_SUCCESS ) goto open_failed;
1310         break;
1311         
1312     case IO_METHOD_MMAP:
1313         if( InitMmap( p_demux, i_fd ) != VLC_SUCCESS ) goto open_failed;
1314         break;
1315         
1316     case IO_METHOD_USERPTR:
1317         if( InitUserP( p_demux, i_fd, fmt.fmt.pix.sizeimage ) != VLC_SUCCESS ) goto open_failed;
1318         break;
1319        
1320     }
1321        
1322     /* Add */    
1323     es_format_t es_fmt;
1324     es_format_Init( &es_fmt, VIDEO_ES, p_sys->i_fourcc );
1325     es_fmt.video.i_width  = p_sys->i_width;
1326     es_fmt.video.i_height = p_sys->i_height;
1327     es_fmt.video.i_aspect = 4 * VOUT_ASPECT_FACTOR / 3;  
1328
1329     /* Setup rgb mask for RGB formats */
1330     if( p_sys->i_fourcc == VLC_FOURCC( 'R','V','2','4' ) )
1331     {
1332         /* This is in BGR format */
1333         es_fmt.video.i_bmask = 0x00ff0000;
1334         es_fmt.video.i_gmask = 0x0000ff00;
1335         es_fmt.video.i_rmask = 0x000000ff;
1336     }
1337
1338     msg_Dbg( p_demux, "added new video es %4.4s %dx%d",
1339         (char*)&es_fmt.i_codec, es_fmt.video.i_width, es_fmt.video.i_height );
1340     p_sys->p_es_video = es_out_Add( p_demux->out, &es_fmt );
1341
1342     /* Start Capture */    
1343     
1344     switch( p_sys->io )
1345     {
1346     case IO_METHOD_READ:
1347         /* Nothing to do */
1348         break;
1349         
1350     case IO_METHOD_MMAP:
1351         for (unsigned int i = 0; i < p_sys->i_nbuffers; ++i)
1352         {
1353             struct v4l2_buffer buf;
1354
1355             memset( &buf, 0, sizeof(buf) );
1356             buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1357             buf.memory = V4L2_MEMORY_MMAP;
1358             buf.index = i;
1359             
1360             if( ioctl( i_fd, VIDIOC_QBUF, &buf ) < 0 ) {
1361                 msg_Err( p_demux, "VIDIOC_QBUF failed" );
1362                 goto open_failed;
1363             }
1364         }
1365
1366         buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1367         if( ioctl( i_fd, VIDIOC_STREAMON, &buf_type ) < 0 ) {
1368             msg_Err( p_demux, "VIDIOC_STREAMON failed" );
1369             goto open_failed;
1370         }
1371     
1372         break;
1373         
1374     case IO_METHOD_USERPTR:
1375         for( unsigned int i = 0; i < p_sys->i_nbuffers; ++i )
1376         {
1377             struct v4l2_buffer buf;
1378
1379             memset( &buf, 0, sizeof(buf) );
1380             buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1381             buf.memory = V4L2_MEMORY_USERPTR;
1382             buf.index = i;
1383             buf.m.userptr = (unsigned long)p_sys->p_buffers[i].start;
1384             buf.length = p_sys->p_buffers[i].length;
1385
1386             if( ioctl( i_fd, VIDIOC_QBUF, &buf ) < 0 ) {
1387                 msg_Err( p_demux, "VIDIOC_QBUF failed" );
1388                 goto open_failed;
1389             }
1390         }
1391
1392         buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1393         if( ioctl( i_fd, VIDIOC_STREAMON, &buf_type ) < 0 ) {
1394             msg_Err( p_demux, "VIDIOC_STREAMON failed" );
1395             goto open_failed;
1396         }
1397
1398         break;
1399     }
1400     
1401     /* report fps */
1402     if( p_sys->f_fps >= 0.1 )
1403     {
1404         msg_Dbg( p_demux, "User set fps=%f", p_sys->f_fps );
1405     }
1406  
1407     return i_fd;
1408
1409 open_failed:
1410     if( i_fd ) close( i_fd );
1411     return -1;
1412
1413 }
1414
1415 /*****************************************************************************
1416  * OpenAudioDev: open and set up the audio device and probe for capabilities
1417  *****************************************************************************/
1418 int OpenAudioDev( demux_t *p_demux, char *psz_device )
1419 {
1420     demux_sys_t *p_sys = p_demux->p_sys;
1421     int i_fd, i_format;
1422
1423     if( (i_fd = open( psz_device, O_RDONLY | O_NONBLOCK )) < 0 )
1424     {
1425         msg_Err( p_demux, "cannot open audio device (%m)" );
1426         goto adev_fail;
1427     }
1428
1429     i_format = AFMT_S16_LE;
1430     if( ioctl( i_fd, SNDCTL_DSP_SETFMT, &i_format ) < 0
1431         || i_format != AFMT_S16_LE )
1432     {
1433         msg_Err( p_demux, "cannot set audio format (16b little endian) "
1434                  "(%m)" );
1435         goto adev_fail;
1436     }
1437
1438     if( ioctl( i_fd, SNDCTL_DSP_STEREO,
1439                &p_sys->b_stereo ) < 0 )
1440     {
1441         msg_Err( p_demux, "cannot set audio channels count (%m)" );
1442         goto adev_fail;
1443     }
1444
1445     if( ioctl( i_fd, SNDCTL_DSP_SPEED,
1446                &p_sys->i_sample_rate ) < 0 )
1447     {
1448         msg_Err( p_demux, "cannot set audio sample rate (%m)" );
1449         goto adev_fail;
1450     }
1451
1452     msg_Dbg( p_demux, "opened adev=`%s' %s %dHz",
1453              psz_device, p_sys->b_stereo ? "stereo" : "mono",
1454              p_sys->i_sample_rate );
1455
1456     p_sys->i_audio_max_frame_size = 6 * 1024;
1457         
1458     es_format_t fmt;
1459     es_format_Init( &fmt, AUDIO_ES, VLC_FOURCC('a','r','a','w') );
1460
1461     fmt.audio.i_channels = p_sys->b_stereo ? 2 : 1;
1462     fmt.audio.i_rate = p_sys->i_sample_rate;
1463     fmt.audio.i_bitspersample = 16; /* FIXME ? */
1464     fmt.audio.i_blockalign = fmt.audio.i_channels * fmt.audio.i_bitspersample / 8;
1465     fmt.i_bitrate = fmt.audio.i_channels * fmt.audio.i_rate * fmt.audio.i_bitspersample;
1466
1467     msg_Dbg( p_demux, "new audio es %d channels %dHz",
1468       fmt.audio.i_channels, fmt.audio.i_rate );
1469
1470     p_sys->p_es_audio = es_out_Add( p_demux->out, &fmt );
1471     
1472     return i_fd;
1473
1474  adev_fail:
1475
1476     if( i_fd >= 0 ) close( i_fd );
1477     return -1;    
1478     
1479 }
1480
1481 /*****************************************************************************
1482  * ProbeVideoDev: probe video for capabilities
1483  *****************************************************************************/
1484 vlc_bool_t ProbeVideoDev( demux_t *p_demux, char *psz_device )
1485 {
1486     int i_index;
1487     int i_standard;
1488
1489     int i_fd;
1490     demux_sys_t *p_sys = p_demux->p_sys;
1491     
1492 /*    msg_Dbg( p_demux, "main device='%s'", p_sys->psz_device ); */
1493
1494     if( ( i_fd = open( psz_device, O_RDWR ) ) < 0 )
1495     {
1496         msg_Err( p_demux, "cannot open video device (%m)" );
1497         goto open_failed;
1498     }
1499
1500     /* Get device capabilites */
1501
1502     if( ioctl( i_fd, VIDIOC_QUERYCAP, &p_sys->dev_cap ) < 0 )
1503     {
1504         msg_Err( p_demux, "cannot get video capabilities (%m)" );
1505         goto open_failed;
1506     }
1507
1508     msg_Dbg( p_demux, "V4L2 device: %s using driver: %s (version: %u.%u.%u) on %s",
1509                             p_sys->dev_cap.card,
1510                             p_sys->dev_cap.driver,
1511                             (p_sys->dev_cap.version >> 16) & 0xFF,
1512                             (p_sys->dev_cap.version >> 8) & 0xFF,
1513                             p_sys->dev_cap.version & 0xFF,
1514                             p_sys->dev_cap.bus_info );
1515
1516     msg_Dbg( p_demux, "the device has the capabilities: (%c) Video Capure, "
1517                                                        "(%c) Audio, "
1518                                                        "(%c) Tuner",
1519              ( p_sys->dev_cap.capabilities & V4L2_CAP_VIDEO_CAPTURE  ? 'X':' '),
1520              ( p_sys->dev_cap.capabilities & V4L2_CAP_AUDIO  ? 'X':' '),
1521              ( p_sys->dev_cap.capabilities & V4L2_CAP_TUNER  ? 'X':' ') );
1522
1523     msg_Dbg( p_demux, "supported I/O methods are: (%c) Read/Write, "
1524                                                  "(%c) Streaming, "
1525                                                  "(%c) Asynchronous",
1526             ( p_sys->dev_cap.capabilities & V4L2_CAP_READWRITE ? 'X':' ' ),
1527             ( p_sys->dev_cap.capabilities & V4L2_CAP_STREAMING ? 'X':' ' ),
1528             ( p_sys->dev_cap.capabilities & V4L2_CAP_ASYNCIO ? 'X':' ' ) );
1529
1530     /* Now, enumerate all the video inputs. This is useless at the moment
1531        since we have no way to present that info to the user except with
1532        debug messages */
1533
1534     if( p_sys->dev_cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
1535     {
1536         while( ioctl( i_fd, VIDIOC_S_INPUT, &p_sys->i_input ) >= 0 )
1537         {
1538             p_sys->i_input++;
1539         }
1540
1541         p_sys->p_inputs = malloc( p_sys->i_input * sizeof( struct v4l2_input ) );
1542         if( !p_sys->p_inputs ) goto open_failed;
1543         memset( p_sys->p_inputs, 0, sizeof( struct v4l2_input ) );
1544
1545         for( i_index = 0; i_index < p_sys->i_input; i_index++ )
1546         {
1547             p_sys->p_inputs[i_index].index = i_index;
1548
1549             if( ioctl( i_fd, VIDIOC_ENUMINPUT, &p_sys->p_inputs[i_index] ) )
1550             {
1551                 msg_Err( p_demux, "cannot get video input characteristics (%m)" );
1552                 goto open_failed;
1553             }
1554             msg_Dbg( p_demux, "video input %i (%s) has type: %s",
1555                                 i_index,
1556                                 p_sys->p_inputs[i_index].name,
1557                                 p_sys->p_inputs[i_index].type
1558                                         == V4L2_INPUT_TYPE_TUNER ?
1559                                         "Tuner adapter" :
1560                                         "External analog input" );
1561         }
1562     }
1563     
1564     /* Probe video standards */
1565     if( p_sys->dev_cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
1566     {
1567         struct v4l2_standard t_standards;
1568         t_standards.index = 0;
1569         while( ioctl( i_fd, VIDIOC_ENUMSTD, &t_standards ) >=0 )
1570         {
1571             p_sys->i_standard++;
1572             t_standards.index = p_sys->i_standard;
1573         }
1574
1575         p_sys->p_standards = malloc( p_sys->i_standard * sizeof( struct v4l2_standard ) );
1576         if( !p_sys->p_standards ) goto open_failed;
1577         memset( p_sys->p_standards, 0, sizeof( struct v4l2_standard ) );
1578
1579         for( i_standard = 0; i_standard < p_sys->i_standard; i_standard++ )
1580         {
1581             p_sys->p_standards[i_standard].index = i_standard;
1582
1583             if( ioctl( i_fd, VIDIOC_ENUMSTD, &p_sys->p_standards[i_standard] ) )
1584             {
1585                 msg_Err( p_demux, "cannot get video input standards (%m)" );
1586                 goto open_failed;
1587             }
1588             msg_Dbg( p_demux, "video standard %i is: %s",
1589                                 i_standard,
1590                                 p_sys->p_standards[i_standard].name);
1591         }
1592     }
1593
1594     /* initialize the structures for the ioctls */
1595     for( i_index = 0; i_index < 32; i_index++ )
1596     {
1597         p_sys->p_audios[i_index].index = i_index;
1598     }
1599
1600     /* Probe audio inputs */
1601
1602     if( p_sys->dev_cap.capabilities & V4L2_CAP_AUDIO )
1603     {
1604         while( p_sys->i_audio < 32 &&
1605                ioctl( i_fd, VIDIOC_S_AUDIO, &p_sys->p_audios[p_sys->i_audio] ) >= 0 )
1606         {
1607             if( ioctl( i_fd, VIDIOC_G_AUDIO, &p_sys->p_audios[ p_sys->i_audio] ) < 0 )
1608             {
1609                 msg_Err( p_demux, "cannot get video input characteristics (%m)" );
1610                 goto open_failed;
1611             }
1612
1613             msg_Dbg( p_demux, "audio device %i (%s) is %s",
1614                                 p_sys->i_audio,
1615                                 p_sys->p_audios[p_sys->i_audio].name,
1616                                 p_sys->p_audios[p_sys->i_audio].capability &
1617                                                     V4L2_AUDCAP_STEREO ?
1618                                         "Stereo" : "Mono" );
1619
1620             p_sys->i_audio++;
1621         }
1622     }
1623
1624     if( p_sys->dev_cap.capabilities & V4L2_CAP_TUNER )
1625     {
1626         struct v4l2_tuner tuner;
1627
1628         memset( &tuner, 0, sizeof(tuner) );
1629         while( ioctl( i_fd, VIDIOC_S_TUNER, &tuner ) >= 0 )
1630         {
1631             p_sys->i_tuner++;
1632             tuner.index = p_sys->i_tuner;
1633         }
1634
1635         p_sys->p_tuners = malloc( p_sys->i_tuner * sizeof( struct v4l2_tuner ) );
1636         if( !p_sys->p_tuners ) goto open_failed;
1637         memset( p_sys->p_tuners, 0, sizeof( struct v4l2_tuner ) );
1638
1639         for( i_index = 0; i_index < p_sys->i_tuner; i_index++ )
1640         {
1641             p_sys->p_tuners[i_index].index = i_index;
1642
1643             if( ioctl( i_fd, VIDIOC_G_TUNER, &p_sys->p_tuners[i_index] ) )
1644             {
1645                 msg_Err( p_demux, "cannot get tuner characteristics (%m)" );
1646                 goto open_failed;
1647             }
1648             msg_Dbg( p_demux, "tuner %i (%s) has type: %s, "
1649                               "frequency range: %.1f %s -> %.1f %s",
1650                                 i_index,
1651                                 p_sys->p_tuners[i_index].name,
1652                                 p_sys->p_tuners[i_index].type
1653                                         == V4L2_TUNER_RADIO ?
1654                                         "Radio" : "Analog TV",
1655                                 p_sys->p_tuners[i_index].rangelow * 62.5,
1656                                 p_sys->p_tuners[i_index].capability &
1657                                         V4L2_TUNER_CAP_LOW ?
1658                                         "Hz" : "kHz",
1659                                 p_sys->p_tuners[i_index].rangehigh * 62.5,
1660                                 p_sys->p_tuners[i_index].capability &
1661                                         V4L2_TUNER_CAP_LOW ?
1662                                         "Hz" : "kHz" );
1663         }
1664     }
1665
1666     /* Probe for available chromas */
1667     if( p_sys->dev_cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
1668     {
1669         struct v4l2_fmtdesc codec;
1670
1671         i_index = 0;
1672         memset( &codec, 0, sizeof(codec) );
1673         codec.index = i_index;
1674         codec.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1675
1676         while( ioctl( i_fd, VIDIOC_ENUM_FMT, &codec ) >= 0 )
1677         {
1678             i_index++;
1679             codec.index = i_index;
1680         }
1681
1682         p_sys->i_codec = i_index;
1683
1684         p_sys->p_codecs = malloc( p_sys->i_codec * sizeof( struct v4l2_fmtdesc ) );
1685         memset( p_sys->p_codecs, 0, p_sys->i_codec * sizeof( struct v4l2_fmtdesc ) );
1686
1687         for( i_index = 0; i_index < p_sys->i_codec; i_index++ )
1688         {
1689             p_sys->p_codecs[i_index].index = i_index;
1690             p_sys->p_codecs[i_index].type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1691
1692             if( ioctl( i_fd, VIDIOC_ENUM_FMT, &p_sys->p_codecs[i_index] ) < 0 )
1693             {
1694                 msg_Err( p_demux, "cannot get codec description (%m)" );
1695                 goto open_failed;
1696             }
1697
1698             msg_Dbg( p_demux, "device supports Codec %s",
1699                                 p_sys->p_codecs[i_index].description );
1700         }
1701     }
1702
1703
1704     if( i_fd >= 0 ) close( i_fd );
1705     return VLC_TRUE;
1706
1707 open_failed:
1708
1709     if( i_fd >= 0 ) close( i_fd );
1710     return VLC_FALSE;
1711
1712 }
1713
1714 /*****************************************************************************
1715  * ProbeAudioDev: probe audio for capabilities
1716  *****************************************************************************/
1717 vlc_bool_t ProbeAudioDev( demux_t *p_demux, char *psz_device )
1718 {
1719     int i_fd = 0;
1720     int i_caps;
1721
1722     if( ( i_fd = open( psz_device, O_RDONLY | O_NONBLOCK ) ) < 0 )
1723     {
1724         msg_Err( p_demux, "cannot open audio device (%m)" );
1725         goto open_failed;
1726     }
1727
1728     /* this will fail if the device is video */    
1729     if( ioctl( i_fd, SNDCTL_DSP_GETCAPS, &i_caps ) < 0 )
1730     {
1731         msg_Err( p_demux, "cannot get audio caps (%m)" );
1732         goto open_failed;
1733     }
1734     
1735     if( i_fd ) close( i_fd );
1736     return VLC_TRUE;
1737
1738 open_failed:
1739     if( i_fd ) close( i_fd );
1740     return VLC_FALSE;
1741     
1742 }
1743