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