]> git.sesse.net Git - vlc/blob - modules/access/v4l2/video.c
v4l2: use thread instead of polling
[vlc] / modules / access / v4l2 / video.c
1 /*****************************************************************************
2  * video.c : Video4Linux2 input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2002-2009 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Benjamin Pracht <bigben at videolan dot org>
8  *          Richard Hosking <richard at hovis dot net>
9  *          Antoine Cellerier <dionoea at videolan d.t org>
10  *          Dennis Lou <dlou99 at yahoo dot com>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU Lesser General Public License as published by
14  * the Free Software Foundation; either version 2.1 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public License
23  * along with this program; if not, write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*
28  * Sections based on the reference V4L2 capture example at
29  * http://v4l2spec.bytesex.org/spec/capture-example.html
30  */
31
32 /*****************************************************************************
33  * Preamble
34  *****************************************************************************/
35
36 #ifdef HAVE_CONFIG_H
37 # include "config.h"
38 #endif
39
40 #include <assert.h>
41 #include <errno.h>
42 #include <sys/ioctl.h>
43 #include <sys/mman.h>
44 #include <poll.h>
45
46 #include <vlc_common.h>
47 #include <vlc_plugin.h>
48 #include <vlc_demux.h>
49
50 #include "v4l2.h"
51
52 /*****************************************************************************
53  * Module descriptior
54  *****************************************************************************/
55
56 #define DEVICE_TEXT N_( "Device" )
57 #define DEVICE_LONGTEXT N_( \
58     "Video device (Default: /dev/video0)." )
59 #define STANDARD_TEXT N_( "Standard" )
60 #define STANDARD_LONGTEXT N_( \
61     "Video standard (Default, SECAM, PAL, or NTSC)." )
62 #define CHROMA_TEXT N_("Video input chroma format")
63 #define CHROMA_LONGTEXT N_( \
64     "Force the Video4Linux2 video device to use a specific chroma format " \
65     "(eg. I420 or I422 for raw images, MJPG for M-JPEG compressed input) " \
66     "(Complete list: GREY, I240, RV16, RV15, RV24, RV32, YUY2, YUYV, UYVY, " \
67     "I41N, I422, I420, I411, I410, MJPG)")
68 #define INPUT_TEXT N_( "Input" )
69 #define INPUT_LONGTEXT N_( \
70     "Input of the card to use (see debug)." )
71 #define AUDIO_INPUT_TEXT N_( "Audio input" )
72 #define AUDIO_INPUT_LONGTEXT N_( \
73     "Audio input of the card to use (see debug)." )
74 #define WIDTH_TEXT N_( "Width" )
75 #define HEIGHT_TEXT N_( "Height" )
76 #define SIZE_LONGTEXT N_( \
77     "The specified pixel resolution is forced " \
78     "(if both width and height are strictly positive)." )
79 #define FPS_TEXT N_( "Framerate" )
80 #define FPS_LONGTEXT N_( "Framerate to capture, if applicable " \
81     "(0 for autodetect)." )
82
83 #define CTRL_RESET_TEXT N_( "Reset controls" )
84 #define CTRL_RESET_LONGTEXT N_( "Reset controls to defaults." )
85 #define BRIGHTNESS_TEXT N_( "Brightness" )
86 #define BRIGHTNESS_LONGTEXT N_( "Picture brightness or black level." )
87 #define BRIGHTNESS_AUTO_TEXT N_( "Automatic brightness" )
88 #define BRIGHTNESS_AUTO_LONGTEXT N_( \
89     "Automatically adjust the picture brightness." )
90 #define CONTRAST_TEXT N_( "Contrast" )
91 #define CONTRAST_LONGTEXT N_( "Picture contrast or luma gain." )
92 #define SATURATION_TEXT N_( "Saturation" )
93 #define SATURATION_LONGTEXT N_( "Picture saturation or chroma gain." )
94 #define HUE_TEXT N_( "Hue" )
95 #define HUE_LONGTEXT N_( "Hue or color balance." )
96 #define HUE_AUTO_TEXT N_( "Automatic hue" )
97 #define HUE_AUTO_LONGTEXT N_( \
98     "Automatically adjust the picture hue." )
99 #define WHITE_BALANCE_TEMP_TEXT N_( "White balance temperature (K)" )
100 #define WHITE_BALANCE_TEMP_LONGTEXT N_( \
101     "White balance temperature as a color temperation in Kelvin " \
102     "(2800 is minimum incandescence, 6500 is maximum daylight)." )
103 #define AUTOWHITEBALANCE_TEXT N_( "Automatic white balance" )
104 #define AUTOWHITEBALANCE_LONGTEXT N_( \
105     "Automatically adjust the picture white balance." )
106 #define REDBALANCE_TEXT N_( "Red balance" )
107 #define REDBALANCE_LONGTEXT N_( \
108     "Red chroma balance." )
109 #define BLUEBALANCE_TEXT N_( "Blue balance" )
110 #define BLUEBALANCE_LONGTEXT N_( \
111     "Blue chroma balance." )
112 #define GAMMA_TEXT N_( "Gamma" )
113 #define GAMMA_LONGTEXT N_( \
114     "Gamma adjust." )
115 #define AUTOGAIN_TEXT N_( "Automatic gain" )
116 #define AUTOGAIN_LONGTEXT N_( \
117     "Automatically set the video gain." )
118 #define GAIN_TEXT N_( "Gain" )
119 #define GAIN_LONGTEXT N_( \
120     "Picture gain." )
121 #define SHARPNESS_TEXT N_( "Sharpness" )
122 #define SHARPNESS_LONGTEXT N_( "Sharpness filter adjust." )
123 #define CHROMA_GAIN_TEXT N_( "Chroma gain" )
124 #define CHROMA_GAIN_LONGTEXT N_( "Chroma gain control." )
125 #define CHROMA_GAIN_AUTO_TEXT N_( "Automatic chroma gain" )
126 #define CHROMA_GAIN_AUTO_LONGTEXT N_( \
127     "Automatically control the chroma gain." )
128 #define POWER_FREQ_TEXT N_( "Power line frequency" )
129 #define POWER_FREQ_LONGTEXT N_( \
130     "Power line frequency anti-flicker filter." )
131 static const int power_freq_vlc[] = { -1,
132     V4L2_CID_POWER_LINE_FREQUENCY_DISABLED,
133     V4L2_CID_POWER_LINE_FREQUENCY_50HZ,
134     V4L2_CID_POWER_LINE_FREQUENCY_60HZ,
135     V4L2_CID_POWER_LINE_FREQUENCY_AUTO,
136 };
137 static const char *const power_freq_user[] = { N_("Unspecified"),
138     N_("Off"), N_("50 Hz"), N_("60 Hz"), N_("Automatic"),
139 };
140 #define BKLT_COMPENSATE_TEXT N_( "Backlight compensation" )
141 #define BKLT_COMPENSATE_LONGTEXT N_( "Backlight compensation." )
142 #define BAND_STOP_FILTER_TEXT N_( "Band-stop filter" )
143 #define BAND_STOP_FILTER_LONGTEXT N_(  \
144     "Cut a light band induced by fluorescent lighting (unit undocumented)." )
145 #define HFLIP_TEXT N_( "Horizontal flip" )
146 #define HFLIP_LONGTEXT N_( \
147     "Flip the picture horizontally." )
148 #define VFLIP_TEXT N_( "Vertical flip" )
149 #define VFLIP_LONGTEXT N_( \
150     "Flip the picture vertically." )
151 #define ROTATE_TEXT N_( "Rotate (degrees)" )
152 #define ROTATE_LONGTEXT N_( "Picture rotation angle (in degrees)." )
153 #define COLOR_KILLER_TEXT N_( "Color killer" )
154 #define COLOR_KILLER_LONGTEXT N_( \
155     "Enable the color killer, i.e. switch to black & white picture " \
156     "whenever the signal is weak." )
157 #define COLOR_EFFECT_TEXT N_( "Color effect" )
158 #define COLOR_EFFECT_LONGTEXT N_( "Select a color effect." )
159 static const int colorfx_vlc[] = { -1, V4L2_COLORFX_NONE,
160     V4L2_COLORFX_BW, V4L2_COLORFX_SEPIA, V4L2_COLORFX_NEGATIVE,
161     V4L2_COLORFX_EMBOSS, V4L2_COLORFX_SKETCH, V4L2_COLORFX_SKY_BLUE,
162     V4L2_COLORFX_GRASS_GREEN, V4L2_COLORFX_SKIN_WHITEN, V4L2_COLORFX_VIVID,
163 };
164 static const char *const colorfx_user[] = { N_("Unspecified"), N_("None"),
165     N_("Black & white"), N_("Sepia"), N_("Negative"),
166     N_("Emboss"), N_("Sketch"), N_("Sky blue"),
167     N_("Grass green"), N_("Skin whiten"), N_("Vivid"),
168 };
169
170 #define AUDIO_VOLUME_TEXT N_( "Audio volume" )
171 #define AUDIO_VOLUME_LONGTEXT N_( \
172     "Volume of the audio input." )
173 #define AUDIO_BALANCE_TEXT N_( "Audio balance" )
174 #define AUDIO_BALANCE_LONGTEXT N_( \
175     "Balance of the audio input." )
176 #define AUDIO_BASS_TEXT N_( "Bass level" )
177 #define AUDIO_BASS_LONGTEXT N_( \
178     "Bass adjustment of the audio input." )
179 #define AUDIO_TREBLE_TEXT N_( "Treble level" )
180 #define AUDIO_TREBLE_LONGTEXT N_( \
181     "Treble adjustment of the audio input." )
182 #define AUDIO_MUTE_TEXT N_( "Mute" )
183 #define AUDIO_MUTE_LONGTEXT N_( \
184     "Mute the audio." )
185 #define AUDIO_LOUDNESS_TEXT N_( "Loudness mode" )
186 #define AUDIO_LOUDNESS_LONGTEXT N_( \
187     "Loudness mode a.k.a. bass boost." )
188
189 #define S_CTRLS_TEXT N_("v4l2 driver controls")
190 #define S_CTRLS_LONGTEXT N_( \
191     "Set the v4l2 driver controls to the values specified using a comma " \
192     "separated list optionally encapsulated by curly braces " \
193     "(e.g.: {video_bitrate=6000000,audio_crc=0,stream_type=3} ). " \
194     "To list available controls, increase verbosity (-vvv) " \
195     "or use the v4l2-ctl application." )
196
197 #define TUNER_TEXT N_("Tuner id")
198 #define TUNER_LONGTEXT N_( \
199     "Tuner id (see debug output)." )
200 #define FREQUENCY_TEXT N_("Frequency")
201 #define FREQUENCY_LONGTEXT N_( \
202     "Tuner frequency in Hz or kHz (see debug output)" )
203 #define TUNER_AUDIO_MODE_TEXT N_("Audio mode")
204 #define TUNER_AUDIO_MODE_LONGTEXT N_( \
205     "Tuner audio mono/stereo and track selection." )
206
207 #define ASPECT_TEXT N_("Picture aspect-ratio n:m")
208 #define ASPECT_LONGTEXT N_("Define input picture aspect-ratio to use. Default is 4:3" )
209
210 static const int tristate_vlc[] = { -1, 0, 1 };
211 static const char *const tristate_user[] = {
212     N_("Unspecified"), N_("Off"), N_("On") };
213
214 static const v4l2_std_id standards_v4l2[] = { V4L2_STD_UNKNOWN, V4L2_STD_ALL,
215     V4L2_STD_PAL,     V4L2_STD_PAL_BG,   V4L2_STD_PAL_DK,
216     V4L2_STD_NTSC,
217     V4L2_STD_SECAM,   V4L2_STD_SECAM_DK,
218     V4L2_STD_MTS,     V4L2_STD_525_60,  V4L2_STD_625_50,
219     V4L2_STD_ATSC,
220
221     V4L2_STD_B,       V4L2_STD_G,        V4L2_STD_H,        V4L2_STD_L,
222     V4L2_STD_GH,      V4L2_STD_DK,       V4L2_STD_BG,       V4L2_STD_MN,
223
224     V4L2_STD_PAL_B,   V4L2_STD_PAL_B1,   V4L2_STD_PAL_G,    V4L2_STD_PAL_H,
225     V4L2_STD_PAL_I,   V4L2_STD_PAL_D,    V4L2_STD_PAL_D1,   V4L2_STD_PAL_K,
226     V4L2_STD_PAL_M,   V4L2_STD_PAL_N,    V4L2_STD_PAL_Nc,   V4L2_STD_PAL_60,
227     V4L2_STD_NTSC_M,  V4L2_STD_NTSC_M_JP,V4L2_STD_NTSC_443, V4L2_STD_NTSC_M_KR,
228     V4L2_STD_SECAM_B, V4L2_STD_SECAM_D,  V4L2_STD_SECAM_G,  V4L2_STD_SECAM_H,
229     V4L2_STD_SECAM_K, V4L2_STD_SECAM_K1, V4L2_STD_SECAM_L,  V4L2_STD_SECAM_LC,
230     V4L2_STD_ATSC_8_VSB, V4L2_STD_ATSC_16_VSB,
231 };
232 static const char *const standards_vlc[] = { "", "ALL",
233     /* Pseudo standards */
234     "PAL", "PAL_BG", "PAL_DK",
235     "NTSC",
236     "SECAM", "SECAM_DK",
237     "MTS", "525_60", "625_50",
238     "ATSC",
239
240     /* Chroma-agnostic ITU standards (PAL/NTSC or PAL/SECAM) */
241     "B",              "G",               "H",               "L",
242     "GH",             "DK",              "BG",              "MN",
243
244     /* Individual standards */
245     "PAL_B",          "PAL_B1",          "PAL_G",           "PAL_H",
246     "PAL_I",          "PAL_D",           "PAL_D1",          "PAL_K",
247     "PAL_M",          "PAL_N",           "PAL_Nc",          "PAL_60",
248     "NTSC_M",         "NTSC_M_JP",       "NTSC_443",        "NTSC_M_KR",
249     "SECAM_B",        "SECAM_D",         "SECAM_G",         "SECAM_H",
250     "SECAM_K",        "SECAM_K1",        "SECAM_L",         "SECAM_LC",
251     "ATSC_8_VSB",     "ATSC_16_VSB",
252 };
253 static const char *const standards_user[] = { N_("Undefined"), N_("All"),
254     "PAL",            "PAL B/G",         "PAL D/K",
255     "NTSC",
256     "SECAM",          "SECAM D/K",
257     N_("Multichannel television sound (MTS)"),
258     N_("525 lines / 60 Hz"), N_("625 lines / 50 Hz"),
259     "ATSC",
260
261     "PAL/SECAM B",    "PAL/SECAM G",     "PAL/SECAM H",     "PAL/SECAM L",
262     "PAL/SECAM G/H",  "PAL/SECAM D/K",   "PAL/SECAM B/G",   "PAL/NTSC M/N",
263
264     "PAL B",          "PAL B1",          "PAL G",           "PAL H",
265     "PAL I",          "PAL D",           "PAL D1",          "PAL K",
266     "PAL M",          "PAL N",           N_("PAL N Argentina"), "PAL 60",
267     "NTSC M",        N_("NTSC M Japan"), "NTSC 443",  N_("NTSC M South Korea"),
268     "SECAM B",        "SECAM D",         "SECAM G",         "SECAM H",
269     "SECAM K",        "SECAM K1",        "SECAM L",         "SECAM L/C",
270     "ATSC 8-VSB",     "ATSC 16-VSB",
271 };
272
273 static const int i_tuner_audio_modes_list[] = {
274       V4L2_TUNER_MODE_MONO, V4L2_TUNER_MODE_STEREO,
275       V4L2_TUNER_MODE_LANG1, V4L2_TUNER_MODE_LANG2, V4L2_TUNER_MODE_LANG1_LANG2
276 };
277 static const char *const psz_tuner_audio_modes_list_text[] = {
278       N_("Mono"),
279       N_("Stereo"),
280       N_("Primary language"),
281       N_("Secondary language or program"),
282       N_("Dual mono" )
283 };
284
285 #define V4L2_DEFAULT "/dev/video0"
286
287 vlc_module_begin ()
288     set_shortname( N_("Video4Linux2") )
289     set_description( N_("Video4Linux2 input") )
290     set_category( CAT_INPUT )
291     set_subcategory( SUBCAT_INPUT_ACCESS )
292
293     set_section( N_( "Video input" ), NULL )
294     add_loadfile( CFG_PREFIX "dev", "/dev/video0",
295                   DEVICE_TEXT, DEVICE_LONGTEXT, false )
296         change_safe()
297     add_string( CFG_PREFIX "standard", "",
298                 STANDARD_TEXT, STANDARD_LONGTEXT, false )
299         change_string_list( standards_vlc, standards_user, NULL )
300         change_safe()
301     add_string( CFG_PREFIX "chroma", NULL, CHROMA_TEXT, CHROMA_LONGTEXT,
302                 true )
303         change_safe()
304     add_integer( CFG_PREFIX "input", 0, INPUT_TEXT, INPUT_LONGTEXT,
305                 true )
306         change_integer_range( 0, 0xFFFFFFFE )
307         change_safe()
308     add_integer( CFG_PREFIX "audio-input", -1, AUDIO_INPUT_TEXT,
309                  AUDIO_INPUT_LONGTEXT, true )
310         change_integer_range( -1, 0xFFFFFFFE )
311         change_safe()
312     add_obsolete_integer( CFG_PREFIX "io" ) /* since 2.0.0 */
313     add_integer( CFG_PREFIX "width", 0, WIDTH_TEXT, SIZE_LONGTEXT, false )
314         change_integer_range( 0, VOUT_MAX_WIDTH )
315         change_safe()
316     add_integer( CFG_PREFIX "height", 0, HEIGHT_TEXT, SIZE_LONGTEXT, false )
317         change_integer_range( 0, VOUT_MAX_WIDTH )
318         change_safe()
319     add_string( CFG_PREFIX "aspect-ratio", "4:3", ASPECT_TEXT,
320               ASPECT_LONGTEXT, true )
321         change_safe()
322     add_float( CFG_PREFIX "fps", 0, FPS_TEXT, FPS_LONGTEXT, true )
323         change_safe()
324     add_obsolete_bool( CFG_PREFIX "use-libv4l2" ) /* since 2.1.0 */
325
326     set_section( N_( "Tuner" ), NULL )
327     add_obsolete_integer( CFG_PREFIX "tuner" ) /* since 2.1.0 */
328     add_integer( CFG_PREFIX "tuner-frequency", -1, FREQUENCY_TEXT,
329                  FREQUENCY_LONGTEXT, true )
330         change_integer_range( -1, 0xFFFFFFFE )
331         change_safe()
332     add_integer( CFG_PREFIX "tuner-audio-mode", V4L2_TUNER_MODE_LANG1,
333                  TUNER_AUDIO_MODE_TEXT, TUNER_AUDIO_MODE_LONGTEXT, true )
334         change_integer_list( i_tuner_audio_modes_list,
335                              psz_tuner_audio_modes_list_text )
336         change_safe()
337
338     set_section( N_( "Controls" ),
339                  N_( "Video capture controls (if supported by the device)" ) )
340     add_bool( CFG_PREFIX "controls-reset", false, CTRL_RESET_TEXT,
341               CTRL_RESET_LONGTEXT, true )
342         change_safe()
343     add_integer( CFG_PREFIX "brightness", -1, BRIGHTNESS_TEXT,
344                  BRIGHTNESS_LONGTEXT, true )
345     add_integer( CFG_PREFIX "brightness-auto", -1,
346                  BRIGHTNESS_AUTO_TEXT, BRIGHTNESS_AUTO_LONGTEXT, true )
347         change_integer_list( tristate_vlc, tristate_user )
348     add_integer( CFG_PREFIX "contrast", -1, CONTRAST_TEXT,
349                  CONTRAST_LONGTEXT, true )
350     add_integer( CFG_PREFIX "saturation", -1, SATURATION_TEXT,
351                  SATURATION_LONGTEXT, true )
352     add_integer( CFG_PREFIX "hue", -1, HUE_TEXT,
353                  HUE_LONGTEXT, true )
354     add_integer( CFG_PREFIX "hue-auto", -1,
355                  HUE_AUTO_TEXT, HUE_AUTO_LONGTEXT, true )
356         change_integer_list( tristate_vlc, tristate_user )
357     add_obsolete_integer( CFG_PREFIX "black-level" ) /* since Linux 2.6.26 */
358     add_integer( CFG_PREFIX "white-balance-temperature", -1,
359                  WHITE_BALANCE_TEMP_TEXT, WHITE_BALANCE_TEMP_LONGTEXT, true )
360         /* Ideally, the range should be 2800-6500 */
361         change_integer_range( -1, 6500 )
362     add_integer( CFG_PREFIX "auto-white-balance", -1,
363                  AUTOWHITEBALANCE_TEXT, AUTOWHITEBALANCE_LONGTEXT, true )
364         change_integer_list( tristate_vlc, tristate_user )
365     add_obsolete_integer( CFG_PREFIX"do-white-balance" ) /* since 2.0.0 */
366     add_integer( CFG_PREFIX "red-balance", -1, REDBALANCE_TEXT,
367                  REDBALANCE_LONGTEXT, true )
368     add_integer( CFG_PREFIX "blue-balance", -1, BLUEBALANCE_TEXT,
369                  BLUEBALANCE_LONGTEXT, true )
370     add_integer( CFG_PREFIX "gamma", -1, GAMMA_TEXT,
371                  GAMMA_LONGTEXT, true )
372     add_integer( CFG_PREFIX "autogain", -1, AUTOGAIN_TEXT,
373                  AUTOGAIN_LONGTEXT, true )
374         change_integer_list( tristate_vlc, tristate_user )
375     add_integer( CFG_PREFIX "gain", -1, GAIN_TEXT,
376                  GAIN_LONGTEXT, true )
377     add_integer( CFG_PREFIX "sharpness", -1,
378                  SHARPNESS_TEXT, SHARPNESS_LONGTEXT, true )
379     add_integer( CFG_PREFIX "chroma-gain", -1,
380                  CHROMA_GAIN_TEXT, CHROMA_GAIN_LONGTEXT, true )
381     add_integer( CFG_PREFIX "chroma-gain-auto", -1,
382                  CHROMA_GAIN_AUTO_TEXT, CHROMA_GAIN_AUTO_LONGTEXT, true )
383     add_integer( CFG_PREFIX"power-line-frequency", -1,
384                  POWER_FREQ_TEXT, POWER_FREQ_LONGTEXT, true )
385         change_integer_list( power_freq_vlc, power_freq_user )
386     add_integer( CFG_PREFIX"backlight-compensation", -1,
387                  BKLT_COMPENSATE_TEXT, BKLT_COMPENSATE_LONGTEXT, true )
388     add_integer( CFG_PREFIX "band-stop-filter", -1,
389                  BAND_STOP_FILTER_TEXT, BAND_STOP_FILTER_LONGTEXT, true )
390     add_bool( CFG_PREFIX "hflip", false, HFLIP_TEXT, HFLIP_LONGTEXT, true )
391     add_bool( CFG_PREFIX "vflip", false, VFLIP_TEXT, VFLIP_LONGTEXT, true )
392     add_integer( CFG_PREFIX "rotate", -1, ROTATE_TEXT, ROTATE_LONGTEXT, true )
393         change_integer_range( -1, 359 )
394     add_obsolete_integer( CFG_PREFIX "hcenter" ) /* since Linux 2.6.26 */
395     add_obsolete_integer( CFG_PREFIX "vcenter" ) /* since Linux 2.6.26 */
396     add_integer( CFG_PREFIX"color-killer", -1,
397                  COLOR_KILLER_TEXT, COLOR_KILLER_LONGTEXT, true )
398         change_integer_list( tristate_vlc, tristate_user )
399     add_integer( CFG_PREFIX"color-effect", -1,
400                  COLOR_EFFECT_TEXT, COLOR_EFFECT_LONGTEXT, true )
401         change_integer_list( colorfx_vlc, colorfx_user )
402
403     add_integer( CFG_PREFIX "audio-volume", -1, AUDIO_VOLUME_TEXT,
404                 AUDIO_VOLUME_LONGTEXT, true )
405     add_integer( CFG_PREFIX "audio-balance", -1, AUDIO_BALANCE_TEXT,
406                 AUDIO_BALANCE_LONGTEXT, true )
407     add_bool( CFG_PREFIX "audio-mute", false, AUDIO_MUTE_TEXT,
408               AUDIO_MUTE_LONGTEXT, true )
409     add_integer( CFG_PREFIX "audio-bass", -1, AUDIO_BASS_TEXT,
410                 AUDIO_BASS_LONGTEXT, true )
411     add_integer( CFG_PREFIX "audio-treble", -1, AUDIO_TREBLE_TEXT,
412                 AUDIO_TREBLE_LONGTEXT, true )
413     add_bool( CFG_PREFIX "audio-loudness", false, AUDIO_LOUDNESS_TEXT,
414               AUDIO_LOUDNESS_LONGTEXT, true )
415     add_string( CFG_PREFIX "set-ctrls", NULL, S_CTRLS_TEXT,
416               S_CTRLS_LONGTEXT, true )
417         change_safe()
418
419     add_obsolete_string( CFG_PREFIX "adev" )
420     add_obsolete_integer( CFG_PREFIX "audio-method" )
421     add_obsolete_bool( CFG_PREFIX "stereo" )
422     add_obsolete_integer( CFG_PREFIX "samplerate" )
423
424     add_shortcut( "v4l2" )
425     set_capability( "access_demux", 0 )
426     set_callbacks( DemuxOpen, DemuxClose )
427
428     add_submodule ()
429     add_shortcut( "v4l2", "v4l2c" )
430     set_description( N_("Video4Linux2 Compressed A/V") )
431     set_capability( "access", 0 )
432     /* use these when open as access_demux fails; VLC will use another demux */
433     set_callbacks( AccessOpen, AccessClose )
434
435 vlc_module_end ()
436
437 /*****************************************************************************
438  * Access: local prototypes
439  *****************************************************************************/
440
441 /**
442  * Parses a V4L2 MRL into VLC object variables.
443  */
444 void ParseMRL( vlc_object_t *obj, const char *mrl )
445 {
446     const char *p = strchr( mrl, ':' );
447     char *dev = NULL;
448
449     if( p != NULL )
450     {
451         var_LocationParse( obj, p + 1, CFG_PREFIX );
452         if( p > mrl )
453             dev = strndup( mrl, p - mrl );
454     }
455     else
456     {
457         if( mrl[0] )
458             dev = strdup( mrl );
459     }
460
461     if( dev != NULL )
462     {
463         var_Create( obj, CFG_PREFIX"dev", VLC_VAR_STRING );
464         var_SetString( obj, CFG_PREFIX"dev", dev );
465         free( dev );
466     }
467 }
468
469 static v4l2_std_id var_InheritStandard (vlc_object_t *obj, const char *varname)
470 {
471     char *name = var_InheritString (obj, varname);
472     if (name == NULL)
473         return V4L2_STD_UNKNOWN;
474
475     const size_t n = sizeof (standards_vlc) / sizeof (*standards_vlc);
476
477     static_assert (sizeof (standards_vlc) / sizeof (*standards_vlc)
478                          == sizeof (standards_v4l2) / sizeof (*standards_v4l2),
479                    "Inconsistent standards tables");
480     static_assert (sizeof (standards_vlc) / sizeof (*standards_vlc)
481                          == sizeof (standards_user) / sizeof (*standards_user),
482                    "Inconsistent standards tables");
483
484     for (size_t i = 0; i < n; i++)
485         if (strcasecmp (name, standards_vlc[i]) == 0)
486         {
487             free (name);
488             return standards_v4l2[i];
489         }
490
491     /* Backward compatibility with old versions using V4L2 magic numbers */
492     char *end;
493     v4l2_std_id std = strtoull (name, &end, 0);
494     if (*end != '\0')
495     {
496         msg_Err (obj, "unknown video standard \"%s\"", name);
497         std = V4L2_STD_UNKNOWN;
498     }
499     free (name);
500     return std;
501 }
502
503 static int SetupStandard (vlc_object_t *obj, int fd,
504                           const struct v4l2_input *restrict input)
505 {
506 #ifdef V4L2_IN_CAP_STD
507     if (!(input->capabilities & V4L2_IN_CAP_STD))
508     {
509         msg_Dbg (obj, "no video standard selection");
510         return 0;
511     }
512 #else
513     (void) input;
514     msg_Dbg (obj, "video standard selection unknown");
515 #endif
516     v4l2_std_id std = var_InheritStandard (obj, CFG_PREFIX"standard");
517     if (std == V4L2_STD_UNKNOWN)
518     {
519         msg_Warn (obj, "video standard not set");
520         return 0;
521     }
522     if (v4l2_ioctl (fd, VIDIOC_S_STD, &std) < 0)
523     {
524         msg_Err (obj, "cannot set video standard 0x%"PRIx64": %m", std);
525         return -1;
526     }
527     msg_Dbg (obj, "video standard set to 0x%"PRIx64":", std);
528     return 0;
529 }
530
531 static int SetupAudio (vlc_object_t *obj, int fd,
532                        const struct v4l2_input *restrict input)
533 {
534     if (input->audioset == 0)
535     {
536         msg_Dbg (obj, "no audio input available");
537         return 0;
538     }
539     msg_Dbg (obj, "available audio inputs: 0x%08"PRIX32, input->audioset);
540
541     uint32_t idx = var_InheritInteger (obj, CFG_PREFIX"audio-input");
542     if (idx == (uint32_t)-1)
543     {
544         msg_Dbg (obj, "no audio input selected");
545         return 0;
546     }
547     if (((1 << idx) & input->audioset) == 0)
548     {
549         msg_Warn (obj, "skipped unavailable audio input %"PRIu32, idx);
550         return -1;
551     }
552
553     /* TODO: Enumerate other selectable audio inputs. How to expose them? */
554     struct v4l2_audio enumaudio = { .index = idx };
555
556     if (v4l2_ioctl (fd, VIDIOC_ENUMAUDIO, &enumaudio) < 0)
557     {
558         msg_Err (obj, "cannot get audio input %"PRIu32" properties: %m", idx);
559         return -1;
560     }
561
562     msg_Dbg (obj, "audio input %s (%"PRIu32") is %s"
563              " (capabilities: 0x%08"PRIX32")", enumaudio.name, enumaudio.index,
564              (enumaudio.capability & V4L2_AUDCAP_STEREO) ? "Stereo" : "Mono",
565              enumaudio.capability);
566     if (enumaudio.capability & V4L2_AUDCAP_AVL)
567         msg_Dbg (obj, " supports Automatic Volume Level");
568
569     /* TODO: AVL mode */
570     struct v4l2_audio audio = { .index = idx };
571
572     if (v4l2_ioctl (fd, VIDIOC_S_AUDIO, &audio) < 0)
573     {
574         msg_Err (obj, "cannot select audio input %"PRIu32": %m", idx);
575         return -1;
576     }
577     msg_Dbg (obj, "selected audio input %"PRIu32, idx);
578     return 0;
579 }
580
581 static int SetupTuner (vlc_object_t *obj, int fd,
582                        const struct v4l2_input *restrict input)
583 {
584     switch (input->type)
585     {
586         case V4L2_INPUT_TYPE_TUNER:
587             msg_Dbg (obj, "tuning required: tuner %"PRIu32, input->tuner);
588             break;
589         case V4L2_INPUT_TYPE_CAMERA:
590             msg_Dbg (obj, "no tuning required (analog baseband input)");
591             return 0;
592         default:
593             msg_Err (obj, "unknown input tuning type %"PRIu32, input->type);
594             return 0; // hopefully we can stream regardless...
595     }
596
597     struct v4l2_tuner tuner = { .index = input->tuner };
598
599     if (v4l2_ioctl (fd, VIDIOC_G_TUNER, &tuner) < 0)
600     {
601         msg_Err (obj, "cannot get tuner %"PRIu32" properties: %m",
602                  input->tuner);
603         return -1;
604     }
605
606     /* NOTE: This is overkill. Only video devices currently work, so the
607      * type is always analog TV. */
608     const char *typename, *mult;
609     switch (tuner.type)
610     {
611         case V4L2_TUNER_RADIO:
612             typename = "Radio";
613             break;
614         case V4L2_TUNER_ANALOG_TV:
615             typename = "Analog TV";
616             break;
617         default:
618             typename = "unknown";
619     }
620     mult = (tuner.capability & V4L2_TUNER_CAP_LOW) ? "" : "k";
621
622     msg_Dbg (obj, "tuner %s (%"PRIu32") is %s", tuner.name, tuner.index,
623              typename);
624     msg_Dbg (obj, " ranges from %u.%u %sHz to %u.%c %sHz",
625              (tuner.rangelow * 125) >> 1, (tuner.rangelow & 1) * 5, mult,
626              (tuner.rangehigh * 125) >> 1, (tuner.rangehigh & 1) * 5,
627              mult);
628
629     /* TODO: only set video standard if the tuner requires it */
630
631     /* Configure the audio mode */
632     /* TODO: Ideally, L1 would be selected for stereo tuners, and L1_L2
633      * for mono tuners. When dual-mono is detected after tuning on a stereo
634      * tuner, we would fallback to L1_L2 too. Then we would flag dual-mono
635      * for the audio E/S. Unfortunately, we have no access to the audio E/S
636      * here (it belongs in the slave audio input...). */
637     tuner.audmode = var_InheritInteger (obj, CFG_PREFIX"tuner-audio-mode");
638     memset (tuner.reserved, 0, sizeof (tuner.reserved));
639
640     if (tuner.capability & V4L2_TUNER_CAP_LANG1)
641         msg_Dbg (obj, " supports primary audio language");
642     else if (tuner.audmode == V4L2_TUNER_MODE_LANG1)
643     {
644         msg_Warn (obj, " falling back to stereo mode");
645         tuner.audmode = V4L2_TUNER_MODE_STEREO;
646     }
647     if (tuner.capability & V4L2_TUNER_CAP_LANG2)
648         msg_Dbg (obj, " supports secondary audio language or program");
649     if (tuner.capability & V4L2_TUNER_CAP_STEREO)
650         msg_Dbg (obj, " supports stereo audio");
651     else if (tuner.audmode == V4L2_TUNER_MODE_STEREO)
652     {
653         msg_Warn (obj, " falling back to mono mode");
654         tuner.audmode = V4L2_TUNER_MODE_MONO;
655     }
656
657     if (v4l2_ioctl (fd, VIDIOC_S_TUNER, &tuner) < 0)
658     {
659         msg_Err (obj, "cannot set tuner %"PRIu32" audio mode: %m",
660                  input->tuner);
661         return -1;
662     }
663     msg_Dbg (obj, "tuner %"PRIu32" audio mode %u set", input->tuner,
664              tuner.audmode);
665
666     /* Tune to the requested frequency */
667     uint32_t freq = var_InheritInteger (obj, CFG_PREFIX"tuner-frequency");
668     if (freq != (uint32_t)-1)
669     {
670         struct v4l2_frequency frequency = {
671             .tuner = input->tuner,
672             .type = V4L2_TUNER_ANALOG_TV,
673             .frequency = freq * 125 / 2
674         };
675
676         if (v4l2_ioctl (fd, VIDIOC_S_FREQUENCY, &frequency) < 0)
677         {
678             msg_Err (obj, "cannot tuner tuner %u to frequency %u %sHz: %m",
679                      input->tuner, freq, mult);
680             return -1;
681         }
682     }
683     msg_Dbg (obj, "tuner %"PRIu32" tuned to frequency %"PRIu32" %sHz",
684              input->tuner, freq, mult);
685     return 0;
686 }
687
688 static int ResetCrop (vlc_object_t *obj, int fd)
689 {
690     struct v4l2_cropcap cropcap = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
691
692     /* In theory, this ioctl() must work for all video capture devices.
693      * In practice, it does not. */
694     if (v4l2_ioctl (fd, VIDIOC_CROPCAP, &cropcap) < 0)
695     {
696         msg_Warn (obj, "cannot get cropping properties: %m");
697         return -1;
698     }
699
700     /* Reset to the default cropping rectangle */
701     struct v4l2_crop crop = {
702         .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
703         .c = cropcap.defrect,
704     };
705
706     if (v4l2_ioctl (fd, VIDIOC_S_CROP, &crop) < 0)
707     {
708         msg_Warn (obj, "cannot reset cropping limits: %m");
709         return -1;
710     }
711     return 0;
712 }
713
714 int SetupInput (vlc_object_t *obj, int fd)
715 {
716     struct v4l2_input input;
717
718     input.index = var_InheritInteger (obj, CFG_PREFIX"input");
719     if (v4l2_ioctl (fd, VIDIOC_ENUMINPUT, &input) < 0)
720     {
721         msg_Err (obj, "invalid video input %"PRIu32": %m", input.index);
722         return -1;
723     }
724
725     const char *typename = "unknown";
726     switch (input.type)
727     {
728         case V4L2_INPUT_TYPE_TUNER:
729             typename = "tuner";
730             break;
731         case V4L2_INPUT_TYPE_CAMERA:
732             typename = "camera";
733             break;
734     }
735
736     msg_Dbg (obj, "video input %s (%"PRIu32") is %s", input.name,
737              input.index, typename);
738
739     /* Select input */
740     if (v4l2_ioctl (fd, VIDIOC_S_INPUT, &input.index) < 0)
741     {
742         msg_Err (obj, "cannot select input %"PRIu32": %m", input.index);
743         return -1;
744     }
745     msg_Dbg (obj, "selected input %"PRIu32, input.index);
746
747     SetupStandard (obj, fd, &input);
748     SetupTuner (obj, fd, &input);
749     SetupAudio (obj, fd, &input);
750     return 0;
751 }
752
753 /** Compares two V4L2 fractions. */
754 static int64_t fcmp (const struct v4l2_fract *a,
755                      const struct v4l2_fract *b)
756 {
757     return (uint64_t)a->numerator * b->denominator
758          - (uint64_t)b->numerator * a->denominator;
759 }
760
761 static const struct v4l2_fract infinity = { 1, 0 };
762
763 /**
764  * Finds the highest frame rate possible of a certain V4L2 format.
765  * @param fmt V4L2 capture format [IN]
766  * @param it V4L2 frame interval [OUT]
767  * @return 0 on success, -1 on error.
768  */
769 static int FindMaxRate (vlc_object_t *obj, int fd,
770                         const struct v4l2_format *restrict fmt,
771                         struct v4l2_fract *restrict it)
772 {
773     struct v4l2_frmivalenum fie = {
774         .pixel_format = fmt->fmt.pix.pixelformat,
775         .width = fmt->fmt.pix.width,
776         .height = fmt->fmt.pix.height,
777     };
778     /* Mind that maximum rate means minimum interval */
779
780     if (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMEINTERVALS, &fie) < 0)
781     {
782         msg_Dbg (obj, "  unknown frame intervals: %m");
783         /* Frame intervals cannot be enumerated. Set the format and then
784          * get the streaming parameters to figure out the default frame
785          * interval. This is not necessarily the maximum though. */
786         struct v4l2_format dummy_fmt = *fmt;
787         struct v4l2_streamparm parm = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
788
789         if (v4l2_ioctl (fd, VIDIOC_S_FMT, &dummy_fmt) < 0
790          || v4l2_ioctl (fd, VIDIOC_G_PARM, &parm) < 0)
791         {
792             *it = infinity;
793             return -1;
794         }
795
796         *it = parm.parm.capture.timeperframe;
797         msg_Dbg (obj, "  %s frame interval: %"PRIu32"/%"PRIu32,
798                  (parm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME)
799                  ? "default" : "constant", it->numerator, it->denominator);
800     }
801     else
802     switch (fie.type)
803     {
804         case V4L2_FRMIVAL_TYPE_DISCRETE:
805             *it = infinity;
806             do
807             {
808                 if (fcmp (&fie.discrete, it) < 0)
809                     *it = fie.discrete;
810                 fie.index++;
811             }
812             while (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMEINTERVALS, &fie) >= 0);
813
814             msg_Dbg (obj, "  %s frame interval: %"PRIu32"/%"PRIu32,
815                      "discrete", it->numerator, it->denominator);
816             break;
817
818         case V4L2_FRMIVAL_TYPE_STEPWISE:
819         case V4L2_FRMIVAL_TYPE_CONTINUOUS:
820             msg_Dbg (obj, "  frame intervals from %"PRIu32"/%"PRIu32
821                      "to %"PRIu32"/%"PRIu32" supported",
822                      fie.stepwise.min.numerator, fie.stepwise.min.denominator,
823                      fie.stepwise.max.numerator, fie.stepwise.max.denominator);
824             if (fie.type == V4L2_FRMIVAL_TYPE_STEPWISE)
825                 msg_Dbg (obj, "  with %"PRIu32"/%"PRIu32" step",
826                          fie.stepwise.step.numerator,
827                          fie.stepwise.step.denominator);
828             *it = fie.stepwise.min;
829             break;
830     }
831     return 0;
832 }
833
834 #undef SetupFormat
835 /**
836  * Finds the best possible frame rate and resolution.
837  * @param fourcc pixel format
838  * @param fmt V4L2 capture format [OUT]
839  * @param parm V4L2 capture streaming parameters [OUT]
840  * @return 0 on success, -1 on failure.
841  */
842 int SetupFormat (vlc_object_t *obj, int fd, uint32_t fourcc,
843                  struct v4l2_format *restrict fmt,
844                  struct v4l2_streamparm *restrict parm)
845 {
846     memset (fmt, 0, sizeof (*fmt));
847     fmt->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
848     memset (parm, 0, sizeof (*parm));
849     parm->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
850
851     if (v4l2_ioctl (fd, VIDIOC_G_FMT, fmt) < 0)
852     {
853         msg_Err (obj, "cannot get default format: %m");
854         return -1;
855     }
856     fmt->fmt.pix.pixelformat = fourcc;
857
858     struct v4l2_frmsizeenum fse = {
859         .pixel_format = fourcc,
860     };
861     struct v4l2_fract best_it = infinity;
862     uint64_t best_area = 0;
863
864     uint32_t width = var_InheritInteger (obj, CFG_PREFIX"width");
865     uint32_t height = var_InheritInteger (obj, CFG_PREFIX"height");
866     if (width > 0 && height > 0)
867     {
868         fmt->fmt.pix.width = width;
869         fmt->fmt.pix.height = height;
870         msg_Dbg (obj, " requested frame size: %"PRIu32"x%"PRIu32,
871                  width, height);
872         FindMaxRate (obj, fd, fmt, &best_it);
873     }
874     else
875     if (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMESIZES, &fse) < 0)
876     {
877         /* Fallback to current format, try to maximize frame rate */
878         msg_Dbg (obj, " unknown frame sizes: %m");
879         msg_Dbg (obj, " current frame size: %"PRIu32"x%"PRIu32,
880                  fmt->fmt.pix.width, fmt->fmt.pix.height);
881         FindMaxRate (obj, fd, fmt, &best_it);
882     }
883     else
884     switch (fse.type)
885     {
886         case V4L2_FRMSIZE_TYPE_DISCRETE:
887             do
888             {
889                 struct v4l2_fract cur_it;
890
891                 msg_Dbg (obj, " frame size %"PRIu32"x%"PRIu32,
892                          fse.discrete.width, fse.discrete.height);
893                 FindMaxRate (obj, fd, fmt, &cur_it);
894
895                 int64_t c = fcmp (&cur_it, &best_it);
896                 uint64_t area = fse.discrete.width * fse.discrete.height;
897                 if (c < 0 || (c == 0 && area > best_area))
898                 {
899                     best_it = cur_it;
900                     best_area = area;
901                     fmt->fmt.pix.width = fse.discrete.width;
902                     fmt->fmt.pix.height = fse.discrete.height;
903                 }
904
905                 fse.index++;
906             }
907             while (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMESIZES, &fse) >= 0);
908
909             msg_Dbg (obj, " best discrete frame size: %"PRIu32"x%"PRIu32,
910                      fmt->fmt.pix.width, fmt->fmt.pix.height);
911             break;
912
913         case V4L2_FRMSIZE_TYPE_STEPWISE:
914         case V4L2_FRMSIZE_TYPE_CONTINUOUS:
915             msg_Dbg (obj, " frame sizes from %"PRIu32"x%"PRIu32" to "
916                      "%"PRIu32"x%"PRIu32" supported",
917                      fse.stepwise.min_width, fse.stepwise.min_height,
918                      fse.stepwise.max_width, fse.stepwise.max_height);
919             if (fse.type == V4L2_FRMSIZE_TYPE_STEPWISE)
920                 msg_Dbg (obj, "  with %"PRIu32"x%"PRIu32" steps",
921                          fse.stepwise.step_width, fse.stepwise.step_height);
922
923             /* FIXME: slow and dumb */
924             for (uint32_t width =  fse.stepwise.min_width;
925                           width <= fse.stepwise.max_width;
926                           width += fse.stepwise.step_width)
927                 for (uint32_t height =  fse.stepwise.min_height;
928                               height <= fse.stepwise.max_width;
929                               height += fse.stepwise.step_height)
930                 {
931                     struct v4l2_fract cur_it;
932
933                     FindMaxRate (obj, fd, fmt, &cur_it);
934
935                     int64_t c = fcmp (&cur_it, &best_it);
936                     uint64_t area = width * height;
937
938                     if (c < 0 || (c == 0 && area > best_area))
939                     {
940                         best_it = cur_it;
941                         best_area = area;
942                         fmt->fmt.pix.width = width;
943                         fmt->fmt.pix.height = height;
944                     }
945                 }
946
947             msg_Dbg (obj, " best frame size: %"PRIu32"x%"PRIu32,
948                      fmt->fmt.pix.width, fmt->fmt.pix.height);
949             break;
950     }
951
952     /* Set the final format */
953     if (v4l2_ioctl (fd, VIDIOC_S_FMT, fmt) < 0)
954     {
955         msg_Err (obj, "cannot set format: %m");
956         return -1;
957     }
958
959     /* Now that the final format is set, fetch and override parameters */
960     if (v4l2_ioctl (fd, VIDIOC_G_PARM, parm) < 0)
961     {
962         msg_Err (obj, "cannot get streaming parameters: %m");
963         return -1;
964     }
965     parm->parm.capture.capturemode = 0; /* normal video mode */
966     parm->parm.capture.extendedmode = 0;
967     if (best_it.denominator != 0)
968         parm->parm.capture.timeperframe = best_it;
969     if (v4l2_ioctl (fd, VIDIOC_S_PARM, parm) < 0)
970         msg_Warn (obj, "cannot set streaming parameters: %m");
971
972     ResetCrop (obj, fd); /* crop depends on frame size */
973
974     return 0;
975 }
976
977
978 /*****************************************************************************
979  * GrabVideo: Grab a video frame
980  *****************************************************************************/
981 block_t* GrabVideo (vlc_object_t *demux, demux_sys_t *sys)
982 {
983     struct v4l2_buffer buf = {
984         .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
985         .memory = V4L2_MEMORY_MMAP,
986     };
987
988     /* Wait for next frame */
989     if (v4l2_ioctl (sys->i_fd, VIDIOC_DQBUF, &buf) < 0)
990     {
991         switch (errno)
992         {
993             case EAGAIN:
994                 return NULL;
995             case EIO:
996                 /* Could ignore EIO, see spec. */
997                 /* fall through */
998             default:
999                 msg_Err (demux, "dequeue error: %m");
1000                 return NULL;
1001         }
1002     }
1003
1004     if (buf.index >= sys->i_nbuffers) {
1005         msg_Err (demux, "Failed capturing new frame as i>=nbuffers");
1006         return NULL;
1007     }
1008
1009     /* Copy frame */
1010     block_t *block = block_Alloc (buf.bytesused);
1011     if (unlikely(block == NULL))
1012         return NULL;
1013     memcpy (block->p_buffer, sys->p_buffers[buf.index].start, buf.bytesused);
1014
1015     /* Unlock */
1016     if (v4l2_ioctl (sys->i_fd, VIDIOC_QBUF, &buf) < 0)
1017     {
1018         msg_Err (demux, "queue error: %m");
1019         block_Release (block);
1020         return NULL;
1021     }
1022     return block;
1023 }
1024
1025 /*****************************************************************************
1026  * Helper function to initalise video IO using the mmap method
1027  *****************************************************************************/
1028 int InitMmap( vlc_object_t *p_demux, demux_sys_t *p_sys, int i_fd )
1029 {
1030     struct v4l2_requestbuffers req;
1031
1032     memset( &req, 0, sizeof(req) );
1033     req.count = 4;
1034     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1035     req.memory = V4L2_MEMORY_MMAP;
1036
1037     if( v4l2_ioctl( i_fd, VIDIOC_REQBUFS, &req ) < 0 )
1038     {
1039         msg_Err( p_demux, "device does not support mmap I/O" );
1040         return -1;
1041     }
1042
1043     if( req.count < 2 )
1044     {
1045         msg_Err( p_demux, "insufficient buffers" );
1046         return -1;
1047     }
1048
1049     p_sys->p_buffers = calloc( req.count, sizeof( *p_sys->p_buffers ) );
1050     if( unlikely(!p_sys->p_buffers) )
1051         return -1;
1052
1053     for( p_sys->i_nbuffers = 0; p_sys->i_nbuffers < req.count; ++p_sys->i_nbuffers )
1054     {
1055         struct v4l2_buffer buf;
1056
1057         memset( &buf, 0, sizeof(buf) );
1058         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1059         buf.memory = V4L2_MEMORY_MMAP;
1060         buf.index = p_sys->i_nbuffers;
1061
1062         if( v4l2_ioctl( i_fd, VIDIOC_QUERYBUF, &buf ) < 0 )
1063         {
1064             msg_Err( p_demux, "VIDIOC_QUERYBUF: %m" );
1065             return -1;
1066         }
1067
1068         p_sys->p_buffers[p_sys->i_nbuffers].length = buf.length;
1069         p_sys->p_buffers[p_sys->i_nbuffers].start =
1070             v4l2_mmap( NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, i_fd, buf.m.offset );
1071
1072         if( p_sys->p_buffers[p_sys->i_nbuffers].start == MAP_FAILED )
1073         {
1074             msg_Err( p_demux, "mmap failed: %m" );
1075             return -1;
1076         }
1077     }
1078
1079     return 0;
1080 }