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