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.

794 lines
28KB

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