]> git.sesse.net Git - ffmpeg/blob - libavcodec/mmaldec.c
Merge commit '99404597201911de90cff2ef85f2d44176d39147'
[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/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, "private_spspps_buf", &dummy_p, &dummy_int, NULL, 0, 0);
369     } else if (avctx->extradata_size) {
370         if ((status = mmal_format_extradata_alloc(format_in, avctx->extradata_size)))
371             goto fail;
372         format_in->extradata_size = avctx->extradata_size;
373         memcpy(format_in->extradata, avctx->extradata, format_in->extradata_size);
374     }
375
376     if ((status = mmal_port_format_commit(decoder->input[0])))
377         goto fail;
378
379     decoder->input[0]->buffer_num =
380         FFMAX(decoder->input[0]->buffer_num_min, 20);
381     decoder->input[0]->buffer_size =
382         FFMAX(decoder->input[0]->buffer_size_min, 512 * 1024);
383     ctx->pool_in = mmal_pool_create(decoder->input[0]->buffer_num, 0);
384     if (!ctx->pool_in) {
385         ret = AVERROR(ENOMEM);
386         goto fail;
387     }
388
389     if ((ret = ffmal_update_format(avctx)) < 0)
390         goto fail;
391
392     ctx->queue_decoded_frames = mmal_queue_create();
393     if (!ctx->queue_decoded_frames)
394         goto fail;
395
396     decoder->input[0]->userdata = (void*)avctx;
397     decoder->output[0]->userdata = (void*)avctx;
398     decoder->control->userdata = (void*)avctx;
399
400     if ((status = mmal_port_enable(decoder->control, control_port_cb)))
401         goto fail;
402     if ((status = mmal_port_enable(decoder->input[0], input_callback)))
403         goto fail;
404     if ((status = mmal_port_enable(decoder->output[0], output_callback)))
405         goto fail;
406
407     if ((status = mmal_component_enable(decoder)))
408         goto fail;
409
410     return 0;
411
412 fail:
413     ffmmal_close_decoder(avctx);
414     return ret < 0 ? ret : AVERROR_UNKNOWN;
415 }
416
417 static void ffmmal_flush(AVCodecContext *avctx)
418 {
419     MMALDecodeContext *ctx = avctx->priv_data;
420     MMAL_COMPONENT_T *decoder = ctx->decoder;
421     MMAL_STATUS_T status;
422
423     ffmmal_stop_decoder(avctx);
424
425     if ((status = mmal_port_enable(decoder->control, control_port_cb)))
426         goto fail;
427     if ((status = mmal_port_enable(decoder->input[0], input_callback)))
428         goto fail;
429     if ((status = mmal_port_enable(decoder->output[0], output_callback)))
430         goto fail;
431
432     return;
433
434 fail:
435     av_log(avctx, AV_LOG_ERROR, "MMAL flush error: %i\n", (int)status);
436 }
437
438 // Split packets and add them to the waiting_buffers list. We don't queue them
439 // immediately, because it can happen that the decoder is temporarily blocked
440 // (due to us not reading/returning enough output buffers) and won't accept
441 // new input. (This wouldn't be an issue if MMAL input buffers always were
442 // complete frames - then the input buffer just would have to be big enough.)
443 static int ffmmal_add_packet(AVCodecContext *avctx, AVPacket *avpkt)
444 {
445     MMALDecodeContext *ctx = avctx->priv_data;
446     AVBufferRef *buf = NULL;
447     int size = 0;
448     uint8_t *data = (uint8_t *)"";
449     uint8_t *start;
450     int ret = 0;
451
452     if (avpkt->size) {
453         if (ctx->bsfc) {
454             uint8_t *tmp_data;
455             int tmp_size;
456             if ((ret = av_bitstream_filter_filter(ctx->bsfc, avctx, "private_spspps_buf",
457                                                   &tmp_data, &tmp_size,
458                                                   avpkt->data, avpkt->size,
459                                                   avpkt->flags & AV_PKT_FLAG_KEY)) < 0)
460                 goto done;
461             buf = av_buffer_create(tmp_data, tmp_size, NULL, NULL, 0);
462         } else {
463             if (avpkt->buf) {
464                 buf = av_buffer_ref(avpkt->buf);
465             } else {
466                 buf = av_buffer_alloc(avpkt->size);
467                 if (buf)
468                     memcpy(buf->data, avpkt->data, avpkt->size);
469             }
470         }
471         if (!buf) {
472             ret = AVERROR(ENOMEM);
473             goto done;
474         }
475         size = buf->size;
476         data = buf->data;
477         ctx->packets_sent++;
478     } else {
479         if (!ctx->packets_sent) {
480             // Short-cut the flush logic to avoid upsetting MMAL.
481             ctx->eos_sent = 1;
482             ctx->eos_received = 1;
483             goto done;
484         }
485     }
486
487     start = data;
488
489     do {
490         FFBufferEntry *buffer = av_mallocz(sizeof(*buffer));
491         if (!buffer) {
492             ret = AVERROR(ENOMEM);
493             goto done;
494         }
495
496         buffer->data = data;
497         buffer->length = FFMIN(size, ctx->decoder->input[0]->buffer_size);
498
499         if (data == start)
500             buffer->flags |= MMAL_BUFFER_HEADER_FLAG_FRAME_START;
501
502         data += buffer->length;
503         size -= buffer->length;
504
505         buffer->pts = avpkt->pts == AV_NOPTS_VALUE ? MMAL_TIME_UNKNOWN : avpkt->pts;
506         buffer->dts = avpkt->dts == AV_NOPTS_VALUE ? MMAL_TIME_UNKNOWN : avpkt->dts;
507
508         if (!size)
509             buffer->flags |= MMAL_BUFFER_HEADER_FLAG_FRAME_END;
510
511         if (!buffer->length) {
512             buffer->flags |= MMAL_BUFFER_HEADER_FLAG_EOS;
513             ctx->eos_sent = 1;
514         }
515
516         if (buf) {
517             buffer->ref = av_buffer_ref(buf);
518             if (!buffer->ref) {
519                 av_free(buffer);
520                 ret = AVERROR(ENOMEM);
521                 goto done;
522             }
523         }
524
525         // Insert at end of the list
526         if (!ctx->waiting_buffers)
527             ctx->waiting_buffers = buffer;
528         if (ctx->waiting_buffers_tail)
529             ctx->waiting_buffers_tail->next = buffer;
530         ctx->waiting_buffers_tail = buffer;
531     } while (size);
532
533 done:
534     av_buffer_unref(&buf);
535     return ret;
536 }
537
538 // Move prepared/split packets from waiting_buffers to the MMAL decoder.
539 static int ffmmal_fill_input_port(AVCodecContext *avctx)
540 {
541     MMALDecodeContext *ctx = avctx->priv_data;
542
543     while (ctx->waiting_buffers) {
544         MMAL_BUFFER_HEADER_T *mbuffer;
545         FFBufferEntry *buffer;
546         MMAL_STATUS_T status;
547
548         mbuffer = mmal_queue_get(ctx->pool_in->queue);
549         if (!mbuffer)
550             return 0;
551
552         buffer = ctx->waiting_buffers;
553
554         mmal_buffer_header_reset(mbuffer);
555         mbuffer->cmd = 0;
556         mbuffer->pts = buffer->pts;
557         mbuffer->dts = buffer->dts;
558         mbuffer->flags = buffer->flags;
559         mbuffer->data = buffer->data;
560         mbuffer->length = buffer->length;
561         mbuffer->user_data = buffer->ref;
562         mbuffer->alloc_size = ctx->decoder->input[0]->buffer_size;
563
564         if ((status = mmal_port_send_buffer(ctx->decoder->input[0], mbuffer))) {
565             mmal_buffer_header_release(mbuffer);
566             av_buffer_unref(&buffer->ref);
567         }
568
569         // Remove from start of the list
570         ctx->waiting_buffers = buffer->next;
571         if (ctx->waiting_buffers_tail == buffer)
572             ctx->waiting_buffers_tail = NULL;
573         av_free(buffer);
574
575         if (status) {
576             av_log(avctx, AV_LOG_ERROR, "MMAL error %d when sending input\n", (int)status);
577             return AVERROR_UNKNOWN;
578         }
579     }
580
581     return 0;
582 }
583
584 static int ffmal_copy_frame(AVCodecContext *avctx,  AVFrame *frame,
585                             MMAL_BUFFER_HEADER_T *buffer)
586 {
587     MMALDecodeContext *ctx = avctx->priv_data;
588     int ret = 0;
589
590     if (avctx->pix_fmt == AV_PIX_FMT_MMAL) {
591         if (!ctx->pool_out)
592             return AVERROR_UNKNOWN; // format change code failed with OOM previously
593
594         if ((ret = ff_decode_frame_props(avctx, frame)) < 0)
595             goto done;
596
597         if ((ret = ffmmal_set_ref(frame, ctx->pool_out, buffer)) < 0)
598             goto done;
599     } else {
600         int w = FFALIGN(avctx->width, 32);
601         int h = FFALIGN(avctx->height, 16);
602         char *ptr;
603         int plane;
604         int i;
605
606         if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
607             goto done;
608
609         ptr = buffer->data + buffer->type->video.offset[0];
610         for (i = 0; i < avctx->height; i++)
611             memcpy(frame->data[0] + frame->linesize[0] * i, ptr + w * i, avctx->width);
612
613         ptr += w * h;
614
615         for (plane = 1; plane < 3; plane++) {
616             for (i = 0; i < avctx->height / 2; i++)
617                 memcpy(frame->data[plane] + frame->linesize[plane] * i, ptr + w / 2 * i, (avctx->width + 1) / 2);
618             ptr += w / 2 * h / 2;
619         }
620     }
621
622     frame->pkt_pts = buffer->pts == MMAL_TIME_UNKNOWN ? AV_NOPTS_VALUE : buffer->pts;
623     frame->pkt_dts = AV_NOPTS_VALUE;
624
625 done:
626     return ret;
627 }
628
629 // Fetch a decoded buffer and place it into the frame parameter.
630 static int ffmmal_read_frame(AVCodecContext *avctx, AVFrame *frame, int *got_frame)
631 {
632     MMALDecodeContext *ctx = avctx->priv_data;
633     MMAL_BUFFER_HEADER_T *buffer = NULL;
634     MMAL_STATUS_T status = 0;
635     int ret = 0;
636
637     if (ctx->eos_received)
638         goto done;
639
640     while (1) {
641         // To ensure decoding in lockstep with a constant delay between fed packets
642         // and output frames, we always wait until an output buffer is available.
643         // Except during start we don't know after how many input packets the decoder
644         // is going to return the first buffer, and we can't distinguish decoder
645         // being busy from decoder waiting for input. So just poll at the start and
646         // keep feeding new data to the buffer.
647         // We are pretty sure the decoder will produce output if we sent more input
648         // frames than what a h264 decoder could logically delay. This avoids too
649         // excessive buffering.
650         // We also wait if we sent eos, but didn't receive it yet (think of decoding
651         // stream with a very low number of frames).
652         if (ctx->frames_output || ctx->packets_sent > MAX_DELAYED_FRAMES ||
653             (ctx->packets_sent && ctx->eos_sent)) {
654             // MMAL will ignore broken input packets, which means the frame we
655             // expect here may never arrive. Dealing with this correctly is
656             // complicated, so here's a hack to avoid that it freezes forever
657             // in this unlikely situation.
658             buffer = mmal_queue_timedwait(ctx->queue_decoded_frames, 100);
659             if (!buffer) {
660                 av_log(avctx, AV_LOG_ERROR, "Did not get output frame from MMAL.\n");
661                 ret = AVERROR_UNKNOWN;
662                 goto done;
663             }
664         } else {
665             buffer = mmal_queue_get(ctx->queue_decoded_frames);
666             if (!buffer)
667                 goto done;
668         }
669
670         ctx->eos_received |= !!(buffer->flags & MMAL_BUFFER_HEADER_FLAG_EOS);
671         if (ctx->eos_received)
672             goto done;
673
674         if (buffer->cmd == MMAL_EVENT_FORMAT_CHANGED) {
675             MMAL_COMPONENT_T *decoder = ctx->decoder;
676             MMAL_EVENT_FORMAT_CHANGED_T *ev = mmal_event_format_changed_get(buffer);
677             MMAL_BUFFER_HEADER_T *stale_buffer;
678
679             av_log(avctx, AV_LOG_INFO, "Changing output format.\n");
680
681             if ((status = mmal_port_disable(decoder->output[0])))
682                 goto done;
683
684             while ((stale_buffer = mmal_queue_get(ctx->queue_decoded_frames)))
685                 mmal_buffer_header_release(stale_buffer);
686
687             mmal_format_copy(decoder->output[0]->format, ev->format);
688
689             if ((ret = ffmal_update_format(avctx)) < 0)
690                 goto done;
691
692             if ((status = mmal_port_enable(decoder->output[0], output_callback)))
693                 goto done;
694
695             if ((ret = ffmmal_fill_output_port(avctx)) < 0)
696                 goto done;
697
698             if ((ret = ffmmal_fill_input_port(avctx)) < 0)
699                 goto done;
700
701             mmal_buffer_header_release(buffer);
702             continue;
703         } else if (buffer->cmd) {
704             char s[20];
705             av_get_codec_tag_string(s, sizeof(s), buffer->cmd);
706             av_log(avctx, AV_LOG_WARNING, "Unknown MMAL event %s on output port\n", s);
707             goto done;
708         } else if (buffer->length == 0) {
709             // Unused output buffer that got drained after format change.
710             mmal_buffer_header_release(buffer);
711             continue;
712         }
713
714         ctx->frames_output++;
715
716         if ((ret = ffmal_copy_frame(avctx, frame, buffer)) < 0)
717             goto done;
718
719         *got_frame = 1;
720         break;
721     }
722
723 done:
724     if (buffer)
725         mmal_buffer_header_release(buffer);
726     if (status && ret >= 0)
727         ret = AVERROR_UNKNOWN;
728     return ret;
729 }
730
731 static int ffmmal_decode(AVCodecContext *avctx, void *data, int *got_frame,
732                          AVPacket *avpkt)
733 {
734     AVFrame *frame = data;
735     int ret = 0;
736
737     if ((ret = ffmmal_add_packet(avctx, avpkt)) < 0)
738         return ret;
739
740     if ((ret = ffmmal_fill_input_port(avctx)) < 0)
741         return ret;
742
743     if ((ret = ffmmal_fill_output_port(avctx)) < 0)
744         return ret;
745
746     if ((ret = ffmmal_read_frame(avctx, frame, got_frame)) < 0)
747         return ret;
748
749     // ffmmal_read_frame() can block for a while. Since the decoder is
750     // asynchronous, it's a good idea to fill the ports again.
751
752     if ((ret = ffmmal_fill_output_port(avctx)) < 0)
753         return ret;
754
755     if ((ret = ffmmal_fill_input_port(avctx)) < 0)
756         return ret;
757
758     return ret;
759 }
760
761 AVHWAccel ff_h264_mmal_hwaccel = {
762     .name       = "h264_mmal",
763     .type       = AVMEDIA_TYPE_VIDEO,
764     .id         = AV_CODEC_ID_H264,
765     .pix_fmt    = AV_PIX_FMT_MMAL,
766 };
767
768 static const AVOption options[]={
769     {"extra_buffers", "extra buffers", offsetof(MMALDecodeContext, extra_buffers), AV_OPT_TYPE_INT, {.i64 = 10}, 0, 256, 0},
770     {NULL}
771 };
772
773 static const AVClass ffmmaldec_class = {
774     .class_name = "mmaldec",
775     .option     = options,
776     .version    = LIBAVUTIL_VERSION_INT,
777 };
778
779 AVCodec ff_h264_mmal_decoder = {
780     .name           = "h264_mmal",
781     .long_name      = NULL_IF_CONFIG_SMALL("h264 (mmal)"),
782     .type           = AVMEDIA_TYPE_VIDEO,
783     .id             = AV_CODEC_ID_H264,
784     .priv_data_size = sizeof(MMALDecodeContext),
785     .init           = ffmmal_init_decoder,
786     .close          = ffmmal_close_decoder,
787     .decode         = ffmmal_decode,
788     .flush          = ffmmal_flush,
789     .priv_class     = &ffmmaldec_class,
790     .capabilities   = AV_CODEC_CAP_DELAY,
791     .caps_internal  = FF_CODEC_CAP_SETS_PKT_DTS,
792     .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_MMAL,
793                                                      AV_PIX_FMT_YUV420P,
794                                                      AV_PIX_FMT_NONE},
795 };