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