You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

807 lines
27KB

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