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