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