]> git.sesse.net Git - ffmpeg/blob - libavdevice/v4l2.c
lavd/v4l2: add list_standards option
[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 = &streamparm.parm.capture.timeperframe;
687     AVRational framerate_q = { 0 };
688     int i, ret;
689
690     streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
691
692     if (s->framerate &&
693         (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
694         av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n",
695                s->framerate);
696         return ret;
697     }
698
699     if (s->standard) {
700         av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s\n",
701                s->standard);
702         /* set tv standard */
703         for(i=0;;i++) {
704             standard.index = i;
705             ret = v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard);
706             if (ret < 0 || !av_strcasecmp(standard.name, s->standard))
707                 break;
708         }
709         if (ret < 0) {
710             av_log(s1, AV_LOG_ERROR, "Unknown standard '%s'\n", s->standard);
711             return ret;
712         }
713
714         av_log(s1, AV_LOG_DEBUG,
715                "The V4L2 driver set standard: %s, id: %"PRIu64"\n",
716                s->standard, (uint64_t)standard.id);
717         if (v4l2_ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
718             av_log(s1, AV_LOG_ERROR,
719                    "The V4L2 driver ioctl set standard(%s) failed\n",
720                    s->standard);
721             return AVERROR(EIO);
722         }
723     }
724
725     if (framerate_q.num && framerate_q.den) {
726         av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
727                framerate_q.den, framerate_q.num);
728         tpf->numerator   = framerate_q.den;
729         tpf->denominator = framerate_q.num;
730
731         if (v4l2_ioctl(s->fd, VIDIOC_S_PARM, &streamparm) != 0) {
732             av_log(s1, AV_LOG_ERROR,
733                    "ioctl set time per frame(%d/%d) failed\n",
734                    framerate_q.den, framerate_q.num);
735             return AVERROR(EIO);
736         }
737
738         if (framerate_q.num != tpf->denominator ||
739             framerate_q.den != tpf->numerator) {
740             av_log(s1, AV_LOG_INFO,
741                    "The driver changed the time per frame from "
742                    "%d/%d to %d/%d\n",
743                    framerate_q.den, framerate_q.num,
744                    tpf->numerator, tpf->denominator);
745         }
746     } else {
747         if (v4l2_ioctl(s->fd, VIDIOC_G_PARM, &streamparm) != 0) {
748             av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n",
749                    strerror(errno));
750             return AVERROR(errno);
751         }
752     }
753     s1->streams[0]->avg_frame_rate.num = tpf->denominator;
754     s1->streams[0]->avg_frame_rate.den = tpf->numerator;
755
756     return 0;
757 }
758
759 static int device_try_init(AVFormatContext *s1,
760                            enum AVPixelFormat pix_fmt,
761                            int *width,
762                            int *height,
763                            uint32_t *desired_format,
764                            enum AVCodecID *codec_id)
765 {
766     int ret, i;
767
768     *desired_format = fmt_ff2v4l(pix_fmt, s1->video_codec_id);
769
770     if (*desired_format) {
771         ret = device_init(s1, width, height, *desired_format);
772         if (ret < 0) {
773             *desired_format = 0;
774             if (ret != AVERROR(EINVAL))
775                 return ret;
776         }
777     }
778
779     if (!*desired_format) {
780         for (i = 0; i<FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
781             if (s1->video_codec_id == AV_CODEC_ID_NONE ||
782                 fmt_conversion_table[i].codec_id == s1->video_codec_id) {
783                 av_log(s1, AV_LOG_DEBUG, "Trying to set codec:%s pix_fmt:%s\n",
784                        avcodec_get_name(fmt_conversion_table[i].codec_id),
785                        (char *)av_x_if_null(av_get_pix_fmt_name(fmt_conversion_table[i].ff_fmt), "none"));
786
787                 *desired_format = fmt_conversion_table[i].v4l2_fmt;
788                 ret = device_init(s1, width, height, *desired_format);
789                 if (ret >= 0)
790                     break;
791                 else if (ret != AVERROR(EINVAL))
792                     return ret;
793                 *desired_format = 0;
794             }
795         }
796
797         if (*desired_format == 0) {
798             av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
799                    "codec '%s' (id %d), pixel format '%s' (id %d)\n",
800                    avcodec_get_name(s1->video_codec_id), s1->video_codec_id,
801                    (char *)av_x_if_null(av_get_pix_fmt_name(pix_fmt), "none"), pix_fmt);
802             ret = AVERROR(EINVAL);
803         }
804     }
805
806     *codec_id = fmt_v4l2codec(*desired_format);
807     av_assert0(*codec_id != AV_CODEC_ID_NONE);
808     return ret;
809 }
810
811 static int v4l2_read_header(AVFormatContext *s1)
812 {
813     struct video_data *s = s1->priv_data;
814     AVStream *st;
815     int res = 0;
816     uint32_t desired_format;
817     enum AVCodecID codec_id = AV_CODEC_ID_NONE;
818     enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;
819     struct v4l2_input input = { 0 };
820
821     st = avformat_new_stream(s1, NULL);
822     if (!st)
823         return AVERROR(ENOMEM);
824
825     s->fd = device_open(s1);
826     if (s->fd < 0)
827         return s->fd;
828
829     /* set tv video input */
830     av_log(s1, AV_LOG_DEBUG, "Selecting input_channel: %d\n", s->channel);
831     if (v4l2_ioctl(s->fd, VIDIOC_S_INPUT, &s->channel) < 0) {
832         res = errno;
833         av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_INPUT): %s\n", strerror(errno));
834         return AVERROR(res);
835     }
836
837     input.index = s->channel;
838     if (v4l2_ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
839         res = errno;
840         av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMINPUT): %s\n", strerror(errno));
841         return AVERROR(res);
842     }
843     s->std_id = input.std;
844     av_log(s1, AV_LOG_DEBUG, "input_channel: %d, input_name: %s\n",
845            s->channel, input.name);
846
847     if (s->list_format) {
848         list_formats(s1, s->fd, s->list_format);
849         return AVERROR_EXIT;
850     }
851
852     if (s->list_standard) {
853         list_standards(s1);
854         return AVERROR_EXIT;
855     }
856
857     avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
858
859     if (s->pixel_format) {
860         AVCodec *codec = avcodec_find_decoder_by_name(s->pixel_format);
861
862         if (codec)
863             s1->video_codec_id = codec->id;
864
865         pix_fmt = av_get_pix_fmt(s->pixel_format);
866
867         if (pix_fmt == AV_PIX_FMT_NONE && !codec) {
868             av_log(s1, AV_LOG_ERROR, "No such input format: %s.\n",
869                    s->pixel_format);
870
871             return AVERROR(EINVAL);
872         }
873     }
874
875     if (!s->width && !s->height) {
876         struct v4l2_format fmt;
877
878         av_log(s1, AV_LOG_VERBOSE,
879                "Querying the device for the current frame size\n");
880         fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
881         if (v4l2_ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
882             av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n",
883                    strerror(errno));
884             return AVERROR(errno);
885         }
886
887         s->width  = fmt.fmt.pix.width;
888         s->height = fmt.fmt.pix.height;
889         av_log(s1, AV_LOG_VERBOSE,
890                "Setting frame size to %dx%d\n", s->width, s->height);
891     }
892
893     res = device_try_init(s1, pix_fmt, &s->width, &s->height, &desired_format, &codec_id);
894     if (res < 0) {
895         v4l2_close(s->fd);
896         return res;
897     }
898
899     /* If no pixel_format was specified, the codec_id was not known up
900      * until now. Set video_codec_id in the context, as codec_id will
901      * not be available outside this function
902      */
903     if (codec_id != AV_CODEC_ID_NONE && s1->video_codec_id == AV_CODEC_ID_NONE)
904         s1->video_codec_id = codec_id;
905
906     if ((res = av_image_check_size(s->width, s->height, 0, s1)) < 0)
907         return res;
908
909     s->frame_format = desired_format;
910
911     if ((res = v4l2_set_parameters(s1)) < 0)
912         return res;
913
914     st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);
915     s->frame_size =
916         avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
917
918     if ((res = mmap_init(s1)) ||
919         (res = mmap_start(s1)) < 0) {
920         v4l2_close(s->fd);
921         return res;
922     }
923
924     s->top_field_first = first_field(s->fd);
925
926     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
927     st->codec->codec_id = codec_id;
928     if (codec_id == AV_CODEC_ID_RAWVIDEO)
929         st->codec->codec_tag =
930             avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
931     if (desired_format == V4L2_PIX_FMT_YVU420)
932         st->codec->codec_tag = MKTAG('Y', 'V', '1', '2');
933     st->codec->width = s->width;
934     st->codec->height = s->height;
935     st->codec->bit_rate = s->frame_size * av_q2d(st->avg_frame_rate) * 8;
936
937     return 0;
938 }
939
940 static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
941 {
942     struct video_data *s = s1->priv_data;
943     AVFrame *frame = s1->streams[0]->codec->coded_frame;
944     int res;
945
946     av_init_packet(pkt);
947     if ((res = mmap_read_frame(s1, pkt)) < 0) {
948         return res;
949     }
950
951     if (frame && s->interlaced) {
952         frame->interlaced_frame = 1;
953         frame->top_field_first = s->top_field_first;
954     }
955
956     return pkt->size;
957 }
958
959 static int v4l2_read_close(AVFormatContext *s1)
960 {
961     struct video_data *s = s1->priv_data;
962
963     mmap_close(s);
964
965     v4l2_close(s->fd);
966     return 0;
967 }
968
969 #define OFFSET(x) offsetof(struct video_data, x)
970 #define DEC AV_OPT_FLAG_DECODING_PARAM
971
972 static const AVOption options[] = {
973     { "standard",     "set TV standard, used only by analog frame grabber",       OFFSET(standard),     AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0,       DEC },
974     { "channel",      "set TV channel, used only by frame grabber",               OFFSET(channel),      AV_OPT_TYPE_INT,    {.i64 = 0 },    0, INT_MAX, DEC },
975     { "video_size",   "set frame size",                                           OFFSET(width),        AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL},  0, 0,   DEC },
976     { "pixel_format", "set preferred pixel format",                               OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
977     { "input_format", "set preferred pixel format (for raw video) or codec name", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
978     { "framerate",    "set frame rate",                                           OFFSET(framerate),    AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
979
980     { "list_formats", "list available formats and exit",                          OFFSET(list_format),  AV_OPT_TYPE_INT,    {.i64 = 0 },  0, INT_MAX, DEC, "list_formats" },
981     { "all",          "show all available formats",                               OFFSET(list_format),  AV_OPT_TYPE_CONST,  {.i64 = V4L_ALLFORMATS  },    0, INT_MAX, DEC, "list_formats" },
982     { "raw",          "show only non-compressed formats",                         OFFSET(list_format),  AV_OPT_TYPE_CONST,  {.i64 = V4L_RAWFORMATS  },    0, INT_MAX, DEC, "list_formats" },
983     { "compressed",   "show only compressed formats",                             OFFSET(list_format),  AV_OPT_TYPE_CONST,  {.i64 = V4L_COMPFORMATS },    0, INT_MAX, DEC, "list_formats" },
984
985     { "list_standards", "list supported standards and exit",                      OFFSET(list_standard), AV_OPT_TYPE_INT,   {.i64 = 0 },  0, 1, DEC, "list_standards" },
986     { "all",            "show all supported standards",                           OFFSET(list_standard), AV_OPT_TYPE_CONST, {.i64 = 1 },  0, 0, DEC, "list_standards" },
987
988     { "timestamps",   "set type of timestamps for grabbed frames",                OFFSET(ts_mode),      AV_OPT_TYPE_INT,    {.i64 = 0 }, 0, 2, DEC, "timestamps" },
989     { "ts",           "set type of timestamps for grabbed frames",                OFFSET(ts_mode),      AV_OPT_TYPE_INT,    {.i64 = 0 }, 0, 2, DEC, "timestamps" },
990     { "default",      "use timestamps from the kernel",                           OFFSET(ts_mode),      AV_OPT_TYPE_CONST,  {.i64 = V4L_TS_DEFAULT  }, 0, 2, DEC, "timestamps" },
991     { "abs",          "use absolute timestamps (wall clock)",                     OFFSET(ts_mode),      AV_OPT_TYPE_CONST,  {.i64 = V4L_TS_ABS      }, 0, 2, DEC, "timestamps" },
992     { "mono2abs",     "force conversion from monotonic to absolute timestamps",   OFFSET(ts_mode),      AV_OPT_TYPE_CONST,  {.i64 = V4L_TS_MONO2ABS }, 0, 2, DEC, "timestamps" },
993
994     { NULL },
995 };
996
997 static const AVClass v4l2_class = {
998     .class_name = "V4L2 indev",
999     .item_name  = av_default_item_name,
1000     .option     = options,
1001     .version    = LIBAVUTIL_VERSION_INT,
1002 };
1003
1004 AVInputFormat ff_v4l2_demuxer = {
1005     .name           = "video4linux2,v4l2",
1006     .long_name      = NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
1007     .priv_data_size = sizeof(struct video_data),
1008     .read_header    = v4l2_read_header,
1009     .read_packet    = v4l2_read_packet,
1010     .read_close     = v4l2_read_close,
1011     .flags          = AVFMT_NOFILE,
1012     .priv_class     = &v4l2_class,
1013 };