425ee3d6dab7bdab4f2cd67445a57c266fd14517
[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 static int ProbeVideoDev( vlc_object_t *, demux_sys_t *, int );
428
429 static const struct
430 {
431     unsigned int i_v4l2;
432     vlc_fourcc_t i_fourcc;
433     int i_rmask;
434     int i_gmask;
435     int i_bmask;
436 } v4l2chroma_to_fourcc[] =
437 {
438     /* Raw data types */
439     { V4L2_PIX_FMT_GREY,    VLC_CODEC_GREY, 0, 0, 0 },
440     { V4L2_PIX_FMT_HI240,   VLC_FOURCC('I','2','4','0'), 0, 0, 0 },
441     { V4L2_PIX_FMT_RGB555,  VLC_CODEC_RGB15, 0x001f,0x03e0,0x7c00 },
442     { V4L2_PIX_FMT_RGB565,  VLC_CODEC_RGB16, 0x001f,0x07e0,0xf800 },
443     /* Won't work since we don't know how to handle such gmask values
444      * correctly
445     { V4L2_PIX_FMT_RGB555X, VLC_CODEC_RGB15, 0x007c,0xe003,0x1f00 },
446     { V4L2_PIX_FMT_RGB565X, VLC_CODEC_RGB16, 0x00f8,0xe007,0x1f00 },
447     */
448     { V4L2_PIX_FMT_BGR24,   VLC_CODEC_RGB24, 0xff0000,0xff00,0xff },
449     { V4L2_PIX_FMT_RGB24,   VLC_CODEC_RGB24, 0xff,0xff00,0xff0000 },
450     { V4L2_PIX_FMT_BGR32,   VLC_CODEC_RGB32, 0xff0000,0xff00,0xff },
451     { V4L2_PIX_FMT_RGB32,   VLC_CODEC_RGB32, 0xff,0xff00,0xff0000 },
452     { V4L2_PIX_FMT_YUYV,    VLC_CODEC_YUYV, 0, 0, 0 },
453     { V4L2_PIX_FMT_UYVY,    VLC_CODEC_UYVY, 0, 0, 0 },
454     { V4L2_PIX_FMT_Y41P,    VLC_FOURCC('I','4','1','N'), 0, 0, 0 },
455     { V4L2_PIX_FMT_YUV422P, VLC_CODEC_I422, 0, 0, 0 },
456     { V4L2_PIX_FMT_YVU420,  VLC_CODEC_YV12, 0, 0, 0 },
457     { V4L2_PIX_FMT_YUV411P, VLC_CODEC_I411, 0, 0, 0 },
458     { V4L2_PIX_FMT_YUV410,  VLC_CODEC_I410, 0, 0, 0 },
459
460     /* Raw data types, not in V4L2 spec but still in videodev2.h and supported
461      * by VLC */
462     { V4L2_PIX_FMT_YUV420,  VLC_CODEC_I420, 0, 0, 0 },
463     /* FIXME { V4L2_PIX_FMT_RGB444,  VLC_CODEC_RGB32 }, */
464
465     /* Compressed data types */
466     { V4L2_PIX_FMT_MJPEG,   VLC_CODEC_MJPG, 0, 0, 0 },
467     { V4L2_PIX_FMT_JPEG,    VLC_CODEC_JPEG, 0, 0, 0 },
468 #if 0
469     { V4L2_PIX_FMT_DV,      VLC_FOURCC('?','?','?','?') },
470     { V4L2_PIX_FMT_MPEG,    VLC_FOURCC('?','?','?','?') },
471 #endif
472     { 0, 0, 0, 0, 0 }
473 };
474
475 /**
476  * List of V4L2 chromas were confident enough to use as fallbacks if the
477  * user hasn't provided a --v4l2-chroma value.
478  *
479  * Try YUV chromas first, then RGB little endian and MJPEG as last resort.
480  */
481 static const uint32_t p_chroma_fallbacks[] =
482 { V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_YVU420, V4L2_PIX_FMT_YUV422P,
483   V4L2_PIX_FMT_YUYV, V4L2_PIX_FMT_UYVY, V4L2_PIX_FMT_BGR24,
484   V4L2_PIX_FMT_BGR32, V4L2_PIX_FMT_MJPEG, V4L2_PIX_FMT_JPEG };
485
486 struct buffer_t
487 {
488     void *  start;
489     size_t  length;
490 };
491
492 /*****************************************************************************
493  * DemuxOpen: opens v4l2 device, access_demux callback
494  *****************************************************************************
495  *
496  * url: <video device>::::
497  *
498  *****************************************************************************/
499 static int DemuxOpen( vlc_object_t *p_this )
500 {
501     demux_t     *p_demux = (demux_t*)p_this;
502     demux_sys_t *p_sys;
503
504     /* Set up p_demux */
505     p_demux->pf_control = DemuxControl;
506     p_demux->pf_demux = Demux;
507     p_demux->info.i_update = 0;
508     p_demux->info.i_title = 0;
509     p_demux->info.i_seekpoint = 0;
510
511     p_demux->p_sys = p_sys = calloc( 1, sizeof( demux_sys_t ) );
512     if( p_sys == NULL ) return VLC_ENOMEM;
513
514     char *path = ParseMRL( p_this, p_demux->psz_location );
515     if( path == NULL )
516         path = var_CreateGetNonEmptyString( p_this, CFG_PREFIX"dev" );
517     GetV4L2Params( p_sys, p_this );
518
519 #ifdef HAVE_LIBV4L2
520     p_sys->i_fd = -1;
521     if( !var_InheritBool( p_this, CFG_PREFIX "use-libv4l2" ) )
522     {
523         p_sys->b_libv4l2 = false;
524 #endif
525         msg_Dbg( p_this, "Trying direct kernel v4l2" );
526         p_sys->i_fd = OpenVideoDev( p_this, path, p_sys, true );
527 #ifdef HAVE_LIBV4L2
528     }
529
530     if( p_sys->i_fd == -1 )
531     {
532         p_sys->b_libv4l2 = true;
533         msg_Dbg( p_this, "Trying libv4l2 wrapper" );
534         p_sys->i_fd = OpenVideoDev( p_this, path, p_sys, true );
535     }
536 #endif
537     free( path );
538     if( p_sys->i_fd == -1 )
539     {
540         free( p_sys->p_codecs );
541         free( p_sys );
542         return VLC_EGENERIC;
543     }
544     return VLC_SUCCESS;
545 }
546
547 /*****************************************************************************
548  * GetV4L2Params: fill in p_sys parameters (shared by DemuxOpen and AccessOpen)
549  *****************************************************************************/
550 static void GetV4L2Params( demux_sys_t *p_sys, vlc_object_t *p_obj )
551 {
552     p_sys->i_selected_input = var_CreateGetInteger( p_obj, "v4l2-input" );
553     p_sys->i_audio_input = var_CreateGetInteger( p_obj, "v4l2-audio-input" );
554
555     p_sys->i_width = var_CreateGetInteger( p_obj, "v4l2-width" );
556     p_sys->i_height = var_CreateGetInteger( p_obj, "v4l2-height" );
557
558     p_sys->i_tuner = var_CreateGetInteger( p_obj, "v4l2-tuner" );
559     p_sys->i_tuner_type = V4L2_TUNER_RADIO; /* non-trap default value */
560     p_sys->i_tuner_audio_mode = var_CreateGetInteger( p_obj, "v4l2-tuner-audio-mode" );
561
562     char *psz_aspect = var_CreateGetString( p_obj, "v4l2-aspect-ratio" );
563     char *psz_delim = !EMPTY_STR(psz_aspect) ? strchr( psz_aspect, ':' ) : NULL;
564     if( psz_delim )
565     {
566         p_sys->i_aspect = atoi( psz_aspect ) * VOUT_ASPECT_FACTOR / atoi( psz_delim + 1 );
567     }
568     else
569     {
570         p_sys->i_aspect = 4 * VOUT_ASPECT_FACTOR / 3 ;
571
572     }
573     free( psz_aspect );
574
575     p_sys->i_fd = -1;
576
577     p_sys->p_es = NULL;
578 }
579
580 /**
581  * Parses a V4L2 MRL.
582  * \return device node path (use free()) or NULL if not specified
583  */
584 static char *ParseMRL( vlc_object_t *obj, const char *mrl )
585 {
586     const char *p = strchr( mrl, ':' );
587
588     if( p != NULL )
589     {
590         var_LocationParse( obj, p + 1, CFG_PREFIX );
591         if( p > mrl )
592             return strndup( mrl, p - mrl );
593     }
594     else
595     {
596         if( mrl[0] )
597             return strdup( mrl );
598     }
599     return NULL;
600 }
601
602 /*****************************************************************************
603  * Close: close device, free resources
604  *****************************************************************************/
605 static void AccessClose( vlc_object_t *p_this )
606 {
607     access_t    *p_access = (access_t *)p_this;
608     demux_sys_t *p_sys   = (demux_sys_t *) p_access->p_sys;
609
610     CommonClose( p_this, p_sys );
611 }
612
613 static void DemuxClose( vlc_object_t *p_this )
614 {
615     struct v4l2_buffer buf;
616     enum v4l2_buf_type buf_type;
617     unsigned int i;
618
619     demux_t     *p_demux = (demux_t *)p_this;
620     demux_sys_t *p_sys   = p_demux->p_sys;
621
622     /* Stop video capture */
623     if( p_sys->i_fd >= 0 )
624     {
625         switch( p_sys->io )
626         {
627         case IO_METHOD_READ:
628             /* Nothing to do */
629             break;
630
631         case IO_METHOD_MMAP:
632         case IO_METHOD_USERPTR:
633             /* Some drivers 'hang' internally if this is not done before streamoff */
634             for( unsigned int i = 0; i < p_sys->i_nbuffers; i++ )
635             {
636                 memset( &buf, 0, sizeof(buf) );
637                 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
638                 buf.memory = ( p_sys->io == IO_METHOD_USERPTR ) ?
639                     V4L2_MEMORY_USERPTR : V4L2_MEMORY_MMAP;
640                 v4l2_ioctl( p_sys->i_fd, VIDIOC_DQBUF, &buf ); /* ignore result */
641             }
642
643             buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
644             if( v4l2_ioctl( p_sys->i_fd, VIDIOC_STREAMOFF, &buf_type ) < 0 ) {
645                 msg_Err( p_this, "VIDIOC_STREAMOFF failed" );
646             }
647
648             break;
649         }
650     }
651
652     /* Free Video Buffers */
653     if( p_sys->p_buffers ) {
654         switch( p_sys->io )
655         {
656         case IO_METHOD_READ:
657             free( p_sys->p_buffers[0].start );
658             break;
659
660         case IO_METHOD_MMAP:
661             for( i = 0; i < p_sys->i_nbuffers; ++i )
662             {
663                 if( v4l2_munmap( p_sys->p_buffers[i].start, p_sys->p_buffers[i].length ) )
664                 {
665                     msg_Err( p_this, "munmap failed" );
666                 }
667             }
668             break;
669
670         case IO_METHOD_USERPTR:
671             for( i = 0; i < p_sys->i_nbuffers; ++i )
672             {
673                free( p_sys->p_buffers[i].start );
674             }
675             break;
676         }
677         free( p_sys->p_buffers );
678     }
679
680     CommonClose( p_this, p_sys );
681 }
682
683 static void CommonClose( vlc_object_t *p_this, demux_sys_t *p_sys )
684 {
685     (void)p_this;
686     /* Close */
687     if( p_sys->i_fd >= 0 ) v4l2_close( p_sys->i_fd );
688     free( p_sys->p_codecs );
689     free( p_sys );
690 }
691
692 /*****************************************************************************
693  * AccessOpen: opens v4l2 device, access callback
694  *****************************************************************************
695  *
696  * url: <video device>::::
697  *
698  *****************************************************************************/
699 static int AccessOpen( vlc_object_t * p_this )
700 {
701     access_t *p_access = (access_t*) p_this;
702     demux_sys_t * p_sys;
703
704     /* Only when selected */
705     if( *p_access->psz_access == '\0' ) return VLC_EGENERIC;
706
707     access_InitFields( p_access );
708     p_sys = calloc( 1, sizeof( demux_sys_t ));
709     if( !p_sys ) return VLC_ENOMEM;
710     p_access->p_sys = (access_sys_t*)p_sys;
711
712     char *path = ParseMRL( p_this, p_access->psz_location );
713     if( path == NULL )
714         path = var_InheritString( p_this, CFG_PREFIX"dev" );
715     GetV4L2Params( p_sys, p_this );
716
717 #ifdef HAVE_LIBV4L2
718     p_sys->i_fd = -1;
719     if( !var_InheritBool( p_this, CFG_PREFIX "use-libv4l2" ) )
720     {
721         p_sys->b_libv4l2 = false;
722 #endif
723         msg_Dbg( p_this, "Trying direct kernel v4l2" );
724         p_sys->i_fd = OpenVideoDev( p_this, path, p_sys, false );
725 #ifdef HAVE_LIBV4L2
726     }
727     if( p_sys->i_fd == -1 )
728     {
729         p_sys->b_libv4l2 = true;
730         msg_Dbg( p_this, "Trying libv4l2 wrapper" );
731         p_sys->i_fd = OpenVideoDev( p_this, path, p_sys, false );
732     }
733 #endif
734     free( path );
735     if( p_sys->i_fd == -1 )
736     {
737         free( p_sys->p_codecs );
738         free( p_sys );
739         return VLC_EGENERIC;
740     }
741
742     if( p_sys->io == IO_METHOD_READ )
743         ACCESS_SET_CALLBACKS( AccessReadStream, NULL, AccessControl, NULL );
744     else
745         ACCESS_SET_CALLBACKS( NULL, AccessRead, AccessControl, NULL );
746     return VLC_SUCCESS;
747 }
748
749 /*****************************************************************************
750  * DemuxControl:
751  *****************************************************************************/
752 static int DemuxControl( demux_t *p_demux, int i_query, va_list args )
753 {
754     switch( i_query )
755     {
756         /* Special for access_demux */
757         case DEMUX_CAN_PAUSE:
758         case DEMUX_CAN_SEEK:
759         case DEMUX_CAN_CONTROL_PACE:
760             *va_arg( args, bool * ) = false;
761             return VLC_SUCCESS;
762
763         case DEMUX_GET_PTS_DELAY:
764             *va_arg(args,int64_t *) = INT64_C(1000)
765                 * var_InheritInteger( p_demux, "live-caching" );
766             return VLC_SUCCESS;
767
768         case DEMUX_GET_TIME:
769             *va_arg( args, int64_t * ) = mdate();
770             return VLC_SUCCESS;
771
772         /* TODO implement others */
773         default:
774             return VLC_EGENERIC;
775     }
776
777     return VLC_EGENERIC;
778 }
779
780 /*****************************************************************************
781  * AccessControl: access callback
782  *****************************************************************************/
783 static int AccessControl( access_t *p_access, int i_query, va_list args )
784 {
785     switch( i_query )
786     {
787         /* */
788         case ACCESS_CAN_SEEK:
789         case ACCESS_CAN_FASTSEEK:
790         case ACCESS_CAN_PAUSE:
791         case ACCESS_CAN_CONTROL_PACE:
792             *va_arg( args, bool* ) = false;
793             break;
794
795         /* */
796         case ACCESS_GET_PTS_DELAY:
797             *va_arg(args,int64_t *) = INT64_C(1000)
798                 * var_InheritInteger( p_access, "live-caching" );
799             break;
800
801         /* */
802         case ACCESS_SET_PAUSE_STATE:
803             /* Nothing to do */
804             break;
805
806         case ACCESS_GET_TITLE_INFO:
807         case ACCESS_SET_TITLE:
808         case ACCESS_SET_SEEKPOINT:
809         case ACCESS_SET_PRIVATE_ID_STATE:
810         case ACCESS_GET_CONTENT_TYPE:
811         case ACCESS_GET_META:
812             return VLC_EGENERIC;
813
814         default:
815             msg_Warn( p_access, "Unimplemented query in control(%d).", i_query);
816             return VLC_EGENERIC;
817
818     }
819     return VLC_SUCCESS;
820 }
821
822 /*****************************************************************************
823  * AccessRead: access callback
824  ******************************************************************************/
825 static block_t *AccessRead( access_t * p_access )
826 {
827     demux_sys_t *p_sys = (demux_sys_t *)p_access->p_sys;
828
829     struct pollfd fd;
830     fd.fd = p_sys->i_fd;
831     fd.events = POLLIN|POLLPRI;
832     fd.revents = 0;
833
834     /* Wait for data */
835     if( poll( &fd, 1, 500 ) > 0 ) /* Timeout after 0.5 seconds since I don't know if pf_demux can be blocking. */
836         return GrabVideo( VLC_OBJECT(p_access), p_sys );
837
838     return NULL;
839 }
840
841 static ssize_t AccessReadStream( access_t * p_access, uint8_t * p_buffer, size_t i_len )
842 {
843     demux_sys_t *p_sys = (demux_sys_t *) p_access->p_sys;
844     struct pollfd ufd;
845     int i_ret;
846
847     ufd.fd = p_sys->i_fd;
848     ufd.events = POLLIN;
849
850     if( p_access->info.b_eof )
851         return 0;
852
853     do
854     {
855         if( !vlc_object_alive (p_access) )
856             return 0;
857
858         ufd.revents = 0;
859     }
860     while( ( i_ret = poll( &ufd, 1, 500 ) ) == 0 );
861
862     if( i_ret < 0 )
863     {
864         if( errno != EINTR )
865             msg_Err( p_access, "poll error" );
866         return -1;
867     }
868
869     i_ret = v4l2_read( p_sys->i_fd, p_buffer, i_len );
870     if( i_ret == 0 )
871     {
872         p_access->info.b_eof = true;
873     }
874     else if( i_ret > 0 )
875     {
876         p_access->info.i_pos += i_ret;
877     }
878
879     return i_ret;
880 }
881
882 /*****************************************************************************
883  * Demux: Processes the audio or video frame
884  *****************************************************************************/
885 static int Demux( demux_t *p_demux )
886 {
887     demux_sys_t *p_sys = p_demux->p_sys;
888
889     struct pollfd fd;
890     fd.fd = p_sys->i_fd;
891     fd.events = POLLIN|POLLPRI;
892     fd.revents = 0;
893
894     /* Wait for data */
895     /* Timeout after 0.5 seconds since I don't know if pf_demux can be blocking. */
896     while( poll( &fd, 1, 500 ) == -1 )
897         if( errno != EINTR )
898         {
899             msg_Err( p_demux, "poll error: %m" );
900             return -1;
901         }
902
903     if( fd.revents )
904     {
905          block_t *p_block = GrabVideo( VLC_OBJECT(p_demux), p_sys );
906          if( p_block )
907          {
908              es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_block->i_pts );
909              es_out_Send( p_demux->out, p_sys->p_es, p_block );
910         }
911     }
912
913     return 1;
914 }
915
916 /*****************************************************************************
917  * GrabVideo: Grab a video frame
918  *****************************************************************************/
919 static block_t* GrabVideo( vlc_object_t *p_demux, demux_sys_t *p_sys )
920 {
921     block_t *p_block;
922     struct v4l2_buffer buf;
923     ssize_t i_ret;
924
925     /* Grab Video Frame */
926     switch( p_sys->io )
927     {
928     case IO_METHOD_READ:
929         i_ret = v4l2_read( p_sys->i_fd, p_sys->p_buffers[0].start, p_sys->p_buffers[0].length );
930         if( i_ret == -1 )
931         {
932             switch( errno )
933             {
934             case EAGAIN:
935                 return NULL;
936             case EIO:
937                 /* Could ignore EIO, see spec. */
938                 /* fall through */
939             default:
940                 msg_Err( p_demux, "Failed to read frame" );
941                 return 0;
942                }
943         }
944
945         p_block = ProcessVideoFrame( p_demux, (uint8_t*)p_sys->p_buffers[0].start, i_ret );
946         if( !p_block )
947             return NULL;
948
949         break;
950
951     case IO_METHOD_MMAP:
952         memset( &buf, 0, sizeof(buf) );
953         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
954         buf.memory = V4L2_MEMORY_MMAP;
955
956         /* Wait for next frame */
957         if (v4l2_ioctl( p_sys->i_fd, VIDIOC_DQBUF, &buf ) < 0 )
958         {
959             switch( errno )
960             {
961             case EAGAIN:
962                 return NULL;
963             case EIO:
964                 /* Could ignore EIO, see spec. */
965                 /* fall through */
966             default:
967                 msg_Err( p_demux, "Failed to wait (VIDIOC_DQBUF)" );
968                 return NULL;
969                }
970         }
971
972         if( buf.index >= p_sys->i_nbuffers ) {
973             msg_Err( p_demux, "Failed capturing new frame as i>=nbuffers" );
974             return NULL;
975         }
976
977         p_block = ProcessVideoFrame( p_demux, p_sys->p_buffers[buf.index].start, buf.bytesused );
978         if( !p_block )
979             return NULL;
980
981         /* Unlock */
982         if( v4l2_ioctl( p_sys->i_fd, VIDIOC_QBUF, &buf ) < 0 )
983         {
984             msg_Err( p_demux, "Failed to unlock (VIDIOC_QBUF)" );
985             block_Release( p_block );
986             return NULL;
987         }
988
989         break;
990
991     case IO_METHOD_USERPTR:
992         memset( &buf, 0, sizeof(buf) );
993         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
994         buf.memory = V4L2_MEMORY_USERPTR;
995
996         /* Wait for next frame */
997         if (v4l2_ioctl( p_sys->i_fd, VIDIOC_DQBUF, &buf ) < 0 )
998         {
999             switch( errno )
1000             {
1001             case EAGAIN:
1002                 return NULL;
1003             case EIO:
1004                 /* Could ignore EIO, see spec. */
1005                 /* fall through */
1006             default:
1007                 msg_Err( p_demux, "Failed to wait (VIDIOC_DQBUF)" );
1008                 return NULL;
1009             }
1010         }
1011
1012         /* Find frame? */
1013         unsigned int i;
1014         for( i = 0; i < p_sys->i_nbuffers; i++ )
1015         {
1016             if( buf.m.userptr == (unsigned long)p_sys->p_buffers[i].start &&
1017                 buf.length == p_sys->p_buffers[i].length ) break;
1018         }
1019
1020         if( i >= p_sys->i_nbuffers )
1021         {
1022             msg_Err( p_demux, "Failed capturing new frame as i>=nbuffers" );
1023             return NULL;
1024         }
1025
1026         p_block = ProcessVideoFrame( p_demux, (uint8_t*)buf.m.userptr, buf.bytesused );
1027         if( !p_block )
1028             return NULL;
1029
1030         /* Unlock */
1031         if( v4l2_ioctl( p_sys->i_fd, VIDIOC_QBUF, &buf ) < 0 )
1032         {
1033             msg_Err( p_demux, "Failed to unlock (VIDIOC_QBUF)" );
1034             block_Release( p_block );
1035             return NULL;
1036         }
1037
1038         break;
1039     }
1040
1041     /* Timestamp */
1042     p_block->i_pts = p_block->i_dts = mdate();
1043     p_block->i_flags |= p_sys->i_block_flags;
1044
1045     return p_block;
1046 }
1047
1048 /*****************************************************************************
1049  * ProcessVideoFrame: Helper function to take a buffer and copy it into
1050  * a new block
1051  *****************************************************************************/
1052 static block_t* ProcessVideoFrame( vlc_object_t *p_demux, uint8_t *p_frame, size_t i_size )
1053 {
1054     block_t *p_block;
1055
1056     if( !p_frame ) return NULL;
1057
1058     /* New block */
1059     if( !( p_block = block_New( p_demux, i_size ) ) )
1060     {
1061         msg_Warn( p_demux, "Cannot get new block" );
1062         return NULL;
1063     }
1064
1065     /* Copy frame */
1066     memcpy( p_block->p_buffer, p_frame, i_size );
1067
1068     return p_block;
1069 }
1070
1071 /*****************************************************************************
1072  * Helper function to initalise video IO using the Read method
1073  *****************************************************************************/
1074 static int InitRead( vlc_object_t *p_demux, demux_sys_t *p_sys, unsigned int i_buffer_size )
1075 {
1076     (void)p_demux;
1077
1078     p_sys->p_buffers = calloc( 1, sizeof( *p_sys->p_buffers ) );
1079     if( unlikely(p_sys->p_buffers == NULL) )
1080         return -1;
1081
1082     p_sys->p_buffers[0].length = i_buffer_size;
1083     p_sys->p_buffers[0].start = malloc( i_buffer_size );
1084     if( !p_sys->p_buffers[0].start )
1085         return -1;
1086
1087     return 0;
1088 }
1089
1090 /*****************************************************************************
1091  * Helper function to initalise video IO using the mmap method
1092  *****************************************************************************/
1093 static int InitMmap( vlc_object_t *p_demux, demux_sys_t *p_sys, int i_fd )
1094 {
1095     struct v4l2_requestbuffers req;
1096
1097     memset( &req, 0, sizeof(req) );
1098     req.count = 4;
1099     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1100     req.memory = V4L2_MEMORY_MMAP;
1101
1102     if( v4l2_ioctl( i_fd, VIDIOC_REQBUFS, &req ) < 0 )
1103     {
1104         msg_Err( p_demux, "device does not support mmap I/O" );
1105         return -1;
1106     }
1107
1108     if( req.count < 2 )
1109     {
1110         msg_Err( p_demux, "insufficient buffers" );
1111         return -1;
1112     }
1113
1114     p_sys->p_buffers = calloc( req.count, sizeof( *p_sys->p_buffers ) );
1115     if( unlikely(!p_sys->p_buffers) )
1116         return -1;
1117
1118     for( p_sys->i_nbuffers = 0; p_sys->i_nbuffers < req.count; ++p_sys->i_nbuffers )
1119     {
1120         struct v4l2_buffer buf;
1121
1122         memset( &buf, 0, sizeof(buf) );
1123         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1124         buf.memory = V4L2_MEMORY_MMAP;
1125         buf.index = p_sys->i_nbuffers;
1126
1127         if( v4l2_ioctl( i_fd, VIDIOC_QUERYBUF, &buf ) < 0 )
1128         {
1129             msg_Err( p_demux, "VIDIOC_QUERYBUF: %m" );
1130             return -1;
1131         }
1132
1133         p_sys->p_buffers[p_sys->i_nbuffers].length = buf.length;
1134         p_sys->p_buffers[p_sys->i_nbuffers].start =
1135             v4l2_mmap( NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, i_fd, buf.m.offset );
1136
1137         if( p_sys->p_buffers[p_sys->i_nbuffers].start == MAP_FAILED )
1138         {
1139             msg_Err( p_demux, "mmap failed: %m" );
1140             return -1;
1141         }
1142     }
1143
1144     return 0;
1145 }
1146
1147 /*****************************************************************************
1148  * Helper function to initalise video IO using the userbuf method
1149  *****************************************************************************/
1150 static int InitUserP( vlc_object_t *p_demux, demux_sys_t *p_sys, int i_fd, unsigned int i_buffer_size )
1151 {
1152     struct v4l2_requestbuffers req;
1153     unsigned int i_page_size;
1154
1155     i_page_size = sysconf(_SC_PAGESIZE);
1156     i_buffer_size = ( i_buffer_size + i_page_size - 1 ) & ~( i_page_size - 1);
1157
1158     memset( &req, 0, sizeof(req) );
1159     req.count = 4;
1160     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1161     req.memory = V4L2_MEMORY_USERPTR;
1162
1163     if( v4l2_ioctl( i_fd, VIDIOC_REQBUFS, &req ) < 0 )
1164     {
1165         msg_Err( p_demux, "device does not support user pointer i/o" );
1166         return -1;
1167     }
1168
1169     p_sys->p_buffers = calloc( 4, sizeof( *p_sys->p_buffers ) );
1170     if( !p_sys->p_buffers )
1171         return -1;
1172
1173     for( p_sys->i_nbuffers = 0; p_sys->i_nbuffers < 4; ++p_sys->i_nbuffers )
1174     {
1175         p_sys->p_buffers[p_sys->i_nbuffers].length = i_buffer_size;
1176         if( posix_memalign( &p_sys->p_buffers[p_sys->i_nbuffers].start,
1177                 /* boundary */ i_page_size, i_buffer_size ) )
1178             return -1;
1179     }
1180
1181     return 0;
1182 }
1183
1184 /*****************************************************************************
1185  * IsPixelFormatSupported: returns true if the specified V4L2 pixel format is
1186  * in the array of supported formats returned by the driver
1187  *****************************************************************************/
1188 static bool IsPixelFormatSupported( demux_t *p_demux, unsigned int i_pixelformat )
1189 {
1190     demux_sys_t *p_sys = p_demux->p_sys;
1191
1192     for( unsigned i_index = 0; i_index < p_sys->i_codec; i_index++ )
1193     {
1194         if( p_sys->p_codecs[i_index].pixelformat == i_pixelformat )
1195             return true;
1196     }
1197
1198     return false;
1199 }
1200
1201 static float GetMaxFrameRate( int i_fd, uint32_t i_pixel_format,
1202                               uint32_t i_width, uint32_t i_height )
1203 {
1204 #ifdef VIDIOC_ENUM_FRAMEINTERVALS
1205     /* This is new in Linux 2.6.19 */
1206     struct v4l2_frmivalenum frmival;
1207     memset( &frmival, 0, sizeof(frmival) );
1208     frmival.pixel_format = i_pixel_format;
1209     frmival.width = i_width;
1210     frmival.height = i_height;
1211     if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival ) >= 0 )
1212     {
1213         switch( frmival.type )
1214         {
1215             case V4L2_FRMIVAL_TYPE_DISCRETE:
1216             {
1217                 float f_fps_max = -1;
1218                 do
1219                 {
1220                     float f_fps = (float)frmival.discrete.denominator
1221                                 / (float)frmival.discrete.numerator;
1222                     if( f_fps > f_fps_max ) f_fps_max = f_fps;
1223                     frmival.index++;
1224                 } while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMEINTERVALS,
1225                                      &frmival ) >= 0 );
1226                 return f_fps_max;
1227             }
1228             case V4L2_FRMSIZE_TYPE_STEPWISE:
1229             case V4L2_FRMIVAL_TYPE_CONTINUOUS:
1230                 return __MAX( (float)frmival.stepwise.max.denominator
1231                             / (float)frmival.stepwise.max.numerator,
1232                               (float)frmival.stepwise.min.denominator
1233                             / (float)frmival.stepwise.min.numerator );
1234         }
1235     }
1236 #endif
1237     return -1.;
1238 }
1239
1240 static float GetAbsoluteMaxFrameRate( demux_t *p_demux, int i_fd,
1241                                       uint32_t i_pixel_format )
1242 {
1243     float f_fps_max = -1.;
1244 #ifdef VIDIOC_ENUM_FRAMESIZES
1245     /* This is new in Linux 2.6.19 */
1246     struct v4l2_frmsizeenum frmsize;
1247     memset( &frmsize, 0, sizeof(frmsize) );
1248     frmsize.pixel_format = i_pixel_format;
1249     if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize ) >= 0 )
1250     {
1251         switch( frmsize.type )
1252         {
1253             case V4L2_FRMSIZE_TYPE_DISCRETE:
1254                 do
1255                 {
1256                     frmsize.index++;
1257                     float f_fps = GetMaxFrameRate( i_fd, i_pixel_format,
1258                                                    frmsize.discrete.width,
1259                                                    frmsize.discrete.height );
1260                     if( f_fps > f_fps_max ) f_fps_max = f_fps;
1261                 } while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES,
1262                          &frmsize ) >= 0 );
1263                 break;
1264             case V4L2_FRMSIZE_TYPE_STEPWISE:
1265             {
1266                 uint32_t i_width = frmsize.stepwise.min_width;
1267                 uint32_t i_height = frmsize.stepwise.min_height;
1268                 for( ;
1269                      i_width <= frmsize.stepwise.max_width &&
1270                      i_height <= frmsize.stepwise.max_width;
1271                      i_width += frmsize.stepwise.step_width,
1272                      i_height += frmsize.stepwise.step_height )
1273                 {
1274                     float f_fps = GetMaxFrameRate( i_fd, i_pixel_format,
1275                                                    i_width, i_height );
1276                     if( f_fps > f_fps_max ) f_fps_max = f_fps;
1277                 }
1278                 break;
1279             }
1280             case V4L2_FRMSIZE_TYPE_CONTINUOUS:
1281                 /* FIXME */
1282                 msg_Err( p_demux, "GetAbsoluteMaxFrameRate implementation for V4L2_FRMSIZE_TYPE_CONTINUOUS isn't correct" );
1283                  f_fps_max = GetMaxFrameRate( i_fd, i_pixel_format,
1284                                               frmsize.stepwise.max_width,
1285                                               frmsize.stepwise.max_height );
1286                 break;
1287         }
1288     }
1289 #endif
1290     return f_fps_max;
1291 }
1292
1293 static void GetMaxDimensions( demux_t *p_demux, int i_fd,
1294                               uint32_t i_pixel_format, float f_fps_min,
1295                               uint32_t *pi_width, uint32_t *pi_height )
1296 {
1297     *pi_width = 0;
1298     *pi_height = 0;
1299 #ifdef VIDIOC_ENUM_FRAMESIZES
1300     /* This is new in Linux 2.6.19 */
1301     struct v4l2_frmsizeenum frmsize;
1302     memset( &frmsize, 0, sizeof(frmsize) );
1303     frmsize.pixel_format = i_pixel_format;
1304     if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize ) >= 0 )
1305     {
1306         switch( frmsize.type )
1307         {
1308             case V4L2_FRMSIZE_TYPE_DISCRETE:
1309                 do
1310                 {
1311                     frmsize.index++;
1312                     float f_fps = GetMaxFrameRate( i_fd, i_pixel_format,
1313                                                    frmsize.discrete.width,
1314                                                    frmsize.discrete.height );
1315                     if( f_fps >= f_fps_min &&
1316                         frmsize.discrete.width > *pi_width )
1317                     {
1318                         *pi_width = frmsize.discrete.width;
1319                         *pi_height = frmsize.discrete.height;
1320                     }
1321                 } while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES,
1322                          &frmsize ) >= 0 );
1323                 break;
1324             case V4L2_FRMSIZE_TYPE_STEPWISE:
1325             {
1326                 uint32_t i_width = frmsize.stepwise.min_width;
1327                 uint32_t i_height = frmsize.stepwise.min_height;
1328                 for( ;
1329                      i_width <= frmsize.stepwise.max_width &&
1330                      i_height <= frmsize.stepwise.max_width;
1331                      i_width += frmsize.stepwise.step_width,
1332                      i_height += frmsize.stepwise.step_height )
1333                 {
1334                     float f_fps = GetMaxFrameRate( i_fd, i_pixel_format,
1335                                                    i_width, i_height );
1336                     if( f_fps >= f_fps_min && i_width > *pi_width )
1337                     {
1338                         *pi_width = i_width;
1339                         *pi_height = i_height;
1340                     }
1341                 }
1342                 break;
1343             }
1344             case V4L2_FRMSIZE_TYPE_CONTINUOUS:
1345                 /* FIXME */
1346                 msg_Err( p_demux, "GetMaxDimension implementation for V4L2_FRMSIZE_TYPE_CONTINUOUS isn't correct" );
1347                 float f_fps = GetMaxFrameRate( i_fd, i_pixel_format,
1348                                                frmsize.stepwise.max_width,
1349                                                frmsize.stepwise.max_height );
1350                 if( f_fps >= f_fps_min &&
1351                     frmsize.stepwise.max_width > *pi_width )
1352                 {
1353                     *pi_width = frmsize.stepwise.max_width;
1354                     *pi_height = frmsize.stepwise.max_height;
1355                 }
1356                 break;
1357         }
1358     }
1359 #endif
1360 }
1361
1362 /**
1363  * Opens and sets up a video device
1364  * \return file descriptor or -1 on error
1365  */
1366 static int OpenVideoDev( vlc_object_t *p_obj, const char *path,
1367                          demux_sys_t *p_sys, bool b_demux )
1368 {
1369     struct v4l2_cropcap cropcap;
1370     struct v4l2_crop crop;
1371     struct v4l2_format fmt;
1372     unsigned int i_min;
1373     enum v4l2_buf_type buf_type;
1374     es_format_t es_fmt;
1375
1376     msg_Dbg( p_obj, "opening device '%s'", path );
1377
1378     int i_fd = vlc_open( path, O_RDWR );
1379     if( i_fd == -1 )
1380     {
1381         msg_Err( p_obj, "cannot open device %s: %m", path );
1382         return -1;
1383     }
1384
1385 #ifdef HAVE_LIBV4L2
1386     /* Note the v4l2_xxx functions are designed so that if they get passed an
1387        unknown fd, the will behave exactly as their regular xxx counterparts,
1388        so if v4l2_fd_open fails, we continue as normal (missing the libv4l2
1389        custom cam format to normal formats conversion). Chances are big we will
1390        still fail then though, as normally v4l2_fd_open only fails if the
1391        device is not a v4l2 device. */
1392     if( p_sys->b_libv4l2 )
1393     {
1394         int libv4l2_fd;
1395         libv4l2_fd = v4l2_fd_open( i_fd, 0 );
1396         if( libv4l2_fd != -1 )
1397             i_fd = libv4l2_fd;
1398     }
1399 #endif
1400
1401     if( ProbeVideoDev( p_obj, p_sys, i_fd ) )
1402         goto error;
1403
1404     /* Select input */
1405     if( v4l2_ioctl( i_fd, VIDIOC_S_INPUT, &p_sys->i_selected_input ) < 0 )
1406     {
1407         msg_Err( p_obj, "cannot set input %u: %m", p_sys->i_selected_input );
1408         goto error;
1409     }
1410     msg_Dbg( p_obj, "input set to %u", p_sys->i_selected_input );
1411
1412     /* Select standard */
1413     bool bottom_first;
1414     const char *stdname = var_InheritString( p_obj, CFG_PREFIX"standard" );
1415     if( stdname != NULL )
1416     {
1417         v4l2_std_id std = strtoull( stdname, NULL, 0 );
1418         if( std == 0 )
1419         {
1420             const size_t n = sizeof(standards_vlc) / sizeof(*standards_vlc);
1421             assert( n == sizeof(standards_v4l2) / sizeof(*standards_v4l2) );
1422             assert( n == sizeof(standards_user) / sizeof(*standards_user) );
1423             for( size_t i = 0; i < n; i++ )
1424                 if( strcasecmp( stdname, standards_vlc[i] ) == 0 )
1425                 {
1426                     std = standards_v4l2[i];
1427                     break;
1428                 }
1429         }
1430
1431         if( v4l2_ioctl( i_fd, VIDIOC_S_STD, &std ) < 0
1432          || v4l2_ioctl( i_fd, VIDIOC_G_STD, &std ) < 0 )
1433         {
1434             msg_Err( p_obj, "cannot set standard 0x%"PRIx64": %m", std );
1435             goto error;
1436         }
1437         msg_Dbg( p_obj, "standard set to 0x%"PRIx64":", std );
1438         bottom_first = std == V4L2_STD_NTSC;
1439     }
1440     else
1441         bottom_first = false;
1442
1443     /* Tune the tuner */
1444     uint32_t freq = var_InheritInteger( p_obj, CFG_PREFIX"tuner-frequency" );
1445     if( freq != (uint32_t)-1 )
1446     {
1447         struct v4l2_frequency frequency = {
1448             .tuner = p_sys->i_tuner,
1449             .type = p_sys->i_tuner_type,
1450             .frequency = freq / 62.5,
1451         };
1452
1453         if( v4l2_ioctl( i_fd, VIDIOC_S_FREQUENCY, &frequency ) < 0 )
1454         {
1455             msg_Err( p_obj, "cannot set tuner frequency: %m" );
1456             goto error;
1457         }
1458         msg_Dbg( p_obj, "tuner frequency set" );
1459     }
1460
1461     /* Set the tuner's audio mode */
1462     if( p_sys->i_tuner_audio_mode >= 0 )
1463     {
1464         struct v4l2_tuner tuner = {
1465             .index = p_sys->i_tuner,
1466             .audmode = p_sys->i_tuner_audio_mode,
1467         };
1468
1469         if( v4l2_ioctl( i_fd, VIDIOC_S_TUNER, &tuner ) < 0 )
1470         {
1471             msg_Err( p_obj, "cannot set tuner audio mode: %m" );
1472             goto error;
1473         }
1474         msg_Dbg( p_obj, "tuner audio mode set" );
1475     }
1476
1477     /* Set audio input */
1478     if( p_sys->i_audio_input != (uint32_t)-1 )
1479     {
1480         struct v4l2_audio audio = {
1481             .index = p_sys->i_audio_input,
1482             .mode = 0, /* TODO: AVL support */
1483         };
1484
1485         if( v4l2_ioctl( i_fd, VIDIOC_S_AUDIO, &audio ) < 0 )
1486         {
1487             msg_Err( p_obj, "cannot set audio input %u: %m",
1488                      p_sys->i_audio_input );
1489             goto error;
1490         }
1491         msg_Dbg( p_obj, "audio input set to %u",
1492                  p_sys->i_audio_input );
1493     }
1494
1495
1496     /* TODO: Move the resolution stuff up here */
1497     /* if MPEG encoder card, no need to do anything else after this */
1498     ControlList( p_obj, i_fd, b_demux );
1499
1500     /* Reset Cropping */
1501     memset( &cropcap, 0, sizeof(cropcap) );
1502     cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1503     if( v4l2_ioctl( i_fd, VIDIOC_CROPCAP, &cropcap ) >= 0 )
1504     {
1505         crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1506         crop.c = cropcap.defrect; /* reset to default */
1507         if( crop.c.width > 0 && crop.c.height > 0 ) /* Fix for fm tuners */
1508         {
1509             if( v4l2_ioctl( i_fd, VIDIOC_S_CROP, &crop ) < 0 )
1510             {
1511                 switch( errno )
1512                 {
1513                     case EINVAL:
1514                         /* Cropping not supported. */
1515                         break;
1516                     default:
1517                         /* Errors ignored. */
1518                         break;
1519                 }
1520             }
1521         }
1522     }
1523
1524     /* Try and find default resolution if not specified */
1525     memset( &fmt, 0, sizeof(fmt) );
1526     fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1527
1528     if( p_sys->i_width <= 0 || p_sys->i_height <= 0 )
1529     {
1530         /* Use current width and height settings */
1531         if( v4l2_ioctl( i_fd, VIDIOC_G_FMT, &fmt ) < 0 )
1532         {
1533             msg_Err( p_obj, "cannot get default width and height: %m" );
1534             goto error;
1535         }
1536
1537         msg_Dbg( p_obj, "found default width and height of %ux%u",
1538                  fmt.fmt.pix.width, fmt.fmt.pix.height );
1539
1540         if( p_sys->i_width < 0 || p_sys->i_height < 0 )
1541         {
1542             msg_Dbg( p_obj, "will try to find optimal width and height" );
1543         }
1544     }
1545     else
1546     {
1547         /* Use user specified width and height */
1548         msg_Dbg( p_obj, "trying specified size %dx%d",
1549                  p_sys->i_width, p_sys->i_height );
1550         fmt.fmt.pix.width = p_sys->i_width;
1551         fmt.fmt.pix.height = p_sys->i_height;
1552     }
1553
1554     fmt.fmt.pix.field = V4L2_FIELD_NONE;
1555
1556     float f_fps;
1557     if (b_demux)
1558     {
1559         demux_t *p_demux = (demux_t *) p_obj;
1560         char *reqchroma = var_InheritString( p_obj, CFG_PREFIX"chroma" );
1561
1562         /* Test and set Chroma */
1563         fmt.fmt.pix.pixelformat = 0;
1564         if( reqchroma != NULL )
1565         {
1566             /* User specified chroma */
1567             const vlc_fourcc_t i_requested_fourcc =
1568                 vlc_fourcc_GetCodecFromString( VIDEO_ES, reqchroma );
1569
1570             for( int i = 0; v4l2chroma_to_fourcc[i].i_v4l2 != 0; i++ )
1571             {
1572                 if( v4l2chroma_to_fourcc[i].i_fourcc == i_requested_fourcc )
1573                 {
1574                     fmt.fmt.pix.pixelformat = v4l2chroma_to_fourcc[i].i_v4l2;
1575                     break;
1576                 }
1577             }
1578             /* Try and set user chroma */
1579             bool b_error = !IsPixelFormatSupported( p_demux, fmt.fmt.pix.pixelformat );
1580             if( !b_error && fmt.fmt.pix.pixelformat )
1581             {
1582                 if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 )
1583                 {
1584                     fmt.fmt.pix.field = V4L2_FIELD_ANY;
1585                     if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 )
1586                     {
1587                         fmt.fmt.pix.field = V4L2_FIELD_NONE;
1588                         b_error = true;
1589                     }
1590                 }
1591             }
1592             if( b_error )
1593             {
1594                 msg_Warn( p_obj, "requested chroma %s not supported. "
1595                           " Trying default.", reqchroma );
1596                 fmt.fmt.pix.pixelformat = 0;
1597             }
1598             free( reqchroma );
1599         }
1600
1601         /* If no user specified chroma, find best */
1602         /* This also decides if MPEG encoder card or not */
1603         if( !fmt.fmt.pix.pixelformat )
1604         {
1605             unsigned int i;
1606             for( i = 0; i < ARRAY_SIZE( p_chroma_fallbacks ); i++ )
1607             {
1608                 fmt.fmt.pix.pixelformat = p_chroma_fallbacks[i];
1609                 if( IsPixelFormatSupported( p_demux, fmt.fmt.pix.pixelformat ) )
1610                 {
1611                     if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) >= 0 )
1612                         break;
1613                     fmt.fmt.pix.field = V4L2_FIELD_ANY;
1614                     if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) >= 0 )
1615                         break;
1616                     fmt.fmt.pix.field = V4L2_FIELD_NONE;
1617                 }
1618             }
1619             if( i == ARRAY_SIZE( p_chroma_fallbacks ) )
1620             {
1621                 msg_Warn( p_demux, "Could not select any of the default chromas; attempting to open as MPEG encoder card (access)" );
1622                 goto error;
1623             }
1624         }
1625
1626         if( p_sys->i_width < 0 || p_sys->i_height < 0 )
1627         {
1628             f_fps = var_InheritFloat( p_obj, CFG_PREFIX"fps" );
1629             if( f_fps <= 0. )
1630             {
1631                 f_fps = GetAbsoluteMaxFrameRate( p_demux, i_fd,
1632                                                  fmt.fmt.pix.pixelformat );
1633                 msg_Dbg( p_demux, "Found maximum framerate of %f", f_fps );
1634             }
1635             uint32_t i_width, i_height;
1636             GetMaxDimensions( p_demux, i_fd,
1637                               fmt.fmt.pix.pixelformat, f_fps,
1638                               &i_width, &i_height );
1639             if( i_width || i_height )
1640             {
1641                 msg_Dbg( p_demux, "Found optimal dimensions for framerate %f "
1642                                   "of %ux%u", f_fps, i_width, i_height );
1643                 fmt.fmt.pix.width = i_width;
1644                 fmt.fmt.pix.height = i_height;
1645                 if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 )
1646                 {
1647                     msg_Err( p_obj, "Cannot set size to optimal dimensions "
1648                                     "%ux%u", i_width, i_height );
1649                     goto error;
1650                 }
1651             }
1652             else
1653             {
1654                 msg_Warn( p_obj, "Could not find optimal width and height, "
1655                                  "falling back to driver default." );
1656             }
1657         }
1658     }
1659
1660     p_sys->i_width = fmt.fmt.pix.width;
1661     p_sys->i_height = fmt.fmt.pix.height;
1662
1663     if( v4l2_ioctl( i_fd, VIDIOC_G_FMT, &fmt ) < 0 ) {;}
1664     /* Print extra info */
1665     msg_Dbg( p_obj, "Driver requires at most %d bytes to store a complete image", fmt.fmt.pix.sizeimage );
1666     /* Check interlacing */
1667     switch( fmt.fmt.pix.field )
1668     {
1669         case V4L2_FIELD_NONE:
1670             msg_Dbg( p_obj, "Interlacing setting: progressive" );
1671             break;
1672         case V4L2_FIELD_TOP:
1673             msg_Dbg( p_obj, "Interlacing setting: top field only" );
1674             break;
1675         case V4L2_FIELD_BOTTOM:
1676             msg_Dbg( p_obj, "Interlacing setting: bottom field only" );
1677             break;
1678         case V4L2_FIELD_INTERLACED:
1679             msg_Dbg( p_obj, "Interlacing setting: interleaved (bottom top if M/NTSC, top bottom otherwise)" );
1680             if( bottom_first )
1681                 p_sys->i_block_flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
1682             else
1683                 p_sys->i_block_flags = BLOCK_FLAG_TOP_FIELD_FIRST;
1684             break;
1685         case V4L2_FIELD_SEQ_TB:
1686             msg_Dbg( p_obj, "Interlacing setting: sequential top bottom (TODO)" );
1687             break;
1688         case V4L2_FIELD_SEQ_BT:
1689             msg_Dbg( p_obj, "Interlacing setting: sequential bottom top (TODO)" );
1690             break;
1691         case V4L2_FIELD_ALTERNATE:
1692             msg_Dbg( p_obj, "Interlacing setting: alternate fields (TODO)" );
1693             p_sys->i_height = p_sys->i_height * 2;
1694             break;
1695         case V4L2_FIELD_INTERLACED_TB:
1696             msg_Dbg( p_obj, "Interlacing setting: interleaved top bottom" );
1697             p_sys->i_block_flags = BLOCK_FLAG_TOP_FIELD_FIRST;
1698             break;
1699         case V4L2_FIELD_INTERLACED_BT:
1700             msg_Dbg( p_obj, "Interlacing setting: interleaved bottom top" );
1701             p_sys->i_block_flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
1702             break;
1703         default:
1704             msg_Warn( p_obj, "Interlacing setting: unknown type (%d)",
1705                       fmt.fmt.pix.field );
1706             break;
1707     }
1708
1709     /* Look up final fourcc */
1710     p_sys->i_fourcc = 0;
1711     for( int i = 0; v4l2chroma_to_fourcc[i].i_fourcc != 0; i++ )
1712     {
1713         if( v4l2chroma_to_fourcc[i].i_v4l2 == fmt.fmt.pix.pixelformat )
1714         {
1715             p_sys->i_fourcc = v4l2chroma_to_fourcc[i].i_fourcc;
1716             es_format_Init( &es_fmt, VIDEO_ES, p_sys->i_fourcc );
1717             es_fmt.video.i_rmask = v4l2chroma_to_fourcc[i].i_rmask;
1718             es_fmt.video.i_gmask = v4l2chroma_to_fourcc[i].i_gmask;
1719             es_fmt.video.i_bmask = v4l2chroma_to_fourcc[i].i_bmask;
1720             break;
1721         }
1722     }
1723
1724     /* Buggy driver paranoia */
1725     i_min = fmt.fmt.pix.width * 2;
1726     if( fmt.fmt.pix.bytesperline < i_min )
1727         fmt.fmt.pix.bytesperline = i_min;
1728     i_min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
1729     if( fmt.fmt.pix.sizeimage < i_min )
1730         fmt.fmt.pix.sizeimage = i_min;
1731
1732 #ifdef VIDIOC_ENUM_FRAMEINTERVALS
1733     /* This is new in Linux 2.6.19 */
1734     /* List supported frame rates */
1735     struct v4l2_frmivalenum frmival;
1736     memset( &frmival, 0, sizeof(frmival) );
1737     frmival.pixel_format = fmt.fmt.pix.pixelformat;
1738     frmival.width = p_sys->i_width;
1739     frmival.height = p_sys->i_height;
1740     if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival ) >= 0 )
1741     {
1742         char psz_fourcc[5];
1743         memset( &psz_fourcc, 0, sizeof( psz_fourcc ) );
1744         vlc_fourcc_to_char( p_sys->i_fourcc, &psz_fourcc );
1745         msg_Dbg( p_obj, "supported frame intervals for %4.4s, %dx%d:",
1746                  psz_fourcc, frmival.width, frmival.height );
1747         switch( frmival.type )
1748         {
1749             case V4L2_FRMIVAL_TYPE_DISCRETE:
1750                 do
1751                 {
1752                     msg_Dbg( p_obj, "    supported frame interval: %d/%d",
1753                              frmival.discrete.numerator,
1754                              frmival.discrete.denominator );
1755                     frmival.index++;
1756                 } while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival ) >= 0 );
1757                 break;
1758             case V4L2_FRMIVAL_TYPE_STEPWISE:
1759                 msg_Dbg( p_obj, "    supported frame intervals: %d/%d to "
1760                          "%d/%d using %d/%d increments",
1761                          frmival.stepwise.min.numerator,
1762                          frmival.stepwise.min.denominator,
1763                          frmival.stepwise.max.numerator,
1764                          frmival.stepwise.max.denominator,
1765                          frmival.stepwise.step.numerator,
1766                          frmival.stepwise.step.denominator );
1767                 break;
1768             case V4L2_FRMIVAL_TYPE_CONTINUOUS:
1769                 msg_Dbg( p_obj, "    supported frame intervals: %d/%d to %d/%d",
1770                          frmival.stepwise.min.numerator,
1771                          frmival.stepwise.min.denominator,
1772                          frmival.stepwise.max.numerator,
1773                          frmival.stepwise.max.denominator );
1774                 break;
1775         }
1776     }
1777 #endif
1778
1779
1780     /* Init IO method */
1781     switch( p_sys->io )
1782     {
1783     case IO_METHOD_READ:
1784         if( b_demux && InitRead( p_obj, p_sys, fmt.fmt.pix.sizeimage ) )
1785             goto error;
1786         break;
1787
1788     case IO_METHOD_MMAP:
1789         if( InitMmap( p_obj, p_sys, i_fd ) )
1790             goto error;
1791         break;
1792
1793     case IO_METHOD_USERPTR:
1794         if( InitUserP( p_obj, p_sys, i_fd, fmt.fmt.pix.sizeimage ) )
1795             goto error;
1796         break;
1797     }
1798
1799     if( b_demux )
1800     {
1801         /* Add */
1802         es_fmt.video.i_width  = p_sys->i_width;
1803         es_fmt.video.i_height = p_sys->i_height;
1804
1805         /* Get aspect-ratio */
1806         es_fmt.video.i_sar_num = p_sys->i_aspect    * es_fmt.video.i_height;
1807         es_fmt.video.i_sar_den = VOUT_ASPECT_FACTOR * es_fmt.video.i_width;
1808
1809         /* Framerate */
1810         es_fmt.video.i_frame_rate = lround(f_fps * 1000000.);
1811         es_fmt.video.i_frame_rate_base = 1000000;
1812
1813         demux_t *p_demux = (demux_t *) p_obj;
1814         msg_Dbg( p_demux, "added new video es %4.4s %dx%d",
1815             (char*)&es_fmt.i_codec, es_fmt.video.i_width, es_fmt.video.i_height );
1816         msg_Dbg( p_obj, " frame rate: %f", f_fps );
1817
1818         p_sys->p_es = es_out_Add( p_demux->out, &es_fmt );
1819     }
1820
1821     /* Start Capture */
1822
1823     switch( p_sys->io )
1824     {
1825     case IO_METHOD_READ:
1826         /* Nothing to do */
1827         break;
1828
1829     case IO_METHOD_MMAP:
1830         for (unsigned int i = 0; i < p_sys->i_nbuffers; ++i)
1831         {
1832             struct v4l2_buffer buf;
1833
1834             memset( &buf, 0, sizeof(buf) );
1835             buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1836             buf.memory = V4L2_MEMORY_MMAP;
1837             buf.index = i;
1838
1839             if( v4l2_ioctl( i_fd, VIDIOC_QBUF, &buf ) < 0 )
1840             {
1841                 msg_Err( p_obj, "VIDIOC_QBUF failed" );
1842                 goto error;
1843             }
1844         }
1845
1846         buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1847         if( v4l2_ioctl( i_fd, VIDIOC_STREAMON, &buf_type ) < 0 )
1848         {
1849             msg_Err( p_obj, "VIDIOC_STREAMON failed" );
1850             goto error;
1851         }
1852
1853         break;
1854
1855     case IO_METHOD_USERPTR:
1856         for( unsigned int i = 0; i < p_sys->i_nbuffers; ++i )
1857         {
1858             struct v4l2_buffer buf;
1859
1860             memset( &buf, 0, sizeof(buf) );
1861             buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1862             buf.memory = V4L2_MEMORY_USERPTR;
1863             buf.index = i;
1864             buf.m.userptr = (unsigned long)p_sys->p_buffers[i].start;
1865             buf.length = p_sys->p_buffers[i].length;
1866
1867             if( v4l2_ioctl( i_fd, VIDIOC_QBUF, &buf ) < 0 )
1868             {
1869                 msg_Err( p_obj, "VIDIOC_QBUF failed" );
1870                 goto error;
1871             }
1872         }
1873
1874         buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1875         if( v4l2_ioctl( i_fd, VIDIOC_STREAMON, &buf_type ) < 0 )
1876         {
1877             msg_Err( p_obj, "VIDIOC_STREAMON failed" );
1878             goto error;
1879         }
1880         break;
1881     }
1882
1883     return i_fd;
1884
1885 error:
1886     v4l2_close( i_fd );
1887     return -1;
1888 }
1889
1890 /*****************************************************************************
1891  * ProbeVideoDev: probe video for capabilities
1892  *****************************************************************************/
1893 static int ProbeVideoDev( vlc_object_t *p_obj, demux_sys_t *p_sys, int i_fd )
1894 {
1895     /* Get device capabilites */
1896     struct v4l2_capability cap;
1897
1898     if( v4l2_ioctl( i_fd, VIDIOC_QUERYCAP, &cap ) < 0 )
1899     {
1900         msg_Err( p_obj, "cannot get video capabilities: %m" );
1901         return -1;
1902     }
1903
1904     msg_Dbg( p_obj, "device %s using driver %s (version %u.%u.%u) on %s",
1905             cap.card, cap.driver, (cap.version >> 16) & 0xFF,
1906             (cap.version >> 8) & 0xFF, cap.version & 0xFF, cap.bus_info );
1907     msg_Dbg( p_obj, "the device has the capabilities:"
1908              " (%c) Video Capture, (%c) Audio, (%c) Tuner, (%c) Radio",
1909              ( cap.capabilities & V4L2_CAP_VIDEO_CAPTURE  ? 'X':' '),
1910              ( cap.capabilities & V4L2_CAP_AUDIO  ? 'X':' '),
1911              ( cap.capabilities & V4L2_CAP_TUNER  ? 'X':' '),
1912              ( cap.capabilities & V4L2_CAP_RADIO  ? 'X':' ') );
1913     msg_Dbg( p_obj, "supported I/O methods are:"
1914              " (%c) Read/Write, (%c) Streaming, (%c) Asynchronous",
1915             ( cap.capabilities & V4L2_CAP_READWRITE ? 'X':' ' ),
1916             ( cap.capabilities & V4L2_CAP_STREAMING ? 'X':' ' ),
1917             ( cap.capabilities & V4L2_CAP_ASYNCIO ? 'X':' ' ) );
1918
1919     if( cap.capabilities & V4L2_CAP_STREAMING )
1920         p_sys->io = IO_METHOD_MMAP;
1921     else if( cap.capabilities & V4L2_CAP_READWRITE )
1922         p_sys->io = IO_METHOD_READ;
1923     else
1924     {
1925         msg_Err( p_obj, "no supported I/O method" );
1926         return -1;
1927     }
1928
1929     if( cap.capabilities & V4L2_CAP_RDS_CAPTURE )
1930         msg_Dbg( p_obj, "device supports RDS" );
1931
1932 #ifdef V4L2_CAP_HW_FREQ_SEEK
1933     if( cap.capabilities & V4L2_CAP_HW_FREQ_SEEK )
1934         msg_Dbg( p_obj, "device supports hardware frequency seeking" );
1935 #endif
1936     if( cap.capabilities & V4L2_CAP_VBI_CAPTURE )
1937         msg_Dbg( p_obj, "device supports raw VBI capture" );
1938
1939     if( cap.capabilities & V4L2_CAP_SLICED_VBI_CAPTURE )
1940         msg_Dbg( p_obj, "device supports sliced VBI capture" );
1941
1942     /* Now, enumerate all the video inputs. This is useless at the moment
1943        since we have no way to present that info to the user except with
1944        debug messages */
1945
1946     if( cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
1947     {
1948         struct v4l2_input input;
1949
1950         input.index = 0;
1951         while( v4l2_ioctl( i_fd, VIDIOC_ENUMINPUT, &input ) >= 0 )
1952         {
1953             msg_Dbg( p_obj, "video input %u (%s) has type: %s %c",
1954                      input.index, input.name,
1955                      input.type == V4L2_INPUT_TYPE_TUNER
1956                          ? "Tuner adapter" : "External analog input",
1957                      input.index == p_sys->i_selected_input ? '*' : ' ' );
1958             input.index++;
1959         }
1960     }
1961
1962     /* Probe audio inputs */
1963     if( cap.capabilities & V4L2_CAP_AUDIO )
1964     {
1965         struct v4l2_audio audio = { .index = 0 };
1966
1967         while( v4l2_ioctl( i_fd, VIDIOC_ENUMAUDIO, &audio ) >= 0 )
1968         {
1969             msg_Dbg( p_obj, "audio input %u (%s) is %s%s %c", audio.index,
1970                      audio.name,
1971                      audio.capability & V4L2_AUDCAP_STEREO ? "Stereo" : "Mono",
1972                      audio.capability & V4L2_AUDCAP_AVL
1973                          ? " (Automatic Volume Level supported)" : "",
1974                      p_sys->i_audio_input == audio.index );
1975             audio.index++;
1976         }
1977     }
1978
1979     /* List tuner caps */
1980     if( cap.capabilities & V4L2_CAP_TUNER )
1981     {
1982         struct v4l2_tuner tuner;
1983
1984         tuner.index = 0;
1985         while( v4l2_ioctl( i_fd, VIDIOC_G_TUNER, &tuner ) >= 0 )
1986         {
1987             if( tuner.index == p_sys->i_tuner )
1988                 p_sys->i_tuner_type = tuner.type;
1989
1990             const char *unit =
1991                 (tuner.capability & V4L2_TUNER_CAP_LOW) ? "Hz" : "kHz";
1992             msg_Dbg( p_obj, "tuner %u (%s) has type: %s, "
1993                      "frequency range: %.1f %s -> %.1f %s", tuner.index,
1994                      tuner.name,
1995                      tuner.type == V4L2_TUNER_RADIO ? "Radio" : "Analog TV",
1996                      tuner.rangelow * 62.5, unit,
1997                      tuner.rangehigh * 62.5, unit );
1998
1999             struct v4l2_frequency frequency = { .tuner = tuner.index };
2000             if( v4l2_ioctl( i_fd, VIDIOC_G_FREQUENCY, &frequency ) < 0 )
2001             {
2002                 msg_Err( p_obj, "cannot get tuner frequency: %m" );
2003                 return -1;
2004             }
2005             msg_Dbg( p_obj, "tuner %u (%s) frequency: %.1f %s", tuner.index,
2006                      tuner.name, frequency.frequency * 62.5, unit );
2007
2008             tuner.index++;
2009         }
2010     }
2011
2012     /* Probe for available chromas */
2013     if( cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
2014     {
2015         struct v4l2_fmtdesc codec;
2016
2017         unsigned i_index = 0;
2018         memset( &codec, 0, sizeof(codec) );
2019         codec.index = i_index;
2020         codec.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2021
2022         while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FMT, &codec ) >= 0 )
2023         {
2024             if( codec.index != i_index )
2025                 break;
2026             i_index++;
2027             codec.index = i_index;
2028         }
2029
2030         p_sys->i_codec = i_index;
2031
2032         free( p_sys->p_codecs );
2033         p_sys->p_codecs = calloc( 1, p_sys->i_codec * sizeof( struct v4l2_fmtdesc ) );
2034
2035         for( i_index = 0; i_index < p_sys->i_codec; i_index++ )
2036         {
2037             p_sys->p_codecs[i_index].index = i_index;
2038             p_sys->p_codecs[i_index].type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2039
2040             if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FMT, &p_sys->p_codecs[i_index] ) < 0 )
2041             {
2042                 msg_Err( p_obj, "cannot get codec description: %m" );
2043                 return -1;
2044             }
2045
2046             /* only print if vlc supports the format */
2047             char psz_fourcc_v4l2[5];
2048             memset( &psz_fourcc_v4l2, 0, sizeof( psz_fourcc_v4l2 ) );
2049             vlc_fourcc_to_char( p_sys->p_codecs[i_index].pixelformat,
2050                                 &psz_fourcc_v4l2 );
2051             bool b_codec_supported = false;
2052             for( int i = 0; v4l2chroma_to_fourcc[i].i_v4l2 != 0; i++ )
2053             {
2054                 if( v4l2chroma_to_fourcc[i].i_v4l2 == p_sys->p_codecs[i_index].pixelformat )
2055                 {
2056                     b_codec_supported = true;
2057
2058                     char psz_fourcc[5];
2059                     memset( &psz_fourcc, 0, sizeof( psz_fourcc ) );
2060                     vlc_fourcc_to_char( v4l2chroma_to_fourcc[i].i_fourcc,
2061                                         &psz_fourcc );
2062                     msg_Dbg( p_obj, "device supports chroma %4.4s [%s, %s]",
2063                                 psz_fourcc,
2064                                 p_sys->p_codecs[i_index].description,
2065                                 psz_fourcc_v4l2 );
2066
2067 #ifdef VIDIOC_ENUM_FRAMESIZES
2068                     /* This is new in Linux 2.6.19 */
2069                     /* List valid frame sizes for this format */
2070                     struct v4l2_frmsizeenum frmsize;
2071                     memset( &frmsize, 0, sizeof(frmsize) );
2072                     frmsize.pixel_format = p_sys->p_codecs[i_index].pixelformat;
2073                     if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize ) < 0 )
2074                     {
2075                         /* Not all devices support this ioctl */
2076                         msg_Warn( p_obj, "Unable to query for frame sizes" );
2077                     }
2078                     else
2079                     {
2080                         switch( frmsize.type )
2081                         {
2082                             case V4L2_FRMSIZE_TYPE_DISCRETE:
2083                                 do
2084                                 {
2085                                     msg_Dbg( p_obj,
2086                 "    device supports size %dx%d",
2087                 frmsize.discrete.width, frmsize.discrete.height );
2088                                     frmsize.index++;
2089                                 } while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize ) >= 0 );
2090                                 break;
2091                             case V4L2_FRMSIZE_TYPE_STEPWISE:
2092                                 msg_Dbg( p_obj,
2093                 "    device supports sizes %dx%d to %dx%d using %dx%d increments",
2094                 frmsize.stepwise.min_width, frmsize.stepwise.min_height,
2095                 frmsize.stepwise.max_width, frmsize.stepwise.max_height,
2096                 frmsize.stepwise.step_width, frmsize.stepwise.step_height );
2097                                 break;
2098                             case V4L2_FRMSIZE_TYPE_CONTINUOUS:
2099                                 msg_Dbg( p_obj,
2100                 "    device supports all sizes %dx%d to %dx%d",
2101                 frmsize.stepwise.min_width, frmsize.stepwise.min_height,
2102                 frmsize.stepwise.max_width, frmsize.stepwise.max_height );
2103                                 break;
2104                         }
2105                     }
2106 #endif
2107                 }
2108             }
2109             if( !b_codec_supported )
2110             {
2111                     msg_Dbg( p_obj,
2112                          "device codec %4.4s (%s) not supported",
2113                          psz_fourcc_v4l2,
2114                          p_sys->p_codecs[i_index].description );
2115             }
2116         }
2117     }
2118     return 0;
2119 }