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