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