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 int v4l2_get_framesize_compressed(V4L2Context* ctx, int width, int height)
95 V4L2m2mContext *s = ctx_to_m2mctx(ctx);
96 const int SZ_4K = 0x1000;
99 if (av_codec_is_decoder(s->avctx->codec))
100 return ((width * height * 3 / 2) / 2) + 128;
103 size = FFALIGN(height, 32) * FFALIGN(width, 32) * 3 / 2 / 2;
104 return FFALIGN(size, SZ_4K);
107 static inline void v4l2_save_to_context(V4L2Context* ctx, struct v4l2_format_update *fmt)
109 ctx->format.type = ctx->type;
111 if (fmt->update_avfmt)
112 ctx->av_pix_fmt = fmt->av_fmt;
114 if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
115 /* update the sizes to handle the reconfiguration of the capture stream at runtime */
116 ctx->format.fmt.pix_mp.height = ctx->height;
117 ctx->format.fmt.pix_mp.width = ctx->width;
118 if (fmt->update_v4l2) {
119 ctx->format.fmt.pix_mp.pixelformat = fmt->v4l2_fmt;
121 /* s5p-mfc requires the user to specify a buffer size */
122 ctx->format.fmt.pix_mp.plane_fmt[0].sizeimage =
123 v4l2_get_framesize_compressed(ctx, ctx->width, ctx->height);
126 ctx->format.fmt.pix.height = ctx->height;
127 ctx->format.fmt.pix.width = ctx->width;
128 if (fmt->update_v4l2) {
129 ctx->format.fmt.pix.pixelformat = fmt->v4l2_fmt;
131 /* s5p-mfc requires the user to specify a buffer size */
132 ctx->format.fmt.pix.sizeimage =
133 v4l2_get_framesize_compressed(ctx, ctx->width, ctx->height);
139 * returns 1 if reinit was successful, negative if it failed
140 * returns 0 if reinit was not executed
142 static int v4l2_handle_event(V4L2Context *ctx)
144 V4L2m2mContext *s = ctx_to_m2mctx(ctx);
145 struct v4l2_format cap_fmt = s->capture.format;
146 struct v4l2_format out_fmt = s->output.format;
147 struct v4l2_event evt = { 0 };
148 int full_reinit, reinit, ret;
150 ret = ioctl(s->fd, VIDIOC_DQEVENT, &evt);
152 av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_DQEVENT\n", ctx->name);
156 if (evt.type != V4L2_EVENT_SOURCE_CHANGE)
159 ret = ioctl(s->fd, VIDIOC_G_FMT, &out_fmt);
161 av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_G_FMT\n", s->output.name);
165 ret = ioctl(s->fd, VIDIOC_G_FMT, &cap_fmt);
167 av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_G_FMT\n", s->capture.name);
171 full_reinit = v4l2_resolution_changed(&s->output, &out_fmt);
173 s->output.height = v4l2_get_height(&out_fmt);
174 s->output.width = v4l2_get_width(&out_fmt);
177 reinit = v4l2_resolution_changed(&s->capture, &cap_fmt);
179 s->capture.height = v4l2_get_height(&cap_fmt);
180 s->capture.width = v4l2_get_width(&cap_fmt);
183 if (full_reinit || reinit)
187 ret = ff_v4l2_m2m_codec_full_reinit(s);
189 av_log(logger(ctx), AV_LOG_ERROR, "v4l2_m2m_codec_full_reinit\n");
196 ret = ff_set_dimensions(s->avctx, s->capture.width, s->capture.height);
198 av_log(logger(ctx), AV_LOG_WARNING, "update avcodec height and width\n");
200 ret = ff_v4l2_m2m_codec_reinit(s);
202 av_log(logger(ctx), AV_LOG_ERROR, "v4l2_m2m_codec_reinit\n");
208 /* dummy event received */
211 /* reinit executed */
216 static int v4l2_stop_decode(V4L2Context *ctx)
218 struct v4l2_decoder_cmd cmd = {
219 .cmd = V4L2_DEC_CMD_STOP,
223 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_DECODER_CMD, &cmd);
225 /* DECODER_CMD is optional */
227 return ff_v4l2_context_set_status(ctx, VIDIOC_STREAMOFF);
233 static int v4l2_stop_encode(V4L2Context *ctx)
235 struct v4l2_encoder_cmd cmd = {
236 .cmd = V4L2_ENC_CMD_STOP,
240 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_ENCODER_CMD, &cmd);
242 /* ENCODER_CMD is optional */
244 return ff_v4l2_context_set_status(ctx, VIDIOC_STREAMOFF);
250 static V4L2Buffer* v4l2_dequeue_v4l2buf(V4L2Context *ctx, int timeout)
252 struct v4l2_plane planes[VIDEO_MAX_PLANES];
253 struct v4l2_buffer buf = { 0 };
254 V4L2Buffer* avbuf = NULL;
255 struct pollfd pfd = {
256 .events = POLLIN | POLLRDNORM | POLLPRI | POLLOUT | POLLWRNORM, /* default blocking capture */
257 .fd = ctx_to_m2mctx(ctx)->fd,
261 if (V4L2_TYPE_IS_OUTPUT(ctx->type))
262 pfd.events = POLLOUT | POLLWRNORM;
265 ret = poll(&pfd, 1, timeout);
271 /* timeout is being used to indicate last valid bufer when draining */
272 if (ctx_to_m2mctx(ctx)->draining)
278 /* 0. handle errors */
279 if (pfd.revents & POLLERR) {
280 av_log(logger(ctx), AV_LOG_WARNING, "%s POLLERR\n", ctx->name);
284 /* 1. handle resolution changes */
285 if (pfd.revents & POLLPRI) {
286 ret = v4l2_handle_event(ctx);
288 /* if re-init failed, abort */
293 /* if re-init was successful drop the buffer (if there was one)
294 * since we had to reconfigure capture (unmap all buffers)
300 /* 2. dequeue the buffer */
301 if (pfd.revents & (POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM)) {
303 if (!V4L2_TYPE_IS_OUTPUT(ctx->type)) {
304 /* there is a capture buffer ready */
305 if (pfd.revents & (POLLIN | POLLRDNORM))
308 /* the driver is ready to accept more input; instead of waiting for the capture
309 * buffer to complete we return NULL so input can proceed (we are single threaded)
311 if (pfd.revents & (POLLOUT | POLLWRNORM))
316 memset(&buf, 0, sizeof(buf));
317 buf.memory = V4L2_MEMORY_MMAP;
318 buf.type = ctx->type;
319 if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
320 memset(planes, 0, sizeof(planes));
321 buf.length = VIDEO_MAX_PLANES;
322 buf.m.planes = planes;
325 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_DQBUF, &buf);
327 if (errno != EAGAIN) {
330 av_log(logger(ctx), AV_LOG_DEBUG, "%s VIDIOC_DQBUF, errno (%s)\n",
331 ctx->name, av_err2str(AVERROR(errno)));
334 avbuf = &ctx->buffers[buf.index];
335 avbuf->status = V4L2BUF_AVAILABLE;
337 if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
338 memcpy(avbuf->planes, planes, sizeof(planes));
339 avbuf->buf.m.planes = avbuf->planes;
347 static V4L2Buffer* v4l2_getfree_v4l2buf(V4L2Context *ctx)
349 int timeout = 0; /* return when no more buffers to dequeue */
352 /* get back as many output buffers as possible */
353 if (V4L2_TYPE_IS_OUTPUT(ctx->type)) {
355 } while (v4l2_dequeue_v4l2buf(ctx, timeout));
358 for (i = 0; i < ctx->num_buffers; i++) {
359 if (ctx->buffers[i].status == V4L2BUF_AVAILABLE)
360 return &ctx->buffers[i];
366 static int v4l2_release_buffers(V4L2Context* ctx)
368 struct v4l2_requestbuffers req = {
369 .memory = V4L2_MEMORY_MMAP,
371 .count = 0, /* 0 -> unmaps buffers from the driver */
375 for (i = 0; i < ctx->num_buffers; i++) {
376 V4L2Buffer *buffer = &ctx->buffers[i];
378 for (j = 0; j < buffer->num_planes; j++) {
379 struct V4L2Plane_info *p = &buffer->plane_info[j];
380 if (p->mm_addr && p->length)
381 if (munmap(p->mm_addr, p->length) < 0)
382 av_log(logger(ctx), AV_LOG_ERROR, "%s unmap plane (%s))\n", ctx->name, av_err2str(AVERROR(errno)));
386 return ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_REQBUFS, &req);
389 static inline int v4l2_try_raw_format(V4L2Context* ctx, enum AVPixelFormat pixfmt)
391 struct v4l2_format *fmt = &ctx->format;
395 v4l2_fmt = ff_v4l2_format_avfmt_to_v4l2(pixfmt);
397 return AVERROR(EINVAL);
399 if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type))
400 fmt->fmt.pix_mp.pixelformat = v4l2_fmt;
402 fmt->fmt.pix.pixelformat = v4l2_fmt;
404 fmt->type = ctx->type;
406 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_TRY_FMT, fmt);
408 return AVERROR(EINVAL);
413 static int v4l2_get_raw_format(V4L2Context* ctx, enum AVPixelFormat *p)
415 enum AVPixelFormat pixfmt = ctx->av_pix_fmt;
416 struct v4l2_fmtdesc fdesc;
419 memset(&fdesc, 0, sizeof(fdesc));
420 fdesc.type = ctx->type;
422 if (pixfmt != AV_PIX_FMT_NONE) {
423 ret = v4l2_try_raw_format(ctx, pixfmt);
425 pixfmt = AV_PIX_FMT_NONE;
431 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_ENUM_FMT, &fdesc);
433 return AVERROR(EINVAL);
435 pixfmt = ff_v4l2_format_v4l2_to_avfmt(fdesc.pixelformat, AV_CODEC_ID_RAWVIDEO);
436 ret = v4l2_try_raw_format(ctx, pixfmt);
447 return AVERROR(EINVAL);
450 static int v4l2_get_coded_format(V4L2Context* ctx, uint32_t *p)
452 struct v4l2_fmtdesc fdesc;
456 /* translate to a valid v4l2 format */
457 v4l2_fmt = ff_v4l2_format_avcodec_to_v4l2(ctx->av_codec_id);
459 return AVERROR(EINVAL);
461 /* check if the driver supports this format */
462 memset(&fdesc, 0, sizeof(fdesc));
463 fdesc.type = ctx->type;
466 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_ENUM_FMT, &fdesc);
468 return AVERROR(EINVAL);
470 if (fdesc.pixelformat == v4l2_fmt)
481 /*****************************************************************************
483 * V4L2 Context Interface
485 *****************************************************************************/
487 int ff_v4l2_context_set_status(V4L2Context* ctx, uint32_t cmd)
489 int type = ctx->type;
492 ret = ioctl(ctx_to_m2mctx(ctx)->fd, cmd, &type);
494 return AVERROR(errno);
496 ctx->streamon = (cmd == VIDIOC_STREAMON);
501 int ff_v4l2_context_enqueue_frame(V4L2Context* ctx, const AVFrame* frame)
503 V4L2m2mContext *s = ctx_to_m2mctx(ctx);
508 ret = v4l2_stop_encode(ctx);
510 av_log(logger(ctx), AV_LOG_ERROR, "%s stop_encode\n", ctx->name);
515 avbuf = v4l2_getfree_v4l2buf(ctx);
517 return AVERROR(ENOMEM);
519 ret = ff_v4l2_buffer_avframe_to_buf(frame, avbuf);
523 return ff_v4l2_buffer_enqueue(avbuf);
526 int ff_v4l2_context_enqueue_packet(V4L2Context* ctx, const AVPacket* pkt)
528 V4L2m2mContext *s = ctx_to_m2mctx(ctx);
533 ret = v4l2_stop_decode(ctx);
535 av_log(logger(ctx), AV_LOG_ERROR, "%s stop_decode\n", ctx->name);
540 avbuf = v4l2_getfree_v4l2buf(ctx);
542 return AVERROR(ENOMEM);
544 ret = ff_v4l2_buffer_avpkt_to_buf(pkt, avbuf);
548 return ff_v4l2_buffer_enqueue(avbuf);
551 int ff_v4l2_context_dequeue_frame(V4L2Context* ctx, AVFrame* frame)
553 V4L2Buffer* avbuf = NULL;
555 /* if we are draining, we are no longer inputing data, therefore enable a
556 * timeout so we can dequeue and flag the last valid buffer.
559 * 1. decoded frame available
560 * 2. an input buffer is ready to be dequeued
562 avbuf = v4l2_dequeue_v4l2buf(ctx, ctx_to_m2mctx(ctx)->draining ? 200 : -1);
567 return AVERROR(EAGAIN);
570 return ff_v4l2_buffer_buf_to_avframe(frame, avbuf);
573 int ff_v4l2_context_dequeue_packet(V4L2Context* ctx, AVPacket* pkt)
575 V4L2Buffer* avbuf = NULL;
577 /* if we are draining, we are no longer inputing data, therefore enable a
578 * timeout so we can dequeue and flag the last valid buffer.
581 * 1. encoded packet available
582 * 2. an input buffer ready to be dequeued
584 avbuf = v4l2_dequeue_v4l2buf(ctx, ctx_to_m2mctx(ctx)->draining ? 200 : -1);
589 return AVERROR(EAGAIN);
592 return ff_v4l2_buffer_buf_to_avpkt(pkt, avbuf);
595 int ff_v4l2_context_get_format(V4L2Context* ctx)
597 struct v4l2_format_update fmt = { 0 };
600 if (ctx->av_codec_id == AV_CODEC_ID_RAWVIDEO) {
601 ret = v4l2_get_raw_format(ctx, &fmt.av_fmt);
605 fmt.update_avfmt = 1;
606 v4l2_save_to_context(ctx, &fmt);
608 /* format has been tried already */
612 ret = v4l2_get_coded_format(ctx, &fmt.v4l2_fmt);
617 v4l2_save_to_context(ctx, &fmt);
619 return ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_TRY_FMT, &ctx->format);
622 int ff_v4l2_context_set_format(V4L2Context* ctx)
624 return ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_S_FMT, &ctx->format);
627 void ff_v4l2_context_release(V4L2Context* ctx)
634 ret = v4l2_release_buffers(ctx);
636 av_log(logger(ctx), AV_LOG_WARNING, "V4L2 failed to unmap the %s buffers\n", ctx->name);
638 av_free(ctx->buffers);
642 int ff_v4l2_context_init(V4L2Context* ctx)
644 V4L2m2mContext *s = ctx_to_m2mctx(ctx);
645 struct v4l2_requestbuffers req;
648 if (!v4l2_type_supported(ctx)) {
649 av_log(logger(ctx), AV_LOG_ERROR, "type %i not supported\n", ctx->type);
650 return AVERROR_PATCHWELCOME;
653 ret = ioctl(s->fd, VIDIOC_G_FMT, &ctx->format);
655 av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_G_FMT failed\n", ctx->name);
657 memset(&req, 0, sizeof(req));
658 req.count = ctx->num_buffers;
659 req.memory = V4L2_MEMORY_MMAP;
660 req.type = ctx->type;
661 ret = ioctl(s->fd, VIDIOC_REQBUFS, &req);
663 return AVERROR(errno);
665 ctx->num_buffers = req.count;
666 ctx->buffers = av_mallocz(ctx->num_buffers * sizeof(V4L2Buffer));
668 av_log(logger(ctx), AV_LOG_ERROR, "%s malloc enomem\n", ctx->name);
669 return AVERROR(ENOMEM);
672 for (i = 0; i < req.count; i++) {
673 ctx->buffers[i].context = ctx;
674 ret = ff_v4l2_buffer_initialize(&ctx->buffers[i], i);
676 av_log(logger(ctx), AV_LOG_ERROR, "%s buffer initialization (%s)\n", ctx->name, av_err2str(ret));
677 av_free(ctx->buffers);
682 av_log(logger(ctx), AV_LOG_DEBUG, "%s: %s %02d buffers initialized: %04ux%04u, sizeimage %08u, bytesperline %08u\n", ctx->name,
683 V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ? av_fourcc2str(ctx->format.fmt.pix_mp.pixelformat) : av_fourcc2str(ctx->format.fmt.pix.pixelformat),
685 v4l2_get_width(&ctx->format),
686 v4l2_get_height(&ctx->format),
687 V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ? ctx->format.fmt.pix_mp.plane_fmt[0].sizeimage : ctx->format.fmt.pix.sizeimage,
688 V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ? ctx->format.fmt.pix_mp.plane_fmt[0].bytesperline : ctx->format.fmt.pix.bytesperline);