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