]> git.sesse.net Git - ffmpeg/blob - libavdevice/v4l2.c
avopt: Store defaults for AV_OPT_TYPE_INT in the i64 union member
[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 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 PixelFormat 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     { PIX_FMT_YUV420P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV420  },
95     { PIX_FMT_YUV422P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV422P },
96     { PIX_FMT_YUYV422, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUYV    },
97     { PIX_FMT_UYVY422, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_UYVY    },
98     { PIX_FMT_YUV411P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV411P },
99     { PIX_FMT_YUV410P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV410  },
100     { PIX_FMT_RGB555,  AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555  },
101     { PIX_FMT_RGB565,  AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565  },
102     { PIX_FMT_BGR24,   AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR24   },
103     { PIX_FMT_RGB24,   AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB24   },
104     { PIX_FMT_BGRA,    AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR32   },
105     { PIX_FMT_GRAY8,   AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_GREY    },
106     { PIX_FMT_NV12,    AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_NV12    },
107     { PIX_FMT_NONE,    AV_CODEC_ID_MJPEG,    V4L2_PIX_FMT_MJPEG   },
108     { 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 PixelFormat 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 == 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 PixelFormat 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 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 PixelFormat 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     assert (buf.index < s->buffers);
464     if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
465         av_log(ctx, AV_LOG_ERROR,
466                "The v4l2 frame is %d bytes, but %d bytes are expected\n",
467                buf.bytesused, s->frame_size);
468
469         return AVERROR_INVALIDDATA;
470     }
471
472     /* Image is at s->buff_start[buf.index] */
473     pkt->data= s->buf_start[buf.index];
474     pkt->size = buf.bytesused;
475     pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
476     pkt->destruct = mmap_release_buffer;
477     buf_descriptor = av_malloc(sizeof(struct buff_data));
478     if (buf_descriptor == NULL) {
479         /* Something went wrong... Since av_malloc() failed, we cannot even
480          * allocate a buffer for memcopying into it
481          */
482         av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
483         res = ioctl(s->fd, VIDIOC_QBUF, &buf);
484
485         return AVERROR(ENOMEM);
486     }
487     buf_descriptor->fd = s->fd;
488     buf_descriptor->index = buf.index;
489     pkt->priv = buf_descriptor;
490
491     return s->buf_len[buf.index];
492 }
493
494 static int mmap_start(AVFormatContext *ctx)
495 {
496     struct video_data *s = ctx->priv_data;
497     enum v4l2_buf_type type;
498     int i, res;
499
500     for (i = 0; i < s->buffers; i++) {
501         struct v4l2_buffer buf = {
502             .type   = V4L2_BUF_TYPE_VIDEO_CAPTURE,
503             .index  = i,
504             .memory = V4L2_MEMORY_MMAP
505         };
506
507         res = ioctl(s->fd, VIDIOC_QBUF, &buf);
508         if (res < 0) {
509             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
510                    strerror(errno));
511
512             return AVERROR(errno);
513         }
514     }
515
516     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
517     res = ioctl(s->fd, VIDIOC_STREAMON, &type);
518     if (res < 0) {
519         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n",
520                strerror(errno));
521
522         return AVERROR(errno);
523     }
524
525     return 0;
526 }
527
528 static void mmap_close(struct video_data *s)
529 {
530     enum v4l2_buf_type type;
531     int i;
532
533     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
534     /* We do not check for the result, because we could
535      * not do anything about it anyway...
536      */
537     ioctl(s->fd, VIDIOC_STREAMOFF, &type);
538     for (i = 0; i < s->buffers; i++) {
539         munmap(s->buf_start[i], s->buf_len[i]);
540     }
541     av_free(s->buf_start);
542     av_free(s->buf_len);
543 }
544
545 static int v4l2_set_parameters(AVFormatContext *s1)
546 {
547     struct video_data *s = s1->priv_data;
548     struct v4l2_input input = { 0 };
549     struct v4l2_standard standard = { 0 };
550     struct v4l2_streamparm streamparm = { 0 };
551     struct v4l2_fract *tpf = &streamparm.parm.capture.timeperframe;
552     AVRational framerate_q = { 0 };
553     int i, ret;
554
555     streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
556
557     if (s->framerate &&
558         (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
559         av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n",
560                s->framerate);
561         return ret;
562     }
563
564     /* set tv video input */
565     input.index = s->channel;
566     if (ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
567         av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl enum input failed:\n");
568         return AVERROR(EIO);
569     }
570
571     av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set input_id: %d, input: %s\n",
572             s->channel, input.name);
573     if (ioctl(s->fd, VIDIOC_S_INPUT, &input.index) < 0) {
574         av_log(s1, AV_LOG_ERROR,
575                "The V4L2 driver ioctl set input(%d) failed\n",
576                 s->channel);
577         return AVERROR(EIO);
578     }
579
580     if (s->standard) {
581         av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s\n",
582                s->standard);
583         /* set tv standard */
584         for(i=0;;i++) {
585             standard.index = i;
586             if (ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
587                 av_log(s1, AV_LOG_ERROR,
588                        "The V4L2 driver ioctl set standard(%s) failed\n",
589                        s->standard);
590                 return AVERROR(EIO);
591             }
592
593             if (!av_strcasecmp(standard.name, s->standard)) {
594                 break;
595             }
596         }
597
598         av_log(s1, AV_LOG_DEBUG,
599                "The V4L2 driver set standard: %s, id: %"PRIu64"\n",
600                s->standard, (uint64_t)standard.id);
601         if (ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
602             av_log(s1, AV_LOG_ERROR,
603                    "The V4L2 driver ioctl set standard(%s) failed\n",
604                    s->standard);
605             return AVERROR(EIO);
606         }
607     }
608
609     if (framerate_q.num && framerate_q.den) {
610         av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
611                framerate_q.den, framerate_q.num);
612         tpf->numerator   = framerate_q.den;
613         tpf->denominator = framerate_q.num;
614
615         if (ioctl(s->fd, VIDIOC_S_PARM, &streamparm) != 0) {
616             av_log(s1, AV_LOG_ERROR,
617                    "ioctl set time per frame(%d/%d) failed\n",
618                    framerate_q.den, framerate_q.num);
619             return AVERROR(EIO);
620         }
621
622         if (framerate_q.num != tpf->denominator ||
623             framerate_q.den != tpf->numerator) {
624             av_log(s1, AV_LOG_INFO,
625                    "The driver changed the time per frame from "
626                    "%d/%d to %d/%d\n",
627                    framerate_q.den, framerate_q.num,
628                    tpf->numerator, tpf->denominator);
629         }
630     } else {
631         if (ioctl(s->fd, VIDIOC_G_PARM, &streamparm) != 0) {
632             av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n",
633                    strerror(errno));
634             return AVERROR(errno);
635         }
636     }
637     s1->streams[0]->codec->time_base.den = tpf->denominator;
638     s1->streams[0]->codec->time_base.num = tpf->numerator;
639
640     s->timeout = 100 +
641         av_rescale_q(1, s1->streams[0]->codec->time_base,
642                         (AVRational){1, 1000});
643
644     return 0;
645 }
646
647 static uint32_t device_try_init(AVFormatContext *s1,
648                                 enum PixelFormat pix_fmt,
649                                 int *width,
650                                 int *height,
651                                 enum AVCodecID *codec_id)
652 {
653     uint32_t desired_format = fmt_ff2v4l(pix_fmt, s1->video_codec_id);
654
655     if (desired_format == 0 ||
656         device_init(s1, width, height, desired_format) < 0) {
657         int i;
658
659         desired_format = 0;
660         for (i = 0; i<FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
661             if (s1->video_codec_id == AV_CODEC_ID_NONE ||
662                 fmt_conversion_table[i].codec_id == s1->video_codec_id) {
663                 desired_format = fmt_conversion_table[i].v4l2_fmt;
664                 if (device_init(s1, width, height, desired_format) >= 0) {
665                     break;
666                 }
667                 desired_format = 0;
668             }
669         }
670     }
671
672     if (desired_format != 0) {
673         *codec_id = fmt_v4l2codec(desired_format);
674         assert(*codec_id != AV_CODEC_ID_NONE);
675     }
676
677     return desired_format;
678 }
679
680 static int v4l2_read_header(AVFormatContext *s1)
681 {
682     struct video_data *s = s1->priv_data;
683     AVStream *st;
684     int res = 0;
685     uint32_t desired_format;
686     enum AVCodecID codec_id;
687     enum PixelFormat pix_fmt = PIX_FMT_NONE;
688
689     st = avformat_new_stream(s1, NULL);
690     if (!st) {
691         res = AVERROR(ENOMEM);
692         goto out;
693     }
694
695     s->fd = device_open(s1);
696     if (s->fd < 0) {
697         res = s->fd;
698         goto out;
699     }
700
701     if (s->list_format) {
702         list_formats(s1, s->fd, s->list_format);
703         res = AVERROR_EXIT;
704         goto out;
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         goto out;
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 == PIX_FMT_NONE && !codec) {
725             av_log(s1, AV_LOG_ERROR, "No such input format: %s.\n",
726                    s->pixel_format);
727
728             res = AVERROR(EINVAL);
729             goto out;
730         }
731     }
732
733     if (!s->width && !s->height) {
734         struct v4l2_format fmt;
735
736         av_log(s1, AV_LOG_VERBOSE,
737                "Querying the device for the current frame size\n");
738         fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
739         if (ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
740             av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n",
741                    strerror(errno));
742             res = AVERROR(errno);
743             goto out;
744         }
745
746         s->width  = fmt.fmt.pix.width;
747         s->height = fmt.fmt.pix.height;
748         av_log(s1, AV_LOG_VERBOSE,
749                "Setting frame size to %dx%d\n", s->width, s->height);
750     }
751
752     desired_format = device_try_init(s1, pix_fmt, &s->width, &s->height,
753                                      &codec_id);
754     if (desired_format == 0) {
755         av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
756                "codec_id %d, pix_fmt %d.\n", s1->video_codec_id, pix_fmt);
757         close(s->fd);
758
759         res = AVERROR(EIO);
760         goto out;
761     }
762
763     if ((res = av_image_check_size(s->width, s->height, 0, s1) < 0))
764         goto out;
765
766     s->frame_format = desired_format;
767
768     if ((res = v4l2_set_parameters(s1) < 0))
769         goto out;
770
771     st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);
772     s->frame_size =
773         avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
774
775     if ((res = mmap_init(s1)) ||
776         (res = mmap_start(s1)) < 0) {
777         close(s->fd);
778         goto out;
779     }
780
781     s->top_field_first = first_field(s->fd);
782
783     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
784     st->codec->codec_id = codec_id;
785     if (codec_id == AV_CODEC_ID_RAWVIDEO)
786         st->codec->codec_tag =
787             avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
788     st->codec->width = s->width;
789     st->codec->height = s->height;
790     st->codec->bit_rate = s->frame_size * 1/av_q2d(st->codec->time_base) * 8;
791
792 out:
793     return res;
794 }
795
796 static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
797 {
798     struct video_data *s = s1->priv_data;
799     AVFrame *frame = s1->streams[0]->codec->coded_frame;
800     int res;
801
802     av_init_packet(pkt);
803     if ((res = mmap_read_frame(s1, pkt)) < 0) {
804         return res;
805     }
806
807     if (frame && s->interlaced) {
808         frame->interlaced_frame = 1;
809         frame->top_field_first = s->top_field_first;
810     }
811
812     return pkt->size;
813 }
814
815 static int v4l2_read_close(AVFormatContext *s1)
816 {
817     struct video_data *s = s1->priv_data;
818
819     mmap_close(s);
820
821     close(s->fd);
822     return 0;
823 }
824
825 #define OFFSET(x) offsetof(struct video_data, x)
826 #define DEC AV_OPT_FLAG_DECODING_PARAM
827 static const AVOption options[] = {
828     { "standard",     "TV standard, used only by analog frame grabber",            OFFSET(standard),     AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0,       DEC },
829     { "channel",      "TV channel, used only by frame grabber",                    OFFSET(channel),      AV_OPT_TYPE_INT,    {.i64 = 0 },    0, INT_MAX, DEC },
830     { "video_size",   "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size),   AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
831     { "pixel_format", "Preferred pixel format",                                    OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
832     { "input_format", "Preferred pixel format (for raw video) or codec name",      OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
833     { "framerate",    "",                                                          OFFSET(framerate),    AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
834     { "list_formats", "List available formats and exit",                           OFFSET(list_format),  AV_OPT_TYPE_INT,    {.i64 = 0 },  0, INT_MAX, DEC, "list_formats" },
835     { "all",          "Show all available formats",                                OFFSET(list_format),  AV_OPT_TYPE_CONST,  {.i64 = V4L_ALLFORMATS  },    0, INT_MAX, DEC, "list_formats" },
836     { "raw",          "Show only non-compressed formats",                          OFFSET(list_format),  AV_OPT_TYPE_CONST,  {.i64 = V4L_RAWFORMATS  },    0, INT_MAX, DEC, "list_formats" },
837     { "compressed",   "Show only compressed formats",                              OFFSET(list_format),  AV_OPT_TYPE_CONST,  {.i64 = V4L_COMPFORMATS },    0, INT_MAX, DEC, "list_formats" },
838     { NULL },
839 };
840
841 static const AVClass v4l2_class = {
842     .class_name = "V4L2 indev",
843     .item_name  = av_default_item_name,
844     .option     = options,
845     .version    = LIBAVUTIL_VERSION_INT,
846 };
847
848 AVInputFormat ff_v4l2_demuxer = {
849     .name           = "video4linux2",
850     .long_name      = NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
851     .priv_data_size = sizeof(struct video_data),
852     .read_header    = v4l2_read_header,
853     .read_packet    = v4l2_read_packet,
854     .read_close     = v4l2_read_close,
855     .flags          = AVFMT_NOFILE,
856     .priv_class     = &v4l2_class,
857 };