]> git.sesse.net Git - vlc/blob - modules/access/v4l2/video.c
V4L2: merge two switches
[vlc] / modules / access / v4l2 / video.c
1 /*****************************************************************************
2  * v4l2.c : Video4Linux2 input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2002-2009 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Benjamin Pracht <bigben at videolan dot org>
8  *          Richard Hosking <richard at hovis dot net>
9  *          Antoine Cellerier <dionoea at videolan d.t org>
10  *          Dennis Lou <dlou99 at yahoo dot com>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*
28  * Sections based on the reference V4L2 capture example at
29  * http://v4l2spec.bytesex.org/spec/capture-example.html
30  */
31
32 /*****************************************************************************
33  * Preamble
34  *****************************************************************************/
35
36 #ifdef HAVE_CONFIG_H
37 # include "config.h"
38 #endif
39
40 #include "v4l2.h"
41 #include <vlc_plugin.h>
42 #include <vlc_access.h>
43 #include <vlc_fs.h>
44 #include <vlc_demux.h>
45
46 #include <math.h>
47 #include <assert.h>
48 #include <errno.h>
49 #include <fcntl.h>
50 #include <sys/ioctl.h>
51 #include <sys/mman.h>
52 #include <poll.h>
53
54 /*****************************************************************************
55  * Module descriptior
56  *****************************************************************************/
57
58 static int  DemuxOpen ( vlc_object_t * );
59 static void DemuxClose( vlc_object_t * );
60 static int  AccessOpen ( vlc_object_t * );
61 static void AccessClose( vlc_object_t * );
62
63 #define DEVICE_TEXT N_( "Device" )
64 #define DEVICE_LONGTEXT N_( \
65     "Video device (Default: /dev/video0)." )
66 #define STANDARD_TEXT N_( "Standard" )
67 #define STANDARD_LONGTEXT N_( \
68     "Video standard (Default, SECAM, PAL, or NTSC)." )
69 #define CHROMA_TEXT N_("Video input chroma format")
70 #define CHROMA_LONGTEXT N_( \
71     "Force the Video4Linux2 video device to use a specific chroma format " \
72     "(eg. I420 or I422 for raw images, MJPG for M-JPEG compressed input) " \
73     "(Complete list: GREY, I240, RV16, RV15, RV24, RV32, YUY2, YUYV, UYVY, " \
74     "I41N, I422, I420, I411, I410, MJPG)")
75 #define INPUT_TEXT N_( "Input" )
76 #define INPUT_LONGTEXT N_( \
77     "Input of the card to use (see debug)." )
78 #define AUDIO_INPUT_TEXT N_( "Audio input" )
79 #define AUDIO_INPUT_LONGTEXT N_( \
80     "Audio input of the card to use (see debug)." )
81 #define WIDTH_TEXT N_( "Width" )
82 #define WIDTH_LONGTEXT N_( \
83     "Force width (-1 for autodetect, 0 for driver default)." )
84 #define HEIGHT_TEXT N_( "Height" )
85 #define HEIGHT_LONGTEXT N_( \
86     "Force height (-1 for autodetect, 0 for driver default)." )
87 #define FPS_TEXT N_( "Framerate" )
88 #define FPS_LONGTEXT N_( "Framerate to capture, if applicable " \
89     "(0 for autodetect)." )
90
91 #ifdef HAVE_LIBV4L2
92 #define LIBV4L2_TEXT N_( "Use libv4l2" )
93 #define LIBV4L2_LONGTEXT N_( \
94     "Force usage of the libv4l2 wrapper." )
95 #endif
96
97 #define CTRL_RESET_TEXT N_( "Reset v4l2 controls" )
98 #define CTRL_RESET_LONGTEXT N_( \
99     "Reset controls to defaults provided by the v4l2 driver." )
100 #define BRIGHTNESS_TEXT N_( "Brightness" )
101 #define BRIGHTNESS_LONGTEXT N_( \
102     "Brightness of the video input (if supported by the v4l2 driver)." )
103 #define CONTRAST_TEXT N_( "Contrast" )
104 #define CONTRAST_LONGTEXT N_( \
105     "Contrast of the video input (if supported by the v4l2 driver)." )
106 #define SATURATION_TEXT N_( "Saturation" )
107 #define SATURATION_LONGTEXT N_( \
108     "Saturation of the video input (if supported by the v4l2 driver)." )
109 #define HUE_TEXT N_( "Hue" )
110 #define HUE_LONGTEXT N_( \
111     "Hue of the video input (if supported by the v4l2 driver)." )
112 #define BLACKLEVEL_TEXT N_( "Black level" )
113 #define BLACKLEVEL_LONGTEXT N_( \
114     "Black level of the video input (if supported by the v4l2 driver)." )
115 #define AUTOWHITEBALANCE_TEXT N_( "Auto white balance" )
116 #define AUTOWHITEBALANCE_LONGTEXT N_( \
117     "Automatically set the white balance of the video input " \
118     "(if supported by the v4l2 driver)." )
119 #define DOWHITEBALANCE_TEXT N_( "Do white balance" )
120 #define DOWHITEBALANCE_LONGTEXT N_( \
121     "Trigger a white balancing action, useless if auto white balance is " \
122     "activated (if supported by the v4l2 driver)." )
123 #define REDBALANCE_TEXT N_( "Red balance" )
124 #define REDBALANCE_LONGTEXT N_( \
125     "Red balance of the video input (if supported by the v4l2 driver)." )
126 #define BLUEBALANCE_TEXT N_( "Blue balance" )
127 #define BLUEBALANCE_LONGTEXT N_( \
128     "Blue balance of the video input (if supported by the v4l2 driver)." )
129 #define GAMMA_TEXT N_( "Gamma" )
130 #define GAMMA_LONGTEXT N_( \
131     "Gamma of the video input (if supported by the v4l2 driver)." )
132 #define EXPOSURE_TEXT N_( "Exposure" )
133 #define EXPOSURE_LONGTEXT N_( \
134     "Exposure of the video input (if supported by the v4L2 driver)." )
135 #define AUTOGAIN_TEXT N_( "Auto gain" )
136 #define AUTOGAIN_LONGTEXT N_( \
137     "Automatically set the video input's gain (if supported by the " \
138     "v4l2 driver)." )
139 #define GAIN_TEXT N_( "Gain" )
140 #define GAIN_LONGTEXT N_( \
141     "Video input's gain (if supported by the v4l2 driver)." )
142 #define HFLIP_TEXT N_( "Horizontal flip" )
143 #define HFLIP_LONGTEXT N_( \
144     "Flip the video horizontally (if supported by the v4l2 driver)." )
145 #define VFLIP_TEXT N_( "Vertical flip" )
146 #define VFLIP_LONGTEXT N_( \
147     "Flip the video vertically (if supported by the v4l2 driver)." )
148 #define HCENTER_TEXT N_( "Horizontal centering" )
149 #define HCENTER_LONGTEXT N_( \
150     "Set the camera's horizontal centering (if supported by the v4l2 driver)." )
151 #define VCENTER_TEXT N_( "Vertical centering" )
152 #define VCENTER_LONGTEXT N_( \
153     "Set the camera's vertical centering (if supported by the v4l2 driver)." )
154
155 #define AUDIO_VOLUME_TEXT N_( "Volume" )
156 #define AUDIO_VOLUME_LONGTEXT N_( \
157     "Volume of the audio input (if supported by the v4l2 driver)." )
158 #define AUDIO_BALANCE_TEXT N_( "Balance" )
159 #define AUDIO_BALANCE_LONGTEXT N_( \
160     "Balance of the audio input (if supported by the v4l2 driver)." )
161 #define AUDIO_MUTE_TEXT N_( "Mute" )
162 #define AUDIO_MUTE_LONGTEXT N_( \
163     "Mute audio input (if supported by the v4l2 driver)." )
164 #define AUDIO_BASS_TEXT N_( "Bass" )
165 #define AUDIO_BASS_LONGTEXT N_( \
166     "Bass level of the audio input (if supported by the v4l2 driver)." )
167 #define AUDIO_TREBLE_TEXT N_( "Treble" )
168 #define AUDIO_TREBLE_LONGTEXT N_( \
169     "Treble level of the audio input (if supported by the v4l2 driver)." )
170 #define AUDIO_LOUDNESS_TEXT N_( "Loudness" )
171 #define AUDIO_LOUDNESS_LONGTEXT N_( \
172     "Loudness of the audio input (if supported by the v4l2 driver)." )
173
174 #define S_CTRLS_TEXT N_("v4l2 driver controls")
175 #define S_CTRLS_LONGTEXT N_( \
176     "Set the v4l2 driver controls to the values specified using a comma " \
177     "separated list optionally encapsulated by curly braces " \
178     "(e.g.: {video_bitrate=6000000,audio_crc=0,stream_type=3} ). " \
179     "To list available controls, increase verbosity (-vvv) " \
180     "or use the v4l2-ctl application." )
181
182 #define TUNER_TEXT N_("Tuner id")
183 #define TUNER_LONGTEXT N_( \
184     "Tuner id (see debug output)." )
185 #define FREQUENCY_TEXT N_("Frequency")
186 #define FREQUENCY_LONGTEXT N_( \
187     "Tuner frequency in Hz or kHz (see debug output)" )
188 #define TUNER_AUDIO_MODE_TEXT N_("Audio mode")
189 #define TUNER_AUDIO_MODE_LONGTEXT N_( \
190     "Tuner audio mono/stereo and track selection." )
191
192 #define ASPECT_TEXT N_("Picture aspect-ratio n:m")
193 #define ASPECT_LONGTEXT N_("Define input picture aspect-ratio to use. Default is 4:3" )
194
195 static const v4l2_std_id standards_v4l2[] = { V4L2_STD_UNKNOWN, V4L2_STD_ALL,
196     V4L2_STD_PAL,     V4L2_STD_PAL_BG,   V4L2_STD_PAL_DK,
197     V4L2_STD_NTSC,
198     V4L2_STD_SECAM,   V4L2_STD_SECAM_DK,
199     V4L2_STD_525_60,  V4L2_STD_625_50,
200     V4L2_STD_ATSC,
201
202     V4L2_STD_MN,      V4L2_STD_B,        V4L2_STD_GH,       V4L2_STD_DK,
203
204     V4L2_STD_PAL_B,   V4L2_STD_PAL_B1,   V4L2_STD_PAL_G,    V4L2_STD_PAL_H,
205     V4L2_STD_PAL_I,   V4L2_STD_PAL_D,    V4L2_STD_PAL_D1,   V4L2_STD_PAL_K,
206     V4L2_STD_PAL_M,   V4L2_STD_PAL_N,    V4L2_STD_PAL_Nc,   V4L2_STD_PAL_60,
207     V4L2_STD_NTSC_M,  V4L2_STD_NTSC_M_JP,V4L2_STD_NTSC_443, V4L2_STD_NTSC_M_KR,
208     V4L2_STD_SECAM_B, V4L2_STD_SECAM_D,  V4L2_STD_SECAM_G,  V4L2_STD_SECAM_H,
209     V4L2_STD_SECAM_K, V4L2_STD_SECAM_K1, V4L2_STD_SECAM_L,  V4L2_STD_SECAM_LC,
210     V4L2_STD_ATSC_8_VSB, V4L2_STD_ATSC_16_VSB,
211 };
212 static const char *const standards_vlc[] = { "", "ALL",
213     /* Pseudo standards */
214     "PAL", "PAL_BG", "PAL_DK",
215     "NTSC",
216     "SECAM", "SECAM_DK",
217     "525_60", "625_50",
218     "ATSC",
219
220     /* Areas (PAL/NTSC or PAL/SECAM) */
221     "MN", "B", "GH", "DK",
222
223     /* Individual standards */
224     "PAL_B",          "PAL_B1",          "PAL_G",           "PAL_H",
225     "PAL_I",          "PAL_D",           "PAL_D1",          "PAL_K",
226     "PAL_M",          "PAL_N",           "PAL_Nc",          "PAL_60",
227     "NTSC_M",         "NTSC_M_JP",       "NTSC_443",        "NTSC_M_KR",
228     "SECAM_B",        "SECAM_D",         "SECAM_G",         "SECAM_H",
229     "SECAM_K",        "SECAM_K1",        "SECAM_L",         "SECAM_LC",
230     "ATSC_8_VSB",     "ATSC_16_VSB",
231 };
232 static const char *const standards_user[] = { N_("Undefined"), N_("All"),
233     "PAL",            "PAL B/G",         "PAL D/K",
234     "NTSC",
235     "SECAM",          "SECAM D/K",
236     N_("525 lines / 60 Hz"), N_("625 lines / 50 Hz"),
237     "ATSC",
238
239     "PAL/NTSC M/N",
240     "PAL/SECAM B",    "PAL/SECAM G/H",   "PAL/SECAM D/K",
241
242     "PAL B",          "PAL B1",          "PAL G",           "PAL H",
243     "PAL I",          "PAL D",           "PAL D1",          "PAL K",
244     "PAL M",          "PAL N",           N_("PAL N Argentina"), "PAL 60",
245     "NTSC M",        N_("NTSC M Japan"), "NTSC 443",  N_("NTSC M South Korea"),
246     "SECAM B",        "SECAM D",         "SECAM G",         "SECAM H",
247     "SECAM K",        "SECAM K1",        "SECAM L",         "SECAM L/C",
248     "ATSC 8-VSB",     "ATSC 16-VSB",
249 };
250
251 static const int i_tuner_audio_modes_list[] = {
252       -1, V4L2_TUNER_MODE_MONO, V4L2_TUNER_MODE_STEREO,
253       V4L2_TUNER_MODE_LANG1, V4L2_TUNER_MODE_LANG2,
254       V4L2_TUNER_MODE_SAP, V4L2_TUNER_MODE_LANG1_LANG2 };
255 static const char *const psz_tuner_audio_modes_list_text[] = {
256       N_("Unspecified"),
257       N_( "Mono" ),
258       N_( "Stereo" ),
259       N_( "Primary language (Analog TV tuners only)" ),
260       N_( "Secondary language (Analog TV tuners only)" ),
261       N_( "Second audio program (Analog TV tuners only)" ),
262       N_( "Primary language left, Secondary language right" ) };
263
264 #define V4L2_DEFAULT "/dev/video0"
265
266 #ifdef HAVE_MAEMO
267 # define DEFAULT_WIDTH  640
268 # define DEFAULT_HEIGHT 492
269 #endif
270
271 #ifndef DEFAULT_WIDTH
272 # define DEFAULT_WIDTH  (-1)
273 # define DEFAULT_HEIGHT (-1)
274 #endif
275
276 vlc_module_begin ()
277     set_shortname( N_("Video4Linux2") )
278     set_description( N_("Video4Linux2 input") )
279     set_category( CAT_INPUT )
280     set_subcategory( SUBCAT_INPUT_ACCESS )
281
282     set_section( N_( "Video input" ), NULL )
283     add_string( CFG_PREFIX "dev", "/dev/video0", DEVICE_TEXT, DEVICE_LONGTEXT,
284                  false )
285         change_safe()
286     add_string( CFG_PREFIX "standard", "",
287                 STANDARD_TEXT, STANDARD_LONGTEXT, false )
288         change_string_list( standards_vlc, standards_user, NULL )
289         change_safe()
290     add_string( CFG_PREFIX "chroma", NULL, CHROMA_TEXT, CHROMA_LONGTEXT,
291                 true )
292         change_safe()
293     add_integer( CFG_PREFIX "input", 0, INPUT_TEXT, INPUT_LONGTEXT,
294                 true )
295         change_integer_range( 0, 0xFFFFFFFE )
296         change_safe()
297     add_integer( CFG_PREFIX "audio-input", -1, AUDIO_INPUT_TEXT,
298                  AUDIO_INPUT_LONGTEXT, true )
299         change_integer_range( -1, 0xFFFFFFFE )
300         change_safe()
301     add_obsolete_integer( CFG_PREFIX "io" ) /* since 1.2.0 */
302     add_integer( CFG_PREFIX "width", DEFAULT_WIDTH, WIDTH_TEXT,
303                 WIDTH_LONGTEXT, true )
304         change_safe()
305     add_integer( CFG_PREFIX "height", DEFAULT_HEIGHT, HEIGHT_TEXT,
306                 HEIGHT_LONGTEXT, true )
307         change_safe()
308     add_string( CFG_PREFIX "aspect-ratio", "4:3", ASPECT_TEXT,
309               ASPECT_LONGTEXT, true )
310         change_safe()
311     add_float( CFG_PREFIX "fps", 0, FPS_TEXT, FPS_LONGTEXT, true )
312         change_safe()
313 #ifdef HAVE_LIBV4L2
314     add_bool( CFG_PREFIX "use-libv4l2", false, LIBV4L2_TEXT, LIBV4L2_LONGTEXT, true );
315 #endif
316
317     set_section( N_( "Tuner" ), NULL )
318     add_integer( CFG_PREFIX "tuner", 0, TUNER_TEXT, TUNER_LONGTEXT,
319                  true )
320         change_integer_range( 0, 0xFFFFFFFE )
321         change_safe()
322     add_integer( CFG_PREFIX "tuner-frequency", -1, FREQUENCY_TEXT,
323                  FREQUENCY_LONGTEXT, true )
324         change_integer_range( -1, 0xFFFFFFFE )
325         change_safe()
326     add_integer( CFG_PREFIX "tuner-audio-mode", -1, TUNER_AUDIO_MODE_TEXT,
327                  TUNER_AUDIO_MODE_LONGTEXT, true )
328         change_integer_list( i_tuner_audio_modes_list,
329                              psz_tuner_audio_modes_list_text )
330         change_safe()
331
332     set_section( N_( "Controls" ),
333                  N_( "v4l2 driver controls, if supported by your v4l2 driver." ) )
334     add_bool( CFG_PREFIX "controls-reset", false, CTRL_RESET_TEXT,
335               CTRL_RESET_LONGTEXT, true )
336         change_safe()
337     add_integer( CFG_PREFIX "brightness", -1, BRIGHTNESS_TEXT,
338                  BRIGHTNESS_LONGTEXT, true )
339     add_integer( CFG_PREFIX "contrast", -1, CONTRAST_TEXT,
340                  CONTRAST_LONGTEXT, true )
341     add_integer( CFG_PREFIX "saturation", -1, SATURATION_TEXT,
342                  SATURATION_LONGTEXT, true )
343     add_integer( CFG_PREFIX "hue", -1, HUE_TEXT,
344                  HUE_LONGTEXT, true )
345     add_integer( CFG_PREFIX "black-level", -1, BLACKLEVEL_TEXT,
346                  BLACKLEVEL_LONGTEXT, true )
347     add_integer( CFG_PREFIX "auto-white-balance", -1,
348                  AUTOWHITEBALANCE_TEXT, AUTOWHITEBALANCE_LONGTEXT, true )
349     add_integer( CFG_PREFIX "do-white-balance", -1, DOWHITEBALANCE_TEXT,
350                  DOWHITEBALANCE_LONGTEXT, true )
351     add_integer( CFG_PREFIX "red-balance", -1, REDBALANCE_TEXT,
352                  REDBALANCE_LONGTEXT, true )
353     add_integer( CFG_PREFIX "blue-balance", -1, BLUEBALANCE_TEXT,
354                  BLUEBALANCE_LONGTEXT, true )
355     add_integer( CFG_PREFIX "gamma", -1, GAMMA_TEXT,
356                  GAMMA_LONGTEXT, true )
357     add_integer( CFG_PREFIX "exposure", -1, EXPOSURE_TEXT,
358                  EXPOSURE_LONGTEXT, true )
359     add_integer( CFG_PREFIX "autogain", -1, AUTOGAIN_TEXT,
360                  AUTOGAIN_LONGTEXT, true )
361     add_integer( CFG_PREFIX "gain", -1, GAIN_TEXT,
362                  GAIN_LONGTEXT, true )
363     add_integer( CFG_PREFIX "hflip", -1, HFLIP_TEXT,
364                  HFLIP_LONGTEXT, true )
365     add_integer( CFG_PREFIX "vflip", -1, VFLIP_TEXT,
366                  VFLIP_LONGTEXT, true )
367     add_integer( CFG_PREFIX "hcenter", -1, HCENTER_TEXT,
368                  HCENTER_LONGTEXT, true )
369     add_integer( CFG_PREFIX "vcenter", -1, VCENTER_TEXT,
370                  VCENTER_LONGTEXT, true )
371     add_integer( CFG_PREFIX "audio-volume", -1, AUDIO_VOLUME_TEXT,
372                 AUDIO_VOLUME_LONGTEXT, true )
373     add_integer( CFG_PREFIX "audio-balance", -1, AUDIO_BALANCE_TEXT,
374                 AUDIO_BALANCE_LONGTEXT, true )
375     add_bool( CFG_PREFIX "audio-mute", false, AUDIO_MUTE_TEXT,
376               AUDIO_MUTE_LONGTEXT, true )
377     add_integer( CFG_PREFIX "audio-bass", -1, AUDIO_BASS_TEXT,
378                 AUDIO_BASS_LONGTEXT, true )
379     add_integer( CFG_PREFIX "audio-treble", -1, AUDIO_TREBLE_TEXT,
380                 AUDIO_TREBLE_LONGTEXT, true )
381     add_integer( CFG_PREFIX "audio-loudness", -1, AUDIO_LOUDNESS_TEXT,
382                 AUDIO_LOUDNESS_LONGTEXT, true )
383     add_string( CFG_PREFIX "set-ctrls", NULL, S_CTRLS_TEXT,
384               S_CTRLS_LONGTEXT, true )
385         change_safe()
386
387     add_obsolete_string( CFG_PREFIX "adev" )
388     add_obsolete_integer( CFG_PREFIX "audio-method" )
389     add_obsolete_bool( CFG_PREFIX "stereo" )
390     add_obsolete_integer( CFG_PREFIX "samplerate" )
391
392     add_shortcut( "v4l2" )
393     set_capability( "access_demux", 0 )
394     set_callbacks( DemuxOpen, DemuxClose )
395
396     add_submodule ()
397     add_shortcut( "v4l2", "v4l2c" )
398     set_description( N_("Video4Linux2 Compressed A/V") )
399     set_capability( "access", 0 )
400     /* use these when open as access_demux fails; VLC will use another demux */
401     set_callbacks( AccessOpen, AccessClose )
402
403 vlc_module_end ()
404
405 /*****************************************************************************
406  * Access: local prototypes
407  *****************************************************************************/
408
409 static void CommonClose( vlc_object_t *, demux_sys_t * );
410 static char *ParseMRL( vlc_object_t *, const char * );
411
412 static int DemuxControl( demux_t *, int, va_list );
413 static int AccessControl( access_t *, int, va_list );
414
415 static int Demux( demux_t * );
416 static block_t *AccessRead( access_t * );
417 static ssize_t AccessReadStream( access_t * p_access, uint8_t * p_buffer, size_t i_len );
418
419 static block_t* GrabVideo( vlc_object_t *p_demux, demux_sys_t *p_sys );
420 static block_t* ProcessVideoFrame( vlc_object_t *p_demux, uint8_t *p_frame, size_t );
421
422 static int OpenVideoDev( vlc_object_t *, const char *path, demux_sys_t *, bool );
423
424 static const struct
425 {
426     unsigned int i_v4l2;
427     vlc_fourcc_t i_fourcc;
428     int i_rmask;
429     int i_gmask;
430     int i_bmask;
431 } v4l2chroma_to_fourcc[] =
432 {
433     /* Raw data types */
434     { V4L2_PIX_FMT_GREY,    VLC_CODEC_GREY, 0, 0, 0 },
435     { V4L2_PIX_FMT_HI240,   VLC_FOURCC('I','2','4','0'), 0, 0, 0 },
436     { V4L2_PIX_FMT_RGB555,  VLC_CODEC_RGB15, 0x001f,0x03e0,0x7c00 },
437     { V4L2_PIX_FMT_RGB565,  VLC_CODEC_RGB16, 0x001f,0x07e0,0xf800 },
438     /* Won't work since we don't know how to handle such gmask values
439      * correctly
440     { V4L2_PIX_FMT_RGB555X, VLC_CODEC_RGB15, 0x007c,0xe003,0x1f00 },
441     { V4L2_PIX_FMT_RGB565X, VLC_CODEC_RGB16, 0x00f8,0xe007,0x1f00 },
442     */
443     { V4L2_PIX_FMT_BGR24,   VLC_CODEC_RGB24, 0xff0000,0xff00,0xff },
444     { V4L2_PIX_FMT_RGB24,   VLC_CODEC_RGB24, 0xff,0xff00,0xff0000 },
445     { V4L2_PIX_FMT_BGR32,   VLC_CODEC_RGB32, 0xff0000,0xff00,0xff },
446     { V4L2_PIX_FMT_RGB32,   VLC_CODEC_RGB32, 0xff,0xff00,0xff0000 },
447     { V4L2_PIX_FMT_YUYV,    VLC_CODEC_YUYV, 0, 0, 0 },
448     { V4L2_PIX_FMT_UYVY,    VLC_CODEC_UYVY, 0, 0, 0 },
449     { V4L2_PIX_FMT_Y41P,    VLC_FOURCC('I','4','1','N'), 0, 0, 0 },
450     { V4L2_PIX_FMT_YUV422P, VLC_CODEC_I422, 0, 0, 0 },
451     { V4L2_PIX_FMT_YVU420,  VLC_CODEC_YV12, 0, 0, 0 },
452     { V4L2_PIX_FMT_YUV411P, VLC_CODEC_I411, 0, 0, 0 },
453     { V4L2_PIX_FMT_YUV410,  VLC_CODEC_I410, 0, 0, 0 },
454
455     /* Raw data types, not in V4L2 spec but still in videodev2.h and supported
456      * by VLC */
457     { V4L2_PIX_FMT_YUV420,  VLC_CODEC_I420, 0, 0, 0 },
458     /* FIXME { V4L2_PIX_FMT_RGB444,  VLC_CODEC_RGB32 }, */
459
460     /* Compressed data types */
461     { V4L2_PIX_FMT_MJPEG,   VLC_CODEC_MJPG, 0, 0, 0 },
462     { V4L2_PIX_FMT_JPEG,    VLC_CODEC_JPEG, 0, 0, 0 },
463 #if 0
464     { V4L2_PIX_FMT_DV,      VLC_FOURCC('?','?','?','?') },
465     { V4L2_PIX_FMT_MPEG,    VLC_FOURCC('?','?','?','?') },
466 #endif
467     { 0, 0, 0, 0, 0 }
468 };
469
470 /**
471  * List of V4L2 chromas were confident enough to use as fallbacks if the
472  * user hasn't provided a --v4l2-chroma value.
473  *
474  * Try YUV chromas first, then RGB little endian and MJPEG as last resort.
475  */
476 static const uint32_t p_chroma_fallbacks[] =
477 { V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_YVU420, V4L2_PIX_FMT_YUV422P,
478   V4L2_PIX_FMT_YUYV, V4L2_PIX_FMT_UYVY, V4L2_PIX_FMT_BGR24,
479   V4L2_PIX_FMT_BGR32, V4L2_PIX_FMT_MJPEG, V4L2_PIX_FMT_JPEG };
480
481 struct buffer_t
482 {
483     void *  start;
484     size_t  length;
485 };
486
487 /*****************************************************************************
488  * DemuxOpen: opens v4l2 device, access_demux callback
489  *****************************************************************************
490  *
491  * url: <video device>::::
492  *
493  *****************************************************************************/
494 static int DemuxOpen( vlc_object_t *p_this )
495 {
496     demux_t     *p_demux = (demux_t*)p_this;
497     demux_sys_t *p_sys;
498
499     /* Set up p_demux */
500     p_demux->pf_control = DemuxControl;
501     p_demux->pf_demux = Demux;
502     p_demux->info.i_update = 0;
503     p_demux->info.i_title = 0;
504     p_demux->info.i_seekpoint = 0;
505
506     p_demux->p_sys = p_sys = calloc( 1, sizeof( demux_sys_t ) );
507     if( p_sys == NULL ) return VLC_ENOMEM;
508
509     char *path = ParseMRL( p_this, p_demux->psz_location );
510     if( path == NULL )
511         path = var_CreateGetNonEmptyString( p_this, CFG_PREFIX"dev" );
512
513 #ifdef HAVE_LIBV4L2
514     p_sys->i_fd = -1;
515     if( !var_InheritBool( p_this, CFG_PREFIX "use-libv4l2" ) )
516     {
517         p_sys->b_libv4l2 = false;
518 #endif
519         msg_Dbg( p_this, "Trying direct kernel v4l2" );
520         p_sys->i_fd = OpenVideoDev( p_this, path, p_sys, true );
521 #ifdef HAVE_LIBV4L2
522     }
523
524     if( p_sys->i_fd == -1 )
525     {
526         p_sys->b_libv4l2 = true;
527         msg_Dbg( p_this, "Trying libv4l2 wrapper" );
528         p_sys->i_fd = OpenVideoDev( p_this, path, p_sys, true );
529     }
530 #endif
531     free( path );
532     if( p_sys->i_fd == -1 )
533     {
534         free( p_sys );
535         return VLC_EGENERIC;
536     }
537     return VLC_SUCCESS;
538 }
539
540 /**
541  * Parses a V4L2 MRL.
542  * \return device node path (use free()) or NULL if not specified
543  */
544 static char *ParseMRL( vlc_object_t *obj, const char *mrl )
545 {
546     const char *p = strchr( mrl, ':' );
547
548     if( p != NULL )
549     {
550         var_LocationParse( obj, p + 1, CFG_PREFIX );
551         if( p > mrl )
552             return strndup( mrl, p - mrl );
553     }
554     else
555     {
556         if( mrl[0] )
557             return strdup( mrl );
558     }
559     return NULL;
560 }
561
562 /*****************************************************************************
563  * Close: close device, free resources
564  *****************************************************************************/
565 static void AccessClose( vlc_object_t *p_this )
566 {
567     access_t    *p_access = (access_t *)p_this;
568     demux_sys_t *p_sys   = (demux_sys_t *) p_access->p_sys;
569
570     CommonClose( p_this, p_sys );
571 }
572
573 static void DemuxClose( vlc_object_t *p_this )
574 {
575     struct v4l2_buffer buf;
576     enum v4l2_buf_type buf_type;
577     unsigned int i;
578
579     demux_t     *p_demux = (demux_t *)p_this;
580     demux_sys_t *p_sys   = p_demux->p_sys;
581
582     /* Stop video capture */
583     if( p_sys->i_fd >= 0 )
584     {
585         switch( p_sys->io )
586         {
587         case IO_METHOD_READ:
588             /* Nothing to do */
589             break;
590
591         case IO_METHOD_MMAP:
592         case IO_METHOD_USERPTR:
593             /* Some drivers 'hang' internally if this is not done before streamoff */
594             for( unsigned int i = 0; i < p_sys->i_nbuffers; i++ )
595             {
596                 memset( &buf, 0, sizeof(buf) );
597                 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
598                 buf.memory = ( p_sys->io == IO_METHOD_USERPTR ) ?
599                     V4L2_MEMORY_USERPTR : V4L2_MEMORY_MMAP;
600                 v4l2_ioctl( p_sys->i_fd, VIDIOC_DQBUF, &buf ); /* ignore result */
601             }
602
603             buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
604             if( v4l2_ioctl( p_sys->i_fd, VIDIOC_STREAMOFF, &buf_type ) < 0 ) {
605                 msg_Err( p_this, "VIDIOC_STREAMOFF failed" );
606             }
607
608             break;
609         }
610     }
611
612     /* Free Video Buffers */
613     if( p_sys->p_buffers ) {
614         switch( p_sys->io )
615         {
616         case IO_METHOD_READ:
617             free( p_sys->p_buffers[0].start );
618             break;
619
620         case IO_METHOD_MMAP:
621             for( i = 0; i < p_sys->i_nbuffers; ++i )
622             {
623                 if( v4l2_munmap( p_sys->p_buffers[i].start, p_sys->p_buffers[i].length ) )
624                 {
625                     msg_Err( p_this, "munmap failed" );
626                 }
627             }
628             break;
629
630         case IO_METHOD_USERPTR:
631             for( i = 0; i < p_sys->i_nbuffers; ++i )
632             {
633                free( p_sys->p_buffers[i].start );
634             }
635             break;
636         }
637         free( p_sys->p_buffers );
638     }
639
640     CommonClose( p_this, p_sys );
641 }
642
643 static void CommonClose( vlc_object_t *p_this, demux_sys_t *p_sys )
644 {
645     (void)p_this;
646     /* Close */
647     if( p_sys->i_fd >= 0 ) v4l2_close( p_sys->i_fd );
648     free( p_sys );
649 }
650
651 /*****************************************************************************
652  * AccessOpen: opens v4l2 device, access callback
653  *****************************************************************************
654  *
655  * url: <video device>::::
656  *
657  *****************************************************************************/
658 static int AccessOpen( vlc_object_t * p_this )
659 {
660     access_t *p_access = (access_t*) p_this;
661     demux_sys_t * p_sys;
662
663     /* Only when selected */
664     if( *p_access->psz_access == '\0' ) return VLC_EGENERIC;
665
666     access_InitFields( p_access );
667     p_sys = calloc( 1, sizeof( demux_sys_t ));
668     if( !p_sys ) return VLC_ENOMEM;
669     p_access->p_sys = (access_sys_t*)p_sys;
670
671     char *path = ParseMRL( p_this, p_access->psz_location );
672     if( path == NULL )
673         path = var_InheritString( p_this, CFG_PREFIX"dev" );
674
675 #ifdef HAVE_LIBV4L2
676     p_sys->i_fd = -1;
677     if( !var_InheritBool( p_this, CFG_PREFIX "use-libv4l2" ) )
678     {
679         p_sys->b_libv4l2 = false;
680 #endif
681         msg_Dbg( p_this, "Trying direct kernel v4l2" );
682         p_sys->i_fd = OpenVideoDev( p_this, path, p_sys, false );
683 #ifdef HAVE_LIBV4L2
684     }
685     if( p_sys->i_fd == -1 )
686     {
687         p_sys->b_libv4l2 = true;
688         msg_Dbg( p_this, "Trying libv4l2 wrapper" );
689         p_sys->i_fd = OpenVideoDev( p_this, path, p_sys, false );
690     }
691 #endif
692     free( path );
693     if( p_sys->i_fd == -1 )
694     {
695         free( p_sys );
696         return VLC_EGENERIC;
697     }
698
699     if( p_sys->io == IO_METHOD_READ )
700         ACCESS_SET_CALLBACKS( AccessReadStream, NULL, AccessControl, NULL );
701     else
702         ACCESS_SET_CALLBACKS( NULL, AccessRead, AccessControl, NULL );
703     return VLC_SUCCESS;
704 }
705
706 /*****************************************************************************
707  * DemuxControl:
708  *****************************************************************************/
709 static int DemuxControl( demux_t *p_demux, int i_query, va_list args )
710 {
711     switch( i_query )
712     {
713         /* Special for access_demux */
714         case DEMUX_CAN_PAUSE:
715         case DEMUX_CAN_SEEK:
716         case DEMUX_CAN_CONTROL_PACE:
717             *va_arg( args, bool * ) = false;
718             return VLC_SUCCESS;
719
720         case DEMUX_GET_PTS_DELAY:
721             *va_arg(args,int64_t *) = INT64_C(1000)
722                 * var_InheritInteger( p_demux, "live-caching" );
723             return VLC_SUCCESS;
724
725         case DEMUX_GET_TIME:
726             *va_arg( args, int64_t * ) = mdate();
727             return VLC_SUCCESS;
728
729         /* TODO implement others */
730         default:
731             return VLC_EGENERIC;
732     }
733
734     return VLC_EGENERIC;
735 }
736
737 /*****************************************************************************
738  * AccessControl: access callback
739  *****************************************************************************/
740 static int AccessControl( access_t *p_access, int i_query, va_list args )
741 {
742     switch( i_query )
743     {
744         /* */
745         case ACCESS_CAN_SEEK:
746         case ACCESS_CAN_FASTSEEK:
747         case ACCESS_CAN_PAUSE:
748         case ACCESS_CAN_CONTROL_PACE:
749             *va_arg( args, bool* ) = false;
750             break;
751
752         /* */
753         case ACCESS_GET_PTS_DELAY:
754             *va_arg(args,int64_t *) = INT64_C(1000)
755                 * var_InheritInteger( p_access, "live-caching" );
756             break;
757
758         /* */
759         case ACCESS_SET_PAUSE_STATE:
760             /* Nothing to do */
761             break;
762
763         case ACCESS_GET_TITLE_INFO:
764         case ACCESS_SET_TITLE:
765         case ACCESS_SET_SEEKPOINT:
766         case ACCESS_SET_PRIVATE_ID_STATE:
767         case ACCESS_GET_CONTENT_TYPE:
768         case ACCESS_GET_META:
769             return VLC_EGENERIC;
770
771         default:
772             msg_Warn( p_access, "Unimplemented query in control(%d).", i_query);
773             return VLC_EGENERIC;
774
775     }
776     return VLC_SUCCESS;
777 }
778
779 /*****************************************************************************
780  * AccessRead: access callback
781  ******************************************************************************/
782 static block_t *AccessRead( access_t * p_access )
783 {
784     demux_sys_t *p_sys = (demux_sys_t *)p_access->p_sys;
785
786     struct pollfd fd;
787     fd.fd = p_sys->i_fd;
788     fd.events = POLLIN|POLLPRI;
789     fd.revents = 0;
790
791     /* Wait for data */
792     if( poll( &fd, 1, 500 ) > 0 ) /* Timeout after 0.5 seconds since I don't know if pf_demux can be blocking. */
793         return GrabVideo( VLC_OBJECT(p_access), p_sys );
794
795     return NULL;
796 }
797
798 static ssize_t AccessReadStream( access_t * p_access, uint8_t * p_buffer, size_t i_len )
799 {
800     demux_sys_t *p_sys = (demux_sys_t *) p_access->p_sys;
801     struct pollfd ufd;
802     int i_ret;
803
804     ufd.fd = p_sys->i_fd;
805     ufd.events = POLLIN;
806
807     if( p_access->info.b_eof )
808         return 0;
809
810     do
811     {
812         if( !vlc_object_alive (p_access) )
813             return 0;
814
815         ufd.revents = 0;
816     }
817     while( ( i_ret = poll( &ufd, 1, 500 ) ) == 0 );
818
819     if( i_ret < 0 )
820     {
821         if( errno != EINTR )
822             msg_Err( p_access, "poll error" );
823         return -1;
824     }
825
826     i_ret = v4l2_read( p_sys->i_fd, p_buffer, i_len );
827     if( i_ret == 0 )
828     {
829         p_access->info.b_eof = true;
830     }
831     else if( i_ret > 0 )
832     {
833         p_access->info.i_pos += i_ret;
834     }
835
836     return i_ret;
837 }
838
839 /*****************************************************************************
840  * Demux: Processes the audio or video frame
841  *****************************************************************************/
842 static int Demux( demux_t *p_demux )
843 {
844     demux_sys_t *p_sys = p_demux->p_sys;
845
846     struct pollfd fd;
847     fd.fd = p_sys->i_fd;
848     fd.events = POLLIN|POLLPRI;
849     fd.revents = 0;
850
851     /* Wait for data */
852     /* Timeout after 0.5 seconds since I don't know if pf_demux can be blocking. */
853     while( poll( &fd, 1, 500 ) == -1 )
854         if( errno != EINTR )
855         {
856             msg_Err( p_demux, "poll error: %m" );
857             return -1;
858         }
859
860     if( fd.revents )
861     {
862          block_t *p_block = GrabVideo( VLC_OBJECT(p_demux), p_sys );
863          if( p_block )
864          {
865              es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_block->i_pts );
866              es_out_Send( p_demux->out, p_sys->p_es, p_block );
867         }
868     }
869
870     return 1;
871 }
872
873 /*****************************************************************************
874  * GrabVideo: Grab a video frame
875  *****************************************************************************/
876 static block_t* GrabVideo( vlc_object_t *p_demux, demux_sys_t *p_sys )
877 {
878     block_t *p_block;
879     struct v4l2_buffer buf;
880     ssize_t i_ret;
881
882     /* Grab Video Frame */
883     switch( p_sys->io )
884     {
885     case IO_METHOD_READ:
886         i_ret = v4l2_read( p_sys->i_fd, p_sys->p_buffers[0].start, p_sys->p_buffers[0].length );
887         if( i_ret == -1 )
888         {
889             switch( errno )
890             {
891             case EAGAIN:
892                 return NULL;
893             case EIO:
894                 /* Could ignore EIO, see spec. */
895                 /* fall through */
896             default:
897                 msg_Err( p_demux, "Failed to read frame" );
898                 return 0;
899                }
900         }
901
902         p_block = ProcessVideoFrame( p_demux, (uint8_t*)p_sys->p_buffers[0].start, i_ret );
903         if( !p_block )
904             return NULL;
905
906         break;
907
908     case IO_METHOD_MMAP:
909         memset( &buf, 0, sizeof(buf) );
910         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
911         buf.memory = V4L2_MEMORY_MMAP;
912
913         /* Wait for next frame */
914         if (v4l2_ioctl( p_sys->i_fd, VIDIOC_DQBUF, &buf ) < 0 )
915         {
916             switch( errno )
917             {
918             case EAGAIN:
919                 return NULL;
920             case EIO:
921                 /* Could ignore EIO, see spec. */
922                 /* fall through */
923             default:
924                 msg_Err( p_demux, "Failed to wait (VIDIOC_DQBUF)" );
925                 return NULL;
926                }
927         }
928
929         if( buf.index >= p_sys->i_nbuffers ) {
930             msg_Err( p_demux, "Failed capturing new frame as i>=nbuffers" );
931             return NULL;
932         }
933
934         p_block = ProcessVideoFrame( p_demux, p_sys->p_buffers[buf.index].start, buf.bytesused );
935         if( !p_block )
936             return NULL;
937
938         /* Unlock */
939         if( v4l2_ioctl( p_sys->i_fd, VIDIOC_QBUF, &buf ) < 0 )
940         {
941             msg_Err( p_demux, "Failed to unlock (VIDIOC_QBUF)" );
942             block_Release( p_block );
943             return NULL;
944         }
945
946         break;
947
948     case IO_METHOD_USERPTR:
949         memset( &buf, 0, sizeof(buf) );
950         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
951         buf.memory = V4L2_MEMORY_USERPTR;
952
953         /* Wait for next frame */
954         if (v4l2_ioctl( p_sys->i_fd, VIDIOC_DQBUF, &buf ) < 0 )
955         {
956             switch( errno )
957             {
958             case EAGAIN:
959                 return NULL;
960             case EIO:
961                 /* Could ignore EIO, see spec. */
962                 /* fall through */
963             default:
964                 msg_Err( p_demux, "Failed to wait (VIDIOC_DQBUF)" );
965                 return NULL;
966             }
967         }
968
969         /* Find frame? */
970         unsigned int i;
971         for( i = 0; i < p_sys->i_nbuffers; i++ )
972         {
973             if( buf.m.userptr == (unsigned long)p_sys->p_buffers[i].start &&
974                 buf.length == p_sys->p_buffers[i].length ) break;
975         }
976
977         if( i >= p_sys->i_nbuffers )
978         {
979             msg_Err( p_demux, "Failed capturing new frame as i>=nbuffers" );
980             return NULL;
981         }
982
983         p_block = ProcessVideoFrame( p_demux, (uint8_t*)buf.m.userptr, buf.bytesused );
984         if( !p_block )
985             return NULL;
986
987         /* Unlock */
988         if( v4l2_ioctl( p_sys->i_fd, VIDIOC_QBUF, &buf ) < 0 )
989         {
990             msg_Err( p_demux, "Failed to unlock (VIDIOC_QBUF)" );
991             block_Release( p_block );
992             return NULL;
993         }
994
995         break;
996     }
997
998     /* Timestamp */
999     p_block->i_pts = p_block->i_dts = mdate();
1000     p_block->i_flags |= p_sys->i_block_flags;
1001
1002     return p_block;
1003 }
1004
1005 /*****************************************************************************
1006  * ProcessVideoFrame: Helper function to take a buffer and copy it into
1007  * a new block
1008  *****************************************************************************/
1009 static block_t* ProcessVideoFrame( vlc_object_t *p_demux, uint8_t *p_frame, size_t i_size )
1010 {
1011     block_t *p_block;
1012
1013     if( !p_frame ) return NULL;
1014
1015     /* New block */
1016     if( !( p_block = block_New( p_demux, i_size ) ) )
1017     {
1018         msg_Warn( p_demux, "Cannot get new block" );
1019         return NULL;
1020     }
1021
1022     /* Copy frame */
1023     memcpy( p_block->p_buffer, p_frame, i_size );
1024
1025     return p_block;
1026 }
1027
1028 /*****************************************************************************
1029  * Helper function to initalise video IO using the Read method
1030  *****************************************************************************/
1031 static int InitRead( vlc_object_t *p_demux, demux_sys_t *p_sys, unsigned int i_buffer_size )
1032 {
1033     (void)p_demux;
1034
1035     p_sys->p_buffers = calloc( 1, sizeof( *p_sys->p_buffers ) );
1036     if( unlikely(p_sys->p_buffers == NULL) )
1037         return -1;
1038
1039     p_sys->p_buffers[0].length = i_buffer_size;
1040     p_sys->p_buffers[0].start = malloc( i_buffer_size );
1041     if( !p_sys->p_buffers[0].start )
1042         return -1;
1043
1044     return 0;
1045 }
1046
1047 /*****************************************************************************
1048  * Helper function to initalise video IO using the mmap method
1049  *****************************************************************************/
1050 static int InitMmap( vlc_object_t *p_demux, demux_sys_t *p_sys, int i_fd )
1051 {
1052     struct v4l2_requestbuffers req;
1053
1054     memset( &req, 0, sizeof(req) );
1055     req.count = 4;
1056     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1057     req.memory = V4L2_MEMORY_MMAP;
1058
1059     if( v4l2_ioctl( i_fd, VIDIOC_REQBUFS, &req ) < 0 )
1060     {
1061         msg_Err( p_demux, "device does not support mmap I/O" );
1062         return -1;
1063     }
1064
1065     if( req.count < 2 )
1066     {
1067         msg_Err( p_demux, "insufficient buffers" );
1068         return -1;
1069     }
1070
1071     p_sys->p_buffers = calloc( req.count, sizeof( *p_sys->p_buffers ) );
1072     if( unlikely(!p_sys->p_buffers) )
1073         return -1;
1074
1075     for( p_sys->i_nbuffers = 0; p_sys->i_nbuffers < req.count; ++p_sys->i_nbuffers )
1076     {
1077         struct v4l2_buffer buf;
1078
1079         memset( &buf, 0, sizeof(buf) );
1080         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1081         buf.memory = V4L2_MEMORY_MMAP;
1082         buf.index = p_sys->i_nbuffers;
1083
1084         if( v4l2_ioctl( i_fd, VIDIOC_QUERYBUF, &buf ) < 0 )
1085         {
1086             msg_Err( p_demux, "VIDIOC_QUERYBUF: %m" );
1087             return -1;
1088         }
1089
1090         p_sys->p_buffers[p_sys->i_nbuffers].length = buf.length;
1091         p_sys->p_buffers[p_sys->i_nbuffers].start =
1092             v4l2_mmap( NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, i_fd, buf.m.offset );
1093
1094         if( p_sys->p_buffers[p_sys->i_nbuffers].start == MAP_FAILED )
1095         {
1096             msg_Err( p_demux, "mmap failed: %m" );
1097             return -1;
1098         }
1099     }
1100
1101     return 0;
1102 }
1103
1104 /*****************************************************************************
1105  * Helper function to initalise video IO using the userbuf method
1106  *****************************************************************************/
1107 static int InitUserP( vlc_object_t *p_demux, demux_sys_t *p_sys, int i_fd, unsigned int i_buffer_size )
1108 {
1109     struct v4l2_requestbuffers req;
1110     unsigned int i_page_size;
1111
1112     i_page_size = sysconf(_SC_PAGESIZE);
1113     i_buffer_size = ( i_buffer_size + i_page_size - 1 ) & ~( i_page_size - 1);
1114
1115     memset( &req, 0, sizeof(req) );
1116     req.count = 4;
1117     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1118     req.memory = V4L2_MEMORY_USERPTR;
1119
1120     if( v4l2_ioctl( i_fd, VIDIOC_REQBUFS, &req ) < 0 )
1121     {
1122         msg_Err( p_demux, "device does not support user pointer i/o" );
1123         return -1;
1124     }
1125
1126     p_sys->p_buffers = calloc( 4, sizeof( *p_sys->p_buffers ) );
1127     if( !p_sys->p_buffers )
1128         return -1;
1129
1130     for( p_sys->i_nbuffers = 0; p_sys->i_nbuffers < 4; ++p_sys->i_nbuffers )
1131     {
1132         p_sys->p_buffers[p_sys->i_nbuffers].length = i_buffer_size;
1133         if( posix_memalign( &p_sys->p_buffers[p_sys->i_nbuffers].start,
1134                 /* boundary */ i_page_size, i_buffer_size ) )
1135             return -1;
1136     }
1137
1138     return 0;
1139 }
1140
1141 /**
1142  * \return true if the specified V4L2 pixel format is
1143  * in the array of supported formats returned by the driver
1144  */
1145 static bool IsPixelFormatSupported( struct v4l2_fmtdesc *codecs, size_t n,
1146                                     unsigned int i_pixelformat )
1147 {
1148     for( size_t i = 0; i < n; i++ )
1149         if( codecs[i].pixelformat == i_pixelformat )
1150             return true;
1151     return false;
1152 }
1153
1154 static float GetMaxFrameRate( int i_fd, uint32_t i_pixel_format,
1155                               uint32_t i_width, uint32_t i_height )
1156 {
1157 #ifdef VIDIOC_ENUM_FRAMEINTERVALS
1158     /* This is new in Linux 2.6.19 */
1159     struct v4l2_frmivalenum frmival;
1160     memset( &frmival, 0, sizeof(frmival) );
1161     frmival.pixel_format = i_pixel_format;
1162     frmival.width = i_width;
1163     frmival.height = i_height;
1164     if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival ) >= 0 )
1165     {
1166         switch( frmival.type )
1167         {
1168             case V4L2_FRMIVAL_TYPE_DISCRETE:
1169             {
1170                 float f_fps_max = -1;
1171                 do
1172                 {
1173                     float f_fps = (float)frmival.discrete.denominator
1174                                 / (float)frmival.discrete.numerator;
1175                     if( f_fps > f_fps_max ) f_fps_max = f_fps;
1176                     frmival.index++;
1177                 } while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMEINTERVALS,
1178                                      &frmival ) >= 0 );
1179                 return f_fps_max;
1180             }
1181             case V4L2_FRMSIZE_TYPE_STEPWISE:
1182             case V4L2_FRMIVAL_TYPE_CONTINUOUS:
1183                 return __MAX( (float)frmival.stepwise.max.denominator
1184                             / (float)frmival.stepwise.max.numerator,
1185                               (float)frmival.stepwise.min.denominator
1186                             / (float)frmival.stepwise.min.numerator );
1187         }
1188     }
1189 #endif
1190     return -1.;
1191 }
1192
1193 static float GetAbsoluteMaxFrameRate( demux_t *p_demux, int i_fd,
1194                                       uint32_t i_pixel_format )
1195 {
1196     float f_fps_max = -1.;
1197 #ifdef VIDIOC_ENUM_FRAMESIZES
1198     /* This is new in Linux 2.6.19 */
1199     struct v4l2_frmsizeenum frmsize;
1200     memset( &frmsize, 0, sizeof(frmsize) );
1201     frmsize.pixel_format = i_pixel_format;
1202     if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize ) >= 0 )
1203     {
1204         switch( frmsize.type )
1205         {
1206             case V4L2_FRMSIZE_TYPE_DISCRETE:
1207                 do
1208                 {
1209                     frmsize.index++;
1210                     float f_fps = GetMaxFrameRate( i_fd, i_pixel_format,
1211                                                    frmsize.discrete.width,
1212                                                    frmsize.discrete.height );
1213                     if( f_fps > f_fps_max ) f_fps_max = f_fps;
1214                 } while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES,
1215                          &frmsize ) >= 0 );
1216                 break;
1217             case V4L2_FRMSIZE_TYPE_STEPWISE:
1218             {
1219                 uint32_t i_width = frmsize.stepwise.min_width;
1220                 uint32_t i_height = frmsize.stepwise.min_height;
1221                 for( ;
1222                      i_width <= frmsize.stepwise.max_width &&
1223                      i_height <= frmsize.stepwise.max_width;
1224                      i_width += frmsize.stepwise.step_width,
1225                      i_height += frmsize.stepwise.step_height )
1226                 {
1227                     float f_fps = GetMaxFrameRate( i_fd, i_pixel_format,
1228                                                    i_width, i_height );
1229                     if( f_fps > f_fps_max ) f_fps_max = f_fps;
1230                 }
1231                 break;
1232             }
1233             case V4L2_FRMSIZE_TYPE_CONTINUOUS:
1234                 /* FIXME */
1235                 msg_Err( p_demux, "GetAbsoluteMaxFrameRate implementation for V4L2_FRMSIZE_TYPE_CONTINUOUS isn't correct" );
1236                  f_fps_max = GetMaxFrameRate( i_fd, i_pixel_format,
1237                                               frmsize.stepwise.max_width,
1238                                               frmsize.stepwise.max_height );
1239                 break;
1240         }
1241     }
1242 #endif
1243     return f_fps_max;
1244 }
1245
1246 static void GetMaxDimensions( demux_t *p_demux, int i_fd,
1247                               uint32_t i_pixel_format, float f_fps_min,
1248                               uint32_t *pi_width, uint32_t *pi_height )
1249 {
1250     *pi_width = 0;
1251     *pi_height = 0;
1252 #ifdef VIDIOC_ENUM_FRAMESIZES
1253     /* This is new in Linux 2.6.19 */
1254     struct v4l2_frmsizeenum frmsize;
1255     memset( &frmsize, 0, sizeof(frmsize) );
1256     frmsize.pixel_format = i_pixel_format;
1257     if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize ) >= 0 )
1258     {
1259         switch( frmsize.type )
1260         {
1261             case V4L2_FRMSIZE_TYPE_DISCRETE:
1262                 do
1263                 {
1264                     frmsize.index++;
1265                     float f_fps = GetMaxFrameRate( i_fd, i_pixel_format,
1266                                                    frmsize.discrete.width,
1267                                                    frmsize.discrete.height );
1268                     if( f_fps >= f_fps_min &&
1269                         frmsize.discrete.width > *pi_width )
1270                     {
1271                         *pi_width = frmsize.discrete.width;
1272                         *pi_height = frmsize.discrete.height;
1273                     }
1274                 } while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES,
1275                          &frmsize ) >= 0 );
1276                 break;
1277             case V4L2_FRMSIZE_TYPE_STEPWISE:
1278             {
1279                 uint32_t i_width = frmsize.stepwise.min_width;
1280                 uint32_t i_height = frmsize.stepwise.min_height;
1281                 for( ;
1282                      i_width <= frmsize.stepwise.max_width &&
1283                      i_height <= frmsize.stepwise.max_width;
1284                      i_width += frmsize.stepwise.step_width,
1285                      i_height += frmsize.stepwise.step_height )
1286                 {
1287                     float f_fps = GetMaxFrameRate( i_fd, i_pixel_format,
1288                                                    i_width, i_height );
1289                     if( f_fps >= f_fps_min && i_width > *pi_width )
1290                     {
1291                         *pi_width = i_width;
1292                         *pi_height = i_height;
1293                     }
1294                 }
1295                 break;
1296             }
1297             case V4L2_FRMSIZE_TYPE_CONTINUOUS:
1298                 /* FIXME */
1299                 msg_Err( p_demux, "GetMaxDimension implementation for V4L2_FRMSIZE_TYPE_CONTINUOUS isn't correct" );
1300                 float f_fps = GetMaxFrameRate( i_fd, i_pixel_format,
1301                                                frmsize.stepwise.max_width,
1302                                                frmsize.stepwise.max_height );
1303                 if( f_fps >= f_fps_min &&
1304                     frmsize.stepwise.max_width > *pi_width )
1305                 {
1306                     *pi_width = frmsize.stepwise.max_width;
1307                     *pi_height = frmsize.stepwise.max_height;
1308                 }
1309                 break;
1310         }
1311     }
1312 #endif
1313 }
1314
1315 /**
1316  * Opens and sets up a video device
1317  * \return file descriptor or -1 on error
1318  */
1319 static int OpenVideoDev( vlc_object_t *p_obj, const char *path,
1320                          demux_sys_t *p_sys, bool b_demux )
1321 {
1322     struct v4l2_cropcap cropcap;
1323     struct v4l2_crop crop;
1324     struct v4l2_format fmt;
1325     unsigned int i_min;
1326     enum v4l2_buf_type buf_type;
1327     es_format_t es_fmt;
1328     struct v4l2_fmtdesc *codecs = NULL;
1329
1330     msg_Dbg( p_obj, "opening device '%s'", path );
1331
1332     int i_fd = vlc_open( path, O_RDWR );
1333     if( i_fd == -1 )
1334     {
1335         msg_Err( p_obj, "cannot open device %s: %m", path );
1336         return -1;
1337     }
1338
1339 #ifdef HAVE_LIBV4L2
1340     /* Note the v4l2_xxx functions are designed so that if they get passed an
1341        unknown fd, the will behave exactly as their regular xxx counterparts,
1342        so if v4l2_fd_open fails, we continue as normal (missing the libv4l2
1343        custom cam format to normal formats conversion). Chances are big we will
1344        still fail then though, as normally v4l2_fd_open only fails if the
1345        device is not a v4l2 device. */
1346     if( p_sys->b_libv4l2 )
1347     {
1348         int libv4l2_fd;
1349         libv4l2_fd = v4l2_fd_open( i_fd, 0 );
1350         if( libv4l2_fd != -1 )
1351             i_fd = libv4l2_fd;
1352     }
1353 #endif
1354
1355     /* Get device capabilites */
1356     struct v4l2_capability cap;
1357     if( v4l2_ioctl( i_fd, VIDIOC_QUERYCAP, &cap ) < 0 )
1358     {
1359         msg_Err( p_obj, "cannot get video capabilities: %m" );
1360         return -1;
1361     }
1362
1363     msg_Dbg( p_obj, "device %s using driver %s (version %u.%u.%u) on %s",
1364             cap.card, cap.driver, (cap.version >> 16) & 0xFF,
1365             (cap.version >> 8) & 0xFF, cap.version & 0xFF, cap.bus_info );
1366     msg_Dbg( p_obj, "the device has the capabilities: 0x%08X",
1367              cap.capabilities );
1368     msg_Dbg( p_obj, " (%c) Video Capture, (%c) Audio, (%c) Tuner, (%c) Radio",
1369              ( cap.capabilities & V4L2_CAP_VIDEO_CAPTURE  ? 'X':' '),
1370              ( cap.capabilities & V4L2_CAP_AUDIO  ? 'X':' '),
1371              ( cap.capabilities & V4L2_CAP_TUNER  ? 'X':' '),
1372              ( cap.capabilities & V4L2_CAP_RADIO  ? 'X':' ') );
1373     msg_Dbg( p_obj, " (%c) Read/Write, (%c) Streaming, (%c) Asynchronous",
1374             ( cap.capabilities & V4L2_CAP_READWRITE ? 'X':' ' ),
1375             ( cap.capabilities & V4L2_CAP_STREAMING ? 'X':' ' ),
1376             ( cap.capabilities & V4L2_CAP_ASYNCIO ? 'X':' ' ) );
1377
1378     if( cap.capabilities & V4L2_CAP_STREAMING )
1379         p_sys->io = IO_METHOD_MMAP;
1380     else if( cap.capabilities & V4L2_CAP_READWRITE )
1381         p_sys->io = IO_METHOD_READ;
1382     else
1383     {
1384         msg_Err( p_obj, "no supported I/O method" );
1385         goto error;
1386     }
1387
1388     /* Now, enumerate all the video inputs. This is useless at the moment
1389        since we have no way to present that info to the user except with
1390        debug messages */
1391     if( cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
1392     {
1393         struct v4l2_input input;
1394         unsigned index = var_InheritInteger( p_obj, CFG_PREFIX"input" );
1395
1396         input.index = 0;
1397         while( v4l2_ioctl( i_fd, VIDIOC_ENUMINPUT, &input ) >= 0 )
1398         {
1399             msg_Dbg( p_obj, "video input %u (%s) has type: %s %c",
1400                      input.index, input.name,
1401                      input.type == V4L2_INPUT_TYPE_TUNER
1402                           ? "Tuner adapter" : "External analog input",
1403                      input.index == index ? '*' : ' ' );
1404             input.index++;
1405         }
1406
1407         /* Select input */
1408         if( v4l2_ioctl( i_fd, VIDIOC_S_INPUT, &index ) < 0 )
1409         {
1410             msg_Err( p_obj, "cannot set input %u: %m", index );
1411             goto error;
1412         }
1413         msg_Dbg( p_obj, "input set to %u", index );
1414     }
1415
1416     /* Select standard */
1417     bool bottom_first;
1418     const char *stdname = var_InheritString( p_obj, CFG_PREFIX"standard" );
1419     if( stdname != NULL )
1420     {
1421         v4l2_std_id std = strtoull( stdname, NULL, 0 );
1422         if( std == 0 )
1423         {
1424             const size_t n = sizeof(standards_vlc) / sizeof(*standards_vlc);
1425             assert( n == sizeof(standards_v4l2) / sizeof(*standards_v4l2) );
1426             assert( n == sizeof(standards_user) / sizeof(*standards_user) );
1427             for( size_t i = 0; i < n; i++ )
1428                 if( strcasecmp( stdname, standards_vlc[i] ) == 0 )
1429                 {
1430                     std = standards_v4l2[i];
1431                     break;
1432                 }
1433         }
1434
1435         if( v4l2_ioctl( i_fd, VIDIOC_S_STD, &std ) < 0
1436          || v4l2_ioctl( i_fd, VIDIOC_G_STD, &std ) < 0 )
1437         {
1438             msg_Err( p_obj, "cannot set standard 0x%"PRIx64": %m", std );
1439             goto error;
1440         }
1441         msg_Dbg( p_obj, "standard set to 0x%"PRIx64":", std );
1442         bottom_first = std == V4L2_STD_NTSC;
1443     }
1444     else
1445         bottom_first = false;
1446
1447     /* Set audio input */
1448     if( cap.capabilities & V4L2_CAP_AUDIO )
1449     {
1450         struct v4l2_audio audio = { .index = 0 };
1451         uint32_t idx = var_InheritInteger( p_obj, CFG_PREFIX"audio-input" );
1452
1453         /* Probe audio inputs */
1454         while( v4l2_ioctl( i_fd, VIDIOC_ENUMAUDIO, &audio ) >= 0 )
1455         {
1456             msg_Dbg( p_obj, "audio input %u (%s) is %s%s %c", audio.index,
1457                      audio.name,
1458                      audio.capability & V4L2_AUDCAP_STEREO ? "Stereo" : "Mono",
1459                      audio.capability & V4L2_AUDCAP_AVL
1460                          ? " (Automatic Volume Level supported)" : "",
1461                      audio.index == idx );
1462             audio.index++;
1463         }
1464
1465         if( idx != (uint32_t)-1 )
1466         {
1467             memset( &audio, 0, sizeof(audio) );
1468             audio.index = idx;
1469             /* TODO: AVL support (audio.mode) */
1470
1471             if( v4l2_ioctl( i_fd, VIDIOC_S_AUDIO, &audio ) < 0 )
1472             {
1473                 msg_Err( p_obj, "cannot set audio input %"PRIu32": %m", idx );
1474                 goto error;
1475             }
1476             msg_Dbg( p_obj, "audio input set to %"PRIu32, idx );
1477         }
1478     }
1479
1480     /* List tuner caps */
1481     if( cap.capabilities & V4L2_CAP_TUNER )
1482     {
1483         struct v4l2_tuner tuner;
1484         uint32_t idx = var_CreateGetInteger( p_obj, CFG_PREFIX"tuner" );
1485         enum v4l2_tuner_type type = V4L2_TUNER_RADIO;
1486
1487         tuner.index = 0;
1488         while( v4l2_ioctl( i_fd, VIDIOC_G_TUNER, &tuner ) >= 0 )
1489         {
1490             if( tuner.index == idx )
1491                 type = tuner.type;
1492
1493             const char *unit =
1494                 (tuner.capability & V4L2_TUNER_CAP_LOW) ? "Hz" : "kHz";
1495             msg_Dbg( p_obj, "tuner %u (%s) has type: %s, "
1496                      "frequency range: %.1f %s -> %.1f %s", tuner.index,
1497                      tuner.name,
1498                      tuner.type == V4L2_TUNER_RADIO ? "Radio" : "Analog TV",
1499                      tuner.rangelow * 62.5, unit,
1500                      tuner.rangehigh * 62.5, unit );
1501
1502             struct v4l2_frequency frequency = { .tuner = tuner.index };
1503             if( v4l2_ioctl( i_fd, VIDIOC_G_FREQUENCY, &frequency ) < 0 )
1504             {
1505                 msg_Err( p_obj, "cannot get tuner frequency: %m" );
1506                 return -1;
1507             }
1508             msg_Dbg( p_obj, "tuner %u (%s) frequency: %.1f %s", tuner.index,
1509                      tuner.name, frequency.frequency * 62.5, unit );
1510             tuner.index++;
1511         }
1512
1513         /* Tune the tuner */
1514         uint32_t freq = var_InheritInteger( p_obj,
1515                                             CFG_PREFIX"tuner-frequency" );
1516         if( freq != (uint32_t)-1 )
1517         {
1518             struct v4l2_frequency frequency = {
1519                 .tuner = idx,
1520                 .type = type,
1521                 .frequency = freq / 62.5,
1522             };
1523
1524             if( v4l2_ioctl( i_fd, VIDIOC_S_FREQUENCY, &frequency ) < 0 )
1525             {
1526                 msg_Err( p_obj, "cannot set tuner frequency: %m" );
1527                 goto error;
1528             }
1529             msg_Dbg( p_obj, "tuner frequency set" );
1530         }
1531
1532         /* Set the tuner audio mode */
1533         int32_t audmode = var_InheritInteger( p_obj,
1534                                               CFG_PREFIX"tuner-audio-mode" );
1535         if( audmode >= 0 )
1536         {
1537             struct v4l2_tuner tuner = {
1538                 .index = idx,
1539                 .audmode = audmode,
1540             };
1541
1542             if( v4l2_ioctl( i_fd, VIDIOC_S_TUNER, &tuner ) < 0 )
1543             {
1544                 msg_Err( p_obj, "cannot set tuner audio mode: %m" );
1545                 goto error;
1546             }
1547             msg_Dbg( p_obj, "tuner audio mode set" );
1548         }
1549     }
1550
1551     /* Probe for available chromas */
1552     uint_fast32_t ncodec = 0;
1553     if( cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
1554     {
1555         struct v4l2_fmtdesc codec = {
1556             .index = 0,
1557             .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
1558         };
1559
1560         while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FMT, &codec ) >= 0 )
1561             codec.index = ++ncodec;
1562
1563         codecs = malloc( ncodec * sizeof( *codecs ) );
1564         if( unlikely(codecs == NULL) )
1565             ncodec = 0;
1566
1567         for( uint_fast32_t i = 0; i < ncodec; i++ )
1568         {
1569             codecs[i].index = i;
1570             codecs[i].type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1571
1572             if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FMT, &codecs[i] ) < 0 )
1573             {
1574                 msg_Err( p_obj, "cannot get codec description: %m" );
1575                 return -1;
1576             }
1577
1578             /* only print if vlc supports the format */
1579             char fourcc_v4l2[5];
1580             memset( fourcc_v4l2, 0, sizeof( fourcc_v4l2 ) );
1581             vlc_fourcc_to_char( codecs[i].pixelformat, fourcc_v4l2 );
1582
1583             bool b_codec_supported = false;
1584             for( unsigned j = 0; v4l2chroma_to_fourcc[j].i_v4l2 != 0; j++ )
1585             {
1586                 if( v4l2chroma_to_fourcc[j].i_v4l2 == codecs[i].pixelformat )
1587                 {
1588                     char fourcc[5];
1589                     memset( fourcc, 0, sizeof( fourcc ) );
1590                     vlc_fourcc_to_char( v4l2chroma_to_fourcc[j].i_fourcc,
1591                                         fourcc );
1592                     msg_Dbg( p_obj, "device supports chroma %4.4s [%s, %s]",
1593                              fourcc, codecs[i].description, fourcc_v4l2 );
1594                     b_codec_supported = true;
1595
1596 #ifdef VIDIOC_ENUM_FRAMESIZES
1597                     /* This is new in Linux 2.6.19 */
1598                     /* List valid frame sizes for this format */
1599                     struct v4l2_frmsizeenum frmsize;
1600                     memset( &frmsize, 0, sizeof(frmsize) );
1601                     frmsize.pixel_format = codecs[i].pixelformat;
1602                     if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize ) < 0 )
1603                     {
1604                         /* Not all devices support this ioctl */
1605                         msg_Warn( p_obj, "Unable to query for frame sizes" );
1606                     }
1607                     else
1608                     {
1609                         switch( frmsize.type )
1610                         {
1611                             case V4L2_FRMSIZE_TYPE_DISCRETE:
1612                                 do
1613                                 {
1614                                     msg_Dbg( p_obj,
1615                 "    device supports size %dx%d",
1616                 frmsize.discrete.width, frmsize.discrete.height );
1617                                     frmsize.index++;
1618                                 } while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize ) >= 0 );
1619                                 break;
1620                             case V4L2_FRMSIZE_TYPE_STEPWISE:
1621                                 msg_Dbg( p_obj,
1622                 "    device supports sizes %dx%d to %dx%d using %dx%d increments",
1623                 frmsize.stepwise.min_width, frmsize.stepwise.min_height,
1624                 frmsize.stepwise.max_width, frmsize.stepwise.max_height,
1625                 frmsize.stepwise.step_width, frmsize.stepwise.step_height );
1626                                 break;
1627                             case V4L2_FRMSIZE_TYPE_CONTINUOUS:
1628                                 msg_Dbg( p_obj,
1629                 "    device supports all sizes %dx%d to %dx%d",
1630                 frmsize.stepwise.min_width, frmsize.stepwise.min_height,
1631                 frmsize.stepwise.max_width, frmsize.stepwise.max_height );
1632                                 break;
1633                         }
1634                     }
1635 #endif
1636                 }
1637             }
1638             if( !b_codec_supported )
1639             {
1640                 msg_Dbg( p_obj, "device codec %4.4s (%s) not supported",
1641                          fourcc_v4l2, codecs[i].description );
1642             }
1643         }
1644     }
1645
1646     /* TODO: Move the resolution stuff up here */
1647     /* if MPEG encoder card, no need to do anything else after this */
1648     ControlList( p_obj, i_fd, b_demux );
1649
1650     /* Reset Cropping */
1651     memset( &cropcap, 0, sizeof(cropcap) );
1652     cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1653     if( v4l2_ioctl( i_fd, VIDIOC_CROPCAP, &cropcap ) >= 0 )
1654     {
1655         crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1656         crop.c = cropcap.defrect; /* reset to default */
1657         if( crop.c.width > 0 && crop.c.height > 0 ) /* Fix for fm tuners */
1658         {
1659             if( v4l2_ioctl( i_fd, VIDIOC_S_CROP, &crop ) < 0 )
1660             {
1661                 switch( errno )
1662                 {
1663                     case EINVAL:
1664                         /* Cropping not supported. */
1665                         break;
1666                     default:
1667                         /* Errors ignored. */
1668                         break;
1669                 }
1670             }
1671         }
1672     }
1673
1674     /* Try and find default resolution if not specified */
1675     int width = var_InheritInteger( p_obj, CFG_PREFIX"width" );
1676     int height = var_InheritInteger( p_obj, CFG_PREFIX"height" );
1677
1678     memset( &fmt, 0, sizeof(fmt) );
1679     fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1680
1681     if( width <= 0 || height <= 0 )
1682     {
1683         /* Use current width and height settings */
1684         if( v4l2_ioctl( i_fd, VIDIOC_G_FMT, &fmt ) < 0 )
1685         {
1686             msg_Err( p_obj, "cannot get default width and height: %m" );
1687             goto error;
1688         }
1689
1690         msg_Dbg( p_obj, "found default width and height of %ux%u",
1691                  fmt.fmt.pix.width, fmt.fmt.pix.height );
1692
1693         if( width < 0 || height < 0 )
1694         {
1695             msg_Dbg( p_obj, "will try to find optimal width and height" );
1696         }
1697     }
1698     else
1699     {
1700         /* Use user specified width and height */
1701         msg_Dbg( p_obj, "trying specified size %dx%d", width, height );
1702         fmt.fmt.pix.width = width;
1703         fmt.fmt.pix.height = height;
1704     }
1705
1706     fmt.fmt.pix.field = V4L2_FIELD_NONE;
1707
1708     float f_fps;
1709     if (b_demux)
1710     {
1711         demux_t *p_demux = (demux_t *) p_obj;
1712         char *reqchroma = var_InheritString( p_obj, CFG_PREFIX"chroma" );
1713
1714         /* Test and set Chroma */
1715         fmt.fmt.pix.pixelformat = 0;
1716         if( reqchroma != NULL )
1717         {
1718             /* User specified chroma */
1719             const vlc_fourcc_t i_requested_fourcc =
1720                 vlc_fourcc_GetCodecFromString( VIDEO_ES, reqchroma );
1721
1722             for( int i = 0; v4l2chroma_to_fourcc[i].i_v4l2 != 0; i++ )
1723             {
1724                 if( v4l2chroma_to_fourcc[i].i_fourcc == i_requested_fourcc )
1725                 {
1726                     fmt.fmt.pix.pixelformat = v4l2chroma_to_fourcc[i].i_v4l2;
1727                     break;
1728                 }
1729             }
1730             /* Try and set user chroma */
1731             bool b_error = !IsPixelFormatSupported( codecs, ncodec,
1732                                                     fmt.fmt.pix.pixelformat );
1733             if( !b_error && fmt.fmt.pix.pixelformat )
1734             {
1735                 if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 )
1736                 {
1737                     fmt.fmt.pix.field = V4L2_FIELD_ANY;
1738                     if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 )
1739                     {
1740                         fmt.fmt.pix.field = V4L2_FIELD_NONE;
1741                         b_error = true;
1742                     }
1743                 }
1744             }
1745             if( b_error )
1746             {
1747                 msg_Warn( p_obj, "requested chroma %s not supported. "
1748                           " Trying default.", reqchroma );
1749                 fmt.fmt.pix.pixelformat = 0;
1750             }
1751             free( reqchroma );
1752         }
1753
1754         /* If no user specified chroma, find best */
1755         /* This also decides if MPEG encoder card or not */
1756         if( !fmt.fmt.pix.pixelformat )
1757         {
1758             unsigned int i;
1759             for( i = 0; i < ARRAY_SIZE( p_chroma_fallbacks ); i++ )
1760             {
1761                 fmt.fmt.pix.pixelformat = p_chroma_fallbacks[i];
1762                 if( IsPixelFormatSupported( codecs, ncodec,
1763                                             fmt.fmt.pix.pixelformat ) )
1764                 {
1765                     if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) >= 0 )
1766                         break;
1767                     fmt.fmt.pix.field = V4L2_FIELD_ANY;
1768                     if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) >= 0 )
1769                         break;
1770                     fmt.fmt.pix.field = V4L2_FIELD_NONE;
1771                 }
1772             }
1773             if( i == ARRAY_SIZE( p_chroma_fallbacks ) )
1774             {
1775                 msg_Warn( p_demux, "Could not select any of the default chromas; attempting to open as MPEG encoder card (access)" );
1776                 goto error;
1777             }
1778         }
1779
1780         if( width < 0 || height < 0 )
1781         {
1782             f_fps = var_InheritFloat( p_obj, CFG_PREFIX"fps" );
1783             if( f_fps <= 0. )
1784             {
1785                 f_fps = GetAbsoluteMaxFrameRate( p_demux, i_fd,
1786                                                  fmt.fmt.pix.pixelformat );
1787                 msg_Dbg( p_demux, "Found maximum framerate of %f", f_fps );
1788             }
1789             uint32_t i_width, i_height;
1790             GetMaxDimensions( p_demux, i_fd,
1791                               fmt.fmt.pix.pixelformat, f_fps,
1792                               &i_width, &i_height );
1793             if( i_width || i_height )
1794             {
1795                 msg_Dbg( p_demux, "Found optimal dimensions for framerate %f "
1796                                   "of %ux%u", f_fps, i_width, i_height );
1797                 fmt.fmt.pix.width = i_width;
1798                 fmt.fmt.pix.height = i_height;
1799                 if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 )
1800                 {
1801                     msg_Err( p_obj, "Cannot set size to optimal dimensions "
1802                                     "%ux%u", i_width, i_height );
1803                     goto error;
1804                 }
1805             }
1806             else
1807             {
1808                 msg_Warn( p_obj, "Could not find optimal width and height, "
1809                                  "falling back to driver default." );
1810             }
1811         }
1812     }
1813
1814     width = fmt.fmt.pix.width;
1815     height = fmt.fmt.pix.height;
1816
1817     if( v4l2_ioctl( i_fd, VIDIOC_G_FMT, &fmt ) < 0 ) {;}
1818     /* Print extra info */
1819     msg_Dbg( p_obj, "Driver requires at most %d bytes to store a complete image", fmt.fmt.pix.sizeimage );
1820     /* Check interlacing */
1821     switch( fmt.fmt.pix.field )
1822     {
1823         case V4L2_FIELD_NONE:
1824             msg_Dbg( p_obj, "Interlacing setting: progressive" );
1825             break;
1826         case V4L2_FIELD_TOP:
1827             msg_Dbg( p_obj, "Interlacing setting: top field only" );
1828             break;
1829         case V4L2_FIELD_BOTTOM:
1830             msg_Dbg( p_obj, "Interlacing setting: bottom field only" );
1831             break;
1832         case V4L2_FIELD_INTERLACED:
1833             msg_Dbg( p_obj, "Interlacing setting: interleaved (bottom top if M/NTSC, top bottom otherwise)" );
1834             if( bottom_first )
1835                 p_sys->i_block_flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
1836             else
1837                 p_sys->i_block_flags = BLOCK_FLAG_TOP_FIELD_FIRST;
1838             break;
1839         case V4L2_FIELD_SEQ_TB:
1840             msg_Dbg( p_obj, "Interlacing setting: sequential top bottom (TODO)" );
1841             break;
1842         case V4L2_FIELD_SEQ_BT:
1843             msg_Dbg( p_obj, "Interlacing setting: sequential bottom top (TODO)" );
1844             break;
1845         case V4L2_FIELD_ALTERNATE:
1846             msg_Dbg( p_obj, "Interlacing setting: alternate fields (TODO)" );
1847             height *= 2;
1848             break;
1849         case V4L2_FIELD_INTERLACED_TB:
1850             msg_Dbg( p_obj, "Interlacing setting: interleaved top bottom" );
1851             p_sys->i_block_flags = BLOCK_FLAG_TOP_FIELD_FIRST;
1852             break;
1853         case V4L2_FIELD_INTERLACED_BT:
1854             msg_Dbg( p_obj, "Interlacing setting: interleaved bottom top" );
1855             p_sys->i_block_flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
1856             break;
1857         default:
1858             msg_Warn( p_obj, "Interlacing setting: unknown type (%d)",
1859                       fmt.fmt.pix.field );
1860             break;
1861     }
1862
1863     /* Look up final fourcc */
1864     p_sys->i_fourcc = 0;
1865     for( int i = 0; v4l2chroma_to_fourcc[i].i_fourcc != 0; i++ )
1866     {
1867         if( v4l2chroma_to_fourcc[i].i_v4l2 == fmt.fmt.pix.pixelformat )
1868         {
1869             p_sys->i_fourcc = v4l2chroma_to_fourcc[i].i_fourcc;
1870             es_format_Init( &es_fmt, VIDEO_ES, p_sys->i_fourcc );
1871             es_fmt.video.i_rmask = v4l2chroma_to_fourcc[i].i_rmask;
1872             es_fmt.video.i_gmask = v4l2chroma_to_fourcc[i].i_gmask;
1873             es_fmt.video.i_bmask = v4l2chroma_to_fourcc[i].i_bmask;
1874             break;
1875         }
1876     }
1877
1878     /* Buggy driver paranoia */
1879     i_min = fmt.fmt.pix.width * 2;
1880     if( fmt.fmt.pix.bytesperline < i_min )
1881         fmt.fmt.pix.bytesperline = i_min;
1882     i_min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
1883     if( fmt.fmt.pix.sizeimage < i_min )
1884         fmt.fmt.pix.sizeimage = i_min;
1885
1886 #ifdef VIDIOC_ENUM_FRAMEINTERVALS
1887     /* This is new in Linux 2.6.19 */
1888     /* List supported frame rates */
1889     struct v4l2_frmivalenum frmival;
1890     memset( &frmival, 0, sizeof(frmival) );
1891     frmival.pixel_format = fmt.fmt.pix.pixelformat;
1892     frmival.width = width;
1893     frmival.height = height;
1894     if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival ) >= 0 )
1895     {
1896         char psz_fourcc[5];
1897         memset( &psz_fourcc, 0, sizeof( psz_fourcc ) );
1898         vlc_fourcc_to_char( p_sys->i_fourcc, &psz_fourcc );
1899         msg_Dbg( p_obj, "supported frame intervals for %4.4s, %dx%d:",
1900                  psz_fourcc, frmival.width, frmival.height );
1901         switch( frmival.type )
1902         {
1903             case V4L2_FRMIVAL_TYPE_DISCRETE:
1904                 do
1905                 {
1906                     msg_Dbg( p_obj, "    supported frame interval: %d/%d",
1907                              frmival.discrete.numerator,
1908                              frmival.discrete.denominator );
1909                     frmival.index++;
1910                 } while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival ) >= 0 );
1911                 break;
1912             case V4L2_FRMIVAL_TYPE_STEPWISE:
1913                 msg_Dbg( p_obj, "    supported frame intervals: %d/%d to "
1914                          "%d/%d using %d/%d increments",
1915                          frmival.stepwise.min.numerator,
1916                          frmival.stepwise.min.denominator,
1917                          frmival.stepwise.max.numerator,
1918                          frmival.stepwise.max.denominator,
1919                          frmival.stepwise.step.numerator,
1920                          frmival.stepwise.step.denominator );
1921                 break;
1922             case V4L2_FRMIVAL_TYPE_CONTINUOUS:
1923                 msg_Dbg( p_obj, "    supported frame intervals: %d/%d to %d/%d",
1924                          frmival.stepwise.min.numerator,
1925                          frmival.stepwise.min.denominator,
1926                          frmival.stepwise.max.numerator,
1927                          frmival.stepwise.max.denominator );
1928                 break;
1929         }
1930     }
1931 #endif
1932
1933
1934     /* Init I/O method */
1935     switch( p_sys->io )
1936     {
1937     case IO_METHOD_READ:
1938         if( b_demux && InitRead( p_obj, p_sys, fmt.fmt.pix.sizeimage ) )
1939             goto error;
1940         break;
1941
1942     case IO_METHOD_MMAP:
1943         if( InitMmap( p_obj, p_sys, i_fd ) )
1944             goto error;
1945         for (unsigned int i = 0; i < p_sys->i_nbuffers; ++i)
1946         {
1947             struct v4l2_buffer buf;
1948
1949             memset( &buf, 0, sizeof(buf) );
1950             buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1951             buf.memory = V4L2_MEMORY_MMAP;
1952             buf.index = i;
1953
1954             if( v4l2_ioctl( i_fd, VIDIOC_QBUF, &buf ) < 0 )
1955             {
1956                 msg_Err( p_obj, "VIDIOC_QBUF failed" );
1957                 goto error;
1958             }
1959         }
1960
1961         buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1962         if( v4l2_ioctl( i_fd, VIDIOC_STREAMON, &buf_type ) < 0 )
1963         {
1964             msg_Err( p_obj, "VIDIOC_STREAMON failed" );
1965             goto error;
1966         }
1967         break;
1968
1969     case IO_METHOD_USERPTR:
1970         if( InitUserP( p_obj, p_sys, i_fd, fmt.fmt.pix.sizeimage ) )
1971             goto error;
1972         for( unsigned int i = 0; i < p_sys->i_nbuffers; ++i )
1973         {
1974             struct v4l2_buffer buf;
1975
1976             memset( &buf, 0, sizeof(buf) );
1977             buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1978             buf.memory = V4L2_MEMORY_USERPTR;
1979             buf.index = i;
1980             buf.m.userptr = (unsigned long)p_sys->p_buffers[i].start;
1981             buf.length = p_sys->p_buffers[i].length;
1982
1983             if( v4l2_ioctl( i_fd, VIDIOC_QBUF, &buf ) < 0 )
1984             {
1985                 msg_Err( p_obj, "VIDIOC_QBUF failed" );
1986                 goto error;
1987             }
1988         }
1989
1990         buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1991         if( v4l2_ioctl( i_fd, VIDIOC_STREAMON, &buf_type ) < 0 )
1992         {
1993             msg_Err( p_obj, "VIDIOC_STREAMON failed" );
1994             goto error;
1995         }
1996         break;
1997     }
1998
1999     free( codecs );
2000
2001     if( b_demux )
2002     {
2003         int ar = 4 * VOUT_ASPECT_FACTOR / 3;
2004         char *str = var_InheritString( p_obj, CFG_PREFIX"aspect-ratio" );
2005         if( likely(str != NULL) )
2006         {
2007             const char *delim = strchr( str, ':' );
2008             if( delim )
2009                 ar = atoi( str ) * VOUT_ASPECT_FACTOR / atoi( delim + 1 );
2010             free( str );
2011         }
2012
2013         /* Add */
2014         es_fmt.video.i_width  = width;
2015         es_fmt.video.i_height = height;
2016
2017         /* Get aspect-ratio */
2018         es_fmt.video.i_sar_num = ar * es_fmt.video.i_height;
2019         es_fmt.video.i_sar_den = VOUT_ASPECT_FACTOR * es_fmt.video.i_width;
2020
2021         /* Framerate */
2022         es_fmt.video.i_frame_rate = lround(f_fps * 1000000.);
2023         es_fmt.video.i_frame_rate_base = 1000000;
2024
2025         demux_t *p_demux = (demux_t *) p_obj;
2026         msg_Dbg( p_demux, "added new video es %4.4s %dx%d",
2027             (char*)&es_fmt.i_codec, es_fmt.video.i_width, es_fmt.video.i_height );
2028         msg_Dbg( p_obj, " frame rate: %f", f_fps );
2029
2030         p_sys->p_es = es_out_Add( p_demux->out, &es_fmt );
2031     }
2032     return i_fd;
2033
2034 error:
2035     v4l2_close( i_fd );
2036     free( codecs );
2037     return -1;
2038 }