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