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 VulkanExecCtx {
51 typedef struct VulkanDevicePriv {
53 VkPhysicalDeviceProperties props;
54 VkPhysicalDeviceMemoryProperties mprops;
61 VkDebugUtilsMessengerEXT debug_ctx;
70 int use_linear_images;
76 typedef struct VulkanFramesPriv {
80 typedef struct AVVkFrameInternal {
82 /* Importing external memory into cuda is really expensive so we keep the
83 * memory imported all the time */
84 AVBufferRef *cuda_fc_ref; /* Need to keep it around for uninit */
85 CUexternalMemory ext_mem[AV_NUM_DATA_POINTERS];
86 CUmipmappedArray cu_mma[AV_NUM_DATA_POINTERS];
87 CUarray cu_array[AV_NUM_DATA_POINTERS];
88 CUexternalSemaphore cu_sem;
92 #define VK_LOAD_PFN(inst, name) PFN_##name pfn_##name = (PFN_##name) \
93 vkGetInstanceProcAddr(inst, #name)
95 #define DEFAULT_USAGE_FLAGS (VK_IMAGE_USAGE_SAMPLED_BIT | \
96 VK_IMAGE_USAGE_STORAGE_BIT | \
97 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | \
98 VK_IMAGE_USAGE_TRANSFER_DST_BIT)
100 #define ADD_VAL_TO_LIST(list, count, val) \
102 list = av_realloc_array(list, sizeof(*list), ++count); \
104 err = AVERROR(ENOMEM); \
107 list[count - 1] = av_strdup(val); \
108 if (!list[count - 1]) { \
109 err = AVERROR(ENOMEM); \
114 static const struct {
115 enum AVPixelFormat pixfmt;
116 const VkFormat vkfmts[3];
117 } vk_pixfmt_map[] = {
118 { AV_PIX_FMT_GRAY8, { VK_FORMAT_R8_UNORM } },
119 { AV_PIX_FMT_GRAY16, { VK_FORMAT_R16_UNORM } },
120 { AV_PIX_FMT_GRAYF32, { VK_FORMAT_R32_SFLOAT } },
122 { AV_PIX_FMT_NV12, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8G8_UNORM } },
123 { AV_PIX_FMT_P010, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16G16_UNORM } },
124 { AV_PIX_FMT_P016, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16G16_UNORM } },
126 { AV_PIX_FMT_YUV420P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
127 { AV_PIX_FMT_YUV422P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
128 { AV_PIX_FMT_YUV444P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
130 { AV_PIX_FMT_YUV420P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
131 { AV_PIX_FMT_YUV422P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
132 { AV_PIX_FMT_YUV444P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
134 { AV_PIX_FMT_ABGR, { VK_FORMAT_A8B8G8R8_UNORM_PACK32 } },
135 { AV_PIX_FMT_BGRA, { VK_FORMAT_B8G8R8A8_UNORM } },
136 { AV_PIX_FMT_RGBA, { VK_FORMAT_R8G8B8A8_UNORM } },
137 { AV_PIX_FMT_RGB24, { VK_FORMAT_R8G8B8_UNORM } },
138 { AV_PIX_FMT_BGR24, { VK_FORMAT_B8G8R8_UNORM } },
139 { AV_PIX_FMT_RGB48, { VK_FORMAT_R16G16B16_UNORM } },
140 { AV_PIX_FMT_RGBA64, { VK_FORMAT_R16G16B16A16_UNORM } },
141 { AV_PIX_FMT_RGB565, { VK_FORMAT_R5G6B5_UNORM_PACK16 } },
142 { AV_PIX_FMT_BGR565, { VK_FORMAT_B5G6R5_UNORM_PACK16 } },
143 { AV_PIX_FMT_BGR0, { VK_FORMAT_B8G8R8A8_UNORM } },
144 { AV_PIX_FMT_0BGR, { VK_FORMAT_A8B8G8R8_UNORM_PACK32 } },
145 { AV_PIX_FMT_RGB0, { VK_FORMAT_R8G8B8A8_UNORM } },
147 { AV_PIX_FMT_GBRPF32, { VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32_SFLOAT } },
150 const VkFormat *av_vkfmt_from_pixfmt(enum AVPixelFormat p)
152 for (enum AVPixelFormat i = 0; i < FF_ARRAY_ELEMS(vk_pixfmt_map); i++)
153 if (vk_pixfmt_map[i].pixfmt == p)
154 return vk_pixfmt_map[i].vkfmts;
158 static int pixfmt_is_supported(AVVulkanDeviceContext *hwctx, enum AVPixelFormat p,
161 const VkFormat *fmt = av_vkfmt_from_pixfmt(p);
162 int planes = av_pix_fmt_count_planes(p);
167 for (int i = 0; i < planes; i++) {
168 VkFormatFeatureFlags flags;
169 VkFormatProperties2 prop = {
170 .sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2,
172 vkGetPhysicalDeviceFormatProperties2(hwctx->phys_dev, fmt[i], &prop);
173 flags = linear ? prop.formatProperties.linearTilingFeatures :
174 prop.formatProperties.optimalTilingFeatures;
175 if (!(flags & DEFAULT_USAGE_FLAGS))
182 enum VulkanExtensions {
183 EXT_EXTERNAL_DMABUF_MEMORY = 1ULL << 0, /* VK_EXT_external_memory_dma_buf */
184 EXT_DRM_MODIFIER_FLAGS = 1ULL << 1, /* VK_EXT_image_drm_format_modifier */
185 EXT_EXTERNAL_FD_MEMORY = 1ULL << 2, /* VK_KHR_external_memory_fd */
186 EXT_EXTERNAL_FD_SEM = 1ULL << 3, /* VK_KHR_external_semaphore_fd */
188 EXT_NO_FLAG = 1ULL << 63,
191 typedef struct VulkanOptExtension {
194 } VulkanOptExtension;
196 static const VulkanOptExtension optional_instance_exts[] = {
197 { VK_KHR_SURFACE_EXTENSION_NAME, EXT_NO_FLAG },
200 static const VulkanOptExtension optional_device_exts[] = {
201 { VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME, EXT_EXTERNAL_FD_MEMORY, },
202 { VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME, EXT_EXTERNAL_DMABUF_MEMORY, },
203 { VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME, EXT_DRM_MODIFIER_FLAGS, },
204 { VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME, EXT_EXTERNAL_FD_SEM, },
207 /* Converts return values to strings */
208 static const char *vk_ret2str(VkResult res)
210 #define CASE(VAL) case VAL: return #VAL
216 CASE(VK_EVENT_RESET);
218 CASE(VK_ERROR_OUT_OF_HOST_MEMORY);
219 CASE(VK_ERROR_OUT_OF_DEVICE_MEMORY);
220 CASE(VK_ERROR_INITIALIZATION_FAILED);
221 CASE(VK_ERROR_DEVICE_LOST);
222 CASE(VK_ERROR_MEMORY_MAP_FAILED);
223 CASE(VK_ERROR_LAYER_NOT_PRESENT);
224 CASE(VK_ERROR_EXTENSION_NOT_PRESENT);
225 CASE(VK_ERROR_FEATURE_NOT_PRESENT);
226 CASE(VK_ERROR_INCOMPATIBLE_DRIVER);
227 CASE(VK_ERROR_TOO_MANY_OBJECTS);
228 CASE(VK_ERROR_FORMAT_NOT_SUPPORTED);
229 CASE(VK_ERROR_FRAGMENTED_POOL);
230 CASE(VK_ERROR_SURFACE_LOST_KHR);
231 CASE(VK_ERROR_NATIVE_WINDOW_IN_USE_KHR);
232 CASE(VK_SUBOPTIMAL_KHR);
233 CASE(VK_ERROR_OUT_OF_DATE_KHR);
234 CASE(VK_ERROR_INCOMPATIBLE_DISPLAY_KHR);
235 CASE(VK_ERROR_VALIDATION_FAILED_EXT);
236 CASE(VK_ERROR_INVALID_SHADER_NV);
237 CASE(VK_ERROR_OUT_OF_POOL_MEMORY);
238 CASE(VK_ERROR_INVALID_EXTERNAL_HANDLE);
239 CASE(VK_ERROR_NOT_PERMITTED_EXT);
240 CASE(VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT);
241 CASE(VK_ERROR_INVALID_DEVICE_ADDRESS_EXT);
242 CASE(VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT);
243 default: return "Unknown error";
248 static VkBool32 vk_dbg_callback(VkDebugUtilsMessageSeverityFlagBitsEXT severity,
249 VkDebugUtilsMessageTypeFlagsEXT messageType,
250 const VkDebugUtilsMessengerCallbackDataEXT *data,
254 AVHWDeviceContext *ctx = priv;
257 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT: l = AV_LOG_VERBOSE; break;
258 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT: l = AV_LOG_INFO; break;
259 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT: l = AV_LOG_WARNING; break;
260 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT: l = AV_LOG_ERROR; break;
261 default: l = AV_LOG_DEBUG; break;
264 av_log(ctx, l, "%s\n", data->pMessage);
265 for (int i = 0; i < data->cmdBufLabelCount; i++)
266 av_log(ctx, l, "\t%i: %s\n", i, data->pCmdBufLabels[i].pLabelName);
271 static int check_extensions(AVHWDeviceContext *ctx, int dev, AVDictionary *opts,
272 const char * const **dst, uint32_t *num, int debug)
275 const char **extension_names = NULL;
276 VulkanDevicePriv *p = ctx->internal->priv;
277 AVVulkanDeviceContext *hwctx = ctx->hwctx;
278 int err = 0, found, extensions_found = 0;
281 int optional_exts_num;
282 uint32_t sup_ext_count;
283 char *user_exts_str = NULL;
284 AVDictionaryEntry *user_exts;
285 VkExtensionProperties *sup_ext;
286 const VulkanOptExtension *optional_exts;
290 optional_exts = optional_instance_exts;
291 optional_exts_num = FF_ARRAY_ELEMS(optional_instance_exts);
292 user_exts = av_dict_get(opts, "instance_extensions", NULL, 0);
294 user_exts_str = av_strdup(user_exts->value);
295 if (!user_exts_str) {
296 err = AVERROR(ENOMEM);
300 vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, NULL);
301 sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
303 return AVERROR(ENOMEM);
304 vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, sup_ext);
307 optional_exts = optional_device_exts;
308 optional_exts_num = FF_ARRAY_ELEMS(optional_device_exts);
309 user_exts = av_dict_get(opts, "device_extensions", NULL, 0);
311 user_exts_str = av_strdup(user_exts->value);
312 if (!user_exts_str) {
313 err = AVERROR(ENOMEM);
317 vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
318 &sup_ext_count, NULL);
319 sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
321 return AVERROR(ENOMEM);
322 vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
323 &sup_ext_count, sup_ext);
326 for (int i = 0; i < optional_exts_num; i++) {
327 tstr = optional_exts[i].name;
329 for (int j = 0; j < sup_ext_count; j++) {
330 if (!strcmp(tstr, sup_ext[j].extensionName)) {
338 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
339 p->extensions |= optional_exts[i].flag;
340 ADD_VAL_TO_LIST(extension_names, extensions_found, tstr);
344 tstr = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
346 for (int j = 0; j < sup_ext_count; j++) {
347 if (!strcmp(tstr, sup_ext[j].extensionName)) {
353 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
354 ADD_VAL_TO_LIST(extension_names, extensions_found, tstr);
356 av_log(ctx, AV_LOG_ERROR, "Debug extension \"%s\" not found!\n",
358 err = AVERROR(EINVAL);
364 char *save, *token = av_strtok(user_exts_str, "+", &save);
367 for (int j = 0; j < sup_ext_count; j++) {
368 if (!strcmp(token, sup_ext[j].extensionName)) {
374 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
375 ADD_VAL_TO_LIST(extension_names, extensions_found, token);
377 av_log(ctx, AV_LOG_ERROR, "%s extension \"%s\" not found!\n",
379 err = AVERROR(EINVAL);
382 token = av_strtok(NULL, "+", &save);
386 *dst = extension_names;
387 *num = extensions_found;
389 av_free(user_exts_str);
395 for (int i = 0; i < extensions_found; i++)
396 av_free((void *)extension_names[i]);
397 av_free(extension_names);
398 av_free(user_exts_str);
403 /* Creates a VkInstance */
404 static int create_instance(AVHWDeviceContext *ctx, AVDictionary *opts)
408 VulkanDevicePriv *p = ctx->internal->priv;
409 AVVulkanDeviceContext *hwctx = ctx->hwctx;
410 AVDictionaryEntry *debug_opt = av_dict_get(opts, "debug", NULL, 0);
411 const int debug_mode = debug_opt && strtol(debug_opt->value, NULL, 10);
412 VkApplicationInfo application_info = {
413 .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
414 .pEngineName = "libavutil",
415 .apiVersion = VK_API_VERSION_1_1,
416 .engineVersion = VK_MAKE_VERSION(LIBAVUTIL_VERSION_MAJOR,
417 LIBAVUTIL_VERSION_MINOR,
418 LIBAVUTIL_VERSION_MICRO),
420 VkInstanceCreateInfo inst_props = {
421 .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
422 .pApplicationInfo = &application_info,
425 /* Check for present/missing extensions */
426 err = check_extensions(ctx, 0, opts, &inst_props.ppEnabledExtensionNames,
427 &inst_props.enabledExtensionCount, debug_mode);
432 static const char *layers[] = { "VK_LAYER_KHRONOS_validation" };
433 inst_props.ppEnabledLayerNames = layers;
434 inst_props.enabledLayerCount = FF_ARRAY_ELEMS(layers);
437 /* Try to create the instance */
438 ret = vkCreateInstance(&inst_props, hwctx->alloc, &hwctx->inst);
440 /* Check for errors */
441 if (ret != VK_SUCCESS) {
442 av_log(ctx, AV_LOG_ERROR, "Instance creation failure: %s\n",
444 for (int i = 0; i < inst_props.enabledExtensionCount; i++)
445 av_free((void *)inst_props.ppEnabledExtensionNames[i]);
446 av_free((void *)inst_props.ppEnabledExtensionNames);
447 return AVERROR_EXTERNAL;
451 VkDebugUtilsMessengerCreateInfoEXT dbg = {
452 .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT,
453 .messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT |
454 VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT |
455 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
456 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT,
457 .messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
458 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
459 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT,
460 .pfnUserCallback = vk_dbg_callback,
463 VK_LOAD_PFN(hwctx->inst, vkCreateDebugUtilsMessengerEXT);
465 pfn_vkCreateDebugUtilsMessengerEXT(hwctx->inst, &dbg,
466 hwctx->alloc, &p->debug_ctx);
469 hwctx->enabled_inst_extensions = inst_props.ppEnabledExtensionNames;
470 hwctx->nb_enabled_inst_extensions = inst_props.enabledExtensionCount;
475 typedef struct VulkanDeviceSelection {
476 uint8_t uuid[VK_UUID_SIZE]; /* Will use this first unless !has_uuid */
478 const char *name; /* Will use this second unless NULL */
479 uint32_t pci_device; /* Will use this third unless 0x0 */
480 uint32_t vendor_id; /* Last resort to find something deterministic */
481 int index; /* Finally fall back to index */
482 } VulkanDeviceSelection;
484 static const char *vk_dev_type(enum VkPhysicalDeviceType type)
487 case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: return "integrated";
488 case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: return "discrete";
489 case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: return "virtual";
490 case VK_PHYSICAL_DEVICE_TYPE_CPU: return "software";
491 default: return "unknown";
496 static int find_device(AVHWDeviceContext *ctx, VulkanDeviceSelection *select)
498 int err = 0, choice = -1;
501 VkPhysicalDevice *devices = NULL;
502 VkPhysicalDeviceIDProperties *idp = NULL;
503 VkPhysicalDeviceProperties2 *prop = NULL;
504 VulkanDevicePriv *p = ctx->internal->priv;
505 AVVulkanDeviceContext *hwctx = ctx->hwctx;
507 ret = vkEnumeratePhysicalDevices(hwctx->inst, &num, NULL);
508 if (ret != VK_SUCCESS || !num) {
509 av_log(ctx, AV_LOG_ERROR, "No devices found: %s!\n", vk_ret2str(ret));
510 return AVERROR(ENODEV);
513 devices = av_malloc_array(num, sizeof(VkPhysicalDevice));
515 return AVERROR(ENOMEM);
517 ret = vkEnumeratePhysicalDevices(hwctx->inst, &num, devices);
518 if (ret != VK_SUCCESS) {
519 av_log(ctx, AV_LOG_ERROR, "Failed enumerating devices: %s\n",
521 err = AVERROR(ENODEV);
525 prop = av_mallocz_array(num, sizeof(*prop));
527 err = AVERROR(ENOMEM);
531 idp = av_mallocz_array(num, sizeof(*idp));
533 err = AVERROR(ENOMEM);
537 av_log(ctx, AV_LOG_VERBOSE, "GPU listing:\n");
538 for (int i = 0; i < num; i++) {
539 idp[i].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES;
540 prop[i].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
541 prop[i].pNext = &idp[i];
543 vkGetPhysicalDeviceProperties2(devices[i], &prop[i]);
544 av_log(ctx, AV_LOG_VERBOSE, " %d: %s (%s) (0x%x)\n", i,
545 prop[i].properties.deviceName,
546 vk_dev_type(prop[i].properties.deviceType),
547 prop[i].properties.deviceID);
550 if (select->has_uuid) {
551 for (int i = 0; i < num; i++) {
552 if (!strncmp(idp[i].deviceUUID, select->uuid, VK_UUID_SIZE)) {
557 av_log(ctx, AV_LOG_ERROR, "Unable to find device by given UUID!\n");
558 err = AVERROR(ENODEV);
560 } else if (select->name) {
561 av_log(ctx, AV_LOG_VERBOSE, "Requested device: %s\n", select->name);
562 for (int i = 0; i < num; i++) {
563 if (strstr(prop[i].properties.deviceName, select->name)) {
568 av_log(ctx, AV_LOG_ERROR, "Unable to find device \"%s\"!\n",
570 err = AVERROR(ENODEV);
572 } else if (select->pci_device) {
573 av_log(ctx, AV_LOG_VERBOSE, "Requested device: 0x%x\n", select->pci_device);
574 for (int i = 0; i < num; i++) {
575 if (select->pci_device == prop[i].properties.deviceID) {
580 av_log(ctx, AV_LOG_ERROR, "Unable to find device with PCI ID 0x%x!\n",
582 err = AVERROR(EINVAL);
584 } else if (select->vendor_id) {
585 av_log(ctx, AV_LOG_VERBOSE, "Requested vendor: 0x%x\n", select->vendor_id);
586 for (int i = 0; i < num; i++) {
587 if (select->vendor_id == prop[i].properties.vendorID) {
592 av_log(ctx, AV_LOG_ERROR, "Unable to find device with Vendor ID 0x%x!\n",
594 err = AVERROR(ENODEV);
597 if (select->index < num) {
598 choice = select->index;
601 av_log(ctx, AV_LOG_ERROR, "Unable to find device with index %i!\n",
603 err = AVERROR(ENODEV);
609 p->dev_is_nvidia = (prop[choice].properties.vendorID == 0x10de);
610 hwctx->phys_dev = devices[choice];
619 static int search_queue_families(AVHWDeviceContext *ctx, VkDeviceCreateInfo *cd)
622 VkQueueFamilyProperties *qs = NULL;
623 AVVulkanDeviceContext *hwctx = ctx->hwctx;
624 int graph_index = -1, comp_index = -1, tx_index = -1;
625 VkDeviceQueueCreateInfo *pc = (VkDeviceQueueCreateInfo *)cd->pQueueCreateInfos;
627 /* First get the number of queue families */
628 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, NULL);
630 av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
631 return AVERROR_EXTERNAL;
634 /* Then allocate memory */
635 qs = av_malloc_array(num, sizeof(VkQueueFamilyProperties));
637 return AVERROR(ENOMEM);
639 /* Finally retrieve the queue families */
640 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, qs);
642 #define SEARCH_FLAGS(expr, out) \
643 for (int i = 0; i < num; i++) { \
644 const VkQueueFlagBits flags = qs[i].queueFlags; \
651 SEARCH_FLAGS(flags & VK_QUEUE_GRAPHICS_BIT, graph_index)
653 SEARCH_FLAGS((flags & VK_QUEUE_COMPUTE_BIT) && (i != graph_index),
656 SEARCH_FLAGS((flags & VK_QUEUE_TRANSFER_BIT) && (i != graph_index) &&
657 (i != comp_index), tx_index)
660 #define QF_FLAGS(flags) \
661 ((flags) & VK_QUEUE_GRAPHICS_BIT ) ? "(graphics) " : "", \
662 ((flags) & VK_QUEUE_COMPUTE_BIT ) ? "(compute) " : "", \
663 ((flags) & VK_QUEUE_TRANSFER_BIT ) ? "(transfer) " : "", \
664 ((flags) & VK_QUEUE_SPARSE_BINDING_BIT) ? "(sparse) " : ""
666 av_log(ctx, AV_LOG_VERBOSE, "Using queue family %i for graphics, "
667 "flags: %s%s%s%s\n", graph_index, QF_FLAGS(qs[graph_index].queueFlags));
669 hwctx->queue_family_index = graph_index;
670 hwctx->queue_family_tx_index = graph_index;
671 hwctx->queue_family_comp_index = graph_index;
673 pc[cd->queueCreateInfoCount++].queueFamilyIndex = graph_index;
675 if (comp_index != -1) {
676 av_log(ctx, AV_LOG_VERBOSE, "Using queue family %i for compute, "
677 "flags: %s%s%s%s\n", comp_index, QF_FLAGS(qs[comp_index].queueFlags));
678 hwctx->queue_family_tx_index = comp_index;
679 hwctx->queue_family_comp_index = comp_index;
680 pc[cd->queueCreateInfoCount++].queueFamilyIndex = comp_index;
683 if (tx_index != -1) {
684 av_log(ctx, AV_LOG_VERBOSE, "Using queue family %i for transfers, "
685 "flags: %s%s%s%s\n", tx_index, QF_FLAGS(qs[tx_index].queueFlags));
686 hwctx->queue_family_tx_index = tx_index;
687 pc[cd->queueCreateInfoCount++].queueFamilyIndex = tx_index;
697 static int create_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd,
698 int queue_family_index)
701 AVVulkanDeviceContext *hwctx = ctx->hwctx;
703 VkCommandPoolCreateInfo cqueue_create = {
704 .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
705 .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
706 .queueFamilyIndex = queue_family_index,
708 VkCommandBufferAllocateInfo cbuf_create = {
709 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
710 .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
711 .commandBufferCount = 1,
714 VkFenceCreateInfo fence_spawn = {
715 .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
718 ret = vkCreateFence(hwctx->act_dev, &fence_spawn,
719 hwctx->alloc, &cmd->fence);
720 if (ret != VK_SUCCESS) {
721 av_log(ctx, AV_LOG_ERROR, "Failed to create frame fence: %s\n",
723 return AVERROR_EXTERNAL;
726 ret = vkCreateCommandPool(hwctx->act_dev, &cqueue_create,
727 hwctx->alloc, &cmd->pool);
728 if (ret != VK_SUCCESS) {
729 av_log(ctx, AV_LOG_ERROR, "Command pool creation failure: %s\n",
731 return AVERROR_EXTERNAL;
734 cbuf_create.commandPool = cmd->pool;
736 ret = vkAllocateCommandBuffers(hwctx->act_dev, &cbuf_create, &cmd->buf);
737 if (ret != VK_SUCCESS) {
738 av_log(ctx, AV_LOG_ERROR, "Command buffer alloc failure: %s\n",
740 return AVERROR_EXTERNAL;
743 vkGetDeviceQueue(hwctx->act_dev, cqueue_create.queueFamilyIndex, 0,
749 static void free_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd)
751 AVVulkanDeviceContext *hwctx = ctx->hwctx;
754 vkDestroyFence(hwctx->act_dev, cmd->fence, hwctx->alloc);
756 vkFreeCommandBuffers(hwctx->act_dev, cmd->pool, 1, &cmd->buf);
758 vkDestroyCommandPool(hwctx->act_dev, cmd->pool, hwctx->alloc);
761 static void vulkan_device_free(AVHWDeviceContext *ctx)
763 VulkanDevicePriv *p = ctx->internal->priv;
764 AVVulkanDeviceContext *hwctx = ctx->hwctx;
766 free_exec_ctx(ctx, &p->cmd);
768 vkDestroyDevice(hwctx->act_dev, hwctx->alloc);
771 VK_LOAD_PFN(hwctx->inst, vkDestroyDebugUtilsMessengerEXT);
772 pfn_vkDestroyDebugUtilsMessengerEXT(hwctx->inst, p->debug_ctx,
776 vkDestroyInstance(hwctx->inst, hwctx->alloc);
778 for (int i = 0; i < hwctx->nb_enabled_inst_extensions; i++)
779 av_free((void *)hwctx->enabled_inst_extensions[i]);
780 av_free((void *)hwctx->enabled_inst_extensions);
782 for (int i = 0; i < hwctx->nb_enabled_dev_extensions; i++)
783 av_free((void *)hwctx->enabled_dev_extensions[i]);
784 av_free((void *)hwctx->enabled_dev_extensions);
787 static int vulkan_device_create_internal(AVHWDeviceContext *ctx,
788 VulkanDeviceSelection *dev_select,
789 AVDictionary *opts, int flags)
793 AVDictionaryEntry *opt_d;
794 VulkanDevicePriv *p = ctx->internal->priv;
795 AVVulkanDeviceContext *hwctx = ctx->hwctx;
796 VkDeviceQueueCreateInfo queue_create_info[3] = {
797 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
798 .pQueuePriorities = (float []){ 1.0f },
800 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
801 .pQueuePriorities = (float []){ 1.0f },
803 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
804 .pQueuePriorities = (float []){ 1.0f },
808 VkDeviceCreateInfo dev_info = {
809 .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
810 .pQueueCreateInfos = queue_create_info,
811 .queueCreateInfoCount = 0,
814 ctx->free = vulkan_device_free;
816 /* Create an instance if not given one */
817 if ((err = create_instance(ctx, opts)))
820 /* Find a device (if not given one) */
821 if ((err = find_device(ctx, dev_select)))
824 vkGetPhysicalDeviceProperties(hwctx->phys_dev, &p->props);
825 av_log(ctx, AV_LOG_VERBOSE, "Using device: %s\n", p->props.deviceName);
826 av_log(ctx, AV_LOG_VERBOSE, "Alignments:\n");
827 av_log(ctx, AV_LOG_VERBOSE, " optimalBufferCopyOffsetAlignment: %li\n",
828 p->props.limits.optimalBufferCopyOffsetAlignment);
829 av_log(ctx, AV_LOG_VERBOSE, " optimalBufferCopyRowPitchAlignment: %li\n",
830 p->props.limits.optimalBufferCopyRowPitchAlignment);
831 av_log(ctx, AV_LOG_VERBOSE, " minMemoryMapAlignment: %li\n",
832 p->props.limits.minMemoryMapAlignment);
834 /* Search queue family */
835 if ((err = search_queue_families(ctx, &dev_info)))
838 if ((err = check_extensions(ctx, 1, opts, &dev_info.ppEnabledExtensionNames,
839 &dev_info.enabledExtensionCount, 0)))
842 ret = vkCreateDevice(hwctx->phys_dev, &dev_info, hwctx->alloc,
845 if (ret != VK_SUCCESS) {
846 av_log(ctx, AV_LOG_ERROR, "Device creation failure: %s\n",
848 for (int i = 0; i < dev_info.enabledExtensionCount; i++)
849 av_free((void *)dev_info.ppEnabledExtensionNames[i]);
850 av_free((void *)dev_info.ppEnabledExtensionNames);
851 err = AVERROR_EXTERNAL;
855 /* Tiled images setting, use them by default */
856 opt_d = av_dict_get(opts, "linear_images", NULL, 0);
858 p->use_linear_images = strtol(opt_d->value, NULL, 10);
860 hwctx->enabled_dev_extensions = dev_info.ppEnabledExtensionNames;
861 hwctx->nb_enabled_dev_extensions = dev_info.enabledExtensionCount;
867 static int vulkan_device_init(AVHWDeviceContext *ctx)
871 AVVulkanDeviceContext *hwctx = ctx->hwctx;
872 VulkanDevicePriv *p = ctx->internal->priv;
874 /* Set device extension flags */
875 for (int i = 0; i < hwctx->nb_enabled_dev_extensions; i++) {
876 for (int j = 0; j < FF_ARRAY_ELEMS(optional_device_exts); j++) {
877 if (!strcmp(hwctx->enabled_dev_extensions[i],
878 optional_device_exts[j].name)) {
879 p->extensions |= optional_device_exts[j].flag;
885 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &queue_num, NULL);
887 av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
888 return AVERROR_EXTERNAL;
891 #define CHECK_QUEUE(type, n) \
892 if (n >= queue_num) { \
893 av_log(ctx, AV_LOG_ERROR, "Invalid %s queue index %i (device has %i queues)!\n", \
894 type, n, queue_num); \
895 return AVERROR(EINVAL); \
898 CHECK_QUEUE("graphics", hwctx->queue_family_index)
899 CHECK_QUEUE("upload", hwctx->queue_family_tx_index)
900 CHECK_QUEUE("compute", hwctx->queue_family_comp_index)
904 p->qfs[p->num_qfs++] = hwctx->queue_family_index;
905 if ((hwctx->queue_family_tx_index != hwctx->queue_family_index) &&
906 (hwctx->queue_family_tx_index != hwctx->queue_family_comp_index))
907 p->qfs[p->num_qfs++] = hwctx->queue_family_tx_index;
908 if ((hwctx->queue_family_comp_index != hwctx->queue_family_index) &&
909 (hwctx->queue_family_comp_index != hwctx->queue_family_tx_index))
910 p->qfs[p->num_qfs++] = hwctx->queue_family_comp_index;
912 /* Create exec context - if there's something invalid this will error out */
913 err = create_exec_ctx(ctx, &p->cmd, hwctx->queue_family_tx_index);
917 /* Get device capabilities */
918 vkGetPhysicalDeviceMemoryProperties(hwctx->phys_dev, &p->mprops);
923 static int vulkan_device_create(AVHWDeviceContext *ctx, const char *device,
924 AVDictionary *opts, int flags)
926 VulkanDeviceSelection dev_select = { 0 };
927 if (device && device[0]) {
929 dev_select.index = strtol(device, &end, 10);
931 dev_select.index = 0;
932 dev_select.name = device;
936 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
939 static int vulkan_device_derive(AVHWDeviceContext *ctx,
940 AVHWDeviceContext *src_ctx, int flags)
942 av_unused VulkanDeviceSelection dev_select = { 0 };
944 /* If there's only one device on the system, then even if its not covered
945 * by the following checks (e.g. non-PCIe ARM GPU), having an empty
946 * dev_select will mean it'll get picked. */
947 switch(src_ctx->type) {
950 case AV_HWDEVICE_TYPE_VAAPI: {
951 AVVAAPIDeviceContext *src_hwctx = src_ctx->hwctx;
953 const char *vendor = vaQueryVendorString(src_hwctx->display);
955 av_log(ctx, AV_LOG_ERROR, "Unable to get device info from VAAPI!\n");
956 return AVERROR_EXTERNAL;
959 if (strstr(vendor, "Intel"))
960 dev_select.vendor_id = 0x8086;
961 if (strstr(vendor, "AMD"))
962 dev_select.vendor_id = 0x1002;
964 return vulkan_device_create_internal(ctx, &dev_select, NULL, flags);
967 case AV_HWDEVICE_TYPE_DRM: {
968 AVDRMDeviceContext *src_hwctx = src_ctx->hwctx;
970 drmDevice *drm_dev_info;
971 int err = drmGetDevice(src_hwctx->fd, &drm_dev_info);
973 av_log(ctx, AV_LOG_ERROR, "Unable to get device info from DRM fd!\n");
974 return AVERROR_EXTERNAL;
977 if (drm_dev_info->bustype == DRM_BUS_PCI)
978 dev_select.pci_device = drm_dev_info->deviceinfo.pci->device_id;
980 drmFreeDevice(&drm_dev_info);
982 return vulkan_device_create_internal(ctx, &dev_select, NULL, flags);
986 case AV_HWDEVICE_TYPE_CUDA: {
987 AVHWDeviceContext *cuda_cu = src_ctx;
988 AVCUDADeviceContext *src_hwctx = src_ctx->hwctx;
989 AVCUDADeviceContextInternal *cu_internal = src_hwctx->internal;
990 CudaFunctions *cu = cu_internal->cuda_dl;
992 int ret = CHECK_CU(cu->cuDeviceGetUuid((CUuuid *)&dev_select.uuid,
993 cu_internal->cuda_device));
995 av_log(ctx, AV_LOG_ERROR, "Unable to get UUID from CUDA!\n");
996 return AVERROR_EXTERNAL;
999 dev_select.has_uuid = 1;
1001 return vulkan_device_create_internal(ctx, &dev_select, NULL, flags);
1005 return AVERROR(ENOSYS);
1009 static int vulkan_frames_get_constraints(AVHWDeviceContext *ctx,
1010 const void *hwconfig,
1011 AVHWFramesConstraints *constraints)
1014 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1015 VulkanDevicePriv *p = ctx->internal->priv;
1017 for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
1018 count += pixfmt_is_supported(hwctx, i, p->use_linear_images);
1021 if (p->dev_is_nvidia)
1025 constraints->valid_sw_formats = av_malloc_array(count + 1,
1026 sizeof(enum AVPixelFormat));
1027 if (!constraints->valid_sw_formats)
1028 return AVERROR(ENOMEM);
1031 for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
1032 if (pixfmt_is_supported(hwctx, i, p->use_linear_images))
1033 constraints->valid_sw_formats[count++] = i;
1036 if (p->dev_is_nvidia)
1037 constraints->valid_sw_formats[count++] = AV_PIX_FMT_CUDA;
1039 constraints->valid_sw_formats[count++] = AV_PIX_FMT_NONE;
1041 constraints->min_width = 0;
1042 constraints->min_height = 0;
1043 constraints->max_width = p->props.limits.maxImageDimension2D;
1044 constraints->max_height = p->props.limits.maxImageDimension2D;
1046 constraints->valid_hw_formats = av_malloc_array(2, sizeof(enum AVPixelFormat));
1047 if (!constraints->valid_hw_formats)
1048 return AVERROR(ENOMEM);
1050 constraints->valid_hw_formats[0] = AV_PIX_FMT_VULKAN;
1051 constraints->valid_hw_formats[1] = AV_PIX_FMT_NONE;
1056 static int alloc_mem(AVHWDeviceContext *ctx, VkMemoryRequirements *req,
1057 VkMemoryPropertyFlagBits req_flags, void *alloc_extension,
1058 VkMemoryPropertyFlagBits *mem_flags, VkDeviceMemory *mem)
1062 VulkanDevicePriv *p = ctx->internal->priv;
1063 AVVulkanDeviceContext *dev_hwctx = ctx->hwctx;
1064 VkMemoryAllocateInfo alloc_info = {
1065 .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
1066 .pNext = alloc_extension,
1069 /* Align if we need to */
1070 if (req_flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)
1071 req->size = FFALIGN(req->size, p->props.limits.minMemoryMapAlignment);
1073 alloc_info.allocationSize = req->size;
1075 /* The vulkan spec requires memory types to be sorted in the "optimal"
1076 * order, so the first matching type we find will be the best/fastest one */
1077 for (int i = 0; i < p->mprops.memoryTypeCount; i++) {
1078 /* The memory type must be supported by the requirements (bitfield) */
1079 if (!(req->memoryTypeBits & (1 << i)))
1082 /* The memory type flags must include our properties */
1083 if ((p->mprops.memoryTypes[i].propertyFlags & req_flags) != req_flags)
1086 /* Found a suitable memory type */
1092 av_log(ctx, AV_LOG_ERROR, "No memory type found for flags 0x%x\n",
1094 return AVERROR(EINVAL);
1097 alloc_info.memoryTypeIndex = index;
1099 ret = vkAllocateMemory(dev_hwctx->act_dev, &alloc_info,
1100 dev_hwctx->alloc, mem);
1101 if (ret != VK_SUCCESS) {
1102 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory: %s\n",
1104 return AVERROR(ENOMEM);
1107 *mem_flags |= p->mprops.memoryTypes[index].propertyFlags;
1112 static void vulkan_free_internal(AVVkFrameInternal *internal)
1118 if (internal->cuda_fc_ref) {
1119 AVHWFramesContext *cuda_fc = (AVHWFramesContext *)internal->cuda_fc_ref->data;
1120 int planes = av_pix_fmt_count_planes(cuda_fc->sw_format);
1121 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
1122 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
1123 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
1124 CudaFunctions *cu = cu_internal->cuda_dl;
1126 if (internal->cu_sem)
1127 CHECK_CU(cu->cuDestroyExternalSemaphore(internal->cu_sem));
1129 for (int i = 0; i < planes; i++) {
1130 if (internal->cu_mma[i])
1131 CHECK_CU(cu->cuMipmappedArrayDestroy(internal->cu_mma[i]));
1132 if (internal->ext_mem[i])
1133 CHECK_CU(cu->cuDestroyExternalMemory(internal->ext_mem[i]));
1136 av_buffer_unref(&internal->cuda_fc_ref);
1143 static void vulkan_frame_free(void *opaque, uint8_t *data)
1145 AVVkFrame *f = (AVVkFrame *)data;
1146 AVHWFramesContext *hwfc = opaque;
1147 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1148 int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1150 vulkan_free_internal(f->internal);
1152 for (int i = 0; i < planes; i++) {
1153 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
1154 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
1157 vkDestroySemaphore(hwctx->act_dev, f->sem, hwctx->alloc);
1162 static int alloc_bind_mem(AVHWFramesContext *hwfc, AVVkFrame *f,
1163 void *alloc_pnext, size_t alloc_pnext_stride)
1167 AVHWDeviceContext *ctx = hwfc->device_ctx;
1168 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1169 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { { 0 } };
1171 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1173 for (int i = 0; i < planes; i++) {
1175 VkImageMemoryRequirementsInfo2 req_desc = {
1176 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
1179 VkMemoryDedicatedAllocateInfo ded_alloc = {
1180 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
1181 .pNext = (void *)(((uint8_t *)alloc_pnext) + i*alloc_pnext_stride),
1183 VkMemoryDedicatedRequirements ded_req = {
1184 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
1186 VkMemoryRequirements2 req = {
1187 .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
1191 vkGetImageMemoryRequirements2(hwctx->act_dev, &req_desc, &req);
1193 /* In case the implementation prefers/requires dedicated allocation */
1194 use_ded_mem = ded_req.prefersDedicatedAllocation |
1195 ded_req.requiresDedicatedAllocation;
1197 ded_alloc.image = f->img[i];
1199 /* Allocate memory */
1200 if ((err = alloc_mem(ctx, &req.memoryRequirements,
1201 f->tiling == VK_IMAGE_TILING_LINEAR ?
1202 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT :
1203 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1204 use_ded_mem ? &ded_alloc : (void *)ded_alloc.pNext,
1205 &f->flags, &f->mem[i])))
1208 f->size[i] = req.memoryRequirements.size;
1209 bind_info[i].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
1210 bind_info[i].image = f->img[i];
1211 bind_info[i].memory = f->mem[i];
1214 /* Bind the allocated memory to the images */
1215 ret = vkBindImageMemory2(hwctx->act_dev, planes, bind_info);
1216 if (ret != VK_SUCCESS) {
1217 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
1219 return AVERROR_EXTERNAL;
1227 PREP_MODE_RO_SHADER,
1230 static int prepare_frame(AVHWFramesContext *hwfc, VulkanExecCtx *ectx,
1231 AVVkFrame *frame, enum PrepMode pmode)
1234 VkImageLayout new_layout;
1235 VkAccessFlags new_access;
1236 AVHWDeviceContext *ctx = hwfc->device_ctx;
1237 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1238 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1240 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
1242 VkCommandBufferBeginInfo cmd_start = {
1243 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
1244 .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
1247 VkSubmitInfo s_info = {
1248 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
1249 .commandBufferCount = 1,
1250 .pCommandBuffers = &ectx->buf,
1252 .pSignalSemaphores = &frame->sem,
1253 .signalSemaphoreCount = 1,
1257 case PREP_MODE_WRITE:
1258 new_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
1259 new_access = VK_ACCESS_TRANSFER_WRITE_BIT;
1261 case PREP_MODE_RO_SHADER:
1262 new_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
1263 new_access = VK_ACCESS_TRANSFER_READ_BIT;
1267 ret = vkBeginCommandBuffer(ectx->buf, &cmd_start);
1268 if (ret != VK_SUCCESS)
1269 return AVERROR_EXTERNAL;
1271 /* Change the image layout to something more optimal for writes.
1272 * This also signals the newly created semaphore, making it usable
1273 * for synchronization */
1274 for (int i = 0; i < planes; i++) {
1275 img_bar[i].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1276 img_bar[i].srcAccessMask = 0x0;
1277 img_bar[i].dstAccessMask = new_access;
1278 img_bar[i].oldLayout = frame->layout[i];
1279 img_bar[i].newLayout = new_layout;
1280 img_bar[i].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1281 img_bar[i].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1282 img_bar[i].image = frame->img[i];
1283 img_bar[i].subresourceRange.levelCount = 1;
1284 img_bar[i].subresourceRange.layerCount = 1;
1285 img_bar[i].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1287 frame->layout[i] = img_bar[i].newLayout;
1288 frame->access[i] = img_bar[i].dstAccessMask;
1291 vkCmdPipelineBarrier(ectx->buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
1292 VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
1293 0, NULL, 0, NULL, planes, img_bar);
1295 ret = vkEndCommandBuffer(ectx->buf);
1296 if (ret != VK_SUCCESS)
1297 return AVERROR_EXTERNAL;
1299 ret = vkQueueSubmit(ectx->queue, 1, &s_info, ectx->fence);
1300 if (ret != VK_SUCCESS) {
1301 return AVERROR_EXTERNAL;
1303 vkWaitForFences(hwctx->act_dev, 1, &ectx->fence, VK_TRUE, UINT64_MAX);
1304 vkResetFences(hwctx->act_dev, 1, &ectx->fence);
1310 static int create_frame(AVHWFramesContext *hwfc, AVVkFrame **frame,
1311 VkImageTiling tiling, VkImageUsageFlagBits usage,
1316 AVHWDeviceContext *ctx = hwfc->device_ctx;
1317 VulkanDevicePriv *p = ctx->internal->priv;
1318 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1319 enum AVPixelFormat format = hwfc->sw_format;
1320 const VkFormat *img_fmts = av_vkfmt_from_pixfmt(format);
1321 const int planes = av_pix_fmt_count_planes(format);
1323 VkExportSemaphoreCreateInfo ext_sem_info = {
1324 .sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO,
1325 .handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
1328 VkSemaphoreCreateInfo sem_spawn = {
1329 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1330 .pNext = p->extensions & EXT_EXTERNAL_FD_SEM ? &ext_sem_info : NULL,
1333 AVVkFrame *f = av_vk_frame_alloc();
1335 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1336 return AVERROR(ENOMEM);
1339 /* Create the images */
1340 for (int i = 0; i < planes; i++) {
1341 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
1342 int w = hwfc->width;
1343 int h = hwfc->height;
1344 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
1345 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
1347 VkImageCreateInfo image_create_info = {
1348 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1349 .pNext = create_pnext,
1350 .imageType = VK_IMAGE_TYPE_2D,
1351 .format = img_fmts[i],
1352 .extent.width = p_w,
1353 .extent.height = p_h,
1357 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1359 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1361 .samples = VK_SAMPLE_COUNT_1_BIT,
1362 .pQueueFamilyIndices = p->qfs,
1363 .queueFamilyIndexCount = p->num_qfs,
1364 .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
1365 VK_SHARING_MODE_EXCLUSIVE,
1368 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
1369 hwctx->alloc, &f->img[i]);
1370 if (ret != VK_SUCCESS) {
1371 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1373 err = AVERROR(EINVAL);
1377 f->layout[i] = image_create_info.initialLayout;
1381 /* Create semaphore */
1382 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1383 hwctx->alloc, &f->sem);
1384 if (ret != VK_SUCCESS) {
1385 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1387 return AVERROR_EXTERNAL;
1397 vulkan_frame_free(hwfc, (uint8_t *)f);
1401 /* Checks if an export flag is enabled, and if it is ORs it with *iexp */
1402 static void try_export_flags(AVHWFramesContext *hwfc,
1403 VkExternalMemoryHandleTypeFlags *comp_handle_types,
1404 VkExternalMemoryHandleTypeFlagBits *iexp,
1405 VkExternalMemoryHandleTypeFlagBits exp)
1408 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1409 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1410 VkExternalImageFormatProperties eprops = {
1411 .sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES_KHR,
1413 VkImageFormatProperties2 props = {
1414 .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,
1417 VkPhysicalDeviceExternalImageFormatInfo enext = {
1418 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
1421 VkPhysicalDeviceImageFormatInfo2 pinfo = {
1422 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1423 .pNext = !exp ? NULL : &enext,
1424 .format = av_vkfmt_from_pixfmt(hwfc->sw_format)[0],
1425 .type = VK_IMAGE_TYPE_2D,
1426 .tiling = hwctx->tiling,
1427 .usage = hwctx->usage,
1428 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1431 ret = vkGetPhysicalDeviceImageFormatProperties2(dev_hwctx->phys_dev,
1433 if (ret == VK_SUCCESS) {
1435 *comp_handle_types |= eprops.externalMemoryProperties.compatibleHandleTypes;
1439 static AVBufferRef *vulkan_pool_alloc(void *opaque, int size)
1443 AVBufferRef *avbuf = NULL;
1444 AVHWFramesContext *hwfc = opaque;
1445 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1446 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1447 VkExportMemoryAllocateInfo eminfo[AV_NUM_DATA_POINTERS];
1448 VkExternalMemoryHandleTypeFlags e = 0x0;
1450 VkExternalMemoryImageCreateInfo eiinfo = {
1451 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1452 .pNext = hwctx->create_pnext,
1455 if (p->extensions & EXT_EXTERNAL_FD_MEMORY)
1456 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1457 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT);
1459 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
1460 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1461 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
1463 for (int i = 0; i < av_pix_fmt_count_planes(hwfc->sw_format); i++) {
1464 eminfo[i].sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO;
1465 eminfo[i].pNext = hwctx->alloc_pnext[i];
1466 eminfo[i].handleTypes = e;
1469 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1470 eiinfo.handleTypes ? &eiinfo : NULL);
1474 err = alloc_bind_mem(hwfc, f, eminfo, sizeof(*eminfo));
1478 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_WRITE);
1482 avbuf = av_buffer_create((uint8_t *)f, sizeof(AVVkFrame),
1483 vulkan_frame_free, hwfc, 0);
1490 vulkan_frame_free(hwfc, (uint8_t *)f);
1494 static void vulkan_frames_uninit(AVHWFramesContext *hwfc)
1496 VulkanFramesPriv *fp = hwfc->internal->priv;
1498 free_exec_ctx(hwfc->device_ctx, &fp->cmd);
1501 static int vulkan_frames_init(AVHWFramesContext *hwfc)
1505 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1506 VulkanFramesPriv *fp = hwfc->internal->priv;
1507 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1508 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1513 /* Default pool flags */
1514 hwctx->tiling = hwctx->tiling ? hwctx->tiling : p->use_linear_images ?
1515 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1517 hwctx->usage |= DEFAULT_USAGE_FLAGS;
1519 err = create_exec_ctx(hwfc->device_ctx, &fp->cmd,
1520 dev_hwctx->queue_family_tx_index);
1524 /* Test to see if allocation will fail */
1525 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1526 hwctx->create_pnext);
1528 free_exec_ctx(hwfc->device_ctx, &p->cmd);
1532 vulkan_frame_free(hwfc, (uint8_t *)f);
1534 hwfc->internal->pool_internal = av_buffer_pool_init2(sizeof(AVVkFrame),
1535 hwfc, vulkan_pool_alloc,
1537 if (!hwfc->internal->pool_internal) {
1538 free_exec_ctx(hwfc->device_ctx, &p->cmd);
1539 return AVERROR(ENOMEM);
1545 static int vulkan_get_buffer(AVHWFramesContext *hwfc, AVFrame *frame)
1547 frame->buf[0] = av_buffer_pool_get(hwfc->pool);
1549 return AVERROR(ENOMEM);
1551 frame->data[0] = frame->buf[0]->data;
1552 frame->format = AV_PIX_FMT_VULKAN;
1553 frame->width = hwfc->width;
1554 frame->height = hwfc->height;
1559 static int vulkan_transfer_get_formats(AVHWFramesContext *hwfc,
1560 enum AVHWFrameTransferDirection dir,
1561 enum AVPixelFormat **formats)
1563 enum AVPixelFormat *fmts = av_malloc_array(2, sizeof(*fmts));
1565 return AVERROR(ENOMEM);
1567 fmts[0] = hwfc->sw_format;
1568 fmts[1] = AV_PIX_FMT_NONE;
1574 typedef struct VulkanMapping {
1579 static void vulkan_unmap_frame(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1581 VulkanMapping *map = hwmap->priv;
1582 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1583 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1585 /* Check if buffer needs flushing */
1586 if ((map->flags & AV_HWFRAME_MAP_WRITE) &&
1587 !(map->frame->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1589 VkMappedMemoryRange flush_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1591 for (int i = 0; i < planes; i++) {
1592 flush_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1593 flush_ranges[i].memory = map->frame->mem[i];
1594 flush_ranges[i].size = VK_WHOLE_SIZE;
1597 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, planes,
1599 if (ret != VK_SUCCESS) {
1600 av_log(hwfc, AV_LOG_ERROR, "Failed to flush memory: %s\n",
1605 for (int i = 0; i < planes; i++)
1606 vkUnmapMemory(hwctx->act_dev, map->frame->mem[i]);
1611 static int vulkan_map_frame_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
1612 const AVFrame *src, int flags)
1615 int err, mapped_mem_count = 0;
1616 AVVkFrame *f = (AVVkFrame *)src->data[0];
1617 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1618 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1620 VulkanMapping *map = av_mallocz(sizeof(VulkanMapping));
1622 return AVERROR(EINVAL);
1624 if (src->format != AV_PIX_FMT_VULKAN) {
1625 av_log(hwfc, AV_LOG_ERROR, "Cannot map from pixel format %s!\n",
1626 av_get_pix_fmt_name(src->format));
1627 err = AVERROR(EINVAL);
1631 if (!(f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ||
1632 !(f->tiling == VK_IMAGE_TILING_LINEAR)) {
1633 av_log(hwfc, AV_LOG_ERROR, "Unable to map frame, not host visible "
1635 err = AVERROR(EINVAL);
1639 dst->width = src->width;
1640 dst->height = src->height;
1642 for (int i = 0; i < planes; i++) {
1643 ret = vkMapMemory(hwctx->act_dev, f->mem[i], 0,
1644 VK_WHOLE_SIZE, 0, (void **)&dst->data[i]);
1645 if (ret != VK_SUCCESS) {
1646 av_log(hwfc, AV_LOG_ERROR, "Failed to map image memory: %s\n",
1648 err = AVERROR_EXTERNAL;
1654 /* Check if the memory contents matter */
1655 if (((flags & AV_HWFRAME_MAP_READ) || !(flags & AV_HWFRAME_MAP_OVERWRITE)) &&
1656 !(f->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1657 VkMappedMemoryRange map_mem_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1658 for (int i = 0; i < planes; i++) {
1659 map_mem_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1660 map_mem_ranges[i].size = VK_WHOLE_SIZE;
1661 map_mem_ranges[i].memory = f->mem[i];
1664 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, planes,
1666 if (ret != VK_SUCCESS) {
1667 av_log(hwfc, AV_LOG_ERROR, "Failed to invalidate memory: %s\n",
1669 err = AVERROR_EXTERNAL;
1674 for (int i = 0; i < planes; i++) {
1675 VkImageSubresource sub = {
1676 .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
1678 VkSubresourceLayout layout;
1679 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
1680 dst->linesize[i] = layout.rowPitch;
1686 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src,
1687 &vulkan_unmap_frame, map);
1694 for (int i = 0; i < mapped_mem_count; i++)
1695 vkUnmapMemory(hwctx->act_dev, f->mem[i]);
1702 static void vulkan_unmap_from(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1704 VulkanMapping *map = hwmap->priv;
1705 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1706 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1708 for (int i = 0; i < planes; i++) {
1709 vkDestroyImage(hwctx->act_dev, map->frame->img[i], hwctx->alloc);
1710 vkFreeMemory(hwctx->act_dev, map->frame->mem[i], hwctx->alloc);
1713 vkDestroySemaphore(hwctx->act_dev, map->frame->sem, hwctx->alloc);
1715 av_freep(&map->frame);
1718 static const struct {
1719 uint32_t drm_fourcc;
1721 } vulkan_drm_format_map[] = {
1722 { DRM_FORMAT_R8, VK_FORMAT_R8_UNORM },
1723 { DRM_FORMAT_R16, VK_FORMAT_R16_UNORM },
1724 { DRM_FORMAT_GR88, VK_FORMAT_R8G8_UNORM },
1725 { DRM_FORMAT_RG88, VK_FORMAT_R8G8_UNORM },
1726 { DRM_FORMAT_GR1616, VK_FORMAT_R16G16_UNORM },
1727 { DRM_FORMAT_RG1616, VK_FORMAT_R16G16_UNORM },
1728 { DRM_FORMAT_ARGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1729 { DRM_FORMAT_XRGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1730 { DRM_FORMAT_ABGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1731 { DRM_FORMAT_XBGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1734 static inline VkFormat drm_to_vulkan_fmt(uint32_t drm_fourcc)
1736 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
1737 if (vulkan_drm_format_map[i].drm_fourcc == drm_fourcc)
1738 return vulkan_drm_format_map[i].vk_format;
1739 return VK_FORMAT_UNDEFINED;
1742 static int vulkan_map_from_drm_frame_desc(AVHWFramesContext *hwfc, AVVkFrame **frame,
1743 AVDRMFrameDescriptor *desc)
1748 int bind_counts = 0;
1749 AVHWDeviceContext *ctx = hwfc->device_ctx;
1750 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1751 VulkanDevicePriv *p = ctx->internal->priv;
1752 const AVPixFmtDescriptor *fmt_desc = av_pix_fmt_desc_get(hwfc->sw_format);
1753 const int has_modifiers = p->extensions & EXT_DRM_MODIFIER_FLAGS;
1754 VkSubresourceLayout plane_data[AV_NUM_DATA_POINTERS] = { 0 };
1755 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { 0 };
1756 VkBindImagePlaneMemoryInfo plane_info[AV_NUM_DATA_POINTERS] = { 0 };
1757 VkExternalMemoryHandleTypeFlagBits htype = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
1758 VkSemaphoreCreateInfo sem_spawn = {
1759 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1762 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdPropertiesKHR);
1764 for (int i = 0; i < desc->nb_layers; i++) {
1765 if (drm_to_vulkan_fmt(desc->layers[i].format) == VK_FORMAT_UNDEFINED) {
1766 av_log(ctx, AV_LOG_ERROR, "Unsupported DMABUF layer format %#08x!\n",
1767 desc->layers[i].format);
1768 return AVERROR(EINVAL);
1772 if (!(f = av_vk_frame_alloc())) {
1773 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1774 err = AVERROR(ENOMEM);
1778 for (int i = 0; i < desc->nb_objects; i++) {
1779 VkMemoryFdPropertiesKHR fdmp = {
1780 .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,
1782 VkMemoryRequirements req = {
1783 .size = desc->objects[i].size,
1785 VkImportMemoryFdInfoKHR idesc = {
1786 .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
1787 .handleType = htype,
1788 .fd = dup(desc->objects[i].fd),
1791 ret = pfn_vkGetMemoryFdPropertiesKHR(hwctx->act_dev, htype,
1793 if (ret != VK_SUCCESS) {
1794 av_log(hwfc, AV_LOG_ERROR, "Failed to get FD properties: %s\n",
1796 err = AVERROR_EXTERNAL;
1801 req.memoryTypeBits = fdmp.memoryTypeBits;
1803 err = alloc_mem(ctx, &req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1804 &idesc, &f->flags, &f->mem[i]);
1810 f->size[i] = desc->objects[i].size;
1813 f->tiling = has_modifiers ? VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT :
1814 desc->objects[0].format_modifier == DRM_FORMAT_MOD_LINEAR ?
1815 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1817 for (int i = 0; i < desc->nb_layers; i++) {
1818 const int planes = desc->layers[i].nb_planes;
1819 const int signal_p = has_modifiers && (planes > 1);
1821 VkImageDrmFormatModifierExplicitCreateInfoEXT drm_info = {
1822 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
1823 .drmFormatModifier = desc->objects[0].format_modifier,
1824 .drmFormatModifierPlaneCount = planes,
1825 .pPlaneLayouts = (const VkSubresourceLayout *)&plane_data,
1828 VkExternalMemoryImageCreateInfo einfo = {
1829 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1830 .pNext = has_modifiers ? &drm_info : NULL,
1831 .handleTypes = htype,
1834 const int p_w = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, fmt_desc->log2_chroma_w) : hwfc->width;
1835 const int p_h = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, fmt_desc->log2_chroma_h) : hwfc->height;
1837 VkImageCreateInfo image_create_info = {
1838 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1840 .imageType = VK_IMAGE_TYPE_2D,
1841 .format = drm_to_vulkan_fmt(desc->layers[i].format),
1842 .extent.width = p_w,
1843 .extent.height = p_h,
1847 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1848 .tiling = f->tiling,
1849 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, /* specs say so */
1850 .usage = DEFAULT_USAGE_FLAGS,
1851 .samples = VK_SAMPLE_COUNT_1_BIT,
1852 .pQueueFamilyIndices = p->qfs,
1853 .queueFamilyIndexCount = p->num_qfs,
1854 .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
1855 VK_SHARING_MODE_EXCLUSIVE,
1858 for (int j = 0; j < planes; j++) {
1859 plane_data[j].offset = desc->layers[i].planes[j].offset;
1860 plane_data[j].rowPitch = desc->layers[i].planes[j].pitch;
1861 plane_data[j].size = 0; /* The specs say so for all 3 */
1862 plane_data[j].arrayPitch = 0;
1863 plane_data[j].depthPitch = 0;
1867 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
1868 hwctx->alloc, &f->img[i]);
1869 if (ret != VK_SUCCESS) {
1870 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1872 err = AVERROR(EINVAL);
1876 f->layout[i] = image_create_info.initialLayout;
1879 for (int j = 0; j < planes; j++) {
1880 VkImageAspectFlagBits aspect = j == 0 ? VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
1881 j == 1 ? VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT :
1882 VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT;
1884 plane_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO;
1885 plane_info[bind_counts].planeAspect = aspect;
1887 bind_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
1888 bind_info[bind_counts].pNext = signal_p ? &plane_info[bind_counts] : NULL;
1889 bind_info[bind_counts].image = f->img[i];
1890 bind_info[bind_counts].memory = f->mem[desc->layers[i].planes[j].object_index];
1891 bind_info[bind_counts].memoryOffset = desc->layers[i].planes[j].offset;
1896 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1897 hwctx->alloc, &f->sem);
1898 if (ret != VK_SUCCESS) {
1899 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1901 return AVERROR_EXTERNAL;
1904 /* We'd import a semaphore onto the one we created using
1905 * vkImportSemaphoreFdKHR but unfortunately neither DRM nor VAAPI
1906 * offer us anything we could import and sync with, so instead
1907 * just signal the semaphore we created. */
1909 /* Bind the allocated memory to the images */
1910 ret = vkBindImageMemory2(hwctx->act_dev, bind_counts, bind_info);
1911 if (ret != VK_SUCCESS) {
1912 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
1914 return AVERROR_EXTERNAL;
1917 /* NOTE: This is completely uneccesary and unneeded once we can import
1918 * semaphores from DRM. Otherwise we have to activate the semaphores.
1919 * We're reusing the exec context that's also used for uploads/downloads. */
1920 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_RO_SHADER);
1929 for (int i = 0; i < desc->nb_layers; i++)
1930 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
1931 for (int i = 0; i < desc->nb_objects; i++)
1932 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
1933 vkDestroySemaphore(hwctx->act_dev, f->sem, hwctx->alloc);
1940 static int vulkan_map_from_drm(AVHWFramesContext *hwfc, AVFrame *dst,
1941 const AVFrame *src, int flags)
1945 VulkanMapping *map = NULL;
1947 err = vulkan_map_from_drm_frame_desc(hwfc, &f,
1948 (AVDRMFrameDescriptor *)src->data[0]);
1952 /* The unmapping function will free this */
1953 dst->data[0] = (uint8_t *)f;
1954 dst->width = src->width;
1955 dst->height = src->height;
1957 map = av_mallocz(sizeof(VulkanMapping));
1964 err = ff_hwframe_map_create(dst->hw_frames_ctx, dst, src,
1965 &vulkan_unmap_from, map);
1969 av_log(hwfc, AV_LOG_DEBUG, "Mapped DRM object to Vulkan!\n");
1974 vulkan_frame_free(hwfc->device_ctx->hwctx, (uint8_t *)f);
1980 static int vulkan_map_from_vaapi(AVHWFramesContext *dst_fc,
1981 AVFrame *dst, const AVFrame *src,
1985 AVFrame *tmp = av_frame_alloc();
1986 AVHWFramesContext *vaapi_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
1987 AVVAAPIDeviceContext *vaapi_ctx = vaapi_fc->device_ctx->hwctx;
1988 VASurfaceID surface_id = (VASurfaceID)(uintptr_t)src->data[3];
1991 return AVERROR(ENOMEM);
1993 /* We have to sync since like the previous comment said, no semaphores */
1994 vaSyncSurface(vaapi_ctx->display, surface_id);
1996 tmp->format = AV_PIX_FMT_DRM_PRIME;
1998 err = av_hwframe_map(tmp, src, flags);
2002 err = vulkan_map_from_drm(dst_fc, dst, tmp, flags);
2006 err = ff_hwframe_map_replace(dst, src);
2009 av_frame_free(&tmp);
2016 static int vulkan_export_to_cuda(AVHWFramesContext *hwfc,
2017 AVBufferRef *cuda_hwfc,
2018 const AVFrame *frame)
2023 AVVkFrameInternal *dst_int;
2024 AVHWDeviceContext *ctx = hwfc->device_ctx;
2025 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2026 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2027 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2028 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2029 VK_LOAD_PFN(hwctx->inst, vkGetSemaphoreFdKHR);
2031 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)cuda_hwfc->data;
2032 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2033 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2034 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2035 CudaFunctions *cu = cu_internal->cuda_dl;
2036 CUarray_format cufmt = desc->comp[0].depth > 8 ? CU_AD_FORMAT_UNSIGNED_INT16 :
2037 CU_AD_FORMAT_UNSIGNED_INT8;
2039 dst_f = (AVVkFrame *)frame->data[0];
2041 dst_int = dst_f->internal;
2042 if (!dst_int || !dst_int->cuda_fc_ref) {
2043 VkSemaphoreGetFdInfoKHR sem_export = {
2044 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR,
2045 .semaphore = dst_f->sem,
2046 .handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
2048 CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC ext_sem_desc = {
2049 .type = CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD,
2052 if (!dst_f->internal)
2053 dst_f->internal = dst_int = av_mallocz(sizeof(*dst_f->internal));
2056 err = AVERROR(ENOMEM);
2060 dst_int->cuda_fc_ref = av_buffer_ref(cuda_hwfc);
2061 if (!dst_int->cuda_fc_ref) {
2062 err = AVERROR(ENOMEM);
2066 for (int i = 0; i < planes; i++) {
2067 CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC tex_desc = {
2070 .Width = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2072 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2076 .NumChannels = 1 + ((planes == 2) && i),
2081 CUDA_EXTERNAL_MEMORY_HANDLE_DESC ext_desc = {
2082 .type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD,
2083 .size = dst_f->size[i],
2085 VkMemoryGetFdInfoKHR export_info = {
2086 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2087 .memory = dst_f->mem[i],
2088 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR,
2091 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2092 &ext_desc.handle.fd);
2093 if (ret != VK_SUCCESS) {
2094 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2095 err = AVERROR_EXTERNAL;
2099 ret = CHECK_CU(cu->cuImportExternalMemory(&dst_int->ext_mem[i], &ext_desc));
2101 err = AVERROR_EXTERNAL;
2105 ret = CHECK_CU(cu->cuExternalMemoryGetMappedMipmappedArray(&dst_int->cu_mma[i],
2106 dst_int->ext_mem[i],
2109 err = AVERROR_EXTERNAL;
2113 ret = CHECK_CU(cu->cuMipmappedArrayGetLevel(&dst_int->cu_array[i],
2114 dst_int->cu_mma[i], 0));
2116 err = AVERROR_EXTERNAL;
2121 ret = pfn_vkGetSemaphoreFdKHR(hwctx->act_dev, &sem_export,
2122 &ext_sem_desc.handle.fd);
2123 if (ret != VK_SUCCESS) {
2124 av_log(ctx, AV_LOG_ERROR, "Failed to export semaphore: %s\n",
2126 err = AVERROR_EXTERNAL;
2130 ret = CHECK_CU(cu->cuImportExternalSemaphore(&dst_int->cu_sem,
2133 err = AVERROR_EXTERNAL;
2144 static int vulkan_transfer_data_from_cuda(AVHWFramesContext *hwfc,
2145 AVFrame *dst, const AVFrame *src)
2151 AVVkFrameInternal *dst_int;
2152 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2153 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2155 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2156 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2157 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2158 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2159 CudaFunctions *cu = cu_internal->cuda_dl;
2160 CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS s_w_par = { 0 };
2161 CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS s_s_par = { 0 };
2163 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2165 err = AVERROR_EXTERNAL;
2169 dst_f = (AVVkFrame *)dst->data[0];
2171 ret = vulkan_export_to_cuda(hwfc, src->hw_frames_ctx, dst);
2175 dst_int = dst_f->internal;
2177 ret = CHECK_CU(cu->cuWaitExternalSemaphoresAsync(&dst_int->cu_sem, &s_w_par,
2178 1, cuda_dev->stream));
2180 err = AVERROR_EXTERNAL;
2184 for (int i = 0; i < planes; i++) {
2185 CUDA_MEMCPY2D cpy = {
2186 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
2187 .srcDevice = (CUdeviceptr)src->data[i],
2188 .srcPitch = src->linesize[i],
2191 .dstMemoryType = CU_MEMORYTYPE_ARRAY,
2192 .dstArray = dst_int->cu_array[i],
2193 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2194 : hwfc->width) * desc->comp[i].step,
2195 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2199 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2201 err = AVERROR_EXTERNAL;
2206 ret = CHECK_CU(cu->cuSignalExternalSemaphoresAsync(&dst_int->cu_sem, &s_s_par,
2207 1, cuda_dev->stream));
2209 err = AVERROR_EXTERNAL;
2213 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2215 av_log(hwfc, AV_LOG_VERBOSE, "Transfered CUDA image to Vulkan!\n");
2220 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2221 vulkan_free_internal(dst_int);
2222 dst_f->internal = NULL;
2223 av_buffer_unref(&dst->buf[0]);
2228 static int vulkan_map_to(AVHWFramesContext *hwfc, AVFrame *dst,
2229 const AVFrame *src, int flags)
2231 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2233 switch (src->format) {
2236 case AV_PIX_FMT_VAAPI:
2237 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2238 return vulkan_map_from_vaapi(hwfc, dst, src, flags);
2240 case AV_PIX_FMT_DRM_PRIME:
2241 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2242 return vulkan_map_from_drm(hwfc, dst, src, flags);
2245 return AVERROR(ENOSYS);
2250 typedef struct VulkanDRMMapping {
2251 AVDRMFrameDescriptor drm_desc;
2255 static void vulkan_unmap_to_drm(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
2257 AVDRMFrameDescriptor *drm_desc = hwmap->priv;
2259 for (int i = 0; i < drm_desc->nb_objects; i++)
2260 close(drm_desc->objects[i].fd);
2265 static inline uint32_t vulkan_fmt_to_drm(VkFormat vkfmt)
2267 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
2268 if (vulkan_drm_format_map[i].vk_format == vkfmt)
2269 return vulkan_drm_format_map[i].drm_fourcc;
2270 return DRM_FORMAT_INVALID;
2273 static int vulkan_map_to_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2274 const AVFrame *src, int flags)
2278 AVVkFrame *f = (AVVkFrame *)src->data[0];
2279 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2280 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
2281 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2282 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2283 VkImageDrmFormatModifierPropertiesEXT drm_mod = {
2284 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT,
2287 AVDRMFrameDescriptor *drm_desc = av_mallocz(sizeof(*drm_desc));
2289 return AVERROR(ENOMEM);
2291 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src, &vulkan_unmap_to_drm, drm_desc);
2295 if (p->extensions & EXT_DRM_MODIFIER_FLAGS) {
2296 VK_LOAD_PFN(hwctx->inst, vkGetImageDrmFormatModifierPropertiesEXT);
2297 ret = pfn_vkGetImageDrmFormatModifierPropertiesEXT(hwctx->act_dev, f->img[0],
2299 if (ret != VK_SUCCESS) {
2300 av_log(hwfc, AV_LOG_ERROR, "Failed to retrieve DRM format modifier!\n");
2301 err = AVERROR_EXTERNAL;
2306 for (int i = 0; (i < planes) && (f->mem[i]); i++) {
2307 VkMemoryGetFdInfoKHR export_info = {
2308 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2309 .memory = f->mem[i],
2310 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,
2313 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2314 &drm_desc->objects[i].fd);
2315 if (ret != VK_SUCCESS) {
2316 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2317 err = AVERROR_EXTERNAL;
2321 drm_desc->nb_objects++;
2322 drm_desc->objects[i].size = f->size[i];
2323 drm_desc->objects[i].format_modifier = drm_mod.drmFormatModifier;
2326 drm_desc->nb_layers = planes;
2327 for (int i = 0; i < drm_desc->nb_layers; i++) {
2328 VkSubresourceLayout layout;
2329 VkImageSubresource sub = {
2330 .aspectMask = p->extensions & EXT_DRM_MODIFIER_FLAGS ?
2331 VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2332 VK_IMAGE_ASPECT_COLOR_BIT,
2334 VkFormat plane_vkfmt = av_vkfmt_from_pixfmt(hwfc->sw_format)[i];
2336 drm_desc->layers[i].format = vulkan_fmt_to_drm(plane_vkfmt);
2337 drm_desc->layers[i].nb_planes = 1;
2339 if (drm_desc->layers[i].format == DRM_FORMAT_INVALID) {
2340 av_log(hwfc, AV_LOG_ERROR, "Cannot map to DRM layer, unsupported!\n");
2341 err = AVERROR_PATCHWELCOME;
2345 drm_desc->layers[i].planes[0].object_index = FFMIN(i, drm_desc->nb_objects - 1);
2347 if (f->tiling == VK_IMAGE_TILING_OPTIMAL)
2350 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
2351 drm_desc->layers[i].planes[0].offset = layout.offset;
2352 drm_desc->layers[i].planes[0].pitch = layout.rowPitch;
2355 dst->width = src->width;
2356 dst->height = src->height;
2357 dst->data[0] = (uint8_t *)drm_desc;
2359 av_log(hwfc, AV_LOG_VERBOSE, "Mapped AVVkFrame to a DRM object!\n");
2369 static int vulkan_map_to_vaapi(AVHWFramesContext *hwfc, AVFrame *dst,
2370 const AVFrame *src, int flags)
2373 AVFrame *tmp = av_frame_alloc();
2375 return AVERROR(ENOMEM);
2377 tmp->format = AV_PIX_FMT_DRM_PRIME;
2379 err = vulkan_map_to_drm(hwfc, tmp, src, flags);
2383 err = av_hwframe_map(dst, tmp, flags);
2387 err = ff_hwframe_map_replace(dst, src);
2390 av_frame_free(&tmp);
2396 static int vulkan_map_from(AVHWFramesContext *hwfc, AVFrame *dst,
2397 const AVFrame *src, int flags)
2399 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2401 switch (dst->format) {
2403 case AV_PIX_FMT_DRM_PRIME:
2404 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2405 return vulkan_map_to_drm(hwfc, dst, src, flags);
2407 case AV_PIX_FMT_VAAPI:
2408 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2409 return vulkan_map_to_vaapi(hwfc, dst, src, flags);
2413 return vulkan_map_frame_to_mem(hwfc, dst, src, flags);
2417 typedef struct ImageBuffer {
2420 VkMemoryPropertyFlagBits flags;
2423 static void free_buf(AVHWDeviceContext *ctx, ImageBuffer *buf)
2425 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2429 vkDestroyBuffer(hwctx->act_dev, buf->buf, hwctx->alloc);
2430 vkFreeMemory(hwctx->act_dev, buf->mem, hwctx->alloc);
2433 static int create_buf(AVHWDeviceContext *ctx, ImageBuffer *buf, int height,
2434 int *stride, VkBufferUsageFlags usage,
2435 VkMemoryPropertyFlagBits flags, void *create_pnext,
2440 VkMemoryRequirements req;
2441 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2442 VulkanDevicePriv *p = ctx->internal->priv;
2444 VkBufferCreateInfo buf_spawn = {
2445 .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
2446 .pNext = create_pnext,
2448 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
2451 *stride = FFALIGN(*stride, p->props.limits.optimalBufferCopyRowPitchAlignment);
2452 buf_spawn.size = height*(*stride);
2454 ret = vkCreateBuffer(hwctx->act_dev, &buf_spawn, NULL, &buf->buf);
2455 if (ret != VK_SUCCESS) {
2456 av_log(ctx, AV_LOG_ERROR, "Failed to create buffer: %s\n",
2458 return AVERROR_EXTERNAL;
2461 vkGetBufferMemoryRequirements(hwctx->act_dev, buf->buf, &req);
2463 err = alloc_mem(ctx, &req, flags, alloc_pnext, &buf->flags, &buf->mem);
2467 ret = vkBindBufferMemory(hwctx->act_dev, buf->buf, buf->mem, 0);
2468 if (ret != VK_SUCCESS) {
2469 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory to buffer: %s\n",
2472 return AVERROR_EXTERNAL;
2478 static int map_buffers(AVHWDeviceContext *ctx, ImageBuffer *buf, uint8_t *mem[],
2479 int nb_buffers, int invalidate)
2482 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2483 VkMappedMemoryRange invalidate_ctx[AV_NUM_DATA_POINTERS];
2484 int invalidate_count = 0;
2486 for (int i = 0; i < nb_buffers; i++) {
2487 ret = vkMapMemory(hwctx->act_dev, buf[i].mem, 0,
2488 VK_WHOLE_SIZE, 0, (void **)&mem[i]);
2489 if (ret != VK_SUCCESS) {
2490 av_log(ctx, AV_LOG_ERROR, "Failed to map buffer memory: %s\n",
2492 return AVERROR_EXTERNAL;
2499 for (int i = 0; i < nb_buffers; i++) {
2500 const VkMappedMemoryRange ival_buf = {
2501 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2502 .memory = buf[i].mem,
2503 .size = VK_WHOLE_SIZE,
2505 if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2507 invalidate_ctx[invalidate_count++] = ival_buf;
2510 if (invalidate_count) {
2511 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, invalidate_count,
2513 if (ret != VK_SUCCESS)
2514 av_log(ctx, AV_LOG_WARNING, "Failed to invalidate memory: %s\n",
2521 static int unmap_buffers(AVHWDeviceContext *ctx, ImageBuffer *buf,
2522 int nb_buffers, int flush)
2526 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2527 VkMappedMemoryRange flush_ctx[AV_NUM_DATA_POINTERS];
2528 int flush_count = 0;
2531 for (int i = 0; i < nb_buffers; i++) {
2532 const VkMappedMemoryRange flush_buf = {
2533 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2534 .memory = buf[i].mem,
2535 .size = VK_WHOLE_SIZE,
2537 if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2539 flush_ctx[flush_count++] = flush_buf;
2544 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, flush_count, flush_ctx);
2545 if (ret != VK_SUCCESS) {
2546 av_log(ctx, AV_LOG_ERROR, "Failed to flush memory: %s\n",
2548 err = AVERROR_EXTERNAL; /* We still want to try to unmap them */
2552 for (int i = 0; i < nb_buffers; i++)
2553 vkUnmapMemory(hwctx->act_dev, buf[i].mem);
2558 static int transfer_image_buf(AVHWDeviceContext *ctx, AVVkFrame *frame,
2559 ImageBuffer *buffer, const int *buf_stride, int w,
2560 int h, enum AVPixelFormat pix_fmt, int to_buf)
2563 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2564 VulkanDevicePriv *s = ctx->internal->priv;
2567 VkPipelineStageFlagBits sem_wait_dst[AV_NUM_DATA_POINTERS];
2569 const int planes = av_pix_fmt_count_planes(pix_fmt);
2570 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2572 VkCommandBufferBeginInfo cmd_start = {
2573 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
2574 .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
2577 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
2579 VkSubmitInfo s_info = {
2580 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
2581 .commandBufferCount = 1,
2582 .pCommandBuffers = &s->cmd.buf,
2583 .pSignalSemaphores = &frame->sem,
2584 .pWaitSemaphores = &frame->sem,
2585 .pWaitDstStageMask = sem_wait_dst,
2586 .signalSemaphoreCount = 1,
2587 .waitSemaphoreCount = 1,
2590 ret = vkBeginCommandBuffer(s->cmd.buf, &cmd_start);
2591 if (ret != VK_SUCCESS) {
2592 av_log(ctx, AV_LOG_ERROR, "Unable to init command buffer: %s\n",
2594 return AVERROR_EXTERNAL;
2597 /* Change the image layout to something more optimal for transfers */
2598 for (int i = 0; i < planes; i++) {
2599 VkImageLayout new_layout = to_buf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL :
2600 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
2601 VkAccessFlags new_access = to_buf ? VK_ACCESS_TRANSFER_READ_BIT :
2602 VK_ACCESS_TRANSFER_WRITE_BIT;
2604 sem_wait_dst[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
2606 /* If the layout matches and we have read access skip the barrier */
2607 if ((frame->layout[i] == new_layout) && (frame->access[i] & new_access))
2610 img_bar[bar_num].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
2611 img_bar[bar_num].srcAccessMask = 0x0;
2612 img_bar[bar_num].dstAccessMask = new_access;
2613 img_bar[bar_num].oldLayout = frame->layout[i];
2614 img_bar[bar_num].newLayout = new_layout;
2615 img_bar[bar_num].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2616 img_bar[bar_num].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2617 img_bar[bar_num].image = frame->img[i];
2618 img_bar[bar_num].subresourceRange.levelCount = 1;
2619 img_bar[bar_num].subresourceRange.layerCount = 1;
2620 img_bar[bar_num].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2622 frame->layout[i] = img_bar[bar_num].newLayout;
2623 frame->access[i] = img_bar[bar_num].dstAccessMask;
2629 vkCmdPipelineBarrier(s->cmd.buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
2630 VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
2631 0, NULL, 0, NULL, bar_num, img_bar);
2633 /* Schedule a copy for each plane */
2634 for (int i = 0; i < planes; i++) {
2635 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
2636 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
2637 VkBufferImageCopy buf_reg = {
2639 /* Buffer stride isn't in bytes, it's in samples, the implementation
2640 * uses the image's VkFormat to know how many bytes per sample
2641 * the buffer has. So we have to convert by dividing. Stupid.
2642 * Won't work with YUVA or other planar formats with alpha. */
2643 .bufferRowLength = buf_stride[i] / desc->comp[i].step,
2644 .bufferImageHeight = p_h,
2645 .imageSubresource.layerCount = 1,
2646 .imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
2647 .imageOffset = { 0, 0, 0, },
2648 .imageExtent = { p_w, p_h, 1, },
2652 vkCmdCopyImageToBuffer(s->cmd.buf, frame->img[i], frame->layout[i],
2653 buffer[i].buf, 1, &buf_reg);
2655 vkCmdCopyBufferToImage(s->cmd.buf, buffer[i].buf, frame->img[i],
2656 frame->layout[i], 1, &buf_reg);
2659 ret = vkEndCommandBuffer(s->cmd.buf);
2660 if (ret != VK_SUCCESS) {
2661 av_log(ctx, AV_LOG_ERROR, "Unable to finish command buffer: %s\n",
2663 return AVERROR_EXTERNAL;
2666 /* Wait for the download/upload to finish if uploading, otherwise the
2667 * semaphore will take care of synchronization when uploading */
2668 ret = vkQueueSubmit(s->cmd.queue, 1, &s_info, s->cmd.fence);
2669 if (ret != VK_SUCCESS) {
2670 av_log(ctx, AV_LOG_ERROR, "Unable to submit command buffer: %s\n",
2672 return AVERROR_EXTERNAL;
2674 vkWaitForFences(hwctx->act_dev, 1, &s->cmd.fence, VK_TRUE, UINT64_MAX);
2675 vkResetFences(hwctx->act_dev, 1, &s->cmd.fence);
2681 /* Technically we can use VK_EXT_external_memory_host to upload and download,
2682 * however the alignment requirements make this unfeasible as both the pointer
2683 * and the size of each plane need to be aligned to the minimum alignment
2684 * requirement, which on all current implementations (anv, radv) is 4096.
2685 * If the requirement gets relaxed (unlikely) this can easily be implemented. */
2686 static int vulkan_transfer_data_from_mem(AVHWFramesContext *hwfc, AVFrame *dst,
2691 AVVkFrame *f = (AVVkFrame *)dst->data[0];
2692 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
2693 ImageBuffer buf[AV_NUM_DATA_POINTERS] = { { 0 } };
2694 const int planes = av_pix_fmt_count_planes(src->format);
2695 int log2_chroma = av_pix_fmt_desc_get(src->format)->log2_chroma_h;
2697 if ((src->format != AV_PIX_FMT_NONE && !av_vkfmt_from_pixfmt(src->format))) {
2698 av_log(hwfc, AV_LOG_ERROR, "Unsupported source pixel format!\n");
2699 return AVERROR(EINVAL);
2702 if (src->width > hwfc->width || src->height > hwfc->height)
2703 return AVERROR(EINVAL);
2705 /* For linear, host visiable images */
2706 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
2707 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
2708 AVFrame *map = av_frame_alloc();
2710 return AVERROR(ENOMEM);
2711 map->format = src->format;
2713 err = vulkan_map_frame_to_mem(hwfc, map, dst, AV_HWFRAME_MAP_WRITE);
2717 err = av_frame_copy(map, src);
2718 av_frame_free(&map);
2722 /* Create buffers */
2723 for (int i = 0; i < planes; i++) {
2724 int h = src->height;
2725 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
2727 tmp.linesize[i] = FFABS(src->linesize[i]);
2728 err = create_buf(dev_ctx, &buf[i], p_height,
2729 &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
2730 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
2735 /* Map, copy image to buffer, unmap */
2736 if ((err = map_buffers(dev_ctx, buf, tmp.data, planes, 0)))
2739 av_image_copy(tmp.data, tmp.linesize, (const uint8_t **)src->data,
2740 src->linesize, src->format, src->width, src->height);
2742 if ((err = unmap_buffers(dev_ctx, buf, planes, 1)))
2745 /* Copy buffers to image */
2746 err = transfer_image_buf(dev_ctx, f, buf, tmp.linesize,
2747 src->width, src->height, src->format, 0);
2750 for (int i = 0; i < planes; i++)
2751 free_buf(dev_ctx, &buf[i]);
2756 static int vulkan_transfer_data_to(AVHWFramesContext *hwfc, AVFrame *dst,
2759 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2761 switch (src->format) {
2763 case AV_PIX_FMT_CUDA:
2764 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
2765 (p->extensions & EXT_EXTERNAL_FD_SEM))
2766 return vulkan_transfer_data_from_cuda(hwfc, dst, src);
2769 if (src->hw_frames_ctx)
2770 return AVERROR(ENOSYS);
2772 return vulkan_transfer_data_from_mem(hwfc, dst, src);
2777 static int vulkan_transfer_data_to_cuda(AVHWFramesContext *hwfc, AVFrame *dst,
2784 AVVkFrameInternal *dst_int;
2785 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2786 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2788 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)dst->hw_frames_ctx->data;
2789 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2790 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2791 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2792 CudaFunctions *cu = cu_internal->cuda_dl;
2794 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2796 err = AVERROR_EXTERNAL;
2800 dst_f = (AVVkFrame *)src->data[0];
2802 err = vulkan_export_to_cuda(hwfc, dst->hw_frames_ctx, src);
2807 dst_int = dst_f->internal;
2809 for (int i = 0; i < planes; i++) {
2810 CUDA_MEMCPY2D cpy = {
2811 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
2812 .dstDevice = (CUdeviceptr)dst->data[i],
2813 .dstPitch = dst->linesize[i],
2816 .srcMemoryType = CU_MEMORYTYPE_ARRAY,
2817 .srcArray = dst_int->cu_array[i],
2818 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2819 : hwfc->width) * desc->comp[i].step,
2820 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2824 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2826 err = AVERROR_EXTERNAL;
2831 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2833 av_log(hwfc, AV_LOG_VERBOSE, "Transfered Vulkan image to CUDA!\n");
2838 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2839 vulkan_free_internal(dst_int);
2840 dst_f->internal = NULL;
2841 av_buffer_unref(&dst->buf[0]);
2846 static int vulkan_transfer_data_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
2851 AVVkFrame *f = (AVVkFrame *)src->data[0];
2852 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
2853 ImageBuffer buf[AV_NUM_DATA_POINTERS] = { { 0 } };
2854 const int planes = av_pix_fmt_count_planes(dst->format);
2855 int log2_chroma = av_pix_fmt_desc_get(dst->format)->log2_chroma_h;
2857 if (dst->width > hwfc->width || dst->height > hwfc->height)
2858 return AVERROR(EINVAL);
2860 /* For linear, host visiable images */
2861 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
2862 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
2863 AVFrame *map = av_frame_alloc();
2865 return AVERROR(ENOMEM);
2866 map->format = dst->format;
2868 err = vulkan_map_frame_to_mem(hwfc, map, src, AV_HWFRAME_MAP_READ);
2872 err = av_frame_copy(dst, map);
2873 av_frame_free(&map);
2877 /* Create buffers */
2878 for (int i = 0; i < planes; i++) {
2879 int h = dst->height;
2880 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
2882 tmp.linesize[i] = FFABS(dst->linesize[i]);
2883 err = create_buf(dev_ctx, &buf[i], p_height,
2884 &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_DST_BIT,
2885 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
2888 /* Copy image to buffer */
2889 if ((err = transfer_image_buf(dev_ctx, f, buf, tmp.linesize,
2890 dst->width, dst->height, dst->format, 1)))
2893 /* Map, copy buffer to frame, unmap */
2894 if ((err = map_buffers(dev_ctx, buf, tmp.data, planes, 1)))
2897 av_image_copy(dst->data, dst->linesize, (const uint8_t **)tmp.data,
2898 tmp.linesize, dst->format, dst->width, dst->height);
2900 err = unmap_buffers(dev_ctx, buf, planes, 0);
2903 for (int i = 0; i < planes; i++)
2904 free_buf(dev_ctx, &buf[i]);
2909 static int vulkan_transfer_data_from(AVHWFramesContext *hwfc, AVFrame *dst,
2912 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2914 switch (dst->format) {
2916 case AV_PIX_FMT_CUDA:
2917 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
2918 (p->extensions & EXT_EXTERNAL_FD_SEM))
2919 return vulkan_transfer_data_to_cuda(hwfc, dst, src);
2922 if (dst->hw_frames_ctx)
2923 return AVERROR(ENOSYS);
2925 return vulkan_transfer_data_to_mem(hwfc, dst, src);
2929 AVVkFrame *av_vk_frame_alloc(void)
2931 return av_mallocz(sizeof(AVVkFrame));
2934 const HWContextType ff_hwcontext_type_vulkan = {
2935 .type = AV_HWDEVICE_TYPE_VULKAN,
2938 .device_hwctx_size = sizeof(AVVulkanDeviceContext),
2939 .device_priv_size = sizeof(VulkanDevicePriv),
2940 .frames_hwctx_size = sizeof(AVVulkanFramesContext),
2941 .frames_priv_size = sizeof(VulkanFramesPriv),
2943 .device_init = &vulkan_device_init,
2944 .device_create = &vulkan_device_create,
2945 .device_derive = &vulkan_device_derive,
2947 .frames_get_constraints = &vulkan_frames_get_constraints,
2948 .frames_init = vulkan_frames_init,
2949 .frames_get_buffer = vulkan_get_buffer,
2950 .frames_uninit = vulkan_frames_uninit,
2952 .transfer_get_formats = vulkan_transfer_get_formats,
2953 .transfer_data_to = vulkan_transfer_data_to,
2954 .transfer_data_from = vulkan_transfer_data_from,
2956 .map_to = vulkan_map_to,
2957 .map_from = vulkan_map_from,
2959 .pix_fmts = (const enum AVPixelFormat []) {