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