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