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