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