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.

3387 lines
119KB

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