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