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 int create_frame(AVHWFramesContext *hwfc, AVVkFrame **frame,
1513 VkImageTiling tiling, VkImageUsageFlagBits usage,
1518 AVHWDeviceContext *ctx = hwfc->device_ctx;
1519 VulkanDevicePriv *p = ctx->internal->priv;
1520 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1521 enum AVPixelFormat format = hwfc->sw_format;
1522 const VkFormat *img_fmts = av_vkfmt_from_pixfmt(format);
1523 const int planes = av_pix_fmt_count_planes(format);
1525 VkExportSemaphoreCreateInfo ext_sem_info = {
1526 .sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO,
1527 .handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
1530 VkSemaphoreCreateInfo sem_spawn = {
1531 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1532 .pNext = p->extensions & EXT_EXTERNAL_FD_SEM ? &ext_sem_info : NULL,
1535 AVVkFrame *f = av_vk_frame_alloc();
1537 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1538 return AVERROR(ENOMEM);
1541 /* Create the images */
1542 for (int i = 0; i < planes; i++) {
1543 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
1544 int w = hwfc->width;
1545 int h = hwfc->height;
1546 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
1547 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
1549 VkImageCreateInfo image_create_info = {
1550 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1551 .pNext = create_pnext,
1552 .imageType = VK_IMAGE_TYPE_2D,
1553 .format = img_fmts[i],
1554 .extent.width = p_w,
1555 .extent.height = p_h,
1559 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1561 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1563 .samples = VK_SAMPLE_COUNT_1_BIT,
1564 .pQueueFamilyIndices = p->qfs,
1565 .queueFamilyIndexCount = p->num_qfs,
1566 .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
1567 VK_SHARING_MODE_EXCLUSIVE,
1570 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
1571 hwctx->alloc, &f->img[i]);
1572 if (ret != VK_SUCCESS) {
1573 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1575 err = AVERROR(EINVAL);
1579 /* Create semaphore */
1580 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1581 hwctx->alloc, &f->sem[i]);
1582 if (ret != VK_SUCCESS) {
1583 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1585 return AVERROR_EXTERNAL;
1588 f->layout[i] = image_create_info.initialLayout;
1599 vulkan_frame_free(hwfc, (uint8_t *)f);
1603 /* Checks if an export flag is enabled, and if it is ORs it with *iexp */
1604 static void try_export_flags(AVHWFramesContext *hwfc,
1605 VkExternalMemoryHandleTypeFlags *comp_handle_types,
1606 VkExternalMemoryHandleTypeFlagBits *iexp,
1607 VkExternalMemoryHandleTypeFlagBits exp)
1610 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1611 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1612 VkExternalImageFormatProperties eprops = {
1613 .sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES_KHR,
1615 VkImageFormatProperties2 props = {
1616 .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,
1619 VkPhysicalDeviceExternalImageFormatInfo enext = {
1620 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
1623 VkPhysicalDeviceImageFormatInfo2 pinfo = {
1624 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1625 .pNext = !exp ? NULL : &enext,
1626 .format = av_vkfmt_from_pixfmt(hwfc->sw_format)[0],
1627 .type = VK_IMAGE_TYPE_2D,
1628 .tiling = hwctx->tiling,
1629 .usage = hwctx->usage,
1630 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1633 ret = vkGetPhysicalDeviceImageFormatProperties2(dev_hwctx->phys_dev,
1635 if (ret == VK_SUCCESS) {
1637 *comp_handle_types |= eprops.externalMemoryProperties.compatibleHandleTypes;
1641 static AVBufferRef *vulkan_pool_alloc(void *opaque, int size)
1645 AVBufferRef *avbuf = NULL;
1646 AVHWFramesContext *hwfc = opaque;
1647 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1648 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1649 VulkanFramesPriv *fp = hwfc->internal->priv;
1650 VkExportMemoryAllocateInfo eminfo[AV_NUM_DATA_POINTERS];
1651 VkExternalMemoryHandleTypeFlags e = 0x0;
1653 VkExternalMemoryImageCreateInfo eiinfo = {
1654 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1655 .pNext = hwctx->create_pnext,
1658 if (p->extensions & EXT_EXTERNAL_FD_MEMORY)
1659 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1660 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT);
1662 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
1663 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1664 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
1666 for (int i = 0; i < av_pix_fmt_count_planes(hwfc->sw_format); i++) {
1667 eminfo[i].sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO;
1668 eminfo[i].pNext = hwctx->alloc_pnext[i];
1669 eminfo[i].handleTypes = e;
1672 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1673 eiinfo.handleTypes ? &eiinfo : NULL);
1677 err = alloc_bind_mem(hwfc, f, eminfo, sizeof(*eminfo));
1681 err = prepare_frame(hwfc, &fp->conv_ctx, f, PREP_MODE_WRITE);
1685 avbuf = av_buffer_create((uint8_t *)f, sizeof(AVVkFrame),
1686 vulkan_frame_free, hwfc, 0);
1693 vulkan_frame_free(hwfc, (uint8_t *)f);
1697 static void vulkan_frames_uninit(AVHWFramesContext *hwfc)
1699 VulkanFramesPriv *fp = hwfc->internal->priv;
1701 free_exec_ctx(hwfc, &fp->conv_ctx);
1702 free_exec_ctx(hwfc, &fp->upload_ctx);
1703 free_exec_ctx(hwfc, &fp->download_ctx);
1706 static int vulkan_frames_init(AVHWFramesContext *hwfc)
1710 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1711 VulkanFramesPriv *fp = hwfc->internal->priv;
1712 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1713 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1715 /* Default pool flags */
1716 hwctx->tiling = hwctx->tiling ? hwctx->tiling : p->use_linear_images ?
1717 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1720 hwctx->usage = DEFAULT_USAGE_FLAGS;
1722 err = create_exec_ctx(hwfc, &fp->conv_ctx,
1723 dev_hwctx->queue_family_comp_index,
1724 GET_QUEUE_COUNT(dev_hwctx, 0, 1, 0));
1728 err = create_exec_ctx(hwfc, &fp->upload_ctx,
1729 dev_hwctx->queue_family_tx_index,
1730 GET_QUEUE_COUNT(dev_hwctx, 0, 0, 1));
1734 err = create_exec_ctx(hwfc, &fp->download_ctx,
1735 dev_hwctx->queue_family_tx_index, 1);
1739 /* Test to see if allocation will fail */
1740 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1741 hwctx->create_pnext);
1745 vulkan_frame_free(hwfc, (uint8_t *)f);
1747 /* If user did not specify a pool, hwfc->pool will be set to the internal one
1748 * in hwcontext.c just after this gets called */
1750 hwfc->internal->pool_internal = av_buffer_pool_init2(sizeof(AVVkFrame),
1751 hwfc, vulkan_pool_alloc,
1753 if (!hwfc->internal->pool_internal)
1754 return AVERROR(ENOMEM);
1760 static int vulkan_get_buffer(AVHWFramesContext *hwfc, AVFrame *frame)
1762 frame->buf[0] = av_buffer_pool_get(hwfc->pool);
1764 return AVERROR(ENOMEM);
1766 frame->data[0] = frame->buf[0]->data;
1767 frame->format = AV_PIX_FMT_VULKAN;
1768 frame->width = hwfc->width;
1769 frame->height = hwfc->height;
1774 static int vulkan_transfer_get_formats(AVHWFramesContext *hwfc,
1775 enum AVHWFrameTransferDirection dir,
1776 enum AVPixelFormat **formats)
1778 enum AVPixelFormat *fmts = av_malloc_array(2, sizeof(*fmts));
1780 return AVERROR(ENOMEM);
1782 fmts[0] = hwfc->sw_format;
1783 fmts[1] = AV_PIX_FMT_NONE;
1789 typedef struct VulkanMapping {
1794 static void vulkan_unmap_frame(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1796 VulkanMapping *map = hwmap->priv;
1797 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1798 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1800 /* Check if buffer needs flushing */
1801 if ((map->flags & AV_HWFRAME_MAP_WRITE) &&
1802 !(map->frame->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1804 VkMappedMemoryRange flush_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1806 for (int i = 0; i < planes; i++) {
1807 flush_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1808 flush_ranges[i].memory = map->frame->mem[i];
1809 flush_ranges[i].size = VK_WHOLE_SIZE;
1812 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, planes,
1814 if (ret != VK_SUCCESS) {
1815 av_log(hwfc, AV_LOG_ERROR, "Failed to flush memory: %s\n",
1820 for (int i = 0; i < planes; i++)
1821 vkUnmapMemory(hwctx->act_dev, map->frame->mem[i]);
1826 static int vulkan_map_frame_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
1827 const AVFrame *src, int flags)
1830 int err, mapped_mem_count = 0;
1831 AVVkFrame *f = (AVVkFrame *)src->data[0];
1832 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1833 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1835 VulkanMapping *map = av_mallocz(sizeof(VulkanMapping));
1837 return AVERROR(EINVAL);
1839 if (src->format != AV_PIX_FMT_VULKAN) {
1840 av_log(hwfc, AV_LOG_ERROR, "Cannot map from pixel format %s!\n",
1841 av_get_pix_fmt_name(src->format));
1842 err = AVERROR(EINVAL);
1846 if (!(f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ||
1847 !(f->tiling == VK_IMAGE_TILING_LINEAR)) {
1848 av_log(hwfc, AV_LOG_ERROR, "Unable to map frame, not host visible "
1850 err = AVERROR(EINVAL);
1854 dst->width = src->width;
1855 dst->height = src->height;
1857 for (int i = 0; i < planes; i++) {
1858 ret = vkMapMemory(hwctx->act_dev, f->mem[i], 0,
1859 VK_WHOLE_SIZE, 0, (void **)&dst->data[i]);
1860 if (ret != VK_SUCCESS) {
1861 av_log(hwfc, AV_LOG_ERROR, "Failed to map image memory: %s\n",
1863 err = AVERROR_EXTERNAL;
1869 /* Check if the memory contents matter */
1870 if (((flags & AV_HWFRAME_MAP_READ) || !(flags & AV_HWFRAME_MAP_OVERWRITE)) &&
1871 !(f->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1872 VkMappedMemoryRange map_mem_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1873 for (int i = 0; i < planes; i++) {
1874 map_mem_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1875 map_mem_ranges[i].size = VK_WHOLE_SIZE;
1876 map_mem_ranges[i].memory = f->mem[i];
1879 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, planes,
1881 if (ret != VK_SUCCESS) {
1882 av_log(hwfc, AV_LOG_ERROR, "Failed to invalidate memory: %s\n",
1884 err = AVERROR_EXTERNAL;
1889 for (int i = 0; i < planes; i++) {
1890 VkImageSubresource sub = {
1891 .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
1893 VkSubresourceLayout layout;
1894 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
1895 dst->linesize[i] = layout.rowPitch;
1901 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src,
1902 &vulkan_unmap_frame, map);
1909 for (int i = 0; i < mapped_mem_count; i++)
1910 vkUnmapMemory(hwctx->act_dev, f->mem[i]);
1917 static void vulkan_unmap_from(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1919 VulkanMapping *map = hwmap->priv;
1920 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1921 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1923 for (int i = 0; i < planes; i++) {
1924 vkDestroyImage(hwctx->act_dev, map->frame->img[i], hwctx->alloc);
1925 vkFreeMemory(hwctx->act_dev, map->frame->mem[i], hwctx->alloc);
1926 vkDestroySemaphore(hwctx->act_dev, map->frame->sem[i], hwctx->alloc);
1929 av_freep(&map->frame);
1932 static const struct {
1933 uint32_t drm_fourcc;
1935 } vulkan_drm_format_map[] = {
1936 { DRM_FORMAT_R8, VK_FORMAT_R8_UNORM },
1937 { DRM_FORMAT_R16, VK_FORMAT_R16_UNORM },
1938 { DRM_FORMAT_GR88, VK_FORMAT_R8G8_UNORM },
1939 { DRM_FORMAT_RG88, VK_FORMAT_R8G8_UNORM },
1940 { DRM_FORMAT_GR1616, VK_FORMAT_R16G16_UNORM },
1941 { DRM_FORMAT_RG1616, VK_FORMAT_R16G16_UNORM },
1942 { DRM_FORMAT_ARGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1943 { DRM_FORMAT_XRGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1944 { DRM_FORMAT_ABGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1945 { DRM_FORMAT_XBGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1948 static inline VkFormat drm_to_vulkan_fmt(uint32_t drm_fourcc)
1950 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
1951 if (vulkan_drm_format_map[i].drm_fourcc == drm_fourcc)
1952 return vulkan_drm_format_map[i].vk_format;
1953 return VK_FORMAT_UNDEFINED;
1956 static int vulkan_map_from_drm_frame_desc(AVHWFramesContext *hwfc, AVVkFrame **frame,
1957 AVDRMFrameDescriptor *desc)
1962 int bind_counts = 0;
1963 AVHWDeviceContext *ctx = hwfc->device_ctx;
1964 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1965 VulkanDevicePriv *p = ctx->internal->priv;
1966 VulkanFramesPriv *fp = hwfc->internal->priv;
1967 AVVulkanFramesContext *frames_hwctx = hwfc->hwctx;
1968 const AVPixFmtDescriptor *fmt_desc = av_pix_fmt_desc_get(hwfc->sw_format);
1969 const int has_modifiers = !!(p->extensions & EXT_DRM_MODIFIER_FLAGS);
1970 VkSubresourceLayout plane_data[AV_NUM_DATA_POINTERS] = { 0 };
1971 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { 0 };
1972 VkBindImagePlaneMemoryInfo plane_info[AV_NUM_DATA_POINTERS] = { 0 };
1973 VkExternalMemoryHandleTypeFlagBits htype = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
1975 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdPropertiesKHR);
1977 for (int i = 0; i < desc->nb_layers; i++) {
1978 if (drm_to_vulkan_fmt(desc->layers[i].format) == VK_FORMAT_UNDEFINED) {
1979 av_log(ctx, AV_LOG_ERROR, "Unsupported DMABUF layer format %#08x!\n",
1980 desc->layers[i].format);
1981 return AVERROR(EINVAL);
1985 if (!(f = av_vk_frame_alloc())) {
1986 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1987 err = AVERROR(ENOMEM);
1991 f->tiling = has_modifiers ? VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT :
1992 desc->objects[0].format_modifier == DRM_FORMAT_MOD_LINEAR ?
1993 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1995 for (int i = 0; i < desc->nb_layers; i++) {
1996 const int planes = desc->layers[i].nb_planes;
1997 VkImageDrmFormatModifierExplicitCreateInfoEXT drm_info = {
1998 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
1999 .drmFormatModifier = desc->objects[0].format_modifier,
2000 .drmFormatModifierPlaneCount = planes,
2001 .pPlaneLayouts = (const VkSubresourceLayout *)&plane_data,
2004 VkExternalMemoryImageCreateInfo einfo = {
2005 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
2006 .pNext = has_modifiers ? &drm_info : NULL,
2007 .handleTypes = htype,
2010 VkSemaphoreCreateInfo sem_spawn = {
2011 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
2014 const int p_w = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, fmt_desc->log2_chroma_w) : hwfc->width;
2015 const int p_h = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, fmt_desc->log2_chroma_h) : hwfc->height;
2017 VkImageCreateInfo image_create_info = {
2018 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
2020 .imageType = VK_IMAGE_TYPE_2D,
2021 .format = drm_to_vulkan_fmt(desc->layers[i].format),
2022 .extent.width = p_w,
2023 .extent.height = p_h,
2027 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
2028 .tiling = f->tiling,
2029 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, /* specs say so */
2030 .usage = frames_hwctx->usage,
2031 .samples = VK_SAMPLE_COUNT_1_BIT,
2032 .pQueueFamilyIndices = p->qfs,
2033 .queueFamilyIndexCount = p->num_qfs,
2034 .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
2035 VK_SHARING_MODE_EXCLUSIVE,
2038 for (int j = 0; j < planes; j++) {
2039 plane_data[j].offset = desc->layers[i].planes[j].offset;
2040 plane_data[j].rowPitch = desc->layers[i].planes[j].pitch;
2041 plane_data[j].size = 0; /* The specs say so for all 3 */
2042 plane_data[j].arrayPitch = 0;
2043 plane_data[j].depthPitch = 0;
2047 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
2048 hwctx->alloc, &f->img[i]);
2049 if (ret != VK_SUCCESS) {
2050 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
2052 err = AVERROR(EINVAL);
2056 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
2057 hwctx->alloc, &f->sem[i]);
2058 if (ret != VK_SUCCESS) {
2059 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
2061 return AVERROR_EXTERNAL;
2064 /* We'd import a semaphore onto the one we created using
2065 * vkImportSemaphoreFdKHR but unfortunately neither DRM nor VAAPI
2066 * offer us anything we could import and sync with, so instead
2067 * just signal the semaphore we created. */
2069 f->layout[i] = image_create_info.initialLayout;
2073 for (int i = 0; i < desc->nb_objects; i++) {
2074 int use_ded_mem = 0;
2075 VkMemoryFdPropertiesKHR fdmp = {
2076 .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,
2078 VkMemoryRequirements req = {
2079 .size = desc->objects[i].size,
2081 VkImportMemoryFdInfoKHR idesc = {
2082 .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
2083 .handleType = htype,
2084 .fd = dup(desc->objects[i].fd),
2086 VkMemoryDedicatedAllocateInfo ded_alloc = {
2087 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
2091 ret = pfn_vkGetMemoryFdPropertiesKHR(hwctx->act_dev, htype,
2093 if (ret != VK_SUCCESS) {
2094 av_log(hwfc, AV_LOG_ERROR, "Failed to get FD properties: %s\n",
2096 err = AVERROR_EXTERNAL;
2101 req.memoryTypeBits = fdmp.memoryTypeBits;
2103 /* Dedicated allocation only makes sense if there's a one to one mapping
2104 * between images and the memory backing them, so only check in this
2106 if (desc->nb_layers == desc->nb_objects) {
2107 VkImageMemoryRequirementsInfo2 req_desc = {
2108 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
2111 VkMemoryDedicatedRequirements ded_req = {
2112 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
2114 VkMemoryRequirements2 req2 = {
2115 .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
2119 vkGetImageMemoryRequirements2(hwctx->act_dev, &req_desc, &req2);
2121 use_ded_mem = ded_req.prefersDedicatedAllocation |
2122 ded_req.requiresDedicatedAllocation;
2124 ded_alloc.image = f->img[i];
2127 err = alloc_mem(ctx, &req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
2128 use_ded_mem ? &ded_alloc : ded_alloc.pNext,
2129 &f->flags, &f->mem[i]);
2135 f->size[i] = desc->objects[i].size;
2138 for (int i = 0; i < desc->nb_layers; i++) {
2139 const int planes = desc->layers[i].nb_planes;
2140 const int signal_p = has_modifiers && (planes > 1);
2141 for (int j = 0; j < planes; j++) {
2142 VkImageAspectFlagBits aspect = j == 0 ? VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2143 j == 1 ? VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT :
2144 VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT;
2146 plane_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO;
2147 plane_info[bind_counts].planeAspect = aspect;
2149 bind_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
2150 bind_info[bind_counts].pNext = signal_p ? &plane_info[bind_counts] : NULL;
2151 bind_info[bind_counts].image = f->img[i];
2152 bind_info[bind_counts].memory = f->mem[desc->layers[i].planes[j].object_index];
2153 bind_info[bind_counts].memoryOffset = desc->layers[i].planes[j].offset;
2158 /* Bind the allocated memory to the images */
2159 ret = vkBindImageMemory2(hwctx->act_dev, bind_counts, bind_info);
2160 if (ret != VK_SUCCESS) {
2161 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
2163 return AVERROR_EXTERNAL;
2166 /* NOTE: This is completely uneccesary and unneeded once we can import
2167 * semaphores from DRM. Otherwise we have to activate the semaphores.
2168 * We're reusing the exec context that's also used for uploads/downloads. */
2169 err = prepare_frame(hwfc, &fp->conv_ctx, f, PREP_MODE_RO_SHADER);
2178 for (int i = 0; i < desc->nb_layers; i++) {
2179 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
2180 vkDestroySemaphore(hwctx->act_dev, f->sem[i], hwctx->alloc);
2182 for (int i = 0; i < desc->nb_objects; i++)
2183 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
2190 static int vulkan_map_from_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2191 const AVFrame *src, int flags)
2195 VulkanMapping *map = NULL;
2197 err = vulkan_map_from_drm_frame_desc(hwfc, &f,
2198 (AVDRMFrameDescriptor *)src->data[0]);
2202 /* The unmapping function will free this */
2203 dst->data[0] = (uint8_t *)f;
2204 dst->width = src->width;
2205 dst->height = src->height;
2207 map = av_mallocz(sizeof(VulkanMapping));
2214 err = ff_hwframe_map_create(dst->hw_frames_ctx, dst, src,
2215 &vulkan_unmap_from, map);
2219 av_log(hwfc, AV_LOG_DEBUG, "Mapped DRM object to Vulkan!\n");
2224 vulkan_frame_free(hwfc->device_ctx->hwctx, (uint8_t *)f);
2230 static int vulkan_map_from_vaapi(AVHWFramesContext *dst_fc,
2231 AVFrame *dst, const AVFrame *src,
2235 AVFrame *tmp = av_frame_alloc();
2236 AVHWFramesContext *vaapi_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2237 AVVAAPIDeviceContext *vaapi_ctx = vaapi_fc->device_ctx->hwctx;
2238 VASurfaceID surface_id = (VASurfaceID)(uintptr_t)src->data[3];
2241 return AVERROR(ENOMEM);
2243 /* We have to sync since like the previous comment said, no semaphores */
2244 vaSyncSurface(vaapi_ctx->display, surface_id);
2246 tmp->format = AV_PIX_FMT_DRM_PRIME;
2248 err = av_hwframe_map(tmp, src, flags);
2252 err = vulkan_map_from_drm(dst_fc, dst, tmp, flags);
2256 err = ff_hwframe_map_replace(dst, src);
2259 av_frame_free(&tmp);
2266 static int vulkan_export_to_cuda(AVHWFramesContext *hwfc,
2267 AVBufferRef *cuda_hwfc,
2268 const AVFrame *frame)
2273 AVVkFrameInternal *dst_int;
2274 AVHWDeviceContext *ctx = hwfc->device_ctx;
2275 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2276 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2277 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2278 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2279 VK_LOAD_PFN(hwctx->inst, vkGetSemaphoreFdKHR);
2281 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)cuda_hwfc->data;
2282 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2283 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2284 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2285 CudaFunctions *cu = cu_internal->cuda_dl;
2286 CUarray_format cufmt = desc->comp[0].depth > 8 ? CU_AD_FORMAT_UNSIGNED_INT16 :
2287 CU_AD_FORMAT_UNSIGNED_INT8;
2289 dst_f = (AVVkFrame *)frame->data[0];
2291 dst_int = dst_f->internal;
2292 if (!dst_int || !dst_int->cuda_fc_ref) {
2293 if (!dst_f->internal)
2294 dst_f->internal = dst_int = av_mallocz(sizeof(*dst_f->internal));
2297 err = AVERROR(ENOMEM);
2301 dst_int->cuda_fc_ref = av_buffer_ref(cuda_hwfc);
2302 if (!dst_int->cuda_fc_ref) {
2303 err = AVERROR(ENOMEM);
2307 for (int i = 0; i < planes; i++) {
2308 CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC tex_desc = {
2311 .Width = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2313 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2317 .NumChannels = 1 + ((planes == 2) && i),
2322 CUDA_EXTERNAL_MEMORY_HANDLE_DESC ext_desc = {
2323 .type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD,
2324 .size = dst_f->size[i],
2326 VkMemoryGetFdInfoKHR export_info = {
2327 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2328 .memory = dst_f->mem[i],
2329 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR,
2331 VkSemaphoreGetFdInfoKHR sem_export = {
2332 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR,
2333 .semaphore = dst_f->sem[i],
2334 .handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
2336 CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC ext_sem_desc = {
2337 .type = CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD,
2340 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2341 &ext_desc.handle.fd);
2342 if (ret != VK_SUCCESS) {
2343 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2344 err = AVERROR_EXTERNAL;
2348 ret = CHECK_CU(cu->cuImportExternalMemory(&dst_int->ext_mem[i], &ext_desc));
2350 err = AVERROR_EXTERNAL;
2354 ret = CHECK_CU(cu->cuExternalMemoryGetMappedMipmappedArray(&dst_int->cu_mma[i],
2355 dst_int->ext_mem[i],
2358 err = AVERROR_EXTERNAL;
2362 ret = CHECK_CU(cu->cuMipmappedArrayGetLevel(&dst_int->cu_array[i],
2363 dst_int->cu_mma[i], 0));
2365 err = AVERROR_EXTERNAL;
2369 ret = pfn_vkGetSemaphoreFdKHR(hwctx->act_dev, &sem_export,
2370 &ext_sem_desc.handle.fd);
2371 if (ret != VK_SUCCESS) {
2372 av_log(ctx, AV_LOG_ERROR, "Failed to export semaphore: %s\n",
2374 err = AVERROR_EXTERNAL;
2378 ret = CHECK_CU(cu->cuImportExternalSemaphore(&dst_int->cu_sem[i],
2381 err = AVERROR_EXTERNAL;
2393 static int vulkan_transfer_data_from_cuda(AVHWFramesContext *hwfc,
2394 AVFrame *dst, const AVFrame *src)
2400 AVVkFrameInternal *dst_int;
2401 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2402 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2404 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2405 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2406 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2407 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2408 CudaFunctions *cu = cu_internal->cuda_dl;
2409 CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS s_w_par[AV_NUM_DATA_POINTERS] = { 0 };
2410 CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS s_s_par[AV_NUM_DATA_POINTERS] = { 0 };
2412 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2414 return AVERROR_EXTERNAL;
2416 dst_f = (AVVkFrame *)dst->data[0];
2418 ret = vulkan_export_to_cuda(hwfc, src->hw_frames_ctx, dst);
2420 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2424 dst_int = dst_f->internal;
2426 ret = CHECK_CU(cu->cuWaitExternalSemaphoresAsync(dst_int->cu_sem, s_w_par,
2427 planes, cuda_dev->stream));
2429 err = AVERROR_EXTERNAL;
2433 for (int i = 0; i < planes; i++) {
2434 CUDA_MEMCPY2D cpy = {
2435 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
2436 .srcDevice = (CUdeviceptr)src->data[i],
2437 .srcPitch = src->linesize[i],
2440 .dstMemoryType = CU_MEMORYTYPE_ARRAY,
2441 .dstArray = dst_int->cu_array[i],
2442 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2443 : hwfc->width) * desc->comp[i].step,
2444 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2448 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2450 err = AVERROR_EXTERNAL;
2455 ret = CHECK_CU(cu->cuSignalExternalSemaphoresAsync(dst_int->cu_sem, s_s_par,
2456 planes, cuda_dev->stream));
2458 err = AVERROR_EXTERNAL;
2462 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2464 av_log(hwfc, AV_LOG_VERBOSE, "Transfered CUDA image to Vulkan!\n");
2469 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2470 vulkan_free_internal(dst_int);
2471 dst_f->internal = NULL;
2472 av_buffer_unref(&dst->buf[0]);
2477 static int vulkan_map_to(AVHWFramesContext *hwfc, AVFrame *dst,
2478 const AVFrame *src, int flags)
2480 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2482 switch (src->format) {
2485 case AV_PIX_FMT_VAAPI:
2486 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2487 return vulkan_map_from_vaapi(hwfc, dst, src, flags);
2489 case AV_PIX_FMT_DRM_PRIME:
2490 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2491 return vulkan_map_from_drm(hwfc, dst, src, flags);
2494 return AVERROR(ENOSYS);
2499 typedef struct VulkanDRMMapping {
2500 AVDRMFrameDescriptor drm_desc;
2504 static void vulkan_unmap_to_drm(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
2506 AVDRMFrameDescriptor *drm_desc = hwmap->priv;
2508 for (int i = 0; i < drm_desc->nb_objects; i++)
2509 close(drm_desc->objects[i].fd);
2514 static inline uint32_t vulkan_fmt_to_drm(VkFormat vkfmt)
2516 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
2517 if (vulkan_drm_format_map[i].vk_format == vkfmt)
2518 return vulkan_drm_format_map[i].drm_fourcc;
2519 return DRM_FORMAT_INVALID;
2522 static int vulkan_map_to_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2523 const AVFrame *src, int flags)
2527 AVVkFrame *f = (AVVkFrame *)src->data[0];
2528 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2529 VulkanFramesPriv *fp = hwfc->internal->priv;
2530 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
2531 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2532 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2533 VkImageDrmFormatModifierPropertiesEXT drm_mod = {
2534 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT,
2537 AVDRMFrameDescriptor *drm_desc = av_mallocz(sizeof(*drm_desc));
2539 return AVERROR(ENOMEM);
2541 err = prepare_frame(hwfc, &fp->conv_ctx, f, PREP_MODE_EXTERNAL_EXPORT);
2545 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src, &vulkan_unmap_to_drm, drm_desc);
2549 if (p->extensions & EXT_DRM_MODIFIER_FLAGS) {
2550 VK_LOAD_PFN(hwctx->inst, vkGetImageDrmFormatModifierPropertiesEXT);
2551 ret = pfn_vkGetImageDrmFormatModifierPropertiesEXT(hwctx->act_dev, f->img[0],
2553 if (ret != VK_SUCCESS) {
2554 av_log(hwfc, AV_LOG_ERROR, "Failed to retrieve DRM format modifier!\n");
2555 err = AVERROR_EXTERNAL;
2560 for (int i = 0; (i < planes) && (f->mem[i]); i++) {
2561 VkMemoryGetFdInfoKHR export_info = {
2562 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2563 .memory = f->mem[i],
2564 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,
2567 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2568 &drm_desc->objects[i].fd);
2569 if (ret != VK_SUCCESS) {
2570 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2571 err = AVERROR_EXTERNAL;
2575 drm_desc->nb_objects++;
2576 drm_desc->objects[i].size = f->size[i];
2577 drm_desc->objects[i].format_modifier = drm_mod.drmFormatModifier;
2580 drm_desc->nb_layers = planes;
2581 for (int i = 0; i < drm_desc->nb_layers; i++) {
2582 VkSubresourceLayout layout;
2583 VkImageSubresource sub = {
2584 .aspectMask = p->extensions & EXT_DRM_MODIFIER_FLAGS ?
2585 VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2586 VK_IMAGE_ASPECT_COLOR_BIT,
2588 VkFormat plane_vkfmt = av_vkfmt_from_pixfmt(hwfc->sw_format)[i];
2590 drm_desc->layers[i].format = vulkan_fmt_to_drm(plane_vkfmt);
2591 drm_desc->layers[i].nb_planes = 1;
2593 if (drm_desc->layers[i].format == DRM_FORMAT_INVALID) {
2594 av_log(hwfc, AV_LOG_ERROR, "Cannot map to DRM layer, unsupported!\n");
2595 err = AVERROR_PATCHWELCOME;
2599 drm_desc->layers[i].planes[0].object_index = FFMIN(i, drm_desc->nb_objects - 1);
2601 if (f->tiling == VK_IMAGE_TILING_OPTIMAL)
2604 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
2605 drm_desc->layers[i].planes[0].offset = layout.offset;
2606 drm_desc->layers[i].planes[0].pitch = layout.rowPitch;
2609 dst->width = src->width;
2610 dst->height = src->height;
2611 dst->data[0] = (uint8_t *)drm_desc;
2613 av_log(hwfc, AV_LOG_VERBOSE, "Mapped AVVkFrame to a DRM object!\n");
2623 static int vulkan_map_to_vaapi(AVHWFramesContext *hwfc, AVFrame *dst,
2624 const AVFrame *src, int flags)
2627 AVFrame *tmp = av_frame_alloc();
2629 return AVERROR(ENOMEM);
2631 tmp->format = AV_PIX_FMT_DRM_PRIME;
2633 err = vulkan_map_to_drm(hwfc, tmp, src, flags);
2637 err = av_hwframe_map(dst, tmp, flags);
2641 err = ff_hwframe_map_replace(dst, src);
2644 av_frame_free(&tmp);
2650 static int vulkan_map_from(AVHWFramesContext *hwfc, AVFrame *dst,
2651 const AVFrame *src, int flags)
2653 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2655 switch (dst->format) {
2657 case AV_PIX_FMT_DRM_PRIME:
2658 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2659 return vulkan_map_to_drm(hwfc, dst, src, flags);
2661 case AV_PIX_FMT_VAAPI:
2662 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2663 return vulkan_map_to_vaapi(hwfc, dst, src, flags);
2667 return vulkan_map_frame_to_mem(hwfc, dst, src, flags);
2671 typedef struct ImageBuffer {
2674 VkMemoryPropertyFlagBits flags;
2678 static void free_buf(void *opaque, uint8_t *data)
2680 AVHWDeviceContext *ctx = opaque;
2681 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2682 ImageBuffer *vkbuf = (ImageBuffer *)data;
2685 vkDestroyBuffer(hwctx->act_dev, vkbuf->buf, hwctx->alloc);
2687 vkFreeMemory(hwctx->act_dev, vkbuf->mem, hwctx->alloc);
2692 static size_t get_req_buffer_size(VulkanDevicePriv *p, int *stride, int height)
2695 *stride = FFALIGN(*stride, p->props.properties.limits.optimalBufferCopyRowPitchAlignment);
2696 size = height*(*stride);
2697 size = FFALIGN(size, p->props.properties.limits.minMemoryMapAlignment);
2701 static int create_buf(AVHWDeviceContext *ctx, AVBufferRef **buf,
2702 VkBufferUsageFlags usage, VkMemoryPropertyFlagBits flags,
2703 size_t size, uint32_t req_memory_bits, int host_mapped,
2704 void *create_pnext, void *alloc_pnext)
2709 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2711 VkBufferCreateInfo buf_spawn = {
2712 .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
2713 .pNext = create_pnext,
2716 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
2719 VkBufferMemoryRequirementsInfo2 req_desc = {
2720 .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2,
2722 VkMemoryDedicatedAllocateInfo ded_alloc = {
2723 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
2724 .pNext = alloc_pnext,
2726 VkMemoryDedicatedRequirements ded_req = {
2727 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
2729 VkMemoryRequirements2 req = {
2730 .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
2734 ImageBuffer *vkbuf = av_mallocz(sizeof(*vkbuf));
2736 return AVERROR(ENOMEM);
2738 vkbuf->mapped_mem = host_mapped;
2740 ret = vkCreateBuffer(hwctx->act_dev, &buf_spawn, NULL, &vkbuf->buf);
2741 if (ret != VK_SUCCESS) {
2742 av_log(ctx, AV_LOG_ERROR, "Failed to create buffer: %s\n",
2744 err = AVERROR_EXTERNAL;
2748 req_desc.buffer = vkbuf->buf;
2750 vkGetBufferMemoryRequirements2(hwctx->act_dev, &req_desc, &req);
2752 /* In case the implementation prefers/requires dedicated allocation */
2753 use_ded_mem = ded_req.prefersDedicatedAllocation |
2754 ded_req.requiresDedicatedAllocation;
2756 ded_alloc.buffer = vkbuf->buf;
2758 /* Additional requirements imposed on us */
2759 if (req_memory_bits)
2760 req.memoryRequirements.memoryTypeBits &= req_memory_bits;
2762 err = alloc_mem(ctx, &req.memoryRequirements, flags,
2763 use_ded_mem ? &ded_alloc : (void *)ded_alloc.pNext,
2764 &vkbuf->flags, &vkbuf->mem);
2768 ret = vkBindBufferMemory(hwctx->act_dev, vkbuf->buf, vkbuf->mem, 0);
2769 if (ret != VK_SUCCESS) {
2770 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory to buffer: %s\n",
2772 err = AVERROR_EXTERNAL;
2776 *buf = av_buffer_create((uint8_t *)vkbuf, sizeof(*vkbuf), free_buf, ctx, 0);
2778 err = AVERROR(ENOMEM);
2785 free_buf(ctx, (uint8_t *)vkbuf);
2789 /* Skips mapping of host mapped buffers but still invalidates them */
2790 static int map_buffers(AVHWDeviceContext *ctx, AVBufferRef **bufs, uint8_t *mem[],
2791 int nb_buffers, int invalidate)
2794 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2795 VkMappedMemoryRange invalidate_ctx[AV_NUM_DATA_POINTERS];
2796 int invalidate_count = 0;
2798 for (int i = 0; i < nb_buffers; i++) {
2799 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2800 if (vkbuf->mapped_mem)
2803 ret = vkMapMemory(hwctx->act_dev, vkbuf->mem, 0,
2804 VK_WHOLE_SIZE, 0, (void **)&mem[i]);
2805 if (ret != VK_SUCCESS) {
2806 av_log(ctx, AV_LOG_ERROR, "Failed to map buffer memory: %s\n",
2808 return AVERROR_EXTERNAL;
2815 for (int i = 0; i < nb_buffers; i++) {
2816 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2817 const VkMappedMemoryRange ival_buf = {
2818 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2819 .memory = vkbuf->mem,
2820 .size = VK_WHOLE_SIZE,
2823 /* For host imported memory Vulkan says to use platform-defined
2824 * sync methods, but doesn't really say not to call flush or invalidate
2825 * on original host pointers. It does explicitly allow to do that on
2826 * host-mapped pointers which are then mapped again using vkMapMemory,
2827 * but known implementations return the original pointers when mapped
2829 if (vkbuf->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2832 invalidate_ctx[invalidate_count++] = ival_buf;
2835 if (invalidate_count) {
2836 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, invalidate_count,
2838 if (ret != VK_SUCCESS)
2839 av_log(ctx, AV_LOG_WARNING, "Failed to invalidate memory: %s\n",
2846 static int unmap_buffers(AVHWDeviceContext *ctx, AVBufferRef **bufs,
2847 int nb_buffers, int flush)
2851 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2852 VkMappedMemoryRange flush_ctx[AV_NUM_DATA_POINTERS];
2853 int flush_count = 0;
2856 for (int i = 0; i < nb_buffers; i++) {
2857 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2858 const VkMappedMemoryRange flush_buf = {
2859 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2860 .memory = vkbuf->mem,
2861 .size = VK_WHOLE_SIZE,
2864 if (vkbuf->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2867 flush_ctx[flush_count++] = flush_buf;
2872 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, flush_count, flush_ctx);
2873 if (ret != VK_SUCCESS) {
2874 av_log(ctx, AV_LOG_ERROR, "Failed to flush memory: %s\n",
2876 err = AVERROR_EXTERNAL; /* We still want to try to unmap them */
2880 for (int i = 0; i < nb_buffers; i++) {
2881 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2882 if (vkbuf->mapped_mem)
2885 vkUnmapMemory(hwctx->act_dev, vkbuf->mem);
2891 static int transfer_image_buf(AVHWFramesContext *hwfc, const AVFrame *f,
2892 AVBufferRef **bufs, size_t *buf_offsets,
2893 const int *buf_stride, int w,
2894 int h, enum AVPixelFormat pix_fmt, int to_buf)
2897 AVVkFrame *frame = (AVVkFrame *)f->data[0];
2898 VulkanFramesPriv *fp = hwfc->internal->priv;
2901 VkPipelineStageFlagBits sem_wait_dst[AV_NUM_DATA_POINTERS];
2903 const int planes = av_pix_fmt_count_planes(pix_fmt);
2904 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2906 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
2907 VulkanExecCtx *ectx = to_buf ? &fp->download_ctx : &fp->upload_ctx;
2908 VkCommandBuffer cmd_buf = get_buf_exec_ctx(hwfc, ectx);
2910 VkSubmitInfo s_info = {
2911 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
2912 .pSignalSemaphores = frame->sem,
2913 .pWaitSemaphores = frame->sem,
2914 .pWaitDstStageMask = sem_wait_dst,
2915 .signalSemaphoreCount = planes,
2916 .waitSemaphoreCount = planes,
2919 if ((err = wait_start_exec_ctx(hwfc, ectx)))
2922 /* Change the image layout to something more optimal for transfers */
2923 for (int i = 0; i < planes; i++) {
2924 VkImageLayout new_layout = to_buf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL :
2925 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
2926 VkAccessFlags new_access = to_buf ? VK_ACCESS_TRANSFER_READ_BIT :
2927 VK_ACCESS_TRANSFER_WRITE_BIT;
2929 sem_wait_dst[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
2931 /* If the layout matches and we have read access skip the barrier */
2932 if ((frame->layout[i] == new_layout) && (frame->access[i] & new_access))
2935 img_bar[bar_num].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
2936 img_bar[bar_num].srcAccessMask = 0x0;
2937 img_bar[bar_num].dstAccessMask = new_access;
2938 img_bar[bar_num].oldLayout = frame->layout[i];
2939 img_bar[bar_num].newLayout = new_layout;
2940 img_bar[bar_num].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2941 img_bar[bar_num].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2942 img_bar[bar_num].image = frame->img[i];
2943 img_bar[bar_num].subresourceRange.levelCount = 1;
2944 img_bar[bar_num].subresourceRange.layerCount = 1;
2945 img_bar[bar_num].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2947 frame->layout[i] = img_bar[bar_num].newLayout;
2948 frame->access[i] = img_bar[bar_num].dstAccessMask;
2954 vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
2955 VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
2956 0, NULL, 0, NULL, bar_num, img_bar);
2958 /* Schedule a copy for each plane */
2959 for (int i = 0; i < planes; i++) {
2960 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2961 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
2962 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
2963 VkBufferImageCopy buf_reg = {
2964 .bufferOffset = buf_offsets[i],
2965 /* Buffer stride isn't in bytes, it's in samples, the implementation
2966 * uses the image's VkFormat to know how many bytes per sample
2967 * the buffer has. So we have to convert by dividing. Stupid.
2968 * Won't work with YUVA or other planar formats with alpha. */
2969 .bufferRowLength = buf_stride[i] / desc->comp[i].step,
2970 .bufferImageHeight = p_h,
2971 .imageSubresource.layerCount = 1,
2972 .imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
2973 .imageOffset = { 0, 0, 0, },
2974 .imageExtent = { p_w, p_h, 1, },
2978 vkCmdCopyImageToBuffer(cmd_buf, frame->img[i], frame->layout[i],
2979 vkbuf->buf, 1, &buf_reg);
2981 vkCmdCopyBufferToImage(cmd_buf, vkbuf->buf, frame->img[i],
2982 frame->layout[i], 1, &buf_reg);
2985 /* When uploading, do this asynchronously if the source is refcounted by
2986 * keeping the buffers as a submission dependency.
2987 * The hwcontext is guaranteed to not be freed until all frames are freed
2988 * in the frames_unint function.
2989 * When downloading to buffer, do this synchronously and wait for the
2990 * queue submission to finish executing */
2993 for (ref = 0; ref < AV_NUM_DATA_POINTERS; ref++) {
2996 if ((err = add_buf_dep_exec_ctx(hwfc, ectx, &f->buf[ref], 1)))
2999 if (ref && (err = add_buf_dep_exec_ctx(hwfc, ectx, bufs, planes)))
3001 return submit_exec_ctx(hwfc, ectx, &s_info, !ref);
3003 return submit_exec_ctx(hwfc, ectx, &s_info, 1);
3007 static int vulkan_transfer_data(AVHWFramesContext *hwfc, const AVFrame *vkf,
3008 const AVFrame *swf, int from)
3012 AVVkFrame *f = (AVVkFrame *)vkf->data[0];
3013 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
3014 AVVulkanDeviceContext *hwctx = dev_ctx->hwctx;
3015 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
3018 AVBufferRef *bufs[AV_NUM_DATA_POINTERS] = { 0 };
3019 size_t buf_offsets[AV_NUM_DATA_POINTERS] = { 0 };
3021 const int planes = av_pix_fmt_count_planes(swf->format);
3022 int log2_chroma = av_pix_fmt_desc_get(swf->format)->log2_chroma_h;
3024 int host_mapped[AV_NUM_DATA_POINTERS] = { 0 };
3025 const int map_host = !!(p->extensions & EXT_EXTERNAL_HOST_MEMORY);
3027 VK_LOAD_PFN(hwctx->inst, vkGetMemoryHostPointerPropertiesEXT);
3029 if ((swf->format != AV_PIX_FMT_NONE && !av_vkfmt_from_pixfmt(swf->format))) {
3030 av_log(hwfc, AV_LOG_ERROR, "Unsupported software frame pixel format!\n");
3031 return AVERROR(EINVAL);
3034 if (swf->width > hwfc->width || swf->height > hwfc->height)
3035 return AVERROR(EINVAL);
3037 /* For linear, host visiable images */
3038 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
3039 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
3040 AVFrame *map = av_frame_alloc();
3042 return AVERROR(ENOMEM);
3043 map->format = swf->format;
3045 err = vulkan_map_frame_to_mem(hwfc, map, vkf, AV_HWFRAME_MAP_WRITE);
3049 err = av_frame_copy((AVFrame *)(from ? swf : map), from ? map : swf);
3050 av_frame_free(&map);
3054 /* Create buffers */
3055 for (int i = 0; i < planes; i++) {
3057 int h = swf->height;
3058 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
3060 VkExternalMemoryBufferCreateInfo create_desc = {
3061 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO,
3062 .handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT,
3065 VkImportMemoryHostPointerInfoEXT import_desc = {
3066 .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT,
3067 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT,
3070 VkMemoryHostPointerPropertiesEXT p_props = {
3071 .sType = VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT,
3074 tmp.linesize[i] = FFABS(swf->linesize[i]);
3076 /* Do not map images with a negative stride */
3077 if (map_host && swf->linesize[i] > 0) {
3079 offs = (uintptr_t)swf->data[i] % p->hprops.minImportedHostPointerAlignment;
3080 import_desc.pHostPointer = swf->data[i] - offs;
3082 /* We have to compensate for the few extra bytes of padding we
3083 * completely ignore at the start */
3084 req_size = FFALIGN(offs + tmp.linesize[i] * p_height,
3085 p->hprops.minImportedHostPointerAlignment);
3087 ret = pfn_vkGetMemoryHostPointerPropertiesEXT(hwctx->act_dev,
3088 import_desc.handleType,
3089 import_desc.pHostPointer,
3092 if (ret == VK_SUCCESS) {
3094 buf_offsets[i] = offs;
3098 if (!host_mapped[i])
3099 req_size = get_req_buffer_size(p, &tmp.linesize[i], p_height);
3101 err = create_buf(dev_ctx, &bufs[i],
3102 from ? VK_BUFFER_USAGE_TRANSFER_DST_BIT :
3103 VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
3104 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
3105 req_size, p_props.memoryTypeBits, host_mapped[i],
3106 host_mapped[i] ? &create_desc : NULL,
3107 host_mapped[i] ? &import_desc : NULL);
3113 /* Map, copy image to buffer, unmap */
3114 if ((err = map_buffers(dev_ctx, bufs, tmp.data, planes, 0)))
3117 for (int i = 0; i < planes; i++) {
3118 int h = swf->height;
3119 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
3124 av_image_copy_plane(tmp.data[i], tmp.linesize[i],
3125 (const uint8_t *)swf->data[i], swf->linesize[i],
3126 FFMIN(tmp.linesize[i], FFABS(swf->linesize[i])),
3130 if ((err = unmap_buffers(dev_ctx, bufs, planes, 1)))
3134 /* Copy buffers into/from image */
3135 err = transfer_image_buf(hwfc, vkf, bufs, buf_offsets, tmp.linesize,
3136 swf->width, swf->height, swf->format, from);
3139 /* Map, copy image to buffer, unmap */
3140 if ((err = map_buffers(dev_ctx, bufs, tmp.data, planes, 0)))
3143 for (int i = 0; i < planes; i++) {
3144 int h = swf->height;
3145 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
3150 av_image_copy_plane(swf->data[i], swf->linesize[i],
3151 (const uint8_t *)tmp.data[i], tmp.linesize[i],
3152 FFMIN(tmp.linesize[i], FFABS(swf->linesize[i])),
3156 if ((err = unmap_buffers(dev_ctx, bufs, planes, 1)))
3161 for (int i = 0; i < planes; i++)
3162 av_buffer_unref(&bufs[i]);
3167 static int vulkan_transfer_data_to(AVHWFramesContext *hwfc, AVFrame *dst,
3170 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
3172 switch (src->format) {
3174 case AV_PIX_FMT_CUDA:
3175 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
3176 (p->extensions & EXT_EXTERNAL_FD_SEM))
3177 return vulkan_transfer_data_from_cuda(hwfc, dst, src);
3180 if (src->hw_frames_ctx)
3181 return AVERROR(ENOSYS);
3183 return vulkan_transfer_data(hwfc, dst, src, 0);
3188 static int vulkan_transfer_data_to_cuda(AVHWFramesContext *hwfc, AVFrame *dst,
3195 AVVkFrameInternal *dst_int;
3196 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
3197 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
3199 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)dst->hw_frames_ctx->data;
3200 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
3201 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
3202 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
3203 CudaFunctions *cu = cu_internal->cuda_dl;
3205 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
3207 return AVERROR_EXTERNAL;
3209 dst_f = (AVVkFrame *)src->data[0];
3211 err = vulkan_export_to_cuda(hwfc, dst->hw_frames_ctx, src);
3213 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
3217 dst_int = dst_f->internal;
3219 for (int i = 0; i < planes; i++) {
3220 CUDA_MEMCPY2D cpy = {
3221 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
3222 .dstDevice = (CUdeviceptr)dst->data[i],
3223 .dstPitch = dst->linesize[i],
3226 .srcMemoryType = CU_MEMORYTYPE_ARRAY,
3227 .srcArray = dst_int->cu_array[i],
3228 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
3229 : hwfc->width) * desc->comp[i].step,
3230 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
3234 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
3236 err = AVERROR_EXTERNAL;
3241 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
3243 av_log(hwfc, AV_LOG_VERBOSE, "Transfered Vulkan image to CUDA!\n");
3248 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
3249 vulkan_free_internal(dst_int);
3250 dst_f->internal = NULL;
3251 av_buffer_unref(&dst->buf[0]);
3256 static int vulkan_transfer_data_from(AVHWFramesContext *hwfc, AVFrame *dst,
3259 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
3261 switch (dst->format) {
3263 case AV_PIX_FMT_CUDA:
3264 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
3265 (p->extensions & EXT_EXTERNAL_FD_SEM))
3266 return vulkan_transfer_data_to_cuda(hwfc, dst, src);
3269 if (dst->hw_frames_ctx)
3270 return AVERROR(ENOSYS);
3272 return vulkan_transfer_data(hwfc, src, dst, 1);
3276 static int vulkan_frames_derive_to(AVHWFramesContext *dst_fc,
3277 AVHWFramesContext *src_fc, int flags)
3279 return vulkan_frames_init(dst_fc);
3282 AVVkFrame *av_vk_frame_alloc(void)
3284 return av_mallocz(sizeof(AVVkFrame));
3287 const HWContextType ff_hwcontext_type_vulkan = {
3288 .type = AV_HWDEVICE_TYPE_VULKAN,
3291 .device_hwctx_size = sizeof(AVVulkanDeviceContext),
3292 .device_priv_size = sizeof(VulkanDevicePriv),
3293 .frames_hwctx_size = sizeof(AVVulkanFramesContext),
3294 .frames_priv_size = sizeof(VulkanFramesPriv),
3296 .device_init = &vulkan_device_init,
3297 .device_create = &vulkan_device_create,
3298 .device_derive = &vulkan_device_derive,
3300 .frames_get_constraints = &vulkan_frames_get_constraints,
3301 .frames_init = vulkan_frames_init,
3302 .frames_get_buffer = vulkan_get_buffer,
3303 .frames_uninit = vulkan_frames_uninit,
3305 .transfer_get_formats = vulkan_transfer_get_formats,
3306 .transfer_data_to = vulkan_transfer_data_to,
3307 .transfer_data_from = vulkan_transfer_data_from,
3309 .map_to = vulkan_map_to,
3310 .map_from = vulkan_map_from,
3311 .frames_derive_to = &vulkan_frames_derive_to,
3313 .pix_fmts = (const enum AVPixelFormat []) {