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