]> git.sesse.net Git - ffmpeg/blob - libavcodec/mmaldec.c
Merge commit 'a17a7661906ba295d67afd80ac0770422e1b02b3'
[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     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     volatile int packets_buffered;
85     int64_t frames_output;
86     int eos_received;
87     int eos_sent;
88     int extradata_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     av_assert0(avpriv_atomic_int_get(&ctx->packets_buffered) == 0);
169
170     ctx->frames_output = ctx->eos_received = ctx->eos_sent = ctx->packets_sent = ctx->extradata_sent = 0;
171 }
172
173 static av_cold int ffmmal_close_decoder(AVCodecContext *avctx)
174 {
175     MMALDecodeContext *ctx = avctx->priv_data;
176
177     if (ctx->decoder)
178         ffmmal_stop_decoder(avctx);
179
180     mmal_component_destroy(ctx->decoder);
181     ctx->decoder = NULL;
182     mmal_queue_destroy(ctx->queue_decoded_frames);
183     mmal_pool_destroy(ctx->pool_in);
184     ffmmal_poolref_unref(ctx->pool_out);
185
186     mmal_vc_deinit();
187
188     return 0;
189 }
190
191 static void input_callback(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer)
192 {
193     AVCodecContext *avctx = (AVCodecContext*)port->userdata;
194     MMALDecodeContext *ctx = avctx->priv_data;
195
196     if (!buffer->cmd) {
197         FFBufferEntry *entry = buffer->user_data;
198         av_buffer_unref(&entry->ref);
199         if (entry->flags & MMAL_BUFFER_HEADER_FLAG_FRAME_END)
200             avpriv_atomic_int_add_and_fetch(&ctx->packets_buffered, -1);
201         av_free(entry);
202     }
203     mmal_buffer_header_release(buffer);
204 }
205
206 static void output_callback(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer)
207 {
208     AVCodecContext *avctx = (AVCodecContext*)port->userdata;
209     MMALDecodeContext *ctx = avctx->priv_data;
210
211     mmal_queue_put(ctx->queue_decoded_frames, buffer);
212 }
213
214 static void control_port_cb(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer)
215 {
216     AVCodecContext *avctx = (AVCodecContext*)port->userdata;
217     MMAL_STATUS_T status;
218
219     if (buffer->cmd == MMAL_EVENT_ERROR) {
220         status = *(uint32_t *)buffer->data;
221         av_log(avctx, AV_LOG_ERROR, "MMAL error %d on control port\n", (int)status);
222     } else {
223         char s[20];
224         av_get_codec_tag_string(s, sizeof(s), buffer->cmd);
225         av_log(avctx, AV_LOG_WARNING, "Unknown MMAL event %s on control port\n", s);
226     }
227
228     mmal_buffer_header_release(buffer);
229 }
230
231 // Feed free output buffers to the decoder.
232 static int ffmmal_fill_output_port(AVCodecContext *avctx)
233 {
234     MMALDecodeContext *ctx = avctx->priv_data;
235     MMAL_BUFFER_HEADER_T *buffer;
236     MMAL_STATUS_T status;
237
238     if (!ctx->pool_out)
239         return AVERROR_UNKNOWN; // format change code failed with OOM previously
240
241     while ((buffer = mmal_queue_get(ctx->pool_out->pool->queue))) {
242         if ((status = mmal_port_send_buffer(ctx->decoder->output[0], buffer))) {
243             mmal_buffer_header_release(buffer);
244             av_log(avctx, AV_LOG_ERROR, "MMAL error %d when sending output buffer.\n", (int)status);
245             return AVERROR_UNKNOWN;
246         }
247     }
248
249     return 0;
250 }
251
252 static enum AVColorSpace ffmmal_csp_to_av_csp(MMAL_FOURCC_T fourcc)
253 {
254     switch (fourcc) {
255     case MMAL_COLOR_SPACE_BT470_2_BG:
256     case MMAL_COLOR_SPACE_BT470_2_M:
257     case MMAL_COLOR_SPACE_ITUR_BT601:   return AVCOL_SPC_BT470BG;
258     case MMAL_COLOR_SPACE_ITUR_BT709:   return AVCOL_SPC_BT709;
259     case MMAL_COLOR_SPACE_FCC:          return AVCOL_SPC_FCC;
260     case MMAL_COLOR_SPACE_SMPTE240M:    return AVCOL_SPC_SMPTE240M;
261     default:                            return AVCOL_SPC_UNSPECIFIED;
262     }
263 }
264
265 static int ffmal_update_format(AVCodecContext *avctx)
266 {
267     MMALDecodeContext *ctx = avctx->priv_data;
268     MMAL_STATUS_T status;
269     int ret = 0;
270     MMAL_COMPONENT_T *decoder = ctx->decoder;
271     MMAL_ES_FORMAT_T *format_out = decoder->output[0]->format;
272
273     ffmmal_poolref_unref(ctx->pool_out);
274     if (!(ctx->pool_out = av_mallocz(sizeof(*ctx->pool_out)))) {
275         ret = AVERROR(ENOMEM);
276         goto fail;
277     }
278     ctx->pool_out->refcount = 1;
279
280     if (!format_out)
281         goto fail;
282
283     if ((status = mmal_port_parameter_set_uint32(decoder->output[0], MMAL_PARAMETER_EXTRA_BUFFERS, ctx->extra_buffers)))
284         goto fail;
285
286     if ((status = mmal_port_parameter_set_boolean(decoder->output[0], MMAL_PARAMETER_VIDEO_INTERPOLATE_TIMESTAMPS, 0)))
287         goto fail;
288
289     if (avctx->pix_fmt == AV_PIX_FMT_MMAL) {
290         format_out->encoding = MMAL_ENCODING_OPAQUE;
291     } else {
292         format_out->encoding_variant = format_out->encoding = MMAL_ENCODING_I420;
293     }
294
295     if ((status = mmal_port_format_commit(decoder->output[0])))
296         goto fail;
297
298     if ((ret = ff_set_dimensions(avctx, format_out->es->video.crop.x + format_out->es->video.crop.width,
299                                         format_out->es->video.crop.y + format_out->es->video.crop.height)) < 0)
300         goto fail;
301
302     if (format_out->es->video.par.num && format_out->es->video.par.den) {
303         avctx->sample_aspect_ratio.num = format_out->es->video.par.num;
304         avctx->sample_aspect_ratio.den = format_out->es->video.par.den;
305     }
306
307     avctx->colorspace = ffmmal_csp_to_av_csp(format_out->es->video.color_space);
308
309     decoder->output[0]->buffer_size =
310         FFMAX(decoder->output[0]->buffer_size_min, decoder->output[0]->buffer_size_recommended);
311     decoder->output[0]->buffer_num =
312         FFMAX(decoder->output[0]->buffer_num_min, decoder->output[0]->buffer_num_recommended) + ctx->extra_buffers;
313     ctx->pool_out->pool = mmal_pool_create(decoder->output[0]->buffer_num,
314                                            decoder->output[0]->buffer_size);
315     if (!ctx->pool_out->pool) {
316         ret = AVERROR(ENOMEM);
317         goto fail;
318     }
319
320     return 0;
321
322 fail:
323     return ret < 0 ? ret : AVERROR_UNKNOWN;
324 }
325
326 static av_cold int ffmmal_init_decoder(AVCodecContext *avctx)
327 {
328     MMALDecodeContext *ctx = avctx->priv_data;
329     MMAL_STATUS_T status;
330     MMAL_ES_FORMAT_T *format_in;
331     MMAL_COMPONENT_T *decoder;
332     int ret = 0;
333
334     bcm_host_init();
335
336     if (mmal_vc_init()) {
337         av_log(avctx, AV_LOG_ERROR, "Cannot initialize MMAL VC driver!\n");
338         return AVERROR(ENOSYS);
339     }
340
341     if ((ret = ff_get_format(avctx, avctx->codec->pix_fmts)) < 0)
342         return ret;
343
344     avctx->pix_fmt = ret;
345
346     if ((status = mmal_component_create(MMAL_COMPONENT_DEFAULT_VIDEO_DECODER, &ctx->decoder)))
347         goto fail;
348
349     decoder = ctx->decoder;
350
351     format_in = decoder->input[0]->format;
352     format_in->type = MMAL_ES_TYPE_VIDEO;
353     switch (avctx->codec_id) {
354         case AV_CODEC_ID_MPEG2VIDEO:
355             format_in->encoding = MMAL_ENCODING_MP2V;
356             av_log(avctx, AV_LOG_DEBUG, "Use MMAL MP2V encoding\n");
357             break;
358         case AV_CODEC_ID_H264:
359         default:
360             format_in->encoding = MMAL_ENCODING_H264;
361             av_log(avctx, AV_LOG_DEBUG, "Use MMAL H264 encoding\n");
362             break;
363     }
364     format_in->es->video.width = FFALIGN(avctx->width, 32);
365     format_in->es->video.height = FFALIGN(avctx->height, 16);
366     format_in->es->video.crop.width = avctx->width;
367     format_in->es->video.crop.height = avctx->height;
368     format_in->es->video.frame_rate.num = 24000;
369     format_in->es->video.frame_rate.den = 1001;
370     format_in->es->video.par.num = avctx->sample_aspect_ratio.num;
371     format_in->es->video.par.den = avctx->sample_aspect_ratio.den;
372     format_in->flags = MMAL_ES_FORMAT_FLAG_FRAMED;
373
374     if ((status = mmal_port_format_commit(decoder->input[0])))
375         goto fail;
376
377     decoder->input[0]->buffer_num =
378         FFMAX(decoder->input[0]->buffer_num_min, 20);
379     decoder->input[0]->buffer_size =
380         FFMAX(decoder->input[0]->buffer_size_min, 512 * 1024);
381     ctx->pool_in = mmal_pool_create(decoder->input[0]->buffer_num, 0);
382     if (!ctx->pool_in) {
383         ret = AVERROR(ENOMEM);
384         goto fail;
385     }
386
387     if ((ret = ffmal_update_format(avctx)) < 0)
388         goto fail;
389
390     ctx->queue_decoded_frames = mmal_queue_create();
391     if (!ctx->queue_decoded_frames)
392         goto fail;
393
394     decoder->input[0]->userdata = (void*)avctx;
395     decoder->output[0]->userdata = (void*)avctx;
396     decoder->control->userdata = (void*)avctx;
397
398     if ((status = mmal_port_enable(decoder->control, control_port_cb)))
399         goto fail;
400     if ((status = mmal_port_enable(decoder->input[0], input_callback)))
401         goto fail;
402     if ((status = mmal_port_enable(decoder->output[0], output_callback)))
403         goto fail;
404
405     if ((status = mmal_component_enable(decoder)))
406         goto fail;
407
408     return 0;
409
410 fail:
411     ffmmal_close_decoder(avctx);
412     return ret < 0 ? ret : AVERROR_UNKNOWN;
413 }
414
415 static void ffmmal_flush(AVCodecContext *avctx)
416 {
417     MMALDecodeContext *ctx = avctx->priv_data;
418     MMAL_COMPONENT_T *decoder = ctx->decoder;
419     MMAL_STATUS_T status;
420
421     ffmmal_stop_decoder(avctx);
422
423     if ((status = mmal_port_enable(decoder->control, control_port_cb)))
424         goto fail;
425     if ((status = mmal_port_enable(decoder->input[0], input_callback)))
426         goto fail;
427     if ((status = mmal_port_enable(decoder->output[0], output_callback)))
428         goto fail;
429
430     return;
431
432 fail:
433     av_log(avctx, AV_LOG_ERROR, "MMAL flush error: %i\n", (int)status);
434 }
435
436 // Split packets and add them to the waiting_buffers list. We don't queue them
437 // immediately, because it can happen that the decoder is temporarily blocked
438 // (due to us not reading/returning enough output buffers) and won't accept
439 // new input. (This wouldn't be an issue if MMAL input buffers always were
440 // complete frames - then the input buffer just would have to be big enough.)
441 // If is_extradata is set, send it as MMAL_BUFFER_HEADER_FLAG_CONFIG.
442 static int ffmmal_add_packet(AVCodecContext *avctx, AVPacket *avpkt,
443                              int is_extradata)
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 (avpkt->buf) {
454             buf = av_buffer_ref(avpkt->buf);
455             size = avpkt->size;
456             data = avpkt->data;
457         } else {
458             buf = av_buffer_alloc(avpkt->size);
459             if (buf) {
460                 memcpy(buf->data, avpkt->data, avpkt->size);
461                 size = buf->size;
462                 data = buf->data;
463             }
464         }
465         if (!buf) {
466             ret = AVERROR(ENOMEM);
467             goto done;
468         }
469         if (!is_extradata)
470             ctx->packets_sent++;
471     } else {
472         if (!ctx->packets_sent) {
473             // Short-cut the flush logic to avoid upsetting MMAL.
474             ctx->eos_sent = 1;
475             ctx->eos_received = 1;
476             goto done;
477         }
478     }
479
480     start = data;
481
482     do {
483         FFBufferEntry *buffer = av_mallocz(sizeof(*buffer));
484         if (!buffer) {
485             ret = AVERROR(ENOMEM);
486             goto done;
487         }
488
489         buffer->data = data;
490         buffer->length = FFMIN(size, ctx->decoder->input[0]->buffer_size);
491
492         if (is_extradata)
493             buffer->flags |= MMAL_BUFFER_HEADER_FLAG_CONFIG;
494
495         if (data == start)
496             buffer->flags |= MMAL_BUFFER_HEADER_FLAG_FRAME_START;
497
498         data += buffer->length;
499         size -= buffer->length;
500
501         buffer->pts = avpkt->pts == AV_NOPTS_VALUE ? MMAL_TIME_UNKNOWN : avpkt->pts;
502         buffer->dts = avpkt->dts == AV_NOPTS_VALUE ? MMAL_TIME_UNKNOWN : avpkt->dts;
503
504         if (!size) {
505             buffer->flags |= MMAL_BUFFER_HEADER_FLAG_FRAME_END;
506             avpriv_atomic_int_add_and_fetch(&ctx->packets_buffered, 1);
507         }
508
509         if (!buffer->length) {
510             buffer->flags |= MMAL_BUFFER_HEADER_FLAG_EOS;
511             ctx->eos_sent = 1;
512         }
513
514         if (buf) {
515             buffer->ref = av_buffer_ref(buf);
516             if (!buffer->ref) {
517                 av_free(buffer);
518                 ret = AVERROR(ENOMEM);
519                 goto done;
520             }
521         }
522
523         // Insert at end of the list
524         if (!ctx->waiting_buffers)
525             ctx->waiting_buffers = buffer;
526         if (ctx->waiting_buffers_tail)
527             ctx->waiting_buffers_tail->next = buffer;
528         ctx->waiting_buffers_tail = buffer;
529     } while (size);
530
531 done:
532     av_buffer_unref(&buf);
533     return ret;
534 }
535
536 // Move prepared/split packets from waiting_buffers to the MMAL decoder.
537 static int ffmmal_fill_input_port(AVCodecContext *avctx)
538 {
539     MMALDecodeContext *ctx = avctx->priv_data;
540
541     while (ctx->waiting_buffers) {
542         MMAL_BUFFER_HEADER_T *mbuffer;
543         FFBufferEntry *buffer;
544         MMAL_STATUS_T status;
545
546         mbuffer = mmal_queue_get(ctx->pool_in->queue);
547         if (!mbuffer)
548             return 0;
549
550         buffer = ctx->waiting_buffers;
551
552         mmal_buffer_header_reset(mbuffer);
553         mbuffer->cmd = 0;
554         mbuffer->pts = buffer->pts;
555         mbuffer->dts = buffer->dts;
556         mbuffer->flags = buffer->flags;
557         mbuffer->data = buffer->data;
558         mbuffer->length = buffer->length;
559         mbuffer->user_data = buffer;
560         mbuffer->alloc_size = ctx->decoder->input[0]->buffer_size;
561
562         // Remove from start of the list
563         ctx->waiting_buffers = buffer->next;
564         if (ctx->waiting_buffers_tail == buffer)
565             ctx->waiting_buffers_tail = NULL;
566
567         if ((status = mmal_port_send_buffer(ctx->decoder->input[0], mbuffer))) {
568             mmal_buffer_header_release(mbuffer);
569             av_buffer_unref(&buffer->ref);
570             if (buffer->flags & MMAL_BUFFER_HEADER_FLAG_FRAME_END)
571                 avpriv_atomic_int_add_and_fetch(&ctx->packets_buffered, -1);
572             av_free(buffer);
573         }
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 (avpriv_atomic_int_get(&ctx->packets_buffered) > 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     MMALDecodeContext *ctx = avctx->priv_data;
735     AVFrame *frame = data;
736     int ret = 0;
737
738     if (avctx->extradata_size && !ctx->extradata_sent) {
739         AVPacket pkt = {0};
740         av_init_packet(&pkt);
741         pkt.data = avctx->extradata;
742         pkt.size = avctx->extradata_size;
743         ctx->extradata_sent = 1;
744         if ((ret = ffmmal_add_packet(avctx, &pkt, 1)) < 0)
745             return ret;
746     }
747
748     if ((ret = ffmmal_add_packet(avctx, avpkt, 0)) < 0)
749         return ret;
750
751     if ((ret = ffmmal_fill_input_port(avctx)) < 0)
752         return ret;
753
754     if ((ret = ffmmal_fill_output_port(avctx)) < 0)
755         return ret;
756
757     if ((ret = ffmmal_read_frame(avctx, frame, got_frame)) < 0)
758         return ret;
759
760     // ffmmal_read_frame() can block for a while. Since the decoder is
761     // asynchronous, it's a good idea to fill the ports again.
762
763     if ((ret = ffmmal_fill_output_port(avctx)) < 0)
764         return ret;
765
766     if ((ret = ffmmal_fill_input_port(avctx)) < 0)
767         return ret;
768
769     return ret;
770 }
771
772 AVHWAccel ff_h264_mmal_hwaccel = {
773     .name       = "h264_mmal",
774     .type       = AVMEDIA_TYPE_VIDEO,
775     .id         = AV_CODEC_ID_H264,
776     .pix_fmt    = AV_PIX_FMT_MMAL,
777 };
778
779 AVHWAccel ff_mpeg2_mmal_hwaccel = {
780     .name       = "mpeg2_mmal",
781     .type       = AVMEDIA_TYPE_VIDEO,
782     .id         = AV_CODEC_ID_MPEG2VIDEO,
783     .pix_fmt    = AV_PIX_FMT_MMAL,
784 };
785
786 static const AVOption options[]={
787     {"extra_buffers", "extra buffers", offsetof(MMALDecodeContext, extra_buffers), AV_OPT_TYPE_INT, {.i64 = 10}, 0, 256, 0},
788     {NULL}
789 };
790
791 #define FFMMAL_DEC_CLASS(NAME) \
792     static const AVClass ffmmal_##NAME##_dec_class = { \
793         .class_name = "mmal_" #NAME "_dec", \
794         .option     = options, \
795         .version    = LIBAVUTIL_VERSION_INT, \
796     };
797
798 #define FFMMAL_DEC(NAME, ID) \
799     FFMMAL_DEC_CLASS(NAME) \
800     AVCodec ff_##NAME##_mmal_decoder = { \
801         .name           = #NAME "_mmal", \
802         .long_name      = NULL_IF_CONFIG_SMALL(#NAME " (mmal)"), \
803         .type           = AVMEDIA_TYPE_VIDEO, \
804         .id             = ID, \
805         .priv_data_size = sizeof(MMALDecodeContext), \
806         .init           = ffmmal_init_decoder, \
807         .close          = ffmmal_close_decoder, \
808         .decode         = ffmmal_decode, \
809         .flush          = ffmmal_flush, \
810         .priv_class     = &ffmmal_##NAME##_dec_class, \
811         .capabilities   = AV_CODEC_CAP_DELAY, \
812         .caps_internal  = FF_CODEC_CAP_SETS_PKT_DTS, \
813         .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_MMAL, \
814                                                          AV_PIX_FMT_YUV420P, \
815                                                          AV_PIX_FMT_NONE}, \
816     };
817
818 FFMMAL_DEC(h264, AV_CODEC_ID_H264)
819 FFMMAL_DEC(mpeg2, AV_CODEC_ID_MPEG2VIDEO)