]> git.sesse.net Git - vlc/blob - modules/access/v4l2/video.c
v4l2: correct frame rate if enumeration fails
[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 static block_t* ProcessVideoFrame( vlc_object_t *p_demux, uint8_t *p_frame, size_t );
442
443 /**
444  * Parses a V4L2 MRL into VLC object variables.
445  */
446 void ParseMRL( vlc_object_t *obj, const char *mrl )
447 {
448     const char *p = strchr( mrl, ':' );
449     char *dev = NULL;
450
451     if( p != NULL )
452     {
453         var_LocationParse( obj, p + 1, CFG_PREFIX );
454         if( p > mrl )
455             dev = strndup( mrl, p - mrl );
456     }
457     else
458     {
459         if( mrl[0] )
460             dev = strdup( mrl );
461     }
462
463     if( dev != NULL )
464     {
465         var_Create( obj, CFG_PREFIX"dev", VLC_VAR_STRING );
466         var_SetString( obj, CFG_PREFIX"dev", dev );
467         free( dev );
468     }
469 }
470
471 static v4l2_std_id var_InheritStandard (vlc_object_t *obj, const char *varname)
472 {
473     char *name = var_InheritString (obj, varname);
474     if (name == NULL)
475         return V4L2_STD_UNKNOWN;
476
477     const size_t n = sizeof (standards_vlc) / sizeof (*standards_vlc);
478
479     static_assert (sizeof (standards_vlc) / sizeof (*standards_vlc)
480                          == sizeof (standards_v4l2) / sizeof (*standards_v4l2),
481                    "Inconsistent standards tables");
482     static_assert (sizeof (standards_vlc) / sizeof (*standards_vlc)
483                          == sizeof (standards_user) / sizeof (*standards_user),
484                    "Inconsistent standards tables");
485
486     for (size_t i = 0; i < n; i++)
487         if (strcasecmp (name, standards_vlc[i]) == 0)
488         {
489             free (name);
490             return standards_v4l2[i];
491         }
492
493     /* Backward compatibility with old versions using V4L2 magic numbers */
494     char *end;
495     v4l2_std_id std = strtoull (name, &end, 0);
496     if (*end != '\0')
497     {
498         msg_Err (obj, "unknown video standard \"%s\"", name);
499         std = V4L2_STD_UNKNOWN;
500     }
501     free (name);
502     return std;
503 }
504
505 static int SetupStandard (vlc_object_t *obj, int fd,
506                           const struct v4l2_input *restrict input)
507 {
508 #ifdef V4L2_IN_CAP_STD
509     if (!(input->capabilities & V4L2_IN_CAP_STD))
510     {
511         msg_Dbg (obj, "no video standard selection");
512         return 0;
513     }
514 #else
515     (void) input;
516     msg_Dbg (obj, "video standard selection unknown");
517 #endif
518     v4l2_std_id std = var_InheritStandard (obj, CFG_PREFIX"standard");
519     if (std == V4L2_STD_UNKNOWN)
520     {
521         msg_Warn (obj, "video standard not set");
522         return 0;
523     }
524     if (v4l2_ioctl (fd, VIDIOC_S_STD, &std) < 0)
525     {
526         msg_Err (obj, "cannot set video standard 0x%"PRIx64": %m", std);
527         return -1;
528     }
529     msg_Dbg (obj, "video standard set to 0x%"PRIx64":", std);
530     return 0;
531 }
532
533 static int SetupAudio (vlc_object_t *obj, int fd,
534                        const struct v4l2_input *restrict input)
535 {
536     if (input->audioset == 0)
537     {
538         msg_Dbg (obj, "no audio input available");
539         return 0;
540     }
541     msg_Dbg (obj, "available audio inputs: 0x%08"PRIX32, input->audioset);
542
543     uint32_t idx = var_InheritInteger (obj, CFG_PREFIX"audio-input");
544     if (idx == (uint32_t)-1)
545     {
546         msg_Dbg (obj, "no audio input selected");
547         return 0;
548     }
549     if (((1 << idx) & input->audioset) == 0)
550     {
551         msg_Warn (obj, "skipped unavailable audio input %"PRIu32, idx);
552         return -1;
553     }
554
555     /* TODO: Enumerate other selectable audio inputs. How to expose them? */
556     struct v4l2_audio enumaudio = { .index = idx };
557
558     if (v4l2_ioctl (fd, VIDIOC_ENUMAUDIO, &enumaudio) < 0)
559     {
560         msg_Err (obj, "cannot get audio input %"PRIu32" properties: %m", idx);
561         return -1;
562     }
563
564     msg_Dbg (obj, "audio input %s (%"PRIu32") is %s"
565              " (capabilities: 0x%08"PRIX32")", enumaudio.name, enumaudio.index,
566              (enumaudio.capability & V4L2_AUDCAP_STEREO) ? "Stereo" : "Mono",
567              enumaudio.capability);
568     if (enumaudio.capability & V4L2_AUDCAP_AVL)
569         msg_Dbg (obj, " supports Automatic Volume Level");
570
571     /* TODO: AVL mode */
572     struct v4l2_audio audio = { .index = idx };
573
574     if (v4l2_ioctl (fd, VIDIOC_S_AUDIO, &audio) < 0)
575     {
576         msg_Err (obj, "cannot select audio input %"PRIu32": %m", idx);
577         return -1;
578     }
579     msg_Dbg (obj, "selected audio input %"PRIu32, idx);
580     return 0;
581 }
582
583 static int SetupTuner (vlc_object_t *obj, int fd,
584                        const struct v4l2_input *restrict input)
585 {
586     switch (input->type)
587     {
588         case V4L2_INPUT_TYPE_TUNER:
589             msg_Dbg (obj, "tuning required: tuner %"PRIu32, input->tuner);
590             break;
591         case V4L2_INPUT_TYPE_CAMERA:
592             msg_Dbg (obj, "no tuning required (analog baseband input)");
593             return 0;
594         default:
595             msg_Err (obj, "unknown input tuning type %"PRIu32, input->type);
596             return 0; // hopefully we can stream regardless...
597     }
598
599     struct v4l2_tuner tuner = { .index = input->tuner };
600
601     if (v4l2_ioctl (fd, VIDIOC_G_TUNER, &tuner) < 0)
602     {
603         msg_Err (obj, "cannot get tuner %"PRIu32" properties: %m",
604                  input->tuner);
605         return -1;
606     }
607
608     /* NOTE: This is overkill. Only video devices currently work, so the
609      * type is always analog TV. */
610     const char *typename, *mult;
611     switch (tuner.type)
612     {
613         case V4L2_TUNER_RADIO:
614             typename = "Radio";
615             break;
616         case V4L2_TUNER_ANALOG_TV:
617             typename = "Analog TV";
618             break;
619         default:
620             typename = "unknown";
621     }
622     mult = (tuner.capability & V4L2_TUNER_CAP_LOW) ? "" : "k";
623
624     msg_Dbg (obj, "tuner %s (%"PRIu32") is %s", tuner.name, tuner.index,
625              typename);
626     msg_Dbg (obj, " ranges from %u.%u %sHz to %u.%c %sHz",
627              (tuner.rangelow * 125) >> 1, (tuner.rangelow & 1) * 5, mult,
628              (tuner.rangehigh * 125) >> 1, (tuner.rangehigh & 1) * 5,
629              mult);
630
631     /* TODO: only set video standard if the tuner requires it */
632
633     /* Configure the audio mode */
634     /* TODO: Ideally, L1 would be selected for stereo tuners, and L1_L2
635      * for mono tuners. When dual-mono is detected after tuning on a stereo
636      * tuner, we would fallback to L1_L2 too. Then we would flag dual-mono
637      * for the audio E/S. Unfortunately, we have no access to the audio E/S
638      * here (it belongs in the slave audio input...). */
639     tuner.audmode = var_InheritInteger (obj, CFG_PREFIX"tuner-audio-mode");
640     memset (tuner.reserved, 0, sizeof (tuner.reserved));
641
642     if (tuner.capability & V4L2_TUNER_CAP_LANG1)
643         msg_Dbg (obj, " supports primary audio language");
644     else if (tuner.audmode == V4L2_TUNER_MODE_LANG1)
645     {
646         msg_Warn (obj, " falling back to stereo mode");
647         tuner.audmode = V4L2_TUNER_MODE_STEREO;
648     }
649     if (tuner.capability & V4L2_TUNER_CAP_LANG2)
650         msg_Dbg (obj, " supports secondary audio language or program");
651     if (tuner.capability & V4L2_TUNER_CAP_STEREO)
652         msg_Dbg (obj, " supports stereo audio");
653     else if (tuner.audmode == V4L2_TUNER_MODE_STEREO)
654     {
655         msg_Warn (obj, " falling back to mono mode");
656         tuner.audmode = V4L2_TUNER_MODE_MONO;
657     }
658
659     if (v4l2_ioctl (fd, VIDIOC_S_TUNER, &tuner) < 0)
660     {
661         msg_Err (obj, "cannot set tuner %"PRIu32" audio mode: %m",
662                  input->tuner);
663         return -1;
664     }
665     msg_Dbg (obj, "tuner %"PRIu32" audio mode %u set", input->tuner,
666              tuner.audmode);
667
668     /* Tune to the requested frequency */
669     uint32_t freq = var_InheritInteger (obj, CFG_PREFIX"tuner-frequency");
670     if (freq != (uint32_t)-1)
671     {
672         struct v4l2_frequency frequency = {
673             .tuner = input->tuner,
674             .type = V4L2_TUNER_ANALOG_TV,
675             .frequency = freq * 125 / 2
676         };
677
678         if (v4l2_ioctl (fd, VIDIOC_S_FREQUENCY, &frequency) < 0)
679         {
680             msg_Err (obj, "cannot tuner tuner %u to frequency %u %sHz: %m",
681                      input->tuner, freq, mult);
682             return -1;
683         }
684     }
685     msg_Dbg (obj, "tuner %"PRIu32" tuned to frequency %"PRIu32" %sHz",
686              input->tuner, freq, mult);
687     return 0;
688 }
689
690 static int ResetCrop (vlc_object_t *obj, int fd)
691 {
692     struct v4l2_cropcap cropcap = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
693
694     /* In theory, this ioctl() must work for all video capture devices.
695      * In practice, it does not. */
696     if (v4l2_ioctl (fd, VIDIOC_CROPCAP, &cropcap) < 0)
697     {
698         msg_Warn (obj, "cannot get cropping properties: %m");
699         return -1;
700     }
701
702     /* Reset to the default cropping rectangle */
703     struct v4l2_crop crop = {
704         .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
705         .c = cropcap.defrect,
706     };
707
708     if (v4l2_ioctl (fd, VIDIOC_S_CROP, &crop) < 0)
709     {
710         msg_Warn (obj, "cannot reset cropping limits: %m");
711         return -1;
712     }
713     return 0;
714 }
715
716 int SetupInput (vlc_object_t *obj, int fd)
717 {
718     struct v4l2_input input;
719
720     input.index = var_InheritInteger (obj, CFG_PREFIX"input");
721     if (v4l2_ioctl (fd, VIDIOC_ENUMINPUT, &input) < 0)
722     {
723         msg_Err (obj, "invalid video input %"PRIu32": %m", input.index);
724         return -1;
725     }
726
727     const char *typename = "unknown";
728     switch (input.type)
729     {
730         case V4L2_INPUT_TYPE_TUNER:
731             typename = "tuner";
732             break;
733         case V4L2_INPUT_TYPE_CAMERA:
734             typename = "camera";
735             break;
736     }
737
738     msg_Dbg (obj, "video input %s (%"PRIu32") is %s", input.name,
739              input.index, typename);
740
741     /* Select input */
742     if (v4l2_ioctl (fd, VIDIOC_S_INPUT, &input.index) < 0)
743     {
744         msg_Err (obj, "cannot select input %"PRIu32": %m", input.index);
745         return -1;
746     }
747     msg_Dbg (obj, "selected input %"PRIu32, input.index);
748
749     SetupStandard (obj, fd, &input);
750     SetupTuner (obj, fd, &input);
751     SetupAudio (obj, fd, &input);
752     return 0;
753 }
754
755 /** Compares two V4L2 fractions. */
756 static int64_t fcmp (const struct v4l2_fract *a,
757                      const struct v4l2_fract *b)
758 {
759     return (uint64_t)a->numerator * b->denominator
760          - (uint64_t)b->numerator * a->denominator;
761 }
762
763 static const struct v4l2_fract infinity = { 1, 0 };
764
765 /**
766  * Finds the highest frame rate possible of a certain V4L2 format.
767  * @param fmt V4L2 capture format [IN]
768  * @param it V4L2 frame interval [OUT]
769  * @return 0 on success, -1 on error.
770  */
771 static int FindMaxRate (vlc_object_t *obj, int fd,
772                         const struct v4l2_format *restrict fmt,
773                         struct v4l2_fract *restrict it)
774 {
775     struct v4l2_frmivalenum fie = {
776         .pixel_format = fmt->fmt.pix.pixelformat,
777         .width = fmt->fmt.pix.width,
778         .height = fmt->fmt.pix.height,
779     };
780     /* Mind that maximum rate means minimum interval */
781
782     if (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMEINTERVALS, &fie) < 0)
783     {
784         msg_Dbg (obj, "  unknown frame intervals: %m");
785         /* Frame intervals cannot be enumerated. Set the format and then
786          * get the streaming parameters to figure out the default frame
787          * interval. This is not necessarily the maximum though. */
788         struct v4l2_format dummy_fmt = *fmt;
789         struct v4l2_streamparm parm = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
790
791         if (v4l2_ioctl (fd, VIDIOC_S_FMT, &dummy_fmt) < 0
792          || v4l2_ioctl (fd, VIDIOC_G_PARM, &parm) < 0)
793         {
794             *it = infinity;
795             return -1;
796         }
797
798         *it = parm.parm.capture.timeperframe;
799         msg_Dbg (obj, "  %s frame interval: %"PRIu32"/%"PRIu32,
800                  (parm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME)
801                  ? "default" : "constant", it->numerator, it->denominator);
802     }
803     else
804     switch (fie.type)
805     {
806         case V4L2_FRMIVAL_TYPE_DISCRETE:
807             *it = infinity;
808             do
809             {
810                 if (fcmp (&fie.discrete, it) < 0)
811                     *it = fie.discrete;
812                 fie.index++;
813             }
814             while (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMEINTERVALS, &fie) >= 0);
815
816             msg_Dbg (obj, "  %s frame interval: %"PRIu32"/%"PRIu32,
817                      "discrete", it->numerator, it->denominator);
818             break;
819
820         case V4L2_FRMIVAL_TYPE_STEPWISE:
821         case V4L2_FRMIVAL_TYPE_CONTINUOUS:
822             msg_Dbg (obj, "  frame intervals from %"PRIu32"/%"PRIu32
823                      "to %"PRIu32"/%"PRIu32" supported",
824                      fie.stepwise.min.numerator, fie.stepwise.min.denominator,
825                      fie.stepwise.max.numerator, fie.stepwise.max.denominator);
826             if (fie.type == V4L2_FRMIVAL_TYPE_STEPWISE)
827                 msg_Dbg (obj, "  with %"PRIu32"/%"PRIu32" step",
828                          fie.stepwise.step.numerator,
829                          fie.stepwise.step.denominator);
830             *it = fie.stepwise.min;
831             break;
832     }
833     return 0;
834 }
835
836 #undef SetupFormat
837 /**
838  * Finds the best possible frame rate and resolution.
839  * @param fourcc pixel format
840  * @param fmt V4L2 capture format [OUT]
841  * @param parm V4L2 capture streaming parameters [OUT]
842  * @return 0 on success, -1 on failure.
843  */
844 int SetupFormat (vlc_object_t *obj, int fd, uint32_t fourcc,
845                  struct v4l2_format *restrict fmt,
846                  struct v4l2_streamparm *restrict parm)
847 {
848     memset (fmt, 0, sizeof (*fmt));
849     fmt->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
850     memset (parm, 0, sizeof (*parm));
851     parm->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
852
853     if (v4l2_ioctl (fd, VIDIOC_G_FMT, fmt) < 0)
854     {
855         msg_Err (obj, "cannot get default format: %m");
856         return -1;
857     }
858     fmt->fmt.pix.pixelformat = fourcc;
859
860     struct v4l2_frmsizeenum fse = {
861         .pixel_format = fourcc,
862     };
863     struct v4l2_fract best_it = infinity;
864     uint64_t best_area = 0;
865
866     uint32_t width = var_InheritInteger (obj, CFG_PREFIX"width");
867     uint32_t height = var_InheritInteger (obj, CFG_PREFIX"height");
868     if (width > 0 && height > 0)
869     {
870         fmt->fmt.pix.width = width;
871         fmt->fmt.pix.height = height;
872         msg_Dbg (obj, " requested frame size: %"PRIu32"x%"PRIu32,
873                  width, height);
874         FindMaxRate (obj, fd, fmt, &best_it);
875     }
876     else
877     if (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMESIZES, &fse) < 0)
878     {
879         /* Fallback to current format, try to maximize frame rate */
880         msg_Dbg (obj, " unknown frame sizes: %m");
881         msg_Dbg (obj, " current frame size: %"PRIu32"x%"PRIu32,
882                  fmt->fmt.pix.width, fmt->fmt.pix.height);
883         FindMaxRate (obj, fd, fmt, &best_it);
884     }
885     else
886     switch (fse.type)
887     {
888         case V4L2_FRMSIZE_TYPE_DISCRETE:
889             do
890             {
891                 struct v4l2_fract cur_it;
892
893                 msg_Dbg (obj, " frame size %"PRIu32"x%"PRIu32,
894                          fse.discrete.width, fse.discrete.height);
895                 FindMaxRate (obj, fd, fmt, &cur_it);
896
897                 int64_t c = fcmp (&cur_it, &best_it);
898                 uint64_t area = fse.discrete.width * fse.discrete.height;
899                 if (c < 0 || (c == 0 && area > best_area))
900                 {
901                     best_it = cur_it;
902                     best_area = area;
903                     fmt->fmt.pix.width = fse.discrete.width;
904                     fmt->fmt.pix.height = fse.discrete.height;
905                 }
906
907                 fse.index++;
908             }
909             while (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMESIZES, &fse) >= 0);
910
911             msg_Dbg (obj, " best discrete frame size: %"PRIu32"x%"PRIu32,
912                      fmt->fmt.pix.width, fmt->fmt.pix.height);
913             break;
914
915         case V4L2_FRMSIZE_TYPE_STEPWISE:
916         case V4L2_FRMSIZE_TYPE_CONTINUOUS:
917             msg_Dbg (obj, " frame sizes from %"PRIu32"x%"PRIu32" to "
918                      "%"PRIu32"x%"PRIu32" supported",
919                      fse.stepwise.min_width, fse.stepwise.min_height,
920                      fse.stepwise.max_width, fse.stepwise.max_height);
921             if (fse.type == V4L2_FRMSIZE_TYPE_STEPWISE)
922                 msg_Dbg (obj, "  with %"PRIu32"x%"PRIu32" steps",
923                          fse.stepwise.step_width, fse.stepwise.step_height);
924
925             /* FIXME: slow and dumb */
926             for (uint32_t width =  fse.stepwise.min_width;
927                           width <= fse.stepwise.max_width;
928                           width += fse.stepwise.step_width)
929                 for (uint32_t height =  fse.stepwise.min_height;
930                               height <= fse.stepwise.max_width;
931                               height += fse.stepwise.step_height)
932                 {
933                     struct v4l2_fract cur_it;
934
935                     FindMaxRate (obj, fd, fmt, &cur_it);
936
937                     int64_t c = fcmp (&cur_it, &best_it);
938                     uint64_t area = width * height;
939
940                     if (c < 0 || (c == 0 && area > best_area))
941                     {
942                         best_it = cur_it;
943                         best_area = area;
944                         fmt->fmt.pix.width = width;
945                         fmt->fmt.pix.height = height;
946                     }
947                 }
948
949             msg_Dbg (obj, " best frame size: %"PRIu32"x%"PRIu32,
950                      fmt->fmt.pix.width, fmt->fmt.pix.height);
951             break;
952     }
953
954     /* Set the final format */
955     if (v4l2_ioctl (fd, VIDIOC_S_FMT, fmt) < 0)
956     {
957         msg_Err (obj, "cannot set format: %m");
958         return -1;
959     }
960
961     /* Now that the final format is set, fetch and override parameters */
962     if (v4l2_ioctl (fd, VIDIOC_G_PARM, parm) < 0)
963     {
964         msg_Err (obj, "cannot get streaming parameters: %m");
965         return -1;
966     }
967     parm->parm.capture.capturemode = 0; /* normal video mode */
968     parm->parm.capture.extendedmode = 0;
969     if (best_it.denominator != 0)
970         parm->parm.capture.timeperframe = best_it;
971     if (v4l2_ioctl (fd, VIDIOC_S_PARM, parm) < 0)
972         msg_Warn (obj, "cannot set streaming parameters: %m");
973
974     ResetCrop (obj, fd); /* crop depends on frame size */
975
976     return 0;
977 }
978
979
980 /*****************************************************************************
981  * GrabVideo: Grab a video frame
982  *****************************************************************************/
983 block_t* GrabVideo (vlc_object_t *demux, demux_sys_t *sys)
984 {
985     struct v4l2_buffer buf = {
986         .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
987         .memory = V4L2_MEMORY_MMAP,
988     };
989
990     /* Wait for next frame */
991     if (v4l2_ioctl (sys->i_fd, VIDIOC_DQBUF, &buf) < 0)
992     {
993         switch (errno)
994         {
995             case EAGAIN:
996                 return NULL;
997             case EIO:
998                 /* Could ignore EIO, see spec. */
999                 /* fall through */
1000             default:
1001                 msg_Err (demux, "dequeue error: %m");
1002                 return NULL;
1003         }
1004     }
1005
1006     if (buf.index >= sys->i_nbuffers) {
1007         msg_Err (demux, "Failed capturing new frame as i>=nbuffers");
1008         return NULL;
1009     }
1010
1011     block_t *block = ProcessVideoFrame(demux, sys->p_buffers[buf.index].start,
1012                                        buf.bytesused);
1013     if (block == NULL)
1014         return NULL;
1015
1016     /* Unlock */
1017     if (v4l2_ioctl (sys->i_fd, VIDIOC_QBUF, &buf) < 0)
1018     {
1019         msg_Err (demux, "queue error: %m");
1020         block_Release (block);
1021         return NULL;
1022     }
1023     return block;
1024 }
1025
1026 /*****************************************************************************
1027  * ProcessVideoFrame: Helper function to take a buffer and copy it into
1028  * a new block
1029  *****************************************************************************/
1030 static block_t* ProcessVideoFrame( vlc_object_t *p_demux, uint8_t *p_frame, size_t i_size )
1031 {
1032     block_t *p_block;
1033
1034     if( !p_frame ) return NULL;
1035
1036     /* New block */
1037     if( !( p_block = block_New( p_demux, i_size ) ) )
1038     {
1039         msg_Warn( p_demux, "Cannot get new block" );
1040         return NULL;
1041     }
1042
1043     /* Copy frame */
1044     memcpy( p_block->p_buffer, p_frame, i_size );
1045
1046     return p_block;
1047 }
1048
1049 /*****************************************************************************
1050  * Helper function to initalise video IO using the mmap method
1051  *****************************************************************************/
1052 int InitMmap( vlc_object_t *p_demux, demux_sys_t *p_sys, int i_fd )
1053 {
1054     struct v4l2_requestbuffers req;
1055
1056     memset( &req, 0, sizeof(req) );
1057     req.count = 4;
1058     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1059     req.memory = V4L2_MEMORY_MMAP;
1060
1061     if( v4l2_ioctl( i_fd, VIDIOC_REQBUFS, &req ) < 0 )
1062     {
1063         msg_Err( p_demux, "device does not support mmap I/O" );
1064         return -1;
1065     }
1066
1067     if( req.count < 2 )
1068     {
1069         msg_Err( p_demux, "insufficient buffers" );
1070         return -1;
1071     }
1072
1073     p_sys->p_buffers = calloc( req.count, sizeof( *p_sys->p_buffers ) );
1074     if( unlikely(!p_sys->p_buffers) )
1075         return -1;
1076
1077     for( p_sys->i_nbuffers = 0; p_sys->i_nbuffers < req.count; ++p_sys->i_nbuffers )
1078     {
1079         struct v4l2_buffer buf;
1080
1081         memset( &buf, 0, sizeof(buf) );
1082         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1083         buf.memory = V4L2_MEMORY_MMAP;
1084         buf.index = p_sys->i_nbuffers;
1085
1086         if( v4l2_ioctl( i_fd, VIDIOC_QUERYBUF, &buf ) < 0 )
1087         {
1088             msg_Err( p_demux, "VIDIOC_QUERYBUF: %m" );
1089             return -1;
1090         }
1091
1092         p_sys->p_buffers[p_sys->i_nbuffers].length = buf.length;
1093         p_sys->p_buffers[p_sys->i_nbuffers].start =
1094             v4l2_mmap( NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, i_fd, buf.m.offset );
1095
1096         if( p_sys->p_buffers[p_sys->i_nbuffers].start == MAP_FAILED )
1097         {
1098             msg_Err( p_demux, "mmap failed: %m" );
1099             return -1;
1100         }
1101     }
1102
1103     return 0;
1104 }