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,
224 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_DECODER_CMD, &cmd);
226 /* DECODER_CMD is optional */
228 return ff_v4l2_context_set_status(ctx, VIDIOC_STREAMOFF);
234 static int v4l2_stop_encode(V4L2Context *ctx)
236 struct v4l2_encoder_cmd cmd = {
237 .cmd = V4L2_ENC_CMD_STOP,
242 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_ENCODER_CMD, &cmd);
244 /* ENCODER_CMD is optional */
246 return ff_v4l2_context_set_status(ctx, VIDIOC_STREAMOFF);
252 static V4L2Buffer* v4l2_dequeue_v4l2buf(V4L2Context *ctx, int timeout)
254 struct v4l2_plane planes[VIDEO_MAX_PLANES];
255 struct v4l2_buffer buf = { 0 };
256 V4L2Buffer* avbuf = NULL;
257 struct pollfd pfd = {
258 .events = POLLIN | POLLRDNORM | POLLPRI | POLLOUT | POLLWRNORM, /* default blocking capture */
259 .fd = ctx_to_m2mctx(ctx)->fd,
263 /* if we are draining and there are no more capture buffers queued in the driver we are done */
264 if (!V4L2_TYPE_IS_OUTPUT(ctx->type) && ctx_to_m2mctx(ctx)->draining) {
265 for (i = 0; i < ctx->num_buffers; i++) {
266 if (ctx->buffers[i].status == V4L2BUF_IN_DRIVER)
274 if (V4L2_TYPE_IS_OUTPUT(ctx->type))
275 pfd.events = POLLOUT | POLLWRNORM;
277 /* no need to listen to requests for more input while draining */
278 if (ctx_to_m2mctx(ctx)->draining)
279 pfd.events = POLLIN | POLLRDNORM | POLLPRI;
283 ret = poll(&pfd, 1, timeout);
291 /* 0. handle errors */
292 if (pfd.revents & POLLERR) {
293 /* if we are trying to get free buffers but none have been queued yet
294 no need to raise a warning */
296 for (i = 0; i < ctx->num_buffers; i++) {
297 if (ctx->buffers[i].status != V4L2BUF_AVAILABLE)
298 av_log(logger(ctx), AV_LOG_WARNING, "%s POLLERR\n", ctx->name);
302 av_log(logger(ctx), AV_LOG_WARNING, "%s POLLERR\n", ctx->name);
307 /* 1. handle resolution changes */
308 if (pfd.revents & POLLPRI) {
309 ret = v4l2_handle_event(ctx);
311 /* if re-init failed, abort */
316 /* if re-init was successful drop the buffer (if there was one)
317 * since we had to reconfigure capture (unmap all buffers)
323 /* 2. dequeue the buffer */
324 if (pfd.revents & (POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM)) {
326 if (!V4L2_TYPE_IS_OUTPUT(ctx->type)) {
327 /* there is a capture buffer ready */
328 if (pfd.revents & (POLLIN | POLLRDNORM))
331 /* the driver is ready to accept more input; instead of waiting for the capture
332 * buffer to complete we return NULL so input can proceed (we are single threaded)
334 if (pfd.revents & (POLLOUT | POLLWRNORM))
339 memset(&buf, 0, sizeof(buf));
340 buf.memory = V4L2_MEMORY_MMAP;
341 buf.type = ctx->type;
342 if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
343 memset(planes, 0, sizeof(planes));
344 buf.length = VIDEO_MAX_PLANES;
345 buf.m.planes = planes;
348 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_DQBUF, &buf);
350 if (errno != EAGAIN) {
353 av_log(logger(ctx), AV_LOG_DEBUG, "%s VIDIOC_DQBUF, errno (%s)\n",
354 ctx->name, av_err2str(AVERROR(errno)));
359 avbuf = &ctx->buffers[buf.index];
360 avbuf->status = V4L2BUF_AVAILABLE;
362 if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
363 memcpy(avbuf->planes, planes, sizeof(planes));
364 avbuf->buf.m.planes = avbuf->planes;
372 static V4L2Buffer* v4l2_getfree_v4l2buf(V4L2Context *ctx)
374 int timeout = 0; /* return when no more buffers to dequeue */
377 /* get back as many output buffers as possible */
378 if (V4L2_TYPE_IS_OUTPUT(ctx->type)) {
380 } while (v4l2_dequeue_v4l2buf(ctx, timeout));
383 for (i = 0; i < ctx->num_buffers; i++) {
384 if (ctx->buffers[i].status == V4L2BUF_AVAILABLE)
385 return &ctx->buffers[i];
391 static int v4l2_release_buffers(V4L2Context* ctx)
393 struct v4l2_requestbuffers req = {
394 .memory = V4L2_MEMORY_MMAP,
396 .count = 0, /* 0 -> unmaps buffers from the driver */
400 for (i = 0; i < ctx->num_buffers; i++) {
401 V4L2Buffer *buffer = &ctx->buffers[i];
403 for (j = 0; j < buffer->num_planes; j++) {
404 struct V4L2Plane_info *p = &buffer->plane_info[j];
405 if (p->mm_addr && p->length)
406 if (munmap(p->mm_addr, p->length) < 0)
407 av_log(logger(ctx), AV_LOG_ERROR, "%s unmap plane (%s))\n", ctx->name, av_err2str(AVERROR(errno)));
411 return ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_REQBUFS, &req);
414 static inline int v4l2_try_raw_format(V4L2Context* ctx, enum AVPixelFormat pixfmt)
416 struct v4l2_format *fmt = &ctx->format;
420 v4l2_fmt = ff_v4l2_format_avfmt_to_v4l2(pixfmt);
422 return AVERROR(EINVAL);
424 if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type))
425 fmt->fmt.pix_mp.pixelformat = v4l2_fmt;
427 fmt->fmt.pix.pixelformat = v4l2_fmt;
429 fmt->type = ctx->type;
431 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_TRY_FMT, fmt);
433 return AVERROR(EINVAL);
438 static int v4l2_get_raw_format(V4L2Context* ctx, enum AVPixelFormat *p)
440 enum AVPixelFormat pixfmt = ctx->av_pix_fmt;
441 struct v4l2_fmtdesc fdesc;
444 memset(&fdesc, 0, sizeof(fdesc));
445 fdesc.type = ctx->type;
447 if (pixfmt != AV_PIX_FMT_NONE) {
448 ret = v4l2_try_raw_format(ctx, pixfmt);
454 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_ENUM_FMT, &fdesc);
456 return AVERROR(EINVAL);
458 pixfmt = ff_v4l2_format_v4l2_to_avfmt(fdesc.pixelformat, AV_CODEC_ID_RAWVIDEO);
459 ret = v4l2_try_raw_format(ctx, pixfmt);
470 return AVERROR(EINVAL);
473 static int v4l2_get_coded_format(V4L2Context* ctx, uint32_t *p)
475 struct v4l2_fmtdesc fdesc;
479 /* translate to a valid v4l2 format */
480 v4l2_fmt = ff_v4l2_format_avcodec_to_v4l2(ctx->av_codec_id);
482 return AVERROR(EINVAL);
484 /* check if the driver supports this format */
485 memset(&fdesc, 0, sizeof(fdesc));
486 fdesc.type = ctx->type;
489 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_ENUM_FMT, &fdesc);
491 return AVERROR(EINVAL);
493 if (fdesc.pixelformat == v4l2_fmt)
504 /*****************************************************************************
506 * V4L2 Context Interface
508 *****************************************************************************/
510 int ff_v4l2_context_set_status(V4L2Context* ctx, uint32_t cmd)
512 int type = ctx->type;
515 ret = ioctl(ctx_to_m2mctx(ctx)->fd, cmd, &type);
517 return AVERROR(errno);
519 ctx->streamon = (cmd == VIDIOC_STREAMON);
524 int ff_v4l2_context_enqueue_frame(V4L2Context* ctx, const AVFrame* frame)
526 V4L2m2mContext *s = ctx_to_m2mctx(ctx);
531 ret = v4l2_stop_encode(ctx);
533 av_log(logger(ctx), AV_LOG_ERROR, "%s stop_encode\n", ctx->name);
538 avbuf = v4l2_getfree_v4l2buf(ctx);
540 return AVERROR(ENOMEM);
542 ret = ff_v4l2_buffer_avframe_to_buf(frame, avbuf);
546 return ff_v4l2_buffer_enqueue(avbuf);
549 int ff_v4l2_context_enqueue_packet(V4L2Context* ctx, const AVPacket* pkt)
551 V4L2m2mContext *s = ctx_to_m2mctx(ctx);
556 ret = v4l2_stop_decode(ctx);
558 av_log(logger(ctx), AV_LOG_ERROR, "%s stop_decode\n", ctx->name);
563 avbuf = v4l2_getfree_v4l2buf(ctx);
565 return AVERROR(ENOMEM);
567 ret = ff_v4l2_buffer_avpkt_to_buf(pkt, avbuf);
571 return ff_v4l2_buffer_enqueue(avbuf);
574 int ff_v4l2_context_dequeue_frame(V4L2Context* ctx, AVFrame* frame)
576 V4L2Buffer* avbuf = NULL;
580 * 1. decoded frame available
581 * 2. an input buffer is ready to be dequeued
583 avbuf = v4l2_dequeue_v4l2buf(ctx, -1);
588 return AVERROR(EAGAIN);
591 return ff_v4l2_buffer_buf_to_avframe(frame, avbuf);
594 int ff_v4l2_context_dequeue_packet(V4L2Context* ctx, AVPacket* pkt)
596 V4L2Buffer* avbuf = NULL;
600 * 1. encoded packet available
601 * 2. an input buffer ready to be dequeued
603 avbuf = v4l2_dequeue_v4l2buf(ctx, -1);
608 return AVERROR(EAGAIN);
611 return ff_v4l2_buffer_buf_to_avpkt(pkt, avbuf);
614 int ff_v4l2_context_get_format(V4L2Context* ctx)
616 struct v4l2_format_update fmt = { 0 };
619 if (ctx->av_codec_id == AV_CODEC_ID_RAWVIDEO) {
620 ret = v4l2_get_raw_format(ctx, &fmt.av_fmt);
624 fmt.update_avfmt = 1;
625 v4l2_save_to_context(ctx, &fmt);
627 /* format has been tried already */
631 ret = v4l2_get_coded_format(ctx, &fmt.v4l2_fmt);
636 v4l2_save_to_context(ctx, &fmt);
638 return ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_TRY_FMT, &ctx->format);
641 int ff_v4l2_context_set_format(V4L2Context* ctx)
643 return ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_S_FMT, &ctx->format);
646 void ff_v4l2_context_release(V4L2Context* ctx)
653 ret = v4l2_release_buffers(ctx);
655 av_log(logger(ctx), AV_LOG_WARNING, "V4L2 failed to unmap the %s buffers\n", ctx->name);
657 av_free(ctx->buffers);
661 int ff_v4l2_context_init(V4L2Context* ctx)
663 V4L2m2mContext *s = ctx_to_m2mctx(ctx);
664 struct v4l2_requestbuffers req;
667 if (!v4l2_type_supported(ctx)) {
668 av_log(logger(ctx), AV_LOG_ERROR, "type %i not supported\n", ctx->type);
669 return AVERROR_PATCHWELCOME;
672 ret = ioctl(s->fd, VIDIOC_G_FMT, &ctx->format);
674 av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_G_FMT failed\n", ctx->name);
676 memset(&req, 0, sizeof(req));
677 req.count = ctx->num_buffers;
678 req.memory = V4L2_MEMORY_MMAP;
679 req.type = ctx->type;
680 ret = ioctl(s->fd, VIDIOC_REQBUFS, &req);
682 return AVERROR(errno);
684 ctx->num_buffers = req.count;
685 ctx->buffers = av_mallocz(ctx->num_buffers * sizeof(V4L2Buffer));
687 av_log(logger(ctx), AV_LOG_ERROR, "%s malloc enomem\n", ctx->name);
688 return AVERROR(ENOMEM);
691 for (i = 0; i < req.count; i++) {
692 ctx->buffers[i].context = ctx;
693 ret = ff_v4l2_buffer_initialize(&ctx->buffers[i], i);
695 av_log(logger(ctx), AV_LOG_ERROR, "%s buffer initialization (%s)\n", ctx->name, av_err2str(ret));
696 av_free(ctx->buffers);
701 av_log(logger(ctx), AV_LOG_DEBUG, "%s: %s %02d buffers initialized: %04ux%04u, sizeimage %08u, bytesperline %08u\n", ctx->name,
702 V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ? av_fourcc2str(ctx->format.fmt.pix_mp.pixelformat) : av_fourcc2str(ctx->format.fmt.pix.pixelformat),
704 v4l2_get_width(&ctx->format),
705 v4l2_get_height(&ctx->format),
706 V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ? ctx->format.fmt.pix_mp.plane_fmt[0].sizeimage : ctx->format.fmt.pix.sizeimage,
707 V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ? ctx->format.fmt.pix_mp.plane_fmt[0].bytesperline : ctx->format.fmt.pix.bytesperline);