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.

912 lines
30KB

  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_RANGE_FULL = 0x1,
  83. COLOR_RANGE_LIMITED = 0x2,
  84. };
  85. static enum AVColorRange mcdec_get_color_range(int color_range)
  86. {
  87. switch (color_range) {
  88. case COLOR_RANGE_FULL:
  89. return AVCOL_RANGE_JPEG;
  90. case COLOR_RANGE_LIMITED:
  91. return AVCOL_RANGE_MPEG;
  92. default:
  93. return AVCOL_RANGE_UNSPECIFIED;
  94. }
  95. }
  96. enum {
  97. COLOR_STANDARD_BT709 = 0x1,
  98. COLOR_STANDARD_BT601_PAL = 0x2,
  99. COLOR_STANDARD_BT601_NTSC = 0x4,
  100. COLOR_STANDARD_BT2020 = 0x6,
  101. };
  102. static enum AVColorSpace mcdec_get_color_space(int color_standard)
  103. {
  104. switch (color_standard) {
  105. case COLOR_STANDARD_BT709:
  106. return AVCOL_SPC_BT709;
  107. case COLOR_STANDARD_BT601_PAL:
  108. return AVCOL_SPC_BT470BG;
  109. case COLOR_STANDARD_BT601_NTSC:
  110. return AVCOL_SPC_SMPTE170M;
  111. case COLOR_STANDARD_BT2020:
  112. return AVCOL_SPC_BT2020_NCL;
  113. default:
  114. return AVCOL_SPC_UNSPECIFIED;
  115. }
  116. }
  117. static enum AVColorPrimaries mcdec_get_color_pri(int color_standard)
  118. {
  119. switch (color_standard) {
  120. case COLOR_STANDARD_BT709:
  121. return AVCOL_PRI_BT709;
  122. case COLOR_STANDARD_BT601_PAL:
  123. return AVCOL_PRI_BT470BG;
  124. case COLOR_STANDARD_BT601_NTSC:
  125. return AVCOL_PRI_SMPTE170M;
  126. case COLOR_STANDARD_BT2020:
  127. return AVCOL_PRI_BT2020;
  128. default:
  129. return AVCOL_PRI_UNSPECIFIED;
  130. }
  131. }
  132. enum {
  133. COLOR_TRANSFER_LINEAR = 0x1,
  134. COLOR_TRANSFER_SDR_VIDEO = 0x3,
  135. COLOR_TRANSFER_ST2084 = 0x6,
  136. COLOR_TRANSFER_HLG = 0x7,
  137. };
  138. static enum AVColorTransferCharacteristic mcdec_get_color_trc(int color_transfer)
  139. {
  140. switch (color_transfer) {
  141. case COLOR_TRANSFER_LINEAR:
  142. return AVCOL_TRC_LINEAR;
  143. case COLOR_TRANSFER_SDR_VIDEO:
  144. return AVCOL_TRC_SMPTE170M;
  145. case COLOR_TRANSFER_ST2084:
  146. return AVCOL_TRC_SMPTEST2084;
  147. case COLOR_TRANSFER_HLG:
  148. return AVCOL_TRC_ARIB_STD_B67;
  149. default:
  150. return AVCOL_TRC_UNSPECIFIED;
  151. }
  152. }
  153. enum {
  154. COLOR_FormatYUV420Planar = 0x13,
  155. COLOR_FormatYUV420SemiPlanar = 0x15,
  156. COLOR_FormatYCbYCr = 0x19,
  157. COLOR_FormatAndroidOpaque = 0x7F000789,
  158. COLOR_QCOM_FormatYUV420SemiPlanar = 0x7fa30c00,
  159. COLOR_QCOM_FormatYUV420SemiPlanar32m = 0x7fa30c04,
  160. COLOR_QCOM_FormatYUV420PackedSemiPlanar64x32Tile2m8ka = 0x7fa30c03,
  161. COLOR_TI_FormatYUV420PackedSemiPlanar = 0x7f000100,
  162. COLOR_TI_FormatYUV420PackedSemiPlanarInterlaced = 0x7f000001,
  163. };
  164. static const struct {
  165. int color_format;
  166. enum AVPixelFormat pix_fmt;
  167. } color_formats[] = {
  168. { COLOR_FormatYUV420Planar, AV_PIX_FMT_YUV420P },
  169. { COLOR_FormatYUV420SemiPlanar, AV_PIX_FMT_NV12 },
  170. { COLOR_QCOM_FormatYUV420SemiPlanar, AV_PIX_FMT_NV12 },
  171. { COLOR_QCOM_FormatYUV420SemiPlanar32m, AV_PIX_FMT_NV12 },
  172. { COLOR_QCOM_FormatYUV420PackedSemiPlanar64x32Tile2m8ka, AV_PIX_FMT_NV12 },
  173. { COLOR_TI_FormatYUV420PackedSemiPlanar, AV_PIX_FMT_NV12 },
  174. { COLOR_TI_FormatYUV420PackedSemiPlanarInterlaced, AV_PIX_FMT_NV12 },
  175. { 0 }
  176. };
  177. static enum AVPixelFormat mcdec_map_color_format(AVCodecContext *avctx,
  178. MediaCodecDecContext *s,
  179. int color_format)
  180. {
  181. int i;
  182. enum AVPixelFormat ret = AV_PIX_FMT_NONE;
  183. if (s->surface) {
  184. return AV_PIX_FMT_MEDIACODEC;
  185. }
  186. if (!strcmp(s->codec_name, "OMX.k3.video.decoder.avc") && color_format == COLOR_FormatYCbYCr) {
  187. s->color_format = color_format = COLOR_TI_FormatYUV420PackedSemiPlanar;
  188. }
  189. for (i = 0; i < FF_ARRAY_ELEMS(color_formats); i++) {
  190. if (color_formats[i].color_format == color_format) {
  191. return color_formats[i].pix_fmt;
  192. }
  193. }
  194. av_log(avctx, AV_LOG_ERROR, "Output color format 0x%x (value=%d) is not supported\n",
  195. color_format, color_format);
  196. return ret;
  197. }
  198. static void ff_mediacodec_dec_ref(MediaCodecDecContext *s)
  199. {
  200. atomic_fetch_add(&s->refcount, 1);
  201. }
  202. static void ff_mediacodec_dec_unref(MediaCodecDecContext *s)
  203. {
  204. if (!s)
  205. return;
  206. if (atomic_fetch_sub(&s->refcount, 1) == 1) {
  207. if (s->codec) {
  208. ff_AMediaCodec_delete(s->codec);
  209. s->codec = NULL;
  210. }
  211. if (s->format) {
  212. ff_AMediaFormat_delete(s->format);
  213. s->format = NULL;
  214. }
  215. if (s->surface) {
  216. ff_mediacodec_surface_unref(s->surface, NULL);
  217. s->surface = NULL;
  218. }
  219. av_freep(&s->codec_name);
  220. av_freep(&s);
  221. }
  222. }
  223. static void mediacodec_buffer_release(void *opaque, uint8_t *data)
  224. {
  225. AVMediaCodecBuffer *buffer = opaque;
  226. MediaCodecDecContext *ctx = buffer->ctx;
  227. int released = atomic_load(&buffer->released);
  228. if (!released && (ctx->delay_flush || buffer->serial == atomic_load(&ctx->serial))) {
  229. atomic_fetch_sub(&ctx->hw_buffer_count, 1);
  230. av_log(ctx->avctx, AV_LOG_DEBUG,
  231. "Releasing output buffer %zd (%p) ts=%"PRId64" on free() [%d pending]\n",
  232. buffer->index, buffer, buffer->pts, atomic_load(&ctx->hw_buffer_count));
  233. ff_AMediaCodec_releaseOutputBuffer(ctx->codec, buffer->index, 0);
  234. }
  235. if (ctx->delay_flush)
  236. ff_mediacodec_dec_unref(ctx);
  237. av_freep(&buffer);
  238. }
  239. static int mediacodec_wrap_hw_buffer(AVCodecContext *avctx,
  240. MediaCodecDecContext *s,
  241. ssize_t index,
  242. FFAMediaCodecBufferInfo *info,
  243. AVFrame *frame)
  244. {
  245. int ret = 0;
  246. int status = 0;
  247. AVMediaCodecBuffer *buffer = NULL;
  248. frame->buf[0] = NULL;
  249. frame->width = avctx->width;
  250. frame->height = avctx->height;
  251. frame->format = avctx->pix_fmt;
  252. frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
  253. if (avctx->pkt_timebase.num && avctx->pkt_timebase.den) {
  254. frame->pts = av_rescale_q(info->presentationTimeUs,
  255. AV_TIME_BASE_Q,
  256. avctx->pkt_timebase);
  257. } else {
  258. frame->pts = info->presentationTimeUs;
  259. }
  260. #if FF_API_PKT_PTS
  261. FF_DISABLE_DEPRECATION_WARNINGS
  262. frame->pkt_pts = frame->pts;
  263. FF_ENABLE_DEPRECATION_WARNINGS
  264. #endif
  265. frame->pkt_dts = AV_NOPTS_VALUE;
  266. frame->color_range = avctx->color_range;
  267. frame->color_primaries = avctx->color_primaries;
  268. frame->color_trc = avctx->color_trc;
  269. frame->colorspace = avctx->colorspace;
  270. buffer = av_mallocz(sizeof(AVMediaCodecBuffer));
  271. if (!buffer) {
  272. ret = AVERROR(ENOMEM);
  273. goto fail;
  274. }
  275. atomic_init(&buffer->released, 0);
  276. frame->buf[0] = av_buffer_create(NULL,
  277. 0,
  278. mediacodec_buffer_release,
  279. buffer,
  280. AV_BUFFER_FLAG_READONLY);
  281. if (!frame->buf[0]) {
  282. ret = AVERROR(ENOMEM);
  283. goto fail;
  284. }
  285. buffer->ctx = s;
  286. buffer->serial = atomic_load(&s->serial);
  287. if (s->delay_flush)
  288. ff_mediacodec_dec_ref(s);
  289. buffer->index = index;
  290. buffer->pts = info->presentationTimeUs;
  291. frame->data[3] = (uint8_t *)buffer;
  292. atomic_fetch_add(&s->hw_buffer_count, 1);
  293. av_log(avctx, AV_LOG_DEBUG,
  294. "Wrapping output buffer %zd (%p) ts=%"PRId64" [%d pending]\n",
  295. buffer->index, buffer, buffer->pts, atomic_load(&s->hw_buffer_count));
  296. return 0;
  297. fail:
  298. av_freep(buffer);
  299. av_buffer_unref(&frame->buf[0]);
  300. status = ff_AMediaCodec_releaseOutputBuffer(s->codec, index, 0);
  301. if (status < 0) {
  302. av_log(avctx, AV_LOG_ERROR, "Failed to release output buffer\n");
  303. ret = AVERROR_EXTERNAL;
  304. }
  305. return ret;
  306. }
  307. static int mediacodec_wrap_sw_buffer(AVCodecContext *avctx,
  308. MediaCodecDecContext *s,
  309. uint8_t *data,
  310. size_t size,
  311. ssize_t index,
  312. FFAMediaCodecBufferInfo *info,
  313. AVFrame *frame)
  314. {
  315. int ret = 0;
  316. int status = 0;
  317. frame->width = avctx->width;
  318. frame->height = avctx->height;
  319. frame->format = avctx->pix_fmt;
  320. /* MediaCodec buffers needs to be copied to our own refcounted buffers
  321. * because the flush command invalidates all input and output buffers.
  322. */
  323. if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
  324. av_log(avctx, AV_LOG_ERROR, "Could not allocate buffer\n");
  325. goto done;
  326. }
  327. /* Override frame->pkt_pts as ff_get_buffer will override its value based
  328. * on the last avpacket received which is not in sync with the frame:
  329. * * N avpackets can be pushed before 1 frame is actually returned
  330. * * 0-sized avpackets are pushed to flush remaining frames at EOS */
  331. if (avctx->pkt_timebase.num && avctx->pkt_timebase.den) {
  332. frame->pts = av_rescale_q(info->presentationTimeUs,
  333. AV_TIME_BASE_Q,
  334. avctx->pkt_timebase);
  335. } else {
  336. frame->pts = info->presentationTimeUs;
  337. }
  338. #if FF_API_PKT_PTS
  339. FF_DISABLE_DEPRECATION_WARNINGS
  340. frame->pkt_pts = frame->pts;
  341. FF_ENABLE_DEPRECATION_WARNINGS
  342. #endif
  343. frame->pkt_dts = AV_NOPTS_VALUE;
  344. av_log(avctx, AV_LOG_TRACE,
  345. "Frame: width=%d stride=%d height=%d slice-height=%d "
  346. "crop-top=%d crop-bottom=%d crop-left=%d crop-right=%d encoder=%s "
  347. "destination linesizes=%d,%d,%d\n" ,
  348. avctx->width, s->stride, avctx->height, s->slice_height,
  349. s->crop_top, s->crop_bottom, s->crop_left, s->crop_right, s->codec_name,
  350. frame->linesize[0], frame->linesize[1], frame->linesize[2]);
  351. switch (s->color_format) {
  352. case COLOR_FormatYUV420Planar:
  353. ff_mediacodec_sw_buffer_copy_yuv420_planar(avctx, s, data, size, info, frame);
  354. break;
  355. case COLOR_FormatYUV420SemiPlanar:
  356. case COLOR_QCOM_FormatYUV420SemiPlanar:
  357. case COLOR_QCOM_FormatYUV420SemiPlanar32m:
  358. ff_mediacodec_sw_buffer_copy_yuv420_semi_planar(avctx, s, data, size, info, frame);
  359. break;
  360. case COLOR_TI_FormatYUV420PackedSemiPlanar:
  361. case COLOR_TI_FormatYUV420PackedSemiPlanarInterlaced:
  362. ff_mediacodec_sw_buffer_copy_yuv420_packed_semi_planar(avctx, s, data, size, info, frame);
  363. break;
  364. case COLOR_QCOM_FormatYUV420PackedSemiPlanar64x32Tile2m8ka:
  365. ff_mediacodec_sw_buffer_copy_yuv420_packed_semi_planar_64x32Tile2m8ka(avctx, s, data, size, info, frame);
  366. break;
  367. default:
  368. av_log(avctx, AV_LOG_ERROR, "Unsupported color format 0x%x (value=%d)\n",
  369. s->color_format, s->color_format);
  370. ret = AVERROR(EINVAL);
  371. goto done;
  372. }
  373. ret = 0;
  374. done:
  375. status = ff_AMediaCodec_releaseOutputBuffer(s->codec, index, 0);
  376. if (status < 0) {
  377. av_log(avctx, AV_LOG_ERROR, "Failed to release output buffer\n");
  378. ret = AVERROR_EXTERNAL;
  379. }
  380. return ret;
  381. }
  382. #define AMEDIAFORMAT_GET_INT32(name, key, mandatory) do { \
  383. int32_t value = 0; \
  384. if (ff_AMediaFormat_getInt32(s->format, key, &value)) { \
  385. (name) = value; \
  386. } else if (mandatory) { \
  387. av_log(avctx, AV_LOG_ERROR, "Could not get %s from format %s\n", key, format); \
  388. ret = AVERROR_EXTERNAL; \
  389. goto fail; \
  390. } \
  391. } while (0) \
  392. static int mediacodec_dec_parse_format(AVCodecContext *avctx, MediaCodecDecContext *s)
  393. {
  394. int ret = 0;
  395. int width = 0;
  396. int height = 0;
  397. int color_range = 0;
  398. int color_standard = 0;
  399. int color_transfer = 0;
  400. char *format = NULL;
  401. if (!s->format) {
  402. av_log(avctx, AV_LOG_ERROR, "Output MediaFormat is not set\n");
  403. return AVERROR(EINVAL);
  404. }
  405. format = ff_AMediaFormat_toString(s->format);
  406. if (!format) {
  407. return AVERROR_EXTERNAL;
  408. }
  409. av_log(avctx, AV_LOG_DEBUG, "Parsing MediaFormat %s\n", format);
  410. /* Mandatory fields */
  411. AMEDIAFORMAT_GET_INT32(s->width, "width", 1);
  412. AMEDIAFORMAT_GET_INT32(s->height, "height", 1);
  413. AMEDIAFORMAT_GET_INT32(s->stride, "stride", 0);
  414. s->stride = s->stride > 0 ? s->stride : s->width;
  415. AMEDIAFORMAT_GET_INT32(s->slice_height, "slice-height", 0);
  416. if (strstr(s->codec_name, "OMX.Nvidia.") && s->slice_height == 0) {
  417. s->slice_height = FFALIGN(s->height, 16);
  418. } else if (strstr(s->codec_name, "OMX.SEC.avc.dec")) {
  419. s->slice_height = avctx->height;
  420. s->stride = avctx->width;
  421. } else if (s->slice_height == 0) {
  422. s->slice_height = s->height;
  423. }
  424. AMEDIAFORMAT_GET_INT32(s->color_format, "color-format", 1);
  425. avctx->pix_fmt = mcdec_map_color_format(avctx, s, s->color_format);
  426. if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
  427. av_log(avctx, AV_LOG_ERROR, "Output color format is not supported\n");
  428. ret = AVERROR(EINVAL);
  429. goto fail;
  430. }
  431. /* Optional fields */
  432. AMEDIAFORMAT_GET_INT32(s->crop_top, "crop-top", 0);
  433. AMEDIAFORMAT_GET_INT32(s->crop_bottom, "crop-bottom", 0);
  434. AMEDIAFORMAT_GET_INT32(s->crop_left, "crop-left", 0);
  435. AMEDIAFORMAT_GET_INT32(s->crop_right, "crop-right", 0);
  436. width = s->crop_right + 1 - s->crop_left;
  437. height = s->crop_bottom + 1 - s->crop_top;
  438. AMEDIAFORMAT_GET_INT32(s->display_width, "display-width", 0);
  439. AMEDIAFORMAT_GET_INT32(s->display_height, "display-height", 0);
  440. if (s->display_width && s->display_height) {
  441. AVRational sar = av_div_q(
  442. (AVRational){ s->display_width, s->display_height },
  443. (AVRational){ width, height });
  444. ff_set_sar(avctx, sar);
  445. }
  446. AMEDIAFORMAT_GET_INT32(color_range, "color-range", 0);
  447. if (color_range)
  448. avctx->color_range = mcdec_get_color_range(color_range);
  449. AMEDIAFORMAT_GET_INT32(color_standard, "color-standard", 0);
  450. if (color_standard) {
  451. avctx->colorspace = mcdec_get_color_space(color_standard);
  452. avctx->color_primaries = mcdec_get_color_pri(color_standard);
  453. }
  454. AMEDIAFORMAT_GET_INT32(color_transfer, "color-transfer", 0);
  455. if (color_transfer)
  456. avctx->color_trc = mcdec_get_color_trc(color_transfer);
  457. av_log(avctx, AV_LOG_INFO,
  458. "Output crop parameters top=%d bottom=%d left=%d right=%d, "
  459. "resulting dimensions width=%d height=%d\n",
  460. s->crop_top, s->crop_bottom, s->crop_left, s->crop_right,
  461. width, height);
  462. av_freep(&format);
  463. return ff_set_dimensions(avctx, width, height);
  464. fail:
  465. av_freep(&format);
  466. return ret;
  467. }
  468. static int mediacodec_dec_flush_codec(AVCodecContext *avctx, MediaCodecDecContext *s)
  469. {
  470. FFAMediaCodec *codec = s->codec;
  471. int status;
  472. s->output_buffer_count = 0;
  473. s->draining = 0;
  474. s->flushing = 0;
  475. s->eos = 0;
  476. atomic_fetch_add(&s->serial, 1);
  477. atomic_init(&s->hw_buffer_count, 0);
  478. s->current_input_buffer = -1;
  479. status = ff_AMediaCodec_flush(codec);
  480. if (status < 0) {
  481. av_log(avctx, AV_LOG_ERROR, "Failed to flush codec\n");
  482. return AVERROR_EXTERNAL;
  483. }
  484. return 0;
  485. }
  486. int ff_mediacodec_dec_init(AVCodecContext *avctx, MediaCodecDecContext *s,
  487. const char *mime, FFAMediaFormat *format)
  488. {
  489. int ret = 0;
  490. int status;
  491. int profile;
  492. enum AVPixelFormat pix_fmt;
  493. static const enum AVPixelFormat pix_fmts[] = {
  494. AV_PIX_FMT_MEDIACODEC,
  495. AV_PIX_FMT_NONE,
  496. };
  497. s->avctx = avctx;
  498. atomic_init(&s->refcount, 1);
  499. atomic_init(&s->hw_buffer_count, 0);
  500. atomic_init(&s->serial, 1);
  501. s->current_input_buffer = -1;
  502. pix_fmt = ff_get_format(avctx, pix_fmts);
  503. if (pix_fmt == AV_PIX_FMT_MEDIACODEC) {
  504. AVMediaCodecContext *user_ctx = avctx->hwaccel_context;
  505. if (avctx->hw_device_ctx) {
  506. AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)(avctx->hw_device_ctx->data);
  507. if (device_ctx->type == AV_HWDEVICE_TYPE_MEDIACODEC) {
  508. if (device_ctx->hwctx) {
  509. AVMediaCodecDeviceContext *mediacodec_ctx = (AVMediaCodecDeviceContext *)device_ctx->hwctx;
  510. s->surface = ff_mediacodec_surface_ref(mediacodec_ctx->surface, avctx);
  511. av_log(avctx, AV_LOG_INFO, "Using surface %p\n", s->surface);
  512. }
  513. }
  514. }
  515. if (!s->surface && user_ctx && user_ctx->surface) {
  516. s->surface = ff_mediacodec_surface_ref(user_ctx->surface, avctx);
  517. av_log(avctx, AV_LOG_INFO, "Using surface %p\n", s->surface);
  518. }
  519. }
  520. profile = ff_AMediaCodecProfile_getProfileFromAVCodecContext(avctx);
  521. if (profile < 0) {
  522. av_log(avctx, AV_LOG_WARNING, "Unsupported or unknown profile\n");
  523. }
  524. s->codec_name = ff_AMediaCodecList_getCodecNameByType(mime, profile, 0, avctx);
  525. if (!s->codec_name) {
  526. ret = AVERROR_EXTERNAL;
  527. goto fail;
  528. }
  529. av_log(avctx, AV_LOG_DEBUG, "Found decoder %s\n", s->codec_name);
  530. s->codec = ff_AMediaCodec_createCodecByName(s->codec_name);
  531. if (!s->codec) {
  532. av_log(avctx, AV_LOG_ERROR, "Failed to create media decoder for type %s and name %s\n", mime, s->codec_name);
  533. ret = AVERROR_EXTERNAL;
  534. goto fail;
  535. }
  536. status = ff_AMediaCodec_configure(s->codec, format, s->surface, NULL, 0);
  537. if (status < 0) {
  538. char *desc = ff_AMediaFormat_toString(format);
  539. av_log(avctx, AV_LOG_ERROR,
  540. "Failed to configure codec %s (status = %d) with format %s\n",
  541. s->codec_name, status, desc);
  542. av_freep(&desc);
  543. ret = AVERROR_EXTERNAL;
  544. goto fail;
  545. }
  546. status = ff_AMediaCodec_start(s->codec);
  547. if (status < 0) {
  548. char *desc = ff_AMediaFormat_toString(format);
  549. av_log(avctx, AV_LOG_ERROR,
  550. "Failed to start codec %s (status = %d) with format %s\n",
  551. s->codec_name, status, desc);
  552. av_freep(&desc);
  553. ret = AVERROR_EXTERNAL;
  554. goto fail;
  555. }
  556. s->format = ff_AMediaCodec_getOutputFormat(s->codec);
  557. if (s->format) {
  558. if ((ret = mediacodec_dec_parse_format(avctx, s)) < 0) {
  559. av_log(avctx, AV_LOG_ERROR,
  560. "Failed to configure context\n");
  561. goto fail;
  562. }
  563. }
  564. av_log(avctx, AV_LOG_DEBUG, "MediaCodec %p started successfully\n", s->codec);
  565. return 0;
  566. fail:
  567. av_log(avctx, AV_LOG_ERROR, "MediaCodec %p failed to start\n", s->codec);
  568. ff_mediacodec_dec_close(avctx, s);
  569. return ret;
  570. }
  571. int ff_mediacodec_dec_send(AVCodecContext *avctx, MediaCodecDecContext *s,
  572. AVPacket *pkt, bool wait)
  573. {
  574. int offset = 0;
  575. int need_draining = 0;
  576. uint8_t *data;
  577. size_t size;
  578. FFAMediaCodec *codec = s->codec;
  579. int status;
  580. int64_t input_dequeue_timeout_us = wait ? INPUT_DEQUEUE_TIMEOUT_US : 0;
  581. int64_t pts;
  582. if (s->flushing) {
  583. av_log(avctx, AV_LOG_ERROR, "Decoder is flushing and cannot accept new buffer "
  584. "until all output buffers have been released\n");
  585. return AVERROR_EXTERNAL;
  586. }
  587. if (pkt->size == 0) {
  588. need_draining = 1;
  589. }
  590. if (s->draining && s->eos) {
  591. return AVERROR_EOF;
  592. }
  593. while (offset < pkt->size || (need_draining && !s->draining)) {
  594. ssize_t index = s->current_input_buffer;
  595. if (index < 0) {
  596. index = ff_AMediaCodec_dequeueInputBuffer(codec, input_dequeue_timeout_us);
  597. if (ff_AMediaCodec_infoTryAgainLater(codec, index)) {
  598. av_log(avctx, AV_LOG_TRACE, "No input buffer available, try again later\n");
  599. break;
  600. }
  601. if (index < 0) {
  602. av_log(avctx, AV_LOG_ERROR, "Failed to dequeue input buffer (status=%zd)\n", index);
  603. return AVERROR_EXTERNAL;
  604. }
  605. }
  606. s->current_input_buffer = -1;
  607. data = ff_AMediaCodec_getInputBuffer(codec, index, &size);
  608. if (!data) {
  609. av_log(avctx, AV_LOG_ERROR, "Failed to get input buffer\n");
  610. return AVERROR_EXTERNAL;
  611. }
  612. pts = pkt->pts;
  613. if (pts == AV_NOPTS_VALUE) {
  614. av_log(avctx, AV_LOG_WARNING, "Input packet is missing PTS\n");
  615. pts = 0;
  616. }
  617. if (pts && avctx->pkt_timebase.num && avctx->pkt_timebase.den) {
  618. pts = av_rescale_q(pts, avctx->pkt_timebase, AV_TIME_BASE_Q);
  619. }
  620. if (need_draining) {
  621. uint32_t flags = ff_AMediaCodec_getBufferFlagEndOfStream(codec);
  622. av_log(avctx, AV_LOG_DEBUG, "Sending End Of Stream signal\n");
  623. status = ff_AMediaCodec_queueInputBuffer(codec, index, 0, 0, pts, flags);
  624. if (status < 0) {
  625. av_log(avctx, AV_LOG_ERROR, "Failed to queue input empty buffer (status = %d)\n", status);
  626. return AVERROR_EXTERNAL;
  627. }
  628. av_log(avctx, AV_LOG_TRACE,
  629. "Queued empty EOS input buffer %zd with flags=%d\n", index, flags);
  630. s->draining = 1;
  631. return 0;
  632. }
  633. size = FFMIN(pkt->size - offset, size);
  634. memcpy(data, pkt->data + offset, size);
  635. offset += size;
  636. status = ff_AMediaCodec_queueInputBuffer(codec, index, 0, size, pts, 0);
  637. if (status < 0) {
  638. av_log(avctx, AV_LOG_ERROR, "Failed to queue input buffer (status = %d)\n", status);
  639. return AVERROR_EXTERNAL;
  640. }
  641. av_log(avctx, AV_LOG_TRACE,
  642. "Queued input buffer %zd size=%zd ts=%"PRIi64"\n", index, size, pts);
  643. }
  644. if (offset == 0)
  645. return AVERROR(EAGAIN);
  646. return offset;
  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. if (s->draining && s->eos) {
  660. return AVERROR_EOF;
  661. }
  662. if (s->draining) {
  663. /* If the codec is flushing or need to be flushed, block for a fair
  664. * amount of time to ensure we got a frame */
  665. output_dequeue_timeout_us = OUTPUT_DEQUEUE_BLOCK_TIMEOUT_US;
  666. } else if (s->output_buffer_count == 0 || !wait) {
  667. /* If the codec hasn't produced any frames, do not block so we
  668. * can push data to it as fast as possible, and get the first
  669. * frame */
  670. output_dequeue_timeout_us = 0;
  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. if (info.flags & ff_AMediaCodec_getBufferFlagEndOfStream(codec)) {
  679. s->eos = 1;
  680. }
  681. if (info.size) {
  682. if (s->surface) {
  683. if ((ret = mediacodec_wrap_hw_buffer(avctx, s, index, &info, frame)) < 0) {
  684. av_log(avctx, AV_LOG_ERROR, "Failed to wrap MediaCodec buffer\n");
  685. return ret;
  686. }
  687. } else {
  688. data = ff_AMediaCodec_getOutputBuffer(codec, index, &size);
  689. if (!data) {
  690. av_log(avctx, AV_LOG_ERROR, "Failed to get output buffer\n");
  691. return AVERROR_EXTERNAL;
  692. }
  693. if ((ret = mediacodec_wrap_sw_buffer(avctx, s, data, size, index, &info, frame)) < 0) {
  694. av_log(avctx, AV_LOG_ERROR, "Failed to wrap MediaCodec buffer\n");
  695. return ret;
  696. }
  697. }
  698. s->output_buffer_count++;
  699. return 0;
  700. } else {
  701. status = ff_AMediaCodec_releaseOutputBuffer(codec, index, 0);
  702. if (status < 0) {
  703. av_log(avctx, AV_LOG_ERROR, "Failed to release output buffer\n");
  704. }
  705. }
  706. } else if (ff_AMediaCodec_infoOutputFormatChanged(codec, index)) {
  707. char *format = NULL;
  708. if (s->format) {
  709. status = ff_AMediaFormat_delete(s->format);
  710. if (status < 0) {
  711. av_log(avctx, AV_LOG_ERROR, "Failed to delete MediaFormat %p\n", s->format);
  712. }
  713. }
  714. s->format = ff_AMediaCodec_getOutputFormat(codec);
  715. if (!s->format) {
  716. av_log(avctx, AV_LOG_ERROR, "Failed to get output format\n");
  717. return AVERROR_EXTERNAL;
  718. }
  719. format = ff_AMediaFormat_toString(s->format);
  720. if (!format) {
  721. return AVERROR_EXTERNAL;
  722. }
  723. av_log(avctx, AV_LOG_INFO, "Output MediaFormat changed to %s\n", format);
  724. av_freep(&format);
  725. if ((ret = mediacodec_dec_parse_format(avctx, s)) < 0) {
  726. return ret;
  727. }
  728. } else if (ff_AMediaCodec_infoOutputBuffersChanged(codec, index)) {
  729. ff_AMediaCodec_cleanOutputBuffers(codec);
  730. } else if (ff_AMediaCodec_infoTryAgainLater(codec, index)) {
  731. if (s->draining) {
  732. av_log(avctx, AV_LOG_ERROR, "Failed to dequeue output buffer within %" PRIi64 "ms "
  733. "while draining remaining frames, output will probably lack frames\n",
  734. output_dequeue_timeout_us / 1000);
  735. } else {
  736. av_log(avctx, AV_LOG_TRACE, "No output buffer available, try again later\n");
  737. }
  738. } else {
  739. av_log(avctx, AV_LOG_ERROR, "Failed to dequeue output buffer (status=%zd)\n", index);
  740. return AVERROR_EXTERNAL;
  741. }
  742. return AVERROR(EAGAIN);
  743. }
  744. /*
  745. * ff_mediacodec_dec_flush returns 0 if the flush cannot be performed on
  746. * the codec (because the user retains frames). The codec stays in the
  747. * flushing state.
  748. *
  749. * ff_mediacodec_dec_flush returns 1 if the flush can actually be
  750. * performed on the codec. The codec leaves the flushing state and can
  751. * process again packets.
  752. *
  753. * ff_mediacodec_dec_flush returns a negative value if an error has
  754. * occurred.
  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. /* No frames (holding a reference to the codec) are retained by the
  761. * user, thus we can flush the codec and returns accordingly */
  762. if ((ret = mediacodec_dec_flush_codec(avctx, s)) < 0) {
  763. return ret;
  764. }
  765. return 1;
  766. }
  767. s->flushing = 1;
  768. return 0;
  769. }
  770. int ff_mediacodec_dec_close(AVCodecContext *avctx, MediaCodecDecContext *s)
  771. {
  772. ff_mediacodec_dec_unref(s);
  773. return 0;
  774. }
  775. int ff_mediacodec_dec_is_flushing(AVCodecContext *avctx, MediaCodecDecContext *s)
  776. {
  777. return s->flushing;
  778. }