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