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