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