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[AV_NUM_DATA_POINTERS];
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 for (int i = 0; i < planes; i++) {
1127 if (internal->cu_sem[i])
1128 CHECK_CU(cu->cuDestroyExternalSemaphore(internal->cu_sem[i]));
1129 if (internal->cu_mma[i])
1130 CHECK_CU(cu->cuMipmappedArrayDestroy(internal->cu_mma[i]));
1131 if (internal->ext_mem[i])
1132 CHECK_CU(cu->cuDestroyExternalMemory(internal->ext_mem[i]));
1135 av_buffer_unref(&internal->cuda_fc_ref);
1142 static void vulkan_frame_free(void *opaque, uint8_t *data)
1144 AVVkFrame *f = (AVVkFrame *)data;
1145 AVHWFramesContext *hwfc = opaque;
1146 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1147 int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1149 vulkan_free_internal(f->internal);
1151 for (int i = 0; i < planes; i++) {
1152 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
1153 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
1154 vkDestroySemaphore(hwctx->act_dev, f->sem[i], hwctx->alloc);
1160 static int alloc_bind_mem(AVHWFramesContext *hwfc, AVVkFrame *f,
1161 void *alloc_pnext, size_t alloc_pnext_stride)
1165 AVHWDeviceContext *ctx = hwfc->device_ctx;
1166 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1167 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { { 0 } };
1169 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1171 for (int i = 0; i < planes; i++) {
1173 VkImageMemoryRequirementsInfo2 req_desc = {
1174 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
1177 VkMemoryDedicatedAllocateInfo ded_alloc = {
1178 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
1179 .pNext = (void *)(((uint8_t *)alloc_pnext) + i*alloc_pnext_stride),
1181 VkMemoryDedicatedRequirements ded_req = {
1182 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
1184 VkMemoryRequirements2 req = {
1185 .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
1189 vkGetImageMemoryRequirements2(hwctx->act_dev, &req_desc, &req);
1191 /* In case the implementation prefers/requires dedicated allocation */
1192 use_ded_mem = ded_req.prefersDedicatedAllocation |
1193 ded_req.requiresDedicatedAllocation;
1195 ded_alloc.image = f->img[i];
1197 /* Allocate memory */
1198 if ((err = alloc_mem(ctx, &req.memoryRequirements,
1199 f->tiling == VK_IMAGE_TILING_LINEAR ?
1200 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT :
1201 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1202 use_ded_mem ? &ded_alloc : (void *)ded_alloc.pNext,
1203 &f->flags, &f->mem[i])))
1206 f->size[i] = req.memoryRequirements.size;
1207 bind_info[i].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
1208 bind_info[i].image = f->img[i];
1209 bind_info[i].memory = f->mem[i];
1212 /* Bind the allocated memory to the images */
1213 ret = vkBindImageMemory2(hwctx->act_dev, planes, bind_info);
1214 if (ret != VK_SUCCESS) {
1215 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
1217 return AVERROR_EXTERNAL;
1225 PREP_MODE_RO_SHADER,
1226 PREP_MODE_EXTERNAL_EXPORT,
1229 static int prepare_frame(AVHWFramesContext *hwfc, VulkanExecCtx *ectx,
1230 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 VkPipelineStageFlagBits wait_st = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
1249 VkSubmitInfo s_info = {
1250 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
1251 .commandBufferCount = 1,
1252 .pCommandBuffers = &ectx->buf,
1254 .pSignalSemaphores = frame->sem,
1255 .signalSemaphoreCount = planes,
1259 case PREP_MODE_WRITE:
1260 new_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
1261 new_access = VK_ACCESS_TRANSFER_WRITE_BIT;
1262 dst_qf = VK_QUEUE_FAMILY_IGNORED;
1264 case PREP_MODE_RO_SHADER:
1265 new_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
1266 new_access = VK_ACCESS_TRANSFER_READ_BIT;
1267 dst_qf = VK_QUEUE_FAMILY_IGNORED;
1269 case PREP_MODE_EXTERNAL_EXPORT:
1270 new_layout = VK_IMAGE_LAYOUT_GENERAL;
1271 new_access = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
1272 dst_qf = VK_QUEUE_FAMILY_EXTERNAL_KHR;
1273 s_info.pWaitSemaphores = &frame->sem;
1274 s_info.pWaitDstStageMask = &wait_st;
1275 s_info.waitSemaphoreCount = 1;
1279 ret = vkBeginCommandBuffer(ectx->buf, &cmd_start);
1280 if (ret != VK_SUCCESS)
1281 return AVERROR_EXTERNAL;
1283 /* Change the image layout to something more optimal for writes.
1284 * This also signals the newly created semaphore, making it usable
1285 * for synchronization */
1286 for (int i = 0; i < planes; i++) {
1287 img_bar[i].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1288 img_bar[i].srcAccessMask = 0x0;
1289 img_bar[i].dstAccessMask = new_access;
1290 img_bar[i].oldLayout = frame->layout[i];
1291 img_bar[i].newLayout = new_layout;
1292 img_bar[i].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1293 img_bar[i].dstQueueFamilyIndex = dst_qf;
1294 img_bar[i].image = frame->img[i];
1295 img_bar[i].subresourceRange.levelCount = 1;
1296 img_bar[i].subresourceRange.layerCount = 1;
1297 img_bar[i].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1299 frame->layout[i] = img_bar[i].newLayout;
1300 frame->access[i] = img_bar[i].dstAccessMask;
1303 vkCmdPipelineBarrier(ectx->buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
1304 VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
1305 0, NULL, 0, NULL, planes, img_bar);
1307 ret = vkEndCommandBuffer(ectx->buf);
1308 if (ret != VK_SUCCESS)
1309 return AVERROR_EXTERNAL;
1311 ret = vkQueueSubmit(ectx->queue, 1, &s_info, ectx->fence);
1312 if (ret != VK_SUCCESS) {
1313 return AVERROR_EXTERNAL;
1315 vkWaitForFences(hwctx->act_dev, 1, &ectx->fence, VK_TRUE, UINT64_MAX);
1316 vkResetFences(hwctx->act_dev, 1, &ectx->fence);
1322 static int create_frame(AVHWFramesContext *hwfc, AVVkFrame **frame,
1323 VkImageTiling tiling, VkImageUsageFlagBits usage,
1328 AVHWDeviceContext *ctx = hwfc->device_ctx;
1329 VulkanDevicePriv *p = ctx->internal->priv;
1330 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1331 enum AVPixelFormat format = hwfc->sw_format;
1332 const VkFormat *img_fmts = av_vkfmt_from_pixfmt(format);
1333 const int planes = av_pix_fmt_count_planes(format);
1335 VkExportSemaphoreCreateInfo ext_sem_info = {
1336 .sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO,
1337 .handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
1340 VkSemaphoreCreateInfo sem_spawn = {
1341 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1342 .pNext = p->extensions & EXT_EXTERNAL_FD_SEM ? &ext_sem_info : NULL,
1345 AVVkFrame *f = av_vk_frame_alloc();
1347 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1348 return AVERROR(ENOMEM);
1351 /* Create the images */
1352 for (int i = 0; i < planes; i++) {
1353 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
1354 int w = hwfc->width;
1355 int h = hwfc->height;
1356 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
1357 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
1359 VkImageCreateInfo image_create_info = {
1360 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1361 .pNext = create_pnext,
1362 .imageType = VK_IMAGE_TYPE_2D,
1363 .format = img_fmts[i],
1364 .extent.width = p_w,
1365 .extent.height = p_h,
1369 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1371 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1373 .samples = VK_SAMPLE_COUNT_1_BIT,
1374 .pQueueFamilyIndices = p->qfs,
1375 .queueFamilyIndexCount = p->num_qfs,
1376 .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
1377 VK_SHARING_MODE_EXCLUSIVE,
1380 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
1381 hwctx->alloc, &f->img[i]);
1382 if (ret != VK_SUCCESS) {
1383 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1385 err = AVERROR(EINVAL);
1389 /* Create semaphore */
1390 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1391 hwctx->alloc, &f->sem[i]);
1392 if (ret != VK_SUCCESS) {
1393 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1395 return AVERROR_EXTERNAL;
1398 f->layout[i] = image_create_info.initialLayout;
1409 vulkan_frame_free(hwfc, (uint8_t *)f);
1413 /* Checks if an export flag is enabled, and if it is ORs it with *iexp */
1414 static void try_export_flags(AVHWFramesContext *hwfc,
1415 VkExternalMemoryHandleTypeFlags *comp_handle_types,
1416 VkExternalMemoryHandleTypeFlagBits *iexp,
1417 VkExternalMemoryHandleTypeFlagBits exp)
1420 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1421 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1422 VkExternalImageFormatProperties eprops = {
1423 .sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES_KHR,
1425 VkImageFormatProperties2 props = {
1426 .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,
1429 VkPhysicalDeviceExternalImageFormatInfo enext = {
1430 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
1433 VkPhysicalDeviceImageFormatInfo2 pinfo = {
1434 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1435 .pNext = !exp ? NULL : &enext,
1436 .format = av_vkfmt_from_pixfmt(hwfc->sw_format)[0],
1437 .type = VK_IMAGE_TYPE_2D,
1438 .tiling = hwctx->tiling,
1439 .usage = hwctx->usage,
1440 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1443 ret = vkGetPhysicalDeviceImageFormatProperties2(dev_hwctx->phys_dev,
1445 if (ret == VK_SUCCESS) {
1447 *comp_handle_types |= eprops.externalMemoryProperties.compatibleHandleTypes;
1451 static AVBufferRef *vulkan_pool_alloc(void *opaque, int size)
1455 AVBufferRef *avbuf = NULL;
1456 AVHWFramesContext *hwfc = opaque;
1457 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1458 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1459 VkExportMemoryAllocateInfo eminfo[AV_NUM_DATA_POINTERS];
1460 VkExternalMemoryHandleTypeFlags e = 0x0;
1462 VkExternalMemoryImageCreateInfo eiinfo = {
1463 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1464 .pNext = hwctx->create_pnext,
1467 if (p->extensions & EXT_EXTERNAL_FD_MEMORY)
1468 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1469 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT);
1471 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
1472 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1473 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
1475 for (int i = 0; i < av_pix_fmt_count_planes(hwfc->sw_format); i++) {
1476 eminfo[i].sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO;
1477 eminfo[i].pNext = hwctx->alloc_pnext[i];
1478 eminfo[i].handleTypes = e;
1481 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1482 eiinfo.handleTypes ? &eiinfo : NULL);
1486 err = alloc_bind_mem(hwfc, f, eminfo, sizeof(*eminfo));
1490 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_WRITE);
1494 avbuf = av_buffer_create((uint8_t *)f, sizeof(AVVkFrame),
1495 vulkan_frame_free, hwfc, 0);
1502 vulkan_frame_free(hwfc, (uint8_t *)f);
1506 static void vulkan_frames_uninit(AVHWFramesContext *hwfc)
1508 VulkanFramesPriv *fp = hwfc->internal->priv;
1510 free_exec_ctx(hwfc->device_ctx, &fp->cmd);
1513 static int vulkan_frames_init(AVHWFramesContext *hwfc)
1517 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1518 VulkanFramesPriv *fp = hwfc->internal->priv;
1519 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1520 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1525 /* Default pool flags */
1526 hwctx->tiling = hwctx->tiling ? hwctx->tiling : p->use_linear_images ?
1527 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1529 hwctx->usage |= DEFAULT_USAGE_FLAGS;
1531 err = create_exec_ctx(hwfc->device_ctx, &fp->cmd,
1532 dev_hwctx->queue_family_tx_index);
1536 /* Test to see if allocation will fail */
1537 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1538 hwctx->create_pnext);
1540 free_exec_ctx(hwfc->device_ctx, &p->cmd);
1544 vulkan_frame_free(hwfc, (uint8_t *)f);
1546 hwfc->internal->pool_internal = av_buffer_pool_init2(sizeof(AVVkFrame),
1547 hwfc, vulkan_pool_alloc,
1549 if (!hwfc->internal->pool_internal) {
1550 free_exec_ctx(hwfc->device_ctx, &p->cmd);
1551 return AVERROR(ENOMEM);
1557 static int vulkan_get_buffer(AVHWFramesContext *hwfc, AVFrame *frame)
1559 frame->buf[0] = av_buffer_pool_get(hwfc->pool);
1561 return AVERROR(ENOMEM);
1563 frame->data[0] = frame->buf[0]->data;
1564 frame->format = AV_PIX_FMT_VULKAN;
1565 frame->width = hwfc->width;
1566 frame->height = hwfc->height;
1571 static int vulkan_transfer_get_formats(AVHWFramesContext *hwfc,
1572 enum AVHWFrameTransferDirection dir,
1573 enum AVPixelFormat **formats)
1575 enum AVPixelFormat *fmts = av_malloc_array(2, sizeof(*fmts));
1577 return AVERROR(ENOMEM);
1579 fmts[0] = hwfc->sw_format;
1580 fmts[1] = AV_PIX_FMT_NONE;
1586 typedef struct VulkanMapping {
1591 static void vulkan_unmap_frame(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1593 VulkanMapping *map = hwmap->priv;
1594 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1595 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1597 /* Check if buffer needs flushing */
1598 if ((map->flags & AV_HWFRAME_MAP_WRITE) &&
1599 !(map->frame->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1601 VkMappedMemoryRange flush_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1603 for (int i = 0; i < planes; i++) {
1604 flush_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1605 flush_ranges[i].memory = map->frame->mem[i];
1606 flush_ranges[i].size = VK_WHOLE_SIZE;
1609 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, planes,
1611 if (ret != VK_SUCCESS) {
1612 av_log(hwfc, AV_LOG_ERROR, "Failed to flush memory: %s\n",
1617 for (int i = 0; i < planes; i++)
1618 vkUnmapMemory(hwctx->act_dev, map->frame->mem[i]);
1623 static int vulkan_map_frame_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
1624 const AVFrame *src, int flags)
1627 int err, mapped_mem_count = 0;
1628 AVVkFrame *f = (AVVkFrame *)src->data[0];
1629 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1630 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1632 VulkanMapping *map = av_mallocz(sizeof(VulkanMapping));
1634 return AVERROR(EINVAL);
1636 if (src->format != AV_PIX_FMT_VULKAN) {
1637 av_log(hwfc, AV_LOG_ERROR, "Cannot map from pixel format %s!\n",
1638 av_get_pix_fmt_name(src->format));
1639 err = AVERROR(EINVAL);
1643 if (!(f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ||
1644 !(f->tiling == VK_IMAGE_TILING_LINEAR)) {
1645 av_log(hwfc, AV_LOG_ERROR, "Unable to map frame, not host visible "
1647 err = AVERROR(EINVAL);
1651 dst->width = src->width;
1652 dst->height = src->height;
1654 for (int i = 0; i < planes; i++) {
1655 ret = vkMapMemory(hwctx->act_dev, f->mem[i], 0,
1656 VK_WHOLE_SIZE, 0, (void **)&dst->data[i]);
1657 if (ret != VK_SUCCESS) {
1658 av_log(hwfc, AV_LOG_ERROR, "Failed to map image memory: %s\n",
1660 err = AVERROR_EXTERNAL;
1666 /* Check if the memory contents matter */
1667 if (((flags & AV_HWFRAME_MAP_READ) || !(flags & AV_HWFRAME_MAP_OVERWRITE)) &&
1668 !(f->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1669 VkMappedMemoryRange map_mem_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1670 for (int i = 0; i < planes; i++) {
1671 map_mem_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1672 map_mem_ranges[i].size = VK_WHOLE_SIZE;
1673 map_mem_ranges[i].memory = f->mem[i];
1676 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, planes,
1678 if (ret != VK_SUCCESS) {
1679 av_log(hwfc, AV_LOG_ERROR, "Failed to invalidate memory: %s\n",
1681 err = AVERROR_EXTERNAL;
1686 for (int i = 0; i < planes; i++) {
1687 VkImageSubresource sub = {
1688 .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
1690 VkSubresourceLayout layout;
1691 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
1692 dst->linesize[i] = layout.rowPitch;
1698 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src,
1699 &vulkan_unmap_frame, map);
1706 for (int i = 0; i < mapped_mem_count; i++)
1707 vkUnmapMemory(hwctx->act_dev, f->mem[i]);
1714 static void vulkan_unmap_from(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1716 VulkanMapping *map = hwmap->priv;
1717 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1718 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1720 for (int i = 0; i < planes; i++) {
1721 vkDestroyImage(hwctx->act_dev, map->frame->img[i], hwctx->alloc);
1722 vkFreeMemory(hwctx->act_dev, map->frame->mem[i], hwctx->alloc);
1723 vkDestroySemaphore(hwctx->act_dev, map->frame->sem[i], hwctx->alloc);
1726 av_freep(&map->frame);
1729 static const struct {
1730 uint32_t drm_fourcc;
1732 } vulkan_drm_format_map[] = {
1733 { DRM_FORMAT_R8, VK_FORMAT_R8_UNORM },
1734 { DRM_FORMAT_R16, VK_FORMAT_R16_UNORM },
1735 { DRM_FORMAT_GR88, VK_FORMAT_R8G8_UNORM },
1736 { DRM_FORMAT_RG88, VK_FORMAT_R8G8_UNORM },
1737 { DRM_FORMAT_GR1616, VK_FORMAT_R16G16_UNORM },
1738 { DRM_FORMAT_RG1616, VK_FORMAT_R16G16_UNORM },
1739 { DRM_FORMAT_ARGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1740 { DRM_FORMAT_XRGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1741 { DRM_FORMAT_ABGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1742 { DRM_FORMAT_XBGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1745 static inline VkFormat drm_to_vulkan_fmt(uint32_t drm_fourcc)
1747 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
1748 if (vulkan_drm_format_map[i].drm_fourcc == drm_fourcc)
1749 return vulkan_drm_format_map[i].vk_format;
1750 return VK_FORMAT_UNDEFINED;
1753 static int vulkan_map_from_drm_frame_desc(AVHWFramesContext *hwfc, AVVkFrame **frame,
1754 AVDRMFrameDescriptor *desc)
1759 int bind_counts = 0;
1760 AVHWDeviceContext *ctx = hwfc->device_ctx;
1761 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1762 VulkanDevicePriv *p = ctx->internal->priv;
1763 const AVPixFmtDescriptor *fmt_desc = av_pix_fmt_desc_get(hwfc->sw_format);
1764 const int has_modifiers = p->extensions & EXT_DRM_MODIFIER_FLAGS;
1765 VkSubresourceLayout plane_data[AV_NUM_DATA_POINTERS] = { 0 };
1766 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { 0 };
1767 VkBindImagePlaneMemoryInfo plane_info[AV_NUM_DATA_POINTERS] = { 0 };
1768 VkExternalMemoryHandleTypeFlagBits htype = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
1770 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdPropertiesKHR);
1772 for (int i = 0; i < desc->nb_layers; i++) {
1773 if (drm_to_vulkan_fmt(desc->layers[i].format) == VK_FORMAT_UNDEFINED) {
1774 av_log(ctx, AV_LOG_ERROR, "Unsupported DMABUF layer format %#08x!\n",
1775 desc->layers[i].format);
1776 return AVERROR(EINVAL);
1780 if (!(f = av_vk_frame_alloc())) {
1781 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1782 err = AVERROR(ENOMEM);
1786 for (int i = 0; i < desc->nb_objects; i++) {
1787 VkMemoryFdPropertiesKHR fdmp = {
1788 .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,
1790 VkMemoryRequirements req = {
1791 .size = desc->objects[i].size,
1793 VkImportMemoryFdInfoKHR idesc = {
1794 .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
1795 .handleType = htype,
1796 .fd = dup(desc->objects[i].fd),
1799 ret = pfn_vkGetMemoryFdPropertiesKHR(hwctx->act_dev, htype,
1801 if (ret != VK_SUCCESS) {
1802 av_log(hwfc, AV_LOG_ERROR, "Failed to get FD properties: %s\n",
1804 err = AVERROR_EXTERNAL;
1809 req.memoryTypeBits = fdmp.memoryTypeBits;
1811 err = alloc_mem(ctx, &req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1812 &idesc, &f->flags, &f->mem[i]);
1818 f->size[i] = desc->objects[i].size;
1821 f->tiling = has_modifiers ? VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT :
1822 desc->objects[0].format_modifier == DRM_FORMAT_MOD_LINEAR ?
1823 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1825 for (int i = 0; i < desc->nb_layers; i++) {
1826 const int planes = desc->layers[i].nb_planes;
1827 const int signal_p = has_modifiers && (planes > 1);
1829 VkImageDrmFormatModifierExplicitCreateInfoEXT drm_info = {
1830 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
1831 .drmFormatModifier = desc->objects[0].format_modifier,
1832 .drmFormatModifierPlaneCount = planes,
1833 .pPlaneLayouts = (const VkSubresourceLayout *)&plane_data,
1836 VkExternalMemoryImageCreateInfo einfo = {
1837 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1838 .pNext = has_modifiers ? &drm_info : NULL,
1839 .handleTypes = htype,
1842 VkSemaphoreCreateInfo sem_spawn = {
1843 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1846 const int p_w = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, fmt_desc->log2_chroma_w) : hwfc->width;
1847 const int p_h = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, fmt_desc->log2_chroma_h) : hwfc->height;
1849 VkImageCreateInfo image_create_info = {
1850 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1852 .imageType = VK_IMAGE_TYPE_2D,
1853 .format = drm_to_vulkan_fmt(desc->layers[i].format),
1854 .extent.width = p_w,
1855 .extent.height = p_h,
1859 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1860 .tiling = f->tiling,
1861 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, /* specs say so */
1862 .usage = DEFAULT_USAGE_FLAGS,
1863 .samples = VK_SAMPLE_COUNT_1_BIT,
1864 .pQueueFamilyIndices = p->qfs,
1865 .queueFamilyIndexCount = p->num_qfs,
1866 .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
1867 VK_SHARING_MODE_EXCLUSIVE,
1870 for (int j = 0; j < planes; j++) {
1871 plane_data[j].offset = desc->layers[i].planes[j].offset;
1872 plane_data[j].rowPitch = desc->layers[i].planes[j].pitch;
1873 plane_data[j].size = 0; /* The specs say so for all 3 */
1874 plane_data[j].arrayPitch = 0;
1875 plane_data[j].depthPitch = 0;
1879 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
1880 hwctx->alloc, &f->img[i]);
1881 if (ret != VK_SUCCESS) {
1882 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1884 err = AVERROR(EINVAL);
1888 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1889 hwctx->alloc, &f->sem[i]);
1890 if (ret != VK_SUCCESS) {
1891 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1893 return AVERROR_EXTERNAL;
1896 /* We'd import a semaphore onto the one we created using
1897 * vkImportSemaphoreFdKHR but unfortunately neither DRM nor VAAPI
1898 * offer us anything we could import and sync with, so instead
1899 * just signal the semaphore we created. */
1901 f->layout[i] = image_create_info.initialLayout;
1904 for (int j = 0; j < planes; j++) {
1905 VkImageAspectFlagBits aspect = j == 0 ? VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
1906 j == 1 ? VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT :
1907 VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT;
1909 plane_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO;
1910 plane_info[bind_counts].planeAspect = aspect;
1912 bind_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
1913 bind_info[bind_counts].pNext = signal_p ? &plane_info[bind_counts] : NULL;
1914 bind_info[bind_counts].image = f->img[i];
1915 bind_info[bind_counts].memory = f->mem[desc->layers[i].planes[j].object_index];
1916 bind_info[bind_counts].memoryOffset = desc->layers[i].planes[j].offset;
1921 /* Bind the allocated memory to the images */
1922 ret = vkBindImageMemory2(hwctx->act_dev, bind_counts, bind_info);
1923 if (ret != VK_SUCCESS) {
1924 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
1926 return AVERROR_EXTERNAL;
1929 /* NOTE: This is completely uneccesary and unneeded once we can import
1930 * semaphores from DRM. Otherwise we have to activate the semaphores.
1931 * We're reusing the exec context that's also used for uploads/downloads. */
1932 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_RO_SHADER);
1941 for (int i = 0; i < desc->nb_layers; i++) {
1942 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
1943 vkDestroySemaphore(hwctx->act_dev, f->sem[i], hwctx->alloc);
1945 for (int i = 0; i < desc->nb_objects; i++)
1946 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
1953 static int vulkan_map_from_drm(AVHWFramesContext *hwfc, AVFrame *dst,
1954 const AVFrame *src, int flags)
1958 VulkanMapping *map = NULL;
1960 err = vulkan_map_from_drm_frame_desc(hwfc, &f,
1961 (AVDRMFrameDescriptor *)src->data[0]);
1965 /* The unmapping function will free this */
1966 dst->data[0] = (uint8_t *)f;
1967 dst->width = src->width;
1968 dst->height = src->height;
1970 map = av_mallocz(sizeof(VulkanMapping));
1977 err = ff_hwframe_map_create(dst->hw_frames_ctx, dst, src,
1978 &vulkan_unmap_from, map);
1982 av_log(hwfc, AV_LOG_DEBUG, "Mapped DRM object to Vulkan!\n");
1987 vulkan_frame_free(hwfc->device_ctx->hwctx, (uint8_t *)f);
1993 static int vulkan_map_from_vaapi(AVHWFramesContext *dst_fc,
1994 AVFrame *dst, const AVFrame *src,
1998 AVFrame *tmp = av_frame_alloc();
1999 AVHWFramesContext *vaapi_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2000 AVVAAPIDeviceContext *vaapi_ctx = vaapi_fc->device_ctx->hwctx;
2001 VASurfaceID surface_id = (VASurfaceID)(uintptr_t)src->data[3];
2004 return AVERROR(ENOMEM);
2006 /* We have to sync since like the previous comment said, no semaphores */
2007 vaSyncSurface(vaapi_ctx->display, surface_id);
2009 tmp->format = AV_PIX_FMT_DRM_PRIME;
2011 err = av_hwframe_map(tmp, src, flags);
2015 err = vulkan_map_from_drm(dst_fc, dst, tmp, flags);
2019 err = ff_hwframe_map_replace(dst, src);
2022 av_frame_free(&tmp);
2029 static int vulkan_export_to_cuda(AVHWFramesContext *hwfc,
2030 AVBufferRef *cuda_hwfc,
2031 const AVFrame *frame)
2036 AVVkFrameInternal *dst_int;
2037 AVHWDeviceContext *ctx = hwfc->device_ctx;
2038 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2039 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2040 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2041 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2042 VK_LOAD_PFN(hwctx->inst, vkGetSemaphoreFdKHR);
2044 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)cuda_hwfc->data;
2045 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2046 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2047 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2048 CudaFunctions *cu = cu_internal->cuda_dl;
2049 CUarray_format cufmt = desc->comp[0].depth > 8 ? CU_AD_FORMAT_UNSIGNED_INT16 :
2050 CU_AD_FORMAT_UNSIGNED_INT8;
2052 dst_f = (AVVkFrame *)frame->data[0];
2054 dst_int = dst_f->internal;
2055 if (!dst_int || !dst_int->cuda_fc_ref) {
2056 if (!dst_f->internal)
2057 dst_f->internal = dst_int = av_mallocz(sizeof(*dst_f->internal));
2060 err = AVERROR(ENOMEM);
2064 dst_int->cuda_fc_ref = av_buffer_ref(cuda_hwfc);
2065 if (!dst_int->cuda_fc_ref) {
2066 err = AVERROR(ENOMEM);
2070 for (int i = 0; i < planes; i++) {
2071 CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC tex_desc = {
2074 .Width = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2076 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2080 .NumChannels = 1 + ((planes == 2) && i),
2085 CUDA_EXTERNAL_MEMORY_HANDLE_DESC ext_desc = {
2086 .type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD,
2087 .size = dst_f->size[i],
2089 VkMemoryGetFdInfoKHR export_info = {
2090 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2091 .memory = dst_f->mem[i],
2092 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR,
2094 VkSemaphoreGetFdInfoKHR sem_export = {
2095 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR,
2096 .semaphore = dst_f->sem[i],
2097 .handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
2099 CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC ext_sem_desc = {
2100 .type = CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD,
2103 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2104 &ext_desc.handle.fd);
2105 if (ret != VK_SUCCESS) {
2106 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2107 err = AVERROR_EXTERNAL;
2111 ret = CHECK_CU(cu->cuImportExternalMemory(&dst_int->ext_mem[i], &ext_desc));
2113 err = AVERROR_EXTERNAL;
2117 ret = CHECK_CU(cu->cuExternalMemoryGetMappedMipmappedArray(&dst_int->cu_mma[i],
2118 dst_int->ext_mem[i],
2121 err = AVERROR_EXTERNAL;
2125 ret = CHECK_CU(cu->cuMipmappedArrayGetLevel(&dst_int->cu_array[i],
2126 dst_int->cu_mma[i], 0));
2128 err = AVERROR_EXTERNAL;
2132 ret = pfn_vkGetSemaphoreFdKHR(hwctx->act_dev, &sem_export,
2133 &ext_sem_desc.handle.fd);
2134 if (ret != VK_SUCCESS) {
2135 av_log(ctx, AV_LOG_ERROR, "Failed to export semaphore: %s\n",
2137 err = AVERROR_EXTERNAL;
2141 ret = CHECK_CU(cu->cuImportExternalSemaphore(&dst_int->cu_sem[i],
2144 err = AVERROR_EXTERNAL;
2156 static int vulkan_transfer_data_from_cuda(AVHWFramesContext *hwfc,
2157 AVFrame *dst, const AVFrame *src)
2163 AVVkFrameInternal *dst_int;
2164 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2165 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2167 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2168 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2169 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2170 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2171 CudaFunctions *cu = cu_internal->cuda_dl;
2172 CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS s_w_par[AV_NUM_DATA_POINTERS] = { 0 };
2173 CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS s_s_par[AV_NUM_DATA_POINTERS] = { 0 };
2175 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2177 err = AVERROR_EXTERNAL;
2181 dst_f = (AVVkFrame *)dst->data[0];
2183 ret = vulkan_export_to_cuda(hwfc, src->hw_frames_ctx, dst);
2187 dst_int = dst_f->internal;
2189 ret = CHECK_CU(cu->cuWaitExternalSemaphoresAsync(dst_int->cu_sem, s_w_par,
2190 planes, cuda_dev->stream));
2192 err = AVERROR_EXTERNAL;
2196 for (int i = 0; i < planes; i++) {
2197 CUDA_MEMCPY2D cpy = {
2198 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
2199 .srcDevice = (CUdeviceptr)src->data[i],
2200 .srcPitch = src->linesize[i],
2203 .dstMemoryType = CU_MEMORYTYPE_ARRAY,
2204 .dstArray = dst_int->cu_array[i],
2205 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2206 : hwfc->width) * desc->comp[i].step,
2207 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2211 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2213 err = AVERROR_EXTERNAL;
2218 ret = CHECK_CU(cu->cuSignalExternalSemaphoresAsync(dst_int->cu_sem, s_s_par,
2219 planes, cuda_dev->stream));
2221 err = AVERROR_EXTERNAL;
2225 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2227 av_log(hwfc, AV_LOG_VERBOSE, "Transfered CUDA image to Vulkan!\n");
2232 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2233 vulkan_free_internal(dst_int);
2234 dst_f->internal = NULL;
2235 av_buffer_unref(&dst->buf[0]);
2240 static int vulkan_map_to(AVHWFramesContext *hwfc, AVFrame *dst,
2241 const AVFrame *src, int flags)
2243 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2245 switch (src->format) {
2248 case AV_PIX_FMT_VAAPI:
2249 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2250 return vulkan_map_from_vaapi(hwfc, dst, src, flags);
2252 case AV_PIX_FMT_DRM_PRIME:
2253 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2254 return vulkan_map_from_drm(hwfc, dst, src, flags);
2257 return AVERROR(ENOSYS);
2262 typedef struct VulkanDRMMapping {
2263 AVDRMFrameDescriptor drm_desc;
2267 static void vulkan_unmap_to_drm(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
2269 AVDRMFrameDescriptor *drm_desc = hwmap->priv;
2271 for (int i = 0; i < drm_desc->nb_objects; i++)
2272 close(drm_desc->objects[i].fd);
2277 static inline uint32_t vulkan_fmt_to_drm(VkFormat vkfmt)
2279 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
2280 if (vulkan_drm_format_map[i].vk_format == vkfmt)
2281 return vulkan_drm_format_map[i].drm_fourcc;
2282 return DRM_FORMAT_INVALID;
2285 static int vulkan_map_to_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2286 const AVFrame *src, int flags)
2290 AVVkFrame *f = (AVVkFrame *)src->data[0];
2291 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2292 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
2293 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2294 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2295 VkImageDrmFormatModifierPropertiesEXT drm_mod = {
2296 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT,
2299 AVDRMFrameDescriptor *drm_desc = av_mallocz(sizeof(*drm_desc));
2301 return AVERROR(ENOMEM);
2303 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_EXTERNAL_EXPORT);
2307 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src, &vulkan_unmap_to_drm, drm_desc);
2311 if (p->extensions & EXT_DRM_MODIFIER_FLAGS) {
2312 VK_LOAD_PFN(hwctx->inst, vkGetImageDrmFormatModifierPropertiesEXT);
2313 ret = pfn_vkGetImageDrmFormatModifierPropertiesEXT(hwctx->act_dev, f->img[0],
2315 if (ret != VK_SUCCESS) {
2316 av_log(hwfc, AV_LOG_ERROR, "Failed to retrieve DRM format modifier!\n");
2317 err = AVERROR_EXTERNAL;
2322 for (int i = 0; (i < planes) && (f->mem[i]); i++) {
2323 VkMemoryGetFdInfoKHR export_info = {
2324 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2325 .memory = f->mem[i],
2326 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,
2329 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2330 &drm_desc->objects[i].fd);
2331 if (ret != VK_SUCCESS) {
2332 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2333 err = AVERROR_EXTERNAL;
2337 drm_desc->nb_objects++;
2338 drm_desc->objects[i].size = f->size[i];
2339 drm_desc->objects[i].format_modifier = drm_mod.drmFormatModifier;
2342 drm_desc->nb_layers = planes;
2343 for (int i = 0; i < drm_desc->nb_layers; i++) {
2344 VkSubresourceLayout layout;
2345 VkImageSubresource sub = {
2346 .aspectMask = p->extensions & EXT_DRM_MODIFIER_FLAGS ?
2347 VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2348 VK_IMAGE_ASPECT_COLOR_BIT,
2350 VkFormat plane_vkfmt = av_vkfmt_from_pixfmt(hwfc->sw_format)[i];
2352 drm_desc->layers[i].format = vulkan_fmt_to_drm(plane_vkfmt);
2353 drm_desc->layers[i].nb_planes = 1;
2355 if (drm_desc->layers[i].format == DRM_FORMAT_INVALID) {
2356 av_log(hwfc, AV_LOG_ERROR, "Cannot map to DRM layer, unsupported!\n");
2357 err = AVERROR_PATCHWELCOME;
2361 drm_desc->layers[i].planes[0].object_index = FFMIN(i, drm_desc->nb_objects - 1);
2363 if (f->tiling == VK_IMAGE_TILING_OPTIMAL)
2366 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
2367 drm_desc->layers[i].planes[0].offset = layout.offset;
2368 drm_desc->layers[i].planes[0].pitch = layout.rowPitch;
2371 dst->width = src->width;
2372 dst->height = src->height;
2373 dst->data[0] = (uint8_t *)drm_desc;
2375 av_log(hwfc, AV_LOG_VERBOSE, "Mapped AVVkFrame to a DRM object!\n");
2385 static int vulkan_map_to_vaapi(AVHWFramesContext *hwfc, AVFrame *dst,
2386 const AVFrame *src, int flags)
2389 AVFrame *tmp = av_frame_alloc();
2391 return AVERROR(ENOMEM);
2393 tmp->format = AV_PIX_FMT_DRM_PRIME;
2395 err = vulkan_map_to_drm(hwfc, tmp, src, flags);
2399 err = av_hwframe_map(dst, tmp, flags);
2403 err = ff_hwframe_map_replace(dst, src);
2406 av_frame_free(&tmp);
2412 static int vulkan_map_from(AVHWFramesContext *hwfc, AVFrame *dst,
2413 const AVFrame *src, int flags)
2415 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2417 switch (dst->format) {
2419 case AV_PIX_FMT_DRM_PRIME:
2420 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2421 return vulkan_map_to_drm(hwfc, dst, src, flags);
2423 case AV_PIX_FMT_VAAPI:
2424 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2425 return vulkan_map_to_vaapi(hwfc, dst, src, flags);
2429 return vulkan_map_frame_to_mem(hwfc, dst, src, flags);
2433 typedef struct ImageBuffer {
2436 VkMemoryPropertyFlagBits flags;
2439 static void free_buf(AVHWDeviceContext *ctx, ImageBuffer *buf)
2441 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2445 vkDestroyBuffer(hwctx->act_dev, buf->buf, hwctx->alloc);
2446 vkFreeMemory(hwctx->act_dev, buf->mem, hwctx->alloc);
2449 static int create_buf(AVHWDeviceContext *ctx, ImageBuffer *buf, int height,
2450 int *stride, VkBufferUsageFlags usage,
2451 VkMemoryPropertyFlagBits flags, void *create_pnext,
2456 VkMemoryRequirements req;
2457 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2458 VulkanDevicePriv *p = ctx->internal->priv;
2460 VkBufferCreateInfo buf_spawn = {
2461 .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
2462 .pNext = create_pnext,
2464 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
2467 *stride = FFALIGN(*stride, p->props.limits.optimalBufferCopyRowPitchAlignment);
2468 buf_spawn.size = height*(*stride);
2470 ret = vkCreateBuffer(hwctx->act_dev, &buf_spawn, NULL, &buf->buf);
2471 if (ret != VK_SUCCESS) {
2472 av_log(ctx, AV_LOG_ERROR, "Failed to create buffer: %s\n",
2474 return AVERROR_EXTERNAL;
2477 vkGetBufferMemoryRequirements(hwctx->act_dev, buf->buf, &req);
2479 err = alloc_mem(ctx, &req, flags, alloc_pnext, &buf->flags, &buf->mem);
2483 ret = vkBindBufferMemory(hwctx->act_dev, buf->buf, buf->mem, 0);
2484 if (ret != VK_SUCCESS) {
2485 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory to buffer: %s\n",
2488 return AVERROR_EXTERNAL;
2494 static int map_buffers(AVHWDeviceContext *ctx, ImageBuffer *buf, uint8_t *mem[],
2495 int nb_buffers, int invalidate)
2498 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2499 VkMappedMemoryRange invalidate_ctx[AV_NUM_DATA_POINTERS];
2500 int invalidate_count = 0;
2502 for (int i = 0; i < nb_buffers; i++) {
2503 ret = vkMapMemory(hwctx->act_dev, buf[i].mem, 0,
2504 VK_WHOLE_SIZE, 0, (void **)&mem[i]);
2505 if (ret != VK_SUCCESS) {
2506 av_log(ctx, AV_LOG_ERROR, "Failed to map buffer memory: %s\n",
2508 return AVERROR_EXTERNAL;
2515 for (int i = 0; i < nb_buffers; i++) {
2516 const VkMappedMemoryRange ival_buf = {
2517 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2518 .memory = buf[i].mem,
2519 .size = VK_WHOLE_SIZE,
2521 if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2523 invalidate_ctx[invalidate_count++] = ival_buf;
2526 if (invalidate_count) {
2527 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, invalidate_count,
2529 if (ret != VK_SUCCESS)
2530 av_log(ctx, AV_LOG_WARNING, "Failed to invalidate memory: %s\n",
2537 static int unmap_buffers(AVHWDeviceContext *ctx, ImageBuffer *buf,
2538 int nb_buffers, int flush)
2542 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2543 VkMappedMemoryRange flush_ctx[AV_NUM_DATA_POINTERS];
2544 int flush_count = 0;
2547 for (int i = 0; i < nb_buffers; i++) {
2548 const VkMappedMemoryRange flush_buf = {
2549 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2550 .memory = buf[i].mem,
2551 .size = VK_WHOLE_SIZE,
2553 if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2555 flush_ctx[flush_count++] = flush_buf;
2560 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, flush_count, flush_ctx);
2561 if (ret != VK_SUCCESS) {
2562 av_log(ctx, AV_LOG_ERROR, "Failed to flush memory: %s\n",
2564 err = AVERROR_EXTERNAL; /* We still want to try to unmap them */
2568 for (int i = 0; i < nb_buffers; i++)
2569 vkUnmapMemory(hwctx->act_dev, buf[i].mem);
2574 static int transfer_image_buf(AVHWDeviceContext *ctx, AVVkFrame *frame,
2575 ImageBuffer *buffer, const int *buf_stride, int w,
2576 int h, enum AVPixelFormat pix_fmt, int to_buf)
2579 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2580 VulkanDevicePriv *s = ctx->internal->priv;
2583 VkPipelineStageFlagBits sem_wait_dst[AV_NUM_DATA_POINTERS];
2585 const int planes = av_pix_fmt_count_planes(pix_fmt);
2586 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2588 VkCommandBufferBeginInfo cmd_start = {
2589 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
2590 .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
2593 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
2595 VkSubmitInfo s_info = {
2596 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
2597 .commandBufferCount = 1,
2598 .pCommandBuffers = &s->cmd.buf,
2599 .pSignalSemaphores = frame->sem,
2600 .pWaitSemaphores = frame->sem,
2601 .pWaitDstStageMask = sem_wait_dst,
2602 .signalSemaphoreCount = planes,
2603 .waitSemaphoreCount = planes,
2606 ret = vkBeginCommandBuffer(s->cmd.buf, &cmd_start);
2607 if (ret != VK_SUCCESS) {
2608 av_log(ctx, AV_LOG_ERROR, "Unable to init command buffer: %s\n",
2610 return AVERROR_EXTERNAL;
2613 /* Change the image layout to something more optimal for transfers */
2614 for (int i = 0; i < planes; i++) {
2615 VkImageLayout new_layout = to_buf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL :
2616 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
2617 VkAccessFlags new_access = to_buf ? VK_ACCESS_TRANSFER_READ_BIT :
2618 VK_ACCESS_TRANSFER_WRITE_BIT;
2620 sem_wait_dst[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
2622 /* If the layout matches and we have read access skip the barrier */
2623 if ((frame->layout[i] == new_layout) && (frame->access[i] & new_access))
2626 img_bar[bar_num].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
2627 img_bar[bar_num].srcAccessMask = 0x0;
2628 img_bar[bar_num].dstAccessMask = new_access;
2629 img_bar[bar_num].oldLayout = frame->layout[i];
2630 img_bar[bar_num].newLayout = new_layout;
2631 img_bar[bar_num].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2632 img_bar[bar_num].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2633 img_bar[bar_num].image = frame->img[i];
2634 img_bar[bar_num].subresourceRange.levelCount = 1;
2635 img_bar[bar_num].subresourceRange.layerCount = 1;
2636 img_bar[bar_num].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2638 frame->layout[i] = img_bar[bar_num].newLayout;
2639 frame->access[i] = img_bar[bar_num].dstAccessMask;
2645 vkCmdPipelineBarrier(s->cmd.buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
2646 VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
2647 0, NULL, 0, NULL, bar_num, img_bar);
2649 /* Schedule a copy for each plane */
2650 for (int i = 0; i < planes; i++) {
2651 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
2652 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
2653 VkBufferImageCopy buf_reg = {
2655 /* Buffer stride isn't in bytes, it's in samples, the implementation
2656 * uses the image's VkFormat to know how many bytes per sample
2657 * the buffer has. So we have to convert by dividing. Stupid.
2658 * Won't work with YUVA or other planar formats with alpha. */
2659 .bufferRowLength = buf_stride[i] / desc->comp[i].step,
2660 .bufferImageHeight = p_h,
2661 .imageSubresource.layerCount = 1,
2662 .imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
2663 .imageOffset = { 0, 0, 0, },
2664 .imageExtent = { p_w, p_h, 1, },
2668 vkCmdCopyImageToBuffer(s->cmd.buf, frame->img[i], frame->layout[i],
2669 buffer[i].buf, 1, &buf_reg);
2671 vkCmdCopyBufferToImage(s->cmd.buf, buffer[i].buf, frame->img[i],
2672 frame->layout[i], 1, &buf_reg);
2675 ret = vkEndCommandBuffer(s->cmd.buf);
2676 if (ret != VK_SUCCESS) {
2677 av_log(ctx, AV_LOG_ERROR, "Unable to finish command buffer: %s\n",
2679 return AVERROR_EXTERNAL;
2682 /* Wait for the download/upload to finish if uploading, otherwise the
2683 * semaphore will take care of synchronization when uploading */
2684 ret = vkQueueSubmit(s->cmd.queue, 1, &s_info, s->cmd.fence);
2685 if (ret != VK_SUCCESS) {
2686 av_log(ctx, AV_LOG_ERROR, "Unable to submit command buffer: %s\n",
2688 return AVERROR_EXTERNAL;
2690 vkWaitForFences(hwctx->act_dev, 1, &s->cmd.fence, VK_TRUE, UINT64_MAX);
2691 vkResetFences(hwctx->act_dev, 1, &s->cmd.fence);
2697 /* Technically we can use VK_EXT_external_memory_host to upload and download,
2698 * however the alignment requirements make this unfeasible as both the pointer
2699 * and the size of each plane need to be aligned to the minimum alignment
2700 * requirement, which on all current implementations (anv, radv) is 4096.
2701 * If the requirement gets relaxed (unlikely) this can easily be implemented. */
2702 static int vulkan_transfer_data_from_mem(AVHWFramesContext *hwfc, AVFrame *dst,
2707 AVVkFrame *f = (AVVkFrame *)dst->data[0];
2708 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
2709 ImageBuffer buf[AV_NUM_DATA_POINTERS] = { { 0 } };
2710 const int planes = av_pix_fmt_count_planes(src->format);
2711 int log2_chroma = av_pix_fmt_desc_get(src->format)->log2_chroma_h;
2713 if ((src->format != AV_PIX_FMT_NONE && !av_vkfmt_from_pixfmt(src->format))) {
2714 av_log(hwfc, AV_LOG_ERROR, "Unsupported source pixel format!\n");
2715 return AVERROR(EINVAL);
2718 if (src->width > hwfc->width || src->height > hwfc->height)
2719 return AVERROR(EINVAL);
2721 /* For linear, host visiable images */
2722 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
2723 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
2724 AVFrame *map = av_frame_alloc();
2726 return AVERROR(ENOMEM);
2727 map->format = src->format;
2729 err = vulkan_map_frame_to_mem(hwfc, map, dst, AV_HWFRAME_MAP_WRITE);
2733 err = av_frame_copy(map, src);
2734 av_frame_free(&map);
2738 /* Create buffers */
2739 for (int i = 0; i < planes; i++) {
2740 int h = src->height;
2741 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
2743 tmp.linesize[i] = FFABS(src->linesize[i]);
2744 err = create_buf(dev_ctx, &buf[i], p_height,
2745 &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
2746 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
2751 /* Map, copy image to buffer, unmap */
2752 if ((err = map_buffers(dev_ctx, buf, tmp.data, planes, 0)))
2755 av_image_copy(tmp.data, tmp.linesize, (const uint8_t **)src->data,
2756 src->linesize, src->format, src->width, src->height);
2758 if ((err = unmap_buffers(dev_ctx, buf, planes, 1)))
2761 /* Copy buffers to image */
2762 err = transfer_image_buf(dev_ctx, f, buf, tmp.linesize,
2763 src->width, src->height, src->format, 0);
2766 for (int i = 0; i < planes; i++)
2767 free_buf(dev_ctx, &buf[i]);
2772 static int vulkan_transfer_data_to(AVHWFramesContext *hwfc, AVFrame *dst,
2775 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2777 switch (src->format) {
2779 case AV_PIX_FMT_CUDA:
2780 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
2781 (p->extensions & EXT_EXTERNAL_FD_SEM))
2782 return vulkan_transfer_data_from_cuda(hwfc, dst, src);
2785 if (src->hw_frames_ctx)
2786 return AVERROR(ENOSYS);
2788 return vulkan_transfer_data_from_mem(hwfc, dst, src);
2793 static int vulkan_transfer_data_to_cuda(AVHWFramesContext *hwfc, AVFrame *dst,
2800 AVVkFrameInternal *dst_int;
2801 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2802 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2804 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)dst->hw_frames_ctx->data;
2805 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2806 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2807 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2808 CudaFunctions *cu = cu_internal->cuda_dl;
2810 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2812 err = AVERROR_EXTERNAL;
2816 dst_f = (AVVkFrame *)src->data[0];
2818 err = vulkan_export_to_cuda(hwfc, dst->hw_frames_ctx, src);
2823 dst_int = dst_f->internal;
2825 for (int i = 0; i < planes; i++) {
2826 CUDA_MEMCPY2D cpy = {
2827 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
2828 .dstDevice = (CUdeviceptr)dst->data[i],
2829 .dstPitch = dst->linesize[i],
2832 .srcMemoryType = CU_MEMORYTYPE_ARRAY,
2833 .srcArray = dst_int->cu_array[i],
2834 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2835 : hwfc->width) * desc->comp[i].step,
2836 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2840 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2842 err = AVERROR_EXTERNAL;
2847 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2849 av_log(hwfc, AV_LOG_VERBOSE, "Transfered Vulkan image to CUDA!\n");
2854 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2855 vulkan_free_internal(dst_int);
2856 dst_f->internal = NULL;
2857 av_buffer_unref(&dst->buf[0]);
2862 static int vulkan_transfer_data_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
2867 AVVkFrame *f = (AVVkFrame *)src->data[0];
2868 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
2869 ImageBuffer buf[AV_NUM_DATA_POINTERS] = { { 0 } };
2870 const int planes = av_pix_fmt_count_planes(dst->format);
2871 int log2_chroma = av_pix_fmt_desc_get(dst->format)->log2_chroma_h;
2873 if (dst->width > hwfc->width || dst->height > hwfc->height)
2874 return AVERROR(EINVAL);
2876 /* For linear, host visiable images */
2877 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
2878 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
2879 AVFrame *map = av_frame_alloc();
2881 return AVERROR(ENOMEM);
2882 map->format = dst->format;
2884 err = vulkan_map_frame_to_mem(hwfc, map, src, AV_HWFRAME_MAP_READ);
2888 err = av_frame_copy(dst, map);
2889 av_frame_free(&map);
2893 /* Create buffers */
2894 for (int i = 0; i < planes; i++) {
2895 int h = dst->height;
2896 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
2898 tmp.linesize[i] = FFABS(dst->linesize[i]);
2899 err = create_buf(dev_ctx, &buf[i], p_height,
2900 &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_DST_BIT,
2901 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
2904 /* Copy image to buffer */
2905 if ((err = transfer_image_buf(dev_ctx, f, buf, tmp.linesize,
2906 dst->width, dst->height, dst->format, 1)))
2909 /* Map, copy buffer to frame, unmap */
2910 if ((err = map_buffers(dev_ctx, buf, tmp.data, planes, 1)))
2913 av_image_copy(dst->data, dst->linesize, (const uint8_t **)tmp.data,
2914 tmp.linesize, dst->format, dst->width, dst->height);
2916 err = unmap_buffers(dev_ctx, buf, planes, 0);
2919 for (int i = 0; i < planes; i++)
2920 free_buf(dev_ctx, &buf[i]);
2925 static int vulkan_transfer_data_from(AVHWFramesContext *hwfc, AVFrame *dst,
2928 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2930 switch (dst->format) {
2932 case AV_PIX_FMT_CUDA:
2933 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
2934 (p->extensions & EXT_EXTERNAL_FD_SEM))
2935 return vulkan_transfer_data_to_cuda(hwfc, dst, src);
2938 if (dst->hw_frames_ctx)
2939 return AVERROR(ENOSYS);
2941 return vulkan_transfer_data_to_mem(hwfc, dst, src);
2945 AVVkFrame *av_vk_frame_alloc(void)
2947 return av_mallocz(sizeof(AVVkFrame));
2950 const HWContextType ff_hwcontext_type_vulkan = {
2951 .type = AV_HWDEVICE_TYPE_VULKAN,
2954 .device_hwctx_size = sizeof(AVVulkanDeviceContext),
2955 .device_priv_size = sizeof(VulkanDevicePriv),
2956 .frames_hwctx_size = sizeof(AVVulkanFramesContext),
2957 .frames_priv_size = sizeof(VulkanFramesPriv),
2959 .device_init = &vulkan_device_init,
2960 .device_create = &vulkan_device_create,
2961 .device_derive = &vulkan_device_derive,
2963 .frames_get_constraints = &vulkan_frames_get_constraints,
2964 .frames_init = vulkan_frames_init,
2965 .frames_get_buffer = vulkan_get_buffer,
2966 .frames_uninit = vulkan_frames_uninit,
2968 .transfer_get_formats = vulkan_transfer_get_formats,
2969 .transfer_data_to = vulkan_transfer_data_to,
2970 .transfer_data_from = vulkan_transfer_data_from,
2972 .map_to = vulkan_map_to,
2973 .map_from = vulkan_map_from,
2975 .pix_fmts = (const enum AVPixelFormat []) {