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