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