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