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.

2996 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,
  824. AVDictionary *opts, int flags)
  825. {
  826. av_unused VulkanDeviceSelection dev_select = { 0 };
  827. /* If there's only one device on the system, then even if its not covered
  828. * by the following checks (e.g. non-PCIe ARM GPU), having an empty
  829. * dev_select will mean it'll get picked. */
  830. switch(src_ctx->type) {
  831. #if CONFIG_LIBDRM
  832. #if CONFIG_VAAPI
  833. case AV_HWDEVICE_TYPE_VAAPI: {
  834. AVVAAPIDeviceContext *src_hwctx = src_ctx->hwctx;
  835. const char *vendor = vaQueryVendorString(src_hwctx->display);
  836. if (!vendor) {
  837. av_log(ctx, AV_LOG_ERROR, "Unable to get device info from VAAPI!\n");
  838. return AVERROR_EXTERNAL;
  839. }
  840. if (strstr(vendor, "Intel"))
  841. dev_select.vendor_id = 0x8086;
  842. if (strstr(vendor, "AMD"))
  843. dev_select.vendor_id = 0x1002;
  844. return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
  845. }
  846. #endif
  847. case AV_HWDEVICE_TYPE_DRM: {
  848. AVDRMDeviceContext *src_hwctx = src_ctx->hwctx;
  849. drmDevice *drm_dev_info;
  850. int err = drmGetDevice(src_hwctx->fd, &drm_dev_info);
  851. if (err) {
  852. av_log(ctx, AV_LOG_ERROR, "Unable to get device info from DRM fd!\n");
  853. return AVERROR_EXTERNAL;
  854. }
  855. if (drm_dev_info->bustype == DRM_BUS_PCI)
  856. dev_select.pci_device = drm_dev_info->deviceinfo.pci->device_id;
  857. drmFreeDevice(&drm_dev_info);
  858. return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
  859. }
  860. #endif
  861. #if CONFIG_CUDA
  862. case AV_HWDEVICE_TYPE_CUDA: {
  863. AVHWDeviceContext *cuda_cu = src_ctx;
  864. AVCUDADeviceContext *src_hwctx = src_ctx->hwctx;
  865. AVCUDADeviceContextInternal *cu_internal = src_hwctx->internal;
  866. CudaFunctions *cu = cu_internal->cuda_dl;
  867. int ret = CHECK_CU(cu->cuDeviceGetUuid((CUuuid *)&dev_select.uuid,
  868. cu_internal->cuda_device));
  869. if (ret < 0) {
  870. av_log(ctx, AV_LOG_ERROR, "Unable to get UUID from CUDA!\n");
  871. return AVERROR_EXTERNAL;
  872. }
  873. dev_select.has_uuid = 1;
  874. return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
  875. }
  876. #endif
  877. default:
  878. return AVERROR(ENOSYS);
  879. }
  880. }
  881. static int vulkan_frames_get_constraints(AVHWDeviceContext *ctx,
  882. const void *hwconfig,
  883. AVHWFramesConstraints *constraints)
  884. {
  885. int count = 0;
  886. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  887. VulkanDevicePriv *p = ctx->internal->priv;
  888. for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
  889. count += pixfmt_is_supported(hwctx, i, p->use_linear_images);
  890. #if CONFIG_CUDA
  891. if (p->dev_is_nvidia)
  892. count++;
  893. #endif
  894. constraints->valid_sw_formats = av_malloc_array(count + 1,
  895. sizeof(enum AVPixelFormat));
  896. if (!constraints->valid_sw_formats)
  897. return AVERROR(ENOMEM);
  898. count = 0;
  899. for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
  900. if (pixfmt_is_supported(hwctx, i, p->use_linear_images))
  901. constraints->valid_sw_formats[count++] = i;
  902. #if CONFIG_CUDA
  903. if (p->dev_is_nvidia)
  904. constraints->valid_sw_formats[count++] = AV_PIX_FMT_CUDA;
  905. #endif
  906. constraints->valid_sw_formats[count++] = AV_PIX_FMT_NONE;
  907. constraints->min_width = 0;
  908. constraints->min_height = 0;
  909. constraints->max_width = p->props.limits.maxImageDimension2D;
  910. constraints->max_height = p->props.limits.maxImageDimension2D;
  911. constraints->valid_hw_formats = av_malloc_array(2, sizeof(enum AVPixelFormat));
  912. if (!constraints->valid_hw_formats)
  913. return AVERROR(ENOMEM);
  914. constraints->valid_hw_formats[0] = AV_PIX_FMT_VULKAN;
  915. constraints->valid_hw_formats[1] = AV_PIX_FMT_NONE;
  916. return 0;
  917. }
  918. static int alloc_mem(AVHWDeviceContext *ctx, VkMemoryRequirements *req,
  919. VkMemoryPropertyFlagBits req_flags, void *alloc_extension,
  920. VkMemoryPropertyFlagBits *mem_flags, VkDeviceMemory *mem)
  921. {
  922. VkResult ret;
  923. int index = -1;
  924. VulkanDevicePriv *p = ctx->internal->priv;
  925. AVVulkanDeviceContext *dev_hwctx = ctx->hwctx;
  926. VkMemoryAllocateInfo alloc_info = {
  927. .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
  928. .pNext = alloc_extension,
  929. };
  930. /* Align if we need to */
  931. if (req_flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)
  932. req->size = FFALIGN(req->size, p->props.limits.minMemoryMapAlignment);
  933. alloc_info.allocationSize = req->size;
  934. /* The vulkan spec requires memory types to be sorted in the "optimal"
  935. * order, so the first matching type we find will be the best/fastest one */
  936. for (int i = 0; i < p->mprops.memoryTypeCount; i++) {
  937. /* The memory type must be supported by the requirements (bitfield) */
  938. if (!(req->memoryTypeBits & (1 << i)))
  939. continue;
  940. /* The memory type flags must include our properties */
  941. if ((p->mprops.memoryTypes[i].propertyFlags & req_flags) != req_flags)
  942. continue;
  943. /* Found a suitable memory type */
  944. index = i;
  945. break;
  946. }
  947. if (index < 0) {
  948. av_log(ctx, AV_LOG_ERROR, "No memory type found for flags 0x%x\n",
  949. req_flags);
  950. return AVERROR(EINVAL);
  951. }
  952. alloc_info.memoryTypeIndex = index;
  953. ret = vkAllocateMemory(dev_hwctx->act_dev, &alloc_info,
  954. dev_hwctx->alloc, mem);
  955. if (ret != VK_SUCCESS) {
  956. av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory: %s\n",
  957. vk_ret2str(ret));
  958. return AVERROR(ENOMEM);
  959. }
  960. *mem_flags |= p->mprops.memoryTypes[index].propertyFlags;
  961. return 0;
  962. }
  963. static void vulkan_free_internal(AVVkFrameInternal *internal)
  964. {
  965. if (!internal)
  966. return;
  967. #if CONFIG_CUDA
  968. if (internal->cuda_fc_ref) {
  969. AVHWFramesContext *cuda_fc = (AVHWFramesContext *)internal->cuda_fc_ref->data;
  970. int planes = av_pix_fmt_count_planes(cuda_fc->sw_format);
  971. AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
  972. AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
  973. AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
  974. CudaFunctions *cu = cu_internal->cuda_dl;
  975. for (int i = 0; i < planes; i++) {
  976. if (internal->cu_sem[i])
  977. CHECK_CU(cu->cuDestroyExternalSemaphore(internal->cu_sem[i]));
  978. if (internal->cu_mma[i])
  979. CHECK_CU(cu->cuMipmappedArrayDestroy(internal->cu_mma[i]));
  980. if (internal->ext_mem[i])
  981. CHECK_CU(cu->cuDestroyExternalMemory(internal->ext_mem[i]));
  982. }
  983. av_buffer_unref(&internal->cuda_fc_ref);
  984. }
  985. #endif
  986. av_free(internal);
  987. }
  988. static void vulkan_frame_free(void *opaque, uint8_t *data)
  989. {
  990. AVVkFrame *f = (AVVkFrame *)data;
  991. AVHWFramesContext *hwfc = opaque;
  992. AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
  993. int planes = av_pix_fmt_count_planes(hwfc->sw_format);
  994. vulkan_free_internal(f->internal);
  995. for (int i = 0; i < planes; i++) {
  996. vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
  997. vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
  998. vkDestroySemaphore(hwctx->act_dev, f->sem[i], hwctx->alloc);
  999. }
  1000. av_free(f);
  1001. }
  1002. static int alloc_bind_mem(AVHWFramesContext *hwfc, AVVkFrame *f,
  1003. void *alloc_pnext, size_t alloc_pnext_stride)
  1004. {
  1005. int err;
  1006. VkResult ret;
  1007. AVHWDeviceContext *ctx = hwfc->device_ctx;
  1008. const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
  1009. VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { { 0 } };
  1010. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  1011. for (int i = 0; i < planes; i++) {
  1012. int use_ded_mem;
  1013. VkImageMemoryRequirementsInfo2 req_desc = {
  1014. .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
  1015. .image = f->img[i],
  1016. };
  1017. VkMemoryDedicatedAllocateInfo ded_alloc = {
  1018. .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
  1019. .pNext = (void *)(((uint8_t *)alloc_pnext) + i*alloc_pnext_stride),
  1020. };
  1021. VkMemoryDedicatedRequirements ded_req = {
  1022. .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
  1023. };
  1024. VkMemoryRequirements2 req = {
  1025. .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
  1026. .pNext = &ded_req,
  1027. };
  1028. vkGetImageMemoryRequirements2(hwctx->act_dev, &req_desc, &req);
  1029. /* In case the implementation prefers/requires dedicated allocation */
  1030. use_ded_mem = ded_req.prefersDedicatedAllocation |
  1031. ded_req.requiresDedicatedAllocation;
  1032. if (use_ded_mem)
  1033. ded_alloc.image = f->img[i];
  1034. /* Allocate memory */
  1035. if ((err = alloc_mem(ctx, &req.memoryRequirements,
  1036. f->tiling == VK_IMAGE_TILING_LINEAR ?
  1037. VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT :
  1038. VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
  1039. use_ded_mem ? &ded_alloc : (void *)ded_alloc.pNext,
  1040. &f->flags, &f->mem[i])))
  1041. return err;
  1042. f->size[i] = req.memoryRequirements.size;
  1043. bind_info[i].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
  1044. bind_info[i].image = f->img[i];
  1045. bind_info[i].memory = f->mem[i];
  1046. }
  1047. /* Bind the allocated memory to the images */
  1048. ret = vkBindImageMemory2(hwctx->act_dev, planes, bind_info);
  1049. if (ret != VK_SUCCESS) {
  1050. av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
  1051. vk_ret2str(ret));
  1052. return AVERROR_EXTERNAL;
  1053. }
  1054. return 0;
  1055. }
  1056. enum PrepMode {
  1057. PREP_MODE_WRITE,
  1058. PREP_MODE_RO_SHADER,
  1059. PREP_MODE_EXTERNAL_EXPORT,
  1060. };
  1061. static int prepare_frame(AVHWFramesContext *hwfc, VulkanExecCtx *ectx,
  1062. AVVkFrame *frame, enum PrepMode pmode)
  1063. {
  1064. VkResult ret;
  1065. uint32_t dst_qf;
  1066. VkImageLayout new_layout;
  1067. VkAccessFlags new_access;
  1068. AVHWDeviceContext *ctx = hwfc->device_ctx;
  1069. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  1070. const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
  1071. VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
  1072. VkCommandBufferBeginInfo cmd_start = {
  1073. .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
  1074. .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
  1075. };
  1076. VkSubmitInfo s_info = {
  1077. .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
  1078. .commandBufferCount = 1,
  1079. .pCommandBuffers = &ectx->buf,
  1080. .pSignalSemaphores = frame->sem,
  1081. .signalSemaphoreCount = planes,
  1082. };
  1083. VkPipelineStageFlagBits wait_st[AV_NUM_DATA_POINTERS];
  1084. for (int i = 0; i < planes; i++)
  1085. wait_st[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
  1086. switch (pmode) {
  1087. case PREP_MODE_WRITE:
  1088. new_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  1089. new_access = VK_ACCESS_TRANSFER_WRITE_BIT;
  1090. dst_qf = VK_QUEUE_FAMILY_IGNORED;
  1091. break;
  1092. case PREP_MODE_RO_SHADER:
  1093. new_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  1094. new_access = VK_ACCESS_TRANSFER_READ_BIT;
  1095. dst_qf = VK_QUEUE_FAMILY_IGNORED;
  1096. break;
  1097. case PREP_MODE_EXTERNAL_EXPORT:
  1098. new_layout = VK_IMAGE_LAYOUT_GENERAL;
  1099. new_access = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
  1100. dst_qf = VK_QUEUE_FAMILY_EXTERNAL_KHR;
  1101. s_info.pWaitSemaphores = frame->sem;
  1102. s_info.pWaitDstStageMask = wait_st;
  1103. s_info.waitSemaphoreCount = planes;
  1104. break;
  1105. }
  1106. ret = vkBeginCommandBuffer(ectx->buf, &cmd_start);
  1107. if (ret != VK_SUCCESS)
  1108. return AVERROR_EXTERNAL;
  1109. /* Change the image layout to something more optimal for writes.
  1110. * This also signals the newly created semaphore, making it usable
  1111. * for synchronization */
  1112. for (int i = 0; i < planes; i++) {
  1113. img_bar[i].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  1114. img_bar[i].srcAccessMask = 0x0;
  1115. img_bar[i].dstAccessMask = new_access;
  1116. img_bar[i].oldLayout = frame->layout[i];
  1117. img_bar[i].newLayout = new_layout;
  1118. img_bar[i].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  1119. img_bar[i].dstQueueFamilyIndex = dst_qf;
  1120. img_bar[i].image = frame->img[i];
  1121. img_bar[i].subresourceRange.levelCount = 1;
  1122. img_bar[i].subresourceRange.layerCount = 1;
  1123. img_bar[i].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  1124. frame->layout[i] = img_bar[i].newLayout;
  1125. frame->access[i] = img_bar[i].dstAccessMask;
  1126. }
  1127. vkCmdPipelineBarrier(ectx->buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
  1128. VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
  1129. 0, NULL, 0, NULL, planes, img_bar);
  1130. ret = vkEndCommandBuffer(ectx->buf);
  1131. if (ret != VK_SUCCESS)
  1132. return AVERROR_EXTERNAL;
  1133. ret = vkQueueSubmit(ectx->queue, 1, &s_info, ectx->fence);
  1134. if (ret != VK_SUCCESS) {
  1135. return AVERROR_EXTERNAL;
  1136. } else {
  1137. vkWaitForFences(hwctx->act_dev, 1, &ectx->fence, VK_TRUE, UINT64_MAX);
  1138. vkResetFences(hwctx->act_dev, 1, &ectx->fence);
  1139. }
  1140. return 0;
  1141. }
  1142. static int create_frame(AVHWFramesContext *hwfc, AVVkFrame **frame,
  1143. VkImageTiling tiling, VkImageUsageFlagBits usage,
  1144. void *create_pnext)
  1145. {
  1146. int err;
  1147. VkResult ret;
  1148. AVHWDeviceContext *ctx = hwfc->device_ctx;
  1149. VulkanDevicePriv *p = ctx->internal->priv;
  1150. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  1151. enum AVPixelFormat format = hwfc->sw_format;
  1152. const VkFormat *img_fmts = av_vkfmt_from_pixfmt(format);
  1153. const int planes = av_pix_fmt_count_planes(format);
  1154. VkExportSemaphoreCreateInfo ext_sem_info = {
  1155. .sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO,
  1156. .handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
  1157. };
  1158. VkSemaphoreCreateInfo sem_spawn = {
  1159. .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
  1160. .pNext = p->extensions & EXT_EXTERNAL_FD_SEM ? &ext_sem_info : NULL,
  1161. };
  1162. AVVkFrame *f = av_vk_frame_alloc();
  1163. if (!f) {
  1164. av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
  1165. return AVERROR(ENOMEM);
  1166. }
  1167. /* Create the images */
  1168. for (int i = 0; i < planes; i++) {
  1169. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
  1170. int w = hwfc->width;
  1171. int h = hwfc->height;
  1172. const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
  1173. const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
  1174. VkImageCreateInfo image_create_info = {
  1175. .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
  1176. .pNext = create_pnext,
  1177. .imageType = VK_IMAGE_TYPE_2D,
  1178. .format = img_fmts[i],
  1179. .extent.width = p_w,
  1180. .extent.height = p_h,
  1181. .extent.depth = 1,
  1182. .mipLevels = 1,
  1183. .arrayLayers = 1,
  1184. .flags = VK_IMAGE_CREATE_ALIAS_BIT,
  1185. .tiling = tiling,
  1186. .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
  1187. .usage = usage,
  1188. .samples = VK_SAMPLE_COUNT_1_BIT,
  1189. .pQueueFamilyIndices = p->qfs,
  1190. .queueFamilyIndexCount = p->num_qfs,
  1191. .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
  1192. VK_SHARING_MODE_EXCLUSIVE,
  1193. };
  1194. ret = vkCreateImage(hwctx->act_dev, &image_create_info,
  1195. hwctx->alloc, &f->img[i]);
  1196. if (ret != VK_SUCCESS) {
  1197. av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
  1198. vk_ret2str(ret));
  1199. err = AVERROR(EINVAL);
  1200. goto fail;
  1201. }
  1202. /* Create semaphore */
  1203. ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
  1204. hwctx->alloc, &f->sem[i]);
  1205. if (ret != VK_SUCCESS) {
  1206. av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
  1207. vk_ret2str(ret));
  1208. return AVERROR_EXTERNAL;
  1209. }
  1210. f->layout[i] = image_create_info.initialLayout;
  1211. f->access[i] = 0x0;
  1212. }
  1213. f->flags = 0x0;
  1214. f->tiling = tiling;
  1215. *frame = f;
  1216. return 0;
  1217. fail:
  1218. vulkan_frame_free(hwfc, (uint8_t *)f);
  1219. return err;
  1220. }
  1221. /* Checks if an export flag is enabled, and if it is ORs it with *iexp */
  1222. static void try_export_flags(AVHWFramesContext *hwfc,
  1223. VkExternalMemoryHandleTypeFlags *comp_handle_types,
  1224. VkExternalMemoryHandleTypeFlagBits *iexp,
  1225. VkExternalMemoryHandleTypeFlagBits exp)
  1226. {
  1227. VkResult ret;
  1228. AVVulkanFramesContext *hwctx = hwfc->hwctx;
  1229. AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
  1230. VkExternalImageFormatProperties eprops = {
  1231. .sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES_KHR,
  1232. };
  1233. VkImageFormatProperties2 props = {
  1234. .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,
  1235. .pNext = &eprops,
  1236. };
  1237. VkPhysicalDeviceExternalImageFormatInfo enext = {
  1238. .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
  1239. .handleType = exp,
  1240. };
  1241. VkPhysicalDeviceImageFormatInfo2 pinfo = {
  1242. .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
  1243. .pNext = !exp ? NULL : &enext,
  1244. .format = av_vkfmt_from_pixfmt(hwfc->sw_format)[0],
  1245. .type = VK_IMAGE_TYPE_2D,
  1246. .tiling = hwctx->tiling,
  1247. .usage = hwctx->usage,
  1248. .flags = VK_IMAGE_CREATE_ALIAS_BIT,
  1249. };
  1250. ret = vkGetPhysicalDeviceImageFormatProperties2(dev_hwctx->phys_dev,
  1251. &pinfo, &props);
  1252. if (ret == VK_SUCCESS) {
  1253. *iexp |= exp;
  1254. *comp_handle_types |= eprops.externalMemoryProperties.compatibleHandleTypes;
  1255. }
  1256. }
  1257. static AVBufferRef *vulkan_pool_alloc(void *opaque, int size)
  1258. {
  1259. int err;
  1260. AVVkFrame *f;
  1261. AVBufferRef *avbuf = NULL;
  1262. AVHWFramesContext *hwfc = opaque;
  1263. AVVulkanFramesContext *hwctx = hwfc->hwctx;
  1264. VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
  1265. VkExportMemoryAllocateInfo eminfo[AV_NUM_DATA_POINTERS];
  1266. VkExternalMemoryHandleTypeFlags e = 0x0;
  1267. VkExternalMemoryImageCreateInfo eiinfo = {
  1268. .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
  1269. .pNext = hwctx->create_pnext,
  1270. };
  1271. if (p->extensions & EXT_EXTERNAL_FD_MEMORY)
  1272. try_export_flags(hwfc, &eiinfo.handleTypes, &e,
  1273. VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT);
  1274. if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
  1275. try_export_flags(hwfc, &eiinfo.handleTypes, &e,
  1276. VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
  1277. for (int i = 0; i < av_pix_fmt_count_planes(hwfc->sw_format); i++) {
  1278. eminfo[i].sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO;
  1279. eminfo[i].pNext = hwctx->alloc_pnext[i];
  1280. eminfo[i].handleTypes = e;
  1281. }
  1282. err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
  1283. eiinfo.handleTypes ? &eiinfo : NULL);
  1284. if (err)
  1285. return NULL;
  1286. err = alloc_bind_mem(hwfc, f, eminfo, sizeof(*eminfo));
  1287. if (err)
  1288. goto fail;
  1289. err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_WRITE);
  1290. if (err)
  1291. goto fail;
  1292. avbuf = av_buffer_create((uint8_t *)f, sizeof(AVVkFrame),
  1293. vulkan_frame_free, hwfc, 0);
  1294. if (!avbuf)
  1295. goto fail;
  1296. return avbuf;
  1297. fail:
  1298. vulkan_frame_free(hwfc, (uint8_t *)f);
  1299. return NULL;
  1300. }
  1301. static void vulkan_frames_uninit(AVHWFramesContext *hwfc)
  1302. {
  1303. VulkanFramesPriv *fp = hwfc->internal->priv;
  1304. free_exec_ctx(hwfc->device_ctx, &fp->cmd);
  1305. }
  1306. static int vulkan_frames_init(AVHWFramesContext *hwfc)
  1307. {
  1308. int err;
  1309. AVVkFrame *f;
  1310. AVVulkanFramesContext *hwctx = hwfc->hwctx;
  1311. VulkanFramesPriv *fp = hwfc->internal->priv;
  1312. AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
  1313. VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
  1314. if (hwfc->pool)
  1315. return 0;
  1316. /* Default pool flags */
  1317. hwctx->tiling = hwctx->tiling ? hwctx->tiling : p->use_linear_images ?
  1318. VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
  1319. hwctx->usage |= DEFAULT_USAGE_FLAGS;
  1320. err = create_exec_ctx(hwfc->device_ctx, &fp->cmd,
  1321. dev_hwctx->queue_family_tx_index);
  1322. if (err)
  1323. return err;
  1324. /* Test to see if allocation will fail */
  1325. err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
  1326. hwctx->create_pnext);
  1327. if (err) {
  1328. free_exec_ctx(hwfc->device_ctx, &p->cmd);
  1329. return err;
  1330. }
  1331. vulkan_frame_free(hwfc, (uint8_t *)f);
  1332. hwfc->internal->pool_internal = av_buffer_pool_init2(sizeof(AVVkFrame),
  1333. hwfc, vulkan_pool_alloc,
  1334. NULL);
  1335. if (!hwfc->internal->pool_internal) {
  1336. free_exec_ctx(hwfc->device_ctx, &p->cmd);
  1337. return AVERROR(ENOMEM);
  1338. }
  1339. return 0;
  1340. }
  1341. static int vulkan_get_buffer(AVHWFramesContext *hwfc, AVFrame *frame)
  1342. {
  1343. frame->buf[0] = av_buffer_pool_get(hwfc->pool);
  1344. if (!frame->buf[0])
  1345. return AVERROR(ENOMEM);
  1346. frame->data[0] = frame->buf[0]->data;
  1347. frame->format = AV_PIX_FMT_VULKAN;
  1348. frame->width = hwfc->width;
  1349. frame->height = hwfc->height;
  1350. return 0;
  1351. }
  1352. static int vulkan_transfer_get_formats(AVHWFramesContext *hwfc,
  1353. enum AVHWFrameTransferDirection dir,
  1354. enum AVPixelFormat **formats)
  1355. {
  1356. enum AVPixelFormat *fmts = av_malloc_array(2, sizeof(*fmts));
  1357. if (!fmts)
  1358. return AVERROR(ENOMEM);
  1359. fmts[0] = hwfc->sw_format;
  1360. fmts[1] = AV_PIX_FMT_NONE;
  1361. *formats = fmts;
  1362. return 0;
  1363. }
  1364. typedef struct VulkanMapping {
  1365. AVVkFrame *frame;
  1366. int flags;
  1367. } VulkanMapping;
  1368. static void vulkan_unmap_frame(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
  1369. {
  1370. VulkanMapping *map = hwmap->priv;
  1371. AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
  1372. const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
  1373. /* Check if buffer needs flushing */
  1374. if ((map->flags & AV_HWFRAME_MAP_WRITE) &&
  1375. !(map->frame->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
  1376. VkResult ret;
  1377. VkMappedMemoryRange flush_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
  1378. for (int i = 0; i < planes; i++) {
  1379. flush_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
  1380. flush_ranges[i].memory = map->frame->mem[i];
  1381. flush_ranges[i].size = VK_WHOLE_SIZE;
  1382. }
  1383. ret = vkFlushMappedMemoryRanges(hwctx->act_dev, planes,
  1384. flush_ranges);
  1385. if (ret != VK_SUCCESS) {
  1386. av_log(hwfc, AV_LOG_ERROR, "Failed to flush memory: %s\n",
  1387. vk_ret2str(ret));
  1388. }
  1389. }
  1390. for (int i = 0; i < planes; i++)
  1391. vkUnmapMemory(hwctx->act_dev, map->frame->mem[i]);
  1392. av_free(map);
  1393. }
  1394. static int vulkan_map_frame_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
  1395. const AVFrame *src, int flags)
  1396. {
  1397. VkResult ret;
  1398. int err, mapped_mem_count = 0;
  1399. AVVkFrame *f = (AVVkFrame *)src->data[0];
  1400. AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
  1401. const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
  1402. VulkanMapping *map = av_mallocz(sizeof(VulkanMapping));
  1403. if (!map)
  1404. return AVERROR(EINVAL);
  1405. if (src->format != AV_PIX_FMT_VULKAN) {
  1406. av_log(hwfc, AV_LOG_ERROR, "Cannot map from pixel format %s!\n",
  1407. av_get_pix_fmt_name(src->format));
  1408. err = AVERROR(EINVAL);
  1409. goto fail;
  1410. }
  1411. if (!(f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ||
  1412. !(f->tiling == VK_IMAGE_TILING_LINEAR)) {
  1413. av_log(hwfc, AV_LOG_ERROR, "Unable to map frame, not host visible "
  1414. "and linear!\n");
  1415. err = AVERROR(EINVAL);
  1416. goto fail;
  1417. }
  1418. dst->width = src->width;
  1419. dst->height = src->height;
  1420. for (int i = 0; i < planes; i++) {
  1421. ret = vkMapMemory(hwctx->act_dev, f->mem[i], 0,
  1422. VK_WHOLE_SIZE, 0, (void **)&dst->data[i]);
  1423. if (ret != VK_SUCCESS) {
  1424. av_log(hwfc, AV_LOG_ERROR, "Failed to map image memory: %s\n",
  1425. vk_ret2str(ret));
  1426. err = AVERROR_EXTERNAL;
  1427. goto fail;
  1428. }
  1429. mapped_mem_count++;
  1430. }
  1431. /* Check if the memory contents matter */
  1432. if (((flags & AV_HWFRAME_MAP_READ) || !(flags & AV_HWFRAME_MAP_OVERWRITE)) &&
  1433. !(f->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
  1434. VkMappedMemoryRange map_mem_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
  1435. for (int i = 0; i < planes; i++) {
  1436. map_mem_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
  1437. map_mem_ranges[i].size = VK_WHOLE_SIZE;
  1438. map_mem_ranges[i].memory = f->mem[i];
  1439. }
  1440. ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, planes,
  1441. map_mem_ranges);
  1442. if (ret != VK_SUCCESS) {
  1443. av_log(hwfc, AV_LOG_ERROR, "Failed to invalidate memory: %s\n",
  1444. vk_ret2str(ret));
  1445. err = AVERROR_EXTERNAL;
  1446. goto fail;
  1447. }
  1448. }
  1449. for (int i = 0; i < planes; i++) {
  1450. VkImageSubresource sub = {
  1451. .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
  1452. };
  1453. VkSubresourceLayout layout;
  1454. vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
  1455. dst->linesize[i] = layout.rowPitch;
  1456. }
  1457. map->frame = f;
  1458. map->flags = flags;
  1459. err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src,
  1460. &vulkan_unmap_frame, map);
  1461. if (err < 0)
  1462. goto fail;
  1463. return 0;
  1464. fail:
  1465. for (int i = 0; i < mapped_mem_count; i++)
  1466. vkUnmapMemory(hwctx->act_dev, f->mem[i]);
  1467. av_free(map);
  1468. return err;
  1469. }
  1470. #if CONFIG_LIBDRM
  1471. static void vulkan_unmap_from(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
  1472. {
  1473. VulkanMapping *map = hwmap->priv;
  1474. AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
  1475. const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
  1476. for (int i = 0; i < planes; i++) {
  1477. vkDestroyImage(hwctx->act_dev, map->frame->img[i], hwctx->alloc);
  1478. vkFreeMemory(hwctx->act_dev, map->frame->mem[i], hwctx->alloc);
  1479. vkDestroySemaphore(hwctx->act_dev, map->frame->sem[i], hwctx->alloc);
  1480. }
  1481. av_freep(&map->frame);
  1482. }
  1483. static const struct {
  1484. uint32_t drm_fourcc;
  1485. VkFormat vk_format;
  1486. } vulkan_drm_format_map[] = {
  1487. { DRM_FORMAT_R8, VK_FORMAT_R8_UNORM },
  1488. { DRM_FORMAT_R16, VK_FORMAT_R16_UNORM },
  1489. { DRM_FORMAT_GR88, VK_FORMAT_R8G8_UNORM },
  1490. { DRM_FORMAT_RG88, VK_FORMAT_R8G8_UNORM },
  1491. { DRM_FORMAT_GR1616, VK_FORMAT_R16G16_UNORM },
  1492. { DRM_FORMAT_RG1616, VK_FORMAT_R16G16_UNORM },
  1493. { DRM_FORMAT_ARGB8888, VK_FORMAT_B8G8R8A8_UNORM },
  1494. { DRM_FORMAT_XRGB8888, VK_FORMAT_B8G8R8A8_UNORM },
  1495. { DRM_FORMAT_ABGR8888, VK_FORMAT_R8G8B8A8_UNORM },
  1496. { DRM_FORMAT_XBGR8888, VK_FORMAT_R8G8B8A8_UNORM },
  1497. };
  1498. static inline VkFormat drm_to_vulkan_fmt(uint32_t drm_fourcc)
  1499. {
  1500. for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
  1501. if (vulkan_drm_format_map[i].drm_fourcc == drm_fourcc)
  1502. return vulkan_drm_format_map[i].vk_format;
  1503. return VK_FORMAT_UNDEFINED;
  1504. }
  1505. static int vulkan_map_from_drm_frame_desc(AVHWFramesContext *hwfc, AVVkFrame **frame,
  1506. AVDRMFrameDescriptor *desc)
  1507. {
  1508. int err = 0;
  1509. VkResult ret;
  1510. AVVkFrame *f;
  1511. int bind_counts = 0;
  1512. AVHWDeviceContext *ctx = hwfc->device_ctx;
  1513. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  1514. VulkanDevicePriv *p = ctx->internal->priv;
  1515. const AVPixFmtDescriptor *fmt_desc = av_pix_fmt_desc_get(hwfc->sw_format);
  1516. const int has_modifiers = p->extensions & EXT_DRM_MODIFIER_FLAGS;
  1517. VkSubresourceLayout plane_data[AV_NUM_DATA_POINTERS] = { 0 };
  1518. VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { 0 };
  1519. VkBindImagePlaneMemoryInfo plane_info[AV_NUM_DATA_POINTERS] = { 0 };
  1520. VkExternalMemoryHandleTypeFlagBits htype = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
  1521. VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdPropertiesKHR);
  1522. for (int i = 0; i < desc->nb_layers; i++) {
  1523. if (drm_to_vulkan_fmt(desc->layers[i].format) == VK_FORMAT_UNDEFINED) {
  1524. av_log(ctx, AV_LOG_ERROR, "Unsupported DMABUF layer format %#08x!\n",
  1525. desc->layers[i].format);
  1526. return AVERROR(EINVAL);
  1527. }
  1528. }
  1529. if (!(f = av_vk_frame_alloc())) {
  1530. av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
  1531. err = AVERROR(ENOMEM);
  1532. goto fail;
  1533. }
  1534. for (int i = 0; i < desc->nb_objects; i++) {
  1535. VkMemoryFdPropertiesKHR fdmp = {
  1536. .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,
  1537. };
  1538. VkMemoryRequirements req = {
  1539. .size = desc->objects[i].size,
  1540. };
  1541. VkImportMemoryFdInfoKHR idesc = {
  1542. .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
  1543. .handleType = htype,
  1544. .fd = dup(desc->objects[i].fd),
  1545. };
  1546. ret = pfn_vkGetMemoryFdPropertiesKHR(hwctx->act_dev, htype,
  1547. idesc.fd, &fdmp);
  1548. if (ret != VK_SUCCESS) {
  1549. av_log(hwfc, AV_LOG_ERROR, "Failed to get FD properties: %s\n",
  1550. vk_ret2str(ret));
  1551. err = AVERROR_EXTERNAL;
  1552. close(idesc.fd);
  1553. goto fail;
  1554. }
  1555. req.memoryTypeBits = fdmp.memoryTypeBits;
  1556. err = alloc_mem(ctx, &req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
  1557. &idesc, &f->flags, &f->mem[i]);
  1558. if (err) {
  1559. close(idesc.fd);
  1560. return err;
  1561. }
  1562. f->size[i] = desc->objects[i].size;
  1563. }
  1564. f->tiling = has_modifiers ? VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT :
  1565. desc->objects[0].format_modifier == DRM_FORMAT_MOD_LINEAR ?
  1566. VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
  1567. for (int i = 0; i < desc->nb_layers; i++) {
  1568. const int planes = desc->layers[i].nb_planes;
  1569. const int signal_p = has_modifiers && (planes > 1);
  1570. VkImageDrmFormatModifierExplicitCreateInfoEXT drm_info = {
  1571. .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
  1572. .drmFormatModifier = desc->objects[0].format_modifier,
  1573. .drmFormatModifierPlaneCount = planes,
  1574. .pPlaneLayouts = (const VkSubresourceLayout *)&plane_data,
  1575. };
  1576. VkExternalMemoryImageCreateInfo einfo = {
  1577. .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
  1578. .pNext = has_modifiers ? &drm_info : NULL,
  1579. .handleTypes = htype,
  1580. };
  1581. VkSemaphoreCreateInfo sem_spawn = {
  1582. .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
  1583. };
  1584. const int p_w = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, fmt_desc->log2_chroma_w) : hwfc->width;
  1585. const int p_h = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, fmt_desc->log2_chroma_h) : hwfc->height;
  1586. VkImageCreateInfo image_create_info = {
  1587. .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
  1588. .pNext = &einfo,
  1589. .imageType = VK_IMAGE_TYPE_2D,
  1590. .format = drm_to_vulkan_fmt(desc->layers[i].format),
  1591. .extent.width = p_w,
  1592. .extent.height = p_h,
  1593. .extent.depth = 1,
  1594. .mipLevels = 1,
  1595. .arrayLayers = 1,
  1596. .flags = VK_IMAGE_CREATE_ALIAS_BIT,
  1597. .tiling = f->tiling,
  1598. .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, /* specs say so */
  1599. .usage = DEFAULT_USAGE_FLAGS,
  1600. .samples = VK_SAMPLE_COUNT_1_BIT,
  1601. .pQueueFamilyIndices = p->qfs,
  1602. .queueFamilyIndexCount = p->num_qfs,
  1603. .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
  1604. VK_SHARING_MODE_EXCLUSIVE,
  1605. };
  1606. for (int j = 0; j < planes; j++) {
  1607. plane_data[j].offset = desc->layers[i].planes[j].offset;
  1608. plane_data[j].rowPitch = desc->layers[i].planes[j].pitch;
  1609. plane_data[j].size = 0; /* The specs say so for all 3 */
  1610. plane_data[j].arrayPitch = 0;
  1611. plane_data[j].depthPitch = 0;
  1612. }
  1613. /* Create image */
  1614. ret = vkCreateImage(hwctx->act_dev, &image_create_info,
  1615. hwctx->alloc, &f->img[i]);
  1616. if (ret != VK_SUCCESS) {
  1617. av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
  1618. vk_ret2str(ret));
  1619. err = AVERROR(EINVAL);
  1620. goto fail;
  1621. }
  1622. ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
  1623. hwctx->alloc, &f->sem[i]);
  1624. if (ret != VK_SUCCESS) {
  1625. av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
  1626. vk_ret2str(ret));
  1627. return AVERROR_EXTERNAL;
  1628. }
  1629. /* We'd import a semaphore onto the one we created using
  1630. * vkImportSemaphoreFdKHR but unfortunately neither DRM nor VAAPI
  1631. * offer us anything we could import and sync with, so instead
  1632. * just signal the semaphore we created. */
  1633. f->layout[i] = image_create_info.initialLayout;
  1634. f->access[i] = 0x0;
  1635. for (int j = 0; j < planes; j++) {
  1636. VkImageAspectFlagBits aspect = j == 0 ? VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
  1637. j == 1 ? VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT :
  1638. VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT;
  1639. plane_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO;
  1640. plane_info[bind_counts].planeAspect = aspect;
  1641. bind_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
  1642. bind_info[bind_counts].pNext = signal_p ? &plane_info[bind_counts] : NULL;
  1643. bind_info[bind_counts].image = f->img[i];
  1644. bind_info[bind_counts].memory = f->mem[desc->layers[i].planes[j].object_index];
  1645. bind_info[bind_counts].memoryOffset = desc->layers[i].planes[j].offset;
  1646. bind_counts++;
  1647. }
  1648. }
  1649. /* Bind the allocated memory to the images */
  1650. ret = vkBindImageMemory2(hwctx->act_dev, bind_counts, bind_info);
  1651. if (ret != VK_SUCCESS) {
  1652. av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
  1653. vk_ret2str(ret));
  1654. return AVERROR_EXTERNAL;
  1655. }
  1656. /* NOTE: This is completely uneccesary and unneeded once we can import
  1657. * semaphores from DRM. Otherwise we have to activate the semaphores.
  1658. * We're reusing the exec context that's also used for uploads/downloads. */
  1659. err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_RO_SHADER);
  1660. if (err)
  1661. goto fail;
  1662. *frame = f;
  1663. return 0;
  1664. fail:
  1665. for (int i = 0; i < desc->nb_layers; i++) {
  1666. vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
  1667. vkDestroySemaphore(hwctx->act_dev, f->sem[i], hwctx->alloc);
  1668. }
  1669. for (int i = 0; i < desc->nb_objects; i++)
  1670. vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
  1671. av_free(f);
  1672. return err;
  1673. }
  1674. static int vulkan_map_from_drm(AVHWFramesContext *hwfc, AVFrame *dst,
  1675. const AVFrame *src, int flags)
  1676. {
  1677. int err = 0;
  1678. AVVkFrame *f;
  1679. VulkanMapping *map = NULL;
  1680. err = vulkan_map_from_drm_frame_desc(hwfc, &f,
  1681. (AVDRMFrameDescriptor *)src->data[0]);
  1682. if (err)
  1683. return err;
  1684. /* The unmapping function will free this */
  1685. dst->data[0] = (uint8_t *)f;
  1686. dst->width = src->width;
  1687. dst->height = src->height;
  1688. map = av_mallocz(sizeof(VulkanMapping));
  1689. if (!map)
  1690. goto fail;
  1691. map->frame = f;
  1692. map->flags = flags;
  1693. err = ff_hwframe_map_create(dst->hw_frames_ctx, dst, src,
  1694. &vulkan_unmap_from, map);
  1695. if (err < 0)
  1696. goto fail;
  1697. av_log(hwfc, AV_LOG_DEBUG, "Mapped DRM object to Vulkan!\n");
  1698. return 0;
  1699. fail:
  1700. vulkan_frame_free(hwfc->device_ctx->hwctx, (uint8_t *)f);
  1701. av_free(map);
  1702. return err;
  1703. }
  1704. #if CONFIG_VAAPI
  1705. static int vulkan_map_from_vaapi(AVHWFramesContext *dst_fc,
  1706. AVFrame *dst, const AVFrame *src,
  1707. int flags)
  1708. {
  1709. int err;
  1710. AVFrame *tmp = av_frame_alloc();
  1711. AVHWFramesContext *vaapi_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
  1712. AVVAAPIDeviceContext *vaapi_ctx = vaapi_fc->device_ctx->hwctx;
  1713. VASurfaceID surface_id = (VASurfaceID)(uintptr_t)src->data[3];
  1714. if (!tmp)
  1715. return AVERROR(ENOMEM);
  1716. /* We have to sync since like the previous comment said, no semaphores */
  1717. vaSyncSurface(vaapi_ctx->display, surface_id);
  1718. tmp->format = AV_PIX_FMT_DRM_PRIME;
  1719. err = av_hwframe_map(tmp, src, flags);
  1720. if (err < 0)
  1721. goto fail;
  1722. err = vulkan_map_from_drm(dst_fc, dst, tmp, flags);
  1723. if (err < 0)
  1724. goto fail;
  1725. err = ff_hwframe_map_replace(dst, src);
  1726. fail:
  1727. av_frame_free(&tmp);
  1728. return err;
  1729. }
  1730. #endif
  1731. #endif
  1732. #if CONFIG_CUDA
  1733. static int vulkan_export_to_cuda(AVHWFramesContext *hwfc,
  1734. AVBufferRef *cuda_hwfc,
  1735. const AVFrame *frame)
  1736. {
  1737. int err;
  1738. VkResult ret;
  1739. AVVkFrame *dst_f;
  1740. AVVkFrameInternal *dst_int;
  1741. AVHWDeviceContext *ctx = hwfc->device_ctx;
  1742. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  1743. const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
  1744. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
  1745. VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
  1746. VK_LOAD_PFN(hwctx->inst, vkGetSemaphoreFdKHR);
  1747. AVHWFramesContext *cuda_fc = (AVHWFramesContext*)cuda_hwfc->data;
  1748. AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
  1749. AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
  1750. AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
  1751. CudaFunctions *cu = cu_internal->cuda_dl;
  1752. CUarray_format cufmt = desc->comp[0].depth > 8 ? CU_AD_FORMAT_UNSIGNED_INT16 :
  1753. CU_AD_FORMAT_UNSIGNED_INT8;
  1754. dst_f = (AVVkFrame *)frame->data[0];
  1755. dst_int = dst_f->internal;
  1756. if (!dst_int || !dst_int->cuda_fc_ref) {
  1757. if (!dst_f->internal)
  1758. dst_f->internal = dst_int = av_mallocz(sizeof(*dst_f->internal));
  1759. if (!dst_int) {
  1760. err = AVERROR(ENOMEM);
  1761. goto fail;
  1762. }
  1763. dst_int->cuda_fc_ref = av_buffer_ref(cuda_hwfc);
  1764. if (!dst_int->cuda_fc_ref) {
  1765. err = AVERROR(ENOMEM);
  1766. goto fail;
  1767. }
  1768. for (int i = 0; i < planes; i++) {
  1769. CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC tex_desc = {
  1770. .offset = 0,
  1771. .arrayDesc = {
  1772. .Width = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
  1773. : hwfc->width,
  1774. .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
  1775. : hwfc->height,
  1776. .Depth = 0,
  1777. .Format = cufmt,
  1778. .NumChannels = 1 + ((planes == 2) && i),
  1779. .Flags = 0,
  1780. },
  1781. .numLevels = 1,
  1782. };
  1783. CUDA_EXTERNAL_MEMORY_HANDLE_DESC ext_desc = {
  1784. .type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD,
  1785. .size = dst_f->size[i],
  1786. };
  1787. VkMemoryGetFdInfoKHR export_info = {
  1788. .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
  1789. .memory = dst_f->mem[i],
  1790. .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR,
  1791. };
  1792. VkSemaphoreGetFdInfoKHR sem_export = {
  1793. .sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR,
  1794. .semaphore = dst_f->sem[i],
  1795. .handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
  1796. };
  1797. CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC ext_sem_desc = {
  1798. .type = CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD,
  1799. };
  1800. ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
  1801. &ext_desc.handle.fd);
  1802. if (ret != VK_SUCCESS) {
  1803. av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
  1804. err = AVERROR_EXTERNAL;
  1805. goto fail;
  1806. }
  1807. ret = CHECK_CU(cu->cuImportExternalMemory(&dst_int->ext_mem[i], &ext_desc));
  1808. if (ret < 0) {
  1809. err = AVERROR_EXTERNAL;
  1810. goto fail;
  1811. }
  1812. ret = CHECK_CU(cu->cuExternalMemoryGetMappedMipmappedArray(&dst_int->cu_mma[i],
  1813. dst_int->ext_mem[i],
  1814. &tex_desc));
  1815. if (ret < 0) {
  1816. err = AVERROR_EXTERNAL;
  1817. goto fail;
  1818. }
  1819. ret = CHECK_CU(cu->cuMipmappedArrayGetLevel(&dst_int->cu_array[i],
  1820. dst_int->cu_mma[i], 0));
  1821. if (ret < 0) {
  1822. err = AVERROR_EXTERNAL;
  1823. goto fail;
  1824. }
  1825. ret = pfn_vkGetSemaphoreFdKHR(hwctx->act_dev, &sem_export,
  1826. &ext_sem_desc.handle.fd);
  1827. if (ret != VK_SUCCESS) {
  1828. av_log(ctx, AV_LOG_ERROR, "Failed to export semaphore: %s\n",
  1829. vk_ret2str(ret));
  1830. err = AVERROR_EXTERNAL;
  1831. goto fail;
  1832. }
  1833. ret = CHECK_CU(cu->cuImportExternalSemaphore(&dst_int->cu_sem[i],
  1834. &ext_sem_desc));
  1835. if (ret < 0) {
  1836. err = AVERROR_EXTERNAL;
  1837. goto fail;
  1838. }
  1839. }
  1840. }
  1841. return 0;
  1842. fail:
  1843. return err;
  1844. }
  1845. static int vulkan_transfer_data_from_cuda(AVHWFramesContext *hwfc,
  1846. AVFrame *dst, const AVFrame *src)
  1847. {
  1848. int err;
  1849. VkResult ret;
  1850. CUcontext dummy;
  1851. AVVkFrame *dst_f;
  1852. AVVkFrameInternal *dst_int;
  1853. const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
  1854. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
  1855. AVHWFramesContext *cuda_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
  1856. AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
  1857. AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
  1858. AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
  1859. CudaFunctions *cu = cu_internal->cuda_dl;
  1860. CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS s_w_par[AV_NUM_DATA_POINTERS] = { 0 };
  1861. CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS s_s_par[AV_NUM_DATA_POINTERS] = { 0 };
  1862. ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
  1863. if (ret < 0) {
  1864. err = AVERROR_EXTERNAL;
  1865. goto fail;
  1866. }
  1867. dst_f = (AVVkFrame *)dst->data[0];
  1868. ret = vulkan_export_to_cuda(hwfc, src->hw_frames_ctx, dst);
  1869. if (ret < 0) {
  1870. goto fail;
  1871. }
  1872. dst_int = dst_f->internal;
  1873. ret = CHECK_CU(cu->cuWaitExternalSemaphoresAsync(dst_int->cu_sem, s_w_par,
  1874. planes, cuda_dev->stream));
  1875. if (ret < 0) {
  1876. err = AVERROR_EXTERNAL;
  1877. goto fail;
  1878. }
  1879. for (int i = 0; i < planes; i++) {
  1880. CUDA_MEMCPY2D cpy = {
  1881. .srcMemoryType = CU_MEMORYTYPE_DEVICE,
  1882. .srcDevice = (CUdeviceptr)src->data[i],
  1883. .srcPitch = src->linesize[i],
  1884. .srcY = 0,
  1885. .dstMemoryType = CU_MEMORYTYPE_ARRAY,
  1886. .dstArray = dst_int->cu_array[i],
  1887. .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
  1888. : hwfc->width) * desc->comp[i].step,
  1889. .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
  1890. : hwfc->height,
  1891. };
  1892. ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
  1893. if (ret < 0) {
  1894. err = AVERROR_EXTERNAL;
  1895. goto fail;
  1896. }
  1897. }
  1898. ret = CHECK_CU(cu->cuSignalExternalSemaphoresAsync(dst_int->cu_sem, s_s_par,
  1899. planes, cuda_dev->stream));
  1900. if (ret < 0) {
  1901. err = AVERROR_EXTERNAL;
  1902. goto fail;
  1903. }
  1904. CHECK_CU(cu->cuCtxPopCurrent(&dummy));
  1905. av_log(hwfc, AV_LOG_VERBOSE, "Transfered CUDA image to Vulkan!\n");
  1906. return 0;
  1907. fail:
  1908. CHECK_CU(cu->cuCtxPopCurrent(&dummy));
  1909. vulkan_free_internal(dst_int);
  1910. dst_f->internal = NULL;
  1911. av_buffer_unref(&dst->buf[0]);
  1912. return err;
  1913. }
  1914. #endif
  1915. static int vulkan_map_to(AVHWFramesContext *hwfc, AVFrame *dst,
  1916. const AVFrame *src, int flags)
  1917. {
  1918. av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
  1919. switch (src->format) {
  1920. #if CONFIG_LIBDRM
  1921. #if CONFIG_VAAPI
  1922. case AV_PIX_FMT_VAAPI:
  1923. if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
  1924. return vulkan_map_from_vaapi(hwfc, dst, src, flags);
  1925. #endif
  1926. case AV_PIX_FMT_DRM_PRIME:
  1927. if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
  1928. return vulkan_map_from_drm(hwfc, dst, src, flags);
  1929. #endif
  1930. default:
  1931. return AVERROR(ENOSYS);
  1932. }
  1933. }
  1934. #if CONFIG_LIBDRM
  1935. typedef struct VulkanDRMMapping {
  1936. AVDRMFrameDescriptor drm_desc;
  1937. AVVkFrame *source;
  1938. } VulkanDRMMapping;
  1939. static void vulkan_unmap_to_drm(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
  1940. {
  1941. AVDRMFrameDescriptor *drm_desc = hwmap->priv;
  1942. for (int i = 0; i < drm_desc->nb_objects; i++)
  1943. close(drm_desc->objects[i].fd);
  1944. av_free(drm_desc);
  1945. }
  1946. static inline uint32_t vulkan_fmt_to_drm(VkFormat vkfmt)
  1947. {
  1948. for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
  1949. if (vulkan_drm_format_map[i].vk_format == vkfmt)
  1950. return vulkan_drm_format_map[i].drm_fourcc;
  1951. return DRM_FORMAT_INVALID;
  1952. }
  1953. static int vulkan_map_to_drm(AVHWFramesContext *hwfc, AVFrame *dst,
  1954. const AVFrame *src, int flags)
  1955. {
  1956. int err = 0;
  1957. VkResult ret;
  1958. AVVkFrame *f = (AVVkFrame *)src->data[0];
  1959. VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
  1960. AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
  1961. const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
  1962. VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
  1963. VkImageDrmFormatModifierPropertiesEXT drm_mod = {
  1964. .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT,
  1965. };
  1966. AVDRMFrameDescriptor *drm_desc = av_mallocz(sizeof(*drm_desc));
  1967. if (!drm_desc)
  1968. return AVERROR(ENOMEM);
  1969. err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_EXTERNAL_EXPORT);
  1970. if (err < 0)
  1971. goto end;
  1972. err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src, &vulkan_unmap_to_drm, drm_desc);
  1973. if (err < 0)
  1974. goto end;
  1975. if (p->extensions & EXT_DRM_MODIFIER_FLAGS) {
  1976. VK_LOAD_PFN(hwctx->inst, vkGetImageDrmFormatModifierPropertiesEXT);
  1977. ret = pfn_vkGetImageDrmFormatModifierPropertiesEXT(hwctx->act_dev, f->img[0],
  1978. &drm_mod);
  1979. if (ret != VK_SUCCESS) {
  1980. av_log(hwfc, AV_LOG_ERROR, "Failed to retrieve DRM format modifier!\n");
  1981. err = AVERROR_EXTERNAL;
  1982. goto end;
  1983. }
  1984. }
  1985. for (int i = 0; (i < planes) && (f->mem[i]); i++) {
  1986. VkMemoryGetFdInfoKHR export_info = {
  1987. .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
  1988. .memory = f->mem[i],
  1989. .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,
  1990. };
  1991. ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
  1992. &drm_desc->objects[i].fd);
  1993. if (ret != VK_SUCCESS) {
  1994. av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
  1995. err = AVERROR_EXTERNAL;
  1996. goto end;
  1997. }
  1998. drm_desc->nb_objects++;
  1999. drm_desc->objects[i].size = f->size[i];
  2000. drm_desc->objects[i].format_modifier = drm_mod.drmFormatModifier;
  2001. }
  2002. drm_desc->nb_layers = planes;
  2003. for (int i = 0; i < drm_desc->nb_layers; i++) {
  2004. VkSubresourceLayout layout;
  2005. VkImageSubresource sub = {
  2006. .aspectMask = p->extensions & EXT_DRM_MODIFIER_FLAGS ?
  2007. VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
  2008. VK_IMAGE_ASPECT_COLOR_BIT,
  2009. };
  2010. VkFormat plane_vkfmt = av_vkfmt_from_pixfmt(hwfc->sw_format)[i];
  2011. drm_desc->layers[i].format = vulkan_fmt_to_drm(plane_vkfmt);
  2012. drm_desc->layers[i].nb_planes = 1;
  2013. if (drm_desc->layers[i].format == DRM_FORMAT_INVALID) {
  2014. av_log(hwfc, AV_LOG_ERROR, "Cannot map to DRM layer, unsupported!\n");
  2015. err = AVERROR_PATCHWELCOME;
  2016. goto end;
  2017. }
  2018. drm_desc->layers[i].planes[0].object_index = FFMIN(i, drm_desc->nb_objects - 1);
  2019. if (f->tiling == VK_IMAGE_TILING_OPTIMAL)
  2020. continue;
  2021. vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
  2022. drm_desc->layers[i].planes[0].offset = layout.offset;
  2023. drm_desc->layers[i].planes[0].pitch = layout.rowPitch;
  2024. }
  2025. dst->width = src->width;
  2026. dst->height = src->height;
  2027. dst->data[0] = (uint8_t *)drm_desc;
  2028. av_log(hwfc, AV_LOG_VERBOSE, "Mapped AVVkFrame to a DRM object!\n");
  2029. return 0;
  2030. end:
  2031. av_free(drm_desc);
  2032. return err;
  2033. }
  2034. #if CONFIG_VAAPI
  2035. static int vulkan_map_to_vaapi(AVHWFramesContext *hwfc, AVFrame *dst,
  2036. const AVFrame *src, int flags)
  2037. {
  2038. int err;
  2039. AVFrame *tmp = av_frame_alloc();
  2040. if (!tmp)
  2041. return AVERROR(ENOMEM);
  2042. tmp->format = AV_PIX_FMT_DRM_PRIME;
  2043. err = vulkan_map_to_drm(hwfc, tmp, src, flags);
  2044. if (err < 0)
  2045. goto fail;
  2046. err = av_hwframe_map(dst, tmp, flags);
  2047. if (err < 0)
  2048. goto fail;
  2049. err = ff_hwframe_map_replace(dst, src);
  2050. fail:
  2051. av_frame_free(&tmp);
  2052. return err;
  2053. }
  2054. #endif
  2055. #endif
  2056. static int vulkan_map_from(AVHWFramesContext *hwfc, AVFrame *dst,
  2057. const AVFrame *src, int flags)
  2058. {
  2059. av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
  2060. switch (dst->format) {
  2061. #if CONFIG_LIBDRM
  2062. case AV_PIX_FMT_DRM_PRIME:
  2063. if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
  2064. return vulkan_map_to_drm(hwfc, dst, src, flags);
  2065. #if CONFIG_VAAPI
  2066. case AV_PIX_FMT_VAAPI:
  2067. if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
  2068. return vulkan_map_to_vaapi(hwfc, dst, src, flags);
  2069. #endif
  2070. #endif
  2071. default:
  2072. return vulkan_map_frame_to_mem(hwfc, dst, src, flags);
  2073. }
  2074. }
  2075. typedef struct ImageBuffer {
  2076. VkBuffer buf;
  2077. VkDeviceMemory mem;
  2078. VkMemoryPropertyFlagBits flags;
  2079. } ImageBuffer;
  2080. static void free_buf(AVHWDeviceContext *ctx, ImageBuffer *buf)
  2081. {
  2082. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  2083. if (!buf)
  2084. return;
  2085. vkDestroyBuffer(hwctx->act_dev, buf->buf, hwctx->alloc);
  2086. vkFreeMemory(hwctx->act_dev, buf->mem, hwctx->alloc);
  2087. }
  2088. static int create_buf(AVHWDeviceContext *ctx, ImageBuffer *buf, int height,
  2089. int *stride, VkBufferUsageFlags usage,
  2090. VkMemoryPropertyFlagBits flags, void *create_pnext,
  2091. void *alloc_pnext)
  2092. {
  2093. int err;
  2094. VkResult ret;
  2095. VkMemoryRequirements req;
  2096. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  2097. VulkanDevicePriv *p = ctx->internal->priv;
  2098. VkBufferCreateInfo buf_spawn = {
  2099. .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
  2100. .pNext = create_pnext,
  2101. .usage = usage,
  2102. .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
  2103. };
  2104. *stride = FFALIGN(*stride, p->props.limits.optimalBufferCopyRowPitchAlignment);
  2105. buf_spawn.size = height*(*stride);
  2106. ret = vkCreateBuffer(hwctx->act_dev, &buf_spawn, NULL, &buf->buf);
  2107. if (ret != VK_SUCCESS) {
  2108. av_log(ctx, AV_LOG_ERROR, "Failed to create buffer: %s\n",
  2109. vk_ret2str(ret));
  2110. return AVERROR_EXTERNAL;
  2111. }
  2112. vkGetBufferMemoryRequirements(hwctx->act_dev, buf->buf, &req);
  2113. err = alloc_mem(ctx, &req, flags, alloc_pnext, &buf->flags, &buf->mem);
  2114. if (err)
  2115. return err;
  2116. ret = vkBindBufferMemory(hwctx->act_dev, buf->buf, buf->mem, 0);
  2117. if (ret != VK_SUCCESS) {
  2118. av_log(ctx, AV_LOG_ERROR, "Failed to bind memory to buffer: %s\n",
  2119. vk_ret2str(ret));
  2120. free_buf(ctx, buf);
  2121. return AVERROR_EXTERNAL;
  2122. }
  2123. return 0;
  2124. }
  2125. static int map_buffers(AVHWDeviceContext *ctx, ImageBuffer *buf, uint8_t *mem[],
  2126. int nb_buffers, int invalidate)
  2127. {
  2128. VkResult ret;
  2129. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  2130. VkMappedMemoryRange invalidate_ctx[AV_NUM_DATA_POINTERS];
  2131. int invalidate_count = 0;
  2132. for (int i = 0; i < nb_buffers; i++) {
  2133. ret = vkMapMemory(hwctx->act_dev, buf[i].mem, 0,
  2134. VK_WHOLE_SIZE, 0, (void **)&mem[i]);
  2135. if (ret != VK_SUCCESS) {
  2136. av_log(ctx, AV_LOG_ERROR, "Failed to map buffer memory: %s\n",
  2137. vk_ret2str(ret));
  2138. return AVERROR_EXTERNAL;
  2139. }
  2140. }
  2141. if (!invalidate)
  2142. return 0;
  2143. for (int i = 0; i < nb_buffers; i++) {
  2144. const VkMappedMemoryRange ival_buf = {
  2145. .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
  2146. .memory = buf[i].mem,
  2147. .size = VK_WHOLE_SIZE,
  2148. };
  2149. if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
  2150. continue;
  2151. invalidate_ctx[invalidate_count++] = ival_buf;
  2152. }
  2153. if (invalidate_count) {
  2154. ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, invalidate_count,
  2155. invalidate_ctx);
  2156. if (ret != VK_SUCCESS)
  2157. av_log(ctx, AV_LOG_WARNING, "Failed to invalidate memory: %s\n",
  2158. vk_ret2str(ret));
  2159. }
  2160. return 0;
  2161. }
  2162. static int unmap_buffers(AVHWDeviceContext *ctx, ImageBuffer *buf,
  2163. int nb_buffers, int flush)
  2164. {
  2165. int err = 0;
  2166. VkResult ret;
  2167. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  2168. VkMappedMemoryRange flush_ctx[AV_NUM_DATA_POINTERS];
  2169. int flush_count = 0;
  2170. if (flush) {
  2171. for (int i = 0; i < nb_buffers; i++) {
  2172. const VkMappedMemoryRange flush_buf = {
  2173. .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
  2174. .memory = buf[i].mem,
  2175. .size = VK_WHOLE_SIZE,
  2176. };
  2177. if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
  2178. continue;
  2179. flush_ctx[flush_count++] = flush_buf;
  2180. }
  2181. }
  2182. if (flush_count) {
  2183. ret = vkFlushMappedMemoryRanges(hwctx->act_dev, flush_count, flush_ctx);
  2184. if (ret != VK_SUCCESS) {
  2185. av_log(ctx, AV_LOG_ERROR, "Failed to flush memory: %s\n",
  2186. vk_ret2str(ret));
  2187. err = AVERROR_EXTERNAL; /* We still want to try to unmap them */
  2188. }
  2189. }
  2190. for (int i = 0; i < nb_buffers; i++)
  2191. vkUnmapMemory(hwctx->act_dev, buf[i].mem);
  2192. return err;
  2193. }
  2194. static int transfer_image_buf(AVHWDeviceContext *ctx, AVVkFrame *frame,
  2195. ImageBuffer *buffer, const int *buf_stride, int w,
  2196. int h, enum AVPixelFormat pix_fmt, int to_buf)
  2197. {
  2198. VkResult ret;
  2199. AVVulkanDeviceContext *hwctx = ctx->hwctx;
  2200. VulkanDevicePriv *s = ctx->internal->priv;
  2201. int bar_num = 0;
  2202. VkPipelineStageFlagBits sem_wait_dst[AV_NUM_DATA_POINTERS];
  2203. const int planes = av_pix_fmt_count_planes(pix_fmt);
  2204. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
  2205. VkCommandBufferBeginInfo cmd_start = {
  2206. .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
  2207. .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
  2208. };
  2209. VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
  2210. VkSubmitInfo s_info = {
  2211. .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
  2212. .commandBufferCount = 1,
  2213. .pCommandBuffers = &s->cmd.buf,
  2214. .pSignalSemaphores = frame->sem,
  2215. .pWaitSemaphores = frame->sem,
  2216. .pWaitDstStageMask = sem_wait_dst,
  2217. .signalSemaphoreCount = planes,
  2218. .waitSemaphoreCount = planes,
  2219. };
  2220. ret = vkBeginCommandBuffer(s->cmd.buf, &cmd_start);
  2221. if (ret != VK_SUCCESS) {
  2222. av_log(ctx, AV_LOG_ERROR, "Unable to init command buffer: %s\n",
  2223. vk_ret2str(ret));
  2224. return AVERROR_EXTERNAL;
  2225. }
  2226. /* Change the image layout to something more optimal for transfers */
  2227. for (int i = 0; i < planes; i++) {
  2228. VkImageLayout new_layout = to_buf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL :
  2229. VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2230. VkAccessFlags new_access = to_buf ? VK_ACCESS_TRANSFER_READ_BIT :
  2231. VK_ACCESS_TRANSFER_WRITE_BIT;
  2232. sem_wait_dst[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
  2233. /* If the layout matches and we have read access skip the barrier */
  2234. if ((frame->layout[i] == new_layout) && (frame->access[i] & new_access))
  2235. continue;
  2236. img_bar[bar_num].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2237. img_bar[bar_num].srcAccessMask = 0x0;
  2238. img_bar[bar_num].dstAccessMask = new_access;
  2239. img_bar[bar_num].oldLayout = frame->layout[i];
  2240. img_bar[bar_num].newLayout = new_layout;
  2241. img_bar[bar_num].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2242. img_bar[bar_num].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2243. img_bar[bar_num].image = frame->img[i];
  2244. img_bar[bar_num].subresourceRange.levelCount = 1;
  2245. img_bar[bar_num].subresourceRange.layerCount = 1;
  2246. img_bar[bar_num].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2247. frame->layout[i] = img_bar[bar_num].newLayout;
  2248. frame->access[i] = img_bar[bar_num].dstAccessMask;
  2249. bar_num++;
  2250. }
  2251. if (bar_num)
  2252. vkCmdPipelineBarrier(s->cmd.buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
  2253. VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
  2254. 0, NULL, 0, NULL, bar_num, img_bar);
  2255. /* Schedule a copy for each plane */
  2256. for (int i = 0; i < planes; i++) {
  2257. const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
  2258. const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
  2259. VkBufferImageCopy buf_reg = {
  2260. .bufferOffset = 0,
  2261. /* Buffer stride isn't in bytes, it's in samples, the implementation
  2262. * uses the image's VkFormat to know how many bytes per sample
  2263. * the buffer has. So we have to convert by dividing. Stupid.
  2264. * Won't work with YUVA or other planar formats with alpha. */
  2265. .bufferRowLength = buf_stride[i] / desc->comp[i].step,
  2266. .bufferImageHeight = p_h,
  2267. .imageSubresource.layerCount = 1,
  2268. .imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
  2269. .imageOffset = { 0, 0, 0, },
  2270. .imageExtent = { p_w, p_h, 1, },
  2271. };
  2272. if (to_buf)
  2273. vkCmdCopyImageToBuffer(s->cmd.buf, frame->img[i], frame->layout[i],
  2274. buffer[i].buf, 1, &buf_reg);
  2275. else
  2276. vkCmdCopyBufferToImage(s->cmd.buf, buffer[i].buf, frame->img[i],
  2277. frame->layout[i], 1, &buf_reg);
  2278. }
  2279. ret = vkEndCommandBuffer(s->cmd.buf);
  2280. if (ret != VK_SUCCESS) {
  2281. av_log(ctx, AV_LOG_ERROR, "Unable to finish command buffer: %s\n",
  2282. vk_ret2str(ret));
  2283. return AVERROR_EXTERNAL;
  2284. }
  2285. /* Wait for the download/upload to finish if uploading, otherwise the
  2286. * semaphore will take care of synchronization when uploading */
  2287. ret = vkQueueSubmit(s->cmd.queue, 1, &s_info, s->cmd.fence);
  2288. if (ret != VK_SUCCESS) {
  2289. av_log(ctx, AV_LOG_ERROR, "Unable to submit command buffer: %s\n",
  2290. vk_ret2str(ret));
  2291. return AVERROR_EXTERNAL;
  2292. } else {
  2293. vkWaitForFences(hwctx->act_dev, 1, &s->cmd.fence, VK_TRUE, UINT64_MAX);
  2294. vkResetFences(hwctx->act_dev, 1, &s->cmd.fence);
  2295. }
  2296. return 0;
  2297. }
  2298. /* Technically we can use VK_EXT_external_memory_host to upload and download,
  2299. * however the alignment requirements make this unfeasible as both the pointer
  2300. * and the size of each plane need to be aligned to the minimum alignment
  2301. * requirement, which on all current implementations (anv, radv) is 4096.
  2302. * If the requirement gets relaxed (unlikely) this can easily be implemented. */
  2303. static int vulkan_transfer_data_from_mem(AVHWFramesContext *hwfc, AVFrame *dst,
  2304. const AVFrame *src)
  2305. {
  2306. int err = 0;
  2307. AVFrame tmp;
  2308. AVVkFrame *f = (AVVkFrame *)dst->data[0];
  2309. AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
  2310. ImageBuffer buf[AV_NUM_DATA_POINTERS] = { { 0 } };
  2311. const int planes = av_pix_fmt_count_planes(src->format);
  2312. int log2_chroma = av_pix_fmt_desc_get(src->format)->log2_chroma_h;
  2313. if ((src->format != AV_PIX_FMT_NONE && !av_vkfmt_from_pixfmt(src->format))) {
  2314. av_log(hwfc, AV_LOG_ERROR, "Unsupported source pixel format!\n");
  2315. return AVERROR(EINVAL);
  2316. }
  2317. if (src->width > hwfc->width || src->height > hwfc->height)
  2318. return AVERROR(EINVAL);
  2319. /* For linear, host visiable images */
  2320. if (f->tiling == VK_IMAGE_TILING_LINEAR &&
  2321. f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
  2322. AVFrame *map = av_frame_alloc();
  2323. if (!map)
  2324. return AVERROR(ENOMEM);
  2325. map->format = src->format;
  2326. err = vulkan_map_frame_to_mem(hwfc, map, dst, AV_HWFRAME_MAP_WRITE);
  2327. if (err)
  2328. goto end;
  2329. err = av_frame_copy(map, src);
  2330. av_frame_free(&map);
  2331. goto end;
  2332. }
  2333. /* Create buffers */
  2334. for (int i = 0; i < planes; i++) {
  2335. int h = src->height;
  2336. int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
  2337. tmp.linesize[i] = FFABS(src->linesize[i]);
  2338. err = create_buf(dev_ctx, &buf[i], p_height,
  2339. &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
  2340. VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
  2341. if (err)
  2342. goto end;
  2343. }
  2344. /* Map, copy image to buffer, unmap */
  2345. if ((err = map_buffers(dev_ctx, buf, tmp.data, planes, 0)))
  2346. goto end;
  2347. av_image_copy(tmp.data, tmp.linesize, (const uint8_t **)src->data,
  2348. src->linesize, src->format, src->width, src->height);
  2349. if ((err = unmap_buffers(dev_ctx, buf, planes, 1)))
  2350. goto end;
  2351. /* Copy buffers to image */
  2352. err = transfer_image_buf(dev_ctx, f, buf, tmp.linesize,
  2353. src->width, src->height, src->format, 0);
  2354. end:
  2355. for (int i = 0; i < planes; i++)
  2356. free_buf(dev_ctx, &buf[i]);
  2357. return err;
  2358. }
  2359. static int vulkan_transfer_data_to(AVHWFramesContext *hwfc, AVFrame *dst,
  2360. const AVFrame *src)
  2361. {
  2362. av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
  2363. switch (src->format) {
  2364. #if CONFIG_CUDA
  2365. case AV_PIX_FMT_CUDA:
  2366. if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
  2367. (p->extensions & EXT_EXTERNAL_FD_SEM))
  2368. return vulkan_transfer_data_from_cuda(hwfc, dst, src);
  2369. #endif
  2370. default:
  2371. if (src->hw_frames_ctx)
  2372. return AVERROR(ENOSYS);
  2373. else
  2374. return vulkan_transfer_data_from_mem(hwfc, dst, src);
  2375. }
  2376. }
  2377. #if CONFIG_CUDA
  2378. static int vulkan_transfer_data_to_cuda(AVHWFramesContext *hwfc, AVFrame *dst,
  2379. const AVFrame *src)
  2380. {
  2381. int err;
  2382. VkResult ret;
  2383. CUcontext dummy;
  2384. AVVkFrame *dst_f;
  2385. AVVkFrameInternal *dst_int;
  2386. const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
  2387. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
  2388. AVHWFramesContext *cuda_fc = (AVHWFramesContext*)dst->hw_frames_ctx->data;
  2389. AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
  2390. AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
  2391. AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
  2392. CudaFunctions *cu = cu_internal->cuda_dl;
  2393. ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
  2394. if (ret < 0) {
  2395. err = AVERROR_EXTERNAL;
  2396. goto fail;
  2397. }
  2398. dst_f = (AVVkFrame *)src->data[0];
  2399. err = vulkan_export_to_cuda(hwfc, dst->hw_frames_ctx, src);
  2400. if (err < 0) {
  2401. goto fail;
  2402. }
  2403. dst_int = dst_f->internal;
  2404. for (int i = 0; i < planes; i++) {
  2405. CUDA_MEMCPY2D cpy = {
  2406. .dstMemoryType = CU_MEMORYTYPE_DEVICE,
  2407. .dstDevice = (CUdeviceptr)dst->data[i],
  2408. .dstPitch = dst->linesize[i],
  2409. .dstY = 0,
  2410. .srcMemoryType = CU_MEMORYTYPE_ARRAY,
  2411. .srcArray = dst_int->cu_array[i],
  2412. .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
  2413. : hwfc->width) * desc->comp[i].step,
  2414. .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
  2415. : hwfc->height,
  2416. };
  2417. ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
  2418. if (ret < 0) {
  2419. err = AVERROR_EXTERNAL;
  2420. goto fail;
  2421. }
  2422. }
  2423. CHECK_CU(cu->cuCtxPopCurrent(&dummy));
  2424. av_log(hwfc, AV_LOG_VERBOSE, "Transfered Vulkan image to CUDA!\n");
  2425. return 0;
  2426. fail:
  2427. CHECK_CU(cu->cuCtxPopCurrent(&dummy));
  2428. vulkan_free_internal(dst_int);
  2429. dst_f->internal = NULL;
  2430. av_buffer_unref(&dst->buf[0]);
  2431. return err;
  2432. }
  2433. #endif
  2434. static int vulkan_transfer_data_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
  2435. const AVFrame *src)
  2436. {
  2437. int err = 0;
  2438. AVFrame tmp;
  2439. AVVkFrame *f = (AVVkFrame *)src->data[0];
  2440. AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
  2441. ImageBuffer buf[AV_NUM_DATA_POINTERS] = { { 0 } };
  2442. const int planes = av_pix_fmt_count_planes(dst->format);
  2443. int log2_chroma = av_pix_fmt_desc_get(dst->format)->log2_chroma_h;
  2444. if (dst->width > hwfc->width || dst->height > hwfc->height)
  2445. return AVERROR(EINVAL);
  2446. /* For linear, host visiable images */
  2447. if (f->tiling == VK_IMAGE_TILING_LINEAR &&
  2448. f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
  2449. AVFrame *map = av_frame_alloc();
  2450. if (!map)
  2451. return AVERROR(ENOMEM);
  2452. map->format = dst->format;
  2453. err = vulkan_map_frame_to_mem(hwfc, map, src, AV_HWFRAME_MAP_READ);
  2454. if (err)
  2455. return err;
  2456. err = av_frame_copy(dst, map);
  2457. av_frame_free(&map);
  2458. return err;
  2459. }
  2460. /* Create buffers */
  2461. for (int i = 0; i < planes; i++) {
  2462. int h = dst->height;
  2463. int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
  2464. tmp.linesize[i] = FFABS(dst->linesize[i]);
  2465. err = create_buf(dev_ctx, &buf[i], p_height,
  2466. &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_DST_BIT,
  2467. VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
  2468. }
  2469. /* Copy image to buffer */
  2470. if ((err = transfer_image_buf(dev_ctx, f, buf, tmp.linesize,
  2471. dst->width, dst->height, dst->format, 1)))
  2472. goto end;
  2473. /* Map, copy buffer to frame, unmap */
  2474. if ((err = map_buffers(dev_ctx, buf, tmp.data, planes, 1)))
  2475. goto end;
  2476. av_image_copy(dst->data, dst->linesize, (const uint8_t **)tmp.data,
  2477. tmp.linesize, dst->format, dst->width, dst->height);
  2478. err = unmap_buffers(dev_ctx, buf, planes, 0);
  2479. end:
  2480. for (int i = 0; i < planes; i++)
  2481. free_buf(dev_ctx, &buf[i]);
  2482. return err;
  2483. }
  2484. static int vulkan_transfer_data_from(AVHWFramesContext *hwfc, AVFrame *dst,
  2485. const AVFrame *src)
  2486. {
  2487. av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
  2488. switch (dst->format) {
  2489. #if CONFIG_CUDA
  2490. case AV_PIX_FMT_CUDA:
  2491. if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
  2492. (p->extensions & EXT_EXTERNAL_FD_SEM))
  2493. return vulkan_transfer_data_to_cuda(hwfc, dst, src);
  2494. #endif
  2495. default:
  2496. if (dst->hw_frames_ctx)
  2497. return AVERROR(ENOSYS);
  2498. else
  2499. return vulkan_transfer_data_to_mem(hwfc, dst, src);
  2500. }
  2501. }
  2502. AVVkFrame *av_vk_frame_alloc(void)
  2503. {
  2504. return av_mallocz(sizeof(AVVkFrame));
  2505. }
  2506. const HWContextType ff_hwcontext_type_vulkan = {
  2507. .type = AV_HWDEVICE_TYPE_VULKAN,
  2508. .name = "Vulkan",
  2509. .device_hwctx_size = sizeof(AVVulkanDeviceContext),
  2510. .device_priv_size = sizeof(VulkanDevicePriv),
  2511. .frames_hwctx_size = sizeof(AVVulkanFramesContext),
  2512. .frames_priv_size = sizeof(VulkanFramesPriv),
  2513. .device_init = &vulkan_device_init,
  2514. .device_create = &vulkan_device_create,
  2515. .device_derive = &vulkan_device_derive,
  2516. .frames_get_constraints = &vulkan_frames_get_constraints,
  2517. .frames_init = vulkan_frames_init,
  2518. .frames_get_buffer = vulkan_get_buffer,
  2519. .frames_uninit = vulkan_frames_uninit,
  2520. .transfer_get_formats = vulkan_transfer_get_formats,
  2521. .transfer_data_to = vulkan_transfer_data_to,
  2522. .transfer_data_from = vulkan_transfer_data_from,
  2523. .map_to = vulkan_map_to,
  2524. .map_from = vulkan_map_from,
  2525. .pix_fmts = (const enum AVPixelFormat []) {
  2526. AV_PIX_FMT_VULKAN,
  2527. AV_PIX_FMT_NONE
  2528. },
  2529. };