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