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 cmd->queues = av_mallocz(num_queues * sizeof(*cmd->queues));
757 return AVERROR(ENOMEM);
759 cmd->bufs = av_mallocz(num_queues * sizeof(*cmd->bufs));
761 return AVERROR(ENOMEM);
763 /* Create command pool */
764 ret = vkCreateCommandPool(hwctx->act_dev, &cqueue_create,
765 hwctx->alloc, &cmd->pool);
766 if (ret != VK_SUCCESS) {
767 av_log(hwfc, AV_LOG_ERROR, "Command pool creation failure: %s\n",
769 return AVERROR_EXTERNAL;
772 cbuf_create.commandPool = cmd->pool;
774 /* Allocate command buffer */
775 ret = vkAllocateCommandBuffers(hwctx->act_dev, &cbuf_create, cmd->bufs);
776 if (ret != VK_SUCCESS) {
777 av_log(hwfc, AV_LOG_ERROR, "Command buffer alloc failure: %s\n",
779 return AVERROR_EXTERNAL;
782 for (int i = 0; i < num_queues; i++) {
783 VulkanQueueCtx *q = &cmd->queues[i];
784 vkGetDeviceQueue(hwctx->act_dev, queue_family_index, i, &q->queue);
785 q->was_synchronous = 1;
791 static void free_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd)
793 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
795 /* Make sure all queues have finished executing */
796 for (int i = 0; i < cmd->nb_queues; i++) {
797 VulkanQueueCtx *q = &cmd->queues[i];
799 if (q->fence && !q->was_synchronous) {
800 vkWaitForFences(hwctx->act_dev, 1, &q->fence, VK_TRUE, UINT64_MAX);
801 vkResetFences(hwctx->act_dev, 1, &q->fence);
806 vkDestroyFence(hwctx->act_dev, q->fence, hwctx->alloc);
808 /* Free buffer dependencies */
809 for (int j = 0; j < q->nb_buf_deps; j++)
810 av_buffer_unref(&q->buf_deps[j]);
811 av_free(q->buf_deps);
815 vkFreeCommandBuffers(hwctx->act_dev, cmd->pool, cmd->nb_queues, cmd->bufs);
817 vkDestroyCommandPool(hwctx->act_dev, cmd->pool, hwctx->alloc);
819 av_freep(&cmd->bufs);
820 av_freep(&cmd->queues);
823 static VkCommandBuffer get_buf_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd)
825 return cmd->bufs[cmd->cur_queue_idx];
828 static void unref_exec_ctx_deps(AVHWFramesContext *hwfc, VulkanExecCtx *cmd)
830 VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
832 for (int j = 0; j < q->nb_buf_deps; j++)
833 av_buffer_unref(&q->buf_deps[j]);
837 static int wait_start_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd)
840 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
841 VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
843 VkCommandBufferBeginInfo cmd_start = {
844 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
845 .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
848 /* Create the fence and don't wait for it initially */
850 VkFenceCreateInfo fence_spawn = {
851 .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
853 ret = vkCreateFence(hwctx->act_dev, &fence_spawn, hwctx->alloc,
855 if (ret != VK_SUCCESS) {
856 av_log(hwfc, AV_LOG_ERROR, "Failed to queue frame fence: %s\n",
858 return AVERROR_EXTERNAL;
860 } else if (!q->was_synchronous) {
861 vkWaitForFences(hwctx->act_dev, 1, &q->fence, VK_TRUE, UINT64_MAX);
862 vkResetFences(hwctx->act_dev, 1, &q->fence);
865 /* Discard queue dependencies */
866 unref_exec_ctx_deps(hwfc, cmd);
868 ret = vkBeginCommandBuffer(cmd->bufs[cmd->cur_queue_idx], &cmd_start);
869 if (ret != VK_SUCCESS) {
870 av_log(hwfc, AV_LOG_ERROR, "Unable to init command buffer: %s\n",
872 return AVERROR_EXTERNAL;
878 static int add_buf_dep_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd,
879 AVBufferRef * const *deps, int nb_deps)
882 VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
884 if (!deps || !nb_deps)
887 dst = av_fast_realloc(q->buf_deps, &q->buf_deps_alloc_size,
888 (q->nb_buf_deps + nb_deps) * sizeof(*dst));
894 for (int i = 0; i < nb_deps; i++) {
895 q->buf_deps[q->nb_buf_deps] = av_buffer_ref(deps[i]);
896 if (!q->buf_deps[q->nb_buf_deps])
904 unref_exec_ctx_deps(hwfc, cmd);
905 return AVERROR(ENOMEM);
908 static int submit_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd,
909 VkSubmitInfo *s_info, int synchronous)
912 VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
914 ret = vkEndCommandBuffer(cmd->bufs[cmd->cur_queue_idx]);
915 if (ret != VK_SUCCESS) {
916 av_log(hwfc, AV_LOG_ERROR, "Unable to finish command buffer: %s\n",
918 unref_exec_ctx_deps(hwfc, cmd);
919 return AVERROR_EXTERNAL;
922 s_info->pCommandBuffers = &cmd->bufs[cmd->cur_queue_idx];
923 s_info->commandBufferCount = 1;
925 ret = vkQueueSubmit(q->queue, 1, s_info, q->fence);
926 if (ret != VK_SUCCESS) {
927 unref_exec_ctx_deps(hwfc, cmd);
928 return AVERROR_EXTERNAL;
931 q->was_synchronous = synchronous;
934 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
935 vkWaitForFences(hwctx->act_dev, 1, &q->fence, VK_TRUE, UINT64_MAX);
936 vkResetFences(hwctx->act_dev, 1, &q->fence);
937 unref_exec_ctx_deps(hwfc, cmd);
938 } else { /* Rotate queues */
939 cmd->cur_queue_idx = (cmd->cur_queue_idx + 1) % cmd->nb_queues;
945 static void vulkan_device_free(AVHWDeviceContext *ctx)
947 VulkanDevicePriv *p = ctx->internal->priv;
948 AVVulkanDeviceContext *hwctx = ctx->hwctx;
950 vkDestroyDevice(hwctx->act_dev, hwctx->alloc);
953 VK_LOAD_PFN(hwctx->inst, vkDestroyDebugUtilsMessengerEXT);
954 pfn_vkDestroyDebugUtilsMessengerEXT(hwctx->inst, p->debug_ctx,
958 vkDestroyInstance(hwctx->inst, hwctx->alloc);
960 for (int i = 0; i < hwctx->nb_enabled_inst_extensions; i++)
961 av_free((void *)hwctx->enabled_inst_extensions[i]);
962 av_free((void *)hwctx->enabled_inst_extensions);
964 for (int i = 0; i < hwctx->nb_enabled_dev_extensions; i++)
965 av_free((void *)hwctx->enabled_dev_extensions[i]);
966 av_free((void *)hwctx->enabled_dev_extensions);
969 static int vulkan_device_create_internal(AVHWDeviceContext *ctx,
970 VulkanDeviceSelection *dev_select,
971 AVDictionary *opts, int flags)
975 AVDictionaryEntry *opt_d;
976 VulkanDevicePriv *p = ctx->internal->priv;
977 AVVulkanDeviceContext *hwctx = ctx->hwctx;
978 VkPhysicalDeviceFeatures dev_features = { 0 };
979 VkDeviceQueueCreateInfo queue_create_info[3] = {
980 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, },
981 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, },
982 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, },
985 VkDeviceCreateInfo dev_info = {
986 .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
987 .pNext = &hwctx->device_features,
988 .pQueueCreateInfos = queue_create_info,
989 .queueCreateInfoCount = 0,
992 hwctx->device_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
993 ctx->free = vulkan_device_free;
995 /* Create an instance if not given one */
996 if ((err = create_instance(ctx, opts)))
999 /* Find a device (if not given one) */
1000 if ((err = find_device(ctx, dev_select)))
1003 vkGetPhysicalDeviceFeatures(hwctx->phys_dev, &dev_features);
1004 #define COPY_FEATURE(DST, NAME) (DST).features.NAME = dev_features.NAME;
1005 COPY_FEATURE(hwctx->device_features, shaderImageGatherExtended)
1006 COPY_FEATURE(hwctx->device_features, fragmentStoresAndAtomics)
1007 COPY_FEATURE(hwctx->device_features, vertexPipelineStoresAndAtomics)
1008 COPY_FEATURE(hwctx->device_features, shaderInt64)
1011 /* Search queue family */
1012 if ((err = search_queue_families(ctx, &dev_info)))
1015 if ((err = check_extensions(ctx, 1, opts, &dev_info.ppEnabledExtensionNames,
1016 &dev_info.enabledExtensionCount, 0))) {
1017 av_free((void *)queue_create_info[0].pQueuePriorities);
1018 av_free((void *)queue_create_info[1].pQueuePriorities);
1019 av_free((void *)queue_create_info[2].pQueuePriorities);
1023 ret = vkCreateDevice(hwctx->phys_dev, &dev_info, hwctx->alloc,
1026 av_free((void *)queue_create_info[0].pQueuePriorities);
1027 av_free((void *)queue_create_info[1].pQueuePriorities);
1028 av_free((void *)queue_create_info[2].pQueuePriorities);
1030 if (ret != VK_SUCCESS) {
1031 av_log(ctx, AV_LOG_ERROR, "Device creation failure: %s\n",
1033 for (int i = 0; i < dev_info.enabledExtensionCount; i++)
1034 av_free((void *)dev_info.ppEnabledExtensionNames[i]);
1035 av_free((void *)dev_info.ppEnabledExtensionNames);
1036 err = AVERROR_EXTERNAL;
1040 /* Tiled images setting, use them by default */
1041 opt_d = av_dict_get(opts, "linear_images", NULL, 0);
1043 p->use_linear_images = strtol(opt_d->value, NULL, 10);
1045 hwctx->enabled_dev_extensions = dev_info.ppEnabledExtensionNames;
1046 hwctx->nb_enabled_dev_extensions = dev_info.enabledExtensionCount;
1052 static int vulkan_device_init(AVHWDeviceContext *ctx)
1055 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1056 VulkanDevicePriv *p = ctx->internal->priv;
1058 /* Set device extension flags */
1059 for (int i = 0; i < hwctx->nb_enabled_dev_extensions; i++) {
1060 for (int j = 0; j < FF_ARRAY_ELEMS(optional_device_exts); j++) {
1061 if (!strcmp(hwctx->enabled_dev_extensions[i],
1062 optional_device_exts[j].name)) {
1063 av_log(ctx, AV_LOG_VERBOSE, "Using device extension %s\n",
1064 hwctx->enabled_dev_extensions[i]);
1065 p->extensions |= optional_device_exts[j].flag;
1071 p->props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
1072 p->props.pNext = &p->hprops;
1073 p->hprops.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT;
1075 vkGetPhysicalDeviceProperties2(hwctx->phys_dev, &p->props);
1076 av_log(ctx, AV_LOG_VERBOSE, "Using device: %s\n",
1077 p->props.properties.deviceName);
1078 av_log(ctx, AV_LOG_VERBOSE, "Alignments:\n");
1079 av_log(ctx, AV_LOG_VERBOSE, " optimalBufferCopyRowPitchAlignment: %li\n",
1080 p->props.properties.limits.optimalBufferCopyRowPitchAlignment);
1081 av_log(ctx, AV_LOG_VERBOSE, " minMemoryMapAlignment: %li\n",
1082 p->props.properties.limits.minMemoryMapAlignment);
1083 if (p->extensions & EXT_EXTERNAL_HOST_MEMORY)
1084 av_log(ctx, AV_LOG_VERBOSE, " minImportedHostPointerAlignment: %li\n",
1085 p->hprops.minImportedHostPointerAlignment);
1087 p->dev_is_nvidia = (p->props.properties.vendorID == 0x10de);
1089 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &queue_num, NULL);
1091 av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
1092 return AVERROR_EXTERNAL;
1095 #define CHECK_QUEUE(type, n) \
1096 if (n >= queue_num) { \
1097 av_log(ctx, AV_LOG_ERROR, "Invalid %s queue index %i (device has %i queues)!\n", \
1098 type, n, queue_num); \
1099 return AVERROR(EINVAL); \
1102 CHECK_QUEUE("graphics", hwctx->queue_family_index)
1103 CHECK_QUEUE("upload", hwctx->queue_family_tx_index)
1104 CHECK_QUEUE("compute", hwctx->queue_family_comp_index)
1108 p->qfs[p->num_qfs++] = hwctx->queue_family_index;
1109 if ((hwctx->queue_family_tx_index != hwctx->queue_family_index) &&
1110 (hwctx->queue_family_tx_index != hwctx->queue_family_comp_index))
1111 p->qfs[p->num_qfs++] = hwctx->queue_family_tx_index;
1112 if ((hwctx->queue_family_comp_index != hwctx->queue_family_index) &&
1113 (hwctx->queue_family_comp_index != hwctx->queue_family_tx_index))
1114 p->qfs[p->num_qfs++] = hwctx->queue_family_comp_index;
1116 /* Get device capabilities */
1117 vkGetPhysicalDeviceMemoryProperties(hwctx->phys_dev, &p->mprops);
1122 static int vulkan_device_create(AVHWDeviceContext *ctx, const char *device,
1123 AVDictionary *opts, int flags)
1125 VulkanDeviceSelection dev_select = { 0 };
1126 if (device && device[0]) {
1128 dev_select.index = strtol(device, &end, 10);
1129 if (end == device) {
1130 dev_select.index = 0;
1131 dev_select.name = device;
1135 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1138 static int vulkan_device_derive(AVHWDeviceContext *ctx,
1139 AVHWDeviceContext *src_ctx,
1140 AVDictionary *opts, int flags)
1142 av_unused VulkanDeviceSelection dev_select = { 0 };
1144 /* If there's only one device on the system, then even if its not covered
1145 * by the following checks (e.g. non-PCIe ARM GPU), having an empty
1146 * dev_select will mean it'll get picked. */
1147 switch(src_ctx->type) {
1150 case AV_HWDEVICE_TYPE_VAAPI: {
1151 AVVAAPIDeviceContext *src_hwctx = src_ctx->hwctx;
1153 const char *vendor = vaQueryVendorString(src_hwctx->display);
1155 av_log(ctx, AV_LOG_ERROR, "Unable to get device info from VAAPI!\n");
1156 return AVERROR_EXTERNAL;
1159 if (strstr(vendor, "Intel"))
1160 dev_select.vendor_id = 0x8086;
1161 if (strstr(vendor, "AMD"))
1162 dev_select.vendor_id = 0x1002;
1164 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1167 case AV_HWDEVICE_TYPE_DRM: {
1168 AVDRMDeviceContext *src_hwctx = src_ctx->hwctx;
1170 drmDevice *drm_dev_info;
1171 int err = drmGetDevice(src_hwctx->fd, &drm_dev_info);
1173 av_log(ctx, AV_LOG_ERROR, "Unable to get device info from DRM fd!\n");
1174 return AVERROR_EXTERNAL;
1177 if (drm_dev_info->bustype == DRM_BUS_PCI)
1178 dev_select.pci_device = drm_dev_info->deviceinfo.pci->device_id;
1180 drmFreeDevice(&drm_dev_info);
1182 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1186 case AV_HWDEVICE_TYPE_CUDA: {
1187 AVHWDeviceContext *cuda_cu = src_ctx;
1188 AVCUDADeviceContext *src_hwctx = src_ctx->hwctx;
1189 AVCUDADeviceContextInternal *cu_internal = src_hwctx->internal;
1190 CudaFunctions *cu = cu_internal->cuda_dl;
1192 int ret = CHECK_CU(cu->cuDeviceGetUuid((CUuuid *)&dev_select.uuid,
1193 cu_internal->cuda_device));
1195 av_log(ctx, AV_LOG_ERROR, "Unable to get UUID from CUDA!\n");
1196 return AVERROR_EXTERNAL;
1199 dev_select.has_uuid = 1;
1201 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1205 return AVERROR(ENOSYS);
1209 static int vulkan_frames_get_constraints(AVHWDeviceContext *ctx,
1210 const void *hwconfig,
1211 AVHWFramesConstraints *constraints)
1214 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1215 VulkanDevicePriv *p = ctx->internal->priv;
1217 for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
1218 count += pixfmt_is_supported(hwctx, i, p->use_linear_images);
1221 if (p->dev_is_nvidia)
1225 constraints->valid_sw_formats = av_malloc_array(count + 1,
1226 sizeof(enum AVPixelFormat));
1227 if (!constraints->valid_sw_formats)
1228 return AVERROR(ENOMEM);
1231 for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
1232 if (pixfmt_is_supported(hwctx, i, p->use_linear_images))
1233 constraints->valid_sw_formats[count++] = i;
1236 if (p->dev_is_nvidia)
1237 constraints->valid_sw_formats[count++] = AV_PIX_FMT_CUDA;
1239 constraints->valid_sw_formats[count++] = AV_PIX_FMT_NONE;
1241 constraints->min_width = 0;
1242 constraints->min_height = 0;
1243 constraints->max_width = p->props.properties.limits.maxImageDimension2D;
1244 constraints->max_height = p->props.properties.limits.maxImageDimension2D;
1246 constraints->valid_hw_formats = av_malloc_array(2, sizeof(enum AVPixelFormat));
1247 if (!constraints->valid_hw_formats)
1248 return AVERROR(ENOMEM);
1250 constraints->valid_hw_formats[0] = AV_PIX_FMT_VULKAN;
1251 constraints->valid_hw_formats[1] = AV_PIX_FMT_NONE;
1256 static int alloc_mem(AVHWDeviceContext *ctx, VkMemoryRequirements *req,
1257 VkMemoryPropertyFlagBits req_flags, const void *alloc_extension,
1258 VkMemoryPropertyFlagBits *mem_flags, VkDeviceMemory *mem)
1262 VulkanDevicePriv *p = ctx->internal->priv;
1263 AVVulkanDeviceContext *dev_hwctx = ctx->hwctx;
1264 VkMemoryAllocateInfo alloc_info = {
1265 .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
1266 .pNext = alloc_extension,
1267 .allocationSize = req->size,
1270 /* The vulkan spec requires memory types to be sorted in the "optimal"
1271 * order, so the first matching type we find will be the best/fastest one */
1272 for (int i = 0; i < p->mprops.memoryTypeCount; i++) {
1273 const VkMemoryType *type = &p->mprops.memoryTypes[i];
1275 /* The memory type must be supported by the requirements (bitfield) */
1276 if (!(req->memoryTypeBits & (1 << i)))
1279 /* The memory type flags must include our properties */
1280 if ((type->propertyFlags & req_flags) != req_flags)
1283 /* The memory type must be large enough */
1284 if (req->size > p->mprops.memoryHeaps[type->heapIndex].size)
1287 /* Found a suitable memory type */
1293 av_log(ctx, AV_LOG_ERROR, "No memory type found for flags 0x%x\n",
1295 return AVERROR(EINVAL);
1298 alloc_info.memoryTypeIndex = index;
1300 ret = vkAllocateMemory(dev_hwctx->act_dev, &alloc_info,
1301 dev_hwctx->alloc, mem);
1302 if (ret != VK_SUCCESS) {
1303 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory: %s\n",
1305 return AVERROR(ENOMEM);
1308 *mem_flags |= p->mprops.memoryTypes[index].propertyFlags;
1313 static void vulkan_free_internal(AVVkFrameInternal *internal)
1319 if (internal->cuda_fc_ref) {
1320 AVHWFramesContext *cuda_fc = (AVHWFramesContext *)internal->cuda_fc_ref->data;
1321 int planes = av_pix_fmt_count_planes(cuda_fc->sw_format);
1322 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
1323 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
1324 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
1325 CudaFunctions *cu = cu_internal->cuda_dl;
1327 for (int i = 0; i < planes; i++) {
1328 if (internal->cu_sem[i])
1329 CHECK_CU(cu->cuDestroyExternalSemaphore(internal->cu_sem[i]));
1330 if (internal->cu_mma[i])
1331 CHECK_CU(cu->cuMipmappedArrayDestroy(internal->cu_mma[i]));
1332 if (internal->ext_mem[i])
1333 CHECK_CU(cu->cuDestroyExternalMemory(internal->ext_mem[i]));
1336 av_buffer_unref(&internal->cuda_fc_ref);
1343 static void vulkan_frame_free(void *opaque, uint8_t *data)
1345 AVVkFrame *f = (AVVkFrame *)data;
1346 AVHWFramesContext *hwfc = opaque;
1347 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1348 int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1350 vulkan_free_internal(f->internal);
1352 for (int i = 0; i < planes; i++) {
1353 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
1354 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
1355 vkDestroySemaphore(hwctx->act_dev, f->sem[i], hwctx->alloc);
1361 static int alloc_bind_mem(AVHWFramesContext *hwfc, AVVkFrame *f,
1362 void *alloc_pnext, size_t alloc_pnext_stride)
1366 AVHWDeviceContext *ctx = hwfc->device_ctx;
1367 VulkanDevicePriv *p = ctx->internal->priv;
1368 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1369 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { { 0 } };
1371 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1373 for (int i = 0; i < planes; i++) {
1375 VkImageMemoryRequirementsInfo2 req_desc = {
1376 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
1379 VkMemoryDedicatedAllocateInfo ded_alloc = {
1380 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
1381 .pNext = (void *)(((uint8_t *)alloc_pnext) + i*alloc_pnext_stride),
1383 VkMemoryDedicatedRequirements ded_req = {
1384 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
1386 VkMemoryRequirements2 req = {
1387 .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
1391 vkGetImageMemoryRequirements2(hwctx->act_dev, &req_desc, &req);
1393 if (f->tiling == VK_IMAGE_TILING_LINEAR)
1394 req.memoryRequirements.size = FFALIGN(req.memoryRequirements.size,
1395 p->props.properties.limits.minMemoryMapAlignment);
1397 /* In case the implementation prefers/requires dedicated allocation */
1398 use_ded_mem = ded_req.prefersDedicatedAllocation |
1399 ded_req.requiresDedicatedAllocation;
1401 ded_alloc.image = f->img[i];
1403 /* Allocate memory */
1404 if ((err = alloc_mem(ctx, &req.memoryRequirements,
1405 f->tiling == VK_IMAGE_TILING_LINEAR ?
1406 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT :
1407 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1408 use_ded_mem ? &ded_alloc : (void *)ded_alloc.pNext,
1409 &f->flags, &f->mem[i])))
1412 f->size[i] = req.memoryRequirements.size;
1413 bind_info[i].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
1414 bind_info[i].image = f->img[i];
1415 bind_info[i].memory = f->mem[i];
1418 /* Bind the allocated memory to the images */
1419 ret = vkBindImageMemory2(hwctx->act_dev, planes, bind_info);
1420 if (ret != VK_SUCCESS) {
1421 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
1423 return AVERROR_EXTERNAL;
1431 PREP_MODE_RO_SHADER,
1432 PREP_MODE_EXTERNAL_EXPORT,
1435 static int prepare_frame(AVHWFramesContext *hwfc, VulkanExecCtx *ectx,
1436 AVVkFrame *frame, enum PrepMode pmode)
1440 VkImageLayout new_layout;
1441 VkAccessFlags new_access;
1442 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1444 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
1446 VkSubmitInfo s_info = {
1447 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
1448 .pSignalSemaphores = frame->sem,
1449 .signalSemaphoreCount = planes,
1452 VkPipelineStageFlagBits wait_st[AV_NUM_DATA_POINTERS];
1453 for (int i = 0; i < planes; i++)
1454 wait_st[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
1457 case PREP_MODE_WRITE:
1458 new_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
1459 new_access = VK_ACCESS_TRANSFER_WRITE_BIT;
1460 dst_qf = VK_QUEUE_FAMILY_IGNORED;
1462 case PREP_MODE_RO_SHADER:
1463 new_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
1464 new_access = VK_ACCESS_TRANSFER_READ_BIT;
1465 dst_qf = VK_QUEUE_FAMILY_IGNORED;
1467 case PREP_MODE_EXTERNAL_EXPORT:
1468 new_layout = VK_IMAGE_LAYOUT_GENERAL;
1469 new_access = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
1470 dst_qf = VK_QUEUE_FAMILY_EXTERNAL_KHR;
1471 s_info.pWaitSemaphores = frame->sem;
1472 s_info.pWaitDstStageMask = wait_st;
1473 s_info.waitSemaphoreCount = planes;
1477 if ((err = wait_start_exec_ctx(hwfc, ectx)))
1480 /* Change the image layout to something more optimal for writes.
1481 * This also signals the newly created semaphore, making it usable
1482 * for synchronization */
1483 for (int i = 0; i < planes; i++) {
1484 img_bar[i].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1485 img_bar[i].srcAccessMask = 0x0;
1486 img_bar[i].dstAccessMask = new_access;
1487 img_bar[i].oldLayout = frame->layout[i];
1488 img_bar[i].newLayout = new_layout;
1489 img_bar[i].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1490 img_bar[i].dstQueueFamilyIndex = dst_qf;
1491 img_bar[i].image = frame->img[i];
1492 img_bar[i].subresourceRange.levelCount = 1;
1493 img_bar[i].subresourceRange.layerCount = 1;
1494 img_bar[i].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1496 frame->layout[i] = img_bar[i].newLayout;
1497 frame->access[i] = img_bar[i].dstAccessMask;
1500 vkCmdPipelineBarrier(get_buf_exec_ctx(hwfc, ectx),
1501 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
1502 VK_PIPELINE_STAGE_TRANSFER_BIT,
1503 0, 0, NULL, 0, NULL, planes, img_bar);
1505 return submit_exec_ctx(hwfc, ectx, &s_info, 0);
1508 static int create_frame(AVHWFramesContext *hwfc, AVVkFrame **frame,
1509 VkImageTiling tiling, VkImageUsageFlagBits usage,
1514 AVHWDeviceContext *ctx = hwfc->device_ctx;
1515 VulkanDevicePriv *p = ctx->internal->priv;
1516 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1517 enum AVPixelFormat format = hwfc->sw_format;
1518 const VkFormat *img_fmts = av_vkfmt_from_pixfmt(format);
1519 const int planes = av_pix_fmt_count_planes(format);
1521 VkExportSemaphoreCreateInfo ext_sem_info = {
1522 .sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO,
1523 .handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
1526 VkSemaphoreCreateInfo sem_spawn = {
1527 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1528 .pNext = p->extensions & EXT_EXTERNAL_FD_SEM ? &ext_sem_info : NULL,
1531 AVVkFrame *f = av_vk_frame_alloc();
1533 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1534 return AVERROR(ENOMEM);
1537 /* Create the images */
1538 for (int i = 0; i < planes; i++) {
1539 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
1540 int w = hwfc->width;
1541 int h = hwfc->height;
1542 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
1543 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
1545 VkImageCreateInfo image_create_info = {
1546 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1547 .pNext = create_pnext,
1548 .imageType = VK_IMAGE_TYPE_2D,
1549 .format = img_fmts[i],
1550 .extent.width = p_w,
1551 .extent.height = p_h,
1555 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1557 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1559 .samples = VK_SAMPLE_COUNT_1_BIT,
1560 .pQueueFamilyIndices = p->qfs,
1561 .queueFamilyIndexCount = p->num_qfs,
1562 .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
1563 VK_SHARING_MODE_EXCLUSIVE,
1566 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
1567 hwctx->alloc, &f->img[i]);
1568 if (ret != VK_SUCCESS) {
1569 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1571 err = AVERROR(EINVAL);
1575 /* Create semaphore */
1576 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1577 hwctx->alloc, &f->sem[i]);
1578 if (ret != VK_SUCCESS) {
1579 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1581 return AVERROR_EXTERNAL;
1584 f->layout[i] = image_create_info.initialLayout;
1595 vulkan_frame_free(hwfc, (uint8_t *)f);
1599 /* Checks if an export flag is enabled, and if it is ORs it with *iexp */
1600 static void try_export_flags(AVHWFramesContext *hwfc,
1601 VkExternalMemoryHandleTypeFlags *comp_handle_types,
1602 VkExternalMemoryHandleTypeFlagBits *iexp,
1603 VkExternalMemoryHandleTypeFlagBits exp)
1606 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1607 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1608 VkExternalImageFormatProperties eprops = {
1609 .sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES_KHR,
1611 VkImageFormatProperties2 props = {
1612 .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,
1615 VkPhysicalDeviceExternalImageFormatInfo enext = {
1616 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
1619 VkPhysicalDeviceImageFormatInfo2 pinfo = {
1620 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1621 .pNext = !exp ? NULL : &enext,
1622 .format = av_vkfmt_from_pixfmt(hwfc->sw_format)[0],
1623 .type = VK_IMAGE_TYPE_2D,
1624 .tiling = hwctx->tiling,
1625 .usage = hwctx->usage,
1626 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1629 ret = vkGetPhysicalDeviceImageFormatProperties2(dev_hwctx->phys_dev,
1631 if (ret == VK_SUCCESS) {
1633 *comp_handle_types |= eprops.externalMemoryProperties.compatibleHandleTypes;
1637 static AVBufferRef *vulkan_pool_alloc(void *opaque, int size)
1641 AVBufferRef *avbuf = NULL;
1642 AVHWFramesContext *hwfc = opaque;
1643 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1644 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1645 VulkanFramesPriv *fp = hwfc->internal->priv;
1646 VkExportMemoryAllocateInfo eminfo[AV_NUM_DATA_POINTERS];
1647 VkExternalMemoryHandleTypeFlags e = 0x0;
1649 VkExternalMemoryImageCreateInfo eiinfo = {
1650 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1651 .pNext = hwctx->create_pnext,
1654 if (p->extensions & EXT_EXTERNAL_FD_MEMORY)
1655 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1656 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT);
1658 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
1659 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1660 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
1662 for (int i = 0; i < av_pix_fmt_count_planes(hwfc->sw_format); i++) {
1663 eminfo[i].sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO;
1664 eminfo[i].pNext = hwctx->alloc_pnext[i];
1665 eminfo[i].handleTypes = e;
1668 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1669 eiinfo.handleTypes ? &eiinfo : NULL);
1673 err = alloc_bind_mem(hwfc, f, eminfo, sizeof(*eminfo));
1677 err = prepare_frame(hwfc, &fp->conv_ctx, f, PREP_MODE_WRITE);
1681 avbuf = av_buffer_create((uint8_t *)f, sizeof(AVVkFrame),
1682 vulkan_frame_free, hwfc, 0);
1689 vulkan_frame_free(hwfc, (uint8_t *)f);
1693 static void vulkan_frames_uninit(AVHWFramesContext *hwfc)
1695 VulkanFramesPriv *fp = hwfc->internal->priv;
1697 free_exec_ctx(hwfc, &fp->conv_ctx);
1698 free_exec_ctx(hwfc, &fp->upload_ctx);
1699 free_exec_ctx(hwfc, &fp->download_ctx);
1702 static int vulkan_frames_init(AVHWFramesContext *hwfc)
1706 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1707 VulkanFramesPriv *fp = hwfc->internal->priv;
1708 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1709 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1711 /* Default pool flags */
1712 hwctx->tiling = hwctx->tiling ? hwctx->tiling : p->use_linear_images ?
1713 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1716 hwctx->usage = DEFAULT_USAGE_FLAGS;
1718 err = create_exec_ctx(hwfc, &fp->conv_ctx,
1719 dev_hwctx->queue_family_comp_index,
1720 GET_QUEUE_COUNT(dev_hwctx, 0, 1, 0));
1724 err = create_exec_ctx(hwfc, &fp->upload_ctx,
1725 dev_hwctx->queue_family_tx_index,
1726 GET_QUEUE_COUNT(dev_hwctx, 0, 0, 1));
1730 err = create_exec_ctx(hwfc, &fp->download_ctx,
1731 dev_hwctx->queue_family_tx_index, 1);
1735 /* Test to see if allocation will fail */
1736 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1737 hwctx->create_pnext);
1741 vulkan_frame_free(hwfc, (uint8_t *)f);
1743 /* If user did not specify a pool, hwfc->pool will be set to the internal one
1744 * in hwcontext.c just after this gets called */
1746 hwfc->internal->pool_internal = av_buffer_pool_init2(sizeof(AVVkFrame),
1747 hwfc, vulkan_pool_alloc,
1749 if (!hwfc->internal->pool_internal) {
1750 err = AVERROR(ENOMEM);
1758 free_exec_ctx(hwfc, &fp->conv_ctx);
1759 free_exec_ctx(hwfc, &fp->upload_ctx);
1760 free_exec_ctx(hwfc, &fp->download_ctx);
1765 static int vulkan_get_buffer(AVHWFramesContext *hwfc, AVFrame *frame)
1767 frame->buf[0] = av_buffer_pool_get(hwfc->pool);
1769 return AVERROR(ENOMEM);
1771 frame->data[0] = frame->buf[0]->data;
1772 frame->format = AV_PIX_FMT_VULKAN;
1773 frame->width = hwfc->width;
1774 frame->height = hwfc->height;
1779 static int vulkan_transfer_get_formats(AVHWFramesContext *hwfc,
1780 enum AVHWFrameTransferDirection dir,
1781 enum AVPixelFormat **formats)
1783 enum AVPixelFormat *fmts = av_malloc_array(2, sizeof(*fmts));
1785 return AVERROR(ENOMEM);
1787 fmts[0] = hwfc->sw_format;
1788 fmts[1] = AV_PIX_FMT_NONE;
1794 typedef struct VulkanMapping {
1799 static void vulkan_unmap_frame(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1801 VulkanMapping *map = hwmap->priv;
1802 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1803 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1805 /* Check if buffer needs flushing */
1806 if ((map->flags & AV_HWFRAME_MAP_WRITE) &&
1807 !(map->frame->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1809 VkMappedMemoryRange flush_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1811 for (int i = 0; i < planes; i++) {
1812 flush_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1813 flush_ranges[i].memory = map->frame->mem[i];
1814 flush_ranges[i].size = VK_WHOLE_SIZE;
1817 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, planes,
1819 if (ret != VK_SUCCESS) {
1820 av_log(hwfc, AV_LOG_ERROR, "Failed to flush memory: %s\n",
1825 for (int i = 0; i < planes; i++)
1826 vkUnmapMemory(hwctx->act_dev, map->frame->mem[i]);
1831 static int vulkan_map_frame_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
1832 const AVFrame *src, int flags)
1835 int err, mapped_mem_count = 0;
1836 AVVkFrame *f = (AVVkFrame *)src->data[0];
1837 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1838 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1840 VulkanMapping *map = av_mallocz(sizeof(VulkanMapping));
1842 return AVERROR(EINVAL);
1844 if (src->format != AV_PIX_FMT_VULKAN) {
1845 av_log(hwfc, AV_LOG_ERROR, "Cannot map from pixel format %s!\n",
1846 av_get_pix_fmt_name(src->format));
1847 err = AVERROR(EINVAL);
1851 if (!(f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ||
1852 !(f->tiling == VK_IMAGE_TILING_LINEAR)) {
1853 av_log(hwfc, AV_LOG_ERROR, "Unable to map frame, not host visible "
1855 err = AVERROR(EINVAL);
1859 dst->width = src->width;
1860 dst->height = src->height;
1862 for (int i = 0; i < planes; i++) {
1863 ret = vkMapMemory(hwctx->act_dev, f->mem[i], 0,
1864 VK_WHOLE_SIZE, 0, (void **)&dst->data[i]);
1865 if (ret != VK_SUCCESS) {
1866 av_log(hwfc, AV_LOG_ERROR, "Failed to map image memory: %s\n",
1868 err = AVERROR_EXTERNAL;
1874 /* Check if the memory contents matter */
1875 if (((flags & AV_HWFRAME_MAP_READ) || !(flags & AV_HWFRAME_MAP_OVERWRITE)) &&
1876 !(f->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1877 VkMappedMemoryRange map_mem_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1878 for (int i = 0; i < planes; i++) {
1879 map_mem_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1880 map_mem_ranges[i].size = VK_WHOLE_SIZE;
1881 map_mem_ranges[i].memory = f->mem[i];
1884 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, planes,
1886 if (ret != VK_SUCCESS) {
1887 av_log(hwfc, AV_LOG_ERROR, "Failed to invalidate memory: %s\n",
1889 err = AVERROR_EXTERNAL;
1894 for (int i = 0; i < planes; i++) {
1895 VkImageSubresource sub = {
1896 .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
1898 VkSubresourceLayout layout;
1899 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
1900 dst->linesize[i] = layout.rowPitch;
1906 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src,
1907 &vulkan_unmap_frame, map);
1914 for (int i = 0; i < mapped_mem_count; i++)
1915 vkUnmapMemory(hwctx->act_dev, f->mem[i]);
1922 static void vulkan_unmap_from(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1924 VulkanMapping *map = hwmap->priv;
1925 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1926 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1928 for (int i = 0; i < planes; i++) {
1929 vkDestroyImage(hwctx->act_dev, map->frame->img[i], hwctx->alloc);
1930 vkFreeMemory(hwctx->act_dev, map->frame->mem[i], hwctx->alloc);
1931 vkDestroySemaphore(hwctx->act_dev, map->frame->sem[i], hwctx->alloc);
1934 av_freep(&map->frame);
1937 static const struct {
1938 uint32_t drm_fourcc;
1940 } vulkan_drm_format_map[] = {
1941 { DRM_FORMAT_R8, VK_FORMAT_R8_UNORM },
1942 { DRM_FORMAT_R16, VK_FORMAT_R16_UNORM },
1943 { DRM_FORMAT_GR88, VK_FORMAT_R8G8_UNORM },
1944 { DRM_FORMAT_RG88, VK_FORMAT_R8G8_UNORM },
1945 { DRM_FORMAT_GR1616, VK_FORMAT_R16G16_UNORM },
1946 { DRM_FORMAT_RG1616, VK_FORMAT_R16G16_UNORM },
1947 { DRM_FORMAT_ARGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1948 { DRM_FORMAT_XRGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1949 { DRM_FORMAT_ABGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1950 { DRM_FORMAT_XBGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1953 static inline VkFormat drm_to_vulkan_fmt(uint32_t drm_fourcc)
1955 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
1956 if (vulkan_drm_format_map[i].drm_fourcc == drm_fourcc)
1957 return vulkan_drm_format_map[i].vk_format;
1958 return VK_FORMAT_UNDEFINED;
1961 static int vulkan_map_from_drm_frame_desc(AVHWFramesContext *hwfc, AVVkFrame **frame,
1962 AVDRMFrameDescriptor *desc)
1967 int bind_counts = 0;
1968 AVHWDeviceContext *ctx = hwfc->device_ctx;
1969 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1970 VulkanDevicePriv *p = ctx->internal->priv;
1971 VulkanFramesPriv *fp = hwfc->internal->priv;
1972 AVVulkanFramesContext *frames_hwctx = hwfc->hwctx;
1973 const AVPixFmtDescriptor *fmt_desc = av_pix_fmt_desc_get(hwfc->sw_format);
1974 const int has_modifiers = !!(p->extensions & EXT_DRM_MODIFIER_FLAGS);
1975 VkSubresourceLayout plane_data[AV_NUM_DATA_POINTERS] = { 0 };
1976 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { 0 };
1977 VkBindImagePlaneMemoryInfo plane_info[AV_NUM_DATA_POINTERS] = { 0 };
1978 VkExternalMemoryHandleTypeFlagBits htype = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
1980 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdPropertiesKHR);
1982 for (int i = 0; i < desc->nb_layers; i++) {
1983 if (drm_to_vulkan_fmt(desc->layers[i].format) == VK_FORMAT_UNDEFINED) {
1984 av_log(ctx, AV_LOG_ERROR, "Unsupported DMABUF layer format %#08x!\n",
1985 desc->layers[i].format);
1986 return AVERROR(EINVAL);
1990 if (!(f = av_vk_frame_alloc())) {
1991 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1992 err = AVERROR(ENOMEM);
1996 f->tiling = has_modifiers ? VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT :
1997 desc->objects[0].format_modifier == DRM_FORMAT_MOD_LINEAR ?
1998 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
2000 for (int i = 0; i < desc->nb_layers; i++) {
2001 const int planes = desc->layers[i].nb_planes;
2002 VkImageDrmFormatModifierExplicitCreateInfoEXT drm_info = {
2003 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
2004 .drmFormatModifier = desc->objects[0].format_modifier,
2005 .drmFormatModifierPlaneCount = planes,
2006 .pPlaneLayouts = (const VkSubresourceLayout *)&plane_data,
2009 VkExternalMemoryImageCreateInfo einfo = {
2010 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
2011 .pNext = has_modifiers ? &drm_info : NULL,
2012 .handleTypes = htype,
2015 VkSemaphoreCreateInfo sem_spawn = {
2016 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
2019 const int p_w = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, fmt_desc->log2_chroma_w) : hwfc->width;
2020 const int p_h = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, fmt_desc->log2_chroma_h) : hwfc->height;
2022 VkImageCreateInfo image_create_info = {
2023 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
2025 .imageType = VK_IMAGE_TYPE_2D,
2026 .format = drm_to_vulkan_fmt(desc->layers[i].format),
2027 .extent.width = p_w,
2028 .extent.height = p_h,
2032 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
2033 .tiling = f->tiling,
2034 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, /* specs say so */
2035 .usage = frames_hwctx->usage,
2036 .samples = VK_SAMPLE_COUNT_1_BIT,
2037 .pQueueFamilyIndices = p->qfs,
2038 .queueFamilyIndexCount = p->num_qfs,
2039 .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
2040 VK_SHARING_MODE_EXCLUSIVE,
2043 for (int j = 0; j < planes; j++) {
2044 plane_data[j].offset = desc->layers[i].planes[j].offset;
2045 plane_data[j].rowPitch = desc->layers[i].planes[j].pitch;
2046 plane_data[j].size = 0; /* The specs say so for all 3 */
2047 plane_data[j].arrayPitch = 0;
2048 plane_data[j].depthPitch = 0;
2052 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
2053 hwctx->alloc, &f->img[i]);
2054 if (ret != VK_SUCCESS) {
2055 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
2057 err = AVERROR(EINVAL);
2061 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
2062 hwctx->alloc, &f->sem[i]);
2063 if (ret != VK_SUCCESS) {
2064 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
2066 return AVERROR_EXTERNAL;
2069 /* We'd import a semaphore onto the one we created using
2070 * vkImportSemaphoreFdKHR but unfortunately neither DRM nor VAAPI
2071 * offer us anything we could import and sync with, so instead
2072 * just signal the semaphore we created. */
2074 f->layout[i] = image_create_info.initialLayout;
2078 for (int i = 0; i < desc->nb_objects; i++) {
2079 int use_ded_mem = 0;
2080 VkMemoryFdPropertiesKHR fdmp = {
2081 .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,
2083 VkMemoryRequirements req = {
2084 .size = desc->objects[i].size,
2086 VkImportMemoryFdInfoKHR idesc = {
2087 .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
2088 .handleType = htype,
2089 .fd = dup(desc->objects[i].fd),
2091 VkMemoryDedicatedAllocateInfo ded_alloc = {
2092 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
2096 ret = pfn_vkGetMemoryFdPropertiesKHR(hwctx->act_dev, htype,
2098 if (ret != VK_SUCCESS) {
2099 av_log(hwfc, AV_LOG_ERROR, "Failed to get FD properties: %s\n",
2101 err = AVERROR_EXTERNAL;
2106 req.memoryTypeBits = fdmp.memoryTypeBits;
2108 /* Dedicated allocation only makes sense if there's a one to one mapping
2109 * between images and the memory backing them, so only check in this
2111 if (desc->nb_layers == desc->nb_objects) {
2112 VkImageMemoryRequirementsInfo2 req_desc = {
2113 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
2116 VkMemoryDedicatedRequirements ded_req = {
2117 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
2119 VkMemoryRequirements2 req2 = {
2120 .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
2124 vkGetImageMemoryRequirements2(hwctx->act_dev, &req_desc, &req2);
2126 use_ded_mem = ded_req.prefersDedicatedAllocation |
2127 ded_req.requiresDedicatedAllocation;
2129 ded_alloc.image = f->img[i];
2132 err = alloc_mem(ctx, &req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
2133 use_ded_mem ? &ded_alloc : ded_alloc.pNext,
2134 &f->flags, &f->mem[i]);
2140 f->size[i] = desc->objects[i].size;
2143 for (int i = 0; i < desc->nb_layers; i++) {
2144 const int planes = desc->layers[i].nb_planes;
2145 const int signal_p = has_modifiers && (planes > 1);
2146 for (int j = 0; j < planes; j++) {
2147 VkImageAspectFlagBits aspect = j == 0 ? VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2148 j == 1 ? VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT :
2149 VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT;
2151 plane_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO;
2152 plane_info[bind_counts].planeAspect = aspect;
2154 bind_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
2155 bind_info[bind_counts].pNext = signal_p ? &plane_info[bind_counts] : NULL;
2156 bind_info[bind_counts].image = f->img[i];
2157 bind_info[bind_counts].memory = f->mem[desc->layers[i].planes[j].object_index];
2158 bind_info[bind_counts].memoryOffset = desc->layers[i].planes[j].offset;
2163 /* Bind the allocated memory to the images */
2164 ret = vkBindImageMemory2(hwctx->act_dev, bind_counts, bind_info);
2165 if (ret != VK_SUCCESS) {
2166 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
2168 return AVERROR_EXTERNAL;
2171 /* NOTE: This is completely uneccesary and unneeded once we can import
2172 * semaphores from DRM. Otherwise we have to activate the semaphores.
2173 * We're reusing the exec context that's also used for uploads/downloads. */
2174 err = prepare_frame(hwfc, &fp->conv_ctx, f, PREP_MODE_RO_SHADER);
2183 for (int i = 0; i < desc->nb_layers; i++) {
2184 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
2185 vkDestroySemaphore(hwctx->act_dev, f->sem[i], hwctx->alloc);
2187 for (int i = 0; i < desc->nb_objects; i++)
2188 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
2195 static int vulkan_map_from_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2196 const AVFrame *src, int flags)
2200 VulkanMapping *map = NULL;
2202 err = vulkan_map_from_drm_frame_desc(hwfc, &f,
2203 (AVDRMFrameDescriptor *)src->data[0]);
2207 /* The unmapping function will free this */
2208 dst->data[0] = (uint8_t *)f;
2209 dst->width = src->width;
2210 dst->height = src->height;
2212 map = av_mallocz(sizeof(VulkanMapping));
2219 err = ff_hwframe_map_create(dst->hw_frames_ctx, dst, src,
2220 &vulkan_unmap_from, map);
2224 av_log(hwfc, AV_LOG_DEBUG, "Mapped DRM object to Vulkan!\n");
2229 vulkan_frame_free(hwfc->device_ctx->hwctx, (uint8_t *)f);
2235 static int vulkan_map_from_vaapi(AVHWFramesContext *dst_fc,
2236 AVFrame *dst, const AVFrame *src,
2240 AVFrame *tmp = av_frame_alloc();
2241 AVHWFramesContext *vaapi_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2242 AVVAAPIDeviceContext *vaapi_ctx = vaapi_fc->device_ctx->hwctx;
2243 VASurfaceID surface_id = (VASurfaceID)(uintptr_t)src->data[3];
2246 return AVERROR(ENOMEM);
2248 /* We have to sync since like the previous comment said, no semaphores */
2249 vaSyncSurface(vaapi_ctx->display, surface_id);
2251 tmp->format = AV_PIX_FMT_DRM_PRIME;
2253 err = av_hwframe_map(tmp, src, flags);
2257 err = vulkan_map_from_drm(dst_fc, dst, tmp, flags);
2261 err = ff_hwframe_map_replace(dst, src);
2264 av_frame_free(&tmp);
2271 static int vulkan_export_to_cuda(AVHWFramesContext *hwfc,
2272 AVBufferRef *cuda_hwfc,
2273 const AVFrame *frame)
2278 AVVkFrameInternal *dst_int;
2279 AVHWDeviceContext *ctx = hwfc->device_ctx;
2280 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2281 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2282 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2283 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2284 VK_LOAD_PFN(hwctx->inst, vkGetSemaphoreFdKHR);
2286 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)cuda_hwfc->data;
2287 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2288 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2289 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2290 CudaFunctions *cu = cu_internal->cuda_dl;
2291 CUarray_format cufmt = desc->comp[0].depth > 8 ? CU_AD_FORMAT_UNSIGNED_INT16 :
2292 CU_AD_FORMAT_UNSIGNED_INT8;
2294 dst_f = (AVVkFrame *)frame->data[0];
2296 dst_int = dst_f->internal;
2297 if (!dst_int || !dst_int->cuda_fc_ref) {
2298 if (!dst_f->internal)
2299 dst_f->internal = dst_int = av_mallocz(sizeof(*dst_f->internal));
2302 err = AVERROR(ENOMEM);
2306 dst_int->cuda_fc_ref = av_buffer_ref(cuda_hwfc);
2307 if (!dst_int->cuda_fc_ref) {
2308 err = AVERROR(ENOMEM);
2312 for (int i = 0; i < planes; i++) {
2313 CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC tex_desc = {
2316 .Width = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2318 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
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,
2345 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2346 &ext_desc.handle.fd);
2347 if (ret != VK_SUCCESS) {
2348 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2349 err = AVERROR_EXTERNAL;
2353 ret = CHECK_CU(cu->cuImportExternalMemory(&dst_int->ext_mem[i], &ext_desc));
2355 err = AVERROR_EXTERNAL;
2359 ret = CHECK_CU(cu->cuExternalMemoryGetMappedMipmappedArray(&dst_int->cu_mma[i],
2360 dst_int->ext_mem[i],
2363 err = AVERROR_EXTERNAL;
2367 ret = CHECK_CU(cu->cuMipmappedArrayGetLevel(&dst_int->cu_array[i],
2368 dst_int->cu_mma[i], 0));
2370 err = AVERROR_EXTERNAL;
2374 ret = pfn_vkGetSemaphoreFdKHR(hwctx->act_dev, &sem_export,
2375 &ext_sem_desc.handle.fd);
2376 if (ret != VK_SUCCESS) {
2377 av_log(ctx, AV_LOG_ERROR, "Failed to export semaphore: %s\n",
2379 err = AVERROR_EXTERNAL;
2383 ret = CHECK_CU(cu->cuImportExternalSemaphore(&dst_int->cu_sem[i],
2386 err = AVERROR_EXTERNAL;
2398 static int vulkan_transfer_data_from_cuda(AVHWFramesContext *hwfc,
2399 AVFrame *dst, const AVFrame *src)
2405 AVVkFrameInternal *dst_int;
2406 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2407 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2409 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2410 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2411 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2412 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2413 CudaFunctions *cu = cu_internal->cuda_dl;
2414 CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS s_w_par[AV_NUM_DATA_POINTERS] = { 0 };
2415 CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS s_s_par[AV_NUM_DATA_POINTERS] = { 0 };
2417 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2419 return AVERROR_EXTERNAL;
2421 dst_f = (AVVkFrame *)dst->data[0];
2423 ret = vulkan_export_to_cuda(hwfc, src->hw_frames_ctx, dst);
2425 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2429 dst_int = dst_f->internal;
2431 ret = CHECK_CU(cu->cuWaitExternalSemaphoresAsync(dst_int->cu_sem, s_w_par,
2432 planes, cuda_dev->stream));
2434 err = AVERROR_EXTERNAL;
2438 for (int i = 0; i < planes; i++) {
2439 CUDA_MEMCPY2D cpy = {
2440 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
2441 .srcDevice = (CUdeviceptr)src->data[i],
2442 .srcPitch = src->linesize[i],
2445 .dstMemoryType = CU_MEMORYTYPE_ARRAY,
2446 .dstArray = dst_int->cu_array[i],
2447 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2448 : hwfc->width) * desc->comp[i].step,
2449 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2453 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2455 err = AVERROR_EXTERNAL;
2460 ret = CHECK_CU(cu->cuSignalExternalSemaphoresAsync(dst_int->cu_sem, s_s_par,
2461 planes, cuda_dev->stream));
2463 err = AVERROR_EXTERNAL;
2467 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2469 av_log(hwfc, AV_LOG_VERBOSE, "Transfered CUDA image to Vulkan!\n");
2474 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2475 vulkan_free_internal(dst_int);
2476 dst_f->internal = NULL;
2477 av_buffer_unref(&dst->buf[0]);
2482 static int vulkan_map_to(AVHWFramesContext *hwfc, AVFrame *dst,
2483 const AVFrame *src, int flags)
2485 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2487 switch (src->format) {
2490 case AV_PIX_FMT_VAAPI:
2491 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2492 return vulkan_map_from_vaapi(hwfc, dst, src, flags);
2494 case AV_PIX_FMT_DRM_PRIME:
2495 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2496 return vulkan_map_from_drm(hwfc, dst, src, flags);
2499 return AVERROR(ENOSYS);
2504 typedef struct VulkanDRMMapping {
2505 AVDRMFrameDescriptor drm_desc;
2509 static void vulkan_unmap_to_drm(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
2511 AVDRMFrameDescriptor *drm_desc = hwmap->priv;
2513 for (int i = 0; i < drm_desc->nb_objects; i++)
2514 close(drm_desc->objects[i].fd);
2519 static inline uint32_t vulkan_fmt_to_drm(VkFormat vkfmt)
2521 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
2522 if (vulkan_drm_format_map[i].vk_format == vkfmt)
2523 return vulkan_drm_format_map[i].drm_fourcc;
2524 return DRM_FORMAT_INVALID;
2527 static int vulkan_map_to_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2528 const AVFrame *src, int flags)
2532 AVVkFrame *f = (AVVkFrame *)src->data[0];
2533 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2534 VulkanFramesPriv *fp = hwfc->internal->priv;
2535 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
2536 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2537 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2538 VkImageDrmFormatModifierPropertiesEXT drm_mod = {
2539 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT,
2542 AVDRMFrameDescriptor *drm_desc = av_mallocz(sizeof(*drm_desc));
2544 return AVERROR(ENOMEM);
2546 err = prepare_frame(hwfc, &fp->conv_ctx, f, PREP_MODE_EXTERNAL_EXPORT);
2550 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src, &vulkan_unmap_to_drm, drm_desc);
2554 if (p->extensions & EXT_DRM_MODIFIER_FLAGS) {
2555 VK_LOAD_PFN(hwctx->inst, vkGetImageDrmFormatModifierPropertiesEXT);
2556 ret = pfn_vkGetImageDrmFormatModifierPropertiesEXT(hwctx->act_dev, f->img[0],
2558 if (ret != VK_SUCCESS) {
2559 av_log(hwfc, AV_LOG_ERROR, "Failed to retrieve DRM format modifier!\n");
2560 err = AVERROR_EXTERNAL;
2565 for (int i = 0; (i < planes) && (f->mem[i]); i++) {
2566 VkMemoryGetFdInfoKHR export_info = {
2567 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2568 .memory = f->mem[i],
2569 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,
2572 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2573 &drm_desc->objects[i].fd);
2574 if (ret != VK_SUCCESS) {
2575 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2576 err = AVERROR_EXTERNAL;
2580 drm_desc->nb_objects++;
2581 drm_desc->objects[i].size = f->size[i];
2582 drm_desc->objects[i].format_modifier = drm_mod.drmFormatModifier;
2585 drm_desc->nb_layers = planes;
2586 for (int i = 0; i < drm_desc->nb_layers; i++) {
2587 VkSubresourceLayout layout;
2588 VkImageSubresource sub = {
2589 .aspectMask = p->extensions & EXT_DRM_MODIFIER_FLAGS ?
2590 VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2591 VK_IMAGE_ASPECT_COLOR_BIT,
2593 VkFormat plane_vkfmt = av_vkfmt_from_pixfmt(hwfc->sw_format)[i];
2595 drm_desc->layers[i].format = vulkan_fmt_to_drm(plane_vkfmt);
2596 drm_desc->layers[i].nb_planes = 1;
2598 if (drm_desc->layers[i].format == DRM_FORMAT_INVALID) {
2599 av_log(hwfc, AV_LOG_ERROR, "Cannot map to DRM layer, unsupported!\n");
2600 err = AVERROR_PATCHWELCOME;
2604 drm_desc->layers[i].planes[0].object_index = FFMIN(i, drm_desc->nb_objects - 1);
2606 if (f->tiling == VK_IMAGE_TILING_OPTIMAL)
2609 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
2610 drm_desc->layers[i].planes[0].offset = layout.offset;
2611 drm_desc->layers[i].planes[0].pitch = layout.rowPitch;
2614 dst->width = src->width;
2615 dst->height = src->height;
2616 dst->data[0] = (uint8_t *)drm_desc;
2618 av_log(hwfc, AV_LOG_VERBOSE, "Mapped AVVkFrame to a DRM object!\n");
2628 static int vulkan_map_to_vaapi(AVHWFramesContext *hwfc, AVFrame *dst,
2629 const AVFrame *src, int flags)
2632 AVFrame *tmp = av_frame_alloc();
2634 return AVERROR(ENOMEM);
2636 tmp->format = AV_PIX_FMT_DRM_PRIME;
2638 err = vulkan_map_to_drm(hwfc, tmp, src, flags);
2642 err = av_hwframe_map(dst, tmp, flags);
2646 err = ff_hwframe_map_replace(dst, src);
2649 av_frame_free(&tmp);
2655 static int vulkan_map_from(AVHWFramesContext *hwfc, AVFrame *dst,
2656 const AVFrame *src, int flags)
2658 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2660 switch (dst->format) {
2662 case AV_PIX_FMT_DRM_PRIME:
2663 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2664 return vulkan_map_to_drm(hwfc, dst, src, flags);
2666 case AV_PIX_FMT_VAAPI:
2667 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2668 return vulkan_map_to_vaapi(hwfc, dst, src, flags);
2672 return vulkan_map_frame_to_mem(hwfc, dst, src, flags);
2676 typedef struct ImageBuffer {
2679 VkMemoryPropertyFlagBits flags;
2683 static void free_buf(void *opaque, uint8_t *data)
2685 AVHWDeviceContext *ctx = opaque;
2686 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2687 ImageBuffer *vkbuf = (ImageBuffer *)data;
2690 vkDestroyBuffer(hwctx->act_dev, vkbuf->buf, hwctx->alloc);
2692 vkFreeMemory(hwctx->act_dev, vkbuf->mem, hwctx->alloc);
2697 static int create_buf(AVHWDeviceContext *ctx, AVBufferRef **buf, size_t imp_size,
2698 int height, int *stride, VkBufferUsageFlags usage,
2699 VkMemoryPropertyFlagBits flags, void *create_pnext,
2705 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2706 VulkanDevicePriv *p = ctx->internal->priv;
2708 VkBufferCreateInfo buf_spawn = {
2709 .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
2710 .pNext = create_pnext,
2712 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
2715 VkBufferMemoryRequirementsInfo2 req_desc = {
2716 .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2,
2718 VkMemoryDedicatedAllocateInfo ded_alloc = {
2719 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
2720 .pNext = alloc_pnext,
2722 VkMemoryDedicatedRequirements ded_req = {
2723 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
2725 VkMemoryRequirements2 req = {
2726 .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
2730 ImageBuffer *vkbuf = av_mallocz(sizeof(*vkbuf));
2732 return AVERROR(ENOMEM);
2734 vkbuf->mapped_mem = !!imp_size;
2736 if (!vkbuf->mapped_mem) {
2737 *stride = FFALIGN(*stride, p->props.properties.limits.optimalBufferCopyRowPitchAlignment);
2738 buf_spawn.size = height*(*stride);
2739 buf_spawn.size = FFALIGN(buf_spawn.size, p->props.properties.limits.minMemoryMapAlignment);
2741 buf_spawn.size = imp_size;
2744 ret = vkCreateBuffer(hwctx->act_dev, &buf_spawn, NULL, &vkbuf->buf);
2745 if (ret != VK_SUCCESS) {
2746 av_log(ctx, AV_LOG_ERROR, "Failed to create buffer: %s\n",
2748 return AVERROR_EXTERNAL;
2751 req_desc.buffer = vkbuf->buf;
2753 vkGetBufferMemoryRequirements2(hwctx->act_dev, &req_desc, &req);
2755 /* In case the implementation prefers/requires dedicated allocation */
2756 use_ded_mem = ded_req.prefersDedicatedAllocation |
2757 ded_req.requiresDedicatedAllocation;
2759 ded_alloc.buffer = vkbuf->buf;
2761 err = alloc_mem(ctx, &req.memoryRequirements, flags,
2762 use_ded_mem ? &ded_alloc : (void *)ded_alloc.pNext,
2763 &vkbuf->flags, &vkbuf->mem);
2767 ret = vkBindBufferMemory(hwctx->act_dev, vkbuf->buf, vkbuf->mem, 0);
2768 if (ret != VK_SUCCESS) {
2769 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory to buffer: %s\n",
2771 free_buf(ctx, (uint8_t *)vkbuf);
2772 return AVERROR_EXTERNAL;
2775 *buf = av_buffer_create((uint8_t *)vkbuf, sizeof(*vkbuf), free_buf, ctx, 0);
2777 free_buf(ctx, (uint8_t *)vkbuf);
2778 return AVERROR(ENOMEM);
2784 /* Skips mapping of host mapped buffers but still invalidates them */
2785 static int map_buffers(AVHWDeviceContext *ctx, AVBufferRef **bufs, uint8_t *mem[],
2786 int nb_buffers, int invalidate)
2789 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2790 VkMappedMemoryRange invalidate_ctx[AV_NUM_DATA_POINTERS];
2791 int invalidate_count = 0;
2793 for (int i = 0; i < nb_buffers; i++) {
2794 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2795 if (vkbuf->mapped_mem)
2798 ret = vkMapMemory(hwctx->act_dev, vkbuf->mem, 0,
2799 VK_WHOLE_SIZE, 0, (void **)&mem[i]);
2800 if (ret != VK_SUCCESS) {
2801 av_log(ctx, AV_LOG_ERROR, "Failed to map buffer memory: %s\n",
2803 return AVERROR_EXTERNAL;
2810 for (int i = 0; i < nb_buffers; i++) {
2811 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2812 const VkMappedMemoryRange ival_buf = {
2813 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2814 .memory = vkbuf->mem,
2815 .size = VK_WHOLE_SIZE,
2817 if (vkbuf->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2819 invalidate_ctx[invalidate_count++] = ival_buf;
2822 if (invalidate_count) {
2823 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, invalidate_count,
2825 if (ret != VK_SUCCESS)
2826 av_log(ctx, AV_LOG_WARNING, "Failed to invalidate memory: %s\n",
2833 static int unmap_buffers(AVHWDeviceContext *ctx, AVBufferRef **bufs,
2834 int nb_buffers, int flush)
2838 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2839 VkMappedMemoryRange flush_ctx[AV_NUM_DATA_POINTERS];
2840 int flush_count = 0;
2843 for (int i = 0; i < nb_buffers; i++) {
2844 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2845 const VkMappedMemoryRange flush_buf = {
2846 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2847 .memory = vkbuf->mem,
2848 .size = VK_WHOLE_SIZE,
2850 if (vkbuf->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2852 flush_ctx[flush_count++] = flush_buf;
2857 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, flush_count, flush_ctx);
2858 if (ret != VK_SUCCESS) {
2859 av_log(ctx, AV_LOG_ERROR, "Failed to flush memory: %s\n",
2861 err = AVERROR_EXTERNAL; /* We still want to try to unmap them */
2865 for (int i = 0; i < nb_buffers; i++) {
2866 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2867 if (vkbuf->mapped_mem)
2870 vkUnmapMemory(hwctx->act_dev, vkbuf->mem);
2876 static int transfer_image_buf(AVHWFramesContext *hwfc, const AVFrame *f,
2877 AVBufferRef **bufs, const int *buf_stride, int w,
2878 int h, enum AVPixelFormat pix_fmt, int to_buf)
2881 AVVkFrame *frame = (AVVkFrame *)f->data[0];
2882 VulkanFramesPriv *fp = hwfc->internal->priv;
2885 VkPipelineStageFlagBits sem_wait_dst[AV_NUM_DATA_POINTERS];
2887 const int planes = av_pix_fmt_count_planes(pix_fmt);
2888 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2890 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
2891 VulkanExecCtx *ectx = to_buf ? &fp->download_ctx : &fp->upload_ctx;
2892 VkCommandBuffer cmd_buf = get_buf_exec_ctx(hwfc, ectx);
2894 VkSubmitInfo s_info = {
2895 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
2896 .pSignalSemaphores = frame->sem,
2897 .pWaitSemaphores = frame->sem,
2898 .pWaitDstStageMask = sem_wait_dst,
2899 .signalSemaphoreCount = planes,
2900 .waitSemaphoreCount = planes,
2903 if ((err = wait_start_exec_ctx(hwfc, ectx)))
2906 /* Change the image layout to something more optimal for transfers */
2907 for (int i = 0; i < planes; i++) {
2908 VkImageLayout new_layout = to_buf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL :
2909 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
2910 VkAccessFlags new_access = to_buf ? VK_ACCESS_TRANSFER_READ_BIT :
2911 VK_ACCESS_TRANSFER_WRITE_BIT;
2913 sem_wait_dst[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
2915 /* If the layout matches and we have read access skip the barrier */
2916 if ((frame->layout[i] == new_layout) && (frame->access[i] & new_access))
2919 img_bar[bar_num].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
2920 img_bar[bar_num].srcAccessMask = 0x0;
2921 img_bar[bar_num].dstAccessMask = new_access;
2922 img_bar[bar_num].oldLayout = frame->layout[i];
2923 img_bar[bar_num].newLayout = new_layout;
2924 img_bar[bar_num].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2925 img_bar[bar_num].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2926 img_bar[bar_num].image = frame->img[i];
2927 img_bar[bar_num].subresourceRange.levelCount = 1;
2928 img_bar[bar_num].subresourceRange.layerCount = 1;
2929 img_bar[bar_num].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2931 frame->layout[i] = img_bar[bar_num].newLayout;
2932 frame->access[i] = img_bar[bar_num].dstAccessMask;
2938 vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
2939 VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
2940 0, NULL, 0, NULL, bar_num, img_bar);
2942 /* Schedule a copy for each plane */
2943 for (int i = 0; i < planes; i++) {
2944 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2945 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
2946 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
2947 VkBufferImageCopy buf_reg = {
2949 /* Buffer stride isn't in bytes, it's in samples, the implementation
2950 * uses the image's VkFormat to know how many bytes per sample
2951 * the buffer has. So we have to convert by dividing. Stupid.
2952 * Won't work with YUVA or other planar formats with alpha. */
2953 .bufferRowLength = buf_stride[i] / desc->comp[i].step,
2954 .bufferImageHeight = p_h,
2955 .imageSubresource.layerCount = 1,
2956 .imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
2957 .imageOffset = { 0, 0, 0, },
2958 .imageExtent = { p_w, p_h, 1, },
2962 vkCmdCopyImageToBuffer(cmd_buf, frame->img[i], frame->layout[i],
2963 vkbuf->buf, 1, &buf_reg);
2965 vkCmdCopyBufferToImage(cmd_buf, vkbuf->buf, frame->img[i],
2966 frame->layout[i], 1, &buf_reg);
2969 /* When uploading, do this asynchronously if the source is refcounted by
2970 * keeping the buffers as a submission dependency.
2971 * The hwcontext is guaranteed to not be freed until all frames are freed
2972 * in the frames_unint function.
2973 * When downloading to buffer, do this synchronously and wait for the
2974 * queue submission to finish executing */
2977 for (ref = 0; ref < AV_NUM_DATA_POINTERS; ref++) {
2980 if ((err = add_buf_dep_exec_ctx(hwfc, ectx, &f->buf[ref], 1)))
2983 if (ref && (err = add_buf_dep_exec_ctx(hwfc, ectx, bufs, planes)))
2985 return submit_exec_ctx(hwfc, ectx, &s_info, !ref);
2987 return submit_exec_ctx(hwfc, ectx, &s_info, 1);
2991 static int vulkan_transfer_data(AVHWFramesContext *hwfc, const AVFrame *vkf,
2992 const AVFrame *swf, int from)
2995 AVVkFrame *f = (AVVkFrame *)vkf->data[0];
2996 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
2997 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
3000 AVBufferRef *bufs[AV_NUM_DATA_POINTERS] = { 0 };
3002 const int planes = av_pix_fmt_count_planes(swf->format);
3003 int log2_chroma = av_pix_fmt_desc_get(swf->format)->log2_chroma_h;
3005 int host_mapped[AV_NUM_DATA_POINTERS] = { 0 };
3006 const int map_host = !!(p->extensions & EXT_EXTERNAL_HOST_MEMORY);
3008 if ((swf->format != AV_PIX_FMT_NONE && !av_vkfmt_from_pixfmt(swf->format))) {
3009 av_log(hwfc, AV_LOG_ERROR, "Unsupported software frame pixel format!\n");
3010 return AVERROR(EINVAL);
3013 if (swf->width > hwfc->width || swf->height > hwfc->height)
3014 return AVERROR(EINVAL);
3016 /* For linear, host visiable images */
3017 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
3018 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
3019 AVFrame *map = av_frame_alloc();
3021 return AVERROR(ENOMEM);
3022 map->format = swf->format;
3024 err = vulkan_map_frame_to_mem(hwfc, map, vkf, AV_HWFRAME_MAP_WRITE);
3028 err = av_frame_copy((AVFrame *)(from ? swf : map), from ? map : swf);
3029 av_frame_free(&map);
3033 /* Create buffers */
3034 for (int i = 0; i < planes; i++) {
3035 int h = swf->height;
3036 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
3037 size_t p_size = FFALIGN(FFABS(swf->linesize[i]) * p_height,
3038 p->hprops.minImportedHostPointerAlignment);
3040 VkExternalMemoryBufferCreateInfo create_desc = {
3041 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO,
3042 .handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT,
3045 VkImportMemoryHostPointerInfoEXT import_desc = {
3046 .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT,
3047 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT,
3048 .pHostPointer = swf->data[i],
3051 /* We can only map images with positive stride and alignment appropriate
3052 * for the device. */
3053 host_mapped[i] = map_host && swf->linesize[i] > 0 &&
3054 !(((uintptr_t)import_desc.pHostPointer) %
3055 p->hprops.minImportedHostPointerAlignment);
3056 p_size = host_mapped[i] ? p_size : 0;
3058 tmp.linesize[i] = FFABS(swf->linesize[i]);
3059 err = create_buf(dev_ctx, &bufs[i], p_size, p_height, &tmp.linesize[i],
3060 from ? VK_BUFFER_USAGE_TRANSFER_DST_BIT :
3061 VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
3062 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
3063 host_mapped[i] ? &create_desc : NULL,
3064 host_mapped[i] ? &import_desc : NULL);
3070 /* Map, copy image to buffer, unmap */
3071 if ((err = map_buffers(dev_ctx, bufs, tmp.data, planes, 0)))
3074 for (int i = 0; i < planes; i++) {
3075 int h = swf->height;
3076 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
3081 av_image_copy_plane(tmp.data[i], tmp.linesize[i],
3082 (const uint8_t *)swf->data[i], swf->linesize[i],
3083 FFMIN(tmp.linesize[i], FFABS(swf->linesize[i])),
3087 if ((err = unmap_buffers(dev_ctx, bufs, planes, 1)))
3091 /* Copy buffers into/from image */
3092 err = transfer_image_buf(hwfc, vkf, bufs, tmp.linesize,
3093 swf->width, swf->height, swf->format, from);
3096 /* Map, copy image to buffer, unmap */
3097 if ((err = map_buffers(dev_ctx, bufs, tmp.data, planes, 0)))
3100 for (int i = 0; i < planes; i++) {
3101 int h = swf->height;
3102 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
3107 av_image_copy_plane(swf->data[i], swf->linesize[i],
3108 (const uint8_t *)tmp.data[i], tmp.linesize[i],
3109 FFMIN(tmp.linesize[i], FFABS(swf->linesize[i])),
3113 if ((err = unmap_buffers(dev_ctx, bufs, planes, 1)))
3118 for (int i = 0; i < planes; i++)
3119 av_buffer_unref(&bufs[i]);
3124 static int vulkan_transfer_data_to(AVHWFramesContext *hwfc, AVFrame *dst,
3127 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
3129 switch (src->format) {
3131 case AV_PIX_FMT_CUDA:
3132 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
3133 (p->extensions & EXT_EXTERNAL_FD_SEM))
3134 return vulkan_transfer_data_from_cuda(hwfc, dst, src);
3137 if (src->hw_frames_ctx)
3138 return AVERROR(ENOSYS);
3140 return vulkan_transfer_data(hwfc, dst, src, 0);
3145 static int vulkan_transfer_data_to_cuda(AVHWFramesContext *hwfc, AVFrame *dst,
3152 AVVkFrameInternal *dst_int;
3153 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
3154 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
3156 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)dst->hw_frames_ctx->data;
3157 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
3158 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
3159 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
3160 CudaFunctions *cu = cu_internal->cuda_dl;
3162 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
3164 return AVERROR_EXTERNAL;
3166 dst_f = (AVVkFrame *)src->data[0];
3168 err = vulkan_export_to_cuda(hwfc, dst->hw_frames_ctx, src);
3170 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
3174 dst_int = dst_f->internal;
3176 for (int i = 0; i < planes; i++) {
3177 CUDA_MEMCPY2D cpy = {
3178 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
3179 .dstDevice = (CUdeviceptr)dst->data[i],
3180 .dstPitch = dst->linesize[i],
3183 .srcMemoryType = CU_MEMORYTYPE_ARRAY,
3184 .srcArray = dst_int->cu_array[i],
3185 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
3186 : hwfc->width) * desc->comp[i].step,
3187 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
3191 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
3193 err = AVERROR_EXTERNAL;
3198 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
3200 av_log(hwfc, AV_LOG_VERBOSE, "Transfered Vulkan image to CUDA!\n");
3205 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
3206 vulkan_free_internal(dst_int);
3207 dst_f->internal = NULL;
3208 av_buffer_unref(&dst->buf[0]);
3213 static int vulkan_transfer_data_from(AVHWFramesContext *hwfc, AVFrame *dst,
3216 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
3218 switch (dst->format) {
3220 case AV_PIX_FMT_CUDA:
3221 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
3222 (p->extensions & EXT_EXTERNAL_FD_SEM))
3223 return vulkan_transfer_data_to_cuda(hwfc, dst, src);
3226 if (dst->hw_frames_ctx)
3227 return AVERROR(ENOSYS);
3229 return vulkan_transfer_data(hwfc, src, dst, 1);
3233 static int vulkan_frames_derive_to(AVHWFramesContext *dst_fc,
3234 AVHWFramesContext *src_fc, int flags)
3236 return vulkan_frames_init(dst_fc);
3239 AVVkFrame *av_vk_frame_alloc(void)
3241 return av_mallocz(sizeof(AVVkFrame));
3244 const HWContextType ff_hwcontext_type_vulkan = {
3245 .type = AV_HWDEVICE_TYPE_VULKAN,
3248 .device_hwctx_size = sizeof(AVVulkanDeviceContext),
3249 .device_priv_size = sizeof(VulkanDevicePriv),
3250 .frames_hwctx_size = sizeof(AVVulkanFramesContext),
3251 .frames_priv_size = sizeof(VulkanFramesPriv),
3253 .device_init = &vulkan_device_init,
3254 .device_create = &vulkan_device_create,
3255 .device_derive = &vulkan_device_derive,
3257 .frames_get_constraints = &vulkan_frames_get_constraints,
3258 .frames_init = vulkan_frames_init,
3259 .frames_get_buffer = vulkan_get_buffer,
3260 .frames_uninit = vulkan_frames_uninit,
3262 .transfer_get_formats = vulkan_transfer_get_formats,
3263 .transfer_data_to = vulkan_transfer_data_to,
3264 .transfer_data_from = vulkan_transfer_data_from,
3266 .map_to = vulkan_map_to,
3267 .map_from = vulkan_map_from,
3268 .frames_derive_to = &vulkan_frames_derive_to,
3270 .pix_fmts = (const enum AVPixelFormat []) {