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