2 * This file is part of FFmpeg.
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.
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.
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
23 #include "hwcontext.h"
24 #include "hwcontext_internal.h"
25 #include "hwcontext_vulkan.h"
30 #include <drm_fourcc.h>
31 #include "hwcontext_drm.h"
33 #include <va/va_drmcommon.h>
34 #include "hwcontext_vaapi.h"
39 #include "hwcontext_cuda_internal.h"
40 #include "cuda_check.h"
41 #define CHECK_CU(x) FF_CUDA_CHECK_DL(cuda_cu, cu, x)
44 typedef struct VulkanQueueCtx {
49 /* Buffer dependencies */
50 AVBufferRef **buf_deps;
52 int buf_deps_alloc_size;
55 typedef struct VulkanExecCtx {
57 VkCommandBuffer *bufs;
58 VulkanQueueCtx *queues;
63 typedef struct VulkanDevicePriv {
65 VkPhysicalDeviceProperties2 props;
66 VkPhysicalDeviceMemoryProperties mprops;
67 VkPhysicalDeviceExternalMemoryHostPropertiesEXT hprops;
74 VkDebugUtilsMessengerEXT debug_ctx;
80 int use_linear_images;
86 typedef struct VulkanFramesPriv {
87 /* Image conversions */
88 VulkanExecCtx conv_ctx;
91 VulkanExecCtx upload_ctx;
92 VulkanExecCtx download_ctx;
95 typedef struct AVVkFrameInternal {
97 /* Importing external memory into cuda is really expensive so we keep the
98 * memory imported all the time */
99 AVBufferRef *cuda_fc_ref; /* Need to keep it around for uninit */
100 CUexternalMemory ext_mem[AV_NUM_DATA_POINTERS];
101 CUmipmappedArray cu_mma[AV_NUM_DATA_POINTERS];
102 CUarray cu_array[AV_NUM_DATA_POINTERS];
103 CUexternalSemaphore cu_sem[AV_NUM_DATA_POINTERS];
107 #define GET_QUEUE_COUNT(hwctx, graph, comp, tx) ( \
108 graph ? hwctx->nb_graphics_queues : \
109 comp ? (hwctx->nb_comp_queues ? \
110 hwctx->nb_comp_queues : hwctx->nb_graphics_queues) : \
111 tx ? (hwctx->nb_tx_queues ? hwctx->nb_tx_queues : \
112 (hwctx->nb_comp_queues ? \
113 hwctx->nb_comp_queues : hwctx->nb_graphics_queues)) : \
117 #define VK_LOAD_PFN(inst, name) PFN_##name pfn_##name = (PFN_##name) \
118 vkGetInstanceProcAddr(inst, #name)
120 #define DEFAULT_USAGE_FLAGS (VK_IMAGE_USAGE_SAMPLED_BIT | \
121 VK_IMAGE_USAGE_STORAGE_BIT | \
122 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | \
123 VK_IMAGE_USAGE_TRANSFER_DST_BIT)
125 #define ADD_VAL_TO_LIST(list, count, val) \
127 list = av_realloc_array(list, sizeof(*list), ++count); \
129 err = AVERROR(ENOMEM); \
132 list[count - 1] = av_strdup(val); \
133 if (!list[count - 1]) { \
134 err = AVERROR(ENOMEM); \
139 static const struct {
140 enum AVPixelFormat pixfmt;
141 const VkFormat vkfmts[3];
142 } vk_pixfmt_map[] = {
143 { AV_PIX_FMT_GRAY8, { VK_FORMAT_R8_UNORM } },
144 { AV_PIX_FMT_GRAY16, { VK_FORMAT_R16_UNORM } },
145 { AV_PIX_FMT_GRAYF32, { VK_FORMAT_R32_SFLOAT } },
147 { AV_PIX_FMT_NV12, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8G8_UNORM } },
148 { AV_PIX_FMT_P010, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16G16_UNORM } },
149 { AV_PIX_FMT_P016, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16G16_UNORM } },
151 { AV_PIX_FMT_YUV420P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
152 { AV_PIX_FMT_YUV422P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
153 { AV_PIX_FMT_YUV444P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
155 { AV_PIX_FMT_YUV420P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
156 { AV_PIX_FMT_YUV422P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
157 { AV_PIX_FMT_YUV444P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
159 { AV_PIX_FMT_ABGR, { VK_FORMAT_A8B8G8R8_UNORM_PACK32 } },
160 { AV_PIX_FMT_BGRA, { VK_FORMAT_B8G8R8A8_UNORM } },
161 { AV_PIX_FMT_RGBA, { VK_FORMAT_R8G8B8A8_UNORM } },
162 { AV_PIX_FMT_RGB24, { VK_FORMAT_R8G8B8_UNORM } },
163 { AV_PIX_FMT_BGR24, { VK_FORMAT_B8G8R8_UNORM } },
164 { AV_PIX_FMT_RGB48, { VK_FORMAT_R16G16B16_UNORM } },
165 { AV_PIX_FMT_RGBA64, { VK_FORMAT_R16G16B16A16_UNORM } },
166 { AV_PIX_FMT_RGB565, { VK_FORMAT_R5G6B5_UNORM_PACK16 } },
167 { AV_PIX_FMT_BGR565, { VK_FORMAT_B5G6R5_UNORM_PACK16 } },
168 { AV_PIX_FMT_BGR0, { VK_FORMAT_B8G8R8A8_UNORM } },
169 { AV_PIX_FMT_0BGR, { VK_FORMAT_A8B8G8R8_UNORM_PACK32 } },
170 { AV_PIX_FMT_RGB0, { VK_FORMAT_R8G8B8A8_UNORM } },
172 { AV_PIX_FMT_GBRPF32, { VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32_SFLOAT } },
175 const VkFormat *av_vkfmt_from_pixfmt(enum AVPixelFormat p)
177 for (enum AVPixelFormat i = 0; i < FF_ARRAY_ELEMS(vk_pixfmt_map); i++)
178 if (vk_pixfmt_map[i].pixfmt == p)
179 return vk_pixfmt_map[i].vkfmts;
183 static int pixfmt_is_supported(AVVulkanDeviceContext *hwctx, enum AVPixelFormat p,
186 const VkFormat *fmt = av_vkfmt_from_pixfmt(p);
187 int planes = av_pix_fmt_count_planes(p);
192 for (int i = 0; i < planes; i++) {
193 VkFormatFeatureFlags flags;
194 VkFormatProperties2 prop = {
195 .sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2,
197 vkGetPhysicalDeviceFormatProperties2(hwctx->phys_dev, fmt[i], &prop);
198 flags = linear ? prop.formatProperties.linearTilingFeatures :
199 prop.formatProperties.optimalTilingFeatures;
200 if (!(flags & DEFAULT_USAGE_FLAGS))
207 enum VulkanExtensions {
208 EXT_EXTERNAL_DMABUF_MEMORY = 1ULL << 0, /* VK_EXT_external_memory_dma_buf */
209 EXT_DRM_MODIFIER_FLAGS = 1ULL << 1, /* VK_EXT_image_drm_format_modifier */
210 EXT_EXTERNAL_FD_MEMORY = 1ULL << 2, /* VK_KHR_external_memory_fd */
211 EXT_EXTERNAL_FD_SEM = 1ULL << 3, /* VK_KHR_external_semaphore_fd */
212 EXT_EXTERNAL_HOST_MEMORY = 1ULL << 4, /* VK_EXT_external_memory_host */
214 EXT_NO_FLAG = 1ULL << 63,
217 typedef struct VulkanOptExtension {
220 } VulkanOptExtension;
222 static const VulkanOptExtension optional_instance_exts[] = {
226 static const VulkanOptExtension optional_device_exts[] = {
227 { VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME, EXT_EXTERNAL_FD_MEMORY, },
228 { VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME, EXT_EXTERNAL_DMABUF_MEMORY, },
229 { VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME, EXT_DRM_MODIFIER_FLAGS, },
230 { VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME, EXT_EXTERNAL_FD_SEM, },
231 { VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME, EXT_EXTERNAL_HOST_MEMORY, },
234 /* Converts return values to strings */
235 static const char *vk_ret2str(VkResult res)
237 #define CASE(VAL) case VAL: return #VAL
243 CASE(VK_EVENT_RESET);
245 CASE(VK_ERROR_OUT_OF_HOST_MEMORY);
246 CASE(VK_ERROR_OUT_OF_DEVICE_MEMORY);
247 CASE(VK_ERROR_INITIALIZATION_FAILED);
248 CASE(VK_ERROR_DEVICE_LOST);
249 CASE(VK_ERROR_MEMORY_MAP_FAILED);
250 CASE(VK_ERROR_LAYER_NOT_PRESENT);
251 CASE(VK_ERROR_EXTENSION_NOT_PRESENT);
252 CASE(VK_ERROR_FEATURE_NOT_PRESENT);
253 CASE(VK_ERROR_INCOMPATIBLE_DRIVER);
254 CASE(VK_ERROR_TOO_MANY_OBJECTS);
255 CASE(VK_ERROR_FORMAT_NOT_SUPPORTED);
256 CASE(VK_ERROR_FRAGMENTED_POOL);
257 CASE(VK_ERROR_SURFACE_LOST_KHR);
258 CASE(VK_ERROR_NATIVE_WINDOW_IN_USE_KHR);
259 CASE(VK_SUBOPTIMAL_KHR);
260 CASE(VK_ERROR_OUT_OF_DATE_KHR);
261 CASE(VK_ERROR_INCOMPATIBLE_DISPLAY_KHR);
262 CASE(VK_ERROR_VALIDATION_FAILED_EXT);
263 CASE(VK_ERROR_INVALID_SHADER_NV);
264 CASE(VK_ERROR_OUT_OF_POOL_MEMORY);
265 CASE(VK_ERROR_INVALID_EXTERNAL_HANDLE);
266 CASE(VK_ERROR_NOT_PERMITTED_EXT);
267 CASE(VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT);
268 CASE(VK_ERROR_INVALID_DEVICE_ADDRESS_EXT);
269 CASE(VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT);
270 default: return "Unknown error";
275 static VkBool32 vk_dbg_callback(VkDebugUtilsMessageSeverityFlagBitsEXT severity,
276 VkDebugUtilsMessageTypeFlagsEXT messageType,
277 const VkDebugUtilsMessengerCallbackDataEXT *data,
281 AVHWDeviceContext *ctx = priv;
284 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT: l = AV_LOG_VERBOSE; break;
285 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT: l = AV_LOG_INFO; break;
286 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT: l = AV_LOG_WARNING; break;
287 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT: l = AV_LOG_ERROR; break;
288 default: l = AV_LOG_DEBUG; break;
291 av_log(ctx, l, "%s\n", data->pMessage);
292 for (int i = 0; i < data->cmdBufLabelCount; i++)
293 av_log(ctx, l, "\t%i: %s\n", i, data->pCmdBufLabels[i].pLabelName);
298 static int check_extensions(AVHWDeviceContext *ctx, int dev, AVDictionary *opts,
299 const char * const **dst, uint32_t *num, int debug)
302 const char **extension_names = NULL;
303 VulkanDevicePriv *p = ctx->internal->priv;
304 AVVulkanDeviceContext *hwctx = ctx->hwctx;
305 int err = 0, found, extensions_found = 0;
308 int optional_exts_num;
309 uint32_t sup_ext_count;
310 char *user_exts_str = NULL;
311 AVDictionaryEntry *user_exts;
312 VkExtensionProperties *sup_ext;
313 const VulkanOptExtension *optional_exts;
317 optional_exts = optional_instance_exts;
318 optional_exts_num = FF_ARRAY_ELEMS(optional_instance_exts);
319 user_exts = av_dict_get(opts, "instance_extensions", NULL, 0);
321 user_exts_str = av_strdup(user_exts->value);
322 if (!user_exts_str) {
323 err = AVERROR(ENOMEM);
327 vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, NULL);
328 sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
330 return AVERROR(ENOMEM);
331 vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, sup_ext);
334 optional_exts = optional_device_exts;
335 optional_exts_num = FF_ARRAY_ELEMS(optional_device_exts);
336 user_exts = av_dict_get(opts, "device_extensions", NULL, 0);
338 user_exts_str = av_strdup(user_exts->value);
339 if (!user_exts_str) {
340 err = AVERROR(ENOMEM);
344 vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
345 &sup_ext_count, NULL);
346 sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
348 return AVERROR(ENOMEM);
349 vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
350 &sup_ext_count, sup_ext);
353 for (int i = 0; i < optional_exts_num; i++) {
354 tstr = optional_exts[i].name;
356 for (int j = 0; j < sup_ext_count; j++) {
357 if (!strcmp(tstr, sup_ext[j].extensionName)) {
365 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
366 p->extensions |= optional_exts[i].flag;
367 ADD_VAL_TO_LIST(extension_names, extensions_found, tstr);
371 tstr = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
373 for (int j = 0; j < sup_ext_count; j++) {
374 if (!strcmp(tstr, sup_ext[j].extensionName)) {
380 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
381 ADD_VAL_TO_LIST(extension_names, extensions_found, tstr);
383 av_log(ctx, AV_LOG_ERROR, "Debug extension \"%s\" not found!\n",
385 err = AVERROR(EINVAL);
391 char *save, *token = av_strtok(user_exts_str, "+", &save);
394 for (int j = 0; j < sup_ext_count; j++) {
395 if (!strcmp(token, sup_ext[j].extensionName)) {
401 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, token);
402 ADD_VAL_TO_LIST(extension_names, extensions_found, token);
404 av_log(ctx, AV_LOG_WARNING, "%s extension \"%s\" not found, excluding.\n",
407 token = av_strtok(NULL, "+", &save);
411 *dst = extension_names;
412 *num = extensions_found;
414 av_free(user_exts_str);
420 for (int i = 0; i < extensions_found; i++)
421 av_free((void *)extension_names[i]);
422 av_free(extension_names);
423 av_free(user_exts_str);
428 /* Creates a VkInstance */
429 static int create_instance(AVHWDeviceContext *ctx, AVDictionary *opts)
433 VulkanDevicePriv *p = ctx->internal->priv;
434 AVVulkanDeviceContext *hwctx = ctx->hwctx;
435 AVDictionaryEntry *debug_opt = av_dict_get(opts, "debug", NULL, 0);
436 const int debug_mode = debug_opt && strtol(debug_opt->value, NULL, 10);
437 VkApplicationInfo application_info = {
438 .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
439 .pEngineName = "libavutil",
440 .apiVersion = VK_API_VERSION_1_1,
441 .engineVersion = VK_MAKE_VERSION(LIBAVUTIL_VERSION_MAJOR,
442 LIBAVUTIL_VERSION_MINOR,
443 LIBAVUTIL_VERSION_MICRO),
445 VkInstanceCreateInfo inst_props = {
446 .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
447 .pApplicationInfo = &application_info,
450 /* Check for present/missing extensions */
451 err = check_extensions(ctx, 0, opts, &inst_props.ppEnabledExtensionNames,
452 &inst_props.enabledExtensionCount, debug_mode);
457 static const char *layers[] = { "VK_LAYER_KHRONOS_validation" };
458 inst_props.ppEnabledLayerNames = layers;
459 inst_props.enabledLayerCount = FF_ARRAY_ELEMS(layers);
462 /* Try to create the instance */
463 ret = vkCreateInstance(&inst_props, hwctx->alloc, &hwctx->inst);
465 /* Check for errors */
466 if (ret != VK_SUCCESS) {
467 av_log(ctx, AV_LOG_ERROR, "Instance creation failure: %s\n",
469 for (int i = 0; i < inst_props.enabledExtensionCount; i++)
470 av_free((void *)inst_props.ppEnabledExtensionNames[i]);
471 av_free((void *)inst_props.ppEnabledExtensionNames);
472 return AVERROR_EXTERNAL;
476 VkDebugUtilsMessengerCreateInfoEXT dbg = {
477 .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT,
478 .messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT |
479 VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT |
480 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
481 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT,
482 .messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
483 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
484 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT,
485 .pfnUserCallback = vk_dbg_callback,
488 VK_LOAD_PFN(hwctx->inst, vkCreateDebugUtilsMessengerEXT);
490 pfn_vkCreateDebugUtilsMessengerEXT(hwctx->inst, &dbg,
491 hwctx->alloc, &p->debug_ctx);
494 hwctx->enabled_inst_extensions = inst_props.ppEnabledExtensionNames;
495 hwctx->nb_enabled_inst_extensions = inst_props.enabledExtensionCount;
500 typedef struct VulkanDeviceSelection {
501 uint8_t uuid[VK_UUID_SIZE]; /* Will use this first unless !has_uuid */
503 const char *name; /* Will use this second unless NULL */
504 uint32_t pci_device; /* Will use this third unless 0x0 */
505 uint32_t vendor_id; /* Last resort to find something deterministic */
506 int index; /* Finally fall back to index */
507 } VulkanDeviceSelection;
509 static const char *vk_dev_type(enum VkPhysicalDeviceType type)
512 case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: return "integrated";
513 case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: return "discrete";
514 case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: return "virtual";
515 case VK_PHYSICAL_DEVICE_TYPE_CPU: return "software";
516 default: return "unknown";
521 static int find_device(AVHWDeviceContext *ctx, VulkanDeviceSelection *select)
523 int err = 0, choice = -1;
526 VkPhysicalDevice *devices = NULL;
527 VkPhysicalDeviceIDProperties *idp = NULL;
528 VkPhysicalDeviceProperties2 *prop = NULL;
529 AVVulkanDeviceContext *hwctx = ctx->hwctx;
531 ret = vkEnumeratePhysicalDevices(hwctx->inst, &num, NULL);
532 if (ret != VK_SUCCESS || !num) {
533 av_log(ctx, AV_LOG_ERROR, "No devices found: %s!\n", vk_ret2str(ret));
534 return AVERROR(ENODEV);
537 devices = av_malloc_array(num, sizeof(VkPhysicalDevice));
539 return AVERROR(ENOMEM);
541 ret = vkEnumeratePhysicalDevices(hwctx->inst, &num, devices);
542 if (ret != VK_SUCCESS) {
543 av_log(ctx, AV_LOG_ERROR, "Failed enumerating devices: %s\n",
545 err = AVERROR(ENODEV);
549 prop = av_mallocz_array(num, sizeof(*prop));
551 err = AVERROR(ENOMEM);
555 idp = av_mallocz_array(num, sizeof(*idp));
557 err = AVERROR(ENOMEM);
561 av_log(ctx, AV_LOG_VERBOSE, "GPU listing:\n");
562 for (int i = 0; i < num; i++) {
563 idp[i].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES;
564 prop[i].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
565 prop[i].pNext = &idp[i];
567 vkGetPhysicalDeviceProperties2(devices[i], &prop[i]);
568 av_log(ctx, AV_LOG_VERBOSE, " %d: %s (%s) (0x%x)\n", i,
569 prop[i].properties.deviceName,
570 vk_dev_type(prop[i].properties.deviceType),
571 prop[i].properties.deviceID);
574 if (select->has_uuid) {
575 for (int i = 0; i < num; i++) {
576 if (!strncmp(idp[i].deviceUUID, select->uuid, VK_UUID_SIZE)) {
581 av_log(ctx, AV_LOG_ERROR, "Unable to find device by given UUID!\n");
582 err = AVERROR(ENODEV);
584 } else if (select->name) {
585 av_log(ctx, AV_LOG_VERBOSE, "Requested device: %s\n", select->name);
586 for (int i = 0; i < num; i++) {
587 if (strstr(prop[i].properties.deviceName, select->name)) {
592 av_log(ctx, AV_LOG_ERROR, "Unable to find device \"%s\"!\n",
594 err = AVERROR(ENODEV);
596 } else if (select->pci_device) {
597 av_log(ctx, AV_LOG_VERBOSE, "Requested device: 0x%x\n", select->pci_device);
598 for (int i = 0; i < num; i++) {
599 if (select->pci_device == prop[i].properties.deviceID) {
604 av_log(ctx, AV_LOG_ERROR, "Unable to find device with PCI ID 0x%x!\n",
606 err = AVERROR(EINVAL);
608 } else if (select->vendor_id) {
609 av_log(ctx, AV_LOG_VERBOSE, "Requested vendor: 0x%x\n", select->vendor_id);
610 for (int i = 0; i < num; i++) {
611 if (select->vendor_id == prop[i].properties.vendorID) {
616 av_log(ctx, AV_LOG_ERROR, "Unable to find device with Vendor ID 0x%x!\n",
618 err = AVERROR(ENODEV);
621 if (select->index < num) {
622 choice = select->index;
625 av_log(ctx, AV_LOG_ERROR, "Unable to find device with index %i!\n",
627 err = AVERROR(ENODEV);
633 hwctx->phys_dev = devices[choice];
642 static int search_queue_families(AVHWDeviceContext *ctx, VkDeviceCreateInfo *cd)
646 VkQueueFamilyProperties *qs = NULL;
647 AVVulkanDeviceContext *hwctx = ctx->hwctx;
648 int graph_index = -1, comp_index = -1, tx_index = -1;
649 VkDeviceQueueCreateInfo *pc = (VkDeviceQueueCreateInfo *)cd->pQueueCreateInfos;
651 /* First get the number of queue families */
652 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, NULL);
654 av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
655 return AVERROR_EXTERNAL;
658 /* Then allocate memory */
659 qs = av_malloc_array(num, sizeof(VkQueueFamilyProperties));
661 return AVERROR(ENOMEM);
663 /* Finally retrieve the queue families */
664 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, qs);
666 #define SEARCH_FLAGS(expr, out) \
667 for (int i = 0; i < num; i++) { \
668 const VkQueueFlagBits flags = qs[i].queueFlags; \
675 SEARCH_FLAGS(flags & VK_QUEUE_GRAPHICS_BIT, graph_index)
677 SEARCH_FLAGS((flags & VK_QUEUE_COMPUTE_BIT) && (i != graph_index),
680 SEARCH_FLAGS((flags & VK_QUEUE_TRANSFER_BIT) && (i != graph_index) &&
681 (i != comp_index), tx_index)
684 #define ADD_QUEUE(fidx, graph, comp, tx) \
685 av_log(ctx, AV_LOG_VERBOSE, "Using queue family %i (total queues: %i) for %s%s%s\n", \
686 fidx, qs[fidx].queueCount, graph ? "graphics " : "", \
687 comp ? "compute " : "", tx ? "transfers " : ""); \
688 av_log(ctx, AV_LOG_VERBOSE, " QF %i flags: %s%s%s%s\n", fidx, \
689 ((qs[fidx].queueFlags) & VK_QUEUE_GRAPHICS_BIT) ? "(graphics) " : "", \
690 ((qs[fidx].queueFlags) & VK_QUEUE_COMPUTE_BIT) ? "(compute) " : "", \
691 ((qs[fidx].queueFlags) & VK_QUEUE_TRANSFER_BIT) ? "(transfers) " : "", \
692 ((qs[fidx].queueFlags) & VK_QUEUE_SPARSE_BINDING_BIT) ? "(sparse) " : ""); \
693 pc[cd->queueCreateInfoCount].queueFamilyIndex = fidx; \
694 pc[cd->queueCreateInfoCount].queueCount = qs[fidx].queueCount; \
695 weights = av_malloc(qs[fidx].queueCount * sizeof(float)); \
696 pc[cd->queueCreateInfoCount].pQueuePriorities = weights; \
699 for (int i = 0; i < qs[fidx].queueCount; i++) \
701 cd->queueCreateInfoCount++;
703 ADD_QUEUE(graph_index, 1, comp_index < 0, tx_index < 0 && comp_index < 0)
704 hwctx->queue_family_index = graph_index;
705 hwctx->queue_family_comp_index = graph_index;
706 hwctx->queue_family_tx_index = graph_index;
707 hwctx->nb_graphics_queues = qs[graph_index].queueCount;
709 if (comp_index != -1) {
710 ADD_QUEUE(comp_index, 0, 1, tx_index < 0)
711 hwctx->queue_family_tx_index = comp_index;
712 hwctx->queue_family_comp_index = comp_index;
713 hwctx->nb_comp_queues = qs[comp_index].queueCount;
716 if (tx_index != -1) {
717 ADD_QUEUE(tx_index, 0, 0, 1)
718 hwctx->queue_family_tx_index = tx_index;
719 hwctx->nb_tx_queues = qs[tx_index].queueCount;
728 av_freep(&pc[0].pQueuePriorities);
729 av_freep(&pc[1].pQueuePriorities);
730 av_freep(&pc[2].pQueuePriorities);
733 return AVERROR(ENOMEM);
736 static int create_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd,
737 int queue_family_index, int num_queues)
740 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
742 VkCommandPoolCreateInfo cqueue_create = {
743 .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
744 .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
745 .queueFamilyIndex = queue_family_index,
747 VkCommandBufferAllocateInfo cbuf_create = {
748 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
749 .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
750 .commandBufferCount = num_queues,
753 cmd->nb_queues = num_queues;
755 /* Create command pool */
756 ret = vkCreateCommandPool(hwctx->act_dev, &cqueue_create,
757 hwctx->alloc, &cmd->pool);
758 if (ret != VK_SUCCESS) {
759 av_log(hwfc, AV_LOG_ERROR, "Command pool creation failure: %s\n",
761 return AVERROR_EXTERNAL;
764 cmd->bufs = av_mallocz(num_queues * sizeof(*cmd->bufs));
766 return AVERROR(ENOMEM);
768 cbuf_create.commandPool = cmd->pool;
770 /* Allocate command buffer */
771 ret = vkAllocateCommandBuffers(hwctx->act_dev, &cbuf_create, cmd->bufs);
772 if (ret != VK_SUCCESS) {
773 av_log(hwfc, AV_LOG_ERROR, "Command buffer alloc failure: %s\n",
775 av_freep(&cmd->bufs);
776 return AVERROR_EXTERNAL;
779 cmd->queues = av_mallocz(num_queues * sizeof(*cmd->queues));
781 return AVERROR(ENOMEM);
783 for (int i = 0; i < num_queues; i++) {
784 VulkanQueueCtx *q = &cmd->queues[i];
785 vkGetDeviceQueue(hwctx->act_dev, queue_family_index, i, &q->queue);
786 q->was_synchronous = 1;
792 static void free_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd)
794 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
797 for (int i = 0; i < cmd->nb_queues; i++) {
798 VulkanQueueCtx *q = &cmd->queues[i];
800 /* Make sure all queues have finished executing */
801 if (q->fence && !q->was_synchronous) {
802 vkWaitForFences(hwctx->act_dev, 1, &q->fence, VK_TRUE, UINT64_MAX);
803 vkResetFences(hwctx->act_dev, 1, &q->fence);
808 vkDestroyFence(hwctx->act_dev, q->fence, hwctx->alloc);
810 /* Free buffer dependencies */
811 for (int j = 0; j < q->nb_buf_deps; j++)
812 av_buffer_unref(&q->buf_deps[j]);
813 av_free(q->buf_deps);
818 vkFreeCommandBuffers(hwctx->act_dev, cmd->pool, cmd->nb_queues, cmd->bufs);
820 vkDestroyCommandPool(hwctx->act_dev, cmd->pool, hwctx->alloc);
822 av_freep(&cmd->queues);
823 av_freep(&cmd->bufs);
827 static VkCommandBuffer get_buf_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd)
829 return cmd->bufs[cmd->cur_queue_idx];
832 static void unref_exec_ctx_deps(AVHWFramesContext *hwfc, VulkanExecCtx *cmd)
834 VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
836 for (int j = 0; j < q->nb_buf_deps; j++)
837 av_buffer_unref(&q->buf_deps[j]);
841 static int wait_start_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd)
844 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
845 VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
847 VkCommandBufferBeginInfo cmd_start = {
848 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
849 .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
852 /* Create the fence and don't wait for it initially */
854 VkFenceCreateInfo fence_spawn = {
855 .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
857 ret = vkCreateFence(hwctx->act_dev, &fence_spawn, hwctx->alloc,
859 if (ret != VK_SUCCESS) {
860 av_log(hwfc, AV_LOG_ERROR, "Failed to queue frame fence: %s\n",
862 return AVERROR_EXTERNAL;
864 } else if (!q->was_synchronous) {
865 vkWaitForFences(hwctx->act_dev, 1, &q->fence, VK_TRUE, UINT64_MAX);
866 vkResetFences(hwctx->act_dev, 1, &q->fence);
869 /* Discard queue dependencies */
870 unref_exec_ctx_deps(hwfc, cmd);
872 ret = vkBeginCommandBuffer(cmd->bufs[cmd->cur_queue_idx], &cmd_start);
873 if (ret != VK_SUCCESS) {
874 av_log(hwfc, AV_LOG_ERROR, "Unable to init command buffer: %s\n",
876 return AVERROR_EXTERNAL;
882 static int add_buf_dep_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd,
883 AVBufferRef * const *deps, int nb_deps)
886 VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
888 if (!deps || !nb_deps)
891 dst = av_fast_realloc(q->buf_deps, &q->buf_deps_alloc_size,
892 (q->nb_buf_deps + nb_deps) * sizeof(*dst));
898 for (int i = 0; i < nb_deps; i++) {
899 q->buf_deps[q->nb_buf_deps] = av_buffer_ref(deps[i]);
900 if (!q->buf_deps[q->nb_buf_deps])
908 unref_exec_ctx_deps(hwfc, cmd);
909 return AVERROR(ENOMEM);
912 static int submit_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd,
913 VkSubmitInfo *s_info, int synchronous)
916 VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
918 ret = vkEndCommandBuffer(cmd->bufs[cmd->cur_queue_idx]);
919 if (ret != VK_SUCCESS) {
920 av_log(hwfc, AV_LOG_ERROR, "Unable to finish command buffer: %s\n",
922 unref_exec_ctx_deps(hwfc, cmd);
923 return AVERROR_EXTERNAL;
926 s_info->pCommandBuffers = &cmd->bufs[cmd->cur_queue_idx];
927 s_info->commandBufferCount = 1;
929 ret = vkQueueSubmit(q->queue, 1, s_info, q->fence);
930 if (ret != VK_SUCCESS) {
931 unref_exec_ctx_deps(hwfc, cmd);
932 return AVERROR_EXTERNAL;
935 q->was_synchronous = synchronous;
938 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
939 vkWaitForFences(hwctx->act_dev, 1, &q->fence, VK_TRUE, UINT64_MAX);
940 vkResetFences(hwctx->act_dev, 1, &q->fence);
941 unref_exec_ctx_deps(hwfc, cmd);
942 } else { /* Rotate queues */
943 cmd->cur_queue_idx = (cmd->cur_queue_idx + 1) % cmd->nb_queues;
949 static void vulkan_device_free(AVHWDeviceContext *ctx)
951 VulkanDevicePriv *p = ctx->internal->priv;
952 AVVulkanDeviceContext *hwctx = ctx->hwctx;
954 vkDestroyDevice(hwctx->act_dev, hwctx->alloc);
957 VK_LOAD_PFN(hwctx->inst, vkDestroyDebugUtilsMessengerEXT);
958 pfn_vkDestroyDebugUtilsMessengerEXT(hwctx->inst, p->debug_ctx,
962 vkDestroyInstance(hwctx->inst, hwctx->alloc);
964 for (int i = 0; i < hwctx->nb_enabled_inst_extensions; i++)
965 av_free((void *)hwctx->enabled_inst_extensions[i]);
966 av_free((void *)hwctx->enabled_inst_extensions);
968 for (int i = 0; i < hwctx->nb_enabled_dev_extensions; i++)
969 av_free((void *)hwctx->enabled_dev_extensions[i]);
970 av_free((void *)hwctx->enabled_dev_extensions);
973 static int vulkan_device_create_internal(AVHWDeviceContext *ctx,
974 VulkanDeviceSelection *dev_select,
975 AVDictionary *opts, int flags)
979 AVDictionaryEntry *opt_d;
980 VulkanDevicePriv *p = ctx->internal->priv;
981 AVVulkanDeviceContext *hwctx = ctx->hwctx;
982 VkPhysicalDeviceFeatures dev_features = { 0 };
983 VkDeviceQueueCreateInfo queue_create_info[3] = {
984 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, },
985 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, },
986 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, },
989 VkDeviceCreateInfo dev_info = {
990 .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
991 .pNext = &hwctx->device_features,
992 .pQueueCreateInfos = queue_create_info,
993 .queueCreateInfoCount = 0,
996 hwctx->device_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
997 ctx->free = vulkan_device_free;
999 /* Create an instance if not given one */
1000 if ((err = create_instance(ctx, opts)))
1003 /* Find a device (if not given one) */
1004 if ((err = find_device(ctx, dev_select)))
1007 vkGetPhysicalDeviceFeatures(hwctx->phys_dev, &dev_features);
1008 #define COPY_FEATURE(DST, NAME) (DST).features.NAME = dev_features.NAME;
1009 COPY_FEATURE(hwctx->device_features, shaderImageGatherExtended)
1010 COPY_FEATURE(hwctx->device_features, fragmentStoresAndAtomics)
1011 COPY_FEATURE(hwctx->device_features, vertexPipelineStoresAndAtomics)
1012 COPY_FEATURE(hwctx->device_features, shaderInt64)
1015 /* Search queue family */
1016 if ((err = search_queue_families(ctx, &dev_info)))
1019 if ((err = check_extensions(ctx, 1, opts, &dev_info.ppEnabledExtensionNames,
1020 &dev_info.enabledExtensionCount, 0))) {
1021 av_free((void *)queue_create_info[0].pQueuePriorities);
1022 av_free((void *)queue_create_info[1].pQueuePriorities);
1023 av_free((void *)queue_create_info[2].pQueuePriorities);
1027 ret = vkCreateDevice(hwctx->phys_dev, &dev_info, hwctx->alloc,
1030 av_free((void *)queue_create_info[0].pQueuePriorities);
1031 av_free((void *)queue_create_info[1].pQueuePriorities);
1032 av_free((void *)queue_create_info[2].pQueuePriorities);
1034 if (ret != VK_SUCCESS) {
1035 av_log(ctx, AV_LOG_ERROR, "Device creation failure: %s\n",
1037 for (int i = 0; i < dev_info.enabledExtensionCount; i++)
1038 av_free((void *)dev_info.ppEnabledExtensionNames[i]);
1039 av_free((void *)dev_info.ppEnabledExtensionNames);
1040 err = AVERROR_EXTERNAL;
1044 /* Tiled images setting, use them by default */
1045 opt_d = av_dict_get(opts, "linear_images", NULL, 0);
1047 p->use_linear_images = strtol(opt_d->value, NULL, 10);
1049 hwctx->enabled_dev_extensions = dev_info.ppEnabledExtensionNames;
1050 hwctx->nb_enabled_dev_extensions = dev_info.enabledExtensionCount;
1056 static int vulkan_device_init(AVHWDeviceContext *ctx)
1059 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1060 VulkanDevicePriv *p = ctx->internal->priv;
1062 /* Set device extension flags */
1063 for (int i = 0; i < hwctx->nb_enabled_dev_extensions; i++) {
1064 for (int j = 0; j < FF_ARRAY_ELEMS(optional_device_exts); j++) {
1065 if (!strcmp(hwctx->enabled_dev_extensions[i],
1066 optional_device_exts[j].name)) {
1067 av_log(ctx, AV_LOG_VERBOSE, "Using device extension %s\n",
1068 hwctx->enabled_dev_extensions[i]);
1069 p->extensions |= optional_device_exts[j].flag;
1075 p->props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
1076 p->props.pNext = &p->hprops;
1077 p->hprops.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT;
1079 vkGetPhysicalDeviceProperties2(hwctx->phys_dev, &p->props);
1080 av_log(ctx, AV_LOG_VERBOSE, "Using device: %s\n",
1081 p->props.properties.deviceName);
1082 av_log(ctx, AV_LOG_VERBOSE, "Alignments:\n");
1083 av_log(ctx, AV_LOG_VERBOSE, " optimalBufferCopyRowPitchAlignment: %li\n",
1084 p->props.properties.limits.optimalBufferCopyRowPitchAlignment);
1085 av_log(ctx, AV_LOG_VERBOSE, " minMemoryMapAlignment: %li\n",
1086 p->props.properties.limits.minMemoryMapAlignment);
1087 if (p->extensions & EXT_EXTERNAL_HOST_MEMORY)
1088 av_log(ctx, AV_LOG_VERBOSE, " minImportedHostPointerAlignment: %li\n",
1089 p->hprops.minImportedHostPointerAlignment);
1091 p->dev_is_nvidia = (p->props.properties.vendorID == 0x10de);
1093 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &queue_num, NULL);
1095 av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
1096 return AVERROR_EXTERNAL;
1099 #define CHECK_QUEUE(type, n) \
1100 if (n >= queue_num) { \
1101 av_log(ctx, AV_LOG_ERROR, "Invalid %s queue index %i (device has %i queues)!\n", \
1102 type, n, queue_num); \
1103 return AVERROR(EINVAL); \
1106 CHECK_QUEUE("graphics", hwctx->queue_family_index)
1107 CHECK_QUEUE("upload", hwctx->queue_family_tx_index)
1108 CHECK_QUEUE("compute", hwctx->queue_family_comp_index)
1112 p->qfs[p->num_qfs++] = hwctx->queue_family_index;
1113 if ((hwctx->queue_family_tx_index != hwctx->queue_family_index) &&
1114 (hwctx->queue_family_tx_index != hwctx->queue_family_comp_index))
1115 p->qfs[p->num_qfs++] = hwctx->queue_family_tx_index;
1116 if ((hwctx->queue_family_comp_index != hwctx->queue_family_index) &&
1117 (hwctx->queue_family_comp_index != hwctx->queue_family_tx_index))
1118 p->qfs[p->num_qfs++] = hwctx->queue_family_comp_index;
1120 /* Get device capabilities */
1121 vkGetPhysicalDeviceMemoryProperties(hwctx->phys_dev, &p->mprops);
1126 static int vulkan_device_create(AVHWDeviceContext *ctx, const char *device,
1127 AVDictionary *opts, int flags)
1129 VulkanDeviceSelection dev_select = { 0 };
1130 if (device && device[0]) {
1132 dev_select.index = strtol(device, &end, 10);
1133 if (end == device) {
1134 dev_select.index = 0;
1135 dev_select.name = device;
1139 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1142 static int vulkan_device_derive(AVHWDeviceContext *ctx,
1143 AVHWDeviceContext *src_ctx,
1144 AVDictionary *opts, int flags)
1146 av_unused VulkanDeviceSelection dev_select = { 0 };
1148 /* If there's only one device on the system, then even if its not covered
1149 * by the following checks (e.g. non-PCIe ARM GPU), having an empty
1150 * dev_select will mean it'll get picked. */
1151 switch(src_ctx->type) {
1154 case AV_HWDEVICE_TYPE_VAAPI: {
1155 AVVAAPIDeviceContext *src_hwctx = src_ctx->hwctx;
1157 const char *vendor = vaQueryVendorString(src_hwctx->display);
1159 av_log(ctx, AV_LOG_ERROR, "Unable to get device info from VAAPI!\n");
1160 return AVERROR_EXTERNAL;
1163 if (strstr(vendor, "Intel"))
1164 dev_select.vendor_id = 0x8086;
1165 if (strstr(vendor, "AMD"))
1166 dev_select.vendor_id = 0x1002;
1168 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1171 case AV_HWDEVICE_TYPE_DRM: {
1172 AVDRMDeviceContext *src_hwctx = src_ctx->hwctx;
1174 drmDevice *drm_dev_info;
1175 int err = drmGetDevice(src_hwctx->fd, &drm_dev_info);
1177 av_log(ctx, AV_LOG_ERROR, "Unable to get device info from DRM fd!\n");
1178 return AVERROR_EXTERNAL;
1181 if (drm_dev_info->bustype == DRM_BUS_PCI)
1182 dev_select.pci_device = drm_dev_info->deviceinfo.pci->device_id;
1184 drmFreeDevice(&drm_dev_info);
1186 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1190 case AV_HWDEVICE_TYPE_CUDA: {
1191 AVHWDeviceContext *cuda_cu = src_ctx;
1192 AVCUDADeviceContext *src_hwctx = src_ctx->hwctx;
1193 AVCUDADeviceContextInternal *cu_internal = src_hwctx->internal;
1194 CudaFunctions *cu = cu_internal->cuda_dl;
1196 int ret = CHECK_CU(cu->cuDeviceGetUuid((CUuuid *)&dev_select.uuid,
1197 cu_internal->cuda_device));
1199 av_log(ctx, AV_LOG_ERROR, "Unable to get UUID from CUDA!\n");
1200 return AVERROR_EXTERNAL;
1203 dev_select.has_uuid = 1;
1205 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1209 return AVERROR(ENOSYS);
1213 static int vulkan_frames_get_constraints(AVHWDeviceContext *ctx,
1214 const void *hwconfig,
1215 AVHWFramesConstraints *constraints)
1218 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1219 VulkanDevicePriv *p = ctx->internal->priv;
1221 for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
1222 count += pixfmt_is_supported(hwctx, i, p->use_linear_images);
1225 if (p->dev_is_nvidia)
1229 constraints->valid_sw_formats = av_malloc_array(count + 1,
1230 sizeof(enum AVPixelFormat));
1231 if (!constraints->valid_sw_formats)
1232 return AVERROR(ENOMEM);
1235 for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
1236 if (pixfmt_is_supported(hwctx, i, p->use_linear_images))
1237 constraints->valid_sw_formats[count++] = i;
1240 if (p->dev_is_nvidia)
1241 constraints->valid_sw_formats[count++] = AV_PIX_FMT_CUDA;
1243 constraints->valid_sw_formats[count++] = AV_PIX_FMT_NONE;
1245 constraints->min_width = 0;
1246 constraints->min_height = 0;
1247 constraints->max_width = p->props.properties.limits.maxImageDimension2D;
1248 constraints->max_height = p->props.properties.limits.maxImageDimension2D;
1250 constraints->valid_hw_formats = av_malloc_array(2, sizeof(enum AVPixelFormat));
1251 if (!constraints->valid_hw_formats)
1252 return AVERROR(ENOMEM);
1254 constraints->valid_hw_formats[0] = AV_PIX_FMT_VULKAN;
1255 constraints->valid_hw_formats[1] = AV_PIX_FMT_NONE;
1260 static int alloc_mem(AVHWDeviceContext *ctx, VkMemoryRequirements *req,
1261 VkMemoryPropertyFlagBits req_flags, const void *alloc_extension,
1262 VkMemoryPropertyFlagBits *mem_flags, VkDeviceMemory *mem)
1266 VulkanDevicePriv *p = ctx->internal->priv;
1267 AVVulkanDeviceContext *dev_hwctx = ctx->hwctx;
1268 VkMemoryAllocateInfo alloc_info = {
1269 .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
1270 .pNext = alloc_extension,
1271 .allocationSize = req->size,
1274 /* The vulkan spec requires memory types to be sorted in the "optimal"
1275 * order, so the first matching type we find will be the best/fastest one */
1276 for (int i = 0; i < p->mprops.memoryTypeCount; i++) {
1277 const VkMemoryType *type = &p->mprops.memoryTypes[i];
1279 /* The memory type must be supported by the requirements (bitfield) */
1280 if (!(req->memoryTypeBits & (1 << i)))
1283 /* The memory type flags must include our properties */
1284 if ((type->propertyFlags & req_flags) != req_flags)
1287 /* The memory type must be large enough */
1288 if (req->size > p->mprops.memoryHeaps[type->heapIndex].size)
1291 /* Found a suitable memory type */
1297 av_log(ctx, AV_LOG_ERROR, "No memory type found for flags 0x%x\n",
1299 return AVERROR(EINVAL);
1302 alloc_info.memoryTypeIndex = index;
1304 ret = vkAllocateMemory(dev_hwctx->act_dev, &alloc_info,
1305 dev_hwctx->alloc, mem);
1306 if (ret != VK_SUCCESS) {
1307 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory: %s\n",
1309 return AVERROR(ENOMEM);
1312 *mem_flags |= p->mprops.memoryTypes[index].propertyFlags;
1317 static void vulkan_free_internal(AVVkFrameInternal *internal)
1323 if (internal->cuda_fc_ref) {
1324 AVHWFramesContext *cuda_fc = (AVHWFramesContext *)internal->cuda_fc_ref->data;
1325 int planes = av_pix_fmt_count_planes(cuda_fc->sw_format);
1326 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
1327 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
1328 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
1329 CudaFunctions *cu = cu_internal->cuda_dl;
1331 for (int i = 0; i < planes; i++) {
1332 if (internal->cu_sem[i])
1333 CHECK_CU(cu->cuDestroyExternalSemaphore(internal->cu_sem[i]));
1334 if (internal->cu_mma[i])
1335 CHECK_CU(cu->cuMipmappedArrayDestroy(internal->cu_mma[i]));
1336 if (internal->ext_mem[i])
1337 CHECK_CU(cu->cuDestroyExternalMemory(internal->ext_mem[i]));
1340 av_buffer_unref(&internal->cuda_fc_ref);
1347 static void vulkan_frame_free(void *opaque, uint8_t *data)
1349 AVVkFrame *f = (AVVkFrame *)data;
1350 AVHWFramesContext *hwfc = opaque;
1351 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1352 int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1354 vulkan_free_internal(f->internal);
1356 for (int i = 0; i < planes; i++) {
1357 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
1358 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
1359 vkDestroySemaphore(hwctx->act_dev, f->sem[i], hwctx->alloc);
1365 static int alloc_bind_mem(AVHWFramesContext *hwfc, AVVkFrame *f,
1366 void *alloc_pnext, size_t alloc_pnext_stride)
1370 AVHWDeviceContext *ctx = hwfc->device_ctx;
1371 VulkanDevicePriv *p = ctx->internal->priv;
1372 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1373 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { { 0 } };
1375 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1377 for (int i = 0; i < planes; i++) {
1379 VkImageMemoryRequirementsInfo2 req_desc = {
1380 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
1383 VkMemoryDedicatedAllocateInfo ded_alloc = {
1384 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
1385 .pNext = (void *)(((uint8_t *)alloc_pnext) + i*alloc_pnext_stride),
1387 VkMemoryDedicatedRequirements ded_req = {
1388 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
1390 VkMemoryRequirements2 req = {
1391 .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
1395 vkGetImageMemoryRequirements2(hwctx->act_dev, &req_desc, &req);
1397 if (f->tiling == VK_IMAGE_TILING_LINEAR)
1398 req.memoryRequirements.size = FFALIGN(req.memoryRequirements.size,
1399 p->props.properties.limits.minMemoryMapAlignment);
1401 /* In case the implementation prefers/requires dedicated allocation */
1402 use_ded_mem = ded_req.prefersDedicatedAllocation |
1403 ded_req.requiresDedicatedAllocation;
1405 ded_alloc.image = f->img[i];
1407 /* Allocate memory */
1408 if ((err = alloc_mem(ctx, &req.memoryRequirements,
1409 f->tiling == VK_IMAGE_TILING_LINEAR ?
1410 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT :
1411 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1412 use_ded_mem ? &ded_alloc : (void *)ded_alloc.pNext,
1413 &f->flags, &f->mem[i])))
1416 f->size[i] = req.memoryRequirements.size;
1417 bind_info[i].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
1418 bind_info[i].image = f->img[i];
1419 bind_info[i].memory = f->mem[i];
1422 /* Bind the allocated memory to the images */
1423 ret = vkBindImageMemory2(hwctx->act_dev, planes, bind_info);
1424 if (ret != VK_SUCCESS) {
1425 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
1427 return AVERROR_EXTERNAL;
1435 PREP_MODE_RO_SHADER,
1436 PREP_MODE_EXTERNAL_EXPORT,
1439 static int prepare_frame(AVHWFramesContext *hwfc, VulkanExecCtx *ectx,
1440 AVVkFrame *frame, enum PrepMode pmode)
1444 VkImageLayout new_layout;
1445 VkAccessFlags new_access;
1446 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1448 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
1450 VkSubmitInfo s_info = {
1451 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
1452 .pSignalSemaphores = frame->sem,
1453 .signalSemaphoreCount = planes,
1456 VkPipelineStageFlagBits wait_st[AV_NUM_DATA_POINTERS];
1457 for (int i = 0; i < planes; i++)
1458 wait_st[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
1461 case PREP_MODE_WRITE:
1462 new_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
1463 new_access = VK_ACCESS_TRANSFER_WRITE_BIT;
1464 dst_qf = VK_QUEUE_FAMILY_IGNORED;
1466 case PREP_MODE_RO_SHADER:
1467 new_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
1468 new_access = VK_ACCESS_TRANSFER_READ_BIT;
1469 dst_qf = VK_QUEUE_FAMILY_IGNORED;
1471 case PREP_MODE_EXTERNAL_EXPORT:
1472 new_layout = VK_IMAGE_LAYOUT_GENERAL;
1473 new_access = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
1474 dst_qf = VK_QUEUE_FAMILY_EXTERNAL_KHR;
1475 s_info.pWaitSemaphores = frame->sem;
1476 s_info.pWaitDstStageMask = wait_st;
1477 s_info.waitSemaphoreCount = planes;
1481 if ((err = wait_start_exec_ctx(hwfc, ectx)))
1484 /* Change the image layout to something more optimal for writes.
1485 * This also signals the newly created semaphore, making it usable
1486 * for synchronization */
1487 for (int i = 0; i < planes; i++) {
1488 img_bar[i].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1489 img_bar[i].srcAccessMask = 0x0;
1490 img_bar[i].dstAccessMask = new_access;
1491 img_bar[i].oldLayout = frame->layout[i];
1492 img_bar[i].newLayout = new_layout;
1493 img_bar[i].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1494 img_bar[i].dstQueueFamilyIndex = dst_qf;
1495 img_bar[i].image = frame->img[i];
1496 img_bar[i].subresourceRange.levelCount = 1;
1497 img_bar[i].subresourceRange.layerCount = 1;
1498 img_bar[i].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1500 frame->layout[i] = img_bar[i].newLayout;
1501 frame->access[i] = img_bar[i].dstAccessMask;
1504 vkCmdPipelineBarrier(get_buf_exec_ctx(hwfc, ectx),
1505 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
1506 VK_PIPELINE_STAGE_TRANSFER_BIT,
1507 0, 0, NULL, 0, NULL, planes, img_bar);
1509 return submit_exec_ctx(hwfc, ectx, &s_info, 0);
1512 static inline void get_plane_wh(int *w, int *h, enum AVPixelFormat format,
1513 int frame_w, int frame_h, int plane)
1515 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
1517 /* Currently always true unless gray + alpha support is added */
1518 if (!plane || (plane == 3) || desc->flags & AV_PIX_FMT_FLAG_RGB ||
1519 !(desc->flags & AV_PIX_FMT_FLAG_PLANAR)) {
1525 *w = AV_CEIL_RSHIFT(frame_w, desc->log2_chroma_w);
1526 *h = AV_CEIL_RSHIFT(frame_h, desc->log2_chroma_h);
1529 static int create_frame(AVHWFramesContext *hwfc, AVVkFrame **frame,
1530 VkImageTiling tiling, VkImageUsageFlagBits usage,
1535 AVHWDeviceContext *ctx = hwfc->device_ctx;
1536 VulkanDevicePriv *p = ctx->internal->priv;
1537 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1538 enum AVPixelFormat format = hwfc->sw_format;
1539 const VkFormat *img_fmts = av_vkfmt_from_pixfmt(format);
1540 const int planes = av_pix_fmt_count_planes(format);
1542 VkExportSemaphoreCreateInfo ext_sem_info = {
1543 .sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO,
1544 .handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
1547 VkSemaphoreCreateInfo sem_spawn = {
1548 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1549 .pNext = p->extensions & EXT_EXTERNAL_FD_SEM ? &ext_sem_info : NULL,
1552 AVVkFrame *f = av_vk_frame_alloc();
1554 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1555 return AVERROR(ENOMEM);
1558 /* Create the images */
1559 for (int i = 0; i < planes; i++) {
1560 VkImageCreateInfo create_info = {
1561 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1562 .pNext = create_pnext,
1563 .imageType = VK_IMAGE_TYPE_2D,
1564 .format = img_fmts[i],
1568 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1570 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1572 .samples = VK_SAMPLE_COUNT_1_BIT,
1573 .pQueueFamilyIndices = p->qfs,
1574 .queueFamilyIndexCount = p->num_qfs,
1575 .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
1576 VK_SHARING_MODE_EXCLUSIVE,
1579 get_plane_wh(&create_info.extent.width, &create_info.extent.height,
1580 format, hwfc->width, hwfc->height, i);
1582 ret = vkCreateImage(hwctx->act_dev, &create_info,
1583 hwctx->alloc, &f->img[i]);
1584 if (ret != VK_SUCCESS) {
1585 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1587 err = AVERROR(EINVAL);
1591 /* Create semaphore */
1592 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1593 hwctx->alloc, &f->sem[i]);
1594 if (ret != VK_SUCCESS) {
1595 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1597 return AVERROR_EXTERNAL;
1600 f->layout[i] = create_info.initialLayout;
1611 vulkan_frame_free(hwfc, (uint8_t *)f);
1615 /* Checks if an export flag is enabled, and if it is ORs it with *iexp */
1616 static void try_export_flags(AVHWFramesContext *hwfc,
1617 VkExternalMemoryHandleTypeFlags *comp_handle_types,
1618 VkExternalMemoryHandleTypeFlagBits *iexp,
1619 VkExternalMemoryHandleTypeFlagBits exp)
1622 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1623 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1624 VkExternalImageFormatProperties eprops = {
1625 .sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES_KHR,
1627 VkImageFormatProperties2 props = {
1628 .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,
1631 VkPhysicalDeviceExternalImageFormatInfo enext = {
1632 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
1635 VkPhysicalDeviceImageFormatInfo2 pinfo = {
1636 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1637 .pNext = !exp ? NULL : &enext,
1638 .format = av_vkfmt_from_pixfmt(hwfc->sw_format)[0],
1639 .type = VK_IMAGE_TYPE_2D,
1640 .tiling = hwctx->tiling,
1641 .usage = hwctx->usage,
1642 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1645 ret = vkGetPhysicalDeviceImageFormatProperties2(dev_hwctx->phys_dev,
1647 if (ret == VK_SUCCESS) {
1649 *comp_handle_types |= eprops.externalMemoryProperties.compatibleHandleTypes;
1653 static AVBufferRef *vulkan_pool_alloc(void *opaque, int size)
1657 AVBufferRef *avbuf = NULL;
1658 AVHWFramesContext *hwfc = opaque;
1659 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1660 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1661 VulkanFramesPriv *fp = hwfc->internal->priv;
1662 VkExportMemoryAllocateInfo eminfo[AV_NUM_DATA_POINTERS];
1663 VkExternalMemoryHandleTypeFlags e = 0x0;
1665 VkExternalMemoryImageCreateInfo eiinfo = {
1666 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1667 .pNext = hwctx->create_pnext,
1670 if (p->extensions & EXT_EXTERNAL_FD_MEMORY)
1671 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1672 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT);
1674 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
1675 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1676 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
1678 for (int i = 0; i < av_pix_fmt_count_planes(hwfc->sw_format); i++) {
1679 eminfo[i].sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO;
1680 eminfo[i].pNext = hwctx->alloc_pnext[i];
1681 eminfo[i].handleTypes = e;
1684 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1685 eiinfo.handleTypes ? &eiinfo : NULL);
1689 err = alloc_bind_mem(hwfc, f, eminfo, sizeof(*eminfo));
1693 err = prepare_frame(hwfc, &fp->conv_ctx, f, PREP_MODE_WRITE);
1697 avbuf = av_buffer_create((uint8_t *)f, sizeof(AVVkFrame),
1698 vulkan_frame_free, hwfc, 0);
1705 vulkan_frame_free(hwfc, (uint8_t *)f);
1709 static void vulkan_frames_uninit(AVHWFramesContext *hwfc)
1711 VulkanFramesPriv *fp = hwfc->internal->priv;
1713 free_exec_ctx(hwfc, &fp->conv_ctx);
1714 free_exec_ctx(hwfc, &fp->upload_ctx);
1715 free_exec_ctx(hwfc, &fp->download_ctx);
1718 static int vulkan_frames_init(AVHWFramesContext *hwfc)
1722 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1723 VulkanFramesPriv *fp = hwfc->internal->priv;
1724 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1725 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1727 /* Default pool flags */
1728 hwctx->tiling = hwctx->tiling ? hwctx->tiling : p->use_linear_images ?
1729 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1732 hwctx->usage = DEFAULT_USAGE_FLAGS;
1734 err = create_exec_ctx(hwfc, &fp->conv_ctx,
1735 dev_hwctx->queue_family_comp_index,
1736 GET_QUEUE_COUNT(dev_hwctx, 0, 1, 0));
1740 err = create_exec_ctx(hwfc, &fp->upload_ctx,
1741 dev_hwctx->queue_family_tx_index,
1742 GET_QUEUE_COUNT(dev_hwctx, 0, 0, 1));
1746 err = create_exec_ctx(hwfc, &fp->download_ctx,
1747 dev_hwctx->queue_family_tx_index, 1);
1751 /* Test to see if allocation will fail */
1752 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1753 hwctx->create_pnext);
1757 vulkan_frame_free(hwfc, (uint8_t *)f);
1759 /* If user did not specify a pool, hwfc->pool will be set to the internal one
1760 * in hwcontext.c just after this gets called */
1762 hwfc->internal->pool_internal = av_buffer_pool_init2(sizeof(AVVkFrame),
1763 hwfc, vulkan_pool_alloc,
1765 if (!hwfc->internal->pool_internal)
1766 return AVERROR(ENOMEM);
1772 static int vulkan_get_buffer(AVHWFramesContext *hwfc, AVFrame *frame)
1774 frame->buf[0] = av_buffer_pool_get(hwfc->pool);
1776 return AVERROR(ENOMEM);
1778 frame->data[0] = frame->buf[0]->data;
1779 frame->format = AV_PIX_FMT_VULKAN;
1780 frame->width = hwfc->width;
1781 frame->height = hwfc->height;
1786 static int vulkan_transfer_get_formats(AVHWFramesContext *hwfc,
1787 enum AVHWFrameTransferDirection dir,
1788 enum AVPixelFormat **formats)
1790 enum AVPixelFormat *fmts = av_malloc_array(2, sizeof(*fmts));
1792 return AVERROR(ENOMEM);
1794 fmts[0] = hwfc->sw_format;
1795 fmts[1] = AV_PIX_FMT_NONE;
1801 typedef struct VulkanMapping {
1806 static void vulkan_unmap_frame(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1808 VulkanMapping *map = hwmap->priv;
1809 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1810 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1812 /* Check if buffer needs flushing */
1813 if ((map->flags & AV_HWFRAME_MAP_WRITE) &&
1814 !(map->frame->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1816 VkMappedMemoryRange flush_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1818 for (int i = 0; i < planes; i++) {
1819 flush_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1820 flush_ranges[i].memory = map->frame->mem[i];
1821 flush_ranges[i].size = VK_WHOLE_SIZE;
1824 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, planes,
1826 if (ret != VK_SUCCESS) {
1827 av_log(hwfc, AV_LOG_ERROR, "Failed to flush memory: %s\n",
1832 for (int i = 0; i < planes; i++)
1833 vkUnmapMemory(hwctx->act_dev, map->frame->mem[i]);
1838 static int vulkan_map_frame_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
1839 const AVFrame *src, int flags)
1842 int err, mapped_mem_count = 0;
1843 AVVkFrame *f = (AVVkFrame *)src->data[0];
1844 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1845 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1847 VulkanMapping *map = av_mallocz(sizeof(VulkanMapping));
1849 return AVERROR(EINVAL);
1851 if (src->format != AV_PIX_FMT_VULKAN) {
1852 av_log(hwfc, AV_LOG_ERROR, "Cannot map from pixel format %s!\n",
1853 av_get_pix_fmt_name(src->format));
1854 err = AVERROR(EINVAL);
1858 if (!(f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ||
1859 !(f->tiling == VK_IMAGE_TILING_LINEAR)) {
1860 av_log(hwfc, AV_LOG_ERROR, "Unable to map frame, not host visible "
1862 err = AVERROR(EINVAL);
1866 dst->width = src->width;
1867 dst->height = src->height;
1869 for (int i = 0; i < planes; i++) {
1870 ret = vkMapMemory(hwctx->act_dev, f->mem[i], 0,
1871 VK_WHOLE_SIZE, 0, (void **)&dst->data[i]);
1872 if (ret != VK_SUCCESS) {
1873 av_log(hwfc, AV_LOG_ERROR, "Failed to map image memory: %s\n",
1875 err = AVERROR_EXTERNAL;
1881 /* Check if the memory contents matter */
1882 if (((flags & AV_HWFRAME_MAP_READ) || !(flags & AV_HWFRAME_MAP_OVERWRITE)) &&
1883 !(f->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1884 VkMappedMemoryRange map_mem_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1885 for (int i = 0; i < planes; i++) {
1886 map_mem_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1887 map_mem_ranges[i].size = VK_WHOLE_SIZE;
1888 map_mem_ranges[i].memory = f->mem[i];
1891 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, planes,
1893 if (ret != VK_SUCCESS) {
1894 av_log(hwfc, AV_LOG_ERROR, "Failed to invalidate memory: %s\n",
1896 err = AVERROR_EXTERNAL;
1901 for (int i = 0; i < planes; i++) {
1902 VkImageSubresource sub = {
1903 .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
1905 VkSubresourceLayout layout;
1906 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
1907 dst->linesize[i] = layout.rowPitch;
1913 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src,
1914 &vulkan_unmap_frame, map);
1921 for (int i = 0; i < mapped_mem_count; i++)
1922 vkUnmapMemory(hwctx->act_dev, f->mem[i]);
1929 static void vulkan_unmap_from(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1931 VulkanMapping *map = hwmap->priv;
1932 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1933 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1935 for (int i = 0; i < planes; i++) {
1936 vkDestroyImage(hwctx->act_dev, map->frame->img[i], hwctx->alloc);
1937 vkFreeMemory(hwctx->act_dev, map->frame->mem[i], hwctx->alloc);
1938 vkDestroySemaphore(hwctx->act_dev, map->frame->sem[i], hwctx->alloc);
1941 av_freep(&map->frame);
1944 static const struct {
1945 uint32_t drm_fourcc;
1947 } vulkan_drm_format_map[] = {
1948 { DRM_FORMAT_R8, VK_FORMAT_R8_UNORM },
1949 { DRM_FORMAT_R16, VK_FORMAT_R16_UNORM },
1950 { DRM_FORMAT_GR88, VK_FORMAT_R8G8_UNORM },
1951 { DRM_FORMAT_RG88, VK_FORMAT_R8G8_UNORM },
1952 { DRM_FORMAT_GR1616, VK_FORMAT_R16G16_UNORM },
1953 { DRM_FORMAT_RG1616, VK_FORMAT_R16G16_UNORM },
1954 { DRM_FORMAT_ARGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1955 { DRM_FORMAT_XRGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1956 { DRM_FORMAT_ABGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1957 { DRM_FORMAT_XBGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1960 static inline VkFormat drm_to_vulkan_fmt(uint32_t drm_fourcc)
1962 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
1963 if (vulkan_drm_format_map[i].drm_fourcc == drm_fourcc)
1964 return vulkan_drm_format_map[i].vk_format;
1965 return VK_FORMAT_UNDEFINED;
1968 static int vulkan_map_from_drm_frame_desc(AVHWFramesContext *hwfc, AVVkFrame **frame,
1969 AVDRMFrameDescriptor *desc)
1974 int bind_counts = 0;
1975 AVHWDeviceContext *ctx = hwfc->device_ctx;
1976 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1977 VulkanDevicePriv *p = ctx->internal->priv;
1978 VulkanFramesPriv *fp = hwfc->internal->priv;
1979 AVVulkanFramesContext *frames_hwctx = hwfc->hwctx;
1980 const int has_modifiers = !!(p->extensions & EXT_DRM_MODIFIER_FLAGS);
1981 VkSubresourceLayout plane_data[AV_NUM_DATA_POINTERS] = { 0 };
1982 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { 0 };
1983 VkBindImagePlaneMemoryInfo plane_info[AV_NUM_DATA_POINTERS] = { 0 };
1984 VkExternalMemoryHandleTypeFlagBits htype = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
1986 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdPropertiesKHR);
1988 for (int i = 0; i < desc->nb_layers; i++) {
1989 if (drm_to_vulkan_fmt(desc->layers[i].format) == VK_FORMAT_UNDEFINED) {
1990 av_log(ctx, AV_LOG_ERROR, "Unsupported DMABUF layer format %#08x!\n",
1991 desc->layers[i].format);
1992 return AVERROR(EINVAL);
1996 if (!(f = av_vk_frame_alloc())) {
1997 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1998 err = AVERROR(ENOMEM);
2002 f->tiling = has_modifiers ? VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT :
2003 desc->objects[0].format_modifier == DRM_FORMAT_MOD_LINEAR ?
2004 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
2006 for (int i = 0; i < desc->nb_layers; i++) {
2007 const int planes = desc->layers[i].nb_planes;
2008 VkImageDrmFormatModifierExplicitCreateInfoEXT drm_info = {
2009 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
2010 .drmFormatModifier = desc->objects[0].format_modifier,
2011 .drmFormatModifierPlaneCount = planes,
2012 .pPlaneLayouts = (const VkSubresourceLayout *)&plane_data,
2015 VkExternalMemoryImageCreateInfo einfo = {
2016 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
2017 .pNext = has_modifiers ? &drm_info : NULL,
2018 .handleTypes = htype,
2021 VkSemaphoreCreateInfo sem_spawn = {
2022 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
2025 VkImageCreateInfo create_info = {
2026 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
2028 .imageType = VK_IMAGE_TYPE_2D,
2029 .format = drm_to_vulkan_fmt(desc->layers[i].format),
2033 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
2034 .tiling = f->tiling,
2035 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, /* specs say so */
2036 .usage = frames_hwctx->usage,
2037 .samples = VK_SAMPLE_COUNT_1_BIT,
2038 .pQueueFamilyIndices = p->qfs,
2039 .queueFamilyIndexCount = p->num_qfs,
2040 .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
2041 VK_SHARING_MODE_EXCLUSIVE,
2044 get_plane_wh(&create_info.extent.width, &create_info.extent.height,
2045 hwfc->sw_format, hwfc->width, hwfc->height, i);
2047 for (int j = 0; j < planes; j++) {
2048 plane_data[j].offset = desc->layers[i].planes[j].offset;
2049 plane_data[j].rowPitch = desc->layers[i].planes[j].pitch;
2050 plane_data[j].size = 0; /* The specs say so for all 3 */
2051 plane_data[j].arrayPitch = 0;
2052 plane_data[j].depthPitch = 0;
2056 ret = vkCreateImage(hwctx->act_dev, &create_info,
2057 hwctx->alloc, &f->img[i]);
2058 if (ret != VK_SUCCESS) {
2059 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
2061 err = AVERROR(EINVAL);
2065 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
2066 hwctx->alloc, &f->sem[i]);
2067 if (ret != VK_SUCCESS) {
2068 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
2070 return AVERROR_EXTERNAL;
2073 /* We'd import a semaphore onto the one we created using
2074 * vkImportSemaphoreFdKHR but unfortunately neither DRM nor VAAPI
2075 * offer us anything we could import and sync with, so instead
2076 * just signal the semaphore we created. */
2078 f->layout[i] = create_info.initialLayout;
2082 for (int i = 0; i < desc->nb_objects; i++) {
2083 int use_ded_mem = 0;
2084 VkMemoryFdPropertiesKHR fdmp = {
2085 .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,
2087 VkMemoryRequirements req = {
2088 .size = desc->objects[i].size,
2090 VkImportMemoryFdInfoKHR idesc = {
2091 .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
2092 .handleType = htype,
2093 .fd = dup(desc->objects[i].fd),
2095 VkMemoryDedicatedAllocateInfo ded_alloc = {
2096 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
2100 ret = pfn_vkGetMemoryFdPropertiesKHR(hwctx->act_dev, htype,
2102 if (ret != VK_SUCCESS) {
2103 av_log(hwfc, AV_LOG_ERROR, "Failed to get FD properties: %s\n",
2105 err = AVERROR_EXTERNAL;
2110 req.memoryTypeBits = fdmp.memoryTypeBits;
2112 /* Dedicated allocation only makes sense if there's a one to one mapping
2113 * between images and the memory backing them, so only check in this
2115 if (desc->nb_layers == desc->nb_objects) {
2116 VkImageMemoryRequirementsInfo2 req_desc = {
2117 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
2120 VkMemoryDedicatedRequirements ded_req = {
2121 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
2123 VkMemoryRequirements2 req2 = {
2124 .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
2128 vkGetImageMemoryRequirements2(hwctx->act_dev, &req_desc, &req2);
2130 use_ded_mem = ded_req.prefersDedicatedAllocation |
2131 ded_req.requiresDedicatedAllocation;
2133 ded_alloc.image = f->img[i];
2136 err = alloc_mem(ctx, &req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
2137 use_ded_mem ? &ded_alloc : ded_alloc.pNext,
2138 &f->flags, &f->mem[i]);
2144 f->size[i] = desc->objects[i].size;
2147 for (int i = 0; i < desc->nb_layers; i++) {
2148 const int planes = desc->layers[i].nb_planes;
2149 const int signal_p = has_modifiers && (planes > 1);
2150 for (int j = 0; j < planes; j++) {
2151 VkImageAspectFlagBits aspect = j == 0 ? VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2152 j == 1 ? VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT :
2153 VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT;
2155 plane_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO;
2156 plane_info[bind_counts].planeAspect = aspect;
2158 bind_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
2159 bind_info[bind_counts].pNext = signal_p ? &plane_info[bind_counts] : NULL;
2160 bind_info[bind_counts].image = f->img[i];
2161 bind_info[bind_counts].memory = f->mem[desc->layers[i].planes[j].object_index];
2162 bind_info[bind_counts].memoryOffset = desc->layers[i].planes[j].offset;
2167 /* Bind the allocated memory to the images */
2168 ret = vkBindImageMemory2(hwctx->act_dev, bind_counts, bind_info);
2169 if (ret != VK_SUCCESS) {
2170 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
2172 return AVERROR_EXTERNAL;
2175 /* NOTE: This is completely uneccesary and unneeded once we can import
2176 * semaphores from DRM. Otherwise we have to activate the semaphores.
2177 * We're reusing the exec context that's also used for uploads/downloads. */
2178 err = prepare_frame(hwfc, &fp->conv_ctx, f, PREP_MODE_RO_SHADER);
2187 for (int i = 0; i < desc->nb_layers; i++) {
2188 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
2189 vkDestroySemaphore(hwctx->act_dev, f->sem[i], hwctx->alloc);
2191 for (int i = 0; i < desc->nb_objects; i++)
2192 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
2199 static int vulkan_map_from_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2200 const AVFrame *src, int flags)
2204 VulkanMapping *map = NULL;
2206 err = vulkan_map_from_drm_frame_desc(hwfc, &f,
2207 (AVDRMFrameDescriptor *)src->data[0]);
2211 /* The unmapping function will free this */
2212 dst->data[0] = (uint8_t *)f;
2213 dst->width = src->width;
2214 dst->height = src->height;
2216 map = av_mallocz(sizeof(VulkanMapping));
2223 err = ff_hwframe_map_create(dst->hw_frames_ctx, dst, src,
2224 &vulkan_unmap_from, map);
2228 av_log(hwfc, AV_LOG_DEBUG, "Mapped DRM object to Vulkan!\n");
2233 vulkan_frame_free(hwfc->device_ctx->hwctx, (uint8_t *)f);
2239 static int vulkan_map_from_vaapi(AVHWFramesContext *dst_fc,
2240 AVFrame *dst, const AVFrame *src,
2244 AVFrame *tmp = av_frame_alloc();
2245 AVHWFramesContext *vaapi_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2246 AVVAAPIDeviceContext *vaapi_ctx = vaapi_fc->device_ctx->hwctx;
2247 VASurfaceID surface_id = (VASurfaceID)(uintptr_t)src->data[3];
2250 return AVERROR(ENOMEM);
2252 /* We have to sync since like the previous comment said, no semaphores */
2253 vaSyncSurface(vaapi_ctx->display, surface_id);
2255 tmp->format = AV_PIX_FMT_DRM_PRIME;
2257 err = av_hwframe_map(tmp, src, flags);
2261 err = vulkan_map_from_drm(dst_fc, dst, tmp, flags);
2265 err = ff_hwframe_map_replace(dst, src);
2268 av_frame_free(&tmp);
2275 static int vulkan_export_to_cuda(AVHWFramesContext *hwfc,
2276 AVBufferRef *cuda_hwfc,
2277 const AVFrame *frame)
2282 AVVkFrameInternal *dst_int;
2283 AVHWDeviceContext *ctx = hwfc->device_ctx;
2284 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2285 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2286 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2287 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2288 VK_LOAD_PFN(hwctx->inst, vkGetSemaphoreFdKHR);
2290 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)cuda_hwfc->data;
2291 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2292 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2293 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2294 CudaFunctions *cu = cu_internal->cuda_dl;
2295 CUarray_format cufmt = desc->comp[0].depth > 8 ? CU_AD_FORMAT_UNSIGNED_INT16 :
2296 CU_AD_FORMAT_UNSIGNED_INT8;
2298 dst_f = (AVVkFrame *)frame->data[0];
2300 dst_int = dst_f->internal;
2301 if (!dst_int || !dst_int->cuda_fc_ref) {
2302 if (!dst_f->internal)
2303 dst_f->internal = dst_int = av_mallocz(sizeof(*dst_f->internal));
2306 err = AVERROR(ENOMEM);
2310 dst_int->cuda_fc_ref = av_buffer_ref(cuda_hwfc);
2311 if (!dst_int->cuda_fc_ref) {
2312 err = AVERROR(ENOMEM);
2316 for (int i = 0; i < planes; i++) {
2317 CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC tex_desc = {
2322 .NumChannels = 1 + ((planes == 2) && i),
2327 CUDA_EXTERNAL_MEMORY_HANDLE_DESC ext_desc = {
2328 .type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD,
2329 .size = dst_f->size[i],
2331 VkMemoryGetFdInfoKHR export_info = {
2332 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2333 .memory = dst_f->mem[i],
2334 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR,
2336 VkSemaphoreGetFdInfoKHR sem_export = {
2337 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR,
2338 .semaphore = dst_f->sem[i],
2339 .handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
2341 CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC ext_sem_desc = {
2342 .type = CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD,
2346 get_plane_wh(&p_w, &p_h, hwfc->sw_format, hwfc->width, hwfc->height, i);
2348 tex_desc.arrayDesc.Width = p_w;
2349 tex_desc.arrayDesc.Height = p_h;
2351 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2352 &ext_desc.handle.fd);
2353 if (ret != VK_SUCCESS) {
2354 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2355 err = AVERROR_EXTERNAL;
2359 ret = CHECK_CU(cu->cuImportExternalMemory(&dst_int->ext_mem[i], &ext_desc));
2361 err = AVERROR_EXTERNAL;
2365 ret = CHECK_CU(cu->cuExternalMemoryGetMappedMipmappedArray(&dst_int->cu_mma[i],
2366 dst_int->ext_mem[i],
2369 err = AVERROR_EXTERNAL;
2373 ret = CHECK_CU(cu->cuMipmappedArrayGetLevel(&dst_int->cu_array[i],
2374 dst_int->cu_mma[i], 0));
2376 err = AVERROR_EXTERNAL;
2380 ret = pfn_vkGetSemaphoreFdKHR(hwctx->act_dev, &sem_export,
2381 &ext_sem_desc.handle.fd);
2382 if (ret != VK_SUCCESS) {
2383 av_log(ctx, AV_LOG_ERROR, "Failed to export semaphore: %s\n",
2385 err = AVERROR_EXTERNAL;
2389 ret = CHECK_CU(cu->cuImportExternalSemaphore(&dst_int->cu_sem[i],
2392 err = AVERROR_EXTERNAL;
2404 static int vulkan_transfer_data_from_cuda(AVHWFramesContext *hwfc,
2405 AVFrame *dst, const AVFrame *src)
2411 AVVkFrameInternal *dst_int;
2412 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2413 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2415 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2416 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2417 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2418 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2419 CudaFunctions *cu = cu_internal->cuda_dl;
2420 CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS s_w_par[AV_NUM_DATA_POINTERS] = { 0 };
2421 CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS s_s_par[AV_NUM_DATA_POINTERS] = { 0 };
2423 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2425 return AVERROR_EXTERNAL;
2427 dst_f = (AVVkFrame *)dst->data[0];
2429 ret = vulkan_export_to_cuda(hwfc, src->hw_frames_ctx, dst);
2431 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2435 dst_int = dst_f->internal;
2437 ret = CHECK_CU(cu->cuWaitExternalSemaphoresAsync(dst_int->cu_sem, s_w_par,
2438 planes, cuda_dev->stream));
2440 err = AVERROR_EXTERNAL;
2444 for (int i = 0; i < planes; i++) {
2445 CUDA_MEMCPY2D cpy = {
2446 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
2447 .srcDevice = (CUdeviceptr)src->data[i],
2448 .srcPitch = src->linesize[i],
2451 .dstMemoryType = CU_MEMORYTYPE_ARRAY,
2452 .dstArray = dst_int->cu_array[i],
2456 get_plane_wh(&p_w, &p_h, hwfc->sw_format, hwfc->width, hwfc->height, i);
2458 cpy.WidthInBytes = p_w * desc->comp[i].step;
2461 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2463 err = AVERROR_EXTERNAL;
2468 ret = CHECK_CU(cu->cuSignalExternalSemaphoresAsync(dst_int->cu_sem, s_s_par,
2469 planes, cuda_dev->stream));
2471 err = AVERROR_EXTERNAL;
2475 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2477 av_log(hwfc, AV_LOG_VERBOSE, "Transfered CUDA image to Vulkan!\n");
2482 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2483 vulkan_free_internal(dst_int);
2484 dst_f->internal = NULL;
2485 av_buffer_unref(&dst->buf[0]);
2490 static int vulkan_map_to(AVHWFramesContext *hwfc, AVFrame *dst,
2491 const AVFrame *src, int flags)
2493 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2495 switch (src->format) {
2498 case AV_PIX_FMT_VAAPI:
2499 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2500 return vulkan_map_from_vaapi(hwfc, dst, src, flags);
2502 case AV_PIX_FMT_DRM_PRIME:
2503 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2504 return vulkan_map_from_drm(hwfc, dst, src, flags);
2507 return AVERROR(ENOSYS);
2512 typedef struct VulkanDRMMapping {
2513 AVDRMFrameDescriptor drm_desc;
2517 static void vulkan_unmap_to_drm(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
2519 AVDRMFrameDescriptor *drm_desc = hwmap->priv;
2521 for (int i = 0; i < drm_desc->nb_objects; i++)
2522 close(drm_desc->objects[i].fd);
2527 static inline uint32_t vulkan_fmt_to_drm(VkFormat vkfmt)
2529 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
2530 if (vulkan_drm_format_map[i].vk_format == vkfmt)
2531 return vulkan_drm_format_map[i].drm_fourcc;
2532 return DRM_FORMAT_INVALID;
2535 static int vulkan_map_to_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2536 const AVFrame *src, int flags)
2540 AVVkFrame *f = (AVVkFrame *)src->data[0];
2541 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2542 VulkanFramesPriv *fp = hwfc->internal->priv;
2543 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
2544 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2545 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2546 VkImageDrmFormatModifierPropertiesEXT drm_mod = {
2547 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT,
2550 AVDRMFrameDescriptor *drm_desc = av_mallocz(sizeof(*drm_desc));
2552 return AVERROR(ENOMEM);
2554 err = prepare_frame(hwfc, &fp->conv_ctx, f, PREP_MODE_EXTERNAL_EXPORT);
2558 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src, &vulkan_unmap_to_drm, drm_desc);
2562 if (p->extensions & EXT_DRM_MODIFIER_FLAGS) {
2563 VK_LOAD_PFN(hwctx->inst, vkGetImageDrmFormatModifierPropertiesEXT);
2564 ret = pfn_vkGetImageDrmFormatModifierPropertiesEXT(hwctx->act_dev, f->img[0],
2566 if (ret != VK_SUCCESS) {
2567 av_log(hwfc, AV_LOG_ERROR, "Failed to retrieve DRM format modifier!\n");
2568 err = AVERROR_EXTERNAL;
2573 for (int i = 0; (i < planes) && (f->mem[i]); i++) {
2574 VkMemoryGetFdInfoKHR export_info = {
2575 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2576 .memory = f->mem[i],
2577 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,
2580 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2581 &drm_desc->objects[i].fd);
2582 if (ret != VK_SUCCESS) {
2583 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2584 err = AVERROR_EXTERNAL;
2588 drm_desc->nb_objects++;
2589 drm_desc->objects[i].size = f->size[i];
2590 drm_desc->objects[i].format_modifier = drm_mod.drmFormatModifier;
2593 drm_desc->nb_layers = planes;
2594 for (int i = 0; i < drm_desc->nb_layers; i++) {
2595 VkSubresourceLayout layout;
2596 VkImageSubresource sub = {
2597 .aspectMask = p->extensions & EXT_DRM_MODIFIER_FLAGS ?
2598 VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2599 VK_IMAGE_ASPECT_COLOR_BIT,
2601 VkFormat plane_vkfmt = av_vkfmt_from_pixfmt(hwfc->sw_format)[i];
2603 drm_desc->layers[i].format = vulkan_fmt_to_drm(plane_vkfmt);
2604 drm_desc->layers[i].nb_planes = 1;
2606 if (drm_desc->layers[i].format == DRM_FORMAT_INVALID) {
2607 av_log(hwfc, AV_LOG_ERROR, "Cannot map to DRM layer, unsupported!\n");
2608 err = AVERROR_PATCHWELCOME;
2612 drm_desc->layers[i].planes[0].object_index = FFMIN(i, drm_desc->nb_objects - 1);
2614 if (f->tiling == VK_IMAGE_TILING_OPTIMAL)
2617 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
2618 drm_desc->layers[i].planes[0].offset = layout.offset;
2619 drm_desc->layers[i].planes[0].pitch = layout.rowPitch;
2622 dst->width = src->width;
2623 dst->height = src->height;
2624 dst->data[0] = (uint8_t *)drm_desc;
2626 av_log(hwfc, AV_LOG_VERBOSE, "Mapped AVVkFrame to a DRM object!\n");
2636 static int vulkan_map_to_vaapi(AVHWFramesContext *hwfc, AVFrame *dst,
2637 const AVFrame *src, int flags)
2640 AVFrame *tmp = av_frame_alloc();
2642 return AVERROR(ENOMEM);
2644 tmp->format = AV_PIX_FMT_DRM_PRIME;
2646 err = vulkan_map_to_drm(hwfc, tmp, src, flags);
2650 err = av_hwframe_map(dst, tmp, flags);
2654 err = ff_hwframe_map_replace(dst, src);
2657 av_frame_free(&tmp);
2663 static int vulkan_map_from(AVHWFramesContext *hwfc, AVFrame *dst,
2664 const AVFrame *src, int flags)
2666 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2668 switch (dst->format) {
2670 case AV_PIX_FMT_DRM_PRIME:
2671 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2672 return vulkan_map_to_drm(hwfc, dst, src, flags);
2674 case AV_PIX_FMT_VAAPI:
2675 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2676 return vulkan_map_to_vaapi(hwfc, dst, src, flags);
2680 return vulkan_map_frame_to_mem(hwfc, dst, src, flags);
2684 typedef struct ImageBuffer {
2687 VkMemoryPropertyFlagBits flags;
2691 static void free_buf(void *opaque, uint8_t *data)
2693 AVHWDeviceContext *ctx = opaque;
2694 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2695 ImageBuffer *vkbuf = (ImageBuffer *)data;
2698 vkDestroyBuffer(hwctx->act_dev, vkbuf->buf, hwctx->alloc);
2700 vkFreeMemory(hwctx->act_dev, vkbuf->mem, hwctx->alloc);
2705 static size_t get_req_buffer_size(VulkanDevicePriv *p, int *stride, int height)
2708 *stride = FFALIGN(*stride, p->props.properties.limits.optimalBufferCopyRowPitchAlignment);
2709 size = height*(*stride);
2710 size = FFALIGN(size, p->props.properties.limits.minMemoryMapAlignment);
2714 static int create_buf(AVHWDeviceContext *ctx, AVBufferRef **buf,
2715 VkBufferUsageFlags usage, VkMemoryPropertyFlagBits flags,
2716 size_t size, uint32_t req_memory_bits, int host_mapped,
2717 void *create_pnext, void *alloc_pnext)
2722 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2724 VkBufferCreateInfo buf_spawn = {
2725 .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
2726 .pNext = create_pnext,
2729 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
2732 VkBufferMemoryRequirementsInfo2 req_desc = {
2733 .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2,
2735 VkMemoryDedicatedAllocateInfo ded_alloc = {
2736 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
2737 .pNext = alloc_pnext,
2739 VkMemoryDedicatedRequirements ded_req = {
2740 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
2742 VkMemoryRequirements2 req = {
2743 .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
2747 ImageBuffer *vkbuf = av_mallocz(sizeof(*vkbuf));
2749 return AVERROR(ENOMEM);
2751 vkbuf->mapped_mem = host_mapped;
2753 ret = vkCreateBuffer(hwctx->act_dev, &buf_spawn, NULL, &vkbuf->buf);
2754 if (ret != VK_SUCCESS) {
2755 av_log(ctx, AV_LOG_ERROR, "Failed to create buffer: %s\n",
2757 err = AVERROR_EXTERNAL;
2761 req_desc.buffer = vkbuf->buf;
2763 vkGetBufferMemoryRequirements2(hwctx->act_dev, &req_desc, &req);
2765 /* In case the implementation prefers/requires dedicated allocation */
2766 use_ded_mem = ded_req.prefersDedicatedAllocation |
2767 ded_req.requiresDedicatedAllocation;
2769 ded_alloc.buffer = vkbuf->buf;
2771 /* Additional requirements imposed on us */
2772 if (req_memory_bits)
2773 req.memoryRequirements.memoryTypeBits &= req_memory_bits;
2775 err = alloc_mem(ctx, &req.memoryRequirements, flags,
2776 use_ded_mem ? &ded_alloc : (void *)ded_alloc.pNext,
2777 &vkbuf->flags, &vkbuf->mem);
2781 ret = vkBindBufferMemory(hwctx->act_dev, vkbuf->buf, vkbuf->mem, 0);
2782 if (ret != VK_SUCCESS) {
2783 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory to buffer: %s\n",
2785 err = AVERROR_EXTERNAL;
2789 *buf = av_buffer_create((uint8_t *)vkbuf, sizeof(*vkbuf), free_buf, ctx, 0);
2791 err = AVERROR(ENOMEM);
2798 free_buf(ctx, (uint8_t *)vkbuf);
2802 /* Skips mapping of host mapped buffers but still invalidates them */
2803 static int map_buffers(AVHWDeviceContext *ctx, AVBufferRef **bufs, uint8_t *mem[],
2804 int nb_buffers, int invalidate)
2807 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2808 VkMappedMemoryRange invalidate_ctx[AV_NUM_DATA_POINTERS];
2809 int invalidate_count = 0;
2811 for (int i = 0; i < nb_buffers; i++) {
2812 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2813 if (vkbuf->mapped_mem)
2816 ret = vkMapMemory(hwctx->act_dev, vkbuf->mem, 0,
2817 VK_WHOLE_SIZE, 0, (void **)&mem[i]);
2818 if (ret != VK_SUCCESS) {
2819 av_log(ctx, AV_LOG_ERROR, "Failed to map buffer memory: %s\n",
2821 return AVERROR_EXTERNAL;
2828 for (int i = 0; i < nb_buffers; i++) {
2829 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2830 const VkMappedMemoryRange ival_buf = {
2831 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2832 .memory = vkbuf->mem,
2833 .size = VK_WHOLE_SIZE,
2836 /* For host imported memory Vulkan says to use platform-defined
2837 * sync methods, but doesn't really say not to call flush or invalidate
2838 * on original host pointers. It does explicitly allow to do that on
2839 * host-mapped pointers which are then mapped again using vkMapMemory,
2840 * but known implementations return the original pointers when mapped
2842 if (vkbuf->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2845 invalidate_ctx[invalidate_count++] = ival_buf;
2848 if (invalidate_count) {
2849 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, invalidate_count,
2851 if (ret != VK_SUCCESS)
2852 av_log(ctx, AV_LOG_WARNING, "Failed to invalidate memory: %s\n",
2859 static int unmap_buffers(AVHWDeviceContext *ctx, AVBufferRef **bufs,
2860 int nb_buffers, int flush)
2864 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2865 VkMappedMemoryRange flush_ctx[AV_NUM_DATA_POINTERS];
2866 int flush_count = 0;
2869 for (int i = 0; i < nb_buffers; i++) {
2870 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2871 const VkMappedMemoryRange flush_buf = {
2872 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2873 .memory = vkbuf->mem,
2874 .size = VK_WHOLE_SIZE,
2877 if (vkbuf->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2880 flush_ctx[flush_count++] = flush_buf;
2885 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, flush_count, flush_ctx);
2886 if (ret != VK_SUCCESS) {
2887 av_log(ctx, AV_LOG_ERROR, "Failed to flush memory: %s\n",
2889 err = AVERROR_EXTERNAL; /* We still want to try to unmap them */
2893 for (int i = 0; i < nb_buffers; i++) {
2894 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2895 if (vkbuf->mapped_mem)
2898 vkUnmapMemory(hwctx->act_dev, vkbuf->mem);
2904 static int transfer_image_buf(AVHWFramesContext *hwfc, const AVFrame *f,
2905 AVBufferRef **bufs, size_t *buf_offsets,
2906 const int *buf_stride, int w,
2907 int h, enum AVPixelFormat pix_fmt, int to_buf)
2910 AVVkFrame *frame = (AVVkFrame *)f->data[0];
2911 VulkanFramesPriv *fp = hwfc->internal->priv;
2914 VkPipelineStageFlagBits sem_wait_dst[AV_NUM_DATA_POINTERS];
2916 const int planes = av_pix_fmt_count_planes(pix_fmt);
2917 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2919 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
2920 VulkanExecCtx *ectx = to_buf ? &fp->download_ctx : &fp->upload_ctx;
2921 VkCommandBuffer cmd_buf = get_buf_exec_ctx(hwfc, ectx);
2923 VkSubmitInfo s_info = {
2924 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
2925 .pSignalSemaphores = frame->sem,
2926 .pWaitSemaphores = frame->sem,
2927 .pWaitDstStageMask = sem_wait_dst,
2928 .signalSemaphoreCount = planes,
2929 .waitSemaphoreCount = planes,
2932 if ((err = wait_start_exec_ctx(hwfc, ectx)))
2935 /* Change the image layout to something more optimal for transfers */
2936 for (int i = 0; i < planes; i++) {
2937 VkImageLayout new_layout = to_buf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL :
2938 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
2939 VkAccessFlags new_access = to_buf ? VK_ACCESS_TRANSFER_READ_BIT :
2940 VK_ACCESS_TRANSFER_WRITE_BIT;
2942 sem_wait_dst[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
2944 /* If the layout matches and we have read access skip the barrier */
2945 if ((frame->layout[i] == new_layout) && (frame->access[i] & new_access))
2948 img_bar[bar_num].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
2949 img_bar[bar_num].srcAccessMask = 0x0;
2950 img_bar[bar_num].dstAccessMask = new_access;
2951 img_bar[bar_num].oldLayout = frame->layout[i];
2952 img_bar[bar_num].newLayout = new_layout;
2953 img_bar[bar_num].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2954 img_bar[bar_num].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2955 img_bar[bar_num].image = frame->img[i];
2956 img_bar[bar_num].subresourceRange.levelCount = 1;
2957 img_bar[bar_num].subresourceRange.layerCount = 1;
2958 img_bar[bar_num].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2960 frame->layout[i] = img_bar[bar_num].newLayout;
2961 frame->access[i] = img_bar[bar_num].dstAccessMask;
2967 vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
2968 VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
2969 0, NULL, 0, NULL, bar_num, img_bar);
2971 /* Schedule a copy for each plane */
2972 for (int i = 0; i < planes; i++) {
2973 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2974 VkBufferImageCopy buf_reg = {
2975 .bufferOffset = buf_offsets[i],
2976 .bufferRowLength = buf_stride[i] / desc->comp[i].step,
2977 .imageSubresource.layerCount = 1,
2978 .imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
2979 .imageOffset = { 0, 0, 0, },
2983 get_plane_wh(&p_w, &p_h, pix_fmt, w, h, i);
2985 buf_reg.bufferImageHeight = p_h;
2986 buf_reg.imageExtent = (VkExtent3D){ p_w, p_h, 1, };
2989 vkCmdCopyImageToBuffer(cmd_buf, frame->img[i], frame->layout[i],
2990 vkbuf->buf, 1, &buf_reg);
2992 vkCmdCopyBufferToImage(cmd_buf, vkbuf->buf, frame->img[i],
2993 frame->layout[i], 1, &buf_reg);
2996 /* When uploading, do this asynchronously if the source is refcounted by
2997 * keeping the buffers as a submission dependency.
2998 * The hwcontext is guaranteed to not be freed until all frames are freed
2999 * in the frames_unint function.
3000 * When downloading to buffer, do this synchronously and wait for the
3001 * queue submission to finish executing */
3004 for (ref = 0; ref < AV_NUM_DATA_POINTERS; ref++) {
3007 if ((err = add_buf_dep_exec_ctx(hwfc, ectx, &f->buf[ref], 1)))
3010 if (ref && (err = add_buf_dep_exec_ctx(hwfc, ectx, bufs, planes)))
3012 return submit_exec_ctx(hwfc, ectx, &s_info, !ref);
3014 return submit_exec_ctx(hwfc, ectx, &s_info, 1);
3018 static int vulkan_transfer_data(AVHWFramesContext *hwfc, const AVFrame *vkf,
3019 const AVFrame *swf, int from)
3023 AVVkFrame *f = (AVVkFrame *)vkf->data[0];
3024 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
3025 AVVulkanDeviceContext *hwctx = dev_ctx->hwctx;
3026 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
3029 AVBufferRef *bufs[AV_NUM_DATA_POINTERS] = { 0 };
3030 size_t buf_offsets[AV_NUM_DATA_POINTERS] = { 0 };
3033 const int planes = av_pix_fmt_count_planes(swf->format);
3035 int host_mapped[AV_NUM_DATA_POINTERS] = { 0 };
3036 const int map_host = !!(p->extensions & EXT_EXTERNAL_HOST_MEMORY);
3038 VK_LOAD_PFN(hwctx->inst, vkGetMemoryHostPointerPropertiesEXT);
3040 if ((swf->format != AV_PIX_FMT_NONE && !av_vkfmt_from_pixfmt(swf->format))) {
3041 av_log(hwfc, AV_LOG_ERROR, "Unsupported software frame pixel format!\n");
3042 return AVERROR(EINVAL);
3045 if (swf->width > hwfc->width || swf->height > hwfc->height)
3046 return AVERROR(EINVAL);
3048 /* For linear, host visiable images */
3049 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
3050 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
3051 AVFrame *map = av_frame_alloc();
3053 return AVERROR(ENOMEM);
3054 map->format = swf->format;
3056 err = vulkan_map_frame_to_mem(hwfc, map, vkf, AV_HWFRAME_MAP_WRITE);
3060 err = av_frame_copy((AVFrame *)(from ? swf : map), from ? map : swf);
3061 av_frame_free(&map);
3065 /* Create buffers */
3066 for (int i = 0; i < planes; i++) {
3069 VkExternalMemoryBufferCreateInfo create_desc = {
3070 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO,
3071 .handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT,
3074 VkImportMemoryHostPointerInfoEXT import_desc = {
3075 .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT,
3076 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT,
3079 VkMemoryHostPointerPropertiesEXT p_props = {
3080 .sType = VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT,
3083 get_plane_wh(&p_w, &p_h, swf->format, swf->width, swf->height, i);
3085 tmp.linesize[i] = FFABS(swf->linesize[i]);
3087 /* Do not map images with a negative stride */
3088 if (map_host && swf->linesize[i] > 0) {
3090 offs = (uintptr_t)swf->data[i] % p->hprops.minImportedHostPointerAlignment;
3091 import_desc.pHostPointer = swf->data[i] - offs;
3093 /* We have to compensate for the few extra bytes of padding we
3094 * completely ignore at the start */
3095 req_size = FFALIGN(offs + tmp.linesize[i] * p_h,
3096 p->hprops.minImportedHostPointerAlignment);
3098 ret = pfn_vkGetMemoryHostPointerPropertiesEXT(hwctx->act_dev,
3099 import_desc.handleType,
3100 import_desc.pHostPointer,
3103 if (ret == VK_SUCCESS) {
3105 buf_offsets[i] = offs;
3109 if (!host_mapped[i])
3110 req_size = get_req_buffer_size(p, &tmp.linesize[i], p_h);
3112 err = create_buf(dev_ctx, &bufs[i],
3113 from ? VK_BUFFER_USAGE_TRANSFER_DST_BIT :
3114 VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
3115 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
3116 req_size, p_props.memoryTypeBits, host_mapped[i],
3117 host_mapped[i] ? &create_desc : NULL,
3118 host_mapped[i] ? &import_desc : NULL);
3124 /* Map, copy image to buffer, unmap */
3125 if ((err = map_buffers(dev_ctx, bufs, tmp.data, planes, 0)))
3128 for (int i = 0; i < planes; i++) {
3132 get_plane_wh(&p_w, &p_h, swf->format, swf->width, swf->height, i);
3134 av_image_copy_plane(tmp.data[i], tmp.linesize[i],
3135 (const uint8_t *)swf->data[i], swf->linesize[i],
3136 FFMIN(tmp.linesize[i], FFABS(swf->linesize[i])),
3140 if ((err = unmap_buffers(dev_ctx, bufs, planes, 1)))
3144 /* Copy buffers into/from image */
3145 err = transfer_image_buf(hwfc, vkf, bufs, buf_offsets, tmp.linesize,
3146 swf->width, swf->height, swf->format, from);
3149 /* Map, copy image to buffer, unmap */
3150 if ((err = map_buffers(dev_ctx, bufs, tmp.data, planes, 0)))
3153 for (int i = 0; i < planes; i++) {
3157 get_plane_wh(&p_w, &p_h, swf->format, swf->width, swf->height, i);
3159 av_image_copy_plane(swf->data[i], swf->linesize[i],
3160 (const uint8_t *)tmp.data[i], tmp.linesize[i],
3161 FFMIN(tmp.linesize[i], FFABS(swf->linesize[i])),
3165 if ((err = unmap_buffers(dev_ctx, bufs, planes, 1)))
3170 for (int i = 0; i < planes; i++)
3171 av_buffer_unref(&bufs[i]);
3176 static int vulkan_transfer_data_to(AVHWFramesContext *hwfc, AVFrame *dst,
3179 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
3181 switch (src->format) {
3183 case AV_PIX_FMT_CUDA:
3184 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
3185 (p->extensions & EXT_EXTERNAL_FD_SEM))
3186 return vulkan_transfer_data_from_cuda(hwfc, dst, src);
3189 if (src->hw_frames_ctx)
3190 return AVERROR(ENOSYS);
3192 return vulkan_transfer_data(hwfc, dst, src, 0);
3197 static int vulkan_transfer_data_to_cuda(AVHWFramesContext *hwfc, AVFrame *dst,
3204 AVVkFrameInternal *dst_int;
3205 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
3206 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
3208 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)dst->hw_frames_ctx->data;
3209 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
3210 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
3211 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
3212 CudaFunctions *cu = cu_internal->cuda_dl;
3214 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
3216 return AVERROR_EXTERNAL;
3218 dst_f = (AVVkFrame *)src->data[0];
3220 err = vulkan_export_to_cuda(hwfc, dst->hw_frames_ctx, src);
3222 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
3226 dst_int = dst_f->internal;
3228 for (int i = 0; i < planes; i++) {
3229 CUDA_MEMCPY2D cpy = {
3230 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
3231 .dstDevice = (CUdeviceptr)dst->data[i],
3232 .dstPitch = dst->linesize[i],
3235 .srcMemoryType = CU_MEMORYTYPE_ARRAY,
3236 .srcArray = dst_int->cu_array[i],
3240 get_plane_wh(&w, &h, hwfc->sw_format, hwfc->width, hwfc->height, i);
3242 cpy.WidthInBytes = w * desc->comp[i].step;
3245 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
3247 err = AVERROR_EXTERNAL;
3252 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
3254 av_log(hwfc, AV_LOG_VERBOSE, "Transfered Vulkan image to CUDA!\n");
3259 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
3260 vulkan_free_internal(dst_int);
3261 dst_f->internal = NULL;
3262 av_buffer_unref(&dst->buf[0]);
3267 static int vulkan_transfer_data_from(AVHWFramesContext *hwfc, AVFrame *dst,
3270 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
3272 switch (dst->format) {
3274 case AV_PIX_FMT_CUDA:
3275 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
3276 (p->extensions & EXT_EXTERNAL_FD_SEM))
3277 return vulkan_transfer_data_to_cuda(hwfc, dst, src);
3280 if (dst->hw_frames_ctx)
3281 return AVERROR(ENOSYS);
3283 return vulkan_transfer_data(hwfc, src, dst, 1);
3287 static int vulkan_frames_derive_to(AVHWFramesContext *dst_fc,
3288 AVHWFramesContext *src_fc, int flags)
3290 return vulkan_frames_init(dst_fc);
3293 AVVkFrame *av_vk_frame_alloc(void)
3295 return av_mallocz(sizeof(AVVkFrame));
3298 const HWContextType ff_hwcontext_type_vulkan = {
3299 .type = AV_HWDEVICE_TYPE_VULKAN,
3302 .device_hwctx_size = sizeof(AVVulkanDeviceContext),
3303 .device_priv_size = sizeof(VulkanDevicePriv),
3304 .frames_hwctx_size = sizeof(AVVulkanFramesContext),
3305 .frames_priv_size = sizeof(VulkanFramesPriv),
3307 .device_init = &vulkan_device_init,
3308 .device_create = &vulkan_device_create,
3309 .device_derive = &vulkan_device_derive,
3311 .frames_get_constraints = &vulkan_frames_get_constraints,
3312 .frames_init = vulkan_frames_init,
3313 .frames_get_buffer = vulkan_get_buffer,
3314 .frames_uninit = vulkan_frames_uninit,
3316 .transfer_get_formats = vulkan_transfer_get_formats,
3317 .transfer_data_to = vulkan_transfer_data_to,
3318 .transfer_data_from = vulkan_transfer_data_from,
3320 .map_to = vulkan_map_to,
3321 .map_from = vulkan_map_from,
3322 .frames_derive_to = &vulkan_frames_derive_to,
3324 .pix_fmts = (const enum AVPixelFormat []) {