]> git.sesse.net Git - vlc/blob - modules/access/v4l2.c
v4l2: ALSA error handling.
[vlc] / 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  * Authors: Benjamin Pracht <bigben at videolan dot org>
8  *          Richard Hosking <richard at hovis dot net>
9  *          Antoine Cellerier <dionoea at videolan d.t net>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 /*
27  * Sections based on the reference V4L2 capture example at
28  * http://v4l2spec.bytesex.org/spec/capture-example.html
29  *
30  * ALSA support based on parts of
31  * http://www.equalarea.com/paul/alsa-audio.html
32  * and hints taken from alsa-utils (aplay/arecord)
33  * http://www.alsa-project.org
34  */
35
36 /*
37  * TODO: Tuner partial implementation.
38  */
39
40 /*****************************************************************************
41  * Preamble
42  *****************************************************************************/
43
44 #include <vlc/vlc.h>
45 #include <vlc_access.h>
46 #include <vlc_demux.h>
47 #include <vlc_input.h>
48 #include <vlc_vout.h>
49
50 #include <fcntl.h>
51 #include <unistd.h>
52 #include <sys/ioctl.h>
53 #include <sys/mman.h>
54
55 #include <linux/videodev2.h>
56
57 #include <sys/soundcard.h>
58
59 #ifdef HAVE_ALSA
60 # define ALSA_PCM_NEW_HW_PARAMS_API
61 # define ALSA_PCM_NEW_SW_PARAMS_API
62 # include <alsa/asoundlib.h>
63 #endif
64
65 /*****************************************************************************
66  * Module descriptior
67  *****************************************************************************/
68
69 static int  Open ( vlc_object_t * );
70 static void Close( vlc_object_t * );
71
72 #define DEV_TEXT N_("Device name")
73 #define DEV_LONGTEXT N_( \
74     "Name of the device to use. " \
75     "If you don't specify anything, /dev/video0 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 or I422 for raw images, MJPEG for M-JPEG compressed input) " \
83     "(Complete list: GREY, I240, RV16, RV15, RV24, RV32, YUY2, YUYV, UYVY, " \
84     "I41N, I422, I420, I411, I410, MJPG)")
85 #define INPUT_TEXT N_( "Input" )
86 #define INPUT_LONGTEXT N_( \
87     "Input of the card to use (Usually, 0 = tuner, " \
88     "1 = composite, 2 = svideo)." )
89 #define IOMETHOD_TEXT N_( "IO Method" )
90 #define IOMETHOD_LONGTEXT N_( \
91     "IO Method (READ, MMAP, USERPTR)." )
92 #define WIDTH_TEXT N_( "Width" )
93 #define WIDTH_LONGTEXT N_( \
94     "Force width (-1 for autodetect)." )
95 #define HEIGHT_TEXT N_( "Height" )
96 #define HEIGHT_LONGTEXT N_( \
97     "Force height (-1 for autodetect)." )
98 #define FPS_TEXT N_( "Framerate" )
99 #define FPS_LONGTEXT N_( "Framerate to capture, if applicable " \
100     "(-1 for autodetect)." )
101
102 #define CTRL_RESET_TEXT N_( "Reset v4l2 controls" )
103 #define CTRL_RESET_LONGTEXT N_( \
104     "Reset controls to defaults provided by the v4l2 driver." )
105 #define BRIGHTNESS_TEXT N_( "Brightness" )
106 #define BRIGHTNESS_LONGTEXT N_( \
107     "Brightness of the video input." )
108 #define CONTRAST_TEXT N_( "Contrast" )
109 #define CONTRAST_LONGTEXT N_( \
110     "Contrast of the video input." )
111 #define SATURATION_TEXT N_( "Saturation" )
112 #define SATURATION_LONGTEXT N_( \
113     "Saturation of the video input." )
114 #define HUE_TEXT N_( "Hue" )
115 #define HUE_LONGTEXT N_( \
116     "Hue of the video input." )
117 #define GAMMA_TEXT N_( "Gamma" )
118 #define GAMMA_LONGTEXT N_( \
119     "Gamma of the video input." )
120
121 #define ADEV_TEXT N_("Audio device name")
122 #define ADEV_LONGTEXT N_( \
123     "Name of the audio device to use. " \
124     "If you don't specify anything, /dev/dsp will be used.")
125 #define ALSA_TEXT N_( "Use Alsa" )
126 #define ALSA_LONGTEXT N_( \
127     "Use ALSA instead of OSS for audio" )
128 #define STEREO_TEXT N_( "Stereo" )
129 #define STEREO_LONGTEXT N_( \
130     "Capture the audio stream in stereo." )
131 #define SAMPLERATE_TEXT N_( "Samplerate" )
132 #define SAMPLERATE_LONGTEXT N_( \
133     "Samplerate of the captured audio stream, in Hz (eg: 11025, 22050, 44100, 48000)" )
134
135 #define CACHING_TEXT N_("Caching value in ms")
136 #define CACHING_LONGTEXT N_( \
137     "Caching value for V4L2 captures. This " \
138     "value should be set in milliseconds." )
139
140 typedef enum {
141     IO_METHOD_READ,
142     IO_METHOD_MMAP,
143     IO_METHOD_USERPTR,
144 } io_method;
145
146 static int i_standards_list[] =
147     { V4L2_STD_UNKNOWN, V4L2_STD_SECAM, V4L2_STD_PAL, V4L2_STD_NTSC };
148 static const char *psz_standards_list_text[] =
149     { N_("Default"), N_("SECAM"), N_("PAL"),  N_("NTSC") };
150
151 static int i_iomethod_list[] =
152     { IO_METHOD_READ, IO_METHOD_MMAP, IO_METHOD_USERPTR };
153 static const char *psz_iomethod_list_text[] =
154     { N_("READ"), N_("MMAP"),  N_("USERPTR") };
155
156 #define CFG_PREFIX "v4l2-"
157
158 vlc_module_begin();
159     set_shortname( _("Video4Linux2") );
160     set_description( _("Video4Linux2 input") );
161     set_category( CAT_INPUT );
162     set_subcategory( SUBCAT_INPUT_ACCESS );
163
164     set_section( N_( "Video input" ), NULL );
165     add_string( CFG_PREFIX "dev", "/dev/video0", 0, DEV_TEXT, DEV_LONGTEXT,
166                 VLC_FALSE );
167     add_integer( CFG_PREFIX "standard", 0, NULL, STANDARD_TEXT,
168                  STANDARD_LONGTEXT, VLC_FALSE );
169         change_integer_list( i_standards_list, psz_standards_list_text, 0 );
170     add_string( CFG_PREFIX "chroma", NULL, NULL, CHROMA_TEXT, CHROMA_LONGTEXT,
171                 VLC_TRUE );
172     add_integer( CFG_PREFIX "input", 0, NULL, INPUT_TEXT, INPUT_LONGTEXT,
173                 VLC_TRUE );
174     add_integer( CFG_PREFIX "io", IO_METHOD_MMAP, NULL, IOMETHOD_TEXT,
175                  IOMETHOD_LONGTEXT, VLC_TRUE );
176         change_integer_list( i_iomethod_list, psz_iomethod_list_text, 0 );
177     add_integer( CFG_PREFIX "width", 0, NULL, WIDTH_TEXT,
178                 WIDTH_LONGTEXT, VLC_TRUE );
179     add_integer( CFG_PREFIX "height", 0, NULL, HEIGHT_TEXT,
180                 HEIGHT_LONGTEXT, VLC_TRUE );
181     add_float( CFG_PREFIX "fps", 0, NULL, FPS_TEXT, FPS_LONGTEXT, VLC_TRUE );
182
183     set_section( N_( "Video controls" ), NULL );
184     add_bool( CFG_PREFIX "controls-reset", VLC_FALSE, NULL, CTRL_RESET_TEXT,
185               CTRL_RESET_LONGTEXT, VLC_TRUE );
186     add_integer( CFG_PREFIX "brightness", -1, NULL, BRIGHTNESS_TEXT,
187                 BRIGHTNESS_LONGTEXT, VLC_TRUE );
188     add_integer( CFG_PREFIX "contrast", -1, NULL, CONTRAST_TEXT,
189                 CONTRAST_LONGTEXT, VLC_TRUE );
190     add_integer( CFG_PREFIX "saturation", -1, NULL, SATURATION_TEXT,
191                 SATURATION_LONGTEXT, VLC_TRUE );
192     add_integer( CFG_PREFIX "hue", -1, NULL, HUE_TEXT,
193                 HUE_LONGTEXT, VLC_TRUE );
194     add_integer( CFG_PREFIX "gamma", -1, NULL, GAMMA_TEXT,
195                 GAMMA_LONGTEXT, VLC_TRUE );
196
197     set_section( N_( "Audio input" ), NULL );
198     add_string( CFG_PREFIX "adev", "/dev/dsp", 0, ADEV_TEXT, ADEV_LONGTEXT,
199                 VLC_FALSE );
200 #ifdef HAVE_ALSA
201     add_bool( CFG_PREFIX "alsa", VLC_FALSE, NULL, ALSA_TEXT, ALSA_LONGTEXT,
202                 VLC_TRUE );
203 #endif
204     add_bool( CFG_PREFIX "stereo", VLC_TRUE, NULL, STEREO_TEXT, STEREO_LONGTEXT,
205                 VLC_TRUE );
206     add_integer( CFG_PREFIX "samplerate", 48000, NULL, SAMPLERATE_TEXT,
207                 SAMPLERATE_LONGTEXT, VLC_TRUE );
208     add_integer( CFG_PREFIX "caching", DEFAULT_PTS_DELAY / 1000, NULL,
209                 CACHING_TEXT, CACHING_LONGTEXT, VLC_TRUE );
210
211     add_shortcut( "v4l2" );
212     set_capability( "access_demux", 10 );
213     set_callbacks( Open, Close );
214 vlc_module_end();
215
216 /*****************************************************************************
217  * Access: local prototypes
218  *****************************************************************************/
219
220 static void ParseMRL( demux_t * );
221
222 static int DemuxControl( demux_t *, int, va_list );
223
224 static int Demux( demux_t * );
225 static block_t* GrabVideo( demux_t *p_demux );
226 static block_t* ProcessVideoFrame( demux_t *p_demux, uint8_t *p_frame, size_t );
227 static block_t* GrabAudio( demux_t *p_demux );
228
229 vlc_bool_t IsPixelFormatSupported( demux_t *p_demux, unsigned int i_pixelformat );
230
231 char* ResolveALSADeviceName( char *psz_device );
232 static int OpenVideoDev( demux_t *, char *psz_device );
233 static int OpenAudioDev( demux_t *, char *psz_device );
234 static vlc_bool_t ProbeVideoDev( demux_t *, char *psz_device );
235 static vlc_bool_t ProbeAudioDev( demux_t *, char *psz_device );
236
237 static int ControlList( demux_t *p_demux, int i_fd, vlc_bool_t b_reset );
238 static int Control( demux_t *, int i_fd,
239                     const char *psz_name, int i_cid, int i_value );
240 static int ControlCallback( vlc_object_t *p_this,
241     const char *psz_var, vlc_value_t oldval, vlc_value_t newval,
242     void *p_data );
243 static int ControlResetCallback( vlc_object_t *p_this,
244     const char *psz_var, vlc_value_t oldval, vlc_value_t newval,
245     void *p_data );
246
247 static struct
248 {
249     unsigned int i_v4l2;
250     int i_fourcc;
251 } v4l2chroma_to_fourcc[] =
252 {
253     /* Raw data types */
254     { V4L2_PIX_FMT_GREY,    VLC_FOURCC('G','R','E','Y') },
255     { V4L2_PIX_FMT_HI240,   VLC_FOURCC('I','2','4','0') },
256     { V4L2_PIX_FMT_RGB565,  VLC_FOURCC('R','V','1','6') },
257     { V4L2_PIX_FMT_RGB555,  VLC_FOURCC('R','V','1','5') },
258     { V4L2_PIX_FMT_BGR24,   VLC_FOURCC('R','V','2','4') },
259     { V4L2_PIX_FMT_BGR32,   VLC_FOURCC('R','V','3','2') },
260     { V4L2_PIX_FMT_YUYV,    VLC_FOURCC('Y','U','Y','2') },
261     { V4L2_PIX_FMT_YUYV,    VLC_FOURCC('Y','U','Y','V') },
262     { V4L2_PIX_FMT_UYVY,    VLC_FOURCC('U','Y','V','Y') },
263     { V4L2_PIX_FMT_Y41P,    VLC_FOURCC('I','4','1','N') },
264     { V4L2_PIX_FMT_YUV422P, VLC_FOURCC('I','4','2','2') },
265     { V4L2_PIX_FMT_YVU420,  VLC_FOURCC('I','4','2','0') },
266     { V4L2_PIX_FMT_YUV411P, VLC_FOURCC('I','4','1','1') },
267     { V4L2_PIX_FMT_YUV410,  VLC_FOURCC('I','4','1','0') },
268     /* Compressed data types */
269     { V4L2_PIX_FMT_MJPEG,   VLC_FOURCC('M','J','P','G') },
270 #if 0
271     { V4L2_PIX_FMT_JPEG,    VLC_FOURCC('J','P','E','G') },
272     { V4L2_PIX_FMT_DV,      VLC_FOURCC('?','?','?','?') },
273     { V4L2_PIX_FMT_MPEG,    VLC_FOURCC('?','?','?','?') },
274 #endif
275     { 0, 0 }
276 };
277
278 static struct
279 {
280     const char *psz_name;
281     unsigned int i_cid;
282 } controls[] =
283 {
284     { "brightness", V4L2_CID_BRIGHTNESS },
285     { "contrast", V4L2_CID_CONTRAST },
286     { "saturation", V4L2_CID_SATURATION },
287     { "hue", V4L2_CID_HUE },
288     { "audio-volume", V4L2_CID_AUDIO_VOLUME },
289     { "audio-balance", V4L2_CID_AUDIO_BALANCE },
290     { "audio-bass", V4L2_CID_AUDIO_BASS },
291     { "audio-treble", V4L2_CID_AUDIO_TREBLE },
292     { "audio-mute", V4L2_CID_AUDIO_MUTE },
293     { "audio-loudness", V4L2_CID_AUDIO_LOUDNESS },
294     { "black-level", V4L2_CID_BLACK_LEVEL },
295     { "auto-white-balance", V4L2_CID_AUTO_WHITE_BALANCE },
296     { "do-white-balance", V4L2_CID_DO_WHITE_BALANCE },
297     { "red-balance", V4L2_CID_RED_BALANCE },
298     { "blue-balance", V4L2_CID_BLUE_BALANCE },
299     { "gamma", V4L2_CID_GAMMA },
300     { "exposure", V4L2_CID_EXPOSURE },
301     { "autogain", V4L2_CID_AUTOGAIN },
302     { "gain", V4L2_CID_GAIN },
303     { "hflip", V4L2_CID_HFLIP },
304     { "vflip", V4L2_CID_VFLIP },
305     { "hcenter", V4L2_CID_HCENTER },
306     { "vcenter", V4L2_CID_VCENTER },
307     { NULL, 0 }
308 };
309
310 struct buffer_t
311 {
312     void *  start;
313     size_t  length;
314     void *  orig_userp;
315 };
316
317 struct demux_sys_t
318 {
319     char *psz_device;  /* Main device from MRL, can be video or audio */
320
321     char *psz_vdev;
322     int  i_fd_video;
323
324     char *psz_adev;
325     int  i_fd_audio;
326
327     char *psz_requested_chroma;
328
329     /* Video */
330     io_method io;
331
332     int i_pts;
333
334     struct v4l2_capability dev_cap;
335
336     int i_input;
337     struct v4l2_input *p_inputs;
338     int i_selected_input;
339
340     int i_standard;
341     struct v4l2_standard *p_standards;
342     v4l2_std_id i_selected_standard_id;
343
344     int i_audio;
345     /* V4L2 devices cannot have more than 32 audio inputs */
346     struct v4l2_audio p_audios[32];
347
348     int i_tuner;
349     struct v4l2_tuner *p_tuners;
350
351     int i_codec;
352     struct v4l2_fmtdesc *p_codecs;
353
354     struct buffer_t *p_buffers;
355     unsigned int i_nbuffers;
356
357     int i_width;
358     int i_height;
359     float f_fps;            /* <= 0.0 mean to grab at full rate */
360     mtime_t i_video_pts;    /* only used when f_fps > 0 */
361     int i_fourcc;
362
363     es_out_id_t *p_es_video;
364
365     /* Audio */
366     unsigned int i_sample_rate;
367     vlc_bool_t b_stereo;
368     int i_audio_max_frame_size;
369     block_t *p_block_audio;
370     es_out_id_t *p_es_audio;
371
372 #ifdef HAVE_ALSA
373     /* ALSA Audio */
374     vlc_bool_t b_use_alsa;
375     snd_pcm_t *p_alsa_pcm;
376     int i_alsa_frame_size;
377     int i_alsa_chunk_size;
378 #endif
379 };
380
381 /*****************************************************************************
382  * Open: opens v4l2 device
383  *****************************************************************************
384  *
385  * url: <video device>::::
386  *
387  *****************************************************************************/
388 static int Open( vlc_object_t *p_this )
389 {
390     demux_t     *p_demux = (demux_t*)p_this;
391     demux_sys_t *p_sys;
392     vlc_value_t val;
393
394     /* Only when selected */
395     if( *p_demux->psz_access == '\0' ) return VLC_EGENERIC;
396
397     /* Set up p_demux */
398     p_demux->pf_control = DemuxControl;
399     p_demux->pf_demux = Demux;
400     p_demux->info.i_update = 0;
401     p_demux->info.i_title = 0;
402     p_demux->info.i_seekpoint = 0;
403
404     p_demux->p_sys = p_sys = calloc( 1, sizeof( demux_sys_t ) );
405     if( p_sys == NULL ) return VLC_ENOMEM;
406
407     p_sys->i_video_pts = -1;
408
409     var_Create( p_demux, "v4l2-standard", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
410     var_Get( p_demux, "v4l2-standard", &val );
411     p_sys->i_selected_standard_id = i_standards_list[val.i_int];
412
413     p_sys->i_selected_input = var_CreateGetInteger( p_demux, "v4l2-input" );
414
415     p_sys->io = var_CreateGetInteger( p_demux, "v4l2-io" );
416
417     p_sys->i_width = var_CreateGetInteger( p_demux, "v4l2-width" );
418     p_sys->i_height = var_CreateGetInteger( p_demux, "v4l2-height" );
419
420     var_CreateGetBool( p_demux, "v4l2-controls-reset" );
421
422     var_Create( p_demux, "v4l2-fps", VLC_VAR_FLOAT | VLC_VAR_DOINHERIT );
423     var_Get( p_demux, "v4l2-fps", &val );
424     p_sys->f_fps = val.f_float;
425
426     var_Create( p_demux, "v4l2-samplerate", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
427     var_Get( p_demux, "v4l2-samplerate", &val );
428     p_sys->i_sample_rate = val.i_int;
429
430     p_sys->psz_requested_chroma = var_CreateGetString( p_demux, "v4l2-chroma" );
431
432 #ifdef HAVE_ALSA
433     var_Create( p_demux, "v4l2-alsa", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
434     var_Get( p_demux, "v4l2-alsa", &val );
435     p_sys->b_use_alsa = val.b_bool;
436 #endif
437
438     var_Create( p_demux, "v4l2-stereo", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
439     var_Get( p_demux, "v4l2-stereo", &val );
440     p_sys->b_stereo = val.b_bool;
441
442     p_sys->i_pts = var_CreateGetInteger( p_demux, "v4l2-caching" );
443
444     p_sys->psz_device = p_sys->psz_vdev = p_sys->psz_adev = NULL;
445     p_sys->i_fd_video = -1;
446     p_sys->i_fd_audio = -1;
447
448     p_sys->p_es_video = p_sys->p_es_audio = 0;
449     p_sys->p_block_audio = 0;
450
451     ParseMRL( p_demux );
452
453 #ifdef HAVE_ALSA
454     /* Alsa support available? */
455     msg_Dbg( p_demux, "ALSA input support available" );
456 #endif
457
458     /* Find main device (video or audio) */
459     if( p_sys->psz_device && *p_sys->psz_device )
460     {
461         msg_Dbg( p_demux, "main device='%s'", p_sys->psz_device );
462
463         /* Try to open as video device */
464         msg_Dbg( p_demux, "trying device '%s' as video", p_sys->psz_device );
465         if( ProbeVideoDev( p_demux, p_sys->psz_device ) )
466         {
467             msg_Dbg( p_demux, "'%s' is a video device", p_sys->psz_device );
468             /* Device was a video device */
469             if( p_sys->psz_vdev ) free( p_sys->psz_vdev );
470             p_sys->psz_vdev = p_sys->psz_device;
471             p_sys->psz_device = NULL;
472             p_sys->i_fd_video = OpenVideoDev( p_demux, p_sys->psz_vdev );
473             if( p_sys->i_fd_video < 0 )
474             {
475                 Close( p_this );
476                 return VLC_EGENERIC;
477             }
478         }
479         else
480         {
481             /* Try to open as audio device */
482             msg_Dbg( p_demux, "trying device '%s' as audio", p_sys->psz_device );
483             if( ProbeAudioDev( p_demux, p_sys->psz_device ) )
484             {
485                 msg_Dbg( p_demux, "'%s' is an audio device", p_sys->psz_device );
486                 /* Device was an audio device */
487                 if( p_sys->psz_adev ) free( p_sys->psz_adev );
488                 p_sys->psz_adev = p_sys->psz_device;
489                 p_sys->psz_device = NULL;
490                 p_sys->i_fd_audio = OpenAudioDev( p_demux, p_sys->psz_adev );
491                 if( p_sys->i_fd_audio < 0 )
492                 {
493                     Close( p_this );
494                     return VLC_EGENERIC;
495                 }
496             }
497         }
498     }
499
500     /* If no device opened, only continue if the access was forced */
501     if( p_sys->i_fd_video < 0 && p_sys->i_fd_audio < 0 )
502     {
503         if( strcmp( p_demux->psz_access, "v4l2" ) )
504         {
505             Close( p_this );
506             return VLC_EGENERIC;
507         }
508     }
509
510     /* Find video device */
511     if( p_sys->i_fd_video < 0 )
512     {
513         if( !p_sys->psz_vdev || !*p_sys->psz_vdev )
514         {
515             if( p_sys->psz_vdev ) free( p_sys->psz_vdev );
516             p_sys->psz_vdev = var_CreateGetString( p_demux, "v4l2-dev" );
517         }
518
519         msg_Dbg( p_demux, "opening '%s' as video", p_sys->psz_vdev );
520         if( p_sys->psz_vdev && *p_sys->psz_vdev && ProbeVideoDev( p_demux, p_sys->psz_vdev ) )
521         {
522             p_sys->i_fd_video = OpenVideoDev( p_demux, p_sys->psz_vdev );
523         }
524     }
525
526     /* Find audio device */
527     if( p_sys->i_fd_audio < 0 )
528     {
529         if( !p_sys->psz_adev || !*p_sys->psz_adev )
530         {
531             if( p_sys->psz_adev ) free( p_sys->psz_adev );
532             p_sys->psz_adev = var_CreateGetString( p_demux, "v4l2-adev" );
533         }
534
535         msg_Dbg( p_demux, "opening '%s' as audio", p_sys->psz_adev );
536         if( p_sys->psz_adev && *p_sys->psz_adev && ProbeAudioDev( p_demux, p_sys->psz_adev ) )
537         {
538             p_sys->i_fd_audio = OpenAudioDev( p_demux, p_sys->psz_adev );
539         }
540     }
541
542     if( p_sys->i_fd_video < 0 && p_sys->i_fd_audio < 0 )
543     {
544         Close( p_this );
545         return VLC_EGENERIC;
546     }
547
548     return VLC_SUCCESS;
549 }
550
551 /*****************************************************************************
552  * ParseMRL: parse the options contained in the MRL
553  *****************************************************************************/
554 static void ParseMRL( demux_t *p_demux )
555 {
556     demux_sys_t *p_sys = p_demux->p_sys;
557
558     char *psz_dup = strdup( p_demux->psz_path );
559     char *psz_parser = psz_dup;
560
561     while( *psz_parser && *psz_parser != ':' )
562     {
563         psz_parser++;
564     }
565
566     if( *psz_parser == ':' )
567     {
568         /* read options */
569         for( ;; )
570         {
571             *psz_parser++ = '\0';
572
573             if( !strncmp( psz_parser, "adev=", strlen( "adev=" ) ) )
574             {
575                 int  i_len;
576
577                 psz_parser += strlen( "adev=" );
578                 if( strchr( psz_parser, ':' ) )
579                 {
580                     i_len = strchr( psz_parser, ':' ) - psz_parser;
581                 }
582                 else
583                 {
584                     i_len = strlen( psz_parser );
585                 }
586
587                 p_sys->psz_adev = strndup( psz_parser, i_len );
588
589                 psz_parser += i_len;
590             }
591             else if( !strncmp( psz_parser, "standard=", strlen( "standard=" ) ) )
592             {
593                 psz_parser += strlen( "standard=" );
594                 if( !strncmp( psz_parser, "pal", strlen( "pal" ) ) )
595                 {
596                     p_sys->i_selected_standard_id = V4L2_STD_PAL;
597                     psz_parser += strlen( "pal" );
598                 }
599                 else if( !strncmp( psz_parser, "ntsc", strlen( "ntsc" ) ) )
600                 {
601                     p_sys->i_selected_standard_id = V4L2_STD_NTSC;
602                     psz_parser += strlen( "ntsc" );
603                 }
604                 else if( !strncmp( psz_parser, "secam", strlen( "secam" ) ) )
605                 {
606                     p_sys->i_selected_standard_id = V4L2_STD_SECAM;
607                     psz_parser += strlen( "secam" );
608                 }
609                 else if( !strncmp( psz_parser, "default", strlen( "default" ) ) )
610                 {
611                     p_sys->i_selected_standard_id = V4L2_STD_UNKNOWN;
612                     psz_parser += strlen( "default" );
613                 }
614                 else
615                 {
616                     p_sys->i_selected_standard_id = i_standards_list[strtol( psz_parser, &psz_parser, 0 )];
617                 }
618             }
619             else if( !strncmp( psz_parser, "chroma=", strlen( "chroma=" ) ) )
620             {
621                 int  i_len;
622
623                 psz_parser += strlen( "chroma=" );
624                 if( strchr( psz_parser, ':' ) )
625                 {
626                     i_len = strchr( psz_parser, ':' ) - psz_parser;
627                 }
628                 else
629                 {
630                     i_len = strlen( psz_parser );
631                 }
632
633                 if( p_sys->psz_requested_chroma ) free( p_sys->psz_requested_chroma );
634                 p_sys->psz_requested_chroma = strndup( psz_parser, i_len );
635
636                 psz_parser += i_len;
637             }
638             else if( !strncmp( psz_parser, "input=", strlen( "input=" ) ) )
639             {
640                 p_sys->i_selected_input = strtol( psz_parser + strlen( "input=" ),
641                                        &psz_parser, 0 );
642             }
643             else if( !strncmp( psz_parser, "fps=", strlen( "fps=" ) ) )
644             {
645                 p_sys->f_fps = strtof( psz_parser + strlen( "fps=" ),
646                                        &psz_parser );
647             }
648             else if( !strncmp( psz_parser, "io=", strlen( "io=" ) ) )
649             {
650                 psz_parser += strlen( "io=" );
651                 if( !strncmp( psz_parser, "read", strlen( "read" ) ) )
652                 {
653                     p_sys->io = IO_METHOD_READ;
654                     psz_parser += strlen( "read" );
655                 }
656                 else if( !strncmp( psz_parser, "mmap", strlen( "mmap" ) ) )
657                 {
658                     p_sys->io = IO_METHOD_MMAP;
659                     psz_parser += strlen( "mmap" );
660                 }
661                 else if( !strncmp( psz_parser, "userptr", strlen( "userptr" ) ) )
662                 {
663                     p_sys->io = IO_METHOD_USERPTR;
664                     psz_parser += strlen( "userptr" );
665                 }
666                 else
667                 {
668                     p_sys->io = strtol( psz_parser, &psz_parser, 0 );
669                 }
670             }
671             else if( !strncmp( psz_parser, "width=",
672                                strlen( "width=" ) ) )
673             {
674                 p_sys->i_width =
675                     strtol( psz_parser + strlen( "width=" ),
676                             &psz_parser, 0 );
677             }
678             else if( !strncmp( psz_parser, "height=",
679                                strlen( "height=" ) ) )
680             {
681                 p_sys->i_height =
682                     strtol( psz_parser + strlen( "height=" ),
683                             &psz_parser, 0 );
684             }
685             else if( !strncmp( psz_parser, "controls-reset",
686                                strlen( "controls-reset" ) ) )
687             {
688                 var_SetBool( p_demux, "v4l2-controls-reset", VLC_TRUE );
689                 psz_parser += strlen( "controls-reset" );
690             }
691 #if 0
692             else if( !strncmp( psz_parser, "brightness=",
693                                strlen( "brightness=" ) ) )
694             {
695                 var_SetInteger( p_demux, "brightness",
696                     strtol( psz_parser + strlen( "brightness=" ),
697                             &psz_parser, 0 ) );
698             }
699             else if( !strncmp( psz_parser, "contrast=",
700                                strlen( "contrast=" ) ) )
701             {
702                 var_SetInteger( p_demux, "contrast",
703                     strtol( psz_parser + strlen( "contrast=" ),
704                             &psz_parser, 0 ) );
705             }
706             else if( !strncmp( psz_parser, "saturation=",
707                                strlen( "saturation=" ) ) )
708             {
709                 var_SetInteger( p_demux, "saturation",
710                     strtol( psz_parser + strlen( "saturation=" ),
711                             &psz_parser, 0 ) );
712             }
713             else if( !strncmp( psz_parser, "hue=",
714                                strlen( "hue=" ) ) )
715             {
716                 var_SetInteger( p_demux, "hue",
717                     strtol( psz_parser + strlen( "hue=" ),
718                             &psz_parser, 0 ) );
719             }
720             else if( !strncmp( psz_parser, "gamma=",
721                                strlen( "gamma=" ) ) )
722             {
723                 var_SetInteger( p_demux, "gamma",
724                     strtol( psz_parser + strlen( "gamma=" ),
725                             &psz_parser, 0 ) );
726             }
727 #endif
728             else if( !strncmp( psz_parser, "samplerate=",
729                                strlen( "samplerate=" ) ) )
730             {
731                 p_sys->i_sample_rate =
732                     strtol( psz_parser + strlen( "samplerate=" ),
733                             &psz_parser, 0 );
734             }
735 #ifdef HAVE_ALSA
736             else if( !strncmp( psz_parser, "alsa", strlen( "alsa" ) ) )
737             {
738                 psz_parser += strlen( "alsa" );
739                 p_sys->b_use_alsa = VLC_TRUE;
740             }
741 #endif
742             else if( !strncmp( psz_parser, "stereo", strlen( "stereo" ) ) )
743             {
744                 psz_parser += strlen( "stereo" );
745                 p_sys->b_stereo = VLC_TRUE;
746             }
747             else if( !strncmp( psz_parser, "mono", strlen( "mono" ) ) )
748             {
749                 psz_parser += strlen( "mono" );
750                 p_sys->b_stereo = VLC_FALSE;
751             }
752             else if( !strncmp( psz_parser, "caching=", strlen( "caching=" ) ) )
753             {
754                 p_sys->i_pts = strtol( psz_parser + strlen( "caching=" ),
755                                        &psz_parser, 0 );
756             }
757             else
758             {
759                 msg_Warn( p_demux, "unknown option" );
760             }
761
762             while( *psz_parser && *psz_parser != ':' )
763             {
764                 psz_parser++;
765             }
766
767             if( *psz_parser == '\0' )
768             {
769                 break;
770             }
771         }
772     }
773
774     /* Main device */
775     if( *psz_dup )
776     {
777         p_sys->psz_device = strdup( psz_dup );
778     }
779     if( psz_dup ) free( psz_dup );
780 }
781
782 /*****************************************************************************
783  * Close: close device, free resources
784  *****************************************************************************/
785 static void Close( vlc_object_t *p_this )
786 {
787     demux_t     *p_demux = (demux_t *)p_this;
788     demux_sys_t *p_sys   = p_demux->p_sys;
789     struct v4l2_buffer buf;
790     enum v4l2_buf_type buf_type;
791     unsigned int i;
792
793     /* Stop video capture */
794     if( p_sys->i_fd_video >= 0 )
795     {
796         switch( p_sys->io )
797         {
798         case IO_METHOD_READ:
799             /* Nothing to do */
800             break;
801
802         case IO_METHOD_MMAP:
803         case IO_METHOD_USERPTR:
804             /* Some drivers 'hang' internally if this is not done before streamoff */
805             for( unsigned int i = 0; i < p_sys->i_nbuffers; i++ )
806             {
807                 memset( &buf, 0, sizeof(buf) );
808                 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
809                 buf.memory = ( p_sys->io == IO_METHOD_USERPTR ) ?
810                     V4L2_MEMORY_USERPTR : V4L2_MEMORY_MMAP;
811                 ioctl( p_sys->i_fd_video, VIDIOC_DQBUF, &buf ); /* ignore result */
812             }
813
814             buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
815             if( ioctl( p_sys->i_fd_video, VIDIOC_STREAMOFF, &buf_type ) < 0 ) {
816                 msg_Err( p_demux, "VIDIOC_STREAMOFF failed" );
817             }
818
819             break;
820         }
821     }
822
823     /* Free Video Buffers */
824     if( p_sys->p_buffers ) {
825         switch( p_sys->io )
826         {
827         case IO_METHOD_READ:
828             free( p_sys->p_buffers[0].start );
829             break;
830
831         case IO_METHOD_MMAP:
832             for( i = 0; i < p_sys->i_nbuffers; ++i )
833             {
834                 if( munmap( p_sys->p_buffers[i].start, p_sys->p_buffers[i].length ) )
835                 {
836                     msg_Err( p_demux, "munmap failed" );
837                 }
838             }
839             break;
840
841         case IO_METHOD_USERPTR:
842             for( i = 0; i < p_sys->i_nbuffers; ++i )
843             {
844                free( p_sys->p_buffers[i].orig_userp );
845             }
846             break;
847         }
848         free( p_sys->p_buffers );
849     }
850
851     /* Close */
852     if( p_sys->i_fd_video >= 0 ) close( p_sys->i_fd_video );
853 #ifdef HAVE_ALSA
854     if( p_sys->b_use_alsa )
855     {
856         if( p_sys->p_alsa_pcm ) snd_pcm_close( p_sys->p_alsa_pcm );
857     }
858     else
859 #endif
860     {
861         if( p_sys->i_fd_audio >= 0 ) close( p_sys->i_fd_audio );
862     }
863
864     if( p_sys->p_block_audio ) block_Release( p_sys->p_block_audio );
865     if( p_sys->psz_device ) free( p_sys->psz_device );
866     if( p_sys->psz_vdev ) free( p_sys->psz_vdev );
867     if( p_sys->psz_adev ) free( p_sys->psz_adev );
868     if( p_sys->p_standards ) free( p_sys->p_standards );
869     if( p_sys->p_inputs ) free( p_sys->p_inputs );
870     if( p_sys->p_tuners ) free( p_sys->p_tuners );
871     if( p_sys->p_codecs ) free( p_sys->p_codecs );
872     if( p_sys->psz_requested_chroma ) free( p_sys->psz_requested_chroma );
873
874     free( p_sys );
875 }
876
877 /*****************************************************************************
878  * DemuxControl:
879  *****************************************************************************/
880 static int DemuxControl( demux_t *p_demux, int i_query, va_list args )
881 {
882     demux_sys_t *p_sys = p_demux->p_sys;
883     vlc_bool_t *pb;
884     int64_t    *pi64;
885
886     switch( i_query )
887     {
888         /* Special for access_demux */
889         case DEMUX_CAN_PAUSE:
890         case DEMUX_SET_PAUSE_STATE:
891         case DEMUX_CAN_CONTROL_PACE:
892             pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
893             *pb = VLC_FALSE;
894             return VLC_SUCCESS;
895
896         case DEMUX_GET_PTS_DELAY:
897             pi64 = (int64_t*)va_arg( args, int64_t * );
898             *pi64 = (int64_t)p_sys->i_pts * 1000;
899             return VLC_SUCCESS;
900
901         case DEMUX_GET_TIME:
902             pi64 = (int64_t*)va_arg( args, int64_t * );
903             *pi64 = mdate();
904             return VLC_SUCCESS;
905
906         /* TODO implement others */
907         default:
908             return VLC_EGENERIC;
909     }
910
911     return VLC_EGENERIC;
912 }
913
914 /*****************************************************************************
915  * Demux: Processes the audio or video frame
916  *****************************************************************************/
917 static int Demux( demux_t *p_demux )
918 {
919     demux_sys_t *p_sys = p_demux->p_sys;
920     es_out_id_t *p_es = p_sys->p_es_audio;
921     block_t *p_block = NULL;
922
923     /* Try grabbing audio frames first */
924     if( p_sys->i_fd_audio < 0 || !( p_block = GrabAudio( p_demux ) ) )
925     {
926         /* Try grabbing video frame */
927         p_es = p_sys->p_es_video;
928         if( p_sys->i_fd_video > 0 ) p_block = GrabVideo( p_demux );
929     }
930
931     if( !p_block )
932     {
933         /* Sleep so we do not consume all the cpu, 10ms seems
934          * like a good value (100fps) */
935         msleep( 10 );
936         return 1;
937     }
938
939     es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_block->i_pts );
940     es_out_Send( p_demux->out, p_es, p_block );
941
942     return 1;
943 }
944
945 /*****************************************************************************
946  * GrabVideo: Grab a video frame
947  *****************************************************************************/
948 static block_t* GrabVideo( demux_t *p_demux )
949 {
950     demux_sys_t *p_sys = p_demux->p_sys;
951
952     block_t *p_block = NULL;
953     struct v4l2_buffer buf;
954     ssize_t i_ret;
955
956     if( p_sys->f_fps >= 0.1 && p_sys->i_video_pts > 0 )
957     {
958         mtime_t i_dur = (mtime_t)((double)1000000 / (double)p_sys->f_fps);
959
960         /* Did we wait long enough ? (frame rate reduction) */
961         if( p_sys->i_video_pts + i_dur > mdate() ) return 0;
962     }
963
964     /* Grab Video Frame */
965     switch( p_sys->io )
966     {
967     case IO_METHOD_READ:
968         i_ret = read( p_sys->i_fd_video, p_sys->p_buffers[0].start, p_sys->p_buffers[0].length );
969         if( i_ret == -1 )
970         {
971             switch( errno )
972             {
973             case EAGAIN:
974                 return 0;
975             case EIO:
976                 /* Could ignore EIO, see spec. */
977                 /* fall through */
978             default:
979                 msg_Err( p_demux, "Failed to read frame" );
980                 return 0;
981                }
982         }
983
984         p_block = ProcessVideoFrame( p_demux, (uint8_t*)p_sys->p_buffers[0].start, i_ret );
985         if( !p_block ) return 0;
986
987         break;
988
989     case IO_METHOD_MMAP:
990         memset( &buf, 0, sizeof(buf) );
991         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
992         buf.memory = V4L2_MEMORY_MMAP;
993
994         /* Wait for next frame */
995         if (ioctl( p_sys->i_fd_video, VIDIOC_DQBUF, &buf ) < 0 )
996         {
997             switch( errno )
998             {
999             case EAGAIN:
1000                 return 0;
1001             case EIO:
1002                 /* Could ignore EIO, see spec. */
1003                 /* fall through */
1004             default:
1005                 msg_Err( p_demux, "Failed to wait (VIDIOC_DQBUF)" );
1006                 return 0;
1007                }
1008         }
1009
1010         if( buf.index >= p_sys->i_nbuffers ) {
1011             msg_Err( p_demux, "Failed capturing new frame as i>=nbuffers" );
1012             return 0;
1013         }
1014
1015         p_block = ProcessVideoFrame( p_demux, p_sys->p_buffers[buf.index].start, buf.bytesused );
1016         if( !p_block ) return 0;
1017
1018         /* Unlock */
1019         if( ioctl( p_sys->i_fd_video, VIDIOC_QBUF, &buf ) < 0 )
1020         {
1021             msg_Err (p_demux, "Failed to unlock (VIDIOC_QBUF)");
1022             return 0;
1023         }
1024
1025         break;
1026
1027     case IO_METHOD_USERPTR:
1028         memset( &buf, 0, sizeof(buf) );
1029         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1030         buf.memory = V4L2_MEMORY_USERPTR;
1031
1032         /* Wait for next frame */
1033         if (ioctl( p_sys->i_fd_video, VIDIOC_DQBUF, &buf ) < 0 )
1034         {
1035             switch( errno )
1036             {
1037             case EAGAIN:
1038                 return 0;
1039             case EIO:
1040                 /* Could ignore EIO, see spec. */
1041                 /* fall through */
1042             default:
1043                 msg_Err( p_demux, "Failed to wait (VIDIOC_DQBUF)" );
1044                 return 0;
1045             }
1046         }
1047
1048         /* Find frame? */
1049         unsigned int i;
1050         for( i = 0; i < p_sys->i_nbuffers; i++ )
1051         {
1052             if( buf.m.userptr == (unsigned long)p_sys->p_buffers[i].start &&
1053                 buf.length == p_sys->p_buffers[i].length ) break;
1054         }
1055
1056         if( i >= p_sys->i_nbuffers )
1057         {
1058             msg_Err( p_demux, "Failed capturing new frame as i>=nbuffers" );
1059             return 0;
1060         }
1061
1062         p_block = ProcessVideoFrame( p_demux, (uint8_t*)buf.m.userptr, buf.bytesused );
1063         if( !p_block ) return 0;
1064
1065         /* Unlock */
1066         if( ioctl( p_sys->i_fd_video, VIDIOC_QBUF, &buf ) < 0 )
1067         {
1068             msg_Err (p_demux, "Failed to unlock (VIDIOC_QBUF)");
1069             return 0;
1070         }
1071
1072         break;
1073
1074     }
1075
1076     /* Timestamp */
1077     p_sys->i_video_pts = p_block->i_pts = p_block->i_dts = mdate();
1078
1079     return p_block;
1080 }
1081
1082 /*****************************************************************************
1083  * ProcessVideoFrame: Helper function to take a buffer and copy it into
1084  * a new block
1085  *****************************************************************************/
1086 static block_t* ProcessVideoFrame( demux_t *p_demux, uint8_t *p_frame, size_t i_size )
1087 {
1088     block_t *p_block;
1089
1090     if( !p_frame ) return 0;
1091
1092     /* New block */
1093     if( !( p_block = block_New( p_demux, i_size ) ) )
1094     {
1095         msg_Warn( p_demux, "Cannot get new block" );
1096         return 0;
1097     }
1098
1099     /* Copy frame */
1100     memcpy( p_block->p_buffer, p_frame, i_size );
1101
1102     return p_block;
1103 }
1104
1105 /*****************************************************************************
1106  * GrabAudio: Grab an audio frame
1107  *****************************************************************************/
1108 static block_t* GrabAudio( demux_t *p_demux )
1109 {
1110     demux_sys_t *p_sys = p_demux->p_sys;
1111     struct audio_buf_info buf_info;
1112     int i_read, i_correct;
1113     block_t *p_block;
1114
1115     if( p_sys->p_block_audio ) p_block = p_sys->p_block_audio;
1116     else p_block = block_New( p_demux, p_sys->i_audio_max_frame_size );
1117
1118     if( !p_block )
1119     {
1120         msg_Warn( p_demux, "cannot get block" );
1121         return 0;
1122     }
1123
1124     p_sys->p_block_audio = p_block;
1125
1126 #ifdef HAVE_ALSA
1127     if( p_sys->b_use_alsa )
1128     {
1129         /* ALSA */
1130         i_read = snd_pcm_readi( p_sys->p_alsa_pcm, p_block->p_buffer, p_sys->i_alsa_chunk_size );
1131         if( i_read <= 0 )
1132         {
1133             int i_resume;
1134             switch( i_read )
1135             {
1136                 case -EAGAIN:
1137                     break;
1138                 case -EPIPE:
1139                     /* xrun */
1140                     snd_pcm_prepare( p_sys->p_alsa_pcm );
1141                     break;
1142                 case -ESTRPIPE:
1143                     /* suspend */
1144                     i_resume = snd_pcm_resume( p_sys->p_alsa_pcm );
1145                     if( i_resume < 0 && i_resume != -EAGAIN ) snd_pcm_prepare( p_sys->p_alsa_pcm );
1146                     break;
1147                 default:
1148                     msg_Err( p_demux, "Failed to read alsa frame (%s)", snd_strerror( i_read ) );
1149                     return 0;
1150             }
1151         }
1152         else
1153         {
1154             /* convert from frames to bytes */
1155             i_read *= p_sys->i_alsa_frame_size;
1156         }
1157     }
1158     else
1159 #endif
1160     {
1161         /* OSS */
1162         i_read = read( p_sys->i_fd_audio, p_block->p_buffer,
1163                     p_sys->i_audio_max_frame_size );
1164     }
1165
1166     if( i_read <= 0 ) return 0;
1167
1168     p_block->i_buffer = i_read;
1169     p_sys->p_block_audio = 0;
1170
1171     /* Correct the date because of kernel buffering */
1172     i_correct = i_read;
1173 #ifdef HAVE_ALSA
1174     if( !p_sys->b_use_alsa )
1175 #endif
1176     {
1177         /* OSS */
1178         if( ioctl( p_sys->i_fd_audio, SNDCTL_DSP_GETISPACE, &buf_info ) == 0 )
1179         {
1180             i_correct += buf_info.bytes;
1181         }
1182     }
1183 #ifdef HAVE_ALSA
1184     else
1185     {
1186         /* ALSA */
1187         int i_err;
1188         snd_pcm_sframes_t delay = 0;
1189         if( ( i_err = snd_pcm_delay( p_sys->p_alsa_pcm, &delay ) ) >= 0 )
1190         {
1191             int i_correction_delta = delay * p_sys->i_alsa_frame_size;
1192             /* Test for overrun */
1193             if( i_correction_delta>p_sys->i_audio_max_frame_size )
1194             {
1195                 msg_Warn( p_demux, "ALSA read overrun" );
1196                 i_correction_delta = p_sys->i_audio_max_frame_size;
1197                 snd_pcm_prepare( p_sys->p_alsa_pcm );
1198             }
1199             i_correct += i_correction_delta;
1200         }
1201         else
1202         {
1203             /* delay failed so reset */
1204             msg_Warn( p_demux, "ALSA snd_pcm_delay failed (%s)", snd_strerror( i_err ) );
1205             snd_pcm_prepare( p_sys->p_alsa_pcm );
1206         }
1207     }
1208 #endif
1209
1210     /* Timestamp */
1211     p_block->i_pts = p_block->i_dts =
1212         mdate() - I64C(1000000) * (mtime_t)i_correct /
1213         2 / ( p_sys->b_stereo ? 2 : 1) / p_sys->i_sample_rate;
1214
1215     return p_block;
1216 }
1217
1218 /*****************************************************************************
1219  * Helper function to initalise video IO using the Read method
1220  *****************************************************************************/
1221 static int InitRead( demux_t *p_demux, int i_fd, unsigned int i_buffer_size )
1222 {
1223     demux_sys_t *p_sys = p_demux->p_sys;
1224
1225     p_sys->p_buffers = calloc( 1, sizeof( *p_sys->p_buffers ) );
1226     if( !p_sys->p_buffers )
1227     {
1228         msg_Err( p_demux, "Out of memory" );
1229         goto open_failed;
1230     }
1231
1232     p_sys->p_buffers[0].length = i_buffer_size;
1233     p_sys->p_buffers[0].start = malloc( i_buffer_size );
1234     if( !p_sys->p_buffers[0].start )
1235     {
1236         msg_Err( p_demux, "Out of memory" );
1237         goto open_failed;
1238     }
1239
1240     return VLC_SUCCESS;
1241
1242 open_failed:
1243     return VLC_EGENERIC;
1244
1245 }
1246
1247 /*****************************************************************************
1248  * Helper function to initalise video IO using the mmap method
1249  *****************************************************************************/
1250 static int InitMmap( demux_t *p_demux, int i_fd )
1251 {
1252     demux_sys_t *p_sys = p_demux->p_sys;
1253     struct v4l2_requestbuffers req;
1254
1255     memset( &req, 0, sizeof(req) );
1256     req.count = 4;
1257     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1258     req.memory = V4L2_MEMORY_MMAP;
1259
1260     if( ioctl( i_fd, VIDIOC_REQBUFS, &req ) < 0 )
1261     {
1262         msg_Err( p_demux, "device does not support mmap i/o" );
1263         goto open_failed;
1264     }
1265
1266     if( req.count < 2 )
1267     {
1268         msg_Err( p_demux, "Insufficient buffer memory" );
1269         goto open_failed;
1270     }
1271
1272     p_sys->p_buffers = calloc( req.count, sizeof( *p_sys->p_buffers ) );
1273     if( !p_sys->p_buffers )
1274     {
1275         msg_Err( p_demux, "Out of memory" );
1276         goto open_failed;
1277     }
1278
1279     for( p_sys->i_nbuffers = 0; p_sys->i_nbuffers < req.count; ++p_sys->i_nbuffers )
1280     {
1281         struct v4l2_buffer buf;
1282
1283         memset( &buf, 0, sizeof(buf) );
1284         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1285         buf.memory = V4L2_MEMORY_MMAP;
1286         buf.index = p_sys->i_nbuffers;
1287
1288         if( ioctl( i_fd, VIDIOC_QUERYBUF, &buf ) < 0 )
1289         {
1290             msg_Err( p_demux, "VIDIOC_QUERYBUF" );
1291             goto open_failed;
1292         }
1293
1294         p_sys->p_buffers[p_sys->i_nbuffers].length = buf.length;
1295         p_sys->p_buffers[p_sys->i_nbuffers].start =
1296             mmap( NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, i_fd, buf.m.offset );
1297
1298         if( p_sys->p_buffers[p_sys->i_nbuffers].start == MAP_FAILED )
1299         {
1300             msg_Err( p_demux, "mmap failed (%m)" );
1301             goto open_failed;
1302         }
1303     }
1304
1305     return VLC_SUCCESS;
1306
1307 open_failed:
1308     return VLC_EGENERIC;
1309
1310 }
1311
1312 /*****************************************************************************
1313  * Helper function to initalise video IO using the userbuf method
1314  *****************************************************************************/
1315 static int InitUserP( demux_t *p_demux, int i_fd, unsigned int i_buffer_size )
1316 {
1317     demux_sys_t *p_sys = p_demux->p_sys;
1318     struct v4l2_requestbuffers req;
1319     unsigned int i_page_size;
1320
1321     i_page_size = getpagesize();
1322     i_buffer_size = ( i_buffer_size + i_page_size - 1 ) & ~( i_page_size - 1);
1323
1324     memset( &req, 0, sizeof(req) );
1325     req.count = 4;
1326     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1327     req.memory = V4L2_MEMORY_USERPTR;
1328
1329     if( ioctl( i_fd, VIDIOC_REQBUFS, &req ) < 0 )
1330     {
1331         msg_Err( p_demux, "device does not support user pointer i/o" );
1332         goto open_failed;
1333     }
1334
1335     p_sys->p_buffers = calloc( 4, sizeof( *p_sys->p_buffers ) );
1336     if( !p_sys->p_buffers )
1337     {
1338         msg_Err( p_demux, "Out of memory" );
1339         goto open_failed;
1340     }
1341
1342     for( p_sys->i_nbuffers = 0; p_sys->i_nbuffers < 4; ++p_sys->i_nbuffers )
1343     {
1344         p_sys->p_buffers[p_sys->i_nbuffers].length = i_buffer_size;
1345         p_sys->p_buffers[p_sys->i_nbuffers].start =
1346             vlc_memalign( &p_sys->p_buffers[p_sys->i_nbuffers].orig_userp,
1347                 /* boundary */ i_page_size, i_buffer_size );
1348
1349         if( !p_sys->p_buffers[p_sys->i_nbuffers].start )
1350         {
1351             msg_Err( p_demux, "out of memory" );
1352             goto open_failed;
1353         }
1354     }
1355
1356     return VLC_SUCCESS;
1357
1358 open_failed:
1359     return VLC_EGENERIC;
1360
1361 }
1362
1363 /*****************************************************************************
1364  * IsPixelFormatSupported: returns true if the specified V4L2 pixel format is
1365  * in the array of supported formats returned by the driver
1366  *****************************************************************************/
1367 vlc_bool_t IsPixelFormatSupported( demux_t *p_demux, unsigned int i_pixelformat )
1368 {
1369     demux_sys_t *p_sys = p_demux->p_sys;
1370
1371     for( int i_index = 0; i_index < p_sys->i_codec; i_index++ )
1372     {
1373         if( p_sys->p_codecs[i_index].pixelformat == i_pixelformat ) return VLC_TRUE;
1374     }
1375
1376     return VLC_FALSE;
1377 }
1378
1379 /*****************************************************************************
1380  * OpenVideoDev: open and set up the video device and probe for capabilities
1381  *****************************************************************************/
1382 int OpenVideoDev( demux_t *p_demux, char *psz_device )
1383 {
1384     int i_fd;
1385     demux_sys_t *p_sys = p_demux->p_sys;
1386     struct v4l2_cropcap cropcap;
1387     struct v4l2_crop crop;
1388     struct v4l2_format fmt;
1389     unsigned int i_min;
1390     enum v4l2_buf_type buf_type;
1391
1392     if( ( i_fd = open( psz_device, O_RDWR ) ) < 0 )
1393     {
1394         msg_Err( p_demux, "cannot open device (%m)" );
1395         goto open_failed;
1396     }
1397
1398     /* Select standard */
1399
1400     if( p_sys->i_selected_standard_id != V4L2_STD_UNKNOWN )
1401     {
1402         if( ioctl( i_fd, VIDIOC_S_STD, &p_sys->i_selected_standard_id ) < 0 )
1403         {
1404             msg_Err( p_demux, "cannot set standard (%m)" );
1405             goto open_failed;
1406         }
1407         msg_Dbg( p_demux, "Set standard" );
1408     }
1409
1410     /* Select input */
1411
1412     if( p_sys->i_selected_input > p_sys->i_input )
1413     {
1414         msg_Warn( p_demux, "invalid input. Using the default one" );
1415         p_sys->i_selected_input = 0;
1416     }
1417
1418     if( ioctl( i_fd, VIDIOC_S_INPUT, &p_sys->i_selected_input ) < 0 )
1419     {
1420         msg_Err( p_demux, "cannot set input (%m)" );
1421         goto open_failed;
1422     }
1423
1424     /* Verify device support for the various IO methods */
1425     switch( p_sys->io )
1426     {
1427         case IO_METHOD_READ:
1428             if( !(p_sys->dev_cap.capabilities & V4L2_CAP_READWRITE) )
1429             {
1430                 msg_Err( p_demux, "device does not support read i/o" );
1431                 goto open_failed;
1432             }
1433             break;
1434
1435         case IO_METHOD_MMAP:
1436         case IO_METHOD_USERPTR:
1437             if( !(p_sys->dev_cap.capabilities & V4L2_CAP_STREAMING) )
1438             {
1439                 msg_Err( p_demux, "device does not support streaming i/o" );
1440                 goto open_failed;
1441             }
1442             break;
1443
1444         default:
1445             msg_Err( p_demux, "io method not supported" );
1446             goto open_failed;
1447     }
1448
1449     /* Reset Cropping */
1450     memset( &cropcap, 0, sizeof(cropcap) );
1451     cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1452     if( ioctl( i_fd, VIDIOC_CROPCAP, &cropcap ) >= 0 )
1453     {
1454         crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1455         crop.c = cropcap.defrect; /* reset to default */
1456         if( ioctl( i_fd, VIDIOC_S_CROP, &crop ) < 0 )
1457         {
1458             switch( errno )
1459             {
1460                 case EINVAL:
1461                     /* Cropping not supported. */
1462                     break;
1463                 default:
1464                     /* Errors ignored. */
1465                     break;
1466             }
1467         }
1468     }
1469
1470     /* Try and find default resolution if not specified */
1471     memset( &fmt, 0, sizeof(fmt) );
1472     fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1473
1474     if( p_sys->i_width <= 0 || p_sys->i_height <= 0 )
1475     {
1476         if( ioctl( i_fd, VIDIOC_G_FMT, &fmt ) < 0 )
1477         {
1478             msg_Err( p_demux, "Cannot get default width and height." );
1479             goto open_failed;
1480         }
1481
1482         p_sys->i_width = fmt.fmt.pix.width;
1483         p_sys->i_height = fmt.fmt.pix.height;
1484
1485         if( fmt.fmt.pix.field == V4L2_FIELD_ALTERNATE )
1486         {
1487             p_sys->i_height = p_sys->i_height * 2;
1488         }
1489     }
1490     else
1491     {
1492         msg_Dbg( p_demux, "trying specified size %dx%d", p_sys->i_width, p_sys->i_height );
1493     }
1494
1495     fmt.fmt.pix.width = p_sys->i_width;
1496     fmt.fmt.pix.height = p_sys->i_height;
1497     fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
1498
1499     /* Test and set Chroma */
1500     fmt.fmt.pix.pixelformat = 0;
1501     if( p_sys->psz_requested_chroma && strlen( p_sys->psz_requested_chroma ) > 0 )
1502     {
1503         /* User specified chroma */
1504         if( strlen( p_sys->psz_requested_chroma ) >= 4 )
1505         {
1506             int i_requested_fourcc = VLC_FOURCC(
1507                 p_sys->psz_requested_chroma[0], p_sys->psz_requested_chroma[1],
1508                 p_sys->psz_requested_chroma[2], p_sys->psz_requested_chroma[3] );
1509             for( int i = 0; v4l2chroma_to_fourcc[i].i_v4l2 != 0; i++ )
1510             {
1511                 if( v4l2chroma_to_fourcc[i].i_fourcc == i_requested_fourcc )
1512                 {
1513                     fmt.fmt.pix.pixelformat = v4l2chroma_to_fourcc[i].i_v4l2;
1514                     break;
1515                 }
1516             }
1517         }
1518         /* Try and set user chroma */
1519         if( !IsPixelFormatSupported( p_demux, fmt.fmt.pix.pixelformat ) || ( fmt.fmt.pix.pixelformat && ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 ) )
1520         {
1521             msg_Warn( p_demux, "Driver is unable to use specified chroma %s. Trying defaults.", p_sys->psz_requested_chroma );
1522             fmt.fmt.pix.pixelformat = 0;
1523         }
1524     }
1525
1526     /* If no user specified chroma, find best */
1527     if( !fmt.fmt.pix.pixelformat )
1528     {
1529         fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YVU420;
1530         if( !IsPixelFormatSupported( p_demux, fmt.fmt.pix.pixelformat ) || ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 )
1531         {
1532             fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUV422P;
1533             if( !IsPixelFormatSupported( p_demux, fmt.fmt.pix.pixelformat ) || ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 )
1534             {
1535                 fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
1536                 if( !IsPixelFormatSupported( p_demux, fmt.fmt.pix.pixelformat ) || ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 )
1537                 {
1538                     msg_Err( p_demux, "Could not select any of the default chromas!" );
1539                     goto open_failed;
1540                 }
1541             }
1542         }
1543     }
1544
1545     /* Reassign width, height and chroma incase driver override */
1546     p_sys->i_width = fmt.fmt.pix.width;
1547     p_sys->i_height = fmt.fmt.pix.height;
1548
1549     /* Look up final fourcc */
1550     p_sys->i_fourcc = 0;
1551     for( int i = 0; v4l2chroma_to_fourcc[i].i_fourcc != 0; i++ )
1552     {
1553         if( v4l2chroma_to_fourcc[i].i_v4l2 == fmt.fmt.pix.pixelformat )
1554         {
1555             p_sys->i_fourcc = v4l2chroma_to_fourcc[i].i_fourcc;
1556             break;
1557         }
1558     }
1559
1560     /* Buggy driver paranoia */
1561     i_min = fmt.fmt.pix.width * 2;
1562     if( fmt.fmt.pix.bytesperline < i_min )
1563         fmt.fmt.pix.bytesperline = i_min;
1564     i_min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
1565     if( fmt.fmt.pix.sizeimage < i_min )
1566         fmt.fmt.pix.sizeimage = i_min;
1567
1568 #ifdef VIDIOC_ENUM_FRAMEINTERVALS
1569     /* This is new in Linux 2.6.19 */
1570     /* List supported frame rates */
1571     struct v4l2_frmivalenum frmival;
1572     frmival.index = 0;
1573     frmival.pixel_format = fmt.fmt.pix.pixelformat;
1574     frmival.width = p_sys->i_width;
1575     frmival.height = p_sys->i_height;
1576     if( ioctl( i_fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival ) >= 0 )
1577     {
1578         char sz_fourcc[5];
1579         memset( &sz_fourcc, 0, sizeof( sz_fourcc ) );
1580         vlc_fourcc_to_char( p_sys->i_fourcc, &sz_fourcc );
1581         msg_Dbg( p_demux, "supported frame intervals for %4s, %dx%d:",
1582                  sz_fourcc, frmival.width, frmival.height );
1583         switch( frmival.type )
1584         {
1585             case V4L2_FRMIVAL_TYPE_DISCRETE:
1586                 do
1587                 {
1588                     msg_Dbg( p_demux, "    supported frame interval: %d/%d",
1589                              frmival.discrete.numerator,
1590                              frmival.discrete.denominator );
1591                     frmival.index++;
1592                 } while( ioctl( i_fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival ) >= 0 );
1593                 break;
1594             case V4L2_FRMIVAL_TYPE_STEPWISE:
1595                 msg_Dbg( p_demux, "    supported frame intervals: %d/%d to "
1596                          "%d/%d using %d/%d increments",
1597                          frmival.stepwise.min.numerator,
1598                          frmival.stepwise.min.denominator,
1599                          frmival.stepwise.max.numerator,
1600                          frmival.stepwise.max.denominator,
1601                          frmival.stepwise.step.numerator,
1602                          frmival.stepwise.step.denominator );
1603                 break;
1604             case V4L2_FRMIVAL_TYPE_CONTINUOUS:
1605                 msg_Dbg( p_demux, "    supported frame intervals: %d/%d to %d/%d",
1606                          frmival.stepwise.min.numerator,
1607                          frmival.stepwise.min.denominator,
1608                          frmival.stepwise.max.numerator,
1609                          frmival.stepwise.max.denominator );
1610                 break;
1611         }
1612     }
1613 #endif
1614
1615     ControlList( p_demux, i_fd,
1616                       var_GetBool( p_demux, "v4l2-controls-reset" ) );
1617
1618     /* Init IO method */
1619     switch( p_sys->io )
1620     {
1621     case IO_METHOD_READ:
1622         if( InitRead( p_demux, i_fd, fmt.fmt.pix.sizeimage ) != VLC_SUCCESS ) goto open_failed;
1623         break;
1624
1625     case IO_METHOD_MMAP:
1626         if( InitMmap( p_demux, i_fd ) != VLC_SUCCESS ) goto open_failed;
1627         break;
1628
1629     case IO_METHOD_USERPTR:
1630         if( InitUserP( p_demux, i_fd, fmt.fmt.pix.sizeimage ) != VLC_SUCCESS ) goto open_failed;
1631         break;
1632
1633     }
1634
1635     /* Add */
1636     es_format_t es_fmt;
1637     es_format_Init( &es_fmt, VIDEO_ES, p_sys->i_fourcc );
1638     es_fmt.video.i_width  = p_sys->i_width;
1639     es_fmt.video.i_height = p_sys->i_height;
1640     es_fmt.video.i_aspect = 4 * VOUT_ASPECT_FACTOR / 3;
1641
1642     /* Setup rgb mask for RGB formats */
1643     if( p_sys->i_fourcc == VLC_FOURCC( 'R','V','2','4' ) )
1644     {
1645         /* This is in BGR format */
1646         es_fmt.video.i_bmask = 0x00ff0000;
1647         es_fmt.video.i_gmask = 0x0000ff00;
1648         es_fmt.video.i_rmask = 0x000000ff;
1649     }
1650
1651     msg_Dbg( p_demux, "added new video es %4.4s %dx%d",
1652         (char*)&es_fmt.i_codec, es_fmt.video.i_width, es_fmt.video.i_height );
1653     p_sys->p_es_video = es_out_Add( p_demux->out, &es_fmt );
1654
1655     /* Start Capture */
1656
1657     switch( p_sys->io )
1658     {
1659     case IO_METHOD_READ:
1660         /* Nothing to do */
1661         break;
1662
1663     case IO_METHOD_MMAP:
1664         for (unsigned int i = 0; i < p_sys->i_nbuffers; ++i)
1665         {
1666             struct v4l2_buffer buf;
1667
1668             memset( &buf, 0, sizeof(buf) );
1669             buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1670             buf.memory = V4L2_MEMORY_MMAP;
1671             buf.index = i;
1672
1673             if( ioctl( i_fd, VIDIOC_QBUF, &buf ) < 0 )
1674             {
1675                 msg_Err( p_demux, "VIDIOC_QBUF failed" );
1676                 goto open_failed;
1677             }
1678         }
1679
1680         buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1681         if( ioctl( i_fd, VIDIOC_STREAMON, &buf_type ) < 0 )
1682         {
1683             msg_Err( p_demux, "VIDIOC_STREAMON failed" );
1684             goto open_failed;
1685         }
1686
1687         break;
1688
1689     case IO_METHOD_USERPTR:
1690         for( unsigned int i = 0; i < p_sys->i_nbuffers; ++i )
1691         {
1692             struct v4l2_buffer buf;
1693
1694             memset( &buf, 0, sizeof(buf) );
1695             buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1696             buf.memory = V4L2_MEMORY_USERPTR;
1697             buf.index = i;
1698             buf.m.userptr = (unsigned long)p_sys->p_buffers[i].start;
1699             buf.length = p_sys->p_buffers[i].length;
1700
1701             if( ioctl( i_fd, VIDIOC_QBUF, &buf ) < 0 )
1702             {
1703                 msg_Err( p_demux, "VIDIOC_QBUF failed" );
1704                 goto open_failed;
1705             }
1706         }
1707
1708         buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1709         if( ioctl( i_fd, VIDIOC_STREAMON, &buf_type ) < 0 )
1710         {
1711             msg_Err( p_demux, "VIDIOC_STREAMON failed" );
1712             goto open_failed;
1713         }
1714
1715         break;
1716     }
1717
1718     /* report fps */
1719     if( p_sys->f_fps >= 0.1 )
1720     {
1721         msg_Dbg( p_demux, "User set fps=%f", p_sys->f_fps );
1722     }
1723
1724     return i_fd;
1725
1726 open_failed:
1727     if( i_fd >= 0 ) close( i_fd );
1728     return -1;
1729
1730 }
1731
1732 #ifdef HAVE_ALSA
1733 /*****************************************************************************
1734  * ResolveALSADeviceName: Change any . to : in the ALSA device name
1735  *****************************************************************************/
1736 char* ResolveALSADeviceName( char *psz_device )
1737 {
1738     char* psz_alsa_name = strdup( psz_device );
1739     for( unsigned int i = 0; i < strlen( psz_device ); i++ )
1740     {
1741         if( psz_alsa_name[i] == '.' ) psz_alsa_name[i] = ':';
1742     }
1743     return psz_alsa_name;
1744 }
1745 #endif
1746
1747 /*****************************************************************************
1748  * OpenAudioDev: open and set up the audio device and probe for capabilities
1749  *****************************************************************************/
1750 int OpenAudioDev( demux_t *p_demux, char *psz_device )
1751 {
1752     demux_sys_t *p_sys = p_demux->p_sys;
1753     int i_fd = 0;
1754     int i_format;
1755 #ifdef HAVE_ALSA
1756     p_sys->p_alsa_pcm = NULL;
1757     char* psz_alsa_device_name = ResolveALSADeviceName( psz_device );
1758     snd_pcm_hw_params_t *p_hw_params = NULL;
1759     snd_pcm_uframes_t buffer_size;
1760     snd_pcm_uframes_t chunk_size;
1761 #endif
1762
1763 #ifdef HAVE_ALSA
1764     if( p_sys->b_use_alsa )
1765     {
1766         /* ALSA */
1767
1768         int i_err;
1769
1770         if( ( i_err = snd_pcm_open( &p_sys->p_alsa_pcm, psz_alsa_device_name,
1771             SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK ) ) < 0)
1772         {
1773             msg_Err( p_demux, "Cannot open ALSA audio device %s (%s)",
1774                 psz_alsa_device_name,
1775                 snd_strerror( i_err ) );
1776             goto adev_fail;
1777         }
1778
1779         if( ( i_err = snd_pcm_nonblock( p_sys->p_alsa_pcm, 1 ) ) < 0)
1780         {
1781             msg_Err( p_demux, "Cannot set ALSA nonblock (%s)", 
1782                 snd_strerror( i_err ) );
1783             goto adev_fail;
1784         }
1785
1786         /* Begin setting hardware parameters */
1787
1788         if( ( i_err = snd_pcm_hw_params_malloc( &p_hw_params ) ) < 0 )
1789         {
1790             msg_Err( p_demux, "ALSA: cannot allocate hardware parameter structure (%s)",
1791                 snd_strerror( i_err ) );
1792             goto adev_fail;
1793         }
1794
1795         if( ( i_err = snd_pcm_hw_params_any( p_sys->p_alsa_pcm, p_hw_params ) ) < 0 )
1796         {
1797             msg_Err( p_demux, "ALSA: cannot initialize hardware parameter structure (%s)",
1798                 snd_strerror( i_err ) );
1799             goto adev_fail;
1800         }
1801
1802         /* Set Interleaved access */
1803         if( ( i_err = snd_pcm_hw_params_set_access( p_sys->p_alsa_pcm, p_hw_params, SND_PCM_ACCESS_RW_INTERLEAVED ) ) < 0 )
1804         {
1805             msg_Err( p_demux, "ALSA: cannot set access type (%s)",
1806                 snd_strerror( i_err ) );
1807             goto adev_fail;
1808         }
1809
1810         /* Set 16 bit little endian */
1811         if( ( i_err = snd_pcm_hw_params_set_format( p_sys->p_alsa_pcm, p_hw_params, SND_PCM_FORMAT_S16_LE ) ) < 0 )
1812         {
1813             msg_Err( p_demux, "ALSA: cannot set sample format (%s)",
1814                 snd_strerror( i_err ) );
1815             goto adev_fail;
1816         }
1817
1818         /* Set sample rate */
1819 #ifdef HAVE_ALSA_NEW_API
1820         i_err = snd_pcm_hw_params_set_rate_near( p_sys->p_alsa_pcm, p_hw_params, &p_sys->i_sample_rate, NULL );
1821 #else
1822         i_err = snd_pcm_hw_params_set_rate_near( p_sys->p_alsa_pcm, p_hw_params, p_sys->i_sample_rate, NULL );
1823 #endif
1824         if( i_err < 0 )
1825         {
1826             msg_Err( p_demux, "ALSA: cannot set sample rate (%s)",
1827                 snd_strerror( i_err ) );
1828             goto adev_fail;
1829         }
1830
1831         /* Set channels */
1832         unsigned int channels = p_sys->b_stereo ? 2 : 1;
1833         if( ( i_err = snd_pcm_hw_params_set_channels( p_sys->p_alsa_pcm, p_hw_params, channels ) ) < 0 )
1834         {
1835             channels = ( channels==1 ) ? 2 : 1;
1836             msg_Warn( p_demux, "ALSA: cannot set channel count (%s). Trying with channels=%d",
1837                 snd_strerror( i_err ),
1838                 channels );
1839             if( ( i_err = snd_pcm_hw_params_set_channels( p_sys->p_alsa_pcm, p_hw_params, channels ) ) < 0 )
1840             {
1841                 msg_Err( p_demux, "ALSA: cannot set channel count (%s)",
1842                     snd_strerror( i_err ) );
1843                 goto adev_fail;
1844             }
1845             p_sys->b_stereo = ( channels == 2 );
1846         }
1847
1848         /* Set metrics for buffer calculations later */
1849         unsigned int buffer_time;
1850         if( ( i_err = snd_pcm_hw_params_get_buffer_time_max(p_hw_params, &buffer_time, 0) ) < 0 )
1851         {
1852             msg_Err( p_demux, "ALSA: cannot get buffer time max (%s)",
1853                 snd_strerror( i_err ) );
1854             goto adev_fail;
1855         }
1856         if (buffer_time > 500000) buffer_time = 500000;
1857
1858         /* Set period time */
1859         unsigned int period_time = buffer_time / 4;
1860 #ifdef HAVE_ALSA_NEW_API
1861         i_err = snd_pcm_hw_params_set_period_time_near( p_sys->p_alsa_pcm, p_hw_params, &period_time, 0 );
1862 #else
1863         i_err = snd_pcm_hw_params_set_period_time_near( p_sys->p_alsa_pcm, p_hw_params, period_time, 0 );
1864 #endif
1865         if( i_err < 0 )
1866         {
1867             msg_Err( p_demux, "ALSA: cannot set period time (%s)",
1868                 snd_strerror( i_err ) );
1869             goto adev_fail;
1870         }
1871
1872         /* Set buffer time */
1873 #ifdef HAVE_ALSA_NEW_API
1874         i_err = snd_pcm_hw_params_set_buffer_time_near( p_sys->p_alsa_pcm, p_hw_params, &buffer_time, 0 );
1875 #else
1876         i_err = snd_pcm_hw_params_set_buffer_time_near( p_sys->p_alsa_pcm, p_hw_params, buffer_time, 0 );
1877 #endif
1878         if( i_err < 0 )
1879         {
1880             msg_Err( p_demux, "ALSA: cannot set buffer time (%s)",
1881                 snd_strerror( i_err ) );
1882             goto adev_fail;
1883         }
1884
1885         /* Apply new hardware parameters */
1886         if( ( i_err = snd_pcm_hw_params( p_sys->p_alsa_pcm, p_hw_params ) ) < 0 )
1887         {
1888             msg_Err( p_demux, "ALSA: cannot set hw parameters (%s)",
1889                 snd_strerror( i_err ) );
1890             goto adev_fail;
1891         }
1892
1893         /* Get various buffer metrics */
1894         snd_pcm_hw_params_get_period_size( p_hw_params, &chunk_size, 0 );
1895         snd_pcm_hw_params_get_buffer_size( p_hw_params, &buffer_size );
1896         if (chunk_size == buffer_size)
1897         {
1898             msg_Err( p_demux, "ALSA: period cannot equal buffer size (%lu == %lu)",
1899                 chunk_size, buffer_size);
1900             goto adev_fail;
1901         }
1902
1903         int bits_per_sample = snd_pcm_format_physical_width(SND_PCM_FORMAT_S16_LE);
1904         int bits_per_frame = bits_per_sample * channels;
1905
1906         p_sys->i_alsa_chunk_size = chunk_size;
1907         p_sys->i_alsa_frame_size = (bits_per_sample / 8) * channels;
1908         p_sys->i_audio_max_frame_size = chunk_size * bits_per_frame / 8; 
1909
1910         snd_pcm_hw_params_free( p_hw_params );
1911         p_hw_params = NULL;
1912
1913         /* Prep device */
1914         if( ( i_err = snd_pcm_prepare( p_sys->p_alsa_pcm ) ) < 0 )
1915         {
1916             msg_Err( p_demux, "ALSA: cannot prepare audio interface for use (%s)",
1917                 snd_strerror( i_err ) );
1918             goto adev_fail;
1919         }
1920
1921         /* Return a fake handle so other tests work */
1922         i_fd = 1;
1923
1924     }
1925     else
1926 #endif /* HAVE_ALSA */
1927     {
1928         /* OSS */
1929
1930         if( (i_fd = open( psz_device, O_RDONLY | O_NONBLOCK )) < 0 )
1931         {
1932             msg_Err( p_demux, "cannot open OSS audio device (%m)" );
1933             goto adev_fail;
1934         }
1935
1936         i_format = AFMT_S16_LE;
1937         if( ioctl( i_fd, SNDCTL_DSP_SETFMT, &i_format ) < 0
1938             || i_format != AFMT_S16_LE )
1939         {
1940             msg_Err( p_demux, "cannot set audio format (16b little endian) "
1941                      "(%m)" );
1942             goto adev_fail;
1943         }
1944
1945         if( ioctl( i_fd, SNDCTL_DSP_STEREO,
1946                    &p_sys->b_stereo ) < 0 )
1947         {
1948             msg_Err( p_demux, "cannot set audio channels count (%m)" );
1949             goto adev_fail;
1950         }
1951
1952         if( ioctl( i_fd, SNDCTL_DSP_SPEED,
1953                    &p_sys->i_sample_rate ) < 0 )
1954         {
1955             msg_Err( p_demux, "cannot set audio sample rate (%m)" );
1956             goto adev_fail;
1957         }
1958
1959         p_sys->i_audio_max_frame_size = 6 * 1024;
1960     }
1961
1962     msg_Dbg( p_demux, "opened adev=`%s' %s %dHz",
1963              psz_device, p_sys->b_stereo ? "stereo" : "mono",
1964              p_sys->i_sample_rate );
1965
1966     es_format_t fmt;
1967     es_format_Init( &fmt, AUDIO_ES, VLC_FOURCC('a','r','a','w') );
1968
1969     fmt.audio.i_channels = p_sys->b_stereo ? 2 : 1;
1970     fmt.audio.i_rate = p_sys->i_sample_rate;
1971     fmt.audio.i_bitspersample = 16;
1972     fmt.audio.i_blockalign = fmt.audio.i_channels * fmt.audio.i_bitspersample / 8;
1973     fmt.i_bitrate = fmt.audio.i_channels * fmt.audio.i_rate * fmt.audio.i_bitspersample;
1974
1975     msg_Dbg( p_demux, "new audio es %d channels %dHz",
1976       fmt.audio.i_channels, fmt.audio.i_rate );
1977
1978     p_sys->p_es_audio = es_out_Add( p_demux->out, &fmt );
1979
1980 #ifdef HAVE_ALSA
1981     free( psz_alsa_device_name );
1982 #endif
1983
1984     return i_fd;
1985
1986  adev_fail:
1987
1988     if( i_fd >= 0 ) close( i_fd );
1989
1990 #ifdef HAVE_ALSA
1991     if( p_hw_params ) snd_pcm_hw_params_free( p_hw_params );
1992     if( p_sys->p_alsa_pcm ) snd_pcm_close( p_sys->p_alsa_pcm );
1993     free( psz_alsa_device_name );
1994 #endif
1995
1996     return -1;
1997
1998 }
1999
2000 /*****************************************************************************
2001  * ProbeVideoDev: probe video for capabilities
2002  *****************************************************************************/
2003 vlc_bool_t ProbeVideoDev( demux_t *p_demux, char *psz_device )
2004 {
2005     int i_index;
2006     int i_standard;
2007
2008     int i_fd;
2009     demux_sys_t *p_sys = p_demux->p_sys;
2010
2011     if( ( i_fd = open( psz_device, O_RDWR ) ) < 0 )
2012     {
2013         msg_Err( p_demux, "cannot open video device (%m)" );
2014         goto open_failed;
2015     }
2016
2017     /* Get device capabilites */
2018
2019     if( ioctl( i_fd, VIDIOC_QUERYCAP, &p_sys->dev_cap ) < 0 )
2020     {
2021         msg_Err( p_demux, "cannot get video capabilities (%m)" );
2022         goto open_failed;
2023     }
2024
2025     msg_Dbg( p_demux, "V4L2 device: %s using driver: %s (version: %u.%u.%u) on %s",
2026                             p_sys->dev_cap.card,
2027                             p_sys->dev_cap.driver,
2028                             (p_sys->dev_cap.version >> 16) & 0xFF,
2029                             (p_sys->dev_cap.version >> 8) & 0xFF,
2030                             p_sys->dev_cap.version & 0xFF,
2031                             p_sys->dev_cap.bus_info );
2032
2033     msg_Dbg( p_demux, "the device has the capabilities: (%c) Video Capure, "
2034                                                        "(%c) Audio, "
2035                                                        "(%c) Tuner",
2036              ( p_sys->dev_cap.capabilities & V4L2_CAP_VIDEO_CAPTURE  ? 'X':' '),
2037              ( p_sys->dev_cap.capabilities & V4L2_CAP_AUDIO  ? 'X':' '),
2038              ( p_sys->dev_cap.capabilities & V4L2_CAP_TUNER  ? 'X':' ') );
2039
2040     msg_Dbg( p_demux, "supported I/O methods are: (%c) Read/Write, "
2041                                                  "(%c) Streaming, "
2042                                                  "(%c) Asynchronous",
2043             ( p_sys->dev_cap.capabilities & V4L2_CAP_READWRITE ? 'X':' ' ),
2044             ( p_sys->dev_cap.capabilities & V4L2_CAP_STREAMING ? 'X':' ' ),
2045             ( p_sys->dev_cap.capabilities & V4L2_CAP_ASYNCIO ? 'X':' ' ) );
2046
2047     /* Now, enumerate all the video inputs. This is useless at the moment
2048        since we have no way to present that info to the user except with
2049        debug messages */
2050
2051     if( p_sys->dev_cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
2052     {
2053         struct v4l2_input t_input;
2054         t_input.index = 0;
2055         while( ioctl( i_fd, VIDIOC_ENUMINPUT, &t_input ) >= 0 )
2056         {
2057             p_sys->i_input++;
2058             t_input.index = p_sys->i_input;
2059         }
2060
2061         p_sys->p_inputs = calloc( 1, p_sys->i_input * sizeof( struct v4l2_input ) );
2062         if( !p_sys->p_inputs ) goto open_failed;
2063
2064         for( i_index = 0; i_index < p_sys->i_input; i_index++ )
2065         {
2066             p_sys->p_inputs[i_index].index = i_index;
2067
2068             if( ioctl( i_fd, VIDIOC_ENUMINPUT, &p_sys->p_inputs[i_index] ) )
2069             {
2070                 msg_Err( p_demux, "cannot get video input characteristics (%m)" );
2071                 goto open_failed;
2072             }
2073             msg_Dbg( p_demux, "video input %i (%s) has type: %s",
2074                                 i_index,
2075                                 p_sys->p_inputs[i_index].name,
2076                                 p_sys->p_inputs[i_index].type
2077                                         == V4L2_INPUT_TYPE_TUNER ?
2078                                         "Tuner adapter" :
2079                                         "External analog input" );
2080         }
2081     }
2082
2083     /* Probe video standards */
2084     if( p_sys->dev_cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
2085     {
2086         struct v4l2_standard t_standards;
2087         t_standards.index = 0;
2088         while( ioctl( i_fd, VIDIOC_ENUMSTD, &t_standards ) >=0 )
2089         {
2090             p_sys->i_standard++;
2091             t_standards.index = p_sys->i_standard;
2092         }
2093
2094         p_sys->p_standards = calloc( 1, p_sys->i_standard * sizeof( struct v4l2_standard ) );
2095         if( !p_sys->p_standards ) goto open_failed;
2096
2097         for( i_standard = 0; i_standard < p_sys->i_standard; i_standard++ )
2098         {
2099             p_sys->p_standards[i_standard].index = i_standard;
2100
2101             if( ioctl( i_fd, VIDIOC_ENUMSTD, &p_sys->p_standards[i_standard] ) )
2102             {
2103                 msg_Err( p_demux, "cannot get video input standards (%m)" );
2104                 goto open_failed;
2105             }
2106             msg_Dbg( p_demux, "video standard %i is: %s",
2107                                 i_standard,
2108                                 p_sys->p_standards[i_standard].name);
2109         }
2110     }
2111
2112     /* initialize the structures for the ioctls */
2113     for( i_index = 0; i_index < 32; i_index++ )
2114     {
2115         p_sys->p_audios[i_index].index = i_index;
2116     }
2117
2118     /* Probe audio inputs */
2119     if( p_sys->dev_cap.capabilities & V4L2_CAP_AUDIO )
2120     {
2121         while( p_sys->i_audio < 32 &&
2122                ioctl( i_fd, VIDIOC_S_AUDIO, &p_sys->p_audios[p_sys->i_audio] ) >= 0 )
2123         {
2124             if( ioctl( i_fd, VIDIOC_G_AUDIO, &p_sys->p_audios[ p_sys->i_audio] ) < 0 )
2125             {
2126                 msg_Err( p_demux, "cannot get audio input characteristics (%m)" );
2127                 goto open_failed;
2128             }
2129
2130             msg_Dbg( p_demux, "audio device %i (%s) is %s",
2131                                 p_sys->i_audio,
2132                                 p_sys->p_audios[p_sys->i_audio].name,
2133                                 p_sys->p_audios[p_sys->i_audio].capability &
2134                                                     V4L2_AUDCAP_STEREO ?
2135                                         "Stereo" : "Mono" );
2136
2137             p_sys->i_audio++;
2138         }
2139     }
2140
2141     /* List tuner caps */
2142     if( p_sys->dev_cap.capabilities & V4L2_CAP_TUNER )
2143     {
2144         struct v4l2_tuner tuner;
2145         memset( &tuner, 0, sizeof(tuner) );
2146         while( ioctl( i_fd, VIDIOC_G_TUNER, &tuner ) >= 0 )
2147         {
2148             p_sys->i_tuner++;
2149             memset( &tuner, 0, sizeof(tuner) );
2150             tuner.index = p_sys->i_tuner;
2151         }
2152
2153         p_sys->p_tuners = calloc( 1, p_sys->i_tuner * sizeof( struct v4l2_tuner ) );
2154         if( !p_sys->p_tuners ) goto open_failed;
2155
2156         for( i_index = 0; i_index < p_sys->i_tuner; i_index++ )
2157         {
2158             p_sys->p_tuners[i_index].index = i_index;
2159
2160             if( ioctl( i_fd, VIDIOC_G_TUNER, &p_sys->p_tuners[i_index] ) )
2161             {
2162                 msg_Err( p_demux, "cannot get tuner characteristics (%m)" );
2163                 goto open_failed;
2164             }
2165             msg_Dbg( p_demux, "tuner %i (%s) has type: %s, "
2166                               "frequency range: %.1f %s -> %.1f %s",
2167                                 i_index,
2168                                 p_sys->p_tuners[i_index].name,
2169                                 p_sys->p_tuners[i_index].type
2170                                         == V4L2_TUNER_RADIO ?
2171                                         "Radio" : "Analog TV",
2172                                 p_sys->p_tuners[i_index].rangelow * 62.5,
2173                                 p_sys->p_tuners[i_index].capability &
2174                                         V4L2_TUNER_CAP_LOW ?
2175                                         "Hz" : "kHz",
2176                                 p_sys->p_tuners[i_index].rangehigh * 62.5,
2177                                 p_sys->p_tuners[i_index].capability &
2178                                         V4L2_TUNER_CAP_LOW ?
2179                                         "Hz" : "kHz" );
2180         }
2181     }
2182
2183     /* Probe for available chromas */
2184     if( p_sys->dev_cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
2185     {
2186         struct v4l2_fmtdesc codec;
2187
2188         i_index = 0;
2189         memset( &codec, 0, sizeof(codec) );
2190         codec.index = i_index;
2191         codec.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2192
2193         while( ioctl( i_fd, VIDIOC_ENUM_FMT, &codec ) >= 0 )
2194         {
2195             i_index++;
2196             codec.index = i_index;
2197         }
2198
2199         p_sys->i_codec = i_index;
2200
2201         p_sys->p_codecs = calloc( 1, p_sys->i_codec * sizeof( struct v4l2_fmtdesc ) );
2202
2203         for( i_index = 0; i_index < p_sys->i_codec; i_index++ )
2204         {
2205             p_sys->p_codecs[i_index].index = i_index;
2206             p_sys->p_codecs[i_index].type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2207
2208             if( ioctl( i_fd, VIDIOC_ENUM_FMT, &p_sys->p_codecs[i_index] ) < 0 )
2209             {
2210                 msg_Err( p_demux, "cannot get codec description (%m)" );
2211                 goto open_failed;
2212             }
2213
2214             /* only print if vlc supports the format */
2215             vlc_bool_t b_codec_supported = VLC_FALSE;
2216             for( int i = 0; v4l2chroma_to_fourcc[i].i_v4l2 != 0; i++ )
2217             {
2218                 if( v4l2chroma_to_fourcc[i].i_v4l2 == p_sys->p_codecs[i_index].pixelformat )
2219                 {
2220                     b_codec_supported = VLC_TRUE;
2221
2222                     char sz_fourcc[5];
2223                     memset( &sz_fourcc, 0, sizeof( sz_fourcc ) );
2224                     vlc_fourcc_to_char( v4l2chroma_to_fourcc[i].i_fourcc, &sz_fourcc );
2225                     msg_Dbg( p_demux, "device supports chroma %4s [%s]",
2226                                 sz_fourcc,
2227                                 p_sys->p_codecs[i_index].description );
2228
2229 #ifdef VIDIOC_ENUM_FRAMESIZES
2230                     /* This is new in Linux 2.6.19 */
2231                     /* List valid frame sizes for this format */
2232                     struct v4l2_frmsizeenum frmsize;
2233                     frmsize.index = 0;
2234                     frmsize.pixel_format = p_sys->p_codecs[i_index].pixelformat;
2235                     if( ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize ) < 0 )
2236                     {
2237                         /* Not all devices support this ioctl */
2238                         msg_Warn( p_demux, "Unable to query for frame sizes" );
2239                     }
2240                     else
2241                     {
2242                         switch( frmsize.type )
2243                         {
2244                             case V4L2_FRMSIZE_TYPE_DISCRETE:
2245                                 do
2246                                 {
2247                                     msg_Dbg( p_demux,
2248                 "    device supports size %dx%d",
2249                 frmsize.discrete.width, frmsize.discrete.height );
2250                                     frmsize.index++;
2251                                 } while( ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize ) >= 0 );
2252                                 break;
2253                             case V4L2_FRMSIZE_TYPE_STEPWISE:
2254                                 msg_Dbg( p_demux,
2255                 "    device supports sizes %dx%d to %dx%d using %dx%d increments",
2256                 frmsize.stepwise.min_width, frmsize.stepwise.min_height,
2257                 frmsize.stepwise.max_width, frmsize.stepwise.max_height,
2258                 frmsize.stepwise.step_width, frmsize.stepwise.step_height );
2259                                 break;
2260                             case V4L2_FRMSIZE_TYPE_CONTINUOUS:
2261                                 msg_Dbg( p_demux,
2262                 "    device supports all sizes %dx%d to %dx%d",
2263                 frmsize.stepwise.min_width, frmsize.stepwise.min_height,
2264                 frmsize.stepwise.max_width, frmsize.stepwise.max_height );
2265                                 break;
2266                         }
2267                     }
2268 #endif
2269                 }
2270             }
2271             if( !b_codec_supported )
2272             {
2273                 msg_Dbg( p_demux, "device codec %s not supported",
2274                     p_sys->p_codecs[i_index].description );
2275             }
2276
2277         }
2278     }
2279
2280
2281     if( i_fd >= 0 ) close( i_fd );
2282     return VLC_TRUE;
2283
2284 open_failed:
2285
2286     if( i_fd >= 0 ) close( i_fd );
2287     return VLC_FALSE;
2288
2289 }
2290
2291 /*****************************************************************************
2292  * ProbeAudioDev: probe audio for capabilities
2293  *****************************************************************************/
2294 vlc_bool_t ProbeAudioDev( demux_t *p_demux, char *psz_device )
2295 {
2296     int i_fd = 0;
2297     int i_caps;
2298
2299 #ifdef HAVE_ALSA
2300     demux_sys_t *p_sys = p_demux->p_sys;
2301
2302     if( p_sys->b_use_alsa )
2303     {
2304         /* ALSA */
2305
2306         int i_err;
2307         snd_pcm_t *p_alsa_pcm;
2308         char* psz_alsa_device_name = ResolveALSADeviceName( psz_device );
2309
2310         if( ( i_err = snd_pcm_open( &p_alsa_pcm, psz_alsa_device_name, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK ) ) < 0 )
2311         {
2312             msg_Err( p_demux, "cannot open device %s for ALSA audio (%s)", psz_alsa_device_name, snd_strerror( i_err ) );
2313             free( psz_alsa_device_name );
2314             goto open_failed;
2315         }
2316
2317         snd_pcm_close( p_alsa_pcm );
2318         free( psz_alsa_device_name );
2319     }
2320     else
2321 #endif /* HAVE_ALSA */
2322     {
2323         /* OSS */
2324
2325         if( ( i_fd = open( psz_device, O_RDONLY | O_NONBLOCK ) ) < 0 )
2326         {
2327             msg_Err( p_demux, "cannot open device %s for OSS audio (%m)", psz_device );
2328             goto open_failed;
2329         }
2330
2331         /* this will fail if the device is video */
2332         if( ioctl( i_fd, SNDCTL_DSP_GETCAPS, &i_caps ) < 0 )
2333         {
2334             msg_Err( p_demux, "cannot get audio caps (%m)" );
2335             goto open_failed;
2336         }
2337
2338         if( i_fd >= 0 ) close( i_fd );
2339     }
2340
2341     return VLC_TRUE;
2342
2343 open_failed:
2344     if( i_fd >= 0 ) close( i_fd );
2345     return VLC_FALSE;
2346
2347 }
2348
2349 /*****************************************************************************
2350  * Print a user-class v4l2 control's details, create the relevant variable,
2351  * change the value if needed.
2352  *****************************************************************************/
2353 static void ControlListPrint( demux_t *p_demux, int i_fd,
2354                               struct v4l2_queryctrl queryctrl,
2355                               vlc_bool_t b_reset )
2356 {
2357     struct v4l2_querymenu querymenu;
2358     unsigned int i_mid;
2359
2360     int i;
2361     int i_val;
2362
2363     char *psz_name;
2364     vlc_value_t val, val2;
2365
2366     if( queryctrl.flags & V4L2_CTRL_FLAG_GRABBED )
2367         msg_Dbg( p_demux, "    control is busy" );
2368     if( queryctrl.flags & V4L2_CTRL_FLAG_READ_ONLY )
2369         msg_Dbg( p_demux, "    control is read-only" );
2370
2371     for( i = 0; controls[i].psz_name != NULL; i++ )
2372         if( controls[i].i_cid == queryctrl.id ) break;
2373
2374     if( controls[i].psz_name )
2375     {
2376         psz_name = strdup( controls[i].psz_name );
2377         char psz_cfg_name[40];
2378         sprintf( psz_cfg_name, CFG_PREFIX "%s", psz_name );
2379         i_val = var_CreateGetInteger( p_demux, psz_cfg_name );
2380         var_Destroy( p_demux, psz_cfg_name );
2381     }
2382     else
2383     {
2384         char *psz_buf;
2385         psz_name = strdup( (const char *)queryctrl.name );
2386         for( psz_buf = psz_name; *psz_buf; psz_buf++ )
2387         {
2388             if( *psz_buf == ' ' ) *psz_buf = '-';
2389         }
2390         i_val = -1;
2391     }
2392
2393     switch( queryctrl.type )
2394     {
2395         case V4L2_CTRL_TYPE_INTEGER:
2396             msg_Dbg( p_demux, "    integer control" );
2397             msg_Dbg( p_demux,
2398                      "    valid values: %d to %d by steps of %d",
2399                      queryctrl.minimum, queryctrl.maximum,
2400                      queryctrl.step );
2401
2402             var_Create( p_demux, psz_name,
2403                         VLC_VAR_INTEGER | VLC_VAR_HASMIN | VLC_VAR_HASMAX
2404                       | VLC_VAR_HASSTEP | VLC_VAR_ISCOMMAND );
2405             val.i_int = queryctrl.minimum;
2406             var_Change( p_demux, psz_name, VLC_VAR_SETMIN, &val, NULL );
2407             val.i_int = queryctrl.maximum;
2408             var_Change( p_demux, psz_name, VLC_VAR_SETMAX, &val, NULL );
2409             val.i_int = queryctrl.step;
2410             var_Change( p_demux, psz_name, VLC_VAR_SETSTEP, &val, NULL );
2411             break;
2412         case V4L2_CTRL_TYPE_BOOLEAN:
2413             msg_Dbg( p_demux, "    boolean control" );
2414             var_Create( p_demux, psz_name,
2415                         VLC_VAR_BOOL | VLC_VAR_ISCOMMAND );
2416             break;
2417         case V4L2_CTRL_TYPE_MENU:
2418             msg_Dbg( p_demux, "    menu control" );
2419             var_Create( p_demux, psz_name,
2420                         VLC_VAR_INTEGER | VLC_VAR_HASCHOICE
2421                       | VLC_VAR_ISCOMMAND );
2422             memset( &querymenu, 0, sizeof( querymenu ) );
2423             for( i_mid = queryctrl.minimum;
2424                  i_mid <= (unsigned)queryctrl.maximum;
2425                  i_mid++ )
2426             {
2427                 querymenu.index = i_mid;
2428                 querymenu.id = queryctrl.id;
2429                 if( ioctl( i_fd, VIDIOC_QUERYMENU, &querymenu ) >= 0 )
2430                 {
2431                     msg_Dbg( p_demux, "        %d: %s",
2432                              querymenu.index, querymenu.name );
2433                     val.i_int = querymenu.index;
2434                     val2.psz_string = (char *)querymenu.name;
2435                     var_Change( p_demux, psz_name,
2436                                 VLC_VAR_ADDCHOICE, &val, &val2 );
2437                 }
2438             }
2439             break;
2440         case V4L2_CTRL_TYPE_BUTTON:
2441             msg_Dbg( p_demux, "    button control" );
2442             var_Create( p_demux, psz_name,
2443                         VLC_VAR_VOID | VLC_VAR_ISCOMMAND );
2444             break;
2445         default:
2446             msg_Dbg( p_demux, "    unknown control type (FIXME)" );
2447             /* FIXME */
2448             break;
2449     }
2450
2451     switch( queryctrl.type )
2452     {
2453         case V4L2_CTRL_TYPE_INTEGER:
2454         case V4L2_CTRL_TYPE_BOOLEAN:
2455         case V4L2_CTRL_TYPE_MENU:
2456             {
2457                 struct v4l2_control control;
2458                 msg_Dbg( p_demux, "    default value: %d",
2459                          queryctrl.default_value );
2460                 memset( &control, 0, sizeof( control ) );
2461                 control.id = queryctrl.id;
2462                 if( ioctl( i_fd, VIDIOC_G_CTRL, &control ) >= 0 )
2463                 {
2464                     msg_Dbg( p_demux, "    current value: %d", control.value );
2465                 }
2466                 if( i_val == -1 )
2467                 {
2468                     i_val = control.value;
2469                     if( b_reset && queryctrl.default_value != control.value )
2470                     {
2471                         msg_Dbg( p_demux, "    reset value to default" );
2472                         Control( p_demux, i_fd, psz_name,
2473                                       queryctrl.id, queryctrl.default_value );
2474                     }
2475                 }
2476                 else
2477                 {
2478                     Control( p_demux, i_fd, psz_name,
2479                                   queryctrl.id, i_val );
2480                 }
2481             }
2482             break;
2483         default:
2484             break;
2485     }
2486
2487     val.psz_string = (char *)queryctrl.name;
2488     var_Change( p_demux, psz_name, VLC_VAR_SETTEXT, &val, NULL );
2489     val.i_int = queryctrl.id;
2490     val2.psz_string = (char *)psz_name;
2491     var_Change( p_demux, "controls", VLC_VAR_ADDCHOICE, &val, &val2 );
2492
2493     switch( var_Type( p_demux, psz_name ) & VLC_VAR_TYPE )
2494     {
2495         case VLC_VAR_BOOL:
2496             var_SetBool( p_demux, psz_name, i_val );
2497             break;
2498         case VLC_VAR_INTEGER:
2499             var_SetInteger( p_demux, psz_name, i_val );
2500             break;
2501         case VLC_VAR_VOID:
2502             break;
2503         default:
2504             msg_Warn( p_demux, "FIXME: %s %s %d", __FILE__, __func__,
2505                       __LINE__ );
2506             break;
2507     }
2508
2509     var_AddCallback( p_demux, psz_name,
2510                     ControlCallback, (void*)queryctrl.id );
2511
2512     free( psz_name );
2513 }
2514
2515 /*****************************************************************************
2516  * List all user-class v4l2 controls, set them to the user specified
2517  * value and create the relevant variables to enable runtime changes
2518  *****************************************************************************/
2519 static int ControlList( demux_t *p_demux, int i_fd, vlc_bool_t b_reset )
2520 {
2521     struct v4l2_queryctrl queryctrl;
2522     int i_cid;
2523
2524     memset( &queryctrl, 0, sizeof( queryctrl ) );
2525
2526     /* A list of available controls (aka the variable name) will be
2527      * stored as choices in the "controls" variable. We'll thus be able
2528      * to use those to create an appropriate interface */
2529     var_Create( p_demux, "controls", VLC_VAR_INTEGER | VLC_VAR_HASCHOICE );
2530
2531     var_Create( p_demux, "controls-update", VLC_VAR_VOID | VLC_VAR_ISCOMMAND );
2532
2533     /* Add a control to reset all controls to their default values */
2534     vlc_value_t val, val2;
2535     var_Create( p_demux, "controls-reset", VLC_VAR_VOID | VLC_VAR_ISCOMMAND );
2536     val.psz_string = _( "Reset controls to default" );
2537     var_Change( p_demux, "controls-reset", VLC_VAR_SETTEXT, &val, NULL );
2538     val.i_int = -1;
2539     val2.psz_string = (char *)"controls-reset";
2540     var_Change( p_demux, "controls", VLC_VAR_ADDCHOICE, &val, &val2 );
2541     var_AddCallback( p_demux, "controls-reset", ControlResetCallback, NULL );
2542
2543     /* List public controls */
2544     for( i_cid = V4L2_CID_BASE;
2545          i_cid < V4L2_CID_LASTP1;
2546          i_cid ++ )
2547     {
2548         queryctrl.id = i_cid;
2549         if( ioctl( i_fd, VIDIOC_QUERYCTRL, &queryctrl ) >= 0 )
2550         {
2551             if( queryctrl.flags & V4L2_CTRL_FLAG_DISABLED )
2552                 continue;
2553             msg_Dbg( p_demux, "Available control: %s (%x)",
2554                      queryctrl.name, queryctrl.id );
2555             ControlListPrint( p_demux, i_fd, queryctrl, b_reset );
2556         }
2557     }
2558
2559     /* List private controls */
2560     for( i_cid = V4L2_CID_PRIVATE_BASE;
2561          ;
2562          i_cid ++ )
2563     {
2564         queryctrl.id = i_cid;
2565         if( ioctl( i_fd, VIDIOC_QUERYCTRL, &queryctrl ) >= 0 )
2566         {
2567             if( queryctrl.flags & V4L2_CTRL_FLAG_DISABLED )
2568                 continue;
2569             msg_Dbg( p_demux, "Available private control: %s (%x)",
2570                      queryctrl.name, queryctrl.id );
2571             ControlListPrint( p_demux, i_fd, queryctrl, b_reset );
2572         }
2573         else
2574             break;
2575     }
2576     return VLC_SUCCESS;
2577 }
2578
2579 /*****************************************************************************
2580  * Reset all user-class v4l2 controls to their default value
2581  *****************************************************************************/
2582 static int ControlReset( demux_t *p_demux, int i_fd )
2583 {
2584     struct v4l2_queryctrl queryctrl;
2585     int i_cid;
2586
2587     memset( &queryctrl, 0, sizeof( queryctrl ) );
2588
2589     /* public controls */
2590     for( i_cid = V4L2_CID_BASE;
2591          i_cid < V4L2_CID_LASTP1;
2592          i_cid ++ )
2593     {
2594         queryctrl.id = i_cid;
2595         if( ioctl( i_fd, VIDIOC_QUERYCTRL, &queryctrl ) >= 0 )
2596         {
2597             struct v4l2_control control;
2598             if( queryctrl.flags & V4L2_CTRL_FLAG_DISABLED )
2599                 continue;
2600             memset( &control, 0, sizeof( control ) );
2601             control.id = queryctrl.id;
2602             if( ioctl( i_fd, VIDIOC_G_CTRL, &control ) >= 0
2603              && queryctrl.default_value != control.value )
2604             {
2605                 int i;
2606                 for( i = 0; controls[i].psz_name != NULL; i++ )
2607                     if( controls[i].i_cid == queryctrl.id ) break;
2608                 Control( p_demux, i_fd,
2609                          controls[i].psz_name ? controls[i].psz_name
2610                                               : (const char *)queryctrl.name,
2611                          queryctrl.id, queryctrl.default_value );
2612             }
2613         }
2614     }
2615
2616     /* private controls */
2617     for( i_cid = V4L2_CID_PRIVATE_BASE;
2618          ;
2619          i_cid ++ )
2620     {
2621         queryctrl.id = i_cid;
2622         if( ioctl( i_fd, VIDIOC_QUERYCTRL, &queryctrl ) >= 0 )
2623         {
2624             struct v4l2_control control;
2625             if( queryctrl.flags & V4L2_CTRL_FLAG_DISABLED )
2626                 continue;
2627             memset( &control, 0, sizeof( control ) );
2628             control.id = queryctrl.id;
2629             if( ioctl( i_fd, VIDIOC_G_CTRL, &control ) >= 0
2630              && queryctrl.default_value != control.value )
2631             {
2632                 Control( p_demux, i_fd, (const char *)queryctrl.name,
2633                          queryctrl.id, queryctrl.default_value );
2634             }
2635         }
2636         else
2637             break;
2638     }
2639     return VLC_SUCCESS;
2640 }
2641
2642 /*****************************************************************************
2643  * Issue user-class v4l2 controls
2644  *****************************************************************************/
2645 static int Control( demux_t *p_demux, int i_fd,
2646                     const char *psz_name, int i_cid, int i_value )
2647 {
2648     struct v4l2_queryctrl queryctrl;
2649     struct v4l2_control control;
2650
2651     if( i_value == -1 )
2652         return VLC_SUCCESS;
2653
2654     memset( &queryctrl, 0, sizeof( queryctrl ) );
2655
2656     queryctrl.id = i_cid;
2657
2658     if( ioctl( i_fd, VIDIOC_QUERYCTRL, &queryctrl ) < 0
2659         || queryctrl.flags & V4L2_CTRL_FLAG_DISABLED )
2660     {
2661         msg_Dbg( p_demux, "%s (%x) control is not supported.", psz_name,
2662                  i_cid );
2663         return VLC_EGENERIC;
2664     }
2665
2666     memset( &control, 0, sizeof( control ) );
2667     control.id = i_cid;
2668
2669     if( i_value >= 0 )
2670     {
2671         control.value = i_value;
2672         if( ioctl( i_fd, VIDIOC_S_CTRL, &control ) < 0 )
2673         {
2674             msg_Err( p_demux, "unable to set %s to %d (%m)", psz_name,
2675                      i_value );
2676             return VLC_EGENERIC;
2677         }
2678     }
2679     if( ioctl( i_fd, VIDIOC_G_CTRL, &control ) >= 0 )
2680     {
2681         vlc_value_t val;
2682         msg_Dbg( p_demux, "video %s: %d", psz_name, control.value );
2683         switch( var_Type( p_demux, psz_name ) & VLC_VAR_TYPE )
2684         {
2685             case VLC_VAR_BOOL:
2686                 val.b_bool = control.value;
2687                 var_Change( p_demux, psz_name, VLC_VAR_SETVALUE, &val, NULL );
2688                 var_SetVoid( p_demux, "controls-update" );
2689                 break;
2690             case VLC_VAR_INTEGER:
2691                 val.i_int = control.value;
2692                 var_Change( p_demux, psz_name, VLC_VAR_SETVALUE, &val, NULL );
2693                 var_SetVoid( p_demux, "controls-update" );
2694                 break;
2695         }
2696     }
2697     return VLC_SUCCESS;
2698 }
2699
2700 /*****************************************************************************
2701  * On the fly change settings callback
2702  *****************************************************************************/
2703 static int ControlCallback( vlc_object_t *p_this,
2704     const char *psz_var, vlc_value_t oldval, vlc_value_t newval,
2705     void *p_data )
2706 {
2707     demux_t *p_demux = (demux_t*)p_this;
2708     demux_sys_t *p_sys = p_demux->p_sys;
2709     int i_cid = (int)p_data;
2710
2711     int i_fd = p_sys->i_fd_video;
2712
2713     if( i_fd < 0 )
2714         return VLC_EGENERIC;
2715
2716     Control( p_demux, i_fd, psz_var, i_cid, newval.i_int );
2717
2718     return VLC_EGENERIC;
2719 }
2720
2721 static int ControlResetCallback( vlc_object_t *p_this,
2722     const char *psz_var, vlc_value_t oldval, vlc_value_t newval,
2723     void *p_data )
2724 {
2725     demux_t *p_demux = (demux_t*)p_this;
2726     demux_sys_t *p_sys = p_demux->p_sys;
2727
2728     int i_fd = p_sys->i_fd_video;
2729
2730     if( i_fd < 0 )
2731         return VLC_EGENERIC;
2732
2733     ControlReset( p_demux, i_fd );
2734
2735     return VLC_EGENERIC;
2736 }