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