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.

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