Inline V4L2 device probing into device initialization
[vlc.git] / modules / access / v4l2 / video.c
1 /*****************************************************************************
2  * v4l2.c : Video4Linux2 input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2002-2009 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Benjamin Pracht <bigben at videolan dot org>
8  *          Richard Hosking <richard at hovis dot net>
9  *          Antoine Cellerier <dionoea at videolan d.t org>
10  *          Dennis Lou <dlou99 at yahoo dot com>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*
28  * Sections based on the reference V4L2 capture example at
29  * http://v4l2spec.bytesex.org/spec/capture-example.html
30  */
31
32 /*****************************************************************************
33  * Preamble
34  *****************************************************************************/
35
36 #ifdef HAVE_CONFIG_H
37 # include "config.h"
38 #endif
39
40 #include "v4l2.h"
41 #include <vlc_plugin.h>
42 #include <vlc_access.h>
43 #include <vlc_fs.h>
44 #include <vlc_demux.h>
45
46 #include <math.h>
47 #include <assert.h>
48 #include <errno.h>
49 #include <fcntl.h>
50 #include <sys/ioctl.h>
51 #include <sys/mman.h>
52 #include <poll.h>
53
54 /*****************************************************************************
55  * Module descriptior
56  *****************************************************************************/
57
58 static int  DemuxOpen ( vlc_object_t * );
59 static void DemuxClose( vlc_object_t * );
60 static int  AccessOpen ( vlc_object_t * );
61 static void AccessClose( vlc_object_t * );
62
63 #define DEVICE_TEXT N_( "Device" )
64 #define DEVICE_LONGTEXT N_( \
65     "Video device (Default: /dev/video0)." )
66 #define STANDARD_TEXT N_( "Standard" )
67 #define STANDARD_LONGTEXT N_( \
68     "Video standard (Default, SECAM, PAL, or NTSC)." )
69 #define CHROMA_TEXT N_("Video input chroma format")
70 #define CHROMA_LONGTEXT N_( \
71     "Force the Video4Linux2 video device to use a specific chroma format " \
72     "(eg. I420 or I422 for raw images, MJPG for M-JPEG compressed input) " \
73     "(Complete list: GREY, I240, RV16, RV15, RV24, RV32, YUY2, YUYV, UYVY, " \
74     "I41N, I422, I420, I411, I410, MJPG)")
75 #define INPUT_TEXT N_( "Input" )
76 #define INPUT_LONGTEXT N_( \
77     "Input of the card to use (see debug)." )
78 #define AUDIO_INPUT_TEXT N_( "Audio input" )
79 #define AUDIO_INPUT_LONGTEXT N_( \
80     "Audio input of the card to use (see debug)." )
81 #define WIDTH_TEXT N_( "Width" )
82 #define WIDTH_LONGTEXT N_( \
83     "Force width (-1 for autodetect, 0 for driver default)." )
84 #define HEIGHT_TEXT N_( "Height" )
85 #define HEIGHT_LONGTEXT N_( \
86     "Force height (-1 for autodetect, 0 for driver default)." )
87 #define FPS_TEXT N_( "Framerate" )
88 #define FPS_LONGTEXT N_( "Framerate to capture, if applicable " \
89     "(0 for autodetect)." )
90
91 #ifdef HAVE_LIBV4L2
92 #define LIBV4L2_TEXT N_( "Use libv4l2" )
93 #define LIBV4L2_LONGTEXT N_( \
94     "Force usage of the libv4l2 wrapper." )
95 #endif
96
97 #define CTRL_RESET_TEXT N_( "Reset v4l2 controls" )
98 #define CTRL_RESET_LONGTEXT N_( \
99     "Reset controls to defaults provided by the v4l2 driver." )
100 #define BRIGHTNESS_TEXT N_( "Brightness" )
101 #define BRIGHTNESS_LONGTEXT N_( \
102     "Brightness of the video input (if supported by the v4l2 driver)." )
103 #define CONTRAST_TEXT N_( "Contrast" )
104 #define CONTRAST_LONGTEXT N_( \
105     "Contrast of the video input (if supported by the v4l2 driver)." )
106 #define SATURATION_TEXT N_( "Saturation" )
107 #define SATURATION_LONGTEXT N_( \
108     "Saturation of the video input (if supported by the v4l2 driver)." )
109 #define HUE_TEXT N_( "Hue" )
110 #define HUE_LONGTEXT N_( \
111     "Hue of the video input (if supported by the v4l2 driver)." )
112 #define BLACKLEVEL_TEXT N_( "Black level" )
113 #define BLACKLEVEL_LONGTEXT N_( \
114     "Black level of the video input (if supported by the v4l2 driver)." )
115 #define AUTOWHITEBALANCE_TEXT N_( "Auto white balance" )
116 #define AUTOWHITEBALANCE_LONGTEXT N_( \
117     "Automatically set the white balance of the video input " \
118     "(if supported by the v4l2 driver)." )
119 #define DOWHITEBALANCE_TEXT N_( "Do white balance" )
120 #define DOWHITEBALANCE_LONGTEXT N_( \
121     "Trigger a white balancing action, useless if auto white balance is " \
122     "activated (if supported by the v4l2 driver)." )
123 #define REDBALANCE_TEXT N_( "Red balance" )
124 #define REDBALANCE_LONGTEXT N_( \
125     "Red balance of the video input (if supported by the v4l2 driver)." )
126 #define BLUEBALANCE_TEXT N_( "Blue balance" )
127 #define BLUEBALANCE_LONGTEXT N_( \
128     "Blue balance of the video input (if supported by the v4l2 driver)." )
129 #define GAMMA_TEXT N_( "Gamma" )
130 #define GAMMA_LONGTEXT N_( \
131     "Gamma of the video input (if supported by the v4l2 driver)." )
132 #define EXPOSURE_TEXT N_( "Exposure" )
133 #define EXPOSURE_LONGTEXT N_( \
134     "Exposure of the video input (if supported by the v4L2 driver)." )
135 #define AUTOGAIN_TEXT N_( "Auto gain" )
136 #define AUTOGAIN_LONGTEXT N_( \
137     "Automatically set the video input's gain (if supported by the " \
138     "v4l2 driver)." )
139 #define GAIN_TEXT N_( "Gain" )
140 #define GAIN_LONGTEXT N_( \
141     "Video input's gain (if supported by the v4l2 driver)." )
142 #define HFLIP_TEXT N_( "Horizontal flip" )
143 #define HFLIP_LONGTEXT N_( \
144     "Flip the video horizontally (if supported by the v4l2 driver)." )
145 #define VFLIP_TEXT N_( "Vertical flip" )
146 #define VFLIP_LONGTEXT N_( \
147     "Flip the video vertically (if supported by the v4l2 driver)." )
148 #define HCENTER_TEXT N_( "Horizontal centering" )
149 #define HCENTER_LONGTEXT N_( \
150     "Set the camera's horizontal centering (if supported by the v4l2 driver)." )
151 #define VCENTER_TEXT N_( "Vertical centering" )
152 #define VCENTER_LONGTEXT N_( \
153     "Set the camera's vertical centering (if supported by the v4l2 driver)." )
154
155 #define AUDIO_VOLUME_TEXT N_( "Volume" )
156 #define AUDIO_VOLUME_LONGTEXT N_( \
157     "Volume of the audio input (if supported by the v4l2 driver)." )
158 #define AUDIO_BALANCE_TEXT N_( "Balance" )
159 #define AUDIO_BALANCE_LONGTEXT N_( \
160     "Balance of the audio input (if supported by the v4l2 driver)." )
161 #define AUDIO_MUTE_TEXT N_( "Mute" )
162 #define AUDIO_MUTE_LONGTEXT N_( \
163     "Mute audio input (if supported by the v4l2 driver)." )
164 #define AUDIO_BASS_TEXT N_( "Bass" )
165 #define AUDIO_BASS_LONGTEXT N_( \
166     "Bass level of the audio input (if supported by the v4l2 driver)." )
167 #define AUDIO_TREBLE_TEXT N_( "Treble" )
168 #define AUDIO_TREBLE_LONGTEXT N_( \
169     "Treble level of the audio input (if supported by the v4l2 driver)." )
170 #define AUDIO_LOUDNESS_TEXT N_( "Loudness" )
171 #define AUDIO_LOUDNESS_LONGTEXT N_( \
172     "Loudness of the audio input (if supported by the v4l2 driver)." )
173
174 #define S_CTRLS_TEXT N_("v4l2 driver controls")
175 #define S_CTRLS_LONGTEXT N_( \
176     "Set the v4l2 driver controls to the values specified using a comma " \
177     "separated list optionally encapsulated by curly braces " \
178     "(e.g.: {video_bitrate=6000000,audio_crc=0,stream_type=3} ). " \
179     "To list available controls, increase verbosity (-vvv) " \
180     "or use the v4l2-ctl application." )
181
182 #define TUNER_TEXT N_("Tuner id")
183 #define TUNER_LONGTEXT N_( \
184     "Tuner id (see debug output)." )
185 #define FREQUENCY_TEXT N_("Frequency")
186 #define FREQUENCY_LONGTEXT N_( \
187     "Tuner frequency in Hz or kHz (see debug output)" )
188 #define TUNER_AUDIO_MODE_TEXT N_("Audio mode")
189 #define TUNER_AUDIO_MODE_LONGTEXT N_( \
190     "Tuner audio mono/stereo and track selection." )
191
192 #define ASPECT_TEXT N_("Picture aspect-ratio n:m")
193 #define ASPECT_LONGTEXT N_("Define input picture aspect-ratio to use. Default is 4:3" )
194
195 static const v4l2_std_id standards_v4l2[] = { V4L2_STD_UNKNOWN, V4L2_STD_ALL,
196     V4L2_STD_PAL,     V4L2_STD_PAL_BG,   V4L2_STD_PAL_DK,
197     V4L2_STD_NTSC,
198     V4L2_STD_SECAM,   V4L2_STD_SECAM_DK,
199     V4L2_STD_525_60,  V4L2_STD_625_50,
200     V4L2_STD_ATSC,
201
202     V4L2_STD_MN,      V4L2_STD_B,        V4L2_STD_GH,       V4L2_STD_DK,
203
204     V4L2_STD_PAL_B,   V4L2_STD_PAL_B1,   V4L2_STD_PAL_G,    V4L2_STD_PAL_H,
205     V4L2_STD_PAL_I,   V4L2_STD_PAL_D,    V4L2_STD_PAL_D1,   V4L2_STD_PAL_K,
206     V4L2_STD_PAL_M,   V4L2_STD_PAL_N,    V4L2_STD_PAL_Nc,   V4L2_STD_PAL_60,
207     V4L2_STD_NTSC_M,  V4L2_STD_NTSC_M_JP,V4L2_STD_NTSC_443, V4L2_STD_NTSC_M_KR,
208     V4L2_STD_SECAM_B, V4L2_STD_SECAM_D,  V4L2_STD_SECAM_G,  V4L2_STD_SECAM_H,
209     V4L2_STD_SECAM_K, V4L2_STD_SECAM_K1, V4L2_STD_SECAM_L,  V4L2_STD_SECAM_LC,
210     V4L2_STD_ATSC_8_VSB, V4L2_STD_ATSC_16_VSB,
211 };
212 static const char *const standards_vlc[] = { "", "ALL",
213     /* Pseudo standards */
214     "PAL", "PAL_BG", "PAL_DK",
215     "NTSC",
216     "SECAM", "SECAM_DK",
217     "525_60", "625_50",
218     "ATSC",
219
220     /* Areas (PAL/NTSC or PAL/SECAM) */
221     "MN", "B", "GH", "DK",
222
223     /* Individual standards */
224     "PAL_B",          "PAL_B1",          "PAL_G",           "PAL_H",
225     "PAL_I",          "PAL_D",           "PAL_D1",          "PAL_K",
226     "PAL_M",          "PAL_N",           "PAL_Nc",          "PAL_60",
227     "NTSC_M",         "NTSC_M_JP",       "NTSC_443",        "NTSC_M_KR",
228     "SECAM_B",        "SECAM_D",         "SECAM_G",         "SECAM_H",
229     "SECAM_K",        "SECAM_K1",        "SECAM_L",         "SECAM_LC",
230     "ATSC_8_VSB",     "ATSC_16_VSB",
231 };
232 static const char *const standards_user[] = { N_("Undefined"), N_("All"),
233     "PAL",            "PAL B/G",         "PAL D/K",
234     "NTSC",
235     "SECAM",          "SECAM D/K",
236     N_("525 lines / 60 Hz"), N_("625 lines / 50 Hz"),
237     "ATSC",
238
239     "PAL/NTSC M/N",
240     "PAL/SECAM B",    "PAL/SECAM G/H",   "PAL/SECAM D/K",
241
242     "PAL B",          "PAL B1",          "PAL G",           "PAL H",
243     "PAL I",          "PAL D",           "PAL D1",          "PAL K",
244     "PAL M",          "PAL N",           N_("PAL N Argentina"), "PAL 60",
245     "NTSC M",        N_("NTSC M Japan"), "NTSC 443",  N_("NTSC M South Korea"),
246     "SECAM B",        "SECAM D",         "SECAM G",         "SECAM H",
247     "SECAM K",        "SECAM K1",        "SECAM L",         "SECAM L/C",
248     "ATSC 8-VSB",     "ATSC 16-VSB",
249 };
250
251 static const int i_tuner_audio_modes_list[] = {
252       -1, V4L2_TUNER_MODE_MONO, V4L2_TUNER_MODE_STEREO,
253       V4L2_TUNER_MODE_LANG1, V4L2_TUNER_MODE_LANG2,
254       V4L2_TUNER_MODE_SAP, V4L2_TUNER_MODE_LANG1_LANG2 };
255 static const char *const psz_tuner_audio_modes_list_text[] = {
256       N_("Unspecified"),
257       N_( "Mono" ),
258       N_( "Stereo" ),
259       N_( "Primary language (Analog TV tuners only)" ),
260       N_( "Secondary language (Analog TV tuners only)" ),
261       N_( "Second audio program (Analog TV tuners only)" ),
262       N_( "Primary language left, Secondary language right" ) };
263
264 #define V4L2_DEFAULT "/dev/video0"
265
266 #ifdef HAVE_MAEMO
267 # define DEFAULT_WIDTH  640
268 # define DEFAULT_HEIGHT 492
269 #endif
270
271 #ifndef DEFAULT_WIDTH
272 # define DEFAULT_WIDTH  (-1)
273 # define DEFAULT_HEIGHT (-1)
274 #endif
275
276 vlc_module_begin ()
277     set_shortname( N_("Video4Linux2") )
278     set_description( N_("Video4Linux2 input") )
279     set_category( CAT_INPUT )
280     set_subcategory( SUBCAT_INPUT_ACCESS )
281
282     set_section( N_( "Video input" ), NULL )
283     add_string( CFG_PREFIX "dev", "/dev/video0", DEVICE_TEXT, DEVICE_LONGTEXT,
284                  false )
285         change_safe()
286     add_string( CFG_PREFIX "standard", "",
287                 STANDARD_TEXT, STANDARD_LONGTEXT, false )
288         change_string_list( standards_vlc, standards_user, NULL )
289         change_safe()
290     add_string( CFG_PREFIX "chroma", NULL, CHROMA_TEXT, CHROMA_LONGTEXT,
291                 true )
292         change_safe()
293     add_integer( CFG_PREFIX "input", 0, INPUT_TEXT, INPUT_LONGTEXT,
294                 true )
295         change_integer_range( 0, 0xFFFFFFFE )
296         change_safe()
297     add_integer( CFG_PREFIX "audio-input", -1, AUDIO_INPUT_TEXT,
298                  AUDIO_INPUT_LONGTEXT, true )
299         change_integer_range( -1, 0xFFFFFFFE )
300         change_safe()
301     add_obsolete_integer( CFG_PREFIX "io" ) /* since 1.2.0 */
302     add_integer( CFG_PREFIX "width", DEFAULT_WIDTH, WIDTH_TEXT,
303                 WIDTH_LONGTEXT, true )
304         change_safe()
305     add_integer( CFG_PREFIX "height", DEFAULT_HEIGHT, HEIGHT_TEXT,
306                 HEIGHT_LONGTEXT, true )
307         change_safe()
308     add_string( CFG_PREFIX "aspect-ratio", "4:3", ASPECT_TEXT,
309               ASPECT_LONGTEXT, true )
310         change_safe()
311     add_float( CFG_PREFIX "fps", 0, FPS_TEXT, FPS_LONGTEXT, true )
312         change_safe()
313 #ifdef HAVE_LIBV4L2
314     add_bool( CFG_PREFIX "use-libv4l2", false, LIBV4L2_TEXT, LIBV4L2_LONGTEXT, true );
315 #endif
316
317     set_section( N_( "Tuner" ), NULL )
318     add_integer( CFG_PREFIX "tuner", 0, TUNER_TEXT, TUNER_LONGTEXT,
319                  true )
320         change_integer_range( 0, 0xFFFFFFFE )
321         change_safe()
322     add_integer( CFG_PREFIX "tuner-frequency", -1, FREQUENCY_TEXT,
323                  FREQUENCY_LONGTEXT, true )
324         change_integer_range( -1, 0xFFFFFFFE )
325         change_safe()
326     add_integer( CFG_PREFIX "tuner-audio-mode", -1, TUNER_AUDIO_MODE_TEXT,
327                  TUNER_AUDIO_MODE_LONGTEXT, true )
328         change_integer_list( i_tuner_audio_modes_list,
329                              psz_tuner_audio_modes_list_text )
330         change_safe()
331
332     set_section( N_( "Controls" ),
333                  N_( "v4l2 driver controls, if supported by your v4l2 driver." ) )
334     add_bool( CFG_PREFIX "controls-reset", false, CTRL_RESET_TEXT,
335               CTRL_RESET_LONGTEXT, true )
336         change_safe()
337     add_integer( CFG_PREFIX "brightness", -1, BRIGHTNESS_TEXT,
338                  BRIGHTNESS_LONGTEXT, true )
339     add_integer( CFG_PREFIX "contrast", -1, CONTRAST_TEXT,
340                  CONTRAST_LONGTEXT, true )
341     add_integer( CFG_PREFIX "saturation", -1, SATURATION_TEXT,
342                  SATURATION_LONGTEXT, true )
343     add_integer( CFG_PREFIX "hue", -1, HUE_TEXT,
344                  HUE_LONGTEXT, true )
345     add_integer( CFG_PREFIX "black-level", -1, BLACKLEVEL_TEXT,
346                  BLACKLEVEL_LONGTEXT, true )
347     add_integer( CFG_PREFIX "auto-white-balance", -1,
348                  AUTOWHITEBALANCE_TEXT, AUTOWHITEBALANCE_LONGTEXT, true )
349     add_integer( CFG_PREFIX "do-white-balance", -1, DOWHITEBALANCE_TEXT,
350                  DOWHITEBALANCE_LONGTEXT, true )
351     add_integer( CFG_PREFIX "red-balance", -1, REDBALANCE_TEXT,
352                  REDBALANCE_LONGTEXT, true )
353     add_integer( CFG_PREFIX "blue-balance", -1, BLUEBALANCE_TEXT,
354                  BLUEBALANCE_LONGTEXT, true )
355     add_integer( CFG_PREFIX "gamma", -1, GAMMA_TEXT,
356                  GAMMA_LONGTEXT, true )
357     add_integer( CFG_PREFIX "exposure", -1, EXPOSURE_TEXT,
358                  EXPOSURE_LONGTEXT, true )
359     add_integer( CFG_PREFIX "autogain", -1, AUTOGAIN_TEXT,
360                  AUTOGAIN_LONGTEXT, true )
361     add_integer( CFG_PREFIX "gain", -1, GAIN_TEXT,
362                  GAIN_LONGTEXT, true )
363     add_integer( CFG_PREFIX "hflip", -1, HFLIP_TEXT,
364                  HFLIP_LONGTEXT, true )
365     add_integer( CFG_PREFIX "vflip", -1, VFLIP_TEXT,
366                  VFLIP_LONGTEXT, true )
367     add_integer( CFG_PREFIX "hcenter", -1, HCENTER_TEXT,
368                  HCENTER_LONGTEXT, true )
369     add_integer( CFG_PREFIX "vcenter", -1, VCENTER_TEXT,
370                  VCENTER_LONGTEXT, true )
371     add_integer( CFG_PREFIX "audio-volume", -1, AUDIO_VOLUME_TEXT,
372                 AUDIO_VOLUME_LONGTEXT, true )
373     add_integer( CFG_PREFIX "audio-balance", -1, AUDIO_BALANCE_TEXT,
374                 AUDIO_BALANCE_LONGTEXT, true )
375     add_bool( CFG_PREFIX "audio-mute", false, AUDIO_MUTE_TEXT,
376               AUDIO_MUTE_LONGTEXT, true )
377     add_integer( CFG_PREFIX "audio-bass", -1, AUDIO_BASS_TEXT,
378                 AUDIO_BASS_LONGTEXT, true )
379     add_integer( CFG_PREFIX "audio-treble", -1, AUDIO_TREBLE_TEXT,
380                 AUDIO_TREBLE_LONGTEXT, true )
381     add_integer( CFG_PREFIX "audio-loudness", -1, AUDIO_LOUDNESS_TEXT,
382                 AUDIO_LOUDNESS_LONGTEXT, true )
383     add_string( CFG_PREFIX "set-ctrls", NULL, S_CTRLS_TEXT,
384               S_CTRLS_LONGTEXT, true )
385         change_safe()
386
387     add_obsolete_string( CFG_PREFIX "adev" )
388     add_obsolete_integer( CFG_PREFIX "audio-method" )
389     add_obsolete_bool( CFG_PREFIX "stereo" )
390     add_obsolete_integer( CFG_PREFIX "samplerate" )
391
392     add_shortcut( "v4l2" )
393     set_capability( "access_demux", 0 )
394     set_callbacks( DemuxOpen, DemuxClose )
395
396     add_submodule ()
397     add_shortcut( "v4l2", "v4l2c" )
398     set_description( N_("Video4Linux2 Compressed A/V") )
399     set_capability( "access", 0 )
400     /* use these when open as access_demux fails; VLC will use another demux */
401     set_callbacks( AccessOpen, AccessClose )
402
403 vlc_module_end ()
404
405 /*****************************************************************************
406  * Access: local prototypes
407  *****************************************************************************/
408
409 static void CommonClose( vlc_object_t *, demux_sys_t * );
410 static char *ParseMRL( vlc_object_t *, const char * );
411 static void GetV4L2Params( demux_sys_t *, vlc_object_t * );
412
413 static int DemuxControl( demux_t *, int, va_list );
414 static int AccessControl( access_t *, int, va_list );
415
416 static int Demux( demux_t * );
417 static block_t *AccessRead( access_t * );
418 static ssize_t AccessReadStream( access_t * p_access, uint8_t * p_buffer, size_t i_len );
419
420 static block_t* GrabVideo( vlc_object_t *p_demux, demux_sys_t *p_sys );
421 static block_t* ProcessVideoFrame( vlc_object_t *p_demux, uint8_t *p_frame, size_t );
422
423 static bool IsPixelFormatSupported( demux_t *p_demux,
424                                           unsigned int i_pixelformat );
425
426 static int OpenVideoDev( vlc_object_t *, const char *path, demux_sys_t *, bool );
427
428 static const struct
429 {
430     unsigned int i_v4l2;
431     vlc_fourcc_t i_fourcc;
432     int i_rmask;
433     int i_gmask;
434     int i_bmask;
435 } v4l2chroma_to_fourcc[] =
436 {
437     /* Raw data types */
438     { V4L2_PIX_FMT_GREY,    VLC_CODEC_GREY, 0, 0, 0 },
439     { V4L2_PIX_FMT_HI240,   VLC_FOURCC('I','2','4','0'), 0, 0, 0 },
440     { V4L2_PIX_FMT_RGB555,  VLC_CODEC_RGB15, 0x001f,0x03e0,0x7c00 },
441     { V4L2_PIX_FMT_RGB565,  VLC_CODEC_RGB16, 0x001f,0x07e0,0xf800 },
442     /* Won't work since we don't know how to handle such gmask values
443      * correctly
444     { V4L2_PIX_FMT_RGB555X, VLC_CODEC_RGB15, 0x007c,0xe003,0x1f00 },
445     { V4L2_PIX_FMT_RGB565X, VLC_CODEC_RGB16, 0x00f8,0xe007,0x1f00 },
446     */
447     { V4L2_PIX_FMT_BGR24,   VLC_CODEC_RGB24, 0xff0000,0xff00,0xff },
448     { V4L2_PIX_FMT_RGB24,   VLC_CODEC_RGB24, 0xff,0xff00,0xff0000 },
449     { V4L2_PIX_FMT_BGR32,   VLC_CODEC_RGB32, 0xff0000,0xff00,0xff },
450     { V4L2_PIX_FMT_RGB32,   VLC_CODEC_RGB32, 0xff,0xff00,0xff0000 },
451     { V4L2_PIX_FMT_YUYV,    VLC_CODEC_YUYV, 0, 0, 0 },
452     { V4L2_PIX_FMT_UYVY,    VLC_CODEC_UYVY, 0, 0, 0 },
453     { V4L2_PIX_FMT_Y41P,    VLC_FOURCC('I','4','1','N'), 0, 0, 0 },
454     { V4L2_PIX_FMT_YUV422P, VLC_CODEC_I422, 0, 0, 0 },
455     { V4L2_PIX_FMT_YVU420,  VLC_CODEC_YV12, 0, 0, 0 },
456     { V4L2_PIX_FMT_YUV411P, VLC_CODEC_I411, 0, 0, 0 },
457     { V4L2_PIX_FMT_YUV410,  VLC_CODEC_I410, 0, 0, 0 },
458
459     /* Raw data types, not in V4L2 spec but still in videodev2.h and supported
460      * by VLC */
461     { V4L2_PIX_FMT_YUV420,  VLC_CODEC_I420, 0, 0, 0 },
462     /* FIXME { V4L2_PIX_FMT_RGB444,  VLC_CODEC_RGB32 }, */
463
464     /* Compressed data types */
465     { V4L2_PIX_FMT_MJPEG,   VLC_CODEC_MJPG, 0, 0, 0 },
466     { V4L2_PIX_FMT_JPEG,    VLC_CODEC_JPEG, 0, 0, 0 },
467 #if 0
468     { V4L2_PIX_FMT_DV,      VLC_FOURCC('?','?','?','?') },
469     { V4L2_PIX_FMT_MPEG,    VLC_FOURCC('?','?','?','?') },
470 #endif
471     { 0, 0, 0, 0, 0 }
472 };
473
474 /**
475  * List of V4L2 chromas were confident enough to use as fallbacks if the
476  * user hasn't provided a --v4l2-chroma value.
477  *
478  * Try YUV chromas first, then RGB little endian and MJPEG as last resort.
479  */
480 static const uint32_t p_chroma_fallbacks[] =
481 { V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_YVU420, V4L2_PIX_FMT_YUV422P,
482   V4L2_PIX_FMT_YUYV, V4L2_PIX_FMT_UYVY, V4L2_PIX_FMT_BGR24,
483   V4L2_PIX_FMT_BGR32, V4L2_PIX_FMT_MJPEG, V4L2_PIX_FMT_JPEG };
484
485 struct buffer_t
486 {
487     void *  start;
488     size_t  length;
489 };
490
491 /*****************************************************************************
492  * DemuxOpen: opens v4l2 device, access_demux callback
493  *****************************************************************************
494  *
495  * url: <video device>::::
496  *
497  *****************************************************************************/
498 static int DemuxOpen( vlc_object_t *p_this )
499 {
500     demux_t     *p_demux = (demux_t*)p_this;
501     demux_sys_t *p_sys;
502
503     /* Set up p_demux */
504     p_demux->pf_control = DemuxControl;
505     p_demux->pf_demux = Demux;
506     p_demux->info.i_update = 0;
507     p_demux->info.i_title = 0;
508     p_demux->info.i_seekpoint = 0;
509
510     p_demux->p_sys = p_sys = calloc( 1, sizeof( demux_sys_t ) );
511     if( p_sys == NULL ) return VLC_ENOMEM;
512
513     char *path = ParseMRL( p_this, p_demux->psz_location );
514     if( path == NULL )
515         path = var_CreateGetNonEmptyString( p_this, CFG_PREFIX"dev" );
516     GetV4L2Params( p_sys, p_this );
517
518 #ifdef HAVE_LIBV4L2
519     p_sys->i_fd = -1;
520     if( !var_InheritBool( p_this, CFG_PREFIX "use-libv4l2" ) )
521     {
522         p_sys->b_libv4l2 = false;
523 #endif
524         msg_Dbg( p_this, "Trying direct kernel v4l2" );
525         p_sys->i_fd = OpenVideoDev( p_this, path, p_sys, true );
526 #ifdef HAVE_LIBV4L2
527     }
528
529     if( p_sys->i_fd == -1 )
530     {
531         p_sys->b_libv4l2 = true;
532         msg_Dbg( p_this, "Trying libv4l2 wrapper" );
533         p_sys->i_fd = OpenVideoDev( p_this, path, p_sys, true );
534     }
535 #endif
536     free( path );
537     if( p_sys->i_fd == -1 )
538     {
539         free( p_sys->p_codecs );
540         free( p_sys );
541         return VLC_EGENERIC;
542     }
543     return VLC_SUCCESS;
544 }
545
546 /*****************************************************************************
547  * GetV4L2Params: fill in p_sys parameters (shared by DemuxOpen and AccessOpen)
548  *****************************************************************************/
549 static void GetV4L2Params( demux_sys_t *p_sys, vlc_object_t *p_obj )
550 {
551     p_sys->i_selected_input = var_CreateGetInteger( p_obj, "v4l2-input" );
552     p_sys->i_audio_input = var_CreateGetInteger( p_obj, "v4l2-audio-input" );
553
554     p_sys->i_width = var_CreateGetInteger( p_obj, "v4l2-width" );
555     p_sys->i_height = var_CreateGetInteger( p_obj, "v4l2-height" );
556
557     p_sys->i_tuner = var_CreateGetInteger( p_obj, "v4l2-tuner" );
558     p_sys->i_tuner_type = V4L2_TUNER_RADIO; /* non-trap default value */
559     p_sys->i_tuner_audio_mode = var_CreateGetInteger( p_obj, "v4l2-tuner-audio-mode" );
560
561     char *psz_aspect = var_CreateGetString( p_obj, "v4l2-aspect-ratio" );
562     char *psz_delim = !EMPTY_STR(psz_aspect) ? strchr( psz_aspect, ':' ) : NULL;
563     if( psz_delim )
564     {
565         p_sys->i_aspect = atoi( psz_aspect ) * VOUT_ASPECT_FACTOR / atoi( psz_delim + 1 );
566     }
567     else
568     {
569         p_sys->i_aspect = 4 * VOUT_ASPECT_FACTOR / 3 ;
570
571     }
572     free( psz_aspect );
573
574     p_sys->i_fd = -1;
575
576     p_sys->p_es = NULL;
577 }
578
579 /**
580  * Parses a V4L2 MRL.
581  * \return device node path (use free()) or NULL if not specified
582  */
583 static char *ParseMRL( vlc_object_t *obj, const char *mrl )
584 {
585     const char *p = strchr( mrl, ':' );
586
587     if( p != NULL )
588     {
589         var_LocationParse( obj, p + 1, CFG_PREFIX );
590         if( p > mrl )
591             return strndup( mrl, p - mrl );
592     }
593     else
594     {
595         if( mrl[0] )
596             return strdup( mrl );
597     }
598     return NULL;
599 }
600
601 /*****************************************************************************
602  * Close: close device, free resources
603  *****************************************************************************/
604 static void AccessClose( vlc_object_t *p_this )
605 {
606     access_t    *p_access = (access_t *)p_this;
607     demux_sys_t *p_sys   = (demux_sys_t *) p_access->p_sys;
608
609     CommonClose( p_this, p_sys );
610 }
611
612 static void DemuxClose( vlc_object_t *p_this )
613 {
614     struct v4l2_buffer buf;
615     enum v4l2_buf_type buf_type;
616     unsigned int i;
617
618     demux_t     *p_demux = (demux_t *)p_this;
619     demux_sys_t *p_sys   = p_demux->p_sys;
620
621     /* Stop video capture */
622     if( p_sys->i_fd >= 0 )
623     {
624         switch( p_sys->io )
625         {
626         case IO_METHOD_READ:
627             /* Nothing to do */
628             break;
629
630         case IO_METHOD_MMAP:
631         case IO_METHOD_USERPTR:
632             /* Some drivers 'hang' internally if this is not done before streamoff */
633             for( unsigned int i = 0; i < p_sys->i_nbuffers; i++ )
634             {
635                 memset( &buf, 0, sizeof(buf) );
636                 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
637                 buf.memory = ( p_sys->io == IO_METHOD_USERPTR ) ?
638                     V4L2_MEMORY_USERPTR : V4L2_MEMORY_MMAP;
639                 v4l2_ioctl( p_sys->i_fd, VIDIOC_DQBUF, &buf ); /* ignore result */
640             }
641
642             buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
643             if( v4l2_ioctl( p_sys->i_fd, VIDIOC_STREAMOFF, &buf_type ) < 0 ) {
644                 msg_Err( p_this, "VIDIOC_STREAMOFF failed" );
645             }
646
647             break;
648         }
649     }
650
651     /* Free Video Buffers */
652     if( p_sys->p_buffers ) {
653         switch( p_sys->io )
654         {
655         case IO_METHOD_READ:
656             free( p_sys->p_buffers[0].start );
657             break;
658
659         case IO_METHOD_MMAP:
660             for( i = 0; i < p_sys->i_nbuffers; ++i )
661             {
662                 if( v4l2_munmap( p_sys->p_buffers[i].start, p_sys->p_buffers[i].length ) )
663                 {
664                     msg_Err( p_this, "munmap failed" );
665                 }
666             }
667             break;
668
669         case IO_METHOD_USERPTR:
670             for( i = 0; i < p_sys->i_nbuffers; ++i )
671             {
672                free( p_sys->p_buffers[i].start );
673             }
674             break;
675         }
676         free( p_sys->p_buffers );
677     }
678
679     CommonClose( p_this, p_sys );
680 }
681
682 static void CommonClose( vlc_object_t *p_this, demux_sys_t *p_sys )
683 {
684     (void)p_this;
685     /* Close */
686     if( p_sys->i_fd >= 0 ) v4l2_close( p_sys->i_fd );
687     free( p_sys->p_codecs );
688     free( p_sys );
689 }
690
691 /*****************************************************************************
692  * AccessOpen: opens v4l2 device, access callback
693  *****************************************************************************
694  *
695  * url: <video device>::::
696  *
697  *****************************************************************************/
698 static int AccessOpen( vlc_object_t * p_this )
699 {
700     access_t *p_access = (access_t*) p_this;
701     demux_sys_t * p_sys;
702
703     /* Only when selected */
704     if( *p_access->psz_access == '\0' ) return VLC_EGENERIC;
705
706     access_InitFields( p_access );
707     p_sys = calloc( 1, sizeof( demux_sys_t ));
708     if( !p_sys ) return VLC_ENOMEM;
709     p_access->p_sys = (access_sys_t*)p_sys;
710
711     char *path = ParseMRL( p_this, p_access->psz_location );
712     if( path == NULL )
713         path = var_InheritString( p_this, CFG_PREFIX"dev" );
714     GetV4L2Params( p_sys, p_this );
715
716 #ifdef HAVE_LIBV4L2
717     p_sys->i_fd = -1;
718     if( !var_InheritBool( p_this, CFG_PREFIX "use-libv4l2" ) )
719     {
720         p_sys->b_libv4l2 = false;
721 #endif
722         msg_Dbg( p_this, "Trying direct kernel v4l2" );
723         p_sys->i_fd = OpenVideoDev( p_this, path, p_sys, false );
724 #ifdef HAVE_LIBV4L2
725     }
726     if( p_sys->i_fd == -1 )
727     {
728         p_sys->b_libv4l2 = true;
729         msg_Dbg( p_this, "Trying libv4l2 wrapper" );
730         p_sys->i_fd = OpenVideoDev( p_this, path, p_sys, false );
731     }
732 #endif
733     free( path );
734     if( p_sys->i_fd == -1 )
735     {
736         free( p_sys->p_codecs );
737         free( p_sys );
738         return VLC_EGENERIC;
739     }
740
741     if( p_sys->io == IO_METHOD_READ )
742         ACCESS_SET_CALLBACKS( AccessReadStream, NULL, AccessControl, NULL );
743     else
744         ACCESS_SET_CALLBACKS( NULL, AccessRead, AccessControl, NULL );
745     return VLC_SUCCESS;
746 }
747
748 /*****************************************************************************
749  * DemuxControl:
750  *****************************************************************************/
751 static int DemuxControl( demux_t *p_demux, int i_query, va_list args )
752 {
753     switch( i_query )
754     {
755         /* Special for access_demux */
756         case DEMUX_CAN_PAUSE:
757         case DEMUX_CAN_SEEK:
758         case DEMUX_CAN_CONTROL_PACE:
759             *va_arg( args, bool * ) = false;
760             return VLC_SUCCESS;
761
762         case DEMUX_GET_PTS_DELAY:
763             *va_arg(args,int64_t *) = INT64_C(1000)
764                 * var_InheritInteger( p_demux, "live-caching" );
765             return VLC_SUCCESS;
766
767         case DEMUX_GET_TIME:
768             *va_arg( args, int64_t * ) = mdate();
769             return VLC_SUCCESS;
770
771         /* TODO implement others */
772         default:
773             return VLC_EGENERIC;
774     }
775
776     return VLC_EGENERIC;
777 }
778
779 /*****************************************************************************
780  * AccessControl: access callback
781  *****************************************************************************/
782 static int AccessControl( access_t *p_access, int i_query, va_list args )
783 {
784     switch( i_query )
785     {
786         /* */
787         case ACCESS_CAN_SEEK:
788         case ACCESS_CAN_FASTSEEK:
789         case ACCESS_CAN_PAUSE:
790         case ACCESS_CAN_CONTROL_PACE:
791             *va_arg( args, bool* ) = false;
792             break;
793
794         /* */
795         case ACCESS_GET_PTS_DELAY:
796             *va_arg(args,int64_t *) = INT64_C(1000)
797                 * var_InheritInteger( p_access, "live-caching" );
798             break;
799
800         /* */
801         case ACCESS_SET_PAUSE_STATE:
802             /* Nothing to do */
803             break;
804
805         case ACCESS_GET_TITLE_INFO:
806         case ACCESS_SET_TITLE:
807         case ACCESS_SET_SEEKPOINT:
808         case ACCESS_SET_PRIVATE_ID_STATE:
809         case ACCESS_GET_CONTENT_TYPE:
810         case ACCESS_GET_META:
811             return VLC_EGENERIC;
812
813         default:
814             msg_Warn( p_access, "Unimplemented query in control(%d).", i_query);
815             return VLC_EGENERIC;
816
817     }
818     return VLC_SUCCESS;
819 }
820
821 /*****************************************************************************
822  * AccessRead: access callback
823  ******************************************************************************/
824 static block_t *AccessRead( access_t * p_access )
825 {
826     demux_sys_t *p_sys = (demux_sys_t *)p_access->p_sys;
827
828     struct pollfd fd;
829     fd.fd = p_sys->i_fd;
830     fd.events = POLLIN|POLLPRI;
831     fd.revents = 0;
832
833     /* Wait for data */
834     if( poll( &fd, 1, 500 ) > 0 ) /* Timeout after 0.5 seconds since I don't know if pf_demux can be blocking. */
835         return GrabVideo( VLC_OBJECT(p_access), p_sys );
836
837     return NULL;
838 }
839
840 static ssize_t AccessReadStream( access_t * p_access, uint8_t * p_buffer, size_t i_len )
841 {
842     demux_sys_t *p_sys = (demux_sys_t *) p_access->p_sys;
843     struct pollfd ufd;
844     int i_ret;
845
846     ufd.fd = p_sys->i_fd;
847     ufd.events = POLLIN;
848
849     if( p_access->info.b_eof )
850         return 0;
851
852     do
853     {
854         if( !vlc_object_alive (p_access) )
855             return 0;
856
857         ufd.revents = 0;
858     }
859     while( ( i_ret = poll( &ufd, 1, 500 ) ) == 0 );
860
861     if( i_ret < 0 )
862     {
863         if( errno != EINTR )
864             msg_Err( p_access, "poll error" );
865         return -1;
866     }
867
868     i_ret = v4l2_read( p_sys->i_fd, p_buffer, i_len );
869     if( i_ret == 0 )
870     {
871         p_access->info.b_eof = true;
872     }
873     else if( i_ret > 0 )
874     {
875         p_access->info.i_pos += i_ret;
876     }
877
878     return i_ret;
879 }
880
881 /*****************************************************************************
882  * Demux: Processes the audio or video frame
883  *****************************************************************************/
884 static int Demux( demux_t *p_demux )
885 {
886     demux_sys_t *p_sys = p_demux->p_sys;
887
888     struct pollfd fd;
889     fd.fd = p_sys->i_fd;
890     fd.events = POLLIN|POLLPRI;
891     fd.revents = 0;
892
893     /* Wait for data */
894     /* Timeout after 0.5 seconds since I don't know if pf_demux can be blocking. */
895     while( poll( &fd, 1, 500 ) == -1 )
896         if( errno != EINTR )
897         {
898             msg_Err( p_demux, "poll error: %m" );
899             return -1;
900         }
901
902     if( fd.revents )
903     {
904          block_t *p_block = GrabVideo( VLC_OBJECT(p_demux), p_sys );
905          if( p_block )
906          {
907              es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_block->i_pts );
908              es_out_Send( p_demux->out, p_sys->p_es, p_block );
909         }
910     }
911
912     return 1;
913 }
914
915 /*****************************************************************************
916  * GrabVideo: Grab a video frame
917  *****************************************************************************/
918 static block_t* GrabVideo( vlc_object_t *p_demux, demux_sys_t *p_sys )
919 {
920     block_t *p_block;
921     struct v4l2_buffer buf;
922     ssize_t i_ret;
923
924     /* Grab Video Frame */
925     switch( p_sys->io )
926     {
927     case IO_METHOD_READ:
928         i_ret = v4l2_read( p_sys->i_fd, p_sys->p_buffers[0].start, p_sys->p_buffers[0].length );
929         if( i_ret == -1 )
930         {
931             switch( errno )
932             {
933             case EAGAIN:
934                 return NULL;
935             case EIO:
936                 /* Could ignore EIO, see spec. */
937                 /* fall through */
938             default:
939                 msg_Err( p_demux, "Failed to read frame" );
940                 return 0;
941                }
942         }
943
944         p_block = ProcessVideoFrame( p_demux, (uint8_t*)p_sys->p_buffers[0].start, i_ret );
945         if( !p_block )
946             return NULL;
947
948         break;
949
950     case IO_METHOD_MMAP:
951         memset( &buf, 0, sizeof(buf) );
952         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
953         buf.memory = V4L2_MEMORY_MMAP;
954
955         /* Wait for next frame */
956         if (v4l2_ioctl( p_sys->i_fd, VIDIOC_DQBUF, &buf ) < 0 )
957         {
958             switch( errno )
959             {
960             case EAGAIN:
961                 return NULL;
962             case EIO:
963                 /* Could ignore EIO, see spec. */
964                 /* fall through */
965             default:
966                 msg_Err( p_demux, "Failed to wait (VIDIOC_DQBUF)" );
967                 return NULL;
968                }
969         }
970
971         if( buf.index >= p_sys->i_nbuffers ) {
972             msg_Err( p_demux, "Failed capturing new frame as i>=nbuffers" );
973             return NULL;
974         }
975
976         p_block = ProcessVideoFrame( p_demux, p_sys->p_buffers[buf.index].start, buf.bytesused );
977         if( !p_block )
978             return NULL;
979
980         /* Unlock */
981         if( v4l2_ioctl( p_sys->i_fd, VIDIOC_QBUF, &buf ) < 0 )
982         {
983             msg_Err( p_demux, "Failed to unlock (VIDIOC_QBUF)" );
984             block_Release( p_block );
985             return NULL;
986         }
987
988         break;
989
990     case IO_METHOD_USERPTR:
991         memset( &buf, 0, sizeof(buf) );
992         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
993         buf.memory = V4L2_MEMORY_USERPTR;
994
995         /* Wait for next frame */
996         if (v4l2_ioctl( p_sys->i_fd, VIDIOC_DQBUF, &buf ) < 0 )
997         {
998             switch( errno )
999             {
1000             case EAGAIN:
1001                 return NULL;
1002             case EIO:
1003                 /* Could ignore EIO, see spec. */
1004                 /* fall through */
1005             default:
1006                 msg_Err( p_demux, "Failed to wait (VIDIOC_DQBUF)" );
1007                 return NULL;
1008             }
1009         }
1010
1011         /* Find frame? */
1012         unsigned int i;
1013         for( i = 0; i < p_sys->i_nbuffers; i++ )
1014         {
1015             if( buf.m.userptr == (unsigned long)p_sys->p_buffers[i].start &&
1016                 buf.length == p_sys->p_buffers[i].length ) break;
1017         }
1018
1019         if( i >= p_sys->i_nbuffers )
1020         {
1021             msg_Err( p_demux, "Failed capturing new frame as i>=nbuffers" );
1022             return NULL;
1023         }
1024
1025         p_block = ProcessVideoFrame( p_demux, (uint8_t*)buf.m.userptr, buf.bytesused );
1026         if( !p_block )
1027             return NULL;
1028
1029         /* Unlock */
1030         if( v4l2_ioctl( p_sys->i_fd, VIDIOC_QBUF, &buf ) < 0 )
1031         {
1032             msg_Err( p_demux, "Failed to unlock (VIDIOC_QBUF)" );
1033             block_Release( p_block );
1034             return NULL;
1035         }
1036
1037         break;
1038     }
1039
1040     /* Timestamp */
1041     p_block->i_pts = p_block->i_dts = mdate();
1042     p_block->i_flags |= p_sys->i_block_flags;
1043
1044     return p_block;
1045 }
1046
1047 /*****************************************************************************
1048  * ProcessVideoFrame: Helper function to take a buffer and copy it into
1049  * a new block
1050  *****************************************************************************/
1051 static block_t* ProcessVideoFrame( vlc_object_t *p_demux, uint8_t *p_frame, size_t i_size )
1052 {
1053     block_t *p_block;
1054
1055     if( !p_frame ) return NULL;
1056
1057     /* New block */
1058     if( !( p_block = block_New( p_demux, i_size ) ) )
1059     {
1060         msg_Warn( p_demux, "Cannot get new block" );
1061         return NULL;
1062     }
1063
1064     /* Copy frame */
1065     memcpy( p_block->p_buffer, p_frame, i_size );
1066
1067     return p_block;
1068 }
1069
1070 /*****************************************************************************
1071  * Helper function to initalise video IO using the Read method
1072  *****************************************************************************/
1073 static int InitRead( vlc_object_t *p_demux, demux_sys_t *p_sys, unsigned int i_buffer_size )
1074 {
1075     (void)p_demux;
1076
1077     p_sys->p_buffers = calloc( 1, sizeof( *p_sys->p_buffers ) );
1078     if( unlikely(p_sys->p_buffers == NULL) )
1079         return -1;
1080
1081     p_sys->p_buffers[0].length = i_buffer_size;
1082     p_sys->p_buffers[0].start = malloc( i_buffer_size );
1083     if( !p_sys->p_buffers[0].start )
1084         return -1;
1085
1086     return 0;
1087 }
1088
1089 /*****************************************************************************
1090  * Helper function to initalise video IO using the mmap method
1091  *****************************************************************************/
1092 static int InitMmap( vlc_object_t *p_demux, demux_sys_t *p_sys, int i_fd )
1093 {
1094     struct v4l2_requestbuffers req;
1095
1096     memset( &req, 0, sizeof(req) );
1097     req.count = 4;
1098     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1099     req.memory = V4L2_MEMORY_MMAP;
1100
1101     if( v4l2_ioctl( i_fd, VIDIOC_REQBUFS, &req ) < 0 )
1102     {
1103         msg_Err( p_demux, "device does not support mmap I/O" );
1104         return -1;
1105     }
1106
1107     if( req.count < 2 )
1108     {
1109         msg_Err( p_demux, "insufficient buffers" );
1110         return -1;
1111     }
1112
1113     p_sys->p_buffers = calloc( req.count, sizeof( *p_sys->p_buffers ) );
1114     if( unlikely(!p_sys->p_buffers) )
1115         return -1;
1116
1117     for( p_sys->i_nbuffers = 0; p_sys->i_nbuffers < req.count; ++p_sys->i_nbuffers )
1118     {
1119         struct v4l2_buffer buf;
1120
1121         memset( &buf, 0, sizeof(buf) );
1122         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1123         buf.memory = V4L2_MEMORY_MMAP;
1124         buf.index = p_sys->i_nbuffers;
1125
1126         if( v4l2_ioctl( i_fd, VIDIOC_QUERYBUF, &buf ) < 0 )
1127         {
1128             msg_Err( p_demux, "VIDIOC_QUERYBUF: %m" );
1129             return -1;
1130         }
1131
1132         p_sys->p_buffers[p_sys->i_nbuffers].length = buf.length;
1133         p_sys->p_buffers[p_sys->i_nbuffers].start =
1134             v4l2_mmap( NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, i_fd, buf.m.offset );
1135
1136         if( p_sys->p_buffers[p_sys->i_nbuffers].start == MAP_FAILED )
1137         {
1138             msg_Err( p_demux, "mmap failed: %m" );
1139             return -1;
1140         }
1141     }
1142
1143     return 0;
1144 }
1145
1146 /*****************************************************************************
1147  * Helper function to initalise video IO using the userbuf method
1148  *****************************************************************************/
1149 static int InitUserP( vlc_object_t *p_demux, demux_sys_t *p_sys, int i_fd, unsigned int i_buffer_size )
1150 {
1151     struct v4l2_requestbuffers req;
1152     unsigned int i_page_size;
1153
1154     i_page_size = sysconf(_SC_PAGESIZE);
1155     i_buffer_size = ( i_buffer_size + i_page_size - 1 ) & ~( i_page_size - 1);
1156
1157     memset( &req, 0, sizeof(req) );
1158     req.count = 4;
1159     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1160     req.memory = V4L2_MEMORY_USERPTR;
1161
1162     if( v4l2_ioctl( i_fd, VIDIOC_REQBUFS, &req ) < 0 )
1163     {
1164         msg_Err( p_demux, "device does not support user pointer i/o" );
1165         return -1;
1166     }
1167
1168     p_sys->p_buffers = calloc( 4, sizeof( *p_sys->p_buffers ) );
1169     if( !p_sys->p_buffers )
1170         return -1;
1171
1172     for( p_sys->i_nbuffers = 0; p_sys->i_nbuffers < 4; ++p_sys->i_nbuffers )
1173     {
1174         p_sys->p_buffers[p_sys->i_nbuffers].length = i_buffer_size;
1175         if( posix_memalign( &p_sys->p_buffers[p_sys->i_nbuffers].start,
1176                 /* boundary */ i_page_size, i_buffer_size ) )
1177             return -1;
1178     }
1179
1180     return 0;
1181 }
1182
1183 /*****************************************************************************
1184  * IsPixelFormatSupported: returns true if the specified V4L2 pixel format is
1185  * in the array of supported formats returned by the driver
1186  *****************************************************************************/
1187 static bool IsPixelFormatSupported( demux_t *p_demux, unsigned int i_pixelformat )
1188 {
1189     demux_sys_t *p_sys = p_demux->p_sys;
1190
1191     for( unsigned i_index = 0; i_index < p_sys->i_codec; i_index++ )
1192     {
1193         if( p_sys->p_codecs[i_index].pixelformat == i_pixelformat )
1194             return true;
1195     }
1196
1197     return false;
1198 }
1199
1200 static float GetMaxFrameRate( int i_fd, uint32_t i_pixel_format,
1201                               uint32_t i_width, uint32_t i_height )
1202 {
1203 #ifdef VIDIOC_ENUM_FRAMEINTERVALS
1204     /* This is new in Linux 2.6.19 */
1205     struct v4l2_frmivalenum frmival;
1206     memset( &frmival, 0, sizeof(frmival) );
1207     frmival.pixel_format = i_pixel_format;
1208     frmival.width = i_width;
1209     frmival.height = i_height;
1210     if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival ) >= 0 )
1211     {
1212         switch( frmival.type )
1213         {
1214             case V4L2_FRMIVAL_TYPE_DISCRETE:
1215             {
1216                 float f_fps_max = -1;
1217                 do
1218                 {
1219                     float f_fps = (float)frmival.discrete.denominator
1220                                 / (float)frmival.discrete.numerator;
1221                     if( f_fps > f_fps_max ) f_fps_max = f_fps;
1222                     frmival.index++;
1223                 } while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMEINTERVALS,
1224                                      &frmival ) >= 0 );
1225                 return f_fps_max;
1226             }
1227             case V4L2_FRMSIZE_TYPE_STEPWISE:
1228             case V4L2_FRMIVAL_TYPE_CONTINUOUS:
1229                 return __MAX( (float)frmival.stepwise.max.denominator
1230                             / (float)frmival.stepwise.max.numerator,
1231                               (float)frmival.stepwise.min.denominator
1232                             / (float)frmival.stepwise.min.numerator );
1233         }
1234     }
1235 #endif
1236     return -1.;
1237 }
1238
1239 static float GetAbsoluteMaxFrameRate( demux_t *p_demux, int i_fd,
1240                                       uint32_t i_pixel_format )
1241 {
1242     float f_fps_max = -1.;
1243 #ifdef VIDIOC_ENUM_FRAMESIZES
1244     /* This is new in Linux 2.6.19 */
1245     struct v4l2_frmsizeenum frmsize;
1246     memset( &frmsize, 0, sizeof(frmsize) );
1247     frmsize.pixel_format = i_pixel_format;
1248     if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize ) >= 0 )
1249     {
1250         switch( frmsize.type )
1251         {
1252             case V4L2_FRMSIZE_TYPE_DISCRETE:
1253                 do
1254                 {
1255                     frmsize.index++;
1256                     float f_fps = GetMaxFrameRate( i_fd, i_pixel_format,
1257                                                    frmsize.discrete.width,
1258                                                    frmsize.discrete.height );
1259                     if( f_fps > f_fps_max ) f_fps_max = f_fps;
1260                 } while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES,
1261                          &frmsize ) >= 0 );
1262                 break;
1263             case V4L2_FRMSIZE_TYPE_STEPWISE:
1264             {
1265                 uint32_t i_width = frmsize.stepwise.min_width;
1266                 uint32_t i_height = frmsize.stepwise.min_height;
1267                 for( ;
1268                      i_width <= frmsize.stepwise.max_width &&
1269                      i_height <= frmsize.stepwise.max_width;
1270                      i_width += frmsize.stepwise.step_width,
1271                      i_height += frmsize.stepwise.step_height )
1272                 {
1273                     float f_fps = GetMaxFrameRate( i_fd, i_pixel_format,
1274                                                    i_width, i_height );
1275                     if( f_fps > f_fps_max ) f_fps_max = f_fps;
1276                 }
1277                 break;
1278             }
1279             case V4L2_FRMSIZE_TYPE_CONTINUOUS:
1280                 /* FIXME */
1281                 msg_Err( p_demux, "GetAbsoluteMaxFrameRate implementation for V4L2_FRMSIZE_TYPE_CONTINUOUS isn't correct" );
1282                  f_fps_max = GetMaxFrameRate( i_fd, i_pixel_format,
1283                                               frmsize.stepwise.max_width,
1284                                               frmsize.stepwise.max_height );
1285                 break;
1286         }
1287     }
1288 #endif
1289     return f_fps_max;
1290 }
1291
1292 static void GetMaxDimensions( demux_t *p_demux, int i_fd,
1293                               uint32_t i_pixel_format, float f_fps_min,
1294                               uint32_t *pi_width, uint32_t *pi_height )
1295 {
1296     *pi_width = 0;
1297     *pi_height = 0;
1298 #ifdef VIDIOC_ENUM_FRAMESIZES
1299     /* This is new in Linux 2.6.19 */
1300     struct v4l2_frmsizeenum frmsize;
1301     memset( &frmsize, 0, sizeof(frmsize) );
1302     frmsize.pixel_format = i_pixel_format;
1303     if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize ) >= 0 )
1304     {
1305         switch( frmsize.type )
1306         {
1307             case V4L2_FRMSIZE_TYPE_DISCRETE:
1308                 do
1309                 {
1310                     frmsize.index++;
1311                     float f_fps = GetMaxFrameRate( i_fd, i_pixel_format,
1312                                                    frmsize.discrete.width,
1313                                                    frmsize.discrete.height );
1314                     if( f_fps >= f_fps_min &&
1315                         frmsize.discrete.width > *pi_width )
1316                     {
1317                         *pi_width = frmsize.discrete.width;
1318                         *pi_height = frmsize.discrete.height;
1319                     }
1320                 } while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES,
1321                          &frmsize ) >= 0 );
1322                 break;
1323             case V4L2_FRMSIZE_TYPE_STEPWISE:
1324             {
1325                 uint32_t i_width = frmsize.stepwise.min_width;
1326                 uint32_t i_height = frmsize.stepwise.min_height;
1327                 for( ;
1328                      i_width <= frmsize.stepwise.max_width &&
1329                      i_height <= frmsize.stepwise.max_width;
1330                      i_width += frmsize.stepwise.step_width,
1331                      i_height += frmsize.stepwise.step_height )
1332                 {
1333                     float f_fps = GetMaxFrameRate( i_fd, i_pixel_format,
1334                                                    i_width, i_height );
1335                     if( f_fps >= f_fps_min && i_width > *pi_width )
1336                     {
1337                         *pi_width = i_width;
1338                         *pi_height = i_height;
1339                     }
1340                 }
1341                 break;
1342             }
1343             case V4L2_FRMSIZE_TYPE_CONTINUOUS:
1344                 /* FIXME */
1345                 msg_Err( p_demux, "GetMaxDimension implementation for V4L2_FRMSIZE_TYPE_CONTINUOUS isn't correct" );
1346                 float f_fps = GetMaxFrameRate( i_fd, i_pixel_format,
1347                                                frmsize.stepwise.max_width,
1348                                                frmsize.stepwise.max_height );
1349                 if( f_fps >= f_fps_min &&
1350                     frmsize.stepwise.max_width > *pi_width )
1351                 {
1352                     *pi_width = frmsize.stepwise.max_width;
1353                     *pi_height = frmsize.stepwise.max_height;
1354                 }
1355                 break;
1356         }
1357     }
1358 #endif
1359 }
1360
1361 /**
1362  * Opens and sets up a video device
1363  * \return file descriptor or -1 on error
1364  */
1365 static int OpenVideoDev( vlc_object_t *p_obj, const char *path,
1366                          demux_sys_t *p_sys, bool b_demux )
1367 {
1368     struct v4l2_cropcap cropcap;
1369     struct v4l2_crop crop;
1370     struct v4l2_format fmt;
1371     unsigned int i_min;
1372     enum v4l2_buf_type buf_type;
1373     es_format_t es_fmt;
1374
1375     msg_Dbg( p_obj, "opening device '%s'", path );
1376
1377     int i_fd = vlc_open( path, O_RDWR );
1378     if( i_fd == -1 )
1379     {
1380         msg_Err( p_obj, "cannot open device %s: %m", path );
1381         return -1;
1382     }
1383
1384 #ifdef HAVE_LIBV4L2
1385     /* Note the v4l2_xxx functions are designed so that if they get passed an
1386        unknown fd, the will behave exactly as their regular xxx counterparts,
1387        so if v4l2_fd_open fails, we continue as normal (missing the libv4l2
1388        custom cam format to normal formats conversion). Chances are big we will
1389        still fail then though, as normally v4l2_fd_open only fails if the
1390        device is not a v4l2 device. */
1391     if( p_sys->b_libv4l2 )
1392     {
1393         int libv4l2_fd;
1394         libv4l2_fd = v4l2_fd_open( i_fd, 0 );
1395         if( libv4l2_fd != -1 )
1396             i_fd = libv4l2_fd;
1397     }
1398 #endif
1399
1400     /* Get device capabilites */
1401     struct v4l2_capability cap;
1402     if( v4l2_ioctl( i_fd, VIDIOC_QUERYCAP, &cap ) < 0 )
1403     {
1404         msg_Err( p_obj, "cannot get video capabilities: %m" );
1405         return -1;
1406     }
1407
1408     msg_Dbg( p_obj, "device %s using driver %s (version %u.%u.%u) on %s",
1409             cap.card, cap.driver, (cap.version >> 16) & 0xFF,
1410             (cap.version >> 8) & 0xFF, cap.version & 0xFF, cap.bus_info );
1411     msg_Dbg( p_obj, "the device has the capabilities: 0x%08X",
1412              cap.capabilities );
1413     msg_Dbg( p_obj, " (%c) Video Capture, (%c) Audio, (%c) Tuner, (%c) Radio",
1414              ( cap.capabilities & V4L2_CAP_VIDEO_CAPTURE  ? 'X':' '),
1415              ( cap.capabilities & V4L2_CAP_AUDIO  ? 'X':' '),
1416              ( cap.capabilities & V4L2_CAP_TUNER  ? 'X':' '),
1417              ( cap.capabilities & V4L2_CAP_RADIO  ? 'X':' ') );
1418     msg_Dbg( p_obj, " (%c) Read/Write, (%c) Streaming, (%c) Asynchronous",
1419             ( cap.capabilities & V4L2_CAP_READWRITE ? 'X':' ' ),
1420             ( cap.capabilities & V4L2_CAP_STREAMING ? 'X':' ' ),
1421             ( cap.capabilities & V4L2_CAP_ASYNCIO ? 'X':' ' ) );
1422
1423     if( cap.capabilities & V4L2_CAP_STREAMING )
1424         p_sys->io = IO_METHOD_MMAP;
1425     else if( cap.capabilities & V4L2_CAP_READWRITE )
1426         p_sys->io = IO_METHOD_READ;
1427     else
1428     {
1429         msg_Err( p_obj, "no supported I/O method" );
1430         goto error;
1431     }
1432
1433     /* Now, enumerate all the video inputs. This is useless at the moment
1434        since we have no way to present that info to the user except with
1435        debug messages */
1436     if( cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
1437     {
1438         struct v4l2_input input;
1439         input.index = 0;
1440         while( v4l2_ioctl( i_fd, VIDIOC_ENUMINPUT, &input ) >= 0 )
1441         {
1442             msg_Dbg( p_obj, "video input %u (%s) has type: %s %c",
1443                      input.index, input.name,
1444                      input.type == V4L2_INPUT_TYPE_TUNER
1445                           ? "Tuner adapter" : "External analog input",
1446                      input.index == p_sys->i_selected_input ? '*' : ' ' );
1447             input.index++;
1448         }
1449
1450         /* Select input */
1451         if( v4l2_ioctl( i_fd, VIDIOC_S_INPUT, &p_sys->i_selected_input ) < 0 )
1452         {
1453             msg_Err( p_obj, "cannot set input %u: %m",
1454                      p_sys->i_selected_input );
1455             goto error;
1456         }
1457         msg_Dbg( p_obj, "input set to %u", p_sys->i_selected_input );
1458     }
1459
1460     /* Select standard */
1461     bool bottom_first;
1462     const char *stdname = var_InheritString( p_obj, CFG_PREFIX"standard" );
1463     if( stdname != NULL )
1464     {
1465         v4l2_std_id std = strtoull( stdname, NULL, 0 );
1466         if( std == 0 )
1467         {
1468             const size_t n = sizeof(standards_vlc) / sizeof(*standards_vlc);
1469             assert( n == sizeof(standards_v4l2) / sizeof(*standards_v4l2) );
1470             assert( n == sizeof(standards_user) / sizeof(*standards_user) );
1471             for( size_t i = 0; i < n; i++ )
1472                 if( strcasecmp( stdname, standards_vlc[i] ) == 0 )
1473                 {
1474                     std = standards_v4l2[i];
1475                     break;
1476                 }
1477         }
1478
1479         if( v4l2_ioctl( i_fd, VIDIOC_S_STD, &std ) < 0
1480          || v4l2_ioctl( i_fd, VIDIOC_G_STD, &std ) < 0 )
1481         {
1482             msg_Err( p_obj, "cannot set standard 0x%"PRIx64": %m", std );
1483             goto error;
1484         }
1485         msg_Dbg( p_obj, "standard set to 0x%"PRIx64":", std );
1486         bottom_first = std == V4L2_STD_NTSC;
1487     }
1488     else
1489         bottom_first = false;
1490
1491     /* Probe audio inputs */
1492     if( cap.capabilities & V4L2_CAP_AUDIO )
1493     {
1494         struct v4l2_audio audio = { .index = 0 };
1495
1496         while( v4l2_ioctl( i_fd, VIDIOC_ENUMAUDIO, &audio ) >= 0 )
1497         {
1498             msg_Dbg( p_obj, "audio input %u (%s) is %s%s %c", audio.index,
1499                      audio.name,
1500                      audio.capability & V4L2_AUDCAP_STEREO ? "Stereo" : "Mono",
1501                      audio.capability & V4L2_AUDCAP_AVL
1502                          ? " (Automatic Volume Level supported)" : "",
1503                      p_sys->i_audio_input == audio.index );
1504             audio.index++;
1505         }
1506     }
1507
1508     /* Set audio input */
1509     if( p_sys->i_audio_input != (uint32_t)-1 )
1510     {
1511         struct v4l2_audio audio = {
1512             .index = p_sys->i_audio_input,
1513             .mode = 0, /* TODO: AVL support */
1514         };
1515
1516         if( v4l2_ioctl( i_fd, VIDIOC_S_AUDIO, &audio ) < 0 )
1517         {
1518             msg_Err( p_obj, "cannot set audio input %u: %m",
1519                      p_sys->i_audio_input );
1520             goto error;
1521         }
1522         msg_Dbg( p_obj, "audio input set to %u",
1523                  p_sys->i_audio_input );
1524     }
1525
1526     /* List tuner caps */
1527     if( cap.capabilities & V4L2_CAP_TUNER )
1528     {
1529         struct v4l2_tuner tuner;
1530
1531         tuner.index = 0;
1532         while( v4l2_ioctl( i_fd, VIDIOC_G_TUNER, &tuner ) >= 0 )
1533         {
1534             if( tuner.index == p_sys->i_tuner )
1535                 p_sys->i_tuner_type = tuner.type;
1536
1537             const char *unit =
1538                 (tuner.capability & V4L2_TUNER_CAP_LOW) ? "Hz" : "kHz";
1539             msg_Dbg( p_obj, "tuner %u (%s) has type: %s, "
1540                      "frequency range: %.1f %s -> %.1f %s", tuner.index,
1541                      tuner.name,
1542                      tuner.type == V4L2_TUNER_RADIO ? "Radio" : "Analog TV",
1543                      tuner.rangelow * 62.5, unit,
1544                      tuner.rangehigh * 62.5, unit );
1545
1546             struct v4l2_frequency frequency = { .tuner = tuner.index };
1547             if( v4l2_ioctl( i_fd, VIDIOC_G_FREQUENCY, &frequency ) < 0 )
1548             {
1549                 msg_Err( p_obj, "cannot get tuner frequency: %m" );
1550                 return -1;
1551             }
1552             msg_Dbg( p_obj, "tuner %u (%s) frequency: %.1f %s", tuner.index,
1553                      tuner.name, frequency.frequency * 62.5, unit );
1554
1555             tuner.index++;
1556         }
1557     }
1558
1559     /* Tune the tuner */
1560     uint32_t freq = var_InheritInteger( p_obj, CFG_PREFIX"tuner-frequency" );
1561     if( freq != (uint32_t)-1 )
1562     {
1563         struct v4l2_frequency frequency = {
1564             .tuner = p_sys->i_tuner,
1565             .type = p_sys->i_tuner_type,
1566             .frequency = freq / 62.5,
1567         };
1568
1569         if( v4l2_ioctl( i_fd, VIDIOC_S_FREQUENCY, &frequency ) < 0 )
1570         {
1571             msg_Err( p_obj, "cannot set tuner frequency: %m" );
1572             goto error;
1573         }
1574         msg_Dbg( p_obj, "tuner frequency set" );
1575     }
1576
1577     /* Set the tuner's audio mode */
1578     if( p_sys->i_tuner_audio_mode >= 0 )
1579     {
1580         struct v4l2_tuner tuner = {
1581             .index = p_sys->i_tuner,
1582             .audmode = p_sys->i_tuner_audio_mode,
1583         };
1584
1585         if( v4l2_ioctl( i_fd, VIDIOC_S_TUNER, &tuner ) < 0 )
1586         {
1587             msg_Err( p_obj, "cannot set tuner audio mode: %m" );
1588             goto error;
1589         }
1590         msg_Dbg( p_obj, "tuner audio mode set" );
1591     }
1592
1593     /* Probe for available chromas */
1594     if( cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
1595     {
1596         struct v4l2_fmtdesc codec;
1597
1598         unsigned i_index = 0;
1599         memset( &codec, 0, sizeof(codec) );
1600         codec.index = i_index;
1601         codec.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1602
1603         while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FMT, &codec ) >= 0 )
1604         {
1605             if( codec.index != i_index )
1606                 break;
1607             i_index++;
1608             codec.index = i_index;
1609         }
1610
1611         p_sys->i_codec = i_index;
1612
1613         free( p_sys->p_codecs );
1614         p_sys->p_codecs = calloc( 1, p_sys->i_codec * sizeof( struct v4l2_fmtdesc ) );
1615
1616         for( i_index = 0; i_index < p_sys->i_codec; i_index++ )
1617         {
1618             p_sys->p_codecs[i_index].index = i_index;
1619             p_sys->p_codecs[i_index].type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1620
1621             if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FMT, &p_sys->p_codecs[i_index] ) < 0 )
1622             {
1623                 msg_Err( p_obj, "cannot get codec description: %m" );
1624                 return -1;
1625             }
1626
1627             /* only print if vlc supports the format */
1628             char psz_fourcc_v4l2[5];
1629             memset( &psz_fourcc_v4l2, 0, sizeof( psz_fourcc_v4l2 ) );
1630             vlc_fourcc_to_char( p_sys->p_codecs[i_index].pixelformat,
1631                                 &psz_fourcc_v4l2 );
1632             bool b_codec_supported = false;
1633             for( int i = 0; v4l2chroma_to_fourcc[i].i_v4l2 != 0; i++ )
1634             {
1635                 if( v4l2chroma_to_fourcc[i].i_v4l2 == p_sys->p_codecs[i_index].pixelformat )
1636                 {
1637                     b_codec_supported = true;
1638
1639                     char psz_fourcc[5];
1640                     memset( &psz_fourcc, 0, sizeof( psz_fourcc ) );
1641                     vlc_fourcc_to_char( v4l2chroma_to_fourcc[i].i_fourcc,
1642                                         &psz_fourcc );
1643                     msg_Dbg( p_obj, "device supports chroma %4.4s [%s, %s]",
1644                                 psz_fourcc,
1645                                 p_sys->p_codecs[i_index].description,
1646                                 psz_fourcc_v4l2 );
1647
1648 #ifdef VIDIOC_ENUM_FRAMESIZES
1649                     /* This is new in Linux 2.6.19 */
1650                     /* List valid frame sizes for this format */
1651                     struct v4l2_frmsizeenum frmsize;
1652                     memset( &frmsize, 0, sizeof(frmsize) );
1653                     frmsize.pixel_format = p_sys->p_codecs[i_index].pixelformat;
1654                     if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize ) < 0 )
1655                     {
1656                         /* Not all devices support this ioctl */
1657                         msg_Warn( p_obj, "Unable to query for frame sizes" );
1658                     }
1659                     else
1660                     {
1661                         switch( frmsize.type )
1662                         {
1663                             case V4L2_FRMSIZE_TYPE_DISCRETE:
1664                                 do
1665                                 {
1666                                     msg_Dbg( p_obj,
1667                 "    device supports size %dx%d",
1668                 frmsize.discrete.width, frmsize.discrete.height );
1669                                     frmsize.index++;
1670                                 } while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize ) >= 0 );
1671                                 break;
1672                             case V4L2_FRMSIZE_TYPE_STEPWISE:
1673                                 msg_Dbg( p_obj,
1674                 "    device supports sizes %dx%d to %dx%d using %dx%d increments",
1675                 frmsize.stepwise.min_width, frmsize.stepwise.min_height,
1676                 frmsize.stepwise.max_width, frmsize.stepwise.max_height,
1677                 frmsize.stepwise.step_width, frmsize.stepwise.step_height );
1678                                 break;
1679                             case V4L2_FRMSIZE_TYPE_CONTINUOUS:
1680                                 msg_Dbg( p_obj,
1681                 "    device supports all sizes %dx%d to %dx%d",
1682                 frmsize.stepwise.min_width, frmsize.stepwise.min_height,
1683                 frmsize.stepwise.max_width, frmsize.stepwise.max_height );
1684                                 break;
1685                         }
1686                     }
1687 #endif
1688                 }
1689             }
1690             if( !b_codec_supported )
1691             {
1692                     msg_Dbg( p_obj,
1693                          "device codec %4.4s (%s) not supported",
1694                          psz_fourcc_v4l2,
1695                          p_sys->p_codecs[i_index].description );
1696             }
1697         }
1698     }
1699
1700     /* TODO: Move the resolution stuff up here */
1701     /* if MPEG encoder card, no need to do anything else after this */
1702     ControlList( p_obj, i_fd, b_demux );
1703
1704     /* Reset Cropping */
1705     memset( &cropcap, 0, sizeof(cropcap) );
1706     cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1707     if( v4l2_ioctl( i_fd, VIDIOC_CROPCAP, &cropcap ) >= 0 )
1708     {
1709         crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1710         crop.c = cropcap.defrect; /* reset to default */
1711         if( crop.c.width > 0 && crop.c.height > 0 ) /* Fix for fm tuners */
1712         {
1713             if( v4l2_ioctl( i_fd, VIDIOC_S_CROP, &crop ) < 0 )
1714             {
1715                 switch( errno )
1716                 {
1717                     case EINVAL:
1718                         /* Cropping not supported. */
1719                         break;
1720                     default:
1721                         /* Errors ignored. */
1722                         break;
1723                 }
1724             }
1725         }
1726     }
1727
1728     /* Try and find default resolution if not specified */
1729     memset( &fmt, 0, sizeof(fmt) );
1730     fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1731
1732     if( p_sys->i_width <= 0 || p_sys->i_height <= 0 )
1733     {
1734         /* Use current width and height settings */
1735         if( v4l2_ioctl( i_fd, VIDIOC_G_FMT, &fmt ) < 0 )
1736         {
1737             msg_Err( p_obj, "cannot get default width and height: %m" );
1738             goto error;
1739         }
1740
1741         msg_Dbg( p_obj, "found default width and height of %ux%u",
1742                  fmt.fmt.pix.width, fmt.fmt.pix.height );
1743
1744         if( p_sys->i_width < 0 || p_sys->i_height < 0 )
1745         {
1746             msg_Dbg( p_obj, "will try to find optimal width and height" );
1747         }
1748     }
1749     else
1750     {
1751         /* Use user specified width and height */
1752         msg_Dbg( p_obj, "trying specified size %dx%d",
1753                  p_sys->i_width, p_sys->i_height );
1754         fmt.fmt.pix.width = p_sys->i_width;
1755         fmt.fmt.pix.height = p_sys->i_height;
1756     }
1757
1758     fmt.fmt.pix.field = V4L2_FIELD_NONE;
1759
1760     float f_fps;
1761     if (b_demux)
1762     {
1763         demux_t *p_demux = (demux_t *) p_obj;
1764         char *reqchroma = var_InheritString( p_obj, CFG_PREFIX"chroma" );
1765
1766         /* Test and set Chroma */
1767         fmt.fmt.pix.pixelformat = 0;
1768         if( reqchroma != NULL )
1769         {
1770             /* User specified chroma */
1771             const vlc_fourcc_t i_requested_fourcc =
1772                 vlc_fourcc_GetCodecFromString( VIDEO_ES, reqchroma );
1773
1774             for( int i = 0; v4l2chroma_to_fourcc[i].i_v4l2 != 0; i++ )
1775             {
1776                 if( v4l2chroma_to_fourcc[i].i_fourcc == i_requested_fourcc )
1777                 {
1778                     fmt.fmt.pix.pixelformat = v4l2chroma_to_fourcc[i].i_v4l2;
1779                     break;
1780                 }
1781             }
1782             /* Try and set user chroma */
1783             bool b_error = !IsPixelFormatSupported( p_demux, fmt.fmt.pix.pixelformat );
1784             if( !b_error && fmt.fmt.pix.pixelformat )
1785             {
1786                 if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 )
1787                 {
1788                     fmt.fmt.pix.field = V4L2_FIELD_ANY;
1789                     if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 )
1790                     {
1791                         fmt.fmt.pix.field = V4L2_FIELD_NONE;
1792                         b_error = true;
1793                     }
1794                 }
1795             }
1796             if( b_error )
1797             {
1798                 msg_Warn( p_obj, "requested chroma %s not supported. "
1799                           " Trying default.", reqchroma );
1800                 fmt.fmt.pix.pixelformat = 0;
1801             }
1802             free( reqchroma );
1803         }
1804
1805         /* If no user specified chroma, find best */
1806         /* This also decides if MPEG encoder card or not */
1807         if( !fmt.fmt.pix.pixelformat )
1808         {
1809             unsigned int i;
1810             for( i = 0; i < ARRAY_SIZE( p_chroma_fallbacks ); i++ )
1811             {
1812                 fmt.fmt.pix.pixelformat = p_chroma_fallbacks[i];
1813                 if( IsPixelFormatSupported( p_demux, fmt.fmt.pix.pixelformat ) )
1814                 {
1815                     if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) >= 0 )
1816                         break;
1817                     fmt.fmt.pix.field = V4L2_FIELD_ANY;
1818                     if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) >= 0 )
1819                         break;
1820                     fmt.fmt.pix.field = V4L2_FIELD_NONE;
1821                 }
1822             }
1823             if( i == ARRAY_SIZE( p_chroma_fallbacks ) )
1824             {
1825                 msg_Warn( p_demux, "Could not select any of the default chromas; attempting to open as MPEG encoder card (access)" );
1826                 goto error;
1827             }
1828         }
1829
1830         if( p_sys->i_width < 0 || p_sys->i_height < 0 )
1831         {
1832             f_fps = var_InheritFloat( p_obj, CFG_PREFIX"fps" );
1833             if( f_fps <= 0. )
1834             {
1835                 f_fps = GetAbsoluteMaxFrameRate( p_demux, i_fd,
1836                                                  fmt.fmt.pix.pixelformat );
1837                 msg_Dbg( p_demux, "Found maximum framerate of %f", f_fps );
1838             }
1839             uint32_t i_width, i_height;
1840             GetMaxDimensions( p_demux, i_fd,
1841                               fmt.fmt.pix.pixelformat, f_fps,
1842                               &i_width, &i_height );
1843             if( i_width || i_height )
1844             {
1845                 msg_Dbg( p_demux, "Found optimal dimensions for framerate %f "
1846                                   "of %ux%u", f_fps, i_width, i_height );
1847                 fmt.fmt.pix.width = i_width;
1848                 fmt.fmt.pix.height = i_height;
1849                 if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 )
1850                 {
1851                     msg_Err( p_obj, "Cannot set size to optimal dimensions "
1852                                     "%ux%u", i_width, i_height );
1853                     goto error;
1854                 }
1855             }
1856             else
1857             {
1858                 msg_Warn( p_obj, "Could not find optimal width and height, "
1859                                  "falling back to driver default." );
1860             }
1861         }
1862     }
1863
1864     p_sys->i_width = fmt.fmt.pix.width;
1865     p_sys->i_height = fmt.fmt.pix.height;
1866
1867     if( v4l2_ioctl( i_fd, VIDIOC_G_FMT, &fmt ) < 0 ) {;}
1868     /* Print extra info */
1869     msg_Dbg( p_obj, "Driver requires at most %d bytes to store a complete image", fmt.fmt.pix.sizeimage );
1870     /* Check interlacing */
1871     switch( fmt.fmt.pix.field )
1872     {
1873         case V4L2_FIELD_NONE:
1874             msg_Dbg( p_obj, "Interlacing setting: progressive" );
1875             break;
1876         case V4L2_FIELD_TOP:
1877             msg_Dbg( p_obj, "Interlacing setting: top field only" );
1878             break;
1879         case V4L2_FIELD_BOTTOM:
1880             msg_Dbg( p_obj, "Interlacing setting: bottom field only" );
1881             break;
1882         case V4L2_FIELD_INTERLACED:
1883             msg_Dbg( p_obj, "Interlacing setting: interleaved (bottom top if M/NTSC, top bottom otherwise)" );
1884             if( bottom_first )
1885                 p_sys->i_block_flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
1886             else
1887                 p_sys->i_block_flags = BLOCK_FLAG_TOP_FIELD_FIRST;
1888             break;
1889         case V4L2_FIELD_SEQ_TB:
1890             msg_Dbg( p_obj, "Interlacing setting: sequential top bottom (TODO)" );
1891             break;
1892         case V4L2_FIELD_SEQ_BT:
1893             msg_Dbg( p_obj, "Interlacing setting: sequential bottom top (TODO)" );
1894             break;
1895         case V4L2_FIELD_ALTERNATE:
1896             msg_Dbg( p_obj, "Interlacing setting: alternate fields (TODO)" );
1897             p_sys->i_height = p_sys->i_height * 2;
1898             break;
1899         case V4L2_FIELD_INTERLACED_TB:
1900             msg_Dbg( p_obj, "Interlacing setting: interleaved top bottom" );
1901             p_sys->i_block_flags = BLOCK_FLAG_TOP_FIELD_FIRST;
1902             break;
1903         case V4L2_FIELD_INTERLACED_BT:
1904             msg_Dbg( p_obj, "Interlacing setting: interleaved bottom top" );
1905             p_sys->i_block_flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
1906             break;
1907         default:
1908             msg_Warn( p_obj, "Interlacing setting: unknown type (%d)",
1909                       fmt.fmt.pix.field );
1910             break;
1911     }
1912
1913     /* Look up final fourcc */
1914     p_sys->i_fourcc = 0;
1915     for( int i = 0; v4l2chroma_to_fourcc[i].i_fourcc != 0; i++ )
1916     {
1917         if( v4l2chroma_to_fourcc[i].i_v4l2 == fmt.fmt.pix.pixelformat )
1918         {
1919             p_sys->i_fourcc = v4l2chroma_to_fourcc[i].i_fourcc;
1920             es_format_Init( &es_fmt, VIDEO_ES, p_sys->i_fourcc );
1921             es_fmt.video.i_rmask = v4l2chroma_to_fourcc[i].i_rmask;
1922             es_fmt.video.i_gmask = v4l2chroma_to_fourcc[i].i_gmask;
1923             es_fmt.video.i_bmask = v4l2chroma_to_fourcc[i].i_bmask;
1924             break;
1925         }
1926     }
1927
1928     /* Buggy driver paranoia */
1929     i_min = fmt.fmt.pix.width * 2;
1930     if( fmt.fmt.pix.bytesperline < i_min )
1931         fmt.fmt.pix.bytesperline = i_min;
1932     i_min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
1933     if( fmt.fmt.pix.sizeimage < i_min )
1934         fmt.fmt.pix.sizeimage = i_min;
1935
1936 #ifdef VIDIOC_ENUM_FRAMEINTERVALS
1937     /* This is new in Linux 2.6.19 */
1938     /* List supported frame rates */
1939     struct v4l2_frmivalenum frmival;
1940     memset( &frmival, 0, sizeof(frmival) );
1941     frmival.pixel_format = fmt.fmt.pix.pixelformat;
1942     frmival.width = p_sys->i_width;
1943     frmival.height = p_sys->i_height;
1944     if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival ) >= 0 )
1945     {
1946         char psz_fourcc[5];
1947         memset( &psz_fourcc, 0, sizeof( psz_fourcc ) );
1948         vlc_fourcc_to_char( p_sys->i_fourcc, &psz_fourcc );
1949         msg_Dbg( p_obj, "supported frame intervals for %4.4s, %dx%d:",
1950                  psz_fourcc, frmival.width, frmival.height );
1951         switch( frmival.type )
1952         {
1953             case V4L2_FRMIVAL_TYPE_DISCRETE:
1954                 do
1955                 {
1956                     msg_Dbg( p_obj, "    supported frame interval: %d/%d",
1957                              frmival.discrete.numerator,
1958                              frmival.discrete.denominator );
1959                     frmival.index++;
1960                 } while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival ) >= 0 );
1961                 break;
1962             case V4L2_FRMIVAL_TYPE_STEPWISE:
1963                 msg_Dbg( p_obj, "    supported frame intervals: %d/%d to "
1964                          "%d/%d using %d/%d increments",
1965                          frmival.stepwise.min.numerator,
1966                          frmival.stepwise.min.denominator,
1967                          frmival.stepwise.max.numerator,
1968                          frmival.stepwise.max.denominator,
1969                          frmival.stepwise.step.numerator,
1970                          frmival.stepwise.step.denominator );
1971                 break;
1972             case V4L2_FRMIVAL_TYPE_CONTINUOUS:
1973                 msg_Dbg( p_obj, "    supported frame intervals: %d/%d to %d/%d",
1974                          frmival.stepwise.min.numerator,
1975                          frmival.stepwise.min.denominator,
1976                          frmival.stepwise.max.numerator,
1977                          frmival.stepwise.max.denominator );
1978                 break;
1979         }
1980     }
1981 #endif
1982
1983
1984     /* Init IO method */
1985     switch( p_sys->io )
1986     {
1987     case IO_METHOD_READ:
1988         if( b_demux && InitRead( p_obj, p_sys, fmt.fmt.pix.sizeimage ) )
1989             goto error;
1990         break;
1991
1992     case IO_METHOD_MMAP:
1993         if( InitMmap( p_obj, p_sys, i_fd ) )
1994             goto error;
1995         break;
1996
1997     case IO_METHOD_USERPTR:
1998         if( InitUserP( p_obj, p_sys, i_fd, fmt.fmt.pix.sizeimage ) )
1999             goto error;
2000         break;
2001     }
2002
2003     if( b_demux )
2004     {
2005         /* Add */
2006         es_fmt.video.i_width  = p_sys->i_width;
2007         es_fmt.video.i_height = p_sys->i_height;
2008
2009         /* Get aspect-ratio */
2010         es_fmt.video.i_sar_num = p_sys->i_aspect    * es_fmt.video.i_height;
2011         es_fmt.video.i_sar_den = VOUT_ASPECT_FACTOR * es_fmt.video.i_width;
2012
2013         /* Framerate */
2014         es_fmt.video.i_frame_rate = lround(f_fps * 1000000.);
2015         es_fmt.video.i_frame_rate_base = 1000000;
2016
2017         demux_t *p_demux = (demux_t *) p_obj;
2018         msg_Dbg( p_demux, "added new video es %4.4s %dx%d",
2019             (char*)&es_fmt.i_codec, es_fmt.video.i_width, es_fmt.video.i_height );
2020         msg_Dbg( p_obj, " frame rate: %f", f_fps );
2021
2022         p_sys->p_es = es_out_Add( p_demux->out, &es_fmt );
2023     }
2024
2025     /* Start Capture */
2026
2027     switch( p_sys->io )
2028     {
2029     case IO_METHOD_READ:
2030         /* Nothing to do */
2031         break;
2032
2033     case IO_METHOD_MMAP:
2034         for (unsigned int i = 0; i < p_sys->i_nbuffers; ++i)
2035         {
2036             struct v4l2_buffer buf;
2037
2038             memset( &buf, 0, sizeof(buf) );
2039             buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2040             buf.memory = V4L2_MEMORY_MMAP;
2041             buf.index = i;
2042
2043             if( v4l2_ioctl( i_fd, VIDIOC_QBUF, &buf ) < 0 )
2044             {
2045                 msg_Err( p_obj, "VIDIOC_QBUF failed" );
2046                 goto error;
2047             }
2048         }
2049
2050         buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2051         if( v4l2_ioctl( i_fd, VIDIOC_STREAMON, &buf_type ) < 0 )
2052         {
2053             msg_Err( p_obj, "VIDIOC_STREAMON failed" );
2054             goto error;
2055         }
2056
2057         break;
2058
2059     case IO_METHOD_USERPTR:
2060         for( unsigned int i = 0; i < p_sys->i_nbuffers; ++i )
2061         {
2062             struct v4l2_buffer buf;
2063
2064             memset( &buf, 0, sizeof(buf) );
2065             buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2066             buf.memory = V4L2_MEMORY_USERPTR;
2067             buf.index = i;
2068             buf.m.userptr = (unsigned long)p_sys->p_buffers[i].start;
2069             buf.length = p_sys->p_buffers[i].length;
2070
2071             if( v4l2_ioctl( i_fd, VIDIOC_QBUF, &buf ) < 0 )
2072             {
2073                 msg_Err( p_obj, "VIDIOC_QBUF failed" );
2074                 goto error;
2075             }
2076         }
2077
2078         buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2079         if( v4l2_ioctl( i_fd, VIDIOC_STREAMON, &buf_type ) < 0 )
2080         {
2081             msg_Err( p_obj, "VIDIOC_STREAMON failed" );
2082             goto error;
2083         }
2084         break;
2085     }
2086
2087     return i_fd;
2088
2089 error:
2090     v4l2_close( i_fd );
2091     return -1;
2092 }