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