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