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.

3269 lines
114KB

  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 "pixdesc.h"
  20. #include "avstring.h"
  21. #include "imgutils.h"
  22. #include "hwcontext.h"
  23. #include "hwcontext_internal.h"
  24. #include "hwcontext_vulkan.h"
  25. #if CONFIG_LIBDRM
  26. #include <unistd.h>
  27. #include <xf86drm.h>
  28. #include <drm_fourcc.h>
  29. #include "hwcontext_drm.h"
  30. #if CONFIG_VAAPI
  31. #include <va/va_drmcommon.h>
  32. #include "hwcontext_vaapi.h"
  33. #endif
  34. #endif
  35. #if CONFIG_CUDA
  36. #include "hwcontext_cuda_internal.h"
  37. #include "cuda_check.h"
  38. #define CHECK_CU(x) FF_CUDA_CHECK_DL(cuda_cu, cu, x)
  39. #endif
  40. typedef struct VulkanQueueCtx {
  41. VkFence fence;
  42. VkQueue queue;
  43. int was_synchronous;
  44. /* Buffer dependencies */
  45. AVBufferRef **buf_deps;
  46. int nb_buf_deps;
  47. int buf_deps_alloc_size;
  48. } VulkanQueueCtx;
  49. typedef struct VulkanExecCtx {
  50. VkCommandPool pool;
  51. VkCommandBuffer *bufs;
  52. VulkanQueueCtx *queues;
  53. int nb_queues;
  54. int cur_queue_idx;
  55. } VulkanExecCtx;
  56. typedef struct VulkanDevicePriv {
  57. /* Properties */
  58. VkPhysicalDeviceProperties2 props;
  59. VkPhysicalDeviceMemoryProperties mprops;
  60. VkPhysicalDeviceExternalMemoryHostPropertiesEXT hprops;
  61. /* Queues */
  62. uint32_t qfs[3];
  63. int num_qfs;
  64. /* Debug callback */
  65. VkDebugUtilsMessengerEXT debug_ctx;
  66. /* Extensions */
  67. uint64_t extensions;
  68. /* Settings */
  69. int use_linear_images;
  70. /* Nvidia */
  71. int dev_is_nvidia;
  72. } VulkanDevicePriv;
  73. typedef struct VulkanFramesPriv {
  74. /* Image conversions */
  75. VulkanExecCtx conv_ctx;
  76. /* Image transfers */
  77. VulkanExecCtx upload_ctx;
  78. VulkanExecCtx download_ctx;
  79. } VulkanFramesPriv;
  80. typedef struct AVVkFrameInternal {
  81. #if CONFIG_CUDA
  82. /* Importing external memory into cuda is really expensive so we keep the
  83. * memory imported all the time */
  84. AVBufferRef *cuda_fc_ref; /* Need to keep it around for uninit */
  85. CUexternalMemory ext_mem[AV_NUM_DATA_POINTERS];
  86. CUmipmappedArray cu_mma[AV_NUM_DATA_POINTERS];
  87. CUarray cu_array[AV_NUM_DATA_POINTERS];
  88. CUexternalSemaphore cu_sem[AV_NUM_DATA_POINTERS];
  89. #endif
  90. } AVVkFrameInternal;
  91. #define GET_QUEUE_COUNT(hwctx, graph, comp, tx) ( \
  92. graph ? hwctx->nb_graphics_queues : \
  93. comp ? (hwctx->nb_comp_queues ? \
  94. hwctx->nb_comp_queues : hwctx->nb_graphics_queues) : \
  95. tx ? (hwctx->nb_tx_queues ? hwctx->nb_tx_queues : \
  96. (hwctx->nb_comp_queues ? \
  97. hwctx->nb_comp_queues : hwctx->nb_graphics_queues)) : \
  98. 0 \
  99. )
  100. #define VK_LOAD_PFN(inst, name) PFN_##name pfn_##name = (PFN_##name) \
  101. vkGetInstanceProcAddr(inst, #name)
  102. #define DEFAULT_USAGE_FLAGS (VK_IMAGE_USAGE_SAMPLED_BIT | \
  103. VK_IMAGE_USAGE_STORAGE_BIT | \
  104. VK_IMAGE_USAGE_TRANSFER_SRC_BIT | \
  105. VK_IMAGE_USAGE_TRANSFER_DST_BIT)
  106. #define ADD_VAL_TO_LIST(list, count, val) \
  107. do { \
  108. list = av_realloc_array(list, sizeof(*list), ++count); \
  109. if (!list) { \
  110. err = AVERROR(ENOMEM); \
  111. goto fail; \
  112. } \
  113. list[count - 1] = av_strdup(val); \
  114. if (!list[count - 1]) { \
  115. err = AVERROR(ENOMEM); \
  116. goto fail; \
  117. } \
  118. } while(0)
  119. static const struct {
  120. enum AVPixelFormat pixfmt;
  121. const VkFormat vkfmts[3];
  122. } vk_pixfmt_map[] = {
  123. { AV_PIX_FMT_GRAY8, { VK_FORMAT_R8_UNORM } },
  124. { AV_PIX_FMT_GRAY16, { VK_FORMAT_R16_UNORM } },
  125. { AV_PIX_FMT_GRAYF32, { VK_FORMAT_R32_SFLOAT } },
  126. { AV_PIX_FMT_NV12, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8G8_UNORM } },
  127. { AV_PIX_FMT_P010, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16G16_UNORM } },
  128. { AV_PIX_FMT_P016, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16G16_UNORM } },
  129. { AV_PIX_FMT_YUV420P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
  130. { AV_PIX_FMT_YUV422P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
  131. { AV_PIX_FMT_YUV444P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
  132. { AV_PIX_FMT_YUV420P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
  133. { AV_PIX_FMT_YUV422P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
  134. { AV_PIX_FMT_YUV444P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
  135. { AV_PIX_FMT_ABGR, { VK_FORMAT_A8B8G8R8_UNORM_PACK32 } },
  136. { AV_PIX_FMT_BGRA, { VK_FORMAT_B8G8R8A8_UNORM } },
  137. { AV_PIX_FMT_RGBA, { VK_FORMAT_R8G8B8A8_UNORM } },
  138. { AV_PIX_FMT_RGB24, { VK_FORMAT_R8G8B8_UNORM } },
  139. { AV_PIX_FMT_BGR24, { VK_FORMAT_B8G8R8_UNORM } },
  140. { AV_PIX_FMT_RGB48, { VK_FORMAT_R16G16B16_UNORM } },
  141. { AV_PIX_FMT_RGBA64, { VK_FORMAT_R16G16B16A16_UNORM } },
  142. { AV_PIX_FMT_RGB565, { VK_FORMAT_R5G6B5_UNORM_PACK16 } },
  143. { AV_PIX_FMT_BGR565, { VK_FORMAT_B5G6R5_UNORM_PACK16 } },
  144. { AV_PIX_FMT_BGR0, { VK_FORMAT_B8G8R8A8_UNORM } },
  145. { AV_PIX_FMT_0BGR, { VK_FORMAT_A8B8G8R8_UNORM_PACK32 } },
  146. { AV_PIX_FMT_RGB0, { VK_FORMAT_R8G8B8A8_UNORM } },
  147. { AV_PIX_FMT_GBRPF32, { VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32_SFLOAT } },
  148. };
  149. const VkFormat *av_vkfmt_from_pixfmt(enum AVPixelFormat p)
  150. {
  151. for (enum AVPixelFormat i = 0; i < FF_ARRAY_ELEMS(vk_pixfmt_map); i++)
  152. if (vk_pixfmt_map[i].pixfmt == p)
  153. return vk_pixfmt_map[i].vkfmts;
  154. return NULL;
  155. }
  156. static int pixfmt_is_supported(AVVulkanDeviceContext *hwctx, enum AVPixelFormat p,
  157. int linear)
  158. {
  159. const VkFormat *fmt = av_vkfmt_from_pixfmt(p);
  160. int planes = av_pix_fmt_count_planes(p);
  161. if (!fmt)
  162. return 0;
  163. for (int i = 0; i < planes; i++) {
  164. VkFormatFeatureFlags flags;
  165. VkFormatProperties2 prop = {
  166. .sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2,
  167. };
  168. vkGetPhysicalDeviceFormatProperties2(hwctx->phys_dev, fmt[i], &prop);
  169. flags = linear ? prop.formatProperties.linearTilingFeatures :
  170. prop.formatProperties.optimalTilingFeatures;
  171. if (!(flags & DEFAULT_USAGE_FLAGS))
  172. return 0;
  173. }
  174. return 1;
  175. }
  176. enum VulkanExtensions {
  177. EXT_EXTERNAL_DMABUF_MEMORY = 1ULL << 0, /* VK_EXT_external_memory_dma_buf */
  178. EXT_DRM_MODIFIER_FLAGS = 1ULL << 1, /* VK_EXT_image_drm_format_modifier */
  179. EXT_EXTERNAL_FD_MEMORY = 1ULL << 2, /* VK_KHR_external_memory_fd */
  180. EXT_EXTERNAL_FD_SEM = 1ULL << 3, /* VK_KHR_external_semaphore_fd */
  181. EXT_EXTERNAL_HOST_MEMORY = 1ULL << 4, /* VK_EXT_external_memory_host */
  182. EXT_NO_FLAG = 1ULL << 63,
  183. };
  184. typedef struct VulkanOptExtension {
  185. const char *name;
  186. uint64_t flag;
  187. } VulkanOptExtension;
  188. static const VulkanOptExtension optional_instance_exts[] = {
  189. /* For future use */
  190. };
  191. static const VulkanOptExtension optional_device_exts[] = {
  192. { VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME, EXT_EXTERNAL_FD_MEMORY, },
  193. { VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME, EXT_EXTERNAL_DMABUF_MEMORY, },
  194. { VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME, EXT_DRM_MODIFIER_FLAGS, },
  195. { VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME, EXT_EXTERNAL_FD_SEM, },
  196. { VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME, EXT_EXTERNAL_HOST_MEMORY, },
  197. };
  198. /* Converts return values to strings */
  199. static const char *vk_ret2str(VkResult res)
  200. {
  201. #define CASE(VAL) case VAL: return #VAL
  202. switch (res) {
  203. CASE(VK_SUCCESS);
  204. CASE(VK_NOT_READY);
  205. CASE(VK_TIMEOUT);
  206. CASE(VK_EVENT_SET);
  207. CASE(VK_EVENT_RESET);
  208. CASE(VK_INCOMPLETE);
  209. CASE(VK_ERROR_OUT_OF_HOST_MEMORY);
  210. CASE(VK_ERROR_OUT_OF_DEVICE_MEMORY);
  211. CASE(VK_ERROR_INITIALIZATION_FAILED);
  212. CASE(VK_ERROR_DEVICE_LOST);
  213. CASE(VK_ERROR_MEMORY_MAP_FAILED);
  214. CASE(VK_ERROR_LAYER_NOT_PRESENT);
  215. CASE(VK_ERROR_EXTENSION_NOT_PRESENT);
  216. CASE(VK_ERROR_FEATURE_NOT_PRESENT);
  217. CASE(VK_ERROR_INCOMPATIBLE_DRIVER);
  218. CASE(VK_ERROR_TOO_MANY_OBJECTS);
  219. CASE(VK_ERROR_FORMAT_NOT_SUPPORTED);
  220. CASE(VK_ERROR_FRAGMENTED_POOL);
  221. CASE(VK_ERROR_SURFACE_LOST_KHR);
  222. CASE(VK_ERROR_NATIVE_WINDOW_IN_USE_KHR);
  223. CASE(VK_SUBOPTIMAL_KHR);
  224. CASE(VK_ERROR_OUT_OF_DATE_KHR);
  225. CASE(VK_ERROR_INCOMPATIBLE_DISPLAY_KHR);
  226. CASE(VK_ERROR_VALIDATION_FAILED_EXT);
  227. CASE(VK_ERROR_INVALID_SHADER_NV);
  228. CASE(VK_ERROR_OUT_OF_POOL_MEMORY);
  229. CASE(VK_ERROR_INVALID_EXTERNAL_HANDLE);
  230. CASE(VK_ERROR_NOT_PERMITTED_EXT);
  231. CASE(VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT);
  232. CASE(VK_ERROR_INVALID_DEVICE_ADDRESS_EXT);
  233. CASE(VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT);
  234. default: return "Unknown error";
  235. }
  236. #undef CASE
  237. }
  238. static VkBool32 vk_dbg_callback(VkDebugUtilsMessageSeverityFlagBitsEXT severity,
  239. VkDebugUtilsMessageTypeFlagsEXT messageType,
  240. const VkDebugUtilsMessengerCallbackDataEXT *data,
  241. void *priv)
  242. {
  243. int l;
  244. AVHWDeviceContext *ctx = priv;
  245. switch (severity) {
  246. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT: l = AV_LOG_VERBOSE; break;
  247. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT: l = AV_LOG_INFO; break;
  248. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT: l = AV_LOG_WARNING; break;
  249. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT: l = AV_LOG_ERROR; break;
  250. default: l = AV_LOG_DEBUG; break;
  251. }
  252. av_log(ctx, l, "%s\n", data->pMessage);
  253. for (int i = 0; i < data->cmdBufLabelCount; i++)
  254. av_log(ctx, l, "\t%i: %s\n", i, data->pCmdBufLabels[i].pLabelName);
  255. return 0;
  256. }
  257. static int check_extensions(AVHWDeviceContext *ctx, int dev, AVDictionary *opts,
  258. const char * const **dst, uint32_t *num, int debug)
  259. {
  260. const char *tstr;
  261. const char **extension_names = NULL;
  262. VulkanDevicePriv *p = ctx->internal->priv;
  263. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  264. int err = 0, found, extensions_found = 0;
  265. const char *mod;
  266. int optional_exts_num;
  267. uint32_t sup_ext_count;
  268. char *user_exts_str = NULL;
  269. AVDictionaryEntry *user_exts;
  270. VkExtensionProperties *sup_ext;
  271. const VulkanOptExtension *optional_exts;
  272. if (!dev) {
  273. mod = "instance";
  274. optional_exts = optional_instance_exts;
  275. optional_exts_num = FF_ARRAY_ELEMS(optional_instance_exts);
  276. user_exts = av_dict_get(opts, "instance_extensions", NULL, 0);
  277. if (user_exts) {
  278. user_exts_str = av_strdup(user_exts->value);
  279. if (!user_exts_str) {
  280. err = AVERROR(ENOMEM);
  281. goto fail;
  282. }
  283. }
  284. vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, NULL);
  285. sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
  286. if (!sup_ext)
  287. return AVERROR(ENOMEM);
  288. vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, sup_ext);
  289. } else {
  290. mod = "device";
  291. optional_exts = optional_device_exts;
  292. optional_exts_num = FF_ARRAY_ELEMS(optional_device_exts);
  293. user_exts = av_dict_get(opts, "device_extensions", NULL, 0);
  294. if (user_exts) {
  295. user_exts_str = av_strdup(user_exts->value);
  296. if (!user_exts_str) {
  297. err = AVERROR(ENOMEM);
  298. goto fail;
  299. }
  300. }
  301. vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
  302. &sup_ext_count, NULL);
  303. sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
  304. if (!sup_ext)
  305. return AVERROR(ENOMEM);
  306. vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
  307. &sup_ext_count, sup_ext);
  308. }
  309. for (int i = 0; i < optional_exts_num; i++) {
  310. tstr = optional_exts[i].name;
  311. found = 0;
  312. for (int j = 0; j < sup_ext_count; j++) {
  313. if (!strcmp(tstr, sup_ext[j].extensionName)) {
  314. found = 1;
  315. break;
  316. }
  317. }
  318. if (!found)
  319. continue;
  320. av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
  321. p->extensions |= optional_exts[i].flag;
  322. ADD_VAL_TO_LIST(extension_names, extensions_found, tstr);
  323. }
  324. if (debug && !dev) {
  325. tstr = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
  326. found = 0;
  327. for (int j = 0; j < sup_ext_count; j++) {
  328. if (!strcmp(tstr, sup_ext[j].extensionName)) {
  329. found = 1;
  330. break;
  331. }
  332. }
  333. if (found) {
  334. av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
  335. ADD_VAL_TO_LIST(extension_names, extensions_found, tstr);
  336. } else {
  337. av_log(ctx, AV_LOG_ERROR, "Debug extension \"%s\" not found!\n",
  338. tstr);
  339. err = AVERROR(EINVAL);
  340. goto fail;
  341. }
  342. }
  343. if (user_exts_str) {
  344. char *save, *token = av_strtok(user_exts_str, "+", &save);
  345. while (token) {
  346. found = 0;
  347. for (int j = 0; j < sup_ext_count; j++) {
  348. if (!strcmp(token, sup_ext[j].extensionName)) {
  349. found = 1;
  350. break;
  351. }
  352. }
  353. if (found) {
  354. av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, token);
  355. ADD_VAL_TO_LIST(extension_names, extensions_found, token);
  356. } else {
  357. av_log(ctx, AV_LOG_WARNING, "%s extension \"%s\" not found, excluding.\n",
  358. mod, token);
  359. }
  360. token = av_strtok(NULL, "+", &save);
  361. }
  362. }
  363. *dst = extension_names;
  364. *num = extensions_found;
  365. av_free(user_exts_str);
  366. av_free(sup_ext);
  367. return 0;
  368. fail:
  369. if (extension_names)
  370. for (int i = 0; i < extensions_found; i++)
  371. av_free((void *)extension_names[i]);
  372. av_free(extension_names);
  373. av_free(user_exts_str);
  374. av_free(sup_ext);
  375. return err;
  376. }
  377. /* Creates a VkInstance */
  378. static int create_instance(AVHWDeviceContext *ctx, AVDictionary *opts)
  379. {
  380. int err = 0;
  381. VkResult ret;
  382. VulkanDevicePriv *p = ctx->internal->priv;
  383. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  384. AVDictionaryEntry *debug_opt = av_dict_get(opts, "debug", NULL, 0);
  385. const int debug_mode = debug_opt && strtol(debug_opt->value, NULL, 10);
  386. VkApplicationInfo application_info = {
  387. .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
  388. .pEngineName = "libavutil",
  389. .apiVersion = VK_API_VERSION_1_1,
  390. .engineVersion = VK_MAKE_VERSION(LIBAVUTIL_VERSION_MAJOR,
  391. LIBAVUTIL_VERSION_MINOR,
  392. LIBAVUTIL_VERSION_MICRO),
  393. };
  394. VkInstanceCreateInfo inst_props = {
  395. .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
  396. .pApplicationInfo = &application_info,
  397. };
  398. /* Check for present/missing extensions */
  399. err = check_extensions(ctx, 0, opts, &inst_props.ppEnabledExtensionNames,
  400. &inst_props.enabledExtensionCount, debug_mode);
  401. if (err < 0)
  402. return err;
  403. if (debug_mode) {
  404. static const char *layers[] = { "VK_LAYER_KHRONOS_validation" };
  405. inst_props.ppEnabledLayerNames = layers;
  406. inst_props.enabledLayerCount = FF_ARRAY_ELEMS(layers);
  407. }
  408. /* Try to create the instance */
  409. ret = vkCreateInstance(&inst_props, hwctx->alloc, &hwctx->inst);
  410. /* Check for errors */
  411. if (ret != VK_SUCCESS) {
  412. av_log(ctx, AV_LOG_ERROR, "Instance creation failure: %s\n",
  413. vk_ret2str(ret));
  414. for (int i = 0; i < inst_props.enabledExtensionCount; i++)
  415. av_free((void *)inst_props.ppEnabledExtensionNames[i]);
  416. av_free((void *)inst_props.ppEnabledExtensionNames);
  417. return AVERROR_EXTERNAL;
  418. }
  419. if (debug_mode) {
  420. VkDebugUtilsMessengerCreateInfoEXT dbg = {
  421. .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT,
  422. .messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT |
  423. VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT |
  424. VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
  425. VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT,
  426. .messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
  427. VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
  428. VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT,
  429. .pfnUserCallback = vk_dbg_callback,
  430. .pUserData = ctx,
  431. };
  432. VK_LOAD_PFN(hwctx->inst, vkCreateDebugUtilsMessengerEXT);
  433. pfn_vkCreateDebugUtilsMessengerEXT(hwctx->inst, &dbg,
  434. hwctx->alloc, &p->debug_ctx);
  435. }
  436. hwctx->enabled_inst_extensions = inst_props.ppEnabledExtensionNames;
  437. hwctx->nb_enabled_inst_extensions = inst_props.enabledExtensionCount;
  438. return 0;
  439. }
  440. typedef struct VulkanDeviceSelection {
  441. uint8_t uuid[VK_UUID_SIZE]; /* Will use this first unless !has_uuid */
  442. int has_uuid;
  443. const char *name; /* Will use this second unless NULL */
  444. uint32_t pci_device; /* Will use this third unless 0x0 */
  445. uint32_t vendor_id; /* Last resort to find something deterministic */
  446. int index; /* Finally fall back to index */
  447. } VulkanDeviceSelection;
  448. static const char *vk_dev_type(enum VkPhysicalDeviceType type)
  449. {
  450. switch (type) {
  451. case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: return "integrated";
  452. case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: return "discrete";
  453. case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: return "virtual";
  454. case VK_PHYSICAL_DEVICE_TYPE_CPU: return "software";
  455. default: return "unknown";
  456. }
  457. }
  458. /* Finds a device */
  459. static int find_device(AVHWDeviceContext *ctx, VulkanDeviceSelection *select)
  460. {
  461. int err = 0, choice = -1;
  462. uint32_t num;
  463. VkResult ret;
  464. VkPhysicalDevice *devices = NULL;
  465. VkPhysicalDeviceIDProperties *idp = NULL;
  466. VkPhysicalDeviceProperties2 *prop = NULL;
  467. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  468. ret = vkEnumeratePhysicalDevices(hwctx->inst, &num, NULL);
  469. if (ret != VK_SUCCESS || !num) {
  470. av_log(ctx, AV_LOG_ERROR, "No devices found: %s!\n", vk_ret2str(ret));
  471. return AVERROR(ENODEV);
  472. }
  473. devices = av_malloc_array(num, sizeof(VkPhysicalDevice));
  474. if (!devices)
  475. return AVERROR(ENOMEM);
  476. ret = vkEnumeratePhysicalDevices(hwctx->inst, &num, devices);
  477. if (ret != VK_SUCCESS) {
  478. av_log(ctx, AV_LOG_ERROR, "Failed enumerating devices: %s\n",
  479. vk_ret2str(ret));
  480. err = AVERROR(ENODEV);
  481. goto end;
  482. }
  483. prop = av_mallocz_array(num, sizeof(*prop));
  484. if (!prop) {
  485. err = AVERROR(ENOMEM);
  486. goto end;
  487. }
  488. idp = av_mallocz_array(num, sizeof(*idp));
  489. if (!idp) {
  490. err = AVERROR(ENOMEM);
  491. goto end;
  492. }
  493. av_log(ctx, AV_LOG_VERBOSE, "GPU listing:\n");
  494. for (int i = 0; i < num; i++) {
  495. idp[i].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES;
  496. prop[i].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
  497. prop[i].pNext = &idp[i];
  498. vkGetPhysicalDeviceProperties2(devices[i], &prop[i]);
  499. av_log(ctx, AV_LOG_VERBOSE, " %d: %s (%s) (0x%x)\n", i,
  500. prop[i].properties.deviceName,
  501. vk_dev_type(prop[i].properties.deviceType),
  502. prop[i].properties.deviceID);
  503. }
  504. if (select->has_uuid) {
  505. for (int i = 0; i < num; i++) {
  506. if (!strncmp(idp[i].deviceUUID, select->uuid, VK_UUID_SIZE)) {
  507. choice = i;
  508. goto end;
  509. }
  510. }
  511. av_log(ctx, AV_LOG_ERROR, "Unable to find device by given UUID!\n");
  512. err = AVERROR(ENODEV);
  513. goto end;
  514. } else if (select->name) {
  515. av_log(ctx, AV_LOG_VERBOSE, "Requested device: %s\n", select->name);
  516. for (int i = 0; i < num; i++) {
  517. if (strstr(prop[i].properties.deviceName, select->name)) {
  518. choice = i;
  519. goto end;
  520. }
  521. }
  522. av_log(ctx, AV_LOG_ERROR, "Unable to find device \"%s\"!\n",
  523. select->name);
  524. err = AVERROR(ENODEV);
  525. goto end;
  526. } else if (select->pci_device) {
  527. av_log(ctx, AV_LOG_VERBOSE, "Requested device: 0x%x\n", select->pci_device);
  528. for (int i = 0; i < num; i++) {
  529. if (select->pci_device == prop[i].properties.deviceID) {
  530. choice = i;
  531. goto end;
  532. }
  533. }
  534. av_log(ctx, AV_LOG_ERROR, "Unable to find device with PCI ID 0x%x!\n",
  535. select->pci_device);
  536. err = AVERROR(EINVAL);
  537. goto end;
  538. } else if (select->vendor_id) {
  539. av_log(ctx, AV_LOG_VERBOSE, "Requested vendor: 0x%x\n", select->vendor_id);
  540. for (int i = 0; i < num; i++) {
  541. if (select->vendor_id == prop[i].properties.vendorID) {
  542. choice = i;
  543. goto end;
  544. }
  545. }
  546. av_log(ctx, AV_LOG_ERROR, "Unable to find device with Vendor ID 0x%x!\n",
  547. select->vendor_id);
  548. err = AVERROR(ENODEV);
  549. goto end;
  550. } else {
  551. if (select->index < num) {
  552. choice = select->index;
  553. goto end;
  554. }
  555. av_log(ctx, AV_LOG_ERROR, "Unable to find device with index %i!\n",
  556. select->index);
  557. err = AVERROR(ENODEV);
  558. goto end;
  559. }
  560. end:
  561. if (choice > -1)
  562. hwctx->phys_dev = devices[choice];
  563. av_free(devices);
  564. av_free(prop);
  565. av_free(idp);
  566. return err;
  567. }
  568. static int search_queue_families(AVHWDeviceContext *ctx, VkDeviceCreateInfo *cd)
  569. {
  570. uint32_t num;
  571. float *weights;
  572. VkQueueFamilyProperties *qs = NULL;
  573. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  574. int graph_index = -1, comp_index = -1, tx_index = -1;
  575. VkDeviceQueueCreateInfo *pc = (VkDeviceQueueCreateInfo *)cd->pQueueCreateInfos;
  576. /* First get the number of queue families */
  577. vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, NULL);
  578. if (!num) {
  579. av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
  580. return AVERROR_EXTERNAL;
  581. }
  582. /* Then allocate memory */
  583. qs = av_malloc_array(num, sizeof(VkQueueFamilyProperties));
  584. if (!qs)
  585. return AVERROR(ENOMEM);
  586. /* Finally retrieve the queue families */
  587. vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, qs);
  588. #define SEARCH_FLAGS(expr, out) \
  589. for (int i = 0; i < num; i++) { \
  590. const VkQueueFlagBits flags = qs[i].queueFlags; \
  591. if (expr) { \
  592. out = i; \
  593. break; \
  594. } \
  595. }
  596. SEARCH_FLAGS(flags & VK_QUEUE_GRAPHICS_BIT, graph_index)
  597. SEARCH_FLAGS((flags & VK_QUEUE_COMPUTE_BIT) && (i != graph_index),
  598. comp_index)
  599. SEARCH_FLAGS((flags & VK_QUEUE_TRANSFER_BIT) && (i != graph_index) &&
  600. (i != comp_index), tx_index)
  601. #undef SEARCH_FLAGS
  602. #define ADD_QUEUE(fidx, graph, comp, tx) \
  603. av_log(ctx, AV_LOG_VERBOSE, "Using queue family %i (total queues: %i) for %s%s%s\n", \
  604. fidx, qs[fidx].queueCount, graph ? "graphics " : "", \
  605. comp ? "compute " : "", tx ? "transfers " : ""); \
  606. av_log(ctx, AV_LOG_VERBOSE, " QF %i flags: %s%s%s%s\n", fidx, \
  607. ((qs[fidx].queueFlags) & VK_QUEUE_GRAPHICS_BIT) ? "(graphics) " : "", \
  608. ((qs[fidx].queueFlags) & VK_QUEUE_COMPUTE_BIT) ? "(compute) " : "", \
  609. ((qs[fidx].queueFlags) & VK_QUEUE_TRANSFER_BIT) ? "(transfers) " : "", \
  610. ((qs[fidx].queueFlags) & VK_QUEUE_SPARSE_BINDING_BIT) ? "(sparse) " : ""); \
  611. pc[cd->queueCreateInfoCount].queueFamilyIndex = fidx; \
  612. pc[cd->queueCreateInfoCount].queueCount = qs[fidx].queueCount; \
  613. weights = av_malloc(qs[fidx].queueCount * sizeof(float)); \
  614. pc[cd->queueCreateInfoCount].pQueuePriorities = weights; \
  615. if (!weights) \
  616. goto fail; \
  617. for (int i = 0; i < qs[fidx].queueCount; i++) \
  618. weights[i] = 1.0f; \
  619. cd->queueCreateInfoCount++;
  620. ADD_QUEUE(graph_index, 1, comp_index < 0, tx_index < 0 && comp_index < 0)
  621. hwctx->queue_family_index = graph_index;
  622. hwctx->queue_family_comp_index = graph_index;
  623. hwctx->queue_family_tx_index = graph_index;
  624. hwctx->nb_graphics_queues = qs[graph_index].queueCount;
  625. if (comp_index != -1) {
  626. ADD_QUEUE(comp_index, 0, 1, tx_index < 0)
  627. hwctx->queue_family_tx_index = comp_index;
  628. hwctx->queue_family_comp_index = comp_index;
  629. hwctx->nb_comp_queues = qs[comp_index].queueCount;
  630. }
  631. if (tx_index != -1) {
  632. ADD_QUEUE(tx_index, 0, 0, 1)
  633. hwctx->queue_family_tx_index = tx_index;
  634. hwctx->nb_tx_queues = qs[tx_index].queueCount;
  635. }
  636. #undef ADD_QUEUE
  637. av_free(qs);
  638. return 0;
  639. fail:
  640. av_freep(&pc[0].pQueuePriorities);
  641. av_freep(&pc[1].pQueuePriorities);
  642. av_freep(&pc[2].pQueuePriorities);
  643. av_free(qs);
  644. return AVERROR(ENOMEM);
  645. }
  646. static int create_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd,
  647. int queue_family_index, int num_queues)
  648. {
  649. VkResult ret;
  650. AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
  651. VkCommandPoolCreateInfo cqueue_create = {
  652. .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
  653. .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
  654. .queueFamilyIndex = queue_family_index,
  655. };
  656. VkCommandBufferAllocateInfo cbuf_create = {
  657. .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
  658. .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
  659. .commandBufferCount = num_queues,
  660. };
  661. cmd->nb_queues = num_queues;
  662. cmd->queues = av_mallocz(num_queues * sizeof(*cmd->queues));
  663. if (!cmd->queues)
  664. return AVERROR(ENOMEM);
  665. cmd->bufs = av_mallocz(num_queues * sizeof(*cmd->bufs));
  666. if (!cmd->bufs)
  667. return AVERROR(ENOMEM);
  668. /* Create command pool */
  669. ret = vkCreateCommandPool(hwctx->act_dev, &cqueue_create,
  670. hwctx->alloc, &cmd->pool);
  671. if (ret != VK_SUCCESS) {
  672. av_log(hwfc, AV_LOG_ERROR, "Command pool creation failure: %s\n",
  673. vk_ret2str(ret));
  674. return AVERROR_EXTERNAL;
  675. }
  676. cbuf_create.commandPool = cmd->pool;
  677. /* Allocate command buffer */
  678. ret = vkAllocateCommandBuffers(hwctx->act_dev, &cbuf_create, cmd->bufs);
  679. if (ret != VK_SUCCESS) {
  680. av_log(hwfc, AV_LOG_ERROR, "Command buffer alloc failure: %s\n",
  681. vk_ret2str(ret));
  682. return AVERROR_EXTERNAL;
  683. }
  684. for (int i = 0; i < num_queues; i++) {
  685. VulkanQueueCtx *q = &cmd->queues[i];
  686. vkGetDeviceQueue(hwctx->act_dev, queue_family_index, i, &q->queue);
  687. q->was_synchronous = 1;
  688. }
  689. return 0;
  690. }
  691. static void free_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd)
  692. {
  693. AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
  694. /* Make sure all queues have finished executing */
  695. for (int i = 0; i < cmd->nb_queues; i++) {
  696. VulkanQueueCtx *q = &cmd->queues[i];
  697. if (q->fence && !q->was_synchronous) {
  698. vkWaitForFences(hwctx->act_dev, 1, &q->fence, VK_TRUE, UINT64_MAX);
  699. vkResetFences(hwctx->act_dev, 1, &q->fence);
  700. }
  701. /* Free the fence */
  702. if (q->fence)
  703. vkDestroyFence(hwctx->act_dev, q->fence, hwctx->alloc);
  704. /* Free buffer dependencies */
  705. for (int j = 0; j < q->nb_buf_deps; j++)
  706. av_buffer_unref(&q->buf_deps[j]);
  707. av_free(q->buf_deps);
  708. }
  709. if (cmd->bufs)
  710. vkFreeCommandBuffers(hwctx->act_dev, cmd->pool, cmd->nb_queues, cmd->bufs);
  711. if (cmd->pool)
  712. vkDestroyCommandPool(hwctx->act_dev, cmd->pool, hwctx->alloc);
  713. av_freep(&cmd->bufs);
  714. av_freep(&cmd->queues);
  715. }
  716. static VkCommandBuffer get_buf_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd)
  717. {
  718. return cmd->bufs[cmd->cur_queue_idx];
  719. }
  720. static void unref_exec_ctx_deps(AVHWFramesContext *hwfc, VulkanExecCtx *cmd)
  721. {
  722. VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
  723. for (int j = 0; j < q->nb_buf_deps; j++)
  724. av_buffer_unref(&q->buf_deps[j]);
  725. q->nb_buf_deps = 0;
  726. }
  727. static int wait_start_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd)
  728. {
  729. VkResult ret;
  730. AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
  731. VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
  732. VkCommandBufferBeginInfo cmd_start = {
  733. .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
  734. .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
  735. };
  736. /* Create the fence and don't wait for it initially */
  737. if (!q->fence) {
  738. VkFenceCreateInfo fence_spawn = {
  739. .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
  740. };
  741. ret = vkCreateFence(hwctx->act_dev, &fence_spawn, hwctx->alloc,
  742. &q->fence);
  743. if (ret != VK_SUCCESS) {
  744. av_log(hwfc, AV_LOG_ERROR, "Failed to queue frame fence: %s\n",
  745. vk_ret2str(ret));
  746. return AVERROR_EXTERNAL;
  747. }
  748. } else if (!q->was_synchronous) {
  749. vkWaitForFences(hwctx->act_dev, 1, &q->fence, VK_TRUE, UINT64_MAX);
  750. vkResetFences(hwctx->act_dev, 1, &q->fence);
  751. }
  752. /* Discard queue dependencies */
  753. unref_exec_ctx_deps(hwfc, cmd);
  754. ret = vkBeginCommandBuffer(cmd->bufs[cmd->cur_queue_idx], &cmd_start);
  755. if (ret != VK_SUCCESS) {
  756. av_log(hwfc, AV_LOG_ERROR, "Unable to init command buffer: %s\n",
  757. vk_ret2str(ret));
  758. return AVERROR_EXTERNAL;
  759. }
  760. return 0;
  761. }
  762. static int add_buf_dep_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd,
  763. AVBufferRef * const *deps, int nb_deps)
  764. {
  765. AVBufferRef **dst;
  766. VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
  767. if (!deps || !nb_deps)
  768. return 0;
  769. dst = av_fast_realloc(q->buf_deps, &q->buf_deps_alloc_size,
  770. (q->nb_buf_deps + nb_deps) * sizeof(*dst));
  771. if (!dst)
  772. goto err;
  773. q->buf_deps = dst;
  774. for (int i = 0; i < nb_deps; i++) {
  775. q->buf_deps[q->nb_buf_deps] = av_buffer_ref(deps[i]);
  776. if (!q->buf_deps[q->nb_buf_deps])
  777. goto err;
  778. q->nb_buf_deps++;
  779. }
  780. return 0;
  781. err:
  782. unref_exec_ctx_deps(hwfc, cmd);
  783. return AVERROR(ENOMEM);
  784. }
  785. static int submit_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd,
  786. VkSubmitInfo *s_info, int synchronous)
  787. {
  788. VkResult ret;
  789. VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
  790. ret = vkEndCommandBuffer(cmd->bufs[cmd->cur_queue_idx]);
  791. if (ret != VK_SUCCESS) {
  792. av_log(hwfc, AV_LOG_ERROR, "Unable to finish command buffer: %s\n",
  793. vk_ret2str(ret));
  794. unref_exec_ctx_deps(hwfc, cmd);
  795. return AVERROR_EXTERNAL;
  796. }
  797. s_info->pCommandBuffers = &cmd->bufs[cmd->cur_queue_idx];
  798. s_info->commandBufferCount = 1;
  799. ret = vkQueueSubmit(q->queue, 1, s_info, q->fence);
  800. if (ret != VK_SUCCESS) {
  801. unref_exec_ctx_deps(hwfc, cmd);
  802. return AVERROR_EXTERNAL;
  803. }
  804. q->was_synchronous = synchronous;
  805. if (synchronous) {
  806. AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
  807. vkWaitForFences(hwctx->act_dev, 1, &q->fence, VK_TRUE, UINT64_MAX);
  808. vkResetFences(hwctx->act_dev, 1, &q->fence);
  809. unref_exec_ctx_deps(hwfc, cmd);
  810. } else { /* Rotate queues */
  811. cmd->cur_queue_idx = (cmd->cur_queue_idx + 1) % cmd->nb_queues;
  812. }
  813. return 0;
  814. }
  815. static void vulkan_device_free(AVHWDeviceContext *ctx)
  816. {
  817. VulkanDevicePriv *p = ctx->internal->priv;
  818. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  819. vkDestroyDevice(hwctx->act_dev, hwctx->alloc);
  820. if (p->debug_ctx) {
  821. VK_LOAD_PFN(hwctx->inst, vkDestroyDebugUtilsMessengerEXT);
  822. pfn_vkDestroyDebugUtilsMessengerEXT(hwctx->inst, p->debug_ctx,
  823. hwctx->alloc);
  824. }
  825. vkDestroyInstance(hwctx->inst, hwctx->alloc);
  826. for (int i = 0; i < hwctx->nb_enabled_inst_extensions; i++)
  827. av_free((void *)hwctx->enabled_inst_extensions[i]);
  828. av_free((void *)hwctx->enabled_inst_extensions);
  829. for (int i = 0; i < hwctx->nb_enabled_dev_extensions; i++)
  830. av_free((void *)hwctx->enabled_dev_extensions[i]);
  831. av_free((void *)hwctx->enabled_dev_extensions);
  832. }
  833. static int vulkan_device_create_internal(AVHWDeviceContext *ctx,
  834. VulkanDeviceSelection *dev_select,
  835. AVDictionary *opts, int flags)
  836. {
  837. int err = 0;
  838. VkResult ret;
  839. AVDictionaryEntry *opt_d;
  840. VulkanDevicePriv *p = ctx->internal->priv;
  841. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  842. VkPhysicalDeviceFeatures dev_features = { 0 };
  843. VkDeviceQueueCreateInfo queue_create_info[3] = {
  844. { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, },
  845. { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, },
  846. { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, },
  847. };
  848. VkDeviceCreateInfo dev_info = {
  849. .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
  850. .pNext = &hwctx->device_features,
  851. .pQueueCreateInfos = queue_create_info,
  852. .queueCreateInfoCount = 0,
  853. };
  854. hwctx->device_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  855. ctx->free = vulkan_device_free;
  856. /* Create an instance if not given one */
  857. if ((err = create_instance(ctx, opts)))
  858. goto end;
  859. /* Find a device (if not given one) */
  860. if ((err = find_device(ctx, dev_select)))
  861. goto end;
  862. vkGetPhysicalDeviceFeatures(hwctx->phys_dev, &dev_features);
  863. #define COPY_FEATURE(DST, NAME) (DST).features.NAME = dev_features.NAME;
  864. COPY_FEATURE(hwctx->device_features, shaderImageGatherExtended)
  865. COPY_FEATURE(hwctx->device_features, fragmentStoresAndAtomics)
  866. COPY_FEATURE(hwctx->device_features, vertexPipelineStoresAndAtomics)
  867. COPY_FEATURE(hwctx->device_features, shaderInt64)
  868. #undef COPY_FEATURE
  869. /* Search queue family */
  870. if ((err = search_queue_families(ctx, &dev_info)))
  871. goto end;
  872. if ((err = check_extensions(ctx, 1, opts, &dev_info.ppEnabledExtensionNames,
  873. &dev_info.enabledExtensionCount, 0))) {
  874. av_free((void *)queue_create_info[0].pQueuePriorities);
  875. av_free((void *)queue_create_info[1].pQueuePriorities);
  876. av_free((void *)queue_create_info[2].pQueuePriorities);
  877. goto end;
  878. }
  879. ret = vkCreateDevice(hwctx->phys_dev, &dev_info, hwctx->alloc,
  880. &hwctx->act_dev);
  881. av_free((void *)queue_create_info[0].pQueuePriorities);
  882. av_free((void *)queue_create_info[1].pQueuePriorities);
  883. av_free((void *)queue_create_info[2].pQueuePriorities);
  884. if (ret != VK_SUCCESS) {
  885. av_log(ctx, AV_LOG_ERROR, "Device creation failure: %s\n",
  886. vk_ret2str(ret));
  887. for (int i = 0; i < dev_info.enabledExtensionCount; i++)
  888. av_free((void *)dev_info.ppEnabledExtensionNames[i]);
  889. av_free((void *)dev_info.ppEnabledExtensionNames);
  890. err = AVERROR_EXTERNAL;
  891. goto end;
  892. }
  893. /* Tiled images setting, use them by default */
  894. opt_d = av_dict_get(opts, "linear_images", NULL, 0);
  895. if (opt_d)
  896. p->use_linear_images = strtol(opt_d->value, NULL, 10);
  897. hwctx->enabled_dev_extensions = dev_info.ppEnabledExtensionNames;
  898. hwctx->nb_enabled_dev_extensions = dev_info.enabledExtensionCount;
  899. end:
  900. return err;
  901. }
  902. static int vulkan_device_init(AVHWDeviceContext *ctx)
  903. {
  904. uint32_t queue_num;
  905. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  906. VulkanDevicePriv *p = ctx->internal->priv;
  907. /* Set device extension flags */
  908. for (int i = 0; i < hwctx->nb_enabled_dev_extensions; i++) {
  909. for (int j = 0; j < FF_ARRAY_ELEMS(optional_device_exts); j++) {
  910. if (!strcmp(hwctx->enabled_dev_extensions[i],
  911. optional_device_exts[j].name)) {
  912. av_log(ctx, AV_LOG_VERBOSE, "Using device extension %s\n",
  913. hwctx->enabled_dev_extensions[i]);
  914. p->extensions |= optional_device_exts[j].flag;
  915. break;
  916. }
  917. }
  918. }
  919. p->props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
  920. p->props.pNext = &p->hprops;
  921. p->hprops.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT;
  922. vkGetPhysicalDeviceProperties2(hwctx->phys_dev, &p->props);
  923. av_log(ctx, AV_LOG_VERBOSE, "Using device: %s\n",
  924. p->props.properties.deviceName);
  925. av_log(ctx, AV_LOG_VERBOSE, "Alignments:\n");
  926. av_log(ctx, AV_LOG_VERBOSE, " optimalBufferCopyRowPitchAlignment: %li\n",
  927. p->props.properties.limits.optimalBufferCopyRowPitchAlignment);
  928. av_log(ctx, AV_LOG_VERBOSE, " minMemoryMapAlignment: %li\n",
  929. p->props.properties.limits.minMemoryMapAlignment);
  930. if (p->extensions & EXT_EXTERNAL_HOST_MEMORY)
  931. av_log(ctx, AV_LOG_VERBOSE, " minImportedHostPointerAlignment: %li\n",
  932. p->hprops.minImportedHostPointerAlignment);
  933. p->dev_is_nvidia = (p->props.properties.vendorID == 0x10de);
  934. vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &queue_num, NULL);
  935. if (!queue_num) {
  936. av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
  937. return AVERROR_EXTERNAL;
  938. }
  939. #define CHECK_QUEUE(type, n) \
  940. if (n >= queue_num) { \
  941. av_log(ctx, AV_LOG_ERROR, "Invalid %s queue index %i (device has %i queues)!\n", \
  942. type, n, queue_num); \
  943. return AVERROR(EINVAL); \
  944. }
  945. CHECK_QUEUE("graphics", hwctx->queue_family_index)
  946. CHECK_QUEUE("upload", hwctx->queue_family_tx_index)
  947. CHECK_QUEUE("compute", hwctx->queue_family_comp_index)
  948. #undef CHECK_QUEUE
  949. p->qfs[p->num_qfs++] = hwctx->queue_family_index;
  950. if ((hwctx->queue_family_tx_index != hwctx->queue_family_index) &&
  951. (hwctx->queue_family_tx_index != hwctx->queue_family_comp_index))
  952. p->qfs[p->num_qfs++] = hwctx->queue_family_tx_index;
  953. if ((hwctx->queue_family_comp_index != hwctx->queue_family_index) &&
  954. (hwctx->queue_family_comp_index != hwctx->queue_family_tx_index))
  955. p->qfs[p->num_qfs++] = hwctx->queue_family_comp_index;
  956. /* Get device capabilities */
  957. vkGetPhysicalDeviceMemoryProperties(hwctx->phys_dev, &p->mprops);
  958. return 0;
  959. }
  960. static int vulkan_device_create(AVHWDeviceContext *ctx, const char *device,
  961. AVDictionary *opts, int flags)
  962. {
  963. VulkanDeviceSelection dev_select = { 0 };
  964. if (device && device[0]) {
  965. char *end = NULL;
  966. dev_select.index = strtol(device, &end, 10);
  967. if (end == device) {
  968. dev_select.index = 0;
  969. dev_select.name = device;
  970. }
  971. }
  972. return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
  973. }
  974. static int vulkan_device_derive(AVHWDeviceContext *ctx,
  975. AVHWDeviceContext *src_ctx,
  976. AVDictionary *opts, int flags)
  977. {
  978. av_unused VulkanDeviceSelection dev_select = { 0 };
  979. /* If there's only one device on the system, then even if its not covered
  980. * by the following checks (e.g. non-PCIe ARM GPU), having an empty
  981. * dev_select will mean it'll get picked. */
  982. switch(src_ctx->type) {
  983. #if CONFIG_LIBDRM
  984. #if CONFIG_VAAPI
  985. case AV_HWDEVICE_TYPE_VAAPI: {
  986. AVVAAPIDeviceContext *src_hwctx = src_ctx->hwctx;
  987. const char *vendor = vaQueryVendorString(src_hwctx->display);
  988. if (!vendor) {
  989. av_log(ctx, AV_LOG_ERROR, "Unable to get device info from VAAPI!\n");
  990. return AVERROR_EXTERNAL;
  991. }
  992. if (strstr(vendor, "Intel"))
  993. dev_select.vendor_id = 0x8086;
  994. if (strstr(vendor, "AMD"))
  995. dev_select.vendor_id = 0x1002;
  996. return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
  997. }
  998. #endif
  999. case AV_HWDEVICE_TYPE_DRM: {
  1000. AVDRMDeviceContext *src_hwctx = src_ctx->hwctx;
  1001. drmDevice *drm_dev_info;
  1002. int err = drmGetDevice(src_hwctx->fd, &drm_dev_info);
  1003. if (err) {
  1004. av_log(ctx, AV_LOG_ERROR, "Unable to get device info from DRM fd!\n");
  1005. return AVERROR_EXTERNAL;
  1006. }
  1007. if (drm_dev_info->bustype == DRM_BUS_PCI)
  1008. dev_select.pci_device = drm_dev_info->deviceinfo.pci->device_id;
  1009. drmFreeDevice(&drm_dev_info);
  1010. return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
  1011. }
  1012. #endif
  1013. #if CONFIG_CUDA
  1014. case AV_HWDEVICE_TYPE_CUDA: {
  1015. AVHWDeviceContext *cuda_cu = src_ctx;
  1016. AVCUDADeviceContext *src_hwctx = src_ctx->hwctx;
  1017. AVCUDADeviceContextInternal *cu_internal = src_hwctx->internal;
  1018. CudaFunctions *cu = cu_internal->cuda_dl;
  1019. int ret = CHECK_CU(cu->cuDeviceGetUuid((CUuuid *)&dev_select.uuid,
  1020. cu_internal->cuda_device));
  1021. if (ret < 0) {
  1022. av_log(ctx, AV_LOG_ERROR, "Unable to get UUID from CUDA!\n");
  1023. return AVERROR_EXTERNAL;
  1024. }
  1025. dev_select.has_uuid = 1;
  1026. return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
  1027. }
  1028. #endif
  1029. default:
  1030. return AVERROR(ENOSYS);
  1031. }
  1032. }
  1033. static int vulkan_frames_get_constraints(AVHWDeviceContext *ctx,
  1034. const void *hwconfig,
  1035. AVHWFramesConstraints *constraints)
  1036. {
  1037. int count = 0;
  1038. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  1039. VulkanDevicePriv *p = ctx->internal->priv;
  1040. for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
  1041. count += pixfmt_is_supported(hwctx, i, p->use_linear_images);
  1042. #if CONFIG_CUDA
  1043. if (p->dev_is_nvidia)
  1044. count++;
  1045. #endif
  1046. constraints->valid_sw_formats = av_malloc_array(count + 1,
  1047. sizeof(enum AVPixelFormat));
  1048. if (!constraints->valid_sw_formats)
  1049. return AVERROR(ENOMEM);
  1050. count = 0;
  1051. for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
  1052. if (pixfmt_is_supported(hwctx, i, p->use_linear_images))
  1053. constraints->valid_sw_formats[count++] = i;
  1054. #if CONFIG_CUDA
  1055. if (p->dev_is_nvidia)
  1056. constraints->valid_sw_formats[count++] = AV_PIX_FMT_CUDA;
  1057. #endif
  1058. constraints->valid_sw_formats[count++] = AV_PIX_FMT_NONE;
  1059. constraints->min_width = 0;
  1060. constraints->min_height = 0;
  1061. constraints->max_width = p->props.properties.limits.maxImageDimension2D;
  1062. constraints->max_height = p->props.properties.limits.maxImageDimension2D;
  1063. constraints->valid_hw_formats = av_malloc_array(2, sizeof(enum AVPixelFormat));
  1064. if (!constraints->valid_hw_formats)
  1065. return AVERROR(ENOMEM);
  1066. constraints->valid_hw_formats[0] = AV_PIX_FMT_VULKAN;
  1067. constraints->valid_hw_formats[1] = AV_PIX_FMT_NONE;
  1068. return 0;
  1069. }
  1070. static int alloc_mem(AVHWDeviceContext *ctx, VkMemoryRequirements *req,
  1071. VkMemoryPropertyFlagBits req_flags, const void *alloc_extension,
  1072. VkMemoryPropertyFlagBits *mem_flags, VkDeviceMemory *mem)
  1073. {
  1074. VkResult ret;
  1075. int index = -1;
  1076. VulkanDevicePriv *p = ctx->internal->priv;
  1077. AVVulkanDeviceContext *dev_hwctx = ctx->hwctx;
  1078. VkMemoryAllocateInfo alloc_info = {
  1079. .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
  1080. .pNext = alloc_extension,
  1081. .allocationSize = req->size,
  1082. };
  1083. /* The vulkan spec requires memory types to be sorted in the "optimal"
  1084. * order, so the first matching type we find will be the best/fastest one */
  1085. for (int i = 0; i < p->mprops.memoryTypeCount; i++) {
  1086. /* The memory type must be supported by the requirements (bitfield) */
  1087. if (!(req->memoryTypeBits & (1 << i)))
  1088. continue;
  1089. /* The memory type flags must include our properties */
  1090. if ((p->mprops.memoryTypes[i].propertyFlags & req_flags) != req_flags)
  1091. continue;
  1092. /* Found a suitable memory type */
  1093. index = i;
  1094. break;
  1095. }
  1096. if (index < 0) {
  1097. av_log(ctx, AV_LOG_ERROR, "No memory type found for flags 0x%x\n",
  1098. req_flags);
  1099. return AVERROR(EINVAL);
  1100. }
  1101. alloc_info.memoryTypeIndex = index;
  1102. ret = vkAllocateMemory(dev_hwctx->act_dev, &alloc_info,
  1103. dev_hwctx->alloc, mem);
  1104. if (ret != VK_SUCCESS) {
  1105. av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory: %s\n",
  1106. vk_ret2str(ret));
  1107. return AVERROR(ENOMEM);
  1108. }
  1109. *mem_flags |= p->mprops.memoryTypes[index].propertyFlags;
  1110. return 0;
  1111. }
  1112. static void vulkan_free_internal(AVVkFrameInternal *internal)
  1113. {
  1114. if (!internal)
  1115. return;
  1116. #if CONFIG_CUDA
  1117. if (internal->cuda_fc_ref) {
  1118. AVHWFramesContext *cuda_fc = (AVHWFramesContext *)internal->cuda_fc_ref->data;
  1119. int planes = av_pix_fmt_count_planes(cuda_fc->sw_format);
  1120. AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
  1121. AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
  1122. AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
  1123. CudaFunctions *cu = cu_internal->cuda_dl;
  1124. for (int i = 0; i < planes; i++) {
  1125. if (internal->cu_sem[i])
  1126. CHECK_CU(cu->cuDestroyExternalSemaphore(internal->cu_sem[i]));
  1127. if (internal->cu_mma[i])
  1128. CHECK_CU(cu->cuMipmappedArrayDestroy(internal->cu_mma[i]));
  1129. if (internal->ext_mem[i])
  1130. CHECK_CU(cu->cuDestroyExternalMemory(internal->ext_mem[i]));
  1131. }
  1132. av_buffer_unref(&internal->cuda_fc_ref);
  1133. }
  1134. #endif
  1135. av_free(internal);
  1136. }
  1137. static void vulkan_frame_free(void *opaque, uint8_t *data)
  1138. {
  1139. AVVkFrame *f = (AVVkFrame *)data;
  1140. AVHWFramesContext *hwfc = opaque;
  1141. AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
  1142. int planes = av_pix_fmt_count_planes(hwfc->sw_format);
  1143. vulkan_free_internal(f->internal);
  1144. for (int i = 0; i < planes; i++) {
  1145. vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
  1146. vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
  1147. vkDestroySemaphore(hwctx->act_dev, f->sem[i], hwctx->alloc);
  1148. }
  1149. av_free(f);
  1150. }
  1151. static int alloc_bind_mem(AVHWFramesContext *hwfc, AVVkFrame *f,
  1152. void *alloc_pnext, size_t alloc_pnext_stride)
  1153. {
  1154. int err;
  1155. VkResult ret;
  1156. AVHWDeviceContext *ctx = hwfc->device_ctx;
  1157. VulkanDevicePriv *p = ctx->internal->priv;
  1158. const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
  1159. VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { { 0 } };
  1160. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  1161. for (int i = 0; i < planes; i++) {
  1162. int use_ded_mem;
  1163. VkImageMemoryRequirementsInfo2 req_desc = {
  1164. .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
  1165. .image = f->img[i],
  1166. };
  1167. VkMemoryDedicatedAllocateInfo ded_alloc = {
  1168. .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
  1169. .pNext = (void *)(((uint8_t *)alloc_pnext) + i*alloc_pnext_stride),
  1170. };
  1171. VkMemoryDedicatedRequirements ded_req = {
  1172. .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
  1173. };
  1174. VkMemoryRequirements2 req = {
  1175. .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
  1176. .pNext = &ded_req,
  1177. };
  1178. vkGetImageMemoryRequirements2(hwctx->act_dev, &req_desc, &req);
  1179. if (f->tiling == VK_IMAGE_TILING_LINEAR)
  1180. req.memoryRequirements.size = FFALIGN(req.memoryRequirements.size,
  1181. p->props.properties.limits.minMemoryMapAlignment);
  1182. /* In case the implementation prefers/requires dedicated allocation */
  1183. use_ded_mem = ded_req.prefersDedicatedAllocation |
  1184. ded_req.requiresDedicatedAllocation;
  1185. if (use_ded_mem)
  1186. ded_alloc.image = f->img[i];
  1187. /* Allocate memory */
  1188. if ((err = alloc_mem(ctx, &req.memoryRequirements,
  1189. f->tiling == VK_IMAGE_TILING_LINEAR ?
  1190. VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT :
  1191. VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
  1192. use_ded_mem ? &ded_alloc : (void *)ded_alloc.pNext,
  1193. &f->flags, &f->mem[i])))
  1194. return err;
  1195. f->size[i] = req.memoryRequirements.size;
  1196. bind_info[i].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
  1197. bind_info[i].image = f->img[i];
  1198. bind_info[i].memory = f->mem[i];
  1199. }
  1200. /* Bind the allocated memory to the images */
  1201. ret = vkBindImageMemory2(hwctx->act_dev, planes, bind_info);
  1202. if (ret != VK_SUCCESS) {
  1203. av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
  1204. vk_ret2str(ret));
  1205. return AVERROR_EXTERNAL;
  1206. }
  1207. return 0;
  1208. }
  1209. enum PrepMode {
  1210. PREP_MODE_WRITE,
  1211. PREP_MODE_RO_SHADER,
  1212. PREP_MODE_EXTERNAL_EXPORT,
  1213. };
  1214. static int prepare_frame(AVHWFramesContext *hwfc, VulkanExecCtx *ectx,
  1215. AVVkFrame *frame, enum PrepMode pmode)
  1216. {
  1217. int err;
  1218. uint32_t dst_qf;
  1219. VkImageLayout new_layout;
  1220. VkAccessFlags new_access;
  1221. const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
  1222. VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
  1223. VkSubmitInfo s_info = {
  1224. .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
  1225. .pSignalSemaphores = frame->sem,
  1226. .signalSemaphoreCount = planes,
  1227. };
  1228. VkPipelineStageFlagBits wait_st[AV_NUM_DATA_POINTERS];
  1229. for (int i = 0; i < planes; i++)
  1230. wait_st[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
  1231. switch (pmode) {
  1232. case PREP_MODE_WRITE:
  1233. new_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  1234. new_access = VK_ACCESS_TRANSFER_WRITE_BIT;
  1235. dst_qf = VK_QUEUE_FAMILY_IGNORED;
  1236. break;
  1237. case PREP_MODE_RO_SHADER:
  1238. new_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  1239. new_access = VK_ACCESS_TRANSFER_READ_BIT;
  1240. dst_qf = VK_QUEUE_FAMILY_IGNORED;
  1241. break;
  1242. case PREP_MODE_EXTERNAL_EXPORT:
  1243. new_layout = VK_IMAGE_LAYOUT_GENERAL;
  1244. new_access = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
  1245. dst_qf = VK_QUEUE_FAMILY_EXTERNAL_KHR;
  1246. s_info.pWaitSemaphores = frame->sem;
  1247. s_info.pWaitDstStageMask = wait_st;
  1248. s_info.waitSemaphoreCount = planes;
  1249. break;
  1250. }
  1251. if ((err = wait_start_exec_ctx(hwfc, ectx)))
  1252. return err;
  1253. /* Change the image layout to something more optimal for writes.
  1254. * This also signals the newly created semaphore, making it usable
  1255. * for synchronization */
  1256. for (int i = 0; i < planes; i++) {
  1257. img_bar[i].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  1258. img_bar[i].srcAccessMask = 0x0;
  1259. img_bar[i].dstAccessMask = new_access;
  1260. img_bar[i].oldLayout = frame->layout[i];
  1261. img_bar[i].newLayout = new_layout;
  1262. img_bar[i].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  1263. img_bar[i].dstQueueFamilyIndex = dst_qf;
  1264. img_bar[i].image = frame->img[i];
  1265. img_bar[i].subresourceRange.levelCount = 1;
  1266. img_bar[i].subresourceRange.layerCount = 1;
  1267. img_bar[i].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  1268. frame->layout[i] = img_bar[i].newLayout;
  1269. frame->access[i] = img_bar[i].dstAccessMask;
  1270. }
  1271. vkCmdPipelineBarrier(get_buf_exec_ctx(hwfc, ectx),
  1272. VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
  1273. VK_PIPELINE_STAGE_TRANSFER_BIT,
  1274. 0, 0, NULL, 0, NULL, planes, img_bar);
  1275. return submit_exec_ctx(hwfc, ectx, &s_info, 0);
  1276. }
  1277. static int create_frame(AVHWFramesContext *hwfc, AVVkFrame **frame,
  1278. VkImageTiling tiling, VkImageUsageFlagBits usage,
  1279. void *create_pnext)
  1280. {
  1281. int err;
  1282. VkResult ret;
  1283. AVHWDeviceContext *ctx = hwfc->device_ctx;
  1284. VulkanDevicePriv *p = ctx->internal->priv;
  1285. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  1286. enum AVPixelFormat format = hwfc->sw_format;
  1287. const VkFormat *img_fmts = av_vkfmt_from_pixfmt(format);
  1288. const int planes = av_pix_fmt_count_planes(format);
  1289. VkExportSemaphoreCreateInfo ext_sem_info = {
  1290. .sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO,
  1291. .handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
  1292. };
  1293. VkSemaphoreCreateInfo sem_spawn = {
  1294. .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
  1295. .pNext = p->extensions & EXT_EXTERNAL_FD_SEM ? &ext_sem_info : NULL,
  1296. };
  1297. AVVkFrame *f = av_vk_frame_alloc();
  1298. if (!f) {
  1299. av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
  1300. return AVERROR(ENOMEM);
  1301. }
  1302. /* Create the images */
  1303. for (int i = 0; i < planes; i++) {
  1304. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
  1305. int w = hwfc->width;
  1306. int h = hwfc->height;
  1307. const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
  1308. const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
  1309. VkImageCreateInfo image_create_info = {
  1310. .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
  1311. .pNext = create_pnext,
  1312. .imageType = VK_IMAGE_TYPE_2D,
  1313. .format = img_fmts[i],
  1314. .extent.width = p_w,
  1315. .extent.height = p_h,
  1316. .extent.depth = 1,
  1317. .mipLevels = 1,
  1318. .arrayLayers = 1,
  1319. .flags = VK_IMAGE_CREATE_ALIAS_BIT,
  1320. .tiling = tiling,
  1321. .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
  1322. .usage = usage,
  1323. .samples = VK_SAMPLE_COUNT_1_BIT,
  1324. .pQueueFamilyIndices = p->qfs,
  1325. .queueFamilyIndexCount = p->num_qfs,
  1326. .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
  1327. VK_SHARING_MODE_EXCLUSIVE,
  1328. };
  1329. ret = vkCreateImage(hwctx->act_dev, &image_create_info,
  1330. hwctx->alloc, &f->img[i]);
  1331. if (ret != VK_SUCCESS) {
  1332. av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
  1333. vk_ret2str(ret));
  1334. err = AVERROR(EINVAL);
  1335. goto fail;
  1336. }
  1337. /* Create semaphore */
  1338. ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
  1339. hwctx->alloc, &f->sem[i]);
  1340. if (ret != VK_SUCCESS) {
  1341. av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
  1342. vk_ret2str(ret));
  1343. return AVERROR_EXTERNAL;
  1344. }
  1345. f->layout[i] = image_create_info.initialLayout;
  1346. f->access[i] = 0x0;
  1347. }
  1348. f->flags = 0x0;
  1349. f->tiling = tiling;
  1350. *frame = f;
  1351. return 0;
  1352. fail:
  1353. vulkan_frame_free(hwfc, (uint8_t *)f);
  1354. return err;
  1355. }
  1356. /* Checks if an export flag is enabled, and if it is ORs it with *iexp */
  1357. static void try_export_flags(AVHWFramesContext *hwfc,
  1358. VkExternalMemoryHandleTypeFlags *comp_handle_types,
  1359. VkExternalMemoryHandleTypeFlagBits *iexp,
  1360. VkExternalMemoryHandleTypeFlagBits exp)
  1361. {
  1362. VkResult ret;
  1363. AVVulkanFramesContext *hwctx = hwfc->hwctx;
  1364. AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
  1365. VkExternalImageFormatProperties eprops = {
  1366. .sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES_KHR,
  1367. };
  1368. VkImageFormatProperties2 props = {
  1369. .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,
  1370. .pNext = &eprops,
  1371. };
  1372. VkPhysicalDeviceExternalImageFormatInfo enext = {
  1373. .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
  1374. .handleType = exp,
  1375. };
  1376. VkPhysicalDeviceImageFormatInfo2 pinfo = {
  1377. .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
  1378. .pNext = !exp ? NULL : &enext,
  1379. .format = av_vkfmt_from_pixfmt(hwfc->sw_format)[0],
  1380. .type = VK_IMAGE_TYPE_2D,
  1381. .tiling = hwctx->tiling,
  1382. .usage = hwctx->usage,
  1383. .flags = VK_IMAGE_CREATE_ALIAS_BIT,
  1384. };
  1385. ret = vkGetPhysicalDeviceImageFormatProperties2(dev_hwctx->phys_dev,
  1386. &pinfo, &props);
  1387. if (ret == VK_SUCCESS) {
  1388. *iexp |= exp;
  1389. *comp_handle_types |= eprops.externalMemoryProperties.compatibleHandleTypes;
  1390. }
  1391. }
  1392. static AVBufferRef *vulkan_pool_alloc(void *opaque, int size)
  1393. {
  1394. int err;
  1395. AVVkFrame *f;
  1396. AVBufferRef *avbuf = NULL;
  1397. AVHWFramesContext *hwfc = opaque;
  1398. AVVulkanFramesContext *hwctx = hwfc->hwctx;
  1399. VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
  1400. VulkanFramesPriv *fp = hwfc->internal->priv;
  1401. VkExportMemoryAllocateInfo eminfo[AV_NUM_DATA_POINTERS];
  1402. VkExternalMemoryHandleTypeFlags e = 0x0;
  1403. VkExternalMemoryImageCreateInfo eiinfo = {
  1404. .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
  1405. .pNext = hwctx->create_pnext,
  1406. };
  1407. if (p->extensions & EXT_EXTERNAL_FD_MEMORY)
  1408. try_export_flags(hwfc, &eiinfo.handleTypes, &e,
  1409. VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT);
  1410. if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
  1411. try_export_flags(hwfc, &eiinfo.handleTypes, &e,
  1412. VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
  1413. for (int i = 0; i < av_pix_fmt_count_planes(hwfc->sw_format); i++) {
  1414. eminfo[i].sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO;
  1415. eminfo[i].pNext = hwctx->alloc_pnext[i];
  1416. eminfo[i].handleTypes = e;
  1417. }
  1418. err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
  1419. eiinfo.handleTypes ? &eiinfo : NULL);
  1420. if (err)
  1421. return NULL;
  1422. err = alloc_bind_mem(hwfc, f, eminfo, sizeof(*eminfo));
  1423. if (err)
  1424. goto fail;
  1425. err = prepare_frame(hwfc, &fp->conv_ctx, f, PREP_MODE_WRITE);
  1426. if (err)
  1427. goto fail;
  1428. avbuf = av_buffer_create((uint8_t *)f, sizeof(AVVkFrame),
  1429. vulkan_frame_free, hwfc, 0);
  1430. if (!avbuf)
  1431. goto fail;
  1432. return avbuf;
  1433. fail:
  1434. vulkan_frame_free(hwfc, (uint8_t *)f);
  1435. return NULL;
  1436. }
  1437. static void vulkan_frames_uninit(AVHWFramesContext *hwfc)
  1438. {
  1439. VulkanFramesPriv *fp = hwfc->internal->priv;
  1440. free_exec_ctx(hwfc, &fp->conv_ctx);
  1441. free_exec_ctx(hwfc, &fp->upload_ctx);
  1442. free_exec_ctx(hwfc, &fp->download_ctx);
  1443. }
  1444. static int vulkan_frames_init(AVHWFramesContext *hwfc)
  1445. {
  1446. int err;
  1447. AVVkFrame *f;
  1448. AVVulkanFramesContext *hwctx = hwfc->hwctx;
  1449. VulkanFramesPriv *fp = hwfc->internal->priv;
  1450. AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
  1451. VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
  1452. /* Default pool flags */
  1453. hwctx->tiling = hwctx->tiling ? hwctx->tiling : p->use_linear_images ?
  1454. VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
  1455. if (!hwctx->usage)
  1456. hwctx->usage = DEFAULT_USAGE_FLAGS;
  1457. err = create_exec_ctx(hwfc, &fp->conv_ctx,
  1458. dev_hwctx->queue_family_comp_index,
  1459. GET_QUEUE_COUNT(dev_hwctx, 0, 1, 0));
  1460. if (err)
  1461. goto fail;
  1462. err = create_exec_ctx(hwfc, &fp->upload_ctx,
  1463. dev_hwctx->queue_family_tx_index,
  1464. GET_QUEUE_COUNT(dev_hwctx, 0, 0, 1));
  1465. if (err)
  1466. goto fail;
  1467. err = create_exec_ctx(hwfc, &fp->download_ctx,
  1468. dev_hwctx->queue_family_tx_index, 1);
  1469. if (err)
  1470. goto fail;
  1471. /* Test to see if allocation will fail */
  1472. err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
  1473. hwctx->create_pnext);
  1474. if (err)
  1475. goto fail;
  1476. vulkan_frame_free(hwfc, (uint8_t *)f);
  1477. /* If user did not specify a pool, hwfc->pool will be set to the internal one
  1478. * in hwcontext.c just after this gets called */
  1479. if (!hwfc->pool) {
  1480. hwfc->internal->pool_internal = av_buffer_pool_init2(sizeof(AVVkFrame),
  1481. hwfc, vulkan_pool_alloc,
  1482. NULL);
  1483. if (!hwfc->internal->pool_internal) {
  1484. err = AVERROR(ENOMEM);
  1485. goto fail;
  1486. }
  1487. }
  1488. return 0;
  1489. fail:
  1490. free_exec_ctx(hwfc, &fp->conv_ctx);
  1491. free_exec_ctx(hwfc, &fp->upload_ctx);
  1492. free_exec_ctx(hwfc, &fp->download_ctx);
  1493. return err;
  1494. }
  1495. static int vulkan_get_buffer(AVHWFramesContext *hwfc, AVFrame *frame)
  1496. {
  1497. frame->buf[0] = av_buffer_pool_get(hwfc->pool);
  1498. if (!frame->buf[0])
  1499. return AVERROR(ENOMEM);
  1500. frame->data[0] = frame->buf[0]->data;
  1501. frame->format = AV_PIX_FMT_VULKAN;
  1502. frame->width = hwfc->width;
  1503. frame->height = hwfc->height;
  1504. return 0;
  1505. }
  1506. static int vulkan_transfer_get_formats(AVHWFramesContext *hwfc,
  1507. enum AVHWFrameTransferDirection dir,
  1508. enum AVPixelFormat **formats)
  1509. {
  1510. enum AVPixelFormat *fmts = av_malloc_array(2, sizeof(*fmts));
  1511. if (!fmts)
  1512. return AVERROR(ENOMEM);
  1513. fmts[0] = hwfc->sw_format;
  1514. fmts[1] = AV_PIX_FMT_NONE;
  1515. *formats = fmts;
  1516. return 0;
  1517. }
  1518. typedef struct VulkanMapping {
  1519. AVVkFrame *frame;
  1520. int flags;
  1521. } VulkanMapping;
  1522. static void vulkan_unmap_frame(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
  1523. {
  1524. VulkanMapping *map = hwmap->priv;
  1525. AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
  1526. const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
  1527. /* Check if buffer needs flushing */
  1528. if ((map->flags & AV_HWFRAME_MAP_WRITE) &&
  1529. !(map->frame->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
  1530. VkResult ret;
  1531. VkMappedMemoryRange flush_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
  1532. for (int i = 0; i < planes; i++) {
  1533. flush_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
  1534. flush_ranges[i].memory = map->frame->mem[i];
  1535. flush_ranges[i].size = VK_WHOLE_SIZE;
  1536. }
  1537. ret = vkFlushMappedMemoryRanges(hwctx->act_dev, planes,
  1538. flush_ranges);
  1539. if (ret != VK_SUCCESS) {
  1540. av_log(hwfc, AV_LOG_ERROR, "Failed to flush memory: %s\n",
  1541. vk_ret2str(ret));
  1542. }
  1543. }
  1544. for (int i = 0; i < planes; i++)
  1545. vkUnmapMemory(hwctx->act_dev, map->frame->mem[i]);
  1546. av_free(map);
  1547. }
  1548. static int vulkan_map_frame_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
  1549. const AVFrame *src, int flags)
  1550. {
  1551. VkResult ret;
  1552. int err, mapped_mem_count = 0;
  1553. AVVkFrame *f = (AVVkFrame *)src->data[0];
  1554. AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
  1555. const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
  1556. VulkanMapping *map = av_mallocz(sizeof(VulkanMapping));
  1557. if (!map)
  1558. return AVERROR(EINVAL);
  1559. if (src->format != AV_PIX_FMT_VULKAN) {
  1560. av_log(hwfc, AV_LOG_ERROR, "Cannot map from pixel format %s!\n",
  1561. av_get_pix_fmt_name(src->format));
  1562. err = AVERROR(EINVAL);
  1563. goto fail;
  1564. }
  1565. if (!(f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ||
  1566. !(f->tiling == VK_IMAGE_TILING_LINEAR)) {
  1567. av_log(hwfc, AV_LOG_ERROR, "Unable to map frame, not host visible "
  1568. "and linear!\n");
  1569. err = AVERROR(EINVAL);
  1570. goto fail;
  1571. }
  1572. dst->width = src->width;
  1573. dst->height = src->height;
  1574. for (int i = 0; i < planes; i++) {
  1575. ret = vkMapMemory(hwctx->act_dev, f->mem[i], 0,
  1576. VK_WHOLE_SIZE, 0, (void **)&dst->data[i]);
  1577. if (ret != VK_SUCCESS) {
  1578. av_log(hwfc, AV_LOG_ERROR, "Failed to map image memory: %s\n",
  1579. vk_ret2str(ret));
  1580. err = AVERROR_EXTERNAL;
  1581. goto fail;
  1582. }
  1583. mapped_mem_count++;
  1584. }
  1585. /* Check if the memory contents matter */
  1586. if (((flags & AV_HWFRAME_MAP_READ) || !(flags & AV_HWFRAME_MAP_OVERWRITE)) &&
  1587. !(f->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
  1588. VkMappedMemoryRange map_mem_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
  1589. for (int i = 0; i < planes; i++) {
  1590. map_mem_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
  1591. map_mem_ranges[i].size = VK_WHOLE_SIZE;
  1592. map_mem_ranges[i].memory = f->mem[i];
  1593. }
  1594. ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, planes,
  1595. map_mem_ranges);
  1596. if (ret != VK_SUCCESS) {
  1597. av_log(hwfc, AV_LOG_ERROR, "Failed to invalidate memory: %s\n",
  1598. vk_ret2str(ret));
  1599. err = AVERROR_EXTERNAL;
  1600. goto fail;
  1601. }
  1602. }
  1603. for (int i = 0; i < planes; i++) {
  1604. VkImageSubresource sub = {
  1605. .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
  1606. };
  1607. VkSubresourceLayout layout;
  1608. vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
  1609. dst->linesize[i] = layout.rowPitch;
  1610. }
  1611. map->frame = f;
  1612. map->flags = flags;
  1613. err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src,
  1614. &vulkan_unmap_frame, map);
  1615. if (err < 0)
  1616. goto fail;
  1617. return 0;
  1618. fail:
  1619. for (int i = 0; i < mapped_mem_count; i++)
  1620. vkUnmapMemory(hwctx->act_dev, f->mem[i]);
  1621. av_free(map);
  1622. return err;
  1623. }
  1624. #if CONFIG_LIBDRM
  1625. static void vulkan_unmap_from(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
  1626. {
  1627. VulkanMapping *map = hwmap->priv;
  1628. AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
  1629. const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
  1630. for (int i = 0; i < planes; i++) {
  1631. vkDestroyImage(hwctx->act_dev, map->frame->img[i], hwctx->alloc);
  1632. vkFreeMemory(hwctx->act_dev, map->frame->mem[i], hwctx->alloc);
  1633. vkDestroySemaphore(hwctx->act_dev, map->frame->sem[i], hwctx->alloc);
  1634. }
  1635. av_freep(&map->frame);
  1636. }
  1637. static const struct {
  1638. uint32_t drm_fourcc;
  1639. VkFormat vk_format;
  1640. } vulkan_drm_format_map[] = {
  1641. { DRM_FORMAT_R8, VK_FORMAT_R8_UNORM },
  1642. { DRM_FORMAT_R16, VK_FORMAT_R16_UNORM },
  1643. { DRM_FORMAT_GR88, VK_FORMAT_R8G8_UNORM },
  1644. { DRM_FORMAT_RG88, VK_FORMAT_R8G8_UNORM },
  1645. { DRM_FORMAT_GR1616, VK_FORMAT_R16G16_UNORM },
  1646. { DRM_FORMAT_RG1616, VK_FORMAT_R16G16_UNORM },
  1647. { DRM_FORMAT_ARGB8888, VK_FORMAT_B8G8R8A8_UNORM },
  1648. { DRM_FORMAT_XRGB8888, VK_FORMAT_B8G8R8A8_UNORM },
  1649. { DRM_FORMAT_ABGR8888, VK_FORMAT_R8G8B8A8_UNORM },
  1650. { DRM_FORMAT_XBGR8888, VK_FORMAT_R8G8B8A8_UNORM },
  1651. };
  1652. static inline VkFormat drm_to_vulkan_fmt(uint32_t drm_fourcc)
  1653. {
  1654. for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
  1655. if (vulkan_drm_format_map[i].drm_fourcc == drm_fourcc)
  1656. return vulkan_drm_format_map[i].vk_format;
  1657. return VK_FORMAT_UNDEFINED;
  1658. }
  1659. static int vulkan_map_from_drm_frame_desc(AVHWFramesContext *hwfc, AVVkFrame **frame,
  1660. AVDRMFrameDescriptor *desc)
  1661. {
  1662. int err = 0;
  1663. VkResult ret;
  1664. AVVkFrame *f;
  1665. int bind_counts = 0;
  1666. AVHWDeviceContext *ctx = hwfc->device_ctx;
  1667. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  1668. VulkanDevicePriv *p = ctx->internal->priv;
  1669. VulkanFramesPriv *fp = hwfc->internal->priv;
  1670. AVVulkanFramesContext *frames_hwctx = hwfc->hwctx;
  1671. const AVPixFmtDescriptor *fmt_desc = av_pix_fmt_desc_get(hwfc->sw_format);
  1672. const int has_modifiers = p->extensions & EXT_DRM_MODIFIER_FLAGS;
  1673. VkSubresourceLayout plane_data[AV_NUM_DATA_POINTERS] = { 0 };
  1674. VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { 0 };
  1675. VkBindImagePlaneMemoryInfo plane_info[AV_NUM_DATA_POINTERS] = { 0 };
  1676. VkExternalMemoryHandleTypeFlagBits htype = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
  1677. VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdPropertiesKHR);
  1678. for (int i = 0; i < desc->nb_layers; i++) {
  1679. if (drm_to_vulkan_fmt(desc->layers[i].format) == VK_FORMAT_UNDEFINED) {
  1680. av_log(ctx, AV_LOG_ERROR, "Unsupported DMABUF layer format %#08x!\n",
  1681. desc->layers[i].format);
  1682. return AVERROR(EINVAL);
  1683. }
  1684. }
  1685. if (!(f = av_vk_frame_alloc())) {
  1686. av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
  1687. err = AVERROR(ENOMEM);
  1688. goto fail;
  1689. }
  1690. f->tiling = has_modifiers ? VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT :
  1691. desc->objects[0].format_modifier == DRM_FORMAT_MOD_LINEAR ?
  1692. VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
  1693. for (int i = 0; i < desc->nb_layers; i++) {
  1694. const int planes = desc->layers[i].nb_planes;
  1695. VkImageDrmFormatModifierExplicitCreateInfoEXT drm_info = {
  1696. .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
  1697. .drmFormatModifier = desc->objects[0].format_modifier,
  1698. .drmFormatModifierPlaneCount = planes,
  1699. .pPlaneLayouts = (const VkSubresourceLayout *)&plane_data,
  1700. };
  1701. VkExternalMemoryImageCreateInfo einfo = {
  1702. .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
  1703. .pNext = has_modifiers ? &drm_info : NULL,
  1704. .handleTypes = htype,
  1705. };
  1706. VkSemaphoreCreateInfo sem_spawn = {
  1707. .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
  1708. };
  1709. const int p_w = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, fmt_desc->log2_chroma_w) : hwfc->width;
  1710. const int p_h = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, fmt_desc->log2_chroma_h) : hwfc->height;
  1711. VkImageCreateInfo image_create_info = {
  1712. .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
  1713. .pNext = &einfo,
  1714. .imageType = VK_IMAGE_TYPE_2D,
  1715. .format = drm_to_vulkan_fmt(desc->layers[i].format),
  1716. .extent.width = p_w,
  1717. .extent.height = p_h,
  1718. .extent.depth = 1,
  1719. .mipLevels = 1,
  1720. .arrayLayers = 1,
  1721. .flags = VK_IMAGE_CREATE_ALIAS_BIT,
  1722. .tiling = f->tiling,
  1723. .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, /* specs say so */
  1724. .usage = frames_hwctx->usage,
  1725. .samples = VK_SAMPLE_COUNT_1_BIT,
  1726. .pQueueFamilyIndices = p->qfs,
  1727. .queueFamilyIndexCount = p->num_qfs,
  1728. .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
  1729. VK_SHARING_MODE_EXCLUSIVE,
  1730. };
  1731. for (int j = 0; j < planes; j++) {
  1732. plane_data[j].offset = desc->layers[i].planes[j].offset;
  1733. plane_data[j].rowPitch = desc->layers[i].planes[j].pitch;
  1734. plane_data[j].size = 0; /* The specs say so for all 3 */
  1735. plane_data[j].arrayPitch = 0;
  1736. plane_data[j].depthPitch = 0;
  1737. }
  1738. /* Create image */
  1739. ret = vkCreateImage(hwctx->act_dev, &image_create_info,
  1740. hwctx->alloc, &f->img[i]);
  1741. if (ret != VK_SUCCESS) {
  1742. av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
  1743. vk_ret2str(ret));
  1744. err = AVERROR(EINVAL);
  1745. goto fail;
  1746. }
  1747. ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
  1748. hwctx->alloc, &f->sem[i]);
  1749. if (ret != VK_SUCCESS) {
  1750. av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
  1751. vk_ret2str(ret));
  1752. return AVERROR_EXTERNAL;
  1753. }
  1754. /* We'd import a semaphore onto the one we created using
  1755. * vkImportSemaphoreFdKHR but unfortunately neither DRM nor VAAPI
  1756. * offer us anything we could import and sync with, so instead
  1757. * just signal the semaphore we created. */
  1758. f->layout[i] = image_create_info.initialLayout;
  1759. f->access[i] = 0x0;
  1760. }
  1761. for (int i = 0; i < desc->nb_objects; i++) {
  1762. int use_ded_mem = 0;
  1763. VkMemoryFdPropertiesKHR fdmp = {
  1764. .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,
  1765. };
  1766. VkMemoryRequirements req = {
  1767. .size = desc->objects[i].size,
  1768. };
  1769. VkImportMemoryFdInfoKHR idesc = {
  1770. .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
  1771. .handleType = htype,
  1772. .fd = dup(desc->objects[i].fd),
  1773. };
  1774. VkMemoryDedicatedAllocateInfo ded_alloc = {
  1775. .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
  1776. .pNext = &idesc,
  1777. };
  1778. ret = pfn_vkGetMemoryFdPropertiesKHR(hwctx->act_dev, htype,
  1779. idesc.fd, &fdmp);
  1780. if (ret != VK_SUCCESS) {
  1781. av_log(hwfc, AV_LOG_ERROR, "Failed to get FD properties: %s\n",
  1782. vk_ret2str(ret));
  1783. err = AVERROR_EXTERNAL;
  1784. close(idesc.fd);
  1785. goto fail;
  1786. }
  1787. req.memoryTypeBits = fdmp.memoryTypeBits;
  1788. /* Dedicated allocation only makes sense if there's a one to one mapping
  1789. * between images and the memory backing them, so only check in this
  1790. * case. */
  1791. if (desc->nb_layers == desc->nb_objects) {
  1792. VkImageMemoryRequirementsInfo2 req_desc = {
  1793. .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
  1794. .image = f->img[i],
  1795. };
  1796. VkMemoryDedicatedRequirements ded_req = {
  1797. .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
  1798. };
  1799. VkMemoryRequirements2 req2 = {
  1800. .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
  1801. .pNext = &ded_req,
  1802. };
  1803. vkGetImageMemoryRequirements2(hwctx->act_dev, &req_desc, &req2);
  1804. use_ded_mem = ded_req.prefersDedicatedAllocation |
  1805. ded_req.requiresDedicatedAllocation;
  1806. if (use_ded_mem)
  1807. ded_alloc.image = f->img[i];
  1808. }
  1809. err = alloc_mem(ctx, &req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
  1810. use_ded_mem ? &ded_alloc : ded_alloc.pNext,
  1811. &f->flags, &f->mem[i]);
  1812. if (err) {
  1813. close(idesc.fd);
  1814. return err;
  1815. }
  1816. f->size[i] = desc->objects[i].size;
  1817. }
  1818. for (int i = 0; i < desc->nb_layers; i++) {
  1819. const int planes = desc->layers[i].nb_planes;
  1820. const int signal_p = has_modifiers && (planes > 1);
  1821. for (int j = 0; j < planes; j++) {
  1822. VkImageAspectFlagBits aspect = j == 0 ? VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
  1823. j == 1 ? VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT :
  1824. VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT;
  1825. plane_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO;
  1826. plane_info[bind_counts].planeAspect = aspect;
  1827. bind_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
  1828. bind_info[bind_counts].pNext = signal_p ? &plane_info[bind_counts] : NULL;
  1829. bind_info[bind_counts].image = f->img[i];
  1830. bind_info[bind_counts].memory = f->mem[desc->layers[i].planes[j].object_index];
  1831. bind_info[bind_counts].memoryOffset = desc->layers[i].planes[j].offset;
  1832. bind_counts++;
  1833. }
  1834. }
  1835. /* Bind the allocated memory to the images */
  1836. ret = vkBindImageMemory2(hwctx->act_dev, bind_counts, bind_info);
  1837. if (ret != VK_SUCCESS) {
  1838. av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
  1839. vk_ret2str(ret));
  1840. return AVERROR_EXTERNAL;
  1841. }
  1842. /* NOTE: This is completely uneccesary and unneeded once we can import
  1843. * semaphores from DRM. Otherwise we have to activate the semaphores.
  1844. * We're reusing the exec context that's also used for uploads/downloads. */
  1845. err = prepare_frame(hwfc, &fp->conv_ctx, f, PREP_MODE_RO_SHADER);
  1846. if (err)
  1847. goto fail;
  1848. *frame = f;
  1849. return 0;
  1850. fail:
  1851. for (int i = 0; i < desc->nb_layers; i++) {
  1852. vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
  1853. vkDestroySemaphore(hwctx->act_dev, f->sem[i], hwctx->alloc);
  1854. }
  1855. for (int i = 0; i < desc->nb_objects; i++)
  1856. vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
  1857. av_free(f);
  1858. return err;
  1859. }
  1860. static int vulkan_map_from_drm(AVHWFramesContext *hwfc, AVFrame *dst,
  1861. const AVFrame *src, int flags)
  1862. {
  1863. int err = 0;
  1864. AVVkFrame *f;
  1865. VulkanMapping *map = NULL;
  1866. err = vulkan_map_from_drm_frame_desc(hwfc, &f,
  1867. (AVDRMFrameDescriptor *)src->data[0]);
  1868. if (err)
  1869. return err;
  1870. /* The unmapping function will free this */
  1871. dst->data[0] = (uint8_t *)f;
  1872. dst->width = src->width;
  1873. dst->height = src->height;
  1874. map = av_mallocz(sizeof(VulkanMapping));
  1875. if (!map)
  1876. goto fail;
  1877. map->frame = f;
  1878. map->flags = flags;
  1879. err = ff_hwframe_map_create(dst->hw_frames_ctx, dst, src,
  1880. &vulkan_unmap_from, map);
  1881. if (err < 0)
  1882. goto fail;
  1883. av_log(hwfc, AV_LOG_DEBUG, "Mapped DRM object to Vulkan!\n");
  1884. return 0;
  1885. fail:
  1886. vulkan_frame_free(hwfc->device_ctx->hwctx, (uint8_t *)f);
  1887. av_free(map);
  1888. return err;
  1889. }
  1890. #if CONFIG_VAAPI
  1891. static int vulkan_map_from_vaapi(AVHWFramesContext *dst_fc,
  1892. AVFrame *dst, const AVFrame *src,
  1893. int flags)
  1894. {
  1895. int err;
  1896. AVFrame *tmp = av_frame_alloc();
  1897. AVHWFramesContext *vaapi_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
  1898. AVVAAPIDeviceContext *vaapi_ctx = vaapi_fc->device_ctx->hwctx;
  1899. VASurfaceID surface_id = (VASurfaceID)(uintptr_t)src->data[3];
  1900. if (!tmp)
  1901. return AVERROR(ENOMEM);
  1902. /* We have to sync since like the previous comment said, no semaphores */
  1903. vaSyncSurface(vaapi_ctx->display, surface_id);
  1904. tmp->format = AV_PIX_FMT_DRM_PRIME;
  1905. err = av_hwframe_map(tmp, src, flags);
  1906. if (err < 0)
  1907. goto fail;
  1908. err = vulkan_map_from_drm(dst_fc, dst, tmp, flags);
  1909. if (err < 0)
  1910. goto fail;
  1911. err = ff_hwframe_map_replace(dst, src);
  1912. fail:
  1913. av_frame_free(&tmp);
  1914. return err;
  1915. }
  1916. #endif
  1917. #endif
  1918. #if CONFIG_CUDA
  1919. static int vulkan_export_to_cuda(AVHWFramesContext *hwfc,
  1920. AVBufferRef *cuda_hwfc,
  1921. const AVFrame *frame)
  1922. {
  1923. int err;
  1924. VkResult ret;
  1925. AVVkFrame *dst_f;
  1926. AVVkFrameInternal *dst_int;
  1927. AVHWDeviceContext *ctx = hwfc->device_ctx;
  1928. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  1929. const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
  1930. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
  1931. VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
  1932. VK_LOAD_PFN(hwctx->inst, vkGetSemaphoreFdKHR);
  1933. AVHWFramesContext *cuda_fc = (AVHWFramesContext*)cuda_hwfc->data;
  1934. AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
  1935. AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
  1936. AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
  1937. CudaFunctions *cu = cu_internal->cuda_dl;
  1938. CUarray_format cufmt = desc->comp[0].depth > 8 ? CU_AD_FORMAT_UNSIGNED_INT16 :
  1939. CU_AD_FORMAT_UNSIGNED_INT8;
  1940. dst_f = (AVVkFrame *)frame->data[0];
  1941. dst_int = dst_f->internal;
  1942. if (!dst_int || !dst_int->cuda_fc_ref) {
  1943. if (!dst_f->internal)
  1944. dst_f->internal = dst_int = av_mallocz(sizeof(*dst_f->internal));
  1945. if (!dst_int) {
  1946. err = AVERROR(ENOMEM);
  1947. goto fail;
  1948. }
  1949. dst_int->cuda_fc_ref = av_buffer_ref(cuda_hwfc);
  1950. if (!dst_int->cuda_fc_ref) {
  1951. err = AVERROR(ENOMEM);
  1952. goto fail;
  1953. }
  1954. for (int i = 0; i < planes; i++) {
  1955. CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC tex_desc = {
  1956. .offset = 0,
  1957. .arrayDesc = {
  1958. .Width = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
  1959. : hwfc->width,
  1960. .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
  1961. : hwfc->height,
  1962. .Depth = 0,
  1963. .Format = cufmt,
  1964. .NumChannels = 1 + ((planes == 2) && i),
  1965. .Flags = 0,
  1966. },
  1967. .numLevels = 1,
  1968. };
  1969. CUDA_EXTERNAL_MEMORY_HANDLE_DESC ext_desc = {
  1970. .type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD,
  1971. .size = dst_f->size[i],
  1972. };
  1973. VkMemoryGetFdInfoKHR export_info = {
  1974. .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
  1975. .memory = dst_f->mem[i],
  1976. .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR,
  1977. };
  1978. VkSemaphoreGetFdInfoKHR sem_export = {
  1979. .sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR,
  1980. .semaphore = dst_f->sem[i],
  1981. .handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
  1982. };
  1983. CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC ext_sem_desc = {
  1984. .type = CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD,
  1985. };
  1986. ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
  1987. &ext_desc.handle.fd);
  1988. if (ret != VK_SUCCESS) {
  1989. av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
  1990. err = AVERROR_EXTERNAL;
  1991. goto fail;
  1992. }
  1993. ret = CHECK_CU(cu->cuImportExternalMemory(&dst_int->ext_mem[i], &ext_desc));
  1994. if (ret < 0) {
  1995. err = AVERROR_EXTERNAL;
  1996. goto fail;
  1997. }
  1998. ret = CHECK_CU(cu->cuExternalMemoryGetMappedMipmappedArray(&dst_int->cu_mma[i],
  1999. dst_int->ext_mem[i],
  2000. &tex_desc));
  2001. if (ret < 0) {
  2002. err = AVERROR_EXTERNAL;
  2003. goto fail;
  2004. }
  2005. ret = CHECK_CU(cu->cuMipmappedArrayGetLevel(&dst_int->cu_array[i],
  2006. dst_int->cu_mma[i], 0));
  2007. if (ret < 0) {
  2008. err = AVERROR_EXTERNAL;
  2009. goto fail;
  2010. }
  2011. ret = pfn_vkGetSemaphoreFdKHR(hwctx->act_dev, &sem_export,
  2012. &ext_sem_desc.handle.fd);
  2013. if (ret != VK_SUCCESS) {
  2014. av_log(ctx, AV_LOG_ERROR, "Failed to export semaphore: %s\n",
  2015. vk_ret2str(ret));
  2016. err = AVERROR_EXTERNAL;
  2017. goto fail;
  2018. }
  2019. ret = CHECK_CU(cu->cuImportExternalSemaphore(&dst_int->cu_sem[i],
  2020. &ext_sem_desc));
  2021. if (ret < 0) {
  2022. err = AVERROR_EXTERNAL;
  2023. goto fail;
  2024. }
  2025. }
  2026. }
  2027. return 0;
  2028. fail:
  2029. return err;
  2030. }
  2031. static int vulkan_transfer_data_from_cuda(AVHWFramesContext *hwfc,
  2032. AVFrame *dst, const AVFrame *src)
  2033. {
  2034. int err;
  2035. VkResult ret;
  2036. CUcontext dummy;
  2037. AVVkFrame *dst_f;
  2038. AVVkFrameInternal *dst_int;
  2039. const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
  2040. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
  2041. AVHWFramesContext *cuda_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
  2042. AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
  2043. AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
  2044. AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
  2045. CudaFunctions *cu = cu_internal->cuda_dl;
  2046. CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS s_w_par[AV_NUM_DATA_POINTERS] = { 0 };
  2047. CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS s_s_par[AV_NUM_DATA_POINTERS] = { 0 };
  2048. ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
  2049. if (ret < 0)
  2050. return AVERROR_EXTERNAL;
  2051. dst_f = (AVVkFrame *)dst->data[0];
  2052. ret = vulkan_export_to_cuda(hwfc, src->hw_frames_ctx, dst);
  2053. if (ret < 0) {
  2054. CHECK_CU(cu->cuCtxPopCurrent(&dummy));
  2055. return ret;
  2056. }
  2057. dst_int = dst_f->internal;
  2058. ret = CHECK_CU(cu->cuWaitExternalSemaphoresAsync(dst_int->cu_sem, s_w_par,
  2059. planes, cuda_dev->stream));
  2060. if (ret < 0) {
  2061. err = AVERROR_EXTERNAL;
  2062. goto fail;
  2063. }
  2064. for (int i = 0; i < planes; i++) {
  2065. CUDA_MEMCPY2D cpy = {
  2066. .srcMemoryType = CU_MEMORYTYPE_DEVICE,
  2067. .srcDevice = (CUdeviceptr)src->data[i],
  2068. .srcPitch = src->linesize[i],
  2069. .srcY = 0,
  2070. .dstMemoryType = CU_MEMORYTYPE_ARRAY,
  2071. .dstArray = dst_int->cu_array[i],
  2072. .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
  2073. : hwfc->width) * desc->comp[i].step,
  2074. .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
  2075. : hwfc->height,
  2076. };
  2077. ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
  2078. if (ret < 0) {
  2079. err = AVERROR_EXTERNAL;
  2080. goto fail;
  2081. }
  2082. }
  2083. ret = CHECK_CU(cu->cuSignalExternalSemaphoresAsync(dst_int->cu_sem, s_s_par,
  2084. planes, cuda_dev->stream));
  2085. if (ret < 0) {
  2086. err = AVERROR_EXTERNAL;
  2087. goto fail;
  2088. }
  2089. CHECK_CU(cu->cuCtxPopCurrent(&dummy));
  2090. av_log(hwfc, AV_LOG_VERBOSE, "Transfered CUDA image to Vulkan!\n");
  2091. return 0;
  2092. fail:
  2093. CHECK_CU(cu->cuCtxPopCurrent(&dummy));
  2094. vulkan_free_internal(dst_int);
  2095. dst_f->internal = NULL;
  2096. av_buffer_unref(&dst->buf[0]);
  2097. return err;
  2098. }
  2099. #endif
  2100. static int vulkan_map_to(AVHWFramesContext *hwfc, AVFrame *dst,
  2101. const AVFrame *src, int flags)
  2102. {
  2103. av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
  2104. switch (src->format) {
  2105. #if CONFIG_LIBDRM
  2106. #if CONFIG_VAAPI
  2107. case AV_PIX_FMT_VAAPI:
  2108. if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
  2109. return vulkan_map_from_vaapi(hwfc, dst, src, flags);
  2110. #endif
  2111. case AV_PIX_FMT_DRM_PRIME:
  2112. if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
  2113. return vulkan_map_from_drm(hwfc, dst, src, flags);
  2114. #endif
  2115. default:
  2116. return AVERROR(ENOSYS);
  2117. }
  2118. }
  2119. #if CONFIG_LIBDRM
  2120. typedef struct VulkanDRMMapping {
  2121. AVDRMFrameDescriptor drm_desc;
  2122. AVVkFrame *source;
  2123. } VulkanDRMMapping;
  2124. static void vulkan_unmap_to_drm(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
  2125. {
  2126. AVDRMFrameDescriptor *drm_desc = hwmap->priv;
  2127. for (int i = 0; i < drm_desc->nb_objects; i++)
  2128. close(drm_desc->objects[i].fd);
  2129. av_free(drm_desc);
  2130. }
  2131. static inline uint32_t vulkan_fmt_to_drm(VkFormat vkfmt)
  2132. {
  2133. for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
  2134. if (vulkan_drm_format_map[i].vk_format == vkfmt)
  2135. return vulkan_drm_format_map[i].drm_fourcc;
  2136. return DRM_FORMAT_INVALID;
  2137. }
  2138. static int vulkan_map_to_drm(AVHWFramesContext *hwfc, AVFrame *dst,
  2139. const AVFrame *src, int flags)
  2140. {
  2141. int err = 0;
  2142. VkResult ret;
  2143. AVVkFrame *f = (AVVkFrame *)src->data[0];
  2144. VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
  2145. VulkanFramesPriv *fp = hwfc->internal->priv;
  2146. AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
  2147. const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
  2148. VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
  2149. VkImageDrmFormatModifierPropertiesEXT drm_mod = {
  2150. .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT,
  2151. };
  2152. AVDRMFrameDescriptor *drm_desc = av_mallocz(sizeof(*drm_desc));
  2153. if (!drm_desc)
  2154. return AVERROR(ENOMEM);
  2155. err = prepare_frame(hwfc, &fp->conv_ctx, f, PREP_MODE_EXTERNAL_EXPORT);
  2156. if (err < 0)
  2157. goto end;
  2158. err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src, &vulkan_unmap_to_drm, drm_desc);
  2159. if (err < 0)
  2160. goto end;
  2161. if (p->extensions & EXT_DRM_MODIFIER_FLAGS) {
  2162. VK_LOAD_PFN(hwctx->inst, vkGetImageDrmFormatModifierPropertiesEXT);
  2163. ret = pfn_vkGetImageDrmFormatModifierPropertiesEXT(hwctx->act_dev, f->img[0],
  2164. &drm_mod);
  2165. if (ret != VK_SUCCESS) {
  2166. av_log(hwfc, AV_LOG_ERROR, "Failed to retrieve DRM format modifier!\n");
  2167. err = AVERROR_EXTERNAL;
  2168. goto end;
  2169. }
  2170. }
  2171. for (int i = 0; (i < planes) && (f->mem[i]); i++) {
  2172. VkMemoryGetFdInfoKHR export_info = {
  2173. .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
  2174. .memory = f->mem[i],
  2175. .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,
  2176. };
  2177. ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
  2178. &drm_desc->objects[i].fd);
  2179. if (ret != VK_SUCCESS) {
  2180. av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
  2181. err = AVERROR_EXTERNAL;
  2182. goto end;
  2183. }
  2184. drm_desc->nb_objects++;
  2185. drm_desc->objects[i].size = f->size[i];
  2186. drm_desc->objects[i].format_modifier = drm_mod.drmFormatModifier;
  2187. }
  2188. drm_desc->nb_layers = planes;
  2189. for (int i = 0; i < drm_desc->nb_layers; i++) {
  2190. VkSubresourceLayout layout;
  2191. VkImageSubresource sub = {
  2192. .aspectMask = p->extensions & EXT_DRM_MODIFIER_FLAGS ?
  2193. VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
  2194. VK_IMAGE_ASPECT_COLOR_BIT,
  2195. };
  2196. VkFormat plane_vkfmt = av_vkfmt_from_pixfmt(hwfc->sw_format)[i];
  2197. drm_desc->layers[i].format = vulkan_fmt_to_drm(plane_vkfmt);
  2198. drm_desc->layers[i].nb_planes = 1;
  2199. if (drm_desc->layers[i].format == DRM_FORMAT_INVALID) {
  2200. av_log(hwfc, AV_LOG_ERROR, "Cannot map to DRM layer, unsupported!\n");
  2201. err = AVERROR_PATCHWELCOME;
  2202. goto end;
  2203. }
  2204. drm_desc->layers[i].planes[0].object_index = FFMIN(i, drm_desc->nb_objects - 1);
  2205. if (f->tiling == VK_IMAGE_TILING_OPTIMAL)
  2206. continue;
  2207. vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
  2208. drm_desc->layers[i].planes[0].offset = layout.offset;
  2209. drm_desc->layers[i].planes[0].pitch = layout.rowPitch;
  2210. }
  2211. dst->width = src->width;
  2212. dst->height = src->height;
  2213. dst->data[0] = (uint8_t *)drm_desc;
  2214. av_log(hwfc, AV_LOG_VERBOSE, "Mapped AVVkFrame to a DRM object!\n");
  2215. return 0;
  2216. end:
  2217. av_free(drm_desc);
  2218. return err;
  2219. }
  2220. #if CONFIG_VAAPI
  2221. static int vulkan_map_to_vaapi(AVHWFramesContext *hwfc, AVFrame *dst,
  2222. const AVFrame *src, int flags)
  2223. {
  2224. int err;
  2225. AVFrame *tmp = av_frame_alloc();
  2226. if (!tmp)
  2227. return AVERROR(ENOMEM);
  2228. tmp->format = AV_PIX_FMT_DRM_PRIME;
  2229. err = vulkan_map_to_drm(hwfc, tmp, src, flags);
  2230. if (err < 0)
  2231. goto fail;
  2232. err = av_hwframe_map(dst, tmp, flags);
  2233. if (err < 0)
  2234. goto fail;
  2235. err = ff_hwframe_map_replace(dst, src);
  2236. fail:
  2237. av_frame_free(&tmp);
  2238. return err;
  2239. }
  2240. #endif
  2241. #endif
  2242. static int vulkan_map_from(AVHWFramesContext *hwfc, AVFrame *dst,
  2243. const AVFrame *src, int flags)
  2244. {
  2245. av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
  2246. switch (dst->format) {
  2247. #if CONFIG_LIBDRM
  2248. case AV_PIX_FMT_DRM_PRIME:
  2249. if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
  2250. return vulkan_map_to_drm(hwfc, dst, src, flags);
  2251. #if CONFIG_VAAPI
  2252. case AV_PIX_FMT_VAAPI:
  2253. if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
  2254. return vulkan_map_to_vaapi(hwfc, dst, src, flags);
  2255. #endif
  2256. #endif
  2257. default:
  2258. return vulkan_map_frame_to_mem(hwfc, dst, src, flags);
  2259. }
  2260. }
  2261. typedef struct ImageBuffer {
  2262. VkBuffer buf;
  2263. VkDeviceMemory mem;
  2264. VkMemoryPropertyFlagBits flags;
  2265. int mapped_mem;
  2266. } ImageBuffer;
  2267. static void free_buf(void *opaque, uint8_t *data)
  2268. {
  2269. AVHWDeviceContext *ctx = opaque;
  2270. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  2271. ImageBuffer *vkbuf = (ImageBuffer *)data;
  2272. if (vkbuf->buf)
  2273. vkDestroyBuffer(hwctx->act_dev, vkbuf->buf, hwctx->alloc);
  2274. if (vkbuf->mem)
  2275. vkFreeMemory(hwctx->act_dev, vkbuf->mem, hwctx->alloc);
  2276. av_free(data);
  2277. }
  2278. static int create_buf(AVHWDeviceContext *ctx, AVBufferRef **buf, size_t imp_size,
  2279. int height, int *stride, VkBufferUsageFlags usage,
  2280. VkMemoryPropertyFlagBits flags, void *create_pnext,
  2281. void *alloc_pnext)
  2282. {
  2283. int err;
  2284. VkResult ret;
  2285. int use_ded_mem;
  2286. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  2287. VulkanDevicePriv *p = ctx->internal->priv;
  2288. VkBufferCreateInfo buf_spawn = {
  2289. .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
  2290. .pNext = create_pnext,
  2291. .usage = usage,
  2292. .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
  2293. };
  2294. VkBufferMemoryRequirementsInfo2 req_desc = {
  2295. .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2,
  2296. };
  2297. VkMemoryDedicatedAllocateInfo ded_alloc = {
  2298. .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
  2299. .pNext = alloc_pnext,
  2300. };
  2301. VkMemoryDedicatedRequirements ded_req = {
  2302. .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
  2303. };
  2304. VkMemoryRequirements2 req = {
  2305. .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
  2306. .pNext = &ded_req,
  2307. };
  2308. ImageBuffer *vkbuf = av_mallocz(sizeof(*vkbuf));
  2309. if (!vkbuf)
  2310. return AVERROR(ENOMEM);
  2311. vkbuf->mapped_mem = !!imp_size;
  2312. if (!vkbuf->mapped_mem) {
  2313. *stride = FFALIGN(*stride, p->props.properties.limits.optimalBufferCopyRowPitchAlignment);
  2314. buf_spawn.size = height*(*stride);
  2315. buf_spawn.size = FFALIGN(buf_spawn.size, p->props.properties.limits.minMemoryMapAlignment);
  2316. } else {
  2317. buf_spawn.size = imp_size;
  2318. }
  2319. ret = vkCreateBuffer(hwctx->act_dev, &buf_spawn, NULL, &vkbuf->buf);
  2320. if (ret != VK_SUCCESS) {
  2321. av_log(ctx, AV_LOG_ERROR, "Failed to create buffer: %s\n",
  2322. vk_ret2str(ret));
  2323. return AVERROR_EXTERNAL;
  2324. }
  2325. req_desc.buffer = vkbuf->buf;
  2326. vkGetBufferMemoryRequirements2(hwctx->act_dev, &req_desc, &req);
  2327. /* In case the implementation prefers/requires dedicated allocation */
  2328. use_ded_mem = ded_req.prefersDedicatedAllocation |
  2329. ded_req.requiresDedicatedAllocation;
  2330. if (use_ded_mem)
  2331. ded_alloc.buffer = vkbuf->buf;
  2332. err = alloc_mem(ctx, &req.memoryRequirements, flags,
  2333. use_ded_mem ? &ded_alloc : (void *)ded_alloc.pNext,
  2334. &vkbuf->flags, &vkbuf->mem);
  2335. if (err)
  2336. return err;
  2337. ret = vkBindBufferMemory(hwctx->act_dev, vkbuf->buf, vkbuf->mem, 0);
  2338. if (ret != VK_SUCCESS) {
  2339. av_log(ctx, AV_LOG_ERROR, "Failed to bind memory to buffer: %s\n",
  2340. vk_ret2str(ret));
  2341. free_buf(ctx, (uint8_t *)vkbuf);
  2342. return AVERROR_EXTERNAL;
  2343. }
  2344. *buf = av_buffer_create((uint8_t *)vkbuf, sizeof(*vkbuf), free_buf, ctx, 0);
  2345. if (!(*buf)) {
  2346. free_buf(ctx, (uint8_t *)vkbuf);
  2347. return AVERROR(ENOMEM);
  2348. }
  2349. return 0;
  2350. }
  2351. /* Skips mapping of host mapped buffers but still invalidates them */
  2352. static int map_buffers(AVHWDeviceContext *ctx, AVBufferRef **bufs, uint8_t *mem[],
  2353. int nb_buffers, int invalidate)
  2354. {
  2355. VkResult ret;
  2356. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  2357. VkMappedMemoryRange invalidate_ctx[AV_NUM_DATA_POINTERS];
  2358. int invalidate_count = 0;
  2359. for (int i = 0; i < nb_buffers; i++) {
  2360. ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
  2361. if (vkbuf->mapped_mem)
  2362. continue;
  2363. ret = vkMapMemory(hwctx->act_dev, vkbuf->mem, 0,
  2364. VK_WHOLE_SIZE, 0, (void **)&mem[i]);
  2365. if (ret != VK_SUCCESS) {
  2366. av_log(ctx, AV_LOG_ERROR, "Failed to map buffer memory: %s\n",
  2367. vk_ret2str(ret));
  2368. return AVERROR_EXTERNAL;
  2369. }
  2370. }
  2371. if (!invalidate)
  2372. return 0;
  2373. for (int i = 0; i < nb_buffers; i++) {
  2374. ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
  2375. const VkMappedMemoryRange ival_buf = {
  2376. .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
  2377. .memory = vkbuf->mem,
  2378. .size = VK_WHOLE_SIZE,
  2379. };
  2380. if (vkbuf->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
  2381. continue;
  2382. invalidate_ctx[invalidate_count++] = ival_buf;
  2383. }
  2384. if (invalidate_count) {
  2385. ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, invalidate_count,
  2386. invalidate_ctx);
  2387. if (ret != VK_SUCCESS)
  2388. av_log(ctx, AV_LOG_WARNING, "Failed to invalidate memory: %s\n",
  2389. vk_ret2str(ret));
  2390. }
  2391. return 0;
  2392. }
  2393. static int unmap_buffers(AVHWDeviceContext *ctx, AVBufferRef **bufs,
  2394. int nb_buffers, int flush)
  2395. {
  2396. int err = 0;
  2397. VkResult ret;
  2398. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  2399. VkMappedMemoryRange flush_ctx[AV_NUM_DATA_POINTERS];
  2400. int flush_count = 0;
  2401. if (flush) {
  2402. for (int i = 0; i < nb_buffers; i++) {
  2403. ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
  2404. const VkMappedMemoryRange flush_buf = {
  2405. .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
  2406. .memory = vkbuf->mem,
  2407. .size = VK_WHOLE_SIZE,
  2408. };
  2409. if (vkbuf->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
  2410. continue;
  2411. flush_ctx[flush_count++] = flush_buf;
  2412. }
  2413. }
  2414. if (flush_count) {
  2415. ret = vkFlushMappedMemoryRanges(hwctx->act_dev, flush_count, flush_ctx);
  2416. if (ret != VK_SUCCESS) {
  2417. av_log(ctx, AV_LOG_ERROR, "Failed to flush memory: %s\n",
  2418. vk_ret2str(ret));
  2419. err = AVERROR_EXTERNAL; /* We still want to try to unmap them */
  2420. }
  2421. }
  2422. for (int i = 0; i < nb_buffers; i++) {
  2423. ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
  2424. if (vkbuf->mapped_mem)
  2425. continue;
  2426. vkUnmapMemory(hwctx->act_dev, vkbuf->mem);
  2427. }
  2428. return err;
  2429. }
  2430. static int transfer_image_buf(AVHWFramesContext *hwfc, const AVFrame *f,
  2431. AVBufferRef **bufs, const int *buf_stride, int w,
  2432. int h, enum AVPixelFormat pix_fmt, int to_buf)
  2433. {
  2434. int err;
  2435. AVVkFrame *frame = (AVVkFrame *)f->data[0];
  2436. VulkanFramesPriv *fp = hwfc->internal->priv;
  2437. int bar_num = 0;
  2438. VkPipelineStageFlagBits sem_wait_dst[AV_NUM_DATA_POINTERS];
  2439. const int planes = av_pix_fmt_count_planes(pix_fmt);
  2440. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
  2441. VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
  2442. VulkanExecCtx *ectx = to_buf ? &fp->download_ctx : &fp->upload_ctx;
  2443. VkCommandBuffer cmd_buf = get_buf_exec_ctx(hwfc, ectx);
  2444. VkSubmitInfo s_info = {
  2445. .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
  2446. .pSignalSemaphores = frame->sem,
  2447. .pWaitSemaphores = frame->sem,
  2448. .pWaitDstStageMask = sem_wait_dst,
  2449. .signalSemaphoreCount = planes,
  2450. .waitSemaphoreCount = planes,
  2451. };
  2452. if ((err = wait_start_exec_ctx(hwfc, ectx)))
  2453. return err;
  2454. /* Change the image layout to something more optimal for transfers */
  2455. for (int i = 0; i < planes; i++) {
  2456. VkImageLayout new_layout = to_buf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL :
  2457. VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2458. VkAccessFlags new_access = to_buf ? VK_ACCESS_TRANSFER_READ_BIT :
  2459. VK_ACCESS_TRANSFER_WRITE_BIT;
  2460. sem_wait_dst[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
  2461. /* If the layout matches and we have read access skip the barrier */
  2462. if ((frame->layout[i] == new_layout) && (frame->access[i] & new_access))
  2463. continue;
  2464. img_bar[bar_num].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2465. img_bar[bar_num].srcAccessMask = 0x0;
  2466. img_bar[bar_num].dstAccessMask = new_access;
  2467. img_bar[bar_num].oldLayout = frame->layout[i];
  2468. img_bar[bar_num].newLayout = new_layout;
  2469. img_bar[bar_num].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2470. img_bar[bar_num].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2471. img_bar[bar_num].image = frame->img[i];
  2472. img_bar[bar_num].subresourceRange.levelCount = 1;
  2473. img_bar[bar_num].subresourceRange.layerCount = 1;
  2474. img_bar[bar_num].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2475. frame->layout[i] = img_bar[bar_num].newLayout;
  2476. frame->access[i] = img_bar[bar_num].dstAccessMask;
  2477. bar_num++;
  2478. }
  2479. if (bar_num)
  2480. vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
  2481. VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
  2482. 0, NULL, 0, NULL, bar_num, img_bar);
  2483. /* Schedule a copy for each plane */
  2484. for (int i = 0; i < planes; i++) {
  2485. ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
  2486. const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
  2487. const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
  2488. VkBufferImageCopy buf_reg = {
  2489. .bufferOffset = 0,
  2490. /* Buffer stride isn't in bytes, it's in samples, the implementation
  2491. * uses the image's VkFormat to know how many bytes per sample
  2492. * the buffer has. So we have to convert by dividing. Stupid.
  2493. * Won't work with YUVA or other planar formats with alpha. */
  2494. .bufferRowLength = buf_stride[i] / desc->comp[i].step,
  2495. .bufferImageHeight = p_h,
  2496. .imageSubresource.layerCount = 1,
  2497. .imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
  2498. .imageOffset = { 0, 0, 0, },
  2499. .imageExtent = { p_w, p_h, 1, },
  2500. };
  2501. if (to_buf)
  2502. vkCmdCopyImageToBuffer(cmd_buf, frame->img[i], frame->layout[i],
  2503. vkbuf->buf, 1, &buf_reg);
  2504. else
  2505. vkCmdCopyBufferToImage(cmd_buf, vkbuf->buf, frame->img[i],
  2506. frame->layout[i], 1, &buf_reg);
  2507. }
  2508. /* When uploading, do this asynchronously if the source is refcounted by
  2509. * keeping the buffers as a submission dependency.
  2510. * The hwcontext is guaranteed to not be freed until all frames are freed
  2511. * in the frames_unint function.
  2512. * When downloading to buffer, do this synchronously and wait for the
  2513. * queue submission to finish executing */
  2514. if (!to_buf) {
  2515. int ref;
  2516. for (ref = 0; ref < AV_NUM_DATA_POINTERS; ref++) {
  2517. if (!f->buf[ref])
  2518. break;
  2519. if ((err = add_buf_dep_exec_ctx(hwfc, ectx, &f->buf[ref], 1)))
  2520. return err;
  2521. }
  2522. if (ref && (err = add_buf_dep_exec_ctx(hwfc, ectx, bufs, planes)))
  2523. return err;
  2524. return submit_exec_ctx(hwfc, ectx, &s_info, !ref);
  2525. } else {
  2526. return submit_exec_ctx(hwfc, ectx, &s_info, 1);
  2527. }
  2528. }
  2529. static int vulkan_transfer_data(AVHWFramesContext *hwfc, const AVFrame *vkf,
  2530. const AVFrame *swf, int from)
  2531. {
  2532. int err = 0;
  2533. AVVkFrame *f = (AVVkFrame *)vkf->data[0];
  2534. AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
  2535. VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
  2536. AVFrame tmp;
  2537. AVBufferRef *bufs[AV_NUM_DATA_POINTERS] = { 0 };
  2538. const int planes = av_pix_fmt_count_planes(swf->format);
  2539. int log2_chroma = av_pix_fmt_desc_get(swf->format)->log2_chroma_h;
  2540. int host_mapped[AV_NUM_DATA_POINTERS] = { 0 };
  2541. const int map_host = p->extensions & EXT_EXTERNAL_HOST_MEMORY;
  2542. if ((swf->format != AV_PIX_FMT_NONE && !av_vkfmt_from_pixfmt(swf->format))) {
  2543. av_log(hwfc, AV_LOG_ERROR, "Unsupported software frame pixel format!\n");
  2544. return AVERROR(EINVAL);
  2545. }
  2546. if (swf->width > hwfc->width || swf->height > hwfc->height)
  2547. return AVERROR(EINVAL);
  2548. /* For linear, host visiable images */
  2549. if (f->tiling == VK_IMAGE_TILING_LINEAR &&
  2550. f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
  2551. AVFrame *map = av_frame_alloc();
  2552. if (!map)
  2553. return AVERROR(ENOMEM);
  2554. map->format = swf->format;
  2555. err = vulkan_map_frame_to_mem(hwfc, map, vkf, AV_HWFRAME_MAP_WRITE);
  2556. if (err)
  2557. return err;
  2558. err = av_frame_copy((AVFrame *)(from ? swf : map), from ? map : swf);
  2559. av_frame_free(&map);
  2560. return err;
  2561. }
  2562. /* Create buffers */
  2563. for (int i = 0; i < planes; i++) {
  2564. int h = swf->height;
  2565. int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
  2566. size_t p_size = FFALIGN(FFABS(swf->linesize[i]) * p_height,
  2567. p->hprops.minImportedHostPointerAlignment);
  2568. VkExternalMemoryBufferCreateInfo create_desc = {
  2569. .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO,
  2570. .handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT,
  2571. };
  2572. VkImportMemoryHostPointerInfoEXT import_desc = {
  2573. .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT,
  2574. .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT,
  2575. .pHostPointer = swf->data[i],
  2576. };
  2577. /* We can only map images with positive stride and alignment appropriate
  2578. * for the device. */
  2579. host_mapped[i] = map_host && swf->linesize[i] > 0 &&
  2580. !(((uintptr_t)import_desc.pHostPointer) %
  2581. p->hprops.minImportedHostPointerAlignment);
  2582. p_size = host_mapped[i] ? p_size : 0;
  2583. tmp.linesize[i] = FFABS(swf->linesize[i]);
  2584. err = create_buf(dev_ctx, &bufs[i], p_size, p_height, &tmp.linesize[i],
  2585. from ? VK_BUFFER_USAGE_TRANSFER_DST_BIT :
  2586. VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
  2587. VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
  2588. host_mapped[i] ? &create_desc : NULL,
  2589. host_mapped[i] ? &import_desc : NULL);
  2590. if (err)
  2591. goto end;
  2592. }
  2593. if (!from) {
  2594. /* Map, copy image to buffer, unmap */
  2595. if ((err = map_buffers(dev_ctx, bufs, tmp.data, planes, 0)))
  2596. goto end;
  2597. for (int i = 0; i < planes; i++) {
  2598. int h = swf->height;
  2599. int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
  2600. if (host_mapped[i])
  2601. continue;
  2602. av_image_copy_plane(tmp.data[i], tmp.linesize[i],
  2603. (const uint8_t *)swf->data[i], swf->linesize[i],
  2604. FFMIN(tmp.linesize[i], FFABS(swf->linesize[i])),
  2605. p_height);
  2606. }
  2607. if ((err = unmap_buffers(dev_ctx, bufs, planes, 1)))
  2608. goto end;
  2609. }
  2610. /* Copy buffers into/from image */
  2611. err = transfer_image_buf(hwfc, vkf, bufs, tmp.linesize,
  2612. swf->width, swf->height, swf->format, from);
  2613. if (from) {
  2614. /* Map, copy image to buffer, unmap */
  2615. if ((err = map_buffers(dev_ctx, bufs, tmp.data, planes, 0)))
  2616. goto end;
  2617. for (int i = 0; i < planes; i++) {
  2618. int h = swf->height;
  2619. int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
  2620. if (host_mapped[i])
  2621. continue;
  2622. av_image_copy_plane(swf->data[i], swf->linesize[i],
  2623. (const uint8_t *)tmp.data[i], tmp.linesize[i],
  2624. FFMIN(tmp.linesize[i], FFABS(swf->linesize[i])),
  2625. p_height);
  2626. }
  2627. if ((err = unmap_buffers(dev_ctx, bufs, planes, 1)))
  2628. goto end;
  2629. }
  2630. end:
  2631. for (int i = 0; i < planes; i++)
  2632. av_buffer_unref(&bufs[i]);
  2633. return err;
  2634. }
  2635. static int vulkan_transfer_data_to(AVHWFramesContext *hwfc, AVFrame *dst,
  2636. const AVFrame *src)
  2637. {
  2638. av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
  2639. switch (src->format) {
  2640. #if CONFIG_CUDA
  2641. case AV_PIX_FMT_CUDA:
  2642. if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
  2643. (p->extensions & EXT_EXTERNAL_FD_SEM))
  2644. return vulkan_transfer_data_from_cuda(hwfc, dst, src);
  2645. #endif
  2646. default:
  2647. if (src->hw_frames_ctx)
  2648. return AVERROR(ENOSYS);
  2649. else
  2650. return vulkan_transfer_data(hwfc, dst, src, 0);
  2651. }
  2652. }
  2653. #if CONFIG_CUDA
  2654. static int vulkan_transfer_data_to_cuda(AVHWFramesContext *hwfc, AVFrame *dst,
  2655. const AVFrame *src)
  2656. {
  2657. int err;
  2658. VkResult ret;
  2659. CUcontext dummy;
  2660. AVVkFrame *dst_f;
  2661. AVVkFrameInternal *dst_int;
  2662. const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
  2663. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
  2664. AVHWFramesContext *cuda_fc = (AVHWFramesContext*)dst->hw_frames_ctx->data;
  2665. AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
  2666. AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
  2667. AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
  2668. CudaFunctions *cu = cu_internal->cuda_dl;
  2669. ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
  2670. if (ret < 0)
  2671. return AVERROR_EXTERNAL;
  2672. dst_f = (AVVkFrame *)src->data[0];
  2673. err = vulkan_export_to_cuda(hwfc, dst->hw_frames_ctx, src);
  2674. if (err < 0) {
  2675. CHECK_CU(cu->cuCtxPopCurrent(&dummy));
  2676. return err;
  2677. }
  2678. dst_int = dst_f->internal;
  2679. for (int i = 0; i < planes; i++) {
  2680. CUDA_MEMCPY2D cpy = {
  2681. .dstMemoryType = CU_MEMORYTYPE_DEVICE,
  2682. .dstDevice = (CUdeviceptr)dst->data[i],
  2683. .dstPitch = dst->linesize[i],
  2684. .dstY = 0,
  2685. .srcMemoryType = CU_MEMORYTYPE_ARRAY,
  2686. .srcArray = dst_int->cu_array[i],
  2687. .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
  2688. : hwfc->width) * desc->comp[i].step,
  2689. .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
  2690. : hwfc->height,
  2691. };
  2692. ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
  2693. if (ret < 0) {
  2694. err = AVERROR_EXTERNAL;
  2695. goto fail;
  2696. }
  2697. }
  2698. CHECK_CU(cu->cuCtxPopCurrent(&dummy));
  2699. av_log(hwfc, AV_LOG_VERBOSE, "Transfered Vulkan image to CUDA!\n");
  2700. return 0;
  2701. fail:
  2702. CHECK_CU(cu->cuCtxPopCurrent(&dummy));
  2703. vulkan_free_internal(dst_int);
  2704. dst_f->internal = NULL;
  2705. av_buffer_unref(&dst->buf[0]);
  2706. return err;
  2707. }
  2708. #endif
  2709. static int vulkan_transfer_data_from(AVHWFramesContext *hwfc, AVFrame *dst,
  2710. const AVFrame *src)
  2711. {
  2712. av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
  2713. switch (dst->format) {
  2714. #if CONFIG_CUDA
  2715. case AV_PIX_FMT_CUDA:
  2716. if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
  2717. (p->extensions & EXT_EXTERNAL_FD_SEM))
  2718. return vulkan_transfer_data_to_cuda(hwfc, dst, src);
  2719. #endif
  2720. default:
  2721. if (dst->hw_frames_ctx)
  2722. return AVERROR(ENOSYS);
  2723. else
  2724. return vulkan_transfer_data(hwfc, src, dst, 1);
  2725. }
  2726. }
  2727. static int vulkan_frames_derive_to(AVHWFramesContext *dst_fc,
  2728. AVHWFramesContext *src_fc, int flags)
  2729. {
  2730. return vulkan_frames_init(dst_fc);
  2731. }
  2732. AVVkFrame *av_vk_frame_alloc(void)
  2733. {
  2734. return av_mallocz(sizeof(AVVkFrame));
  2735. }
  2736. const HWContextType ff_hwcontext_type_vulkan = {
  2737. .type = AV_HWDEVICE_TYPE_VULKAN,
  2738. .name = "Vulkan",
  2739. .device_hwctx_size = sizeof(AVVulkanDeviceContext),
  2740. .device_priv_size = sizeof(VulkanDevicePriv),
  2741. .frames_hwctx_size = sizeof(AVVulkanFramesContext),
  2742. .frames_priv_size = sizeof(VulkanFramesPriv),
  2743. .device_init = &vulkan_device_init,
  2744. .device_create = &vulkan_device_create,
  2745. .device_derive = &vulkan_device_derive,
  2746. .frames_get_constraints = &vulkan_frames_get_constraints,
  2747. .frames_init = vulkan_frames_init,
  2748. .frames_get_buffer = vulkan_get_buffer,
  2749. .frames_uninit = vulkan_frames_uninit,
  2750. .transfer_get_formats = vulkan_transfer_get_formats,
  2751. .transfer_data_to = vulkan_transfer_data_to,
  2752. .transfer_data_from = vulkan_transfer_data_from,
  2753. .map_to = vulkan_map_to,
  2754. .map_from = vulkan_map_from,
  2755. .frames_derive_to = &vulkan_frames_derive_to,
  2756. .pix_fmts = (const enum AVPixelFormat []) {
  2757. AV_PIX_FMT_VULKAN,
  2758. AV_PIX_FMT_NONE
  2759. },
  2760. };