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