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