OSDN Git Service

lavdev: improve feedback in case of invalid frame rate/size
[coroid/libav_saccubus.git] / libavdevice / v4l2.c
1 /*
2  * Video4Linux2 grab interface
3  * Copyright (c) 2000,2001 Fabrice Bellard
4  * Copyright (c) 2006 Luca Abeni
5  *
6  * Part of this file is based on the V4L2 video capture example
7  * (http://v4l2spec.bytesex.org/v4l2spec/capture.c)
8  *
9  * Thanks to Michael Niedermayer for providing the mapping between
10  * V4L2_PIX_FMT_* and PIX_FMT_*
11  *
12  *
13  * This file is part of Libav.
14  *
15  * Libav is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU Lesser General Public
17  * License as published by the Free Software Foundation; either
18  * version 2.1 of the License, or (at your option) any later version.
19  *
20  * Libav is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23  * Lesser General Public License for more details.
24  *
25  * You should have received a copy of the GNU Lesser General Public
26  * License along with Libav; if not, write to the Free Software
27  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28  */
29
30 #undef __STRICT_ANSI__ //workaround due to broken kernel headers
31 #include "config.h"
32 #include "libavformat/avformat.h"
33 #include <unistd.h>
34 #include <fcntl.h>
35 #include <sys/ioctl.h>
36 #include <sys/mman.h>
37 #include <sys/time.h>
38 #if HAVE_SYS_VIDEOIO_H
39 #include <sys/videoio.h>
40 #else
41 #include <asm/types.h>
42 #include <linux/videodev2.h>
43 #endif
44 #include <time.h>
45 #include <strings.h>
46 #include "libavutil/imgutils.h"
47 #include "libavutil/log.h"
48 #include "libavutil/opt.h"
49 #include "libavutil/parseutils.h"
50 #include "libavutil/pixdesc.h"
51
52 static const int desired_video_buffers = 256;
53
54 enum io_method {
55     io_read,
56     io_mmap,
57     io_userptr
58 };
59
60 struct video_data {
61     AVClass *class;
62     int fd;
63     int frame_format; /* V4L2_PIX_FMT_* */
64     enum io_method io_method;
65     int width, height;
66     int frame_size;
67     int top_field_first;
68
69     int buffers;
70     void **buf_start;
71     unsigned int *buf_len;
72     char *standard;
73     int channel;
74     char *video_size; /**< String describing video size, set by a private option. */
75     char *pixel_format; /**< Set by a private option. */
76     char *framerate;    /**< Set by a private option. */
77 };
78
79 struct buff_data {
80     int index;
81     int fd;
82 };
83
84 struct fmt_map {
85     enum PixelFormat ff_fmt;
86     enum CodecID codec_id;
87     uint32_t v4l2_fmt;
88 };
89
90 static struct fmt_map fmt_conversion_table[] = {
91     //ff_fmt           codec_id           v4l2_fmt
92     { PIX_FMT_YUV420P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV420  },
93     { PIX_FMT_YUV422P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV422P },
94     { PIX_FMT_YUYV422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUYV    },
95     { PIX_FMT_UYVY422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_UYVY    },
96     { PIX_FMT_YUV411P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV411P },
97     { PIX_FMT_YUV410P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV410  },
98     { PIX_FMT_RGB555,  CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555  },
99     { PIX_FMT_RGB565,  CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565  },
100     { PIX_FMT_BGR24,   CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR24   },
101     { PIX_FMT_RGB24,   CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB24   },
102     { PIX_FMT_BGRA,    CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR32   },
103     { PIX_FMT_GRAY8,   CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_GREY    },
104     { PIX_FMT_NV12,    CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_NV12    },
105     { PIX_FMT_NONE,    CODEC_ID_MJPEG,    V4L2_PIX_FMT_MJPEG   },
106     { PIX_FMT_NONE,    CODEC_ID_MJPEG,    V4L2_PIX_FMT_JPEG    },
107 };
108
109 static int device_open(AVFormatContext *ctx, uint32_t *capabilities)
110 {
111     struct v4l2_capability cap;
112     int fd;
113     int res, err;
114     int flags = O_RDWR;
115
116     if (ctx->flags & AVFMT_FLAG_NONBLOCK) {
117         flags |= O_NONBLOCK;
118     }
119     fd = open(ctx->filename, flags, 0);
120     if (fd < 0) {
121         av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s : %s\n",
122                  ctx->filename, strerror(errno));
123
124         return AVERROR(errno);
125     }
126
127     res = ioctl(fd, VIDIOC_QUERYCAP, &cap);
128     // ENOIOCTLCMD definition only availble on __KERNEL__
129     if (res < 0 && ((err = errno) == 515)) {
130         av_log(ctx, AV_LOG_ERROR, "QUERYCAP not implemented, probably V4L device but not supporting V4L2\n");
131         close(fd);
132
133         return AVERROR(515);
134     }
135     if (res < 0) {
136         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",
137                  strerror(errno));
138         close(fd);
139
140         return AVERROR(err);
141     }
142     if ((cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) == 0) {
143         av_log(ctx, AV_LOG_ERROR, "Not a video capture device\n");
144         close(fd);
145
146         return AVERROR(ENODEV);
147     }
148     *capabilities = cap.capabilities;
149
150     return fd;
151 }
152
153 static int device_init(AVFormatContext *ctx, int *width, int *height, uint32_t pix_fmt)
154 {
155     struct video_data *s = ctx->priv_data;
156     int fd = s->fd;
157     struct v4l2_format fmt;
158     int res;
159
160     memset(&fmt, 0, sizeof(struct v4l2_format));
161     fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
162     fmt.fmt.pix.width = *width;
163     fmt.fmt.pix.height = *height;
164     fmt.fmt.pix.pixelformat = pix_fmt;
165     fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
166     res = ioctl(fd, VIDIOC_S_FMT, &fmt);
167     if ((*width != fmt.fmt.pix.width) || (*height != fmt.fmt.pix.height)) {
168         av_log(ctx, AV_LOG_INFO, "The V4L2 driver changed the video from %dx%d to %dx%d\n", *width, *height, fmt.fmt.pix.width, fmt.fmt.pix.height);
169         *width = fmt.fmt.pix.width;
170         *height = fmt.fmt.pix.height;
171     }
172
173     if (pix_fmt != fmt.fmt.pix.pixelformat) {
174         av_log(ctx, AV_LOG_DEBUG, "The V4L2 driver changed the pixel format from 0x%08X to 0x%08X\n", pix_fmt, fmt.fmt.pix.pixelformat);
175         res = -1;
176     }
177
178     return res;
179 }
180
181 static int first_field(int fd)
182 {
183     int res;
184     v4l2_std_id std;
185
186     res = ioctl(fd, VIDIOC_G_STD, &std);
187     if (res < 0) {
188         return 0;
189     }
190     if (std & V4L2_STD_NTSC) {
191         return 0;
192     }
193
194     return 1;
195 }
196
197 static uint32_t fmt_ff2v4l(enum PixelFormat pix_fmt, enum CodecID codec_id)
198 {
199     int i;
200
201     for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
202         if ((codec_id == CODEC_ID_NONE ||
203              fmt_conversion_table[i].codec_id == codec_id) &&
204             (pix_fmt == PIX_FMT_NONE ||
205              fmt_conversion_table[i].ff_fmt == pix_fmt)) {
206             return fmt_conversion_table[i].v4l2_fmt;
207         }
208     }
209
210     return 0;
211 }
212
213 static enum PixelFormat fmt_v4l2ff(uint32_t v4l2_fmt, enum CodecID codec_id)
214 {
215     int i;
216
217     for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
218         if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt &&
219             fmt_conversion_table[i].codec_id == codec_id) {
220             return fmt_conversion_table[i].ff_fmt;
221         }
222     }
223
224     return PIX_FMT_NONE;
225 }
226
227 static enum CodecID fmt_v4l2codec(uint32_t v4l2_fmt)
228 {
229     int i;
230
231     for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
232         if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt) {
233             return fmt_conversion_table[i].codec_id;
234         }
235     }
236
237     return CODEC_ID_NONE;
238 }
239
240 static int mmap_init(AVFormatContext *ctx)
241 {
242     struct video_data *s = ctx->priv_data;
243     struct v4l2_requestbuffers req;
244     int i, res;
245
246     memset(&req, 0, sizeof(struct v4l2_requestbuffers));
247     req.count = desired_video_buffers;
248     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
249     req.memory = V4L2_MEMORY_MMAP;
250     res = ioctl(s->fd, VIDIOC_REQBUFS, &req);
251     if (res < 0) {
252         if (errno == EINVAL) {
253             av_log(ctx, AV_LOG_ERROR, "Device does not support mmap\n");
254         } else {
255             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_REQBUFS)\n");
256         }
257
258         return AVERROR(errno);
259     }
260
261     if (req.count < 2) {
262         av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
263
264         return AVERROR(ENOMEM);
265     }
266     s->buffers = req.count;
267     s->buf_start = av_malloc(sizeof(void *) * s->buffers);
268     if (s->buf_start == NULL) {
269         av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer pointers\n");
270
271         return AVERROR(ENOMEM);
272     }
273     s->buf_len = av_malloc(sizeof(unsigned int) * s->buffers);
274     if (s->buf_len == NULL) {
275         av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer sizes\n");
276         av_free(s->buf_start);
277
278         return AVERROR(ENOMEM);
279     }
280
281     for (i = 0; i < req.count; i++) {
282         struct v4l2_buffer buf;
283
284         memset(&buf, 0, sizeof(struct v4l2_buffer));
285         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
286         buf.memory = V4L2_MEMORY_MMAP;
287         buf.index = i;
288         res = ioctl(s->fd, VIDIOC_QUERYBUF, &buf);
289         if (res < 0) {
290             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF)\n");
291
292             return AVERROR(errno);
293         }
294
295         s->buf_len[i] = buf.length;
296         if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
297             av_log(ctx, AV_LOG_ERROR, "Buffer len [%d] = %d != %d\n", i, s->buf_len[i], s->frame_size);
298
299             return -1;
300         }
301         s->buf_start[i] = mmap (NULL, buf.length,
302                         PROT_READ | PROT_WRITE, MAP_SHARED, s->fd, buf.m.offset);
303         if (s->buf_start[i] == MAP_FAILED) {
304             av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", strerror(errno));
305
306             return AVERROR(errno);
307         }
308     }
309
310     return 0;
311 }
312
313 static int read_init(AVFormatContext *ctx)
314 {
315     return -1;
316 }
317
318 static void mmap_release_buffer(AVPacket *pkt)
319 {
320     struct v4l2_buffer buf;
321     int res, fd;
322     struct buff_data *buf_descriptor = pkt->priv;
323
324     if (pkt->data == NULL) {
325          return;
326     }
327
328     memset(&buf, 0, sizeof(struct v4l2_buffer));
329     buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
330     buf.memory = V4L2_MEMORY_MMAP;
331     buf.index = buf_descriptor->index;
332     fd = buf_descriptor->fd;
333     av_free(buf_descriptor);
334
335     res = ioctl(fd, VIDIOC_QBUF, &buf);
336     if (res < 0) {
337         av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", strerror(errno));
338     }
339     pkt->data = NULL;
340     pkt->size = 0;
341 }
342
343 static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
344 {
345     struct video_data *s = ctx->priv_data;
346     struct v4l2_buffer buf;
347     struct buff_data *buf_descriptor;
348     int res;
349
350     memset(&buf, 0, sizeof(struct v4l2_buffer));
351     buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
352     buf.memory = V4L2_MEMORY_MMAP;
353
354     /* FIXME: Some special treatment might be needed in case of loss of signal... */
355     while ((res = ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
356     if (res < 0) {
357         if (errno == EAGAIN) {
358             pkt->size = 0;
359
360             return AVERROR(EAGAIN);
361         }
362         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n", strerror(errno));
363
364         return AVERROR(errno);
365     }
366     assert (buf.index < s->buffers);
367     if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
368         av_log(ctx, AV_LOG_ERROR, "The v4l2 frame is %d bytes, but %d bytes are expected\n", buf.bytesused, s->frame_size);
369
370         return AVERROR_INVALIDDATA;
371     }
372
373     /* Image is at s->buff_start[buf.index] */
374     pkt->data= s->buf_start[buf.index];
375     pkt->size = buf.bytesused;
376     pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
377     pkt->destruct = mmap_release_buffer;
378     buf_descriptor = av_malloc(sizeof(struct buff_data));
379     if (buf_descriptor == NULL) {
380         /* Something went wrong... Since av_malloc() failed, we cannot even
381          * allocate a buffer for memcopying into it
382          */
383         av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
384         res = ioctl(s->fd, VIDIOC_QBUF, &buf);
385
386         return AVERROR(ENOMEM);
387     }
388     buf_descriptor->fd = s->fd;
389     buf_descriptor->index = buf.index;
390     pkt->priv = buf_descriptor;
391
392     return s->buf_len[buf.index];
393 }
394
395 static int read_frame(AVFormatContext *ctx, AVPacket *pkt)
396 {
397     return -1;
398 }
399
400 static int mmap_start(AVFormatContext *ctx)
401 {
402     struct video_data *s = ctx->priv_data;
403     enum v4l2_buf_type type;
404     int i, res;
405
406     for (i = 0; i < s->buffers; i++) {
407         struct v4l2_buffer buf;
408
409         memset(&buf, 0, sizeof(struct v4l2_buffer));
410         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
411         buf.memory = V4L2_MEMORY_MMAP;
412         buf.index  = i;
413
414         res = ioctl(s->fd, VIDIOC_QBUF, &buf);
415         if (res < 0) {
416             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", strerror(errno));
417
418             return AVERROR(errno);
419         }
420     }
421
422     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
423     res = ioctl(s->fd, VIDIOC_STREAMON, &type);
424     if (res < 0) {
425         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n", strerror(errno));
426
427         return AVERROR(errno);
428     }
429
430     return 0;
431 }
432
433 static void mmap_close(struct video_data *s)
434 {
435     enum v4l2_buf_type type;
436     int i;
437
438     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
439     /* We do not check for the result, because we could
440      * not do anything about it anyway...
441      */
442     ioctl(s->fd, VIDIOC_STREAMOFF, &type);
443     for (i = 0; i < s->buffers; i++) {
444         munmap(s->buf_start[i], s->buf_len[i]);
445     }
446     av_free(s->buf_start);
447     av_free(s->buf_len);
448 }
449
450 static int v4l2_set_parameters(AVFormatContext *s1, AVFormatParameters *ap)
451 {
452     struct video_data *s = s1->priv_data;
453     struct v4l2_input input;
454     struct v4l2_standard standard;
455     struct v4l2_streamparm streamparm = { 0 };
456     struct v4l2_fract *tpf = &streamparm.parm.capture.timeperframe;
457     int i, ret;
458     AVRational framerate_q;
459
460     streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
461
462     if (s->framerate && (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
463         av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n", s->framerate);
464         return ret;
465     }
466 #if FF_API_FORMAT_PARAMETERS
467     if (ap->channel > 0)
468         s->channel = ap->channel;
469     if (ap->time_base.num)
470         framerate_q = (AVRational){ap->time_base.den, ap->time_base.num};
471 #endif
472
473     /* set tv video input */
474     memset (&input, 0, sizeof (input));
475     input.index = s->channel;
476     if (ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
477         av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl enum input failed:\n");
478         return AVERROR(EIO);
479     }
480
481     av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set input_id: %d, input: %s\n",
482             s->channel, input.name);
483     if (ioctl(s->fd, VIDIOC_S_INPUT, &input.index) < 0) {
484         av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set input(%d) failed\n",
485                 s->channel);
486         return AVERROR(EIO);
487     }
488
489 #if FF_API_FORMAT_PARAMETERS
490     if (ap->standard) {
491         av_freep(&s->standard);
492         s->standard = av_strdup(ap->standard);
493     }
494 #endif
495
496     if (s->standard) {
497         av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s\n",
498                s->standard);
499         /* set tv standard */
500         memset (&standard, 0, sizeof (standard));
501         for(i=0;;i++) {
502             standard.index = i;
503             if (ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
504                 av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set standard(%s) failed\n",
505                        s->standard);
506                 return AVERROR(EIO);
507             }
508
509             if (!strcasecmp(standard.name, s->standard)) {
510                 break;
511             }
512         }
513
514         av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s, id: %"PRIu64"\n",
515                s->standard, (uint64_t)standard.id);
516         if (ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
517             av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set standard(%s) failed\n",
518                    s->standard);
519             return AVERROR(EIO);
520         }
521     }
522
523     if (framerate_q.num && framerate_q.den) {
524         av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
525                framerate_q.den, framerate_q.num);
526         tpf->numerator   = framerate_q.den;
527         tpf->denominator = framerate_q.num;
528         if (ioctl(s->fd, VIDIOC_S_PARM, &streamparm) != 0) {
529             av_log(s1, AV_LOG_ERROR,
530                    "ioctl set time per frame(%d/%d) failed\n",
531                    framerate_q.den, framerate_q.num);
532             return AVERROR(EIO);
533         }
534
535         if (framerate_q.num != tpf->denominator ||
536             framerate_q.den != tpf->numerator) {
537             av_log(s1, AV_LOG_INFO,
538                    "The driver changed the time per frame from %d/%d to %d/%d\n",
539                    framerate_q.den, framerate_q.num,
540                    tpf->numerator, tpf->denominator);
541         }
542     } else {
543         /* if timebase value is not set, read the timebase value from the driver */
544         if (ioctl(s->fd, VIDIOC_G_PARM, &streamparm) != 0) {
545             av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n", strerror(errno));
546             return AVERROR(errno);
547         }
548     }
549     s1->streams[0]->codec->time_base.den = tpf->denominator;
550     s1->streams[0]->codec->time_base.num = tpf->numerator;
551
552     return 0;
553 }
554
555 static uint32_t device_try_init(AVFormatContext *s1,
556                                 enum PixelFormat pix_fmt,
557                                 int *width,
558                                 int *height,
559                                 enum CodecID *codec_id)
560 {
561     uint32_t desired_format = fmt_ff2v4l(pix_fmt, s1->video_codec_id);
562
563     if (desired_format == 0 ||
564         device_init(s1, width, height, desired_format) < 0) {
565         int i;
566
567         desired_format = 0;
568         for (i = 0; i<FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
569             if (s1->video_codec_id == CODEC_ID_NONE ||
570                 fmt_conversion_table[i].codec_id == s1->video_codec_id) {
571                 desired_format = fmt_conversion_table[i].v4l2_fmt;
572                 if (device_init(s1, width, height, desired_format) >= 0) {
573                     break;
574                 }
575                 desired_format = 0;
576             }
577         }
578     }
579     if (desired_format != 0) {
580         *codec_id = fmt_v4l2codec(desired_format);
581         assert(*codec_id != CODEC_ID_NONE);
582     }
583
584     return desired_format;
585 }
586
587 static int v4l2_read_header(AVFormatContext *s1, AVFormatParameters *ap)
588 {
589     struct video_data *s = s1->priv_data;
590     AVStream *st;
591     int res = 0;
592     uint32_t desired_format, capabilities;
593     enum CodecID codec_id;
594     enum PixelFormat pix_fmt = PIX_FMT_NONE;
595
596     st = av_new_stream(s1, 0);
597     if (!st) {
598         res = AVERROR(ENOMEM);
599         goto out;
600     }
601     av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
602
603     if (s->video_size && (res = av_parse_video_size(&s->width, &s->height, s->video_size)) < 0) {
604         av_log(s1, AV_LOG_ERROR, "Could not parse video size '%s'.\n", s->video_size);
605         goto out;
606     }
607     if (s->pixel_format && (pix_fmt = av_get_pix_fmt(s->pixel_format)) == PIX_FMT_NONE) {
608         av_log(s1, AV_LOG_ERROR, "No such pixel format: %s.\n", s->pixel_format);
609         res = AVERROR(EINVAL);
610         goto out;
611     }
612 #if FF_API_FORMAT_PARAMETERS
613     if (ap->width > 0)
614         s->width  = ap->width;
615     if (ap->height > 0)
616         s->height = ap->height;
617     if (ap->pix_fmt)
618         pix_fmt = ap->pix_fmt;
619 #endif
620
621     capabilities = 0;
622     s->fd = device_open(s1, &capabilities);
623     if (s->fd < 0) {
624         res = AVERROR(EIO);
625         goto out;
626     }
627     av_log(s1, AV_LOG_VERBOSE, "[%d]Capabilities: %x\n", s->fd, capabilities);
628
629     if (!s->width && !s->height) {
630         struct v4l2_format fmt;
631
632         av_log(s1, AV_LOG_VERBOSE, "Querying the device for the current frame size\n");
633         fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
634         if (ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
635             av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n", strerror(errno));
636             res = AVERROR(errno);
637             goto out;
638         }
639         s->width  = fmt.fmt.pix.width;
640         s->height = fmt.fmt.pix.height;
641         av_log(s1, AV_LOG_VERBOSE, "Setting frame size to %dx%d\n", s->width, s->height);
642     }
643
644     desired_format = device_try_init(s1, pix_fmt, &s->width, &s->height, &codec_id);
645     if (desired_format == 0) {
646         av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
647                "codec_id %d, pix_fmt %d.\n", s1->video_codec_id, pix_fmt);
648         close(s->fd);
649
650         res = AVERROR(EIO);
651         goto out;
652     }
653     if ((res = av_image_check_size(s->width, s->height, 0, s1) < 0))
654         goto out;
655     s->frame_format = desired_format;
656
657     if ((res = v4l2_set_parameters(s1, ap) < 0))
658         goto out;
659
660     st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);
661     s->frame_size = avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
662     if (capabilities & V4L2_CAP_STREAMING) {
663         s->io_method = io_mmap;
664         res = mmap_init(s1);
665         if (res == 0) {
666             res = mmap_start(s1);
667         }
668     } else {
669         s->io_method = io_read;
670         res = read_init(s1);
671     }
672     if (res < 0) {
673         close(s->fd);
674
675         res = AVERROR(EIO);
676         goto out;
677     }
678     s->top_field_first = first_field(s->fd);
679
680     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
681     st->codec->codec_id = codec_id;
682     st->codec->width = s->width;
683     st->codec->height = s->height;
684     st->codec->bit_rate = s->frame_size * 1/av_q2d(st->codec->time_base) * 8;
685
686 out:
687     return res;
688 }
689
690 static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
691 {
692     struct video_data *s = s1->priv_data;
693     int res;
694
695     if (s->io_method == io_mmap) {
696         av_init_packet(pkt);
697         res = mmap_read_frame(s1, pkt);
698     } else if (s->io_method == io_read) {
699         if (av_new_packet(pkt, s->frame_size) < 0)
700             return AVERROR(EIO);
701
702         res = read_frame(s1, pkt);
703     } else {
704         return AVERROR(EIO);
705     }
706     if (res < 0) {
707         return res;
708     }
709
710     if (s1->streams[0]->codec->coded_frame) {
711         s1->streams[0]->codec->coded_frame->interlaced_frame = 1;
712         s1->streams[0]->codec->coded_frame->top_field_first = s->top_field_first;
713     }
714
715     return pkt->size;
716 }
717
718 static int v4l2_read_close(AVFormatContext *s1)
719 {
720     struct video_data *s = s1->priv_data;
721
722     if (s->io_method == io_mmap) {
723         mmap_close(s);
724     }
725
726     close(s->fd);
727     return 0;
728 }
729
730 #define OFFSET(x) offsetof(struct video_data, x)
731 #define DEC AV_OPT_FLAG_DECODING_PARAM
732 static const AVOption options[] = {
733     { "standard", "", offsetof(struct video_data, standard), FF_OPT_TYPE_STRING, {.str = NULL }, 0, 0, AV_OPT_FLAG_DECODING_PARAM },
734     { "channel",  "", offsetof(struct video_data, channel),  FF_OPT_TYPE_INT,    {.dbl = 0 }, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
735     { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), FF_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
736     { "pixel_format", "", OFFSET(pixel_format), FF_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
737     { "framerate", "", OFFSET(framerate), FF_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
738     { NULL },
739 };
740
741 static const AVClass v4l2_class = {
742     .class_name = "V4L2 indev",
743     .item_name  = av_default_item_name,
744     .option     = options,
745     .version    = LIBAVUTIL_VERSION_INT,
746 };
747
748 AVInputFormat ff_v4l2_demuxer = {
749     "video4linux2",
750     NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
751     sizeof(struct video_data),
752     NULL,
753     v4l2_read_header,
754     v4l2_read_packet,
755     v4l2_read_close,
756     .flags = AVFMT_NOFILE,
757     .priv_class = &v4l2_class,
758 };