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.

704 lines
27KB

  1. /*
  2. * AMD AMF support
  3. * Copyright (C) 2017 Luca Barbato
  4. * Copyright (C) 2017 Mikhail Mironov <mikhail.mironov@amd.com>
  5. *
  6. * This file is part of Libav.
  7. *
  8. * Libav 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. * Libav 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 Libav; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #include "libavutil/avassert.h"
  23. #include "libavutil/imgutils.h"
  24. #include "libavutil/hwcontext.h"
  25. #include "internal.h"
  26. #if CONFIG_D3D11VA
  27. #include "libavutil/hwcontext_d3d11va.h"
  28. #endif
  29. #include "libavutil/mem.h"
  30. #include "libavutil/pixdesc.h"
  31. #include "libavutil/time.h"
  32. #include "amfenc.h"
  33. #if CONFIG_D3D11VA
  34. #include <d3d11.h>
  35. #endif
  36. #if HAVE_WINDOWS_H
  37. #include <windows.h>
  38. #define dlopen(filename, flags) LoadLibrary((filename))
  39. #define dlsym(handle, symbol) GetProcAddress(handle, symbol)
  40. #define dlclose(handle) FreeLibrary(handle)
  41. #else
  42. #include <dlfcn.h>
  43. #endif
  44. #define LIBAV_AMF_WRITER_ID L"libav_log"
  45. #define PTS_PROP L"PtsProp"
  46. const enum AVPixelFormat ff_amf_pix_fmts[] = {
  47. AV_PIX_FMT_NV12,
  48. AV_PIX_FMT_YUV420P,
  49. #if CONFIG_D3D11VA
  50. AV_PIX_FMT_D3D11,
  51. #endif
  52. AV_PIX_FMT_NONE
  53. };
  54. typedef struct FormatMap {
  55. enum AVPixelFormat av_format;
  56. enum AMF_SURFACE_FORMAT amf_format;
  57. } FormatMap;
  58. static const FormatMap format_map[] =
  59. {
  60. { AV_PIX_FMT_NONE, AMF_SURFACE_UNKNOWN },
  61. { AV_PIX_FMT_NV12, AMF_SURFACE_NV12 },
  62. // { AV_PIX_FMT_BGR0, AMF_SURFACE_BGRA },
  63. // { AV_PIX_FMT_RGB0, AMF_SURFACE_RGBA },
  64. { AV_PIX_FMT_GRAY8, AMF_SURFACE_GRAY8 },
  65. { AV_PIX_FMT_YUV420P, AMF_SURFACE_YUV420P },
  66. { AV_PIX_FMT_YUYV422, AMF_SURFACE_YUY2 },
  67. { AV_PIX_FMT_D3D11, AMF_SURFACE_NV12 },
  68. };
  69. static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
  70. {
  71. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
  72. return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
  73. }
  74. static enum AMF_SURFACE_FORMAT amf_av_to_amf_format(enum AVPixelFormat fmt)
  75. {
  76. int i;
  77. for (i = 0; i < amf_countof(format_map); i++) {
  78. if (format_map[i].av_format == fmt) {
  79. return format_map[i].amf_format;
  80. }
  81. }
  82. return AMF_SURFACE_UNKNOWN;
  83. }
  84. static void AMF_CDECL_CALL AMFTraceWriter_Write(AMFTraceWriter *pThis,
  85. const wchar_t *scope, const wchar_t *message)
  86. {
  87. AmfTraceWriter *tracer = (AmfTraceWriter*)pThis;
  88. av_log(tracer->avctx, AV_LOG_DEBUG, "%ls: %ls", scope, message); // \n is provided from AMF
  89. }
  90. static void AMF_CDECL_CALL AMFTraceWriter_Flush(AMFTraceWriter *pThis)
  91. {
  92. }
  93. static AMFTraceWriterVtbl tracer_vtbl =
  94. {
  95. .Write = AMFTraceWriter_Write,
  96. .Flush = AMFTraceWriter_Flush,
  97. };
  98. static int amf_load_library(AVCodecContext *avctx)
  99. {
  100. AmfContext *ctx = avctx->priv_data;
  101. AMFInit_Fn init_fun = NULL;
  102. AMFQueryVersion_Fn version_fun = NULL;
  103. AMF_RESULT res = AMF_OK;
  104. ctx->eof = 0;
  105. ctx->delayed_drain = 0;
  106. ctx->hw_frames_ctx = NULL;
  107. ctx->hw_device_ctx = NULL;
  108. ctx->delayed_surface = NULL;
  109. ctx->delayed_frame = av_frame_alloc();
  110. if (!ctx->delayed_frame) {
  111. return AVERROR(ENOMEM);
  112. }
  113. // hardcoded to current HW queue size - will realloc in timestamp_queue_enqueue() if too small
  114. ctx->timestamp_list = av_fifo_alloc((avctx->max_b_frames + 16) * sizeof(int64_t));
  115. if (!ctx->timestamp_list) {
  116. return AVERROR(ENOMEM);
  117. }
  118. ctx->dts_delay = 0;
  119. ctx->library = dlopen(AMF_DLL_NAMEA, RTLD_NOW | RTLD_LOCAL);
  120. AMF_RETURN_IF_FALSE(ctx, ctx->library != NULL,
  121. AVERROR_UNKNOWN, "DLL %s failed to open\n", AMF_DLL_NAMEA);
  122. init_fun = (AMFInit_Fn)dlsym(ctx->library, AMF_INIT_FUNCTION_NAME);
  123. AMF_RETURN_IF_FALSE(ctx, init_fun != NULL, AVERROR_UNKNOWN, "DLL %s failed to find function %s\n", AMF_DLL_NAMEA, AMF_INIT_FUNCTION_NAME);
  124. version_fun = (AMFQueryVersion_Fn)dlsym(ctx->library, AMF_QUERY_VERSION_FUNCTION_NAME);
  125. AMF_RETURN_IF_FALSE(ctx, version_fun != NULL, AVERROR_UNKNOWN, "DLL %s failed to find function %s\n", AMF_DLL_NAMEA, AMF_QUERY_VERSION_FUNCTION_NAME);
  126. res = version_fun(&ctx->version);
  127. AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "%s failed with error %d\n", AMF_QUERY_VERSION_FUNCTION_NAME, res);
  128. res = init_fun(AMF_FULL_VERSION, &ctx->factory);
  129. AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "%s failed with error %d\n", AMF_INIT_FUNCTION_NAME, res);
  130. res = ctx->factory->pVtbl->GetTrace(ctx->factory, &ctx->trace);
  131. AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "GetTrace() failed with error %d\n", res);
  132. res = ctx->factory->pVtbl->GetDebug(ctx->factory, &ctx->debug);
  133. AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "GetDebug() failed with error %d\n", res);
  134. return 0;
  135. }
  136. static int amf_init_context(AVCodecContext *avctx)
  137. {
  138. AmfContext *ctx = avctx->priv_data;
  139. AMF_RESULT res = AMF_OK;
  140. ctx->hwsurfaces_in_queue = 0;
  141. ctx->hwsurfaces_in_queue_max = 16;
  142. // configure AMF logger
  143. // the return of these functions indicates old state and do not affect behaviour
  144. ctx->trace->pVtbl->EnableWriter(ctx->trace, AMF_TRACE_WRITER_DEBUG_OUTPUT, ctx->log_to_dbg != 0 );
  145. if (ctx->log_to_dbg)
  146. ctx->trace->pVtbl->SetWriterLevel(ctx->trace, AMF_TRACE_WRITER_DEBUG_OUTPUT, AMF_TRACE_TRACE);
  147. ctx->trace->pVtbl->EnableWriter(ctx->trace, AMF_TRACE_WRITER_CONSOLE, 0);
  148. ctx->trace->pVtbl->SetGlobalLevel(ctx->trace, AMF_TRACE_TRACE);
  149. // connect AMF logger to av_log
  150. ctx->tracer.vtbl = &tracer_vtbl;
  151. ctx->tracer.avctx = avctx;
  152. ctx->trace->pVtbl->RegisterWriter(ctx->trace, LIBAV_AMF_WRITER_ID,(AMFTraceWriter *)&ctx->tracer, 1);
  153. ctx->trace->pVtbl->SetWriterLevel(ctx->trace, LIBAV_AMF_WRITER_ID, AMF_TRACE_TRACE);
  154. res = ctx->factory->pVtbl->CreateContext(ctx->factory, &ctx->context);
  155. AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "CreateContext() failed with error %d\n", res);
  156. // try to reuse existing DX device
  157. #if CONFIG_D3D11VA
  158. if (avctx->hw_frames_ctx) {
  159. AVHWFramesContext *device_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  160. if (device_ctx->device_ctx->type == AV_HWDEVICE_TYPE_D3D11VA) {
  161. if (amf_av_to_amf_format(device_ctx->sw_format) != AMF_SURFACE_UNKNOWN) {
  162. if (device_ctx->device_ctx->hwctx) {
  163. AVD3D11VADeviceContext *device_d3d11 = (AVD3D11VADeviceContext *)device_ctx->device_ctx->hwctx;
  164. res = ctx->context->pVtbl->InitDX11(ctx->context, device_d3d11->device, AMF_DX11_1);
  165. if (res == AMF_OK) {
  166. ctx->hw_frames_ctx = av_buffer_ref(avctx->hw_frames_ctx);
  167. if (!ctx->hw_frames_ctx) {
  168. return AVERROR(ENOMEM);
  169. }
  170. if (device_ctx->initial_pool_size > 0)
  171. ctx->hwsurfaces_in_queue_max = device_ctx->initial_pool_size - 1;
  172. } else {
  173. if(res == AMF_NOT_SUPPORTED)
  174. av_log(avctx, AV_LOG_INFO, "avctx->hw_frames_ctx has D3D11 device which doesn't have D3D11VA interface, switching to default\n");
  175. else
  176. av_log(avctx, AV_LOG_INFO, "avctx->hw_frames_ctx has non-AMD device, switching to default\n");
  177. }
  178. }
  179. } else {
  180. av_log(avctx, AV_LOG_INFO, "avctx->hw_frames_ctx has format not uspported by AMF, switching to default\n");
  181. }
  182. }
  183. } else if (avctx->hw_device_ctx) {
  184. AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)(avctx->hw_device_ctx->data);
  185. if (device_ctx->type == AV_HWDEVICE_TYPE_D3D11VA) {
  186. if (device_ctx->hwctx) {
  187. AVD3D11VADeviceContext *device_d3d11 = (AVD3D11VADeviceContext *)device_ctx->hwctx;
  188. res = ctx->context->pVtbl->InitDX11(ctx->context, device_d3d11->device, AMF_DX11_1);
  189. if (res == AMF_OK) {
  190. ctx->hw_device_ctx = av_buffer_ref(avctx->hw_device_ctx);
  191. if (!ctx->hw_device_ctx) {
  192. return AVERROR(ENOMEM);
  193. }
  194. } else {
  195. if (res == AMF_NOT_SUPPORTED)
  196. av_log(avctx, AV_LOG_INFO, "avctx->hw_device_ctx has D3D11 device which doesn't have D3D11VA interface, switching to default\n");
  197. else
  198. av_log(avctx, AV_LOG_INFO, "avctx->hw_device_ctx has non-AMD device, switching to default\n");
  199. }
  200. }
  201. }
  202. }
  203. #endif
  204. if (!ctx->hw_frames_ctx && !ctx->hw_device_ctx) {
  205. res = ctx->context->pVtbl->InitDX11(ctx->context, NULL, AMF_DX11_1);
  206. if (res != AMF_OK) {
  207. res = ctx->context->pVtbl->InitDX9(ctx->context, NULL);
  208. AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "InitDX9() failed with error %d\n", res);
  209. }
  210. }
  211. return 0;
  212. }
  213. static int amf_init_encoder(AVCodecContext *avctx)
  214. {
  215. AmfContext *ctx = avctx->priv_data;
  216. const wchar_t *codec_id = NULL;
  217. AMF_RESULT res = AMF_OK;
  218. switch (avctx->codec->id) {
  219. case AV_CODEC_ID_H264:
  220. codec_id = AMFVideoEncoderVCE_AVC;
  221. break;
  222. case AV_CODEC_ID_HEVC:
  223. codec_id = AMFVideoEncoder_HEVC;
  224. break;
  225. default:
  226. break;
  227. }
  228. AMF_RETURN_IF_FALSE(ctx, codec_id != NULL, AVERROR(EINVAL), "Codec %d is not supported\n", avctx->codec->id);
  229. ctx->format = amf_av_to_amf_format(avctx->pix_fmt);
  230. AMF_RETURN_IF_FALSE(ctx, ctx->format != AMF_SURFACE_UNKNOWN, AVERROR(EINVAL), "Format %d is not supported\n", avctx->pix_fmt);
  231. res = ctx->factory->pVtbl->CreateComponent(ctx->factory, ctx->context, codec_id, &ctx->encoder);
  232. AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_ENCODER_NOT_FOUND, "CreateComponent(%ls) failed with error %d\n", codec_id, res);
  233. return 0;
  234. }
  235. int av_cold ff_amf_encode_close(AVCodecContext *avctx)
  236. {
  237. AmfContext *ctx = avctx->priv_data;
  238. if (ctx->delayed_surface)
  239. {
  240. ctx->delayed_surface->pVtbl->Release(ctx->delayed_surface);
  241. ctx->delayed_surface = NULL;
  242. }
  243. if (ctx->encoder) {
  244. ctx->encoder->pVtbl->Terminate(ctx->encoder);
  245. ctx->encoder->pVtbl->Release(ctx->encoder);
  246. ctx->encoder = NULL;
  247. }
  248. if (ctx->context) {
  249. ctx->context->pVtbl->Terminate(ctx->context);
  250. ctx->context->pVtbl->Release(ctx->context);
  251. ctx->context = NULL;
  252. }
  253. av_buffer_unref(&ctx->hw_device_ctx);
  254. av_buffer_unref(&ctx->hw_frames_ctx);
  255. if (ctx->trace) {
  256. ctx->trace->pVtbl->UnregisterWriter(ctx->trace, LIBAV_AMF_WRITER_ID);
  257. }
  258. if (ctx->library) {
  259. dlclose(ctx->library);
  260. ctx->library = NULL;
  261. }
  262. ctx->trace = NULL;
  263. ctx->debug = NULL;
  264. ctx->factory = NULL;
  265. ctx->version = 0;
  266. ctx->delayed_drain = 0;
  267. av_frame_free(&ctx->delayed_frame);
  268. av_fifo_free(ctx->timestamp_list);
  269. ctx->timestamp_list = NULL;
  270. ctx->timestamp_last = 0;
  271. return 0;
  272. }
  273. static int amf_copy_surface(AVCodecContext *avctx, const AVFrame *frame,
  274. AMFSurface* surface)
  275. {
  276. AVFrame *sw_frame = NULL;
  277. AMFPlane *plane = NULL;
  278. uint8_t *dst_data[4];
  279. int dst_linesize[4];
  280. int ret = 0;
  281. int planes;
  282. int i;
  283. if (frame->hw_frames_ctx && is_hwaccel_pix_fmt(frame->format)) {
  284. if (!(sw_frame = av_frame_alloc())) {
  285. av_log(avctx, AV_LOG_ERROR, "Can not alloc frame\n");
  286. ret = AVERROR(ENOMEM);
  287. goto fail;
  288. }
  289. if ((ret = av_hwframe_transfer_data(sw_frame, frame, 0)) < 0) {
  290. av_log(avctx, AV_LOG_ERROR, "Error transferring the data to system memory\n");
  291. goto fail;
  292. }
  293. frame = sw_frame;
  294. }
  295. planes = (int)surface->pVtbl->GetPlanesCount(surface);
  296. if (planes > amf_countof(dst_data)) {
  297. av_log(avctx, AV_LOG_ERROR, "Invalid number of planes %d in surface\n", planes);
  298. ret = AVERROR(EINVAL);
  299. goto fail;
  300. }
  301. for (i = 0; i < planes; i++) {
  302. plane = surface->pVtbl->GetPlaneAt(surface, i);
  303. dst_data[i] = plane->pVtbl->GetNative(plane);
  304. dst_linesize[i] = plane->pVtbl->GetHPitch(plane);
  305. }
  306. av_image_copy(dst_data, dst_linesize,
  307. (const uint8_t**)frame->data, frame->linesize, frame->format,
  308. avctx->width, avctx->height);
  309. fail:
  310. if (sw_frame) {
  311. av_frame_free(&sw_frame);
  312. }
  313. return ret;
  314. }
  315. static inline int timestamp_queue_enqueue(AVCodecContext *avctx, int64_t timestamp)
  316. {
  317. AmfContext *ctx = avctx->priv_data;
  318. if (av_fifo_space(ctx->timestamp_list) < sizeof(timestamp)) {
  319. int size = av_fifo_size(ctx->timestamp_list);
  320. if (INT_MAX / 2 - size < sizeof(timestamp))
  321. return AVERROR(EINVAL);
  322. av_fifo_realloc2(ctx->timestamp_list, (size + sizeof(timestamp)) * 2);
  323. }
  324. av_fifo_generic_write(ctx->timestamp_list, &timestamp, sizeof(timestamp), NULL);
  325. ctx->timestamp_last = timestamp;
  326. return 0;
  327. }
  328. static int amf_copy_buffer(AVCodecContext *avctx, AVPacket *pkt, AMFBuffer *buffer)
  329. {
  330. AmfContext *ctx = avctx->priv_data;
  331. int ret;
  332. AMFVariantStruct var = {0};
  333. int64_t timestamp = AV_NOPTS_VALUE;
  334. int64_t size = buffer->pVtbl->GetSize(buffer);
  335. //if ((ret = ff_alloc_packet2(avctx, pkt, size, 0)) < 0) {
  336. if (ret = ff_alloc_packet(pkt, size)) {
  337. return ret;
  338. }
  339. memcpy(pkt->data, buffer->pVtbl->GetNative(buffer), size);
  340. switch (avctx->codec->id) {
  341. case AV_CODEC_ID_H264:
  342. buffer->pVtbl->GetProperty(buffer, AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE, &var);
  343. if(var.int64Value == AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_IDR) {
  344. pkt->flags = AV_PKT_FLAG_KEY;
  345. }
  346. break;
  347. case AV_CODEC_ID_HEVC:
  348. buffer->pVtbl->GetProperty(buffer, AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE, &var);
  349. if (var.int64Value == AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE_IDR) {
  350. pkt->flags = AV_PKT_FLAG_KEY;
  351. }
  352. break;
  353. default:
  354. break;
  355. }
  356. buffer->pVtbl->GetProperty(buffer, PTS_PROP, &var);
  357. pkt->pts = var.int64Value; // original pts
  358. AMF_RETURN_IF_FALSE(ctx, av_fifo_size(ctx->timestamp_list) > 0, AVERROR_UNKNOWN, "timestamp_list is empty\n");
  359. av_fifo_generic_read(ctx->timestamp_list, &timestamp, sizeof(timestamp), NULL);
  360. // calc dts shift if max_b_frames > 0
  361. if (avctx->max_b_frames > 0 && ctx->dts_delay == 0) {
  362. AMF_RETURN_IF_FALSE(ctx, av_fifo_size(ctx->timestamp_list) > 0, AVERROR_UNKNOWN,
  363. "timestamp_list is empty while max_b_frames = %d\n", avctx->max_b_frames);
  364. if (timestamp < 0 || ctx->timestamp_last < AV_NOPTS_VALUE) {
  365. return AVERROR(ERANGE);
  366. }
  367. ctx->dts_delay = ctx->timestamp_last - timestamp;
  368. }
  369. pkt->dts = timestamp - ctx->dts_delay;
  370. return 0;
  371. }
  372. // amfenc API implementation
  373. int ff_amf_encode_init(AVCodecContext *avctx)
  374. {
  375. AmfContext *ctx = avctx->priv_data;
  376. int ret;
  377. ctx->factory = NULL;
  378. ctx->debug = NULL;
  379. ctx->trace = NULL;
  380. ctx->context = NULL;
  381. ctx->encoder = NULL;
  382. ctx->library = NULL;
  383. ctx->version = 0;
  384. ctx->eof = 0;
  385. ctx->format = 0;
  386. ctx->tracer.vtbl = NULL;
  387. ctx->tracer.avctx = NULL;
  388. if ((ret = amf_load_library(avctx)) == 0) {
  389. if ((ret = amf_init_context(avctx)) == 0) {
  390. if ((ret = amf_init_encoder(avctx)) == 0) {
  391. return 0;
  392. }
  393. }
  394. }
  395. ff_amf_encode_close(avctx);
  396. return ret;
  397. }
  398. static AMF_RESULT amf_set_property_buffer(AMFSurface *object, const wchar_t *name, AMFBuffer *val)
  399. {
  400. AMF_RESULT res;
  401. AMFVariantStruct var;
  402. res = AMFVariantInit(&var);
  403. if (res == AMF_OK) {
  404. AMFGuid guid_AMFInterface = IID_AMFInterface();
  405. AMFInterface *amf_interface;
  406. res = val->pVtbl->QueryInterface(val, &guid_AMFInterface, (void**)&amf_interface);
  407. if (res == AMF_OK) {
  408. res = AMFVariantAssignInterface(&var, amf_interface);
  409. amf_interface->pVtbl->Release(amf_interface);
  410. }
  411. if (res == AMF_OK) {
  412. res = object->pVtbl->SetProperty(object, name, var);
  413. }
  414. AMFVariantClear(&var);
  415. }
  416. return res;
  417. }
  418. static AMF_RESULT amf_get_property_buffer(AMFData *object, const wchar_t *name, AMFBuffer **val)
  419. {
  420. AMF_RESULT res;
  421. AMFVariantStruct var;
  422. res = AMFVariantInit(&var);
  423. if (res == AMF_OK) {
  424. res = object->pVtbl->GetProperty(object, name, &var);
  425. if (res == AMF_OK) {
  426. if (var.type == AMF_VARIANT_INTERFACE) {
  427. AMFGuid guid_AMFBuffer = IID_AMFBuffer();
  428. AMFInterface *amf_interface = AMFVariantInterface(&var);
  429. res = amf_interface->pVtbl->QueryInterface(amf_interface, &guid_AMFBuffer, (void**)val);
  430. } else {
  431. res = AMF_INVALID_DATA_TYPE;
  432. }
  433. }
  434. AMFVariantClear(&var);
  435. }
  436. return res;
  437. }
  438. static AMFBuffer *amf_create_buffer_with_frame_ref(const AVFrame *frame, AMFContext *context)
  439. {
  440. AVFrame *frame_ref;
  441. AMFBuffer *frame_ref_storage_buffer = NULL;
  442. AMF_RESULT res;
  443. res = context->pVtbl->AllocBuffer(context, AMF_MEMORY_HOST, sizeof(frame_ref), &frame_ref_storage_buffer);
  444. if (res == AMF_OK) {
  445. frame_ref = av_frame_clone(frame);
  446. if (frame_ref) {
  447. memcpy(frame_ref_storage_buffer->pVtbl->GetNative(frame_ref_storage_buffer), &frame_ref, sizeof(frame_ref));
  448. } else {
  449. frame_ref_storage_buffer->pVtbl->Release(frame_ref_storage_buffer);
  450. frame_ref_storage_buffer = NULL;
  451. }
  452. }
  453. return frame_ref_storage_buffer;
  454. }
  455. static void amf_release_buffer_with_frame_ref(AMFBuffer *frame_ref_storage_buffer)
  456. {
  457. AVFrame *av_frame_ref;
  458. memcpy(&av_frame_ref, frame_ref_storage_buffer->pVtbl->GetNative(frame_ref_storage_buffer), sizeof(av_frame_ref));
  459. av_frame_free(&av_frame_ref);
  460. frame_ref_storage_buffer->pVtbl->Release(frame_ref_storage_buffer);
  461. }
  462. int ff_amf_send_frame(AVCodecContext *avctx, const AVFrame *frame)
  463. {
  464. AMF_RESULT res = AMF_OK;
  465. AmfContext *ctx = avctx->priv_data;
  466. AMFSurface *surface = NULL;
  467. int ret;
  468. if (!ctx->encoder)
  469. return AVERROR(EINVAL);
  470. if (!frame) { // submit drain
  471. if (!ctx->eof) { // submit drain one time only
  472. if (ctx->delayed_surface != NULL) {
  473. ctx->delayed_drain = 1; // input queue is full: resubmit Drain() in ff_amf_receive_packet
  474. } else if(!ctx->delayed_drain) {
  475. res = ctx->encoder->pVtbl->Drain(ctx->encoder);
  476. if (res == AMF_INPUT_FULL) {
  477. ctx->delayed_drain = 1; // input queue is full: resubmit Drain() in ff_amf_receive_packet
  478. } else {
  479. if (res == AMF_OK) {
  480. ctx->eof = 1; // drain started
  481. }
  482. AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "Drain() failed with error %d\n", res);
  483. }
  484. }
  485. } else{
  486. return AVERROR_EOF;
  487. }
  488. } else { // submit frame
  489. if (ctx->delayed_surface != NULL) {
  490. return AVERROR(EAGAIN); // should not happen when called from ffmpeg, other clients may resubmit
  491. }
  492. // prepare surface from frame
  493. if (frame->hw_frames_ctx && ( // HW frame detected
  494. // check if the same hw_frames_ctx as used in initialization
  495. (ctx->hw_frames_ctx && frame->hw_frames_ctx->data == ctx->hw_frames_ctx->data) ||
  496. // check if the same hw_device_ctx as used in initialization
  497. (ctx->hw_device_ctx && ((AVHWFramesContext*)frame->hw_frames_ctx->data)->device_ctx ==
  498. (AVHWDeviceContext*)ctx->hw_device_ctx->data)
  499. )) {
  500. AMFBuffer *frame_ref_storage_buffer;
  501. #if CONFIG_D3D11VA
  502. static const GUID AMFTextureArrayIndexGUID = { 0x28115527, 0xe7c3, 0x4b66, { 0x99, 0xd3, 0x4f, 0x2a, 0xe6, 0xb4, 0x7f, 0xaf } };
  503. ID3D11Texture2D *texture = (ID3D11Texture2D*)frame->data[0]; // actual texture
  504. int index = (int)(size_t)frame->data[1]; // index is a slice in texture array is - set to tell AMF which slice to use
  505. texture->lpVtbl->SetPrivateData(texture, &AMFTextureArrayIndexGUID, sizeof(index), &index);
  506. res = ctx->context->pVtbl->CreateSurfaceFromDX11Native(ctx->context, texture, &surface, NULL); // wrap to AMF surface
  507. AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR(ENOMEM), "CreateSurfaceFromDX11Native() failed with error %d\n", res);
  508. // input HW surfaces can be vertically aligned by 16; tell AMF the real size
  509. surface->pVtbl->SetCrop(surface, 0, 0, frame->width, frame->height);
  510. #endif
  511. frame_ref_storage_buffer = amf_create_buffer_with_frame_ref(frame, ctx->context);
  512. AMF_RETURN_IF_FALSE(ctx, frame_ref_storage_buffer != NULL, AVERROR(ENOMEM), "create_buffer_with_frame_ref() returned NULL\n");
  513. res = amf_set_property_buffer(surface, L"av_frame_ref", frame_ref_storage_buffer);
  514. AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "SetProperty failed for \"av_frame_ref\" with error %d\n", res);
  515. ctx->hwsurfaces_in_queue++;
  516. frame_ref_storage_buffer->pVtbl->Release(frame_ref_storage_buffer);
  517. } else {
  518. res = ctx->context->pVtbl->AllocSurface(ctx->context, AMF_MEMORY_HOST, ctx->format, avctx->width, avctx->height, &surface);
  519. AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR(ENOMEM), "AllocSurface() failed with error %d\n", res);
  520. amf_copy_surface(avctx, frame, surface);
  521. }
  522. surface->pVtbl->SetPts(surface, frame->pts);
  523. AMF_ASSIGN_PROPERTY_INT64(res, surface, PTS_PROP, frame->pts);
  524. switch (avctx->codec->id) {
  525. case AV_CODEC_ID_H264:
  526. AMF_ASSIGN_PROPERTY_INT64(res, surface, AMF_VIDEO_ENCODER_INSERT_AUD, !!ctx->aud);
  527. break;
  528. case AV_CODEC_ID_HEVC:
  529. AMF_ASSIGN_PROPERTY_INT64(res, surface, AMF_VIDEO_ENCODER_HEVC_INSERT_AUD, !!ctx->aud);
  530. break;
  531. default:
  532. break;
  533. }
  534. // submit surface
  535. res = ctx->encoder->pVtbl->SubmitInput(ctx->encoder, (AMFData*)surface);
  536. if (res == AMF_INPUT_FULL) { // handle full queue
  537. //store surface for later submission
  538. ctx->delayed_surface = surface;
  539. if (surface->pVtbl->GetMemoryType(surface) == AMF_MEMORY_DX11) {
  540. av_frame_ref(ctx->delayed_frame, frame);
  541. }
  542. } else {
  543. surface->pVtbl->Release(surface);
  544. AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "SubmitInput() failed with error %d\n", res);
  545. if ((ret = timestamp_queue_enqueue(avctx, frame->pts)) < 0) {
  546. return ret;
  547. }
  548. }
  549. }
  550. return 0;
  551. }
  552. int ff_amf_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
  553. {
  554. int ret;
  555. AMF_RESULT res;
  556. AMF_RESULT res_query;
  557. AmfContext *ctx = avctx->priv_data;
  558. AMFData *data = NULL;
  559. int block_and_wait;
  560. if (!ctx->encoder)
  561. return AVERROR(EINVAL);
  562. do {
  563. block_and_wait = 0;
  564. // poll data
  565. res_query = ctx->encoder->pVtbl->QueryOutput(ctx->encoder, &data);
  566. if (data) {
  567. // copy data to packet
  568. AMFBuffer* buffer;
  569. AMFGuid guid = IID_AMFBuffer();
  570. data->pVtbl->QueryInterface(data, &guid, (void**)&buffer); // query for buffer interface
  571. ret = amf_copy_buffer(avctx, avpkt, buffer);
  572. buffer->pVtbl->Release(buffer);
  573. if (data->pVtbl->HasProperty(data, L"av_frame_ref")) {
  574. AMFBuffer *frame_ref_storage_buffer;
  575. res = amf_get_property_buffer(data, L"av_frame_ref", &frame_ref_storage_buffer);
  576. AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "GetProperty failed for \"av_frame_ref\" with error %d\n", res);
  577. amf_release_buffer_with_frame_ref(frame_ref_storage_buffer);
  578. ctx->hwsurfaces_in_queue--;
  579. }
  580. data->pVtbl->Release(data);
  581. AMF_RETURN_IF_FALSE(ctx, ret >= 0, ret, "amf_copy_buffer() failed with error %d\n", ret);
  582. if (ctx->delayed_surface != NULL) { // try to resubmit frame
  583. res = ctx->encoder->pVtbl->SubmitInput(ctx->encoder, (AMFData*)ctx->delayed_surface);
  584. if (res != AMF_INPUT_FULL) {
  585. int64_t pts = ctx->delayed_surface->pVtbl->GetPts(ctx->delayed_surface);
  586. ctx->delayed_surface->pVtbl->Release(ctx->delayed_surface);
  587. ctx->delayed_surface = NULL;
  588. av_frame_unref(ctx->delayed_frame);
  589. AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "Repeated SubmitInput() failed with error %d\n", res);
  590. if ((ret = timestamp_queue_enqueue(avctx, pts)) < 0) {
  591. return ret;
  592. }
  593. } else {
  594. av_log(avctx, AV_LOG_WARNING, "Data acquired but delayed frame submission got AMF_INPUT_FULL- should not happen\n");
  595. }
  596. } else if (ctx->delayed_drain) { // try to resubmit drain
  597. res = ctx->encoder->pVtbl->Drain(ctx->encoder);
  598. if (res != AMF_INPUT_FULL) {
  599. ctx->delayed_drain = 0;
  600. ctx->eof = 1; // drain started
  601. AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "Repeated Drain() failed with error %d\n", res);
  602. } else {
  603. av_log(avctx, AV_LOG_WARNING, "Data acquired but delayed drain submission got AMF_INPUT_FULL- should not happen\n");
  604. }
  605. }
  606. } else if (ctx->delayed_surface != NULL || ctx->delayed_drain || (ctx->eof && res_query != AMF_EOF) || (ctx->hwsurfaces_in_queue >= ctx->hwsurfaces_in_queue_max)) {
  607. block_and_wait = 1;
  608. av_usleep(1000); // wait and poll again
  609. }
  610. } while (block_and_wait);
  611. if (res_query == AMF_EOF) {
  612. ret = AVERROR_EOF;
  613. } else if (data == NULL) {
  614. ret = AVERROR(EAGAIN);
  615. } else {
  616. ret = 0;
  617. }
  618. return ret;
  619. }