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