2 * V4L2 context helper functions.
4 * Copyright (C) 2017 Alexis Ballier <aballier@gentoo.org>
5 * Copyright (C) 2017 Jorge Ramirez <jorge.ramirez-ortiz@linaro.org>
7 * This file is part of FFmpeg.
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 #include <linux/videodev2.h>
25 #include <sys/ioctl.h>
30 #include "libavcodec/avcodec.h"
31 #include "libavcodec/internal.h"
32 #include "v4l2_buffers.h"
36 struct v4l2_format_update {
40 enum AVPixelFormat av_fmt;
44 static inline V4L2m2mContext *ctx_to_m2mctx(V4L2Context *ctx)
46 return V4L2_TYPE_IS_OUTPUT(ctx->type) ?
47 container_of(ctx, V4L2m2mContext, output) :
48 container_of(ctx, V4L2m2mContext, capture);
51 static inline AVCodecContext *logger(V4L2Context *ctx)
53 return ctx_to_m2mctx(ctx)->avctx;
56 static inline unsigned int v4l2_get_width(struct v4l2_format *fmt)
58 return V4L2_TYPE_IS_MULTIPLANAR(fmt->type) ? fmt->fmt.pix_mp.width : fmt->fmt.pix.width;
61 static inline unsigned int v4l2_get_height(struct v4l2_format *fmt)
63 return V4L2_TYPE_IS_MULTIPLANAR(fmt->type) ? fmt->fmt.pix_mp.height : fmt->fmt.pix.height;
66 static inline unsigned int v4l2_resolution_changed(V4L2Context *ctx, struct v4l2_format *fmt2)
68 struct v4l2_format *fmt1 = &ctx->format;
69 int ret = V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ?
70 fmt1->fmt.pix_mp.width != fmt2->fmt.pix_mp.width ||
71 fmt1->fmt.pix_mp.height != fmt2->fmt.pix_mp.height
73 fmt1->fmt.pix.width != fmt2->fmt.pix.width ||
74 fmt1->fmt.pix.height != fmt2->fmt.pix.height;
77 av_log(logger(ctx), AV_LOG_DEBUG, "%s changed (%dx%d) -> (%dx%d)\n",
79 v4l2_get_width(fmt1), v4l2_get_height(fmt1),
80 v4l2_get_width(fmt2), v4l2_get_height(fmt2));
85 static inline int v4l2_type_supported(V4L2Context *ctx)
87 return ctx->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE ||
88 ctx->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE ||
89 ctx->type == V4L2_BUF_TYPE_VIDEO_CAPTURE ||
90 ctx->type == V4L2_BUF_TYPE_VIDEO_OUTPUT;
93 static inline void v4l2_save_to_context(V4L2Context* ctx, struct v4l2_format_update *fmt)
95 ctx->format.type = ctx->type;
97 if (fmt->update_avfmt)
98 ctx->av_pix_fmt = fmt->av_fmt;
100 if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
101 /* update the sizes to handle the reconfiguration of the capture stream at runtime */
102 ctx->format.fmt.pix_mp.height = ctx->height;
103 ctx->format.fmt.pix_mp.width = ctx->width;
104 if (fmt->update_v4l2)
105 ctx->format.fmt.pix_mp.pixelformat = fmt->v4l2_fmt;
107 ctx->format.fmt.pix.height = ctx->height;
108 ctx->format.fmt.pix.width = ctx->width;
109 if (fmt->update_v4l2)
110 ctx->format.fmt.pix.pixelformat = fmt->v4l2_fmt;
115 * returns 1 if reinit was successful, negative if it failed
116 * returns 0 if reinit was not executed
118 static int v4l2_handle_event(V4L2Context *ctx)
120 V4L2m2mContext *s = ctx_to_m2mctx(ctx);
121 struct v4l2_format cap_fmt = s->capture.format;
122 struct v4l2_format out_fmt = s->output.format;
123 struct v4l2_event evt = { 0 };
124 int full_reinit, reinit, ret;
126 ret = ioctl(s->fd, VIDIOC_DQEVENT, &evt);
128 av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_DQEVENT\n", ctx->name);
132 if (evt.type != V4L2_EVENT_SOURCE_CHANGE)
135 ret = ioctl(s->fd, VIDIOC_G_FMT, &out_fmt);
137 av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_G_FMT\n", s->output.name);
141 ret = ioctl(s->fd, VIDIOC_G_FMT, &cap_fmt);
143 av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_G_FMT\n", s->capture.name);
147 full_reinit = v4l2_resolution_changed(&s->output, &out_fmt);
149 s->output.height = v4l2_get_height(&out_fmt);
150 s->output.width = v4l2_get_width(&out_fmt);
153 reinit = v4l2_resolution_changed(&s->capture, &cap_fmt);
155 s->capture.height = v4l2_get_height(&cap_fmt);
156 s->capture.width = v4l2_get_width(&cap_fmt);
159 if (full_reinit || reinit)
163 ret = ff_v4l2_m2m_codec_full_reinit(s);
165 av_log(logger(ctx), AV_LOG_ERROR, "v4l2_m2m_codec_full_reinit\n");
172 ret = ff_set_dimensions(s->avctx, s->capture.width, s->capture.height);
174 av_log(logger(ctx), AV_LOG_WARNING, "update avcodec height and width\n");
176 ret = ff_v4l2_m2m_codec_reinit(s);
178 av_log(logger(ctx), AV_LOG_ERROR, "v4l2_m2m_codec_reinit\n");
184 /* dummy event received */
187 /* reinit executed */
192 static int v4l2_stop_decode(V4L2Context *ctx)
194 struct v4l2_decoder_cmd cmd = {
195 .cmd = V4L2_DEC_CMD_STOP,
199 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_DECODER_CMD, &cmd);
201 /* DECODER_CMD is optional */
203 return ff_v4l2_context_set_status(ctx, VIDIOC_STREAMOFF);
209 static int v4l2_stop_encode(V4L2Context *ctx)
211 struct v4l2_encoder_cmd cmd = {
212 .cmd = V4L2_ENC_CMD_STOP,
216 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_ENCODER_CMD, &cmd);
218 /* ENCODER_CMD is optional */
220 return ff_v4l2_context_set_status(ctx, VIDIOC_STREAMOFF);
226 static V4L2Buffer* v4l2_dequeue_v4l2buf(V4L2Context *ctx, int timeout)
228 struct v4l2_plane planes[VIDEO_MAX_PLANES];
229 struct v4l2_buffer buf = { 0 };
230 V4L2Buffer* avbuf = NULL;
231 struct pollfd pfd = {
232 .events = POLLIN | POLLRDNORM | POLLPRI | POLLOUT | POLLWRNORM, /* default blocking capture */
233 .fd = ctx_to_m2mctx(ctx)->fd,
237 if (V4L2_TYPE_IS_OUTPUT(ctx->type))
238 pfd.events = POLLOUT | POLLWRNORM;
241 ret = poll(&pfd, 1, timeout);
247 /* timeout is being used to indicate last valid bufer when draining */
248 if (ctx_to_m2mctx(ctx)->draining)
254 /* 0. handle errors */
255 if (pfd.revents & POLLERR) {
256 av_log(logger(ctx), AV_LOG_WARNING, "%s POLLERR\n", ctx->name);
260 /* 1. handle resolution changes */
261 if (pfd.revents & POLLPRI) {
262 ret = v4l2_handle_event(ctx);
264 /* if re-init failed, abort */
269 /* if re-init was successful drop the buffer (if there was one)
270 * since we had to reconfigure capture (unmap all buffers)
276 /* 2. dequeue the buffer */
277 if (pfd.revents & (POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM)) {
279 if (!V4L2_TYPE_IS_OUTPUT(ctx->type)) {
280 /* there is a capture buffer ready */
281 if (pfd.revents & (POLLIN | POLLRDNORM))
284 /* the driver is ready to accept more input; instead of waiting for the capture
285 * buffer to complete we return NULL so input can proceed (we are single threaded)
287 if (pfd.revents & (POLLOUT | POLLWRNORM))
292 memset(&buf, 0, sizeof(buf));
293 buf.memory = V4L2_MEMORY_MMAP;
294 buf.type = ctx->type;
295 if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
296 memset(planes, 0, sizeof(planes));
297 buf.length = VIDEO_MAX_PLANES;
298 buf.m.planes = planes;
301 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_DQBUF, &buf);
303 if (errno != EAGAIN) {
306 av_log(logger(ctx), AV_LOG_DEBUG, "%s VIDIOC_DQBUF, errno (%s)\n",
307 ctx->name, av_err2str(AVERROR(errno)));
310 avbuf = &ctx->buffers[buf.index];
311 avbuf->status = V4L2BUF_AVAILABLE;
313 if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
314 memcpy(avbuf->planes, planes, sizeof(planes));
315 avbuf->buf.m.planes = avbuf->planes;
323 static V4L2Buffer* v4l2_getfree_v4l2buf(V4L2Context *ctx)
325 int timeout = 0; /* return when no more buffers to dequeue */
328 /* get back as many output buffers as possible */
329 if (V4L2_TYPE_IS_OUTPUT(ctx->type)) {
331 } while (v4l2_dequeue_v4l2buf(ctx, timeout));
334 for (i = 0; i < ctx->num_buffers; i++) {
335 if (ctx->buffers[i].status == V4L2BUF_AVAILABLE)
336 return &ctx->buffers[i];
342 static int v4l2_release_buffers(V4L2Context* ctx)
344 struct v4l2_requestbuffers req = {
345 .memory = V4L2_MEMORY_MMAP,
347 .count = 0, /* 0 -> unmaps buffers from the driver */
351 for (i = 0; i < ctx->num_buffers; i++) {
352 V4L2Buffer *buffer = &ctx->buffers[i];
354 for (j = 0; j < buffer->num_planes; j++) {
355 struct V4L2Plane_info *p = &buffer->plane_info[j];
356 if (p->mm_addr && p->length)
357 if (munmap(p->mm_addr, p->length) < 0)
358 av_log(logger(ctx), AV_LOG_ERROR, "%s unmap plane (%s))\n", ctx->name, av_err2str(AVERROR(errno)));
362 return ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_REQBUFS, &req);
365 static inline int v4l2_try_raw_format(V4L2Context* ctx, enum AVPixelFormat pixfmt)
367 struct v4l2_format *fmt = &ctx->format;
371 v4l2_fmt = ff_v4l2_format_avfmt_to_v4l2(pixfmt);
373 return AVERROR(EINVAL);
375 if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type))
376 fmt->fmt.pix_mp.pixelformat = v4l2_fmt;
378 fmt->fmt.pix.pixelformat = v4l2_fmt;
380 fmt->type = ctx->type;
382 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_TRY_FMT, fmt);
384 return AVERROR(EINVAL);
389 static int v4l2_get_raw_format(V4L2Context* ctx, enum AVPixelFormat *p)
391 enum AVPixelFormat pixfmt = ctx->av_pix_fmt;
392 struct v4l2_fmtdesc fdesc;
395 memset(&fdesc, 0, sizeof(fdesc));
396 fdesc.type = ctx->type;
398 if (pixfmt != AV_PIX_FMT_NONE) {
399 ret = v4l2_try_raw_format(ctx, pixfmt);
401 pixfmt = AV_PIX_FMT_NONE;
407 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_ENUM_FMT, &fdesc);
409 return AVERROR(EINVAL);
411 pixfmt = ff_v4l2_format_v4l2_to_avfmt(fdesc.pixelformat, AV_CODEC_ID_RAWVIDEO);
412 ret = v4l2_try_raw_format(ctx, pixfmt);
423 return AVERROR(EINVAL);
426 static int v4l2_get_coded_format(V4L2Context* ctx, uint32_t *p)
428 struct v4l2_fmtdesc fdesc;
432 /* translate to a valid v4l2 format */
433 v4l2_fmt = ff_v4l2_format_avcodec_to_v4l2(ctx->av_codec_id);
435 return AVERROR(EINVAL);
437 /* check if the driver supports this format */
438 memset(&fdesc, 0, sizeof(fdesc));
439 fdesc.type = ctx->type;
442 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_ENUM_FMT, &fdesc);
444 return AVERROR(EINVAL);
446 if (fdesc.pixelformat == v4l2_fmt)
457 /*****************************************************************************
459 * V4L2 Context Interface
461 *****************************************************************************/
463 int ff_v4l2_context_set_status(V4L2Context* ctx, int cmd)
465 int type = ctx->type;
468 ret = ioctl(ctx_to_m2mctx(ctx)->fd, cmd, &type);
470 return AVERROR(errno);
472 ctx->streamon = (cmd == VIDIOC_STREAMON);
477 int ff_v4l2_context_enqueue_frame(V4L2Context* ctx, const AVFrame* frame)
479 V4L2m2mContext *s = ctx_to_m2mctx(ctx);
484 ret = v4l2_stop_encode(ctx);
486 av_log(logger(ctx), AV_LOG_ERROR, "%s stop_encode\n", ctx->name);
491 avbuf = v4l2_getfree_v4l2buf(ctx);
493 return AVERROR(ENOMEM);
495 ret = ff_v4l2_buffer_avframe_to_buf(frame, avbuf);
499 return ff_v4l2_buffer_enqueue(avbuf);
502 int ff_v4l2_context_enqueue_packet(V4L2Context* ctx, const AVPacket* pkt)
504 V4L2m2mContext *s = ctx_to_m2mctx(ctx);
509 ret = v4l2_stop_decode(ctx);
511 av_log(logger(ctx), AV_LOG_ERROR, "%s stop_decode\n", ctx->name);
516 avbuf = v4l2_getfree_v4l2buf(ctx);
518 return AVERROR(ENOMEM);
520 ret = ff_v4l2_buffer_avpkt_to_buf(pkt, avbuf);
524 return ff_v4l2_buffer_enqueue(avbuf);
527 int ff_v4l2_context_dequeue_frame(V4L2Context* ctx, AVFrame* frame)
529 V4L2Buffer* avbuf = NULL;
531 /* if we are draining, we are no longer inputing data, therefore enable a
532 * timeout so we can dequeue and flag the last valid buffer.
535 * 1. decoded frame available
536 * 2. an input buffer is ready to be dequeued
538 avbuf = v4l2_dequeue_v4l2buf(ctx, ctx_to_m2mctx(ctx)->draining ? 200 : -1);
543 return AVERROR(EAGAIN);
546 return ff_v4l2_buffer_buf_to_avframe(frame, avbuf);
549 int ff_v4l2_context_dequeue_packet(V4L2Context* ctx, AVPacket* pkt)
551 V4L2Buffer* avbuf = NULL;
553 /* if we are draining, we are no longer inputing data, therefore enable a
554 * timeout so we can dequeue and flag the last valid buffer.
557 * 1. encoded packet available
558 * 2. an input buffer ready to be dequeued
560 avbuf = v4l2_dequeue_v4l2buf(ctx, ctx_to_m2mctx(ctx)->draining ? 200 : -1);
565 return AVERROR(EAGAIN);
568 return ff_v4l2_buffer_buf_to_avpkt(pkt, avbuf);
571 int ff_v4l2_context_get_format(V4L2Context* ctx)
573 struct v4l2_format_update fmt = { 0 };
576 if (ctx->av_codec_id == AV_CODEC_ID_RAWVIDEO) {
577 ret = v4l2_get_raw_format(ctx, &fmt.av_fmt);
581 fmt.update_avfmt = 1;
582 v4l2_save_to_context(ctx, &fmt);
584 /* format has been tried already */
588 ret = v4l2_get_coded_format(ctx, &fmt.v4l2_fmt);
593 v4l2_save_to_context(ctx, &fmt);
595 return ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_TRY_FMT, &ctx->format);
598 int ff_v4l2_context_set_format(V4L2Context* ctx)
600 return ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_S_FMT, &ctx->format);
603 void ff_v4l2_context_release(V4L2Context* ctx)
610 ret = v4l2_release_buffers(ctx);
612 av_log(logger(ctx), AV_LOG_WARNING, "V4L2 failed to unmap the %s buffers\n", ctx->name);
614 av_free(ctx->buffers);
618 int ff_v4l2_context_init(V4L2Context* ctx)
620 V4L2m2mContext *s = ctx_to_m2mctx(ctx);
621 struct v4l2_requestbuffers req;
624 if (!v4l2_type_supported(ctx)) {
625 av_log(logger(ctx), AV_LOG_ERROR, "type %i not supported\n", ctx->type);
626 return AVERROR_PATCHWELCOME;
629 ret = ioctl(s->fd, VIDIOC_G_FMT, &ctx->format);
631 av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_G_FMT failed\n", ctx->name);
633 memset(&req, 0, sizeof(req));
634 req.count = ctx->num_buffers;
635 req.memory = V4L2_MEMORY_MMAP;
636 req.type = ctx->type;
637 ret = ioctl(s->fd, VIDIOC_REQBUFS, &req);
639 return AVERROR(errno);
641 ctx->num_buffers = req.count;
642 ctx->buffers = av_mallocz(ctx->num_buffers * sizeof(V4L2Buffer));
644 av_log(logger(ctx), AV_LOG_ERROR, "%s malloc enomem\n", ctx->name);
645 return AVERROR(ENOMEM);
648 for (i = 0; i < req.count; i++) {
649 ctx->buffers[i].context = ctx;
650 ret = ff_v4l2_buffer_initialize(&ctx->buffers[i], i);
652 av_log(logger(ctx), AV_LOG_ERROR, "%s buffer initialization (%s)\n", ctx->name, av_err2str(ret));
653 av_free(ctx->buffers);
658 av_log(logger(ctx), AV_LOG_DEBUG, "%s: %s %02d buffers initialized: %04ux%04u, sizeimage %08u, bytesperline %08u\n", ctx->name,
659 V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ? av_fourcc2str(ctx->format.fmt.pix_mp.pixelformat) : av_fourcc2str(ctx->format.fmt.pix.pixelformat),
661 v4l2_get_width(&ctx->format),
662 v4l2_get_height(&ctx->format),
663 V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ? ctx->format.fmt.pix_mp.plane_fmt[0].sizeimage : ctx->format.fmt.pix.sizeimage,
664 V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ? ctx->format.fmt.pix_mp.plane_fmt[0].bytesperline : ctx->format.fmt.pix.bytesperline);