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