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