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