]> git.sesse.net Git - vlc/blob - modules/access/v4l.c
Use calloc instead of malloc+memset.
[vlc] / modules / access / v4l.c
1 /*****************************************************************************
2  * v4l.c : Video4Linux input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2002-2004 the VideoLAN team
5  * $Id$
6  *
7  * Author: Laurent Aimar <fenrir@via.ecp.fr>
8  *         Paul Forgey <paulf at aphrodite dot com>
9  *         Gildas Bazin <gbazin@videolan.org>
10  *         Benjamin Pracht <bigben at videolan dot org>
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  * Preamble
29  *****************************************************************************/
30
31 #ifdef HAVE_CONFIG_H
32 # include "config.h"
33 #endif
34
35 #include <vlc_common.h>
36 #include <vlc_plugin.h>
37 #include <vlc_input.h>
38 #include <vlc_demux.h>
39 #include <vlc_access.h>
40 #include <vlc_vout.h>
41 #include <vlc_codecs.h>
42
43 #include <sys/types.h>
44 #include <sys/stat.h>
45 #include <sys/ioctl.h>
46 #include <unistd.h>
47 #include <sys/mman.h>
48 #include <errno.h>
49 #include <fcntl.h>
50 #include <arpa/inet.h>
51
52 /* From GStreamer's v4l plugin:
53  * Because of some really cool feature in video4linux1, also known as
54  * 'not including sys/types.h and sys/time.h', we had to include it
55  * ourselves. In all their intelligence, these people decided to fix
56  * this in the next version (video4linux2) in such a cool way that it
57  * breaks all compilations of old stuff...
58  * The real problem is actually that linux/time.h doesn't use proper
59  * macro checks before defining types like struct timeval. The proper
60  * fix here is to either fuck the kernel header (which is what we do
61  * by defining _LINUX_TIME_H, an innocent little hack) or by fixing it
62  * upstream, which I'll consider doing later on. If you get compiler
63  * errors here, check your linux/time.h && sys/time.h header setup.
64 */
65 #define _LINUX_TIME_H
66
67 #include <linux/videodev.h>
68 #include "videodev_mjpeg.h"
69
70 #include <sys/soundcard.h>
71
72 /*****************************************************************************
73  * Module descriptior
74  *****************************************************************************/
75 static int  Open ( vlc_object_t * );
76 static void Close( vlc_object_t * );
77
78 #define CACHING_TEXT N_("Caching value in ms")
79 #define CACHING_LONGTEXT N_( \
80     "Caching value for V4L captures. This " \
81     "value should be set in milliseconds." )
82 #define VDEV_TEXT N_("Video device name")
83 #define VDEV_LONGTEXT N_( \
84     "Name of the video device to use. " \
85     "If you don't specify anything, no video device will be used.")
86 #define ADEV_TEXT N_("Audio device name")
87 #define ADEV_LONGTEXT N_( \
88     "Name of the audio device to use. " \
89     "If you don't specify anything, no audio device will be used.")
90 #define CHROMA_TEXT N_("Video input chroma format")
91 #define CHROMA_LONGTEXT N_( \
92     "Force the Video4Linux video device to use a specific chroma format " \
93     "(eg. I420 (default), RV24, etc.)")
94 #define FREQUENCY_TEXT N_( "Frequency" )
95 #define FREQUENCY_LONGTEXT N_( \
96     "Frequency to capture (in kHz), if applicable." )
97 #define CHANNEL_TEXT N_( "Channel" )
98 #define CHANNEL_LONGTEXT N_( \
99     "Channel of the card to use (Usually, 0 = tuner, " \
100     "1 = composite, 2 = svideo)." )
101 #define NORM_TEXT N_( "Norm" )
102 #define NORM_LONGTEXT N_( \
103     "Norm of the stream (Automatic, SECAM, PAL, or NTSC)." )
104 #define AUDIO_TEXT N_( "Audio Channel" )
105 #define AUDIO_LONGTEXT N_( \
106     "Audio Channel to use, if there are several audio inputs." )
107 #define WIDTH_TEXT N_( "Width" )
108 #define WIDTH_LONGTEXT N_( "Width of the stream to capture " \
109     "(-1 for autodetect)." )
110 #define HEIGHT_TEXT N_( "Height" )
111 #define HEIGHT_LONGTEXT N_( "Height of the stream to capture " \
112     "(-1 for autodetect)." )
113 #define BRIGHTNESS_TEXT N_( "Brightness" )
114 #define BRIGHTNESS_LONGTEXT N_( \
115     "Brightness of the video input." )
116 #define HUE_TEXT N_( "Hue" )
117 #define HUE_LONGTEXT N_( \
118     "Hue of the video input." )
119 #define COLOUR_TEXT N_( "Color" )
120 #define COLOUR_LONGTEXT N_( \
121     "Color of the video input." )
122 #define CONTRAST_TEXT N_( "Contrast" )
123 #define CONTRAST_LONGTEXT N_( \
124     "Contrast of the video input." )
125 #define TUNER_TEXT N_( "Tuner" )
126 #define TUNER_LONGTEXT N_( "Tuner to use, if there are several ones." )
127 #define SAMPLERATE_TEXT N_( "Samplerate" )
128 #define SAMPLERATE_LONGTEXT N_( \
129     "Samplerate of the captured audio stream, in Hz (eg: 11025, 22050, 44100)" )
130 #define STEREO_TEXT N_( "Stereo" )
131 #define STEREO_LONGTEXT N_( \
132     "Capture the audio stream in stereo." )
133 #define MJPEG_TEXT N_( "MJPEG" )
134 #define MJPEG_LONGTEXT N_(  \
135     "Set this option if the capture device outputs MJPEG" )
136 #define DECIMATION_TEXT N_( "Decimation" )
137 #define DECIMATION_LONGTEXT N_( \
138     "Decimation level for MJPEG streams" )
139 #define QUALITY_TEXT N_( "Quality" )
140 #define QUALITY_LONGTEXT N_( "Quality of the stream." )
141 #define FPS_TEXT N_( "Framerate" )
142 #define FPS_LONGTEXT N_( "Framerate to capture, if applicable " \
143     "(-1 for autodetect)." )
144
145 static const int i_norm_list[] =
146     { VIDEO_MODE_AUTO, VIDEO_MODE_SECAM, VIDEO_MODE_PAL, VIDEO_MODE_NTSC };
147 static const char *const psz_norm_list_text[] =
148     { N_("Automatic"), N_("SECAM"), N_("PAL"),  N_("NTSC") };
149
150 vlc_module_begin ()
151     set_shortname( N_("Video4Linux") )
152     set_description( N_("Video4Linux input") )
153     set_category( CAT_INPUT )
154     set_subcategory( SUBCAT_INPUT_ACCESS )
155
156     add_integer( "v4l-caching", DEFAULT_PTS_DELAY / 1000, NULL,
157                  CACHING_TEXT, CACHING_LONGTEXT, true );
158     add_string( "v4l-vdev", "/dev/video", 0, VDEV_TEXT, VDEV_LONGTEXT,
159                 false );
160     add_string( "v4l-adev", "/dev/dsp", 0, ADEV_TEXT, ADEV_LONGTEXT,
161                 false );
162     add_string( "v4l-chroma", NULL, NULL, CHROMA_TEXT, CHROMA_LONGTEXT,
163                 true );
164     add_float( "v4l-fps", -1.0, NULL, FPS_TEXT, FPS_LONGTEXT, true )
165     add_integer( "v4l-samplerate", 44100, NULL, SAMPLERATE_TEXT,
166                 SAMPLERATE_LONGTEXT, true );
167     add_integer( "v4l-channel", 0, NULL, CHANNEL_TEXT, CHANNEL_LONGTEXT,
168                 true );
169     add_integer( "v4l-tuner", -1, NULL, TUNER_TEXT, TUNER_LONGTEXT, true )
170     add_integer( "v4l-norm", VIDEO_MODE_AUTO, NULL, NORM_TEXT, NORM_LONGTEXT,
171                 false );
172         change_integer_list( i_norm_list, psz_norm_list_text, NULL );
173     add_integer( "v4l-frequency", -1, NULL, FREQUENCY_TEXT, FREQUENCY_LONGTEXT,
174                 false );
175     add_integer( "v4l-audio", -1, NULL, AUDIO_TEXT, AUDIO_LONGTEXT, true )
176     add_bool( "v4l-stereo", true, NULL, STEREO_TEXT, STEREO_LONGTEXT,
177             true );
178     add_integer( "v4l-width", 0, NULL, WIDTH_TEXT, WIDTH_LONGTEXT, true )
179     add_integer( "v4l-height", 0, NULL, HEIGHT_TEXT, HEIGHT_LONGTEXT,
180                 true );
181     add_integer( "v4l-brightness", -1, NULL, BRIGHTNESS_TEXT,
182                 BRIGHTNESS_LONGTEXT, true );
183     add_integer( "v4l-colour", -1, NULL, COLOUR_TEXT, COLOUR_LONGTEXT,
184                 true );
185     add_integer( "v4l-hue", -1, NULL, HUE_TEXT, HUE_LONGTEXT, true )
186     add_integer( "v4l-contrast", -1, NULL, CONTRAST_TEXT, CONTRAST_LONGTEXT,
187                 true );
188     add_bool( "v4l-mjpeg", false, NULL, MJPEG_TEXT, MJPEG_LONGTEXT,
189             true );
190     add_integer( "v4l-decimation", 1, NULL, DECIMATION_TEXT,
191             DECIMATION_LONGTEXT, true );
192     add_integer( "v4l-quality", 100, NULL, QUALITY_TEXT, QUALITY_LONGTEXT,
193             true );
194
195     add_shortcut( "v4l" )
196     set_capability( "access_demux", 10 )
197     set_callbacks( Open, Close )
198 vlc_module_end ()
199
200 /*****************************************************************************
201  * Access: local prototypes
202  *****************************************************************************/
203 static int Demux  ( demux_t * );
204 static int Control( demux_t *, int, va_list );
205
206 static void ParseMRL    ( demux_t * );
207 static int  OpenVideoDev( demux_t *, char * );
208 static int  OpenAudioDev( demux_t *, char * );
209
210 static block_t *GrabAudio( demux_t * );
211 static block_t *GrabVideo( demux_t * );
212
213 #define MJPEG_BUFFER_SIZE (256*1024)
214
215 struct quicktime_mjpeg_app1
216 {
217     uint32_t    i_reserved;             /* set to 0 */
218     uint32_t    i_tag;                  /* 'mjpg' */
219     uint32_t    i_field_size;           /* offset following EOI */
220     uint32_t    i_padded_field_size;    /* offset following EOI+pad */
221     uint32_t    i_next_field;           /* offset to next field */
222     uint32_t    i_DQT_offset;
223     uint32_t    i_DHT_offset;
224     uint32_t    i_SOF_offset;
225     uint32_t    i_SOS_offset;
226     uint32_t    i_data_offset;          /* following SOS marker data */
227 };
228
229 static const struct
230 {
231     int i_v4l;
232     int i_fourcc;
233
234 } v4lchroma_to_fourcc[] =
235 {
236     { VIDEO_PALETTE_GREY, VLC_FOURCC( 'G', 'R', 'E', 'Y' ) },
237     { VIDEO_PALETTE_HI240, VLC_FOURCC( 'I', '2', '4', '0' ) },
238     { VIDEO_PALETTE_RGB565, VLC_FOURCC( 'R', 'V', '1', '6' ) },
239     { VIDEO_PALETTE_RGB555, VLC_FOURCC( 'R', 'V', '1', '5' ) },
240     { VIDEO_PALETTE_RGB24, VLC_FOURCC( 'R', 'V', '2', '4' ) },
241     { VIDEO_PALETTE_RGB32, VLC_FOURCC( 'R', 'V', '3', '2' ) },
242     { VIDEO_PALETTE_YUV422, VLC_FOURCC( 'Y', 'U', 'Y', '2' ) },
243     { VIDEO_PALETTE_YUV422, VLC_FOURCC( 'Y', 'U', 'Y', 'V' ) },
244     { VIDEO_PALETTE_YUYV, VLC_FOURCC( 'Y', 'U', 'Y', '2' ) },
245     { VIDEO_PALETTE_YUYV, VLC_FOURCC( 'Y', 'U', 'Y', 'V' ) },
246     { VIDEO_PALETTE_UYVY, VLC_FOURCC( 'U', 'Y', 'V', 'Y' ) },
247     { VIDEO_PALETTE_YUV420, VLC_FOURCC( 'I', '4', '2', 'N' ) },
248     { VIDEO_PALETTE_YUV411, VLC_FOURCC( 'I', '4', '1', 'N' ) },
249     { VIDEO_PALETTE_RAW, VLC_FOURCC( 'G', 'R', 'A', 'W' ) },
250     { VIDEO_PALETTE_YUV422P, VLC_FOURCC( 'I', '4', '2', '2' ) },
251     { VIDEO_PALETTE_YUV420P, VLC_FOURCC( 'I', '4', '2', '0' ) },
252     { VIDEO_PALETTE_YUV411P, VLC_FOURCC( 'I', '4', '1', '1' ) },
253     { 0, 0 }
254 };
255
256 struct demux_sys_t
257 {
258     /* Devices */
259     char *psz_device;         /* Main device from MRL, can be video or audio */
260
261     char *psz_vdev;
262     int  fd_video;
263
264     char *psz_adev;
265     int  fd_audio;
266
267     /* Video properties */
268     picture_t pic;
269
270     int i_fourcc;
271     int i_channel;
272     int i_audio;
273     int i_norm;
274     int i_tuner;
275     int i_frequency;
276     int i_width;
277     int i_height;
278
279     int i_brightness;
280     int i_hue;
281     int i_colour;
282     int i_contrast;
283
284     float f_fps;            /* <= 0.0 mean to grab at full rate */
285     mtime_t i_video_pts;    /* only used when f_fps > 0 */
286
287     bool b_mjpeg;
288     int i_decimation;
289     int i_quality;
290
291     struct video_capability vid_cap;
292     struct video_mbuf       vid_mbuf;
293     struct mjpeg_requestbuffers mjpeg_buffers;
294
295     uint8_t *p_video_mmap;
296     int     i_frame_pos;
297
298     struct video_mmap   vid_mmap;
299     struct video_picture vid_picture;
300
301     int          i_video_frame_size;
302     es_out_id_t  *p_es_video;
303
304     /* Audio properties */
305     vlc_fourcc_t i_acodec_raw;
306     int          i_sample_rate;
307     bool   b_stereo;
308     int          i_audio_max_frame_size;
309     block_t      *p_block_audio;
310     es_out_id_t  *p_es_audio;
311 };
312
313 /*****************************************************************************
314  * Open: opens v4l device
315  *****************************************************************************
316  *
317  * url: <video device>::::
318  *
319  *****************************************************************************/
320 static int Open( vlc_object_t *p_this )
321 {
322     demux_t     *p_demux = (demux_t*)p_this;
323     demux_sys_t *p_sys;
324     vlc_value_t val;
325
326     /* Only when selected */
327     if( *p_demux->psz_access == '\0' )
328         return VLC_EGENERIC;
329
330     /* Set up p_demux */
331     p_demux->pf_demux = Demux;
332     p_demux->pf_control = Control;
333     p_demux->info.i_update = 0;
334     p_demux->info.i_title = 0;
335     p_demux->info.i_seekpoint = 0;
336     p_demux->p_sys = p_sys = calloc( 1, sizeof( demux_sys_t ) );
337     if( !p_sys )
338         return VLC_ENOMEM;
339
340     var_Create( p_demux, "v4l-audio", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
341     var_Get( p_demux, "v4l-audio", &val );
342     p_sys->i_audio          = val.i_int;
343
344     var_Create( p_demux, "v4l-channel", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
345     var_Get( p_demux, "v4l-channel", &val );
346     p_sys->i_channel        = val.i_int;
347
348     var_Create( p_demux, "v4l-norm", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
349     var_Get( p_demux, "v4l-norm", &val );
350     p_sys->i_norm           = val.i_int;
351
352     var_Create( p_demux, "v4l-tuner", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
353     var_Get( p_demux, "v4l-tuner", &val );
354     p_sys->i_tuner          = val.i_int;
355
356     var_Create( p_demux, "v4l-frequency",
357                                     VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
358     var_Get( p_demux, "v4l-frequency", &val );
359     p_sys->i_frequency      = val.i_int;
360
361     var_Create( p_demux, "v4l-fps", VLC_VAR_FLOAT | VLC_VAR_DOINHERIT );
362     var_Get( p_demux, "v4l-fps", &val );
363     p_sys->f_fps            = val.f_float;
364
365     var_Create( p_demux, "v4l-width", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
366     var_Get( p_demux, "v4l-width", &val );
367     p_sys->i_width          = val.i_int;
368
369     var_Create( p_demux, "v4l-height", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
370     var_Get( p_demux, "v4l-height", &val );
371     p_sys->i_height         = val.i_int;
372
373     p_sys->i_video_pts      = -1;
374
375     var_Create( p_demux, "v4l-brightness", VLC_VAR_INTEGER |
376                                                         VLC_VAR_DOINHERIT );
377     var_Get( p_demux, "v4l-brightness", &val );
378     p_sys->i_brightness     = val.i_int;
379
380     var_Create( p_demux, "v4l-hue", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
381     var_Get( p_demux, "v4l-hue", &val );
382     p_sys->i_hue            = -1;
383
384     var_Create( p_demux, "v4l-colour", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
385     var_Get( p_demux, "v4l-colour", &val );
386     p_sys->i_colour         = val.i_int;
387
388     var_Create( p_demux, "v4l-contrast", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
389     var_Get( p_demux, "v4l-contrast", &val );
390     p_sys->i_contrast       = val.i_int;
391
392     var_Create( p_demux, "v4l-mjpeg", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
393     var_Get( p_demux, "v4l-mjpeg", &val );
394     p_sys->b_mjpeg     = val.b_bool;
395
396     var_Create( p_demux, "v4l-decimation", VLC_VAR_INTEGER |
397                                                             VLC_VAR_DOINHERIT );
398     var_Get( p_demux, "v4l-decimation", &val );
399     p_sys->i_decimation = val.i_int;
400
401     var_Create( p_demux, "v4l-quality", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
402     var_Get( p_demux, "v4l-quality", &val );
403     p_sys->i_quality = val.i_int;
404
405     var_Create( p_demux, "v4l-samplerate",
406                                     VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
407     var_Get( p_demux, "v4l-samplerate", &val );
408     p_sys->i_sample_rate  = val.i_int;
409
410     var_Create( p_demux, "v4l-stereo", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
411     var_Get( p_demux, "v4l-stereo", &val );
412     p_sys->b_stereo       = val.b_bool;
413
414     p_sys->psz_device = p_sys->psz_vdev = p_sys->psz_adev = NULL;
415     p_sys->fd_video = -1;
416     p_sys->fd_audio = -1;
417
418     p_sys->p_es_video = p_sys->p_es_audio = 0;
419     p_sys->p_block_audio = 0;
420
421     ParseMRL( p_demux );
422
423     /* Find main device (video or audio) */
424     if( p_sys->psz_device && *p_sys->psz_device )
425     {
426         msg_Dbg( p_demux, "main device=`%s'", p_sys->psz_device );
427
428         /* Try to open as video device */
429         p_sys->fd_video = OpenVideoDev( p_demux, p_sys->psz_device );
430
431         if( p_sys->fd_video < 0 )
432         {
433             /* Try to open as audio device */
434             p_sys->fd_audio = OpenAudioDev( p_demux, p_sys->psz_device );
435             if( p_sys->fd_audio >= 0 )
436             {
437                 free( p_sys->psz_adev );
438                 p_sys->psz_adev = p_sys->psz_device;
439                 p_sys->psz_device = NULL;
440             }
441         }
442         else
443         {
444             free( p_sys->psz_vdev );
445             p_sys->psz_vdev = p_sys->psz_device;
446             p_sys->psz_device = NULL;
447         }
448     }
449
450     /* If no device opened, only continue if the access was forced */
451     if( p_sys->fd_video < 0 && p_sys->fd_audio < 0 )
452     {
453         if( strcmp( p_demux->psz_access, "v4l" ) )
454         {
455             Close( p_this );
456             return VLC_EGENERIC;
457         }
458     }
459
460     /* Find video device */
461     if( p_sys->fd_video < 0 )
462     {
463         if( !p_sys->psz_vdev || !*p_sys->psz_vdev )
464         {
465             free( p_sys->psz_vdev );
466             p_sys->psz_vdev = var_CreateGetString( p_demux, "v4l-vdev" );;
467         }
468
469         if( p_sys->psz_vdev && *p_sys->psz_vdev )
470         {
471             p_sys->fd_video = OpenVideoDev( p_demux, p_sys->psz_vdev );
472         }
473     }
474
475     /* Find audio device */
476     if( p_sys->fd_audio < 0 )
477     {
478         if( !p_sys->psz_adev || !*p_sys->psz_adev )
479         {
480             free( p_sys->psz_adev );
481             p_sys->psz_adev = var_CreateGetString( p_demux, "v4l-adev" );;
482         }
483
484         if( p_sys->psz_adev && *p_sys->psz_adev )
485         {
486             p_sys->fd_audio = OpenAudioDev( p_demux, p_sys->psz_adev );
487         }
488     }
489
490     if( p_sys->fd_video < 0 && p_sys->fd_audio < 0 )
491     {
492         Close( p_this );
493         return VLC_EGENERIC;
494     }
495
496     msg_Dbg( p_demux, "v4l grabbing started" );
497
498     /* Declare elementary streams */
499     if( p_sys->fd_video >= 0 )
500     {
501         es_format_t fmt;
502         es_format_Init( &fmt, VIDEO_ES, p_sys->i_fourcc );
503         fmt.video.i_width  = p_sys->i_width;
504         fmt.video.i_height = p_sys->i_height;
505         fmt.video.i_aspect = 4 * VOUT_ASPECT_FACTOR / 3;
506
507         /* Setup rgb mask for RGB formats */
508         switch( p_sys->i_fourcc )
509         {
510             case VLC_FOURCC('R','V','1','5'):
511                 fmt.video.i_rmask = 0x001f;
512                 fmt.video.i_gmask = 0x03e0;
513                 fmt.video.i_bmask = 0x7c00;
514                 break;
515             case VLC_FOURCC('R','V','1','6'):
516                 fmt.video.i_rmask = 0x001f;
517                 fmt.video.i_gmask = 0x07e0;
518                 fmt.video.i_bmask = 0xf800;
519                 break;
520             case VLC_FOURCC('R','V','2','4'):
521             case VLC_FOURCC('R','V','3','2'):
522                 fmt.video.i_rmask = 0x00ff0000;
523                 fmt.video.i_gmask = 0x0000ff00;
524                 fmt.video.i_bmask = 0x000000ff;
525                 break;
526         }
527
528         msg_Dbg( p_demux, "added new video es %4.4s %dx%d",
529                  (char*)&fmt.i_codec, fmt.video.i_width, fmt.video.i_height );
530         p_sys->p_es_video = es_out_Add( p_demux->out, &fmt );
531     }
532
533     if( p_sys->fd_audio >= 0 )
534     {
535         es_format_t fmt;
536         es_format_Init( &fmt, AUDIO_ES, VLC_FOURCC('a','r','a','w') );
537
538         fmt.audio.i_channels = p_sys->b_stereo ? 2 : 1;
539         fmt.audio.i_rate = p_sys->i_sample_rate;
540         fmt.audio.i_bitspersample = 16; // FIXME ?
541         fmt.audio.i_blockalign = fmt.audio.i_channels *
542             fmt.audio.i_bitspersample / 8;
543         fmt.i_bitrate = fmt.audio.i_channels * fmt.audio.i_rate *
544             fmt.audio.i_bitspersample;
545
546         msg_Dbg( p_demux, "new audio es %d channels %dHz",
547                  fmt.audio.i_channels, fmt.audio.i_rate );
548
549         p_sys->p_es_audio = es_out_Add( p_demux->out, &fmt );
550     }
551
552     /* Update default_pts to a suitable value for access */
553     var_Create( p_demux, "v4l-caching", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
554
555     return VLC_SUCCESS;
556 }
557
558 /*****************************************************************************
559  * Close: close device, free resources
560  *****************************************************************************/
561 static void Close( vlc_object_t *p_this )
562 {
563     demux_t     *p_demux = (demux_t *)p_this;
564     demux_sys_t *p_sys   = p_demux->p_sys;
565
566     free( p_sys->psz_device );
567     free( p_sys->psz_vdev );
568     free( p_sys->psz_adev );
569     if( p_sys->fd_video >= 0 ) close( p_sys->fd_video );
570     if( p_sys->fd_audio >= 0 ) close( p_sys->fd_audio );
571     if( p_sys->p_block_audio ) block_Release( p_sys->p_block_audio );
572
573     if( p_sys->b_mjpeg )
574     {
575         int i_noframe = -1;
576         ioctl( p_sys->fd_video, MJPIOC_QBUF_CAPT, &i_noframe );
577     }
578
579     if( p_sys->p_video_mmap && p_sys->p_video_mmap != MAP_FAILED )
580     {
581         if( p_sys->b_mjpeg )
582             munmap( p_sys->p_video_mmap, p_sys->mjpeg_buffers.size *
583                     p_sys->mjpeg_buffers.count );
584         else
585             munmap( p_sys->p_video_mmap, p_sys->vid_mbuf.size );
586     }
587
588     free( p_sys );
589 }
590
591 /*****************************************************************************
592  * Control:
593  *****************************************************************************/
594 static int Control( demux_t *p_demux, int i_query, va_list args )
595 {
596     bool *pb;
597     int64_t    *pi64;
598
599     switch( i_query )
600     {
601         /* Special for access_demux */
602         case DEMUX_CAN_PAUSE:
603         case DEMUX_CAN_SEEK:
604         case DEMUX_SET_PAUSE_STATE:
605         case DEMUX_CAN_CONTROL_PACE:
606             pb = (bool*)va_arg( args, bool * );
607             *pb = false;
608             return VLC_SUCCESS;
609
610         case DEMUX_GET_PTS_DELAY:
611             pi64 = (int64_t*)va_arg( args, int64_t * );
612             *pi64 = (int64_t)var_GetInteger( p_demux, "v4l-caching" ) * 1000;
613             return VLC_SUCCESS;
614
615         case DEMUX_GET_TIME:
616             pi64 = (int64_t*)va_arg( args, int64_t * );
617             *pi64 = mdate();
618             return VLC_SUCCESS;
619
620         /* TODO implement others */
621         default:
622             return VLC_EGENERIC;
623     }
624
625     return VLC_EGENERIC;
626 }
627
628 /*****************************************************************************
629  * Demux:
630  *****************************************************************************/
631 static int Demux( demux_t *p_demux )
632 {
633     demux_sys_t *p_sys = p_demux->p_sys;
634     es_out_id_t  *p_es = p_sys->p_es_audio;
635     block_t *p_block = NULL;
636
637     /* Try grabbing audio frames first */
638     if( p_sys->fd_audio < 0 || !( p_block = GrabAudio( p_demux ) ) )
639     {
640         /* Try grabbing video frame */
641         p_es = p_sys->p_es_video;
642         if( p_sys->fd_video > 0 ) p_block = GrabVideo( p_demux );
643     }
644
645     if( !p_block )
646     {
647         /* Sleep so we do not consume all the cpu, 10ms seems
648          * like a good value (100fps) */
649         msleep( 10000 );
650         return 1;
651     }
652
653     es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_block->i_pts );
654     es_out_Send( p_demux->out, p_es, p_block );
655
656     return 1;
657 }
658
659 /*****************************************************************************
660  * ParseMRL: parse the options contained in the MRL
661  *****************************************************************************/
662 static void ParseMRL( demux_t *p_demux )
663 {
664     demux_sys_t *p_sys = p_demux->p_sys;
665
666     char *psz_dup = strdup( p_demux->psz_path );
667     char *psz_parser = psz_dup;
668
669     while( *psz_parser && *psz_parser != ':' )
670     {
671         psz_parser++;
672     }
673
674     if( *psz_parser == ':' )
675     {
676         /* read options */
677         for( ;; )
678         {
679             *psz_parser++ = '\0';
680             if( !strncmp( psz_parser, "channel=", strlen( "channel=" ) ) )
681             {
682                 p_sys->i_channel = strtol( psz_parser + strlen( "channel=" ),
683                                            &psz_parser, 0 );
684             }
685             else if( !strncmp( psz_parser, "norm=", strlen( "norm=" ) ) )
686             {
687                 psz_parser += strlen( "norm=" );
688                 if( !strncmp( psz_parser, "pal", strlen( "pal" ) ) )
689                 {
690                     p_sys->i_norm = VIDEO_MODE_PAL;
691                     psz_parser += strlen( "pal" );
692                 }
693                 else if( !strncmp( psz_parser, "ntsc", strlen( "ntsc" ) ) )
694                 {
695                     p_sys->i_norm = VIDEO_MODE_NTSC;
696                     psz_parser += strlen( "ntsc" );
697                 }
698                 else if( !strncmp( psz_parser, "secam", strlen( "secam" ) ) )
699                 {
700                     p_sys->i_norm = VIDEO_MODE_SECAM;
701                     psz_parser += strlen( "secam" );
702                 }
703                 else if( !strncmp( psz_parser, "auto", strlen( "auto" ) ) )
704                 {
705                     p_sys->i_norm = VIDEO_MODE_AUTO;
706                     psz_parser += strlen( "auto" );
707                 }
708                 else
709                 {
710                     p_sys->i_norm = strtol( psz_parser, &psz_parser, 0 );
711                 }
712             }
713             else if( !strncmp( psz_parser, "frequency=",
714                                strlen( "frequency=" ) ) )
715             {
716                 p_sys->i_frequency =
717                     strtol( psz_parser + strlen( "frequency=" ),
718                             &psz_parser, 0 );
719                 if( p_sys->i_frequency < 30000 )
720                 {
721                     msg_Warn( p_demux, "v4l syntax has changed : "
722                               "'frequency' is now channel frequency in kHz");
723                 }
724             }
725             else if( !strncmp( psz_parser, "audio=", strlen( "audio=" ) ) )
726             {
727                 p_sys->i_audio = strtol( psz_parser + strlen( "audio=" ),
728                                          &psz_parser, 0 );
729             }
730             else if( !strncmp( psz_parser, "size=", strlen( "size=" ) ) )
731             {
732                 psz_parser += strlen( "size=" );
733                 if( !strncmp( psz_parser, "subqcif", strlen( "subqcif" ) ) )
734                 {
735                     p_sys->i_width  = 128;
736                     p_sys->i_height = 96;
737                 }
738                 else if( !strncmp( psz_parser, "qsif", strlen( "qsif" ) ) )
739                 {
740                     p_sys->i_width  = 160;
741                     p_sys->i_height = 120;
742                 }
743                 else if( !strncmp( psz_parser, "qcif", strlen( "qcif" ) ) )
744                 {
745                     p_sys->i_width  = 176;
746                     p_sys->i_height = 144;
747                 }
748                 else if( !strncmp( psz_parser, "sif", strlen( "sif" ) ) )
749                 {
750                     p_sys->i_width  = 320;
751                     p_sys->i_height = 244;
752                 }
753                 else if( !strncmp( psz_parser, "cif", strlen( "cif" ) ) )
754                 {
755                     p_sys->i_width  = 352;
756                     p_sys->i_height = 288;
757                 }
758                 else if( !strncmp( psz_parser, "vga", strlen( "vga" ) ) )
759                 {
760                     p_sys->i_width  = 640;
761                     p_sys->i_height = 480;
762                 }
763                 else
764                 {
765                     /* widthxheight */
766                     p_sys->i_width = strtol( psz_parser, &psz_parser, 0 );
767                     if( *psz_parser == 'x' || *psz_parser == 'X')
768                     {
769                         p_sys->i_height = strtol( psz_parser + 1,
770                                                   &psz_parser, 0 );
771                     }
772                     msg_Dbg( p_demux, "WxH %dx%d", p_sys->i_width,
773                              p_sys->i_height );
774                 }
775             }
776             else if( !strncmp( psz_parser, "brightness=", strlen( "brightness=" ) ) )
777             {
778                 p_sys->i_brightness = strtol( psz_parser + strlen( "brightness=" ),
779                                               &psz_parser, 0 );
780             }
781             else if( !strncmp( psz_parser, "colour=", strlen( "colour=" ) ) )
782             {
783                 p_sys->i_colour = strtol( psz_parser + strlen( "colour=" ),
784                                           &psz_parser, 0 );
785             }
786             else if( !strncmp( psz_parser, "hue=", strlen( "hue=" ) ) )
787             {
788                 p_sys->i_hue = strtol( psz_parser + strlen( "hue=" ),
789                                        &psz_parser, 0 );
790             }
791             else if( !strncmp( psz_parser, "contrast=", strlen( "contrast=" ) ) )
792             {
793                 p_sys->i_contrast = strtol( psz_parser + strlen( "contrast=" ),
794                                             &psz_parser, 0 );
795             }
796             else if( !strncmp( psz_parser, "tuner=", strlen( "tuner=" ) ) )
797             {
798                 p_sys->i_tuner = strtol( psz_parser + strlen( "tuner=" ),
799                                          &psz_parser, 0 );
800             }
801             else if( !strncmp( psz_parser, "adev=", strlen( "adev=" ) ) )
802             {
803                 int  i_len;
804
805                 psz_parser += strlen( "adev=" );
806                 if( strchr( psz_parser, ':' ) )
807                 {
808                     i_len = strchr( psz_parser, ':' ) - psz_parser;
809                 }
810                 else
811                 {
812                     i_len = strlen( psz_parser );
813                 }
814
815                 p_sys->psz_adev = strndup( psz_parser, i_len );
816
817                 psz_parser += i_len;
818             }
819             else if( !strncmp( psz_parser, "samplerate=",
820                                strlen( "samplerate=" ) ) )
821             {
822                 p_sys->i_sample_rate =
823                     strtol( psz_parser + strlen( "samplerate=" ),
824                             &psz_parser, 0 );
825             }
826             else if( !strncmp( psz_parser, "stereo", strlen( "stereo" ) ) )
827             {
828                 psz_parser += strlen( "stereo" );
829
830                 p_sys->b_stereo = true;
831             }
832             else if( !strncmp( psz_parser, "mono", strlen( "mono" ) ) )
833             {
834                 psz_parser += strlen( "mono" );
835
836                 p_sys->b_stereo = false;
837             }
838             else if( !strncmp( psz_parser, "mjpeg", strlen( "mjpeg" ) ) )
839             {
840                 psz_parser += strlen( "mjpeg" );
841
842                 p_sys->b_mjpeg = true;
843             }
844             else if( !strncmp( psz_parser, "decimation=",
845                         strlen( "decimation=" ) ) )
846             {
847                 p_sys->i_decimation =
848                     strtol( psz_parser + strlen( "decimation=" ),
849                             &psz_parser, 0 );
850             }
851             else if( !strncmp( psz_parser, "quality=",
852                         strlen( "quality=" ) ) )
853             {
854                 p_sys->i_quality =
855                     strtol( psz_parser + strlen( "quality=" ),
856                             &psz_parser, 0 );
857             }
858             else if( !strncmp( psz_parser, "fps=", strlen( "fps=" ) ) )
859             {
860                 p_sys->f_fps = strtof( psz_parser + strlen( "fps=" ),
861                                        &psz_parser );
862             }
863             else
864             {
865                 msg_Warn( p_demux, "unknown option" );
866             }
867
868             while( *psz_parser && *psz_parser != ':' )
869             {
870                 psz_parser++;
871             }
872
873             if( *psz_parser == '\0' )
874             {
875                 break;
876             }
877         }
878     }
879
880     if( *psz_dup )
881     {
882         p_sys->psz_device = strdup( psz_dup );
883     }
884     free( psz_dup );
885 }
886
887 /*****************************************************************************
888  * OpenVideoDev:
889  *****************************************************************************/
890 static int OpenVideoDev( demux_t *p_demux, char *psz_device )
891 {
892     demux_sys_t *p_sys = p_demux->p_sys;
893     int i_fd;
894
895     struct video_channel vid_channel;
896     struct mjpeg_params mjpeg;
897     int i;
898
899     if( ( i_fd = open( psz_device, O_RDWR ) ) < 0 )
900     {
901         msg_Err( p_demux, "cannot open device (%m)" );
902         goto vdev_failed;
903     }
904
905     if( ioctl( i_fd, VIDIOCGCAP, &p_sys->vid_cap ) < 0 )
906     {
907         msg_Err( p_demux, "cannot get capabilities (%m)" );
908         goto vdev_failed;
909     }
910
911     msg_Dbg( p_demux,
912              "V4L device %s %d channels %d audios %d < w < %d %d < h < %d",
913              p_sys->vid_cap.name,
914              p_sys->vid_cap.channels,
915              p_sys->vid_cap.audios,
916              p_sys->vid_cap.minwidth,  p_sys->vid_cap.maxwidth,
917              p_sys->vid_cap.minheight, p_sys->vid_cap.maxheight );
918
919     if( p_sys->i_channel < 0 || p_sys->i_channel >= p_sys->vid_cap.channels )
920     {
921         msg_Dbg( p_demux, "invalid channel, falling back on channel 0" );
922         p_sys->i_channel = 0;
923     }
924     if( p_sys->vid_cap.audios && p_sys->i_audio >= p_sys->vid_cap.audios )
925     {
926         msg_Dbg( p_demux, "invalid audio, falling back with no audio" );
927         p_sys->i_audio = -1;
928     }
929
930     if( p_sys->i_width < p_sys->vid_cap.minwidth ||
931         p_sys->i_width > p_sys->vid_cap.maxwidth )
932     {
933         msg_Dbg( p_demux, "invalid width %i", p_sys->i_width );
934         p_sys->i_width = 0;
935     }
936     if( p_sys->i_height < p_sys->vid_cap.minheight ||
937         p_sys->i_height > p_sys->vid_cap.maxheight )
938     {
939         msg_Dbg( p_demux, "invalid height %i", p_sys->i_height );
940         p_sys->i_height = 0;
941     }
942
943     if( !( p_sys->vid_cap.type & VID_TYPE_CAPTURE ) )
944     {
945         msg_Err( p_demux, "cannot grab" );
946         goto vdev_failed;
947     }
948
949     vid_channel.channel = p_sys->i_channel;
950     if( ioctl( i_fd, VIDIOCGCHAN, &vid_channel ) < 0 )
951     {
952         msg_Err( p_demux, "cannot get channel infos (%m)" );
953         goto vdev_failed;
954     }
955     msg_Dbg( p_demux,
956              "setting channel %s(%d) %d tuners flags=0x%x type=0x%x norm=0x%x",
957              vid_channel.name, vid_channel.channel, vid_channel.tuners,
958              vid_channel.flags, vid_channel.type, vid_channel.norm );
959
960     if( p_sys->i_tuner >= vid_channel.tuners )
961     {
962         msg_Dbg( p_demux, "invalid tuner, falling back on tuner 0" );
963         p_sys->i_tuner = 0;
964     }
965
966     vid_channel.norm = p_sys->i_norm;
967     if( ioctl( i_fd, VIDIOCSCHAN, &vid_channel ) < 0 )
968     {
969         msg_Err( p_demux, "cannot set channel (%m)" );
970         goto vdev_failed;
971     }
972
973     if( vid_channel.flags & VIDEO_VC_TUNER )
974     {
975
976         /* set tuner */
977 #if 0
978         struct video_tuner vid_tuner;
979         if( p_sys->i_tuner >= 0 )
980         {
981             vid_tuner.tuner = p_sys->i_tuner;
982             if( ioctl( i_fd, VIDIOCGTUNER, &vid_tuner ) < 0 )
983             {
984                 msg_Err( p_demux, "cannot get tuner (%m)" );
985                 goto vdev_failed;
986             }
987             msg_Dbg( p_demux, "tuner %s low=%d high=%d, flags=0x%x "
988                      "mode=0x%x signal=0x%x",
989                      vid_tuner.name, vid_tuner.rangelow, vid_tuner.rangehigh,
990                      vid_tuner.flags, vid_tuner.mode, vid_tuner.signal );
991
992             msg_Dbg( p_demux, "setting tuner %s (%d)",
993                      vid_tuner.name, vid_tuner.tuner );
994
995             /* FIXME FIXME to be checked FIXME FIXME */
996             //vid_tuner.mode = p_sys->i_norm;
997             if( ioctl( i_fd, VIDIOCSTUNER, &vid_tuner ) < 0 )
998             {
999                 msg_Err( p_demux, "cannot set tuner (%m)" );
1000                 goto vdev_failed;
1001             }
1002         }
1003 #endif
1004
1005         /* Show a warning if frequency is < than 30000.
1006          * User is certainly usint old syntax. */
1007
1008
1009         /* set frequency */
1010         if( p_sys->i_frequency >= 0 )
1011         {
1012             int driver_frequency = p_sys->i_frequency * 16 /1000;
1013             if( ioctl( i_fd, VIDIOCSFREQ, &driver_frequency ) < 0 )
1014             {
1015                 msg_Err( p_demux, "cannot set frequency (%m)" );
1016                 goto vdev_failed;
1017             }
1018             msg_Dbg( p_demux, "frequency %d (%d)", p_sys->i_frequency,
1019                                                    driver_frequency );
1020         }
1021     }
1022
1023     /* set audio */
1024     if( vid_channel.flags & VIDEO_VC_AUDIO )
1025     {
1026         struct video_audio      vid_audio;
1027
1028         /* XXX TODO volume, balance, ... */
1029         if( p_sys->i_audio >= 0 )
1030         {
1031             vid_audio.audio = p_sys->i_audio;
1032             if( ioctl( i_fd, VIDIOCGAUDIO, &vid_audio ) < 0 )
1033             {
1034                 msg_Err( p_demux, "cannot get audio (%m)" );
1035                 goto vdev_failed;
1036             }
1037
1038             /* unmute audio */
1039             vid_audio.flags &= ~VIDEO_AUDIO_MUTE;
1040
1041             if( ioctl( i_fd, VIDIOCSAUDIO, &vid_audio ) < 0 )
1042             {
1043                 msg_Err( p_demux, "cannot set audio (%m)" );
1044                 goto vdev_failed;
1045             }
1046         }
1047
1048     }
1049
1050     /* establish basic params with input and norm before feeling width
1051      * or height */
1052     if( p_sys->b_mjpeg )
1053     {
1054         struct quicktime_mjpeg_app1 *p_app1;
1055         int32_t i_offset;
1056
1057         if( ioctl( i_fd, MJPIOC_G_PARAMS, &mjpeg ) < 0 )
1058         {
1059             msg_Err( p_demux, "cannot get mjpeg params (%m)" );
1060             goto vdev_failed;
1061         }
1062         mjpeg.input = p_sys->i_channel;
1063         mjpeg.norm  = p_sys->i_norm;
1064         mjpeg.decimation = p_sys->i_decimation;
1065
1066         if( p_sys->i_width )
1067             mjpeg.img_width = p_sys->i_width / p_sys->i_decimation;
1068         if( p_sys->i_height )
1069             mjpeg.img_height = p_sys->i_height / p_sys->i_decimation;
1070
1071         /* establish Quicktime APP1 marker while we are here */
1072         mjpeg.APPn = 1;
1073         mjpeg.APP_len = 40;
1074
1075         /* aligned */
1076         p_app1 = (struct quicktime_mjpeg_app1 *)mjpeg.APP_data;
1077         p_app1->i_reserved = 0;
1078         p_app1->i_tag = VLC_FOURCC( 'm','j','p','g' );
1079         p_app1->i_field_size = 0;
1080         p_app1->i_padded_field_size = 0;
1081         p_app1->i_next_field = 0;
1082         /* XXX WARNING XXX */
1083         /* these's nothing magic about these values.  We are dangerously
1084          * assuming the encoder card is encoding mjpeg-a and is not throwing
1085          * in marker tags we aren't expecting.  It's bad enough we have to
1086          * search through the jpeg output for every frame we grab just to
1087          * find the first field's end marker, so we take this risk to boost
1088          * performance.
1089          * This is really something the driver could do for us because this
1090          * does conform to standards outside of Apple Quicktime.
1091          */
1092         i_offset = 0x2e;
1093         p_app1->i_DQT_offset = hton32( i_offset );
1094         i_offset = 0xb4;
1095         p_app1->i_DHT_offset = hton32( i_offset );
1096         i_offset = 0x258;
1097         p_app1->i_SOF_offset = hton32( i_offset );
1098         i_offset = 0x26b;
1099         p_app1->i_SOS_offset = hton32( i_offset );
1100         i_offset = 0x279;
1101         p_app1->i_data_offset = hton32( i_offset );
1102
1103         /* SOF and SOS aren't specified by the mjpeg API because they aren't
1104          * optional.  They will be present in the output. */
1105         mjpeg.jpeg_markers = JPEG_MARKER_DHT | JPEG_MARKER_DQT;
1106
1107         if( ioctl( i_fd, MJPIOC_S_PARAMS, &mjpeg ) < 0 )
1108         {
1109             msg_Err( p_demux, "cannot set mjpeg params (%m)" );
1110             goto vdev_failed;
1111         }
1112
1113         p_sys->i_width = mjpeg.img_width * mjpeg.HorDcm;
1114         p_sys->i_height = mjpeg.img_height * mjpeg.VerDcm *
1115             mjpeg.field_per_buff;
1116     }
1117
1118     /* fix width/height */
1119     if( !p_sys->b_mjpeg && ( p_sys->i_width == 0 || p_sys->i_height == 0 ) )
1120     {
1121         struct video_window vid_win;
1122
1123         if( ioctl( i_fd, VIDIOCGWIN, &vid_win ) < 0 )
1124         {
1125             msg_Err( p_demux, "cannot get win (%m)" );
1126             goto vdev_failed;
1127         }
1128         p_sys->i_width  = vid_win.width;
1129         p_sys->i_height = vid_win.height;
1130
1131         if( !p_sys->i_width || !p_sys->i_height )
1132         {
1133             p_sys->i_width = p_sys->vid_cap.maxwidth;
1134             p_sys->i_height = p_sys->vid_cap.maxheight;
1135         }
1136
1137         if( !p_sys->i_width || !p_sys->i_height )
1138         {
1139             msg_Err( p_demux, "invalid video size (%ix%i)",
1140                      p_sys->i_width, p_sys->i_height );
1141             goto vdev_failed;
1142         }
1143
1144         msg_Dbg( p_demux, "will use %dx%d", p_sys->i_width, p_sys->i_height );
1145     }
1146
1147     if( !p_sys->b_mjpeg )
1148     {
1149         /* set hue/color/.. */
1150         if( ioctl( i_fd, VIDIOCGPICT, &p_sys->vid_picture ) == 0 )
1151         {
1152             struct video_picture vid_picture = p_sys->vid_picture;
1153
1154             if( p_sys->i_brightness >= 0 && p_sys->i_brightness < 65536 )
1155             {
1156                 vid_picture.brightness = p_sys->i_brightness;
1157             }
1158             if( p_sys->i_colour >= 0 && p_sys->i_colour < 65536 )
1159             {
1160                 vid_picture.colour = p_sys->i_colour;
1161             }
1162             if( p_sys->i_hue >= 0 && p_sys->i_hue < 65536 )
1163             {
1164                 vid_picture.hue = p_sys->i_hue;
1165             }
1166             if( p_sys->i_contrast  >= 0 && p_sys->i_contrast < 65536 )
1167             {
1168                 vid_picture.contrast = p_sys->i_contrast;
1169             }
1170             if( ioctl( i_fd, VIDIOCSPICT, &vid_picture ) == 0 )
1171             {
1172                 msg_Dbg( p_demux, "v4l device uses brightness: %d",
1173                          vid_picture.brightness );
1174                 msg_Dbg( p_demux, "v4l device uses colour: %d",
1175                          vid_picture.colour );
1176                 msg_Dbg( p_demux, "v4l device uses hue: %d", vid_picture.hue );
1177                 msg_Dbg( p_demux, "v4l device uses contrast: %d",
1178                          vid_picture.contrast );
1179                 p_sys->vid_picture = vid_picture;
1180             }
1181         }
1182
1183         /* Find out video format used by device */
1184         if( ioctl( i_fd, VIDIOCGPICT, &p_sys->vid_picture ) == 0 )
1185         {
1186             struct video_picture vid_picture = p_sys->vid_picture;
1187             char *psz;
1188             int i;
1189
1190             p_sys->i_fourcc = 0;
1191
1192             psz = var_CreateGetString( p_demux, "v4l-chroma" );
1193             if( strlen( psz ) >= 4 )
1194             {
1195                 vid_picture.palette = 0;
1196                 int i_chroma = VLC_FOURCC( psz[0], psz[1], psz[2], psz[3] );
1197
1198                 /* Find out v4l chroma code */
1199                 for( i = 0; v4lchroma_to_fourcc[i].i_v4l != 0; i++ )
1200                 {
1201                     if( v4lchroma_to_fourcc[i].i_fourcc == i_chroma )
1202                     {
1203                         vid_picture.palette = v4lchroma_to_fourcc[i].i_v4l;
1204                         break;
1205                     }
1206                 }
1207             }
1208             free( psz );
1209
1210             if( vid_picture.palette &&
1211                 !ioctl( i_fd, VIDIOCSPICT, &vid_picture ) )
1212             {
1213                 p_sys->vid_picture = vid_picture;
1214             }
1215             else
1216             {
1217                 /* Try to set the format to something easy to encode */
1218                 vid_picture.palette = VIDEO_PALETTE_YUV420P;
1219                 if( ioctl( i_fd, VIDIOCSPICT, &vid_picture ) == 0 )
1220                 {
1221                     p_sys->vid_picture = vid_picture;
1222                 }
1223                 else
1224                 {
1225                     vid_picture.palette = VIDEO_PALETTE_YUV422P;
1226                     if( ioctl( i_fd, VIDIOCSPICT, &vid_picture ) == 0 )
1227                     {
1228                         p_sys->vid_picture = vid_picture;
1229                     }
1230                 }
1231             }
1232
1233             /* Find out final format */
1234             for( i = 0; v4lchroma_to_fourcc[i].i_v4l != 0; i++ )
1235             {
1236                 if( v4lchroma_to_fourcc[i].i_v4l == p_sys->vid_picture.palette)
1237                 {
1238                     p_sys->i_fourcc = v4lchroma_to_fourcc[i].i_fourcc;
1239                     break;
1240                 }
1241             }
1242         }
1243         else
1244         {
1245             msg_Err( p_demux, "ioctl VIDIOCGPICT failed" );
1246             goto vdev_failed;
1247         }
1248     }
1249
1250     if( p_sys->b_mjpeg )
1251     {
1252         int i;
1253
1254         p_sys->mjpeg_buffers.count = 8;
1255         p_sys->mjpeg_buffers.size = MJPEG_BUFFER_SIZE;
1256
1257         if( ioctl( i_fd, MJPIOC_REQBUFS, &p_sys->mjpeg_buffers ) < 0 )
1258         {
1259             msg_Err( p_demux, "mmap unsupported" );
1260             goto vdev_failed;
1261         }
1262
1263         p_sys->p_video_mmap = mmap( 0,
1264                 p_sys->mjpeg_buffers.size * p_sys->mjpeg_buffers.count,
1265                 PROT_READ | PROT_WRITE, MAP_SHARED, i_fd, 0 );
1266         if( p_sys->p_video_mmap == MAP_FAILED )
1267         {
1268             msg_Err( p_demux, "mmap failed" );
1269             goto vdev_failed;
1270         }
1271
1272         p_sys->i_fourcc  = VLC_FOURCC( 'm','j','p','g' );
1273         p_sys->i_frame_pos = -1;
1274
1275         /* queue up all the frames */
1276         for( i = 0; i < (int)p_sys->mjpeg_buffers.count; i++ )
1277         {
1278             if( ioctl( i_fd, MJPIOC_QBUF_CAPT, &i ) < 0 )
1279             {
1280                 msg_Err( p_demux, "unable to queue frame" );
1281                 goto vdev_failed;
1282             }
1283         }
1284     }
1285     else
1286     {
1287         /* Fill in picture_t fields */
1288         vout_InitPicture( VLC_OBJECT(p_demux), &p_sys->pic, p_sys->i_fourcc,
1289                           p_sys->i_width, p_sys->i_height, p_sys->i_width *
1290                           VOUT_ASPECT_FACTOR / p_sys->i_height );
1291         if( !p_sys->pic.i_planes )
1292         {
1293             msg_Err( p_demux, "unsupported chroma" );
1294             goto vdev_failed;
1295         }
1296         p_sys->i_video_frame_size = 0;
1297         for( i = 0; i < p_sys->pic.i_planes; i++ )
1298         {
1299             p_sys->i_video_frame_size += p_sys->pic.p[i].i_visible_lines *
1300               p_sys->pic.p[i].i_visible_pitch;
1301         }
1302
1303         msg_Dbg( p_demux, "v4l device uses frame size: %i",
1304                  p_sys->i_video_frame_size );
1305         msg_Dbg( p_demux, "v4l device uses chroma: %4.4s",
1306                 (char*)&p_sys->i_fourcc );
1307
1308         /* Allocate mmap buffer */
1309         if( ioctl( i_fd, VIDIOCGMBUF, &p_sys->vid_mbuf ) < 0 )
1310         {
1311             msg_Err( p_demux, "mmap unsupported" );
1312             goto vdev_failed;
1313         }
1314
1315         p_sys->p_video_mmap = mmap( 0, p_sys->vid_mbuf.size,
1316                                     PROT_READ|PROT_WRITE, MAP_SHARED,
1317                                     i_fd, 0 );
1318         if( p_sys->p_video_mmap == MAP_FAILED )
1319         {
1320             /* FIXME -> normal read */
1321             msg_Err( p_demux, "mmap failed" );
1322             goto vdev_failed;
1323         }
1324
1325         /* init grabbing */
1326         p_sys->vid_mmap.frame  = 0;
1327         p_sys->vid_mmap.width  = p_sys->i_width;
1328         p_sys->vid_mmap.height = p_sys->i_height;
1329         p_sys->vid_mmap.format = p_sys->vid_picture.palette;
1330         if( ioctl( i_fd, VIDIOCMCAPTURE, &p_sys->vid_mmap ) < 0 )
1331         {
1332             msg_Warn( p_demux, "%4.4s refused", (char*)&p_sys->i_fourcc );
1333             msg_Err( p_demux, "chroma selection failed" );
1334             goto vdev_failed;
1335         }
1336     }
1337     return i_fd;
1338
1339 vdev_failed:
1340
1341     if( i_fd >= 0 ) close( i_fd );
1342     return -1;
1343 }
1344
1345 /*****************************************************************************
1346  * OpenAudioDev:
1347  *****************************************************************************/
1348 static int OpenAudioDev( demux_t *p_demux, char *psz_device )
1349 {
1350     demux_sys_t *p_sys = p_demux->p_sys;
1351     int i_fd, i_format;
1352
1353     if( (i_fd = open( psz_device, O_RDONLY | O_NONBLOCK )) < 0 )
1354     {
1355         msg_Err( p_demux, "cannot open audio device (%m)" );
1356         goto adev_fail;
1357     }
1358
1359     i_format = AFMT_S16_LE;
1360     if( ioctl( i_fd, SNDCTL_DSP_SETFMT, &i_format ) < 0
1361         || i_format != AFMT_S16_LE )
1362     {
1363         msg_Err( p_demux, "cannot set audio format (16b little endian) "
1364                  "(%m)" );
1365         goto adev_fail;
1366     }
1367
1368     if( ioctl( i_fd, SNDCTL_DSP_STEREO,
1369                &p_sys->b_stereo ) < 0 )
1370     {
1371         msg_Err( p_demux, "cannot set audio channels count (%m)" );
1372         goto adev_fail;
1373     }
1374
1375     if( ioctl( i_fd, SNDCTL_DSP_SPEED,
1376                &p_sys->i_sample_rate ) < 0 )
1377     {
1378         msg_Err( p_demux, "cannot set audio sample rate (%m)" );
1379         goto adev_fail;
1380     }
1381
1382     msg_Dbg( p_demux, "opened adev=`%s' %s %dHz",
1383              psz_device, p_sys->b_stereo ? "stereo" : "mono",
1384              p_sys->i_sample_rate );
1385
1386     p_sys->i_audio_max_frame_size = 6 * 1024;
1387
1388     return i_fd;
1389
1390  adev_fail:
1391
1392     if( i_fd >= 0 ) close( i_fd );
1393     return -1;
1394 }
1395
1396 /*****************************************************************************
1397  * GrabAudio: grab audio
1398  *****************************************************************************/
1399 static block_t *GrabAudio( demux_t *p_demux )
1400 {
1401     demux_sys_t *p_sys = p_demux->p_sys;
1402     struct audio_buf_info buf_info;
1403     int i_read, i_correct;
1404     block_t *p_block;
1405
1406     if( p_sys->p_block_audio ) p_block = p_sys->p_block_audio;
1407     else p_block = block_New( p_demux, p_sys->i_audio_max_frame_size );
1408
1409     if( !p_block )
1410     {
1411         msg_Warn( p_demux, "cannot get block" );
1412         return 0;
1413     }
1414
1415     p_sys->p_block_audio = p_block;
1416
1417     i_read = read( p_sys->fd_audio, p_block->p_buffer,
1418                    p_sys->i_audio_max_frame_size );
1419
1420     if( i_read <= 0 ) return 0;
1421
1422     p_block->i_buffer = i_read;
1423     p_sys->p_block_audio = 0;
1424
1425     /* Correct the date because of kernel buffering */
1426     i_correct = i_read;
1427     if( ioctl( p_sys->fd_audio, SNDCTL_DSP_GETISPACE, &buf_info ) == 0 )
1428     {
1429         i_correct += buf_info.bytes;
1430     }
1431
1432     p_block->i_pts = p_block->i_dts =
1433         mdate() - INT64_C(1000000) * (mtime_t)i_correct /
1434         2 / ( p_sys->b_stereo ? 2 : 1) / p_sys->i_sample_rate;
1435
1436     return p_block;
1437 }
1438
1439 /*****************************************************************************
1440  * GrabVideo:
1441  *****************************************************************************/
1442 static uint8_t *GrabCapture( demux_t *p_demux )
1443 {
1444     demux_sys_t *p_sys = p_demux->p_sys;
1445     int i_captured_frame = p_sys->i_frame_pos;
1446
1447     p_sys->vid_mmap.frame = (p_sys->i_frame_pos + 1) % p_sys->vid_mbuf.frames;
1448
1449     while( ioctl( p_sys->fd_video, VIDIOCMCAPTURE, &p_sys->vid_mmap ) < 0 )
1450     {
1451         if( errno != EAGAIN )
1452         {
1453             msg_Err( p_demux, "failed capturing new frame" );
1454             return NULL;
1455         }
1456
1457         if( !vlc_object_alive (p_demux) )
1458         {
1459             return NULL;
1460         }
1461
1462         msg_Dbg( p_demux, "grab failed, trying again" );
1463     }
1464
1465     while( ioctl(p_sys->fd_video, VIDIOCSYNC, &p_sys->i_frame_pos) < 0 )
1466     {
1467         if( errno != EAGAIN && errno != EINTR )
1468         {
1469             msg_Err( p_demux, "failed syncing new frame" );
1470             return NULL;
1471         }
1472     }
1473
1474     p_sys->i_frame_pos = p_sys->vid_mmap.frame;
1475     /* leave i_video_frame_size alone */
1476     return p_sys->p_video_mmap + p_sys->vid_mbuf.offsets[i_captured_frame];
1477 }
1478
1479 static uint8_t *GrabMJPEG( demux_t *p_demux )
1480 {
1481     demux_sys_t *p_sys = p_demux->p_sys;
1482     struct mjpeg_sync sync;
1483     uint8_t *p_frame, *p_field, *p;
1484     uint16_t tag;
1485     uint32_t i_size;
1486     struct quicktime_mjpeg_app1 *p_app1 = NULL;
1487
1488     /* re-queue the last frame we sync'd */
1489     if( p_sys->i_frame_pos != -1 )
1490     {
1491         while( ioctl( p_sys->fd_video, MJPIOC_QBUF_CAPT,
1492                                        &p_sys->i_frame_pos ) < 0 )
1493         {
1494             if( errno != EAGAIN && errno != EINTR )
1495             {
1496                 msg_Err( p_demux, "failed capturing new frame" );
1497                 return NULL;
1498             }
1499         }
1500     }
1501
1502     /* sync on the next frame */
1503     while( ioctl( p_sys->fd_video, MJPIOC_SYNC, &sync ) < 0 )
1504     {
1505         if( errno != EAGAIN && errno != EINTR )
1506         {
1507             msg_Err( p_demux, "failed syncing new frame" );
1508             return NULL;
1509         }
1510     }
1511
1512     p_sys->i_frame_pos = sync.frame;
1513     p_frame = p_sys->p_video_mmap + p_sys->mjpeg_buffers.size * sync.frame;
1514
1515     /* p_frame now points to the data.  fix up the Quicktime APP1 marker */
1516     tag = 0xffd9;
1517     tag = hton16( tag );
1518     p_field = p_frame;
1519
1520     /* look for EOI */
1521     p = memmem( p_field, sync.length, &tag, 2 );
1522
1523     if( p )
1524     {
1525         p += 2; /* data immediately following EOI */
1526         /* UNALIGNED! */
1527         p_app1 = (struct quicktime_mjpeg_app1 *)(p_field + 6);
1528
1529         i_size = ((uint32_t)(p - p_field));
1530         i_size = hton32( i_size );
1531         memcpy( &p_app1->i_field_size, &i_size, 4 );
1532
1533         while( *p == 0xff && *(p+1) == 0xff )
1534             p++;
1535
1536         i_size = ((uint32_t)(p - p_field));
1537         i_size = hton32( i_size );
1538         memcpy( &p_app1->i_padded_field_size, &i_size, 4 );
1539     }
1540
1541     tag = 0xffd8;
1542     tag = hton16( tag );
1543     p_field = memmem( p, sync.length - (size_t)(p - p_frame), &tag, 2 );
1544
1545     if( p_field )
1546     {
1547         i_size = (uint32_t)(p_field - p_frame);
1548         i_size = hton32( i_size );
1549         memcpy( &p_app1->i_next_field, &i_size, 4 );
1550
1551         /* UNALIGNED! */
1552         p_app1 = (struct quicktime_mjpeg_app1 *)(p_field + 6);
1553         tag = 0xffd9;
1554         tag = hton16( tag );
1555         p = memmem( p_field, sync.length - (size_t)(p_field - p_frame),
1556                 &tag, 2 );
1557
1558         if( !p )
1559         {
1560             /* sometimes the second field doesn't have the EOI.  just put it
1561              * there
1562              */
1563             p = p_frame + sync.length;
1564             memcpy( p, &tag, 2 );
1565             sync.length += 2;
1566         }
1567
1568         p += 2;
1569         i_size = (uint32_t)(p - p_field);
1570         i_size = hton32( i_size );
1571         memcpy( &p_app1->i_field_size, &i_size, 4 );
1572         i_size = (uint32_t)(sync.length - (uint32_t)(p_field - p_frame));
1573         i_size = hton32( i_size );
1574         memcpy( &p_app1->i_padded_field_size, &i_size, 4 );
1575     }
1576
1577     p_sys->i_video_frame_size = sync.length;
1578     return p_frame;
1579 }
1580
1581 static block_t *GrabVideo( demux_t *p_demux )
1582 {
1583     demux_sys_t *p_sys = p_demux->p_sys;
1584     uint8_t     *p_frame;
1585     block_t     *p_block;
1586
1587     if( p_sys->f_fps >= 0.1 && p_sys->i_video_pts > 0 )
1588     {
1589         mtime_t i_dur = (mtime_t)((double)1000000 / (double)p_sys->f_fps);
1590
1591         /* Did we wait long enough ? (frame rate reduction) */
1592         if( p_sys->i_video_pts + i_dur > mdate() ) return 0;
1593     }
1594
1595     if( p_sys->b_mjpeg ) p_frame = GrabMJPEG( p_demux );
1596     else p_frame = GrabCapture( p_demux );
1597
1598     if( !p_frame ) return 0;
1599
1600     if( !( p_block = block_New( p_demux, p_sys->i_video_frame_size ) ) )
1601     {
1602         msg_Warn( p_demux, "cannot get block" );
1603         return 0;
1604     }
1605
1606     memcpy( p_block->p_buffer, p_frame, p_sys->i_video_frame_size );
1607     p_sys->i_video_pts = p_block->i_pts = p_block->i_dts = mdate();
1608
1609     return p_block;
1610 }