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