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