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