]> git.sesse.net Git - ffmpeg/blob - libavcodec/mmaldec.c
mmal: Fix AVBufferRef usage
[ffmpeg] / libavcodec / mmaldec.c
1 /*
2  * MMAL Video Decoder
3  * Copyright (c) 2015 Rodger Combs
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * MMAL Video Decoder
25  */
26
27 #include <bcm_host.h>
28 #include <interface/mmal/mmal.h>
29 #include <interface/mmal/mmal_parameters_video.h>
30 #include <interface/mmal/util/mmal_util.h>
31 #include <interface/mmal/util/mmal_util_params.h>
32 #include <interface/mmal/util/mmal_default_components.h>
33 #include <interface/mmal/vc/mmal_vc_api.h>
34
35 #include "avcodec.h"
36 #include "internal.h"
37 #include "libavutil/atomic.h"
38 #include "libavutil/avassert.h"
39 #include "libavutil/buffer.h"
40 #include "libavutil/common.h"
41 #include "libavutil/opt.h"
42 #include "libavutil/log.h"
43
44 typedef struct FFBufferEntry {
45     AVBufferRef *ref;
46     void *data;
47     size_t length;
48     int64_t pts, dts;
49     int flags;
50     struct FFBufferEntry *next;
51 } FFBufferEntry;
52
53 // MMAL_POOL_T destroys all of its MMAL_BUFFER_HEADER_Ts. If we want correct
54 // refcounting for AVFrames, we can free the MMAL_POOL_T only after all AVFrames
55 // have been unreferenced.
56 typedef struct FFPoolRef {
57     volatile int refcount;
58     MMAL_POOL_T *pool;
59 } FFPoolRef;
60
61 typedef struct FFBufferRef {
62     MMAL_BUFFER_HEADER_T *buffer;
63     FFPoolRef *pool;
64 } FFBufferRef;
65
66 typedef struct MMALDecodeContext {
67     AVClass *av_class;
68     int extra_buffers;
69
70     MMAL_COMPONENT_T *decoder;
71     MMAL_QUEUE_T *queue_decoded_frames;
72     MMAL_POOL_T *pool_in;
73     FFPoolRef *pool_out;
74
75     // Waiting input packets. Because the libavcodec API requires decoding and
76     // returning packets in lockstep, it can happen that queue_decoded_frames
77     // contains almost all surfaces - then the decoder input queue can quickly
78     // fill up and won't accept new input either. Without consuming input, the
79     // libavcodec API can't return new frames, and we have a logical deadlock.
80     // This is avoided by queuing such buffers here.
81     FFBufferEntry *waiting_buffers, *waiting_buffers_tail;
82
83     int64_t packets_sent;
84     int64_t frames_output;
85     int eos_received;
86     int eos_sent;
87     int extradata_sent;
88 } MMALDecodeContext;
89
90 // Assume decoder is guaranteed to produce output after at least this many
91 // packets (where each packet contains 1 frame).
92 #define MAX_DELAYED_FRAMES 16
93
94 static void ffmmal_poolref_unref(FFPoolRef *ref)
95 {
96     if (ref && avpriv_atomic_int_add_and_fetch(&ref->refcount, -1) == 0) {
97         mmal_pool_destroy(ref->pool);
98         av_free(ref);
99     }
100 }
101
102 static void ffmmal_release_frame(void *opaque, uint8_t *data)
103 {
104     FFBufferRef *ref = (void *)data;
105
106     mmal_buffer_header_release(ref->buffer);
107     ffmmal_poolref_unref(ref->pool);
108
109     av_free(ref);
110 }
111
112 // Setup frame with a new reference to buffer. The buffer must have been
113 // allocated from the given pool.
114 static int ffmmal_set_ref(AVFrame *frame, FFPoolRef *pool,
115                           MMAL_BUFFER_HEADER_T *buffer)
116 {
117     FFBufferRef *ref = av_mallocz(sizeof(*ref));
118     if (!ref)
119         return AVERROR(ENOMEM);
120
121     ref->pool = pool;
122     ref->buffer = buffer;
123
124     frame->buf[0] = av_buffer_create((void *)ref, sizeof(*ref),
125                                      ffmmal_release_frame, NULL,
126                                      AV_BUFFER_FLAG_READONLY);
127     if (!frame->buf[0]) {
128         av_free(ref);
129         return AVERROR(ENOMEM);
130     }
131
132     avpriv_atomic_int_add_and_fetch(&ref->pool->refcount, 1);
133     mmal_buffer_header_acquire(buffer);
134
135     frame->format = AV_PIX_FMT_MMAL;
136     frame->data[3] = (uint8_t *)ref->buffer;
137     return 0;
138 }
139
140 static void ffmmal_stop_decoder(AVCodecContext *avctx)
141 {
142     MMALDecodeContext *ctx = avctx->priv_data;
143     MMAL_COMPONENT_T *decoder = ctx->decoder;
144     MMAL_BUFFER_HEADER_T *buffer;
145
146     mmal_port_disable(decoder->input[0]);
147     mmal_port_disable(decoder->output[0]);
148     mmal_port_disable(decoder->control);
149
150     mmal_port_flush(decoder->input[0]);
151     mmal_port_flush(decoder->output[0]);
152     mmal_port_flush(decoder->control);
153
154     while ((buffer = mmal_queue_get(ctx->queue_decoded_frames)))
155         mmal_buffer_header_release(buffer);
156
157     while (ctx->waiting_buffers) {
158         FFBufferEntry *buffer = ctx->waiting_buffers;
159
160         ctx->waiting_buffers = buffer->next;
161
162         av_buffer_unref(&buffer->ref);
163         av_free(buffer);
164     }
165     ctx->waiting_buffers_tail = NULL;
166
167     ctx->frames_output = ctx->eos_received = ctx->eos_sent = ctx->packets_sent = ctx->extradata_sent = 0;
168 }
169
170 static av_cold int ffmmal_close_decoder(AVCodecContext *avctx)
171 {
172     MMALDecodeContext *ctx = avctx->priv_data;
173
174     if (ctx->decoder)
175         ffmmal_stop_decoder(avctx);
176
177     mmal_component_destroy(ctx->decoder);
178     ctx->decoder = NULL;
179     mmal_queue_destroy(ctx->queue_decoded_frames);
180     mmal_pool_destroy(ctx->pool_in);
181     ffmmal_poolref_unref(ctx->pool_out);
182
183     mmal_vc_deinit();
184
185     return 0;
186 }
187
188 static void input_callback(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer)
189 {
190     if (!buffer->cmd) {
191         AVBufferRef *buf = buffer->user_data;
192         av_buffer_unref(&buf);
193     }
194     mmal_buffer_header_release(buffer);
195 }
196
197 static void output_callback(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer)
198 {
199     AVCodecContext *avctx = (AVCodecContext*)port->userdata;
200     MMALDecodeContext *ctx = avctx->priv_data;
201
202     mmal_queue_put(ctx->queue_decoded_frames, buffer);
203 }
204
205 static void control_port_cb(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer)
206 {
207     AVCodecContext *avctx = (AVCodecContext*)port->userdata;
208     MMAL_STATUS_T status;
209
210     if (buffer->cmd == MMAL_EVENT_ERROR) {
211         status = *(uint32_t *)buffer->data;
212         av_log(avctx, AV_LOG_ERROR, "MMAL error %d on control port\n", (int)status);
213     } else {
214         char s[20];
215         av_get_codec_tag_string(s, sizeof(s), buffer->cmd);
216         av_log(avctx, AV_LOG_WARNING, "Unknown MMAL event %s on control port\n", s);
217     }
218
219     mmal_buffer_header_release(buffer);
220 }
221
222 // Feed free output buffers to the decoder.
223 static int ffmmal_fill_output_port(AVCodecContext *avctx)
224 {
225     MMALDecodeContext *ctx = avctx->priv_data;
226     MMAL_BUFFER_HEADER_T *buffer;
227     MMAL_STATUS_T status;
228
229     if (!ctx->pool_out)
230         return AVERROR_UNKNOWN; // format change code failed with OOM previously
231
232     while ((buffer = mmal_queue_get(ctx->pool_out->pool->queue))) {
233         if ((status = mmal_port_send_buffer(ctx->decoder->output[0], buffer))) {
234             mmal_buffer_header_release(buffer);
235             av_log(avctx, AV_LOG_ERROR, "MMAL error %d when sending output buffer.\n", (int)status);
236             return AVERROR_UNKNOWN;
237         }
238     }
239
240     return 0;
241 }
242
243 static enum AVColorSpace ffmmal_csp_to_av_csp(MMAL_FOURCC_T fourcc)
244 {
245     switch (fourcc) {
246     case MMAL_COLOR_SPACE_BT470_2_BG:
247     case MMAL_COLOR_SPACE_BT470_2_M:
248     case MMAL_COLOR_SPACE_ITUR_BT601:   return AVCOL_SPC_BT470BG;
249     case MMAL_COLOR_SPACE_ITUR_BT709:   return AVCOL_SPC_BT709;
250     case MMAL_COLOR_SPACE_FCC:          return AVCOL_SPC_FCC;
251     case MMAL_COLOR_SPACE_SMPTE240M:    return AVCOL_SPC_SMPTE240M;
252     default:                            return AVCOL_SPC_UNSPECIFIED;
253     }
254 }
255
256 static int ffmal_update_format(AVCodecContext *avctx)
257 {
258     MMALDecodeContext *ctx = avctx->priv_data;
259     MMAL_STATUS_T status;
260     int ret = 0;
261     MMAL_COMPONENT_T *decoder = ctx->decoder;
262     MMAL_ES_FORMAT_T *format_out = decoder->output[0]->format;
263
264     ffmmal_poolref_unref(ctx->pool_out);
265     if (!(ctx->pool_out = av_mallocz(sizeof(*ctx->pool_out)))) {
266         ret = AVERROR(ENOMEM);
267         goto fail;
268     }
269     ctx->pool_out->refcount = 1;
270
271     if (!format_out)
272         goto fail;
273
274     if ((status = mmal_port_parameter_set_uint32(decoder->output[0], MMAL_PARAMETER_EXTRA_BUFFERS, ctx->extra_buffers)))
275         goto fail;
276
277     if ((status = mmal_port_parameter_set_boolean(decoder->output[0], MMAL_PARAMETER_VIDEO_INTERPOLATE_TIMESTAMPS, 0)))
278         goto fail;
279
280     if (avctx->pix_fmt == AV_PIX_FMT_MMAL) {
281         format_out->encoding = MMAL_ENCODING_OPAQUE;
282     } else {
283         format_out->encoding_variant = format_out->encoding = MMAL_ENCODING_I420;
284     }
285
286     if ((status = mmal_port_format_commit(decoder->output[0])))
287         goto fail;
288
289     if ((ret = ff_set_dimensions(avctx, format_out->es->video.crop.x + format_out->es->video.crop.width,
290                                         format_out->es->video.crop.y + format_out->es->video.crop.height)) < 0)
291         goto fail;
292
293     if (format_out->es->video.par.num && format_out->es->video.par.den) {
294         avctx->sample_aspect_ratio.num = format_out->es->video.par.num;
295         avctx->sample_aspect_ratio.den = format_out->es->video.par.den;
296     }
297
298     avctx->colorspace = ffmmal_csp_to_av_csp(format_out->es->video.color_space);
299
300     decoder->output[0]->buffer_size =
301         FFMAX(decoder->output[0]->buffer_size_min, decoder->output[0]->buffer_size_recommended);
302     decoder->output[0]->buffer_num =
303         FFMAX(decoder->output[0]->buffer_num_min, decoder->output[0]->buffer_num_recommended) + ctx->extra_buffers;
304     ctx->pool_out->pool = mmal_pool_create(decoder->output[0]->buffer_num,
305                                            decoder->output[0]->buffer_size);
306     if (!ctx->pool_out->pool) {
307         ret = AVERROR(ENOMEM);
308         goto fail;
309     }
310
311     return 0;
312
313 fail:
314     return ret < 0 ? ret : AVERROR_UNKNOWN;
315 }
316
317 static av_cold int ffmmal_init_decoder(AVCodecContext *avctx)
318 {
319     MMALDecodeContext *ctx = avctx->priv_data;
320     MMAL_STATUS_T status;
321     MMAL_ES_FORMAT_T *format_in;
322     MMAL_COMPONENT_T *decoder;
323     int ret = 0;
324
325     bcm_host_init();
326
327     if (mmal_vc_init()) {
328         av_log(avctx, AV_LOG_ERROR, "Cannot initialize MMAL VC driver!\n");
329         return AVERROR(ENOSYS);
330     }
331
332     if ((ret = ff_get_format(avctx, avctx->codec->pix_fmts)) < 0)
333         return ret;
334
335     avctx->pix_fmt = ret;
336
337     if ((status = mmal_component_create(MMAL_COMPONENT_DEFAULT_VIDEO_DECODER, &ctx->decoder)))
338         goto fail;
339
340     decoder = ctx->decoder;
341
342     format_in = decoder->input[0]->format;
343     format_in->type = MMAL_ES_TYPE_VIDEO;
344     format_in->encoding = MMAL_ENCODING_H264;
345     format_in->es->video.width = FFALIGN(avctx->width, 32);
346     format_in->es->video.height = FFALIGN(avctx->height, 16);
347     format_in->es->video.crop.width = avctx->width;
348     format_in->es->video.crop.height = avctx->height;
349     format_in->es->video.frame_rate.num = 24000;
350     format_in->es->video.frame_rate.den = 1001;
351     format_in->es->video.par.num = avctx->sample_aspect_ratio.num;
352     format_in->es->video.par.den = avctx->sample_aspect_ratio.den;
353     format_in->flags = MMAL_ES_FORMAT_FLAG_FRAMED;
354
355     if ((status = mmal_port_format_commit(decoder->input[0])))
356         goto fail;
357
358     decoder->input[0]->buffer_num =
359         FFMAX(decoder->input[0]->buffer_num_min, 20);
360     decoder->input[0]->buffer_size =
361         FFMAX(decoder->input[0]->buffer_size_min, 512 * 1024);
362     ctx->pool_in = mmal_pool_create(decoder->input[0]->buffer_num, 0);
363     if (!ctx->pool_in) {
364         ret = AVERROR(ENOMEM);
365         goto fail;
366     }
367
368     if ((ret = ffmal_update_format(avctx)) < 0)
369         goto fail;
370
371     ctx->queue_decoded_frames = mmal_queue_create();
372     if (!ctx->queue_decoded_frames)
373         goto fail;
374
375     decoder->input[0]->userdata = (void*)avctx;
376     decoder->output[0]->userdata = (void*)avctx;
377     decoder->control->userdata = (void*)avctx;
378
379     if ((status = mmal_port_enable(decoder->control, control_port_cb)))
380         goto fail;
381     if ((status = mmal_port_enable(decoder->input[0], input_callback)))
382         goto fail;
383     if ((status = mmal_port_enable(decoder->output[0], output_callback)))
384         goto fail;
385
386     if ((status = mmal_component_enable(decoder)))
387         goto fail;
388
389     return 0;
390
391 fail:
392     ffmmal_close_decoder(avctx);
393     return ret < 0 ? ret : AVERROR_UNKNOWN;
394 }
395
396 static void ffmmal_flush(AVCodecContext *avctx)
397 {
398     MMALDecodeContext *ctx = avctx->priv_data;
399     MMAL_COMPONENT_T *decoder = ctx->decoder;
400     MMAL_STATUS_T status;
401
402     ffmmal_stop_decoder(avctx);
403
404     if ((status = mmal_port_enable(decoder->control, control_port_cb)))
405         goto fail;
406     if ((status = mmal_port_enable(decoder->input[0], input_callback)))
407         goto fail;
408     if ((status = mmal_port_enable(decoder->output[0], output_callback)))
409         goto fail;
410
411     return;
412
413 fail:
414     av_log(avctx, AV_LOG_ERROR, "MMAL flush error: %i\n", (int)status);
415 }
416
417 // Split packets and add them to the waiting_buffers list. We don't queue them
418 // immediately, because it can happen that the decoder is temporarily blocked
419 // (due to us not reading/returning enough output buffers) and won't accept
420 // new input. (This wouldn't be an issue if MMAL input buffers always were
421 // complete frames - then the input buffer just would have to be big enough.)
422 // If is_extradata is set, send it as MMAL_BUFFER_HEADER_FLAG_CONFIG.
423 static int ffmmal_add_packet(AVCodecContext *avctx, AVPacket *avpkt,
424                              int is_extradata)
425 {
426     MMALDecodeContext *ctx = avctx->priv_data;
427     AVBufferRef *buf = NULL;
428     int size = 0;
429     uint8_t *data = (uint8_t *)"";
430     uint8_t *start;
431     int ret = 0;
432
433     if (avpkt->size) {
434         if (avpkt->buf) {
435             buf = av_buffer_ref(avpkt->buf);
436             size = avpkt->size;
437             data = avpkt->data;
438         } else {
439             buf = av_buffer_alloc(avpkt->size);
440             if (buf) {
441                 memcpy(buf->data, avpkt->data, avpkt->size);
442                 size = buf->size;
443                 data = buf->data;
444             }
445         }
446         if (!buf) {
447             ret = AVERROR(ENOMEM);
448             goto done;
449         }
450         if (!is_extradata)
451             ctx->packets_sent++;
452     } else {
453         if (!ctx->packets_sent) {
454             // Short-cut the flush logic to avoid upsetting MMAL.
455             ctx->eos_sent = 1;
456             ctx->eos_received = 1;
457             goto done;
458         }
459     }
460
461     start = data;
462
463     do {
464         FFBufferEntry *buffer = av_mallocz(sizeof(*buffer));
465         if (!buffer) {
466             ret = AVERROR(ENOMEM);
467             goto done;
468         }
469
470         buffer->data = data;
471         buffer->length = FFMIN(size, ctx->decoder->input[0]->buffer_size);
472
473         if (is_extradata)
474             buffer->flags |= MMAL_BUFFER_HEADER_FLAG_CONFIG;
475
476         if (data == start)
477             buffer->flags |= MMAL_BUFFER_HEADER_FLAG_FRAME_START;
478
479         data += buffer->length;
480         size -= buffer->length;
481
482         buffer->pts = avpkt->pts == AV_NOPTS_VALUE ? MMAL_TIME_UNKNOWN : avpkt->pts;
483         buffer->dts = avpkt->dts == AV_NOPTS_VALUE ? MMAL_TIME_UNKNOWN : avpkt->dts;
484
485         if (!size)
486             buffer->flags |= MMAL_BUFFER_HEADER_FLAG_FRAME_END;
487
488         if (!buffer->length) {
489             buffer->flags |= MMAL_BUFFER_HEADER_FLAG_EOS;
490             ctx->eos_sent = 1;
491         }
492
493         if (buf) {
494             buffer->ref = av_buffer_ref(buf);
495             if (!buffer->ref) {
496                 av_free(buffer);
497                 ret = AVERROR(ENOMEM);
498                 goto done;
499             }
500         }
501
502         // Insert at end of the list
503         if (!ctx->waiting_buffers)
504             ctx->waiting_buffers = buffer;
505         if (ctx->waiting_buffers_tail)
506             ctx->waiting_buffers_tail->next = buffer;
507         ctx->waiting_buffers_tail = buffer;
508     } while (size);
509
510 done:
511     av_buffer_unref(&buf);
512     return ret;
513 }
514
515 // Move prepared/split packets from waiting_buffers to the MMAL decoder.
516 static int ffmmal_fill_input_port(AVCodecContext *avctx)
517 {
518     MMALDecodeContext *ctx = avctx->priv_data;
519
520     while (ctx->waiting_buffers) {
521         MMAL_BUFFER_HEADER_T *mbuffer;
522         FFBufferEntry *buffer;
523         MMAL_STATUS_T status;
524
525         mbuffer = mmal_queue_get(ctx->pool_in->queue);
526         if (!mbuffer)
527             return 0;
528
529         buffer = ctx->waiting_buffers;
530
531         mmal_buffer_header_reset(mbuffer);
532         mbuffer->cmd = 0;
533         mbuffer->pts = buffer->pts;
534         mbuffer->dts = buffer->dts;
535         mbuffer->flags = buffer->flags;
536         mbuffer->data = buffer->data;
537         mbuffer->length = buffer->length;
538         mbuffer->user_data = buffer->ref;
539         mbuffer->alloc_size = ctx->decoder->input[0]->buffer_size;
540
541         if ((status = mmal_port_send_buffer(ctx->decoder->input[0], mbuffer))) {
542             mmal_buffer_header_release(mbuffer);
543             av_buffer_unref(&buffer->ref);
544         }
545
546         // Remove from start of the list
547         ctx->waiting_buffers = buffer->next;
548         if (ctx->waiting_buffers_tail == buffer)
549             ctx->waiting_buffers_tail = NULL;
550         av_free(buffer);
551
552         if (status) {
553             av_log(avctx, AV_LOG_ERROR, "MMAL error %d when sending input\n", (int)status);
554             return AVERROR_UNKNOWN;
555         }
556     }
557
558     return 0;
559 }
560
561 static int ffmal_copy_frame(AVCodecContext *avctx,  AVFrame *frame,
562                             MMAL_BUFFER_HEADER_T *buffer)
563 {
564     MMALDecodeContext *ctx = avctx->priv_data;
565     int ret = 0;
566
567     if (avctx->pix_fmt == AV_PIX_FMT_MMAL) {
568         if (!ctx->pool_out)
569             return AVERROR_UNKNOWN; // format change code failed with OOM previously
570
571         if ((ret = ff_decode_frame_props(avctx, frame)) < 0)
572             goto done;
573
574         if ((ret = ffmmal_set_ref(frame, ctx->pool_out, buffer)) < 0)
575             goto done;
576     } else {
577         int w = FFALIGN(avctx->width, 32);
578         int h = FFALIGN(avctx->height, 16);
579         char *ptr;
580         int plane;
581         int i;
582
583         if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
584             goto done;
585
586         ptr = buffer->data + buffer->type->video.offset[0];
587         for (i = 0; i < avctx->height; i++)
588             memcpy(frame->data[0] + frame->linesize[0] * i, ptr + w * i, avctx->width);
589
590         ptr += w * h;
591
592         for (plane = 1; plane < 3; plane++) {
593             for (i = 0; i < avctx->height / 2; i++)
594                 memcpy(frame->data[plane] + frame->linesize[plane] * i, ptr + w / 2 * i, (avctx->width + 1) / 2);
595             ptr += w / 2 * h / 2;
596         }
597     }
598
599     frame->pkt_pts = buffer->pts == MMAL_TIME_UNKNOWN ? AV_NOPTS_VALUE : buffer->pts;
600     frame->pkt_dts = AV_NOPTS_VALUE;
601
602 done:
603     return ret;
604 }
605
606 // Fetch a decoded buffer and place it into the frame parameter.
607 static int ffmmal_read_frame(AVCodecContext *avctx, AVFrame *frame, int *got_frame)
608 {
609     MMALDecodeContext *ctx = avctx->priv_data;
610     MMAL_BUFFER_HEADER_T *buffer = NULL;
611     MMAL_STATUS_T status = 0;
612     int ret = 0;
613
614     if (ctx->eos_received)
615         goto done;
616
617     while (1) {
618         // To ensure decoding in lockstep with a constant delay between fed packets
619         // and output frames, we always wait until an output buffer is available.
620         // Except during start we don't know after how many input packets the decoder
621         // is going to return the first buffer, and we can't distinguish decoder
622         // being busy from decoder waiting for input. So just poll at the start and
623         // keep feeding new data to the buffer.
624         // We are pretty sure the decoder will produce output if we sent more input
625         // frames than what a h264 decoder could logically delay. This avoids too
626         // excessive buffering.
627         // We also wait if we sent eos, but didn't receive it yet (think of decoding
628         // stream with a very low number of frames).
629         if (ctx->frames_output || ctx->packets_sent > MAX_DELAYED_FRAMES ||
630             (ctx->packets_sent && ctx->eos_sent)) {
631             // MMAL will ignore broken input packets, which means the frame we
632             // expect here may never arrive. Dealing with this correctly is
633             // complicated, so here's a hack to avoid that it freezes forever
634             // in this unlikely situation.
635             buffer = mmal_queue_timedwait(ctx->queue_decoded_frames, 100);
636             if (!buffer) {
637                 av_log(avctx, AV_LOG_ERROR, "Did not get output frame from MMAL.\n");
638                 ret = AVERROR_UNKNOWN;
639                 goto done;
640             }
641         } else {
642             buffer = mmal_queue_get(ctx->queue_decoded_frames);
643             if (!buffer)
644                 goto done;
645         }
646
647         ctx->eos_received |= !!(buffer->flags & MMAL_BUFFER_HEADER_FLAG_EOS);
648         if (ctx->eos_received)
649             goto done;
650
651         if (buffer->cmd == MMAL_EVENT_FORMAT_CHANGED) {
652             MMAL_COMPONENT_T *decoder = ctx->decoder;
653             MMAL_EVENT_FORMAT_CHANGED_T *ev = mmal_event_format_changed_get(buffer);
654             MMAL_BUFFER_HEADER_T *stale_buffer;
655
656             av_log(avctx, AV_LOG_INFO, "Changing output format.\n");
657
658             if ((status = mmal_port_disable(decoder->output[0])))
659                 goto done;
660
661             while ((stale_buffer = mmal_queue_get(ctx->queue_decoded_frames)))
662                 mmal_buffer_header_release(stale_buffer);
663
664             mmal_format_copy(decoder->output[0]->format, ev->format);
665
666             if ((ret = ffmal_update_format(avctx)) < 0)
667                 goto done;
668
669             if ((status = mmal_port_enable(decoder->output[0], output_callback)))
670                 goto done;
671
672             if ((ret = ffmmal_fill_output_port(avctx)) < 0)
673                 goto done;
674
675             if ((ret = ffmmal_fill_input_port(avctx)) < 0)
676                 goto done;
677
678             mmal_buffer_header_release(buffer);
679             continue;
680         } else if (buffer->cmd) {
681             char s[20];
682             av_get_codec_tag_string(s, sizeof(s), buffer->cmd);
683             av_log(avctx, AV_LOG_WARNING, "Unknown MMAL event %s on output port\n", s);
684             goto done;
685         } else if (buffer->length == 0) {
686             // Unused output buffer that got drained after format change.
687             mmal_buffer_header_release(buffer);
688             continue;
689         }
690
691         ctx->frames_output++;
692
693         if ((ret = ffmal_copy_frame(avctx, frame, buffer)) < 0)
694             goto done;
695
696         *got_frame = 1;
697         break;
698     }
699
700 done:
701     if (buffer)
702         mmal_buffer_header_release(buffer);
703     if (status && ret >= 0)
704         ret = AVERROR_UNKNOWN;
705     return ret;
706 }
707
708 static int ffmmal_decode(AVCodecContext *avctx, void *data, int *got_frame,
709                          AVPacket *avpkt)
710 {
711     MMALDecodeContext *ctx = avctx->priv_data;
712     AVFrame *frame = data;
713     int ret = 0;
714
715     if (avctx->extradata_size && !ctx->extradata_sent) {
716         AVPacket pkt = {0};
717         av_init_packet(&pkt);
718         pkt.data = avctx->extradata;
719         pkt.size = avctx->extradata_size;
720         ctx->extradata_sent = 1;
721         if ((ret = ffmmal_add_packet(avctx, &pkt, 1)) < 0)
722             return ret;
723     }
724
725     if ((ret = ffmmal_add_packet(avctx, avpkt, 0)) < 0)
726         return ret;
727
728     if ((ret = ffmmal_fill_input_port(avctx)) < 0)
729         return ret;
730
731     if ((ret = ffmmal_fill_output_port(avctx)) < 0)
732         return ret;
733
734     if ((ret = ffmmal_read_frame(avctx, frame, got_frame)) < 0)
735         return ret;
736
737     // ffmmal_read_frame() can block for a while. Since the decoder is
738     // asynchronous, it's a good idea to fill the ports again.
739
740     if ((ret = ffmmal_fill_output_port(avctx)) < 0)
741         return ret;
742
743     if ((ret = ffmmal_fill_input_port(avctx)) < 0)
744         return ret;
745
746     return ret;
747 }
748
749 AVHWAccel ff_h264_mmal_hwaccel = {
750     .name       = "h264_mmal",
751     .type       = AVMEDIA_TYPE_VIDEO,
752     .id         = AV_CODEC_ID_H264,
753     .pix_fmt    = AV_PIX_FMT_MMAL,
754 };
755
756 static const AVOption options[]={
757     {"extra_buffers", "extra buffers", offsetof(MMALDecodeContext, extra_buffers), AV_OPT_TYPE_INT, {.i64 = 10}, 0, 256, 0},
758     {NULL}
759 };
760
761 static const AVClass ffmmaldec_class = {
762     .class_name = "mmaldec",
763     .option     = options,
764     .version    = LIBAVUTIL_VERSION_INT,
765 };
766
767 AVCodec ff_h264_mmal_decoder = {
768     .name           = "h264_mmal",
769     .long_name      = NULL_IF_CONFIG_SMALL("h264 (mmal)"),
770     .type           = AVMEDIA_TYPE_VIDEO,
771     .id             = AV_CODEC_ID_H264,
772     .priv_data_size = sizeof(MMALDecodeContext),
773     .init           = ffmmal_init_decoder,
774     .close          = ffmmal_close_decoder,
775     .decode         = ffmmal_decode,
776     .flush          = ffmmal_flush,
777     .priv_class     = &ffmmaldec_class,
778     .capabilities   = AV_CODEC_CAP_DELAY,
779     .caps_internal  = FF_CODEC_CAP_SETS_PKT_DTS,
780     .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_MMAL,
781                                                      AV_PIX_FMT_YUV420P,
782                                                      AV_PIX_FMT_NONE},
783 };