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