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