]> git.sesse.net Git - ffmpeg/blob - libavcodec/mediacodecdec_common.c
Merge commit '83fef16b6a8dbbcbd80d159ba3ebe818dbbb2776'
[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         atomic_fetch_sub(&ctx->hw_buffer_count, 1);
183         av_log(ctx->avctx, AV_LOG_DEBUG,
184                "Releasing output buffer %zd (%p) ts=%"PRId64" on free() [%d pending]\n",
185                buffer->index, buffer, buffer->pts, atomic_load(&ctx->hw_buffer_count));
186         ff_AMediaCodec_releaseOutputBuffer(ctx->codec, buffer->index, 0);
187     }
188
189     if (ctx->delay_flush)
190         ff_mediacodec_dec_unref(ctx);
191     av_freep(&buffer);
192 }
193
194 static int mediacodec_wrap_hw_buffer(AVCodecContext *avctx,
195                                   MediaCodecDecContext *s,
196                                   ssize_t index,
197                                   FFAMediaCodecBufferInfo *info,
198                                   AVFrame *frame)
199 {
200     int ret = 0;
201     int status = 0;
202     AVMediaCodecBuffer *buffer = NULL;
203
204     frame->buf[0] = NULL;
205     frame->width = avctx->width;
206     frame->height = avctx->height;
207     frame->format = avctx->pix_fmt;
208
209     if (avctx->pkt_timebase.num && avctx->pkt_timebase.den) {
210         frame->pts = av_rescale_q(info->presentationTimeUs,
211                                       av_make_q(1, 1000000),
212                                       avctx->pkt_timebase);
213     } else {
214         frame->pts = info->presentationTimeUs;
215     }
216 #if FF_API_PKT_PTS
217 FF_DISABLE_DEPRECATION_WARNINGS
218     frame->pkt_pts = frame->pts;
219 FF_ENABLE_DEPRECATION_WARNINGS
220 #endif
221     frame->pkt_dts = AV_NOPTS_VALUE;
222
223     buffer = av_mallocz(sizeof(AVMediaCodecBuffer));
224     if (!buffer) {
225         ret = AVERROR(ENOMEM);
226         goto fail;
227     }
228
229     atomic_init(&buffer->released, 0);
230
231     frame->buf[0] = av_buffer_create(NULL,
232                                      0,
233                                      mediacodec_buffer_release,
234                                      buffer,
235                                      AV_BUFFER_FLAG_READONLY);
236
237     if (!frame->buf[0]) {
238         ret = AVERROR(ENOMEM);
239         goto fail;
240
241     }
242
243     buffer->ctx = s;
244     buffer->serial = atomic_load(&s->serial);
245     if (s->delay_flush)
246         ff_mediacodec_dec_ref(s);
247
248     buffer->index = index;
249     buffer->pts = info->presentationTimeUs;
250
251     frame->data[3] = (uint8_t *)buffer;
252
253     atomic_fetch_add(&s->hw_buffer_count, 1);
254     av_log(avctx, AV_LOG_DEBUG,
255             "Wrapping output buffer %zd (%p) ts=%"PRId64" [%d pending]\n",
256             buffer->index, buffer, buffer->pts, atomic_load(&s->hw_buffer_count));
257
258     return 0;
259 fail:
260     av_freep(buffer);
261     av_buffer_unref(&frame->buf[0]);
262     status = ff_AMediaCodec_releaseOutputBuffer(s->codec, index, 0);
263     if (status < 0) {
264         av_log(avctx, AV_LOG_ERROR, "Failed to release output buffer\n");
265         ret = AVERROR_EXTERNAL;
266     }
267
268     return ret;
269 }
270
271 static int mediacodec_wrap_sw_buffer(AVCodecContext *avctx,
272                                   MediaCodecDecContext *s,
273                                   uint8_t *data,
274                                   size_t size,
275                                   ssize_t index,
276                                   FFAMediaCodecBufferInfo *info,
277                                   AVFrame *frame)
278 {
279     int ret = 0;
280     int status = 0;
281
282     frame->width = avctx->width;
283     frame->height = avctx->height;
284     frame->format = avctx->pix_fmt;
285
286     /* MediaCodec buffers needs to be copied to our own refcounted buffers
287      * because the flush command invalidates all input and output buffers.
288      */
289     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
290         av_log(avctx, AV_LOG_ERROR, "Could not allocate buffer\n");
291         goto done;
292     }
293
294     /* Override frame->pkt_pts as ff_get_buffer will override its value based
295      * on the last avpacket received which is not in sync with the frame:
296      *   * N avpackets can be pushed before 1 frame is actually returned
297      *   * 0-sized avpackets are pushed to flush remaining frames at EOS */
298     if (avctx->pkt_timebase.num && avctx->pkt_timebase.den) {
299         frame->pts = av_rescale_q(info->presentationTimeUs,
300                                       av_make_q(1, 1000000),
301                                       avctx->pkt_timebase);
302     } else {
303         frame->pts = info->presentationTimeUs;
304     }
305 #if FF_API_PKT_PTS
306 FF_DISABLE_DEPRECATION_WARNINGS
307     frame->pkt_pts = frame->pts;
308 FF_ENABLE_DEPRECATION_WARNINGS
309 #endif
310     frame->pkt_dts = AV_NOPTS_VALUE;
311
312     av_log(avctx, AV_LOG_TRACE,
313             "Frame: width=%d stride=%d height=%d slice-height=%d "
314             "crop-top=%d crop-bottom=%d crop-left=%d crop-right=%d encoder=%s\n"
315             "destination linesizes=%d,%d,%d\n" ,
316             avctx->width, s->stride, avctx->height, s->slice_height,
317             s->crop_top, s->crop_bottom, s->crop_left, s->crop_right, s->codec_name,
318             frame->linesize[0], frame->linesize[1], frame->linesize[2]);
319
320     switch (s->color_format) {
321     case COLOR_FormatYUV420Planar:
322         ff_mediacodec_sw_buffer_copy_yuv420_planar(avctx, s, data, size, info, frame);
323         break;
324     case COLOR_FormatYUV420SemiPlanar:
325     case COLOR_QCOM_FormatYUV420SemiPlanar:
326     case COLOR_QCOM_FormatYUV420SemiPlanar32m:
327         ff_mediacodec_sw_buffer_copy_yuv420_semi_planar(avctx, s, data, size, info, frame);
328         break;
329     case COLOR_TI_FormatYUV420PackedSemiPlanar:
330     case COLOR_TI_FormatYUV420PackedSemiPlanarInterlaced:
331         ff_mediacodec_sw_buffer_copy_yuv420_packed_semi_planar(avctx, s, data, size, info, frame);
332         break;
333     case COLOR_QCOM_FormatYUV420PackedSemiPlanar64x32Tile2m8ka:
334         ff_mediacodec_sw_buffer_copy_yuv420_packed_semi_planar_64x32Tile2m8ka(avctx, s, data, size, info, frame);
335         break;
336     default:
337         av_log(avctx, AV_LOG_ERROR, "Unsupported color format 0x%x (value=%d)\n",
338             s->color_format, s->color_format);
339         ret = AVERROR(EINVAL);
340         goto done;
341     }
342
343     ret = 0;
344 done:
345     status = ff_AMediaCodec_releaseOutputBuffer(s->codec, index, 0);
346     if (status < 0) {
347         av_log(avctx, AV_LOG_ERROR, "Failed to release output buffer\n");
348         ret = AVERROR_EXTERNAL;
349     }
350
351     return ret;
352 }
353
354 #define AMEDIAFORMAT_GET_INT32(name, key, mandatory) do {                              \
355     int32_t value = 0;                                                                 \
356     if (ff_AMediaFormat_getInt32(s->format, key, &value)) {                            \
357         (name) = value;                                                                \
358     } else if (mandatory) {                                                            \
359         av_log(avctx, AV_LOG_ERROR, "Could not get %s from format %s\n", key, format); \
360         ret = AVERROR_EXTERNAL;                                                        \
361         goto fail;                                                                     \
362     }                                                                                  \
363 } while (0)                                                                            \
364
365 static int mediacodec_dec_parse_format(AVCodecContext *avctx, MediaCodecDecContext *s)
366 {
367     int ret = 0;
368     int width = 0;
369     int height = 0;
370     char *format = NULL;
371
372     if (!s->format) {
373         av_log(avctx, AV_LOG_ERROR, "Output MediaFormat is not set\n");
374         return AVERROR(EINVAL);
375     }
376
377     format = ff_AMediaFormat_toString(s->format);
378     if (!format) {
379         return AVERROR_EXTERNAL;
380     }
381     av_log(avctx, AV_LOG_DEBUG, "Parsing MediaFormat %s\n", format);
382
383     /* Mandatory fields */
384     AMEDIAFORMAT_GET_INT32(s->width,  "width", 1);
385     AMEDIAFORMAT_GET_INT32(s->height, "height", 1);
386
387     AMEDIAFORMAT_GET_INT32(s->stride, "stride", 1);
388     s->stride = s->stride > 0 ? s->stride : s->width;
389
390     AMEDIAFORMAT_GET_INT32(s->slice_height, "slice-height", 1);
391     s->slice_height = s->slice_height > 0 ? s->slice_height : s->height;
392
393     if (strstr(s->codec_name, "OMX.Nvidia.")) {
394         s->slice_height = FFALIGN(s->height, 16);
395     } else if (strstr(s->codec_name, "OMX.SEC.avc.dec")) {
396         s->slice_height = avctx->height;
397         s->stride = avctx->width;
398     }
399
400     AMEDIAFORMAT_GET_INT32(s->color_format, "color-format", 1);
401     avctx->pix_fmt = mcdec_map_color_format(avctx, s, s->color_format);
402     if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
403         av_log(avctx, AV_LOG_ERROR, "Output color format is not supported\n");
404         ret = AVERROR(EINVAL);
405         goto fail;
406     }
407
408     /* Optional fields */
409     AMEDIAFORMAT_GET_INT32(s->crop_top,    "crop-top",    0);
410     AMEDIAFORMAT_GET_INT32(s->crop_bottom, "crop-bottom", 0);
411     AMEDIAFORMAT_GET_INT32(s->crop_left,   "crop-left",   0);
412     AMEDIAFORMAT_GET_INT32(s->crop_right,  "crop-right",  0);
413
414     width = s->crop_right + 1 - s->crop_left;
415     height = s->crop_bottom + 1 - s->crop_top;
416
417     av_log(avctx, AV_LOG_INFO,
418         "Output crop parameters top=%d bottom=%d left=%d right=%d, "
419         "resulting dimensions width=%d height=%d\n",
420         s->crop_top, s->crop_bottom, s->crop_left, s->crop_right,
421         width, height);
422
423     av_freep(&format);
424     return ff_set_dimensions(avctx, width, height);
425 fail:
426     av_freep(&format);
427     return ret;
428 }
429
430 static int mediacodec_dec_flush_codec(AVCodecContext *avctx, MediaCodecDecContext *s)
431 {
432     FFAMediaCodec *codec = s->codec;
433     int status;
434
435     s->output_buffer_count = 0;
436
437     s->draining = 0;
438     s->flushing = 0;
439     s->eos = 0;
440     atomic_fetch_add(&s->serial, 1);
441     atomic_init(&s->hw_buffer_count, 0);
442
443     status = ff_AMediaCodec_flush(codec);
444     if (status < 0) {
445         av_log(avctx, AV_LOG_ERROR, "Failed to flush codec\n");
446         return AVERROR_EXTERNAL;
447     }
448
449     return 0;
450 }
451
452 int ff_mediacodec_dec_init(AVCodecContext *avctx, MediaCodecDecContext *s,
453                            const char *mime, FFAMediaFormat *format)
454 {
455     int ret = 0;
456     int status;
457     int profile;
458
459     enum AVPixelFormat pix_fmt;
460     static const enum AVPixelFormat pix_fmts[] = {
461         AV_PIX_FMT_MEDIACODEC,
462         AV_PIX_FMT_NONE,
463     };
464
465     s->avctx = avctx;
466     atomic_init(&s->refcount, 1);
467     atomic_init(&s->hw_buffer_count, 0);
468     atomic_init(&s->serial, 1);
469
470     pix_fmt = ff_get_format(avctx, pix_fmts);
471     if (pix_fmt == AV_PIX_FMT_MEDIACODEC) {
472         AVMediaCodecContext *user_ctx = avctx->hwaccel_context;
473
474         if (avctx->hw_device_ctx) {
475             AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)(avctx->hw_device_ctx->data);
476             if (device_ctx->type == AV_HWDEVICE_TYPE_MEDIACODEC) {
477                 if (device_ctx->hwctx) {
478                     AVMediaCodecDeviceContext *mediacodec_ctx = (AVMediaCodecDeviceContext *)device_ctx->hwctx;
479                     s->surface = ff_mediacodec_surface_ref(mediacodec_ctx->surface, avctx);
480                     av_log(avctx, AV_LOG_INFO, "Using surface %p\n", s->surface);
481                 }
482             }
483         }
484
485         if (!s->surface && user_ctx && user_ctx->surface) {
486             s->surface = ff_mediacodec_surface_ref(user_ctx->surface, avctx);
487             av_log(avctx, AV_LOG_INFO, "Using surface %p\n", s->surface);
488         }
489     }
490
491     profile = ff_AMediaCodecProfile_getProfileFromAVCodecContext(avctx);
492     if (profile < 0) {
493         av_log(avctx, AV_LOG_WARNING, "Unsupported or unknown profile\n");
494     }
495
496     s->codec_name = ff_AMediaCodecList_getCodecNameByType(mime, profile, 0, avctx);
497     if (!s->codec_name) {
498         ret = AVERROR_EXTERNAL;
499         goto fail;
500     }
501
502     av_log(avctx, AV_LOG_DEBUG, "Found decoder %s\n", s->codec_name);
503     s->codec = ff_AMediaCodec_createCodecByName(s->codec_name);
504     if (!s->codec) {
505         av_log(avctx, AV_LOG_ERROR, "Failed to create media decoder for type %s and name %s\n", mime, s->codec_name);
506         ret = AVERROR_EXTERNAL;
507         goto fail;
508     }
509
510     status = ff_AMediaCodec_configure(s->codec, format, s->surface, NULL, 0);
511     if (status < 0) {
512         char *desc = ff_AMediaFormat_toString(format);
513         av_log(avctx, AV_LOG_ERROR,
514             "Failed to configure codec (status = %d) with format %s\n",
515             status, desc);
516         av_freep(&desc);
517
518         ret = AVERROR_EXTERNAL;
519         goto fail;
520     }
521
522     status = ff_AMediaCodec_start(s->codec);
523     if (status < 0) {
524         char *desc = ff_AMediaFormat_toString(format);
525         av_log(avctx, AV_LOG_ERROR,
526             "Failed to start codec (status = %d) with format %s\n",
527             status, desc);
528         av_freep(&desc);
529         ret = AVERROR_EXTERNAL;
530         goto fail;
531     }
532
533     s->format = ff_AMediaCodec_getOutputFormat(s->codec);
534     if (s->format) {
535         if ((ret = mediacodec_dec_parse_format(avctx, s)) < 0) {
536             av_log(avctx, AV_LOG_ERROR,
537                 "Failed to configure context\n");
538             goto fail;
539         }
540     }
541
542     av_log(avctx, AV_LOG_DEBUG, "MediaCodec %p started successfully\n", s->codec);
543
544     return 0;
545
546 fail:
547     av_log(avctx, AV_LOG_ERROR, "MediaCodec %p failed to start\n", s->codec);
548     ff_mediacodec_dec_close(avctx, s);
549     return ret;
550 }
551
552 int ff_mediacodec_dec_send(AVCodecContext *avctx, MediaCodecDecContext *s,
553                            AVPacket *pkt)
554 {
555     int offset = 0;
556     int need_draining = 0;
557     uint8_t *data;
558     ssize_t index;
559     size_t size;
560     FFAMediaCodec *codec = s->codec;
561     int status;
562     int64_t input_dequeue_timeout_us = INPUT_DEQUEUE_TIMEOUT_US;
563
564     if (s->flushing) {
565         av_log(avctx, AV_LOG_ERROR, "Decoder is flushing and cannot accept new buffer "
566                                     "until all output buffers have been released\n");
567         return AVERROR_EXTERNAL;
568     }
569
570     if (pkt->size == 0) {
571         need_draining = 1;
572     }
573
574     if (s->draining && s->eos) {
575         return AVERROR_EOF;
576     }
577
578     while (offset < pkt->size || (need_draining && !s->draining)) {
579
580         index = ff_AMediaCodec_dequeueInputBuffer(codec, input_dequeue_timeout_us);
581         if (ff_AMediaCodec_infoTryAgainLater(codec, index)) {
582             av_log(avctx, AV_LOG_TRACE, "No input buffer available, try again later\n");
583             break;
584         }
585
586         if (index < 0) {
587             av_log(avctx, AV_LOG_ERROR, "Failed to dequeue input buffer (status=%zd)\n", index);
588             return AVERROR_EXTERNAL;
589         }
590
591         data = ff_AMediaCodec_getInputBuffer(codec, index, &size);
592         if (!data) {
593             av_log(avctx, AV_LOG_ERROR, "Failed to get input buffer\n");
594             return AVERROR_EXTERNAL;
595         }
596
597         if (need_draining) {
598             int64_t pts = pkt->pts;
599             uint32_t flags = ff_AMediaCodec_getBufferFlagEndOfStream(codec);
600
601             if (s->surface) {
602                 pts = av_rescale_q(pts, avctx->pkt_timebase, av_make_q(1, 1000000));
603             }
604
605             av_log(avctx, AV_LOG_DEBUG, "Sending End Of Stream signal\n");
606
607             status = ff_AMediaCodec_queueInputBuffer(codec, index, 0, 0, pts, flags);
608             if (status < 0) {
609                 av_log(avctx, AV_LOG_ERROR, "Failed to queue input empty buffer (status = %d)\n", status);
610                 return AVERROR_EXTERNAL;
611             }
612
613             av_log(avctx, AV_LOG_TRACE,
614                    "Queued input buffer %zd size=%zd ts=%"PRIi64"\n", index, size, pts);
615
616             s->draining = 1;
617             break;
618         } else {
619             int64_t pts = pkt->pts;
620
621             size = FFMIN(pkt->size - offset, size);
622             memcpy(data, pkt->data + offset, size);
623             offset += size;
624
625             if (avctx->pkt_timebase.num && avctx->pkt_timebase.den) {
626                 pts = av_rescale_q(pts, avctx->pkt_timebase, av_make_q(1, 1000000));
627             }
628
629             status = ff_AMediaCodec_queueInputBuffer(codec, index, 0, size, pts, 0);
630             if (status < 0) {
631                 av_log(avctx, AV_LOG_ERROR, "Failed to queue input buffer (status = %d)\n", status);
632                 return AVERROR_EXTERNAL;
633             }
634
635             av_log(avctx, AV_LOG_TRACE,
636                    "Queued input buffer %zd size=%zd ts=%"PRIi64"\n", index, size, pts);
637         }
638     }
639
640     if (offset == 0)
641         return AVERROR(EAGAIN);
642     return offset;
643 }
644
645 int ff_mediacodec_dec_receive(AVCodecContext *avctx, MediaCodecDecContext *s,
646                               AVFrame *frame, bool wait)
647 {
648     int ret;
649     uint8_t *data;
650     ssize_t index;
651     size_t size;
652     FFAMediaCodec *codec = s->codec;
653     FFAMediaCodecBufferInfo info = { 0 };
654     int status;
655     int64_t output_dequeue_timeout_us = OUTPUT_DEQUEUE_TIMEOUT_US;
656
657     if (s->draining && s->eos) {
658         return AVERROR_EOF;
659     }
660
661     if (s->draining) {
662         /* If the codec is flushing or need to be flushed, block for a fair
663          * amount of time to ensure we got a frame */
664         output_dequeue_timeout_us = OUTPUT_DEQUEUE_BLOCK_TIMEOUT_US;
665     } else if (s->output_buffer_count == 0 || !wait) {
666         /* If the codec hasn't produced any frames, do not block so we
667          * can push data to it as fast as possible, and get the first
668          * frame */
669         output_dequeue_timeout_us = 0;
670     }
671
672     index = ff_AMediaCodec_dequeueOutputBuffer(codec, &info, output_dequeue_timeout_us);
673     if (index >= 0) {
674         av_log(avctx, AV_LOG_TRACE, "Got output buffer %zd"
675                 " offset=%" PRIi32 " size=%" PRIi32 " ts=%" PRIi64
676                 " flags=%" PRIu32 "\n", index, info.offset, info.size,
677                 info.presentationTimeUs, info.flags);
678
679         if (info.flags & ff_AMediaCodec_getBufferFlagEndOfStream(codec)) {
680             s->eos = 1;
681         }
682
683         if (info.size) {
684             if (s->surface) {
685                 if ((ret = mediacodec_wrap_hw_buffer(avctx, s, index, &info, frame)) < 0) {
686                     av_log(avctx, AV_LOG_ERROR, "Failed to wrap MediaCodec buffer\n");
687                     return ret;
688                 }
689             } else {
690                 data = ff_AMediaCodec_getOutputBuffer(codec, index, &size);
691                 if (!data) {
692                     av_log(avctx, AV_LOG_ERROR, "Failed to get output buffer\n");
693                     return AVERROR_EXTERNAL;
694                 }
695
696                 if ((ret = mediacodec_wrap_sw_buffer(avctx, s, data, size, index, &info, frame)) < 0) {
697                     av_log(avctx, AV_LOG_ERROR, "Failed to wrap MediaCodec buffer\n");
698                     return ret;
699                 }
700             }
701
702             s->output_buffer_count++;
703             return 0;
704         } else {
705             status = ff_AMediaCodec_releaseOutputBuffer(codec, index, 0);
706             if (status < 0) {
707                 av_log(avctx, AV_LOG_ERROR, "Failed to release output buffer\n");
708             }
709         }
710
711     } else if (ff_AMediaCodec_infoOutputFormatChanged(codec, index)) {
712         char *format = NULL;
713
714         if (s->format) {
715             status = ff_AMediaFormat_delete(s->format);
716             if (status < 0) {
717                 av_log(avctx, AV_LOG_ERROR, "Failed to delete MediaFormat %p\n", s->format);
718             }
719         }
720
721         s->format = ff_AMediaCodec_getOutputFormat(codec);
722         if (!s->format) {
723             av_log(avctx, AV_LOG_ERROR, "Failed to get output format\n");
724             return AVERROR_EXTERNAL;
725         }
726
727         format = ff_AMediaFormat_toString(s->format);
728         if (!format) {
729             return AVERROR_EXTERNAL;
730         }
731         av_log(avctx, AV_LOG_INFO, "Output MediaFormat changed to %s\n", format);
732         av_freep(&format);
733
734         if ((ret = mediacodec_dec_parse_format(avctx, s)) < 0) {
735             return ret;
736         }
737
738     } else if (ff_AMediaCodec_infoOutputBuffersChanged(codec, index)) {
739         ff_AMediaCodec_cleanOutputBuffers(codec);
740     } else if (ff_AMediaCodec_infoTryAgainLater(codec, index)) {
741         if (s->draining) {
742             av_log(avctx, AV_LOG_ERROR, "Failed to dequeue output buffer within %" PRIi64 "ms "
743                                         "while draining remaining frames, output will probably lack frames\n",
744                                         output_dequeue_timeout_us / 1000);
745         } else {
746             av_log(avctx, AV_LOG_TRACE, "No output buffer available, try again later\n");
747         }
748     } else {
749         av_log(avctx, AV_LOG_ERROR, "Failed to dequeue output buffer (status=%zd)\n", index);
750         return AVERROR_EXTERNAL;
751     }
752
753     return AVERROR(EAGAIN);
754 }
755
756 int ff_mediacodec_dec_flush(AVCodecContext *avctx, MediaCodecDecContext *s)
757 {
758     if (!s->surface || atomic_load(&s->refcount) == 1) {
759         int ret;
760
761         /* No frames (holding a reference to the codec) are retained by the
762          * user, thus we can flush the codec and returns accordingly */
763         if ((ret = mediacodec_dec_flush_codec(avctx, s)) < 0) {
764             return ret;
765         }
766
767         return 1;
768     }
769
770     s->flushing = 1;
771     return 0;
772 }
773
774 int ff_mediacodec_dec_close(AVCodecContext *avctx, MediaCodecDecContext *s)
775 {
776     ff_mediacodec_dec_unref(s);
777
778     return 0;
779 }
780
781 int ff_mediacodec_dec_is_flushing(AVCodecContext *avctx, MediaCodecDecContext *s)
782 {
783     return s->flushing;
784 }