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