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