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