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