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;
57 VkDebugUtilsMessengerEXT debug_ctx;
66 int use_linear_images;
72 typedef struct VulkanFramesPriv {
76 typedef struct AVVkFrameInternal {
78 /* Importing external memory into cuda is really expensive so we keep the
79 * memory imported all the time */
80 AVBufferRef *cuda_fc_ref; /* Need to keep it around for uninit */
81 CUexternalMemory ext_mem[AV_NUM_DATA_POINTERS];
82 CUmipmappedArray cu_mma[AV_NUM_DATA_POINTERS];
83 CUarray cu_array[AV_NUM_DATA_POINTERS];
84 CUexternalSemaphore cu_sem;
88 #define VK_LOAD_PFN(inst, name) PFN_##name pfn_##name = (PFN_##name) \
89 vkGetInstanceProcAddr(inst, #name)
91 #define DEFAULT_USAGE_FLAGS (VK_IMAGE_USAGE_SAMPLED_BIT | \
92 VK_IMAGE_USAGE_STORAGE_BIT | \
93 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | \
94 VK_IMAGE_USAGE_TRANSFER_DST_BIT)
96 #define ADD_VAL_TO_LIST(list, count, val) \
98 list = av_realloc_array(list, sizeof(*list), ++count); \
100 err = AVERROR(ENOMEM); \
103 list[count - 1] = av_strdup(val); \
104 if (!list[count - 1]) { \
105 err = AVERROR(ENOMEM); \
110 static const struct {
111 enum AVPixelFormat pixfmt;
112 const VkFormat vkfmts[3];
113 } vk_pixfmt_map[] = {
114 { AV_PIX_FMT_GRAY8, { VK_FORMAT_R8_UNORM } },
115 { AV_PIX_FMT_GRAY16, { VK_FORMAT_R16_UNORM } },
116 { AV_PIX_FMT_GRAYF32, { VK_FORMAT_R32_SFLOAT } },
118 { AV_PIX_FMT_NV12, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8G8_UNORM } },
119 { AV_PIX_FMT_P010, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16G16_UNORM } },
120 { AV_PIX_FMT_P016, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16G16_UNORM } },
122 { AV_PIX_FMT_YUV420P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
123 { AV_PIX_FMT_YUV422P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
124 { AV_PIX_FMT_YUV444P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
126 { AV_PIX_FMT_YUV420P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
127 { AV_PIX_FMT_YUV422P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
128 { AV_PIX_FMT_YUV444P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
130 { AV_PIX_FMT_ABGR, { VK_FORMAT_A8B8G8R8_UNORM_PACK32 } },
131 { AV_PIX_FMT_BGRA, { VK_FORMAT_B8G8R8A8_UNORM } },
132 { AV_PIX_FMT_RGBA, { VK_FORMAT_R8G8B8A8_UNORM } },
133 { AV_PIX_FMT_RGB24, { VK_FORMAT_R8G8B8_UNORM } },
134 { AV_PIX_FMT_BGR24, { VK_FORMAT_B8G8R8_UNORM } },
135 { AV_PIX_FMT_RGB48, { VK_FORMAT_R16G16B16_UNORM } },
136 { AV_PIX_FMT_RGBA64, { VK_FORMAT_R16G16B16A16_UNORM } },
137 { AV_PIX_FMT_RGB565, { VK_FORMAT_R5G6B5_UNORM_PACK16 } },
138 { AV_PIX_FMT_BGR565, { VK_FORMAT_B5G6R5_UNORM_PACK16 } },
139 { AV_PIX_FMT_BGR0, { VK_FORMAT_B8G8R8A8_UNORM } },
140 { AV_PIX_FMT_0BGR, { VK_FORMAT_A8B8G8R8_UNORM_PACK32 } },
141 { AV_PIX_FMT_RGB0, { VK_FORMAT_R8G8B8A8_UNORM } },
143 { AV_PIX_FMT_GBRPF32, { VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32_SFLOAT } },
146 const VkFormat *av_vkfmt_from_pixfmt(enum AVPixelFormat p)
148 for (enum AVPixelFormat i = 0; i < FF_ARRAY_ELEMS(vk_pixfmt_map); i++)
149 if (vk_pixfmt_map[i].pixfmt == p)
150 return vk_pixfmt_map[i].vkfmts;
154 static int pixfmt_is_supported(AVVulkanDeviceContext *hwctx, enum AVPixelFormat p,
157 const VkFormat *fmt = av_vkfmt_from_pixfmt(p);
158 int planes = av_pix_fmt_count_planes(p);
163 for (int i = 0; i < planes; i++) {
164 VkFormatFeatureFlags flags;
165 VkFormatProperties2 prop = {
166 .sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2,
168 vkGetPhysicalDeviceFormatProperties2(hwctx->phys_dev, fmt[i], &prop);
169 flags = linear ? prop.formatProperties.linearTilingFeatures :
170 prop.formatProperties.optimalTilingFeatures;
171 if (!(flags & DEFAULT_USAGE_FLAGS))
178 enum VulkanExtensions {
179 EXT_EXTERNAL_DMABUF_MEMORY = 1ULL << 0, /* VK_EXT_external_memory_dma_buf */
180 EXT_DRM_MODIFIER_FLAGS = 1ULL << 1, /* VK_EXT_image_drm_format_modifier */
181 EXT_EXTERNAL_FD_MEMORY = 1ULL << 2, /* VK_KHR_external_memory_fd */
182 EXT_EXTERNAL_FD_SEM = 1ULL << 3, /* VK_KHR_external_semaphore_fd */
184 EXT_OPTIONAL = 1ULL << 62,
185 EXT_REQUIRED = 1ULL << 63,
188 typedef struct VulkanOptExtension {
191 } VulkanOptExtension;
193 static const VulkanOptExtension optional_instance_exts[] = {
194 { VK_KHR_SURFACE_EXTENSION_NAME, EXT_OPTIONAL },
197 static const VulkanOptExtension optional_device_exts[] = {
198 { VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME, EXT_EXTERNAL_FD_MEMORY, },
199 { VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME, EXT_EXTERNAL_DMABUF_MEMORY, },
200 { VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME, EXT_DRM_MODIFIER_FLAGS, },
201 { VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME, EXT_EXTERNAL_FD_SEM, },
204 /* Converts return values to strings */
205 static const char *vk_ret2str(VkResult res)
207 #define CASE(VAL) case VAL: return #VAL
213 CASE(VK_EVENT_RESET);
215 CASE(VK_ERROR_OUT_OF_HOST_MEMORY);
216 CASE(VK_ERROR_OUT_OF_DEVICE_MEMORY);
217 CASE(VK_ERROR_INITIALIZATION_FAILED);
218 CASE(VK_ERROR_DEVICE_LOST);
219 CASE(VK_ERROR_MEMORY_MAP_FAILED);
220 CASE(VK_ERROR_LAYER_NOT_PRESENT);
221 CASE(VK_ERROR_EXTENSION_NOT_PRESENT);
222 CASE(VK_ERROR_FEATURE_NOT_PRESENT);
223 CASE(VK_ERROR_INCOMPATIBLE_DRIVER);
224 CASE(VK_ERROR_TOO_MANY_OBJECTS);
225 CASE(VK_ERROR_FORMAT_NOT_SUPPORTED);
226 CASE(VK_ERROR_FRAGMENTED_POOL);
227 CASE(VK_ERROR_SURFACE_LOST_KHR);
228 CASE(VK_ERROR_NATIVE_WINDOW_IN_USE_KHR);
229 CASE(VK_SUBOPTIMAL_KHR);
230 CASE(VK_ERROR_OUT_OF_DATE_KHR);
231 CASE(VK_ERROR_INCOMPATIBLE_DISPLAY_KHR);
232 CASE(VK_ERROR_VALIDATION_FAILED_EXT);
233 CASE(VK_ERROR_INVALID_SHADER_NV);
234 CASE(VK_ERROR_OUT_OF_POOL_MEMORY);
235 CASE(VK_ERROR_INVALID_EXTERNAL_HANDLE);
236 CASE(VK_ERROR_NOT_PERMITTED_EXT);
237 CASE(VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT);
238 CASE(VK_ERROR_INVALID_DEVICE_ADDRESS_EXT);
239 CASE(VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT);
240 default: return "Unknown error";
245 static VkBool32 vk_dbg_callback(VkDebugUtilsMessageSeverityFlagBitsEXT severity,
246 VkDebugUtilsMessageTypeFlagsEXT messageType,
247 const VkDebugUtilsMessengerCallbackDataEXT *data,
251 AVHWDeviceContext *ctx = priv;
254 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT: l = AV_LOG_VERBOSE; break;
255 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT: l = AV_LOG_INFO; break;
256 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT: l = AV_LOG_WARNING; break;
257 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT: l = AV_LOG_ERROR; break;
258 default: l = AV_LOG_DEBUG; break;
261 av_log(ctx, l, "%s\n", data->pMessage);
262 for (int i = 0; i < data->cmdBufLabelCount; i++)
263 av_log(ctx, l, "\t%i: %s\n", i, data->pCmdBufLabels[i].pLabelName);
268 static int check_extensions(AVHWDeviceContext *ctx, int dev, AVDictionary *opts,
269 const char * const **dst, uint32_t *num, int debug)
272 const char **extension_names = NULL;
273 VulkanDevicePriv *p = ctx->internal->priv;
274 AVVulkanDeviceContext *hwctx = ctx->hwctx;
275 int err = 0, found, extensions_found = 0;
278 int optional_exts_num;
279 uint32_t sup_ext_count;
280 char *user_exts_str = NULL;
281 AVDictionaryEntry *user_exts;
282 VkExtensionProperties *sup_ext;
283 const VulkanOptExtension *optional_exts;
287 optional_exts = optional_instance_exts;
288 optional_exts_num = FF_ARRAY_ELEMS(optional_instance_exts);
289 user_exts = av_dict_get(opts, "instance_extensions", NULL, 0);
291 user_exts_str = av_strdup(user_exts->value);
292 if (!user_exts_str) {
293 err = AVERROR(ENOMEM);
297 vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, NULL);
298 sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
300 return AVERROR(ENOMEM);
301 vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, sup_ext);
304 optional_exts = optional_device_exts;
305 optional_exts_num = FF_ARRAY_ELEMS(optional_device_exts);
306 user_exts = av_dict_get(opts, "device_extensions", NULL, 0);
308 user_exts_str = av_strdup(user_exts->value);
309 if (!user_exts_str) {
310 err = AVERROR(ENOMEM);
314 vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
315 &sup_ext_count, NULL);
316 sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
318 return AVERROR(ENOMEM);
319 vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
320 &sup_ext_count, sup_ext);
323 for (int i = 0; i < optional_exts_num; i++) {
324 int req = optional_exts[i].flag & EXT_REQUIRED;
325 tstr = optional_exts[i].name;
328 for (int j = 0; j < sup_ext_count; j++) {
329 if (!strcmp(tstr, sup_ext[j].extensionName)) {
335 int lvl = req ? AV_LOG_ERROR : AV_LOG_VERBOSE;
336 av_log(ctx, lvl, "Extension \"%s\" not found!\n", tstr);
338 err = AVERROR(EINVAL);
344 p->extensions |= optional_exts[i].flag;
346 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
348 ADD_VAL_TO_LIST(extension_names, extensions_found, tstr);
352 tstr = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
354 for (int j = 0; j < sup_ext_count; j++) {
355 if (!strcmp(tstr, sup_ext[j].extensionName)) {
361 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
362 ADD_VAL_TO_LIST(extension_names, extensions_found, tstr);
364 av_log(ctx, AV_LOG_ERROR, "Debug extension \"%s\" not found!\n",
366 err = AVERROR(EINVAL);
372 char *save, *token = av_strtok(user_exts_str, "+", &save);
375 for (int j = 0; j < sup_ext_count; j++) {
376 if (!strcmp(token, sup_ext[j].extensionName)) {
382 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
383 ADD_VAL_TO_LIST(extension_names, extensions_found, token);
385 av_log(ctx, AV_LOG_ERROR, "%s extension \"%s\" not found!\n",
387 err = AVERROR(EINVAL);
390 token = av_strtok(NULL, "+", &save);
394 *dst = extension_names;
395 *num = extensions_found;
397 av_free(user_exts_str);
403 for (int i = 0; i < extensions_found; i++)
404 av_free((void *)extension_names[i]);
405 av_free(extension_names);
406 av_free(user_exts_str);
411 /* Creates a VkInstance */
412 static int create_instance(AVHWDeviceContext *ctx, AVDictionary *opts)
416 VulkanDevicePriv *p = ctx->internal->priv;
417 AVVulkanDeviceContext *hwctx = ctx->hwctx;
418 AVDictionaryEntry *debug_opt = av_dict_get(opts, "debug", NULL, 0);
419 const int debug_mode = debug_opt && strtol(debug_opt->value, NULL, 10);
420 VkApplicationInfo application_info = {
421 .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
422 .pEngineName = "libavutil",
423 .apiVersion = VK_API_VERSION_1_1,
424 .engineVersion = VK_MAKE_VERSION(LIBAVUTIL_VERSION_MAJOR,
425 LIBAVUTIL_VERSION_MINOR,
426 LIBAVUTIL_VERSION_MICRO),
428 VkInstanceCreateInfo inst_props = {
429 .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
430 .pApplicationInfo = &application_info,
433 /* Check for present/missing extensions */
434 err = check_extensions(ctx, 0, opts, &inst_props.ppEnabledExtensionNames,
435 &inst_props.enabledExtensionCount, debug_mode);
440 static const char *layers[] = { "VK_LAYER_LUNARG_standard_validation" };
441 inst_props.ppEnabledLayerNames = layers;
442 inst_props.enabledLayerCount = FF_ARRAY_ELEMS(layers);
445 /* Try to create the instance */
446 ret = vkCreateInstance(&inst_props, hwctx->alloc, &hwctx->inst);
448 /* Free used memory */
449 for (int i = 0; i < inst_props.enabledExtensionCount; i++)
450 av_free((void *)inst_props.ppEnabledExtensionNames[i]);
451 av_free((void *)inst_props.ppEnabledExtensionNames);
453 /* Check for errors */
454 if (ret != VK_SUCCESS) {
455 av_log(ctx, AV_LOG_ERROR, "Instance creation failure: %s\n",
457 return AVERROR_EXTERNAL;
461 VkDebugUtilsMessengerCreateInfoEXT dbg = {
462 .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT,
463 .messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT |
464 VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT |
465 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
466 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT,
467 .messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
468 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
469 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT,
470 .pfnUserCallback = vk_dbg_callback,
473 VK_LOAD_PFN(hwctx->inst, vkCreateDebugUtilsMessengerEXT);
475 pfn_vkCreateDebugUtilsMessengerEXT(hwctx->inst, &dbg,
476 hwctx->alloc, &p->debug_ctx);
482 typedef struct VulkanDeviceSelection {
483 uint8_t uuid[VK_UUID_SIZE]; /* Will use this first unless !has_uuid */
485 const char *name; /* Will use this second unless NULL */
486 uint32_t pci_device; /* Will use this third unless 0x0 */
487 uint32_t vendor_id; /* Last resort to find something deterministic */
488 int index; /* Finally fall back to index */
489 } VulkanDeviceSelection;
491 static const char *vk_dev_type(enum VkPhysicalDeviceType type)
494 case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: return "integrated";
495 case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: return "discrete";
496 case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: return "virtual";
497 case VK_PHYSICAL_DEVICE_TYPE_CPU: return "software";
498 default: return "unknown";
503 static int find_device(AVHWDeviceContext *ctx, VulkanDeviceSelection *select)
505 int err = 0, choice = -1;
508 VkPhysicalDevice *devices = NULL;
509 VkPhysicalDeviceIDProperties *idp = NULL;
510 VkPhysicalDeviceProperties2 *prop = NULL;
511 VulkanDevicePriv *p = ctx->internal->priv;
512 AVVulkanDeviceContext *hwctx = ctx->hwctx;
514 ret = vkEnumeratePhysicalDevices(hwctx->inst, &num, NULL);
515 if (ret != VK_SUCCESS || !num) {
516 av_log(ctx, AV_LOG_ERROR, "No devices found: %s!\n", vk_ret2str(ret));
517 return AVERROR(ENODEV);
520 devices = av_malloc_array(num, sizeof(VkPhysicalDevice));
522 return AVERROR(ENOMEM);
524 ret = vkEnumeratePhysicalDevices(hwctx->inst, &num, devices);
525 if (ret != VK_SUCCESS) {
526 av_log(ctx, AV_LOG_ERROR, "Failed enumerating devices: %s\n",
528 err = AVERROR(ENODEV);
532 prop = av_mallocz_array(num, sizeof(*prop));
534 err = AVERROR(ENOMEM);
538 idp = av_mallocz_array(num, sizeof(*idp));
540 err = AVERROR(ENOMEM);
544 av_log(ctx, AV_LOG_VERBOSE, "GPU listing:\n");
545 for (int i = 0; i < num; i++) {
546 idp[i].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES;
547 prop[i].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
548 prop[i].pNext = &idp[i];
550 vkGetPhysicalDeviceProperties2(devices[i], &prop[i]);
551 av_log(ctx, AV_LOG_VERBOSE, " %d: %s (%s) (0x%x)\n", i,
552 prop[i].properties.deviceName,
553 vk_dev_type(prop[i].properties.deviceType),
554 prop[i].properties.deviceID);
557 if (select->has_uuid) {
558 for (int i = 0; i < num; i++) {
559 if (!strncmp(idp[i].deviceUUID, select->uuid, VK_UUID_SIZE)) {
564 av_log(ctx, AV_LOG_ERROR, "Unable to find device by given UUID!\n");
565 err = AVERROR(ENODEV);
567 } else if (select->name) {
568 av_log(ctx, AV_LOG_VERBOSE, "Requested device: %s\n", select->name);
569 for (int i = 0; i < num; i++) {
570 if (strstr(prop[i].properties.deviceName, select->name)) {
575 av_log(ctx, AV_LOG_ERROR, "Unable to find device \"%s\"!\n",
577 err = AVERROR(ENODEV);
579 } else if (select->pci_device) {
580 av_log(ctx, AV_LOG_VERBOSE, "Requested device: 0x%x\n", select->pci_device);
581 for (int i = 0; i < num; i++) {
582 if (select->pci_device == prop[i].properties.deviceID) {
587 av_log(ctx, AV_LOG_ERROR, "Unable to find device with PCI ID 0x%x!\n",
589 err = AVERROR(EINVAL);
591 } else if (select->vendor_id) {
592 av_log(ctx, AV_LOG_VERBOSE, "Requested vendor: 0x%x\n", select->vendor_id);
593 for (int i = 0; i < num; i++) {
594 if (select->vendor_id == prop[i].properties.vendorID) {
599 av_log(ctx, AV_LOG_ERROR, "Unable to find device with Vendor ID 0x%x!\n",
601 err = AVERROR(ENODEV);
604 if (select->index < num) {
605 choice = select->index;
608 av_log(ctx, AV_LOG_ERROR, "Unable to find device with index %i!\n",
610 err = AVERROR(ENODEV);
616 p->dev_is_nvidia = (prop[choice].properties.vendorID == 0x10de);
617 hwctx->phys_dev = devices[choice];
626 static int search_queue_families(AVHWDeviceContext *ctx, VkDeviceCreateInfo *cd)
629 VkQueueFamilyProperties *qs = NULL;
630 AVVulkanDeviceContext *hwctx = ctx->hwctx;
631 int graph_index = -1, comp_index = -1, tx_index = -1;
632 VkDeviceQueueCreateInfo *pc = (VkDeviceQueueCreateInfo *)cd->pQueueCreateInfos;
634 /* First get the number of queue families */
635 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, NULL);
637 av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
638 return AVERROR_EXTERNAL;
641 /* Then allocate memory */
642 qs = av_malloc_array(num, sizeof(VkQueueFamilyProperties));
644 return AVERROR(ENOMEM);
646 /* Finally retrieve the queue families */
647 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, qs);
649 #define SEARCH_FLAGS(expr, out) \
650 for (int i = 0; i < num; i++) { \
651 const VkQueueFlagBits flags = qs[i].queueFlags; \
658 SEARCH_FLAGS(flags & VK_QUEUE_GRAPHICS_BIT, graph_index)
660 SEARCH_FLAGS((flags & VK_QUEUE_COMPUTE_BIT) && (i != graph_index),
663 SEARCH_FLAGS((flags & VK_QUEUE_TRANSFER_BIT) && (i != graph_index) &&
664 (i != comp_index), tx_index)
667 #define QF_FLAGS(flags) \
668 ((flags) & VK_QUEUE_GRAPHICS_BIT ) ? "(graphics) " : "", \
669 ((flags) & VK_QUEUE_COMPUTE_BIT ) ? "(compute) " : "", \
670 ((flags) & VK_QUEUE_TRANSFER_BIT ) ? "(transfer) " : "", \
671 ((flags) & VK_QUEUE_SPARSE_BINDING_BIT) ? "(sparse) " : ""
673 av_log(ctx, AV_LOG_VERBOSE, "Using queue family %i for graphics, "
674 "flags: %s%s%s%s\n", graph_index, QF_FLAGS(qs[graph_index].queueFlags));
676 hwctx->queue_family_index = graph_index;
677 hwctx->queue_family_tx_index = graph_index;
678 hwctx->queue_family_comp_index = graph_index;
680 pc[cd->queueCreateInfoCount++].queueFamilyIndex = graph_index;
682 if (comp_index != -1) {
683 av_log(ctx, AV_LOG_VERBOSE, "Using queue family %i for compute, "
684 "flags: %s%s%s%s\n", comp_index, QF_FLAGS(qs[comp_index].queueFlags));
685 hwctx->queue_family_tx_index = comp_index;
686 hwctx->queue_family_comp_index = comp_index;
687 pc[cd->queueCreateInfoCount++].queueFamilyIndex = comp_index;
690 if (tx_index != -1) {
691 av_log(ctx, AV_LOG_VERBOSE, "Using queue family %i for transfers, "
692 "flags: %s%s%s%s\n", tx_index, QF_FLAGS(qs[tx_index].queueFlags));
693 hwctx->queue_family_tx_index = tx_index;
694 pc[cd->queueCreateInfoCount++].queueFamilyIndex = tx_index;
704 static int create_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd,
705 int queue_family_index)
708 AVVulkanDeviceContext *hwctx = ctx->hwctx;
710 VkCommandPoolCreateInfo cqueue_create = {
711 .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
712 .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
713 .queueFamilyIndex = queue_family_index,
715 VkCommandBufferAllocateInfo cbuf_create = {
716 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
717 .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
718 .commandBufferCount = 1,
721 VkFenceCreateInfo fence_spawn = {
722 .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
725 ret = vkCreateFence(hwctx->act_dev, &fence_spawn,
726 hwctx->alloc, &cmd->fence);
727 if (ret != VK_SUCCESS) {
728 av_log(ctx, AV_LOG_ERROR, "Failed to create frame fence: %s\n",
730 return AVERROR_EXTERNAL;
733 ret = vkCreateCommandPool(hwctx->act_dev, &cqueue_create,
734 hwctx->alloc, &cmd->pool);
735 if (ret != VK_SUCCESS) {
736 av_log(ctx, AV_LOG_ERROR, "Command pool creation failure: %s\n",
738 return AVERROR_EXTERNAL;
741 cbuf_create.commandPool = cmd->pool;
743 ret = vkAllocateCommandBuffers(hwctx->act_dev, &cbuf_create, &cmd->buf);
744 if (ret != VK_SUCCESS) {
745 av_log(ctx, AV_LOG_ERROR, "Command buffer alloc failure: %s\n",
747 return AVERROR_EXTERNAL;
750 vkGetDeviceQueue(hwctx->act_dev, cqueue_create.queueFamilyIndex, 0,
756 static void free_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd)
758 AVVulkanDeviceContext *hwctx = ctx->hwctx;
761 vkDestroyFence(hwctx->act_dev, cmd->fence, hwctx->alloc);
763 vkFreeCommandBuffers(hwctx->act_dev, cmd->pool, 1, &cmd->buf);
765 vkDestroyCommandPool(hwctx->act_dev, cmd->pool, hwctx->alloc);
768 static void vulkan_device_free(AVHWDeviceContext *ctx)
770 VulkanDevicePriv *p = ctx->internal->priv;
771 AVVulkanDeviceContext *hwctx = ctx->hwctx;
773 free_exec_ctx(ctx, &p->cmd);
775 vkDestroyDevice(hwctx->act_dev, hwctx->alloc);
778 VK_LOAD_PFN(hwctx->inst, vkDestroyDebugUtilsMessengerEXT);
779 pfn_vkDestroyDebugUtilsMessengerEXT(hwctx->inst, p->debug_ctx,
783 vkDestroyInstance(hwctx->inst, hwctx->alloc);
786 static int vulkan_device_create_internal(AVHWDeviceContext *ctx,
787 VulkanDeviceSelection *dev_select,
788 AVDictionary *opts, int flags)
792 AVDictionaryEntry *opt_d;
793 VulkanDevicePriv *p = ctx->internal->priv;
794 AVVulkanDeviceContext *hwctx = ctx->hwctx;
795 VkDeviceQueueCreateInfo queue_create_info[3] = {
796 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
797 .pQueuePriorities = (float []){ 1.0f },
799 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
800 .pQueuePriorities = (float []){ 1.0f },
802 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
803 .pQueuePriorities = (float []){ 1.0f },
807 VkDeviceCreateInfo dev_info = {
808 .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
809 .pQueueCreateInfos = queue_create_info,
810 .queueCreateInfoCount = 0,
813 ctx->free = vulkan_device_free;
815 /* Create an instance if not given one */
816 if ((err = create_instance(ctx, opts)))
819 /* Find a device (if not given one) */
820 if ((err = find_device(ctx, dev_select)))
823 vkGetPhysicalDeviceProperties(hwctx->phys_dev, &p->props);
824 av_log(ctx, AV_LOG_VERBOSE, "Using device: %s\n", p->props.deviceName);
825 av_log(ctx, AV_LOG_VERBOSE, "Alignments:\n");
826 av_log(ctx, AV_LOG_VERBOSE, " optimalBufferCopyOffsetAlignment: %li\n",
827 p->props.limits.optimalBufferCopyOffsetAlignment);
828 av_log(ctx, AV_LOG_VERBOSE, " optimalBufferCopyRowPitchAlignment: %li\n",
829 p->props.limits.optimalBufferCopyRowPitchAlignment);
830 av_log(ctx, AV_LOG_VERBOSE, " minMemoryMapAlignment: %li\n",
831 p->props.limits.minMemoryMapAlignment);
833 /* Search queue family */
834 if ((err = search_queue_families(ctx, &dev_info)))
837 if ((err = check_extensions(ctx, 1, opts, &dev_info.ppEnabledExtensionNames,
838 &dev_info.enabledExtensionCount, 0)))
841 ret = vkCreateDevice(hwctx->phys_dev, &dev_info, hwctx->alloc,
844 for (int i = 0; i < dev_info.enabledExtensionCount; i++)
845 av_free((void *)dev_info.ppEnabledExtensionNames[i]);
846 av_free((void *)dev_info.ppEnabledExtensionNames);
848 if (ret != VK_SUCCESS) {
849 av_log(ctx, AV_LOG_ERROR, "Device creation failure: %s\n",
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);
864 static int vulkan_device_init(AVHWDeviceContext *ctx)
868 AVVulkanDeviceContext *hwctx = ctx->hwctx;
869 VulkanDevicePriv *p = ctx->internal->priv;
871 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &queue_num, NULL);
873 av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
874 return AVERROR_EXTERNAL;
877 #define CHECK_QUEUE(type, n) \
878 if (n >= queue_num) { \
879 av_log(ctx, AV_LOG_ERROR, "Invalid %s queue index %i (device has %i queues)!\n", \
880 type, n, queue_num); \
881 return AVERROR(EINVAL); \
884 CHECK_QUEUE("graphics", hwctx->queue_family_index)
885 CHECK_QUEUE("upload", hwctx->queue_family_tx_index)
886 CHECK_QUEUE("compute", hwctx->queue_family_comp_index)
890 /* Create exec context - if there's something invalid this will error out */
891 err = create_exec_ctx(ctx, &p->cmd, hwctx->queue_family_tx_index);
895 /* Get device capabilities */
896 vkGetPhysicalDeviceMemoryProperties(hwctx->phys_dev, &p->mprops);
901 static int vulkan_device_create(AVHWDeviceContext *ctx, const char *device,
902 AVDictionary *opts, int flags)
904 VulkanDeviceSelection dev_select = { 0 };
905 if (device && device[0]) {
907 dev_select.index = strtol(device, &end, 10);
909 dev_select.index = 0;
910 dev_select.name = device;
914 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
917 static int vulkan_device_derive(AVHWDeviceContext *ctx,
918 AVHWDeviceContext *src_ctx, int flags)
920 av_unused VulkanDeviceSelection dev_select = { 0 };
922 /* If there's only one device on the system, then even if its not covered
923 * by the following checks (e.g. non-PCIe ARM GPU), having an empty
924 * dev_select will mean it'll get picked. */
925 switch(src_ctx->type) {
928 case AV_HWDEVICE_TYPE_VAAPI: {
929 AVVAAPIDeviceContext *src_hwctx = src_ctx->hwctx;
931 const char *vendor = vaQueryVendorString(src_hwctx->display);
933 av_log(ctx, AV_LOG_ERROR, "Unable to get device info from VAAPI!\n");
934 return AVERROR_EXTERNAL;
937 if (strstr(vendor, "Intel"))
938 dev_select.vendor_id = 0x8086;
939 if (strstr(vendor, "AMD"))
940 dev_select.vendor_id = 0x1002;
942 return vulkan_device_create_internal(ctx, &dev_select, NULL, flags);
945 case AV_HWDEVICE_TYPE_DRM: {
946 AVDRMDeviceContext *src_hwctx = src_ctx->hwctx;
948 drmDevice *drm_dev_info;
949 int err = drmGetDevice(src_hwctx->fd, &drm_dev_info);
951 av_log(ctx, AV_LOG_ERROR, "Unable to get device info from DRM fd!\n");
952 return AVERROR_EXTERNAL;
955 if (drm_dev_info->bustype == DRM_BUS_PCI)
956 dev_select.pci_device = drm_dev_info->deviceinfo.pci->device_id;
958 drmFreeDevice(&drm_dev_info);
960 return vulkan_device_create_internal(ctx, &dev_select, NULL, flags);
964 case AV_HWDEVICE_TYPE_CUDA: {
965 AVHWDeviceContext *cuda_cu = src_ctx;
966 AVCUDADeviceContext *src_hwctx = src_ctx->hwctx;
967 AVCUDADeviceContextInternal *cu_internal = src_hwctx->internal;
968 CudaFunctions *cu = cu_internal->cuda_dl;
970 int ret = CHECK_CU(cu->cuDeviceGetUuid((CUuuid *)&dev_select.uuid,
971 cu_internal->cuda_device));
973 av_log(ctx, AV_LOG_ERROR, "Unable to get UUID from CUDA!\n");
974 return AVERROR_EXTERNAL;
977 dev_select.has_uuid = 1;
979 return vulkan_device_create_internal(ctx, &dev_select, NULL, flags);
983 return AVERROR(ENOSYS);
987 static int vulkan_frames_get_constraints(AVHWDeviceContext *ctx,
988 const void *hwconfig,
989 AVHWFramesConstraints *constraints)
992 AVVulkanDeviceContext *hwctx = ctx->hwctx;
993 VulkanDevicePriv *p = ctx->internal->priv;
995 for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
996 count += pixfmt_is_supported(hwctx, i, p->use_linear_images);
999 if (p->dev_is_nvidia)
1003 constraints->valid_sw_formats = av_malloc_array(count + 1,
1004 sizeof(enum AVPixelFormat));
1005 if (!constraints->valid_sw_formats)
1006 return AVERROR(ENOMEM);
1009 for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
1010 if (pixfmt_is_supported(hwctx, i, p->use_linear_images))
1011 constraints->valid_sw_formats[count++] = i;
1014 if (p->dev_is_nvidia)
1015 constraints->valid_sw_formats[count++] = AV_PIX_FMT_CUDA;
1017 constraints->valid_sw_formats[count++] = AV_PIX_FMT_NONE;
1019 constraints->min_width = 0;
1020 constraints->min_height = 0;
1021 constraints->max_width = p->props.limits.maxImageDimension2D;
1022 constraints->max_height = p->props.limits.maxImageDimension2D;
1024 constraints->valid_hw_formats = av_malloc_array(2, sizeof(enum AVPixelFormat));
1025 if (!constraints->valid_hw_formats)
1026 return AVERROR(ENOMEM);
1028 constraints->valid_hw_formats[0] = AV_PIX_FMT_VULKAN;
1029 constraints->valid_hw_formats[1] = AV_PIX_FMT_NONE;
1034 static int alloc_mem(AVHWDeviceContext *ctx, VkMemoryRequirements *req,
1035 VkMemoryPropertyFlagBits req_flags, void *alloc_extension,
1036 VkMemoryPropertyFlagBits *mem_flags, VkDeviceMemory *mem)
1040 VulkanDevicePriv *p = ctx->internal->priv;
1041 AVVulkanDeviceContext *dev_hwctx = ctx->hwctx;
1042 VkMemoryAllocateInfo alloc_info = {
1043 .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
1044 .pNext = alloc_extension,
1047 /* Align if we need to */
1048 if (req_flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)
1049 req->size = FFALIGN(req->size, p->props.limits.minMemoryMapAlignment);
1051 alloc_info.allocationSize = req->size;
1053 /* The vulkan spec requires memory types to be sorted in the "optimal"
1054 * order, so the first matching type we find will be the best/fastest one */
1055 for (int i = 0; i < p->mprops.memoryTypeCount; i++) {
1056 /* The memory type must be supported by the requirements (bitfield) */
1057 if (!(req->memoryTypeBits & (1 << i)))
1060 /* The memory type flags must include our properties */
1061 if ((p->mprops.memoryTypes[i].propertyFlags & req_flags) != req_flags)
1064 /* Found a suitable memory type */
1070 av_log(ctx, AV_LOG_ERROR, "No memory type found for flags 0x%x\n",
1072 return AVERROR(EINVAL);
1075 alloc_info.memoryTypeIndex = index;
1077 ret = vkAllocateMemory(dev_hwctx->act_dev, &alloc_info,
1078 dev_hwctx->alloc, mem);
1079 if (ret != VK_SUCCESS) {
1080 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory: %s\n",
1082 return AVERROR(ENOMEM);
1085 *mem_flags |= p->mprops.memoryTypes[index].propertyFlags;
1090 static void vulkan_free_internal(AVVkFrameInternal *internal)
1096 if (internal->cuda_fc_ref) {
1097 AVHWFramesContext *cuda_fc = (AVHWFramesContext *)internal->cuda_fc_ref->data;
1098 int planes = av_pix_fmt_count_planes(cuda_fc->sw_format);
1099 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
1100 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
1101 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
1102 CudaFunctions *cu = cu_internal->cuda_dl;
1104 if (internal->cu_sem)
1105 CHECK_CU(cu->cuDestroyExternalSemaphore(internal->cu_sem));
1107 for (int i = 0; i < planes; i++) {
1108 if (internal->cu_mma[i])
1109 CHECK_CU(cu->cuMipmappedArrayDestroy(internal->cu_mma[i]));
1110 if (internal->ext_mem[i])
1111 CHECK_CU(cu->cuDestroyExternalMemory(internal->ext_mem[i]));
1114 av_buffer_unref(&internal->cuda_fc_ref);
1121 static void vulkan_frame_free(void *opaque, uint8_t *data)
1123 AVVkFrame *f = (AVVkFrame *)data;
1124 AVHWFramesContext *hwfc = opaque;
1125 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1126 int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1128 vulkan_free_internal(f->internal);
1130 for (int i = 0; i < planes; i++) {
1131 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
1132 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
1135 vkDestroySemaphore(hwctx->act_dev, f->sem, hwctx->alloc);
1140 static int alloc_bind_mem(AVHWFramesContext *hwfc, AVVkFrame *f,
1141 void *alloc_pnext, size_t alloc_pnext_stride)
1145 AVHWDeviceContext *ctx = hwfc->device_ctx;
1146 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1147 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { { 0 } };
1149 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1151 for (int i = 0; i < planes; i++) {
1153 VkImageMemoryRequirementsInfo2 req_desc = {
1154 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
1157 VkMemoryDedicatedAllocateInfo ded_alloc = {
1158 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
1159 .pNext = (void *)(((uint8_t *)alloc_pnext) + i*alloc_pnext_stride),
1161 VkMemoryDedicatedRequirements ded_req = {
1162 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
1164 VkMemoryRequirements2 req = {
1165 .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
1169 vkGetImageMemoryRequirements2(hwctx->act_dev, &req_desc, &req);
1171 /* In case the implementation prefers/requires dedicated allocation */
1172 use_ded_mem = ded_req.prefersDedicatedAllocation |
1173 ded_req.requiresDedicatedAllocation;
1175 ded_alloc.image = f->img[i];
1177 /* Allocate memory */
1178 if ((err = alloc_mem(ctx, &req.memoryRequirements,
1179 f->tiling == VK_IMAGE_TILING_LINEAR ?
1180 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT :
1181 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1182 use_ded_mem ? &ded_alloc : (void *)ded_alloc.pNext,
1183 &f->flags, &f->mem[i])))
1186 f->size[i] = req.memoryRequirements.size;
1187 bind_info[i].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
1188 bind_info[i].image = f->img[i];
1189 bind_info[i].memory = f->mem[i];
1192 /* Bind the allocated memory to the images */
1193 ret = vkBindImageMemory2(hwctx->act_dev, planes, bind_info);
1194 if (ret != VK_SUCCESS) {
1195 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
1197 return AVERROR_EXTERNAL;
1205 PREP_MODE_RO_SHADER,
1208 static int prepare_frame(AVHWFramesContext *hwfc, VulkanExecCtx *ectx,
1209 AVVkFrame *frame, enum PrepMode pmode)
1212 VkImageLayout new_layout;
1213 VkAccessFlags new_access;
1214 AVHWDeviceContext *ctx = hwfc->device_ctx;
1215 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1216 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1218 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
1220 VkCommandBufferBeginInfo cmd_start = {
1221 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
1222 .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
1225 VkSubmitInfo s_info = {
1226 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
1227 .commandBufferCount = 1,
1228 .pCommandBuffers = &ectx->buf,
1230 .pSignalSemaphores = &frame->sem,
1231 .signalSemaphoreCount = 1,
1235 case PREP_MODE_WRITE:
1236 new_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
1237 new_access = VK_ACCESS_TRANSFER_WRITE_BIT;
1239 case PREP_MODE_RO_SHADER:
1240 new_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
1241 new_access = VK_ACCESS_TRANSFER_READ_BIT;
1245 ret = vkBeginCommandBuffer(ectx->buf, &cmd_start);
1246 if (ret != VK_SUCCESS)
1247 return AVERROR_EXTERNAL;
1249 /* Change the image layout to something more optimal for writes.
1250 * This also signals the newly created semaphore, making it usable
1251 * for synchronization */
1252 for (int i = 0; i < planes; i++) {
1253 img_bar[i].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1254 img_bar[i].srcAccessMask = 0x0;
1255 img_bar[i].dstAccessMask = new_access;
1256 img_bar[i].oldLayout = frame->layout[i];
1257 img_bar[i].newLayout = new_layout;
1258 img_bar[i].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1259 img_bar[i].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1260 img_bar[i].image = frame->img[i];
1261 img_bar[i].subresourceRange.levelCount = 1;
1262 img_bar[i].subresourceRange.layerCount = 1;
1263 img_bar[i].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1265 frame->layout[i] = img_bar[i].newLayout;
1266 frame->access[i] = img_bar[i].dstAccessMask;
1269 vkCmdPipelineBarrier(ectx->buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
1270 VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
1271 0, NULL, 0, NULL, planes, img_bar);
1273 ret = vkEndCommandBuffer(ectx->buf);
1274 if (ret != VK_SUCCESS)
1275 return AVERROR_EXTERNAL;
1277 ret = vkQueueSubmit(ectx->queue, 1, &s_info, ectx->fence);
1278 if (ret != VK_SUCCESS) {
1279 return AVERROR_EXTERNAL;
1281 vkWaitForFences(hwctx->act_dev, 1, &ectx->fence, VK_TRUE, UINT64_MAX);
1282 vkResetFences(hwctx->act_dev, 1, &ectx->fence);
1288 static int create_frame(AVHWFramesContext *hwfc, AVVkFrame **frame,
1289 VkImageTiling tiling, VkImageUsageFlagBits usage,
1294 AVHWDeviceContext *ctx = hwfc->device_ctx;
1295 VulkanDevicePriv *p = ctx->internal->priv;
1296 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1297 enum AVPixelFormat format = hwfc->sw_format;
1298 const VkFormat *img_fmts = av_vkfmt_from_pixfmt(format);
1299 const int planes = av_pix_fmt_count_planes(format);
1301 VkExportSemaphoreCreateInfo ext_sem_info = {
1302 .sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO,
1303 .handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
1306 VkSemaphoreCreateInfo sem_spawn = {
1307 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1308 .pNext = p->extensions & EXT_EXTERNAL_FD_SEM ? &ext_sem_info : NULL,
1311 AVVkFrame *f = av_vk_frame_alloc();
1313 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1314 return AVERROR(ENOMEM);
1317 /* Create the images */
1318 for (int i = 0; i < planes; i++) {
1319 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
1320 int w = hwfc->width;
1321 int h = hwfc->height;
1322 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
1323 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
1325 VkImageCreateInfo image_create_info = {
1326 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1327 .pNext = create_pnext,
1328 .imageType = VK_IMAGE_TYPE_2D,
1329 .format = img_fmts[i],
1330 .extent.width = p_w,
1331 .extent.height = p_h,
1335 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1337 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1339 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
1340 .samples = VK_SAMPLE_COUNT_1_BIT,
1343 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
1344 hwctx->alloc, &f->img[i]);
1345 if (ret != VK_SUCCESS) {
1346 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1348 err = AVERROR(EINVAL);
1352 f->layout[i] = image_create_info.initialLayout;
1356 /* Create semaphore */
1357 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1358 hwctx->alloc, &f->sem);
1359 if (ret != VK_SUCCESS) {
1360 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1362 return AVERROR_EXTERNAL;
1372 vulkan_frame_free(hwfc, (uint8_t *)f);
1376 /* Checks if an export flag is enabled, and if it is ORs it with *iexp */
1377 static void try_export_flags(AVHWFramesContext *hwfc,
1378 VkExternalMemoryHandleTypeFlags *comp_handle_types,
1379 VkExternalMemoryHandleTypeFlagBits *iexp,
1380 VkExternalMemoryHandleTypeFlagBits exp)
1383 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1384 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1385 VkExternalImageFormatProperties eprops = {
1386 .sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES_KHR,
1388 VkImageFormatProperties2 props = {
1389 .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,
1392 VkPhysicalDeviceExternalImageFormatInfo enext = {
1393 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
1396 VkPhysicalDeviceImageFormatInfo2 pinfo = {
1397 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1398 .pNext = !exp ? NULL : &enext,
1399 .format = av_vkfmt_from_pixfmt(hwfc->sw_format)[0],
1400 .type = VK_IMAGE_TYPE_2D,
1401 .tiling = hwctx->tiling,
1402 .usage = hwctx->usage,
1403 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1406 ret = vkGetPhysicalDeviceImageFormatProperties2(dev_hwctx->phys_dev,
1408 if (ret == VK_SUCCESS) {
1410 *comp_handle_types |= eprops.externalMemoryProperties.compatibleHandleTypes;
1414 static AVBufferRef *vulkan_pool_alloc(void *opaque, int size)
1418 AVBufferRef *avbuf = NULL;
1419 AVHWFramesContext *hwfc = opaque;
1420 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1421 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1422 VkExportMemoryAllocateInfo eminfo[AV_NUM_DATA_POINTERS];
1423 VkExternalMemoryHandleTypeFlags e = 0x0;
1425 VkExternalMemoryImageCreateInfo eiinfo = {
1426 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1427 .pNext = hwctx->create_pnext,
1430 if (p->extensions & EXT_EXTERNAL_FD_MEMORY)
1431 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1432 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT);
1434 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
1435 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1436 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
1438 for (int i = 0; i < av_pix_fmt_count_planes(hwfc->sw_format); i++) {
1439 eminfo[i].sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO;
1440 eminfo[i].pNext = hwctx->alloc_pnext[i];
1441 eminfo[i].handleTypes = e;
1444 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1445 eiinfo.handleTypes ? &eiinfo : NULL);
1449 err = alloc_bind_mem(hwfc, f, eminfo, sizeof(*eminfo));
1453 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_WRITE);
1457 avbuf = av_buffer_create((uint8_t *)f, sizeof(AVVkFrame),
1458 vulkan_frame_free, hwfc, 0);
1465 vulkan_frame_free(hwfc, (uint8_t *)f);
1469 static void vulkan_frames_uninit(AVHWFramesContext *hwfc)
1471 VulkanFramesPriv *fp = hwfc->internal->priv;
1473 free_exec_ctx(hwfc->device_ctx, &fp->cmd);
1476 static int vulkan_frames_init(AVHWFramesContext *hwfc)
1480 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1481 VulkanFramesPriv *fp = hwfc->internal->priv;
1482 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1483 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1488 /* Default pool flags */
1489 hwctx->tiling = hwctx->tiling ? hwctx->tiling : p->use_linear_images ?
1490 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1492 hwctx->usage |= DEFAULT_USAGE_FLAGS;
1494 err = create_exec_ctx(hwfc->device_ctx, &fp->cmd,
1495 dev_hwctx->queue_family_tx_index);
1499 /* Test to see if allocation will fail */
1500 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1501 hwctx->create_pnext);
1503 free_exec_ctx(hwfc->device_ctx, &p->cmd);
1507 vulkan_frame_free(hwfc, (uint8_t *)f);
1509 hwfc->internal->pool_internal = av_buffer_pool_init2(sizeof(AVVkFrame),
1510 hwfc, vulkan_pool_alloc,
1512 if (!hwfc->internal->pool_internal) {
1513 free_exec_ctx(hwfc->device_ctx, &p->cmd);
1514 return AVERROR(ENOMEM);
1520 static int vulkan_get_buffer(AVHWFramesContext *hwfc, AVFrame *frame)
1522 frame->buf[0] = av_buffer_pool_get(hwfc->pool);
1524 return AVERROR(ENOMEM);
1526 frame->data[0] = frame->buf[0]->data;
1527 frame->format = AV_PIX_FMT_VULKAN;
1528 frame->width = hwfc->width;
1529 frame->height = hwfc->height;
1534 static int vulkan_transfer_get_formats(AVHWFramesContext *hwfc,
1535 enum AVHWFrameTransferDirection dir,
1536 enum AVPixelFormat **formats)
1538 enum AVPixelFormat *fmts = av_malloc_array(2, sizeof(*fmts));
1540 return AVERROR(ENOMEM);
1542 fmts[0] = hwfc->sw_format;
1543 fmts[1] = AV_PIX_FMT_NONE;
1549 typedef struct VulkanMapping {
1554 static void vulkan_unmap_frame(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1556 VulkanMapping *map = hwmap->priv;
1557 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1558 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1560 /* Check if buffer needs flushing */
1561 if ((map->flags & AV_HWFRAME_MAP_WRITE) &&
1562 !(map->frame->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1564 VkMappedMemoryRange flush_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1566 for (int i = 0; i < planes; i++) {
1567 flush_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1568 flush_ranges[i].memory = map->frame->mem[i];
1569 flush_ranges[i].size = VK_WHOLE_SIZE;
1572 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, planes,
1574 if (ret != VK_SUCCESS) {
1575 av_log(hwfc, AV_LOG_ERROR, "Failed to flush memory: %s\n",
1580 for (int i = 0; i < planes; i++)
1581 vkUnmapMemory(hwctx->act_dev, map->frame->mem[i]);
1586 static int vulkan_map_frame_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
1587 const AVFrame *src, int flags)
1590 int err, mapped_mem_count = 0;
1591 AVVkFrame *f = (AVVkFrame *)src->data[0];
1592 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1593 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1595 VulkanMapping *map = av_mallocz(sizeof(VulkanMapping));
1597 return AVERROR(EINVAL);
1599 if (src->format != AV_PIX_FMT_VULKAN) {
1600 av_log(hwfc, AV_LOG_ERROR, "Cannot map from pixel format %s!\n",
1601 av_get_pix_fmt_name(src->format));
1602 err = AVERROR(EINVAL);
1606 if (!(f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ||
1607 !(f->tiling == VK_IMAGE_TILING_LINEAR)) {
1608 av_log(hwfc, AV_LOG_ERROR, "Unable to map frame, not host visible "
1610 err = AVERROR(EINVAL);
1614 dst->width = src->width;
1615 dst->height = src->height;
1617 for (int i = 0; i < planes; i++) {
1618 ret = vkMapMemory(hwctx->act_dev, f->mem[i], 0,
1619 VK_WHOLE_SIZE, 0, (void **)&dst->data[i]);
1620 if (ret != VK_SUCCESS) {
1621 av_log(hwfc, AV_LOG_ERROR, "Failed to map image memory: %s\n",
1623 err = AVERROR_EXTERNAL;
1629 /* Check if the memory contents matter */
1630 if (((flags & AV_HWFRAME_MAP_READ) || !(flags & AV_HWFRAME_MAP_OVERWRITE)) &&
1631 !(f->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1632 VkMappedMemoryRange map_mem_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1633 for (int i = 0; i < planes; i++) {
1634 map_mem_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1635 map_mem_ranges[i].size = VK_WHOLE_SIZE;
1636 map_mem_ranges[i].memory = f->mem[i];
1639 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, planes,
1641 if (ret != VK_SUCCESS) {
1642 av_log(hwfc, AV_LOG_ERROR, "Failed to invalidate memory: %s\n",
1644 err = AVERROR_EXTERNAL;
1649 for (int i = 0; i < planes; i++) {
1650 VkImageSubresource sub = {
1651 .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
1653 VkSubresourceLayout layout;
1654 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
1655 dst->linesize[i] = layout.rowPitch;
1661 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src,
1662 &vulkan_unmap_frame, map);
1669 for (int i = 0; i < mapped_mem_count; i++)
1670 vkUnmapMemory(hwctx->act_dev, f->mem[i]);
1677 static void vulkan_unmap_from(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1679 VulkanMapping *map = hwmap->priv;
1680 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1681 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1683 for (int i = 0; i < planes; i++) {
1684 vkDestroyImage(hwctx->act_dev, map->frame->img[i], hwctx->alloc);
1685 vkFreeMemory(hwctx->act_dev, map->frame->mem[i], hwctx->alloc);
1688 vkDestroySemaphore(hwctx->act_dev, map->frame->sem, hwctx->alloc);
1690 av_freep(&map->frame);
1693 static const struct {
1694 uint32_t drm_fourcc;
1696 } vulkan_drm_format_map[] = {
1697 { DRM_FORMAT_R8, VK_FORMAT_R8_UNORM },
1698 { DRM_FORMAT_R16, VK_FORMAT_R16_UNORM },
1699 { DRM_FORMAT_GR88, VK_FORMAT_R8G8_UNORM },
1700 { DRM_FORMAT_RG88, VK_FORMAT_R8G8_UNORM },
1701 { DRM_FORMAT_GR1616, VK_FORMAT_R16G16_UNORM },
1702 { DRM_FORMAT_RG1616, VK_FORMAT_R16G16_UNORM },
1703 { DRM_FORMAT_ARGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1704 { DRM_FORMAT_XRGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1705 { DRM_FORMAT_ABGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1706 { DRM_FORMAT_XBGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1709 static inline VkFormat drm_to_vulkan_fmt(uint32_t drm_fourcc)
1711 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
1712 if (vulkan_drm_format_map[i].drm_fourcc == drm_fourcc)
1713 return vulkan_drm_format_map[i].vk_format;
1714 return VK_FORMAT_UNDEFINED;
1717 static int vulkan_map_from_drm_frame_desc(AVHWFramesContext *hwfc, AVVkFrame **frame,
1718 AVDRMFrameDescriptor *desc)
1723 int bind_counts = 0;
1724 AVHWDeviceContext *ctx = hwfc->device_ctx;
1725 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1726 VulkanDevicePriv *p = ctx->internal->priv;
1727 const AVPixFmtDescriptor *fmt_desc = av_pix_fmt_desc_get(hwfc->sw_format);
1728 const int has_modifiers = p->extensions & EXT_DRM_MODIFIER_FLAGS;
1729 VkSubresourceLayout plane_data[AV_NUM_DATA_POINTERS] = { 0 };
1730 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { 0 };
1731 VkBindImagePlaneMemoryInfo plane_info[AV_NUM_DATA_POINTERS] = { 0 };
1732 VkExternalMemoryHandleTypeFlagBits htype = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
1733 VkSemaphoreCreateInfo sem_spawn = {
1734 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1737 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdPropertiesKHR);
1739 for (int i = 0; i < desc->nb_layers; i++) {
1740 if (drm_to_vulkan_fmt(desc->layers[i].format) == VK_FORMAT_UNDEFINED) {
1741 av_log(ctx, AV_LOG_ERROR, "Unsupported DMABUF layer format %#08x!\n",
1742 desc->layers[i].format);
1743 return AVERROR(EINVAL);
1747 if (!(f = av_vk_frame_alloc())) {
1748 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1749 err = AVERROR(ENOMEM);
1753 for (int i = 0; i < desc->nb_objects; i++) {
1754 VkMemoryFdPropertiesKHR fdmp = {
1755 .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,
1757 VkMemoryRequirements req = {
1758 .size = desc->objects[i].size,
1760 VkImportMemoryFdInfoKHR idesc = {
1761 .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
1762 .handleType = htype,
1763 .fd = dup(desc->objects[i].fd),
1766 ret = pfn_vkGetMemoryFdPropertiesKHR(hwctx->act_dev, htype,
1768 if (ret != VK_SUCCESS) {
1769 av_log(hwfc, AV_LOG_ERROR, "Failed to get FD properties: %s\n",
1771 err = AVERROR_EXTERNAL;
1776 req.memoryTypeBits = fdmp.memoryTypeBits;
1778 err = alloc_mem(ctx, &req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1779 &idesc, &f->flags, &f->mem[i]);
1785 f->size[i] = desc->objects[i].size;
1788 f->tiling = has_modifiers ? VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT :
1789 desc->objects[0].format_modifier == DRM_FORMAT_MOD_LINEAR ?
1790 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1792 for (int i = 0; i < desc->nb_layers; i++) {
1793 const int planes = desc->layers[i].nb_planes;
1794 const int signal_p = has_modifiers && (planes > 1);
1796 VkImageDrmFormatModifierExplicitCreateInfoEXT drm_info = {
1797 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
1798 .drmFormatModifier = desc->objects[0].format_modifier,
1799 .drmFormatModifierPlaneCount = planes,
1800 .pPlaneLayouts = (const VkSubresourceLayout *)&plane_data,
1803 VkExternalMemoryImageCreateInfo einfo = {
1804 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1805 .pNext = has_modifiers ? &drm_info : NULL,
1806 .handleTypes = htype,
1809 const int p_w = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, fmt_desc->log2_chroma_w) : hwfc->width;
1810 const int p_h = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, fmt_desc->log2_chroma_h) : hwfc->height;
1812 VkImageCreateInfo image_create_info = {
1813 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1815 .imageType = VK_IMAGE_TYPE_2D,
1816 .format = drm_to_vulkan_fmt(desc->layers[i].format),
1817 .extent.width = p_w,
1818 .extent.height = p_h,
1822 .flags = VK_IMAGE_CREATE_ALIAS_BIT |
1823 (signal_p ? VK_IMAGE_CREATE_DISJOINT_BIT : 0x0),
1824 .tiling = f->tiling,
1825 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, /* specs say so */
1826 .usage = DEFAULT_USAGE_FLAGS,
1827 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
1828 .samples = VK_SAMPLE_COUNT_1_BIT,
1831 for (int j = 0; j < planes; j++) {
1832 plane_data[j].offset = desc->layers[i].planes[j].offset;
1833 plane_data[j].rowPitch = desc->layers[i].planes[j].pitch;
1834 plane_data[j].size = 0; /* The specs say so for all 3 */
1835 plane_data[j].arrayPitch = 0;
1836 plane_data[j].depthPitch = 0;
1840 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
1841 hwctx->alloc, &f->img[i]);
1842 if (ret != VK_SUCCESS) {
1843 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1845 err = AVERROR(EINVAL);
1849 f->layout[i] = image_create_info.initialLayout;
1852 for (int j = 0; j < planes; j++) {
1853 VkImageAspectFlagBits aspect = j == 0 ? VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
1854 j == 1 ? VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT :
1855 VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT;
1857 plane_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO;
1858 plane_info[bind_counts].planeAspect = aspect;
1860 bind_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
1861 bind_info[bind_counts].pNext = signal_p ? &plane_info[bind_counts] : NULL;
1862 bind_info[bind_counts].image = f->img[i];
1863 bind_info[bind_counts].memory = f->mem[desc->layers[i].planes[j].object_index];
1864 bind_info[bind_counts].memoryOffset = desc->layers[i].planes[j].offset;
1869 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1870 hwctx->alloc, &f->sem);
1871 if (ret != VK_SUCCESS) {
1872 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1874 return AVERROR_EXTERNAL;
1877 /* We'd import a semaphore onto the one we created using
1878 * vkImportSemaphoreFdKHR but unfortunately neither DRM nor VAAPI
1879 * offer us anything we could import and sync with, so instead
1880 * just signal the semaphore we created. */
1882 /* Bind the allocated memory to the images */
1883 ret = vkBindImageMemory2(hwctx->act_dev, bind_counts, bind_info);
1884 if (ret != VK_SUCCESS) {
1885 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
1887 return AVERROR_EXTERNAL;
1890 /* NOTE: This is completely uneccesary and unneeded once we can import
1891 * semaphores from DRM. Otherwise we have to activate the semaphores.
1892 * We're reusing the exec context that's also used for uploads/downloads. */
1893 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_RO_SHADER);
1902 for (int i = 0; i < desc->nb_layers; i++)
1903 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
1904 for (int i = 0; i < desc->nb_objects; i++)
1905 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
1906 vkDestroySemaphore(hwctx->act_dev, f->sem, hwctx->alloc);
1913 static int vulkan_map_from_drm(AVHWFramesContext *hwfc, AVFrame *dst,
1914 const AVFrame *src, int flags)
1918 VulkanMapping *map = NULL;
1920 err = vulkan_map_from_drm_frame_desc(hwfc, &f,
1921 (AVDRMFrameDescriptor *)src->data[0]);
1925 /* The unmapping function will free this */
1926 dst->data[0] = (uint8_t *)f;
1927 dst->width = src->width;
1928 dst->height = src->height;
1930 map = av_mallocz(sizeof(VulkanMapping));
1937 err = ff_hwframe_map_create(dst->hw_frames_ctx, dst, src,
1938 &vulkan_unmap_from, map);
1942 av_log(hwfc, AV_LOG_DEBUG, "Mapped DRM object to Vulkan!\n");
1947 vulkan_frame_free(hwfc->device_ctx->hwctx, (uint8_t *)f);
1953 static int vulkan_map_from_vaapi(AVHWFramesContext *dst_fc,
1954 AVFrame *dst, const AVFrame *src,
1958 AVFrame *tmp = av_frame_alloc();
1959 AVHWFramesContext *vaapi_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
1960 AVVAAPIDeviceContext *vaapi_ctx = vaapi_fc->device_ctx->hwctx;
1961 VASurfaceID surface_id = (VASurfaceID)(uintptr_t)src->data[3];
1964 return AVERROR(ENOMEM);
1966 /* We have to sync since like the previous comment said, no semaphores */
1967 vaSyncSurface(vaapi_ctx->display, surface_id);
1969 tmp->format = AV_PIX_FMT_DRM_PRIME;
1971 err = av_hwframe_map(tmp, src, flags);
1975 err = vulkan_map_from_drm(dst_fc, dst, tmp, flags);
1979 err = ff_hwframe_map_replace(dst, src);
1982 av_frame_free(&tmp);
1989 static int vulkan_export_to_cuda(AVHWFramesContext *hwfc,
1990 AVBufferRef *cuda_hwfc,
1991 const AVFrame *frame)
1996 AVVkFrameInternal *dst_int;
1997 AVHWDeviceContext *ctx = hwfc->device_ctx;
1998 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1999 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2000 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2001 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2002 VK_LOAD_PFN(hwctx->inst, vkGetSemaphoreFdKHR);
2004 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)cuda_hwfc->data;
2005 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2006 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2007 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2008 CudaFunctions *cu = cu_internal->cuda_dl;
2009 CUarray_format cufmt = desc->comp[0].depth > 8 ? CU_AD_FORMAT_UNSIGNED_INT16 :
2010 CU_AD_FORMAT_UNSIGNED_INT8;
2012 dst_f = (AVVkFrame *)frame->data[0];
2014 dst_int = dst_f->internal;
2015 if (!dst_int || !dst_int->cuda_fc_ref) {
2016 VkSemaphoreGetFdInfoKHR sem_export = {
2017 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR,
2018 .semaphore = dst_f->sem,
2019 .handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
2021 CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC ext_sem_desc = {
2022 .type = CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD,
2025 if (!dst_f->internal)
2026 dst_f->internal = dst_int = av_mallocz(sizeof(*dst_f->internal));
2029 err = AVERROR(ENOMEM);
2033 dst_int->cuda_fc_ref = av_buffer_ref(cuda_hwfc);
2034 if (!dst_int->cuda_fc_ref) {
2035 err = AVERROR(ENOMEM);
2039 for (int i = 0; i < planes; i++) {
2040 CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC tex_desc = {
2043 .Width = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2045 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2049 .NumChannels = 1 + ((planes == 2) && i),
2054 CUDA_EXTERNAL_MEMORY_HANDLE_DESC ext_desc = {
2055 .type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD,
2056 .size = dst_f->size[i],
2058 VkMemoryGetFdInfoKHR export_info = {
2059 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2060 .memory = dst_f->mem[i],
2061 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR,
2064 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2065 &ext_desc.handle.fd);
2066 if (ret != VK_SUCCESS) {
2067 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2068 err = AVERROR_EXTERNAL;
2072 ret = CHECK_CU(cu->cuImportExternalMemory(&dst_int->ext_mem[i], &ext_desc));
2074 err = AVERROR_EXTERNAL;
2078 ret = CHECK_CU(cu->cuExternalMemoryGetMappedMipmappedArray(&dst_int->cu_mma[i],
2079 dst_int->ext_mem[i],
2082 err = AVERROR_EXTERNAL;
2086 ret = CHECK_CU(cu->cuMipmappedArrayGetLevel(&dst_int->cu_array[i],
2087 dst_int->cu_mma[i], 0));
2089 err = AVERROR_EXTERNAL;
2094 ret = pfn_vkGetSemaphoreFdKHR(hwctx->act_dev, &sem_export,
2095 &ext_sem_desc.handle.fd);
2096 if (ret != VK_SUCCESS) {
2097 av_log(ctx, AV_LOG_ERROR, "Failed to export semaphore: %s\n",
2099 err = AVERROR_EXTERNAL;
2103 ret = CHECK_CU(cu->cuImportExternalSemaphore(&dst_int->cu_sem,
2106 err = AVERROR_EXTERNAL;
2117 static int vulkan_transfer_data_from_cuda(AVHWFramesContext *hwfc,
2118 AVFrame *dst, const AVFrame *src)
2124 AVVkFrameInternal *dst_int;
2125 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2126 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2128 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2129 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2130 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2131 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2132 CudaFunctions *cu = cu_internal->cuda_dl;
2133 CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS s_w_par = { 0 };
2134 CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS s_s_par = { 0 };
2136 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2138 err = AVERROR_EXTERNAL;
2142 dst_f = (AVVkFrame *)dst->data[0];
2144 ret = vulkan_export_to_cuda(hwfc, src->hw_frames_ctx, dst);
2148 dst_int = dst_f->internal;
2150 ret = CHECK_CU(cu->cuWaitExternalSemaphoresAsync(&dst_int->cu_sem, &s_w_par,
2151 1, cuda_dev->stream));
2153 err = AVERROR_EXTERNAL;
2157 for (int i = 0; i < planes; i++) {
2158 CUDA_MEMCPY2D cpy = {
2159 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
2160 .srcDevice = (CUdeviceptr)src->data[i],
2161 .srcPitch = src->linesize[i],
2164 .dstMemoryType = CU_MEMORYTYPE_ARRAY,
2165 .dstArray = dst_int->cu_array[i],
2166 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2167 : hwfc->width) * desc->comp[i].step,
2168 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2172 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2174 err = AVERROR_EXTERNAL;
2179 ret = CHECK_CU(cu->cuSignalExternalSemaphoresAsync(&dst_int->cu_sem, &s_s_par,
2180 1, cuda_dev->stream));
2182 err = AVERROR_EXTERNAL;
2186 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2188 av_log(hwfc, AV_LOG_VERBOSE, "Transfered CUDA image to Vulkan!\n");
2193 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2194 vulkan_free_internal(dst_int);
2195 dst_f->internal = NULL;
2196 av_buffer_unref(&dst->buf[0]);
2201 static int vulkan_map_to(AVHWFramesContext *hwfc, AVFrame *dst,
2202 const AVFrame *src, int flags)
2204 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2206 switch (src->format) {
2209 case AV_PIX_FMT_VAAPI:
2210 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2211 return vulkan_map_from_vaapi(hwfc, dst, src, flags);
2213 case AV_PIX_FMT_DRM_PRIME:
2214 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2215 return vulkan_map_from_drm(hwfc, dst, src, flags);
2218 return AVERROR(ENOSYS);
2223 typedef struct VulkanDRMMapping {
2224 AVDRMFrameDescriptor drm_desc;
2228 static void vulkan_unmap_to_drm(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
2230 AVDRMFrameDescriptor *drm_desc = hwmap->priv;
2232 for (int i = 0; i < drm_desc->nb_objects; i++)
2233 close(drm_desc->objects[i].fd);
2238 static inline uint32_t vulkan_fmt_to_drm(VkFormat vkfmt)
2240 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
2241 if (vulkan_drm_format_map[i].vk_format == vkfmt)
2242 return vulkan_drm_format_map[i].drm_fourcc;
2243 return DRM_FORMAT_INVALID;
2246 static int vulkan_map_to_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2247 const AVFrame *src, int flags)
2251 AVVkFrame *f = (AVVkFrame *)src->data[0];
2252 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2253 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
2254 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2255 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2256 VkImageDrmFormatModifierPropertiesEXT drm_mod = {
2257 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT,
2260 AVDRMFrameDescriptor *drm_desc = av_mallocz(sizeof(*drm_desc));
2262 return AVERROR(ENOMEM);
2264 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src, &vulkan_unmap_to_drm, drm_desc);
2268 if (p->extensions & EXT_DRM_MODIFIER_FLAGS) {
2269 VK_LOAD_PFN(hwctx->inst, vkGetImageDrmFormatModifierPropertiesEXT);
2270 ret = pfn_vkGetImageDrmFormatModifierPropertiesEXT(hwctx->act_dev, f->img[0],
2272 if (ret != VK_SUCCESS) {
2273 av_log(hwfc, AV_LOG_ERROR, "Failed to retrieve DRM format modifier!\n");
2274 err = AVERROR_EXTERNAL;
2279 for (int i = 0; (i < planes) && (f->mem[i]); i++) {
2280 VkMemoryGetFdInfoKHR export_info = {
2281 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2282 .memory = f->mem[i],
2283 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,
2286 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2287 &drm_desc->objects[i].fd);
2288 if (ret != VK_SUCCESS) {
2289 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2290 err = AVERROR_EXTERNAL;
2294 drm_desc->nb_objects++;
2295 drm_desc->objects[i].size = f->size[i];
2296 drm_desc->objects[i].format_modifier = drm_mod.drmFormatModifier;
2299 drm_desc->nb_layers = planes;
2300 for (int i = 0; i < drm_desc->nb_layers; i++) {
2301 VkSubresourceLayout layout;
2302 VkImageSubresource sub = {
2303 .aspectMask = p->extensions & EXT_DRM_MODIFIER_FLAGS ?
2304 VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2305 VK_IMAGE_ASPECT_COLOR_BIT,
2307 VkFormat plane_vkfmt = av_vkfmt_from_pixfmt(hwfc->sw_format)[i];
2309 drm_desc->layers[i].format = vulkan_fmt_to_drm(plane_vkfmt);
2310 drm_desc->layers[i].nb_planes = 1;
2312 if (drm_desc->layers[i].format == DRM_FORMAT_INVALID) {
2313 av_log(hwfc, AV_LOG_ERROR, "Cannot map to DRM layer, unsupported!\n");
2314 err = AVERROR_PATCHWELCOME;
2318 drm_desc->layers[i].planes[0].object_index = FFMIN(i, drm_desc->nb_objects - 1);
2320 if (f->tiling != VK_IMAGE_TILING_OPTIMAL)
2323 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
2324 drm_desc->layers[i].planes[0].offset = layout.offset;
2325 drm_desc->layers[i].planes[0].pitch = layout.rowPitch;
2328 dst->width = src->width;
2329 dst->height = src->height;
2330 dst->data[0] = (uint8_t *)drm_desc;
2332 av_log(hwfc, AV_LOG_VERBOSE, "Mapped AVVkFrame to a DRM object!\n");
2342 static int vulkan_map_to_vaapi(AVHWFramesContext *hwfc, AVFrame *dst,
2343 const AVFrame *src, int flags)
2346 AVFrame *tmp = av_frame_alloc();
2348 return AVERROR(ENOMEM);
2350 tmp->format = AV_PIX_FMT_DRM_PRIME;
2352 err = vulkan_map_to_drm(hwfc, tmp, src, flags);
2356 err = av_hwframe_map(dst, tmp, flags);
2360 err = ff_hwframe_map_replace(dst, src);
2363 av_frame_free(&tmp);
2369 static int vulkan_map_from(AVHWFramesContext *hwfc, AVFrame *dst,
2370 const AVFrame *src, int flags)
2372 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2374 switch (dst->format) {
2376 case AV_PIX_FMT_DRM_PRIME:
2377 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2378 return vulkan_map_to_drm(hwfc, dst, src, flags);
2380 case AV_PIX_FMT_VAAPI:
2381 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2382 return vulkan_map_to_vaapi(hwfc, dst, src, flags);
2386 return vulkan_map_frame_to_mem(hwfc, dst, src, flags);
2390 typedef struct ImageBuffer {
2393 VkMemoryPropertyFlagBits flags;
2396 static void free_buf(AVHWDeviceContext *ctx, ImageBuffer *buf)
2398 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2402 vkDestroyBuffer(hwctx->act_dev, buf->buf, hwctx->alloc);
2403 vkFreeMemory(hwctx->act_dev, buf->mem, hwctx->alloc);
2406 static int create_buf(AVHWDeviceContext *ctx, ImageBuffer *buf, int height,
2407 int *stride, VkBufferUsageFlags usage,
2408 VkMemoryPropertyFlagBits flags, void *create_pnext,
2413 VkMemoryRequirements req;
2414 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2415 VulkanDevicePriv *p = ctx->internal->priv;
2417 VkBufferCreateInfo buf_spawn = {
2418 .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
2419 .pNext = create_pnext,
2421 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
2424 *stride = FFALIGN(*stride, p->props.limits.optimalBufferCopyRowPitchAlignment);
2425 buf_spawn.size = height*(*stride);
2427 ret = vkCreateBuffer(hwctx->act_dev, &buf_spawn, NULL, &buf->buf);
2428 if (ret != VK_SUCCESS) {
2429 av_log(ctx, AV_LOG_ERROR, "Failed to create buffer: %s\n",
2431 return AVERROR_EXTERNAL;
2434 vkGetBufferMemoryRequirements(hwctx->act_dev, buf->buf, &req);
2436 err = alloc_mem(ctx, &req, flags, alloc_pnext, &buf->flags, &buf->mem);
2440 ret = vkBindBufferMemory(hwctx->act_dev, buf->buf, buf->mem, 0);
2441 if (ret != VK_SUCCESS) {
2442 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory to buffer: %s\n",
2445 return AVERROR_EXTERNAL;
2451 static int map_buffers(AVHWDeviceContext *ctx, ImageBuffer *buf, uint8_t *mem[],
2452 int nb_buffers, int invalidate)
2455 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2456 VkMappedMemoryRange invalidate_ctx[AV_NUM_DATA_POINTERS];
2457 int invalidate_count = 0;
2459 for (int i = 0; i < nb_buffers; i++) {
2460 ret = vkMapMemory(hwctx->act_dev, buf[i].mem, 0,
2461 VK_WHOLE_SIZE, 0, (void **)&mem[i]);
2462 if (ret != VK_SUCCESS) {
2463 av_log(ctx, AV_LOG_ERROR, "Failed to map buffer memory: %s\n",
2465 return AVERROR_EXTERNAL;
2472 for (int i = 0; i < nb_buffers; i++) {
2473 const VkMappedMemoryRange ival_buf = {
2474 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2475 .memory = buf[i].mem,
2476 .size = VK_WHOLE_SIZE,
2478 if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2480 invalidate_ctx[invalidate_count++] = ival_buf;
2483 if (invalidate_count) {
2484 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, invalidate_count,
2486 if (ret != VK_SUCCESS)
2487 av_log(ctx, AV_LOG_WARNING, "Failed to invalidate memory: %s\n",
2494 static int unmap_buffers(AVHWDeviceContext *ctx, ImageBuffer *buf,
2495 int nb_buffers, int flush)
2499 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2500 VkMappedMemoryRange flush_ctx[AV_NUM_DATA_POINTERS];
2501 int flush_count = 0;
2504 for (int i = 0; i < nb_buffers; i++) {
2505 const VkMappedMemoryRange flush_buf = {
2506 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2507 .memory = buf[i].mem,
2508 .size = VK_WHOLE_SIZE,
2510 if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2512 flush_ctx[flush_count++] = flush_buf;
2517 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, flush_count, flush_ctx);
2518 if (ret != VK_SUCCESS) {
2519 av_log(ctx, AV_LOG_ERROR, "Failed to flush memory: %s\n",
2521 err = AVERROR_EXTERNAL; /* We still want to try to unmap them */
2525 for (int i = 0; i < nb_buffers; i++)
2526 vkUnmapMemory(hwctx->act_dev, buf[i].mem);
2531 static int transfer_image_buf(AVHWDeviceContext *ctx, AVVkFrame *frame,
2532 ImageBuffer *buffer, const int *buf_stride, int w,
2533 int h, enum AVPixelFormat pix_fmt, int to_buf)
2536 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2537 VulkanDevicePriv *s = ctx->internal->priv;
2540 VkPipelineStageFlagBits sem_wait_dst[AV_NUM_DATA_POINTERS];
2542 const int planes = av_pix_fmt_count_planes(pix_fmt);
2543 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2545 VkCommandBufferBeginInfo cmd_start = {
2546 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
2547 .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
2550 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
2552 VkSubmitInfo s_info = {
2553 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
2554 .commandBufferCount = 1,
2555 .pCommandBuffers = &s->cmd.buf,
2556 .pSignalSemaphores = &frame->sem,
2557 .pWaitSemaphores = &frame->sem,
2558 .pWaitDstStageMask = sem_wait_dst,
2559 .signalSemaphoreCount = 1,
2560 .waitSemaphoreCount = 1,
2563 ret = vkBeginCommandBuffer(s->cmd.buf, &cmd_start);
2564 if (ret != VK_SUCCESS) {
2565 av_log(ctx, AV_LOG_ERROR, "Unable to init command buffer: %s\n",
2567 return AVERROR_EXTERNAL;
2570 /* Change the image layout to something more optimal for transfers */
2571 for (int i = 0; i < planes; i++) {
2572 VkImageLayout new_layout = to_buf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL :
2573 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
2574 VkAccessFlags new_access = to_buf ? VK_ACCESS_TRANSFER_READ_BIT :
2575 VK_ACCESS_TRANSFER_WRITE_BIT;
2577 sem_wait_dst[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
2579 /* If the layout matches and we have read access skip the barrier */
2580 if ((frame->layout[i] == new_layout) && (frame->access[i] & new_access))
2583 img_bar[bar_num].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
2584 img_bar[bar_num].srcAccessMask = 0x0;
2585 img_bar[bar_num].dstAccessMask = new_access;
2586 img_bar[bar_num].oldLayout = frame->layout[i];
2587 img_bar[bar_num].newLayout = new_layout;
2588 img_bar[bar_num].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2589 img_bar[bar_num].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2590 img_bar[bar_num].image = frame->img[i];
2591 img_bar[bar_num].subresourceRange.levelCount = 1;
2592 img_bar[bar_num].subresourceRange.layerCount = 1;
2593 img_bar[bar_num].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2595 frame->layout[i] = img_bar[bar_num].newLayout;
2596 frame->access[i] = img_bar[bar_num].dstAccessMask;
2602 vkCmdPipelineBarrier(s->cmd.buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
2603 VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
2604 0, NULL, 0, NULL, bar_num, img_bar);
2606 /* Schedule a copy for each plane */
2607 for (int i = 0; i < planes; i++) {
2608 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
2609 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
2610 VkBufferImageCopy buf_reg = {
2612 /* Buffer stride isn't in bytes, it's in samples, the implementation
2613 * uses the image's VkFormat to know how many bytes per sample
2614 * the buffer has. So we have to convert by dividing. Stupid.
2615 * Won't work with YUVA or other planar formats with alpha. */
2616 .bufferRowLength = buf_stride[i] / desc->comp[i].step,
2617 .bufferImageHeight = p_h,
2618 .imageSubresource.layerCount = 1,
2619 .imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
2620 .imageOffset = { 0, 0, 0, },
2621 .imageExtent = { p_w, p_h, 1, },
2625 vkCmdCopyImageToBuffer(s->cmd.buf, frame->img[i], frame->layout[i],
2626 buffer[i].buf, 1, &buf_reg);
2628 vkCmdCopyBufferToImage(s->cmd.buf, buffer[i].buf, frame->img[i],
2629 frame->layout[i], 1, &buf_reg);
2632 ret = vkEndCommandBuffer(s->cmd.buf);
2633 if (ret != VK_SUCCESS) {
2634 av_log(ctx, AV_LOG_ERROR, "Unable to finish command buffer: %s\n",
2636 return AVERROR_EXTERNAL;
2639 /* Wait for the download/upload to finish if uploading, otherwise the
2640 * semaphore will take care of synchronization when uploading */
2641 ret = vkQueueSubmit(s->cmd.queue, 1, &s_info, s->cmd.fence);
2642 if (ret != VK_SUCCESS) {
2643 av_log(ctx, AV_LOG_ERROR, "Unable to submit command buffer: %s\n",
2645 return AVERROR_EXTERNAL;
2647 vkWaitForFences(hwctx->act_dev, 1, &s->cmd.fence, VK_TRUE, UINT64_MAX);
2648 vkResetFences(hwctx->act_dev, 1, &s->cmd.fence);
2654 /* Technically we can use VK_EXT_external_memory_host to upload and download,
2655 * however the alignment requirements make this unfeasible as both the pointer
2656 * and the size of each plane need to be aligned to the minimum alignment
2657 * requirement, which on all current implementations (anv, radv) is 4096.
2658 * If the requirement gets relaxed (unlikely) this can easily be implemented. */
2659 static int vulkan_transfer_data_from_mem(AVHWFramesContext *hwfc, AVFrame *dst,
2664 AVVkFrame *f = (AVVkFrame *)dst->data[0];
2665 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
2666 ImageBuffer buf[AV_NUM_DATA_POINTERS] = { { 0 } };
2667 const int planes = av_pix_fmt_count_planes(src->format);
2668 int log2_chroma = av_pix_fmt_desc_get(src->format)->log2_chroma_h;
2670 if ((src->format != AV_PIX_FMT_NONE && !av_vkfmt_from_pixfmt(src->format))) {
2671 av_log(hwfc, AV_LOG_ERROR, "Unsupported source pixel format!\n");
2672 return AVERROR(EINVAL);
2675 if (src->width > hwfc->width || src->height > hwfc->height)
2676 return AVERROR(EINVAL);
2678 /* For linear, host visiable images */
2679 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
2680 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
2681 AVFrame *map = av_frame_alloc();
2683 return AVERROR(ENOMEM);
2684 map->format = src->format;
2686 err = vulkan_map_frame_to_mem(hwfc, map, dst, AV_HWFRAME_MAP_WRITE);
2690 err = av_frame_copy(map, src);
2691 av_frame_free(&map);
2695 /* Create buffers */
2696 for (int i = 0; i < planes; i++) {
2697 int h = src->height;
2698 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
2700 tmp.linesize[i] = FFABS(src->linesize[i]);
2701 err = create_buf(dev_ctx, &buf[i], p_height,
2702 &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
2703 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
2708 /* Map, copy image to buffer, unmap */
2709 if ((err = map_buffers(dev_ctx, buf, tmp.data, planes, 0)))
2712 av_image_copy(tmp.data, tmp.linesize, (const uint8_t **)src->data,
2713 src->linesize, src->format, src->width, src->height);
2715 if ((err = unmap_buffers(dev_ctx, buf, planes, 1)))
2718 /* Copy buffers to image */
2719 err = transfer_image_buf(dev_ctx, f, buf, tmp.linesize,
2720 src->width, src->height, src->format, 0);
2723 for (int i = 0; i < planes; i++)
2724 free_buf(dev_ctx, &buf[i]);
2729 static int vulkan_transfer_data_to(AVHWFramesContext *hwfc, AVFrame *dst,
2732 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2734 switch (src->format) {
2736 case AV_PIX_FMT_CUDA:
2737 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
2738 (p->extensions & EXT_EXTERNAL_FD_SEM))
2739 return vulkan_transfer_data_from_cuda(hwfc, dst, src);
2742 if (src->hw_frames_ctx)
2743 return AVERROR(ENOSYS);
2745 return vulkan_transfer_data_from_mem(hwfc, dst, src);
2750 static int vulkan_transfer_data_to_cuda(AVHWFramesContext *hwfc, AVFrame *dst,
2757 AVVkFrameInternal *dst_int;
2758 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2759 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2761 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)dst->hw_frames_ctx->data;
2762 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2763 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2764 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2765 CudaFunctions *cu = cu_internal->cuda_dl;
2767 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2769 err = AVERROR_EXTERNAL;
2773 dst_f = (AVVkFrame *)src->data[0];
2775 err = vulkan_export_to_cuda(hwfc, dst->hw_frames_ctx, src);
2780 dst_int = dst_f->internal;
2782 for (int i = 0; i < planes; i++) {
2783 CUDA_MEMCPY2D cpy = {
2784 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
2785 .dstDevice = (CUdeviceptr)dst->data[i],
2786 .dstPitch = dst->linesize[i],
2789 .srcMemoryType = CU_MEMORYTYPE_ARRAY,
2790 .srcArray = dst_int->cu_array[i],
2791 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2792 : hwfc->width) * desc->comp[i].step,
2793 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2797 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2799 err = AVERROR_EXTERNAL;
2804 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2806 av_log(hwfc, AV_LOG_VERBOSE, "Transfered Vulkan image to CUDA!\n");
2811 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2812 vulkan_free_internal(dst_int);
2813 dst_f->internal = NULL;
2814 av_buffer_unref(&dst->buf[0]);
2819 static int vulkan_transfer_data_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
2824 AVVkFrame *f = (AVVkFrame *)src->data[0];
2825 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
2826 ImageBuffer buf[AV_NUM_DATA_POINTERS] = { { 0 } };
2827 const int planes = av_pix_fmt_count_planes(dst->format);
2828 int log2_chroma = av_pix_fmt_desc_get(dst->format)->log2_chroma_h;
2830 if (dst->width > hwfc->width || dst->height > hwfc->height)
2831 return AVERROR(EINVAL);
2833 /* For linear, host visiable images */
2834 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
2835 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
2836 AVFrame *map = av_frame_alloc();
2838 return AVERROR(ENOMEM);
2839 map->format = dst->format;
2841 err = vulkan_map_frame_to_mem(hwfc, map, src, AV_HWFRAME_MAP_READ);
2845 err = av_frame_copy(dst, map);
2846 av_frame_free(&map);
2850 /* Create buffers */
2851 for (int i = 0; i < planes; i++) {
2852 int h = dst->height;
2853 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
2855 tmp.linesize[i] = FFABS(dst->linesize[i]);
2856 err = create_buf(dev_ctx, &buf[i], p_height,
2857 &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_DST_BIT,
2858 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
2861 /* Copy image to buffer */
2862 if ((err = transfer_image_buf(dev_ctx, f, buf, tmp.linesize,
2863 dst->width, dst->height, dst->format, 1)))
2866 /* Map, copy buffer to frame, unmap */
2867 if ((err = map_buffers(dev_ctx, buf, tmp.data, planes, 1)))
2870 av_image_copy(dst->data, dst->linesize, (const uint8_t **)tmp.data,
2871 tmp.linesize, dst->format, dst->width, dst->height);
2873 err = unmap_buffers(dev_ctx, buf, planes, 0);
2876 for (int i = 0; i < planes; i++)
2877 free_buf(dev_ctx, &buf[i]);
2882 static int vulkan_transfer_data_from(AVHWFramesContext *hwfc, AVFrame *dst,
2885 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2887 switch (dst->format) {
2889 case AV_PIX_FMT_CUDA:
2890 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
2891 (p->extensions & EXT_EXTERNAL_FD_SEM))
2892 return vulkan_transfer_data_to_cuda(hwfc, dst, src);
2895 if (dst->hw_frames_ctx)
2896 return AVERROR(ENOSYS);
2898 return vulkan_transfer_data_to_mem(hwfc, dst, src);
2902 AVVkFrame *av_vk_frame_alloc(void)
2904 return av_mallocz(sizeof(AVVkFrame));
2907 const HWContextType ff_hwcontext_type_vulkan = {
2908 .type = AV_HWDEVICE_TYPE_VULKAN,
2911 .device_hwctx_size = sizeof(AVVulkanDeviceContext),
2912 .device_priv_size = sizeof(VulkanDevicePriv),
2913 .frames_hwctx_size = sizeof(AVVulkanFramesContext),
2914 .frames_priv_size = sizeof(VulkanFramesPriv),
2916 .device_init = &vulkan_device_init,
2917 .device_create = &vulkan_device_create,
2918 .device_derive = &vulkan_device_derive,
2920 .frames_get_constraints = &vulkan_frames_get_constraints,
2921 .frames_init = vulkan_frames_init,
2922 .frames_get_buffer = vulkan_get_buffer,
2923 .frames_uninit = vulkan_frames_uninit,
2925 .transfer_get_formats = vulkan_transfer_get_formats,
2926 .transfer_data_to = vulkan_transfer_data_to,
2927 .transfer_data_from = vulkan_transfer_data_from,
2929 .map_to = vulkan_map_to,
2930 .map_from = vulkan_map_from,
2932 .pix_fmts = (const enum AVPixelFormat []) {