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