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