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