]> git.sesse.net Git - vlc/blob - modules/access/v4l2/video.c
V4L2: make loudness, horizontal flip and vertical flip booleans
[vlc] / 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_fs.h>
43 #include <vlc_demux.h>
44
45 #include <math.h>
46 #include <assert.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <sys/ioctl.h>
50 #include <sys/mman.h>
51 #include <poll.h>
52
53 /*****************************************************************************
54  * Module descriptior
55  *****************************************************************************/
56
57 #define DEVICE_TEXT N_( "Device" )
58 #define DEVICE_LONGTEXT N_( \
59     "Video device (Default: /dev/video0)." )
60 #define STANDARD_TEXT N_( "Standard" )
61 #define STANDARD_LONGTEXT N_( \
62     "Video standard (Default, SECAM, PAL, or NTSC)." )
63 #define CHROMA_TEXT N_("Video input chroma format")
64 #define CHROMA_LONGTEXT N_( \
65     "Force the Video4Linux2 video device to use a specific chroma format " \
66     "(eg. I420 or I422 for raw images, MJPG for M-JPEG compressed input) " \
67     "(Complete list: GREY, I240, RV16, RV15, RV24, RV32, YUY2, YUYV, UYVY, " \
68     "I41N, I422, I420, I411, I410, MJPG)")
69 #define INPUT_TEXT N_( "Input" )
70 #define INPUT_LONGTEXT N_( \
71     "Input of the card to use (see debug)." )
72 #define AUDIO_INPUT_TEXT N_( "Audio input" )
73 #define AUDIO_INPUT_LONGTEXT N_( \
74     "Audio input of the card to use (see debug)." )
75 #define WIDTH_TEXT N_( "Width" )
76 #define WIDTH_LONGTEXT N_( \
77     "Force width (-1 for autodetect, 0 for driver default)." )
78 #define HEIGHT_TEXT N_( "Height" )
79 #define HEIGHT_LONGTEXT N_( \
80     "Force height (-1 for autodetect, 0 for driver default)." )
81 #define FPS_TEXT N_( "Framerate" )
82 #define FPS_LONGTEXT N_( "Framerate to capture, if applicable " \
83     "(0 for autodetect)." )
84
85 #ifdef HAVE_LIBV4L2
86 #define LIBV4L2_TEXT N_( "Use libv4l2" )
87 #define LIBV4L2_LONGTEXT N_( \
88     "Force usage of the libv4l2 wrapper." )
89 #endif
90
91 #define CTRL_RESET_TEXT N_( "Reset v4l2 controls" )
92 #define CTRL_RESET_LONGTEXT N_( \
93     "Reset controls to defaults provided by the v4l2 driver." )
94 #define BRIGHTNESS_TEXT N_( "Brightness" )
95 #define BRIGHTNESS_LONGTEXT N_( \
96     "Brightness of the video input (if supported by the v4l2 driver)." )
97 #define CONTRAST_TEXT N_( "Contrast" )
98 #define CONTRAST_LONGTEXT N_( \
99     "Contrast of the video input (if supported by the v4l2 driver)." )
100 #define SATURATION_TEXT N_( "Saturation" )
101 #define SATURATION_LONGTEXT N_( \
102     "Saturation of the video input (if supported by the v4l2 driver)." )
103 #define HUE_TEXT N_( "Hue" )
104 #define HUE_LONGTEXT N_( \
105     "Hue of the video input (if supported by the v4l2 driver)." )
106 #define BLACKLEVEL_TEXT N_( "Black level" )
107 #define BLACKLEVEL_LONGTEXT N_( \
108     "Black level of the video input (if supported by the v4l2 driver)." )
109 #define AUTOWHITEBALANCE_TEXT N_( "Auto white balance" )
110 #define AUTOWHITEBALANCE_LONGTEXT N_( \
111     "Automatically set the white balance of the video input " \
112     "(if supported by the v4l2 driver)." )
113 #define DOWHITEBALANCE_TEXT N_( "Do white balance" )
114 #define DOWHITEBALANCE_LONGTEXT N_( \
115     "Trigger a white balancing action, useless if auto white balance is " \
116     "activated (if supported by the v4l2 driver)." )
117 #define REDBALANCE_TEXT N_( "Red balance" )
118 #define REDBALANCE_LONGTEXT N_( \
119     "Red balance of the video input (if supported by the v4l2 driver)." )
120 #define BLUEBALANCE_TEXT N_( "Blue balance" )
121 #define BLUEBALANCE_LONGTEXT N_( \
122     "Blue balance of the video input (if supported by the v4l2 driver)." )
123 #define GAMMA_TEXT N_( "Gamma" )
124 #define GAMMA_LONGTEXT N_( \
125     "Gamma of the video input (if supported by the v4l2 driver)." )
126 #define EXPOSURE_TEXT N_( "Exposure" )
127 #define EXPOSURE_LONGTEXT N_( \
128     "Exposure of the video input (if supported by the v4L2 driver)." )
129 #define AUTOGAIN_TEXT N_( "Automatic gain/exposure" )
130 #define AUTOGAIN_LONGTEXT N_( \
131     "Automatically set the video gain/exposure (if supported by the " \
132     "v4l2 driver)." )
133 #define GAIN_TEXT N_( "Gain" )
134 #define GAIN_LONGTEXT N_( \
135     "Video input's gain (if supported by the v4l2 driver)." )
136 #define HFLIP_TEXT N_( "Horizontal flip" )
137 #define HFLIP_LONGTEXT N_( \
138     "Flip the video horizontally (if supported by the v4l2 driver)." )
139 #define VFLIP_TEXT N_( "Vertical flip" )
140 #define VFLIP_LONGTEXT N_( \
141     "Flip the video vertically (if supported by the v4l2 driver)." )
142 #define HCENTER_TEXT N_( "Horizontal centering" )
143 #define HCENTER_LONGTEXT N_( \
144     "Set the camera's horizontal centering (if supported by the v4l2 driver)." )
145 #define VCENTER_TEXT N_( "Vertical centering" )
146 #define VCENTER_LONGTEXT N_( \
147     "Set the camera's vertical centering (if supported by the v4l2 driver)." )
148
149 #define AUDIO_VOLUME_TEXT N_( "Volume" )
150 #define AUDIO_VOLUME_LONGTEXT N_( \
151     "Volume of the audio input (if supported by the v4l2 driver)." )
152 #define AUDIO_BALANCE_TEXT N_( "Balance" )
153 #define AUDIO_BALANCE_LONGTEXT N_( \
154     "Balance of the audio input (if supported by the v4l2 driver)." )
155 #define AUDIO_MUTE_TEXT N_( "Mute" )
156 #define AUDIO_MUTE_LONGTEXT N_( \
157     "Mute audio input (if supported by the v4l2 driver)." )
158 #define AUDIO_BASS_TEXT N_( "Bass" )
159 #define AUDIO_BASS_LONGTEXT N_( \
160     "Bass level of the audio input (if supported by the v4l2 driver)." )
161 #define AUDIO_TREBLE_TEXT N_( "Treble" )
162 #define AUDIO_TREBLE_LONGTEXT N_( \
163     "Treble level of the audio input (if supported by the v4l2 driver)." )
164 #define AUDIO_LOUDNESS_TEXT N_( "Loudness mode" )
165 #define AUDIO_LOUDNESS_LONGTEXT N_( \
166     "Loudness mode a.k.a. bass boost (if supported by the v4l2 driver)." )
167
168 #define S_CTRLS_TEXT N_("v4l2 driver controls")
169 #define S_CTRLS_LONGTEXT N_( \
170     "Set the v4l2 driver controls to the values specified using a comma " \
171     "separated list optionally encapsulated by curly braces " \
172     "(e.g.: {video_bitrate=6000000,audio_crc=0,stream_type=3} ). " \
173     "To list available controls, increase verbosity (-vvv) " \
174     "or use the v4l2-ctl application." )
175
176 #define TUNER_TEXT N_("Tuner id")
177 #define TUNER_LONGTEXT N_( \
178     "Tuner id (see debug output)." )
179 #define FREQUENCY_TEXT N_("Frequency")
180 #define FREQUENCY_LONGTEXT N_( \
181     "Tuner frequency in Hz or kHz (see debug output)" )
182 #define TUNER_AUDIO_MODE_TEXT N_("Audio mode")
183 #define TUNER_AUDIO_MODE_LONGTEXT N_( \
184     "Tuner audio mono/stereo and track selection." )
185
186 #define ASPECT_TEXT N_("Picture aspect-ratio n:m")
187 #define ASPECT_LONGTEXT N_("Define input picture aspect-ratio to use. Default is 4:3" )
188
189 static const int tristate_vlc[] = { -1, 0, 1 };
190 static const char *const tristate_user[] = {
191     N_("Unspecified"), N_("Off"), N_("On") };
192
193 static const v4l2_std_id standards_v4l2[] = { V4L2_STD_UNKNOWN, V4L2_STD_ALL,
194     V4L2_STD_PAL,     V4L2_STD_PAL_BG,   V4L2_STD_PAL_DK,
195     V4L2_STD_NTSC,
196     V4L2_STD_SECAM,   V4L2_STD_SECAM_DK,
197     V4L2_STD_525_60,  V4L2_STD_625_50,
198     V4L2_STD_ATSC,
199
200     V4L2_STD_MN,      V4L2_STD_B,        V4L2_STD_GH,       V4L2_STD_DK,
201
202     V4L2_STD_PAL_B,   V4L2_STD_PAL_B1,   V4L2_STD_PAL_G,    V4L2_STD_PAL_H,
203     V4L2_STD_PAL_I,   V4L2_STD_PAL_D,    V4L2_STD_PAL_D1,   V4L2_STD_PAL_K,
204     V4L2_STD_PAL_M,   V4L2_STD_PAL_N,    V4L2_STD_PAL_Nc,   V4L2_STD_PAL_60,
205     V4L2_STD_NTSC_M,  V4L2_STD_NTSC_M_JP,V4L2_STD_NTSC_443, V4L2_STD_NTSC_M_KR,
206     V4L2_STD_SECAM_B, V4L2_STD_SECAM_D,  V4L2_STD_SECAM_G,  V4L2_STD_SECAM_H,
207     V4L2_STD_SECAM_K, V4L2_STD_SECAM_K1, V4L2_STD_SECAM_L,  V4L2_STD_SECAM_LC,
208     V4L2_STD_ATSC_8_VSB, V4L2_STD_ATSC_16_VSB,
209 };
210 static const char *const standards_vlc[] = { "", "ALL",
211     /* Pseudo standards */
212     "PAL", "PAL_BG", "PAL_DK",
213     "NTSC",
214     "SECAM", "SECAM_DK",
215     "525_60", "625_50",
216     "ATSC",
217
218     /* Areas (PAL/NTSC or PAL/SECAM) */
219     "MN", "B", "GH", "DK",
220
221     /* Individual standards */
222     "PAL_B",          "PAL_B1",          "PAL_G",           "PAL_H",
223     "PAL_I",          "PAL_D",           "PAL_D1",          "PAL_K",
224     "PAL_M",          "PAL_N",           "PAL_Nc",          "PAL_60",
225     "NTSC_M",         "NTSC_M_JP",       "NTSC_443",        "NTSC_M_KR",
226     "SECAM_B",        "SECAM_D",         "SECAM_G",         "SECAM_H",
227     "SECAM_K",        "SECAM_K1",        "SECAM_L",         "SECAM_LC",
228     "ATSC_8_VSB",     "ATSC_16_VSB",
229 };
230 static const char *const standards_user[] = { N_("Undefined"), N_("All"),
231     "PAL",            "PAL B/G",         "PAL D/K",
232     "NTSC",
233     "SECAM",          "SECAM D/K",
234     N_("525 lines / 60 Hz"), N_("625 lines / 50 Hz"),
235     "ATSC",
236
237     "PAL/NTSC M/N",
238     "PAL/SECAM B",    "PAL/SECAM G/H",   "PAL/SECAM D/K",
239
240     "PAL B",          "PAL B1",          "PAL G",           "PAL H",
241     "PAL I",          "PAL D",           "PAL D1",          "PAL K",
242     "PAL M",          "PAL N",           N_("PAL N Argentina"), "PAL 60",
243     "NTSC M",        N_("NTSC M Japan"), "NTSC 443",  N_("NTSC M South Korea"),
244     "SECAM B",        "SECAM D",         "SECAM G",         "SECAM H",
245     "SECAM K",        "SECAM K1",        "SECAM L",         "SECAM L/C",
246     "ATSC 8-VSB",     "ATSC 16-VSB",
247 };
248
249 static const int i_tuner_audio_modes_list[] = {
250       -1, V4L2_TUNER_MODE_MONO, V4L2_TUNER_MODE_STEREO,
251       V4L2_TUNER_MODE_LANG1, V4L2_TUNER_MODE_LANG2,
252       V4L2_TUNER_MODE_SAP, V4L2_TUNER_MODE_LANG1_LANG2 };
253 static const char *const psz_tuner_audio_modes_list_text[] = {
254       N_("Unspecified"),
255       N_( "Mono" ),
256       N_( "Stereo" ),
257       N_( "Primary language (Analog TV tuners only)" ),
258       N_( "Secondary language (Analog TV tuners only)" ),
259       N_( "Second audio program (Analog TV tuners only)" ),
260       N_( "Primary language left, Secondary language right" ) };
261
262 #define V4L2_DEFAULT "/dev/video0"
263
264 #ifdef HAVE_MAEMO
265 # define DEFAULT_WIDTH  640
266 # define DEFAULT_HEIGHT 492
267 #endif
268
269 #ifndef DEFAULT_WIDTH
270 # define DEFAULT_WIDTH  (-1)
271 # define DEFAULT_HEIGHT (-1)
272 #endif
273
274 vlc_module_begin ()
275     set_shortname( N_("Video4Linux2") )
276     set_description( N_("Video4Linux2 input") )
277     set_category( CAT_INPUT )
278     set_subcategory( SUBCAT_INPUT_ACCESS )
279
280     set_section( N_( "Video input" ), NULL )
281     add_string( CFG_PREFIX "dev", "/dev/video0", DEVICE_TEXT, DEVICE_LONGTEXT,
282                  false )
283         change_safe()
284     add_string( CFG_PREFIX "standard", "",
285                 STANDARD_TEXT, STANDARD_LONGTEXT, false )
286         change_string_list( standards_vlc, standards_user, NULL )
287         change_safe()
288     add_string( CFG_PREFIX "chroma", NULL, CHROMA_TEXT, CHROMA_LONGTEXT,
289                 true )
290         change_safe()
291     add_integer( CFG_PREFIX "input", 0, INPUT_TEXT, INPUT_LONGTEXT,
292                 true )
293         change_integer_range( 0, 0xFFFFFFFE )
294         change_safe()
295     add_integer( CFG_PREFIX "audio-input", -1, AUDIO_INPUT_TEXT,
296                  AUDIO_INPUT_LONGTEXT, true )
297         change_integer_range( -1, 0xFFFFFFFE )
298         change_safe()
299     add_obsolete_integer( CFG_PREFIX "io" ) /* since 1.2.0 */
300     add_integer( CFG_PREFIX "width", DEFAULT_WIDTH, WIDTH_TEXT,
301                 WIDTH_LONGTEXT, true )
302         change_safe()
303     add_integer( CFG_PREFIX "height", DEFAULT_HEIGHT, HEIGHT_TEXT,
304                 HEIGHT_LONGTEXT, true )
305         change_safe()
306     add_string( CFG_PREFIX "aspect-ratio", "4:3", ASPECT_TEXT,
307               ASPECT_LONGTEXT, true )
308         change_safe()
309     add_float( CFG_PREFIX "fps", 0, FPS_TEXT, FPS_LONGTEXT, true )
310         change_safe()
311 #ifdef HAVE_LIBV4L2
312     add_bool( CFG_PREFIX "use-libv4l2", false, LIBV4L2_TEXT, LIBV4L2_LONGTEXT, true );
313 #endif
314
315     set_section( N_( "Tuner" ), NULL )
316     add_integer( CFG_PREFIX "tuner", 0, TUNER_TEXT, TUNER_LONGTEXT,
317                  true )
318         change_integer_range( 0, 0xFFFFFFFE )
319         change_safe()
320     add_integer( CFG_PREFIX "tuner-frequency", -1, FREQUENCY_TEXT,
321                  FREQUENCY_LONGTEXT, true )
322         change_integer_range( -1, 0xFFFFFFFE )
323         change_safe()
324     add_integer( CFG_PREFIX "tuner-audio-mode", -1, TUNER_AUDIO_MODE_TEXT,
325                  TUNER_AUDIO_MODE_LONGTEXT, true )
326         change_integer_list( i_tuner_audio_modes_list,
327                              psz_tuner_audio_modes_list_text )
328         change_safe()
329
330     set_section( N_( "Controls" ),
331                  N_( "v4l2 driver controls, if supported by your v4l2 driver." ) )
332     add_bool( CFG_PREFIX "controls-reset", false, CTRL_RESET_TEXT,
333               CTRL_RESET_LONGTEXT, true )
334         change_safe()
335     add_integer( CFG_PREFIX "brightness", -1, BRIGHTNESS_TEXT,
336                  BRIGHTNESS_LONGTEXT, true )
337     add_integer( CFG_PREFIX "contrast", -1, CONTRAST_TEXT,
338                  CONTRAST_LONGTEXT, true )
339     add_integer( CFG_PREFIX "saturation", -1, SATURATION_TEXT,
340                  SATURATION_LONGTEXT, true )
341     add_integer( CFG_PREFIX "hue", -1, HUE_TEXT,
342                  HUE_LONGTEXT, true )
343     add_integer( CFG_PREFIX "black-level", -1, BLACKLEVEL_TEXT,
344                  BLACKLEVEL_LONGTEXT, true )
345     add_integer( CFG_PREFIX "auto-white-balance", -1,
346                  AUTOWHITEBALANCE_TEXT, AUTOWHITEBALANCE_LONGTEXT, true )
347         change_integer_list( tristate_vlc, tristate_user )
348     add_integer( CFG_PREFIX "do-white-balance", -1, DOWHITEBALANCE_TEXT,
349                  DOWHITEBALANCE_LONGTEXT, true )
350     add_integer( CFG_PREFIX "red-balance", -1, REDBALANCE_TEXT,
351                  REDBALANCE_LONGTEXT, true )
352     add_integer( CFG_PREFIX "blue-balance", -1, BLUEBALANCE_TEXT,
353                  BLUEBALANCE_LONGTEXT, true )
354     add_integer( CFG_PREFIX "gamma", -1, GAMMA_TEXT,
355                  GAMMA_LONGTEXT, true )
356     add_integer( CFG_PREFIX "exposure", -1, EXPOSURE_TEXT,
357                  EXPOSURE_LONGTEXT, true )
358     add_integer( CFG_PREFIX "autogain", -1, AUTOGAIN_TEXT,
359                  AUTOGAIN_LONGTEXT, true )
360         change_integer_list( tristate_vlc, tristate_user )
361     add_integer( CFG_PREFIX "gain", -1, GAIN_TEXT,
362                  GAIN_LONGTEXT, true )
363     add_bool( CFG_PREFIX "hflip", false, HFLIP_TEXT, HFLIP_LONGTEXT, true )
364     add_bool( CFG_PREFIX "vflip", false, VFLIP_TEXT, VFLIP_LONGTEXT, true )
365     add_integer( CFG_PREFIX "hcenter", -1, HCENTER_TEXT,
366                  HCENTER_LONGTEXT, true )
367     add_integer( CFG_PREFIX "vcenter", -1, VCENTER_TEXT,
368                  VCENTER_LONGTEXT, true )
369     add_integer( CFG_PREFIX "audio-volume", -1, AUDIO_VOLUME_TEXT,
370                 AUDIO_VOLUME_LONGTEXT, true )
371     add_integer( CFG_PREFIX "audio-balance", -1, AUDIO_BALANCE_TEXT,
372                 AUDIO_BALANCE_LONGTEXT, true )
373     add_bool( CFG_PREFIX "audio-mute", false, AUDIO_MUTE_TEXT,
374               AUDIO_MUTE_LONGTEXT, true )
375     add_integer( CFG_PREFIX "audio-bass", -1, AUDIO_BASS_TEXT,
376                 AUDIO_BASS_LONGTEXT, true )
377     add_integer( CFG_PREFIX "audio-treble", -1, AUDIO_TREBLE_TEXT,
378                 AUDIO_TREBLE_LONGTEXT, true )
379     add_bool( CFG_PREFIX "audio-loudness", false, AUDIO_LOUDNESS_TEXT,
380               AUDIO_LOUDNESS_LONGTEXT, true )
381     add_string( CFG_PREFIX "set-ctrls", NULL, S_CTRLS_TEXT,
382               S_CTRLS_LONGTEXT, true )
383         change_safe()
384
385     add_obsolete_string( CFG_PREFIX "adev" )
386     add_obsolete_integer( CFG_PREFIX "audio-method" )
387     add_obsolete_bool( CFG_PREFIX "stereo" )
388     add_obsolete_integer( CFG_PREFIX "samplerate" )
389
390     add_shortcut( "v4l2" )
391     set_capability( "access_demux", 0 )
392     set_callbacks( DemuxOpen, DemuxClose )
393
394     add_submodule ()
395     add_shortcut( "v4l2", "v4l2c" )
396     set_description( N_("Video4Linux2 Compressed A/V") )
397     set_capability( "access", 0 )
398     /* use these when open as access_demux fails; VLC will use another demux */
399     set_callbacks( AccessOpen, AccessClose )
400
401 vlc_module_end ()
402
403 /*****************************************************************************
404  * Access: local prototypes
405  *****************************************************************************/
406
407 static block_t* ProcessVideoFrame( vlc_object_t *p_demux, uint8_t *p_frame, size_t );
408
409 static const struct
410 {
411     unsigned int i_v4l2;
412     vlc_fourcc_t i_fourcc;
413     int i_rmask;
414     int i_gmask;
415     int i_bmask;
416 } v4l2chroma_to_fourcc[] =
417 {
418     /* Raw data types */
419     { V4L2_PIX_FMT_GREY,    VLC_CODEC_GREY, 0, 0, 0 },
420     { V4L2_PIX_FMT_HI240,   VLC_FOURCC('I','2','4','0'), 0, 0, 0 },
421     { V4L2_PIX_FMT_RGB555,  VLC_CODEC_RGB15, 0x001f,0x03e0,0x7c00 },
422     { V4L2_PIX_FMT_RGB565,  VLC_CODEC_RGB16, 0x001f,0x07e0,0xf800 },
423     /* Won't work since we don't know how to handle such gmask values
424      * correctly
425     { V4L2_PIX_FMT_RGB555X, VLC_CODEC_RGB15, 0x007c,0xe003,0x1f00 },
426     { V4L2_PIX_FMT_RGB565X, VLC_CODEC_RGB16, 0x00f8,0xe007,0x1f00 },
427     */
428     { V4L2_PIX_FMT_BGR24,   VLC_CODEC_RGB24, 0xff0000,0xff00,0xff },
429     { V4L2_PIX_FMT_RGB24,   VLC_CODEC_RGB24, 0xff,0xff00,0xff0000 },
430     { V4L2_PIX_FMT_BGR32,   VLC_CODEC_RGB32, 0xff0000,0xff00,0xff },
431     { V4L2_PIX_FMT_RGB32,   VLC_CODEC_RGB32, 0xff,0xff00,0xff0000 },
432     { V4L2_PIX_FMT_YUYV,    VLC_CODEC_YUYV, 0, 0, 0 },
433     { V4L2_PIX_FMT_UYVY,    VLC_CODEC_UYVY, 0, 0, 0 },
434     { V4L2_PIX_FMT_Y41P,    VLC_FOURCC('I','4','1','N'), 0, 0, 0 },
435     { V4L2_PIX_FMT_YUV422P, VLC_CODEC_I422, 0, 0, 0 },
436     { V4L2_PIX_FMT_YVU420,  VLC_CODEC_YV12, 0, 0, 0 },
437     { V4L2_PIX_FMT_YUV411P, VLC_CODEC_I411, 0, 0, 0 },
438     { V4L2_PIX_FMT_YUV410,  VLC_CODEC_I410, 0, 0, 0 },
439
440     /* Raw data types, not in V4L2 spec but still in videodev2.h and supported
441      * by VLC */
442     { V4L2_PIX_FMT_YUV420,  VLC_CODEC_I420, 0, 0, 0 },
443     /* FIXME { V4L2_PIX_FMT_RGB444,  VLC_CODEC_RGB32 }, */
444
445     /* Compressed data types */
446     { V4L2_PIX_FMT_MJPEG,   VLC_CODEC_MJPG, 0, 0, 0 },
447     { V4L2_PIX_FMT_JPEG,    VLC_CODEC_JPEG, 0, 0, 0 },
448 #if 0
449     { V4L2_PIX_FMT_DV,      VLC_FOURCC('?','?','?','?') },
450     { V4L2_PIX_FMT_MPEG,    VLC_FOURCC('?','?','?','?') },
451 #endif
452     { 0, 0, 0, 0, 0 }
453 };
454
455 /**
456  * List of V4L2 chromas were confident enough to use as fallbacks if the
457  * user hasn't provided a --v4l2-chroma value.
458  *
459  * Try YUV chromas first, then RGB little endian and MJPEG as last resort.
460  */
461 static const uint32_t p_chroma_fallbacks[] =
462 { V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_YVU420, V4L2_PIX_FMT_YUV422P,
463   V4L2_PIX_FMT_YUYV, V4L2_PIX_FMT_UYVY, V4L2_PIX_FMT_BGR24,
464   V4L2_PIX_FMT_BGR32, V4L2_PIX_FMT_MJPEG, V4L2_PIX_FMT_JPEG };
465
466 /**
467  * Parses a V4L2 MRL into VLC object variables.
468  */
469 void ParseMRL( vlc_object_t *obj, const char *mrl )
470 {
471     const char *p = strchr( mrl, ':' );
472     char *dev = NULL;
473
474     if( p != NULL )
475     {
476         var_LocationParse( obj, p + 1, CFG_PREFIX );
477         if( p > mrl )
478             dev = strndup( mrl, p - mrl );
479     }
480     else
481     {
482         if( mrl[0] )
483             dev = strdup( mrl );
484     }
485
486     if( dev != NULL )
487     {
488         var_Create( obj, CFG_PREFIX"dev", VLC_VAR_STRING );
489         var_SetString( obj, CFG_PREFIX"dev", dev );
490         free( dev );
491     }
492 }
493
494 /*****************************************************************************
495  * GrabVideo: Grab a video frame
496  *****************************************************************************/
497 block_t* GrabVideo( vlc_object_t *p_demux, demux_sys_t *p_sys )
498 {
499     block_t *p_block;
500     struct v4l2_buffer buf;
501
502     /* Grab Video Frame */
503     switch( p_sys->io )
504     {
505     case IO_METHOD_MMAP:
506         memset( &buf, 0, sizeof(buf) );
507         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
508         buf.memory = V4L2_MEMORY_MMAP;
509
510         /* Wait for next frame */
511         if (v4l2_ioctl( p_sys->i_fd, VIDIOC_DQBUF, &buf ) < 0 )
512         {
513             switch( errno )
514             {
515             case EAGAIN:
516                 return NULL;
517             case EIO:
518                 /* Could ignore EIO, see spec. */
519                 /* fall through */
520             default:
521                 msg_Err( p_demux, "Failed to wait (VIDIOC_DQBUF)" );
522                 return NULL;
523                }
524         }
525
526         if( buf.index >= p_sys->i_nbuffers ) {
527             msg_Err( p_demux, "Failed capturing new frame as i>=nbuffers" );
528             return NULL;
529         }
530
531         p_block = ProcessVideoFrame( p_demux, p_sys->p_buffers[buf.index].start, buf.bytesused );
532         if( !p_block )
533             return NULL;
534
535         /* Unlock */
536         if( v4l2_ioctl( p_sys->i_fd, VIDIOC_QBUF, &buf ) < 0 )
537         {
538             msg_Err( p_demux, "Failed to unlock (VIDIOC_QBUF)" );
539             block_Release( p_block );
540             return NULL;
541         }
542
543         break;
544
545     case IO_METHOD_USERPTR:
546         memset( &buf, 0, sizeof(buf) );
547         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
548         buf.memory = V4L2_MEMORY_USERPTR;
549
550         /* Wait for next frame */
551         if (v4l2_ioctl( p_sys->i_fd, VIDIOC_DQBUF, &buf ) < 0 )
552         {
553             switch( errno )
554             {
555             case EAGAIN:
556                 return NULL;
557             case EIO:
558                 /* Could ignore EIO, see spec. */
559                 /* fall through */
560             default:
561                 msg_Err( p_demux, "Failed to wait (VIDIOC_DQBUF)" );
562                 return NULL;
563             }
564         }
565
566         /* Find frame? */
567         unsigned int i;
568         for( i = 0; i < p_sys->i_nbuffers; i++ )
569         {
570             if( buf.m.userptr == (unsigned long)p_sys->p_buffers[i].start &&
571                 buf.length == p_sys->p_buffers[i].length ) break;
572         }
573
574         if( i >= p_sys->i_nbuffers )
575         {
576             msg_Err( p_demux, "Failed capturing new frame as i>=nbuffers" );
577             return NULL;
578         }
579
580         p_block = ProcessVideoFrame( p_demux, (uint8_t*)buf.m.userptr, buf.bytesused );
581         if( !p_block )
582             return NULL;
583
584         /* Unlock */
585         if( v4l2_ioctl( p_sys->i_fd, VIDIOC_QBUF, &buf ) < 0 )
586         {
587             msg_Err( p_demux, "Failed to unlock (VIDIOC_QBUF)" );
588             block_Release( p_block );
589             return NULL;
590         }
591         break;
592     default:
593         assert(0);
594     }
595     return p_block;
596 }
597
598 /*****************************************************************************
599  * ProcessVideoFrame: Helper function to take a buffer and copy it into
600  * a new block
601  *****************************************************************************/
602 static block_t* ProcessVideoFrame( vlc_object_t *p_demux, uint8_t *p_frame, size_t i_size )
603 {
604     block_t *p_block;
605
606     if( !p_frame ) return NULL;
607
608     /* New block */
609     if( !( p_block = block_New( p_demux, i_size ) ) )
610     {
611         msg_Warn( p_demux, "Cannot get new block" );
612         return NULL;
613     }
614
615     /* Copy frame */
616     memcpy( p_block->p_buffer, p_frame, i_size );
617
618     return p_block;
619 }
620
621 /*****************************************************************************
622  * Helper function to initalise video IO using the mmap method
623  *****************************************************************************/
624 static int InitMmap( vlc_object_t *p_demux, demux_sys_t *p_sys, int i_fd )
625 {
626     struct v4l2_requestbuffers req;
627
628     memset( &req, 0, sizeof(req) );
629     req.count = 4;
630     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
631     req.memory = V4L2_MEMORY_MMAP;
632
633     if( v4l2_ioctl( i_fd, VIDIOC_REQBUFS, &req ) < 0 )
634     {
635         msg_Err( p_demux, "device does not support mmap I/O" );
636         return -1;
637     }
638
639     if( req.count < 2 )
640     {
641         msg_Err( p_demux, "insufficient buffers" );
642         return -1;
643     }
644
645     p_sys->p_buffers = calloc( req.count, sizeof( *p_sys->p_buffers ) );
646     if( unlikely(!p_sys->p_buffers) )
647         return -1;
648
649     for( p_sys->i_nbuffers = 0; p_sys->i_nbuffers < req.count; ++p_sys->i_nbuffers )
650     {
651         struct v4l2_buffer buf;
652
653         memset( &buf, 0, sizeof(buf) );
654         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
655         buf.memory = V4L2_MEMORY_MMAP;
656         buf.index = p_sys->i_nbuffers;
657
658         if( v4l2_ioctl( i_fd, VIDIOC_QUERYBUF, &buf ) < 0 )
659         {
660             msg_Err( p_demux, "VIDIOC_QUERYBUF: %m" );
661             return -1;
662         }
663
664         p_sys->p_buffers[p_sys->i_nbuffers].length = buf.length;
665         p_sys->p_buffers[p_sys->i_nbuffers].start =
666             v4l2_mmap( NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, i_fd, buf.m.offset );
667
668         if( p_sys->p_buffers[p_sys->i_nbuffers].start == MAP_FAILED )
669         {
670             msg_Err( p_demux, "mmap failed: %m" );
671             return -1;
672         }
673     }
674
675     return 0;
676 }
677
678 /*****************************************************************************
679  * Helper function to initalise video IO using the userbuf method
680  *****************************************************************************/
681 static int InitUserP( vlc_object_t *p_demux, demux_sys_t *p_sys, int i_fd, unsigned int i_buffer_size )
682 {
683     struct v4l2_requestbuffers req;
684     unsigned int i_page_size;
685
686     i_page_size = sysconf(_SC_PAGESIZE);
687     i_buffer_size = ( i_buffer_size + i_page_size - 1 ) & ~( i_page_size - 1);
688
689     memset( &req, 0, sizeof(req) );
690     req.count = 4;
691     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
692     req.memory = V4L2_MEMORY_USERPTR;
693
694     if( v4l2_ioctl( i_fd, VIDIOC_REQBUFS, &req ) < 0 )
695     {
696         msg_Err( p_demux, "device does not support user pointer i/o" );
697         return -1;
698     }
699
700     p_sys->p_buffers = calloc( 4, sizeof( *p_sys->p_buffers ) );
701     if( !p_sys->p_buffers )
702         return -1;
703
704     for( p_sys->i_nbuffers = 0; p_sys->i_nbuffers < 4; ++p_sys->i_nbuffers )
705     {
706         p_sys->p_buffers[p_sys->i_nbuffers].length = i_buffer_size;
707         if( posix_memalign( &p_sys->p_buffers[p_sys->i_nbuffers].start,
708                 /* boundary */ i_page_size, i_buffer_size ) )
709             return -1;
710     }
711
712     return 0;
713 }
714
715 /**
716  * \return true if the specified V4L2 pixel format is
717  * in the array of supported formats returned by the driver
718  */
719 static bool IsPixelFormatSupported( struct v4l2_fmtdesc *codecs, size_t n,
720                                     unsigned int i_pixelformat )
721 {
722     for( size_t i = 0; i < n; i++ )
723         if( codecs[i].pixelformat == i_pixelformat )
724             return true;
725     return false;
726 }
727
728
729 static int InitVideo( vlc_object_t *p_obj, int i_fd, demux_sys_t *p_sys,
730                       bool b_demux );
731
732 /**
733  * Opens and sets up a video device
734  * \return file descriptor or -1 on error
735  */
736 int OpenVideo( vlc_object_t *obj, demux_sys_t *sys, bool b_demux )
737 {
738     char *path = var_InheritString( obj, CFG_PREFIX"dev" );
739     if( unlikely(path == NULL) )
740         return -1; /* probably OOM */
741
742     msg_Dbg( obj, "opening device '%s'", path );
743
744     int fd = vlc_open( path, O_RDWR );
745     if( fd == -1 )
746     {
747         msg_Err( obj, "cannot open device '%s': %m", path );
748         free( path );
749         return -1;
750     }
751     free( path );
752 #ifdef HAVE_LIBV4L2
753     if( !var_InheritBool( obj, CFG_PREFIX "use-libv4l2" ) )
754     {
755         msg_Dbg( obj, "trying kernel V4L2" );
756         if( InitVideo( obj, fd, sys, b_demux ) == 0 )
757             return fd;
758     }
759     msg_Dbg( obj, "trying library V4L2" );
760     /* Note the v4l2_xxx functions are designed so that if they get passed an
761        unknown fd, the will behave exactly as their regular xxx counterparts,
762        so if v4l2_fd_open fails, we continue as normal (missing the libv4l2
763        custom cam format to normal formats conversion). Chances are big we will
764        still fail then though, as normally v4l2_fd_open only fails if the
765        device is not a v4l2 device. */
766     int libfd = v4l2_fd_open( fd, 0 );
767     if( libfd == -1 )
768         goto error;
769     fd = libfd;
770 #endif
771     if( InitVideo( obj, fd, sys, b_demux ) )
772         goto error;
773
774     return fd;
775 error:
776     close( fd );
777     return -1;
778 }
779
780 static int InitVideo( vlc_object_t *p_obj, int i_fd, demux_sys_t *p_sys,
781                       bool b_demux )
782 {
783     struct v4l2_cropcap cropcap;
784     struct v4l2_crop crop;
785     struct v4l2_format fmt;
786     unsigned int i_min;
787     enum v4l2_buf_type buf_type;
788     es_format_t es_fmt;
789
790     /* Get device capabilites */
791     struct v4l2_capability cap;
792     if( v4l2_ioctl( i_fd, VIDIOC_QUERYCAP, &cap ) < 0 )
793     {
794         msg_Err( p_obj, "cannot get video capabilities: %m" );
795         return -1;
796     }
797
798     msg_Dbg( p_obj, "device %s using driver %s (version %u.%u.%u) on %s",
799             cap.card, cap.driver, (cap.version >> 16) & 0xFF,
800             (cap.version >> 8) & 0xFF, cap.version & 0xFF, cap.bus_info );
801     msg_Dbg( p_obj, "the device has the capabilities: 0x%08X",
802              cap.capabilities );
803     msg_Dbg( p_obj, " (%c) Video Capture, (%c) Audio, (%c) Tuner, (%c) Radio",
804              ( cap.capabilities & V4L2_CAP_VIDEO_CAPTURE  ? 'X':' '),
805              ( cap.capabilities & V4L2_CAP_AUDIO  ? 'X':' '),
806              ( cap.capabilities & V4L2_CAP_TUNER  ? 'X':' '),
807              ( cap.capabilities & V4L2_CAP_RADIO  ? 'X':' ') );
808     msg_Dbg( p_obj, " (%c) Read/Write, (%c) Streaming, (%c) Asynchronous",
809             ( cap.capabilities & V4L2_CAP_READWRITE ? 'X':' ' ),
810             ( cap.capabilities & V4L2_CAP_STREAMING ? 'X':' ' ),
811             ( cap.capabilities & V4L2_CAP_ASYNCIO ? 'X':' ' ) );
812
813     if( cap.capabilities & V4L2_CAP_STREAMING )
814         p_sys->io = IO_METHOD_MMAP;
815     else if( cap.capabilities & V4L2_CAP_READWRITE )
816         p_sys->io = IO_METHOD_READ;
817     else
818     {
819         msg_Err( p_obj, "no supported I/O method" );
820         return -1;
821     }
822
823     /* Now, enumerate all the video inputs. This is useless at the moment
824        since we have no way to present that info to the user except with
825        debug messages */
826     if( cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
827     {
828         struct v4l2_input input;
829         unsigned index = var_InheritInteger( p_obj, CFG_PREFIX"input" );
830
831         input.index = 0;
832         while( v4l2_ioctl( i_fd, VIDIOC_ENUMINPUT, &input ) >= 0 )
833         {
834             msg_Dbg( p_obj, "video input %u (%s) has type: %s %c",
835                      input.index, input.name,
836                      input.type == V4L2_INPUT_TYPE_TUNER
837                           ? "Tuner adapter" : "External analog input",
838                      input.index == index ? '*' : ' ' );
839             input.index++;
840         }
841
842         /* Select input */
843         if( v4l2_ioctl( i_fd, VIDIOC_S_INPUT, &index ) < 0 )
844         {
845             msg_Err( p_obj, "cannot set input %u: %m", index );
846             return -1;
847         }
848         msg_Dbg( p_obj, "input set to %u", index );
849     }
850
851     /* Select standard */
852     bool bottom_first;
853     const char *stdname = var_InheritString( p_obj, CFG_PREFIX"standard" );
854     if( stdname != NULL )
855     {
856         v4l2_std_id std = strtoull( stdname, NULL, 0 );
857         if( std == 0 )
858         {
859             const size_t n = sizeof(standards_vlc) / sizeof(*standards_vlc);
860             assert( n == sizeof(standards_v4l2) / sizeof(*standards_v4l2) );
861             assert( n == sizeof(standards_user) / sizeof(*standards_user) );
862             for( size_t i = 0; i < n; i++ )
863                 if( strcasecmp( stdname, standards_vlc[i] ) == 0 )
864                 {
865                     std = standards_v4l2[i];
866                     break;
867                 }
868         }
869
870         if( v4l2_ioctl( i_fd, VIDIOC_S_STD, &std ) < 0
871          || v4l2_ioctl( i_fd, VIDIOC_G_STD, &std ) < 0 )
872         {
873             msg_Err( p_obj, "cannot set standard 0x%"PRIx64": %m", std );
874             return -1;
875         }
876         msg_Dbg( p_obj, "standard set to 0x%"PRIx64":", std );
877         bottom_first = std == V4L2_STD_NTSC;
878     }
879     else
880         bottom_first = false;
881
882     /* Set audio input */
883     if( cap.capabilities & V4L2_CAP_AUDIO )
884     {
885         struct v4l2_audio audio = { .index = 0 };
886         uint32_t idx = var_InheritInteger( p_obj, CFG_PREFIX"audio-input" );
887
888         /* Probe audio inputs */
889         while( v4l2_ioctl( i_fd, VIDIOC_ENUMAUDIO, &audio ) >= 0 )
890         {
891             msg_Dbg( p_obj, "audio input %u (%s) is %s%s %c", audio.index,
892                      audio.name,
893                      audio.capability & V4L2_AUDCAP_STEREO ? "Stereo" : "Mono",
894                      audio.capability & V4L2_AUDCAP_AVL
895                          ? " (Automatic Volume Level supported)" : "",
896                      audio.index == idx );
897             audio.index++;
898         }
899
900         if( idx != (uint32_t)-1 )
901         {
902             memset( &audio, 0, sizeof(audio) );
903             audio.index = idx;
904             /* TODO: AVL support (audio.mode) */
905
906             if( v4l2_ioctl( i_fd, VIDIOC_S_AUDIO, &audio ) < 0 )
907             {
908                 msg_Err( p_obj, "cannot set audio input %"PRIu32": %m", idx );
909                 return -1;
910             }
911             msg_Dbg( p_obj, "audio input set to %"PRIu32, idx );
912         }
913     }
914
915     /* List tuner caps */
916     if( cap.capabilities & V4L2_CAP_TUNER )
917     {
918         struct v4l2_tuner tuner;
919         uint32_t idx = var_CreateGetInteger( p_obj, CFG_PREFIX"tuner" );
920         enum v4l2_tuner_type type = V4L2_TUNER_RADIO;
921
922         tuner.index = 0;
923         while( v4l2_ioctl( i_fd, VIDIOC_G_TUNER, &tuner ) >= 0 )
924         {
925             if( tuner.index == idx )
926                 type = tuner.type;
927
928             const char *unit =
929                 (tuner.capability & V4L2_TUNER_CAP_LOW) ? "Hz" : "kHz";
930             msg_Dbg( p_obj, "tuner %u (%s) has type: %s, "
931                      "frequency range: %.1f %s -> %.1f %s", tuner.index,
932                      tuner.name,
933                      tuner.type == V4L2_TUNER_RADIO ? "Radio" : "Analog TV",
934                      tuner.rangelow * 62.5, unit,
935                      tuner.rangehigh * 62.5, unit );
936
937             struct v4l2_frequency frequency = { .tuner = tuner.index };
938             if( v4l2_ioctl( i_fd, VIDIOC_G_FREQUENCY, &frequency ) < 0 )
939             {
940                 msg_Err( p_obj, "cannot get tuner frequency: %m" );
941                 return -1;
942             }
943             msg_Dbg( p_obj, "tuner %u (%s) frequency: %.1f %s", tuner.index,
944                      tuner.name, frequency.frequency * 62.5, unit );
945             tuner.index++;
946         }
947
948         /* Tune the tuner */
949         uint32_t freq = var_InheritInteger( p_obj,
950                                             CFG_PREFIX"tuner-frequency" );
951         if( freq != (uint32_t)-1 )
952         {
953             struct v4l2_frequency frequency = {
954                 .tuner = idx,
955                 .type = type,
956                 .frequency = freq / 62.5,
957             };
958
959             if( v4l2_ioctl( i_fd, VIDIOC_S_FREQUENCY, &frequency ) < 0 )
960             {
961                 msg_Err( p_obj, "cannot set tuner frequency: %m" );
962                 return -1;
963             }
964             msg_Dbg( p_obj, "tuner frequency set" );
965         }
966
967         /* Set the tuner audio mode */
968         int32_t audmode = var_InheritInteger( p_obj,
969                                               CFG_PREFIX"tuner-audio-mode" );
970         if( audmode >= 0 )
971         {
972             struct v4l2_tuner tuner = {
973                 .index = idx,
974                 .audmode = audmode,
975             };
976
977             if( v4l2_ioctl( i_fd, VIDIOC_S_TUNER, &tuner ) < 0 )
978             {
979                 msg_Err( p_obj, "cannot set tuner audio mode: %m" );
980                 return -1;
981             }
982             msg_Dbg( p_obj, "tuner audio mode set" );
983         }
984     }
985
986     /* Probe for available chromas */
987     struct v4l2_fmtdesc *codecs = NULL;
988     uint_fast32_t ncodec = 0;
989     if( cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
990     {
991         struct v4l2_fmtdesc codec = {
992             .index = 0,
993             .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
994         };
995
996         while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FMT, &codec ) >= 0 )
997             codec.index = ++ncodec;
998
999         codecs = malloc( ncodec * sizeof( *codecs ) );
1000         if( unlikely(codecs == NULL) )
1001             ncodec = 0;
1002
1003         for( uint_fast32_t i = 0; i < ncodec; i++ )
1004         {
1005             codecs[i].index = i;
1006             codecs[i].type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1007
1008             if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FMT, &codecs[i] ) < 0 )
1009             {
1010                 msg_Err( p_obj, "cannot get codec description: %m" );
1011                 goto error;
1012             }
1013
1014             /* only print if vlc supports the format */
1015             char fourcc_v4l2[5];
1016             memset( fourcc_v4l2, 0, sizeof( fourcc_v4l2 ) );
1017             vlc_fourcc_to_char( codecs[i].pixelformat, fourcc_v4l2 );
1018
1019             bool b_codec_supported = false;
1020             for( unsigned j = 0; v4l2chroma_to_fourcc[j].i_v4l2 != 0; j++ )
1021             {
1022                 if( v4l2chroma_to_fourcc[j].i_v4l2 == codecs[i].pixelformat )
1023                 {
1024                     char fourcc[5];
1025                     memset( fourcc, 0, sizeof( fourcc ) );
1026                     vlc_fourcc_to_char( v4l2chroma_to_fourcc[j].i_fourcc,
1027                                         fourcc );
1028                     msg_Dbg( p_obj, "device supports chroma %4.4s [%s, %s]",
1029                              fourcc, codecs[i].description, fourcc_v4l2 );
1030                     b_codec_supported = true;
1031                 }
1032             }
1033             if( !b_codec_supported )
1034             {
1035                 msg_Dbg( p_obj, "device codec %4.4s (%s) not supported",
1036                          fourcc_v4l2, codecs[i].description );
1037             }
1038         }
1039     }
1040
1041     /* TODO: Move the resolution stuff up here */
1042     /* if MPEG encoder card, no need to do anything else after this */
1043     p_sys->controls = ControlsInit( p_obj, i_fd );
1044
1045     /* Reset Cropping */
1046     memset( &cropcap, 0, sizeof(cropcap) );
1047     cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1048     if( v4l2_ioctl( i_fd, VIDIOC_CROPCAP, &cropcap ) >= 0 )
1049     {
1050         crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1051         crop.c = cropcap.defrect; /* reset to default */
1052         if( crop.c.width > 0 && crop.c.height > 0 ) /* Fix for fm tuners */
1053         {
1054             if( v4l2_ioctl( i_fd, VIDIOC_S_CROP, &crop ) < 0 )
1055             {
1056                 switch( errno )
1057                 {
1058                     case EINVAL:
1059                         /* Cropping not supported. */
1060                         break;
1061                     default:
1062                         /* Errors ignored. */
1063                         break;
1064                 }
1065             }
1066         }
1067     }
1068
1069     /* Try and find default resolution if not specified */
1070     int width = var_InheritInteger( p_obj, CFG_PREFIX"width" );
1071     int height = var_InheritInteger( p_obj, CFG_PREFIX"height" );
1072
1073     memset( &fmt, 0, sizeof(fmt) );
1074     fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1075
1076     if( width <= 0 || height <= 0 )
1077     {
1078         /* Use current width and height settings */
1079         if( v4l2_ioctl( i_fd, VIDIOC_G_FMT, &fmt ) < 0 )
1080         {
1081             msg_Err( p_obj, "cannot get default width and height: %m" );
1082             goto error;
1083         }
1084
1085         msg_Dbg( p_obj, "found default width and height of %ux%u",
1086                  fmt.fmt.pix.width, fmt.fmt.pix.height );
1087
1088         if( width < 0 || height < 0 )
1089         {
1090             msg_Dbg( p_obj, "will try to find optimal width and height" );
1091         }
1092     }
1093     else
1094     {
1095         /* Use user specified width and height */
1096         msg_Dbg( p_obj, "trying specified size %dx%d", width, height );
1097         fmt.fmt.pix.width = width;
1098         fmt.fmt.pix.height = height;
1099     }
1100
1101     fmt.fmt.pix.field = V4L2_FIELD_NONE;
1102
1103     float f_fps;
1104     if (b_demux)
1105     {
1106         char *reqchroma = var_InheritString( p_obj, CFG_PREFIX"chroma" );
1107
1108         /* Test and set Chroma */
1109         fmt.fmt.pix.pixelformat = 0;
1110         if( reqchroma != NULL )
1111         {
1112             /* User specified chroma */
1113             const vlc_fourcc_t i_requested_fourcc =
1114                 vlc_fourcc_GetCodecFromString( VIDEO_ES, reqchroma );
1115
1116             for( int i = 0; v4l2chroma_to_fourcc[i].i_v4l2 != 0; i++ )
1117             {
1118                 if( v4l2chroma_to_fourcc[i].i_fourcc == i_requested_fourcc )
1119                 {
1120                     fmt.fmt.pix.pixelformat = v4l2chroma_to_fourcc[i].i_v4l2;
1121                     break;
1122                 }
1123             }
1124             /* Try and set user chroma */
1125             bool b_error = !IsPixelFormatSupported( codecs, ncodec,
1126                                                     fmt.fmt.pix.pixelformat );
1127             if( !b_error && fmt.fmt.pix.pixelformat )
1128             {
1129                 if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 )
1130                 {
1131                     fmt.fmt.pix.field = V4L2_FIELD_ANY;
1132                     if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 )
1133                     {
1134                         fmt.fmt.pix.field = V4L2_FIELD_NONE;
1135                         b_error = true;
1136                     }
1137                 }
1138             }
1139             if( b_error )
1140             {
1141                 msg_Warn( p_obj, "requested chroma %s not supported. "
1142                           " Trying default.", reqchroma );
1143                 fmt.fmt.pix.pixelformat = 0;
1144             }
1145             free( reqchroma );
1146         }
1147
1148         /* If no user specified chroma, find best */
1149         /* This also decides if MPEG encoder card or not */
1150         if( !fmt.fmt.pix.pixelformat )
1151         {
1152             unsigned int i;
1153             for( i = 0; i < ARRAY_SIZE( p_chroma_fallbacks ); i++ )
1154             {
1155                 fmt.fmt.pix.pixelformat = p_chroma_fallbacks[i];
1156                 if( IsPixelFormatSupported( codecs, ncodec,
1157                                             fmt.fmt.pix.pixelformat ) )
1158                 {
1159                     if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) >= 0 )
1160                         break;
1161                     fmt.fmt.pix.field = V4L2_FIELD_ANY;
1162                     if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) >= 0 )
1163                         break;
1164                     fmt.fmt.pix.field = V4L2_FIELD_NONE;
1165                 }
1166             }
1167             if( i == ARRAY_SIZE( p_chroma_fallbacks ) )
1168             {
1169                 msg_Warn( p_obj, "Could not select any of the default chromas; attempting to open as MPEG encoder card (access)" );
1170                 goto error;
1171             }
1172         }
1173
1174         if( width < 0 || height < 0 )
1175         {
1176             f_fps = var_InheritFloat( p_obj, CFG_PREFIX"fps" );
1177             if( f_fps <= 0. )
1178             {
1179                 f_fps = GetAbsoluteMaxFrameRate( p_obj, i_fd,
1180                                                  fmt.fmt.pix.pixelformat );
1181                 msg_Dbg( p_obj, "Found maximum framerate of %f", f_fps );
1182             }
1183             uint32_t i_width, i_height;
1184             GetMaxDimensions( p_obj, i_fd,
1185                               fmt.fmt.pix.pixelformat, f_fps,
1186                               &i_width, &i_height );
1187             if( i_width || i_height )
1188             {
1189                 msg_Dbg( p_obj, "Found optimal dimensions for framerate %f "
1190                                   "of %ux%u", f_fps, i_width, i_height );
1191                 fmt.fmt.pix.width = i_width;
1192                 fmt.fmt.pix.height = i_height;
1193                 if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 )
1194                 {
1195                     msg_Err( p_obj, "Cannot set size to optimal dimensions "
1196                                     "%ux%u", i_width, i_height );
1197                     goto error;
1198                 }
1199             }
1200             else
1201             {
1202                 msg_Warn( p_obj, "Could not find optimal width and height, "
1203                                  "falling back to driver default." );
1204             }
1205         }
1206     }
1207
1208     width = fmt.fmt.pix.width;
1209     height = fmt.fmt.pix.height;
1210
1211     if( v4l2_ioctl( i_fd, VIDIOC_G_FMT, &fmt ) < 0 ) {;}
1212     /* Print extra info */
1213     msg_Dbg( p_obj, "Driver requires at most %d bytes to store a complete image", fmt.fmt.pix.sizeimage );
1214     /* Check interlacing */
1215     switch( fmt.fmt.pix.field )
1216     {
1217         case V4L2_FIELD_NONE:
1218             msg_Dbg( p_obj, "Interlacing setting: progressive" );
1219             break;
1220         case V4L2_FIELD_TOP:
1221             msg_Dbg( p_obj, "Interlacing setting: top field only" );
1222             break;
1223         case V4L2_FIELD_BOTTOM:
1224             msg_Dbg( p_obj, "Interlacing setting: bottom field only" );
1225             break;
1226         case V4L2_FIELD_INTERLACED:
1227             msg_Dbg( p_obj, "Interlacing setting: interleaved (bottom top if M/NTSC, top bottom otherwise)" );
1228             if( bottom_first )
1229                 p_sys->i_block_flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
1230             else
1231                 p_sys->i_block_flags = BLOCK_FLAG_TOP_FIELD_FIRST;
1232             break;
1233         case V4L2_FIELD_SEQ_TB:
1234             msg_Dbg( p_obj, "Interlacing setting: sequential top bottom (TODO)" );
1235             break;
1236         case V4L2_FIELD_SEQ_BT:
1237             msg_Dbg( p_obj, "Interlacing setting: sequential bottom top (TODO)" );
1238             break;
1239         case V4L2_FIELD_ALTERNATE:
1240             msg_Dbg( p_obj, "Interlacing setting: alternate fields (TODO)" );
1241             height *= 2;
1242             break;
1243         case V4L2_FIELD_INTERLACED_TB:
1244             msg_Dbg( p_obj, "Interlacing setting: interleaved top bottom" );
1245             p_sys->i_block_flags = BLOCK_FLAG_TOP_FIELD_FIRST;
1246             break;
1247         case V4L2_FIELD_INTERLACED_BT:
1248             msg_Dbg( p_obj, "Interlacing setting: interleaved bottom top" );
1249             p_sys->i_block_flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
1250             break;
1251         default:
1252             msg_Warn( p_obj, "Interlacing setting: unknown type (%d)",
1253                       fmt.fmt.pix.field );
1254             break;
1255     }
1256
1257     /* Look up final fourcc */
1258     p_sys->i_fourcc = 0;
1259     for( int i = 0; v4l2chroma_to_fourcc[i].i_fourcc != 0; i++ )
1260     {
1261         if( v4l2chroma_to_fourcc[i].i_v4l2 == fmt.fmt.pix.pixelformat )
1262         {
1263             p_sys->i_fourcc = v4l2chroma_to_fourcc[i].i_fourcc;
1264             es_format_Init( &es_fmt, VIDEO_ES, p_sys->i_fourcc );
1265             es_fmt.video.i_rmask = v4l2chroma_to_fourcc[i].i_rmask;
1266             es_fmt.video.i_gmask = v4l2chroma_to_fourcc[i].i_gmask;
1267             es_fmt.video.i_bmask = v4l2chroma_to_fourcc[i].i_bmask;
1268             break;
1269         }
1270     }
1271
1272     /* Buggy driver paranoia */
1273     i_min = fmt.fmt.pix.width * 2;
1274     if( fmt.fmt.pix.bytesperline < i_min )
1275         fmt.fmt.pix.bytesperline = i_min;
1276     i_min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
1277     if( fmt.fmt.pix.sizeimage < i_min )
1278         fmt.fmt.pix.sizeimage = i_min;
1279
1280     /* Init I/O method */
1281     switch( p_sys->io )
1282     {
1283     case IO_METHOD_READ:
1284         p_sys->blocksize = fmt.fmt.pix.sizeimage;
1285         break;
1286
1287     case IO_METHOD_MMAP:
1288         if( InitMmap( p_obj, p_sys, i_fd ) )
1289             goto error;
1290         for (unsigned int i = 0; i < p_sys->i_nbuffers; ++i)
1291         {
1292             struct v4l2_buffer buf;
1293
1294             memset( &buf, 0, sizeof(buf) );
1295             buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1296             buf.memory = V4L2_MEMORY_MMAP;
1297             buf.index = i;
1298
1299             if( v4l2_ioctl( i_fd, VIDIOC_QBUF, &buf ) < 0 )
1300             {
1301                 msg_Err( p_obj, "VIDIOC_QBUF failed" );
1302                 goto error;
1303             }
1304         }
1305
1306         buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1307         if( v4l2_ioctl( i_fd, VIDIOC_STREAMON, &buf_type ) < 0 )
1308         {
1309             msg_Err( p_obj, "VIDIOC_STREAMON failed" );
1310             goto error;
1311         }
1312         break;
1313
1314     case IO_METHOD_USERPTR:
1315         if( InitUserP( p_obj, p_sys, i_fd, fmt.fmt.pix.sizeimage ) )
1316             goto error;
1317         for( unsigned int i = 0; i < p_sys->i_nbuffers; ++i )
1318         {
1319             struct v4l2_buffer buf;
1320
1321             memset( &buf, 0, sizeof(buf) );
1322             buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1323             buf.memory = V4L2_MEMORY_USERPTR;
1324             buf.index = i;
1325             buf.m.userptr = (unsigned long)p_sys->p_buffers[i].start;
1326             buf.length = p_sys->p_buffers[i].length;
1327
1328             if( v4l2_ioctl( i_fd, VIDIOC_QBUF, &buf ) < 0 )
1329             {
1330                 msg_Err( p_obj, "VIDIOC_QBUF failed" );
1331                 goto error;
1332             }
1333         }
1334
1335         buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1336         if( v4l2_ioctl( i_fd, VIDIOC_STREAMON, &buf_type ) < 0 )
1337         {
1338             msg_Err( p_obj, "VIDIOC_STREAMON failed" );
1339             goto error;
1340         }
1341         break;
1342     }
1343
1344     free( codecs );
1345
1346     if( b_demux )
1347     {
1348         int ar = 4 * VOUT_ASPECT_FACTOR / 3;
1349         char *str = var_InheritString( p_obj, CFG_PREFIX"aspect-ratio" );
1350         if( likely(str != NULL) )
1351         {
1352             const char *delim = strchr( str, ':' );
1353             if( delim )
1354                 ar = atoi( str ) * VOUT_ASPECT_FACTOR / atoi( delim + 1 );
1355             free( str );
1356         }
1357
1358         /* Add */
1359         es_fmt.video.i_width  = width;
1360         es_fmt.video.i_height = height;
1361
1362         /* Get aspect-ratio */
1363         es_fmt.video.i_sar_num = ar * es_fmt.video.i_height;
1364         es_fmt.video.i_sar_den = VOUT_ASPECT_FACTOR * es_fmt.video.i_width;
1365
1366         /* Framerate */
1367         es_fmt.video.i_frame_rate = lround(f_fps * 1000000.);
1368         es_fmt.video.i_frame_rate_base = 1000000;
1369
1370         demux_t *p_demux = (demux_t *) p_obj;
1371         msg_Dbg( p_obj, "added new video es %4.4s %dx%d",
1372             (char*)&es_fmt.i_codec, es_fmt.video.i_width, es_fmt.video.i_height );
1373         msg_Dbg( p_obj, " frame rate: %f", f_fps );
1374
1375         p_sys->p_es = es_out_Add( p_demux->out, &es_fmt );
1376     }
1377     return 0;
1378
1379 error:
1380     free( codecs );
1381     return -1;
1382 }