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