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