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