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 AVClass *logger(V4L2Context *ctx)
53 return ctx_to_m2mctx(ctx)->priv;
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 AVRational v4l2_get_sar(V4L2Context *ctx)
68 struct AVRational sar = { 0, 1 };
69 struct v4l2_cropcap cropcap;
72 memset(&cropcap, 0, sizeof(cropcap));
73 cropcap.type = ctx->type;
75 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_CROPCAP, &cropcap);
79 sar.num = cropcap.pixelaspect.numerator;
80 sar.den = cropcap.pixelaspect.denominator;
84 static inline unsigned int v4l2_resolution_changed(V4L2Context *ctx, struct v4l2_format *fmt2)
86 struct v4l2_format *fmt1 = &ctx->format;
87 int ret = V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ?
88 fmt1->fmt.pix_mp.width != fmt2->fmt.pix_mp.width ||
89 fmt1->fmt.pix_mp.height != fmt2->fmt.pix_mp.height
91 fmt1->fmt.pix.width != fmt2->fmt.pix.width ||
92 fmt1->fmt.pix.height != fmt2->fmt.pix.height;
95 av_log(logger(ctx), AV_LOG_DEBUG, "%s changed (%dx%d) -> (%dx%d)\n",
97 v4l2_get_width(fmt1), v4l2_get_height(fmt1),
98 v4l2_get_width(fmt2), v4l2_get_height(fmt2));
103 static inline int v4l2_type_supported(V4L2Context *ctx)
105 return ctx->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE ||
106 ctx->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE ||
107 ctx->type == V4L2_BUF_TYPE_VIDEO_CAPTURE ||
108 ctx->type == V4L2_BUF_TYPE_VIDEO_OUTPUT;
111 static inline int v4l2_get_framesize_compressed(V4L2Context* ctx, int width, int height)
113 V4L2m2mContext *s = ctx_to_m2mctx(ctx);
114 const int SZ_4K = 0x1000;
117 if (s->avctx && av_codec_is_decoder(s->avctx->codec))
118 return ((width * height * 3 / 2) / 2) + 128;
121 size = FFALIGN(height, 32) * FFALIGN(width, 32) * 3 / 2 / 2;
122 return FFALIGN(size, SZ_4K);
125 static inline void v4l2_save_to_context(V4L2Context* ctx, struct v4l2_format_update *fmt)
127 ctx->format.type = ctx->type;
129 if (fmt->update_avfmt)
130 ctx->av_pix_fmt = fmt->av_fmt;
132 if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
133 /* update the sizes to handle the reconfiguration of the capture stream at runtime */
134 ctx->format.fmt.pix_mp.height = ctx->height;
135 ctx->format.fmt.pix_mp.width = ctx->width;
136 if (fmt->update_v4l2) {
137 ctx->format.fmt.pix_mp.pixelformat = fmt->v4l2_fmt;
139 /* s5p-mfc requires the user to specify a buffer size */
140 ctx->format.fmt.pix_mp.plane_fmt[0].sizeimage =
141 v4l2_get_framesize_compressed(ctx, ctx->width, ctx->height);
144 ctx->format.fmt.pix.height = ctx->height;
145 ctx->format.fmt.pix.width = ctx->width;
146 if (fmt->update_v4l2) {
147 ctx->format.fmt.pix.pixelformat = fmt->v4l2_fmt;
149 /* s5p-mfc requires the user to specify a buffer size */
150 ctx->format.fmt.pix.sizeimage =
151 v4l2_get_framesize_compressed(ctx, ctx->width, ctx->height);
157 * returns 1 if reinit was successful, negative if it failed
158 * returns 0 if reinit was not executed
160 static int v4l2_handle_event(V4L2Context *ctx)
162 V4L2m2mContext *s = ctx_to_m2mctx(ctx);
163 struct v4l2_format cap_fmt = s->capture.format;
164 struct v4l2_format out_fmt = s->output.format;
165 struct v4l2_event evt = { 0 };
166 int full_reinit, reinit, ret;
168 ret = ioctl(s->fd, VIDIOC_DQEVENT, &evt);
170 av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_DQEVENT\n", ctx->name);
174 if (evt.type != V4L2_EVENT_SOURCE_CHANGE)
177 ret = ioctl(s->fd, VIDIOC_G_FMT, &out_fmt);
179 av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_G_FMT\n", s->output.name);
183 ret = ioctl(s->fd, VIDIOC_G_FMT, &cap_fmt);
185 av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_G_FMT\n", s->capture.name);
189 full_reinit = v4l2_resolution_changed(&s->output, &out_fmt);
191 s->output.height = v4l2_get_height(&out_fmt);
192 s->output.width = v4l2_get_width(&out_fmt);
193 s->output.sample_aspect_ratio = v4l2_get_sar(&s->output);
196 reinit = v4l2_resolution_changed(&s->capture, &cap_fmt);
198 s->capture.height = v4l2_get_height(&cap_fmt);
199 s->capture.width = v4l2_get_width(&cap_fmt);
200 s->capture.sample_aspect_ratio = v4l2_get_sar(&s->capture);
203 if (full_reinit || reinit)
207 ret = ff_v4l2_m2m_codec_full_reinit(s);
209 av_log(logger(ctx), AV_LOG_ERROR, "v4l2_m2m_codec_full_reinit\n");
217 ret = ff_set_dimensions(s->avctx, s->capture.width, s->capture.height);
219 av_log(logger(ctx), AV_LOG_WARNING, "update avcodec height and width\n");
221 ret = ff_v4l2_m2m_codec_reinit(s);
223 av_log(logger(ctx), AV_LOG_ERROR, "v4l2_m2m_codec_reinit\n");
229 /* dummy event received */
232 /* reinit executed */
237 static int v4l2_stop_decode(V4L2Context *ctx)
239 struct v4l2_decoder_cmd cmd = {
240 .cmd = V4L2_DEC_CMD_STOP,
245 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_DECODER_CMD, &cmd);
247 /* DECODER_CMD is optional */
249 return ff_v4l2_context_set_status(ctx, VIDIOC_STREAMOFF);
251 return AVERROR(errno);
257 static int v4l2_stop_encode(V4L2Context *ctx)
259 struct v4l2_encoder_cmd cmd = {
260 .cmd = V4L2_ENC_CMD_STOP,
265 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_ENCODER_CMD, &cmd);
267 /* ENCODER_CMD is optional */
269 return ff_v4l2_context_set_status(ctx, VIDIOC_STREAMOFF);
271 return AVERROR(errno);
277 static V4L2Buffer* v4l2_dequeue_v4l2buf(V4L2Context *ctx, int timeout)
279 struct v4l2_plane planes[VIDEO_MAX_PLANES];
280 struct v4l2_buffer buf = { 0 };
281 V4L2Buffer* avbuf = NULL;
282 struct pollfd pfd = {
283 .events = POLLIN | POLLRDNORM | POLLPRI | POLLOUT | POLLWRNORM, /* default blocking capture */
284 .fd = ctx_to_m2mctx(ctx)->fd,
288 /* if we are draining and there are no more capture buffers queued in the driver we are done */
289 if (!V4L2_TYPE_IS_OUTPUT(ctx->type) && ctx_to_m2mctx(ctx)->draining) {
290 for (i = 0; i < ctx->num_buffers; i++) {
291 /* capture buffer initialization happens during decode hence
292 * detection happens at runtime
297 if (ctx->buffers[i].status == V4L2BUF_IN_DRIVER)
305 if (V4L2_TYPE_IS_OUTPUT(ctx->type))
306 pfd.events = POLLOUT | POLLWRNORM;
308 /* no need to listen to requests for more input while draining */
309 if (ctx_to_m2mctx(ctx)->draining)
310 pfd.events = POLLIN | POLLRDNORM | POLLPRI;
314 ret = poll(&pfd, 1, timeout);
322 /* 0. handle errors */
323 if (pfd.revents & POLLERR) {
324 /* if we are trying to get free buffers but none have been queued yet
325 no need to raise a warning */
327 for (i = 0; i < ctx->num_buffers; i++) {
328 if (ctx->buffers[i].status != V4L2BUF_AVAILABLE)
329 av_log(logger(ctx), AV_LOG_WARNING, "%s POLLERR\n", ctx->name);
333 av_log(logger(ctx), AV_LOG_WARNING, "%s POLLERR\n", ctx->name);
338 /* 1. handle resolution changes */
339 if (pfd.revents & POLLPRI) {
340 ret = v4l2_handle_event(ctx);
342 /* if re-init failed, abort */
347 /* if re-init was successful drop the buffer (if there was one)
348 * since we had to reconfigure capture (unmap all buffers)
354 /* 2. dequeue the buffer */
355 if (pfd.revents & (POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM)) {
357 if (!V4L2_TYPE_IS_OUTPUT(ctx->type)) {
358 /* there is a capture buffer ready */
359 if (pfd.revents & (POLLIN | POLLRDNORM))
362 /* the driver is ready to accept more input; instead of waiting for the capture
363 * buffer to complete we return NULL so input can proceed (we are single threaded)
365 if (pfd.revents & (POLLOUT | POLLWRNORM))
370 memset(&buf, 0, sizeof(buf));
371 buf.memory = V4L2_MEMORY_MMAP;
372 buf.type = ctx->type;
373 if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
374 memset(planes, 0, sizeof(planes));
375 buf.length = VIDEO_MAX_PLANES;
376 buf.m.planes = planes;
379 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_DQBUF, &buf);
381 if (errno != EAGAIN) {
384 av_log(logger(ctx), AV_LOG_DEBUG, "%s VIDIOC_DQBUF, errno (%s)\n",
385 ctx->name, av_err2str(AVERROR(errno)));
390 avbuf = &ctx->buffers[buf.index];
391 avbuf->status = V4L2BUF_AVAILABLE;
393 if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
394 memcpy(avbuf->planes, planes, sizeof(planes));
395 avbuf->buf.m.planes = avbuf->planes;
403 static V4L2Buffer* v4l2_getfree_v4l2buf(V4L2Context *ctx)
405 int timeout = 0; /* return when no more buffers to dequeue */
408 /* get back as many output buffers as possible */
409 if (V4L2_TYPE_IS_OUTPUT(ctx->type)) {
411 } while (v4l2_dequeue_v4l2buf(ctx, timeout));
414 for (i = 0; i < ctx->num_buffers; i++) {
415 if (ctx->buffers[i].status == V4L2BUF_AVAILABLE)
416 return &ctx->buffers[i];
422 static int v4l2_release_buffers(V4L2Context* ctx)
424 struct v4l2_requestbuffers req = {
425 .memory = V4L2_MEMORY_MMAP,
427 .count = 0, /* 0 -> unmaps buffers from the driver */
431 for (i = 0; i < ctx->num_buffers; i++) {
432 V4L2Buffer *buffer = &ctx->buffers[i];
434 for (j = 0; j < buffer->num_planes; j++) {
435 struct V4L2Plane_info *p = &buffer->plane_info[j];
436 if (p->mm_addr && p->length)
437 if (munmap(p->mm_addr, p->length) < 0)
438 av_log(logger(ctx), AV_LOG_ERROR, "%s unmap plane (%s))\n", ctx->name, av_err2str(AVERROR(errno)));
442 return ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_REQBUFS, &req);
445 static inline int v4l2_try_raw_format(V4L2Context* ctx, enum AVPixelFormat pixfmt)
447 struct v4l2_format *fmt = &ctx->format;
451 v4l2_fmt = ff_v4l2_format_avfmt_to_v4l2(pixfmt);
453 return AVERROR(EINVAL);
455 if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type))
456 fmt->fmt.pix_mp.pixelformat = v4l2_fmt;
458 fmt->fmt.pix.pixelformat = v4l2_fmt;
460 fmt->type = ctx->type;
462 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_TRY_FMT, fmt);
464 return AVERROR(EINVAL);
469 static int v4l2_get_raw_format(V4L2Context* ctx, enum AVPixelFormat *p)
471 enum AVPixelFormat pixfmt = ctx->av_pix_fmt;
472 struct v4l2_fmtdesc fdesc;
475 memset(&fdesc, 0, sizeof(fdesc));
476 fdesc.type = ctx->type;
478 if (pixfmt != AV_PIX_FMT_NONE) {
479 ret = v4l2_try_raw_format(ctx, pixfmt);
485 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_ENUM_FMT, &fdesc);
487 return AVERROR(EINVAL);
489 pixfmt = ff_v4l2_format_v4l2_to_avfmt(fdesc.pixelformat, AV_CODEC_ID_RAWVIDEO);
490 ret = v4l2_try_raw_format(ctx, pixfmt);
501 return AVERROR(EINVAL);
504 static int v4l2_get_coded_format(V4L2Context* ctx, uint32_t *p)
506 struct v4l2_fmtdesc fdesc;
510 /* translate to a valid v4l2 format */
511 v4l2_fmt = ff_v4l2_format_avcodec_to_v4l2(ctx->av_codec_id);
513 return AVERROR(EINVAL);
515 /* check if the driver supports this format */
516 memset(&fdesc, 0, sizeof(fdesc));
517 fdesc.type = ctx->type;
520 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_ENUM_FMT, &fdesc);
522 return AVERROR(EINVAL);
524 if (fdesc.pixelformat == v4l2_fmt)
535 /*****************************************************************************
537 * V4L2 Context Interface
539 *****************************************************************************/
541 int ff_v4l2_context_set_status(V4L2Context* ctx, uint32_t cmd)
543 int type = ctx->type;
546 ret = ioctl(ctx_to_m2mctx(ctx)->fd, cmd, &type);
548 return AVERROR(errno);
550 ctx->streamon = (cmd == VIDIOC_STREAMON);
555 int ff_v4l2_context_enqueue_frame(V4L2Context* ctx, const AVFrame* frame)
557 V4L2m2mContext *s = ctx_to_m2mctx(ctx);
562 ret = v4l2_stop_encode(ctx);
564 av_log(logger(ctx), AV_LOG_ERROR, "%s stop_encode\n", ctx->name);
569 avbuf = v4l2_getfree_v4l2buf(ctx);
571 return AVERROR(ENOMEM);
573 ret = ff_v4l2_buffer_avframe_to_buf(frame, avbuf);
577 return ff_v4l2_buffer_enqueue(avbuf);
580 int ff_v4l2_context_enqueue_packet(V4L2Context* ctx, const AVPacket* pkt)
582 V4L2m2mContext *s = ctx_to_m2mctx(ctx);
587 ret = v4l2_stop_decode(ctx);
589 av_log(logger(ctx), AV_LOG_ERROR, "%s stop_decode\n", ctx->name);
594 avbuf = v4l2_getfree_v4l2buf(ctx);
596 return AVERROR(EAGAIN);
598 ret = ff_v4l2_buffer_avpkt_to_buf(pkt, avbuf);
602 return ff_v4l2_buffer_enqueue(avbuf);
605 int ff_v4l2_context_dequeue_frame(V4L2Context* ctx, AVFrame* frame, int timeout)
607 V4L2Buffer* avbuf = NULL;
610 * timeout=-1 blocks until:
611 * 1. decoded frame available
612 * 2. an input buffer is ready to be dequeued
614 avbuf = v4l2_dequeue_v4l2buf(ctx, timeout);
619 return AVERROR(EAGAIN);
622 return ff_v4l2_buffer_buf_to_avframe(frame, avbuf);
625 int ff_v4l2_context_dequeue_packet(V4L2Context* ctx, AVPacket* pkt)
627 V4L2Buffer* avbuf = NULL;
631 * 1. encoded packet available
632 * 2. an input buffer ready to be dequeued
634 avbuf = v4l2_dequeue_v4l2buf(ctx, -1);
639 return AVERROR(EAGAIN);
642 return ff_v4l2_buffer_buf_to_avpkt(pkt, avbuf);
645 int ff_v4l2_context_get_format(V4L2Context* ctx, int probe)
647 struct v4l2_format_update fmt = { 0 };
650 if (ctx->av_codec_id == AV_CODEC_ID_RAWVIDEO) {
651 ret = v4l2_get_raw_format(ctx, &fmt.av_fmt);
655 fmt.update_avfmt = !probe;
656 v4l2_save_to_context(ctx, &fmt);
658 /* format has been tried already */
662 ret = v4l2_get_coded_format(ctx, &fmt.v4l2_fmt);
667 v4l2_save_to_context(ctx, &fmt);
669 return ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_TRY_FMT, &ctx->format);
672 int ff_v4l2_context_set_format(V4L2Context* ctx)
674 return ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_S_FMT, &ctx->format);
677 void ff_v4l2_context_release(V4L2Context* ctx)
684 ret = v4l2_release_buffers(ctx);
686 av_log(logger(ctx), AV_LOG_WARNING, "V4L2 failed to unmap the %s buffers\n", ctx->name);
688 av_free(ctx->buffers);
692 int ff_v4l2_context_init(V4L2Context* ctx)
694 V4L2m2mContext *s = ctx_to_m2mctx(ctx);
695 struct v4l2_requestbuffers req;
698 if (!v4l2_type_supported(ctx)) {
699 av_log(logger(ctx), AV_LOG_ERROR, "type %i not supported\n", ctx->type);
700 return AVERROR_PATCHWELCOME;
703 ret = ioctl(s->fd, VIDIOC_G_FMT, &ctx->format);
705 av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_G_FMT failed\n", ctx->name);
707 memset(&req, 0, sizeof(req));
708 req.count = ctx->num_buffers;
709 req.memory = V4L2_MEMORY_MMAP;
710 req.type = ctx->type;
711 ret = ioctl(s->fd, VIDIOC_REQBUFS, &req);
713 av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_REQBUFS failed: %s\n", ctx->name, strerror(errno));
714 return AVERROR(errno);
717 ctx->num_buffers = req.count;
718 ctx->buffers = av_mallocz(ctx->num_buffers * sizeof(V4L2Buffer));
720 av_log(logger(ctx), AV_LOG_ERROR, "%s malloc enomem\n", ctx->name);
721 return AVERROR(ENOMEM);
724 for (i = 0; i < req.count; i++) {
725 ctx->buffers[i].context = ctx;
726 ret = ff_v4l2_buffer_initialize(&ctx->buffers[i], i);
728 av_log(logger(ctx), AV_LOG_ERROR, "%s buffer[%d] initialization (%s)\n", ctx->name, i, av_err2str(ret));
733 av_log(logger(ctx), AV_LOG_DEBUG, "%s: %s %02d buffers initialized: %04ux%04u, sizeimage %08u, bytesperline %08u\n", ctx->name,
734 V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ? av_fourcc2str(ctx->format.fmt.pix_mp.pixelformat) : av_fourcc2str(ctx->format.fmt.pix.pixelformat),
736 v4l2_get_width(&ctx->format),
737 v4l2_get_height(&ctx->format),
738 V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ? ctx->format.fmt.pix_mp.plane_fmt[0].sizeimage : ctx->format.fmt.pix.sizeimage,
739 V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ? ctx->format.fmt.pix_mp.plane_fmt[0].bytesperline : ctx->format.fmt.pix.bytesperline);
744 v4l2_release_buffers(ctx);
746 av_free(ctx->buffers);