]> git.sesse.net Git - vlc/blob - modules/access/v4l/v4l.c
* ALL: use i_visible_lines in plane_t.
[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
355         msg_Dbg( p_demux, "added new video es %4.4s %dx%d",
356                  (char*)&fmt.i_codec, fmt.video.i_width, fmt.video.i_height );
357         p_sys->p_es_video = es_out_Add( p_demux->out, &fmt );
358     }
359
360     if( p_sys->fd_audio >= 0 )
361     {
362         es_format_t fmt;
363         es_format_Init( &fmt, AUDIO_ES, VLC_FOURCC('a','r','a','w') );
364
365         fmt.audio.i_channels = p_sys->b_stereo ? 2 : 1;
366         fmt.audio.i_rate = p_sys->i_sample_rate;
367         fmt.audio.i_bitspersample = 16; // FIXME ?
368         fmt.audio.i_blockalign = fmt.audio.i_channels *
369             fmt.audio.i_bitspersample / 8;
370         fmt.i_bitrate = fmt.audio.i_channels * fmt.audio.i_rate *
371             fmt.audio.i_bitspersample;
372
373         msg_Dbg( p_demux, "new audio es %d channels %dHz",
374                  fmt.audio.i_channels, fmt.audio.i_rate );
375
376         p_sys->p_es_audio = es_out_Add( p_demux->out, &fmt );
377     }
378
379     /* Update default_pts to a suitable value for access */
380     var_Create( p_demux, "v4l-caching", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
381
382     return VLC_SUCCESS;
383 }
384
385 /*****************************************************************************
386  * Close: close device, free resources
387  *****************************************************************************/
388 static void Close( vlc_object_t *p_this )
389 {
390     demux_t     *p_demux = (demux_t *)p_this;
391     demux_sys_t *p_sys   = p_demux->p_sys;
392
393     if( p_sys->psz_device ) free( p_sys->psz_device );
394     if( p_sys->psz_vdev )   free( p_sys->psz_vdev );
395     if( p_sys->psz_adev )   free( p_sys->psz_adev );
396     if( p_sys->fd_video >= 0 ) close( p_sys->fd_video );
397     if( p_sys->fd_audio >= 0 ) close( p_sys->fd_audio );
398     if( p_sys->p_block_audio ) block_Release( p_sys->p_block_audio );
399
400     if( p_sys->b_mjpeg )
401     {
402         int i_noframe = -1;
403         ioctl( p_sys->fd_video, MJPIOC_QBUF_CAPT, &i_noframe );
404     }
405
406     if( p_sys->p_video_mmap && p_sys->p_video_mmap != MAP_FAILED )
407     {
408         if( p_sys->b_mjpeg )
409             munmap( p_sys->p_video_mmap, p_sys->mjpeg_buffers.size *
410                     p_sys->mjpeg_buffers.count );
411         else
412             munmap( p_sys->p_video_mmap, p_sys->vid_mbuf.size );
413     }
414
415     free( p_sys );
416 }
417
418 /*****************************************************************************
419  * Control:
420  *****************************************************************************/
421 static int Control( demux_t *p_demux, int i_query, va_list args )
422 {
423     vlc_bool_t *pb;
424     int64_t    *pi64;
425
426     switch( i_query )
427     {
428         /* Special for access_demux */
429         case DEMUX_CAN_PAUSE:
430         case DEMUX_SET_PAUSE_STATE:
431         case DEMUX_CAN_CONTROL_PACE:
432             pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
433             *pb = VLC_FALSE;
434             return VLC_SUCCESS;
435
436         case DEMUX_GET_PTS_DELAY:
437             pi64 = (int64_t*)va_arg( args, int64_t * );
438             *pi64 = (int64_t)var_GetInteger( p_demux, "v4l-caching" ) * 1000;
439             return VLC_SUCCESS;
440
441         case DEMUX_GET_TIME:
442             pi64 = (int64_t*)va_arg( args, int64_t * );
443             *pi64 = mdate();
444             return VLC_SUCCESS;
445
446         /* TODO implement others */
447         default:
448             return VLC_EGENERIC;
449     }
450
451     return VLC_EGENERIC;
452 }
453
454 /*****************************************************************************
455  * Demux:
456  *****************************************************************************/
457 static int Demux( demux_t *p_demux )
458 {
459     demux_sys_t *p_sys = p_demux->p_sys;
460     es_out_id_t  *p_es = p_sys->p_es_audio;
461     block_t *p_block = NULL;
462
463     /* Try grabbing audio frames first */
464     if( p_sys->fd_audio < 0 || !( p_block = GrabAudio( p_demux ) ) )
465     {
466         /* Try grabbing video frame */
467         p_es = p_sys->p_es_video;
468         if( p_sys->fd_video > 0 ) p_block = GrabVideo( p_demux );
469     }
470
471     if( !p_block )
472     {
473         /* Sleep so we do not consume all the cpu, 10ms seems
474          * like a good value (100fps) */
475         msleep( 10000 );
476         return 1;
477     }
478
479     es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_block->i_pts );
480     es_out_Send( p_demux->out, p_es, p_block );
481
482     return 1;
483 }
484
485 /*****************************************************************************
486  * ParseMRL: parse the options contained in the MRL
487  *****************************************************************************/
488 static void ParseMRL( demux_t *p_demux )
489 {
490     demux_sys_t *p_sys = p_demux->p_sys;
491
492     char *psz_dup = strdup( p_demux->psz_path );
493     char *psz_parser = psz_dup;
494
495     while( *psz_parser && *psz_parser != ':' )
496     {
497         psz_parser++;
498     }
499
500     if( *psz_parser == ':' )
501     {
502         /* read options */
503         for( ;; )
504         {
505             *psz_parser++ = '\0';
506             if( !strncmp( psz_parser, "channel=", strlen( "channel=" ) ) )
507             {
508                 p_sys->i_channel = strtol( psz_parser + strlen( "channel=" ),
509                                            &psz_parser, 0 );
510             }
511             else if( !strncmp( psz_parser, "norm=", strlen( "norm=" ) ) )
512             {
513                 psz_parser += strlen( "norm=" );
514                 if( !strncmp( psz_parser, "pal", strlen( "pal" ) ) )
515                 {
516                     p_sys->i_norm = VIDEO_MODE_PAL;
517                     psz_parser += strlen( "pal" );
518                 }
519                 else if( !strncmp( psz_parser, "ntsc", strlen( "ntsc" ) ) )
520                 {
521                     p_sys->i_norm = VIDEO_MODE_NTSC;
522                     psz_parser += strlen( "ntsc" );
523                 }
524                 else if( !strncmp( psz_parser, "secam", strlen( "secam" ) ) )
525                 {
526                     p_sys->i_norm = VIDEO_MODE_SECAM;
527                     psz_parser += strlen( "secam" );
528                 }
529                 else if( !strncmp( psz_parser, "auto", strlen( "auto" ) ) )
530                 {
531                     p_sys->i_norm = VIDEO_MODE_AUTO;
532                     psz_parser += strlen( "auto" );
533                 }
534                 else
535                 {
536                     p_sys->i_norm = strtol( psz_parser, &psz_parser, 0 );
537                 }
538             }
539             else if( !strncmp( psz_parser, "frequency=",
540                                strlen( "frequency=" ) ) )
541             {
542                 p_sys->i_frequency =
543                     strtol( psz_parser + strlen( "frequency=" ),
544                             &psz_parser, 0 );
545                 if( p_sys->i_frequency < 30000 )
546                 {
547                     msg_Warn( p_demux, "v4l syntax has changed : "
548                               "'frequency' is now channel frequency in kHz");
549                 }
550             }
551             else if( !strncmp( psz_parser, "audio=", strlen( "audio=" ) ) )
552             {
553                 p_sys->i_audio = strtol( psz_parser + strlen( "audio=" ),
554                                          &psz_parser, 0 );
555             }
556             else if( !strncmp( psz_parser, "size=", strlen( "size=" ) ) )
557             {
558                 psz_parser += strlen( "size=" );
559                 if( !strncmp( psz_parser, "subqcif", strlen( "subqcif" ) ) )
560                 {
561                     p_sys->i_width  = 128;
562                     p_sys->i_height = 96;
563                 }
564                 else if( !strncmp( psz_parser, "qsif", strlen( "qsif" ) ) )
565                 {
566                     p_sys->i_width  = 160;
567                     p_sys->i_height = 120;
568                 }
569                 else if( !strncmp( psz_parser, "qcif", strlen( "qcif" ) ) )
570                 {
571                     p_sys->i_width  = 176;
572                     p_sys->i_height = 144;
573                 }
574                 else if( !strncmp( psz_parser, "sif", strlen( "sif" ) ) )
575                 {
576                     p_sys->i_width  = 320;
577                     p_sys->i_height = 244;
578                 }
579                 else if( !strncmp( psz_parser, "cif", strlen( "cif" ) ) )
580                 {
581                     p_sys->i_width  = 352;
582                     p_sys->i_height = 288;
583                 }
584                 else if( !strncmp( psz_parser, "vga", strlen( "vga" ) ) )
585                 {
586                     p_sys->i_width  = 640;
587                     p_sys->i_height = 480;
588                 }
589                 else
590                 {
591                     /* widthxheight */
592                     p_sys->i_width = strtol( psz_parser, &psz_parser, 0 );
593                     if( *psz_parser == 'x' || *psz_parser == 'X')
594                     {
595                         p_sys->i_height = strtol( psz_parser + 1,
596                                                   &psz_parser, 0 );
597                     }
598                     msg_Dbg( p_demux, "WxH %dx%d", p_sys->i_width,
599                              p_sys->i_height );
600                 }
601             }
602             else if( !strncmp( psz_parser, "brightness=", strlen( "brightness=" ) ) )
603             {
604                 p_sys->i_brightness = strtol( psz_parser + strlen( "brightness=" ),
605                                               &psz_parser, 0 );
606             }
607             else if( !strncmp( psz_parser, "colour=", strlen( "colour=" ) ) )
608             {
609                 p_sys->i_colour = strtol( psz_parser + strlen( "colour=" ),
610                                           &psz_parser, 0 );
611             }
612             else if( !strncmp( psz_parser, "hue=", strlen( "hue=" ) ) )
613             {
614                 p_sys->i_hue = strtol( psz_parser + strlen( "hue=" ), 
615                                        &psz_parser, 0 );
616             }
617             else if( !strncmp( psz_parser, "contrast=", strlen( "contrast=" ) ) )
618             {
619                 p_sys->i_contrast = strtol( psz_parser + strlen( "contrast=" ),
620                                             &psz_parser, 0 );
621             }
622             else if( !strncmp( psz_parser, "tuner=", strlen( "tuner=" ) ) )
623             {
624                 p_sys->i_tuner = strtol( psz_parser + strlen( "tuner=" ),
625                                          &psz_parser, 0 );
626             }
627             else if( !strncmp( psz_parser, "adev=", strlen( "adev=" ) ) )
628             {
629                 int  i_len;
630
631                 psz_parser += strlen( "adev=" );
632                 if( strchr( psz_parser, ':' ) )
633                 {
634                     i_len = strchr( psz_parser, ':' ) - psz_parser;
635                 }
636                 else
637                 {
638                     i_len = strlen( psz_parser );
639                 }
640
641                 p_sys->psz_adev = strndup( psz_parser, i_len );
642
643                 psz_parser += i_len;
644             }
645             else if( !strncmp( psz_parser, "samplerate=",
646                                strlen( "samplerate=" ) ) )
647             {
648                 p_sys->i_sample_rate =
649                     strtol( psz_parser + strlen( "samplerate=" ),
650                             &psz_parser, 0 );
651             }
652             else if( !strncmp( psz_parser, "stereo", strlen( "stereo" ) ) )
653             {
654                 psz_parser += strlen( "stereo" );
655
656                 p_sys->b_stereo = VLC_TRUE;
657             }
658             else if( !strncmp( psz_parser, "mono", strlen( "mono" ) ) )
659             {
660                 psz_parser += strlen( "mono" );
661
662                 p_sys->b_stereo = VLC_FALSE;
663             }
664             else if( !strncmp( psz_parser, "mjpeg", strlen( "mjpeg" ) ) )
665             {
666                 psz_parser += strlen( "mjpeg" );
667
668                 p_sys->b_mjpeg = VLC_TRUE;
669             }
670             else if( !strncmp( psz_parser, "decimation=",
671                         strlen( "decimation=" ) ) )
672             {
673                 p_sys->i_decimation =
674                     strtol( psz_parser + strlen( "decimation=" ),
675                             &psz_parser, 0 );
676             }
677             else if( !strncmp( psz_parser, "quality=",
678                         strlen( "quality=" ) ) )
679             {
680                 p_sys->i_quality =
681                     strtol( psz_parser + strlen( "quality=" ),
682                             &psz_parser, 0 );
683             }
684             else if( !strncmp( psz_parser, "fps=", strlen( "fps=" ) ) )
685             {
686                 p_sys->f_fps = strtof( psz_parser + strlen( "fps=" ),
687                                        &psz_parser );
688             }
689             else
690             {
691                 msg_Warn( p_demux, "unknown option" );
692             }
693
694             while( *psz_parser && *psz_parser != ':' )
695             {
696                 psz_parser++;
697             }
698
699             if( *psz_parser == '\0' )
700             {
701                 break;
702             }
703         }
704     }
705
706     if( *psz_dup )
707     {
708         p_sys->psz_device = strdup( psz_dup );
709     }
710     if( psz_dup ) free( psz_dup );
711 }
712
713 /*****************************************************************************
714  * OpenVideoDev:
715  *****************************************************************************/
716 static int OpenVideoDev( demux_t *p_demux, char *psz_device )
717 {
718     demux_sys_t *p_sys = p_demux->p_sys;
719     int i_fd;
720
721     struct video_channel vid_channel;
722     struct mjpeg_params mjpeg;
723     int i;
724
725     if( ( i_fd = open( psz_device, O_RDWR ) ) < 0 )
726     {
727         msg_Err( p_demux, "cannot open device (%s)", strerror( errno ) );
728         goto vdev_failed;
729     }
730
731     if( ioctl( i_fd, VIDIOCGCAP, &p_sys->vid_cap ) < 0 )
732     {
733         msg_Err( p_demux, "cannot get capabilities (%s)", strerror( errno ) );
734         goto vdev_failed;
735     }
736
737     msg_Dbg( p_demux,
738              "V4L device %s %d channels %d audios %d < w < %d %d < h < %d",
739              p_sys->vid_cap.name,
740              p_sys->vid_cap.channels,
741              p_sys->vid_cap.audios,
742              p_sys->vid_cap.minwidth,  p_sys->vid_cap.maxwidth,
743              p_sys->vid_cap.minheight, p_sys->vid_cap.maxheight );
744
745     if( p_sys->i_channel < 0 || p_sys->i_channel >= p_sys->vid_cap.channels )
746     {
747         msg_Dbg( p_demux, "invalid channel, falling back on channel 0" );
748         p_sys->i_channel = 0;
749     }
750     if( p_sys->i_audio >= p_sys->vid_cap.audios )
751     {
752         msg_Dbg( p_demux, "invalid audio, falling back with no audio" );
753         p_sys->i_audio = -1;
754     }
755
756     if( p_sys->i_width < p_sys->vid_cap.minwidth ||
757         p_sys->i_width > p_sys->vid_cap.maxwidth )
758     {
759         msg_Dbg( p_demux, "invalid width %i", p_sys->i_width );
760         p_sys->i_width = 0;
761     }
762     if( p_sys->i_height < p_sys->vid_cap.minheight ||
763         p_sys->i_height > p_sys->vid_cap.maxheight )
764     {
765         msg_Dbg( p_demux, "invalid height %i", p_sys->i_height );
766         p_sys->i_height = 0;
767     }
768
769     if( !( p_sys->vid_cap.type & VID_TYPE_CAPTURE ) )
770     {
771         msg_Err( p_demux, "cannot grab" );
772         goto vdev_failed;
773     }
774
775     vid_channel.channel = p_sys->i_channel;
776     if( ioctl( i_fd, VIDIOCGCHAN, &vid_channel ) < 0 )
777     {
778         msg_Err( p_demux, "cannot get channel infos (%s)",
779                           strerror( errno ) );
780         goto vdev_failed;
781     }
782     msg_Dbg( p_demux,
783              "setting channel %s(%d) %d tuners flags=0x%x type=0x%x norm=0x%x",
784              vid_channel.name, vid_channel.channel, vid_channel.tuners,
785              vid_channel.flags, vid_channel.type, vid_channel.norm );
786
787     if( p_sys->i_tuner >= vid_channel.tuners )
788     {
789         msg_Dbg( p_demux, "invalid tuner, falling back on tuner 0" );
790         p_sys->i_tuner = 0;
791     }
792
793     vid_channel.norm = p_sys->i_norm;
794     if( ioctl( i_fd, VIDIOCSCHAN, &vid_channel ) < 0 )
795     {
796         msg_Err( p_demux, "cannot set channel (%s)", strerror( errno ) );
797         goto vdev_failed;
798     }
799
800     if( vid_channel.flags & VIDEO_VC_TUNER )
801     {
802
803         /* set tuner */
804 #if 0
805         struct video_tuner vid_tuner;
806         if( p_sys->i_tuner >= 0 )
807         {
808             vid_tuner.tuner = p_sys->i_tuner;
809             if( ioctl( i_fd, VIDIOCGTUNER, &vid_tuner ) < 0 )
810             {
811                 msg_Err( p_demux, "cannot get tuner (%s)", strerror( errno ) );
812                 goto vdev_failed;
813             }
814             msg_Dbg( p_demux, "tuner %s low=%d high=%d, flags=0x%x "
815                      "mode=0x%x signal=0x%x",
816                      vid_tuner.name, vid_tuner.rangelow, vid_tuner.rangehigh,
817                      vid_tuner.flags, vid_tuner.mode, vid_tuner.signal );
818
819             msg_Dbg( p_demux, "setting tuner %s (%d)",
820                      vid_tuner.name, vid_tuner.tuner );
821
822             /* FIXME FIXME to be checked FIXME FIXME */
823             //vid_tuner.mode = p_sys->i_norm;
824             if( ioctl( i_fd, VIDIOCSTUNER, &vid_tuner ) < 0 )
825             {
826                 msg_Err( p_demux, "cannot set tuner (%s)", strerror( errno ) );
827                 goto vdev_failed;
828             }
829         }
830 #endif
831
832         /* Show a warning if frequency is < than 30000.
833          * User is certainly usint old syntax. */
834
835
836         /* set frequency */
837         if( p_sys->i_frequency >= 0 )
838         {
839             int driver_frequency = p_sys->i_frequency * 16 /1000;
840             if( ioctl( i_fd, VIDIOCSFREQ, &driver_frequency ) < 0 )
841             {
842                 msg_Err( p_demux, "cannot set frequency (%s)",
843                                   strerror( errno ) );
844                 goto vdev_failed;
845             }
846             msg_Dbg( p_demux, "frequency %d (%d)", p_sys->i_frequency,
847                                                    driver_frequency );
848         }
849     }
850
851     /* set audio */
852     if( vid_channel.flags & VIDEO_VC_AUDIO )
853     {
854         struct video_audio      vid_audio;
855
856         /* XXX TODO volume, balance, ... */
857         if( p_sys->i_audio >= 0 )
858         {
859             vid_audio.audio = p_sys->i_audio;
860             if( ioctl( i_fd, VIDIOCGAUDIO, &vid_audio ) < 0 )
861             {
862                 msg_Err( p_demux, "cannot get audio (%s)", strerror( errno ) );
863                 goto vdev_failed;
864             }
865
866             /* unmute audio */
867             vid_audio.flags &= ~VIDEO_AUDIO_MUTE;
868
869             if( ioctl( i_fd, VIDIOCSAUDIO, &vid_audio ) < 0 )
870             {
871                 msg_Err( p_demux, "cannot set audio (%s)", strerror( errno ) );
872                 goto vdev_failed;
873             }
874         }
875
876     }
877
878     /* establish basic params with input and norm before feeling width
879      * or height */
880     if( p_sys->b_mjpeg )
881     {
882         struct quicktime_mjpeg_app1 *p_app1;
883         int32_t i_offset;
884
885         if( ioctl( i_fd, MJPIOC_G_PARAMS, &mjpeg ) < 0 )
886         {
887             msg_Err( p_demux, "cannot get mjpeg params (%s)",
888                               strerror( errno ) );
889             goto vdev_failed;
890         }
891         mjpeg.input = p_sys->i_channel;
892         mjpeg.norm  = p_sys->i_norm;
893         mjpeg.decimation = p_sys->i_decimation;
894
895         if( p_sys->i_width )
896             mjpeg.img_width = p_sys->i_width / p_sys->i_decimation;
897         if( p_sys->i_height )
898             mjpeg.img_height = p_sys->i_height / p_sys->i_decimation;
899
900         /* establish Quicktime APP1 marker while we are here */
901         mjpeg.APPn = 1;
902         mjpeg.APP_len = 40;
903
904         /* aligned */
905         p_app1 = (struct quicktime_mjpeg_app1 *)mjpeg.APP_data;
906         p_app1->i_reserved = 0;
907         p_app1->i_tag = VLC_FOURCC( 'm','j','p','g' );
908         p_app1->i_field_size = 0;
909         p_app1->i_padded_field_size = 0;
910         p_app1->i_next_field = 0;
911         /* XXX WARNING XXX */
912         /* these's nothing magic about these values.  We are dangerously
913          * assuming the encoder card is encoding mjpeg-a and is not throwing
914          * in marker tags we aren't expecting.  It's bad enough we have to
915          * search through the jpeg output for every frame we grab just to
916          * find the first field's end marker, so we take this risk to boost
917          * performance.
918          * This is really something the driver could do for us because this
919          * does conform to standards outside of Apple Quicktime.
920          */
921         i_offset = 0x2e;
922         p_app1->i_DQT_offset = hton32( i_offset );
923         i_offset = 0xb4;
924         p_app1->i_DHT_offset = hton32( i_offset );
925         i_offset = 0x258;
926         p_app1->i_SOF_offset = hton32( i_offset );
927         i_offset = 0x26b;
928         p_app1->i_SOS_offset = hton32( i_offset );
929         i_offset = 0x279;
930         p_app1->i_data_offset = hton32( i_offset );
931
932         /* SOF and SOS aren't specified by the mjpeg API because they aren't
933          * optional.  They will be present in the output. */
934         mjpeg.jpeg_markers = JPEG_MARKER_DHT | JPEG_MARKER_DQT;
935
936         if( ioctl( i_fd, MJPIOC_S_PARAMS, &mjpeg ) < 0 )
937         {
938             msg_Err( p_demux, "cannot set mjpeg params (%s)",
939                               strerror( errno ) );
940             goto vdev_failed;
941         }
942
943         p_sys->i_width = mjpeg.img_width * mjpeg.HorDcm;
944         p_sys->i_height = mjpeg.img_height * mjpeg.VerDcm *
945             mjpeg.field_per_buff;
946     }
947
948     /* fix width/height */
949     if( !p_sys->b_mjpeg && ( p_sys->i_width == 0 || p_sys->i_height == 0 ) )
950     {
951         struct video_window vid_win;
952
953         if( ioctl( i_fd, VIDIOCGWIN, &vid_win ) < 0 )
954         {
955             msg_Err( p_demux, "cannot get win (%s)", strerror( errno ) );
956             goto vdev_failed;
957         }
958         p_sys->i_width  = vid_win.width;
959         p_sys->i_height = vid_win.height;
960
961         msg_Dbg( p_demux, "will use %dx%d", p_sys->i_width, p_sys->i_height );
962     }
963
964     if( !p_sys->b_mjpeg )
965     {
966         /* set hue/color/.. */
967         if( ioctl( i_fd, VIDIOCGPICT, &p_sys->vid_picture ) == 0 )
968         {
969             struct video_picture vid_picture = p_sys->vid_picture;
970
971             if( p_sys->i_brightness >= 0 && p_sys->i_brightness < 65536 )
972             {
973                 vid_picture.brightness = p_sys->i_brightness;
974             }
975             if( p_sys->i_colour >= 0 && p_sys->i_colour < 65536 )
976             {
977                 vid_picture.colour = p_sys->i_colour;
978             }
979             if( p_sys->i_hue >= 0 && p_sys->i_hue < 65536 )
980             {
981                 vid_picture.hue = p_sys->i_hue;
982             }
983             if( p_sys->i_contrast  >= 0 && p_sys->i_contrast < 65536 )
984             {
985                 vid_picture.contrast = p_sys->i_contrast;
986             }
987             if( ioctl( i_fd, VIDIOCSPICT, &vid_picture ) == 0 )
988             {
989                 msg_Dbg( p_demux, "v4l device uses brightness: %d",
990                          vid_picture.brightness );
991                 msg_Dbg( p_demux, "v4l device uses colour: %d",
992                          vid_picture.colour );
993                 msg_Dbg( p_demux, "v4l device uses hue: %d", vid_picture.hue );
994                 msg_Dbg( p_demux, "v4l device uses contrast: %d",
995                          vid_picture.contrast );
996                 p_sys->vid_picture = vid_picture;
997             }
998         }
999
1000         /* Find out video format used by device */
1001         if( ioctl( i_fd, VIDIOCGPICT, &p_sys->vid_picture ) == 0 )
1002         {
1003             struct video_picture vid_picture = p_sys->vid_picture;
1004             char *psz;
1005             int i;
1006
1007             vid_picture.palette = 0;
1008             p_sys->i_fourcc = 0;
1009
1010             psz = var_CreateGetString( p_demux, "v4l-chroma" );
1011             if( strlen( psz ) >= 4 )
1012             {
1013                 int i_chroma = VLC_FOURCC( psz[0], psz[1], psz[2], psz[3] );
1014
1015                 /* Find out v4l chroma code */
1016                 for( i = 0; v4lchroma_to_fourcc[i].i_v4l != 0; i++ )
1017                 {
1018                     if( v4lchroma_to_fourcc[i].i_fourcc == i_chroma )
1019                     {
1020                         vid_picture.palette = v4lchroma_to_fourcc[i].i_v4l;
1021                         break;
1022                     }
1023                 }
1024             }
1025             free( psz );
1026
1027             if( vid_picture.palette &&
1028                 !ioctl( i_fd, VIDIOCSPICT, &vid_picture ) )
1029             {
1030                 p_sys->vid_picture = vid_picture;
1031             }
1032             else
1033             {
1034                 /* Try to set the format to something easy to encode */
1035                 vid_picture.palette = VIDEO_PALETTE_YUV420P;
1036                 if( ioctl( i_fd, VIDIOCSPICT, &vid_picture ) == 0 )
1037                 {
1038                     p_sys->vid_picture = vid_picture;
1039                 }
1040                 else
1041                 {
1042                     vid_picture.palette = VIDEO_PALETTE_YUV422P;
1043                     if( ioctl( i_fd, VIDIOCSPICT, &vid_picture ) == 0 )
1044                     {
1045                         p_sys->vid_picture = vid_picture;
1046                     }
1047                 }
1048             }
1049
1050             /* Find out final format */
1051             for( i = 0; v4lchroma_to_fourcc[i].i_v4l != 0; i++ )
1052             {
1053                 if( v4lchroma_to_fourcc[i].i_v4l == p_sys->vid_picture.palette)
1054                 {
1055                     p_sys->i_fourcc = v4lchroma_to_fourcc[i].i_fourcc;
1056                     break;
1057                 }
1058             }
1059
1060         }
1061         else
1062         {
1063             msg_Err( p_demux, "ioctl VIDIOCGPICT failed" );
1064             goto vdev_failed;
1065         }
1066     }
1067
1068     if( p_sys->b_mjpeg )
1069     {
1070         int i;
1071
1072         p_sys->mjpeg_buffers.count = 8;
1073         p_sys->mjpeg_buffers.size = MJPEG_BUFFER_SIZE;
1074
1075         if( ioctl( i_fd, MJPIOC_REQBUFS, &p_sys->mjpeg_buffers ) < 0 )
1076         {
1077             msg_Err( p_demux, "mmap unsupported" );
1078             goto vdev_failed;
1079         }
1080
1081         p_sys->p_video_mmap = mmap( 0,
1082                 p_sys->mjpeg_buffers.size * p_sys->mjpeg_buffers.count,
1083                 PROT_READ | PROT_WRITE, MAP_SHARED, i_fd, 0 );
1084         if( p_sys->p_video_mmap == MAP_FAILED )
1085         {
1086             msg_Err( p_demux, "mmap failed" );
1087             goto vdev_failed;
1088         }
1089
1090         p_sys->i_fourcc  = VLC_FOURCC( 'm','j','p','g' );
1091         p_sys->i_frame_pos = -1;
1092
1093         /* queue up all the frames */
1094         for( i = 0; i < (int)p_sys->mjpeg_buffers.count; i++ )
1095         {
1096             if( ioctl( i_fd, MJPIOC_QBUF_CAPT, &i ) < 0 )
1097             {
1098                 msg_Err( p_demux, "unable to queue frame" );
1099                 goto vdev_failed;
1100             }
1101         }
1102     }
1103     else
1104     {
1105         /* Fill in picture_t fields */
1106         vout_InitPicture( VLC_OBJECT(p_demux), &p_sys->pic, p_sys->i_fourcc,
1107                           p_sys->i_width, p_sys->i_height, p_sys->i_width *
1108                           VOUT_ASPECT_FACTOR / p_sys->i_height );
1109         if( !p_sys->pic.i_planes )
1110         {
1111             msg_Err( p_demux, "unsupported chroma" );
1112             goto vdev_failed;
1113         }
1114         p_sys->i_video_frame_size = 0;
1115         for( i = 0; i < p_sys->pic.i_planes; i++ )
1116         {
1117             p_sys->i_video_frame_size += p_sys->pic.p[i].i_visible_lines *
1118               p_sys->pic.p[i].i_visible_pitch;
1119         }
1120
1121         msg_Dbg( p_demux, "v4l device uses frame size: %i",
1122                  p_sys->i_video_frame_size );
1123         msg_Dbg( p_demux, "v4l device uses chroma: %4.4s",
1124                 (char*)&p_sys->i_fourcc );
1125
1126         /* Allocate mmap buffer */
1127         if( ioctl( i_fd, VIDIOCGMBUF, &p_sys->vid_mbuf ) < 0 )
1128         {
1129             msg_Err( p_demux, "mmap unsupported" );
1130             goto vdev_failed;
1131         }
1132
1133         p_sys->p_video_mmap = mmap( 0, p_sys->vid_mbuf.size,
1134                                     PROT_READ|PROT_WRITE, MAP_SHARED,
1135                                     i_fd, 0 );
1136         if( p_sys->p_video_mmap == MAP_FAILED )
1137         {
1138             /* FIXME -> normal read */
1139             msg_Err( p_demux, "mmap failed" );
1140             goto vdev_failed;
1141         }
1142
1143         /* init grabbing */
1144         p_sys->vid_mmap.frame  = 0;
1145         p_sys->vid_mmap.width  = p_sys->i_width;
1146         p_sys->vid_mmap.height = p_sys->i_height;
1147         p_sys->vid_mmap.format = p_sys->vid_picture.palette;
1148         if( ioctl( i_fd, VIDIOCMCAPTURE, &p_sys->vid_mmap ) < 0 )
1149         {
1150             msg_Warn( p_demux, "%4.4s refused", (char*)&p_sys->i_fourcc );
1151             msg_Err( p_demux, "chroma selection failed" );
1152             goto vdev_failed;
1153         }
1154     }
1155     return i_fd;
1156
1157 vdev_failed:
1158
1159     if( i_fd >= 0 ) close( i_fd );
1160     return -1;
1161 }
1162
1163 /*****************************************************************************
1164  * OpenAudioDev:
1165  *****************************************************************************/
1166 static int OpenAudioDev( demux_t *p_demux, char *psz_device )
1167 {
1168     demux_sys_t *p_sys = p_demux->p_sys;
1169     int i_fd, i_format;
1170
1171     if( (i_fd = open( psz_device, O_RDONLY | O_NONBLOCK )) < 0 )
1172     {
1173         msg_Err( p_demux, "cannot open audio device (%s)", strerror( errno ) );
1174         goto adev_fail;
1175     }
1176
1177     i_format = AFMT_S16_LE;
1178     if( ioctl( i_fd, SNDCTL_DSP_SETFMT, &i_format ) < 0
1179         || i_format != AFMT_S16_LE )
1180     {
1181         msg_Err( p_demux, "cannot set audio format (16b little endian) "
1182                  "(%s)", strerror( errno ) );
1183         goto adev_fail;
1184     }
1185
1186     if( ioctl( i_fd, SNDCTL_DSP_STEREO,
1187                &p_sys->b_stereo ) < 0 )
1188     {
1189         msg_Err( p_demux, "cannot set audio channels count (%s)",
1190                  strerror( errno ) );
1191         goto adev_fail;
1192     }
1193
1194     if( ioctl( i_fd, SNDCTL_DSP_SPEED,
1195                &p_sys->i_sample_rate ) < 0 )
1196     {
1197         msg_Err( p_demux, "cannot set audio sample rate (%s)",
1198                  strerror( errno ) );
1199         goto adev_fail;
1200     }
1201
1202     msg_Dbg( p_demux, "openened adev=`%s' %s %dHz",
1203              psz_device, p_sys->b_stereo ? "stereo" : "mono",
1204              p_sys->i_sample_rate );
1205
1206     p_sys->i_audio_max_frame_size = 6 * 1024;
1207
1208     return i_fd;
1209
1210  adev_fail:
1211
1212     if( i_fd >= 0 ) close( i_fd );
1213     return -1;
1214 }
1215
1216 /*****************************************************************************
1217  * GrabAudio: grab audio
1218  *****************************************************************************/
1219 static block_t *GrabAudio( demux_t *p_demux )
1220 {
1221     demux_sys_t *p_sys = p_demux->p_sys;
1222     struct audio_buf_info buf_info;
1223     int i_read, i_correct;
1224     block_t *p_block;
1225
1226     if( p_sys->p_block_audio ) p_block = p_sys->p_block_audio;
1227     else p_block = block_New( p_demux, p_sys->i_audio_max_frame_size );
1228
1229     if( !p_block )
1230     {
1231         msg_Warn( p_demux, "cannot get block" );
1232         return 0;
1233     }
1234
1235     p_sys->p_block_audio = p_block;
1236
1237     i_read = read( p_sys->fd_audio, p_block->p_buffer,
1238                    p_sys->i_audio_max_frame_size );
1239
1240     if( i_read <= 0 ) return 0;
1241
1242     p_block->i_buffer = i_read;
1243     p_sys->p_block_audio = 0;
1244
1245     /* Correct the date because of kernel buffering */
1246     i_correct = i_read;
1247     if( ioctl( p_sys->fd_audio, SNDCTL_DSP_GETISPACE, &buf_info ) == 0 )
1248     {
1249         i_correct += buf_info.bytes;
1250     }
1251
1252     p_block->i_pts = p_block->i_dts =
1253         mdate() - I64C(1000000) * (mtime_t)i_correct /
1254         2 / ( p_sys->b_stereo ? 2 : 1) / p_sys->i_sample_rate;
1255
1256     return p_block;
1257 }
1258
1259 /*****************************************************************************
1260  * GrabVideo:
1261  *****************************************************************************/
1262 static uint8_t *GrabCapture( demux_t *p_demux )
1263 {
1264     demux_sys_t *p_sys = p_demux->p_sys;
1265     int i_captured_frame = p_sys->i_frame_pos;
1266
1267     p_sys->vid_mmap.frame = (p_sys->i_frame_pos + 1) % p_sys->vid_mbuf.frames;
1268
1269     while( ioctl( p_sys->fd_video, VIDIOCMCAPTURE, &p_sys->vid_mmap ) < 0 )
1270     {
1271         if( errno != EAGAIN )
1272         {
1273             msg_Err( p_demux, "failed capturing new frame" );
1274             return NULL;
1275         }
1276
1277         if( p_demux->b_die )
1278         {
1279             return NULL;
1280         }
1281
1282         msg_Dbg( p_demux, "grab failed, trying again" );
1283     }
1284
1285     while( ioctl(p_sys->fd_video, VIDIOCSYNC, &p_sys->i_frame_pos) < 0 )
1286     {
1287         if( errno != EAGAIN && errno != EINTR )    
1288         {
1289             msg_Err( p_demux, "failed syncing new frame" );
1290             return NULL;
1291         }
1292     }
1293
1294     p_sys->i_frame_pos = p_sys->vid_mmap.frame;
1295     /* leave i_video_frame_size alone */
1296     return p_sys->p_video_mmap + p_sys->vid_mbuf.offsets[i_captured_frame];
1297 }
1298
1299 static uint8_t *GrabMJPEG( demux_t *p_demux )
1300 {
1301     demux_sys_t *p_sys = p_demux->p_sys;
1302     struct mjpeg_sync sync;
1303     uint8_t *p_frame, *p_field, *p;
1304     uint16_t tag;
1305     uint32_t i_size;
1306     struct quicktime_mjpeg_app1 *p_app1 = NULL;
1307
1308     /* re-queue the last frame we sync'd */
1309     if( p_sys->i_frame_pos != -1 )
1310     {
1311         while( ioctl( p_sys->fd_video, MJPIOC_QBUF_CAPT,
1312                                        &p_sys->i_frame_pos ) < 0 )
1313         {
1314             if( errno != EAGAIN && errno != EINTR )
1315             {
1316                 msg_Err( p_demux, "failed capturing new frame" );
1317                 return NULL;
1318             }
1319         }
1320     }
1321
1322     /* sync on the next frame */
1323     while( ioctl( p_sys->fd_video, MJPIOC_SYNC, &sync ) < 0 )
1324     {
1325         if( errno != EAGAIN && errno != EINTR )    
1326         {
1327             msg_Err( p_demux, "failed syncing new frame" );
1328             return NULL;
1329         }
1330     }
1331
1332     p_sys->i_frame_pos = sync.frame;
1333     p_frame = p_sys->p_video_mmap + p_sys->mjpeg_buffers.size * sync.frame;
1334
1335     /* p_frame now points to the data.  fix up the Quicktime APP1 marker */
1336     tag = 0xffd9;
1337     tag = hton16( tag );
1338     p_field = p_frame;
1339
1340     /* look for EOI */
1341     p = memmem( p_field, sync.length, &tag, 2 );
1342
1343     if( p )
1344     {
1345         p += 2; /* data immediately following EOI */
1346         /* UNALIGNED! */
1347         p_app1 = (struct quicktime_mjpeg_app1 *)(p_field + 6);
1348
1349         i_size = ((uint32_t)(p - p_field));
1350         i_size = hton32( i_size );
1351         memcpy( &p_app1->i_field_size, &i_size, 4 );
1352
1353         while( *p == 0xff && *(p+1) == 0xff )
1354             p++;
1355
1356         i_size = ((uint32_t)(p - p_field));
1357         i_size = hton32( i_size );
1358         memcpy( &p_app1->i_padded_field_size, &i_size, 4 );
1359     }
1360
1361     tag = 0xffd8;
1362     tag = hton16( tag );
1363     p_field = memmem( p, sync.length - (size_t)(p - p_frame), &tag, 2 );
1364
1365     if( p_field )
1366     {
1367         i_size = (uint32_t)(p_field - p_frame);
1368         i_size = hton32( i_size );
1369         memcpy( &p_app1->i_next_field, &i_size, 4 );
1370
1371         /* UNALIGNED! */
1372         p_app1 = (struct quicktime_mjpeg_app1 *)(p_field + 6);
1373         tag = 0xffd9;
1374         tag = hton16( tag );
1375         p = memmem( p_field, sync.length - (size_t)(p_field - p_frame),
1376                 &tag, 2 );
1377
1378         if( !p )
1379         {
1380             /* sometimes the second field doesn't have the EOI.  just put it
1381              * there
1382              */
1383             p = p_frame + sync.length;
1384             memcpy( p, &tag, 2 );
1385             sync.length += 2;
1386         }
1387
1388         p += 2;
1389         i_size = (uint32_t)(p - p_field);
1390         i_size = hton32( i_size );
1391         memcpy( &p_app1->i_field_size, &i_size, 4 );
1392         i_size = (uint32_t)(sync.length - (uint32_t)(p_field - p_frame));
1393         i_size = hton32( i_size );
1394         memcpy( &p_app1->i_padded_field_size, &i_size, 4 );
1395     }
1396
1397     p_sys->i_video_frame_size = sync.length;
1398     return p_frame;
1399 }
1400
1401 static block_t *GrabVideo( demux_t *p_demux )
1402 {
1403     demux_sys_t *p_sys = p_demux->p_sys;
1404     uint8_t     *p_frame;
1405     block_t     *p_block;
1406
1407     if( p_sys->f_fps >= 0.1 && p_sys->i_video_pts > 0 )
1408     {
1409         mtime_t i_dur = (mtime_t)((double)1000000 / (double)p_sys->f_fps);
1410
1411         /* Did we wait long enough ? (frame rate reduction) */
1412         if( p_sys->i_video_pts + i_dur > mdate() ) return 0;
1413     }
1414
1415     if( p_sys->b_mjpeg ) p_frame = GrabMJPEG( p_demux );
1416     else p_frame = GrabCapture( p_demux );
1417
1418     if( !p_frame ) return 0;
1419
1420     if( !( p_block = block_New( p_demux, p_sys->i_video_frame_size ) ) )
1421     {
1422         msg_Warn( p_demux, "cannot get block" );
1423         return 0;
1424     }
1425
1426     memcpy( p_block->p_buffer, p_frame, p_sys->i_video_frame_size );
1427     p_sys->i_video_pts = p_block->i_pts = p_block->i_dts = mdate();
1428
1429     return p_block;
1430 }