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