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