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