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