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