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