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