]> git.sesse.net Git - vlc/blob - modules/access/v4l2/video.c
V4L2: move variables out of p_sys
[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 bool IsPixelFormatSupported( demux_t *p_demux,
423                                           unsigned int i_pixelformat );
424
425 static int OpenVideoDev( vlc_object_t *, const char *path, demux_sys_t *, bool );
426
427 static const struct
428 {
429     unsigned int i_v4l2;
430     vlc_fourcc_t i_fourcc;
431     int i_rmask;
432     int i_gmask;
433     int i_bmask;
434 } v4l2chroma_to_fourcc[] =
435 {
436     /* Raw data types */
437     { V4L2_PIX_FMT_GREY,    VLC_CODEC_GREY, 0, 0, 0 },
438     { V4L2_PIX_FMT_HI240,   VLC_FOURCC('I','2','4','0'), 0, 0, 0 },
439     { V4L2_PIX_FMT_RGB555,  VLC_CODEC_RGB15, 0x001f,0x03e0,0x7c00 },
440     { V4L2_PIX_FMT_RGB565,  VLC_CODEC_RGB16, 0x001f,0x07e0,0xf800 },
441     /* Won't work since we don't know how to handle such gmask values
442      * correctly
443     { V4L2_PIX_FMT_RGB555X, VLC_CODEC_RGB15, 0x007c,0xe003,0x1f00 },
444     { V4L2_PIX_FMT_RGB565X, VLC_CODEC_RGB16, 0x00f8,0xe007,0x1f00 },
445     */
446     { V4L2_PIX_FMT_BGR24,   VLC_CODEC_RGB24, 0xff0000,0xff00,0xff },
447     { V4L2_PIX_FMT_RGB24,   VLC_CODEC_RGB24, 0xff,0xff00,0xff0000 },
448     { V4L2_PIX_FMT_BGR32,   VLC_CODEC_RGB32, 0xff0000,0xff00,0xff },
449     { V4L2_PIX_FMT_RGB32,   VLC_CODEC_RGB32, 0xff,0xff00,0xff0000 },
450     { V4L2_PIX_FMT_YUYV,    VLC_CODEC_YUYV, 0, 0, 0 },
451     { V4L2_PIX_FMT_UYVY,    VLC_CODEC_UYVY, 0, 0, 0 },
452     { V4L2_PIX_FMT_Y41P,    VLC_FOURCC('I','4','1','N'), 0, 0, 0 },
453     { V4L2_PIX_FMT_YUV422P, VLC_CODEC_I422, 0, 0, 0 },
454     { V4L2_PIX_FMT_YVU420,  VLC_CODEC_YV12, 0, 0, 0 },
455     { V4L2_PIX_FMT_YUV411P, VLC_CODEC_I411, 0, 0, 0 },
456     { V4L2_PIX_FMT_YUV410,  VLC_CODEC_I410, 0, 0, 0 },
457
458     /* Raw data types, not in V4L2 spec but still in videodev2.h and supported
459      * by VLC */
460     { V4L2_PIX_FMT_YUV420,  VLC_CODEC_I420, 0, 0, 0 },
461     /* FIXME { V4L2_PIX_FMT_RGB444,  VLC_CODEC_RGB32 }, */
462
463     /* Compressed data types */
464     { V4L2_PIX_FMT_MJPEG,   VLC_CODEC_MJPG, 0, 0, 0 },
465     { V4L2_PIX_FMT_JPEG,    VLC_CODEC_JPEG, 0, 0, 0 },
466 #if 0
467     { V4L2_PIX_FMT_DV,      VLC_FOURCC('?','?','?','?') },
468     { V4L2_PIX_FMT_MPEG,    VLC_FOURCC('?','?','?','?') },
469 #endif
470     { 0, 0, 0, 0, 0 }
471 };
472
473 /**
474  * List of V4L2 chromas were confident enough to use as fallbacks if the
475  * user hasn't provided a --v4l2-chroma value.
476  *
477  * Try YUV chromas first, then RGB little endian and MJPEG as last resort.
478  */
479 static const uint32_t p_chroma_fallbacks[] =
480 { V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_YVU420, V4L2_PIX_FMT_YUV422P,
481   V4L2_PIX_FMT_YUYV, V4L2_PIX_FMT_UYVY, V4L2_PIX_FMT_BGR24,
482   V4L2_PIX_FMT_BGR32, V4L2_PIX_FMT_MJPEG, V4L2_PIX_FMT_JPEG };
483
484 struct buffer_t
485 {
486     void *  start;
487     size_t  length;
488 };
489
490 /*****************************************************************************
491  * DemuxOpen: opens v4l2 device, access_demux callback
492  *****************************************************************************
493  *
494  * url: <video device>::::
495  *
496  *****************************************************************************/
497 static int DemuxOpen( vlc_object_t *p_this )
498 {
499     demux_t     *p_demux = (demux_t*)p_this;
500     demux_sys_t *p_sys;
501
502     /* Set up p_demux */
503     p_demux->pf_control = DemuxControl;
504     p_demux->pf_demux = Demux;
505     p_demux->info.i_update = 0;
506     p_demux->info.i_title = 0;
507     p_demux->info.i_seekpoint = 0;
508
509     p_demux->p_sys = p_sys = calloc( 1, sizeof( demux_sys_t ) );
510     if( p_sys == NULL ) return VLC_ENOMEM;
511
512     char *path = ParseMRL( p_this, p_demux->psz_location );
513     if( path == NULL )
514         path = var_CreateGetNonEmptyString( p_this, CFG_PREFIX"dev" );
515
516 #ifdef HAVE_LIBV4L2
517     p_sys->i_fd = -1;
518     if( !var_InheritBool( p_this, CFG_PREFIX "use-libv4l2" ) )
519     {
520         p_sys->b_libv4l2 = false;
521 #endif
522         msg_Dbg( p_this, "Trying direct kernel v4l2" );
523         p_sys->i_fd = OpenVideoDev( p_this, path, p_sys, true );
524 #ifdef HAVE_LIBV4L2
525     }
526
527     if( p_sys->i_fd == -1 )
528     {
529         p_sys->b_libv4l2 = true;
530         msg_Dbg( p_this, "Trying libv4l2 wrapper" );
531         p_sys->i_fd = OpenVideoDev( p_this, path, p_sys, true );
532     }
533 #endif
534     free( path );
535     if( p_sys->i_fd == -1 )
536     {
537         free( p_sys->p_codecs );
538         free( p_sys );
539         return VLC_EGENERIC;
540     }
541     return VLC_SUCCESS;
542 }
543
544 /**
545  * Parses a V4L2 MRL.
546  * \return device node path (use free()) or NULL if not specified
547  */
548 static char *ParseMRL( vlc_object_t *obj, const char *mrl )
549 {
550     const char *p = strchr( mrl, ':' );
551
552     if( p != NULL )
553     {
554         var_LocationParse( obj, p + 1, CFG_PREFIX );
555         if( p > mrl )
556             return strndup( mrl, p - mrl );
557     }
558     else
559     {
560         if( mrl[0] )
561             return strdup( mrl );
562     }
563     return NULL;
564 }
565
566 /*****************************************************************************
567  * Close: close device, free resources
568  *****************************************************************************/
569 static void AccessClose( vlc_object_t *p_this )
570 {
571     access_t    *p_access = (access_t *)p_this;
572     demux_sys_t *p_sys   = (demux_sys_t *) p_access->p_sys;
573
574     CommonClose( p_this, p_sys );
575 }
576
577 static void DemuxClose( vlc_object_t *p_this )
578 {
579     struct v4l2_buffer buf;
580     enum v4l2_buf_type buf_type;
581     unsigned int i;
582
583     demux_t     *p_demux = (demux_t *)p_this;
584     demux_sys_t *p_sys   = p_demux->p_sys;
585
586     /* Stop video capture */
587     if( p_sys->i_fd >= 0 )
588     {
589         switch( p_sys->io )
590         {
591         case IO_METHOD_READ:
592             /* Nothing to do */
593             break;
594
595         case IO_METHOD_MMAP:
596         case IO_METHOD_USERPTR:
597             /* Some drivers 'hang' internally if this is not done before streamoff */
598             for( unsigned int i = 0; i < p_sys->i_nbuffers; i++ )
599             {
600                 memset( &buf, 0, sizeof(buf) );
601                 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
602                 buf.memory = ( p_sys->io == IO_METHOD_USERPTR ) ?
603                     V4L2_MEMORY_USERPTR : V4L2_MEMORY_MMAP;
604                 v4l2_ioctl( p_sys->i_fd, VIDIOC_DQBUF, &buf ); /* ignore result */
605             }
606
607             buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
608             if( v4l2_ioctl( p_sys->i_fd, VIDIOC_STREAMOFF, &buf_type ) < 0 ) {
609                 msg_Err( p_this, "VIDIOC_STREAMOFF failed" );
610             }
611
612             break;
613         }
614     }
615
616     /* Free Video Buffers */
617     if( p_sys->p_buffers ) {
618         switch( p_sys->io )
619         {
620         case IO_METHOD_READ:
621             free( p_sys->p_buffers[0].start );
622             break;
623
624         case IO_METHOD_MMAP:
625             for( i = 0; i < p_sys->i_nbuffers; ++i )
626             {
627                 if( v4l2_munmap( p_sys->p_buffers[i].start, p_sys->p_buffers[i].length ) )
628                 {
629                     msg_Err( p_this, "munmap failed" );
630                 }
631             }
632             break;
633
634         case IO_METHOD_USERPTR:
635             for( i = 0; i < p_sys->i_nbuffers; ++i )
636             {
637                free( p_sys->p_buffers[i].start );
638             }
639             break;
640         }
641         free( p_sys->p_buffers );
642     }
643
644     CommonClose( p_this, p_sys );
645 }
646
647 static void CommonClose( vlc_object_t *p_this, demux_sys_t *p_sys )
648 {
649     (void)p_this;
650     /* Close */
651     if( p_sys->i_fd >= 0 ) v4l2_close( p_sys->i_fd );
652     free( p_sys->p_codecs );
653     free( p_sys );
654 }
655
656 /*****************************************************************************
657  * AccessOpen: opens v4l2 device, access callback
658  *****************************************************************************
659  *
660  * url: <video device>::::
661  *
662  *****************************************************************************/
663 static int AccessOpen( vlc_object_t * p_this )
664 {
665     access_t *p_access = (access_t*) p_this;
666     demux_sys_t * p_sys;
667
668     /* Only when selected */
669     if( *p_access->psz_access == '\0' ) return VLC_EGENERIC;
670
671     access_InitFields( p_access );
672     p_sys = calloc( 1, sizeof( demux_sys_t ));
673     if( !p_sys ) return VLC_ENOMEM;
674     p_access->p_sys = (access_sys_t*)p_sys;
675
676     char *path = ParseMRL( p_this, p_access->psz_location );
677     if( path == NULL )
678         path = var_InheritString( p_this, CFG_PREFIX"dev" );
679
680 #ifdef HAVE_LIBV4L2
681     p_sys->i_fd = -1;
682     if( !var_InheritBool( p_this, CFG_PREFIX "use-libv4l2" ) )
683     {
684         p_sys->b_libv4l2 = false;
685 #endif
686         msg_Dbg( p_this, "Trying direct kernel v4l2" );
687         p_sys->i_fd = OpenVideoDev( p_this, path, p_sys, false );
688 #ifdef HAVE_LIBV4L2
689     }
690     if( p_sys->i_fd == -1 )
691     {
692         p_sys->b_libv4l2 = true;
693         msg_Dbg( p_this, "Trying libv4l2 wrapper" );
694         p_sys->i_fd = OpenVideoDev( p_this, path, p_sys, false );
695     }
696 #endif
697     free( path );
698     if( p_sys->i_fd == -1 )
699     {
700         free( p_sys->p_codecs );
701         free( p_sys );
702         return VLC_EGENERIC;
703     }
704
705     if( p_sys->io == IO_METHOD_READ )
706         ACCESS_SET_CALLBACKS( AccessReadStream, NULL, AccessControl, NULL );
707     else
708         ACCESS_SET_CALLBACKS( NULL, AccessRead, AccessControl, NULL );
709     return VLC_SUCCESS;
710 }
711
712 /*****************************************************************************
713  * DemuxControl:
714  *****************************************************************************/
715 static int DemuxControl( demux_t *p_demux, int i_query, va_list args )
716 {
717     switch( i_query )
718     {
719         /* Special for access_demux */
720         case DEMUX_CAN_PAUSE:
721         case DEMUX_CAN_SEEK:
722         case DEMUX_CAN_CONTROL_PACE:
723             *va_arg( args, bool * ) = false;
724             return VLC_SUCCESS;
725
726         case DEMUX_GET_PTS_DELAY:
727             *va_arg(args,int64_t *) = INT64_C(1000)
728                 * var_InheritInteger( p_demux, "live-caching" );
729             return VLC_SUCCESS;
730
731         case DEMUX_GET_TIME:
732             *va_arg( args, int64_t * ) = mdate();
733             return VLC_SUCCESS;
734
735         /* TODO implement others */
736         default:
737             return VLC_EGENERIC;
738     }
739
740     return VLC_EGENERIC;
741 }
742
743 /*****************************************************************************
744  * AccessControl: access callback
745  *****************************************************************************/
746 static int AccessControl( access_t *p_access, int i_query, va_list args )
747 {
748     switch( i_query )
749     {
750         /* */
751         case ACCESS_CAN_SEEK:
752         case ACCESS_CAN_FASTSEEK:
753         case ACCESS_CAN_PAUSE:
754         case ACCESS_CAN_CONTROL_PACE:
755             *va_arg( args, bool* ) = false;
756             break;
757
758         /* */
759         case ACCESS_GET_PTS_DELAY:
760             *va_arg(args,int64_t *) = INT64_C(1000)
761                 * var_InheritInteger( p_access, "live-caching" );
762             break;
763
764         /* */
765         case ACCESS_SET_PAUSE_STATE:
766             /* Nothing to do */
767             break;
768
769         case ACCESS_GET_TITLE_INFO:
770         case ACCESS_SET_TITLE:
771         case ACCESS_SET_SEEKPOINT:
772         case ACCESS_SET_PRIVATE_ID_STATE:
773         case ACCESS_GET_CONTENT_TYPE:
774         case ACCESS_GET_META:
775             return VLC_EGENERIC;
776
777         default:
778             msg_Warn( p_access, "Unimplemented query in control(%d).", i_query);
779             return VLC_EGENERIC;
780
781     }
782     return VLC_SUCCESS;
783 }
784
785 /*****************************************************************************
786  * AccessRead: access callback
787  ******************************************************************************/
788 static block_t *AccessRead( access_t * p_access )
789 {
790     demux_sys_t *p_sys = (demux_sys_t *)p_access->p_sys;
791
792     struct pollfd fd;
793     fd.fd = p_sys->i_fd;
794     fd.events = POLLIN|POLLPRI;
795     fd.revents = 0;
796
797     /* Wait for data */
798     if( poll( &fd, 1, 500 ) > 0 ) /* Timeout after 0.5 seconds since I don't know if pf_demux can be blocking. */
799         return GrabVideo( VLC_OBJECT(p_access), p_sys );
800
801     return NULL;
802 }
803
804 static ssize_t AccessReadStream( access_t * p_access, uint8_t * p_buffer, size_t i_len )
805 {
806     demux_sys_t *p_sys = (demux_sys_t *) p_access->p_sys;
807     struct pollfd ufd;
808     int i_ret;
809
810     ufd.fd = p_sys->i_fd;
811     ufd.events = POLLIN;
812
813     if( p_access->info.b_eof )
814         return 0;
815
816     do
817     {
818         if( !vlc_object_alive (p_access) )
819             return 0;
820
821         ufd.revents = 0;
822     }
823     while( ( i_ret = poll( &ufd, 1, 500 ) ) == 0 );
824
825     if( i_ret < 0 )
826     {
827         if( errno != EINTR )
828             msg_Err( p_access, "poll error" );
829         return -1;
830     }
831
832     i_ret = v4l2_read( p_sys->i_fd, p_buffer, i_len );
833     if( i_ret == 0 )
834     {
835         p_access->info.b_eof = true;
836     }
837     else if( i_ret > 0 )
838     {
839         p_access->info.i_pos += i_ret;
840     }
841
842     return i_ret;
843 }
844
845 /*****************************************************************************
846  * Demux: Processes the audio or video frame
847  *****************************************************************************/
848 static int Demux( demux_t *p_demux )
849 {
850     demux_sys_t *p_sys = p_demux->p_sys;
851
852     struct pollfd fd;
853     fd.fd = p_sys->i_fd;
854     fd.events = POLLIN|POLLPRI;
855     fd.revents = 0;
856
857     /* Wait for data */
858     /* Timeout after 0.5 seconds since I don't know if pf_demux can be blocking. */
859     while( poll( &fd, 1, 500 ) == -1 )
860         if( errno != EINTR )
861         {
862             msg_Err( p_demux, "poll error: %m" );
863             return -1;
864         }
865
866     if( fd.revents )
867     {
868          block_t *p_block = GrabVideo( VLC_OBJECT(p_demux), p_sys );
869          if( p_block )
870          {
871              es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_block->i_pts );
872              es_out_Send( p_demux->out, p_sys->p_es, p_block );
873         }
874     }
875
876     return 1;
877 }
878
879 /*****************************************************************************
880  * GrabVideo: Grab a video frame
881  *****************************************************************************/
882 static block_t* GrabVideo( vlc_object_t *p_demux, demux_sys_t *p_sys )
883 {
884     block_t *p_block;
885     struct v4l2_buffer buf;
886     ssize_t i_ret;
887
888     /* Grab Video Frame */
889     switch( p_sys->io )
890     {
891     case IO_METHOD_READ:
892         i_ret = v4l2_read( p_sys->i_fd, p_sys->p_buffers[0].start, p_sys->p_buffers[0].length );
893         if( i_ret == -1 )
894         {
895             switch( errno )
896             {
897             case EAGAIN:
898                 return NULL;
899             case EIO:
900                 /* Could ignore EIO, see spec. */
901                 /* fall through */
902             default:
903                 msg_Err( p_demux, "Failed to read frame" );
904                 return 0;
905                }
906         }
907
908         p_block = ProcessVideoFrame( p_demux, (uint8_t*)p_sys->p_buffers[0].start, i_ret );
909         if( !p_block )
910             return NULL;
911
912         break;
913
914     case IO_METHOD_MMAP:
915         memset( &buf, 0, sizeof(buf) );
916         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
917         buf.memory = V4L2_MEMORY_MMAP;
918
919         /* Wait for next frame */
920         if (v4l2_ioctl( p_sys->i_fd, VIDIOC_DQBUF, &buf ) < 0 )
921         {
922             switch( errno )
923             {
924             case EAGAIN:
925                 return NULL;
926             case EIO:
927                 /* Could ignore EIO, see spec. */
928                 /* fall through */
929             default:
930                 msg_Err( p_demux, "Failed to wait (VIDIOC_DQBUF)" );
931                 return NULL;
932                }
933         }
934
935         if( buf.index >= p_sys->i_nbuffers ) {
936             msg_Err( p_demux, "Failed capturing new frame as i>=nbuffers" );
937             return NULL;
938         }
939
940         p_block = ProcessVideoFrame( p_demux, p_sys->p_buffers[buf.index].start, buf.bytesused );
941         if( !p_block )
942             return NULL;
943
944         /* Unlock */
945         if( v4l2_ioctl( p_sys->i_fd, VIDIOC_QBUF, &buf ) < 0 )
946         {
947             msg_Err( p_demux, "Failed to unlock (VIDIOC_QBUF)" );
948             block_Release( p_block );
949             return NULL;
950         }
951
952         break;
953
954     case IO_METHOD_USERPTR:
955         memset( &buf, 0, sizeof(buf) );
956         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
957         buf.memory = V4L2_MEMORY_USERPTR;
958
959         /* Wait for next frame */
960         if (v4l2_ioctl( p_sys->i_fd, VIDIOC_DQBUF, &buf ) < 0 )
961         {
962             switch( errno )
963             {
964             case EAGAIN:
965                 return NULL;
966             case EIO:
967                 /* Could ignore EIO, see spec. */
968                 /* fall through */
969             default:
970                 msg_Err( p_demux, "Failed to wait (VIDIOC_DQBUF)" );
971                 return NULL;
972             }
973         }
974
975         /* Find frame? */
976         unsigned int i;
977         for( i = 0; i < p_sys->i_nbuffers; i++ )
978         {
979             if( buf.m.userptr == (unsigned long)p_sys->p_buffers[i].start &&
980                 buf.length == p_sys->p_buffers[i].length ) break;
981         }
982
983         if( i >= p_sys->i_nbuffers )
984         {
985             msg_Err( p_demux, "Failed capturing new frame as i>=nbuffers" );
986             return NULL;
987         }
988
989         p_block = ProcessVideoFrame( p_demux, (uint8_t*)buf.m.userptr, buf.bytesused );
990         if( !p_block )
991             return NULL;
992
993         /* Unlock */
994         if( v4l2_ioctl( p_sys->i_fd, VIDIOC_QBUF, &buf ) < 0 )
995         {
996             msg_Err( p_demux, "Failed to unlock (VIDIOC_QBUF)" );
997             block_Release( p_block );
998             return NULL;
999         }
1000
1001         break;
1002     }
1003
1004     /* Timestamp */
1005     p_block->i_pts = p_block->i_dts = mdate();
1006     p_block->i_flags |= p_sys->i_block_flags;
1007
1008     return p_block;
1009 }
1010
1011 /*****************************************************************************
1012  * ProcessVideoFrame: Helper function to take a buffer and copy it into
1013  * a new block
1014  *****************************************************************************/
1015 static block_t* ProcessVideoFrame( vlc_object_t *p_demux, uint8_t *p_frame, size_t i_size )
1016 {
1017     block_t *p_block;
1018
1019     if( !p_frame ) return NULL;
1020
1021     /* New block */
1022     if( !( p_block = block_New( p_demux, i_size ) ) )
1023     {
1024         msg_Warn( p_demux, "Cannot get new block" );
1025         return NULL;
1026     }
1027
1028     /* Copy frame */
1029     memcpy( p_block->p_buffer, p_frame, i_size );
1030
1031     return p_block;
1032 }
1033
1034 /*****************************************************************************
1035  * Helper function to initalise video IO using the Read method
1036  *****************************************************************************/
1037 static int InitRead( vlc_object_t *p_demux, demux_sys_t *p_sys, unsigned int i_buffer_size )
1038 {
1039     (void)p_demux;
1040
1041     p_sys->p_buffers = calloc( 1, sizeof( *p_sys->p_buffers ) );
1042     if( unlikely(p_sys->p_buffers == NULL) )
1043         return -1;
1044
1045     p_sys->p_buffers[0].length = i_buffer_size;
1046     p_sys->p_buffers[0].start = malloc( i_buffer_size );
1047     if( !p_sys->p_buffers[0].start )
1048         return -1;
1049
1050     return 0;
1051 }
1052
1053 /*****************************************************************************
1054  * Helper function to initalise video IO using the mmap method
1055  *****************************************************************************/
1056 static int InitMmap( vlc_object_t *p_demux, demux_sys_t *p_sys, int i_fd )
1057 {
1058     struct v4l2_requestbuffers req;
1059
1060     memset( &req, 0, sizeof(req) );
1061     req.count = 4;
1062     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1063     req.memory = V4L2_MEMORY_MMAP;
1064
1065     if( v4l2_ioctl( i_fd, VIDIOC_REQBUFS, &req ) < 0 )
1066     {
1067         msg_Err( p_demux, "device does not support mmap I/O" );
1068         return -1;
1069     }
1070
1071     if( req.count < 2 )
1072     {
1073         msg_Err( p_demux, "insufficient buffers" );
1074         return -1;
1075     }
1076
1077     p_sys->p_buffers = calloc( req.count, sizeof( *p_sys->p_buffers ) );
1078     if( unlikely(!p_sys->p_buffers) )
1079         return -1;
1080
1081     for( p_sys->i_nbuffers = 0; p_sys->i_nbuffers < req.count; ++p_sys->i_nbuffers )
1082     {
1083         struct v4l2_buffer buf;
1084
1085         memset( &buf, 0, sizeof(buf) );
1086         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1087         buf.memory = V4L2_MEMORY_MMAP;
1088         buf.index = p_sys->i_nbuffers;
1089
1090         if( v4l2_ioctl( i_fd, VIDIOC_QUERYBUF, &buf ) < 0 )
1091         {
1092             msg_Err( p_demux, "VIDIOC_QUERYBUF: %m" );
1093             return -1;
1094         }
1095
1096         p_sys->p_buffers[p_sys->i_nbuffers].length = buf.length;
1097         p_sys->p_buffers[p_sys->i_nbuffers].start =
1098             v4l2_mmap( NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, i_fd, buf.m.offset );
1099
1100         if( p_sys->p_buffers[p_sys->i_nbuffers].start == MAP_FAILED )
1101         {
1102             msg_Err( p_demux, "mmap failed: %m" );
1103             return -1;
1104         }
1105     }
1106
1107     return 0;
1108 }
1109
1110 /*****************************************************************************
1111  * Helper function to initalise video IO using the userbuf method
1112  *****************************************************************************/
1113 static int InitUserP( vlc_object_t *p_demux, demux_sys_t *p_sys, int i_fd, unsigned int i_buffer_size )
1114 {
1115     struct v4l2_requestbuffers req;
1116     unsigned int i_page_size;
1117
1118     i_page_size = sysconf(_SC_PAGESIZE);
1119     i_buffer_size = ( i_buffer_size + i_page_size - 1 ) & ~( i_page_size - 1);
1120
1121     memset( &req, 0, sizeof(req) );
1122     req.count = 4;
1123     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1124     req.memory = V4L2_MEMORY_USERPTR;
1125
1126     if( v4l2_ioctl( i_fd, VIDIOC_REQBUFS, &req ) < 0 )
1127     {
1128         msg_Err( p_demux, "device does not support user pointer i/o" );
1129         return -1;
1130     }
1131
1132     p_sys->p_buffers = calloc( 4, sizeof( *p_sys->p_buffers ) );
1133     if( !p_sys->p_buffers )
1134         return -1;
1135
1136     for( p_sys->i_nbuffers = 0; p_sys->i_nbuffers < 4; ++p_sys->i_nbuffers )
1137     {
1138         p_sys->p_buffers[p_sys->i_nbuffers].length = i_buffer_size;
1139         if( posix_memalign( &p_sys->p_buffers[p_sys->i_nbuffers].start,
1140                 /* boundary */ i_page_size, i_buffer_size ) )
1141             return -1;
1142     }
1143
1144     return 0;
1145 }
1146
1147 /*****************************************************************************
1148  * IsPixelFormatSupported: returns true if the specified V4L2 pixel format is
1149  * in the array of supported formats returned by the driver
1150  *****************************************************************************/
1151 static bool IsPixelFormatSupported( demux_t *p_demux, unsigned int i_pixelformat )
1152 {
1153     demux_sys_t *p_sys = p_demux->p_sys;
1154
1155     for( unsigned i_index = 0; i_index < p_sys->i_codec; i_index++ )
1156     {
1157         if( p_sys->p_codecs[i_index].pixelformat == i_pixelformat )
1158             return true;
1159     }
1160
1161     return false;
1162 }
1163
1164 static float GetMaxFrameRate( int i_fd, uint32_t i_pixel_format,
1165                               uint32_t i_width, uint32_t i_height )
1166 {
1167 #ifdef VIDIOC_ENUM_FRAMEINTERVALS
1168     /* This is new in Linux 2.6.19 */
1169     struct v4l2_frmivalenum frmival;
1170     memset( &frmival, 0, sizeof(frmival) );
1171     frmival.pixel_format = i_pixel_format;
1172     frmival.width = i_width;
1173     frmival.height = i_height;
1174     if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival ) >= 0 )
1175     {
1176         switch( frmival.type )
1177         {
1178             case V4L2_FRMIVAL_TYPE_DISCRETE:
1179             {
1180                 float f_fps_max = -1;
1181                 do
1182                 {
1183                     float f_fps = (float)frmival.discrete.denominator
1184                                 / (float)frmival.discrete.numerator;
1185                     if( f_fps > f_fps_max ) f_fps_max = f_fps;
1186                     frmival.index++;
1187                 } while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMEINTERVALS,
1188                                      &frmival ) >= 0 );
1189                 return f_fps_max;
1190             }
1191             case V4L2_FRMSIZE_TYPE_STEPWISE:
1192             case V4L2_FRMIVAL_TYPE_CONTINUOUS:
1193                 return __MAX( (float)frmival.stepwise.max.denominator
1194                             / (float)frmival.stepwise.max.numerator,
1195                               (float)frmival.stepwise.min.denominator
1196                             / (float)frmival.stepwise.min.numerator );
1197         }
1198     }
1199 #endif
1200     return -1.;
1201 }
1202
1203 static float GetAbsoluteMaxFrameRate( demux_t *p_demux, int i_fd,
1204                                       uint32_t i_pixel_format )
1205 {
1206     float f_fps_max = -1.;
1207 #ifdef VIDIOC_ENUM_FRAMESIZES
1208     /* This is new in Linux 2.6.19 */
1209     struct v4l2_frmsizeenum frmsize;
1210     memset( &frmsize, 0, sizeof(frmsize) );
1211     frmsize.pixel_format = i_pixel_format;
1212     if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize ) >= 0 )
1213     {
1214         switch( frmsize.type )
1215         {
1216             case V4L2_FRMSIZE_TYPE_DISCRETE:
1217                 do
1218                 {
1219                     frmsize.index++;
1220                     float f_fps = GetMaxFrameRate( i_fd, i_pixel_format,
1221                                                    frmsize.discrete.width,
1222                                                    frmsize.discrete.height );
1223                     if( f_fps > f_fps_max ) f_fps_max = f_fps;
1224                 } while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES,
1225                          &frmsize ) >= 0 );
1226                 break;
1227             case V4L2_FRMSIZE_TYPE_STEPWISE:
1228             {
1229                 uint32_t i_width = frmsize.stepwise.min_width;
1230                 uint32_t i_height = frmsize.stepwise.min_height;
1231                 for( ;
1232                      i_width <= frmsize.stepwise.max_width &&
1233                      i_height <= frmsize.stepwise.max_width;
1234                      i_width += frmsize.stepwise.step_width,
1235                      i_height += frmsize.stepwise.step_height )
1236                 {
1237                     float f_fps = GetMaxFrameRate( i_fd, i_pixel_format,
1238                                                    i_width, i_height );
1239                     if( f_fps > f_fps_max ) f_fps_max = f_fps;
1240                 }
1241                 break;
1242             }
1243             case V4L2_FRMSIZE_TYPE_CONTINUOUS:
1244                 /* FIXME */
1245                 msg_Err( p_demux, "GetAbsoluteMaxFrameRate implementation for V4L2_FRMSIZE_TYPE_CONTINUOUS isn't correct" );
1246                  f_fps_max = GetMaxFrameRate( i_fd, i_pixel_format,
1247                                               frmsize.stepwise.max_width,
1248                                               frmsize.stepwise.max_height );
1249                 break;
1250         }
1251     }
1252 #endif
1253     return f_fps_max;
1254 }
1255
1256 static void GetMaxDimensions( demux_t *p_demux, int i_fd,
1257                               uint32_t i_pixel_format, float f_fps_min,
1258                               uint32_t *pi_width, uint32_t *pi_height )
1259 {
1260     *pi_width = 0;
1261     *pi_height = 0;
1262 #ifdef VIDIOC_ENUM_FRAMESIZES
1263     /* This is new in Linux 2.6.19 */
1264     struct v4l2_frmsizeenum frmsize;
1265     memset( &frmsize, 0, sizeof(frmsize) );
1266     frmsize.pixel_format = i_pixel_format;
1267     if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize ) >= 0 )
1268     {
1269         switch( frmsize.type )
1270         {
1271             case V4L2_FRMSIZE_TYPE_DISCRETE:
1272                 do
1273                 {
1274                     frmsize.index++;
1275                     float f_fps = GetMaxFrameRate( i_fd, i_pixel_format,
1276                                                    frmsize.discrete.width,
1277                                                    frmsize.discrete.height );
1278                     if( f_fps >= f_fps_min &&
1279                         frmsize.discrete.width > *pi_width )
1280                     {
1281                         *pi_width = frmsize.discrete.width;
1282                         *pi_height = frmsize.discrete.height;
1283                     }
1284                 } while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES,
1285                          &frmsize ) >= 0 );
1286                 break;
1287             case V4L2_FRMSIZE_TYPE_STEPWISE:
1288             {
1289                 uint32_t i_width = frmsize.stepwise.min_width;
1290                 uint32_t i_height = frmsize.stepwise.min_height;
1291                 for( ;
1292                      i_width <= frmsize.stepwise.max_width &&
1293                      i_height <= frmsize.stepwise.max_width;
1294                      i_width += frmsize.stepwise.step_width,
1295                      i_height += frmsize.stepwise.step_height )
1296                 {
1297                     float f_fps = GetMaxFrameRate( i_fd, i_pixel_format,
1298                                                    i_width, i_height );
1299                     if( f_fps >= f_fps_min && i_width > *pi_width )
1300                     {
1301                         *pi_width = i_width;
1302                         *pi_height = i_height;
1303                     }
1304                 }
1305                 break;
1306             }
1307             case V4L2_FRMSIZE_TYPE_CONTINUOUS:
1308                 /* FIXME */
1309                 msg_Err( p_demux, "GetMaxDimension implementation for V4L2_FRMSIZE_TYPE_CONTINUOUS isn't correct" );
1310                 float f_fps = GetMaxFrameRate( i_fd, i_pixel_format,
1311                                                frmsize.stepwise.max_width,
1312                                                frmsize.stepwise.max_height );
1313                 if( f_fps >= f_fps_min &&
1314                     frmsize.stepwise.max_width > *pi_width )
1315                 {
1316                     *pi_width = frmsize.stepwise.max_width;
1317                     *pi_height = frmsize.stepwise.max_height;
1318                 }
1319                 break;
1320         }
1321     }
1322 #endif
1323 }
1324
1325 /**
1326  * Opens and sets up a video device
1327  * \return file descriptor or -1 on error
1328  */
1329 static int OpenVideoDev( vlc_object_t *p_obj, const char *path,
1330                          demux_sys_t *p_sys, bool b_demux )
1331 {
1332     struct v4l2_cropcap cropcap;
1333     struct v4l2_crop crop;
1334     struct v4l2_format fmt;
1335     unsigned int i_min;
1336     enum v4l2_buf_type buf_type;
1337     es_format_t es_fmt;
1338
1339     msg_Dbg( p_obj, "opening device '%s'", path );
1340
1341     int i_fd = vlc_open( path, O_RDWR );
1342     if( i_fd == -1 )
1343     {
1344         msg_Err( p_obj, "cannot open device %s: %m", path );
1345         return -1;
1346     }
1347
1348 #ifdef HAVE_LIBV4L2
1349     /* Note the v4l2_xxx functions are designed so that if they get passed an
1350        unknown fd, the will behave exactly as their regular xxx counterparts,
1351        so if v4l2_fd_open fails, we continue as normal (missing the libv4l2
1352        custom cam format to normal formats conversion). Chances are big we will
1353        still fail then though, as normally v4l2_fd_open only fails if the
1354        device is not a v4l2 device. */
1355     if( p_sys->b_libv4l2 )
1356     {
1357         int libv4l2_fd;
1358         libv4l2_fd = v4l2_fd_open( i_fd, 0 );
1359         if( libv4l2_fd != -1 )
1360             i_fd = libv4l2_fd;
1361     }
1362 #endif
1363
1364     /* Get device capabilites */
1365     struct v4l2_capability cap;
1366     if( v4l2_ioctl( i_fd, VIDIOC_QUERYCAP, &cap ) < 0 )
1367     {
1368         msg_Err( p_obj, "cannot get video capabilities: %m" );
1369         return -1;
1370     }
1371
1372     msg_Dbg( p_obj, "device %s using driver %s (version %u.%u.%u) on %s",
1373             cap.card, cap.driver, (cap.version >> 16) & 0xFF,
1374             (cap.version >> 8) & 0xFF, cap.version & 0xFF, cap.bus_info );
1375     msg_Dbg( p_obj, "the device has the capabilities: 0x%08X",
1376              cap.capabilities );
1377     msg_Dbg( p_obj, " (%c) Video Capture, (%c) Audio, (%c) Tuner, (%c) Radio",
1378              ( cap.capabilities & V4L2_CAP_VIDEO_CAPTURE  ? 'X':' '),
1379              ( cap.capabilities & V4L2_CAP_AUDIO  ? 'X':' '),
1380              ( cap.capabilities & V4L2_CAP_TUNER  ? 'X':' '),
1381              ( cap.capabilities & V4L2_CAP_RADIO  ? 'X':' ') );
1382     msg_Dbg( p_obj, " (%c) Read/Write, (%c) Streaming, (%c) Asynchronous",
1383             ( cap.capabilities & V4L2_CAP_READWRITE ? 'X':' ' ),
1384             ( cap.capabilities & V4L2_CAP_STREAMING ? 'X':' ' ),
1385             ( cap.capabilities & V4L2_CAP_ASYNCIO ? 'X':' ' ) );
1386
1387     if( cap.capabilities & V4L2_CAP_STREAMING )
1388         p_sys->io = IO_METHOD_MMAP;
1389     else if( cap.capabilities & V4L2_CAP_READWRITE )
1390         p_sys->io = IO_METHOD_READ;
1391     else
1392     {
1393         msg_Err( p_obj, "no supported I/O method" );
1394         goto error;
1395     }
1396
1397     /* Now, enumerate all the video inputs. This is useless at the moment
1398        since we have no way to present that info to the user except with
1399        debug messages */
1400     if( cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
1401     {
1402         struct v4l2_input input;
1403         unsigned index = var_InheritInteger( p_obj, CFG_PREFIX"input" );
1404
1405         input.index = 0;
1406         while( v4l2_ioctl( i_fd, VIDIOC_ENUMINPUT, &input ) >= 0 )
1407         {
1408             msg_Dbg( p_obj, "video input %u (%s) has type: %s %c",
1409                      input.index, input.name,
1410                      input.type == V4L2_INPUT_TYPE_TUNER
1411                           ? "Tuner adapter" : "External analog input",
1412                      input.index == index ? '*' : ' ' );
1413             input.index++;
1414         }
1415
1416         /* Select input */
1417         if( v4l2_ioctl( i_fd, VIDIOC_S_INPUT, &index ) < 0 )
1418         {
1419             msg_Err( p_obj, "cannot set input %u: %m", index );
1420             goto error;
1421         }
1422         msg_Dbg( p_obj, "input set to %u", index );
1423     }
1424
1425     /* Select standard */
1426     bool bottom_first;
1427     const char *stdname = var_InheritString( p_obj, CFG_PREFIX"standard" );
1428     if( stdname != NULL )
1429     {
1430         v4l2_std_id std = strtoull( stdname, NULL, 0 );
1431         if( std == 0 )
1432         {
1433             const size_t n = sizeof(standards_vlc) / sizeof(*standards_vlc);
1434             assert( n == sizeof(standards_v4l2) / sizeof(*standards_v4l2) );
1435             assert( n == sizeof(standards_user) / sizeof(*standards_user) );
1436             for( size_t i = 0; i < n; i++ )
1437                 if( strcasecmp( stdname, standards_vlc[i] ) == 0 )
1438                 {
1439                     std = standards_v4l2[i];
1440                     break;
1441                 }
1442         }
1443
1444         if( v4l2_ioctl( i_fd, VIDIOC_S_STD, &std ) < 0
1445          || v4l2_ioctl( i_fd, VIDIOC_G_STD, &std ) < 0 )
1446         {
1447             msg_Err( p_obj, "cannot set standard 0x%"PRIx64": %m", std );
1448             goto error;
1449         }
1450         msg_Dbg( p_obj, "standard set to 0x%"PRIx64":", std );
1451         bottom_first = std == V4L2_STD_NTSC;
1452     }
1453     else
1454         bottom_first = false;
1455
1456     /* Set audio input */
1457     if( cap.capabilities & V4L2_CAP_AUDIO )
1458     {
1459         struct v4l2_audio audio = { .index = 0 };
1460         uint32_t idx = var_InheritInteger( p_obj, CFG_PREFIX"audio-input" );
1461
1462         /* Probe audio inputs */
1463         while( v4l2_ioctl( i_fd, VIDIOC_ENUMAUDIO, &audio ) >= 0 )
1464         {
1465             msg_Dbg( p_obj, "audio input %u (%s) is %s%s %c", audio.index,
1466                      audio.name,
1467                      audio.capability & V4L2_AUDCAP_STEREO ? "Stereo" : "Mono",
1468                      audio.capability & V4L2_AUDCAP_AVL
1469                          ? " (Automatic Volume Level supported)" : "",
1470                      audio.index == idx );
1471             audio.index++;
1472         }
1473
1474         if( idx != (uint32_t)-1 )
1475         {
1476             memset( &audio, 0, sizeof(audio) );
1477             audio.index = idx;
1478             /* TODO: AVL support (audio.mode) */
1479
1480             if( v4l2_ioctl( i_fd, VIDIOC_S_AUDIO, &audio ) < 0 )
1481             {
1482                 msg_Err( p_obj, "cannot set audio input %"PRIu32": %m", idx );
1483                 goto error;
1484             }
1485             msg_Dbg( p_obj, "audio input set to %"PRIu32, idx );
1486         }
1487     }
1488
1489     /* List tuner caps */
1490     if( cap.capabilities & V4L2_CAP_TUNER )
1491     {
1492         struct v4l2_tuner tuner;
1493         uint32_t idx = var_CreateGetInteger( p_obj, CFG_PREFIX"tuner" );
1494         enum v4l2_tuner_type type = V4L2_TUNER_RADIO;
1495
1496         tuner.index = 0;
1497         while( v4l2_ioctl( i_fd, VIDIOC_G_TUNER, &tuner ) >= 0 )
1498         {
1499             if( tuner.index == idx )
1500                 type = tuner.type;
1501
1502             const char *unit =
1503                 (tuner.capability & V4L2_TUNER_CAP_LOW) ? "Hz" : "kHz";
1504             msg_Dbg( p_obj, "tuner %u (%s) has type: %s, "
1505                      "frequency range: %.1f %s -> %.1f %s", tuner.index,
1506                      tuner.name,
1507                      tuner.type == V4L2_TUNER_RADIO ? "Radio" : "Analog TV",
1508                      tuner.rangelow * 62.5, unit,
1509                      tuner.rangehigh * 62.5, unit );
1510
1511             struct v4l2_frequency frequency = { .tuner = tuner.index };
1512             if( v4l2_ioctl( i_fd, VIDIOC_G_FREQUENCY, &frequency ) < 0 )
1513             {
1514                 msg_Err( p_obj, "cannot get tuner frequency: %m" );
1515                 return -1;
1516             }
1517             msg_Dbg( p_obj, "tuner %u (%s) frequency: %.1f %s", tuner.index,
1518                      tuner.name, frequency.frequency * 62.5, unit );
1519             tuner.index++;
1520         }
1521
1522         /* Tune the tuner */
1523         uint32_t freq = var_InheritInteger( p_obj,
1524                                             CFG_PREFIX"tuner-frequency" );
1525         if( freq != (uint32_t)-1 )
1526         {
1527             struct v4l2_frequency frequency = {
1528                 .tuner = idx,
1529                 .type = type,
1530                 .frequency = freq / 62.5,
1531             };
1532
1533             if( v4l2_ioctl( i_fd, VIDIOC_S_FREQUENCY, &frequency ) < 0 )
1534             {
1535                 msg_Err( p_obj, "cannot set tuner frequency: %m" );
1536                 goto error;
1537             }
1538             msg_Dbg( p_obj, "tuner frequency set" );
1539         }
1540
1541         /* Set the tuner audio mode */
1542         int32_t audmode = var_InheritInteger( p_obj,
1543                                               CFG_PREFIX"tuner-audio-mode" );
1544         if( audmode >= 0 )
1545         {
1546             struct v4l2_tuner tuner = {
1547                 .index = idx,
1548                 .audmode = audmode,
1549             };
1550
1551             if( v4l2_ioctl( i_fd, VIDIOC_S_TUNER, &tuner ) < 0 )
1552             {
1553                 msg_Err( p_obj, "cannot set tuner audio mode: %m" );
1554                 goto error;
1555             }
1556             msg_Dbg( p_obj, "tuner audio mode set" );
1557         }
1558     }
1559
1560     /* Probe for available chromas */
1561     if( cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
1562     {
1563         struct v4l2_fmtdesc codec;
1564
1565         unsigned i_index = 0;
1566         memset( &codec, 0, sizeof(codec) );
1567         codec.index = i_index;
1568         codec.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1569
1570         while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FMT, &codec ) >= 0 )
1571         {
1572             if( codec.index != i_index )
1573                 break;
1574             i_index++;
1575             codec.index = i_index;
1576         }
1577
1578         p_sys->i_codec = i_index;
1579
1580         free( p_sys->p_codecs );
1581         p_sys->p_codecs = calloc( 1, p_sys->i_codec * sizeof( struct v4l2_fmtdesc ) );
1582
1583         for( i_index = 0; i_index < p_sys->i_codec; i_index++ )
1584         {
1585             p_sys->p_codecs[i_index].index = i_index;
1586             p_sys->p_codecs[i_index].type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1587
1588             if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FMT, &p_sys->p_codecs[i_index] ) < 0 )
1589             {
1590                 msg_Err( p_obj, "cannot get codec description: %m" );
1591                 return -1;
1592             }
1593
1594             /* only print if vlc supports the format */
1595             char psz_fourcc_v4l2[5];
1596             memset( &psz_fourcc_v4l2, 0, sizeof( psz_fourcc_v4l2 ) );
1597             vlc_fourcc_to_char( p_sys->p_codecs[i_index].pixelformat,
1598                                 &psz_fourcc_v4l2 );
1599             bool b_codec_supported = false;
1600             for( int i = 0; v4l2chroma_to_fourcc[i].i_v4l2 != 0; i++ )
1601             {
1602                 if( v4l2chroma_to_fourcc[i].i_v4l2 == p_sys->p_codecs[i_index].pixelformat )
1603                 {
1604                     b_codec_supported = true;
1605
1606                     char psz_fourcc[5];
1607                     memset( &psz_fourcc, 0, sizeof( psz_fourcc ) );
1608                     vlc_fourcc_to_char( v4l2chroma_to_fourcc[i].i_fourcc,
1609                                         &psz_fourcc );
1610                     msg_Dbg( p_obj, "device supports chroma %4.4s [%s, %s]",
1611                                 psz_fourcc,
1612                                 p_sys->p_codecs[i_index].description,
1613                                 psz_fourcc_v4l2 );
1614
1615 #ifdef VIDIOC_ENUM_FRAMESIZES
1616                     /* This is new in Linux 2.6.19 */
1617                     /* List valid frame sizes for this format */
1618                     struct v4l2_frmsizeenum frmsize;
1619                     memset( &frmsize, 0, sizeof(frmsize) );
1620                     frmsize.pixel_format = p_sys->p_codecs[i_index].pixelformat;
1621                     if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize ) < 0 )
1622                     {
1623                         /* Not all devices support this ioctl */
1624                         msg_Warn( p_obj, "Unable to query for frame sizes" );
1625                     }
1626                     else
1627                     {
1628                         switch( frmsize.type )
1629                         {
1630                             case V4L2_FRMSIZE_TYPE_DISCRETE:
1631                                 do
1632                                 {
1633                                     msg_Dbg( p_obj,
1634                 "    device supports size %dx%d",
1635                 frmsize.discrete.width, frmsize.discrete.height );
1636                                     frmsize.index++;
1637                                 } while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize ) >= 0 );
1638                                 break;
1639                             case V4L2_FRMSIZE_TYPE_STEPWISE:
1640                                 msg_Dbg( p_obj,
1641                 "    device supports sizes %dx%d to %dx%d using %dx%d increments",
1642                 frmsize.stepwise.min_width, frmsize.stepwise.min_height,
1643                 frmsize.stepwise.max_width, frmsize.stepwise.max_height,
1644                 frmsize.stepwise.step_width, frmsize.stepwise.step_height );
1645                                 break;
1646                             case V4L2_FRMSIZE_TYPE_CONTINUOUS:
1647                                 msg_Dbg( p_obj,
1648                 "    device supports all sizes %dx%d to %dx%d",
1649                 frmsize.stepwise.min_width, frmsize.stepwise.min_height,
1650                 frmsize.stepwise.max_width, frmsize.stepwise.max_height );
1651                                 break;
1652                         }
1653                     }
1654 #endif
1655                 }
1656             }
1657             if( !b_codec_supported )
1658             {
1659                     msg_Dbg( p_obj,
1660                          "device codec %4.4s (%s) not supported",
1661                          psz_fourcc_v4l2,
1662                          p_sys->p_codecs[i_index].description );
1663             }
1664         }
1665     }
1666
1667     /* TODO: Move the resolution stuff up here */
1668     /* if MPEG encoder card, no need to do anything else after this */
1669     ControlList( p_obj, i_fd, b_demux );
1670
1671     /* Reset Cropping */
1672     memset( &cropcap, 0, sizeof(cropcap) );
1673     cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1674     if( v4l2_ioctl( i_fd, VIDIOC_CROPCAP, &cropcap ) >= 0 )
1675     {
1676         crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1677         crop.c = cropcap.defrect; /* reset to default */
1678         if( crop.c.width > 0 && crop.c.height > 0 ) /* Fix for fm tuners */
1679         {
1680             if( v4l2_ioctl( i_fd, VIDIOC_S_CROP, &crop ) < 0 )
1681             {
1682                 switch( errno )
1683                 {
1684                     case EINVAL:
1685                         /* Cropping not supported. */
1686                         break;
1687                     default:
1688                         /* Errors ignored. */
1689                         break;
1690                 }
1691             }
1692         }
1693     }
1694
1695     /* Try and find default resolution if not specified */
1696     int width = var_InheritInteger( p_obj, CFG_PREFIX"width" );
1697     int height = var_InheritInteger( p_obj, CFG_PREFIX"height" );
1698
1699     memset( &fmt, 0, sizeof(fmt) );
1700     fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1701
1702     if( width <= 0 || height <= 0 )
1703     {
1704         /* Use current width and height settings */
1705         if( v4l2_ioctl( i_fd, VIDIOC_G_FMT, &fmt ) < 0 )
1706         {
1707             msg_Err( p_obj, "cannot get default width and height: %m" );
1708             goto error;
1709         }
1710
1711         msg_Dbg( p_obj, "found default width and height of %ux%u",
1712                  fmt.fmt.pix.width, fmt.fmt.pix.height );
1713
1714         if( width < 0 || height < 0 )
1715         {
1716             msg_Dbg( p_obj, "will try to find optimal width and height" );
1717         }
1718     }
1719     else
1720     {
1721         /* Use user specified width and height */
1722         msg_Dbg( p_obj, "trying specified size %dx%d", width, height );
1723         fmt.fmt.pix.width = width;
1724         fmt.fmt.pix.height = height;
1725     }
1726
1727     fmt.fmt.pix.field = V4L2_FIELD_NONE;
1728
1729     float f_fps;
1730     if (b_demux)
1731     {
1732         demux_t *p_demux = (demux_t *) p_obj;
1733         char *reqchroma = var_InheritString( p_obj, CFG_PREFIX"chroma" );
1734
1735         /* Test and set Chroma */
1736         fmt.fmt.pix.pixelformat = 0;
1737         if( reqchroma != NULL )
1738         {
1739             /* User specified chroma */
1740             const vlc_fourcc_t i_requested_fourcc =
1741                 vlc_fourcc_GetCodecFromString( VIDEO_ES, reqchroma );
1742
1743             for( int i = 0; v4l2chroma_to_fourcc[i].i_v4l2 != 0; i++ )
1744             {
1745                 if( v4l2chroma_to_fourcc[i].i_fourcc == i_requested_fourcc )
1746                 {
1747                     fmt.fmt.pix.pixelformat = v4l2chroma_to_fourcc[i].i_v4l2;
1748                     break;
1749                 }
1750             }
1751             /* Try and set user chroma */
1752             bool b_error = !IsPixelFormatSupported( p_demux, fmt.fmt.pix.pixelformat );
1753             if( !b_error && fmt.fmt.pix.pixelformat )
1754             {
1755                 if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 )
1756                 {
1757                     fmt.fmt.pix.field = V4L2_FIELD_ANY;
1758                     if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 )
1759                     {
1760                         fmt.fmt.pix.field = V4L2_FIELD_NONE;
1761                         b_error = true;
1762                     }
1763                 }
1764             }
1765             if( b_error )
1766             {
1767                 msg_Warn( p_obj, "requested chroma %s not supported. "
1768                           " Trying default.", reqchroma );
1769                 fmt.fmt.pix.pixelformat = 0;
1770             }
1771             free( reqchroma );
1772         }
1773
1774         /* If no user specified chroma, find best */
1775         /* This also decides if MPEG encoder card or not */
1776         if( !fmt.fmt.pix.pixelformat )
1777         {
1778             unsigned int i;
1779             for( i = 0; i < ARRAY_SIZE( p_chroma_fallbacks ); i++ )
1780             {
1781                 fmt.fmt.pix.pixelformat = p_chroma_fallbacks[i];
1782                 if( IsPixelFormatSupported( p_demux, fmt.fmt.pix.pixelformat ) )
1783                 {
1784                     if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) >= 0 )
1785                         break;
1786                     fmt.fmt.pix.field = V4L2_FIELD_ANY;
1787                     if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) >= 0 )
1788                         break;
1789                     fmt.fmt.pix.field = V4L2_FIELD_NONE;
1790                 }
1791             }
1792             if( i == ARRAY_SIZE( p_chroma_fallbacks ) )
1793             {
1794                 msg_Warn( p_demux, "Could not select any of the default chromas; attempting to open as MPEG encoder card (access)" );
1795                 goto error;
1796             }
1797         }
1798
1799         if( width < 0 || height < 0 )
1800         {
1801             f_fps = var_InheritFloat( p_obj, CFG_PREFIX"fps" );
1802             if( f_fps <= 0. )
1803             {
1804                 f_fps = GetAbsoluteMaxFrameRate( p_demux, i_fd,
1805                                                  fmt.fmt.pix.pixelformat );
1806                 msg_Dbg( p_demux, "Found maximum framerate of %f", f_fps );
1807             }
1808             uint32_t i_width, i_height;
1809             GetMaxDimensions( p_demux, i_fd,
1810                               fmt.fmt.pix.pixelformat, f_fps,
1811                               &i_width, &i_height );
1812             if( i_width || i_height )
1813             {
1814                 msg_Dbg( p_demux, "Found optimal dimensions for framerate %f "
1815                                   "of %ux%u", f_fps, i_width, i_height );
1816                 fmt.fmt.pix.width = i_width;
1817                 fmt.fmt.pix.height = i_height;
1818                 if( v4l2_ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 )
1819                 {
1820                     msg_Err( p_obj, "Cannot set size to optimal dimensions "
1821                                     "%ux%u", i_width, i_height );
1822                     goto error;
1823                 }
1824             }
1825             else
1826             {
1827                 msg_Warn( p_obj, "Could not find optimal width and height, "
1828                                  "falling back to driver default." );
1829             }
1830         }
1831     }
1832
1833     width = fmt.fmt.pix.width;
1834     height = fmt.fmt.pix.height;
1835
1836     if( v4l2_ioctl( i_fd, VIDIOC_G_FMT, &fmt ) < 0 ) {;}
1837     /* Print extra info */
1838     msg_Dbg( p_obj, "Driver requires at most %d bytes to store a complete image", fmt.fmt.pix.sizeimage );
1839     /* Check interlacing */
1840     switch( fmt.fmt.pix.field )
1841     {
1842         case V4L2_FIELD_NONE:
1843             msg_Dbg( p_obj, "Interlacing setting: progressive" );
1844             break;
1845         case V4L2_FIELD_TOP:
1846             msg_Dbg( p_obj, "Interlacing setting: top field only" );
1847             break;
1848         case V4L2_FIELD_BOTTOM:
1849             msg_Dbg( p_obj, "Interlacing setting: bottom field only" );
1850             break;
1851         case V4L2_FIELD_INTERLACED:
1852             msg_Dbg( p_obj, "Interlacing setting: interleaved (bottom top if M/NTSC, top bottom otherwise)" );
1853             if( bottom_first )
1854                 p_sys->i_block_flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
1855             else
1856                 p_sys->i_block_flags = BLOCK_FLAG_TOP_FIELD_FIRST;
1857             break;
1858         case V4L2_FIELD_SEQ_TB:
1859             msg_Dbg( p_obj, "Interlacing setting: sequential top bottom (TODO)" );
1860             break;
1861         case V4L2_FIELD_SEQ_BT:
1862             msg_Dbg( p_obj, "Interlacing setting: sequential bottom top (TODO)" );
1863             break;
1864         case V4L2_FIELD_ALTERNATE:
1865             msg_Dbg( p_obj, "Interlacing setting: alternate fields (TODO)" );
1866             height *= 2;
1867             break;
1868         case V4L2_FIELD_INTERLACED_TB:
1869             msg_Dbg( p_obj, "Interlacing setting: interleaved top bottom" );
1870             p_sys->i_block_flags = BLOCK_FLAG_TOP_FIELD_FIRST;
1871             break;
1872         case V4L2_FIELD_INTERLACED_BT:
1873             msg_Dbg( p_obj, "Interlacing setting: interleaved bottom top" );
1874             p_sys->i_block_flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
1875             break;
1876         default:
1877             msg_Warn( p_obj, "Interlacing setting: unknown type (%d)",
1878                       fmt.fmt.pix.field );
1879             break;
1880     }
1881
1882     /* Look up final fourcc */
1883     p_sys->i_fourcc = 0;
1884     for( int i = 0; v4l2chroma_to_fourcc[i].i_fourcc != 0; i++ )
1885     {
1886         if( v4l2chroma_to_fourcc[i].i_v4l2 == fmt.fmt.pix.pixelformat )
1887         {
1888             p_sys->i_fourcc = v4l2chroma_to_fourcc[i].i_fourcc;
1889             es_format_Init( &es_fmt, VIDEO_ES, p_sys->i_fourcc );
1890             es_fmt.video.i_rmask = v4l2chroma_to_fourcc[i].i_rmask;
1891             es_fmt.video.i_gmask = v4l2chroma_to_fourcc[i].i_gmask;
1892             es_fmt.video.i_bmask = v4l2chroma_to_fourcc[i].i_bmask;
1893             break;
1894         }
1895     }
1896
1897     /* Buggy driver paranoia */
1898     i_min = fmt.fmt.pix.width * 2;
1899     if( fmt.fmt.pix.bytesperline < i_min )
1900         fmt.fmt.pix.bytesperline = i_min;
1901     i_min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
1902     if( fmt.fmt.pix.sizeimage < i_min )
1903         fmt.fmt.pix.sizeimage = i_min;
1904
1905 #ifdef VIDIOC_ENUM_FRAMEINTERVALS
1906     /* This is new in Linux 2.6.19 */
1907     /* List supported frame rates */
1908     struct v4l2_frmivalenum frmival;
1909     memset( &frmival, 0, sizeof(frmival) );
1910     frmival.pixel_format = fmt.fmt.pix.pixelformat;
1911     frmival.width = width;
1912     frmival.height = height;
1913     if( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival ) >= 0 )
1914     {
1915         char psz_fourcc[5];
1916         memset( &psz_fourcc, 0, sizeof( psz_fourcc ) );
1917         vlc_fourcc_to_char( p_sys->i_fourcc, &psz_fourcc );
1918         msg_Dbg( p_obj, "supported frame intervals for %4.4s, %dx%d:",
1919                  psz_fourcc, frmival.width, frmival.height );
1920         switch( frmival.type )
1921         {
1922             case V4L2_FRMIVAL_TYPE_DISCRETE:
1923                 do
1924                 {
1925                     msg_Dbg( p_obj, "    supported frame interval: %d/%d",
1926                              frmival.discrete.numerator,
1927                              frmival.discrete.denominator );
1928                     frmival.index++;
1929                 } while( v4l2_ioctl( i_fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival ) >= 0 );
1930                 break;
1931             case V4L2_FRMIVAL_TYPE_STEPWISE:
1932                 msg_Dbg( p_obj, "    supported frame intervals: %d/%d to "
1933                          "%d/%d using %d/%d increments",
1934                          frmival.stepwise.min.numerator,
1935                          frmival.stepwise.min.denominator,
1936                          frmival.stepwise.max.numerator,
1937                          frmival.stepwise.max.denominator,
1938                          frmival.stepwise.step.numerator,
1939                          frmival.stepwise.step.denominator );
1940                 break;
1941             case V4L2_FRMIVAL_TYPE_CONTINUOUS:
1942                 msg_Dbg( p_obj, "    supported frame intervals: %d/%d to %d/%d",
1943                          frmival.stepwise.min.numerator,
1944                          frmival.stepwise.min.denominator,
1945                          frmival.stepwise.max.numerator,
1946                          frmival.stepwise.max.denominator );
1947                 break;
1948         }
1949     }
1950 #endif
1951
1952
1953     /* Init IO method */
1954     switch( p_sys->io )
1955     {
1956     case IO_METHOD_READ:
1957         if( b_demux && InitRead( p_obj, p_sys, fmt.fmt.pix.sizeimage ) )
1958             goto error;
1959         break;
1960
1961     case IO_METHOD_MMAP:
1962         if( InitMmap( p_obj, p_sys, i_fd ) )
1963             goto error;
1964         break;
1965
1966     case IO_METHOD_USERPTR:
1967         if( InitUserP( p_obj, p_sys, i_fd, fmt.fmt.pix.sizeimage ) )
1968             goto error;
1969         break;
1970     }
1971
1972     if( b_demux )
1973     {
1974         int ar = 4 * VOUT_ASPECT_FACTOR / 3;
1975         char *str = var_InheritString( p_obj, CFG_PREFIX"aspect-ratio" );
1976         if( likely(str != NULL) )
1977         {
1978             const char *delim = strchr( str, ':' );
1979             if( delim )
1980                 ar = atoi( str ) * VOUT_ASPECT_FACTOR / atoi( delim + 1 );
1981             free( str );
1982         }
1983
1984         /* Add */
1985         es_fmt.video.i_width  = width;
1986         es_fmt.video.i_height = height;
1987
1988         /* Get aspect-ratio */
1989         es_fmt.video.i_sar_num = ar * es_fmt.video.i_height;
1990         es_fmt.video.i_sar_den = VOUT_ASPECT_FACTOR * es_fmt.video.i_width;
1991
1992         /* Framerate */
1993         es_fmt.video.i_frame_rate = lround(f_fps * 1000000.);
1994         es_fmt.video.i_frame_rate_base = 1000000;
1995
1996         demux_t *p_demux = (demux_t *) p_obj;
1997         msg_Dbg( p_demux, "added new video es %4.4s %dx%d",
1998             (char*)&es_fmt.i_codec, es_fmt.video.i_width, es_fmt.video.i_height );
1999         msg_Dbg( p_obj, " frame rate: %f", f_fps );
2000
2001         p_sys->p_es = es_out_Add( p_demux->out, &es_fmt );
2002     }
2003
2004     /* Start Capture */
2005
2006     switch( p_sys->io )
2007     {
2008     case IO_METHOD_READ:
2009         /* Nothing to do */
2010         break;
2011
2012     case IO_METHOD_MMAP:
2013         for (unsigned int i = 0; i < p_sys->i_nbuffers; ++i)
2014         {
2015             struct v4l2_buffer buf;
2016
2017             memset( &buf, 0, sizeof(buf) );
2018             buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2019             buf.memory = V4L2_MEMORY_MMAP;
2020             buf.index = i;
2021
2022             if( v4l2_ioctl( i_fd, VIDIOC_QBUF, &buf ) < 0 )
2023             {
2024                 msg_Err( p_obj, "VIDIOC_QBUF failed" );
2025                 goto error;
2026             }
2027         }
2028
2029         buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2030         if( v4l2_ioctl( i_fd, VIDIOC_STREAMON, &buf_type ) < 0 )
2031         {
2032             msg_Err( p_obj, "VIDIOC_STREAMON failed" );
2033             goto error;
2034         }
2035
2036         break;
2037
2038     case IO_METHOD_USERPTR:
2039         for( unsigned int i = 0; i < p_sys->i_nbuffers; ++i )
2040         {
2041             struct v4l2_buffer buf;
2042
2043             memset( &buf, 0, sizeof(buf) );
2044             buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2045             buf.memory = V4L2_MEMORY_USERPTR;
2046             buf.index = i;
2047             buf.m.userptr = (unsigned long)p_sys->p_buffers[i].start;
2048             buf.length = p_sys->p_buffers[i].length;
2049
2050             if( v4l2_ioctl( i_fd, VIDIOC_QBUF, &buf ) < 0 )
2051             {
2052                 msg_Err( p_obj, "VIDIOC_QBUF failed" );
2053                 goto error;
2054             }
2055         }
2056
2057         buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2058         if( v4l2_ioctl( i_fd, VIDIOC_STREAMON, &buf_type ) < 0 )
2059         {
2060             msg_Err( p_obj, "VIDIOC_STREAMON failed" );
2061             goto error;
2062         }
2063         break;
2064     }
2065
2066     return i_fd;
2067
2068 error:
2069     v4l2_close( i_fd );
2070     return -1;
2071 }