]> git.sesse.net Git - ffmpeg/blob - libavdevice/v4l2.c
Merge commit '56daf10e0313c5e36f43e773f457d2a99ff0df10'
[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     int list_standard;  /**< Set by a private option. */
120     char *framerate;    /**< Set by a private option. */
121 };
122
123 struct buff_data {
124     int index;
125     int fd;
126 };
127
128 struct fmt_map {
129     enum AVPixelFormat ff_fmt;
130     enum AVCodecID codec_id;
131     uint32_t v4l2_fmt;
132 };
133
134 static struct fmt_map fmt_conversion_table[] = {
135     //ff_fmt           codec_id           v4l2_fmt
136     { AV_PIX_FMT_YUV420P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV420  },
137     { AV_PIX_FMT_YUV420P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YVU420  },
138     { AV_PIX_FMT_YUV422P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV422P },
139     { AV_PIX_FMT_YUYV422, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUYV    },
140     { AV_PIX_FMT_UYVY422, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_UYVY    },
141     { AV_PIX_FMT_YUV411P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV411P },
142     { AV_PIX_FMT_YUV410P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV410  },
143     { AV_PIX_FMT_YUV410P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YVU410  },
144     { AV_PIX_FMT_RGB555LE,AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555  },
145     { AV_PIX_FMT_RGB555BE,AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555X },
146     { AV_PIX_FMT_RGB565LE,AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565  },
147     { AV_PIX_FMT_RGB565BE,AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565X },
148     { AV_PIX_FMT_BGR24,   AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR24   },
149     { AV_PIX_FMT_RGB24,   AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB24   },
150     { AV_PIX_FMT_BGR0,    AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR32   },
151     { AV_PIX_FMT_0RGB,    AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB32   },
152     { AV_PIX_FMT_GRAY8,   AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_GREY    },
153 #ifdef V4L2_PIX_FMT_Y16
154     { AV_PIX_FMT_GRAY16LE,AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_Y16     },
155 #endif
156     { AV_PIX_FMT_NV12,    AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_NV12    },
157     { AV_PIX_FMT_NONE,    AV_CODEC_ID_MJPEG,    V4L2_PIX_FMT_MJPEG   },
158     { AV_PIX_FMT_NONE,    AV_CODEC_ID_MJPEG,    V4L2_PIX_FMT_JPEG    },
159 #ifdef V4L2_PIX_FMT_H264
160     { AV_PIX_FMT_NONE,    AV_CODEC_ID_H264,     V4L2_PIX_FMT_H264    },
161 #endif
162 #ifdef V4L2_PIX_FMT_CPIA1
163     { AV_PIX_FMT_NONE,    AV_CODEC_ID_CPIA,     V4L2_PIX_FMT_CPIA1   },
164 #endif
165 };
166
167 static int device_open(AVFormatContext *ctx)
168 {
169     struct v4l2_capability cap;
170     int fd;
171     int ret;
172     int flags = O_RDWR;
173
174     if (ctx->flags & AVFMT_FLAG_NONBLOCK) {
175         flags |= O_NONBLOCK;
176     }
177
178     fd = v4l2_open(ctx->filename, flags, 0);
179     if (fd < 0) {
180         ret = AVERROR(errno);
181         av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s: %s\n",
182                ctx->filename, av_err2str(ret));
183         return ret;
184     }
185
186     if (v4l2_ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0) {
187         ret = AVERROR(errno);
188         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",
189                av_err2str(ret));
190         goto fail;
191     }
192
193     av_log(ctx, AV_LOG_VERBOSE, "fd:%d capabilities:%x\n",
194            fd, cap.capabilities);
195
196     if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
197         av_log(ctx, AV_LOG_ERROR, "Not a video capture device.\n");
198         ret = AVERROR(ENODEV);
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         ret = AVERROR(ENOSYS);
206         goto fail;
207     }
208
209     return fd;
210
211 fail:
212     v4l2_close(fd);
213     return ret;
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_decoder(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 void list_standards(AVFormatContext *ctx)
384 {
385     int ret;
386     struct video_data *s = ctx->priv_data;
387     struct v4l2_standard standard;
388
389     if (s->std_id == 0)
390         return;
391
392     for (standard.index = 0; ; standard.index++) {
393         if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
394             ret = AVERROR(errno);
395             if (ret == AVERROR(EINVAL)) {
396                 break;
397             } else {
398                 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMSTD): %s\n", av_err2str(ret));
399                 return;
400             }
401         }
402         av_log(ctx, AV_LOG_INFO, "%2d, %16llx, %s\n",
403                standard.index, standard.id, standard.name);
404     }
405 }
406
407 static int mmap_init(AVFormatContext *ctx)
408 {
409     int i, res;
410     struct video_data *s = ctx->priv_data;
411     struct v4l2_requestbuffers req = {
412         .type   = V4L2_BUF_TYPE_VIDEO_CAPTURE,
413         .count  = desired_video_buffers,
414         .memory = V4L2_MEMORY_MMAP
415     };
416
417     if (v4l2_ioctl(s->fd, VIDIOC_REQBUFS, &req) < 0) {
418         res = AVERROR(errno);
419         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_REQBUFS): %s\n", av_err2str(res));
420         return res;
421     }
422
423     if (req.count < 2) {
424         av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
425         return AVERROR(ENOMEM);
426     }
427     s->buffers = req.count;
428     s->buf_start = av_malloc(sizeof(void *) * s->buffers);
429     if (s->buf_start == NULL) {
430         av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer pointers\n");
431         return AVERROR(ENOMEM);
432     }
433     s->buf_len = av_malloc(sizeof(unsigned int) * s->buffers);
434     if (s->buf_len == NULL) {
435         av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer sizes\n");
436         av_free(s->buf_start);
437         return AVERROR(ENOMEM);
438     }
439
440     for (i = 0; i < req.count; i++) {
441         struct v4l2_buffer buf = {
442             .type   = V4L2_BUF_TYPE_VIDEO_CAPTURE,
443             .index  = i,
444             .memory = V4L2_MEMORY_MMAP
445         };
446         if (v4l2_ioctl(s->fd, VIDIOC_QUERYBUF, &buf) < 0) {
447             res = AVERROR(errno);
448             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF): %s\n", av_err2str(res));
449             return res;
450         }
451
452         s->buf_len[i] = buf.length;
453         if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
454             av_log(ctx, AV_LOG_ERROR,
455                    "buf_len[%d] = %d < expected frame size %d\n",
456                    i, s->buf_len[i], s->frame_size);
457             return AVERROR(ENOMEM);
458         }
459         s->buf_start[i] = v4l2_mmap(NULL, buf.length,
460                                PROT_READ | PROT_WRITE, MAP_SHARED,
461                                s->fd, buf.m.offset);
462
463         if (s->buf_start[i] == MAP_FAILED) {
464             res = AVERROR(errno);
465             av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", av_err2str(res));
466             return res;
467         }
468     }
469
470     return 0;
471 }
472
473 static void mmap_release_buffer(AVPacket *pkt)
474 {
475     struct v4l2_buffer buf = { 0 };
476     int res, fd;
477     struct buff_data *buf_descriptor = pkt->priv;
478
479     if (pkt->data == NULL)
480         return;
481
482     buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
483     buf.memory = V4L2_MEMORY_MMAP;
484     buf.index = buf_descriptor->index;
485     fd = buf_descriptor->fd;
486     av_free(buf_descriptor);
487
488     if (v4l2_ioctl(fd, VIDIOC_QBUF, &buf) < 0) {
489         res = AVERROR(errno);
490         av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", av_err2str(res));
491     }
492
493     pkt->data = NULL;
494     pkt->size = 0;
495 }
496
497 #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
498 static int64_t av_gettime_monotonic(void)
499 {
500     struct timespec tv;
501
502     clock_gettime(CLOCK_MONOTONIC, &tv);
503     return (int64_t)tv.tv_sec * 1000000 + tv.tv_nsec / 1000;
504 }
505 #endif
506
507 static int init_convert_timestamp(AVFormatContext *ctx, int64_t ts)
508 {
509     struct video_data *s = ctx->priv_data;
510     int64_t now;
511
512     now = av_gettime();
513     if (s->ts_mode == V4L_TS_ABS &&
514         ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE) {
515         av_log(ctx, AV_LOG_INFO, "Detected absolute timestamps\n");
516         s->ts_mode = V4L_TS_CONVERT_READY;
517         return 0;
518     }
519 #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
520     now = av_gettime_monotonic();
521     if (s->ts_mode == V4L_TS_MONO2ABS ||
522         (ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE)) {
523         int64_t period = av_rescale_q(1, AV_TIME_BASE_Q,
524                                       ctx->streams[0]->avg_frame_rate);
525         av_log(ctx, AV_LOG_INFO, "Detected monotonic timestamps, converting\n");
526         /* microseconds instead of seconds, MHz instead of Hz */
527         s->timefilter = ff_timefilter_new(1, period, 1.0E-6);
528         s->ts_mode = V4L_TS_CONVERT_READY;
529         return 0;
530     }
531 #endif
532     av_log(ctx, AV_LOG_ERROR, "Unknown timestamps\n");
533     return AVERROR(EIO);
534 }
535
536 static int convert_timestamp(AVFormatContext *ctx, int64_t *ts)
537 {
538     struct video_data *s = ctx->priv_data;
539
540     if (s->ts_mode) {
541         int r = init_convert_timestamp(ctx, *ts);
542         if (r < 0)
543             return r;
544     }
545 #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
546     if (s->timefilter) {
547         int64_t nowa = av_gettime();
548         int64_t nowm = av_gettime_monotonic();
549         ff_timefilter_update(s->timefilter, nowa, nowm - s->last_time_m);
550         s->last_time_m = nowm;
551         *ts = ff_timefilter_eval(s->timefilter, *ts - nowm);
552     }
553 #endif
554     return 0;
555 }
556
557 static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
558 {
559     struct video_data *s = ctx->priv_data;
560     struct v4l2_buffer buf = {
561         .type   = V4L2_BUF_TYPE_VIDEO_CAPTURE,
562         .memory = V4L2_MEMORY_MMAP
563     };
564     struct buff_data *buf_descriptor;
565     int res;
566
567     /* FIXME: Some special treatment might be needed in case of loss of signal... */
568     while ((res = v4l2_ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
569     if (res < 0) {
570         if (errno == EAGAIN) {
571             pkt->size = 0;
572             return AVERROR(EAGAIN);
573         }
574         res = AVERROR(errno);
575         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n", av_err2str(res));
576         return res;
577     }
578
579     if (buf.index >= s->buffers) {
580         av_log(ctx, AV_LOG_ERROR, "Invalid buffer index received.\n");
581         return AVERROR(EINVAL);
582     }
583
584     /* CPIA is a compressed format and we don't know the exact number of bytes
585      * used by a frame, so set it here as the driver announces it.
586      */
587     if (ctx->video_codec_id == AV_CODEC_ID_CPIA)
588         s->frame_size = buf.bytesused;
589
590     if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
591         av_log(ctx, AV_LOG_ERROR,
592                "The v4l2 frame is %d bytes, but %d bytes are expected\n",
593                buf.bytesused, s->frame_size);
594         return AVERROR_INVALIDDATA;
595     }
596
597     /* Image is at s->buff_start[buf.index] */
598     pkt->data= s->buf_start[buf.index];
599     pkt->size = buf.bytesused;
600     pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
601     res = convert_timestamp(ctx, &pkt->pts);
602     if (res < 0)
603         return res;
604     pkt->destruct = mmap_release_buffer;
605     buf_descriptor = av_malloc(sizeof(struct buff_data));
606     if (buf_descriptor == NULL) {
607         /* Something went wrong... Since av_malloc() failed, we cannot even
608          * allocate a buffer for memcopying into it
609          */
610         av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
611         res = v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf);
612         return AVERROR(ENOMEM);
613     }
614     buf_descriptor->fd = s->fd;
615     buf_descriptor->index = buf.index;
616     pkt->priv = buf_descriptor;
617
618     return s->buf_len[buf.index];
619 }
620
621 static int mmap_start(AVFormatContext *ctx)
622 {
623     struct video_data *s = ctx->priv_data;
624     enum v4l2_buf_type type;
625     int i, res;
626
627     for (i = 0; i < s->buffers; i++) {
628         struct v4l2_buffer buf = {
629             .type   = V4L2_BUF_TYPE_VIDEO_CAPTURE,
630             .index  = i,
631             .memory = V4L2_MEMORY_MMAP
632         };
633
634         if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) < 0) {
635             res = AVERROR(errno);
636             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", av_err2str(res));
637             return res;
638         }
639     }
640
641     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
642     if (v4l2_ioctl(s->fd, VIDIOC_STREAMON, &type) < 0) {
643         res = AVERROR(errno);
644         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n", av_err2str(res));
645         return res;
646     }
647
648     return 0;
649 }
650
651 static void mmap_close(struct video_data *s)
652 {
653     enum v4l2_buf_type type;
654     int i;
655
656     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
657     /* We do not check for the result, because we could
658      * not do anything about it anyway...
659      */
660     v4l2_ioctl(s->fd, VIDIOC_STREAMOFF, &type);
661     for (i = 0; i < s->buffers; i++) {
662         v4l2_munmap(s->buf_start[i], s->buf_len[i]);
663     }
664     av_free(s->buf_start);
665     av_free(s->buf_len);
666 }
667
668 static int v4l2_set_parameters(AVFormatContext *s1)
669 {
670     struct video_data *s = s1->priv_data;
671     struct v4l2_standard standard = { 0 };
672     struct v4l2_streamparm streamparm = { 0 };
673     struct v4l2_fract *tpf;
674     AVRational framerate_q = { 0 };
675     int i, ret;
676
677     if (s->framerate &&
678         (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
679         av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n",
680                s->framerate);
681         return ret;
682     }
683
684     if (s->standard) {
685         if (s->std_id) {
686             ret = 0;
687             av_log(s1, AV_LOG_DEBUG, "Setting standard: %s\n", s->standard);
688             /* set tv standard */
689             for (i = 0; ; i++) {
690                 standard.index = i;
691                 if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
692                     ret = AVERROR(errno);
693                     break;
694                 }
695                 if (!av_strcasecmp(standard.name, s->standard))
696                     break;
697             }
698             if (ret < 0) {
699                 av_log(s1, AV_LOG_ERROR, "Unknown or unsupported standard '%s'\n", s->standard);
700                 return ret;
701             }
702
703             if (v4l2_ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
704                 ret = AVERROR(errno);
705                 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_STD): %s\n", av_err2str(ret));
706                 return ret;
707             }
708         } else {
709             av_log(s1, AV_LOG_WARNING,
710                    "This device does not support any standard\n");
711         }
712     }
713
714     /* get standard */
715     if (v4l2_ioctl(s->fd, VIDIOC_G_STD, &s->std_id) == 0) {
716         tpf = &standard.frameperiod;
717         for (i = 0; ; i++) {
718             standard.index = i;
719             if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
720                 ret = AVERROR(errno);
721                 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMSTD): %s\n", av_err2str(ret));
722                 return ret;
723             }
724             if (standard.id == s->std_id) {
725                 av_log(s1, AV_LOG_DEBUG,
726                        "Current standard: %s, id: %"PRIu64", frameperiod: %d/%d\n",
727                        standard.name, (uint64_t)standard.id, tpf->numerator, tpf->denominator);
728                 break;
729             }
730         }
731     } else {
732         tpf = &streamparm.parm.capture.timeperframe;
733     }
734
735     streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
736     if (v4l2_ioctl(s->fd, VIDIOC_G_PARM, &streamparm) < 0) {
737         ret = AVERROR(errno);
738         av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n", av_err2str(ret));
739         return ret;
740     }
741
742     if (framerate_q.num && framerate_q.den) {
743         if (streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) {
744             tpf = &streamparm.parm.capture.timeperframe;
745
746             av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
747                    framerate_q.den, framerate_q.num);
748             tpf->numerator   = framerate_q.den;
749             tpf->denominator = framerate_q.num;
750
751             if (v4l2_ioctl(s->fd, VIDIOC_S_PARM, &streamparm) < 0) {
752                 ret = AVERROR(errno);
753                 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_PARM): %s\n", av_err2str(ret));
754                 return ret;
755             }
756
757             if (framerate_q.num != tpf->denominator ||
758                 framerate_q.den != tpf->numerator) {
759                 av_log(s1, AV_LOG_INFO,
760                        "The driver changed the time per frame from "
761                        "%d/%d to %d/%d\n",
762                        framerate_q.den, framerate_q.num,
763                        tpf->numerator, tpf->denominator);
764             }
765         } else {
766             av_log(s1, AV_LOG_WARNING,
767                    "The driver does not allow to change time per frame\n");
768         }
769     }
770     s1->streams[0]->avg_frame_rate.num = tpf->denominator;
771     s1->streams[0]->avg_frame_rate.den = tpf->numerator;
772
773     return 0;
774 }
775
776 static int device_try_init(AVFormatContext *s1,
777                            enum AVPixelFormat pix_fmt,
778                            int *width,
779                            int *height,
780                            uint32_t *desired_format,
781                            enum AVCodecID *codec_id)
782 {
783     int ret, i;
784
785     *desired_format = fmt_ff2v4l(pix_fmt, s1->video_codec_id);
786
787     if (*desired_format) {
788         ret = device_init(s1, width, height, *desired_format);
789         if (ret < 0) {
790             *desired_format = 0;
791             if (ret != AVERROR(EINVAL))
792                 return ret;
793         }
794     }
795
796     if (!*desired_format) {
797         for (i = 0; i<FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
798             if (s1->video_codec_id == AV_CODEC_ID_NONE ||
799                 fmt_conversion_table[i].codec_id == s1->video_codec_id) {
800                 av_log(s1, AV_LOG_DEBUG, "Trying to set codec:%s pix_fmt:%s\n",
801                        avcodec_get_name(fmt_conversion_table[i].codec_id),
802                        (char *)av_x_if_null(av_get_pix_fmt_name(fmt_conversion_table[i].ff_fmt), "none"));
803
804                 *desired_format = fmt_conversion_table[i].v4l2_fmt;
805                 ret = device_init(s1, width, height, *desired_format);
806                 if (ret >= 0)
807                     break;
808                 else if (ret != AVERROR(EINVAL))
809                     return ret;
810                 *desired_format = 0;
811             }
812         }
813
814         if (*desired_format == 0) {
815             av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
816                    "codec '%s' (id %d), pixel format '%s' (id %d)\n",
817                    avcodec_get_name(s1->video_codec_id), s1->video_codec_id,
818                    (char *)av_x_if_null(av_get_pix_fmt_name(pix_fmt), "none"), pix_fmt);
819             ret = AVERROR(EINVAL);
820         }
821     }
822
823     *codec_id = fmt_v4l2codec(*desired_format);
824     av_assert0(*codec_id != AV_CODEC_ID_NONE);
825     return ret;
826 }
827
828 static int v4l2_read_header(AVFormatContext *s1)
829 {
830     struct video_data *s = s1->priv_data;
831     AVStream *st;
832     int res = 0;
833     uint32_t desired_format;
834     enum AVCodecID codec_id = AV_CODEC_ID_NONE;
835     enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;
836     struct v4l2_input input = { 0 };
837
838     st = avformat_new_stream(s1, NULL);
839     if (!st)
840         return AVERROR(ENOMEM);
841
842     s->fd = device_open(s1);
843     if (s->fd < 0)
844         return s->fd;
845
846     /* set tv video input */
847     av_log(s1, AV_LOG_DEBUG, "Selecting input_channel: %d\n", s->channel);
848     if (v4l2_ioctl(s->fd, VIDIOC_S_INPUT, &s->channel) < 0) {
849         res = AVERROR(errno);
850         av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_INPUT): %s\n", av_err2str(res));
851         return res;
852     }
853
854     input.index = s->channel;
855     if (v4l2_ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
856         res = AVERROR(errno);
857         av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMINPUT): %s\n", av_err2str(res));
858         return res;
859     }
860     s->std_id = input.std;
861     av_log(s1, AV_LOG_DEBUG, "input_channel: %d, input_name: %s\n",
862            s->channel, input.name);
863
864     if (s->list_format) {
865         list_formats(s1, s->fd, s->list_format);
866         return AVERROR_EXIT;
867     }
868
869     if (s->list_standard) {
870         list_standards(s1);
871         return AVERROR_EXIT;
872     }
873
874     avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
875
876     if (s->pixel_format) {
877         AVCodec *codec = avcodec_find_decoder_by_name(s->pixel_format);
878
879         if (codec)
880             s1->video_codec_id = codec->id;
881
882         pix_fmt = av_get_pix_fmt(s->pixel_format);
883
884         if (pix_fmt == AV_PIX_FMT_NONE && !codec) {
885             av_log(s1, AV_LOG_ERROR, "No such input format: %s.\n",
886                    s->pixel_format);
887
888             return AVERROR(EINVAL);
889         }
890     }
891
892     if (!s->width && !s->height) {
893         struct v4l2_format fmt;
894
895         av_log(s1, AV_LOG_VERBOSE,
896                "Querying the device for the current frame size\n");
897         fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
898         if (v4l2_ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
899             res = AVERROR(errno);
900             av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n", av_err2str(res));
901             return res;
902         }
903
904         s->width  = fmt.fmt.pix.width;
905         s->height = fmt.fmt.pix.height;
906         av_log(s1, AV_LOG_VERBOSE,
907                "Setting frame size to %dx%d\n", s->width, s->height);
908     }
909
910     res = device_try_init(s1, pix_fmt, &s->width, &s->height, &desired_format, &codec_id);
911     if (res < 0) {
912         v4l2_close(s->fd);
913         return res;
914     }
915
916     /* If no pixel_format was specified, the codec_id was not known up
917      * until now. Set video_codec_id in the context, as codec_id will
918      * not be available outside this function
919      */
920     if (codec_id != AV_CODEC_ID_NONE && s1->video_codec_id == AV_CODEC_ID_NONE)
921         s1->video_codec_id = codec_id;
922
923     if ((res = av_image_check_size(s->width, s->height, 0, s1)) < 0)
924         return res;
925
926     s->frame_format = desired_format;
927
928     if ((res = v4l2_set_parameters(s1)) < 0)
929         return res;
930
931     st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);
932     s->frame_size =
933         avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
934
935     if ((res = mmap_init(s1)) ||
936         (res = mmap_start(s1)) < 0) {
937         v4l2_close(s->fd);
938         return res;
939     }
940
941     s->top_field_first = first_field(s->fd);
942
943     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
944     st->codec->codec_id = codec_id;
945     if (codec_id == AV_CODEC_ID_RAWVIDEO)
946         st->codec->codec_tag =
947             avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
948     if (desired_format == V4L2_PIX_FMT_YVU420)
949         st->codec->codec_tag = MKTAG('Y', 'V', '1', '2');
950     else if (desired_format == V4L2_PIX_FMT_YVU410)
951         st->codec->codec_tag = MKTAG('Y', 'V', 'U', '9');
952     st->codec->width = s->width;
953     st->codec->height = s->height;
954     st->codec->bit_rate = s->frame_size * av_q2d(st->avg_frame_rate) * 8;
955
956     return 0;
957 }
958
959 static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
960 {
961     struct video_data *s = s1->priv_data;
962     AVFrame *frame = s1->streams[0]->codec->coded_frame;
963     int res;
964
965     av_init_packet(pkt);
966     if ((res = mmap_read_frame(s1, pkt)) < 0) {
967         return res;
968     }
969
970     if (frame && s->interlaced) {
971         frame->interlaced_frame = 1;
972         frame->top_field_first = s->top_field_first;
973     }
974
975     return pkt->size;
976 }
977
978 static int v4l2_read_close(AVFormatContext *s1)
979 {
980     struct video_data *s = s1->priv_data;
981
982     mmap_close(s);
983
984     v4l2_close(s->fd);
985     return 0;
986 }
987
988 #define OFFSET(x) offsetof(struct video_data, x)
989 #define DEC AV_OPT_FLAG_DECODING_PARAM
990
991 static const AVOption options[] = {
992     { "standard",     "set TV standard, used only by analog frame grabber",       OFFSET(standard),     AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0,       DEC },
993     { "channel",      "set TV channel, used only by frame grabber",               OFFSET(channel),      AV_OPT_TYPE_INT,    {.i64 = 0 },    0, INT_MAX, DEC },
994     { "video_size",   "set frame size",                                           OFFSET(width),        AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL},  0, 0,   DEC },
995     { "pixel_format", "set preferred pixel format",                               OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
996     { "input_format", "set preferred pixel format (for raw video) or codec name", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
997     { "framerate",    "set frame rate",                                           OFFSET(framerate),    AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
998
999     { "list_formats", "list available formats and exit",                          OFFSET(list_format),  AV_OPT_TYPE_INT,    {.i64 = 0 },  0, INT_MAX, DEC, "list_formats" },
1000     { "all",          "show all available formats",                               OFFSET(list_format),  AV_OPT_TYPE_CONST,  {.i64 = V4L_ALLFORMATS  },    0, INT_MAX, DEC, "list_formats" },
1001     { "raw",          "show only non-compressed formats",                         OFFSET(list_format),  AV_OPT_TYPE_CONST,  {.i64 = V4L_RAWFORMATS  },    0, INT_MAX, DEC, "list_formats" },
1002     { "compressed",   "show only compressed formats",                             OFFSET(list_format),  AV_OPT_TYPE_CONST,  {.i64 = V4L_COMPFORMATS },    0, INT_MAX, DEC, "list_formats" },
1003
1004     { "list_standards", "list supported standards and exit",                      OFFSET(list_standard), AV_OPT_TYPE_INT,   {.i64 = 0 },  0, 1, DEC, "list_standards" },
1005     { "all",            "show all supported standards",                           OFFSET(list_standard), AV_OPT_TYPE_CONST, {.i64 = 1 },  0, 0, DEC, "list_standards" },
1006
1007     { "timestamps",   "set type of timestamps for grabbed frames",                OFFSET(ts_mode),      AV_OPT_TYPE_INT,    {.i64 = 0 }, 0, 2, DEC, "timestamps" },
1008     { "ts",           "set type of timestamps for grabbed frames",                OFFSET(ts_mode),      AV_OPT_TYPE_INT,    {.i64 = 0 }, 0, 2, DEC, "timestamps" },
1009     { "default",      "use timestamps from the kernel",                           OFFSET(ts_mode),      AV_OPT_TYPE_CONST,  {.i64 = V4L_TS_DEFAULT  }, 0, 2, DEC, "timestamps" },
1010     { "abs",          "use absolute timestamps (wall clock)",                     OFFSET(ts_mode),      AV_OPT_TYPE_CONST,  {.i64 = V4L_TS_ABS      }, 0, 2, DEC, "timestamps" },
1011     { "mono2abs",     "force conversion from monotonic to absolute timestamps",   OFFSET(ts_mode),      AV_OPT_TYPE_CONST,  {.i64 = V4L_TS_MONO2ABS }, 0, 2, DEC, "timestamps" },
1012
1013     { NULL },
1014 };
1015
1016 static const AVClass v4l2_class = {
1017     .class_name = "V4L2 indev",
1018     .item_name  = av_default_item_name,
1019     .option     = options,
1020     .version    = LIBAVUTIL_VERSION_INT,
1021 };
1022
1023 AVInputFormat ff_v4l2_demuxer = {
1024     .name           = "video4linux2,v4l2",
1025     .long_name      = NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
1026     .priv_data_size = sizeof(struct video_data),
1027     .read_header    = v4l2_read_header,
1028     .read_packet    = v4l2_read_packet,
1029     .read_close     = v4l2_read_close,
1030     .flags          = AVFMT_NOFILE,
1031     .priv_class     = &v4l2_class,
1032 };