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