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