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 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 * handle resolution change event and end of stream event
158 * returns 1 if reinit was successful, negative if it failed
159 * returns 0 if reinit was not executed
161 static int v4l2_handle_event(V4L2Context *ctx)
163 V4L2m2mContext *s = ctx_to_m2mctx(ctx);
164 struct v4l2_format cap_fmt = s->capture.format;
165 struct v4l2_format out_fmt = s->output.format;
166 struct v4l2_event evt = { 0 };
167 int full_reinit, reinit, ret;
169 ret = ioctl(s->fd, VIDIOC_DQEVENT, &evt);
171 av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_DQEVENT\n", ctx->name);
175 if (evt.type == V4L2_EVENT_EOS) {
180 if (evt.type != V4L2_EVENT_SOURCE_CHANGE)
183 ret = ioctl(s->fd, VIDIOC_G_FMT, &out_fmt);
185 av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_G_FMT\n", s->output.name);
189 ret = ioctl(s->fd, VIDIOC_G_FMT, &cap_fmt);
191 av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_G_FMT\n", s->capture.name);
195 full_reinit = v4l2_resolution_changed(&s->output, &out_fmt);
197 s->output.height = v4l2_get_height(&out_fmt);
198 s->output.width = v4l2_get_width(&out_fmt);
199 s->output.sample_aspect_ratio = v4l2_get_sar(&s->output);
202 reinit = v4l2_resolution_changed(&s->capture, &cap_fmt);
204 s->capture.height = v4l2_get_height(&cap_fmt);
205 s->capture.width = v4l2_get_width(&cap_fmt);
206 s->capture.sample_aspect_ratio = v4l2_get_sar(&s->capture);
209 if (full_reinit || reinit)
213 ret = ff_v4l2_m2m_codec_full_reinit(s);
215 av_log(logger(ctx), AV_LOG_ERROR, "v4l2_m2m_codec_full_reinit\n");
216 return AVERROR(EINVAL);
223 ret = ff_set_dimensions(s->avctx, s->capture.width, s->capture.height);
225 av_log(logger(ctx), AV_LOG_WARNING, "update avcodec height and width\n");
227 ret = ff_v4l2_m2m_codec_reinit(s);
229 av_log(logger(ctx), AV_LOG_ERROR, "v4l2_m2m_codec_reinit\n");
230 return AVERROR(EINVAL);
235 /* dummy event received */
238 /* reinit executed */
243 static int v4l2_stop_decode(V4L2Context *ctx)
245 struct v4l2_decoder_cmd cmd = {
246 .cmd = V4L2_DEC_CMD_STOP,
251 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_DECODER_CMD, &cmd);
253 /* DECODER_CMD is optional */
255 return ff_v4l2_context_set_status(ctx, VIDIOC_STREAMOFF);
257 return AVERROR(errno);
263 static int v4l2_stop_encode(V4L2Context *ctx)
265 struct v4l2_encoder_cmd cmd = {
266 .cmd = V4L2_ENC_CMD_STOP,
271 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_ENCODER_CMD, &cmd);
273 /* ENCODER_CMD is optional */
275 return ff_v4l2_context_set_status(ctx, VIDIOC_STREAMOFF);
277 return AVERROR(errno);
283 static V4L2Buffer* v4l2_dequeue_v4l2buf(V4L2Context *ctx, int timeout)
285 struct v4l2_plane planes[VIDEO_MAX_PLANES];
286 struct v4l2_buffer buf = { 0 };
288 struct pollfd pfd = {
289 .events = POLLIN | POLLRDNORM | POLLPRI | POLLOUT | POLLWRNORM, /* default blocking capture */
290 .fd = ctx_to_m2mctx(ctx)->fd,
294 if (!V4L2_TYPE_IS_OUTPUT(ctx->type) && ctx->buffers) {
295 for (i = 0; i < ctx->num_buffers; i++) {
296 if (ctx->buffers[i].status == V4L2BUF_IN_DRIVER)
299 if (i == ctx->num_buffers)
300 av_log(logger(ctx), AV_LOG_WARNING, "All capture buffers returned to "
301 "userspace. Increase num_capture_buffers "
302 "to prevent device deadlock or dropped "
303 "packets/frames.\n");
306 /* if we are draining and there are no more capture buffers queued in the driver we are done */
307 if (!V4L2_TYPE_IS_OUTPUT(ctx->type) && ctx_to_m2mctx(ctx)->draining) {
308 for (i = 0; i < ctx->num_buffers; i++) {
309 /* capture buffer initialization happens during decode hence
310 * detection happens at runtime
315 if (ctx->buffers[i].status == V4L2BUF_IN_DRIVER)
323 if (V4L2_TYPE_IS_OUTPUT(ctx->type))
324 pfd.events = POLLOUT | POLLWRNORM;
326 /* no need to listen to requests for more input while draining */
327 if (ctx_to_m2mctx(ctx)->draining)
328 pfd.events = POLLIN | POLLRDNORM | POLLPRI;
332 ret = poll(&pfd, 1, timeout);
340 /* 0. handle errors */
341 if (pfd.revents & POLLERR) {
342 /* if we are trying to get free buffers but none have been queued yet
343 no need to raise a warning */
345 for (i = 0; i < ctx->num_buffers; i++) {
346 if (ctx->buffers[i].status != V4L2BUF_AVAILABLE)
347 av_log(logger(ctx), AV_LOG_WARNING, "%s POLLERR\n", ctx->name);
351 av_log(logger(ctx), AV_LOG_WARNING, "%s POLLERR\n", ctx->name);
356 /* 1. handle resolution changes */
357 if (pfd.revents & POLLPRI) {
358 ret = v4l2_handle_event(ctx);
360 /* if re-init failed, abort */
365 /* if re-init was successful drop the buffer (if there was one)
366 * since we had to reconfigure capture (unmap all buffers)
372 /* 2. dequeue the buffer */
373 if (pfd.revents & (POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM)) {
375 if (!V4L2_TYPE_IS_OUTPUT(ctx->type)) {
376 /* there is a capture buffer ready */
377 if (pfd.revents & (POLLIN | POLLRDNORM))
380 /* the driver is ready to accept more input; instead of waiting for the capture
381 * buffer to complete we return NULL so input can proceed (we are single threaded)
383 if (pfd.revents & (POLLOUT | POLLWRNORM))
388 memset(&buf, 0, sizeof(buf));
389 buf.memory = V4L2_MEMORY_MMAP;
390 buf.type = ctx->type;
391 if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
392 memset(planes, 0, sizeof(planes));
393 buf.length = VIDEO_MAX_PLANES;
394 buf.m.planes = planes;
397 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_DQBUF, &buf);
399 if (errno != EAGAIN) {
402 av_log(logger(ctx), AV_LOG_DEBUG, "%s VIDIOC_DQBUF, errno (%s)\n",
403 ctx->name, av_err2str(AVERROR(errno)));
408 if (ctx_to_m2mctx(ctx)->draining && !V4L2_TYPE_IS_OUTPUT(ctx->type)) {
409 int bytesused = V4L2_TYPE_IS_MULTIPLANAR(buf.type) ?
410 buf.m.planes[0].bytesused : buf.bytesused;
411 if (bytesused == 0) {
415 #ifdef V4L2_BUF_FLAG_LAST
416 if (buf.flags & V4L2_BUF_FLAG_LAST)
421 avbuf = &ctx->buffers[buf.index];
422 avbuf->status = V4L2BUF_AVAILABLE;
424 if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
425 memcpy(avbuf->planes, planes, sizeof(planes));
426 avbuf->buf.m.planes = avbuf->planes;
434 static V4L2Buffer* v4l2_getfree_v4l2buf(V4L2Context *ctx)
436 int timeout = 0; /* return when no more buffers to dequeue */
439 /* get back as many output buffers as possible */
440 if (V4L2_TYPE_IS_OUTPUT(ctx->type)) {
442 } while (v4l2_dequeue_v4l2buf(ctx, timeout));
445 for (i = 0; i < ctx->num_buffers; i++) {
446 if (ctx->buffers[i].status == V4L2BUF_AVAILABLE)
447 return &ctx->buffers[i];
453 static int v4l2_release_buffers(V4L2Context* ctx)
455 struct v4l2_requestbuffers req = {
456 .memory = V4L2_MEMORY_MMAP,
458 .count = 0, /* 0 -> unmaps buffers from the driver */
462 for (i = 0; i < ctx->num_buffers; i++) {
463 V4L2Buffer *buffer = &ctx->buffers[i];
465 for (j = 0; j < buffer->num_planes; j++) {
466 struct V4L2Plane_info *p = &buffer->plane_info[j];
467 if (p->mm_addr && p->length)
468 if (munmap(p->mm_addr, p->length) < 0)
469 av_log(logger(ctx), AV_LOG_ERROR, "%s unmap plane (%s))\n", ctx->name, av_err2str(AVERROR(errno)));
473 return ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_REQBUFS, &req);
476 static inline int v4l2_try_raw_format(V4L2Context* ctx, enum AVPixelFormat pixfmt)
478 struct v4l2_format *fmt = &ctx->format;
482 v4l2_fmt = ff_v4l2_format_avfmt_to_v4l2(pixfmt);
484 return AVERROR(EINVAL);
486 if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type))
487 fmt->fmt.pix_mp.pixelformat = v4l2_fmt;
489 fmt->fmt.pix.pixelformat = v4l2_fmt;
491 fmt->type = ctx->type;
493 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_TRY_FMT, fmt);
495 return AVERROR(EINVAL);
500 static int v4l2_get_raw_format(V4L2Context* ctx, enum AVPixelFormat *p)
502 enum AVPixelFormat pixfmt = ctx->av_pix_fmt;
503 struct v4l2_fmtdesc fdesc;
506 memset(&fdesc, 0, sizeof(fdesc));
507 fdesc.type = ctx->type;
509 if (pixfmt != AV_PIX_FMT_NONE) {
510 ret = v4l2_try_raw_format(ctx, pixfmt);
516 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_ENUM_FMT, &fdesc);
518 return AVERROR(EINVAL);
520 pixfmt = ff_v4l2_format_v4l2_to_avfmt(fdesc.pixelformat, AV_CODEC_ID_RAWVIDEO);
521 ret = v4l2_try_raw_format(ctx, pixfmt);
532 return AVERROR(EINVAL);
535 static int v4l2_get_coded_format(V4L2Context* ctx, uint32_t *p)
537 struct v4l2_fmtdesc fdesc;
541 /* translate to a valid v4l2 format */
542 v4l2_fmt = ff_v4l2_format_avcodec_to_v4l2(ctx->av_codec_id);
544 return AVERROR(EINVAL);
546 /* check if the driver supports this format */
547 memset(&fdesc, 0, sizeof(fdesc));
548 fdesc.type = ctx->type;
551 ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_ENUM_FMT, &fdesc);
553 return AVERROR(EINVAL);
555 if (fdesc.pixelformat == v4l2_fmt)
566 /*****************************************************************************
568 * V4L2 Context Interface
570 *****************************************************************************/
572 int ff_v4l2_context_set_status(V4L2Context* ctx, uint32_t cmd)
574 int type = ctx->type;
577 ret = ioctl(ctx_to_m2mctx(ctx)->fd, cmd, &type);
579 return AVERROR(errno);
581 ctx->streamon = (cmd == VIDIOC_STREAMON);
586 int ff_v4l2_context_enqueue_frame(V4L2Context* ctx, const AVFrame* frame)
588 V4L2m2mContext *s = ctx_to_m2mctx(ctx);
593 ret = v4l2_stop_encode(ctx);
595 av_log(logger(ctx), AV_LOG_ERROR, "%s stop_encode\n", ctx->name);
600 avbuf = v4l2_getfree_v4l2buf(ctx);
602 return AVERROR(EAGAIN);
604 ret = ff_v4l2_buffer_avframe_to_buf(frame, avbuf);
608 return ff_v4l2_buffer_enqueue(avbuf);
611 int ff_v4l2_context_enqueue_packet(V4L2Context* ctx, const AVPacket* pkt)
613 V4L2m2mContext *s = ctx_to_m2mctx(ctx);
618 ret = v4l2_stop_decode(ctx);
620 av_log(logger(ctx), AV_LOG_ERROR, "%s stop_decode\n", ctx->name);
625 avbuf = v4l2_getfree_v4l2buf(ctx);
627 return AVERROR(EAGAIN);
629 ret = ff_v4l2_buffer_avpkt_to_buf(pkt, avbuf);
633 return ff_v4l2_buffer_enqueue(avbuf);
636 int ff_v4l2_context_dequeue_frame(V4L2Context* ctx, AVFrame* frame, int timeout)
641 * timeout=-1 blocks until:
642 * 1. decoded frame available
643 * 2. an input buffer is ready to be dequeued
645 avbuf = v4l2_dequeue_v4l2buf(ctx, timeout);
650 return AVERROR(EAGAIN);
653 return ff_v4l2_buffer_buf_to_avframe(frame, avbuf);
656 int ff_v4l2_context_dequeue_packet(V4L2Context* ctx, AVPacket* pkt)
662 * 1. encoded packet available
663 * 2. an input buffer ready to be dequeued
665 avbuf = v4l2_dequeue_v4l2buf(ctx, -1);
670 return AVERROR(EAGAIN);
673 return ff_v4l2_buffer_buf_to_avpkt(pkt, avbuf);
676 int ff_v4l2_context_get_format(V4L2Context* ctx, int probe)
678 struct v4l2_format_update fmt = { 0 };
681 if (ctx->av_codec_id == AV_CODEC_ID_RAWVIDEO) {
682 ret = v4l2_get_raw_format(ctx, &fmt.av_fmt);
686 fmt.update_avfmt = !probe;
687 v4l2_save_to_context(ctx, &fmt);
689 /* format has been tried already */
693 ret = v4l2_get_coded_format(ctx, &fmt.v4l2_fmt);
698 v4l2_save_to_context(ctx, &fmt);
700 return ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_TRY_FMT, &ctx->format);
703 int ff_v4l2_context_set_format(V4L2Context* ctx)
705 return ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_S_FMT, &ctx->format);
708 void ff_v4l2_context_release(V4L2Context* ctx)
715 ret = v4l2_release_buffers(ctx);
717 av_log(logger(ctx), AV_LOG_WARNING, "V4L2 failed to unmap the %s buffers\n", ctx->name);
719 av_freep(&ctx->buffers);
722 int ff_v4l2_context_init(V4L2Context* ctx)
724 V4L2m2mContext *s = ctx_to_m2mctx(ctx);
725 struct v4l2_requestbuffers req;
728 if (!v4l2_type_supported(ctx)) {
729 av_log(logger(ctx), AV_LOG_ERROR, "type %i not supported\n", ctx->type);
730 return AVERROR_PATCHWELCOME;
733 ret = ioctl(s->fd, VIDIOC_G_FMT, &ctx->format);
735 av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_G_FMT failed\n", ctx->name);
737 memset(&req, 0, sizeof(req));
738 req.count = ctx->num_buffers;
739 req.memory = V4L2_MEMORY_MMAP;
740 req.type = ctx->type;
741 ret = ioctl(s->fd, VIDIOC_REQBUFS, &req);
743 av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_REQBUFS failed: %s\n", ctx->name, strerror(errno));
744 return AVERROR(errno);
747 ctx->num_buffers = req.count;
748 ctx->buffers = av_mallocz(ctx->num_buffers * sizeof(V4L2Buffer));
750 av_log(logger(ctx), AV_LOG_ERROR, "%s malloc enomem\n", ctx->name);
751 return AVERROR(ENOMEM);
754 for (i = 0; i < req.count; i++) {
755 ctx->buffers[i].context = ctx;
756 ret = ff_v4l2_buffer_initialize(&ctx->buffers[i], i);
758 av_log(logger(ctx), AV_LOG_ERROR, "%s buffer[%d] initialization (%s)\n", ctx->name, i, av_err2str(ret));
763 av_log(logger(ctx), AV_LOG_DEBUG, "%s: %s %02d buffers initialized: %04ux%04u, sizeimage %08u, bytesperline %08u\n", ctx->name,
764 V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ? av_fourcc2str(ctx->format.fmt.pix_mp.pixelformat) : av_fourcc2str(ctx->format.fmt.pix.pixelformat),
766 v4l2_get_width(&ctx->format),
767 v4l2_get_height(&ctx->format),
768 V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ? ctx->format.fmt.pix_mp.plane_fmt[0].sizeimage : ctx->format.fmt.pix.sizeimage,
769 V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ? ctx->format.fmt.pix_mp.plane_fmt[0].bytesperline : ctx->format.fmt.pix.bytesperline);
774 v4l2_release_buffers(ctx);
776 av_freep(&ctx->buffers);