]> git.sesse.net Git - vlc/blob - modules/access/v4l2/v4l2.c
960d4d5e34000a66d7929adf3eb2b393941932cc
[vlc] / modules / access / v4l2 / 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     /* Set audio input */
1901
1902     if( p_sys->i_audio > 0 )
1903     {
1904         if( p_sys->i_selected_audio_input < 0
1905          || p_sys->i_selected_audio_input >= p_sys->i_audio )
1906         {
1907             msg_Warn( p_obj, "invalid audio input. Using the default one" );
1908             p_sys->i_selected_audio_input = 0;
1909         }
1910
1911         if( ioctl( i_fd, VIDIOC_S_AUDIO, &p_sys->p_audios[p_sys->i_selected_audio_input] ) < 0 )
1912         {
1913             msg_Err( p_obj, "cannot set audio input (%m)" );
1914             goto open_failed;
1915         }
1916         msg_Dbg( p_obj, "Audio input set to %d", p_sys->i_selected_audio_input );
1917     }
1918
1919
1920     /* TODO: Move the resolution stuff up here */
1921     /* if MPEG encoder card, no need to do anything else after this */
1922     ControlList( p_obj, i_fd,
1923                   var_GetBool( p_obj, "v4l2-controls-reset" ), b_demux );
1924     SetAvailControlsByString( p_obj, p_sys, i_fd );
1925     if( VLC_FALSE == b_demux)
1926     {
1927         return i_fd;
1928     }
1929
1930     demux_t *p_demux = (demux_t *) p_obj;
1931
1932     /* Verify device support for the various IO methods */
1933     switch( p_sys->io )
1934     {
1935         case IO_METHOD_READ:
1936             if( !(p_sys->dev_cap.capabilities & V4L2_CAP_READWRITE) )
1937             {
1938                 msg_Err( p_demux, "device does not support read i/o" );
1939                 goto open_failed;
1940             }
1941             break;
1942
1943         case IO_METHOD_MMAP:
1944         case IO_METHOD_USERPTR:
1945             if( !(p_sys->dev_cap.capabilities & V4L2_CAP_STREAMING) )
1946             {
1947                 msg_Err( p_demux, "device does not support streaming i/o" );
1948                 goto open_failed;
1949             }
1950             break;
1951
1952         default:
1953             msg_Err( p_demux, "io method not supported" );
1954             goto open_failed;
1955     }
1956
1957     /* Reset Cropping */
1958     memset( &cropcap, 0, sizeof(cropcap) );
1959     cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1960     if( ioctl( i_fd, VIDIOC_CROPCAP, &cropcap ) >= 0 )
1961     {
1962         crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1963         crop.c = cropcap.defrect; /* reset to default */
1964         if( ioctl( i_fd, VIDIOC_S_CROP, &crop ) < 0 )
1965         {
1966             switch( errno )
1967             {
1968                 case EINVAL:
1969                     /* Cropping not supported. */
1970                     break;
1971                 default:
1972                     /* Errors ignored. */
1973                     break;
1974             }
1975         }
1976     }
1977
1978     /* Try and find default resolution if not specified */
1979     memset( &fmt, 0, sizeof(fmt) );
1980     fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1981
1982     if( p_sys->i_width <= 0 || p_sys->i_height <= 0 )
1983     {
1984         if( ioctl( i_fd, VIDIOC_G_FMT, &fmt ) < 0 )
1985         {
1986             msg_Err( p_demux, "Cannot get default width and height." );
1987             goto open_failed;
1988         }
1989
1990         p_sys->i_width = fmt.fmt.pix.width;
1991         p_sys->i_height = fmt.fmt.pix.height;
1992
1993         if( fmt.fmt.pix.field == V4L2_FIELD_ALTERNATE )
1994         {
1995             p_sys->i_height = p_sys->i_height * 2;
1996         }
1997     }
1998     else
1999     {
2000         msg_Dbg( p_demux, "trying specified size %dx%d", p_sys->i_width, p_sys->i_height );
2001     }
2002
2003     fmt.fmt.pix.width = p_sys->i_width;
2004     fmt.fmt.pix.height = p_sys->i_height;
2005     fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
2006
2007     /* Test and set Chroma */
2008     fmt.fmt.pix.pixelformat = 0;
2009     if( p_sys->psz_requested_chroma && strlen( p_sys->psz_requested_chroma ) > 0 )
2010     {
2011         /* User specified chroma */
2012         if( strlen( p_sys->psz_requested_chroma ) >= 4 )
2013         {
2014             int i_requested_fourcc = VLC_FOURCC(
2015                 p_sys->psz_requested_chroma[0], p_sys->psz_requested_chroma[1],
2016                 p_sys->psz_requested_chroma[2], p_sys->psz_requested_chroma[3] );
2017             for( int i = 0; v4l2chroma_to_fourcc[i].i_v4l2 != 0; i++ )
2018             {
2019                 if( v4l2chroma_to_fourcc[i].i_fourcc == i_requested_fourcc )
2020                 {
2021                     fmt.fmt.pix.pixelformat = v4l2chroma_to_fourcc[i].i_v4l2;
2022                     break;
2023                 }
2024             }
2025         }
2026         /* Try and set user chroma */
2027         if( !IsPixelFormatSupported( p_demux, fmt.fmt.pix.pixelformat ) || ( fmt.fmt.pix.pixelformat && ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 ) )
2028         {
2029             msg_Warn( p_demux, "Driver is unable to use specified chroma %s. Trying defaults.", p_sys->psz_requested_chroma );
2030             fmt.fmt.pix.pixelformat = 0;
2031         }
2032     }
2033
2034     /* If no user specified chroma, find best */
2035     /* This also decides if MPEG encoder card or not */
2036     if( !fmt.fmt.pix.pixelformat )
2037     {
2038         unsigned int i;
2039         for( i = 0; i < ARRAY_SIZE( p_chroma_fallbacks ); i++ )
2040         {
2041             fmt.fmt.pix.pixelformat = p_chroma_fallbacks[i];
2042             if( IsPixelFormatSupported( p_demux, fmt.fmt.pix.pixelformat )
2043              && ioctl( i_fd, VIDIOC_S_FMT, &fmt ) >= 0 )
2044                 break;
2045         }
2046         if( i == ARRAY_SIZE( p_chroma_fallbacks ) )
2047         {
2048             msg_Warn( p_demux, "Could not select any of the default chromas; attempting to open as MPEG encoder card (access2)" );
2049             goto open_failed;
2050         }
2051     }
2052
2053     /* Reassign width, height and chroma incase driver override */
2054     p_sys->i_width = fmt.fmt.pix.width;
2055     p_sys->i_height = fmt.fmt.pix.height;
2056
2057     /* Look up final fourcc */
2058     p_sys->i_fourcc = 0;
2059     for( int i = 0; v4l2chroma_to_fourcc[i].i_fourcc != 0; i++ )
2060     {
2061         if( v4l2chroma_to_fourcc[i].i_v4l2 == fmt.fmt.pix.pixelformat )
2062         {
2063             p_sys->i_fourcc = v4l2chroma_to_fourcc[i].i_fourcc;
2064             break;
2065         }
2066     }
2067
2068     /* Buggy driver paranoia */
2069     i_min = fmt.fmt.pix.width * 2;
2070     if( fmt.fmt.pix.bytesperline < i_min )
2071         fmt.fmt.pix.bytesperline = i_min;
2072     i_min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
2073     if( fmt.fmt.pix.sizeimage < i_min )
2074         fmt.fmt.pix.sizeimage = i_min;
2075
2076 #ifdef VIDIOC_ENUM_FRAMEINTERVALS
2077     /* This is new in Linux 2.6.19 */
2078     /* List supported frame rates */
2079     struct v4l2_frmivalenum frmival;
2080     frmival.index = 0;
2081     frmival.pixel_format = fmt.fmt.pix.pixelformat;
2082     frmival.width = p_sys->i_width;
2083     frmival.height = p_sys->i_height;
2084     if( ioctl( i_fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival ) >= 0 )
2085     {
2086         char psz_fourcc[5];
2087         memset( &psz_fourcc, 0, sizeof( psz_fourcc ) );
2088         vlc_fourcc_to_char( p_sys->i_fourcc, &psz_fourcc );
2089         msg_Dbg( p_demux, "supported frame intervals for %4s, %dx%d:",
2090                  psz_fourcc, frmival.width, frmival.height );
2091         switch( frmival.type )
2092         {
2093             case V4L2_FRMIVAL_TYPE_DISCRETE:
2094                 do
2095                 {
2096                     msg_Dbg( p_demux, "    supported frame interval: %d/%d",
2097                              frmival.discrete.numerator,
2098                              frmival.discrete.denominator );
2099                     frmival.index++;
2100                 } while( ioctl( i_fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival ) >= 0 );
2101                 break;
2102             case V4L2_FRMIVAL_TYPE_STEPWISE:
2103                 msg_Dbg( p_demux, "    supported frame intervals: %d/%d to "
2104                          "%d/%d using %d/%d increments",
2105                          frmival.stepwise.min.numerator,
2106                          frmival.stepwise.min.denominator,
2107                          frmival.stepwise.max.numerator,
2108                          frmival.stepwise.max.denominator,
2109                          frmival.stepwise.step.numerator,
2110                          frmival.stepwise.step.denominator );
2111                 break;
2112             case V4L2_FRMIVAL_TYPE_CONTINUOUS:
2113                 msg_Dbg( p_demux, "    supported frame intervals: %d/%d to %d/%d",
2114                          frmival.stepwise.min.numerator,
2115                          frmival.stepwise.min.denominator,
2116                          frmival.stepwise.max.numerator,
2117                          frmival.stepwise.max.denominator );
2118                 break;
2119         }
2120     }
2121 #endif
2122
2123     /* Init IO method */
2124     switch( p_sys->io )
2125     {
2126     case IO_METHOD_READ:
2127         if( InitRead( p_demux, i_fd, fmt.fmt.pix.sizeimage ) != VLC_SUCCESS ) goto open_failed;
2128         break;
2129
2130     case IO_METHOD_MMAP:
2131         if( InitMmap( p_demux, i_fd ) != VLC_SUCCESS ) goto open_failed;
2132         break;
2133
2134     case IO_METHOD_USERPTR:
2135         if( InitUserP( p_demux, i_fd, fmt.fmt.pix.sizeimage ) != VLC_SUCCESS ) goto open_failed;
2136         break;
2137
2138     }
2139
2140     /* Add */
2141     es_format_t es_fmt;
2142     es_format_Init( &es_fmt, VIDEO_ES, p_sys->i_fourcc );
2143     es_fmt.video.i_width  = p_sys->i_width;
2144     es_fmt.video.i_height = p_sys->i_height;
2145     es_fmt.video.i_aspect = 4 * VOUT_ASPECT_FACTOR / 3;
2146
2147     /* Setup rgb mask for RGB formats */
2148     if( p_sys->i_fourcc == VLC_FOURCC( 'R','V','2','4' ) )
2149     {
2150         /* This is in BGR format */
2151         es_fmt.video.i_bmask = 0x00ff0000;
2152         es_fmt.video.i_gmask = 0x0000ff00;
2153         es_fmt.video.i_rmask = 0x000000ff;
2154     }
2155
2156     msg_Dbg( p_demux, "added new video es %4.4s %dx%d",
2157         (char*)&es_fmt.i_codec, es_fmt.video.i_width, es_fmt.video.i_height );
2158     p_sys->p_es_video = es_out_Add( p_demux->out, &es_fmt );
2159
2160     /* Start Capture */
2161
2162     switch( p_sys->io )
2163     {
2164     case IO_METHOD_READ:
2165         /* Nothing to do */
2166         break;
2167
2168     case IO_METHOD_MMAP:
2169         for (unsigned int i = 0; i < p_sys->i_nbuffers; ++i)
2170         {
2171             struct v4l2_buffer buf;
2172
2173             memset( &buf, 0, sizeof(buf) );
2174             buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2175             buf.memory = V4L2_MEMORY_MMAP;
2176             buf.index = i;
2177
2178             if( ioctl( i_fd, VIDIOC_QBUF, &buf ) < 0 )
2179             {
2180                 msg_Err( p_demux, "VIDIOC_QBUF failed" );
2181                 goto open_failed;
2182             }
2183         }
2184
2185         buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2186         if( ioctl( i_fd, VIDIOC_STREAMON, &buf_type ) < 0 )
2187         {
2188             msg_Err( p_demux, "VIDIOC_STREAMON failed" );
2189             goto open_failed;
2190         }
2191
2192         break;
2193
2194     case IO_METHOD_USERPTR:
2195         for( unsigned int i = 0; i < p_sys->i_nbuffers; ++i )
2196         {
2197             struct v4l2_buffer buf;
2198
2199             memset( &buf, 0, sizeof(buf) );
2200             buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2201             buf.memory = V4L2_MEMORY_USERPTR;
2202             buf.index = i;
2203             buf.m.userptr = (unsigned long)p_sys->p_buffers[i].start;
2204             buf.length = p_sys->p_buffers[i].length;
2205
2206             if( ioctl( i_fd, VIDIOC_QBUF, &buf ) < 0 )
2207             {
2208                 msg_Err( p_demux, "VIDIOC_QBUF failed" );
2209                 goto open_failed;
2210             }
2211         }
2212
2213         buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2214         if( ioctl( i_fd, VIDIOC_STREAMON, &buf_type ) < 0 )
2215         {
2216             msg_Err( p_demux, "VIDIOC_STREAMON failed" );
2217             goto open_failed;
2218         }
2219
2220         break;
2221     }
2222
2223     /* report fps */
2224     if( p_sys->f_fps >= 0.1 )
2225     {
2226         msg_Dbg( p_demux, "User set fps=%f", p_sys->f_fps );
2227     }
2228
2229     return i_fd;
2230
2231 open_failed:
2232     if( i_fd >= 0 ) close( i_fd );
2233     return -1;
2234
2235 }
2236
2237 #ifdef HAVE_ALSA
2238 /*****************************************************************************
2239  * ResolveALSADeviceName: Change any . to : in the ALSA device name
2240  *****************************************************************************/
2241 static char *ResolveALSADeviceName( const char *psz_device )
2242 {
2243     char* psz_alsa_name = strdup( psz_device );
2244     for( unsigned int i = 0; i < strlen( psz_device ); i++ )
2245     {
2246         if( psz_alsa_name[i] == '.' ) psz_alsa_name[i] = ':';
2247     }
2248     return psz_alsa_name;
2249 }
2250 #endif
2251
2252 /*****************************************************************************
2253  * OpenAudioDev: open and set up the audio device and probe for capabilities
2254  *****************************************************************************/
2255 #ifdef HAVE_ALSA
2256 static int OpenAudioDevAlsa( vlc_object_t *p_this, demux_sys_t *p_sys,
2257                              vlc_bool_t b_demux )
2258 {
2259     char *psz_device = p_sys->psz_adev;
2260     int i_fd = 0;
2261     p_sys->p_alsa_pcm = NULL;
2262     char* psz_alsa_device_name = NULL;
2263     snd_pcm_hw_params_t *p_hw_params = NULL;
2264     snd_pcm_uframes_t buffer_size;
2265     snd_pcm_uframes_t chunk_size;
2266
2267     /* ALSA */
2268     int i_err;
2269     psz_alsa_device_name =
2270         ResolveALSADeviceName( psz_device?: ALSA_DEFAULT );
2271
2272     if( ( i_err = snd_pcm_open( &p_sys->p_alsa_pcm, psz_alsa_device_name,
2273         SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK ) ) < 0)
2274     {
2275         msg_Err( p_this, "Cannot open ALSA audio device %s (%s)",
2276                  psz_alsa_device_name, snd_strerror( i_err ) );
2277         goto adev_fail;
2278     }
2279
2280     if( ( i_err = snd_pcm_nonblock( p_sys->p_alsa_pcm, 1 ) ) < 0)
2281     {
2282         msg_Err( p_this, "Cannot set ALSA nonblock (%s)",
2283                  snd_strerror( i_err ) );
2284         goto adev_fail;
2285     }
2286
2287     /* Begin setting hardware parameters */
2288
2289     if( ( i_err = snd_pcm_hw_params_malloc( &p_hw_params ) ) < 0 )
2290     {
2291         msg_Err( p_this,
2292                  "ALSA: cannot allocate hardware parameter structure (%s)",
2293                  snd_strerror( i_err ) );
2294         goto adev_fail;
2295     }
2296
2297     if( ( i_err = snd_pcm_hw_params_any( p_sys->p_alsa_pcm, p_hw_params ) ) < 0 )
2298     {
2299         msg_Err( p_this,
2300                 "ALSA: cannot initialize hardware parameter structure (%s)",
2301                  snd_strerror( i_err ) );
2302         goto adev_fail;
2303     }
2304
2305     /* Set Interleaved access */
2306     if( ( i_err = snd_pcm_hw_params_set_access( p_sys->p_alsa_pcm, p_hw_params, SND_PCM_ACCESS_RW_INTERLEAVED ) ) < 0 )
2307     {
2308         msg_Err( p_this, "ALSA: cannot set access type (%s)",
2309                  snd_strerror( i_err ) );
2310         goto adev_fail;
2311     }
2312
2313     /* Set 16 bit little endian */
2314     if( ( i_err = snd_pcm_hw_params_set_format( p_sys->p_alsa_pcm, p_hw_params, SND_PCM_FORMAT_S16_LE ) ) < 0 )
2315     {
2316         msg_Err( p_this, "ALSA: cannot set sample format (%s)",
2317                  snd_strerror( i_err ) );
2318         goto adev_fail;
2319     }
2320
2321     /* Set sample rate */
2322 #ifdef HAVE_ALSA_NEW_API
2323     i_err = snd_pcm_hw_params_set_rate_near( p_sys->p_alsa_pcm, p_hw_params, &p_sys->i_sample_rate, NULL );
2324 #else
2325     i_err = snd_pcm_hw_params_set_rate_near( p_sys->p_alsa_pcm, p_hw_params, p_sys->i_sample_rate, NULL );
2326 #endif
2327     if( i_err < 0 )
2328     {
2329         msg_Err( p_this, "ALSA: cannot set sample rate (%s)",
2330                  snd_strerror( i_err ) );
2331         goto adev_fail;
2332     }
2333
2334     /* Set channels */
2335     unsigned int channels = p_sys->b_stereo ? 2 : 1;
2336     if( ( i_err = snd_pcm_hw_params_set_channels( p_sys->p_alsa_pcm, p_hw_params, channels ) ) < 0 )
2337     {
2338         channels = ( channels==1 ) ? 2 : 1;
2339         msg_Warn( p_this, "ALSA: cannot set channel count (%s). "
2340                   "Trying with channels=%d",
2341                   snd_strerror( i_err ),
2342                   channels );
2343         if( ( i_err = snd_pcm_hw_params_set_channels( p_sys->p_alsa_pcm, p_hw_params, channels ) ) < 0 )
2344         {
2345             msg_Err( p_this, "ALSA: cannot set channel count (%s)",
2346                      snd_strerror( i_err ) );
2347             goto adev_fail;
2348         }
2349         p_sys->b_stereo = ( channels == 2 );
2350     }
2351
2352     /* Set metrics for buffer calculations later */
2353     unsigned int buffer_time;
2354     if( ( i_err = snd_pcm_hw_params_get_buffer_time_max(p_hw_params, &buffer_time, 0) ) < 0 )
2355     {
2356         msg_Err( p_this, "ALSA: cannot get buffer time max (%s)",
2357                  snd_strerror( i_err ) );
2358         goto adev_fail;
2359     }
2360     if (buffer_time > 500000) buffer_time = 500000;
2361
2362     /* Set period time */
2363     unsigned int period_time = buffer_time / 4;
2364 #ifdef HAVE_ALSA_NEW_API
2365     i_err = snd_pcm_hw_params_set_period_time_near( p_sys->p_alsa_pcm, p_hw_params, &period_time, 0 );
2366 #else
2367     i_err = snd_pcm_hw_params_set_period_time_near( p_sys->p_alsa_pcm, p_hw_params, period_time, 0 );
2368 #endif
2369     if( i_err < 0 )
2370     {
2371         msg_Err( p_this, "ALSA: cannot set period time (%s)",
2372                  snd_strerror( i_err ) );
2373         goto adev_fail;
2374     }
2375
2376     /* Set buffer time */
2377 #ifdef HAVE_ALSA_NEW_API
2378     i_err = snd_pcm_hw_params_set_buffer_time_near( p_sys->p_alsa_pcm, p_hw_params, &buffer_time, 0 );
2379 #else
2380     i_err = snd_pcm_hw_params_set_buffer_time_near( p_sys->p_alsa_pcm, p_hw_params, buffer_time, 0 );
2381 #endif
2382     if( i_err < 0 )
2383     {
2384         msg_Err( p_this, "ALSA: cannot set buffer time (%s)",
2385                  snd_strerror( i_err ) );
2386         goto adev_fail;
2387     }
2388
2389     /* Apply new hardware parameters */
2390     if( ( i_err = snd_pcm_hw_params( p_sys->p_alsa_pcm, p_hw_params ) ) < 0 )
2391     {
2392         msg_Err( p_this, "ALSA: cannot set hw parameters (%s)",
2393                  snd_strerror( i_err ) );
2394         goto adev_fail;
2395     }
2396
2397     /* Get various buffer metrics */
2398     snd_pcm_hw_params_get_period_size( p_hw_params, &chunk_size, 0 );
2399     snd_pcm_hw_params_get_buffer_size( p_hw_params, &buffer_size );
2400     if( chunk_size == buffer_size )
2401     {
2402         msg_Err( p_this,
2403                  "ALSA: period cannot equal buffer size (%lu == %lu)",
2404                  chunk_size, buffer_size);
2405         goto adev_fail;
2406     }
2407
2408     int bits_per_sample = snd_pcm_format_physical_width(SND_PCM_FORMAT_S16_LE);
2409     int bits_per_frame = bits_per_sample * channels;
2410
2411     p_sys->i_alsa_chunk_size = chunk_size;
2412     p_sys->i_alsa_frame_size = bits_per_frame / 8;
2413     p_sys->i_audio_max_frame_size = chunk_size * bits_per_frame / 8;
2414
2415     snd_pcm_hw_params_free( p_hw_params );
2416     p_hw_params = NULL;
2417
2418     /* Prep device */
2419     if( ( i_err = snd_pcm_prepare( p_sys->p_alsa_pcm ) ) < 0 )
2420     {
2421         msg_Err( p_this,
2422                  "ALSA: cannot prepare audio interface for use (%s)",
2423                  snd_strerror( i_err ) );
2424         goto adev_fail;
2425     }
2426
2427     /* Return a fake handle so other tests work */
2428     i_fd = 1;
2429
2430     free( psz_alsa_device_name );
2431
2432     if( !p_sys->psz_adev )
2433         p_sys->psz_adev = strdup( ALSA_DEFAULT );
2434     return i_fd;
2435
2436  adev_fail:
2437
2438     if( i_fd >= 0 ) close( i_fd );
2439
2440     if( p_hw_params ) snd_pcm_hw_params_free( p_hw_params );
2441     if( p_sys->p_alsa_pcm ) snd_pcm_close( p_sys->p_alsa_pcm );
2442     free( psz_alsa_device_name );
2443
2444     return -1;
2445
2446 }
2447 #endif
2448
2449 static int OpenAudioDevOss( vlc_object_t *p_this, demux_sys_t *p_sys,
2450                             vlc_bool_t b_demux )
2451 {
2452     char *psz_device = p_sys->psz_adev;
2453     int i_fd = 0;
2454     int i_format;
2455     /* OSS */
2456     if( !psz_device ) psz_device = strdup( OSS_DEFAULT ); /* FIXME leak */
2457
2458     if( (i_fd = open( psz_device, O_RDONLY | O_NONBLOCK )) < 0 )
2459     {
2460         msg_Err( p_this, "cannot open OSS audio device (%m)" );
2461         goto adev_fail;
2462     }
2463
2464     i_format = AFMT_S16_LE;
2465     if( ioctl( i_fd, SNDCTL_DSP_SETFMT, &i_format ) < 0
2466         || i_format != AFMT_S16_LE )
2467     {
2468         msg_Err( p_this,
2469                  "cannot set audio format (16b little endian) (%m)" );
2470         goto adev_fail;
2471     }
2472
2473     if( ioctl( i_fd, SNDCTL_DSP_STEREO,
2474                &p_sys->b_stereo ) < 0 )
2475     {
2476         msg_Err( p_this, "cannot set audio channels count (%m)" );
2477         goto adev_fail;
2478     }
2479
2480     if( ioctl( i_fd, SNDCTL_DSP_SPEED,
2481                &p_sys->i_sample_rate ) < 0 )
2482     {
2483         msg_Err( p_this, "cannot set audio sample rate (%m)" );
2484         goto adev_fail;
2485     }
2486
2487     p_sys->i_audio_max_frame_size = 6 * 1024;
2488
2489     if( !p_sys->psz_adev )
2490         p_sys->psz_adev = strdup( OSS_DEFAULT );
2491     return i_fd;
2492
2493  adev_fail:
2494
2495     if( i_fd >= 0 ) close( i_fd );
2496     return -1;
2497
2498 }
2499
2500 static int OpenAudioDev( vlc_object_t *p_this, demux_sys_t *p_sys,
2501                          vlc_bool_t b_demux )
2502 {
2503     char *psz_device;
2504     int i_fd = -1;
2505
2506 #ifdef HAVE_ALSA
2507     if( ( p_sys->i_audio_method & AUDIO_METHOD_ALSA ) && i_fd < 0 )
2508         i_fd  = OpenAudioDevAlsa( p_this, p_sys, b_demux );
2509 #endif
2510
2511     if( ( p_sys->i_audio_method & AUDIO_METHOD_OSS ) && i_fd < 0 )
2512         i_fd = OpenAudioDevOss( p_this, p_sys, b_demux );
2513
2514     if( i_fd < 0 )
2515         return i_fd;
2516
2517     psz_device = p_sys->psz_adev;
2518
2519     msg_Dbg( p_this, "opened adev=`%s' %s %dHz",
2520              psz_device, p_sys->b_stereo ? "stereo" : "mono",
2521              p_sys->i_sample_rate );
2522
2523     es_format_t fmt;
2524     es_format_Init( &fmt, AUDIO_ES, VLC_FOURCC('a','r','a','w') );
2525
2526     fmt.audio.i_channels = p_sys->b_stereo ? 2 : 1;
2527     fmt.audio.i_rate = p_sys->i_sample_rate;
2528     fmt.audio.i_bitspersample = 16;
2529     fmt.audio.i_blockalign = fmt.audio.i_channels * fmt.audio.i_bitspersample / 8;
2530     fmt.i_bitrate = fmt.audio.i_channels * fmt.audio.i_rate * fmt.audio.i_bitspersample;
2531
2532     msg_Dbg( p_this, "new audio es %d channels %dHz",
2533              fmt.audio.i_channels, fmt.audio.i_rate );
2534
2535     if( b_demux )
2536     {
2537         demux_t *p_demux = (demux_t *)p_this;
2538         p_sys->p_es_audio = es_out_Add( p_demux->out, &fmt );
2539     }
2540
2541     return i_fd;
2542 }
2543
2544 /*****************************************************************************
2545  * ProbeVideoDev: probe video for capabilities
2546  *****************************************************************************/
2547 static vlc_bool_t ProbeVideoDev( vlc_object_t *p_obj, demux_sys_t *p_sys,
2548                                  char *psz_device )
2549 {
2550     int i_index;
2551     int i_standard;
2552
2553     int i_fd;
2554
2555     if( ( i_fd = open( psz_device, O_RDWR ) ) < 0 )
2556     {
2557         msg_Err( p_obj, "cannot open video device (%m)" );
2558         goto open_failed;
2559     }
2560
2561     /* Get device capabilites */
2562
2563     if( ioctl( i_fd, VIDIOC_QUERYCAP, &p_sys->dev_cap ) < 0 )
2564     {
2565         msg_Err( p_obj, "cannot get video capabilities (%m)" );
2566         goto open_failed;
2567     }
2568
2569     msg_Dbg( p_obj, "V4L2 device: %s using driver: %s (version: %u.%u.%u) on %s",
2570                             p_sys->dev_cap.card,
2571                             p_sys->dev_cap.driver,
2572                             (p_sys->dev_cap.version >> 16) & 0xFF,
2573                             (p_sys->dev_cap.version >> 8) & 0xFF,
2574                             p_sys->dev_cap.version & 0xFF,
2575                             p_sys->dev_cap.bus_info );
2576
2577     msg_Dbg( p_obj, "the device has the capabilities: (%c) Video Capure, "
2578                                                        "(%c) Audio, "
2579                                                        "(%c) Tuner",
2580              ( p_sys->dev_cap.capabilities & V4L2_CAP_VIDEO_CAPTURE  ? 'X':' '),
2581              ( p_sys->dev_cap.capabilities & V4L2_CAP_AUDIO  ? 'X':' '),
2582              ( p_sys->dev_cap.capabilities & V4L2_CAP_TUNER  ? 'X':' ') );
2583
2584     msg_Dbg( p_obj, "supported I/O methods are: (%c) Read/Write, "
2585                                                  "(%c) Streaming, "
2586                                                  "(%c) Asynchronous",
2587             ( p_sys->dev_cap.capabilities & V4L2_CAP_READWRITE ? 'X':' ' ),
2588             ( p_sys->dev_cap.capabilities & V4L2_CAP_STREAMING ? 'X':' ' ),
2589             ( p_sys->dev_cap.capabilities & V4L2_CAP_ASYNCIO ? 'X':' ' ) );
2590
2591     /* Now, enumerate all the video inputs. This is useless at the moment
2592        since we have no way to present that info to the user except with
2593        debug messages */
2594
2595     if( p_sys->dev_cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
2596     {
2597         struct v4l2_input t_input;
2598         t_input.index = 0;
2599         while( ioctl( i_fd, VIDIOC_ENUMINPUT, &t_input ) >= 0 )
2600         {
2601             p_sys->i_input++;
2602             t_input.index = p_sys->i_input;
2603         }
2604
2605         p_sys->p_inputs = calloc( 1, p_sys->i_input * sizeof( struct v4l2_input ) );
2606         if( !p_sys->p_inputs ) goto open_failed;
2607
2608         for( i_index = 0; i_index < p_sys->i_input; i_index++ )
2609         {
2610             p_sys->p_inputs[i_index].index = i_index;
2611
2612             if( ioctl( i_fd, VIDIOC_ENUMINPUT, &p_sys->p_inputs[i_index] ) )
2613             {
2614                 msg_Err( p_obj, "cannot get video input characteristics (%m)" );
2615                 goto open_failed;
2616             }
2617             msg_Dbg( p_obj, "video input %i (%s) has type: %s %c",
2618                                 i_index,
2619                                 p_sys->p_inputs[i_index].name,
2620                                 p_sys->p_inputs[i_index].type
2621                                         == V4L2_INPUT_TYPE_TUNER ?
2622                                         "Tuner adapter" :
2623                                         "External analog input",
2624                                 i_index == p_sys->i_selected_input ? '*' : ' ' );
2625         }
2626     }
2627
2628     /* Probe video standards */
2629     if( p_sys->dev_cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
2630     {
2631         struct v4l2_standard t_standards;
2632         t_standards.index = 0;
2633         while( ioctl( i_fd, VIDIOC_ENUMSTD, &t_standards ) >=0 )
2634         {
2635             p_sys->i_standard++;
2636             t_standards.index = p_sys->i_standard;
2637         }
2638
2639         p_sys->p_standards = calloc( 1, p_sys->i_standard * sizeof( struct v4l2_standard ) );
2640         if( !p_sys->p_standards ) goto open_failed;
2641
2642         for( i_standard = 0; i_standard < p_sys->i_standard; i_standard++ )
2643         {
2644             p_sys->p_standards[i_standard].index = i_standard;
2645
2646             if( ioctl( i_fd, VIDIOC_ENUMSTD, &p_sys->p_standards[i_standard] ) )
2647             {
2648                 msg_Err( p_obj, "cannot get video input standards (%m)" );
2649                 goto open_failed;
2650             }
2651             msg_Dbg( p_obj, "video standard %i is: %s %c",
2652                                 i_standard,
2653                                 p_sys->p_standards[i_standard].name,
2654                                 (unsigned)i_standard == p_sys->i_selected_standard_id ? '*' : ' ' );
2655         }
2656     }
2657
2658     /* initialize the structures for the ioctls */
2659     for( i_index = 0; i_index < 32; i_index++ )
2660     {
2661         p_sys->p_audios[i_index].index = i_index;
2662     }
2663
2664     /* Probe audio inputs */
2665     if( p_sys->dev_cap.capabilities & V4L2_CAP_AUDIO )
2666     {
2667         while( p_sys->i_audio < 32 &&
2668                ioctl( i_fd, VIDIOC_S_AUDIO, &p_sys->p_audios[p_sys->i_audio] ) >= 0 )
2669         {
2670             if( ioctl( i_fd, VIDIOC_G_AUDIO, &p_sys->p_audios[ p_sys->i_audio] ) < 0 )
2671             {
2672                 msg_Err( p_obj, "cannot get audio input characteristics (%m)" );
2673                 goto open_failed;
2674             }
2675
2676             msg_Dbg( p_obj, "audio input %i (%s) is %s %s %c",
2677                                 p_sys->i_audio,
2678                                 p_sys->p_audios[p_sys->i_audio].name,
2679                                 p_sys->p_audios[p_sys->i_audio].capability &
2680                                                     V4L2_AUDCAP_STEREO ?
2681                                         "Stereo" : "Mono",
2682                                 p_sys->p_audios[p_sys->i_audio].capability &
2683                                                     V4L2_AUDCAP_AVL ?
2684                                     "(Automatic Volume Level supported)" : "",
2685                                 p_sys->i_audio == p_sys->i_selected_audio_input ? '*' : ' ' );
2686
2687             p_sys->i_audio++;
2688         }
2689     }
2690
2691     /* List tuner caps */
2692     if( p_sys->dev_cap.capabilities & V4L2_CAP_TUNER )
2693     {
2694         struct v4l2_tuner tuner;
2695         memset( &tuner, 0, sizeof(tuner) );
2696         while( ioctl( i_fd, VIDIOC_G_TUNER, &tuner ) >= 0 )
2697         {
2698             p_sys->i_tuner++;
2699             memset( &tuner, 0, sizeof(tuner) );
2700             tuner.index = p_sys->i_tuner;
2701         }
2702
2703         p_sys->p_tuners = calloc( 1, p_sys->i_tuner * sizeof( struct v4l2_tuner ) );
2704         if( !p_sys->p_tuners ) goto open_failed;
2705
2706         for( i_index = 0; i_index < p_sys->i_tuner; i_index++ )
2707         {
2708             p_sys->p_tuners[i_index].index = i_index;
2709
2710             if( ioctl( i_fd, VIDIOC_G_TUNER, &p_sys->p_tuners[i_index] ) )
2711             {
2712                 msg_Err( p_obj, "cannot get tuner characteristics (%m)" );
2713                 goto open_failed;
2714             }
2715             msg_Dbg( p_obj, "tuner %i (%s) has type: %s, "
2716                               "frequency range: %.1f %s -> %.1f %s",
2717                                 i_index,
2718                                 p_sys->p_tuners[i_index].name,
2719                                 p_sys->p_tuners[i_index].type
2720                                         == V4L2_TUNER_RADIO ?
2721                                         "Radio" : "Analog TV",
2722                                 p_sys->p_tuners[i_index].rangelow * 62.5,
2723                                 p_sys->p_tuners[i_index].capability &
2724                                         V4L2_TUNER_CAP_LOW ?
2725                                         "Hz" : "kHz",
2726                                 p_sys->p_tuners[i_index].rangehigh * 62.5,
2727                                 p_sys->p_tuners[i_index].capability &
2728                                         V4L2_TUNER_CAP_LOW ?
2729                                         "Hz" : "kHz" );
2730
2731             struct v4l2_frequency frequency;
2732             memset( &frequency, 0, sizeof( frequency ) );
2733             if( ioctl( i_fd, VIDIOC_G_FREQUENCY, &frequency ) < 0 )
2734             {
2735                 msg_Err( p_obj, "cannot get tuner frequency (%m)" );
2736                 goto open_failed;
2737             }
2738             msg_Dbg( p_obj, "tuner %i (%s) frequency: %.1f %s",
2739                      i_index,
2740                      p_sys->p_tuners[i_index].name,
2741                      frequency.frequency * 62.5,
2742                      p_sys->p_tuners[i_index].capability &
2743                              V4L2_TUNER_CAP_LOW ?
2744                              "Hz" : "kHz" );
2745         }
2746     }
2747
2748     /* Probe for available chromas */
2749     if( p_sys->dev_cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
2750     {
2751         struct v4l2_fmtdesc codec;
2752
2753         i_index = 0;
2754         memset( &codec, 0, sizeof(codec) );
2755         codec.index = i_index;
2756         codec.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2757
2758         while( ioctl( i_fd, VIDIOC_ENUM_FMT, &codec ) >= 0 )
2759         {
2760             i_index++;
2761             codec.index = i_index;
2762         }
2763
2764         p_sys->i_codec = i_index;
2765
2766         p_sys->p_codecs = calloc( 1, p_sys->i_codec * sizeof( struct v4l2_fmtdesc ) );
2767
2768         for( i_index = 0; i_index < p_sys->i_codec; i_index++ )
2769         {
2770             p_sys->p_codecs[i_index].index = i_index;
2771             p_sys->p_codecs[i_index].type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2772
2773             if( ioctl( i_fd, VIDIOC_ENUM_FMT, &p_sys->p_codecs[i_index] ) < 0 )
2774             {
2775                 msg_Err( p_obj, "cannot get codec description (%m)" );
2776                 goto open_failed;
2777             }
2778
2779             /* only print if vlc supports the format */
2780             char psz_fourcc_v4l2[5];
2781             memset( &psz_fourcc_v4l2, 0, sizeof( psz_fourcc_v4l2 ) );
2782             vlc_fourcc_to_char( p_sys->p_codecs[i_index].pixelformat,
2783                                 &psz_fourcc_v4l2 );
2784             vlc_bool_t b_codec_supported = VLC_FALSE;
2785             for( int i = 0; v4l2chroma_to_fourcc[i].i_v4l2 != 0; i++ )
2786             {
2787                 if( v4l2chroma_to_fourcc[i].i_v4l2 == p_sys->p_codecs[i_index].pixelformat )
2788                 {
2789                     b_codec_supported = VLC_TRUE;
2790
2791                     char psz_fourcc[5];
2792                     memset( &psz_fourcc, 0, sizeof( psz_fourcc ) );
2793                     vlc_fourcc_to_char( v4l2chroma_to_fourcc[i].i_fourcc,
2794                                         &psz_fourcc );
2795                     msg_Dbg( p_obj, "device supports chroma %4s [%s, %s]",
2796                                 psz_fourcc,
2797                                 p_sys->p_codecs[i_index].description,
2798                                 psz_fourcc_v4l2 );
2799
2800 #ifdef VIDIOC_ENUM_FRAMESIZES
2801                     /* This is new in Linux 2.6.19 */
2802                     /* List valid frame sizes for this format */
2803                     struct v4l2_frmsizeenum frmsize;
2804                     frmsize.index = 0;
2805                     frmsize.pixel_format = p_sys->p_codecs[i_index].pixelformat;
2806                     if( ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize ) < 0 )
2807                     {
2808                         /* Not all devices support this ioctl */
2809                         msg_Warn( p_obj, "Unable to query for frame sizes" );
2810                     }
2811                     else
2812                     {
2813                         switch( frmsize.type )
2814                         {
2815                             case V4L2_FRMSIZE_TYPE_DISCRETE:
2816                                 do
2817                                 {
2818                                     msg_Dbg( p_obj,
2819                 "    device supports size %dx%d",
2820                 frmsize.discrete.width, frmsize.discrete.height );
2821                                     frmsize.index++;
2822                                 } while( ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize ) >= 0 );
2823                                 break;
2824                             case V4L2_FRMSIZE_TYPE_STEPWISE:
2825                                 msg_Dbg( p_obj,
2826                 "    device supports sizes %dx%d to %dx%d using %dx%d increments",
2827                 frmsize.stepwise.min_width, frmsize.stepwise.min_height,
2828                 frmsize.stepwise.max_width, frmsize.stepwise.max_height,
2829                 frmsize.stepwise.step_width, frmsize.stepwise.step_height );
2830                                 break;
2831                             case V4L2_FRMSIZE_TYPE_CONTINUOUS:
2832                                 msg_Dbg( p_obj,
2833                 "    device supports all sizes %dx%d to %dx%d",
2834                 frmsize.stepwise.min_width, frmsize.stepwise.min_height,
2835                 frmsize.stepwise.max_width, frmsize.stepwise.max_height );
2836                                 break;
2837                         }
2838                     }
2839 #endif
2840                 }
2841             }
2842             if( !b_codec_supported )
2843             {
2844                     msg_Dbg( p_obj,
2845                          "device codec %4s (%s) not supported as access_demux",
2846                          psz_fourcc_v4l2,
2847                          p_sys->p_codecs[i_index].description );
2848             }
2849
2850         }
2851     }
2852
2853
2854     if( i_fd >= 0 ) close( i_fd );
2855     return VLC_TRUE;
2856
2857 open_failed:
2858
2859     if( i_fd >= 0 ) close( i_fd );
2860     return VLC_FALSE;
2861
2862 }
2863
2864 /*****************************************************************************
2865  * ProbeAudioDev: probe audio for capabilities
2866  *****************************************************************************/
2867 #ifdef HAVE_ALSA
2868 static vlc_bool_t ProbeAudioDevAlsa( vlc_object_t *p_this, demux_sys_t *p_sys,
2869                                      char *psz_device )
2870 {
2871     int i_err;
2872     snd_pcm_t *p_alsa_pcm;
2873     char* psz_alsa_device_name = ResolveALSADeviceName( psz_device ?: ALSA_DEFAULT );
2874
2875     if( ( i_err = snd_pcm_open( &p_alsa_pcm, psz_alsa_device_name, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK ) ) < 0 )
2876     {
2877         msg_Err( p_this, "cannot open device %s for ALSA audio (%s)", psz_alsa_device_name, snd_strerror( i_err ) );
2878         free( psz_alsa_device_name );
2879         return VLC_FALSE;
2880     }
2881
2882     snd_pcm_close( p_alsa_pcm );
2883     free( psz_alsa_device_name );
2884
2885     return VLC_TRUE;
2886 }
2887 #endif
2888
2889 static vlc_bool_t ProbeAudioDevOss( vlc_object_t *p_this, demux_sys_t *p_sys,
2890                                     char *psz_device )
2891 {
2892     int i_fd = 0;
2893     int i_caps;
2894     if( !psz_device ) psz_device = strdup( OSS_DEFAULT ); /* FIXME leak */
2895
2896     if( ( i_fd = open( psz_device, O_RDONLY | O_NONBLOCK ) ) < 0 )
2897     {
2898         msg_Err( p_this, "cannot open device %s for OSS audio (%m)", psz_device );
2899         goto open_failed;
2900     }
2901
2902     /* this will fail if the device is video */
2903     if( ioctl( i_fd, SNDCTL_DSP_GETCAPS, &i_caps ) < 0 )
2904     {
2905         msg_Err( p_this, "cannot get audio caps (%m)" );
2906         goto open_failed;
2907     }
2908
2909     if( i_fd >= 0 ) close( i_fd );
2910
2911     return VLC_TRUE;
2912
2913 open_failed:
2914     if( i_fd >= 0 ) close( i_fd );
2915     return VLC_FALSE;
2916 }
2917
2918 static vlc_bool_t ProbeAudioDev( vlc_object_t *p_this, demux_sys_t *p_sys,
2919                                  char *psz_device )
2920 {
2921 #ifdef HAVE_ALSA
2922     if( ( p_sys->i_audio_method & AUDIO_METHOD_ALSA )
2923      && ProbeAudioDevAlsa( p_this, p_sys, psz_device ) )
2924     {
2925         p_sys->i_audio_method = AUDIO_METHOD_ALSA;
2926         return VLC_TRUE;
2927     }
2928 #endif
2929
2930     if( ( p_sys->i_audio_method & AUDIO_METHOD_OSS )
2931      && ProbeAudioDevOss( p_this, p_sys, psz_device ) )
2932     {
2933         p_sys->i_audio_method = AUDIO_METHOD_OSS;
2934         return VLC_TRUE;
2935     }
2936
2937     p_sys->i_audio_method = 0;
2938     return VLC_FALSE;
2939 }
2940
2941 static void name2var( unsigned char *name )
2942 {
2943     for( ; *name; name++ )
2944         *name = (*name == ' ') ? '_' : tolower( *name );
2945 }
2946
2947 /*****************************************************************************
2948  * Print a user-class v4l2 control's details, create the relevant variable,
2949  * change the value if needed.
2950  *****************************************************************************/
2951 static void ControlListPrint( vlc_object_t *p_obj, int i_fd,
2952                               struct v4l2_queryctrl queryctrl,
2953                               vlc_bool_t b_reset, vlc_bool_t b_demux )
2954 {
2955     struct v4l2_querymenu querymenu;
2956     unsigned int i_mid;
2957
2958     int i;
2959     int i_val;
2960
2961     char *psz_name;
2962     vlc_value_t val, val2;
2963
2964     if( queryctrl.flags & V4L2_CTRL_FLAG_GRABBED )
2965         msg_Dbg( p_obj, "    control is busy" );
2966     if( queryctrl.flags & V4L2_CTRL_FLAG_READ_ONLY )
2967         msg_Dbg( p_obj, "    control is read-only" );
2968
2969     for( i = 0; controls[i].psz_name != NULL; i++ )
2970         if( controls[i].i_cid == queryctrl.id ) break;
2971
2972     if( controls[i].psz_name )
2973     {
2974         psz_name = strdup( controls[i].psz_name );
2975         char psz_cfg_name[40];
2976         sprintf( psz_cfg_name, CFG_PREFIX "%s", psz_name );
2977         i_val = var_CreateGetInteger( p_obj, psz_cfg_name );
2978         var_Destroy( p_obj, psz_cfg_name );
2979     }
2980     else
2981     {
2982         psz_name = strdup( (const char *)queryctrl.name );
2983         name2var( (unsigned char *)psz_name );
2984         i_val = -1;
2985     }
2986
2987     switch( queryctrl.type )
2988     {
2989         case V4L2_CTRL_TYPE_INTEGER:
2990             msg_Dbg( p_obj, "    integer control" );
2991             msg_Dbg( p_obj,
2992                      "    valid values: %d to %d by steps of %d",
2993                      queryctrl.minimum, queryctrl.maximum,
2994                      queryctrl.step );
2995
2996             var_Create( p_obj, psz_name,
2997                         VLC_VAR_INTEGER | VLC_VAR_HASMIN | VLC_VAR_HASMAX
2998                       | VLC_VAR_HASSTEP | VLC_VAR_ISCOMMAND );
2999             val.i_int = queryctrl.minimum;
3000             var_Change( p_obj, psz_name, VLC_VAR_SETMIN, &val, NULL );
3001             val.i_int = queryctrl.maximum;
3002             var_Change( p_obj, psz_name, VLC_VAR_SETMAX, &val, NULL );
3003             val.i_int = queryctrl.step;
3004             var_Change( p_obj, psz_name, VLC_VAR_SETSTEP, &val, NULL );
3005             break;
3006         case V4L2_CTRL_TYPE_BOOLEAN:
3007             msg_Dbg( p_obj, "    boolean control" );
3008             var_Create( p_obj, psz_name,
3009                         VLC_VAR_BOOL | VLC_VAR_ISCOMMAND );
3010             break;
3011         case V4L2_CTRL_TYPE_MENU:
3012             msg_Dbg( p_obj, "    menu control" );
3013             var_Create( p_obj, psz_name,
3014                         VLC_VAR_INTEGER | VLC_VAR_HASCHOICE
3015                       | VLC_VAR_ISCOMMAND );
3016             memset( &querymenu, 0, sizeof( querymenu ) );
3017             for( i_mid = queryctrl.minimum;
3018                  i_mid <= (unsigned)queryctrl.maximum;
3019                  i_mid++ )
3020             {
3021                 querymenu.index = i_mid;
3022                 querymenu.id = queryctrl.id;
3023                 if( ioctl( i_fd, VIDIOC_QUERYMENU, &querymenu ) >= 0 )
3024                 {
3025                     msg_Dbg( p_obj, "        %d: %s",
3026                              querymenu.index, querymenu.name );
3027                     val.i_int = querymenu.index;
3028                     val2.psz_string = (char *)querymenu.name;
3029                     var_Change( p_obj, psz_name,
3030                                 VLC_VAR_ADDCHOICE, &val, &val2 );
3031                 }
3032             }
3033             break;
3034         case V4L2_CTRL_TYPE_BUTTON:
3035             msg_Dbg( p_obj, "    button control" );
3036             var_Create( p_obj, psz_name,
3037                         VLC_VAR_VOID | VLC_VAR_ISCOMMAND );
3038             break;
3039         case V4L2_CTRL_TYPE_CTRL_CLASS:
3040             msg_Dbg( p_obj, "    control class" );
3041             var_Create( p_obj, psz_name, VLC_VAR_VOID );
3042             break;
3043         default:
3044             msg_Dbg( p_obj, "    unknown control type (FIXME)" );
3045             /* FIXME */
3046             break;
3047     }
3048
3049     switch( queryctrl.type )
3050     {
3051         case V4L2_CTRL_TYPE_INTEGER:
3052         case V4L2_CTRL_TYPE_BOOLEAN:
3053         case V4L2_CTRL_TYPE_MENU:
3054             {
3055                 struct v4l2_control control;
3056                 msg_Dbg( p_obj, "    default value: %d",
3057                          queryctrl.default_value );
3058                 memset( &control, 0, sizeof( control ) );
3059                 control.id = queryctrl.id;
3060                 if( ioctl( i_fd, VIDIOC_G_CTRL, &control ) >= 0 )
3061                 {
3062                     msg_Dbg( p_obj, "    current value: %d", control.value );
3063                 }
3064                 if( i_val == -1 )
3065                 {
3066                     i_val = control.value;
3067                     if( b_reset && queryctrl.default_value != control.value )
3068                     {
3069                         msg_Dbg( p_obj, "    reset value to default" );
3070                         Control( p_obj, i_fd, psz_name,
3071                                       queryctrl.id, queryctrl.default_value );
3072                     }
3073                 }
3074                 else
3075                 {
3076                     Control( p_obj, i_fd, psz_name,
3077                                   queryctrl.id, i_val );
3078                 }
3079             }
3080             break;
3081         default:
3082             break;
3083     }
3084
3085     val.psz_string = (char *)queryctrl.name;
3086     var_Change( p_obj, psz_name, VLC_VAR_SETTEXT, &val, NULL );
3087     val.i_int = queryctrl.id;
3088     val2.psz_string = (char *)psz_name;
3089     var_Change( p_obj, "allcontrols", VLC_VAR_ADDCHOICE, &val, &val2 );
3090     /* bad things happen changing MPEG mid-stream
3091      * so don't add to Ext Settings GUI */
3092     if( V4L2_CTRL_ID2CLASS( queryctrl.id ) != V4L2_CTRL_CLASS_MPEG )
3093         var_Change( p_obj, "controls", VLC_VAR_ADDCHOICE, &val, &val2 );
3094
3095     switch( var_Type( p_obj, psz_name ) & VLC_VAR_TYPE )
3096     {
3097         case VLC_VAR_BOOL:
3098             var_SetBool( p_obj, psz_name, i_val );
3099             break;
3100         case VLC_VAR_INTEGER:
3101             var_SetInteger( p_obj, psz_name, i_val );
3102             break;
3103         case VLC_VAR_VOID:
3104             break;
3105         default:
3106             msg_Warn( p_obj, "FIXME: %s %s %d", __FILE__, __func__,
3107                       __LINE__ );
3108             break;
3109     }
3110
3111     if( b_demux )
3112         var_AddCallback( p_obj, psz_name,
3113                         DemuxControlCallback, (void*)queryctrl.id );
3114     else
3115         var_AddCallback( p_obj, psz_name,
3116                         AccessControlCallback, (void*)queryctrl.id );
3117
3118     free( psz_name );
3119 }
3120
3121 /*****************************************************************************
3122  * List all user-class v4l2 controls, set them to the user specified
3123  * value and create the relevant variables to enable runtime changes
3124  *****************************************************************************/
3125 static int ControlList( vlc_object_t *p_obj, int i_fd,
3126                         vlc_bool_t b_reset, vlc_bool_t b_demux )
3127 {
3128     struct v4l2_queryctrl queryctrl;
3129     int i_cid;
3130
3131     memset( &queryctrl, 0, sizeof( queryctrl ) );
3132
3133     /* A list of available controls (aka the variable name) will be
3134      * stored as choices in the "allcontrols" variable. We'll thus be able
3135      * to use those to create an appropriate interface
3136      * A list of available controls that can be changed mid-stream will
3137      * be stored in the "controls" variable */
3138     var_Create( p_obj, "controls", VLC_VAR_INTEGER | VLC_VAR_HASCHOICE );
3139     var_Create( p_obj, "allcontrols", VLC_VAR_INTEGER | VLC_VAR_HASCHOICE );
3140
3141     var_Create( p_obj, "controls-update", VLC_VAR_VOID | VLC_VAR_ISCOMMAND );
3142
3143     /* Add a control to reset all controls to their default values */
3144     vlc_value_t val, val2;
3145     var_Create( p_obj, "controls-reset", VLC_VAR_VOID | VLC_VAR_ISCOMMAND );
3146     val.psz_string = _( "Reset controls to default" );
3147     var_Change( p_obj, "controls-reset", VLC_VAR_SETTEXT, &val, NULL );
3148     val.i_int = -1;
3149     val2.psz_string = (char *)"controls-reset";
3150     var_Change( p_obj, "controls", VLC_VAR_ADDCHOICE, &val, &val2 );
3151     if (b_demux)
3152         var_AddCallback( p_obj, "controls-reset", DemuxControlResetCallback, NULL );
3153     else
3154         var_AddCallback( p_obj, "controls-reset", AccessControlResetCallback, NULL );
3155
3156     queryctrl.id = V4L2_CTRL_FLAG_NEXT_CTRL;
3157     if( ioctl( i_fd, VIDIOC_QUERYCTRL, &queryctrl ) >= 0 )
3158     {
3159         msg_Dbg( p_obj, "Extended control API supported by v4l2 driver" );
3160
3161         /* List extended controls */
3162         queryctrl.id = V4L2_CTRL_FLAG_NEXT_CTRL;
3163         while( ioctl( i_fd, VIDIOC_QUERYCTRL, &queryctrl ) >= 0 )
3164         {
3165             if( queryctrl.type == V4L2_CTRL_TYPE_CTRL_CLASS )
3166             {
3167                 msg_Dbg( p_obj, "%s", queryctrl.name );
3168                 queryctrl.id |= V4L2_CTRL_FLAG_NEXT_CTRL;
3169                 continue;
3170             }
3171             switch( V4L2_CTRL_ID2CLASS( queryctrl.id ) )
3172             {
3173                 case V4L2_CTRL_CLASS_USER:
3174                     msg_Dbg( p_obj, "Available control: %s (%x)",
3175                              queryctrl.name, queryctrl.id );
3176                     break;
3177                 case V4L2_CTRL_CLASS_MPEG:
3178                     name2var( queryctrl.name );
3179                     msg_Dbg( p_obj, "Available MPEG control: %s (%x)",
3180                              queryctrl.name, queryctrl.id );
3181                     break;
3182                 default:
3183                     msg_Dbg( p_obj, "Available private control: %s (%x)",
3184                              queryctrl.name, queryctrl.id );
3185                     break;
3186             }
3187             ControlListPrint( p_obj, i_fd, queryctrl, b_reset, b_demux );
3188             queryctrl.id |= V4L2_CTRL_FLAG_NEXT_CTRL;
3189         }
3190     }
3191     else
3192     {
3193         msg_Dbg( p_obj, "Extended control API not supported by v4l2 driver" );
3194
3195         /* List public controls */
3196         for( i_cid = V4L2_CID_BASE;
3197              i_cid < V4L2_CID_LASTP1;
3198              i_cid ++ )
3199         {
3200             queryctrl.id = i_cid;
3201             if( ioctl( i_fd, VIDIOC_QUERYCTRL, &queryctrl ) >= 0 )
3202             {
3203                 if( queryctrl.flags & V4L2_CTRL_FLAG_DISABLED )
3204                     continue;
3205                 msg_Dbg( p_obj, "Available control: %s (%x)",
3206                          queryctrl.name, queryctrl.id );
3207                 ControlListPrint( p_obj, i_fd, queryctrl, b_reset, b_demux );
3208             }
3209         }
3210
3211         /* List private controls */
3212         for( i_cid = V4L2_CID_PRIVATE_BASE;
3213              ;
3214              i_cid ++ )
3215         {
3216             queryctrl.id = i_cid;
3217             if( ioctl( i_fd, VIDIOC_QUERYCTRL, &queryctrl ) >= 0 )
3218             {
3219                 if( queryctrl.flags & V4L2_CTRL_FLAG_DISABLED )
3220                     continue;
3221                 msg_Dbg( p_obj, "Available private control: %s (%x)",
3222                          queryctrl.name, queryctrl.id );
3223                 ControlListPrint( p_obj, i_fd, queryctrl, b_reset, b_demux );
3224             }
3225             else
3226                 break;
3227         }
3228     }
3229
3230     return VLC_SUCCESS;
3231 }
3232
3233 static void SetAvailControlsByString( vlc_object_t *p_obj, demux_sys_t *p_sys,
3234                                       int i_fd )
3235 {
3236     char *psz_parser = p_sys->psz_set_ctrls;
3237     vlc_value_t val, text, name;
3238
3239     if( psz_parser == NULL )
3240         return;
3241
3242     if( *psz_parser == '{' )
3243         psz_parser++;
3244
3245     int i_ret = var_Change( p_obj, "allcontrols", VLC_VAR_GETCHOICES,
3246                             &val, &text );
3247     if( i_ret < 0 )
3248     {
3249         msg_Err( p_obj, "Oops, can't find 'allcontrols' variable." );
3250         return;
3251     }
3252
3253     while( *psz_parser && *psz_parser != '}' )
3254     {
3255         char *psz_delim, *psz_assign;
3256
3257         while( *psz_parser == ',' || *psz_parser == ' ' )
3258             psz_parser++;
3259
3260         psz_delim = strchr( psz_parser, ',' );
3261         if( psz_delim == NULL )
3262             psz_delim = strchr( psz_parser, '}' );
3263         if( psz_delim == NULL )
3264             psz_delim = psz_parser + strlen( psz_parser );
3265
3266         psz_assign = memchr( psz_parser, '=', psz_delim - psz_parser );
3267         if( psz_assign == NULL )
3268         {
3269             char *psz_name = strndup( psz_parser, psz_delim - psz_parser );
3270             msg_Err( p_obj, "%s missing '='", psz_name );
3271             free( psz_name );
3272             psz_parser = psz_delim + 1;
3273             continue;
3274         }
3275
3276         for( int i = 0;
3277              i < val.p_list->i_count ;//&& psz_parser < psz_assign;
3278              i++ )
3279         {
3280             const char *psz_var = text.p_list->p_values[i].psz_string;
3281             int i_cid = val.p_list->p_values[i].i_int;
3282             var_Change( p_obj, psz_var, VLC_VAR_GETTEXT, &name, NULL );
3283             const char *psz_name = name.psz_string;
3284
3285             int i_availstrlen = strlen( psz_name );
3286             int i_parsestrlen = psz_assign - psz_parser;
3287             int i_maxstrlen = __MAX( i_availstrlen, i_parsestrlen);
3288
3289             if( !strncasecmp( psz_name, psz_parser, i_maxstrlen ) )
3290             {
3291                 Control( p_obj, i_fd, psz_name, i_cid,
3292                          strtol( ++psz_assign, &psz_parser, 0) );
3293             }
3294         }
3295
3296         if( psz_parser < psz_assign )
3297         {
3298             char *psz_name = strndup( psz_parser, psz_assign - psz_parser );
3299             msg_Err( p_obj, "Control %s not available", psz_name );
3300             free( psz_name );
3301             psz_parser = ( *psz_delim ) ? ( psz_delim + 1 ) : psz_delim;
3302         }
3303     }
3304 }
3305
3306 /*****************************************************************************
3307  * Reset all user-class v4l2 controls to their default value
3308  *****************************************************************************/
3309 static int ControlReset( vlc_object_t *p_obj, int i_fd )
3310 {
3311     struct v4l2_queryctrl queryctrl;
3312     int i_cid;
3313     memset( &queryctrl, 0, sizeof( queryctrl ) );
3314
3315     queryctrl.id = V4L2_CTRL_FLAG_NEXT_CTRL;
3316     if( ioctl( i_fd, VIDIOC_QUERYCTRL, &queryctrl ) >= 0 )
3317     {
3318         /* Extended control API supported */
3319         queryctrl.id = V4L2_CTRL_FLAG_NEXT_CTRL;
3320         while( ioctl( i_fd, VIDIOC_QUERYCTRL, &queryctrl ) >= 0 )
3321         {
3322             if( queryctrl.type == V4L2_CTRL_TYPE_CTRL_CLASS
3323              || V4L2_CTRL_ID2CLASS( queryctrl.id ) == V4L2_CTRL_CLASS_MPEG )
3324             {
3325                 queryctrl.id |= V4L2_CTRL_FLAG_NEXT_CTRL;
3326                 continue;
3327             }
3328             struct v4l2_control control;
3329             memset( &control, 0, sizeof( control ) );
3330             control.id = queryctrl.id;
3331             if( ioctl( i_fd, VIDIOC_G_CTRL, &control ) >= 0
3332              && queryctrl.default_value != control.value )
3333             {
3334                 int i;
3335                 for( i = 0; controls[i].psz_name != NULL; i++ )
3336                     if( controls[i].i_cid == queryctrl.id ) break;
3337                 name2var( queryctrl.name );
3338                 Control( p_obj, i_fd,
3339                          controls[i].psz_name ? : (const char *)queryctrl.name,
3340                          queryctrl.id, queryctrl.default_value );
3341             }
3342             queryctrl.id |= V4L2_CTRL_FLAG_NEXT_CTRL;
3343         }
3344     }
3345     else
3346     {
3347
3348         /* public controls */
3349         for( i_cid = V4L2_CID_BASE;
3350              i_cid < V4L2_CID_LASTP1;
3351              i_cid ++ )
3352         {
3353             queryctrl.id = i_cid;
3354             if( ioctl( i_fd, VIDIOC_QUERYCTRL, &queryctrl ) >= 0 )
3355             {
3356                 struct v4l2_control control;
3357                 if( queryctrl.flags & V4L2_CTRL_FLAG_DISABLED )
3358                     continue;
3359                 memset( &control, 0, sizeof( control ) );
3360                 control.id = queryctrl.id;
3361                 if( ioctl( i_fd, VIDIOC_G_CTRL, &control ) >= 0
3362                  && queryctrl.default_value != control.value )
3363                 {
3364                     int i;
3365                     for( i = 0; controls[i].psz_name != NULL; i++ )
3366                         if( controls[i].i_cid == queryctrl.id ) break;
3367                     name2var( queryctrl.name );
3368                     Control( p_obj, i_fd,
3369                              controls[i].psz_name ? : (const char *)queryctrl.name,
3370                              queryctrl.id, queryctrl.default_value );
3371                 }
3372             }
3373         }
3374
3375         /* private controls */
3376         for( i_cid = V4L2_CID_PRIVATE_BASE;
3377              ;
3378              i_cid ++ )
3379         {
3380             queryctrl.id = i_cid;
3381             if( ioctl( i_fd, VIDIOC_QUERYCTRL, &queryctrl ) >= 0 )
3382             {
3383                 struct v4l2_control control;
3384                 if( queryctrl.flags & V4L2_CTRL_FLAG_DISABLED )
3385                     continue;
3386                 memset( &control, 0, sizeof( control ) );
3387                 control.id = queryctrl.id;
3388                 if( ioctl( i_fd, VIDIOC_G_CTRL, &control ) >= 0
3389                  && queryctrl.default_value != control.value )
3390                 {
3391                     name2var( queryctrl.name );
3392                     Control( p_obj, i_fd, (const char *)queryctrl.name,
3393                              queryctrl.id, queryctrl.default_value );
3394                 }
3395             }
3396             else
3397                 break;
3398         }
3399     }
3400     return VLC_SUCCESS;
3401 }
3402
3403 /*****************************************************************************
3404  * Issue user-class v4l2 controls
3405  *****************************************************************************/
3406 static int Control( vlc_object_t *p_obj, int i_fd,
3407                     const char *psz_name, int i_cid, int i_value )
3408 {
3409     struct v4l2_queryctrl queryctrl;
3410     struct v4l2_control control;
3411     struct v4l2_ext_control ext_control;
3412     struct v4l2_ext_controls ext_controls;
3413
3414     if( i_value == -1 )
3415         return VLC_SUCCESS;
3416
3417     memset( &queryctrl, 0, sizeof( queryctrl ) );
3418
3419     queryctrl.id = i_cid;
3420
3421     if( ioctl( i_fd, VIDIOC_QUERYCTRL, &queryctrl ) < 0
3422         || queryctrl.flags & V4L2_CTRL_FLAG_DISABLED )
3423     {
3424         msg_Dbg( p_obj, "%s (%x) control is not supported.", psz_name, i_cid );
3425         return VLC_EGENERIC;
3426     }
3427
3428     memset( &control, 0, sizeof( control ) );
3429     memset( &ext_control, 0, sizeof( ext_control ) );
3430     memset( &ext_controls, 0, sizeof( ext_controls ) );
3431     control.id = i_cid;
3432     ext_control.id = i_cid;
3433     ext_controls.ctrl_class = V4L2_CTRL_ID2CLASS( i_cid );
3434     ext_controls.count = 1;
3435     ext_controls.controls = &ext_control;
3436
3437     int i_ret = -1;
3438
3439     if( i_value >= 0 )
3440     {
3441         ext_control.value = i_value;
3442         if( ioctl( i_fd, VIDIOC_S_EXT_CTRLS, &ext_controls ) < 0 )
3443         {
3444             control.value = i_value;
3445             if( ioctl( i_fd, VIDIOC_S_CTRL, &control ) < 0 )
3446             {
3447                 msg_Err( p_obj, "unable to set %s (%x) to %d (%m)",
3448                          psz_name, i_cid, i_value );
3449                 return VLC_EGENERIC;
3450             }
3451             i_ret = ioctl( i_fd, VIDIOC_G_CTRL, &control );
3452         }
3453         else
3454         {
3455             i_ret = ioctl( i_fd, VIDIOC_G_EXT_CTRLS, &ext_controls );
3456             control.value = ext_control.value;
3457         }
3458     }
3459
3460     if( i_ret >= 0 )
3461     {
3462         vlc_value_t val;
3463         msg_Dbg( p_obj, "video %s: %d", psz_name, control.value );
3464         switch( var_Type( p_obj, psz_name ) & VLC_VAR_TYPE )
3465         {
3466             case VLC_VAR_BOOL:
3467                 val.b_bool = control.value;
3468                 var_Change( p_obj, psz_name, VLC_VAR_SETVALUE, &val, NULL );
3469                 var_SetVoid( p_obj, "controls-update" );
3470                 break;
3471             case VLC_VAR_INTEGER:
3472                 val.i_int = control.value;
3473                 var_Change( p_obj, psz_name, VLC_VAR_SETVALUE, &val, NULL );
3474                 var_SetVoid( p_obj, "controls-update" );
3475                 break;
3476         }
3477     }
3478     return VLC_SUCCESS;
3479 }
3480
3481 /*****************************************************************************
3482  * On the fly change settings callback
3483  *****************************************************************************/
3484 static int DemuxControlCallback( vlc_object_t *p_this,
3485     const char *psz_var, vlc_value_t oldval, vlc_value_t newval,
3486     void *p_data )
3487 {
3488     demux_t *p_demux = (demux_t*)p_this;
3489     demux_sys_t *p_sys = p_demux->p_sys;
3490     int i_cid = (int)p_data;
3491
3492     int i_fd = p_sys->i_fd_video;
3493
3494     if( i_fd < 0 )
3495         return VLC_EGENERIC;
3496
3497     Control( p_this, i_fd, psz_var, i_cid, newval.i_int );
3498
3499     return VLC_EGENERIC;
3500 }
3501
3502 static int DemuxControlResetCallback( vlc_object_t *p_this,
3503     const char *psz_var, vlc_value_t oldval, vlc_value_t newval,
3504     void *p_data )
3505 {
3506     demux_t *p_demux = (demux_t*)p_this;
3507     demux_sys_t *p_sys = p_demux->p_sys;
3508
3509     int i_fd = p_sys->i_fd_video;
3510
3511     if( i_fd < 0 )
3512         return VLC_EGENERIC;
3513
3514     ControlReset( p_this, i_fd );
3515
3516     return VLC_EGENERIC;
3517 }
3518
3519 static int AccessControlCallback( vlc_object_t *p_this,
3520     const char *psz_var, vlc_value_t oldval, vlc_value_t newval,
3521     void *p_data )
3522 {
3523     access_t *p_access = (access_t *)p_this;
3524     demux_sys_t *p_sys = (demux_sys_t *) p_access->p_sys;
3525     int i_cid = (int)p_data;
3526
3527     int i_fd = p_sys->i_fd_video;
3528
3529     if( i_fd < 0 )
3530         return VLC_EGENERIC;
3531
3532     Control( p_this, i_fd, psz_var, i_cid, newval.i_int );
3533
3534     return VLC_EGENERIC;
3535 }
3536
3537 static int AccessControlResetCallback( vlc_object_t *p_this,
3538     const char *psz_var, vlc_value_t oldval, vlc_value_t newval,
3539     void *p_data )
3540 {
3541     access_t *p_access = (access_t *)p_this;
3542     demux_sys_t *p_sys = (demux_sys_t *) p_access->p_sys;
3543
3544     int i_fd = p_sys->i_fd_video;
3545
3546     if( i_fd < 0 )
3547         return VLC_EGENERIC;
3548
3549     ControlReset( p_this, i_fd );
3550
3551     return VLC_EGENERIC;
3552 }