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