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