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.

2997 lines
104KB

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