]> git.sesse.net Git - ffmpeg/blob - libavcodec/v4l2_context.c
avcodec/v4l2_m2m: handle v4l2 end of stream event
[ffmpeg] / libavcodec / v4l2_context.c
1 /*
2  * V4L2 context helper functions.
3  *
4  * Copyright (C) 2017 Alexis Ballier <aballier@gentoo.org>
5  * Copyright (C) 2017 Jorge Ramirez <jorge.ramirez-ortiz@linaro.org>
6  *
7  * This file is part of FFmpeg.
8  *
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.
13  *
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.
18  *
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
22  */
23
24 #include <linux/videodev2.h>
25 #include <sys/ioctl.h>
26 #include <sys/mman.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29 #include <poll.h>
30 #include "libavcodec/avcodec.h"
31 #include "libavcodec/internal.h"
32 #include "v4l2_buffers.h"
33 #include "v4l2_fmt.h"
34 #include "v4l2_m2m.h"
35
36 struct v4l2_format_update {
37     uint32_t v4l2_fmt;
38     int update_v4l2;
39
40     enum AVPixelFormat av_fmt;
41     int update_avfmt;
42 };
43
44 static inline V4L2m2mContext *ctx_to_m2mctx(V4L2Context *ctx)
45 {
46     return V4L2_TYPE_IS_OUTPUT(ctx->type) ?
47         container_of(ctx, V4L2m2mContext, output) :
48         container_of(ctx, V4L2m2mContext, capture);
49 }
50
51 static inline AVCodecContext *logger(V4L2Context *ctx)
52 {
53     return ctx_to_m2mctx(ctx)->avctx;
54 }
55
56 static inline unsigned int v4l2_get_width(struct v4l2_format *fmt)
57 {
58     return V4L2_TYPE_IS_MULTIPLANAR(fmt->type) ? fmt->fmt.pix_mp.width : fmt->fmt.pix.width;
59 }
60
61 static inline unsigned int v4l2_get_height(struct v4l2_format *fmt)
62 {
63     return V4L2_TYPE_IS_MULTIPLANAR(fmt->type) ? fmt->fmt.pix_mp.height : fmt->fmt.pix.height;
64 }
65
66 static AVRational v4l2_get_sar(V4L2Context *ctx)
67 {
68     struct AVRational sar = { 0, 1 };
69     struct v4l2_cropcap cropcap;
70     int ret;
71
72     memset(&cropcap, 0, sizeof(cropcap));
73     cropcap.type = ctx->type;
74
75     ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_CROPCAP, &cropcap);
76     if (ret)
77         return sar;
78
79     sar.num = cropcap.pixelaspect.numerator;
80     sar.den = cropcap.pixelaspect.denominator;
81     return sar;
82 }
83
84 static inline unsigned int v4l2_resolution_changed(V4L2Context *ctx, struct v4l2_format *fmt2)
85 {
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
90         :
91         fmt1->fmt.pix.width != fmt2->fmt.pix.width ||
92         fmt1->fmt.pix.height != fmt2->fmt.pix.height;
93
94     if (ret)
95         av_log(logger(ctx), AV_LOG_DEBUG, "%s changed (%dx%d) -> (%dx%d)\n",
96             ctx->name,
97             v4l2_get_width(fmt1), v4l2_get_height(fmt1),
98             v4l2_get_width(fmt2), v4l2_get_height(fmt2));
99
100     return ret;
101 }
102
103 static inline int v4l2_type_supported(V4L2Context *ctx)
104 {
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;
109 }
110
111 static inline int v4l2_get_framesize_compressed(V4L2Context* ctx, int width, int height)
112 {
113     V4L2m2mContext *s = ctx_to_m2mctx(ctx);
114     const int SZ_4K = 0x1000;
115     int size;
116
117     if (s->avctx && av_codec_is_decoder(s->avctx->codec))
118         return ((width * height * 3 / 2) / 2) + 128;
119
120     /* encoder */
121     size = FFALIGN(height, 32) * FFALIGN(width, 32) * 3 / 2 / 2;
122     return FFALIGN(size, SZ_4K);
123 }
124
125 static inline void v4l2_save_to_context(V4L2Context* ctx, struct v4l2_format_update *fmt)
126 {
127     ctx->format.type = ctx->type;
128
129     if (fmt->update_avfmt)
130         ctx->av_pix_fmt = fmt->av_fmt;
131
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;
138
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);
142         }
143     } else {
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;
148
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);
152         }
153     }
154 }
155
156 /**
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
160  */
161 static int v4l2_handle_event(V4L2Context *ctx)
162 {
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;
168
169     ret = ioctl(s->fd, VIDIOC_DQEVENT, &evt);
170     if (ret < 0) {
171         av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_DQEVENT\n", ctx->name);
172         return 0;
173     }
174
175     if (evt.type == V4L2_EVENT_EOS) {
176         ctx->done = 1;
177         return 0;
178     }
179
180     if (evt.type != V4L2_EVENT_SOURCE_CHANGE)
181         return 0;
182
183     ret = ioctl(s->fd, VIDIOC_G_FMT, &out_fmt);
184     if (ret) {
185         av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_G_FMT\n", s->output.name);
186         return 0;
187     }
188
189     ret = ioctl(s->fd, VIDIOC_G_FMT, &cap_fmt);
190     if (ret) {
191         av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_G_FMT\n", s->capture.name);
192         return 0;
193     }
194
195     full_reinit = v4l2_resolution_changed(&s->output, &out_fmt);
196     if (full_reinit) {
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);
200     }
201
202     reinit = v4l2_resolution_changed(&s->capture, &cap_fmt);
203     if (reinit) {
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);
207     }
208
209     if (full_reinit || reinit)
210         s->reinit = 1;
211
212     if (full_reinit) {
213         ret = ff_v4l2_m2m_codec_full_reinit(s);
214         if (ret) {
215             av_log(logger(ctx), AV_LOG_ERROR, "v4l2_m2m_codec_full_reinit\n");
216             return AVERROR(EINVAL);
217         }
218         goto reinit_run;
219     }
220
221     if (reinit) {
222         if (s->avctx)
223             ret = ff_set_dimensions(s->avctx, s->capture.width, s->capture.height);
224         if (ret < 0)
225             av_log(logger(ctx), AV_LOG_WARNING, "update avcodec height and width\n");
226
227         ret = ff_v4l2_m2m_codec_reinit(s);
228         if (ret) {
229             av_log(logger(ctx), AV_LOG_ERROR, "v4l2_m2m_codec_reinit\n");
230             return AVERROR(EINVAL);
231         }
232         goto reinit_run;
233     }
234
235     /* dummy event received */
236     return 0;
237
238     /* reinit executed */
239 reinit_run:
240     return 1;
241 }
242
243 static int v4l2_stop_decode(V4L2Context *ctx)
244 {
245     struct v4l2_decoder_cmd cmd = {
246         .cmd = V4L2_DEC_CMD_STOP,
247         .flags = 0,
248     };
249     int ret;
250
251     ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_DECODER_CMD, &cmd);
252     if (ret) {
253         /* DECODER_CMD is optional */
254         if (errno == ENOTTY)
255             return ff_v4l2_context_set_status(ctx, VIDIOC_STREAMOFF);
256         else
257             return AVERROR(errno);
258     }
259
260     return 0;
261 }
262
263 static int v4l2_stop_encode(V4L2Context *ctx)
264 {
265     struct v4l2_encoder_cmd cmd = {
266         .cmd = V4L2_ENC_CMD_STOP,
267         .flags = 0,
268     };
269     int ret;
270
271     ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_ENCODER_CMD, &cmd);
272     if (ret) {
273         /* ENCODER_CMD is optional */
274         if (errno == ENOTTY)
275             return ff_v4l2_context_set_status(ctx, VIDIOC_STREAMOFF);
276         else
277             return AVERROR(errno);
278     }
279
280     return 0;
281 }
282
283 static V4L2Buffer* v4l2_dequeue_v4l2buf(V4L2Context *ctx, int timeout)
284 {
285     struct v4l2_plane planes[VIDEO_MAX_PLANES];
286     struct v4l2_buffer buf = { 0 };
287     V4L2Buffer *avbuf;
288     struct pollfd pfd = {
289         .events =  POLLIN | POLLRDNORM | POLLPRI | POLLOUT | POLLWRNORM, /* default blocking capture */
290         .fd = ctx_to_m2mctx(ctx)->fd,
291     };
292     int i, ret;
293
294     /* if we are draining and there are no more capture buffers queued in the driver we are done */
295     if (!V4L2_TYPE_IS_OUTPUT(ctx->type) && ctx_to_m2mctx(ctx)->draining) {
296         for (i = 0; i < ctx->num_buffers; i++) {
297             /* capture buffer initialization happens during decode hence
298              * detection happens at runtime
299              */
300             if (!ctx->buffers)
301                 break;
302
303             if (ctx->buffers[i].status == V4L2BUF_IN_DRIVER)
304                 goto start;
305         }
306         ctx->done = 1;
307         return NULL;
308     }
309
310 start:
311     if (V4L2_TYPE_IS_OUTPUT(ctx->type))
312         pfd.events =  POLLOUT | POLLWRNORM;
313     else {
314         /* no need to listen to requests for more input while draining */
315         if (ctx_to_m2mctx(ctx)->draining)
316             pfd.events =  POLLIN | POLLRDNORM | POLLPRI;
317     }
318
319     for (;;) {
320         ret = poll(&pfd, 1, timeout);
321         if (ret > 0)
322             break;
323         if (errno == EINTR)
324             continue;
325         return NULL;
326     }
327
328     /* 0. handle errors */
329     if (pfd.revents & POLLERR) {
330         /* if we are trying to get free buffers but none have been queued yet
331            no need to raise a warning */
332         if (timeout == 0) {
333             for (i = 0; i < ctx->num_buffers; i++) {
334                 if (ctx->buffers[i].status != V4L2BUF_AVAILABLE)
335                     av_log(logger(ctx), AV_LOG_WARNING, "%s POLLERR\n", ctx->name);
336             }
337         }
338         else
339             av_log(logger(ctx), AV_LOG_WARNING, "%s POLLERR\n", ctx->name);
340
341         return NULL;
342     }
343
344     /* 1. handle resolution changes */
345     if (pfd.revents & POLLPRI) {
346         ret = v4l2_handle_event(ctx);
347         if (ret < 0) {
348             /* if re-init failed, abort */
349             ctx->done = 1;
350             return NULL;
351         }
352         if (ret) {
353             /* if re-init was successful drop the buffer (if there was one)
354              * since we had to reconfigure capture (unmap all buffers)
355              */
356             return NULL;
357         }
358     }
359
360     /* 2. dequeue the buffer */
361     if (pfd.revents & (POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM)) {
362
363         if (!V4L2_TYPE_IS_OUTPUT(ctx->type)) {
364             /* there is a capture buffer ready */
365             if (pfd.revents & (POLLIN | POLLRDNORM))
366                 goto dequeue;
367
368             /* the driver is ready to accept more input; instead of waiting for the capture
369              * buffer to complete we return NULL so input can proceed (we are single threaded)
370              */
371             if (pfd.revents & (POLLOUT | POLLWRNORM))
372                 return NULL;
373         }
374
375 dequeue:
376         memset(&buf, 0, sizeof(buf));
377         buf.memory = V4L2_MEMORY_MMAP;
378         buf.type = ctx->type;
379         if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
380             memset(planes, 0, sizeof(planes));
381             buf.length = VIDEO_MAX_PLANES;
382             buf.m.planes = planes;
383         }
384
385         ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_DQBUF, &buf);
386         if (ret) {
387             if (errno != EAGAIN) {
388                 ctx->done = 1;
389                 if (errno != EPIPE)
390                     av_log(logger(ctx), AV_LOG_DEBUG, "%s VIDIOC_DQBUF, errno (%s)\n",
391                         ctx->name, av_err2str(AVERROR(errno)));
392             }
393             return NULL;
394         }
395
396         avbuf = &ctx->buffers[buf.index];
397         avbuf->status = V4L2BUF_AVAILABLE;
398         avbuf->buf = buf;
399         if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
400             memcpy(avbuf->planes, planes, sizeof(planes));
401             avbuf->buf.m.planes = avbuf->planes;
402         }
403         return avbuf;
404     }
405
406     return NULL;
407 }
408
409 static V4L2Buffer* v4l2_getfree_v4l2buf(V4L2Context *ctx)
410 {
411     int timeout = 0; /* return when no more buffers to dequeue */
412     int i;
413
414     /* get back as many output buffers as possible */
415     if (V4L2_TYPE_IS_OUTPUT(ctx->type)) {
416           do {
417           } while (v4l2_dequeue_v4l2buf(ctx, timeout));
418     }
419
420     for (i = 0; i < ctx->num_buffers; i++) {
421         if (ctx->buffers[i].status == V4L2BUF_AVAILABLE)
422             return &ctx->buffers[i];
423     }
424
425     return NULL;
426 }
427
428 static int v4l2_release_buffers(V4L2Context* ctx)
429 {
430     struct v4l2_requestbuffers req = {
431         .memory = V4L2_MEMORY_MMAP,
432         .type = ctx->type,
433         .count = 0, /* 0 -> unmaps buffers from the driver */
434     };
435     int i, j;
436
437     for (i = 0; i < ctx->num_buffers; i++) {
438         V4L2Buffer *buffer = &ctx->buffers[i];
439
440         for (j = 0; j < buffer->num_planes; j++) {
441             struct V4L2Plane_info *p = &buffer->plane_info[j];
442             if (p->mm_addr && p->length)
443                 if (munmap(p->mm_addr, p->length) < 0)
444                     av_log(logger(ctx), AV_LOG_ERROR, "%s unmap plane (%s))\n", ctx->name, av_err2str(AVERROR(errno)));
445         }
446     }
447
448     return ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_REQBUFS, &req);
449 }
450
451 static inline int v4l2_try_raw_format(V4L2Context* ctx, enum AVPixelFormat pixfmt)
452 {
453     struct v4l2_format *fmt = &ctx->format;
454     uint32_t v4l2_fmt;
455     int ret;
456
457     v4l2_fmt = ff_v4l2_format_avfmt_to_v4l2(pixfmt);
458     if (!v4l2_fmt)
459         return AVERROR(EINVAL);
460
461     if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type))
462         fmt->fmt.pix_mp.pixelformat = v4l2_fmt;
463     else
464         fmt->fmt.pix.pixelformat = v4l2_fmt;
465
466     fmt->type = ctx->type;
467
468     ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_TRY_FMT, fmt);
469     if (ret)
470         return AVERROR(EINVAL);
471
472     return 0;
473 }
474
475 static int v4l2_get_raw_format(V4L2Context* ctx, enum AVPixelFormat *p)
476 {
477     enum AVPixelFormat pixfmt = ctx->av_pix_fmt;
478     struct v4l2_fmtdesc fdesc;
479     int ret;
480
481     memset(&fdesc, 0, sizeof(fdesc));
482     fdesc.type = ctx->type;
483
484     if (pixfmt != AV_PIX_FMT_NONE) {
485         ret = v4l2_try_raw_format(ctx, pixfmt);
486         if (!ret)
487             return 0;
488     }
489
490     for (;;) {
491         ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_ENUM_FMT, &fdesc);
492         if (ret)
493             return AVERROR(EINVAL);
494
495         pixfmt = ff_v4l2_format_v4l2_to_avfmt(fdesc.pixelformat, AV_CODEC_ID_RAWVIDEO);
496         ret = v4l2_try_raw_format(ctx, pixfmt);
497         if (ret){
498             fdesc.index++;
499             continue;
500         }
501
502         *p = pixfmt;
503
504         return 0;
505     }
506
507     return AVERROR(EINVAL);
508 }
509
510 static int v4l2_get_coded_format(V4L2Context* ctx, uint32_t *p)
511 {
512     struct v4l2_fmtdesc fdesc;
513     uint32_t v4l2_fmt;
514     int ret;
515
516     /* translate to a valid v4l2 format */
517     v4l2_fmt = ff_v4l2_format_avcodec_to_v4l2(ctx->av_codec_id);
518     if (!v4l2_fmt)
519         return AVERROR(EINVAL);
520
521     /* check if the driver supports this format */
522     memset(&fdesc, 0, sizeof(fdesc));
523     fdesc.type = ctx->type;
524
525     for (;;) {
526         ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_ENUM_FMT, &fdesc);
527         if (ret)
528             return AVERROR(EINVAL);
529
530         if (fdesc.pixelformat == v4l2_fmt)
531             break;
532
533         fdesc.index++;
534     }
535
536     *p = v4l2_fmt;
537
538     return 0;
539 }
540
541  /*****************************************************************************
542   *
543   *             V4L2 Context Interface
544   *
545   *****************************************************************************/
546
547 int ff_v4l2_context_set_status(V4L2Context* ctx, uint32_t cmd)
548 {
549     int type = ctx->type;
550     int ret;
551
552     ret = ioctl(ctx_to_m2mctx(ctx)->fd, cmd, &type);
553     if (ret < 0)
554         return AVERROR(errno);
555
556     ctx->streamon = (cmd == VIDIOC_STREAMON);
557
558     return 0;
559 }
560
561 int ff_v4l2_context_enqueue_frame(V4L2Context* ctx, const AVFrame* frame)
562 {
563     V4L2m2mContext *s = ctx_to_m2mctx(ctx);
564     V4L2Buffer* avbuf;
565     int ret;
566
567     if (!frame) {
568         ret = v4l2_stop_encode(ctx);
569         if (ret)
570             av_log(logger(ctx), AV_LOG_ERROR, "%s stop_encode\n", ctx->name);
571         s->draining= 1;
572         return 0;
573     }
574
575     avbuf = v4l2_getfree_v4l2buf(ctx);
576     if (!avbuf)
577         return AVERROR(ENOMEM);
578
579     ret = ff_v4l2_buffer_avframe_to_buf(frame, avbuf);
580     if (ret)
581         return ret;
582
583     return ff_v4l2_buffer_enqueue(avbuf);
584 }
585
586 int ff_v4l2_context_enqueue_packet(V4L2Context* ctx, const AVPacket* pkt)
587 {
588     V4L2m2mContext *s = ctx_to_m2mctx(ctx);
589     V4L2Buffer* avbuf;
590     int ret;
591
592     if (!pkt->size) {
593         ret = v4l2_stop_decode(ctx);
594         if (ret)
595             av_log(logger(ctx), AV_LOG_ERROR, "%s stop_decode\n", ctx->name);
596         s->draining = 1;
597         return 0;
598     }
599
600     avbuf = v4l2_getfree_v4l2buf(ctx);
601     if (!avbuf)
602         return AVERROR(EAGAIN);
603
604     ret = ff_v4l2_buffer_avpkt_to_buf(pkt, avbuf);
605     if (ret)
606         return ret;
607
608     return ff_v4l2_buffer_enqueue(avbuf);
609 }
610
611 int ff_v4l2_context_dequeue_frame(V4L2Context* ctx, AVFrame* frame, int timeout)
612 {
613     V4L2Buffer *avbuf;
614
615     /*
616      * timeout=-1 blocks until:
617      *  1. decoded frame available
618      *  2. an input buffer is ready to be dequeued
619      */
620     avbuf = v4l2_dequeue_v4l2buf(ctx, timeout);
621     if (!avbuf) {
622         if (ctx->done)
623             return AVERROR_EOF;
624
625         return AVERROR(EAGAIN);
626     }
627
628     return ff_v4l2_buffer_buf_to_avframe(frame, avbuf);
629 }
630
631 int ff_v4l2_context_dequeue_packet(V4L2Context* ctx, AVPacket* pkt)
632 {
633     V4L2Buffer *avbuf;
634
635     /*
636      * blocks until:
637      *  1. encoded packet available
638      *  2. an input buffer ready to be dequeued
639      */
640     avbuf = v4l2_dequeue_v4l2buf(ctx, -1);
641     if (!avbuf) {
642         if (ctx->done)
643             return AVERROR_EOF;
644
645         return AVERROR(EAGAIN);
646     }
647
648     return ff_v4l2_buffer_buf_to_avpkt(pkt, avbuf);
649 }
650
651 int ff_v4l2_context_get_format(V4L2Context* ctx, int probe)
652 {
653     struct v4l2_format_update fmt = { 0 };
654     int ret;
655
656     if  (ctx->av_codec_id == AV_CODEC_ID_RAWVIDEO) {
657         ret = v4l2_get_raw_format(ctx, &fmt.av_fmt);
658         if (ret)
659             return ret;
660
661         fmt.update_avfmt = !probe;
662         v4l2_save_to_context(ctx, &fmt);
663
664         /* format has been tried already */
665         return ret;
666     }
667
668     ret = v4l2_get_coded_format(ctx, &fmt.v4l2_fmt);
669     if (ret)
670         return ret;
671
672     fmt.update_v4l2 = 1;
673     v4l2_save_to_context(ctx, &fmt);
674
675     return ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_TRY_FMT, &ctx->format);
676 }
677
678 int ff_v4l2_context_set_format(V4L2Context* ctx)
679 {
680     return ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_S_FMT, &ctx->format);
681 }
682
683 void ff_v4l2_context_release(V4L2Context* ctx)
684 {
685     int ret;
686
687     if (!ctx->buffers)
688         return;
689
690     ret = v4l2_release_buffers(ctx);
691     if (ret)
692         av_log(logger(ctx), AV_LOG_WARNING, "V4L2 failed to unmap the %s buffers\n", ctx->name);
693
694     av_freep(&ctx->buffers);
695 }
696
697 int ff_v4l2_context_init(V4L2Context* ctx)
698 {
699     V4L2m2mContext *s = ctx_to_m2mctx(ctx);
700     struct v4l2_requestbuffers req;
701     int ret, i;
702
703     if (!v4l2_type_supported(ctx)) {
704         av_log(logger(ctx), AV_LOG_ERROR, "type %i not supported\n", ctx->type);
705         return AVERROR_PATCHWELCOME;
706     }
707
708     ret = ioctl(s->fd, VIDIOC_G_FMT, &ctx->format);
709     if (ret)
710         av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_G_FMT failed\n", ctx->name);
711
712     memset(&req, 0, sizeof(req));
713     req.count = ctx->num_buffers;
714     req.memory = V4L2_MEMORY_MMAP;
715     req.type = ctx->type;
716     ret = ioctl(s->fd, VIDIOC_REQBUFS, &req);
717     if (ret < 0) {
718         av_log(logger(ctx), AV_LOG_ERROR, "%s VIDIOC_REQBUFS failed: %s\n", ctx->name, strerror(errno));
719         return AVERROR(errno);
720     }
721
722     ctx->num_buffers = req.count;
723     ctx->buffers = av_mallocz(ctx->num_buffers * sizeof(V4L2Buffer));
724     if (!ctx->buffers) {
725         av_log(logger(ctx), AV_LOG_ERROR, "%s malloc enomem\n", ctx->name);
726         return AVERROR(ENOMEM);
727     }
728
729     for (i = 0; i < req.count; i++) {
730         ctx->buffers[i].context = ctx;
731         ret = ff_v4l2_buffer_initialize(&ctx->buffers[i], i);
732         if (ret < 0) {
733             av_log(logger(ctx), AV_LOG_ERROR, "%s buffer[%d] initialization (%s)\n", ctx->name, i, av_err2str(ret));
734             goto error;
735         }
736     }
737
738     av_log(logger(ctx), AV_LOG_DEBUG, "%s: %s %02d buffers initialized: %04ux%04u, sizeimage %08u, bytesperline %08u\n", ctx->name,
739         V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ? av_fourcc2str(ctx->format.fmt.pix_mp.pixelformat) : av_fourcc2str(ctx->format.fmt.pix.pixelformat),
740         req.count,
741         v4l2_get_width(&ctx->format),
742         v4l2_get_height(&ctx->format),
743         V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ? ctx->format.fmt.pix_mp.plane_fmt[0].sizeimage : ctx->format.fmt.pix.sizeimage,
744         V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ? ctx->format.fmt.pix_mp.plane_fmt[0].bytesperline : ctx->format.fmt.pix.bytesperline);
745
746     return 0;
747
748 error:
749     v4l2_release_buffers(ctx);
750
751     av_freep(&ctx->buffers);
752
753     return ret;
754 }