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