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