]> git.sesse.net Git - ffmpeg/blob - libavcodec/mediacodecdec_common.c
avcodec/mediacodecdec: add delay_flush option
[ffmpeg] / libavcodec / mediacodecdec_common.c
1 /*
2  * Android MediaCodec decoder
3  *
4  * Copyright (c) 2015-2016 Matthieu Bouron <matthieu.bouron stupeflix.com>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include <string.h>
24 #include <sys/types.h>
25
26 #include "libavutil/common.h"
27 #include "libavutil/hwcontext_mediacodec.h"
28 #include "libavutil/mem.h"
29 #include "libavutil/log.h"
30 #include "libavutil/pixfmt.h"
31 #include "libavutil/time.h"
32 #include "libavutil/timestamp.h"
33
34 #include "avcodec.h"
35 #include "internal.h"
36
37 #include "mediacodec.h"
38 #include "mediacodec_surface.h"
39 #include "mediacodec_sw_buffer.h"
40 #include "mediacodec_wrapper.h"
41 #include "mediacodecdec_common.h"
42
43 /**
44  * OMX.k3.video.decoder.avc, OMX.NVIDIA.* OMX.SEC.avc.dec and OMX.google
45  * codec workarounds used in various place are taken from the Gstreamer
46  * project.
47  *
48  * Gstreamer references:
49  * https://cgit.freedesktop.org/gstreamer/gst-plugins-bad/tree/sys/androidmedia/
50  *
51  * Gstreamer copyright notice:
52  *
53  * Copyright (C) 2012, Collabora Ltd.
54  *   Author: Sebastian Dröge <sebastian.droege@collabora.co.uk>
55  *
56  * Copyright (C) 2012, Rafaël Carré <funman@videolanorg>
57  *
58  * Copyright (C) 2015, Sebastian Dröge <sebastian@centricular.com>
59  *
60  * Copyright (C) 2014-2015, Collabora Ltd.
61  *   Author: Matthieu Bouron <matthieu.bouron@gcollabora.com>
62  *
63  * Copyright (C) 2015, Edward Hervey
64  *   Author: Edward Hervey <bilboed@gmail.com>
65  *
66  * Copyright (C) 2015, Matthew Waters <matthew@centricular.com>
67  *
68  * This library is free software; you can redistribute it and/or
69  * modify it under the terms of the GNU Lesser General Public
70  * License as published by the Free Software Foundation
71  * version 2.1 of the License.
72  *
73  * This library is distributed in the hope that it will be useful,
74  * but WITHOUT ANY WARRANTY; without even the implied warranty of
75  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
76  * Lesser General Public License for more details.
77  *
78  * You should have received a copy of the GNU Lesser General Public
79  * License along with this library; if not, write to the Free Software
80  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
81  *
82  */
83
84 #define INPUT_DEQUEUE_TIMEOUT_US 8000
85 #define OUTPUT_DEQUEUE_TIMEOUT_US 8000
86 #define OUTPUT_DEQUEUE_BLOCK_TIMEOUT_US 1000000
87
88 enum {
89     COLOR_FormatYUV420Planar                              = 0x13,
90     COLOR_FormatYUV420SemiPlanar                          = 0x15,
91     COLOR_FormatYCbYCr                                    = 0x19,
92     COLOR_FormatAndroidOpaque                             = 0x7F000789,
93     COLOR_QCOM_FormatYUV420SemiPlanar                     = 0x7fa30c00,
94     COLOR_QCOM_FormatYUV420SemiPlanar32m                  = 0x7fa30c04,
95     COLOR_QCOM_FormatYUV420PackedSemiPlanar64x32Tile2m8ka = 0x7fa30c03,
96     COLOR_TI_FormatYUV420PackedSemiPlanar                 = 0x7f000100,
97     COLOR_TI_FormatYUV420PackedSemiPlanarInterlaced       = 0x7f000001,
98 };
99
100 static const struct {
101
102     int color_format;
103     enum AVPixelFormat pix_fmt;
104
105 } color_formats[] = {
106
107     { COLOR_FormatYUV420Planar,                              AV_PIX_FMT_YUV420P },
108     { COLOR_FormatYUV420SemiPlanar,                          AV_PIX_FMT_NV12    },
109     { COLOR_QCOM_FormatYUV420SemiPlanar,                     AV_PIX_FMT_NV12    },
110     { COLOR_QCOM_FormatYUV420SemiPlanar32m,                  AV_PIX_FMT_NV12    },
111     { COLOR_QCOM_FormatYUV420PackedSemiPlanar64x32Tile2m8ka, AV_PIX_FMT_NV12    },
112     { COLOR_TI_FormatYUV420PackedSemiPlanar,                 AV_PIX_FMT_NV12    },
113     { COLOR_TI_FormatYUV420PackedSemiPlanarInterlaced,       AV_PIX_FMT_NV12    },
114     { 0 }
115 };
116
117 static enum AVPixelFormat mcdec_map_color_format(AVCodecContext *avctx,
118                                                  MediaCodecDecContext *s,
119                                                  int color_format)
120 {
121     int i;
122     enum AVPixelFormat ret = AV_PIX_FMT_NONE;
123
124     if (s->surface) {
125         return AV_PIX_FMT_MEDIACODEC;
126     }
127
128     if (!strcmp(s->codec_name, "OMX.k3.video.decoder.avc") && color_format == COLOR_FormatYCbYCr) {
129         s->color_format = color_format = COLOR_TI_FormatYUV420PackedSemiPlanar;
130     }
131
132     for (i = 0; i < FF_ARRAY_ELEMS(color_formats); i++) {
133         if (color_formats[i].color_format == color_format) {
134             return color_formats[i].pix_fmt;
135         }
136     }
137
138     av_log(avctx, AV_LOG_ERROR, "Output color format 0x%x (value=%d) is not supported\n",
139         color_format, color_format);
140
141     return ret;
142 }
143
144 static void ff_mediacodec_dec_ref(MediaCodecDecContext *s)
145 {
146     atomic_fetch_add(&s->refcount, 1);
147 }
148
149 static void ff_mediacodec_dec_unref(MediaCodecDecContext *s)
150 {
151     if (!s)
152         return;
153
154     if (atomic_fetch_sub(&s->refcount, 1) == 1) {
155         if (s->codec) {
156             ff_AMediaCodec_delete(s->codec);
157             s->codec = NULL;
158         }
159
160         if (s->format) {
161             ff_AMediaFormat_delete(s->format);
162             s->format = NULL;
163         }
164
165         if (s->surface) {
166             ff_mediacodec_surface_unref(s->surface, NULL);
167             s->surface = NULL;
168         }
169
170         av_freep(&s->codec_name);
171         av_freep(&s);
172     }
173 }
174
175 static void mediacodec_buffer_release(void *opaque, uint8_t *data)
176 {
177     AVMediaCodecBuffer *buffer = opaque;
178     MediaCodecDecContext *ctx = buffer->ctx;
179     int released = atomic_load(&buffer->released);
180
181     if (!released && (ctx->delay_flush || buffer->serial == atomic_load(&ctx->serial))) {
182         ff_AMediaCodec_releaseOutputBuffer(ctx->codec, buffer->index, 0);
183     }
184
185     if (ctx->delay_flush)
186         ff_mediacodec_dec_unref(ctx);
187     av_freep(&buffer);
188 }
189
190 static int mediacodec_wrap_hw_buffer(AVCodecContext *avctx,
191                                   MediaCodecDecContext *s,
192                                   ssize_t index,
193                                   FFAMediaCodecBufferInfo *info,
194                                   AVFrame *frame)
195 {
196     int ret = 0;
197     int status = 0;
198     AVMediaCodecBuffer *buffer = NULL;
199
200     frame->buf[0] = NULL;
201     frame->width = avctx->width;
202     frame->height = avctx->height;
203     frame->format = avctx->pix_fmt;
204
205     if (avctx->pkt_timebase.num && avctx->pkt_timebase.den) {
206         frame->pts = av_rescale_q(info->presentationTimeUs,
207                                       av_make_q(1, 1000000),
208                                       avctx->pkt_timebase);
209     } else {
210         frame->pts = info->presentationTimeUs;
211     }
212 #if FF_API_PKT_PTS
213 FF_DISABLE_DEPRECATION_WARNINGS
214     frame->pkt_pts = frame->pts;
215 FF_ENABLE_DEPRECATION_WARNINGS
216 #endif
217     frame->pkt_dts = AV_NOPTS_VALUE;
218
219     buffer = av_mallocz(sizeof(AVMediaCodecBuffer));
220     if (!buffer) {
221         ret = AVERROR(ENOMEM);
222         goto fail;
223     }
224
225     atomic_init(&buffer->released, 0);
226
227     frame->buf[0] = av_buffer_create(NULL,
228                                      0,
229                                      mediacodec_buffer_release,
230                                      buffer,
231                                      AV_BUFFER_FLAG_READONLY);
232
233     if (!frame->buf[0]) {
234         ret = AVERROR(ENOMEM);
235         goto fail;
236
237     }
238
239     buffer->ctx = s;
240     buffer->serial = atomic_load(&s->serial);
241     if (s->delay_flush)
242         ff_mediacodec_dec_ref(s);
243
244     buffer->index = index;
245     buffer->pts = info->presentationTimeUs;
246
247     frame->data[3] = (uint8_t *)buffer;
248
249     return 0;
250 fail:
251     av_freep(buffer);
252     av_buffer_unref(&frame->buf[0]);
253     status = ff_AMediaCodec_releaseOutputBuffer(s->codec, index, 0);
254     if (status < 0) {
255         av_log(avctx, AV_LOG_ERROR, "Failed to release output buffer\n");
256         ret = AVERROR_EXTERNAL;
257     }
258
259     return ret;
260 }
261
262 static int mediacodec_wrap_sw_buffer(AVCodecContext *avctx,
263                                   MediaCodecDecContext *s,
264                                   uint8_t *data,
265                                   size_t size,
266                                   ssize_t index,
267                                   FFAMediaCodecBufferInfo *info,
268                                   AVFrame *frame)
269 {
270     int ret = 0;
271     int status = 0;
272
273     frame->width = avctx->width;
274     frame->height = avctx->height;
275     frame->format = avctx->pix_fmt;
276
277     /* MediaCodec buffers needs to be copied to our own refcounted buffers
278      * because the flush command invalidates all input and output buffers.
279      */
280     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
281         av_log(avctx, AV_LOG_ERROR, "Could not allocate buffer\n");
282         goto done;
283     }
284
285     /* Override frame->pkt_pts as ff_get_buffer will override its value based
286      * on the last avpacket received which is not in sync with the frame:
287      *   * N avpackets can be pushed before 1 frame is actually returned
288      *   * 0-sized avpackets are pushed to flush remaining frames at EOS */
289     if (avctx->pkt_timebase.num && avctx->pkt_timebase.den) {
290         frame->pts = av_rescale_q(info->presentationTimeUs,
291                                       av_make_q(1, 1000000),
292                                       avctx->pkt_timebase);
293     } else {
294         frame->pts = info->presentationTimeUs;
295     }
296 #if FF_API_PKT_PTS
297 FF_DISABLE_DEPRECATION_WARNINGS
298     frame->pkt_pts = frame->pts;
299 FF_ENABLE_DEPRECATION_WARNINGS
300 #endif
301     frame->pkt_dts = AV_NOPTS_VALUE;
302
303     av_log(avctx, AV_LOG_TRACE,
304             "Frame: width=%d stride=%d height=%d slice-height=%d "
305             "crop-top=%d crop-bottom=%d crop-left=%d crop-right=%d encoder=%s\n"
306             "destination linesizes=%d,%d,%d\n" ,
307             avctx->width, s->stride, avctx->height, s->slice_height,
308             s->crop_top, s->crop_bottom, s->crop_left, s->crop_right, s->codec_name,
309             frame->linesize[0], frame->linesize[1], frame->linesize[2]);
310
311     switch (s->color_format) {
312     case COLOR_FormatYUV420Planar:
313         ff_mediacodec_sw_buffer_copy_yuv420_planar(avctx, s, data, size, info, frame);
314         break;
315     case COLOR_FormatYUV420SemiPlanar:
316     case COLOR_QCOM_FormatYUV420SemiPlanar:
317     case COLOR_QCOM_FormatYUV420SemiPlanar32m:
318         ff_mediacodec_sw_buffer_copy_yuv420_semi_planar(avctx, s, data, size, info, frame);
319         break;
320     case COLOR_TI_FormatYUV420PackedSemiPlanar:
321     case COLOR_TI_FormatYUV420PackedSemiPlanarInterlaced:
322         ff_mediacodec_sw_buffer_copy_yuv420_packed_semi_planar(avctx, s, data, size, info, frame);
323         break;
324     case COLOR_QCOM_FormatYUV420PackedSemiPlanar64x32Tile2m8ka:
325         ff_mediacodec_sw_buffer_copy_yuv420_packed_semi_planar_64x32Tile2m8ka(avctx, s, data, size, info, frame);
326         break;
327     default:
328         av_log(avctx, AV_LOG_ERROR, "Unsupported color format 0x%x (value=%d)\n",
329             s->color_format, s->color_format);
330         ret = AVERROR(EINVAL);
331         goto done;
332     }
333
334     ret = 0;
335 done:
336     status = ff_AMediaCodec_releaseOutputBuffer(s->codec, index, 0);
337     if (status < 0) {
338         av_log(avctx, AV_LOG_ERROR, "Failed to release output buffer\n");
339         ret = AVERROR_EXTERNAL;
340     }
341
342     return ret;
343 }
344
345 #define AMEDIAFORMAT_GET_INT32(name, key, mandatory) do {                              \
346     int32_t value = 0;                                                                 \
347     if (ff_AMediaFormat_getInt32(s->format, key, &value)) {                            \
348         (name) = value;                                                                \
349     } else if (mandatory) {                                                            \
350         av_log(avctx, AV_LOG_ERROR, "Could not get %s from format %s\n", key, format); \
351         ret = AVERROR_EXTERNAL;                                                        \
352         goto fail;                                                                     \
353     }                                                                                  \
354 } while (0)                                                                            \
355
356 static int mediacodec_dec_parse_format(AVCodecContext *avctx, MediaCodecDecContext *s)
357 {
358     int ret = 0;
359     int width = 0;
360     int height = 0;
361     char *format = NULL;
362
363     if (!s->format) {
364         av_log(avctx, AV_LOG_ERROR, "Output MediaFormat is not set\n");
365         return AVERROR(EINVAL);
366     }
367
368     format = ff_AMediaFormat_toString(s->format);
369     if (!format) {
370         return AVERROR_EXTERNAL;
371     }
372     av_log(avctx, AV_LOG_DEBUG, "Parsing MediaFormat %s\n", format);
373
374     /* Mandatory fields */
375     AMEDIAFORMAT_GET_INT32(s->width,  "width", 1);
376     AMEDIAFORMAT_GET_INT32(s->height, "height", 1);
377
378     AMEDIAFORMAT_GET_INT32(s->stride, "stride", 1);
379     s->stride = s->stride > 0 ? s->stride : s->width;
380
381     AMEDIAFORMAT_GET_INT32(s->slice_height, "slice-height", 1);
382     s->slice_height = s->slice_height > 0 ? s->slice_height : s->height;
383
384     if (strstr(s->codec_name, "OMX.Nvidia.")) {
385         s->slice_height = FFALIGN(s->height, 16);
386     } else if (strstr(s->codec_name, "OMX.SEC.avc.dec")) {
387         s->slice_height = avctx->height;
388         s->stride = avctx->width;
389     }
390
391     AMEDIAFORMAT_GET_INT32(s->color_format, "color-format", 1);
392     avctx->pix_fmt = mcdec_map_color_format(avctx, s, s->color_format);
393     if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
394         av_log(avctx, AV_LOG_ERROR, "Output color format is not supported\n");
395         ret = AVERROR(EINVAL);
396         goto fail;
397     }
398
399     /* Optional fields */
400     AMEDIAFORMAT_GET_INT32(s->crop_top,    "crop-top",    0);
401     AMEDIAFORMAT_GET_INT32(s->crop_bottom, "crop-bottom", 0);
402     AMEDIAFORMAT_GET_INT32(s->crop_left,   "crop-left",   0);
403     AMEDIAFORMAT_GET_INT32(s->crop_right,  "crop-right",  0);
404
405     width = s->crop_right + 1 - s->crop_left;
406     height = s->crop_bottom + 1 - s->crop_top;
407
408     av_log(avctx, AV_LOG_INFO,
409         "Output crop parameters top=%d bottom=%d left=%d right=%d, "
410         "resulting dimensions width=%d height=%d\n",
411         s->crop_top, s->crop_bottom, s->crop_left, s->crop_right,
412         width, height);
413
414     av_freep(&format);
415     return ff_set_dimensions(avctx, width, height);
416 fail:
417     av_freep(&format);
418     return ret;
419 }
420
421 static int mediacodec_dec_flush_codec(AVCodecContext *avctx, MediaCodecDecContext *s)
422 {
423     FFAMediaCodec *codec = s->codec;
424     int status;
425
426     s->output_buffer_count = 0;
427
428     s->draining = 0;
429     s->flushing = 0;
430     s->eos = 0;
431     atomic_fetch_add(&s->serial, 1);
432
433     status = ff_AMediaCodec_flush(codec);
434     if (status < 0) {
435         av_log(avctx, AV_LOG_ERROR, "Failed to flush codec\n");
436         return AVERROR_EXTERNAL;
437     }
438
439     return 0;
440 }
441
442 int ff_mediacodec_dec_init(AVCodecContext *avctx, MediaCodecDecContext *s,
443                            const char *mime, FFAMediaFormat *format)
444 {
445     int ret = 0;
446     int status;
447     int profile;
448
449     enum AVPixelFormat pix_fmt;
450     static const enum AVPixelFormat pix_fmts[] = {
451         AV_PIX_FMT_MEDIACODEC,
452         AV_PIX_FMT_NONE,
453     };
454
455     atomic_init(&s->refcount, 1);
456     atomic_init(&s->serial, 1);
457
458     pix_fmt = ff_get_format(avctx, pix_fmts);
459     if (pix_fmt == AV_PIX_FMT_MEDIACODEC) {
460         AVMediaCodecContext *user_ctx = avctx->hwaccel_context;
461
462         if (avctx->hw_device_ctx) {
463             AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)(avctx->hw_device_ctx->data);
464             if (device_ctx->type == AV_HWDEVICE_TYPE_MEDIACODEC) {
465                 if (device_ctx->hwctx) {
466                     AVMediaCodecDeviceContext *mediacodec_ctx = (AVMediaCodecDeviceContext *)device_ctx->hwctx;
467                     s->surface = ff_mediacodec_surface_ref(mediacodec_ctx->surface, avctx);
468                     av_log(avctx, AV_LOG_INFO, "Using surface %p\n", s->surface);
469                 }
470             }
471         }
472
473         if (!s->surface && user_ctx && user_ctx->surface) {
474             s->surface = ff_mediacodec_surface_ref(user_ctx->surface, avctx);
475             av_log(avctx, AV_LOG_INFO, "Using surface %p\n", s->surface);
476         }
477     }
478
479     profile = ff_AMediaCodecProfile_getProfileFromAVCodecContext(avctx);
480     if (profile < 0) {
481         av_log(avctx, AV_LOG_WARNING, "Unsupported or unknown profile\n");
482     }
483
484     s->codec_name = ff_AMediaCodecList_getCodecNameByType(mime, profile, 0, avctx);
485     if (!s->codec_name) {
486         ret = AVERROR_EXTERNAL;
487         goto fail;
488     }
489
490     av_log(avctx, AV_LOG_DEBUG, "Found decoder %s\n", s->codec_name);
491     s->codec = ff_AMediaCodec_createCodecByName(s->codec_name);
492     if (!s->codec) {
493         av_log(avctx, AV_LOG_ERROR, "Failed to create media decoder for type %s and name %s\n", mime, s->codec_name);
494         ret = AVERROR_EXTERNAL;
495         goto fail;
496     }
497
498     status = ff_AMediaCodec_configure(s->codec, format, s->surface, NULL, 0);
499     if (status < 0) {
500         char *desc = ff_AMediaFormat_toString(format);
501         av_log(avctx, AV_LOG_ERROR,
502             "Failed to configure codec (status = %d) with format %s\n",
503             status, desc);
504         av_freep(&desc);
505
506         ret = AVERROR_EXTERNAL;
507         goto fail;
508     }
509
510     status = ff_AMediaCodec_start(s->codec);
511     if (status < 0) {
512         char *desc = ff_AMediaFormat_toString(format);
513         av_log(avctx, AV_LOG_ERROR,
514             "Failed to start codec (status = %d) with format %s\n",
515             status, desc);
516         av_freep(&desc);
517         ret = AVERROR_EXTERNAL;
518         goto fail;
519     }
520
521     s->format = ff_AMediaCodec_getOutputFormat(s->codec);
522     if (s->format) {
523         if ((ret = mediacodec_dec_parse_format(avctx, s)) < 0) {
524             av_log(avctx, AV_LOG_ERROR,
525                 "Failed to configure context\n");
526             goto fail;
527         }
528     }
529
530     av_log(avctx, AV_LOG_DEBUG, "MediaCodec %p started successfully\n", s->codec);
531
532     return 0;
533
534 fail:
535     av_log(avctx, AV_LOG_ERROR, "MediaCodec %p failed to start\n", s->codec);
536     ff_mediacodec_dec_close(avctx, s);
537     return ret;
538 }
539
540 int ff_mediacodec_dec_send(AVCodecContext *avctx, MediaCodecDecContext *s,
541                            AVPacket *pkt)
542 {
543     int offset = 0;
544     int need_draining = 0;
545     uint8_t *data;
546     ssize_t index;
547     size_t size;
548     FFAMediaCodec *codec = s->codec;
549     int status;
550     int64_t input_dequeue_timeout_us = INPUT_DEQUEUE_TIMEOUT_US;
551
552     if (s->flushing) {
553         av_log(avctx, AV_LOG_ERROR, "Decoder is flushing and cannot accept new buffer "
554                                     "until all output buffers have been released\n");
555         return AVERROR_EXTERNAL;
556     }
557
558     if (pkt->size == 0) {
559         need_draining = 1;
560     }
561
562     if (s->draining && s->eos) {
563         return AVERROR_EOF;
564     }
565
566     while (offset < pkt->size || (need_draining && !s->draining)) {
567
568         index = ff_AMediaCodec_dequeueInputBuffer(codec, input_dequeue_timeout_us);
569         if (ff_AMediaCodec_infoTryAgainLater(codec, index)) {
570             av_log(avctx, AV_LOG_TRACE, "Failed to dequeue input buffer, try again later..\n");
571             break;
572         }
573
574         if (index < 0) {
575             av_log(avctx, AV_LOG_ERROR, "Failed to dequeue input buffer (status=%zd)\n", index);
576             return AVERROR_EXTERNAL;
577         }
578
579         data = ff_AMediaCodec_getInputBuffer(codec, index, &size);
580         if (!data) {
581             av_log(avctx, AV_LOG_ERROR, "Failed to get input buffer\n");
582             return AVERROR_EXTERNAL;
583         }
584
585         if (need_draining) {
586             int64_t pts = pkt->pts;
587             uint32_t flags = ff_AMediaCodec_getBufferFlagEndOfStream(codec);
588
589             if (s->surface) {
590                 pts = av_rescale_q(pts, avctx->pkt_timebase, av_make_q(1, 1000000));
591             }
592
593             av_log(avctx, AV_LOG_DEBUG, "Sending End Of Stream signal\n");
594
595             status = ff_AMediaCodec_queueInputBuffer(codec, index, 0, 0, pts, flags);
596             if (status < 0) {
597                 av_log(avctx, AV_LOG_ERROR, "Failed to queue input empty buffer (status = %d)\n", status);
598                 return AVERROR_EXTERNAL;
599             }
600
601             av_log(avctx, AV_LOG_TRACE, "Queued input buffer %zd"
602                     " size=%zd ts=%" PRIi64 "\n", index, size, pts);
603
604             s->draining = 1;
605             break;
606         } else {
607             int64_t pts = pkt->pts;
608
609             size = FFMIN(pkt->size - offset, size);
610             memcpy(data, pkt->data + offset, size);
611             offset += size;
612
613             if (avctx->pkt_timebase.num && avctx->pkt_timebase.den) {
614                 pts = av_rescale_q(pts, avctx->pkt_timebase, av_make_q(1, 1000000));
615             }
616
617             status = ff_AMediaCodec_queueInputBuffer(codec, index, 0, size, pts, 0);
618             if (status < 0) {
619                 av_log(avctx, AV_LOG_ERROR, "Failed to queue input buffer (status = %d)\n", status);
620                 return AVERROR_EXTERNAL;
621             }
622         }
623     }
624
625     if (offset == 0)
626         return AVERROR(EAGAIN);
627     return offset;
628 }
629
630 int ff_mediacodec_dec_receive(AVCodecContext *avctx, MediaCodecDecContext *s,
631                               AVFrame *frame, bool wait)
632 {
633     int ret;
634     uint8_t *data;
635     ssize_t index;
636     size_t size;
637     FFAMediaCodec *codec = s->codec;
638     FFAMediaCodecBufferInfo info = { 0 };
639     int status;
640     int64_t output_dequeue_timeout_us = OUTPUT_DEQUEUE_TIMEOUT_US;
641
642     if (s->draining && s->eos) {
643         return AVERROR_EOF;
644     }
645
646     if (s->draining) {
647         /* If the codec is flushing or need to be flushed, block for a fair
648          * amount of time to ensure we got a frame */
649         output_dequeue_timeout_us = OUTPUT_DEQUEUE_BLOCK_TIMEOUT_US;
650     } else if (s->output_buffer_count == 0 || !wait) {
651         /* If the codec hasn't produced any frames, do not block so we
652          * can push data to it as fast as possible, and get the first
653          * frame */
654         output_dequeue_timeout_us = 0;
655     }
656
657     index = ff_AMediaCodec_dequeueOutputBuffer(codec, &info, output_dequeue_timeout_us);
658     if (index >= 0) {
659         av_log(avctx, AV_LOG_TRACE, "Got output buffer %zd"
660                 " offset=%" PRIi32 " size=%" PRIi32 " ts=%" PRIi64
661                 " flags=%" PRIu32 "\n", index, info.offset, info.size,
662                 info.presentationTimeUs, info.flags);
663
664         if (info.flags & ff_AMediaCodec_getBufferFlagEndOfStream(codec)) {
665             s->eos = 1;
666         }
667
668         if (info.size) {
669             if (s->surface) {
670                 if ((ret = mediacodec_wrap_hw_buffer(avctx, s, index, &info, frame)) < 0) {
671                     av_log(avctx, AV_LOG_ERROR, "Failed to wrap MediaCodec buffer\n");
672                     return ret;
673                 }
674             } else {
675                 data = ff_AMediaCodec_getOutputBuffer(codec, index, &size);
676                 if (!data) {
677                     av_log(avctx, AV_LOG_ERROR, "Failed to get output buffer\n");
678                     return AVERROR_EXTERNAL;
679                 }
680
681                 if ((ret = mediacodec_wrap_sw_buffer(avctx, s, data, size, index, &info, frame)) < 0) {
682                     av_log(avctx, AV_LOG_ERROR, "Failed to wrap MediaCodec buffer\n");
683                     return ret;
684                 }
685             }
686
687             s->output_buffer_count++;
688             return 0;
689         } else {
690             status = ff_AMediaCodec_releaseOutputBuffer(codec, index, 0);
691             if (status < 0) {
692                 av_log(avctx, AV_LOG_ERROR, "Failed to release output buffer\n");
693             }
694         }
695
696     } else if (ff_AMediaCodec_infoOutputFormatChanged(codec, index)) {
697         char *format = NULL;
698
699         if (s->format) {
700             status = ff_AMediaFormat_delete(s->format);
701             if (status < 0) {
702                 av_log(avctx, AV_LOG_ERROR, "Failed to delete MediaFormat %p\n", s->format);
703             }
704         }
705
706         s->format = ff_AMediaCodec_getOutputFormat(codec);
707         if (!s->format) {
708             av_log(avctx, AV_LOG_ERROR, "Failed to get output format\n");
709             return AVERROR_EXTERNAL;
710         }
711
712         format = ff_AMediaFormat_toString(s->format);
713         if (!format) {
714             return AVERROR_EXTERNAL;
715         }
716         av_log(avctx, AV_LOG_INFO, "Output MediaFormat changed to %s\n", format);
717         av_freep(&format);
718
719         if ((ret = mediacodec_dec_parse_format(avctx, s)) < 0) {
720             return ret;
721         }
722
723     } else if (ff_AMediaCodec_infoOutputBuffersChanged(codec, index)) {
724         ff_AMediaCodec_cleanOutputBuffers(codec);
725     } else if (ff_AMediaCodec_infoTryAgainLater(codec, index)) {
726         if (s->draining) {
727             av_log(avctx, AV_LOG_ERROR, "Failed to dequeue output buffer within %" PRIi64 "ms "
728                                         "while draining remaining frames, output will probably lack frames\n",
729                                         output_dequeue_timeout_us / 1000);
730         } else {
731             av_log(avctx, AV_LOG_DEBUG, "No output buffer available, try again later\n");
732         }
733     } else {
734         av_log(avctx, AV_LOG_ERROR, "Failed to dequeue output buffer (status=%zd)\n", index);
735         return AVERROR_EXTERNAL;
736     }
737
738     return AVERROR(EAGAIN);
739 }
740
741 int ff_mediacodec_dec_flush(AVCodecContext *avctx, MediaCodecDecContext *s)
742 {
743     if (!s->surface || atomic_load(&s->refcount) == 1) {
744         int ret;
745
746         /* No frames (holding a reference to the codec) are retained by the
747          * user, thus we can flush the codec and returns accordingly */
748         if ((ret = mediacodec_dec_flush_codec(avctx, s)) < 0) {
749             return ret;
750         }
751
752         return 1;
753     }
754
755     s->flushing = 1;
756     return 0;
757 }
758
759 int ff_mediacodec_dec_close(AVCodecContext *avctx, MediaCodecDecContext *s)
760 {
761     ff_mediacodec_dec_unref(s);
762
763     return 0;
764 }
765
766 int ff_mediacodec_dec_is_flushing(AVCodecContext *avctx, MediaCodecDecContext *s)
767 {
768     return s->flushing;
769 }