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