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] = val; \
106 static const struct {
107 enum AVPixelFormat pixfmt;
108 const VkFormat vkfmts[3];
109 } vk_pixfmt_map[] = {
110 { AV_PIX_FMT_GRAY8, { VK_FORMAT_R8_UNORM } },
111 { AV_PIX_FMT_GRAY16, { VK_FORMAT_R16_UNORM } },
112 { AV_PIX_FMT_GRAYF32, { VK_FORMAT_R32_SFLOAT } },
114 { AV_PIX_FMT_NV12, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8G8_UNORM } },
115 { AV_PIX_FMT_P010, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16G16_UNORM } },
116 { AV_PIX_FMT_P016, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16G16_UNORM } },
118 { AV_PIX_FMT_YUV420P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
119 { AV_PIX_FMT_YUV422P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
120 { AV_PIX_FMT_YUV444P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
122 { AV_PIX_FMT_YUV420P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
123 { AV_PIX_FMT_YUV422P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
124 { AV_PIX_FMT_YUV444P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
126 { AV_PIX_FMT_ABGR, { VK_FORMAT_A8B8G8R8_UNORM_PACK32 } },
127 { AV_PIX_FMT_BGRA, { VK_FORMAT_B8G8R8A8_UNORM } },
128 { AV_PIX_FMT_RGBA, { VK_FORMAT_R8G8B8A8_UNORM } },
129 { AV_PIX_FMT_RGB24, { VK_FORMAT_R8G8B8_UNORM } },
130 { AV_PIX_FMT_BGR24, { VK_FORMAT_B8G8R8_UNORM } },
131 { AV_PIX_FMT_RGB48, { VK_FORMAT_R16G16B16_UNORM } },
132 { AV_PIX_FMT_RGBA64, { VK_FORMAT_R16G16B16A16_UNORM } },
133 { AV_PIX_FMT_RGB565, { VK_FORMAT_R5G6B5_UNORM_PACK16 } },
134 { AV_PIX_FMT_BGR565, { VK_FORMAT_B5G6R5_UNORM_PACK16 } },
135 { AV_PIX_FMT_BGR0, { VK_FORMAT_B8G8R8A8_UNORM } },
136 { AV_PIX_FMT_0BGR, { VK_FORMAT_A8B8G8R8_UNORM_PACK32 } },
137 { AV_PIX_FMT_RGB0, { VK_FORMAT_R8G8B8A8_UNORM } },
139 { AV_PIX_FMT_GBRPF32, { VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32_SFLOAT } },
142 const VkFormat *av_vkfmt_from_pixfmt(enum AVPixelFormat p)
144 for (enum AVPixelFormat i = 0; i < FF_ARRAY_ELEMS(vk_pixfmt_map); i++)
145 if (vk_pixfmt_map[i].pixfmt == p)
146 return vk_pixfmt_map[i].vkfmts;
150 static int pixfmt_is_supported(AVVulkanDeviceContext *hwctx, enum AVPixelFormat p,
153 const VkFormat *fmt = av_vkfmt_from_pixfmt(p);
154 int planes = av_pix_fmt_count_planes(p);
159 for (int i = 0; i < planes; i++) {
160 VkFormatFeatureFlags flags;
161 VkFormatProperties2 prop = {
162 .sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2,
164 vkGetPhysicalDeviceFormatProperties2(hwctx->phys_dev, fmt[i], &prop);
165 flags = linear ? prop.formatProperties.linearTilingFeatures :
166 prop.formatProperties.optimalTilingFeatures;
167 if (!(flags & DEFAULT_USAGE_FLAGS))
174 enum VulkanExtensions {
175 EXT_EXTERNAL_DMABUF_MEMORY = 1ULL << 0, /* VK_EXT_external_memory_dma_buf */
176 EXT_DRM_MODIFIER_FLAGS = 1ULL << 1, /* VK_EXT_image_drm_format_modifier */
177 EXT_EXTERNAL_FD_MEMORY = 1ULL << 2, /* VK_KHR_external_memory_fd */
178 EXT_EXTERNAL_FD_SEM = 1ULL << 3, /* VK_KHR_external_semaphore_fd */
180 EXT_OPTIONAL = 1ULL << 62,
181 EXT_REQUIRED = 1ULL << 63,
184 typedef struct VulkanOptExtension {
187 } VulkanOptExtension;
189 static const VulkanOptExtension optional_instance_exts[] = {
193 static const VulkanOptExtension optional_device_exts[] = {
194 { VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME, EXT_EXTERNAL_FD_MEMORY, },
195 { VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME, EXT_EXTERNAL_DMABUF_MEMORY, },
196 { VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME, EXT_DRM_MODIFIER_FLAGS, },
197 { VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME, EXT_EXTERNAL_FD_SEM, },
200 /* Converts return values to strings */
201 static const char *vk_ret2str(VkResult res)
203 #define CASE(VAL) case VAL: return #VAL
209 CASE(VK_EVENT_RESET);
211 CASE(VK_ERROR_OUT_OF_HOST_MEMORY);
212 CASE(VK_ERROR_OUT_OF_DEVICE_MEMORY);
213 CASE(VK_ERROR_INITIALIZATION_FAILED);
214 CASE(VK_ERROR_DEVICE_LOST);
215 CASE(VK_ERROR_MEMORY_MAP_FAILED);
216 CASE(VK_ERROR_LAYER_NOT_PRESENT);
217 CASE(VK_ERROR_EXTENSION_NOT_PRESENT);
218 CASE(VK_ERROR_FEATURE_NOT_PRESENT);
219 CASE(VK_ERROR_INCOMPATIBLE_DRIVER);
220 CASE(VK_ERROR_TOO_MANY_OBJECTS);
221 CASE(VK_ERROR_FORMAT_NOT_SUPPORTED);
222 CASE(VK_ERROR_FRAGMENTED_POOL);
223 CASE(VK_ERROR_SURFACE_LOST_KHR);
224 CASE(VK_ERROR_NATIVE_WINDOW_IN_USE_KHR);
225 CASE(VK_SUBOPTIMAL_KHR);
226 CASE(VK_ERROR_OUT_OF_DATE_KHR);
227 CASE(VK_ERROR_INCOMPATIBLE_DISPLAY_KHR);
228 CASE(VK_ERROR_VALIDATION_FAILED_EXT);
229 CASE(VK_ERROR_INVALID_SHADER_NV);
230 CASE(VK_ERROR_OUT_OF_POOL_MEMORY);
231 CASE(VK_ERROR_INVALID_EXTERNAL_HANDLE);
232 CASE(VK_ERROR_NOT_PERMITTED_EXT);
233 CASE(VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT);
234 CASE(VK_ERROR_INVALID_DEVICE_ADDRESS_EXT);
235 CASE(VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT);
236 default: return "Unknown error";
241 static VkBool32 vk_dbg_callback(VkDebugUtilsMessageSeverityFlagBitsEXT severity,
242 VkDebugUtilsMessageTypeFlagsEXT messageType,
243 const VkDebugUtilsMessengerCallbackDataEXT *data,
247 AVHWDeviceContext *ctx = priv;
250 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT: l = AV_LOG_VERBOSE; break;
251 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT: l = AV_LOG_INFO; break;
252 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT: l = AV_LOG_WARNING; break;
253 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT: l = AV_LOG_ERROR; break;
254 default: l = AV_LOG_DEBUG; break;
257 av_log(ctx, l, "%s\n", data->pMessage);
258 for (int i = 0; i < data->cmdBufLabelCount; i++)
259 av_log(ctx, l, "\t%i: %s\n", i, data->pCmdBufLabels[i].pLabelName);
264 static int check_extensions(AVHWDeviceContext *ctx, int dev,
265 const char * const **dst, uint32_t *num, int debug)
268 const char **extension_names = NULL;
269 VulkanDevicePriv *p = ctx->internal->priv;
270 AVVulkanDeviceContext *hwctx = ctx->hwctx;
271 int err = 0, found, extensions_found = 0;
274 int optional_exts_num;
275 uint32_t sup_ext_count;
276 VkExtensionProperties *sup_ext;
277 const VulkanOptExtension *optional_exts;
281 optional_exts = optional_instance_exts;
282 optional_exts_num = FF_ARRAY_ELEMS(optional_instance_exts);
283 vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, NULL);
284 sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
286 return AVERROR(ENOMEM);
287 vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, sup_ext);
290 optional_exts = optional_device_exts;
291 optional_exts_num = FF_ARRAY_ELEMS(optional_device_exts);
292 vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
293 &sup_ext_count, NULL);
294 sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
296 return AVERROR(ENOMEM);
297 vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
298 &sup_ext_count, sup_ext);
301 for (int i = 0; i < optional_exts_num; i++) {
302 int req = optional_exts[i].flag & EXT_REQUIRED;
303 tstr = optional_exts[i].name;
306 for (int j = 0; j < sup_ext_count; j++) {
307 if (!strcmp(tstr, sup_ext[j].extensionName)) {
313 int lvl = req ? AV_LOG_ERROR : AV_LOG_VERBOSE;
314 av_log(ctx, lvl, "Extension \"%s\" not found!\n", tstr);
316 err = AVERROR(EINVAL);
322 p->extensions |= optional_exts[i].flag;
324 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
326 ADD_VAL_TO_LIST(extension_names, extensions_found, tstr);
330 tstr = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
332 for (int j = 0; j < sup_ext_count; j++) {
333 if (!strcmp(tstr, sup_ext[j].extensionName)) {
339 ADD_VAL_TO_LIST(extension_names, extensions_found, tstr);
341 av_log(ctx, AV_LOG_ERROR, "Debug extension \"%s\" not found!\n",
343 err = AVERROR(EINVAL);
348 *dst = extension_names;
349 *num = extensions_found;
356 /* Creates a VkInstance */
357 static int create_instance(AVHWDeviceContext *ctx, AVDictionary *opts)
361 VulkanDevicePriv *p = ctx->internal->priv;
362 AVVulkanDeviceContext *hwctx = ctx->hwctx;
363 AVDictionaryEntry *debug_opt = av_dict_get(opts, "debug", NULL, 0);
364 const int debug_mode = debug_opt && strtol(debug_opt->value, NULL, 10);
365 VkApplicationInfo application_info = {
366 .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
367 .pEngineName = "libavutil",
368 .apiVersion = VK_API_VERSION_1_1,
369 .engineVersion = VK_MAKE_VERSION(LIBAVUTIL_VERSION_MAJOR,
370 LIBAVUTIL_VERSION_MINOR,
371 LIBAVUTIL_VERSION_MICRO),
373 VkInstanceCreateInfo inst_props = {
374 .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
375 .pApplicationInfo = &application_info,
378 /* Check for present/missing extensions */
379 err = check_extensions(ctx, 0, &inst_props.ppEnabledExtensionNames,
380 &inst_props.enabledExtensionCount, debug_mode);
385 static const char *layers[] = { "VK_LAYER_LUNARG_standard_validation" };
386 inst_props.ppEnabledLayerNames = layers;
387 inst_props.enabledLayerCount = FF_ARRAY_ELEMS(layers);
390 /* Try to create the instance */
391 ret = vkCreateInstance(&inst_props, hwctx->alloc, &hwctx->inst);
393 /* Free used memory */
394 av_free((void *)inst_props.ppEnabledExtensionNames);
396 /* Check for errors */
397 if (ret != VK_SUCCESS) {
398 av_log(ctx, AV_LOG_ERROR, "Instance creation failure: %s\n",
400 return AVERROR_EXTERNAL;
404 VkDebugUtilsMessengerCreateInfoEXT dbg = {
405 .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT,
406 .messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT |
407 VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT |
408 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
409 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT,
410 .messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
411 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
412 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT,
413 .pfnUserCallback = vk_dbg_callback,
416 VK_LOAD_PFN(hwctx->inst, vkCreateDebugUtilsMessengerEXT);
418 pfn_vkCreateDebugUtilsMessengerEXT(hwctx->inst, &dbg,
419 hwctx->alloc, &p->debug_ctx);
425 typedef struct VulkanDeviceSelection {
426 uint8_t uuid[VK_UUID_SIZE]; /* Will use this first unless !has_uuid */
428 const char *name; /* Will use this second unless NULL */
429 uint32_t pci_device; /* Will use this third unless 0x0 */
430 uint32_t vendor_id; /* Last resort to find something deterministic */
431 int index; /* Finally fall back to index */
432 } VulkanDeviceSelection;
434 static const char *vk_dev_type(enum VkPhysicalDeviceType type)
437 case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: return "integrated";
438 case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: return "discrete";
439 case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: return "virtual";
440 case VK_PHYSICAL_DEVICE_TYPE_CPU: return "software";
441 default: return "unknown";
446 static int find_device(AVHWDeviceContext *ctx, VulkanDeviceSelection *select)
448 int err = 0, choice = -1;
451 VkPhysicalDevice *devices = NULL;
452 VkPhysicalDeviceIDProperties *idp = NULL;
453 VkPhysicalDeviceProperties2 *prop = NULL;
454 VulkanDevicePriv *p = ctx->internal->priv;
455 AVVulkanDeviceContext *hwctx = ctx->hwctx;
457 ret = vkEnumeratePhysicalDevices(hwctx->inst, &num, NULL);
458 if (ret != VK_SUCCESS || !num) {
459 av_log(ctx, AV_LOG_ERROR, "No devices found: %s!\n", vk_ret2str(ret));
460 return AVERROR(ENODEV);
463 devices = av_malloc_array(num, sizeof(VkPhysicalDevice));
465 return AVERROR(ENOMEM);
467 ret = vkEnumeratePhysicalDevices(hwctx->inst, &num, devices);
468 if (ret != VK_SUCCESS) {
469 av_log(ctx, AV_LOG_ERROR, "Failed enumerating devices: %s\n",
471 err = AVERROR(ENODEV);
475 prop = av_mallocz_array(num, sizeof(*prop));
477 err = AVERROR(ENOMEM);
481 idp = av_mallocz_array(num, sizeof(*idp));
483 err = AVERROR(ENOMEM);
487 av_log(ctx, AV_LOG_VERBOSE, "GPU listing:\n");
488 for (int i = 0; i < num; i++) {
489 idp[i].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES;
490 prop[i].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
491 prop[i].pNext = &idp[i];
493 vkGetPhysicalDeviceProperties2(devices[i], &prop[i]);
494 av_log(ctx, AV_LOG_VERBOSE, " %d: %s (%s) (0x%x)\n", i,
495 prop[i].properties.deviceName,
496 vk_dev_type(prop[i].properties.deviceType),
497 prop[i].properties.deviceID);
500 if (select->has_uuid) {
501 for (int i = 0; i < num; i++) {
502 if (!strncmp(idp[i].deviceUUID, select->uuid, VK_UUID_SIZE)) {
507 av_log(ctx, AV_LOG_ERROR, "Unable to find device by given UUID!\n");
508 err = AVERROR(ENODEV);
510 } else if (select->name) {
511 av_log(ctx, AV_LOG_VERBOSE, "Requested device: %s\n", select->name);
512 for (int i = 0; i < num; i++) {
513 if (strstr(prop[i].properties.deviceName, select->name)) {
518 av_log(ctx, AV_LOG_ERROR, "Unable to find device \"%s\"!\n",
520 err = AVERROR(ENODEV);
522 } else if (select->pci_device) {
523 av_log(ctx, AV_LOG_VERBOSE, "Requested device: 0x%x\n", select->pci_device);
524 for (int i = 0; i < num; i++) {
525 if (select->pci_device == prop[i].properties.deviceID) {
530 av_log(ctx, AV_LOG_ERROR, "Unable to find device with PCI ID 0x%x!\n",
532 err = AVERROR(EINVAL);
534 } else if (select->vendor_id) {
535 av_log(ctx, AV_LOG_VERBOSE, "Requested vendor: 0x%x\n", select->vendor_id);
536 for (int i = 0; i < num; i++) {
537 if (select->vendor_id == prop[i].properties.vendorID) {
542 av_log(ctx, AV_LOG_ERROR, "Unable to find device with Vendor ID 0x%x!\n",
544 err = AVERROR(ENODEV);
547 if (select->index < num) {
548 choice = select->index;
551 av_log(ctx, AV_LOG_ERROR, "Unable to find device with index %i!\n",
553 err = AVERROR(ENODEV);
559 p->dev_is_nvidia = (prop[choice].properties.vendorID == 0x10de);
560 hwctx->phys_dev = devices[choice];
569 static int search_queue_families(AVHWDeviceContext *ctx, VkDeviceCreateInfo *cd)
572 VkQueueFamilyProperties *qs = NULL;
573 AVVulkanDeviceContext *hwctx = ctx->hwctx;
574 int graph_index = -1, comp_index = -1, tx_index = -1;
575 VkDeviceQueueCreateInfo *pc = (VkDeviceQueueCreateInfo *)cd->pQueueCreateInfos;
577 /* First get the number of queue families */
578 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, NULL);
580 av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
581 return AVERROR_EXTERNAL;
584 /* Then allocate memory */
585 qs = av_malloc_array(num, sizeof(VkQueueFamilyProperties));
587 return AVERROR(ENOMEM);
589 /* Finally retrieve the queue families */
590 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, qs);
592 #define SEARCH_FLAGS(expr, out) \
593 for (int i = 0; i < num; i++) { \
594 const VkQueueFlagBits flags = qs[i].queueFlags; \
601 SEARCH_FLAGS(flags & VK_QUEUE_GRAPHICS_BIT, graph_index)
603 SEARCH_FLAGS((flags & VK_QUEUE_COMPUTE_BIT) && (i != graph_index),
606 SEARCH_FLAGS((flags & VK_QUEUE_TRANSFER_BIT) && (i != graph_index) &&
607 (i != comp_index), tx_index)
610 #define QF_FLAGS(flags) \
611 ((flags) & VK_QUEUE_GRAPHICS_BIT ) ? "(graphics) " : "", \
612 ((flags) & VK_QUEUE_COMPUTE_BIT ) ? "(compute) " : "", \
613 ((flags) & VK_QUEUE_TRANSFER_BIT ) ? "(transfer) " : "", \
614 ((flags) & VK_QUEUE_SPARSE_BINDING_BIT) ? "(sparse) " : ""
616 av_log(ctx, AV_LOG_VERBOSE, "Using queue family %i for graphics, "
617 "flags: %s%s%s%s\n", graph_index, QF_FLAGS(qs[graph_index].queueFlags));
619 hwctx->queue_family_index = graph_index;
620 hwctx->queue_family_tx_index = graph_index;
621 hwctx->queue_family_comp_index = graph_index;
623 pc[cd->queueCreateInfoCount++].queueFamilyIndex = graph_index;
625 if (comp_index != -1) {
626 av_log(ctx, AV_LOG_VERBOSE, "Using queue family %i for compute, "
627 "flags: %s%s%s%s\n", comp_index, QF_FLAGS(qs[comp_index].queueFlags));
628 hwctx->queue_family_tx_index = comp_index;
629 hwctx->queue_family_comp_index = comp_index;
630 pc[cd->queueCreateInfoCount++].queueFamilyIndex = comp_index;
633 if (tx_index != -1) {
634 av_log(ctx, AV_LOG_VERBOSE, "Using queue family %i for transfers, "
635 "flags: %s%s%s%s\n", tx_index, QF_FLAGS(qs[tx_index].queueFlags));
636 hwctx->queue_family_tx_index = tx_index;
637 pc[cd->queueCreateInfoCount++].queueFamilyIndex = tx_index;
647 static int create_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd,
648 int queue_family_index)
651 AVVulkanDeviceContext *hwctx = ctx->hwctx;
653 VkCommandPoolCreateInfo cqueue_create = {
654 .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
655 .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
656 .queueFamilyIndex = queue_family_index,
658 VkCommandBufferAllocateInfo cbuf_create = {
659 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
660 .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
661 .commandBufferCount = 1,
664 VkFenceCreateInfo fence_spawn = {
665 .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
668 ret = vkCreateFence(hwctx->act_dev, &fence_spawn,
669 hwctx->alloc, &cmd->fence);
670 if (ret != VK_SUCCESS) {
671 av_log(ctx, AV_LOG_ERROR, "Failed to create frame fence: %s\n",
673 return AVERROR_EXTERNAL;
676 ret = vkCreateCommandPool(hwctx->act_dev, &cqueue_create,
677 hwctx->alloc, &cmd->pool);
678 if (ret != VK_SUCCESS) {
679 av_log(ctx, AV_LOG_ERROR, "Command pool creation failure: %s\n",
681 return AVERROR_EXTERNAL;
684 cbuf_create.commandPool = cmd->pool;
686 ret = vkAllocateCommandBuffers(hwctx->act_dev, &cbuf_create, &cmd->buf);
687 if (ret != VK_SUCCESS) {
688 av_log(ctx, AV_LOG_ERROR, "Command buffer alloc failure: %s\n",
690 return AVERROR_EXTERNAL;
693 vkGetDeviceQueue(hwctx->act_dev, cqueue_create.queueFamilyIndex, 0,
699 static void free_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd)
701 AVVulkanDeviceContext *hwctx = ctx->hwctx;
704 vkDestroyFence(hwctx->act_dev, cmd->fence, hwctx->alloc);
706 vkFreeCommandBuffers(hwctx->act_dev, cmd->pool, 1, &cmd->buf);
708 vkDestroyCommandPool(hwctx->act_dev, cmd->pool, hwctx->alloc);
711 static void vulkan_device_free(AVHWDeviceContext *ctx)
713 VulkanDevicePriv *p = ctx->internal->priv;
714 AVVulkanDeviceContext *hwctx = ctx->hwctx;
716 free_exec_ctx(ctx, &p->cmd);
718 vkDestroyDevice(hwctx->act_dev, hwctx->alloc);
721 VK_LOAD_PFN(hwctx->inst, vkDestroyDebugUtilsMessengerEXT);
722 pfn_vkDestroyDebugUtilsMessengerEXT(hwctx->inst, p->debug_ctx,
726 vkDestroyInstance(hwctx->inst, hwctx->alloc);
729 static int vulkan_device_create_internal(AVHWDeviceContext *ctx,
730 VulkanDeviceSelection *dev_select,
731 AVDictionary *opts, int flags)
735 AVDictionaryEntry *opt_d;
736 VulkanDevicePriv *p = ctx->internal->priv;
737 AVVulkanDeviceContext *hwctx = ctx->hwctx;
738 VkDeviceQueueCreateInfo queue_create_info[3] = {
739 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
740 .pQueuePriorities = (float []){ 1.0f },
742 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
743 .pQueuePriorities = (float []){ 1.0f },
745 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
746 .pQueuePriorities = (float []){ 1.0f },
750 VkDeviceCreateInfo dev_info = {
751 .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
752 .pQueueCreateInfos = queue_create_info,
753 .queueCreateInfoCount = 0,
756 ctx->free = vulkan_device_free;
758 /* Create an instance if not given one */
759 if ((err = create_instance(ctx, opts)))
762 /* Find a device (if not given one) */
763 if ((err = find_device(ctx, dev_select)))
766 vkGetPhysicalDeviceProperties(hwctx->phys_dev, &p->props);
767 av_log(ctx, AV_LOG_VERBOSE, "Using device: %s\n", p->props.deviceName);
768 av_log(ctx, AV_LOG_VERBOSE, "Alignments:\n");
769 av_log(ctx, AV_LOG_VERBOSE, " optimalBufferCopyOffsetAlignment: %li\n",
770 p->props.limits.optimalBufferCopyOffsetAlignment);
771 av_log(ctx, AV_LOG_VERBOSE, " optimalBufferCopyRowPitchAlignment: %li\n",
772 p->props.limits.optimalBufferCopyRowPitchAlignment);
773 av_log(ctx, AV_LOG_VERBOSE, " minMemoryMapAlignment: %li\n",
774 p->props.limits.minMemoryMapAlignment);
776 /* Search queue family */
777 if ((err = search_queue_families(ctx, &dev_info)))
780 if ((err = check_extensions(ctx, 1, &dev_info.ppEnabledExtensionNames,
781 &dev_info.enabledExtensionCount, 0)))
784 ret = vkCreateDevice(hwctx->phys_dev, &dev_info, hwctx->alloc,
787 av_free((void *)dev_info.ppEnabledExtensionNames);
789 if (ret != VK_SUCCESS) {
790 av_log(ctx, AV_LOG_ERROR, "Device creation failure: %s\n",
792 err = AVERROR_EXTERNAL;
796 /* Tiled images setting, use them by default */
797 opt_d = av_dict_get(opts, "linear_images", NULL, 0);
799 p->use_linear_images = strtol(opt_d->value, NULL, 10);
805 static int vulkan_device_init(AVHWDeviceContext *ctx)
809 AVVulkanDeviceContext *hwctx = ctx->hwctx;
810 VulkanDevicePriv *p = ctx->internal->priv;
812 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &queue_num, NULL);
814 av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
815 return AVERROR_EXTERNAL;
818 #define CHECK_QUEUE(type, n) \
819 if (n >= queue_num) { \
820 av_log(ctx, AV_LOG_ERROR, "Invalid %s queue index %i (device has %i queues)!\n", \
821 type, n, queue_num); \
822 return AVERROR(EINVAL); \
825 CHECK_QUEUE("graphics", hwctx->queue_family_index)
826 CHECK_QUEUE("upload", hwctx->queue_family_tx_index)
827 CHECK_QUEUE("compute", hwctx->queue_family_comp_index)
831 /* Create exec context - if there's something invalid this will error out */
832 err = create_exec_ctx(ctx, &p->cmd, hwctx->queue_family_tx_index);
836 /* Get device capabilities */
837 vkGetPhysicalDeviceMemoryProperties(hwctx->phys_dev, &p->mprops);
842 static int vulkan_device_create(AVHWDeviceContext *ctx, const char *device,
843 AVDictionary *opts, int flags)
845 VulkanDeviceSelection dev_select = { 0 };
846 if (device && device[0]) {
848 dev_select.index = strtol(device, &end, 10);
850 dev_select.index = 0;
851 dev_select.name = device;
855 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
858 static int vulkan_device_derive(AVHWDeviceContext *ctx,
859 AVHWDeviceContext *src_ctx, int flags)
861 av_unused VulkanDeviceSelection dev_select = { 0 };
863 /* If there's only one device on the system, then even if its not covered
864 * by the following checks (e.g. non-PCIe ARM GPU), having an empty
865 * dev_select will mean it'll get picked. */
866 switch(src_ctx->type) {
869 case AV_HWDEVICE_TYPE_VAAPI: {
870 AVVAAPIDeviceContext *src_hwctx = src_ctx->hwctx;
872 const char *vendor = vaQueryVendorString(src_hwctx->display);
874 av_log(ctx, AV_LOG_ERROR, "Unable to get device info from VAAPI!\n");
875 return AVERROR_EXTERNAL;
878 if (strstr(vendor, "Intel"))
879 dev_select.vendor_id = 0x8086;
880 if (strstr(vendor, "AMD"))
881 dev_select.vendor_id = 0x1002;
883 return vulkan_device_create_internal(ctx, &dev_select, NULL, flags);
886 case AV_HWDEVICE_TYPE_DRM: {
887 AVDRMDeviceContext *src_hwctx = src_ctx->hwctx;
889 drmDevice *drm_dev_info;
890 int err = drmGetDevice(src_hwctx->fd, &drm_dev_info);
892 av_log(ctx, AV_LOG_ERROR, "Unable to get device info from DRM fd!\n");
893 return AVERROR_EXTERNAL;
896 if (drm_dev_info->bustype == DRM_BUS_PCI)
897 dev_select.pci_device = drm_dev_info->deviceinfo.pci->device_id;
899 drmFreeDevice(&drm_dev_info);
901 return vulkan_device_create_internal(ctx, &dev_select, NULL, flags);
905 case AV_HWDEVICE_TYPE_CUDA: {
906 AVHWDeviceContext *cuda_cu = src_ctx;
907 AVCUDADeviceContext *src_hwctx = src_ctx->hwctx;
908 AVCUDADeviceContextInternal *cu_internal = src_hwctx->internal;
909 CudaFunctions *cu = cu_internal->cuda_dl;
911 int ret = CHECK_CU(cu->cuDeviceGetUuid((CUuuid *)&dev_select.uuid,
912 cu_internal->cuda_device));
914 av_log(ctx, AV_LOG_ERROR, "Unable to get UUID from CUDA!\n");
915 return AVERROR_EXTERNAL;
918 dev_select.has_uuid = 1;
920 return vulkan_device_create_internal(ctx, &dev_select, NULL, flags);
924 return AVERROR(ENOSYS);
928 static int vulkan_frames_get_constraints(AVHWDeviceContext *ctx,
929 const void *hwconfig,
930 AVHWFramesConstraints *constraints)
933 AVVulkanDeviceContext *hwctx = ctx->hwctx;
934 VulkanDevicePriv *p = ctx->internal->priv;
936 for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
937 count += pixfmt_is_supported(hwctx, i, p->use_linear_images);
940 if (p->dev_is_nvidia)
944 constraints->valid_sw_formats = av_malloc_array(count + 1,
945 sizeof(enum AVPixelFormat));
946 if (!constraints->valid_sw_formats)
947 return AVERROR(ENOMEM);
950 for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
951 if (pixfmt_is_supported(hwctx, i, p->use_linear_images))
952 constraints->valid_sw_formats[count++] = i;
955 if (p->dev_is_nvidia)
956 constraints->valid_sw_formats[count++] = AV_PIX_FMT_CUDA;
958 constraints->valid_sw_formats[count++] = AV_PIX_FMT_NONE;
960 constraints->min_width = 0;
961 constraints->min_height = 0;
962 constraints->max_width = p->props.limits.maxImageDimension2D;
963 constraints->max_height = p->props.limits.maxImageDimension2D;
965 constraints->valid_hw_formats = av_malloc_array(2, sizeof(enum AVPixelFormat));
966 if (!constraints->valid_hw_formats)
967 return AVERROR(ENOMEM);
969 constraints->valid_hw_formats[0] = AV_PIX_FMT_VULKAN;
970 constraints->valid_hw_formats[1] = AV_PIX_FMT_NONE;
975 static int alloc_mem(AVHWDeviceContext *ctx, VkMemoryRequirements *req,
976 VkMemoryPropertyFlagBits req_flags, void *alloc_extension,
977 VkMemoryPropertyFlagBits *mem_flags, VkDeviceMemory *mem)
981 VulkanDevicePriv *p = ctx->internal->priv;
982 AVVulkanDeviceContext *dev_hwctx = ctx->hwctx;
983 VkMemoryAllocateInfo alloc_info = {
984 .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
985 .pNext = alloc_extension,
988 /* Align if we need to */
989 if (req_flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)
990 req->size = FFALIGN(req->size, p->props.limits.minMemoryMapAlignment);
992 alloc_info.allocationSize = req->size;
994 /* The vulkan spec requires memory types to be sorted in the "optimal"
995 * order, so the first matching type we find will be the best/fastest one */
996 for (int i = 0; i < p->mprops.memoryTypeCount; i++) {
997 /* The memory type must be supported by the requirements (bitfield) */
998 if (!(req->memoryTypeBits & (1 << i)))
1001 /* The memory type flags must include our properties */
1002 if ((p->mprops.memoryTypes[i].propertyFlags & req_flags) != req_flags)
1005 /* Found a suitable memory type */
1011 av_log(ctx, AV_LOG_ERROR, "No memory type found for flags 0x%x\n",
1013 return AVERROR(EINVAL);
1016 alloc_info.memoryTypeIndex = index;
1018 ret = vkAllocateMemory(dev_hwctx->act_dev, &alloc_info,
1019 dev_hwctx->alloc, mem);
1020 if (ret != VK_SUCCESS) {
1021 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory: %s\n",
1023 return AVERROR(ENOMEM);
1026 *mem_flags |= p->mprops.memoryTypes[index].propertyFlags;
1031 static void vulkan_free_internal(AVVkFrameInternal *internal)
1037 if (internal->cuda_fc_ref) {
1038 AVHWFramesContext *cuda_fc = (AVHWFramesContext *)internal->cuda_fc_ref->data;
1039 int planes = av_pix_fmt_count_planes(cuda_fc->sw_format);
1040 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
1041 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
1042 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
1043 CudaFunctions *cu = cu_internal->cuda_dl;
1045 if (internal->cu_sem)
1046 CHECK_CU(cu->cuDestroyExternalSemaphore(internal->cu_sem));
1048 for (int i = 0; i < planes; i++) {
1049 if (internal->cu_mma[i])
1050 CHECK_CU(cu->cuMipmappedArrayDestroy(internal->cu_mma[i]));
1051 if (internal->ext_mem[i])
1052 CHECK_CU(cu->cuDestroyExternalMemory(internal->ext_mem[i]));
1055 av_buffer_unref(&internal->cuda_fc_ref);
1062 static void vulkan_frame_free(void *opaque, uint8_t *data)
1064 AVVkFrame *f = (AVVkFrame *)data;
1065 AVHWFramesContext *hwfc = opaque;
1066 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1067 int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1069 vulkan_free_internal(f->internal);
1071 for (int i = 0; i < planes; i++) {
1072 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
1073 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
1076 vkDestroySemaphore(hwctx->act_dev, f->sem, hwctx->alloc);
1081 static int alloc_bind_mem(AVHWFramesContext *hwfc, AVVkFrame *f,
1082 void *alloc_pnext, size_t alloc_pnext_stride)
1086 AVHWDeviceContext *ctx = hwfc->device_ctx;
1087 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1088 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { { 0 } };
1090 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1092 for (int i = 0; i < planes; i++) {
1094 VkImageMemoryRequirementsInfo2 req_desc = {
1095 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
1098 VkMemoryDedicatedAllocateInfo ded_alloc = {
1099 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
1100 .pNext = (void *)(((uint8_t *)alloc_pnext) + i*alloc_pnext_stride),
1102 VkMemoryDedicatedRequirements ded_req = {
1103 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
1105 VkMemoryRequirements2 req = {
1106 .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
1110 vkGetImageMemoryRequirements2(hwctx->act_dev, &req_desc, &req);
1112 /* In case the implementation prefers/requires dedicated allocation */
1113 use_ded_mem = ded_req.prefersDedicatedAllocation |
1114 ded_req.requiresDedicatedAllocation;
1116 ded_alloc.image = f->img[i];
1118 /* Allocate memory */
1119 if ((err = alloc_mem(ctx, &req.memoryRequirements,
1120 f->tiling == VK_IMAGE_TILING_LINEAR ?
1121 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT :
1122 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1123 use_ded_mem ? &ded_alloc : (void *)ded_alloc.pNext,
1124 &f->flags, &f->mem[i])))
1127 f->size[i] = req.memoryRequirements.size;
1128 bind_info[i].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
1129 bind_info[i].image = f->img[i];
1130 bind_info[i].memory = f->mem[i];
1133 /* Bind the allocated memory to the images */
1134 ret = vkBindImageMemory2(hwctx->act_dev, planes, bind_info);
1135 if (ret != VK_SUCCESS) {
1136 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
1138 return AVERROR_EXTERNAL;
1146 PREP_MODE_RO_SHADER,
1149 static int prepare_frame(AVHWFramesContext *hwfc, VulkanExecCtx *ectx,
1150 AVVkFrame *frame, enum PrepMode pmode)
1153 VkImageLayout new_layout;
1154 VkAccessFlags new_access;
1155 AVHWDeviceContext *ctx = hwfc->device_ctx;
1156 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1157 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1159 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
1161 VkCommandBufferBeginInfo cmd_start = {
1162 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
1163 .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
1166 VkSubmitInfo s_info = {
1167 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
1168 .commandBufferCount = 1,
1169 .pCommandBuffers = &ectx->buf,
1171 .pSignalSemaphores = &frame->sem,
1172 .signalSemaphoreCount = 1,
1176 case PREP_MODE_WRITE:
1177 new_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
1178 new_access = VK_ACCESS_TRANSFER_WRITE_BIT;
1180 case PREP_MODE_RO_SHADER:
1181 new_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
1182 new_access = VK_ACCESS_TRANSFER_READ_BIT;
1186 ret = vkBeginCommandBuffer(ectx->buf, &cmd_start);
1187 if (ret != VK_SUCCESS)
1188 return AVERROR_EXTERNAL;
1190 /* Change the image layout to something more optimal for writes.
1191 * This also signals the newly created semaphore, making it usable
1192 * for synchronization */
1193 for (int i = 0; i < planes; i++) {
1194 img_bar[i].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1195 img_bar[i].srcAccessMask = 0x0;
1196 img_bar[i].dstAccessMask = new_access;
1197 img_bar[i].oldLayout = frame->layout[i];
1198 img_bar[i].newLayout = new_layout;
1199 img_bar[i].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1200 img_bar[i].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1201 img_bar[i].image = frame->img[i];
1202 img_bar[i].subresourceRange.levelCount = 1;
1203 img_bar[i].subresourceRange.layerCount = 1;
1204 img_bar[i].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1206 frame->layout[i] = img_bar[i].newLayout;
1207 frame->access[i] = img_bar[i].dstAccessMask;
1210 vkCmdPipelineBarrier(ectx->buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
1211 VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
1212 0, NULL, 0, NULL, planes, img_bar);
1214 ret = vkEndCommandBuffer(ectx->buf);
1215 if (ret != VK_SUCCESS)
1216 return AVERROR_EXTERNAL;
1218 ret = vkQueueSubmit(ectx->queue, 1, &s_info, ectx->fence);
1219 if (ret != VK_SUCCESS) {
1220 return AVERROR_EXTERNAL;
1222 vkWaitForFences(hwctx->act_dev, 1, &ectx->fence, VK_TRUE, UINT64_MAX);
1223 vkResetFences(hwctx->act_dev, 1, &ectx->fence);
1229 static int create_frame(AVHWFramesContext *hwfc, AVVkFrame **frame,
1230 VkImageTiling tiling, VkImageUsageFlagBits usage,
1235 AVHWDeviceContext *ctx = hwfc->device_ctx;
1236 VulkanDevicePriv *p = ctx->internal->priv;
1237 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1238 enum AVPixelFormat format = hwfc->sw_format;
1239 const VkFormat *img_fmts = av_vkfmt_from_pixfmt(format);
1240 const int planes = av_pix_fmt_count_planes(format);
1242 VkExportSemaphoreCreateInfo ext_sem_info = {
1243 .sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO,
1244 .handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
1247 VkSemaphoreCreateInfo sem_spawn = {
1248 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1249 .pNext = p->extensions & EXT_EXTERNAL_FD_SEM ? &ext_sem_info : NULL,
1252 AVVkFrame *f = av_vk_frame_alloc();
1254 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1255 return AVERROR(ENOMEM);
1258 /* Create the images */
1259 for (int i = 0; i < planes; i++) {
1260 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
1261 int w = hwfc->width;
1262 int h = hwfc->height;
1263 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
1264 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
1266 VkImageCreateInfo image_create_info = {
1267 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1268 .pNext = create_pnext,
1269 .imageType = VK_IMAGE_TYPE_2D,
1270 .format = img_fmts[i],
1271 .extent.width = p_w,
1272 .extent.height = p_h,
1276 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1278 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1280 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
1281 .samples = VK_SAMPLE_COUNT_1_BIT,
1284 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
1285 hwctx->alloc, &f->img[i]);
1286 if (ret != VK_SUCCESS) {
1287 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1289 err = AVERROR(EINVAL);
1293 f->layout[i] = image_create_info.initialLayout;
1297 /* Create semaphore */
1298 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1299 hwctx->alloc, &f->sem);
1300 if (ret != VK_SUCCESS) {
1301 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1303 return AVERROR_EXTERNAL;
1313 vulkan_frame_free(hwfc, (uint8_t *)f);
1317 /* Checks if an export flag is enabled, and if it is ORs it with *iexp */
1318 static void try_export_flags(AVHWFramesContext *hwfc,
1319 VkExternalMemoryHandleTypeFlags *comp_handle_types,
1320 VkExternalMemoryHandleTypeFlagBits *iexp,
1321 VkExternalMemoryHandleTypeFlagBits exp)
1324 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1325 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1326 VkExternalImageFormatProperties eprops = {
1327 .sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES_KHR,
1329 VkImageFormatProperties2 props = {
1330 .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,
1333 VkPhysicalDeviceExternalImageFormatInfo enext = {
1334 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
1337 VkPhysicalDeviceImageFormatInfo2 pinfo = {
1338 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1339 .pNext = !exp ? NULL : &enext,
1340 .format = av_vkfmt_from_pixfmt(hwfc->sw_format)[0],
1341 .type = VK_IMAGE_TYPE_2D,
1342 .tiling = hwctx->tiling,
1343 .usage = hwctx->usage,
1344 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1347 ret = vkGetPhysicalDeviceImageFormatProperties2(dev_hwctx->phys_dev,
1349 if (ret == VK_SUCCESS) {
1351 *comp_handle_types |= eprops.externalMemoryProperties.compatibleHandleTypes;
1355 static AVBufferRef *vulkan_pool_alloc(void *opaque, int size)
1359 AVBufferRef *avbuf = NULL;
1360 AVHWFramesContext *hwfc = opaque;
1361 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1362 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1363 VkExportMemoryAllocateInfo eminfo[AV_NUM_DATA_POINTERS];
1364 VkExternalMemoryHandleTypeFlags e = 0x0;
1366 VkExternalMemoryImageCreateInfo eiinfo = {
1367 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1368 .pNext = hwctx->create_pnext,
1371 if (p->extensions & EXT_EXTERNAL_FD_MEMORY)
1372 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1373 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT);
1375 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
1376 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1377 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
1379 for (int i = 0; i < av_pix_fmt_count_planes(hwfc->sw_format); i++) {
1380 eminfo[i].sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO;
1381 eminfo[i].pNext = hwctx->alloc_pnext[i];
1382 eminfo[i].handleTypes = e;
1385 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1386 eiinfo.handleTypes ? &eiinfo : NULL);
1390 err = alloc_bind_mem(hwfc, f, eminfo, sizeof(*eminfo));
1394 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_WRITE);
1398 avbuf = av_buffer_create((uint8_t *)f, sizeof(AVVkFrame),
1399 vulkan_frame_free, hwfc, 0);
1406 vulkan_frame_free(hwfc, (uint8_t *)f);
1410 static void vulkan_frames_uninit(AVHWFramesContext *hwfc)
1412 VulkanFramesPriv *fp = hwfc->internal->priv;
1414 free_exec_ctx(hwfc->device_ctx, &fp->cmd);
1417 static int vulkan_frames_init(AVHWFramesContext *hwfc)
1421 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1422 VulkanFramesPriv *fp = hwfc->internal->priv;
1423 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1424 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1429 /* Default pool flags */
1430 hwctx->tiling = hwctx->tiling ? hwctx->tiling : p->use_linear_images ?
1431 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1433 hwctx->usage |= DEFAULT_USAGE_FLAGS;
1435 err = create_exec_ctx(hwfc->device_ctx, &fp->cmd,
1436 dev_hwctx->queue_family_tx_index);
1440 /* Test to see if allocation will fail */
1441 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1442 hwctx->create_pnext);
1444 free_exec_ctx(hwfc->device_ctx, &p->cmd);
1448 vulkan_frame_free(hwfc, (uint8_t *)f);
1450 hwfc->internal->pool_internal = av_buffer_pool_init2(sizeof(AVVkFrame),
1451 hwfc, vulkan_pool_alloc,
1453 if (!hwfc->internal->pool_internal) {
1454 free_exec_ctx(hwfc->device_ctx, &p->cmd);
1455 return AVERROR(ENOMEM);
1461 static int vulkan_get_buffer(AVHWFramesContext *hwfc, AVFrame *frame)
1463 frame->buf[0] = av_buffer_pool_get(hwfc->pool);
1465 return AVERROR(ENOMEM);
1467 frame->data[0] = frame->buf[0]->data;
1468 frame->format = AV_PIX_FMT_VULKAN;
1469 frame->width = hwfc->width;
1470 frame->height = hwfc->height;
1475 static int vulkan_transfer_get_formats(AVHWFramesContext *hwfc,
1476 enum AVHWFrameTransferDirection dir,
1477 enum AVPixelFormat **formats)
1479 enum AVPixelFormat *fmts = av_malloc_array(2, sizeof(*fmts));
1481 return AVERROR(ENOMEM);
1483 fmts[0] = hwfc->sw_format;
1484 fmts[1] = AV_PIX_FMT_NONE;
1490 typedef struct VulkanMapping {
1495 static void vulkan_unmap_frame(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1497 VulkanMapping *map = hwmap->priv;
1498 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1499 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1501 /* Check if buffer needs flushing */
1502 if ((map->flags & AV_HWFRAME_MAP_WRITE) &&
1503 !(map->frame->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1505 VkMappedMemoryRange flush_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1507 for (int i = 0; i < planes; i++) {
1508 flush_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1509 flush_ranges[i].memory = map->frame->mem[i];
1510 flush_ranges[i].size = VK_WHOLE_SIZE;
1513 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, planes,
1515 if (ret != VK_SUCCESS) {
1516 av_log(hwfc, AV_LOG_ERROR, "Failed to flush memory: %s\n",
1521 for (int i = 0; i < planes; i++)
1522 vkUnmapMemory(hwctx->act_dev, map->frame->mem[i]);
1527 static int vulkan_map_frame_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
1528 const AVFrame *src, int flags)
1531 int err, mapped_mem_count = 0;
1532 AVVkFrame *f = (AVVkFrame *)src->data[0];
1533 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1534 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1536 VulkanMapping *map = av_mallocz(sizeof(VulkanMapping));
1538 return AVERROR(EINVAL);
1540 if (src->format != AV_PIX_FMT_VULKAN) {
1541 av_log(hwfc, AV_LOG_ERROR, "Cannot map from pixel format %s!\n",
1542 av_get_pix_fmt_name(src->format));
1543 err = AVERROR(EINVAL);
1547 if (!(f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ||
1548 !(f->tiling == VK_IMAGE_TILING_LINEAR)) {
1549 av_log(hwfc, AV_LOG_ERROR, "Unable to map frame, not host visible "
1551 err = AVERROR(EINVAL);
1555 dst->width = src->width;
1556 dst->height = src->height;
1558 for (int i = 0; i < planes; i++) {
1559 ret = vkMapMemory(hwctx->act_dev, f->mem[i], 0,
1560 VK_WHOLE_SIZE, 0, (void **)&dst->data[i]);
1561 if (ret != VK_SUCCESS) {
1562 av_log(hwfc, AV_LOG_ERROR, "Failed to map image memory: %s\n",
1564 err = AVERROR_EXTERNAL;
1570 /* Check if the memory contents matter */
1571 if (((flags & AV_HWFRAME_MAP_READ) || !(flags & AV_HWFRAME_MAP_OVERWRITE)) &&
1572 !(f->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1573 VkMappedMemoryRange map_mem_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1574 for (int i = 0; i < planes; i++) {
1575 map_mem_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1576 map_mem_ranges[i].size = VK_WHOLE_SIZE;
1577 map_mem_ranges[i].memory = f->mem[i];
1580 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, planes,
1582 if (ret != VK_SUCCESS) {
1583 av_log(hwfc, AV_LOG_ERROR, "Failed to invalidate memory: %s\n",
1585 err = AVERROR_EXTERNAL;
1590 for (int i = 0; i < planes; i++) {
1591 VkImageSubresource sub = {
1592 .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
1594 VkSubresourceLayout layout;
1595 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
1596 dst->linesize[i] = layout.rowPitch;
1602 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src,
1603 &vulkan_unmap_frame, map);
1610 for (int i = 0; i < mapped_mem_count; i++)
1611 vkUnmapMemory(hwctx->act_dev, f->mem[i]);
1618 static void vulkan_unmap_from(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1620 VulkanMapping *map = hwmap->priv;
1621 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1622 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1624 for (int i = 0; i < planes; i++) {
1625 vkDestroyImage(hwctx->act_dev, map->frame->img[i], hwctx->alloc);
1626 vkFreeMemory(hwctx->act_dev, map->frame->mem[i], hwctx->alloc);
1629 vkDestroySemaphore(hwctx->act_dev, map->frame->sem, hwctx->alloc);
1631 av_freep(&map->frame);
1634 static const struct {
1635 uint32_t drm_fourcc;
1637 } vulkan_drm_format_map[] = {
1638 { DRM_FORMAT_R8, VK_FORMAT_R8_UNORM },
1639 { DRM_FORMAT_R16, VK_FORMAT_R16_UNORM },
1640 { DRM_FORMAT_GR88, VK_FORMAT_R8G8_UNORM },
1641 { DRM_FORMAT_RG88, VK_FORMAT_R8G8_UNORM },
1642 { DRM_FORMAT_GR1616, VK_FORMAT_R16G16_UNORM },
1643 { DRM_FORMAT_RG1616, VK_FORMAT_R16G16_UNORM },
1644 { DRM_FORMAT_ARGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1645 { DRM_FORMAT_XRGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1646 { DRM_FORMAT_ABGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1647 { DRM_FORMAT_XBGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1650 static inline VkFormat drm_to_vulkan_fmt(uint32_t drm_fourcc)
1652 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
1653 if (vulkan_drm_format_map[i].drm_fourcc == drm_fourcc)
1654 return vulkan_drm_format_map[i].vk_format;
1655 return VK_FORMAT_UNDEFINED;
1658 static int vulkan_map_from_drm_frame_desc(AVHWFramesContext *hwfc, AVVkFrame **frame,
1659 AVDRMFrameDescriptor *desc)
1664 int bind_counts = 0;
1665 AVHWDeviceContext *ctx = hwfc->device_ctx;
1666 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1667 VulkanDevicePriv *p = ctx->internal->priv;
1668 const AVPixFmtDescriptor *fmt_desc = av_pix_fmt_desc_get(hwfc->sw_format);
1669 const int has_modifiers = p->extensions & EXT_DRM_MODIFIER_FLAGS;
1670 VkSubresourceLayout plane_data[AV_NUM_DATA_POINTERS] = { 0 };
1671 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { 0 };
1672 VkBindImagePlaneMemoryInfo plane_info[AV_NUM_DATA_POINTERS] = { 0 };
1673 VkExternalMemoryHandleTypeFlagBits htype = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
1674 VkSemaphoreCreateInfo sem_spawn = {
1675 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1678 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdPropertiesKHR);
1680 for (int i = 0; i < desc->nb_layers; i++) {
1681 if (drm_to_vulkan_fmt(desc->layers[i].format) == VK_FORMAT_UNDEFINED) {
1682 av_log(ctx, AV_LOG_ERROR, "Unsupported DMABUF layer format %#08x!\n",
1683 desc->layers[i].format);
1684 return AVERROR(EINVAL);
1688 if (!(f = av_vk_frame_alloc())) {
1689 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1690 err = AVERROR(ENOMEM);
1694 for (int i = 0; i < desc->nb_objects; i++) {
1695 VkMemoryFdPropertiesKHR fdmp = {
1696 .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,
1698 VkMemoryRequirements req = {
1699 .size = desc->objects[i].size,
1701 VkImportMemoryFdInfoKHR idesc = {
1702 .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
1703 .handleType = htype,
1704 .fd = dup(desc->objects[i].fd),
1707 ret = pfn_vkGetMemoryFdPropertiesKHR(hwctx->act_dev, htype,
1709 if (ret != VK_SUCCESS) {
1710 av_log(hwfc, AV_LOG_ERROR, "Failed to get FD properties: %s\n",
1712 err = AVERROR_EXTERNAL;
1717 req.memoryTypeBits = fdmp.memoryTypeBits;
1719 err = alloc_mem(ctx, &req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1720 &idesc, &f->flags, &f->mem[i]);
1726 f->size[i] = desc->objects[i].size;
1729 f->tiling = has_modifiers ? VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT :
1730 desc->objects[0].format_modifier == DRM_FORMAT_MOD_LINEAR ?
1731 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1733 for (int i = 0; i < desc->nb_layers; i++) {
1734 const int planes = desc->layers[i].nb_planes;
1735 const int signal_p = has_modifiers && (planes > 1);
1737 VkImageDrmFormatModifierExplicitCreateInfoEXT drm_info = {
1738 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
1739 .drmFormatModifier = desc->objects[0].format_modifier,
1740 .drmFormatModifierPlaneCount = planes,
1741 .pPlaneLayouts = (const VkSubresourceLayout *)&plane_data,
1744 VkExternalMemoryImageCreateInfo einfo = {
1745 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1746 .pNext = has_modifiers ? &drm_info : NULL,
1747 .handleTypes = htype,
1750 const int p_w = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, fmt_desc->log2_chroma_w) : hwfc->width;
1751 const int p_h = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, fmt_desc->log2_chroma_h) : hwfc->height;
1753 VkImageCreateInfo image_create_info = {
1754 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1756 .imageType = VK_IMAGE_TYPE_2D,
1757 .format = drm_to_vulkan_fmt(desc->layers[i].format),
1758 .extent.width = p_w,
1759 .extent.height = p_h,
1763 .flags = VK_IMAGE_CREATE_ALIAS_BIT |
1764 (signal_p ? VK_IMAGE_CREATE_DISJOINT_BIT : 0x0),
1765 .tiling = f->tiling,
1766 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, /* specs say so */
1767 .usage = DEFAULT_USAGE_FLAGS,
1768 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
1769 .samples = VK_SAMPLE_COUNT_1_BIT,
1772 for (int j = 0; j < planes; j++) {
1773 plane_data[j].offset = desc->layers[i].planes[j].offset;
1774 plane_data[j].rowPitch = desc->layers[i].planes[j].pitch;
1775 plane_data[j].size = 0; /* The specs say so for all 3 */
1776 plane_data[j].arrayPitch = 0;
1777 plane_data[j].depthPitch = 0;
1781 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
1782 hwctx->alloc, &f->img[i]);
1783 if (ret != VK_SUCCESS) {
1784 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1786 err = AVERROR(EINVAL);
1790 f->layout[i] = image_create_info.initialLayout;
1793 for (int j = 0; j < planes; j++) {
1794 VkImageAspectFlagBits aspect = j == 0 ? VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
1795 j == 1 ? VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT :
1796 VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT;
1798 plane_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO;
1799 plane_info[bind_counts].planeAspect = aspect;
1801 bind_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
1802 bind_info[bind_counts].pNext = signal_p ? &plane_info[bind_counts] : NULL;
1803 bind_info[bind_counts].image = f->img[i];
1804 bind_info[bind_counts].memory = f->mem[desc->layers[i].planes[j].object_index];
1805 bind_info[bind_counts].memoryOffset = desc->layers[i].planes[j].offset;
1810 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1811 hwctx->alloc, &f->sem);
1812 if (ret != VK_SUCCESS) {
1813 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1815 return AVERROR_EXTERNAL;
1818 /* We'd import a semaphore onto the one we created using
1819 * vkImportSemaphoreFdKHR but unfortunately neither DRM nor VAAPI
1820 * offer us anything we could import and sync with, so instead
1821 * just signal the semaphore we created. */
1823 /* Bind the allocated memory to the images */
1824 ret = vkBindImageMemory2(hwctx->act_dev, bind_counts, bind_info);
1825 if (ret != VK_SUCCESS) {
1826 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
1828 return AVERROR_EXTERNAL;
1831 /* NOTE: This is completely uneccesary and unneeded once we can import
1832 * semaphores from DRM. Otherwise we have to activate the semaphores.
1833 * We're reusing the exec context that's also used for uploads/downloads. */
1834 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_RO_SHADER);
1843 for (int i = 0; i < desc->nb_layers; i++)
1844 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
1845 for (int i = 0; i < desc->nb_objects; i++)
1846 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
1847 vkDestroySemaphore(hwctx->act_dev, f->sem, hwctx->alloc);
1854 static int vulkan_map_from_drm(AVHWFramesContext *hwfc, AVFrame *dst,
1855 const AVFrame *src, int flags)
1859 VulkanMapping *map = NULL;
1861 err = vulkan_map_from_drm_frame_desc(hwfc, &f,
1862 (AVDRMFrameDescriptor *)src->data[0]);
1866 /* The unmapping function will free this */
1867 dst->data[0] = (uint8_t *)f;
1868 dst->width = src->width;
1869 dst->height = src->height;
1871 map = av_mallocz(sizeof(VulkanMapping));
1878 err = ff_hwframe_map_create(dst->hw_frames_ctx, dst, src,
1879 &vulkan_unmap_from, map);
1883 av_log(hwfc, AV_LOG_DEBUG, "Mapped DRM object to Vulkan!\n");
1888 vulkan_frame_free(hwfc->device_ctx->hwctx, (uint8_t *)f);
1894 static int vulkan_map_from_vaapi(AVHWFramesContext *dst_fc,
1895 AVFrame *dst, const AVFrame *src,
1899 AVFrame *tmp = av_frame_alloc();
1900 AVHWFramesContext *vaapi_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
1901 AVVAAPIDeviceContext *vaapi_ctx = vaapi_fc->device_ctx->hwctx;
1902 VASurfaceID surface_id = (VASurfaceID)(uintptr_t)src->data[3];
1905 return AVERROR(ENOMEM);
1907 /* We have to sync since like the previous comment said, no semaphores */
1908 vaSyncSurface(vaapi_ctx->display, surface_id);
1910 tmp->format = AV_PIX_FMT_DRM_PRIME;
1912 err = av_hwframe_map(tmp, src, flags);
1916 err = vulkan_map_from_drm(dst_fc, dst, tmp, flags);
1920 err = ff_hwframe_map_replace(dst, src);
1923 av_frame_free(&tmp);
1930 static int vulkan_export_to_cuda(AVHWFramesContext *hwfc,
1931 AVBufferRef *cuda_hwfc,
1932 const AVFrame *frame)
1937 AVVkFrameInternal *dst_int;
1938 AVHWDeviceContext *ctx = hwfc->device_ctx;
1939 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1940 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1941 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
1942 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
1943 VK_LOAD_PFN(hwctx->inst, vkGetSemaphoreFdKHR);
1945 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)cuda_hwfc->data;
1946 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
1947 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
1948 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
1949 CudaFunctions *cu = cu_internal->cuda_dl;
1950 CUarray_format cufmt = desc->comp[0].depth > 8 ? CU_AD_FORMAT_UNSIGNED_INT16 :
1951 CU_AD_FORMAT_UNSIGNED_INT8;
1953 dst_f = (AVVkFrame *)frame->data[0];
1955 dst_int = dst_f->internal;
1956 if (!dst_int || !dst_int->cuda_fc_ref) {
1957 VkSemaphoreGetFdInfoKHR sem_export = {
1958 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR,
1959 .semaphore = dst_f->sem,
1960 .handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
1962 CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC ext_sem_desc = {
1963 .type = CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD,
1966 if (!dst_f->internal)
1967 dst_f->internal = dst_int = av_mallocz(sizeof(*dst_f->internal));
1970 err = AVERROR(ENOMEM);
1974 dst_int->cuda_fc_ref = av_buffer_ref(cuda_hwfc);
1975 if (!dst_int->cuda_fc_ref) {
1976 err = AVERROR(ENOMEM);
1980 for (int i = 0; i < planes; i++) {
1981 CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC tex_desc = {
1984 .Width = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
1986 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
1990 .NumChannels = 1 + ((planes == 2) && i),
1995 CUDA_EXTERNAL_MEMORY_HANDLE_DESC ext_desc = {
1996 .type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD,
1997 .size = dst_f->size[i],
1999 VkMemoryGetFdInfoKHR export_info = {
2000 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2001 .memory = dst_f->mem[i],
2002 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR,
2005 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2006 &ext_desc.handle.fd);
2007 if (ret != VK_SUCCESS) {
2008 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2009 err = AVERROR_EXTERNAL;
2013 ret = CHECK_CU(cu->cuImportExternalMemory(&dst_int->ext_mem[i], &ext_desc));
2015 err = AVERROR_EXTERNAL;
2019 ret = CHECK_CU(cu->cuExternalMemoryGetMappedMipmappedArray(&dst_int->cu_mma[i],
2020 dst_int->ext_mem[i],
2023 err = AVERROR_EXTERNAL;
2027 ret = CHECK_CU(cu->cuMipmappedArrayGetLevel(&dst_int->cu_array[i],
2028 dst_int->cu_mma[i], 0));
2030 err = AVERROR_EXTERNAL;
2035 ret = pfn_vkGetSemaphoreFdKHR(hwctx->act_dev, &sem_export,
2036 &ext_sem_desc.handle.fd);
2037 if (ret != VK_SUCCESS) {
2038 av_log(ctx, AV_LOG_ERROR, "Failed to export semaphore: %s\n",
2040 err = AVERROR_EXTERNAL;
2044 ret = CHECK_CU(cu->cuImportExternalSemaphore(&dst_int->cu_sem,
2047 err = AVERROR_EXTERNAL;
2058 static int vulkan_transfer_data_from_cuda(AVHWFramesContext *hwfc,
2059 AVFrame *dst, const AVFrame *src)
2065 AVVkFrameInternal *dst_int;
2066 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2067 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2069 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2070 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2071 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2072 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2073 CudaFunctions *cu = cu_internal->cuda_dl;
2074 CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS s_w_par = { 0 };
2075 CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS s_s_par = { 0 };
2077 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2079 err = AVERROR_EXTERNAL;
2083 dst_f = (AVVkFrame *)dst->data[0];
2085 ret = vulkan_export_to_cuda(hwfc, src->hw_frames_ctx, dst);
2089 dst_int = dst_f->internal;
2091 ret = CHECK_CU(cu->cuWaitExternalSemaphoresAsync(&dst_int->cu_sem, &s_w_par,
2092 1, cuda_dev->stream));
2094 err = AVERROR_EXTERNAL;
2098 for (int i = 0; i < planes; i++) {
2099 CUDA_MEMCPY2D cpy = {
2100 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
2101 .srcDevice = (CUdeviceptr)src->data[i],
2102 .srcPitch = src->linesize[i],
2105 .dstMemoryType = CU_MEMORYTYPE_ARRAY,
2106 .dstArray = dst_int->cu_array[i],
2107 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2108 : hwfc->width) * desc->comp[i].step,
2109 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2113 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2115 err = AVERROR_EXTERNAL;
2120 ret = CHECK_CU(cu->cuSignalExternalSemaphoresAsync(&dst_int->cu_sem, &s_s_par,
2121 1, cuda_dev->stream));
2123 err = AVERROR_EXTERNAL;
2127 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2129 av_log(hwfc, AV_LOG_VERBOSE, "Transfered CUDA image to Vulkan!\n");
2134 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2135 vulkan_free_internal(dst_int);
2136 dst_f->internal = NULL;
2137 av_buffer_unref(&dst->buf[0]);
2142 static int vulkan_map_to(AVHWFramesContext *hwfc, AVFrame *dst,
2143 const AVFrame *src, int flags)
2145 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2147 switch (src->format) {
2150 case AV_PIX_FMT_VAAPI:
2151 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2152 return vulkan_map_from_vaapi(hwfc, dst, src, flags);
2154 case AV_PIX_FMT_DRM_PRIME:
2155 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2156 return vulkan_map_from_drm(hwfc, dst, src, flags);
2159 return AVERROR(ENOSYS);
2164 typedef struct VulkanDRMMapping {
2165 AVDRMFrameDescriptor drm_desc;
2169 static void vulkan_unmap_to_drm(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
2171 AVDRMFrameDescriptor *drm_desc = hwmap->priv;
2173 for (int i = 0; i < drm_desc->nb_objects; i++)
2174 close(drm_desc->objects[i].fd);
2179 static inline uint32_t vulkan_fmt_to_drm(VkFormat vkfmt)
2181 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
2182 if (vulkan_drm_format_map[i].vk_format == vkfmt)
2183 return vulkan_drm_format_map[i].drm_fourcc;
2184 return DRM_FORMAT_INVALID;
2187 static int vulkan_map_to_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2188 const AVFrame *src, int flags)
2192 AVVkFrame *f = (AVVkFrame *)src->data[0];
2193 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2194 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
2195 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2196 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2197 VkImageDrmFormatModifierPropertiesEXT drm_mod = {
2198 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT,
2201 AVDRMFrameDescriptor *drm_desc = av_mallocz(sizeof(*drm_desc));
2203 return AVERROR(ENOMEM);
2205 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src, &vulkan_unmap_to_drm, drm_desc);
2209 if (p->extensions & EXT_DRM_MODIFIER_FLAGS) {
2210 VK_LOAD_PFN(hwctx->inst, vkGetImageDrmFormatModifierPropertiesEXT);
2211 ret = pfn_vkGetImageDrmFormatModifierPropertiesEXT(hwctx->act_dev, f->img[0],
2213 if (ret != VK_SUCCESS) {
2214 av_log(hwfc, AV_LOG_ERROR, "Failed to retrieve DRM format modifier!\n");
2215 err = AVERROR_EXTERNAL;
2220 for (int i = 0; (i < planes) && (f->mem[i]); i++) {
2221 VkMemoryGetFdInfoKHR export_info = {
2222 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2223 .memory = f->mem[i],
2224 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,
2227 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2228 &drm_desc->objects[i].fd);
2229 if (ret != VK_SUCCESS) {
2230 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2231 err = AVERROR_EXTERNAL;
2235 drm_desc->nb_objects++;
2236 drm_desc->objects[i].size = f->size[i];
2237 drm_desc->objects[i].format_modifier = drm_mod.drmFormatModifier;
2240 drm_desc->nb_layers = planes;
2241 for (int i = 0; i < drm_desc->nb_layers; i++) {
2242 VkSubresourceLayout layout;
2243 VkImageSubresource sub = {
2244 .aspectMask = p->extensions & EXT_DRM_MODIFIER_FLAGS ?
2245 VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2246 VK_IMAGE_ASPECT_COLOR_BIT,
2248 VkFormat plane_vkfmt = av_vkfmt_from_pixfmt(hwfc->sw_format)[i];
2250 drm_desc->layers[i].format = vulkan_fmt_to_drm(plane_vkfmt);
2251 drm_desc->layers[i].nb_planes = 1;
2253 if (drm_desc->layers[i].format == DRM_FORMAT_INVALID) {
2254 av_log(hwfc, AV_LOG_ERROR, "Cannot map to DRM layer, unsupported!\n");
2255 err = AVERROR_PATCHWELCOME;
2259 drm_desc->layers[i].planes[0].object_index = FFMIN(i, drm_desc->nb_objects - 1);
2261 if (f->tiling != VK_IMAGE_TILING_OPTIMAL)
2264 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
2265 drm_desc->layers[i].planes[0].offset = layout.offset;
2266 drm_desc->layers[i].planes[0].pitch = layout.rowPitch;
2269 dst->width = src->width;
2270 dst->height = src->height;
2271 dst->data[0] = (uint8_t *)drm_desc;
2273 av_log(hwfc, AV_LOG_VERBOSE, "Mapped AVVkFrame to a DRM object!\n");
2283 static int vulkan_map_to_vaapi(AVHWFramesContext *hwfc, AVFrame *dst,
2284 const AVFrame *src, int flags)
2287 AVFrame *tmp = av_frame_alloc();
2289 return AVERROR(ENOMEM);
2291 tmp->format = AV_PIX_FMT_DRM_PRIME;
2293 err = vulkan_map_to_drm(hwfc, tmp, src, flags);
2297 err = av_hwframe_map(dst, tmp, flags);
2301 err = ff_hwframe_map_replace(dst, src);
2304 av_frame_free(&tmp);
2310 static int vulkan_map_from(AVHWFramesContext *hwfc, AVFrame *dst,
2311 const AVFrame *src, int flags)
2313 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2315 switch (dst->format) {
2317 case AV_PIX_FMT_DRM_PRIME:
2318 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2319 return vulkan_map_to_drm(hwfc, dst, src, flags);
2321 case AV_PIX_FMT_VAAPI:
2322 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2323 return vulkan_map_to_vaapi(hwfc, dst, src, flags);
2327 return vulkan_map_frame_to_mem(hwfc, dst, src, flags);
2331 typedef struct ImageBuffer {
2334 VkMemoryPropertyFlagBits flags;
2337 static void free_buf(AVHWDeviceContext *ctx, ImageBuffer *buf)
2339 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2343 vkDestroyBuffer(hwctx->act_dev, buf->buf, hwctx->alloc);
2344 vkFreeMemory(hwctx->act_dev, buf->mem, hwctx->alloc);
2347 static int create_buf(AVHWDeviceContext *ctx, ImageBuffer *buf, int height,
2348 int *stride, VkBufferUsageFlags usage,
2349 VkMemoryPropertyFlagBits flags, void *create_pnext,
2354 VkMemoryRequirements req;
2355 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2356 VulkanDevicePriv *p = ctx->internal->priv;
2358 VkBufferCreateInfo buf_spawn = {
2359 .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
2360 .pNext = create_pnext,
2362 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
2365 *stride = FFALIGN(*stride, p->props.limits.optimalBufferCopyRowPitchAlignment);
2366 buf_spawn.size = height*(*stride);
2368 ret = vkCreateBuffer(hwctx->act_dev, &buf_spawn, NULL, &buf->buf);
2369 if (ret != VK_SUCCESS) {
2370 av_log(ctx, AV_LOG_ERROR, "Failed to create buffer: %s\n",
2372 return AVERROR_EXTERNAL;
2375 vkGetBufferMemoryRequirements(hwctx->act_dev, buf->buf, &req);
2377 err = alloc_mem(ctx, &req, flags, alloc_pnext, &buf->flags, &buf->mem);
2381 ret = vkBindBufferMemory(hwctx->act_dev, buf->buf, buf->mem, 0);
2382 if (ret != VK_SUCCESS) {
2383 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory to buffer: %s\n",
2386 return AVERROR_EXTERNAL;
2392 static int map_buffers(AVHWDeviceContext *ctx, ImageBuffer *buf, uint8_t *mem[],
2393 int nb_buffers, int invalidate)
2396 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2397 VkMappedMemoryRange invalidate_ctx[AV_NUM_DATA_POINTERS];
2398 int invalidate_count = 0;
2400 for (int i = 0; i < nb_buffers; i++) {
2401 ret = vkMapMemory(hwctx->act_dev, buf[i].mem, 0,
2402 VK_WHOLE_SIZE, 0, (void **)&mem[i]);
2403 if (ret != VK_SUCCESS) {
2404 av_log(ctx, AV_LOG_ERROR, "Failed to map buffer memory: %s\n",
2406 return AVERROR_EXTERNAL;
2413 for (int i = 0; i < nb_buffers; i++) {
2414 const VkMappedMemoryRange ival_buf = {
2415 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2416 .memory = buf[i].mem,
2417 .size = VK_WHOLE_SIZE,
2419 if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2421 invalidate_ctx[invalidate_count++] = ival_buf;
2424 if (invalidate_count) {
2425 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, invalidate_count,
2427 if (ret != VK_SUCCESS)
2428 av_log(ctx, AV_LOG_WARNING, "Failed to invalidate memory: %s\n",
2435 static int unmap_buffers(AVHWDeviceContext *ctx, ImageBuffer *buf,
2436 int nb_buffers, int flush)
2440 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2441 VkMappedMemoryRange flush_ctx[AV_NUM_DATA_POINTERS];
2442 int flush_count = 0;
2445 for (int i = 0; i < nb_buffers; i++) {
2446 const VkMappedMemoryRange flush_buf = {
2447 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2448 .memory = buf[i].mem,
2449 .size = VK_WHOLE_SIZE,
2451 if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2453 flush_ctx[flush_count++] = flush_buf;
2458 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, flush_count, flush_ctx);
2459 if (ret != VK_SUCCESS) {
2460 av_log(ctx, AV_LOG_ERROR, "Failed to flush memory: %s\n",
2462 err = AVERROR_EXTERNAL; /* We still want to try to unmap them */
2466 for (int i = 0; i < nb_buffers; i++)
2467 vkUnmapMemory(hwctx->act_dev, buf[i].mem);
2472 static int transfer_image_buf(AVHWDeviceContext *ctx, AVVkFrame *frame,
2473 ImageBuffer *buffer, const int *buf_stride, int w,
2474 int h, enum AVPixelFormat pix_fmt, int to_buf)
2477 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2478 VulkanDevicePriv *s = ctx->internal->priv;
2481 VkPipelineStageFlagBits sem_wait_dst[AV_NUM_DATA_POINTERS];
2483 const int planes = av_pix_fmt_count_planes(pix_fmt);
2484 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2486 VkCommandBufferBeginInfo cmd_start = {
2487 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
2488 .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
2491 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
2493 VkSubmitInfo s_info = {
2494 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
2495 .commandBufferCount = 1,
2496 .pCommandBuffers = &s->cmd.buf,
2497 .pSignalSemaphores = &frame->sem,
2498 .pWaitSemaphores = &frame->sem,
2499 .pWaitDstStageMask = sem_wait_dst,
2500 .signalSemaphoreCount = 1,
2501 .waitSemaphoreCount = 1,
2504 ret = vkBeginCommandBuffer(s->cmd.buf, &cmd_start);
2505 if (ret != VK_SUCCESS) {
2506 av_log(ctx, AV_LOG_ERROR, "Unable to init command buffer: %s\n",
2508 return AVERROR_EXTERNAL;
2511 /* Change the image layout to something more optimal for transfers */
2512 for (int i = 0; i < planes; i++) {
2513 VkImageLayout new_layout = to_buf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL :
2514 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
2515 VkAccessFlags new_access = to_buf ? VK_ACCESS_TRANSFER_READ_BIT :
2516 VK_ACCESS_TRANSFER_WRITE_BIT;
2518 sem_wait_dst[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
2520 /* If the layout matches and we have read access skip the barrier */
2521 if ((frame->layout[i] == new_layout) && (frame->access[i] & new_access))
2524 img_bar[bar_num].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
2525 img_bar[bar_num].srcAccessMask = 0x0;
2526 img_bar[bar_num].dstAccessMask = new_access;
2527 img_bar[bar_num].oldLayout = frame->layout[i];
2528 img_bar[bar_num].newLayout = new_layout;
2529 img_bar[bar_num].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2530 img_bar[bar_num].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2531 img_bar[bar_num].image = frame->img[i];
2532 img_bar[bar_num].subresourceRange.levelCount = 1;
2533 img_bar[bar_num].subresourceRange.layerCount = 1;
2534 img_bar[bar_num].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2536 frame->layout[i] = img_bar[bar_num].newLayout;
2537 frame->access[i] = img_bar[bar_num].dstAccessMask;
2543 vkCmdPipelineBarrier(s->cmd.buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
2544 VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
2545 0, NULL, 0, NULL, bar_num, img_bar);
2547 /* Schedule a copy for each plane */
2548 for (int i = 0; i < planes; i++) {
2549 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
2550 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
2551 VkBufferImageCopy buf_reg = {
2553 /* Buffer stride isn't in bytes, it's in samples, the implementation
2554 * uses the image's VkFormat to know how many bytes per sample
2555 * the buffer has. So we have to convert by dividing. Stupid.
2556 * Won't work with YUVA or other planar formats with alpha. */
2557 .bufferRowLength = buf_stride[i] / desc->comp[i].step,
2558 .bufferImageHeight = p_h,
2559 .imageSubresource.layerCount = 1,
2560 .imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
2561 .imageOffset = { 0, 0, 0, },
2562 .imageExtent = { p_w, p_h, 1, },
2566 vkCmdCopyImageToBuffer(s->cmd.buf, frame->img[i], frame->layout[i],
2567 buffer[i].buf, 1, &buf_reg);
2569 vkCmdCopyBufferToImage(s->cmd.buf, buffer[i].buf, frame->img[i],
2570 frame->layout[i], 1, &buf_reg);
2573 ret = vkEndCommandBuffer(s->cmd.buf);
2574 if (ret != VK_SUCCESS) {
2575 av_log(ctx, AV_LOG_ERROR, "Unable to finish command buffer: %s\n",
2577 return AVERROR_EXTERNAL;
2580 /* Wait for the download/upload to finish if uploading, otherwise the
2581 * semaphore will take care of synchronization when uploading */
2582 ret = vkQueueSubmit(s->cmd.queue, 1, &s_info, s->cmd.fence);
2583 if (ret != VK_SUCCESS) {
2584 av_log(ctx, AV_LOG_ERROR, "Unable to submit command buffer: %s\n",
2586 return AVERROR_EXTERNAL;
2588 vkWaitForFences(hwctx->act_dev, 1, &s->cmd.fence, VK_TRUE, UINT64_MAX);
2589 vkResetFences(hwctx->act_dev, 1, &s->cmd.fence);
2595 /* Technically we can use VK_EXT_external_memory_host to upload and download,
2596 * however the alignment requirements make this unfeasible as both the pointer
2597 * and the size of each plane need to be aligned to the minimum alignment
2598 * requirement, which on all current implementations (anv, radv) is 4096.
2599 * If the requirement gets relaxed (unlikely) this can easily be implemented. */
2600 static int vulkan_transfer_data_from_mem(AVHWFramesContext *hwfc, AVFrame *dst,
2605 AVVkFrame *f = (AVVkFrame *)dst->data[0];
2606 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
2607 ImageBuffer buf[AV_NUM_DATA_POINTERS] = { { 0 } };
2608 const int planes = av_pix_fmt_count_planes(src->format);
2609 int log2_chroma = av_pix_fmt_desc_get(src->format)->log2_chroma_h;
2611 if ((src->format != AV_PIX_FMT_NONE && !av_vkfmt_from_pixfmt(src->format))) {
2612 av_log(hwfc, AV_LOG_ERROR, "Unsupported source pixel format!\n");
2613 return AVERROR(EINVAL);
2616 if (src->width > hwfc->width || src->height > hwfc->height)
2617 return AVERROR(EINVAL);
2619 /* For linear, host visiable images */
2620 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
2621 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
2622 AVFrame *map = av_frame_alloc();
2624 return AVERROR(ENOMEM);
2625 map->format = src->format;
2627 err = vulkan_map_frame_to_mem(hwfc, map, dst, AV_HWFRAME_MAP_WRITE);
2631 err = av_frame_copy(map, src);
2632 av_frame_free(&map);
2636 /* Create buffers */
2637 for (int i = 0; i < planes; i++) {
2638 int h = src->height;
2639 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
2641 tmp.linesize[i] = src->linesize[i];
2642 err = create_buf(dev_ctx, &buf[i], p_height,
2643 &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
2644 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
2649 /* Map, copy image to buffer, unmap */
2650 if ((err = map_buffers(dev_ctx, buf, tmp.data, planes, 0)))
2653 av_image_copy(tmp.data, tmp.linesize, (const uint8_t **)src->data,
2654 src->linesize, src->format, src->width, src->height);
2656 if ((err = unmap_buffers(dev_ctx, buf, planes, 1)))
2659 /* Copy buffers to image */
2660 err = transfer_image_buf(dev_ctx, f, buf, tmp.linesize,
2661 src->width, src->height, src->format, 0);
2664 for (int i = 0; i < planes; i++)
2665 free_buf(dev_ctx, &buf[i]);
2670 static int vulkan_transfer_data_to(AVHWFramesContext *hwfc, AVFrame *dst,
2673 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2675 switch (src->format) {
2677 case AV_PIX_FMT_CUDA:
2678 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
2679 (p->extensions & EXT_EXTERNAL_FD_SEM))
2680 return vulkan_transfer_data_from_cuda(hwfc, dst, src);
2683 if (src->hw_frames_ctx)
2684 return AVERROR(ENOSYS);
2686 return vulkan_transfer_data_from_mem(hwfc, dst, src);
2691 static int vulkan_transfer_data_to_cuda(AVHWFramesContext *hwfc, AVFrame *dst,
2698 AVVkFrameInternal *dst_int;
2699 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2700 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2702 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)dst->hw_frames_ctx->data;
2703 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2704 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2705 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2706 CudaFunctions *cu = cu_internal->cuda_dl;
2708 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2710 err = AVERROR_EXTERNAL;
2714 dst_f = (AVVkFrame *)src->data[0];
2716 err = vulkan_export_to_cuda(hwfc, dst->hw_frames_ctx, src);
2721 dst_int = dst_f->internal;
2723 for (int i = 0; i < planes; i++) {
2724 CUDA_MEMCPY2D cpy = {
2725 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
2726 .dstDevice = (CUdeviceptr)dst->data[i],
2727 .dstPitch = dst->linesize[i],
2730 .srcMemoryType = CU_MEMORYTYPE_ARRAY,
2731 .srcArray = dst_int->cu_array[i],
2732 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2733 : hwfc->width) * desc->comp[i].step,
2734 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2738 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2740 err = AVERROR_EXTERNAL;
2745 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2747 av_log(hwfc, AV_LOG_VERBOSE, "Transfered Vulkan image to CUDA!\n");
2752 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2753 vulkan_free_internal(dst_int);
2754 dst_f->internal = NULL;
2755 av_buffer_unref(&dst->buf[0]);
2760 static int vulkan_transfer_data_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
2765 AVVkFrame *f = (AVVkFrame *)src->data[0];
2766 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
2767 ImageBuffer buf[AV_NUM_DATA_POINTERS] = { { 0 } };
2768 const int planes = av_pix_fmt_count_planes(dst->format);
2769 int log2_chroma = av_pix_fmt_desc_get(dst->format)->log2_chroma_h;
2771 if (dst->width > hwfc->width || dst->height > hwfc->height)
2772 return AVERROR(EINVAL);
2774 /* For linear, host visiable images */
2775 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
2776 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
2777 AVFrame *map = av_frame_alloc();
2779 return AVERROR(ENOMEM);
2780 map->format = dst->format;
2782 err = vulkan_map_frame_to_mem(hwfc, map, src, AV_HWFRAME_MAP_READ);
2786 err = av_frame_copy(dst, map);
2787 av_frame_free(&map);
2791 /* Create buffers */
2792 for (int i = 0; i < planes; i++) {
2793 int h = dst->height;
2794 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
2796 tmp.linesize[i] = dst->linesize[i];
2797 err = create_buf(dev_ctx, &buf[i], p_height,
2798 &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_DST_BIT,
2799 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
2802 /* Copy image to buffer */
2803 if ((err = transfer_image_buf(dev_ctx, f, buf, tmp.linesize,
2804 dst->width, dst->height, dst->format, 1)))
2807 /* Map, copy buffer to frame, unmap */
2808 if ((err = map_buffers(dev_ctx, buf, tmp.data, planes, 1)))
2811 av_image_copy(dst->data, dst->linesize, (const uint8_t **)tmp.data,
2812 tmp.linesize, dst->format, dst->width, dst->height);
2814 err = unmap_buffers(dev_ctx, buf, planes, 0);
2817 for (int i = 0; i < planes; i++)
2818 free_buf(dev_ctx, &buf[i]);
2823 static int vulkan_transfer_data_from(AVHWFramesContext *hwfc, AVFrame *dst,
2826 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2828 switch (dst->format) {
2830 case AV_PIX_FMT_CUDA:
2831 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
2832 (p->extensions & EXT_EXTERNAL_FD_SEM))
2833 return vulkan_transfer_data_to_cuda(hwfc, dst, src);
2836 if (dst->hw_frames_ctx)
2837 return AVERROR(ENOSYS);
2839 return vulkan_transfer_data_to_mem(hwfc, dst, src);
2843 AVVkFrame *av_vk_frame_alloc(void)
2845 return av_mallocz(sizeof(AVVkFrame));
2848 const HWContextType ff_hwcontext_type_vulkan = {
2849 .type = AV_HWDEVICE_TYPE_VULKAN,
2852 .device_hwctx_size = sizeof(AVVulkanDeviceContext),
2853 .device_priv_size = sizeof(VulkanDevicePriv),
2854 .frames_hwctx_size = sizeof(AVVulkanFramesContext),
2855 .frames_priv_size = sizeof(VulkanFramesPriv),
2857 .device_init = &vulkan_device_init,
2858 .device_create = &vulkan_device_create,
2859 .device_derive = &vulkan_device_derive,
2861 .frames_get_constraints = &vulkan_frames_get_constraints,
2862 .frames_init = vulkan_frames_init,
2863 .frames_get_buffer = vulkan_get_buffer,
2864 .frames_uninit = vulkan_frames_uninit,
2866 .transfer_get_formats = vulkan_transfer_get_formats,
2867 .transfer_data_to = vulkan_transfer_data_to,
2868 .transfer_data_from = vulkan_transfer_data_from,
2870 .map_to = vulkan_map_to,
2871 .map_from = vulkan_map_from,
2873 .pix_fmts = (const enum AVPixelFormat []) {