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