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