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