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