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