666bd9074691d8e90790a40c3582b51c8fdab25c
[vlc.git] / modules / access / v4l2.c
1 /*****************************************************************************
2  * v4l2.c : Video4Linux2 input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2002-2007 the VideoLAN team
5  * $Id$
6  *
7  * Author: Benjamin Pracht <bigben at videolan dot org>
8  *         Richard Hosking <richard at hovis dot net>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*
26  * Sections based on the reference V4L2 capture example at
27  * http://v4l2spec.bytesex.org/spec/capture-example.html
28  */
29
30 /*
31  * TODO: No mjpeg support yet.
32  * TODO: mmap untested.
33  * TODO: Tuner partial implementation.
34  * TODO: Alsa input support?
35  */
36
37 /*****************************************************************************
38  * Preamble
39  *****************************************************************************/
40
41 #include <vlc/vlc.h>
42 #include <vlc_access.h>
43 #include <vlc_demux.h>
44 #include <vlc_input.h>
45 #include <vlc_vout.h>
46
47 #include <fcntl.h>
48 #include <unistd.h>
49 #include <sys/ioctl.h>
50 #include <sys/mman.h>
51
52 #include <linux/videodev2.h>
53
54 #include <sys/soundcard.h>
55
56 /*****************************************************************************
57  * Module descriptior
58  *****************************************************************************/
59
60 static int  Open ( vlc_object_t * );
61 static void Close( vlc_object_t * );
62
63 #define DEV_TEXT N_("Device name")
64 #define DEV_LONGTEXT N_( \
65     "Name of the device to use. " \
66     "If you don't specify anything, /dev/video0 will be used.")
67 #define ADEV_TEXT N_("Audio device name")
68 #define ADEV_LONGTEXT N_( \
69     "Name of the audio device to use. " \
70     "If you don't specify anything, no audio device will be used.")
71 #define STANDARD_TEXT N_( "Standard" )
72 #define STANDARD_LONGTEXT N_( \
73     "Video standard (Default, SECAM, PAL, or NTSC)." )
74 #define CHROMA_TEXT N_("Video input chroma format")
75 #define CHROMA_LONGTEXT N_( \
76     "Force the Video4Linux2 video device to use a specific chroma format " \
77     "(eg. I420, RV24, etc.)")
78 #define INPUT_TEXT N_( "Input" )
79 #define INPUT_LONGTEXT N_( \
80     "Input of the card to use (Usually, 0 = tuner, " \
81     "1 = composite, 2 = svideo)." )
82 #define IOMETHOD_TEXT N_( "IO Method" )
83 #define IOMETHOD_LONGTEXT N_( \
84     "IO Method (READ, MMAP, USERPTR)." )
85 #define FPS_TEXT N_( "Framerate" )
86 #define FPS_LONGTEXT N_( "Framerate to capture, if applicable " \
87     "(-1 for autodetect)." )
88 #define STEREO_TEXT N_( "Stereo" )
89 #define STEREO_LONGTEXT N_( \
90     "Capture the audio stream in stereo." )
91 #define SAMPLERATE_TEXT N_( "Samplerate" )
92 #define SAMPLERATE_LONGTEXT N_( \
93     "Samplerate of the captured audio stream, in Hz (eg: 11025, 22050, 44100, 48000)" )
94 #define CACHING_TEXT N_("Caching value in ms")
95 #define CACHING_LONGTEXT N_( \
96     "Caching value for V4L2 captures. This " \
97     "value should be set in milliseconds." )
98
99 typedef enum {
100     IO_METHOD_READ,
101     IO_METHOD_MMAP,
102     IO_METHOD_USERPTR,
103 } io_method;
104
105 static int i_standards_list[] =
106     { V4L2_STD_UNKNOWN, V4L2_STD_SECAM, V4L2_STD_PAL, V4L2_STD_NTSC };
107 static const char *psz_standards_list_text[] =
108     { N_("Default"), N_("SECAM"), N_("PAL"),  N_("NTSC") };
109
110 static int i_iomethod_list[] =
111     { IO_METHOD_READ, IO_METHOD_MMAP, IO_METHOD_USERPTR };
112 static const char *psz_iomethod_list_text[] =
113     { N_("READ"), N_("MMAP"),  N_("USERPTR") };
114
115 vlc_module_begin();
116     set_shortname( _("Video4Linux2") );
117     set_description( _("Video4Linux2 input") );
118     set_category( CAT_INPUT );
119     set_subcategory( SUBCAT_INPUT_ACCESS );
120
121     add_string( "v4l2-dev", "/dev/video0", 0, DEV_TEXT, DEV_LONGTEXT,
122                 VLC_FALSE );
123     add_string( "v4l2-adev", "/dev/dsp", 0, DEV_TEXT, DEV_LONGTEXT,
124                 VLC_FALSE );
125     add_integer( "v4l2-standard", 0, NULL, STANDARD_TEXT, STANDARD_LONGTEXT,
126                 VLC_FALSE );
127         change_integer_list( i_standards_list, psz_standards_list_text, 0 );
128     add_string( "v4l2-chroma", NULL, NULL, CHROMA_TEXT, CHROMA_LONGTEXT,
129                 VLC_TRUE );
130     add_integer( "v4l2-input", 0, NULL, INPUT_TEXT, INPUT_LONGTEXT,
131                 VLC_TRUE );
132     add_integer( "v4l2-io", IO_METHOD_MMAP, NULL, IOMETHOD_TEXT,
133                  IOMETHOD_LONGTEXT, VLC_FALSE );
134         change_integer_list( i_iomethod_list, psz_iomethod_list_text, 0 );
135     add_float( "v4l2-fps", 0, NULL, FPS_TEXT, FPS_LONGTEXT, VLC_TRUE );
136     add_bool( "v4l2-stereo", VLC_TRUE, NULL, STEREO_TEXT, STEREO_LONGTEXT,
137                 VLC_TRUE );
138     add_integer( "v4l2-samplerate", 48000, NULL, SAMPLERATE_TEXT,
139                 SAMPLERATE_LONGTEXT, VLC_TRUE );
140     add_integer( "v4l2-caching", DEFAULT_PTS_DELAY / 1000, NULL,
141                 CACHING_TEXT, CACHING_LONGTEXT, VLC_TRUE );
142
143     add_shortcut( "v4l2" );
144     set_capability( "access_demux", 10 );
145     set_callbacks( Open, Close );
146 vlc_module_end();
147
148 /*****************************************************************************
149  * Access: local prototypes
150  *****************************************************************************/
151
152 static void ParseMRL( demux_t * );
153
154 static int Control( demux_t *, int, va_list );
155
156 static int Demux( demux_t * );
157 static block_t* GrabVideo( demux_t *p_demux );
158 static block_t* ProcessVideoFrame( demux_t *p_demux, uint8_t *p_frame );
159 static block_t* GrabAudio( demux_t *p_demux );
160
161 vlc_bool_t IsChromaSupported( demux_t *p_demux, unsigned int i_v4l2 );
162 unsigned int GetChromaFromFourcc( char *psz_fourcc );
163
164 static int OpenVideoDev( demux_t *, char *psz_device );
165 static int OpenAudioDev( demux_t *, char *psz_device );
166 static vlc_bool_t ProbeVideoDev( demux_t *, char *psz_device );
167 static vlc_bool_t ProbeAudioDev( demux_t *, char *psz_device );
168
169 static struct
170 {
171     unsigned int i_v4l2;
172     int i_fourcc;
173 } v4l2chroma_to_fourcc[] =
174 {
175     { V4L2_PIX_FMT_GREY, VLC_FOURCC( 'G', 'R', 'E', 'Y' ) },
176     { V4L2_PIX_FMT_HI240, VLC_FOURCC( 'I', '2', '4', '0' ) },
177     { V4L2_PIX_FMT_RGB565, VLC_FOURCC( 'R', 'V', '1', '6' ) },
178     { V4L2_PIX_FMT_RGB555, VLC_FOURCC( 'R', 'V', '1', '5' ) },
179     { V4L2_PIX_FMT_BGR24, VLC_FOURCC( 'R', 'V', '2', '4' ) },
180     { V4L2_PIX_FMT_BGR32, VLC_FOURCC( 'R', 'V', '3', '2' ) },
181     { V4L2_PIX_FMT_YUYV, VLC_FOURCC( 'Y', 'U', 'Y', '2' ) },
182     { V4L2_PIX_FMT_YUYV, VLC_FOURCC( 'Y', 'U', 'Y', 'V' ) },
183     { V4L2_PIX_FMT_UYVY, VLC_FOURCC( 'U', 'Y', 'V', 'Y' ) },
184     { V4L2_PIX_FMT_Y41P, VLC_FOURCC( 'I', '4', '1', 'N' ) },
185     { V4L2_PIX_FMT_YUV422P, VLC_FOURCC( 'I', '4', '2', '2' ) },
186     { V4L2_PIX_FMT_YVU420, VLC_FOURCC( 'I', '4', '2', '0' ) },
187     { V4L2_PIX_FMT_YUV411P, VLC_FOURCC( 'I', '4', '1', '1' ) },
188     { V4L2_PIX_FMT_YUV410, VLC_FOURCC( 'I', '4', '1', '0' ) },
189     { 0, 0 }
190 };
191
192 struct buffer_t
193 {
194     void *  start;
195     size_t  length;
196 };
197
198 struct demux_sys_t
199 {
200     char *psz_device;  /* Main device from MRL, can be video or audio */
201
202     char *psz_vdev;
203     int  i_fd_video;
204
205     char *psz_adev;
206     int  i_fd_audio;
207
208     /* Video */
209     io_method io;
210
211     int i_pts;
212
213     struct v4l2_capability dev_cap;
214
215     int i_input;
216     struct v4l2_input *p_inputs;
217     int i_selected_input;
218
219     int i_standard;
220     struct v4l2_standard *p_standards;
221     v4l2_std_id i_selected_standard_id;
222
223     int i_audio;
224     /* V4L2 devices cannot have more than 32 audio inputs */
225     struct v4l2_audio p_audios[32];
226
227     int i_tuner;
228     struct v4l2_tuner *p_tuners;
229
230     int i_codec;
231     struct v4l2_fmtdesc *p_codecs;
232
233     struct buffer_t *p_buffers;
234     unsigned int i_nbuffers;
235
236     int i_width;
237     int i_height;
238     float f_fps;            /* <= 0.0 mean to grab at full rate */
239     mtime_t i_video_pts;    /* only used when f_fps > 0 */
240     int i_fourcc;
241
242     picture_t pic;
243     int i_video_frame_size;
244
245     es_out_id_t *p_es_video;
246
247     /* Audio */
248     int i_sample_rate;
249     vlc_bool_t b_stereo;
250     int i_audio_max_frame_size;
251     block_t *p_block_audio;
252     es_out_id_t *p_es_audio;
253 };
254
255 /*****************************************************************************
256  * Open: opens v4l2 device
257  *****************************************************************************
258  *
259  * url: <video device>::::
260  *
261  *****************************************************************************/
262 static int Open( vlc_object_t *p_this )
263 {
264     demux_t     *p_demux = (demux_t*)p_this;
265     demux_sys_t *p_sys;
266     vlc_value_t val;
267     char *psz;
268
269     /* Only when selected */
270     if( *p_demux->psz_access == '\0' ) return VLC_EGENERIC;
271
272     /* Set up p_demux */
273     p_demux->pf_control = Control;
274     p_demux->pf_demux = Demux;
275     p_demux->info.i_update = 0;
276     p_demux->info.i_title = 0;
277     p_demux->info.i_seekpoint = 0;
278
279     p_demux->p_sys = p_sys = calloc( 1, sizeof( demux_sys_t ) );
280     if( p_sys == NULL ) return VLC_ENOMEM;
281
282     p_sys->i_video_pts = -1;
283
284     var_Create( p_demux, "v4l2-standard", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
285     var_Get( p_demux, "v4l2-standard", &val );
286     p_sys->i_selected_standard_id = i_standards_list[val.i_int];
287
288     p_sys->i_selected_input = var_CreateGetInteger( p_demux, "v4l2-input" );
289
290     p_sys->io = var_CreateGetInteger( p_demux, "v4l2-io" );
291
292     var_Create( p_demux, "v4l2-fps", VLC_VAR_FLOAT | VLC_VAR_DOINHERIT );
293     var_Get( p_demux, "v4l2-fps", &val );
294     p_sys->f_fps = val.f_float;
295
296     var_Create( p_demux, "v4l2-samplerate", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
297     var_Get( p_demux, "v4l2-samplerate", &val );
298     p_sys->i_sample_rate = val.i_int;
299
300     psz = var_CreateGetString( p_demux, "v4l2-chroma" );
301     p_sys->i_fourcc = GetChromaFromFourcc( psz );
302     free( psz );
303
304     var_Create( p_demux, "v4l2-stereo", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
305     var_Get( p_demux, "v4l2-stereo", &val );
306     p_sys->b_stereo = val.b_bool;
307
308     p_sys->i_pts = var_CreateGetInteger( p_demux, "v4l2-caching" );
309
310     p_sys->psz_device = p_sys->psz_vdev = p_sys->psz_adev = NULL;
311     p_sys->i_fd_video = -1;
312     p_sys->i_fd_audio = -1;
313
314     p_sys->p_es_video = p_sys->p_es_audio = 0;
315     p_sys->p_block_audio = 0;
316
317     ParseMRL( p_demux );
318
319     /* Find main device (video or audio) */
320     if( p_sys->psz_device && *p_sys->psz_device )
321     {
322         msg_Dbg( p_demux, "main device='%s'", p_sys->psz_device );
323
324         /* Try to open as video device */
325         msg_Dbg( p_demux, "trying device '%s' as video", p_sys->psz_device );
326         if( ProbeVideoDev( p_demux, p_sys->psz_device ) )
327         {
328             msg_Dbg( p_demux, "'%s' is a video device", p_sys->psz_device );
329             /* Device was a video device */
330             if( p_sys->psz_vdev ) free( p_sys->psz_vdev );
331             p_sys->psz_vdev = p_sys->psz_device;
332             p_sys->psz_device = NULL;
333             p_sys->i_fd_video = OpenVideoDev( p_demux, p_sys->psz_vdev );
334             if( p_sys->i_fd_video < 0 )
335             {
336                 Close( p_this );
337                 return VLC_EGENERIC;
338             }
339         }
340         else
341         {
342             /* Try to open as audio device */
343             msg_Dbg( p_demux, "trying device '%s' as audio", p_sys->psz_device );
344             if( ProbeAudioDev( p_demux, p_sys->psz_device ) )
345             {
346                 msg_Dbg( p_demux, "'%s' is an audio device", p_sys->psz_device );
347                 /* Device was an audio device */
348                 if( p_sys->psz_adev ) free( p_sys->psz_adev );
349                 p_sys->psz_adev = p_sys->psz_device;
350                 p_sys->psz_device = NULL;
351                 p_sys->i_fd_audio = OpenAudioDev( p_demux, p_sys->psz_adev );
352                 if( p_sys->i_fd_audio < 0 )
353                 {
354                     Close( p_this );
355                     return VLC_EGENERIC;
356                 }
357             }
358         }
359     }
360
361     /* If no device opened, only continue if the access was forced */
362     if( p_sys->i_fd_video < 0 && p_sys->i_fd_audio < 0 )
363     {
364         if( strcmp( p_demux->psz_access, "v4l2" ) )
365         {
366             Close( p_this );
367             return VLC_EGENERIC;
368         }
369     }
370
371     /* Find video device */
372     if( p_sys->i_fd_video < 0 )
373     {
374         if( !p_sys->psz_vdev || !*p_sys->psz_vdev )
375         {
376             if( p_sys->psz_vdev ) free( p_sys->psz_vdev );
377             p_sys->psz_vdev = var_CreateGetString( p_demux, "v4l2-dev" );;
378         }
379
380         if( p_sys->psz_vdev && *p_sys->psz_vdev && ProbeVideoDev( p_demux, p_sys->psz_vdev ) )
381         {
382             p_sys->i_fd_video = OpenVideoDev( p_demux, p_sys->psz_vdev );
383         }
384     }
385
386     /* Find audio device */
387     if( p_sys->i_fd_audio < 0 )
388     {
389         if( !p_sys->psz_adev || !*p_sys->psz_adev )
390         {
391             if( p_sys->psz_adev ) free( p_sys->psz_adev );
392             p_sys->psz_adev = var_CreateGetString( p_demux, "v4l2-adev" );;
393         }
394
395         if( p_sys->psz_adev && *p_sys->psz_adev && ProbeAudioDev( p_demux, p_sys->psz_adev ) )
396         {
397             p_sys->i_fd_audio = OpenAudioDev( p_demux, p_sys->psz_adev );
398         }
399     }
400
401     if( p_sys->i_fd_video < 0 && p_sys->i_fd_audio < 0 )
402     {
403         Close( p_this );
404         return VLC_EGENERIC;
405     }
406
407     return VLC_SUCCESS;
408 }
409
410 /*****************************************************************************
411  * ParseMRL: parse the options contained in the MRL
412  *****************************************************************************/
413 static void ParseMRL( demux_t *p_demux )
414 {
415     demux_sys_t *p_sys = p_demux->p_sys;
416
417     char *psz_dup = strdup( p_demux->psz_path );
418     char *psz_parser = psz_dup;
419
420     while( *psz_parser && *psz_parser != ':' )
421     {
422         psz_parser++;
423     }
424
425     if( *psz_parser == ':' )
426     {
427         /* read options */
428         for( ;; )
429         {
430             *psz_parser++ = '\0';
431
432             if( !strncmp( psz_parser, "adev=", strlen( "adev=" ) ) )
433             {
434                 int  i_len;
435
436                 psz_parser += strlen( "adev=" );
437                 if( strchr( psz_parser, ':' ) )
438                 {
439                     i_len = strchr( psz_parser, ':' ) - psz_parser;
440                 }
441                 else
442                 {
443                     i_len = strlen( psz_parser );
444                 }
445
446                 p_sys->psz_adev = strndup( psz_parser, i_len );
447
448                 psz_parser += i_len;
449             }
450             else if( !strncmp( psz_parser, "standard=", strlen( "standard=" ) ) )
451             {
452                 psz_parser += strlen( "standard=" );
453                 if( !strncmp( psz_parser, "pal", strlen( "pal" ) ) )
454                 {
455                     p_sys->i_selected_standard_id = V4L2_STD_PAL;
456                     psz_parser += strlen( "pal" );
457                 }
458                 else if( !strncmp( psz_parser, "ntsc", strlen( "ntsc" ) ) )
459                 {
460                     p_sys->i_selected_standard_id = V4L2_STD_NTSC;
461                     psz_parser += strlen( "ntsc" );
462                 }
463                 else if( !strncmp( psz_parser, "secam", strlen( "secam" ) ) )
464                 {
465                     p_sys->i_selected_standard_id = V4L2_STD_SECAM;
466                     psz_parser += strlen( "secam" );
467                 }
468                 else if( !strncmp( psz_parser, "default", strlen( "default" ) ) )
469                 {
470                     p_sys->i_selected_standard_id = V4L2_STD_UNKNOWN;
471                     psz_parser += strlen( "default" );
472                 }
473                 else
474                 {
475                     p_sys->i_selected_standard_id = i_standards_list[strtol( psz_parser, &psz_parser, 0 )];
476                 }
477             }
478             else if( !strncmp( psz_parser, "chroma=", strlen( "chroma=" ) ) )
479             {
480                 int  i_len;
481
482                 psz_parser += strlen( "chroma=" );
483                 if( strchr( psz_parser, ':' ) )
484                 {
485                     i_len = strchr( psz_parser, ':' ) - psz_parser;
486                 }
487                 else
488                 {
489                     i_len = strlen( psz_parser );
490                 }
491
492                 char* chroma = strndup( psz_parser, i_len );
493                 p_sys->i_fourcc = GetChromaFromFourcc( chroma );
494                 free( chroma );
495
496                 psz_parser += i_len;
497             }
498             else if( !strncmp( psz_parser, "input=", strlen( "input=" ) ) )
499             {
500                 p_sys->i_selected_input = strtol( psz_parser + strlen( "input=" ),
501                                        &psz_parser, 0 );
502             }
503             else if( !strncmp( psz_parser, "fps=", strlen( "fps=" ) ) )
504             {
505                 p_sys->f_fps = strtof( psz_parser + strlen( "fps=" ),
506                                        &psz_parser );
507             }
508             else if( !strncmp( psz_parser, "io=", strlen( "io=" ) ) )
509             {
510                 psz_parser += strlen( "io=" );
511                 if( !strncmp( psz_parser, "read", strlen( "read" ) ) )
512                 {
513                     p_sys->io = IO_METHOD_READ;
514                     psz_parser += strlen( "read" );
515                 }
516                 else if( !strncmp( psz_parser, "mmap", strlen( "mmap" ) ) )
517                 {
518                     p_sys->io = IO_METHOD_MMAP;
519                     psz_parser += strlen( "mmap" );
520                 }
521                 else if( !strncmp( psz_parser, "userptr", strlen( "userptr" ) ) )
522                 {
523                     p_sys->io = IO_METHOD_USERPTR;
524                     psz_parser += strlen( "userptr" );
525                 }
526                 else
527                 {
528                     p_sys->io = strtol( psz_parser, &psz_parser, 0 );
529                 }
530             }
531             else if( !strncmp( psz_parser, "samplerate=",
532                                strlen( "samplerate=" ) ) )
533             {
534                 p_sys->i_sample_rate =
535                     strtol( psz_parser + strlen( "samplerate=" ),
536                             &psz_parser, 0 );
537             }
538             else if( !strncmp( psz_parser, "stereo", strlen( "stereo" ) ) )
539             {
540                 psz_parser += strlen( "stereo" );
541                 p_sys->b_stereo = VLC_TRUE;
542             }
543             else if( !strncmp( psz_parser, "mono", strlen( "mono" ) ) )
544             {
545                 psz_parser += strlen( "mono" );
546                 p_sys->b_stereo = VLC_FALSE;
547             }
548             else if( !strncmp( psz_parser, "caching=", strlen( "caching=" ) ) )
549             {
550                 p_sys->i_pts = strtol( psz_parser + strlen( "caching=" ),
551                                        &psz_parser, DEFAULT_PTS_DELAY / 1000 );
552             }
553             else
554             {
555                 msg_Warn( p_demux, "unknown option" );
556             }
557
558             while( *psz_parser && *psz_parser != ':' )
559             {
560                 psz_parser++;
561             }
562
563             if( *psz_parser == '\0' )
564             {
565                 break;
566             }
567         }
568     }
569
570     /* Main device */
571     if( *psz_dup )
572     {
573         p_sys->psz_device = strdup( psz_dup );
574     }
575     if( psz_dup ) free( psz_dup );
576 }
577
578 /*****************************************************************************
579  * Close: close device, free resources
580  *****************************************************************************/
581 static void Close( vlc_object_t *p_this )
582 {
583     demux_t     *p_demux = (demux_t *)p_this;
584     demux_sys_t *p_sys   = p_demux->p_sys;
585     struct v4l2_buffer buf;
586     enum v4l2_buf_type buf_type;
587     unsigned int i;
588
589     /* Stop video capture */
590     if( p_sys->i_fd_video >= 0 )
591     {
592         switch( p_sys->io )
593         {
594         case IO_METHOD_READ:
595             /* Nothing to do */
596             break;
597
598         case IO_METHOD_MMAP:
599         case IO_METHOD_USERPTR:
600             /* Some drivers 'hang' internally if this is not done before streamoff */
601             for( unsigned int i = 0; i < p_sys->i_nbuffers; i++ )
602             {
603                 memset( &buf, 0, sizeof(buf) );
604                 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
605                 buf.memory = V4L2_MEMORY_USERPTR;
606                 ioctl( p_sys->i_fd_video, VIDIOC_DQBUF, &buf ); /* ignore result */
607             }
608
609             buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
610             if( ioctl( p_sys->i_fd_video, VIDIOC_STREAMOFF, &buf_type ) < 0 ) {
611                 msg_Err( p_demux, "VIDIOC_STREAMOFF failed" );
612             }
613
614             break;
615         }
616     }
617
618     /* Close */
619     if( p_sys->i_fd_video >= 0 ) close( p_sys->i_fd_video );
620     if( p_sys->i_fd_audio >= 0 ) close( p_sys->i_fd_audio );
621
622     /* Free Video Buffers */
623     if( p_sys->p_buffers ) {
624         switch( p_sys->io )
625         {
626         case IO_METHOD_READ:
627             free( p_sys->p_buffers[0].start );
628             break;
629
630         case IO_METHOD_MMAP:
631             for( i = 0; i < p_sys->i_nbuffers; ++i )
632             {
633                 if( munmap( p_sys->p_buffers[i].start, p_sys->p_buffers[i].length ) )
634                 {
635                     msg_Err( p_demux, "munmap failed" );
636                 }
637             }
638             break;
639
640         case IO_METHOD_USERPTR:
641             for( i = 0; i < p_sys->i_nbuffers; ++i )
642             {
643                free( p_sys->p_buffers[i].start );
644             }
645             break;
646         }
647         free( p_sys->p_buffers );
648     }
649
650     if( p_sys->p_block_audio ) block_Release( p_sys->p_block_audio );
651     if( p_sys->psz_device ) free( p_sys->psz_device );
652     if( p_sys->psz_vdev ) free( p_sys->psz_vdev );
653     if( p_sys->psz_adev ) free( p_sys->psz_adev );
654     if( p_sys->p_standards ) free( p_sys->p_standards );
655     if( p_sys->p_inputs ) free( p_sys->p_inputs );
656     if( p_sys->p_tuners ) free( p_sys->p_tuners );
657     if( p_sys->p_codecs ) free( p_sys->p_codecs );
658
659     free( p_sys );
660 }
661
662 /*****************************************************************************
663  * Control:
664  *****************************************************************************/
665 static int Control( demux_t *p_demux, int i_query, va_list args )
666 {
667     demux_sys_t *p_sys = p_demux->p_sys;
668     vlc_bool_t *pb;
669     int64_t    *pi64;
670
671     switch( i_query )
672     {
673         /* Special for access_demux */
674         case DEMUX_CAN_PAUSE:
675         case DEMUX_SET_PAUSE_STATE:
676         case DEMUX_CAN_CONTROL_PACE:
677             pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
678             *pb = VLC_FALSE;
679             return VLC_SUCCESS;
680
681         case DEMUX_GET_PTS_DELAY:
682             pi64 = (int64_t*)va_arg( args, int64_t * );
683             *pi64 = (int64_t)p_sys->i_pts * 1000;
684             return VLC_SUCCESS;
685
686         case DEMUX_GET_TIME:
687             pi64 = (int64_t*)va_arg( args, int64_t * );
688             *pi64 = mdate();
689             return VLC_SUCCESS;
690
691         /* TODO implement others */
692         default:
693             return VLC_EGENERIC;
694     }
695
696     return VLC_EGENERIC;
697 }
698
699 /*****************************************************************************
700  * Demux: Processes the audio or video frame
701  *****************************************************************************/
702 static int Demux( demux_t *p_demux )
703 {
704     demux_sys_t *p_sys = p_demux->p_sys;
705     es_out_id_t *p_es = p_sys->p_es_audio;
706     block_t *p_block = NULL;
707
708     /* Try grabbing audio frames first */
709     if( p_sys->i_fd_audio < 0 || !( p_block = GrabAudio( p_demux ) ) )
710     {
711         /* Try grabbing video frame */
712         p_es = p_sys->p_es_video;
713         if( p_sys->i_fd_video > 0 ) p_block = GrabVideo( p_demux );
714     }
715
716     if( !p_block )
717     {
718         /* Sleep so we do not consume all the cpu, 10ms seems
719          * like a good value (100fps) */
720         msleep( 10 );
721         return 1;
722     }
723
724     es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_block->i_pts );
725     es_out_Send( p_demux->out, p_es, p_block );
726
727     return 1;
728 }
729
730 /*****************************************************************************
731  * GrabVideo: Grab a video frame
732  *****************************************************************************/
733 static block_t* GrabVideo( demux_t *p_demux )
734 {
735     demux_sys_t *p_sys = p_demux->p_sys;
736
737     block_t *p_block = NULL;
738     struct v4l2_buffer buf;
739
740     if( p_sys->f_fps >= 0.1 && p_sys->i_video_pts > 0 )
741     {
742         mtime_t i_dur = (mtime_t)((double)1000000 / (double)p_sys->f_fps);
743
744         /* Did we wait long enough ? (frame rate reduction) */
745         if( p_sys->i_video_pts + i_dur > mdate() ) return 0;
746     }
747
748     /* Grab Video Frame */
749     switch( p_sys->io )
750     {
751     case IO_METHOD_READ:
752         if( read( p_sys->i_fd_video, p_sys->p_buffers[0].start, p_sys->p_buffers[0].length ) )
753         {
754             switch( errno )
755             {
756             case EAGAIN:
757                 return 0;
758             case EIO:
759                 /* Could ignore EIO, see spec. */
760                 /* fall through */
761             default:
762                 msg_Err( p_demux, "Failed to read frame" );
763                 return 0;
764                }
765         }
766
767         p_block = ProcessVideoFrame( p_demux, (uint8_t*)p_sys->p_buffers[0].start );
768         if( !p_block ) return 0;
769
770         break;
771
772     case IO_METHOD_MMAP:
773         memset( &buf, 0, sizeof(buf) );
774         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
775         buf.memory = V4L2_MEMORY_MMAP;
776
777         /* Wait for next frame */
778         if (ioctl( p_sys->i_fd_video, VIDIOC_DQBUF, &buf ) < 0 )
779         {
780             switch( errno )
781             {
782             case EAGAIN:
783                 return 0;
784             case EIO:
785                 /* Could ignore EIO, see spec. */
786                 /* fall through */
787             default:
788                 msg_Err( p_demux, "Failed to wait (VIDIOC_DQBUF)" );
789                 return 0;
790                }
791         }
792
793         if( buf.index >= p_sys->i_nbuffers ) {
794             msg_Err( p_demux, "Failed capturing new frame as i>=nbuffers" );
795             return 0;
796         }
797
798         p_block = ProcessVideoFrame( p_demux, p_sys->p_buffers[buf.index].start );
799         if( !p_block ) return 0;
800
801         /* Unlock */
802         if( ioctl( p_sys->i_fd_video, VIDIOC_QBUF, &buf ) < 0 )
803         {
804             msg_Err (p_demux, "Failed to unlock (VIDIOC_QBUF)");
805             return 0;
806         }
807
808         break;
809
810     case IO_METHOD_USERPTR:
811         memset( &buf, 0, sizeof(buf) );
812         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
813         buf.memory = V4L2_MEMORY_USERPTR;
814
815         /* Wait for next frame */
816         if (ioctl( p_sys->i_fd_video, VIDIOC_DQBUF, &buf ) < 0 )
817         {
818             switch( errno )
819             {
820             case EAGAIN:
821                 return 0;
822             case EIO:
823                 /* Could ignore EIO, see spec. */
824                 /* fall through */
825             default:
826                 msg_Err( p_demux, "Failed to wait (VIDIOC_DQBUF)" );
827                 return 0;
828                }
829         }
830
831         /* Find frame? */
832         unsigned int i;
833         for( i = 0; i < p_sys->i_nbuffers; i++ )
834         {
835             if( buf.m.userptr == (unsigned long)p_sys->p_buffers[i].start &&
836                 buf.length == p_sys->p_buffers[i].length ) break;
837         }
838
839         if( i >= p_sys->i_nbuffers ) {
840             msg_Err( p_demux, "Failed capturing new frame as i>=nbuffers" );
841             return 0;
842         }
843
844         p_block = ProcessVideoFrame( p_demux, (uint8_t*)buf.m.userptr );
845         if( !p_block ) return 0;
846
847         /* Unlock */
848         if( ioctl( p_sys->i_fd_video, VIDIOC_QBUF, &buf ) < 0 )
849         {
850             msg_Err (p_demux, "Failed to unlock (VIDIOC_QBUF)");
851             return 0;
852         }
853
854         break;
855
856     }
857
858     /* Timestamp */
859     p_sys->i_video_pts = p_block->i_pts = p_block->i_dts = mdate();
860
861     return p_block;
862 }
863
864 /*****************************************************************************
865  * ProcessVideoFrame: Helper function to take a buffer and copy it into
866  * a new block
867  *****************************************************************************/
868 static block_t* ProcessVideoFrame( demux_t *p_demux, uint8_t *p_frame )
869 {
870     demux_sys_t *p_sys = p_demux->p_sys;
871     block_t *p_block;
872
873     if( !p_frame ) return 0;
874             
875     /* New block */
876     if( !( p_block = block_New( p_demux, p_sys->i_video_frame_size ) ) )
877     {
878         msg_Warn( p_demux, "Cannot get new block" );
879         return 0;
880     }
881
882     /* Copy frame */
883     memcpy( p_block->p_buffer, p_frame, p_sys->i_video_frame_size );
884
885     return p_block;
886 }
887
888 /*****************************************************************************
889  * GrabAudio: Grab an audio frame
890  *****************************************************************************/
891 static block_t* GrabAudio( demux_t *p_demux )
892 {
893     demux_sys_t *p_sys = p_demux->p_sys;
894     struct audio_buf_info buf_info;
895     int i_read, i_correct;
896     block_t *p_block;
897
898     /* Copied from v4l.c */
899
900     if( p_sys->p_block_audio ) p_block = p_sys->p_block_audio;
901     else p_block = block_New( p_demux, p_sys->i_audio_max_frame_size );
902
903     if( !p_block )
904     {
905         msg_Warn( p_demux, "cannot get block" );
906         return 0;
907     }
908
909     p_sys->p_block_audio = p_block;
910
911     i_read = read( p_sys->i_fd_audio, p_block->p_buffer,
912                    p_sys->i_audio_max_frame_size );
913
914     if( i_read <= 0 ) return 0;
915
916     p_block->i_buffer = i_read;
917     p_sys->p_block_audio = 0;
918
919     /* Correct the date because of kernel buffering */
920     i_correct = i_read;
921     if( ioctl( p_sys->i_fd_audio, SNDCTL_DSP_GETISPACE, &buf_info ) == 0 )
922     {
923         i_correct += buf_info.bytes;
924     }
925
926     /* Timestamp */
927     p_block->i_pts = p_block->i_dts =
928         mdate() - I64C(1000000) * (mtime_t)i_correct /
929         2 / ( p_sys->b_stereo ? 2 : 1) / p_sys->i_sample_rate;
930
931     return p_block;
932 }
933
934 /*****************************************************************************
935  * Helper function to initalise video IO using the Read method
936  *****************************************************************************/
937 static int InitRead( demux_t *p_demux, int i_fd, unsigned int i_buffer_size )
938 {
939     demux_sys_t *p_sys = p_demux->p_sys;
940
941     p_sys->p_buffers = calloc( 1, sizeof( *p_sys->p_buffers ) );
942     if( !p_sys->p_buffers )
943     {
944         msg_Err( p_demux, "Out of memory" );
945         goto open_failed;
946     }
947
948     p_sys->p_buffers[0].length = i_buffer_size;
949     p_sys->p_buffers[0].start = malloc( i_buffer_size );
950     if( !p_sys->p_buffers[0].start )
951     {
952         msg_Err( p_demux, "Out of memory" );
953         goto open_failed;
954     }
955
956     return VLC_SUCCESS;
957
958 open_failed:
959     return VLC_EGENERIC;
960
961 }
962
963 /*****************************************************************************
964  * Helper function to initalise video IO using the mmap method
965  *****************************************************************************/
966 static int InitMmap( demux_t *p_demux, int i_fd )
967 {
968     demux_sys_t *p_sys = p_demux->p_sys;
969     struct v4l2_requestbuffers req;
970
971     memset( &req, 0, sizeof(req) );
972     req.count = 4;
973     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
974     req.memory = V4L2_MEMORY_MMAP;
975
976     if( ioctl( i_fd, VIDIOC_REQBUFS, &req ) < 0 )
977     {
978         msg_Err( p_demux, "device does not support mmap i/o" );
979         goto open_failed;
980     }
981
982     if( req.count < 2 )
983     {
984         msg_Err( p_demux, "Insufficient buffer memory" );
985         goto open_failed;
986     }
987
988     p_sys->p_buffers = calloc( req.count, sizeof( *p_sys->p_buffers ) );
989     if( !p_sys->p_buffers )
990     {
991         msg_Err( p_demux, "Out of memory" );
992         goto open_failed;
993     }
994
995     for( p_sys->i_nbuffers = 0; p_sys->i_nbuffers < req.count; ++p_sys->i_nbuffers )
996     {
997         struct v4l2_buffer buf;
998     
999         memset( &buf, 0, sizeof(buf) );
1000         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1001         buf.memory = V4L2_MEMORY_MMAP;
1002         buf.index = p_sys->i_nbuffers;
1003
1004         if( ioctl( i_fd, VIDIOC_QUERYBUF, &buf ) < 0 )
1005         {
1006             msg_Err( p_demux, "VIDIOC_QUERYBUF" );
1007             goto open_failed;
1008         }
1009
1010         p_sys->p_buffers[p_sys->i_nbuffers].length = buf.length;
1011         p_sys->p_buffers[p_sys->i_nbuffers].start =
1012             mmap( NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, p_sys->i_fd_video, buf.m.offset );
1013
1014         if( p_sys->p_buffers[p_sys->i_nbuffers].start == MAP_FAILED )
1015         {
1016             msg_Err( p_demux, "mmap failed" );
1017             goto open_failed;
1018         }
1019     }
1020
1021     return VLC_SUCCESS;
1022
1023 open_failed:
1024     return VLC_EGENERIC;
1025
1026 }
1027
1028 /*****************************************************************************
1029  * Helper function to initalise video IO using the userbuf method
1030  *****************************************************************************/
1031 static int InitUserP( demux_t *p_demux, int i_fd, unsigned int i_buffer_size )
1032 {
1033     demux_sys_t *p_sys = p_demux->p_sys;
1034     struct v4l2_requestbuffers req;
1035
1036     memset( &req, 0, sizeof(req) );
1037     req.count = 4;
1038     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1039     req.memory = V4L2_MEMORY_USERPTR;
1040
1041     if( ioctl( i_fd, VIDIOC_REQBUFS, &req ) < 0 )
1042     {
1043         msg_Err( p_demux, "device does not support user pointer i/o" );
1044         goto open_failed;
1045     }
1046
1047     p_sys->p_buffers = calloc( 4, sizeof( *p_sys->p_buffers ) );
1048     if( !p_sys->p_buffers )
1049     {
1050         msg_Err( p_demux, "Out of memory" );
1051         goto open_failed;
1052     }
1053
1054     for( p_sys->i_nbuffers = 0; p_sys->i_nbuffers < 4; ++p_sys->i_nbuffers )
1055     {
1056         p_sys->p_buffers[p_sys->i_nbuffers].length = i_buffer_size;
1057         p_sys->p_buffers[p_sys->i_nbuffers].start = malloc( i_buffer_size );
1058
1059         if( !p_sys->p_buffers[p_sys->i_nbuffers].start )
1060         {
1061             msg_Err( p_demux, "out of memory" );
1062             goto open_failed;
1063         }
1064     }
1065
1066     return VLC_SUCCESS;
1067
1068 open_failed:
1069     return VLC_EGENERIC;
1070
1071 }
1072
1073 /*****************************************************************************
1074  * GetChromaFromFourcc: Returns the fourcc code from the given string
1075  *****************************************************************************/
1076 unsigned int GetChromaFromFourcc( char *psz_fourcc )
1077 {
1078     if( strlen( psz_fourcc ) >= 4 )
1079     {
1080         int i_chroma = VLC_FOURCC( psz_fourcc[0], psz_fourcc[1], psz_fourcc[2], psz_fourcc[3] );
1081
1082         /* Find out v4l2 chroma code */
1083         for( int i = 0; v4l2chroma_to_fourcc[i].i_fourcc != 0; i++ )
1084         {
1085             if( v4l2chroma_to_fourcc[i].i_fourcc == i_chroma )
1086             {
1087                 return v4l2chroma_to_fourcc[i].i_fourcc;
1088             }
1089         }
1090     }
1091
1092     return 0;
1093 }
1094
1095 /*****************************************************************************
1096  * IsChromaSupported: returns true if the specified V4L2 chroma constant is
1097  * in the array of supported chromas returned by the driver
1098  *****************************************************************************/
1099 vlc_bool_t IsChromaSupported( demux_t *p_demux, unsigned int i_chroma )
1100 {
1101     demux_sys_t *p_sys = p_demux->p_sys;
1102
1103     for( int i_index = 0; i_index < p_sys->i_codec; i_index++ )
1104     {
1105         if( p_sys->p_codecs[i_index].pixelformat == i_chroma ) return VLC_TRUE;
1106     }
1107
1108     return VLC_FALSE;
1109 }
1110
1111 /*****************************************************************************
1112  * OpenVideoDev: open and set up the video device and probe for capabilities
1113  *****************************************************************************/
1114 int OpenVideoDev( demux_t *p_demux, char *psz_device )
1115 {
1116     int i_fd;
1117     demux_sys_t *p_sys = p_demux->p_sys;
1118     struct v4l2_cropcap cropcap;
1119     struct v4l2_crop crop;
1120     struct v4l2_format fmt;
1121     unsigned int i_min;
1122     enum v4l2_buf_type buf_type;
1123
1124     if( ( i_fd = open( psz_device, O_RDWR ) ) < 0 )
1125     {
1126         msg_Err( p_demux, "cannot open device (%m)" );
1127         goto open_failed;
1128     }
1129
1130     /* Select standard */
1131
1132     if( p_sys->i_selected_standard_id != V4L2_STD_UNKNOWN )
1133     {
1134         if( ioctl( i_fd, VIDIOC_S_STD, &p_sys->i_selected_standard_id ) < 0 )
1135         {
1136            msg_Err( p_demux, "cannot set input (%m)" );
1137            goto open_failed;
1138         }
1139         msg_Dbg( p_demux, "Set standard" );
1140     }
1141
1142     /* Select input */
1143
1144     if( p_sys->i_selected_input > p_sys->i_input )
1145     {
1146         msg_Warn( p_demux, "invalid input. Using the default one" );
1147         p_sys->i_selected_input = 0;
1148     }
1149
1150     if( ioctl( i_fd, VIDIOC_S_INPUT, &p_sys->i_selected_input ) < 0 )
1151     {
1152        msg_Err( p_demux, "cannot set input (%m)" );
1153        goto open_failed;
1154     }
1155
1156     /* Verify device support for the various IO methods */
1157     switch( p_sys->io )
1158     {
1159     case IO_METHOD_READ:
1160         if( !(p_sys->dev_cap.capabilities & V4L2_CAP_READWRITE) )
1161         {
1162             msg_Err( p_demux, "device does not support read i/o" );
1163             goto open_failed;
1164         }
1165         break;
1166
1167     case IO_METHOD_MMAP:
1168     case IO_METHOD_USERPTR:
1169         if( !(p_sys->dev_cap.capabilities & V4L2_CAP_STREAMING) )
1170         {
1171             msg_Err( p_demux, "device does not support streaming i/o" );
1172             goto open_failed;
1173         }
1174         break;
1175
1176     default:
1177         msg_Err( p_demux, "io method not supported" );
1178         goto open_failed;
1179     }
1180
1181     /* Reset Cropping */
1182     memset( &cropcap, 0, sizeof(cropcap) );
1183     cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1184     if( ioctl( i_fd, VIDIOC_CROPCAP, &cropcap ) >= 0 )
1185     {
1186         crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1187         crop.c = cropcap.defrect; /* reset to default */
1188         if( ioctl( i_fd, VIDIOC_S_CROP, &crop ) < 0 )
1189         {
1190             switch( errno )
1191             {
1192             case EINVAL:
1193                 /* Cropping not supported. */
1194                 break;
1195             default:
1196                 /* Errors ignored. */
1197                 break;
1198             }
1199         }
1200     }
1201
1202     /* Try and find default resolution if not specified */
1203     if( !p_sys->i_width && !p_sys->i_height ) {
1204         memset( &fmt, 0, sizeof(fmt) );
1205         fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1206
1207         if ( ioctl( i_fd, VIDIOC_G_FMT, &fmt ) < 0 )
1208         {
1209             msg_Err( p_demux, "Cannot get default width and height." );
1210             goto open_failed;
1211         }
1212
1213         p_sys->i_width = fmt.fmt.pix.width;
1214         p_sys->i_height = fmt.fmt.pix.height;
1215
1216         if( fmt.fmt.pix.field == V4L2_FIELD_ALTERNATE )
1217         {
1218             p_sys->i_height = p_sys->i_height * 2;
1219         }
1220     }
1221
1222     fmt.fmt.pix.width = p_sys->i_width;
1223     fmt.fmt.pix.height = p_sys->i_height;
1224     fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
1225
1226     /* Test and set Chroma */
1227     fmt.fmt.pix.pixelformat = 0;
1228     if( p_sys->i_fourcc )
1229     {
1230         /* User specified chroma */
1231         for( int i = 0; v4l2chroma_to_fourcc[i].i_v4l2 != 0; i++ )
1232         {
1233             if( v4l2chroma_to_fourcc[i].i_fourcc == p_sys->i_fourcc )
1234             {
1235                 fmt.fmt.pix.pixelformat = v4l2chroma_to_fourcc[i].i_v4l2;
1236                 break;
1237             }
1238         }
1239         /* Try and set user chroma */
1240         if( !IsChromaSupported( p_demux, fmt.fmt.pix.pixelformat ) || ( fmt.fmt.pix.pixelformat && ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 ) )
1241         {
1242             msg_Warn( p_demux, "Driver is unable to use specified chroma.  Using defaults." );
1243             fmt.fmt.pix.pixelformat = 0;
1244         }
1245     }
1246
1247     /* If no user specified chroma, find best */
1248     if( !fmt.fmt.pix.pixelformat )
1249     {
1250         fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YVU420;
1251         if( !IsChromaSupported( p_demux, fmt.fmt.pix.pixelformat ) || ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 )
1252         {
1253             fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUV422P;
1254             if( !IsChromaSupported( p_demux, fmt.fmt.pix.pixelformat ) || ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 )
1255             {
1256                 fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
1257                 if( !IsChromaSupported( p_demux, fmt.fmt.pix.pixelformat ) || ioctl( i_fd, VIDIOC_S_FMT, &fmt ) < 0 )
1258                 {
1259                     msg_Err( p_demux, "Could not select any of the default chromas!" );
1260                     goto open_failed;
1261                 }
1262             }
1263         }
1264     }
1265
1266     /* Reassign width, height and chroma incase driver override */
1267     p_sys->i_width = fmt.fmt.pix.width;
1268     p_sys->i_height = fmt.fmt.pix.height;
1269
1270     /* Look up final fourcc */
1271     p_sys->i_fourcc = 0;
1272     for( int i = 0; v4l2chroma_to_fourcc[i].i_fourcc != 0; i++ )
1273     {
1274         if( v4l2chroma_to_fourcc[i].i_v4l2 == fmt.fmt.pix.pixelformat )
1275         {
1276             p_sys->i_fourcc = v4l2chroma_to_fourcc[i].i_fourcc;
1277             break;
1278         }
1279     }
1280
1281     /* Buggy driver paranoia */
1282     i_min = fmt.fmt.pix.width * 2;
1283     if( fmt.fmt.pix.bytesperline < i_min )
1284         fmt.fmt.pix.bytesperline = i_min;
1285     i_min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
1286     if( fmt.fmt.pix.sizeimage < i_min )
1287         fmt.fmt.pix.sizeimage = i_min;
1288
1289     /* Init vout Picture */
1290     vout_InitPicture( VLC_OBJECT(p_demux), &p_sys->pic, p_sys->i_fourcc,
1291         p_sys->i_width, p_sys->i_height, p_sys->i_width *
1292         VOUT_ASPECT_FACTOR / p_sys->i_height );
1293     if( !p_sys->pic.i_planes )
1294     {
1295         msg_Err( p_demux, "unsupported chroma" );
1296         goto open_failed;
1297     }
1298     p_sys->i_video_frame_size = 0;
1299     for( int i = 0; i < p_sys->pic.i_planes; i++ )
1300     {
1301          p_sys->i_video_frame_size += p_sys->pic.p[i].i_visible_lines * p_sys->pic.p[i].i_visible_pitch;
1302     }
1303
1304     /* Init IO method */
1305     switch( p_sys->io )
1306     {
1307     case IO_METHOD_READ:
1308         if( InitRead( p_demux, i_fd, fmt.fmt.pix.sizeimage ) != VLC_SUCCESS ) goto open_failed;
1309         break;
1310
1311     case IO_METHOD_MMAP:
1312         if( InitMmap( p_demux, i_fd ) != VLC_SUCCESS ) goto open_failed;
1313         break;
1314
1315     case IO_METHOD_USERPTR:
1316         if( InitUserP( p_demux, i_fd, fmt.fmt.pix.sizeimage ) != VLC_SUCCESS ) goto open_failed;
1317         break;
1318
1319     }
1320
1321     /* Add */
1322     es_format_t es_fmt;
1323     es_format_Init( &es_fmt, VIDEO_ES, p_sys->i_fourcc );
1324     es_fmt.video.i_width  = p_sys->i_width;
1325     es_fmt.video.i_height = p_sys->i_height;
1326     es_fmt.video.i_aspect = 4 * VOUT_ASPECT_FACTOR / 3;
1327
1328     /* Setup rgb mask for RGB formats */
1329     if( p_sys->i_fourcc == VLC_FOURCC( 'R','V','2','4' ) )
1330     {
1331         /* This is in BGR format */
1332         es_fmt.video.i_bmask = 0x00ff0000;
1333         es_fmt.video.i_gmask = 0x0000ff00;
1334         es_fmt.video.i_rmask = 0x000000ff;
1335     }
1336
1337     msg_Dbg( p_demux, "added new video es %4.4s %dx%d",
1338         (char*)&es_fmt.i_codec, es_fmt.video.i_width, es_fmt.video.i_height );
1339     p_sys->p_es_video = es_out_Add( p_demux->out, &es_fmt );
1340
1341     /* Start Capture */
1342
1343     switch( p_sys->io )
1344     {
1345     case IO_METHOD_READ:
1346         /* Nothing to do */
1347         break;
1348
1349     case IO_METHOD_MMAP:
1350         for (unsigned int i = 0; i < p_sys->i_nbuffers; ++i)
1351         {
1352             struct v4l2_buffer buf;
1353
1354             memset( &buf, 0, sizeof(buf) );
1355             buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1356             buf.memory = V4L2_MEMORY_MMAP;
1357             buf.index = i;
1358
1359             if( ioctl( i_fd, VIDIOC_QBUF, &buf ) < 0 ) {
1360                 msg_Err( p_demux, "VIDIOC_QBUF failed" );
1361                 goto open_failed;
1362             }
1363         }
1364
1365         buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1366         if( ioctl( i_fd, VIDIOC_STREAMON, &buf_type ) < 0 ) {
1367             msg_Err( p_demux, "VIDIOC_STREAMON failed" );
1368             goto open_failed;
1369         }
1370
1371         break;
1372
1373     case IO_METHOD_USERPTR:
1374         for( unsigned int i = 0; i < p_sys->i_nbuffers; ++i )
1375         {
1376             struct v4l2_buffer buf;
1377
1378             memset( &buf, 0, sizeof(buf) );
1379             buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1380             buf.memory = V4L2_MEMORY_USERPTR;
1381             buf.index = i;
1382             buf.m.userptr = (unsigned long)p_sys->p_buffers[i].start;
1383             buf.length = p_sys->p_buffers[i].length;
1384
1385             if( ioctl( i_fd, VIDIOC_QBUF, &buf ) < 0 ) {
1386                 msg_Err( p_demux, "VIDIOC_QBUF failed" );
1387                 goto open_failed;
1388             }
1389         }
1390
1391         buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1392         if( ioctl( i_fd, VIDIOC_STREAMON, &buf_type ) < 0 ) {
1393             msg_Err( p_demux, "VIDIOC_STREAMON failed" );
1394             goto open_failed;
1395         }
1396
1397         break;
1398     }
1399
1400     /* report fps */
1401     if( p_sys->f_fps >= 0.1 )
1402     {
1403         msg_Dbg( p_demux, "User set fps=%f", p_sys->f_fps );
1404     }
1405
1406     return i_fd;
1407
1408 open_failed:
1409     if( i_fd ) close( i_fd );
1410     return -1;
1411
1412 }
1413
1414 /*****************************************************************************
1415  * OpenAudioDev: open and set up the audio device and probe for capabilities
1416  *****************************************************************************/
1417 int OpenAudioDev( demux_t *p_demux, char *psz_device )
1418 {
1419     demux_sys_t *p_sys = p_demux->p_sys;
1420     int i_fd, i_format;
1421
1422     if( (i_fd = open( psz_device, O_RDONLY | O_NONBLOCK )) < 0 )
1423     {
1424         msg_Err( p_demux, "cannot open audio device (%m)" );
1425         goto adev_fail;
1426     }
1427
1428     i_format = AFMT_S16_LE;
1429     if( ioctl( i_fd, SNDCTL_DSP_SETFMT, &i_format ) < 0
1430         || i_format != AFMT_S16_LE )
1431     {
1432         msg_Err( p_demux, "cannot set audio format (16b little endian) "
1433                  "(%m)" );
1434         goto adev_fail;
1435     }
1436
1437     if( ioctl( i_fd, SNDCTL_DSP_STEREO,
1438                &p_sys->b_stereo ) < 0 )
1439     {
1440         msg_Err( p_demux, "cannot set audio channels count (%m)" );
1441         goto adev_fail;
1442     }
1443
1444     if( ioctl( i_fd, SNDCTL_DSP_SPEED,
1445                &p_sys->i_sample_rate ) < 0 )
1446     {
1447         msg_Err( p_demux, "cannot set audio sample rate (%m)" );
1448         goto adev_fail;
1449     }
1450
1451     msg_Dbg( p_demux, "opened adev=`%s' %s %dHz",
1452              psz_device, p_sys->b_stereo ? "stereo" : "mono",
1453              p_sys->i_sample_rate );
1454
1455     p_sys->i_audio_max_frame_size = 6 * 1024;
1456
1457     es_format_t fmt;
1458     es_format_Init( &fmt, AUDIO_ES, VLC_FOURCC('a','r','a','w') );
1459
1460     fmt.audio.i_channels = p_sys->b_stereo ? 2 : 1;
1461     fmt.audio.i_rate = p_sys->i_sample_rate;
1462     fmt.audio.i_bitspersample = 16; /* FIXME ? */
1463     fmt.audio.i_blockalign = fmt.audio.i_channels * fmt.audio.i_bitspersample / 8;
1464     fmt.i_bitrate = fmt.audio.i_channels * fmt.audio.i_rate * fmt.audio.i_bitspersample;
1465
1466     msg_Dbg( p_demux, "new audio es %d channels %dHz",
1467       fmt.audio.i_channels, fmt.audio.i_rate );
1468
1469     p_sys->p_es_audio = es_out_Add( p_demux->out, &fmt );
1470
1471     return i_fd;
1472
1473  adev_fail:
1474
1475     if( i_fd >= 0 ) close( i_fd );
1476     return -1;
1477
1478 }
1479
1480 /*****************************************************************************
1481  * ProbeVideoDev: probe video for capabilities
1482  *****************************************************************************/
1483 vlc_bool_t ProbeVideoDev( demux_t *p_demux, char *psz_device )
1484 {
1485     int i_index;
1486     int i_standard;
1487
1488     int i_fd;
1489     demux_sys_t *p_sys = p_demux->p_sys;
1490
1491 /*    msg_Dbg( p_demux, "main device='%s'", p_sys->psz_device ); */
1492
1493     if( ( i_fd = open( psz_device, O_RDWR ) ) < 0 )
1494     {
1495         msg_Err( p_demux, "cannot open video device (%m)" );
1496         goto open_failed;
1497     }
1498
1499     /* Get device capabilites */
1500
1501     if( ioctl( i_fd, VIDIOC_QUERYCAP, &p_sys->dev_cap ) < 0 )
1502     {
1503         msg_Err( p_demux, "cannot get video capabilities (%m)" );
1504         goto open_failed;
1505     }
1506
1507     msg_Dbg( p_demux, "V4L2 device: %s using driver: %s (version: %u.%u.%u) on %s",
1508                             p_sys->dev_cap.card,
1509                             p_sys->dev_cap.driver,
1510                             (p_sys->dev_cap.version >> 16) & 0xFF,
1511                             (p_sys->dev_cap.version >> 8) & 0xFF,
1512                             p_sys->dev_cap.version & 0xFF,
1513                             p_sys->dev_cap.bus_info );
1514
1515     msg_Dbg( p_demux, "the device has the capabilities: (%c) Video Capure, "
1516                                                        "(%c) Audio, "
1517                                                        "(%c) Tuner",
1518              ( p_sys->dev_cap.capabilities & V4L2_CAP_VIDEO_CAPTURE  ? 'X':' '),
1519              ( p_sys->dev_cap.capabilities & V4L2_CAP_AUDIO  ? 'X':' '),
1520              ( p_sys->dev_cap.capabilities & V4L2_CAP_TUNER  ? 'X':' ') );
1521
1522     msg_Dbg( p_demux, "supported I/O methods are: (%c) Read/Write, "
1523                                                  "(%c) Streaming, "
1524                                                  "(%c) Asynchronous",
1525             ( p_sys->dev_cap.capabilities & V4L2_CAP_READWRITE ? 'X':' ' ),
1526             ( p_sys->dev_cap.capabilities & V4L2_CAP_STREAMING ? 'X':' ' ),
1527             ( p_sys->dev_cap.capabilities & V4L2_CAP_ASYNCIO ? 'X':' ' ) );
1528
1529     /* Now, enumerate all the video inputs. This is useless at the moment
1530        since we have no way to present that info to the user except with
1531        debug messages */
1532
1533     if( p_sys->dev_cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
1534     {
1535         while( ioctl( i_fd, VIDIOC_S_INPUT, &p_sys->i_input ) >= 0 )
1536         {
1537             p_sys->i_input++;
1538         }
1539
1540         p_sys->p_inputs = calloc( 1, p_sys->i_input * sizeof( struct v4l2_input ) );
1541         if( !p_sys->p_inputs ) goto open_failed;
1542
1543         for( i_index = 0; i_index < p_sys->i_input; i_index++ )
1544         {
1545             p_sys->p_inputs[i_index].index = i_index;
1546
1547             if( ioctl( i_fd, VIDIOC_ENUMINPUT, &p_sys->p_inputs[i_index] ) )
1548             {
1549                 msg_Err( p_demux, "cannot get video input characteristics (%m)" );
1550                 goto open_failed;
1551             }
1552             msg_Dbg( p_demux, "video input %i (%s) has type: %s",
1553                                 i_index,
1554                                 p_sys->p_inputs[i_index].name,
1555                                 p_sys->p_inputs[i_index].type
1556                                         == V4L2_INPUT_TYPE_TUNER ?
1557                                         "Tuner adapter" :
1558                                         "External analog input" );
1559         }
1560     }
1561
1562     /* Probe video standards */
1563     if( p_sys->dev_cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
1564     {
1565         struct v4l2_standard t_standards;
1566         t_standards.index = 0;
1567         while( ioctl( i_fd, VIDIOC_ENUMSTD, &t_standards ) >=0 )
1568         {
1569             p_sys->i_standard++;
1570             t_standards.index = p_sys->i_standard;
1571         }
1572
1573         p_sys->p_standards = calloc( 1, p_sys->i_standard * sizeof( struct v4l2_standard ) );
1574         if( !p_sys->p_standards ) goto open_failed;
1575
1576         for( i_standard = 0; i_standard < p_sys->i_standard; i_standard++ )
1577         {
1578             p_sys->p_standards[i_standard].index = i_standard;
1579
1580             if( ioctl( i_fd, VIDIOC_ENUMSTD, &p_sys->p_standards[i_standard] ) )
1581             {
1582                 msg_Err( p_demux, "cannot get video input standards (%m)" );
1583                 goto open_failed;
1584             }
1585             msg_Dbg( p_demux, "video standard %i is: %s",
1586                                 i_standard,
1587                                 p_sys->p_standards[i_standard].name);
1588         }
1589     }
1590
1591     /* initialize the structures for the ioctls */
1592     for( i_index = 0; i_index < 32; i_index++ )
1593     {
1594         p_sys->p_audios[i_index].index = i_index;
1595     }
1596
1597     /* Probe audio inputs */
1598
1599     if( p_sys->dev_cap.capabilities & V4L2_CAP_AUDIO )
1600     {
1601         while( p_sys->i_audio < 32 &&
1602                ioctl( i_fd, VIDIOC_S_AUDIO, &p_sys->p_audios[p_sys->i_audio] ) >= 0 )
1603         {
1604             if( ioctl( i_fd, VIDIOC_G_AUDIO, &p_sys->p_audios[ p_sys->i_audio] ) < 0 )
1605             {
1606                 msg_Err( p_demux, "cannot get video input characteristics (%m)" );
1607                 goto open_failed;
1608             }
1609
1610             msg_Dbg( p_demux, "audio device %i (%s) is %s",
1611                                 p_sys->i_audio,
1612                                 p_sys->p_audios[p_sys->i_audio].name,
1613                                 p_sys->p_audios[p_sys->i_audio].capability &
1614                                                     V4L2_AUDCAP_STEREO ?
1615                                         "Stereo" : "Mono" );
1616
1617             p_sys->i_audio++;
1618         }
1619     }
1620
1621     if( p_sys->dev_cap.capabilities & V4L2_CAP_TUNER )
1622     {
1623         struct v4l2_tuner tuner;
1624
1625         memset( &tuner, 0, sizeof(tuner) );
1626         while( ioctl( i_fd, VIDIOC_S_TUNER, &tuner ) >= 0 )
1627         {
1628             p_sys->i_tuner++;
1629             tuner.index = p_sys->i_tuner;
1630         }
1631
1632         p_sys->p_tuners = calloc( 1, p_sys->i_tuner * sizeof( struct v4l2_tuner ) );
1633         if( !p_sys->p_tuners ) goto open_failed;
1634
1635         for( i_index = 0; i_index < p_sys->i_tuner; i_index++ )
1636         {
1637             p_sys->p_tuners[i_index].index = i_index;
1638
1639             if( ioctl( i_fd, VIDIOC_G_TUNER, &p_sys->p_tuners[i_index] ) )
1640             {
1641                 msg_Err( p_demux, "cannot get tuner characteristics (%m)" );
1642                 goto open_failed;
1643             }
1644             msg_Dbg( p_demux, "tuner %i (%s) has type: %s, "
1645                               "frequency range: %.1f %s -> %.1f %s",
1646                                 i_index,
1647                                 p_sys->p_tuners[i_index].name,
1648                                 p_sys->p_tuners[i_index].type
1649                                         == V4L2_TUNER_RADIO ?
1650                                         "Radio" : "Analog TV",
1651                                 p_sys->p_tuners[i_index].rangelow * 62.5,
1652                                 p_sys->p_tuners[i_index].capability &
1653                                         V4L2_TUNER_CAP_LOW ?
1654                                         "Hz" : "kHz",
1655                                 p_sys->p_tuners[i_index].rangehigh * 62.5,
1656                                 p_sys->p_tuners[i_index].capability &
1657                                         V4L2_TUNER_CAP_LOW ?
1658                                         "Hz" : "kHz" );
1659         }
1660     }
1661
1662     /* Probe for available chromas */
1663     if( p_sys->dev_cap.capabilities & V4L2_CAP_VIDEO_CAPTURE )
1664     {
1665         struct v4l2_fmtdesc codec;
1666
1667         i_index = 0;
1668         memset( &codec, 0, sizeof(codec) );
1669         codec.index = i_index;
1670         codec.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1671
1672         while( ioctl( i_fd, VIDIOC_ENUM_FMT, &codec ) >= 0 )
1673         {
1674             i_index++;
1675             codec.index = i_index;
1676         }
1677
1678         p_sys->i_codec = i_index;
1679
1680         p_sys->p_codecs = calloc( 1, p_sys->i_codec * sizeof( struct v4l2_fmtdesc ) );
1681
1682         for( i_index = 0; i_index < p_sys->i_codec; i_index++ )
1683         {
1684             p_sys->p_codecs[i_index].index = i_index;
1685             p_sys->p_codecs[i_index].type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1686
1687             if( ioctl( i_fd, VIDIOC_ENUM_FMT, &p_sys->p_codecs[i_index] ) < 0 )
1688             {
1689                 msg_Err( p_demux, "cannot get codec description (%m)" );
1690                 goto open_failed;
1691             }
1692
1693             msg_Dbg( p_demux, "device supports Codec %s",
1694                                 p_sys->p_codecs[i_index].description );
1695         }
1696     }
1697
1698
1699     if( i_fd >= 0 ) close( i_fd );
1700     return VLC_TRUE;
1701
1702 open_failed:
1703
1704     if( i_fd >= 0 ) close( i_fd );
1705     return VLC_FALSE;
1706
1707 }
1708
1709 /*****************************************************************************
1710  * ProbeAudioDev: probe audio for capabilities
1711  *****************************************************************************/
1712 vlc_bool_t ProbeAudioDev( demux_t *p_demux, char *psz_device )
1713 {
1714     int i_fd = 0;
1715     int i_caps;
1716
1717     if( ( i_fd = open( psz_device, O_RDONLY | O_NONBLOCK ) ) < 0 )
1718     {
1719         msg_Err( p_demux, "cannot open audio device (%m)" );
1720         goto open_failed;
1721     }
1722
1723     /* this will fail if the device is video */
1724     if( ioctl( i_fd, SNDCTL_DSP_GETCAPS, &i_caps ) < 0 )
1725     {
1726         msg_Err( p_demux, "cannot get audio caps (%m)" );
1727         goto open_failed;
1728     }
1729
1730     if( i_fd ) close( i_fd );
1731     return VLC_TRUE;
1732
1733 open_failed:
1734     if( i_fd ) close( i_fd );
1735     return VLC_FALSE;
1736
1737 }
1738