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