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