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