]> git.sesse.net Git - vlc/blob - modules/access/v4l.c
utf8_* -> vlc_* (sed roxxors)
[vlc] / modules / access / v4l.c
1 /*****************************************************************************
2  * v4l.c : Video4Linux input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2002-2004 the VideoLAN team
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  *         Benjamin Pracht <bigben at videolan dot org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30
31 #ifdef HAVE_CONFIG_H
32 # include "config.h"
33 #endif
34
35 #include <vlc_common.h>
36 #include <vlc_plugin.h>
37 #include <vlc_input.h>
38 #include <vlc_demux.h>
39 #include <vlc_access.h>
40 #include <vlc_picture.h>
41 #include <vlc_fs.h>
42
43 #include <sys/ioctl.h>
44 #include <sys/mman.h>
45 #include <fcntl.h>
46 #include <arpa/inet.h>
47 #include <errno.h>
48
49 /* From GStreamer's v4l plugin:
50  * Because of some really cool feature in video4linux1, also known as
51  * 'not including sys/types.h and sys/time.h', we had to include it
52  * ourselves. In all their intelligence, these people decided to fix
53  * this in the next version (video4linux2) in such a cool way that it
54  * breaks all compilations of old stuff...
55  * The real problem is actually that linux/time.h doesn't use proper
56  * macro checks before defining types like struct timeval. The proper
57  * fix here is to either fuck the kernel header (which is what we do
58  * by defining _LINUX_TIME_H, an innocent little hack) or by fixing it
59  * upstream, which I'll consider doing later on. If you get compiler
60  * errors here, check your linux/time.h && sys/time.h header setup.
61 */
62 #define _LINUX_TIME_H
63
64 #include <linux/videodev.h>
65 #include "videodev_mjpeg.h"
66
67 #ifdef HAVE_LIBV4L1
68 #include <libv4l1.h>
69 #endif
70 /*****************************************************************************
71  * Module descriptior
72  *****************************************************************************/
73 static int  Open ( vlc_object_t * );
74 static void Close( vlc_object_t * );
75
76 #define CACHING_TEXT N_("Caching value in ms")
77 #define CACHING_LONGTEXT N_( \
78     "Caching value for V4L captures. This " \
79     "value should be set in milliseconds." )
80 #define VDEV_TEXT N_("Video device name")
81 #define VDEV_LONGTEXT N_( \
82     "Name of the video device to use. " \
83     "If you don't specify anything, no video 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 #define FREQUENCY_TEXT N_( "Frequency" )
89 #define FREQUENCY_LONGTEXT N_( \
90     "Frequency to capture (in kHz), if applicable." )
91 #define CHANNEL_TEXT N_( "Channel" )
92 #define CHANNEL_LONGTEXT N_( \
93     "Channel of the card to use (Usually, 0 = tuner, " \
94     "1 = composite, 2 = svideo)." )
95 #define NORM_TEXT N_( "Norm" )
96 #define NORM_LONGTEXT N_( \
97     "Norm of the stream (Automatic, SECAM, PAL, or NTSC)." )
98 #define AUDIO_TEXT N_( "Audio Channel" )
99 #define AUDIO_LONGTEXT N_( \
100     "Audio Channel to use, if there are several audio inputs." )
101 #define WIDTH_TEXT N_( "Width" )
102 #define WIDTH_LONGTEXT N_( "Width of the stream to capture " \
103     "(-1 for autodetect)." )
104 #define HEIGHT_TEXT N_( "Height" )
105 #define HEIGHT_LONGTEXT N_( "Height of the stream to capture " \
106     "(-1 for autodetect)." )
107 #define BRIGHTNESS_TEXT N_( "Brightness" )
108 #define BRIGHTNESS_LONGTEXT N_( \
109     "Brightness of the video input." )
110 #define HUE_TEXT N_( "Hue" )
111 #define HUE_LONGTEXT N_( \
112     "Hue of the video input." )
113 #define COLOUR_TEXT N_( "Color" )
114 #define COLOUR_LONGTEXT N_( \
115     "Color of the video input." )
116 #define CONTRAST_TEXT N_( "Contrast" )
117 #define CONTRAST_LONGTEXT N_( \
118     "Contrast of the video input." )
119 #define TUNER_TEXT N_( "Tuner" )
120 #define TUNER_LONGTEXT N_( "Tuner to use, if there are several ones." )
121 #define MJPEG_TEXT N_( "MJPEG" )
122 #define MJPEG_LONGTEXT N_(  \
123     "Set this option if the capture device outputs MJPEG" )
124 #define DECIMATION_TEXT N_( "Decimation" )
125 #define DECIMATION_LONGTEXT N_( \
126     "Decimation level for MJPEG streams" )
127 #define QUALITY_TEXT N_( "Quality" )
128 #define QUALITY_LONGTEXT N_( "Quality of the stream." )
129 #define FPS_TEXT N_( "Framerate" )
130 #define FPS_LONGTEXT N_( "Framerate to capture, if applicable " \
131     "(-1 for autodetect)." )
132
133 #define AUDIO_DEPRECATED_ERROR N_( \
134     "Alsa or OSS audio capture in the v4l access is deprecated. " \
135     "please use 'v4l:/""/ :input-slave=alsa:/""/' or " \
136     "'v4l:/""/ :input-slave=oss:/""/' instead." )
137
138 static const int i_norm_list[] =
139     { VIDEO_MODE_AUTO, VIDEO_MODE_SECAM, VIDEO_MODE_PAL, VIDEO_MODE_NTSC };
140 static const char *const psz_norm_list_text[] =
141     { N_("Automatic"), N_("SECAM"), N_("PAL"),  N_("NTSC") };
142
143 #define V4L_DEFAULT "/dev/video"
144
145 vlc_module_begin ()
146     set_shortname( N_("Video4Linux") )
147     set_description( N_("Video4Linux input") )
148     set_category( CAT_INPUT )
149     set_subcategory( SUBCAT_INPUT_ACCESS )
150
151     add_integer( "v4l-caching", DEFAULT_PTS_DELAY / 1000, NULL,
152                  CACHING_TEXT, CACHING_LONGTEXT, true )
153     add_obsolete_string( "v4l-vdev" );
154     add_obsolete_string( "v4l-adev" );
155     add_string( "v4l-chroma", NULL, NULL, CHROMA_TEXT, CHROMA_LONGTEXT,
156                 true )
157     add_float( "v4l-fps", -1.0, NULL, FPS_TEXT, FPS_LONGTEXT, true )
158     add_obsolete_integer( "v4l-samplerate" );
159     add_integer( "v4l-channel", 0, NULL, CHANNEL_TEXT, CHANNEL_LONGTEXT,
160                 true )
161     add_integer( "v4l-tuner", -1, NULL, TUNER_TEXT, TUNER_LONGTEXT, true )
162     add_integer( "v4l-norm", VIDEO_MODE_AUTO, NULL, NORM_TEXT, NORM_LONGTEXT,
163                 false )
164         change_integer_list( i_norm_list, psz_norm_list_text, NULL );
165     add_integer( "v4l-frequency", -1, NULL, FREQUENCY_TEXT, FREQUENCY_LONGTEXT,
166                 false )
167     add_integer( "v4l-audio", -1, NULL, AUDIO_TEXT, AUDIO_LONGTEXT, true )
168     add_obsolete_bool( "v4l-stereo" );
169     add_integer( "v4l-width", 0, NULL, WIDTH_TEXT, WIDTH_LONGTEXT, true )
170     add_integer( "v4l-height", 0, NULL, HEIGHT_TEXT, HEIGHT_LONGTEXT,
171                 true )
172     add_integer( "v4l-brightness", -1, NULL, BRIGHTNESS_TEXT,
173                 BRIGHTNESS_LONGTEXT, true )
174     add_integer( "v4l-colour", -1, NULL, COLOUR_TEXT, COLOUR_LONGTEXT,
175                 true )
176     add_integer( "v4l-hue", -1, NULL, HUE_TEXT, HUE_LONGTEXT, true )
177     add_integer( "v4l-contrast", -1, NULL, CONTRAST_TEXT, CONTRAST_LONGTEXT,
178                 true )
179     add_bool( "v4l-mjpeg", false, NULL, MJPEG_TEXT, MJPEG_LONGTEXT,
180             true )
181     add_integer( "v4l-decimation", 1, NULL, DECIMATION_TEXT,
182             DECIMATION_LONGTEXT, true )
183     add_integer( "v4l-quality", 100, NULL, QUALITY_TEXT, QUALITY_LONGTEXT,
184             true )
185
186     add_shortcut( "v4l" )
187     set_capability( "access_demux", 10 )
188     set_callbacks( Open, Close )
189 vlc_module_end ()
190
191 /*****************************************************************************
192  * Access: local prototypes
193  *****************************************************************************/
194 static int Demux  ( demux_t * );
195 static int Control( demux_t *, int, va_list );
196
197 static void ParseMRL    ( demux_t * );
198 static int  OpenVideoDev( demux_t *, char * );
199 static block_t *GrabVideo( demux_t * );
200
201 #define MJPEG_BUFFER_SIZE (256*1024)
202
203 struct quicktime_mjpeg_app1
204 {
205     uint32_t    i_reserved;             /* set to 0 */
206     uint32_t    i_tag;                  /* 'mjpg' */
207     uint32_t    i_field_size;           /* offset following EOI */
208     uint32_t    i_padded_field_size;    /* offset following EOI+pad */
209     uint32_t    i_next_field;           /* offset to next field */
210     uint32_t    i_DQT_offset;
211     uint32_t    i_DHT_offset;
212     uint32_t    i_SOF_offset;
213     uint32_t    i_SOS_offset;
214     uint32_t    i_data_offset;          /* following SOS marker data */
215 };
216
217 static const struct
218 {
219     int i_v4l;
220     vlc_fourcc_t i_fourcc;
221
222 } v4lchroma_to_fourcc[] =
223 {
224     { VIDEO_PALETTE_GREY, VLC_CODEC_GREY },
225     { VIDEO_PALETTE_HI240, VLC_FOURCC( 'I', '2', '4', '0' ) },
226     { VIDEO_PALETTE_RGB565, VLC_CODEC_RGB16 },
227     { VIDEO_PALETTE_RGB555, VLC_CODEC_RGB15 },
228     { VIDEO_PALETTE_RGB24, VLC_CODEC_RGB24 },
229     { VIDEO_PALETTE_RGB32, VLC_CODEC_RGB32 },
230     { VIDEO_PALETTE_YUV422, VLC_CODEC_YUYV },
231     { VIDEO_PALETTE_YUYV, VLC_CODEC_YUYV },
232     { VIDEO_PALETTE_UYVY, VLC_CODEC_UYVY },
233     { VIDEO_PALETTE_YUV420, VLC_FOURCC( 'I', '4', '2', 'N' ) },
234     { VIDEO_PALETTE_YUV411, VLC_FOURCC( 'I', '4', '1', 'N' ) },
235     { VIDEO_PALETTE_RAW, VLC_FOURCC( 'G', 'R', 'A', 'W' ) },
236     { VIDEO_PALETTE_YUV422P, VLC_CODEC_I422 },
237     { VIDEO_PALETTE_YUV420P, VLC_CODEC_I420 },
238     { VIDEO_PALETTE_YUV411P, VLC_CODEC_I411 },
239     { 0, 0 }
240 };
241
242 struct demux_sys_t
243 {
244     /* Devices */
245     char *psz_device;         /* Main device from MRL */
246     int  i_fd;
247
248     /* Video properties */
249     picture_t pic;
250
251     int i_fourcc;
252     int i_channel;
253     int i_audio;
254     int i_norm;
255     int i_tuner;
256     int i_frequency;
257     int i_width;
258     int i_height;
259
260     int i_brightness;
261     int i_hue;
262     int i_colour;
263     int i_contrast;
264
265     float f_fps;            /* <= 0.0 mean to grab at full rate */
266     mtime_t i_video_pts;    /* only used when f_fps > 0 */
267
268     bool b_mjpeg;
269     int i_decimation;
270     int i_quality;
271
272     struct video_capability vid_cap;
273     struct video_mbuf       vid_mbuf;
274     struct mjpeg_requestbuffers mjpeg_buffers;
275
276     uint8_t *p_video_mmap;
277     int     i_frame_pos;
278
279     struct video_mmap   vid_mmap;
280     struct video_picture vid_picture;
281
282     int          i_video_frame_size;
283     es_out_id_t  *p_es;
284 };
285
286 #ifndef HAVE_LIBV4L1
287 #   define v4l1_close close
288 #   define v4l1_ioctl ioctl
289 #   define v4l1_mmap mmap
290 #   define v4l1_munmap munmap
291 #   define v4l1_open vlc_open
292 #endif
293
294 /*****************************************************************************
295  * Open: opens v4l device
296  *****************************************************************************
297  *
298  * url: <video device>::::
299  *
300  *****************************************************************************/
301 static int Open( vlc_object_t *p_this )
302 {
303     demux_t     *p_demux = (demux_t*)p_this;
304     demux_sys_t *p_sys;
305
306     /* Only when selected */
307     if( *p_demux->psz_access == '\0' )
308         return VLC_EGENERIC;
309
310     /* Set up p_demux */
311     p_demux->pf_demux = Demux;
312     p_demux->pf_control = Control;
313     p_demux->info.i_update = 0;
314     p_demux->info.i_title = 0;
315     p_demux->info.i_seekpoint = 0;
316     p_demux->p_sys = p_sys = calloc( 1, sizeof( demux_sys_t ) );
317     if( !p_sys )
318         return VLC_ENOMEM;
319
320     p_sys->i_audio      = var_CreateGetInteger( p_demux, "v4l-audio" );
321     p_sys->i_channel    = var_CreateGetInteger( p_demux, "v4l-channel" );
322     p_sys->i_norm       = var_CreateGetInteger( p_demux, "v4l-norm" );
323     p_sys->i_tuner      = var_CreateGetInteger( p_demux, "v4l-tuner" );
324     p_sys->i_frequency  = var_CreateGetInteger( p_demux, "v4l-frequency" );
325
326     p_sys->f_fps        = var_CreateGetFloat( p_demux, "v4l-fps" );
327     p_sys->i_width      = var_CreateGetInteger( p_demux, "v4l-width" );
328     p_sys->i_height     = var_CreateGetInteger( p_demux, "v4l-height" );
329     p_sys->i_video_pts  = -1;
330     p_sys->i_brightness = var_CreateGetInteger( p_demux, "v4l-brightness" );
331
332     p_sys->i_hue        = var_CreateGetInteger( p_demux, "v4l-hue" );
333     p_sys->i_colour     = var_CreateGetInteger( p_demux, "v4l-colour" );
334     p_sys->i_contrast   = var_CreateGetInteger( p_demux, "v4l-contrast" );
335
336     p_sys->b_mjpeg      = var_CreateGetBool( p_demux, "v4l-mjpeg" );
337     p_sys->i_decimation = var_CreateGetInteger( p_demux, "v4l-decimation" );
338     p_sys->i_quality    = var_CreateGetInteger( p_demux, "v4l-quality" );
339
340     p_sys->psz_device = NULL;
341     p_sys->i_fd = -1;
342
343     p_sys->p_es = NULL;
344
345     ParseMRL( p_demux );
346
347     msg_Dbg( p_this, "opening device '%s'", p_sys->psz_device );
348     p_sys->i_fd = OpenVideoDev( p_demux, p_sys->psz_device );
349     if( p_sys->i_fd < 0 )
350     {
351         Close( p_this );
352         return VLC_EGENERIC;
353     }
354
355
356     msg_Dbg( p_demux, "v4l grabbing started" );
357
358     /* Declare elementary streams */
359     es_format_t fmt;
360     es_format_Init( &fmt, VIDEO_ES, p_sys->i_fourcc );
361     fmt.video.i_width  = p_sys->i_width;
362     fmt.video.i_height = p_sys->i_height;
363     fmt.video.i_sar_num = 4 * fmt.video.i_height;
364     fmt.video.i_sar_den = 3 * fmt.video.i_width;
365
366     /* Setup rgb mask for RGB formats */
367     switch( p_sys->i_fourcc )
368     {
369         case VLC_CODEC_RGB15:
370             fmt.video.i_rmask = 0x001f;
371             fmt.video.i_gmask = 0x03e0;
372             fmt.video.i_bmask = 0x7c00;
373             break;
374         case VLC_CODEC_RGB16:
375             fmt.video.i_rmask = 0x001f;
376             fmt.video.i_gmask = 0x07e0;
377             fmt.video.i_bmask = 0xf800;
378             break;
379         case VLC_CODEC_RGB24:
380         case VLC_CODEC_RGB32:
381             fmt.video.i_rmask = 0x00ff0000;
382             fmt.video.i_gmask = 0x0000ff00;
383             fmt.video.i_bmask = 0x000000ff;
384             break;
385     }
386
387     msg_Dbg( p_demux, "added new video es %4.4s %dx%d",
388              (char*)&fmt.i_codec, fmt.video.i_width, fmt.video.i_height );
389     p_sys->p_es = es_out_Add( p_demux->out, &fmt );
390
391     /* Update default_pts to a suitable value for access */
392     var_Create( p_demux, "v4l-caching", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
393
394     return VLC_SUCCESS;
395 }
396
397 /*****************************************************************************
398  * Close: close device, free resources
399  *****************************************************************************/
400 static void Close( vlc_object_t *p_this )
401 {
402     demux_t     *p_demux = (demux_t *)p_this;
403     demux_sys_t *p_sys   = p_demux->p_sys;
404
405     free( p_sys->psz_device );
406     if( p_sys->i_fd >= 0 ) v4l1_close( p_sys->i_fd );
407
408     if( p_sys->b_mjpeg )
409     {
410         int i_noframe = -1;
411         v4l1_ioctl( p_sys->i_fd, MJPIOC_QBUF_CAPT, &i_noframe );
412     }
413
414     if( p_sys->p_video_mmap && p_sys->p_video_mmap != MAP_FAILED )
415     {
416         if( p_sys->b_mjpeg )
417             v4l1_munmap( p_sys->p_video_mmap, p_sys->mjpeg_buffers.size *
418                     p_sys->mjpeg_buffers.count );
419         else
420             v4l1_munmap( p_sys->p_video_mmap, p_sys->vid_mbuf.size );
421     }
422
423     free( p_sys );
424 }
425
426 /*****************************************************************************
427  * Control:
428  *****************************************************************************/
429 static int Control( demux_t *p_demux, int i_query, va_list args )
430 {
431     bool *pb;
432     int64_t    *pi64;
433
434     switch( i_query )
435     {
436         /* Special for access_demux */
437         case DEMUX_CAN_PAUSE:
438         case DEMUX_CAN_SEEK:
439         case DEMUX_CAN_CONTROL_PACE:
440             pb = (bool*)va_arg( args, bool * );
441             *pb = false;
442             return VLC_SUCCESS;
443
444         case DEMUX_GET_PTS_DELAY:
445             pi64 = (int64_t*)va_arg( args, int64_t * );
446             *pi64 = (int64_t)var_GetInteger( p_demux, "v4l-caching" ) * 1000;
447             return VLC_SUCCESS;
448
449         case DEMUX_GET_TIME:
450             pi64 = (int64_t*)va_arg( args, int64_t * );
451             *pi64 = mdate();
452             return VLC_SUCCESS;
453
454         /* TODO implement others */
455         default:
456             return VLC_EGENERIC;
457     }
458
459     return VLC_EGENERIC;
460 }
461
462 /*****************************************************************************
463  * Demux:
464  *****************************************************************************/
465 static int Demux( demux_t *p_demux )
466 {
467     demux_sys_t *p_sys = p_demux->p_sys;
468
469     block_t *p_block = GrabVideo( p_demux );
470
471     if( !p_block )
472     {
473         msleep( 10000 ); /* Unfortunately v4l doesn't allow polling */
474         return 1;
475     }
476
477     es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_block->i_pts );
478     es_out_Send( p_demux->out, p_sys->p_es, p_block );
479
480     return 1;
481 }
482
483 /*****************************************************************************
484  * ParseMRL: parse the options contained in the MRL
485  *****************************************************************************/
486 static void ParseMRL( demux_t *p_demux )
487 {
488     demux_sys_t *p_sys = p_demux->p_sys;
489
490     char *psz_dup = strdup( p_demux->psz_path );
491     char *psz_parser = psz_dup;
492
493     while( *psz_parser && *psz_parser != ':' )
494     {
495         psz_parser++;
496     }
497
498     if( *psz_parser == ':' )
499     {
500         /* read options */
501         for( ;; )
502         {
503             *psz_parser++ = '\0';
504             if( !strncmp( psz_parser, "channel=", strlen( "channel=" ) ) )
505             {
506                 p_sys->i_channel = strtol( psz_parser + strlen( "channel=" ),
507                                            &psz_parser, 0 );
508             }
509             else if( !strncmp( psz_parser, "norm=", strlen( "norm=" ) ) )
510             {
511                 psz_parser += strlen( "norm=" );
512                 if( !strncmp( psz_parser, "pal", strlen( "pal" ) ) )
513                 {
514                     p_sys->i_norm = VIDEO_MODE_PAL;
515                     psz_parser += strlen( "pal" );
516                 }
517                 else if( !strncmp( psz_parser, "ntsc", strlen( "ntsc" ) ) )
518                 {
519                     p_sys->i_norm = VIDEO_MODE_NTSC;
520                     psz_parser += strlen( "ntsc" );
521                 }
522                 else if( !strncmp( psz_parser, "secam", strlen( "secam" ) ) )
523                 {
524                     p_sys->i_norm = VIDEO_MODE_SECAM;
525                     psz_parser += strlen( "secam" );
526                 }
527                 else if( !strncmp( psz_parser, "auto", strlen( "auto" ) ) )
528                 {
529                     p_sys->i_norm = VIDEO_MODE_AUTO;
530                     psz_parser += strlen( "auto" );
531                 }
532                 else
533                 {
534                     p_sys->i_norm = strtol( psz_parser, &psz_parser, 0 );
535                 }
536             }
537             else if( !strncmp( psz_parser, "frequency=",
538                                strlen( "frequency=" ) ) )
539             {
540                 p_sys->i_frequency =
541                     strtol( psz_parser + strlen( "frequency=" ),
542                             &psz_parser, 0 );
543                 if( p_sys->i_frequency < 30000 )
544                 {
545                     msg_Warn( p_demux, "v4l syntax has changed : "
546                               "'frequency' is now channel frequency in kHz");
547                 }
548             }
549             else if( !strncmp( psz_parser, "audio=", strlen( "audio=" ) ) )
550             {
551                 p_sys->i_audio = strtol( psz_parser + strlen( "audio=" ),
552                                          &psz_parser, 0 );
553             }
554             else if( !strncmp( psz_parser, "size=", strlen( "size=" ) ) )
555             {
556                 psz_parser += strlen( "size=" );
557                 if( !strncmp( psz_parser, "subqcif", strlen( "subqcif" ) ) )
558                 {
559                     p_sys->i_width  = 128;
560                     p_sys->i_height = 96;
561                 }
562                 else if( !strncmp( psz_parser, "qsif", strlen( "qsif" ) ) )
563                 {
564                     p_sys->i_width  = 160;
565                     p_sys->i_height = 120;
566                 }
567                 else if( !strncmp( psz_parser, "qcif", strlen( "qcif" ) ) )
568                 {
569                     p_sys->i_width  = 176;
570                     p_sys->i_height = 144;
571                 }
572                 else if( !strncmp( psz_parser, "sif", strlen( "sif" ) ) )
573                 {
574                     p_sys->i_width  = 320;
575                     p_sys->i_height = 244;
576                 }
577                 else if( !strncmp( psz_parser, "cif", strlen( "cif" ) ) )
578                 {
579                     p_sys->i_width  = 352;
580                     p_sys->i_height = 288;
581                 }
582                 else if( !strncmp( psz_parser, "vga", strlen( "vga" ) ) )
583                 {
584                     p_sys->i_width  = 640;
585                     p_sys->i_height = 480;
586                 }
587                 else
588                 {
589                     /* widthxheight */
590                     p_sys->i_width = strtol( psz_parser, &psz_parser, 0 );
591                     if( *psz_parser == 'x' || *psz_parser == 'X')
592                     {
593                         p_sys->i_height = strtol( psz_parser + 1,
594                                                   &psz_parser, 0 );
595                     }
596                     msg_Dbg( p_demux, "WxH %dx%d", p_sys->i_width,
597                              p_sys->i_height );
598                 }
599             }
600             else if( !strncmp( psz_parser, "brightness=", strlen( "brightness=" ) ) )
601             {
602                 p_sys->i_brightness = strtol( psz_parser + strlen( "brightness=" ),
603                                               &psz_parser, 0 );
604             }
605             else if( !strncmp( psz_parser, "colour=", strlen( "colour=" ) ) )
606             {
607                 p_sys->i_colour = strtol( psz_parser + strlen( "colour=" ),
608                                           &psz_parser, 0 );
609             }
610             else if( !strncmp( psz_parser, "hue=", strlen( "hue=" ) ) )
611             {
612                 p_sys->i_hue = strtol( psz_parser + strlen( "hue=" ),
613                                        &psz_parser, 0 );
614             }
615             else if( !strncmp( psz_parser, "contrast=", strlen( "contrast=" ) ) )
616             {
617                 p_sys->i_contrast = strtol( psz_parser + strlen( "contrast=" ),
618                                             &psz_parser, 0 );
619             }
620             else if( !strncmp( psz_parser, "tuner=", strlen( "tuner=" ) ) )
621             {
622                 p_sys->i_tuner = strtol( psz_parser + strlen( "tuner=" ),
623                                          &psz_parser, 0 );
624             }
625             else if( !strncmp( psz_parser, "mjpeg", strlen( "mjpeg" ) ) )
626             {
627                 psz_parser += strlen( "mjpeg" );
628
629                 p_sys->b_mjpeg = true;
630             }
631             else if( !strncmp( psz_parser, "decimation=",
632                         strlen( "decimation=" ) ) )
633             {
634                 p_sys->i_decimation =
635                     strtol( psz_parser + strlen( "decimation=" ),
636                             &psz_parser, 0 );
637             }
638             else if( !strncmp( psz_parser, "quality=",
639                         strlen( "quality=" ) ) )
640             {
641                 p_sys->i_quality =
642                     strtol( psz_parser + strlen( "quality=" ),
643                             &psz_parser, 0 );
644             }
645             else if( !strncmp( psz_parser, "fps=", strlen( "fps=" ) ) )
646             {
647                 p_sys->f_fps = us_strtof( psz_parser + strlen( "fps=" ),
648                                           &psz_parser );
649             }
650             else if( !strncmp( psz_parser, "adev=", strlen( "adev=" ) )
651              || !strncmp( psz_parser, "samplerate=", strlen( "samplerate=" ) )
652              || !strncmp( psz_parser, "stereo", strlen( "stereo" ) )
653              || !strncmp( psz_parser, "mono", strlen( "mono" ) ) )
654             {
655                 if( strchr( psz_parser, ':' ) )
656                     psz_parser = strchr( psz_parser, ':' );
657                 else
658                     psz_parser += strlen( psz_parser );
659                 msg_Err( p_demux, AUDIO_DEPRECATED_ERROR );
660             }
661             else
662             {
663                 msg_Warn( p_demux, "unknown option" );
664             }
665
666             while( *psz_parser && *psz_parser != ':' )
667             {
668                 psz_parser++;
669             }
670
671             if( *psz_parser == '\0' )
672             {
673                 break;
674             }
675         }
676     }
677
678     if( *psz_dup )
679         p_sys->psz_device = strdup( psz_dup );
680     else
681         p_sys->psz_device = strdup( V4L_DEFAULT );
682     free( psz_dup );
683 }
684
685 /*****************************************************************************
686  * OpenVideoDev:
687  *****************************************************************************/
688 static int OpenVideoDev( demux_t *p_demux, char *psz_device )
689 {
690     demux_sys_t *p_sys = p_demux->p_sys;
691     int i_fd;
692
693     struct video_channel vid_channel;
694     struct mjpeg_params mjpeg;
695     int i;
696
697     if( ( i_fd = v4l1_open( psz_device, O_RDWR ) ) < 0 )
698     {
699         msg_Err( p_demux, "cannot open device (%m)" );
700         goto vdev_failed;
701     }
702
703     if( v4l1_ioctl( i_fd, VIDIOCGCAP, &p_sys->vid_cap ) < 0 )
704     {
705         msg_Err( p_demux, "cannot get capabilities (%m)" );
706         goto vdev_failed;
707     }
708
709     msg_Dbg( p_demux,
710              "V4L device %s %d channels %d audios %d < w < %d %d < h < %d",
711              p_sys->vid_cap.name,
712              p_sys->vid_cap.channels,
713              p_sys->vid_cap.audios,
714              p_sys->vid_cap.minwidth,  p_sys->vid_cap.maxwidth,
715              p_sys->vid_cap.minheight, p_sys->vid_cap.maxheight );
716
717     if( p_sys->i_channel < 0 || p_sys->i_channel >= p_sys->vid_cap.channels )
718     {
719         msg_Dbg( p_demux, "invalid channel, falling back on channel 0" );
720         p_sys->i_channel = 0;
721     }
722     if( p_sys->vid_cap.audios && p_sys->i_audio >= p_sys->vid_cap.audios )
723     {
724         msg_Dbg( p_demux, "invalid audio, falling back with no audio" );
725         p_sys->i_audio = -1;
726     }
727
728     if( p_sys->i_width < p_sys->vid_cap.minwidth ||
729         p_sys->i_width > p_sys->vid_cap.maxwidth )
730     {
731         msg_Dbg( p_demux, "invalid width %i", p_sys->i_width );
732         p_sys->i_width = 0;
733     }
734     if( p_sys->i_height < p_sys->vid_cap.minheight ||
735         p_sys->i_height > p_sys->vid_cap.maxheight )
736     {
737         msg_Dbg( p_demux, "invalid height %i", p_sys->i_height );
738         p_sys->i_height = 0;
739     }
740
741     if( !( p_sys->vid_cap.type & VID_TYPE_CAPTURE ) )
742     {
743         msg_Err( p_demux, "cannot grab" );
744         goto vdev_failed;
745     }
746
747     vid_channel.channel = p_sys->i_channel;
748     if( v4l1_ioctl( i_fd, VIDIOCGCHAN, &vid_channel ) < 0 )
749     {
750         msg_Err( p_demux, "cannot get channel infos (%m)" );
751         goto vdev_failed;
752     }
753     msg_Dbg( p_demux,
754              "setting channel %s(%d) %d tuners flags=0x%x type=0x%x norm=0x%x",
755              vid_channel.name, vid_channel.channel, vid_channel.tuners,
756              vid_channel.flags, vid_channel.type, vid_channel.norm );
757
758     if( p_sys->i_tuner >= vid_channel.tuners )
759     {
760         msg_Dbg( p_demux, "invalid tuner, falling back on tuner 0" );
761         p_sys->i_tuner = 0;
762     }
763
764     vid_channel.norm = p_sys->i_norm;
765     if( v4l1_ioctl( i_fd, VIDIOCSCHAN, &vid_channel ) < 0 )
766     {
767         msg_Err( p_demux, "cannot set channel (%m)" );
768         goto vdev_failed;
769     }
770
771     if( vid_channel.flags & VIDEO_VC_TUNER )
772     {
773
774         /* set tuner */
775 #if 0
776         struct video_tuner vid_tuner;
777         if( p_sys->i_tuner >= 0 )
778         {
779             vid_tuner.tuner = p_sys->i_tuner;
780             if( v4l1_ioctl( i_fd, VIDIOCGTUNER, &vid_tuner ) < 0 )
781             {
782                 msg_Err( p_demux, "cannot get tuner (%m)" );
783                 goto vdev_failed;
784             }
785             msg_Dbg( p_demux, "tuner %s low=%d high=%d, flags=0x%x "
786                      "mode=0x%x signal=0x%x",
787                      vid_tuner.name, vid_tuner.rangelow, vid_tuner.rangehigh,
788                      vid_tuner.flags, vid_tuner.mode, vid_tuner.signal );
789
790             msg_Dbg( p_demux, "setting tuner %s (%d)",
791                      vid_tuner.name, vid_tuner.tuner );
792
793             /* FIXME FIXME to be checked FIXME FIXME */
794             //vid_tuner.mode = p_sys->i_norm;
795             if( v4l1_ioctl( i_fd, VIDIOCSTUNER, &vid_tuner ) < 0 )
796             {
797                 msg_Err( p_demux, "cannot set tuner (%m)" );
798                 goto vdev_failed;
799             }
800         }
801 #endif
802
803         /* Show a warning if frequency is < than 30000.
804          * User is certainly usint old syntax. */
805
806
807         /* set frequency */
808         if( p_sys->i_frequency >= 0 )
809         {
810             int driver_frequency = p_sys->i_frequency * 16 /1000;
811             if( v4l1_ioctl( i_fd, VIDIOCSFREQ, &driver_frequency ) < 0 )
812             {
813                 msg_Err( p_demux, "cannot set frequency (%m)" );
814                 goto vdev_failed;
815             }
816             msg_Dbg( p_demux, "frequency %d (%d)", p_sys->i_frequency,
817                                                    driver_frequency );
818         }
819     }
820
821     /* set audio */
822     if( vid_channel.flags & VIDEO_VC_AUDIO )
823     {
824         struct video_audio      vid_audio;
825
826         /* XXX TODO volume, balance, ... */
827         if( p_sys->i_audio >= 0 )
828         {
829             vid_audio.audio = p_sys->i_audio;
830             if( v4l1_ioctl( i_fd, VIDIOCGAUDIO, &vid_audio ) < 0 )
831             {
832                 msg_Err( p_demux, "cannot get audio (%m)" );
833                 goto vdev_failed;
834             }
835
836             /* unmute audio */
837             vid_audio.flags &= ~VIDEO_AUDIO_MUTE;
838
839             if( v4l1_ioctl( i_fd, VIDIOCSAUDIO, &vid_audio ) < 0 )
840             {
841                 msg_Err( p_demux, "cannot set audio (%m)" );
842                 goto vdev_failed;
843             }
844         }
845
846     }
847
848     /* establish basic params with input and norm before feeling width
849      * or height */
850     if( p_sys->b_mjpeg )
851     {
852         struct quicktime_mjpeg_app1 p_app1;
853         int32_t i_offset;
854
855         if( v4l1_ioctl( i_fd, MJPIOC_G_PARAMS, &mjpeg ) < 0 )
856         {
857             msg_Err( p_demux, "cannot get mjpeg params (%m)" );
858             goto vdev_failed;
859         }
860         mjpeg.input = p_sys->i_channel;
861         mjpeg.norm  = p_sys->i_norm;
862         mjpeg.decimation = p_sys->i_decimation;
863
864         if( p_sys->i_width )
865             mjpeg.img_width = p_sys->i_width / p_sys->i_decimation;
866         if( p_sys->i_height )
867             mjpeg.img_height = p_sys->i_height / p_sys->i_decimation;
868
869         /* establish Quicktime APP1 marker while we are here */
870         mjpeg.APPn = 1;
871         mjpeg.APP_len = 40;
872
873         /* aligned */
874         p_app1.i_reserved = 0;
875         p_app1.i_tag = VLC_FOURCC( 'm','j','p','g' );
876         p_app1.i_field_size = 0;
877         p_app1.i_padded_field_size = 0;
878         p_app1.i_next_field = 0;
879         /* XXX WARNING XXX */
880         /* these's nothing magic about these values.  We are dangerously
881          * assuming the encoder card is encoding mjpeg-a and is not throwing
882          * in marker tags we aren't expecting.  It's bad enough we have to
883          * search through the jpeg output for every frame we grab just to
884          * find the first field's end marker, so we take this risk to boost
885          * performance.
886          * This is really something the driver could do for us because this
887          * does conform to standards outside of Apple Quicktime.
888          */
889         i_offset = 0x2e;
890         p_app1.i_DQT_offset = hton32( i_offset );
891         i_offset = 0xb4;
892         p_app1.i_DHT_offset = hton32( i_offset );
893         i_offset = 0x258;
894         p_app1.i_SOF_offset = hton32( i_offset );
895         i_offset = 0x26b;
896         p_app1.i_SOS_offset = hton32( i_offset );
897         i_offset = 0x279;
898         p_app1.i_data_offset = hton32( i_offset );
899         memcpy(mjpeg.APP_data, &p_app1, sizeof(struct quicktime_mjpeg_app1));
900
901         /* SOF and SOS aren't specified by the mjpeg API because they aren't
902          * optional.  They will be present in the output. */
903         mjpeg.jpeg_markers = JPEG_MARKER_DHT | JPEG_MARKER_DQT;
904
905         if( v4l1_ioctl( i_fd, MJPIOC_S_PARAMS, &mjpeg ) < 0 )
906         {
907             msg_Err( p_demux, "cannot set mjpeg params (%m)" );
908             goto vdev_failed;
909         }
910
911         p_sys->i_width = mjpeg.img_width * mjpeg.HorDcm;
912         p_sys->i_height = mjpeg.img_height * mjpeg.VerDcm *
913             mjpeg.field_per_buff;
914     }
915
916     /* fix width/height */
917     if( !p_sys->b_mjpeg && ( p_sys->i_width == 0 || p_sys->i_height == 0 ) )
918     {
919         struct video_window vid_win;
920
921         if( v4l1_ioctl( i_fd, VIDIOCGWIN, &vid_win ) < 0 )
922         {
923             msg_Err( p_demux, "cannot get win (%m)" );
924             goto vdev_failed;
925         }
926         p_sys->i_width  = vid_win.width;
927         p_sys->i_height = vid_win.height;
928
929         if( !p_sys->i_width || !p_sys->i_height )
930         {
931             p_sys->i_width = p_sys->vid_cap.maxwidth;
932             p_sys->i_height = p_sys->vid_cap.maxheight;
933         }
934
935         if( !p_sys->i_width || !p_sys->i_height )
936         {
937             msg_Err( p_demux, "invalid video size (%ix%i)",
938                      p_sys->i_width, p_sys->i_height );
939             goto vdev_failed;
940         }
941
942         msg_Dbg( p_demux, "will use %dx%d", p_sys->i_width, p_sys->i_height );
943     }
944
945     if( !p_sys->b_mjpeg )
946     {
947         /* set hue/color/.. */
948         if( v4l1_ioctl( i_fd, VIDIOCGPICT, &p_sys->vid_picture ) == 0 )
949         {
950             struct video_picture vid_picture = p_sys->vid_picture;
951
952             if( p_sys->i_brightness >= 0 && p_sys->i_brightness < 65536 )
953             {
954                 vid_picture.brightness = p_sys->i_brightness;
955             }
956             if( p_sys->i_colour >= 0 && p_sys->i_colour < 65536 )
957             {
958                 vid_picture.colour = p_sys->i_colour;
959             }
960             if( p_sys->i_hue >= 0 && p_sys->i_hue < 65536 )
961             {
962                 vid_picture.hue = p_sys->i_hue;
963             }
964             if( p_sys->i_contrast  >= 0 && p_sys->i_contrast < 65536 )
965             {
966                 vid_picture.contrast = p_sys->i_contrast;
967             }
968             if( v4l1_ioctl( i_fd, VIDIOCSPICT, &vid_picture ) == 0 )
969             {
970                 msg_Dbg( p_demux, "v4l device uses brightness: %d",
971                          vid_picture.brightness );
972                 msg_Dbg( p_demux, "v4l device uses colour: %d",
973                          vid_picture.colour );
974                 msg_Dbg( p_demux, "v4l device uses hue: %d", vid_picture.hue );
975                 msg_Dbg( p_demux, "v4l device uses contrast: %d",
976                          vid_picture.contrast );
977                 p_sys->vid_picture = vid_picture;
978             }
979         }
980
981         /* Find out video format used by device */
982         if( v4l1_ioctl( i_fd, VIDIOCGPICT, &p_sys->vid_picture ) == 0 )
983         {
984             struct video_picture vid_picture = p_sys->vid_picture;
985             char *psz;
986             int i;
987
988             p_sys->i_fourcc = 0;
989
990             psz = var_CreateGetString( p_demux, "v4l-chroma" );
991
992             const vlc_fourcc_t i_chroma =
993                 vlc_fourcc_GetCodecFromString( VIDEO_ES, psz );
994             if( i_chroma )
995             {
996                 vid_picture.palette = 0;
997
998                 /* Find out v4l chroma code */
999                 for( i = 0; v4lchroma_to_fourcc[i].i_v4l != 0; i++ )
1000                 {
1001                     if( v4lchroma_to_fourcc[i].i_fourcc == i_chroma )
1002                     {
1003                         vid_picture.palette = v4lchroma_to_fourcc[i].i_v4l;
1004                         break;
1005                     }
1006                 }
1007             }
1008             free( psz );
1009
1010             if( vid_picture.palette &&
1011                 !v4l1_ioctl( i_fd, VIDIOCSPICT, &vid_picture ) )
1012             {
1013                 p_sys->vid_picture = vid_picture;
1014             }
1015             else
1016             {
1017                 /* Try to set the format to something easy to encode */
1018                 vid_picture.palette = VIDEO_PALETTE_YUV420P;
1019                 if( v4l1_ioctl( i_fd, VIDIOCSPICT, &vid_picture ) == 0 )
1020                 {
1021                     p_sys->vid_picture = vid_picture;
1022                 }
1023                 else
1024                 {
1025                     vid_picture.palette = VIDEO_PALETTE_YUV422P;
1026                     if( v4l1_ioctl( i_fd, VIDIOCSPICT, &vid_picture ) == 0 )
1027                     {
1028                         p_sys->vid_picture = vid_picture;
1029                     }
1030                 }
1031             }
1032
1033             /* Find out final format */
1034             for( i = 0; v4lchroma_to_fourcc[i].i_v4l != 0; i++ )
1035             {
1036                 if( v4lchroma_to_fourcc[i].i_v4l == p_sys->vid_picture.palette)
1037                 {
1038                     p_sys->i_fourcc = v4lchroma_to_fourcc[i].i_fourcc;
1039                     break;
1040                 }
1041             }
1042         }
1043         else
1044         {
1045             msg_Err( p_demux, "ioctl VIDIOCGPICT failed" );
1046             goto vdev_failed;
1047         }
1048     }
1049
1050     if( p_sys->b_mjpeg )
1051     {
1052         int i;
1053
1054         p_sys->mjpeg_buffers.count = 8;
1055         p_sys->mjpeg_buffers.size = MJPEG_BUFFER_SIZE;
1056
1057         if( v4l1_ioctl( i_fd, MJPIOC_REQBUFS, &p_sys->mjpeg_buffers ) < 0 )
1058         {
1059             msg_Err( p_demux, "mmap unsupported" );
1060             goto vdev_failed;
1061         }
1062
1063         p_sys->p_video_mmap = v4l1_mmap( 0,
1064                 p_sys->mjpeg_buffers.size * p_sys->mjpeg_buffers.count,
1065                 PROT_READ | PROT_WRITE, MAP_SHARED, i_fd, 0 );
1066         if( p_sys->p_video_mmap == MAP_FAILED )
1067         {
1068             msg_Err( p_demux, "mmap failed" );
1069             goto vdev_failed;
1070         }
1071
1072         p_sys->i_fourcc  = VLC_CODEC_MJPG;
1073         p_sys->i_frame_pos = -1;
1074
1075         /* queue up all the frames */
1076         for( i = 0; i < (int)p_sys->mjpeg_buffers.count; i++ )
1077         {
1078             if( v4l1_ioctl( i_fd, MJPIOC_QBUF_CAPT, &i ) < 0 )
1079             {
1080                 msg_Err( p_demux, "unable to queue frame" );
1081                 goto vdev_failed;
1082             }
1083         }
1084     }
1085     else
1086     {
1087         /* Fill in picture_t fields */
1088         if( picture_Setup( &p_sys->pic, p_sys->i_fourcc,
1089                            p_sys->i_width, p_sys->i_height,
1090                            1, 1 ) )
1091         {
1092             msg_Err( p_demux, "unsupported chroma" );
1093             goto vdev_failed;
1094         }
1095         p_sys->i_video_frame_size = 0;
1096         for( i = 0; i < p_sys->pic.i_planes; i++ )
1097         {
1098             p_sys->i_video_frame_size += p_sys->pic.p[i].i_visible_lines *
1099               p_sys->pic.p[i].i_visible_pitch;
1100         }
1101
1102         msg_Dbg( p_demux, "v4l device uses frame size: %i",
1103                  p_sys->i_video_frame_size );
1104         msg_Dbg( p_demux, "v4l device uses chroma: %4.4s",
1105                 (char*)&p_sys->i_fourcc );
1106
1107         /* Allocate mmap buffer */
1108         if( v4l1_ioctl( i_fd, VIDIOCGMBUF, &p_sys->vid_mbuf ) < 0 )
1109         {
1110             msg_Err( p_demux, "mmap unsupported" );
1111             goto vdev_failed;
1112         }
1113
1114         p_sys->p_video_mmap = v4l1_mmap( 0, p_sys->vid_mbuf.size,
1115                                     PROT_READ|PROT_WRITE, MAP_SHARED,
1116                                     i_fd, 0 );
1117         if( p_sys->p_video_mmap == MAP_FAILED )
1118         {
1119             /* FIXME -> normal read */
1120             msg_Err( p_demux, "mmap failed" );
1121             goto vdev_failed;
1122         }
1123
1124         /* init grabbing */
1125         p_sys->vid_mmap.frame  = 0;
1126         p_sys->vid_mmap.width  = p_sys->i_width;
1127         p_sys->vid_mmap.height = p_sys->i_height;
1128         p_sys->vid_mmap.format = p_sys->vid_picture.palette;
1129         if( v4l1_ioctl( i_fd, VIDIOCMCAPTURE, &p_sys->vid_mmap ) < 0 )
1130         {
1131             msg_Warn( p_demux, "%4.4s refused", (char*)&p_sys->i_fourcc );
1132             msg_Err( p_demux, "chroma selection failed" );
1133             goto vdev_failed;
1134         }
1135     }
1136     return i_fd;
1137
1138 vdev_failed:
1139
1140     if( i_fd >= 0 ) v4l1_close( i_fd );
1141     return -1;
1142 }
1143
1144 /*****************************************************************************
1145  * GrabVideo:
1146  *****************************************************************************/
1147 static uint8_t *GrabCapture( demux_t *p_demux )
1148 {
1149     demux_sys_t *p_sys = p_demux->p_sys;
1150     int i_captured_frame = p_sys->i_frame_pos;
1151
1152     p_sys->vid_mmap.frame = (p_sys->i_frame_pos + 1) % p_sys->vid_mbuf.frames;
1153
1154     while( v4l1_ioctl( p_sys->i_fd, VIDIOCMCAPTURE, &p_sys->vid_mmap ) < 0 )
1155     {
1156         if( errno != EAGAIN )
1157         {
1158             msg_Err( p_demux, "failed capturing new frame" );
1159             return NULL;
1160         }
1161
1162         if( !vlc_object_alive (p_demux) )
1163         {
1164             return NULL;
1165         }
1166
1167         msg_Dbg( p_demux, "grab failed, trying again" );
1168     }
1169
1170     while( v4l1_ioctl(p_sys->i_fd, VIDIOCSYNC, &p_sys->i_frame_pos) < 0 )
1171     {
1172         if( errno != EAGAIN && errno != EINTR )
1173         {
1174             msg_Err( p_demux, "failed syncing new frame" );
1175             return NULL;
1176         }
1177     }
1178
1179     p_sys->i_frame_pos = p_sys->vid_mmap.frame;
1180     /* leave i_video_frame_size alone */
1181     return p_sys->p_video_mmap + p_sys->vid_mbuf.offsets[i_captured_frame];
1182 }
1183
1184 static uint8_t *GrabMJPEG( demux_t *p_demux )
1185 {
1186     demux_sys_t *p_sys = p_demux->p_sys;
1187     struct mjpeg_sync sync;
1188     uint8_t *p_frame, *p_field, *p;
1189     uint16_t tag;
1190     uint32_t i_size;
1191     struct quicktime_mjpeg_app1 *p_app1 = NULL;
1192
1193     /* re-queue the last frame we sync'd */
1194     if( p_sys->i_frame_pos != -1 )
1195     {
1196         while( v4l1_ioctl( p_sys->i_fd, MJPIOC_QBUF_CAPT,
1197                                        &p_sys->i_frame_pos ) < 0 )
1198         {
1199             if( errno != EAGAIN && errno != EINTR )
1200             {
1201                 msg_Err( p_demux, "failed capturing new frame" );
1202                 return NULL;
1203             }
1204         }
1205     }
1206
1207     /* sync on the next frame */
1208     while( v4l1_ioctl( p_sys->i_fd, MJPIOC_SYNC, &sync ) < 0 )
1209     {
1210         if( errno != EAGAIN && errno != EINTR )
1211         {
1212             msg_Err( p_demux, "failed syncing new frame" );
1213             return NULL;
1214         }
1215     }
1216
1217     p_sys->i_frame_pos = sync.frame;
1218     p_frame = p_sys->p_video_mmap + p_sys->mjpeg_buffers.size * sync.frame;
1219
1220     /* p_frame now points to the data.  fix up the Quicktime APP1 marker */
1221     tag = 0xffd9;
1222     tag = hton16( tag );
1223     p_field = p_frame;
1224
1225     /* look for EOI */
1226     p = memmem( p_field, sync.length, &tag, 2 );
1227
1228     if( p )
1229     {
1230         p += 2; /* data immediately following EOI */
1231         /* UNALIGNED! */
1232         p_app1 = (struct quicktime_mjpeg_app1 *)(p_field + 6);
1233
1234         i_size = ((uint32_t)(p - p_field));
1235         i_size = hton32( i_size );
1236         memcpy( &p_app1->i_field_size, &i_size, 4 );
1237
1238         while( *p == 0xff && *(p+1) == 0xff )
1239             p++;
1240
1241         i_size = ((uint32_t)(p - p_field));
1242         i_size = hton32( i_size );
1243         memcpy( &p_app1->i_padded_field_size, &i_size, 4 );
1244     }
1245
1246     tag = 0xffd8;
1247     tag = hton16( tag );
1248     p_field = memmem( p, sync.length - (size_t)(p - p_frame), &tag, 2 );
1249
1250     if( p_field )
1251     {
1252         i_size = (uint32_t)(p_field - p_frame);
1253         i_size = hton32( i_size );
1254         memcpy( &p_app1->i_next_field, &i_size, 4 );
1255
1256         /* UNALIGNED! */
1257         p_app1 = (struct quicktime_mjpeg_app1 *)(p_field + 6);
1258         tag = 0xffd9;
1259         tag = hton16( tag );
1260         p = memmem( p_field, sync.length - (size_t)(p_field - p_frame),
1261                 &tag, 2 );
1262
1263         if( !p )
1264         {
1265             /* sometimes the second field doesn't have the EOI.  just put it
1266              * there
1267              */
1268             p = p_frame + sync.length;
1269             memcpy( p, &tag, 2 );
1270             sync.length += 2;
1271         }
1272
1273         p += 2;
1274         i_size = (uint32_t)(p - p_field);
1275         i_size = hton32( i_size );
1276         memcpy( &p_app1->i_field_size, &i_size, 4 );
1277         i_size = (uint32_t)(sync.length - (uint32_t)(p_field - p_frame));
1278         i_size = hton32( i_size );
1279         memcpy( &p_app1->i_padded_field_size, &i_size, 4 );
1280     }
1281
1282     p_sys->i_video_frame_size = sync.length;
1283     return p_frame;
1284 }
1285
1286 static block_t *GrabVideo( demux_t *p_demux )
1287 {
1288     demux_sys_t *p_sys = p_demux->p_sys;
1289     uint8_t     *p_frame;
1290     block_t     *p_block;
1291
1292     if( p_sys->f_fps >= 0.1 && p_sys->i_video_pts > 0 )
1293     {
1294         mtime_t i_dur = (mtime_t)((double)1000000 / (double)p_sys->f_fps);
1295
1296         /* Did we wait long enough ? (frame rate reduction) */
1297         if( p_sys->i_video_pts + i_dur > mdate() ) return 0;
1298     }
1299
1300     if( p_sys->b_mjpeg ) p_frame = GrabMJPEG( p_demux );
1301     else p_frame = GrabCapture( p_demux );
1302
1303     if( !p_frame ) return 0;
1304
1305     if( !( p_block = block_New( p_demux, p_sys->i_video_frame_size ) ) )
1306     {
1307         msg_Warn( p_demux, "cannot get block" );
1308         return 0;
1309     }
1310
1311     memcpy( p_block->p_buffer, p_frame, p_sys->i_video_frame_size );
1312     p_sys->i_video_pts = p_block->i_pts = p_block->i_dts = mdate();
1313
1314     return p_block;
1315 }