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