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