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