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_NO_FLAG = 1ULL << 63,
187 typedef struct VulkanOptExtension {
190 } VulkanOptExtension;
192 static const VulkanOptExtension optional_instance_exts[] = {
193 { VK_KHR_SURFACE_EXTENSION_NAME, EXT_NO_FLAG },
196 static const VulkanOptExtension optional_device_exts[] = {
197 { VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME, EXT_EXTERNAL_FD_MEMORY, },
198 { VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME, EXT_EXTERNAL_DMABUF_MEMORY, },
199 { VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME, EXT_DRM_MODIFIER_FLAGS, },
200 { VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME, EXT_EXTERNAL_FD_SEM, },
203 /* Converts return values to strings */
204 static const char *vk_ret2str(VkResult res)
206 #define CASE(VAL) case VAL: return #VAL
212 CASE(VK_EVENT_RESET);
214 CASE(VK_ERROR_OUT_OF_HOST_MEMORY);
215 CASE(VK_ERROR_OUT_OF_DEVICE_MEMORY);
216 CASE(VK_ERROR_INITIALIZATION_FAILED);
217 CASE(VK_ERROR_DEVICE_LOST);
218 CASE(VK_ERROR_MEMORY_MAP_FAILED);
219 CASE(VK_ERROR_LAYER_NOT_PRESENT);
220 CASE(VK_ERROR_EXTENSION_NOT_PRESENT);
221 CASE(VK_ERROR_FEATURE_NOT_PRESENT);
222 CASE(VK_ERROR_INCOMPATIBLE_DRIVER);
223 CASE(VK_ERROR_TOO_MANY_OBJECTS);
224 CASE(VK_ERROR_FORMAT_NOT_SUPPORTED);
225 CASE(VK_ERROR_FRAGMENTED_POOL);
226 CASE(VK_ERROR_SURFACE_LOST_KHR);
227 CASE(VK_ERROR_NATIVE_WINDOW_IN_USE_KHR);
228 CASE(VK_SUBOPTIMAL_KHR);
229 CASE(VK_ERROR_OUT_OF_DATE_KHR);
230 CASE(VK_ERROR_INCOMPATIBLE_DISPLAY_KHR);
231 CASE(VK_ERROR_VALIDATION_FAILED_EXT);
232 CASE(VK_ERROR_INVALID_SHADER_NV);
233 CASE(VK_ERROR_OUT_OF_POOL_MEMORY);
234 CASE(VK_ERROR_INVALID_EXTERNAL_HANDLE);
235 CASE(VK_ERROR_NOT_PERMITTED_EXT);
236 CASE(VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT);
237 CASE(VK_ERROR_INVALID_DEVICE_ADDRESS_EXT);
238 CASE(VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT);
239 default: return "Unknown error";
244 static VkBool32 vk_dbg_callback(VkDebugUtilsMessageSeverityFlagBitsEXT severity,
245 VkDebugUtilsMessageTypeFlagsEXT messageType,
246 const VkDebugUtilsMessengerCallbackDataEXT *data,
250 AVHWDeviceContext *ctx = priv;
253 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT: l = AV_LOG_VERBOSE; break;
254 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT: l = AV_LOG_INFO; break;
255 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT: l = AV_LOG_WARNING; break;
256 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT: l = AV_LOG_ERROR; break;
257 default: l = AV_LOG_DEBUG; break;
260 av_log(ctx, l, "%s\n", data->pMessage);
261 for (int i = 0; i < data->cmdBufLabelCount; i++)
262 av_log(ctx, l, "\t%i: %s\n", i, data->pCmdBufLabels[i].pLabelName);
267 static int check_extensions(AVHWDeviceContext *ctx, int dev, AVDictionary *opts,
268 const char * const **dst, uint32_t *num, int debug)
271 const char **extension_names = NULL;
272 VulkanDevicePriv *p = ctx->internal->priv;
273 AVVulkanDeviceContext *hwctx = ctx->hwctx;
274 int err = 0, found, extensions_found = 0;
277 int optional_exts_num;
278 uint32_t sup_ext_count;
279 char *user_exts_str = NULL;
280 AVDictionaryEntry *user_exts;
281 VkExtensionProperties *sup_ext;
282 const VulkanOptExtension *optional_exts;
286 optional_exts = optional_instance_exts;
287 optional_exts_num = FF_ARRAY_ELEMS(optional_instance_exts);
288 user_exts = av_dict_get(opts, "instance_extensions", NULL, 0);
290 user_exts_str = av_strdup(user_exts->value);
291 if (!user_exts_str) {
292 err = AVERROR(ENOMEM);
296 vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, NULL);
297 sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
299 return AVERROR(ENOMEM);
300 vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, sup_ext);
303 optional_exts = optional_device_exts;
304 optional_exts_num = FF_ARRAY_ELEMS(optional_device_exts);
305 user_exts = av_dict_get(opts, "device_extensions", NULL, 0);
307 user_exts_str = av_strdup(user_exts->value);
308 if (!user_exts_str) {
309 err = AVERROR(ENOMEM);
313 vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
314 &sup_ext_count, NULL);
315 sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
317 return AVERROR(ENOMEM);
318 vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
319 &sup_ext_count, sup_ext);
322 for (int i = 0; i < optional_exts_num; i++) {
323 tstr = optional_exts[i].name;
325 for (int j = 0; j < sup_ext_count; j++) {
326 if (!strcmp(tstr, sup_ext[j].extensionName)) {
334 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
335 p->extensions |= optional_exts[i].flag;
336 ADD_VAL_TO_LIST(extension_names, extensions_found, tstr);
340 tstr = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
342 for (int j = 0; j < sup_ext_count; j++) {
343 if (!strcmp(tstr, sup_ext[j].extensionName)) {
349 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
350 ADD_VAL_TO_LIST(extension_names, extensions_found, tstr);
352 av_log(ctx, AV_LOG_ERROR, "Debug extension \"%s\" not found!\n",
354 err = AVERROR(EINVAL);
360 char *save, *token = av_strtok(user_exts_str, "+", &save);
363 for (int j = 0; j < sup_ext_count; j++) {
364 if (!strcmp(token, sup_ext[j].extensionName)) {
370 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
371 ADD_VAL_TO_LIST(extension_names, extensions_found, token);
373 av_log(ctx, AV_LOG_ERROR, "%s extension \"%s\" not found!\n",
375 err = AVERROR(EINVAL);
378 token = av_strtok(NULL, "+", &save);
382 *dst = extension_names;
383 *num = extensions_found;
385 av_free(user_exts_str);
391 for (int i = 0; i < extensions_found; i++)
392 av_free((void *)extension_names[i]);
393 av_free(extension_names);
394 av_free(user_exts_str);
399 /* Creates a VkInstance */
400 static int create_instance(AVHWDeviceContext *ctx, AVDictionary *opts)
404 VulkanDevicePriv *p = ctx->internal->priv;
405 AVVulkanDeviceContext *hwctx = ctx->hwctx;
406 AVDictionaryEntry *debug_opt = av_dict_get(opts, "debug", NULL, 0);
407 const int debug_mode = debug_opt && strtol(debug_opt->value, NULL, 10);
408 VkApplicationInfo application_info = {
409 .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
410 .pEngineName = "libavutil",
411 .apiVersion = VK_API_VERSION_1_1,
412 .engineVersion = VK_MAKE_VERSION(LIBAVUTIL_VERSION_MAJOR,
413 LIBAVUTIL_VERSION_MINOR,
414 LIBAVUTIL_VERSION_MICRO),
416 VkInstanceCreateInfo inst_props = {
417 .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
418 .pApplicationInfo = &application_info,
421 /* Check for present/missing extensions */
422 err = check_extensions(ctx, 0, opts, &inst_props.ppEnabledExtensionNames,
423 &inst_props.enabledExtensionCount, debug_mode);
428 static const char *layers[] = { "VK_LAYER_KHRONOS_validation" };
429 inst_props.ppEnabledLayerNames = layers;
430 inst_props.enabledLayerCount = FF_ARRAY_ELEMS(layers);
433 /* Try to create the instance */
434 ret = vkCreateInstance(&inst_props, hwctx->alloc, &hwctx->inst);
436 /* Check for errors */
437 if (ret != VK_SUCCESS) {
438 av_log(ctx, AV_LOG_ERROR, "Instance creation failure: %s\n",
440 for (int i = 0; i < inst_props.enabledExtensionCount; i++)
441 av_free((void *)inst_props.ppEnabledExtensionNames[i]);
442 av_free((void *)inst_props.ppEnabledExtensionNames);
443 return AVERROR_EXTERNAL;
447 VkDebugUtilsMessengerCreateInfoEXT dbg = {
448 .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT,
449 .messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT |
450 VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT |
451 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
452 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT,
453 .messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
454 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
455 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT,
456 .pfnUserCallback = vk_dbg_callback,
459 VK_LOAD_PFN(hwctx->inst, vkCreateDebugUtilsMessengerEXT);
461 pfn_vkCreateDebugUtilsMessengerEXT(hwctx->inst, &dbg,
462 hwctx->alloc, &p->debug_ctx);
465 hwctx->enabled_inst_extensions = inst_props.ppEnabledExtensionNames;
466 hwctx->nb_enabled_inst_extensions = inst_props.enabledExtensionCount;
471 typedef struct VulkanDeviceSelection {
472 uint8_t uuid[VK_UUID_SIZE]; /* Will use this first unless !has_uuid */
474 const char *name; /* Will use this second unless NULL */
475 uint32_t pci_device; /* Will use this third unless 0x0 */
476 uint32_t vendor_id; /* Last resort to find something deterministic */
477 int index; /* Finally fall back to index */
478 } VulkanDeviceSelection;
480 static const char *vk_dev_type(enum VkPhysicalDeviceType type)
483 case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: return "integrated";
484 case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: return "discrete";
485 case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: return "virtual";
486 case VK_PHYSICAL_DEVICE_TYPE_CPU: return "software";
487 default: return "unknown";
492 static int find_device(AVHWDeviceContext *ctx, VulkanDeviceSelection *select)
494 int err = 0, choice = -1;
497 VkPhysicalDevice *devices = NULL;
498 VkPhysicalDeviceIDProperties *idp = NULL;
499 VkPhysicalDeviceProperties2 *prop = NULL;
500 VulkanDevicePriv *p = ctx->internal->priv;
501 AVVulkanDeviceContext *hwctx = ctx->hwctx;
503 ret = vkEnumeratePhysicalDevices(hwctx->inst, &num, NULL);
504 if (ret != VK_SUCCESS || !num) {
505 av_log(ctx, AV_LOG_ERROR, "No devices found: %s!\n", vk_ret2str(ret));
506 return AVERROR(ENODEV);
509 devices = av_malloc_array(num, sizeof(VkPhysicalDevice));
511 return AVERROR(ENOMEM);
513 ret = vkEnumeratePhysicalDevices(hwctx->inst, &num, devices);
514 if (ret != VK_SUCCESS) {
515 av_log(ctx, AV_LOG_ERROR, "Failed enumerating devices: %s\n",
517 err = AVERROR(ENODEV);
521 prop = av_mallocz_array(num, sizeof(*prop));
523 err = AVERROR(ENOMEM);
527 idp = av_mallocz_array(num, sizeof(*idp));
529 err = AVERROR(ENOMEM);
533 av_log(ctx, AV_LOG_VERBOSE, "GPU listing:\n");
534 for (int i = 0; i < num; i++) {
535 idp[i].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES;
536 prop[i].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
537 prop[i].pNext = &idp[i];
539 vkGetPhysicalDeviceProperties2(devices[i], &prop[i]);
540 av_log(ctx, AV_LOG_VERBOSE, " %d: %s (%s) (0x%x)\n", i,
541 prop[i].properties.deviceName,
542 vk_dev_type(prop[i].properties.deviceType),
543 prop[i].properties.deviceID);
546 if (select->has_uuid) {
547 for (int i = 0; i < num; i++) {
548 if (!strncmp(idp[i].deviceUUID, select->uuid, VK_UUID_SIZE)) {
553 av_log(ctx, AV_LOG_ERROR, "Unable to find device by given UUID!\n");
554 err = AVERROR(ENODEV);
556 } else if (select->name) {
557 av_log(ctx, AV_LOG_VERBOSE, "Requested device: %s\n", select->name);
558 for (int i = 0; i < num; i++) {
559 if (strstr(prop[i].properties.deviceName, select->name)) {
564 av_log(ctx, AV_LOG_ERROR, "Unable to find device \"%s\"!\n",
566 err = AVERROR(ENODEV);
568 } else if (select->pci_device) {
569 av_log(ctx, AV_LOG_VERBOSE, "Requested device: 0x%x\n", select->pci_device);
570 for (int i = 0; i < num; i++) {
571 if (select->pci_device == prop[i].properties.deviceID) {
576 av_log(ctx, AV_LOG_ERROR, "Unable to find device with PCI ID 0x%x!\n",
578 err = AVERROR(EINVAL);
580 } else if (select->vendor_id) {
581 av_log(ctx, AV_LOG_VERBOSE, "Requested vendor: 0x%x\n", select->vendor_id);
582 for (int i = 0; i < num; i++) {
583 if (select->vendor_id == prop[i].properties.vendorID) {
588 av_log(ctx, AV_LOG_ERROR, "Unable to find device with Vendor ID 0x%x!\n",
590 err = AVERROR(ENODEV);
593 if (select->index < num) {
594 choice = select->index;
597 av_log(ctx, AV_LOG_ERROR, "Unable to find device with index %i!\n",
599 err = AVERROR(ENODEV);
605 p->dev_is_nvidia = (prop[choice].properties.vendorID == 0x10de);
606 hwctx->phys_dev = devices[choice];
615 static int search_queue_families(AVHWDeviceContext *ctx, VkDeviceCreateInfo *cd)
618 VkQueueFamilyProperties *qs = NULL;
619 AVVulkanDeviceContext *hwctx = ctx->hwctx;
620 int graph_index = -1, comp_index = -1, tx_index = -1;
621 VkDeviceQueueCreateInfo *pc = (VkDeviceQueueCreateInfo *)cd->pQueueCreateInfos;
623 /* First get the number of queue families */
624 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, NULL);
626 av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
627 return AVERROR_EXTERNAL;
630 /* Then allocate memory */
631 qs = av_malloc_array(num, sizeof(VkQueueFamilyProperties));
633 return AVERROR(ENOMEM);
635 /* Finally retrieve the queue families */
636 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, qs);
638 #define SEARCH_FLAGS(expr, out) \
639 for (int i = 0; i < num; i++) { \
640 const VkQueueFlagBits flags = qs[i].queueFlags; \
647 SEARCH_FLAGS(flags & VK_QUEUE_GRAPHICS_BIT, graph_index)
649 SEARCH_FLAGS((flags & VK_QUEUE_COMPUTE_BIT) && (i != graph_index),
652 SEARCH_FLAGS((flags & VK_QUEUE_TRANSFER_BIT) && (i != graph_index) &&
653 (i != comp_index), tx_index)
656 #define QF_FLAGS(flags) \
657 ((flags) & VK_QUEUE_GRAPHICS_BIT ) ? "(graphics) " : "", \
658 ((flags) & VK_QUEUE_COMPUTE_BIT ) ? "(compute) " : "", \
659 ((flags) & VK_QUEUE_TRANSFER_BIT ) ? "(transfer) " : "", \
660 ((flags) & VK_QUEUE_SPARSE_BINDING_BIT) ? "(sparse) " : ""
662 av_log(ctx, AV_LOG_VERBOSE, "Using queue family %i for graphics, "
663 "flags: %s%s%s%s\n", graph_index, QF_FLAGS(qs[graph_index].queueFlags));
665 hwctx->queue_family_index = graph_index;
666 hwctx->queue_family_tx_index = graph_index;
667 hwctx->queue_family_comp_index = graph_index;
669 pc[cd->queueCreateInfoCount++].queueFamilyIndex = graph_index;
671 if (comp_index != -1) {
672 av_log(ctx, AV_LOG_VERBOSE, "Using queue family %i for compute, "
673 "flags: %s%s%s%s\n", comp_index, QF_FLAGS(qs[comp_index].queueFlags));
674 hwctx->queue_family_tx_index = comp_index;
675 hwctx->queue_family_comp_index = comp_index;
676 pc[cd->queueCreateInfoCount++].queueFamilyIndex = comp_index;
679 if (tx_index != -1) {
680 av_log(ctx, AV_LOG_VERBOSE, "Using queue family %i for transfers, "
681 "flags: %s%s%s%s\n", tx_index, QF_FLAGS(qs[tx_index].queueFlags));
682 hwctx->queue_family_tx_index = tx_index;
683 pc[cd->queueCreateInfoCount++].queueFamilyIndex = tx_index;
693 static int create_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd,
694 int queue_family_index)
697 AVVulkanDeviceContext *hwctx = ctx->hwctx;
699 VkCommandPoolCreateInfo cqueue_create = {
700 .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
701 .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
702 .queueFamilyIndex = queue_family_index,
704 VkCommandBufferAllocateInfo cbuf_create = {
705 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
706 .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
707 .commandBufferCount = 1,
710 VkFenceCreateInfo fence_spawn = {
711 .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
714 ret = vkCreateFence(hwctx->act_dev, &fence_spawn,
715 hwctx->alloc, &cmd->fence);
716 if (ret != VK_SUCCESS) {
717 av_log(ctx, AV_LOG_ERROR, "Failed to create frame fence: %s\n",
719 return AVERROR_EXTERNAL;
722 ret = vkCreateCommandPool(hwctx->act_dev, &cqueue_create,
723 hwctx->alloc, &cmd->pool);
724 if (ret != VK_SUCCESS) {
725 av_log(ctx, AV_LOG_ERROR, "Command pool creation failure: %s\n",
727 return AVERROR_EXTERNAL;
730 cbuf_create.commandPool = cmd->pool;
732 ret = vkAllocateCommandBuffers(hwctx->act_dev, &cbuf_create, &cmd->buf);
733 if (ret != VK_SUCCESS) {
734 av_log(ctx, AV_LOG_ERROR, "Command buffer alloc failure: %s\n",
736 return AVERROR_EXTERNAL;
739 vkGetDeviceQueue(hwctx->act_dev, cqueue_create.queueFamilyIndex, 0,
745 static void free_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd)
747 AVVulkanDeviceContext *hwctx = ctx->hwctx;
750 vkDestroyFence(hwctx->act_dev, cmd->fence, hwctx->alloc);
752 vkFreeCommandBuffers(hwctx->act_dev, cmd->pool, 1, &cmd->buf);
754 vkDestroyCommandPool(hwctx->act_dev, cmd->pool, hwctx->alloc);
757 static void vulkan_device_free(AVHWDeviceContext *ctx)
759 VulkanDevicePriv *p = ctx->internal->priv;
760 AVVulkanDeviceContext *hwctx = ctx->hwctx;
762 free_exec_ctx(ctx, &p->cmd);
764 vkDestroyDevice(hwctx->act_dev, hwctx->alloc);
767 VK_LOAD_PFN(hwctx->inst, vkDestroyDebugUtilsMessengerEXT);
768 pfn_vkDestroyDebugUtilsMessengerEXT(hwctx->inst, p->debug_ctx,
772 vkDestroyInstance(hwctx->inst, hwctx->alloc);
774 for (int i = 0; i < hwctx->nb_enabled_inst_extensions; i++)
775 av_free((void *)hwctx->enabled_inst_extensions[i]);
776 av_free((void *)hwctx->enabled_inst_extensions);
778 for (int i = 0; i < hwctx->nb_enabled_dev_extensions; i++)
779 av_free((void *)hwctx->enabled_dev_extensions[i]);
780 av_free((void *)hwctx->enabled_dev_extensions);
783 static int vulkan_device_create_internal(AVHWDeviceContext *ctx,
784 VulkanDeviceSelection *dev_select,
785 AVDictionary *opts, int flags)
789 AVDictionaryEntry *opt_d;
790 VulkanDevicePriv *p = ctx->internal->priv;
791 AVVulkanDeviceContext *hwctx = ctx->hwctx;
792 VkDeviceQueueCreateInfo queue_create_info[3] = {
793 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
794 .pQueuePriorities = (float []){ 1.0f },
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 },
804 VkDeviceCreateInfo dev_info = {
805 .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
806 .pQueueCreateInfos = queue_create_info,
807 .queueCreateInfoCount = 0,
810 ctx->free = vulkan_device_free;
812 /* Create an instance if not given one */
813 if ((err = create_instance(ctx, opts)))
816 /* Find a device (if not given one) */
817 if ((err = find_device(ctx, dev_select)))
820 vkGetPhysicalDeviceProperties(hwctx->phys_dev, &p->props);
821 av_log(ctx, AV_LOG_VERBOSE, "Using device: %s\n", p->props.deviceName);
822 av_log(ctx, AV_LOG_VERBOSE, "Alignments:\n");
823 av_log(ctx, AV_LOG_VERBOSE, " optimalBufferCopyOffsetAlignment: %li\n",
824 p->props.limits.optimalBufferCopyOffsetAlignment);
825 av_log(ctx, AV_LOG_VERBOSE, " optimalBufferCopyRowPitchAlignment: %li\n",
826 p->props.limits.optimalBufferCopyRowPitchAlignment);
827 av_log(ctx, AV_LOG_VERBOSE, " minMemoryMapAlignment: %li\n",
828 p->props.limits.minMemoryMapAlignment);
830 /* Search queue family */
831 if ((err = search_queue_families(ctx, &dev_info)))
834 if ((err = check_extensions(ctx, 1, opts, &dev_info.ppEnabledExtensionNames,
835 &dev_info.enabledExtensionCount, 0)))
838 ret = vkCreateDevice(hwctx->phys_dev, &dev_info, hwctx->alloc,
841 if (ret != VK_SUCCESS) {
842 av_log(ctx, AV_LOG_ERROR, "Device creation failure: %s\n",
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);
847 err = AVERROR_EXTERNAL;
851 /* Tiled images setting, use them by default */
852 opt_d = av_dict_get(opts, "linear_images", NULL, 0);
854 p->use_linear_images = strtol(opt_d->value, NULL, 10);
856 hwctx->enabled_dev_extensions = dev_info.ppEnabledExtensionNames;
857 hwctx->nb_enabled_dev_extensions = dev_info.enabledExtensionCount;
863 static int vulkan_device_init(AVHWDeviceContext *ctx)
867 AVVulkanDeviceContext *hwctx = ctx->hwctx;
868 VulkanDevicePriv *p = ctx->internal->priv;
870 /* Set device extension flags */
871 for (int i = 0; i < hwctx->nb_enabled_dev_extensions; i++) {
872 for (int j = 0; j < FF_ARRAY_ELEMS(optional_device_exts); j++) {
873 if (!strcmp(hwctx->enabled_dev_extensions[i],
874 optional_device_exts[j].name)) {
875 p->extensions |= optional_device_exts[j].flag;
881 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &queue_num, NULL);
883 av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
884 return AVERROR_EXTERNAL;
887 #define CHECK_QUEUE(type, n) \
888 if (n >= queue_num) { \
889 av_log(ctx, AV_LOG_ERROR, "Invalid %s queue index %i (device has %i queues)!\n", \
890 type, n, queue_num); \
891 return AVERROR(EINVAL); \
894 CHECK_QUEUE("graphics", hwctx->queue_family_index)
895 CHECK_QUEUE("upload", hwctx->queue_family_tx_index)
896 CHECK_QUEUE("compute", hwctx->queue_family_comp_index)
900 /* Create exec context - if there's something invalid this will error out */
901 err = create_exec_ctx(ctx, &p->cmd, hwctx->queue_family_tx_index);
905 /* Get device capabilities */
906 vkGetPhysicalDeviceMemoryProperties(hwctx->phys_dev, &p->mprops);
911 static int vulkan_device_create(AVHWDeviceContext *ctx, const char *device,
912 AVDictionary *opts, int flags)
914 VulkanDeviceSelection dev_select = { 0 };
915 if (device && device[0]) {
917 dev_select.index = strtol(device, &end, 10);
919 dev_select.index = 0;
920 dev_select.name = device;
924 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
927 static int vulkan_device_derive(AVHWDeviceContext *ctx,
928 AVHWDeviceContext *src_ctx, int flags)
930 av_unused VulkanDeviceSelection dev_select = { 0 };
932 /* If there's only one device on the system, then even if its not covered
933 * by the following checks (e.g. non-PCIe ARM GPU), having an empty
934 * dev_select will mean it'll get picked. */
935 switch(src_ctx->type) {
938 case AV_HWDEVICE_TYPE_VAAPI: {
939 AVVAAPIDeviceContext *src_hwctx = src_ctx->hwctx;
941 const char *vendor = vaQueryVendorString(src_hwctx->display);
943 av_log(ctx, AV_LOG_ERROR, "Unable to get device info from VAAPI!\n");
944 return AVERROR_EXTERNAL;
947 if (strstr(vendor, "Intel"))
948 dev_select.vendor_id = 0x8086;
949 if (strstr(vendor, "AMD"))
950 dev_select.vendor_id = 0x1002;
952 return vulkan_device_create_internal(ctx, &dev_select, NULL, flags);
955 case AV_HWDEVICE_TYPE_DRM: {
956 AVDRMDeviceContext *src_hwctx = src_ctx->hwctx;
958 drmDevice *drm_dev_info;
959 int err = drmGetDevice(src_hwctx->fd, &drm_dev_info);
961 av_log(ctx, AV_LOG_ERROR, "Unable to get device info from DRM fd!\n");
962 return AVERROR_EXTERNAL;
965 if (drm_dev_info->bustype == DRM_BUS_PCI)
966 dev_select.pci_device = drm_dev_info->deviceinfo.pci->device_id;
968 drmFreeDevice(&drm_dev_info);
970 return vulkan_device_create_internal(ctx, &dev_select, NULL, flags);
974 case AV_HWDEVICE_TYPE_CUDA: {
975 AVHWDeviceContext *cuda_cu = src_ctx;
976 AVCUDADeviceContext *src_hwctx = src_ctx->hwctx;
977 AVCUDADeviceContextInternal *cu_internal = src_hwctx->internal;
978 CudaFunctions *cu = cu_internal->cuda_dl;
980 int ret = CHECK_CU(cu->cuDeviceGetUuid((CUuuid *)&dev_select.uuid,
981 cu_internal->cuda_device));
983 av_log(ctx, AV_LOG_ERROR, "Unable to get UUID from CUDA!\n");
984 return AVERROR_EXTERNAL;
987 dev_select.has_uuid = 1;
989 return vulkan_device_create_internal(ctx, &dev_select, NULL, flags);
993 return AVERROR(ENOSYS);
997 static int vulkan_frames_get_constraints(AVHWDeviceContext *ctx,
998 const void *hwconfig,
999 AVHWFramesConstraints *constraints)
1002 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1003 VulkanDevicePriv *p = ctx->internal->priv;
1005 for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
1006 count += pixfmt_is_supported(hwctx, i, p->use_linear_images);
1009 if (p->dev_is_nvidia)
1013 constraints->valid_sw_formats = av_malloc_array(count + 1,
1014 sizeof(enum AVPixelFormat));
1015 if (!constraints->valid_sw_formats)
1016 return AVERROR(ENOMEM);
1019 for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
1020 if (pixfmt_is_supported(hwctx, i, p->use_linear_images))
1021 constraints->valid_sw_formats[count++] = i;
1024 if (p->dev_is_nvidia)
1025 constraints->valid_sw_formats[count++] = AV_PIX_FMT_CUDA;
1027 constraints->valid_sw_formats[count++] = AV_PIX_FMT_NONE;
1029 constraints->min_width = 0;
1030 constraints->min_height = 0;
1031 constraints->max_width = p->props.limits.maxImageDimension2D;
1032 constraints->max_height = p->props.limits.maxImageDimension2D;
1034 constraints->valid_hw_formats = av_malloc_array(2, sizeof(enum AVPixelFormat));
1035 if (!constraints->valid_hw_formats)
1036 return AVERROR(ENOMEM);
1038 constraints->valid_hw_formats[0] = AV_PIX_FMT_VULKAN;
1039 constraints->valid_hw_formats[1] = AV_PIX_FMT_NONE;
1044 static int alloc_mem(AVHWDeviceContext *ctx, VkMemoryRequirements *req,
1045 VkMemoryPropertyFlagBits req_flags, void *alloc_extension,
1046 VkMemoryPropertyFlagBits *mem_flags, VkDeviceMemory *mem)
1050 VulkanDevicePriv *p = ctx->internal->priv;
1051 AVVulkanDeviceContext *dev_hwctx = ctx->hwctx;
1052 VkMemoryAllocateInfo alloc_info = {
1053 .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
1054 .pNext = alloc_extension,
1057 /* Align if we need to */
1058 if (req_flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)
1059 req->size = FFALIGN(req->size, p->props.limits.minMemoryMapAlignment);
1061 alloc_info.allocationSize = req->size;
1063 /* The vulkan spec requires memory types to be sorted in the "optimal"
1064 * order, so the first matching type we find will be the best/fastest one */
1065 for (int i = 0; i < p->mprops.memoryTypeCount; i++) {
1066 /* The memory type must be supported by the requirements (bitfield) */
1067 if (!(req->memoryTypeBits & (1 << i)))
1070 /* The memory type flags must include our properties */
1071 if ((p->mprops.memoryTypes[i].propertyFlags & req_flags) != req_flags)
1074 /* Found a suitable memory type */
1080 av_log(ctx, AV_LOG_ERROR, "No memory type found for flags 0x%x\n",
1082 return AVERROR(EINVAL);
1085 alloc_info.memoryTypeIndex = index;
1087 ret = vkAllocateMemory(dev_hwctx->act_dev, &alloc_info,
1088 dev_hwctx->alloc, mem);
1089 if (ret != VK_SUCCESS) {
1090 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory: %s\n",
1092 return AVERROR(ENOMEM);
1095 *mem_flags |= p->mprops.memoryTypes[index].propertyFlags;
1100 static void vulkan_free_internal(AVVkFrameInternal *internal)
1106 if (internal->cuda_fc_ref) {
1107 AVHWFramesContext *cuda_fc = (AVHWFramesContext *)internal->cuda_fc_ref->data;
1108 int planes = av_pix_fmt_count_planes(cuda_fc->sw_format);
1109 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
1110 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
1111 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
1112 CudaFunctions *cu = cu_internal->cuda_dl;
1114 if (internal->cu_sem)
1115 CHECK_CU(cu->cuDestroyExternalSemaphore(internal->cu_sem));
1117 for (int i = 0; i < planes; i++) {
1118 if (internal->cu_mma[i])
1119 CHECK_CU(cu->cuMipmappedArrayDestroy(internal->cu_mma[i]));
1120 if (internal->ext_mem[i])
1121 CHECK_CU(cu->cuDestroyExternalMemory(internal->ext_mem[i]));
1124 av_buffer_unref(&internal->cuda_fc_ref);
1131 static void vulkan_frame_free(void *opaque, uint8_t *data)
1133 AVVkFrame *f = (AVVkFrame *)data;
1134 AVHWFramesContext *hwfc = opaque;
1135 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1136 int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1138 vulkan_free_internal(f->internal);
1140 for (int i = 0; i < planes; i++) {
1141 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
1142 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
1145 vkDestroySemaphore(hwctx->act_dev, f->sem, hwctx->alloc);
1150 static int alloc_bind_mem(AVHWFramesContext *hwfc, AVVkFrame *f,
1151 void *alloc_pnext, size_t alloc_pnext_stride)
1155 AVHWDeviceContext *ctx = hwfc->device_ctx;
1156 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1157 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { { 0 } };
1159 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1161 for (int i = 0; i < planes; i++) {
1163 VkImageMemoryRequirementsInfo2 req_desc = {
1164 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
1167 VkMemoryDedicatedAllocateInfo ded_alloc = {
1168 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
1169 .pNext = (void *)(((uint8_t *)alloc_pnext) + i*alloc_pnext_stride),
1171 VkMemoryDedicatedRequirements ded_req = {
1172 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
1174 VkMemoryRequirements2 req = {
1175 .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
1179 vkGetImageMemoryRequirements2(hwctx->act_dev, &req_desc, &req);
1181 /* In case the implementation prefers/requires dedicated allocation */
1182 use_ded_mem = ded_req.prefersDedicatedAllocation |
1183 ded_req.requiresDedicatedAllocation;
1185 ded_alloc.image = f->img[i];
1187 /* Allocate memory */
1188 if ((err = alloc_mem(ctx, &req.memoryRequirements,
1189 f->tiling == VK_IMAGE_TILING_LINEAR ?
1190 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT :
1191 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1192 use_ded_mem ? &ded_alloc : (void *)ded_alloc.pNext,
1193 &f->flags, &f->mem[i])))
1196 f->size[i] = req.memoryRequirements.size;
1197 bind_info[i].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
1198 bind_info[i].image = f->img[i];
1199 bind_info[i].memory = f->mem[i];
1202 /* Bind the allocated memory to the images */
1203 ret = vkBindImageMemory2(hwctx->act_dev, planes, bind_info);
1204 if (ret != VK_SUCCESS) {
1205 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
1207 return AVERROR_EXTERNAL;
1215 PREP_MODE_RO_SHADER,
1218 static int prepare_frame(AVHWFramesContext *hwfc, VulkanExecCtx *ectx,
1219 AVVkFrame *frame, enum PrepMode pmode)
1222 VkImageLayout new_layout;
1223 VkAccessFlags new_access;
1224 AVHWDeviceContext *ctx = hwfc->device_ctx;
1225 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1226 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1228 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
1230 VkCommandBufferBeginInfo cmd_start = {
1231 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
1232 .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
1235 VkSubmitInfo s_info = {
1236 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
1237 .commandBufferCount = 1,
1238 .pCommandBuffers = &ectx->buf,
1240 .pSignalSemaphores = &frame->sem,
1241 .signalSemaphoreCount = 1,
1245 case PREP_MODE_WRITE:
1246 new_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
1247 new_access = VK_ACCESS_TRANSFER_WRITE_BIT;
1249 case PREP_MODE_RO_SHADER:
1250 new_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
1251 new_access = VK_ACCESS_TRANSFER_READ_BIT;
1255 ret = vkBeginCommandBuffer(ectx->buf, &cmd_start);
1256 if (ret != VK_SUCCESS)
1257 return AVERROR_EXTERNAL;
1259 /* Change the image layout to something more optimal for writes.
1260 * This also signals the newly created semaphore, making it usable
1261 * for synchronization */
1262 for (int i = 0; i < planes; i++) {
1263 img_bar[i].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1264 img_bar[i].srcAccessMask = 0x0;
1265 img_bar[i].dstAccessMask = new_access;
1266 img_bar[i].oldLayout = frame->layout[i];
1267 img_bar[i].newLayout = new_layout;
1268 img_bar[i].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1269 img_bar[i].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1270 img_bar[i].image = frame->img[i];
1271 img_bar[i].subresourceRange.levelCount = 1;
1272 img_bar[i].subresourceRange.layerCount = 1;
1273 img_bar[i].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1275 frame->layout[i] = img_bar[i].newLayout;
1276 frame->access[i] = img_bar[i].dstAccessMask;
1279 vkCmdPipelineBarrier(ectx->buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
1280 VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
1281 0, NULL, 0, NULL, planes, img_bar);
1283 ret = vkEndCommandBuffer(ectx->buf);
1284 if (ret != VK_SUCCESS)
1285 return AVERROR_EXTERNAL;
1287 ret = vkQueueSubmit(ectx->queue, 1, &s_info, ectx->fence);
1288 if (ret != VK_SUCCESS) {
1289 return AVERROR_EXTERNAL;
1291 vkWaitForFences(hwctx->act_dev, 1, &ectx->fence, VK_TRUE, UINT64_MAX);
1292 vkResetFences(hwctx->act_dev, 1, &ectx->fence);
1298 static int create_frame(AVHWFramesContext *hwfc, AVVkFrame **frame,
1299 VkImageTiling tiling, VkImageUsageFlagBits usage,
1304 AVHWDeviceContext *ctx = hwfc->device_ctx;
1305 VulkanDevicePriv *p = ctx->internal->priv;
1306 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1307 enum AVPixelFormat format = hwfc->sw_format;
1308 const VkFormat *img_fmts = av_vkfmt_from_pixfmt(format);
1309 const int planes = av_pix_fmt_count_planes(format);
1311 VkExportSemaphoreCreateInfo ext_sem_info = {
1312 .sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO,
1313 .handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
1316 VkSemaphoreCreateInfo sem_spawn = {
1317 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1318 .pNext = p->extensions & EXT_EXTERNAL_FD_SEM ? &ext_sem_info : NULL,
1321 AVVkFrame *f = av_vk_frame_alloc();
1323 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1324 return AVERROR(ENOMEM);
1327 /* Create the images */
1328 for (int i = 0; i < planes; i++) {
1329 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
1330 int w = hwfc->width;
1331 int h = hwfc->height;
1332 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
1333 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
1335 VkImageCreateInfo image_create_info = {
1336 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1337 .pNext = create_pnext,
1338 .imageType = VK_IMAGE_TYPE_2D,
1339 .format = img_fmts[i],
1340 .extent.width = p_w,
1341 .extent.height = p_h,
1345 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1347 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1349 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
1350 .samples = VK_SAMPLE_COUNT_1_BIT,
1353 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
1354 hwctx->alloc, &f->img[i]);
1355 if (ret != VK_SUCCESS) {
1356 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1358 err = AVERROR(EINVAL);
1362 f->layout[i] = image_create_info.initialLayout;
1366 /* Create semaphore */
1367 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1368 hwctx->alloc, &f->sem);
1369 if (ret != VK_SUCCESS) {
1370 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1372 return AVERROR_EXTERNAL;
1382 vulkan_frame_free(hwfc, (uint8_t *)f);
1386 /* Checks if an export flag is enabled, and if it is ORs it with *iexp */
1387 static void try_export_flags(AVHWFramesContext *hwfc,
1388 VkExternalMemoryHandleTypeFlags *comp_handle_types,
1389 VkExternalMemoryHandleTypeFlagBits *iexp,
1390 VkExternalMemoryHandleTypeFlagBits exp)
1393 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1394 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1395 VkExternalImageFormatProperties eprops = {
1396 .sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES_KHR,
1398 VkImageFormatProperties2 props = {
1399 .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,
1402 VkPhysicalDeviceExternalImageFormatInfo enext = {
1403 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
1406 VkPhysicalDeviceImageFormatInfo2 pinfo = {
1407 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1408 .pNext = !exp ? NULL : &enext,
1409 .format = av_vkfmt_from_pixfmt(hwfc->sw_format)[0],
1410 .type = VK_IMAGE_TYPE_2D,
1411 .tiling = hwctx->tiling,
1412 .usage = hwctx->usage,
1413 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1416 ret = vkGetPhysicalDeviceImageFormatProperties2(dev_hwctx->phys_dev,
1418 if (ret == VK_SUCCESS) {
1420 *comp_handle_types |= eprops.externalMemoryProperties.compatibleHandleTypes;
1424 static AVBufferRef *vulkan_pool_alloc(void *opaque, int size)
1428 AVBufferRef *avbuf = NULL;
1429 AVHWFramesContext *hwfc = opaque;
1430 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1431 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1432 VkExportMemoryAllocateInfo eminfo[AV_NUM_DATA_POINTERS];
1433 VkExternalMemoryHandleTypeFlags e = 0x0;
1435 VkExternalMemoryImageCreateInfo eiinfo = {
1436 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1437 .pNext = hwctx->create_pnext,
1440 if (p->extensions & EXT_EXTERNAL_FD_MEMORY)
1441 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1442 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT);
1444 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
1445 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1446 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
1448 for (int i = 0; i < av_pix_fmt_count_planes(hwfc->sw_format); i++) {
1449 eminfo[i].sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO;
1450 eminfo[i].pNext = hwctx->alloc_pnext[i];
1451 eminfo[i].handleTypes = e;
1454 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1455 eiinfo.handleTypes ? &eiinfo : NULL);
1459 err = alloc_bind_mem(hwfc, f, eminfo, sizeof(*eminfo));
1463 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_WRITE);
1467 avbuf = av_buffer_create((uint8_t *)f, sizeof(AVVkFrame),
1468 vulkan_frame_free, hwfc, 0);
1475 vulkan_frame_free(hwfc, (uint8_t *)f);
1479 static void vulkan_frames_uninit(AVHWFramesContext *hwfc)
1481 VulkanFramesPriv *fp = hwfc->internal->priv;
1483 free_exec_ctx(hwfc->device_ctx, &fp->cmd);
1486 static int vulkan_frames_init(AVHWFramesContext *hwfc)
1490 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1491 VulkanFramesPriv *fp = hwfc->internal->priv;
1492 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1493 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1498 /* Default pool flags */
1499 hwctx->tiling = hwctx->tiling ? hwctx->tiling : p->use_linear_images ?
1500 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1502 hwctx->usage |= DEFAULT_USAGE_FLAGS;
1504 err = create_exec_ctx(hwfc->device_ctx, &fp->cmd,
1505 dev_hwctx->queue_family_tx_index);
1509 /* Test to see if allocation will fail */
1510 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1511 hwctx->create_pnext);
1513 free_exec_ctx(hwfc->device_ctx, &p->cmd);
1517 vulkan_frame_free(hwfc, (uint8_t *)f);
1519 hwfc->internal->pool_internal = av_buffer_pool_init2(sizeof(AVVkFrame),
1520 hwfc, vulkan_pool_alloc,
1522 if (!hwfc->internal->pool_internal) {
1523 free_exec_ctx(hwfc->device_ctx, &p->cmd);
1524 return AVERROR(ENOMEM);
1530 static int vulkan_get_buffer(AVHWFramesContext *hwfc, AVFrame *frame)
1532 frame->buf[0] = av_buffer_pool_get(hwfc->pool);
1534 return AVERROR(ENOMEM);
1536 frame->data[0] = frame->buf[0]->data;
1537 frame->format = AV_PIX_FMT_VULKAN;
1538 frame->width = hwfc->width;
1539 frame->height = hwfc->height;
1544 static int vulkan_transfer_get_formats(AVHWFramesContext *hwfc,
1545 enum AVHWFrameTransferDirection dir,
1546 enum AVPixelFormat **formats)
1548 enum AVPixelFormat *fmts = av_malloc_array(2, sizeof(*fmts));
1550 return AVERROR(ENOMEM);
1552 fmts[0] = hwfc->sw_format;
1553 fmts[1] = AV_PIX_FMT_NONE;
1559 typedef struct VulkanMapping {
1564 static void vulkan_unmap_frame(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1566 VulkanMapping *map = hwmap->priv;
1567 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1568 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1570 /* Check if buffer needs flushing */
1571 if ((map->flags & AV_HWFRAME_MAP_WRITE) &&
1572 !(map->frame->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1574 VkMappedMemoryRange flush_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1576 for (int i = 0; i < planes; i++) {
1577 flush_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1578 flush_ranges[i].memory = map->frame->mem[i];
1579 flush_ranges[i].size = VK_WHOLE_SIZE;
1582 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, planes,
1584 if (ret != VK_SUCCESS) {
1585 av_log(hwfc, AV_LOG_ERROR, "Failed to flush memory: %s\n",
1590 for (int i = 0; i < planes; i++)
1591 vkUnmapMemory(hwctx->act_dev, map->frame->mem[i]);
1596 static int vulkan_map_frame_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
1597 const AVFrame *src, int flags)
1600 int err, mapped_mem_count = 0;
1601 AVVkFrame *f = (AVVkFrame *)src->data[0];
1602 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1603 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1605 VulkanMapping *map = av_mallocz(sizeof(VulkanMapping));
1607 return AVERROR(EINVAL);
1609 if (src->format != AV_PIX_FMT_VULKAN) {
1610 av_log(hwfc, AV_LOG_ERROR, "Cannot map from pixel format %s!\n",
1611 av_get_pix_fmt_name(src->format));
1612 err = AVERROR(EINVAL);
1616 if (!(f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ||
1617 !(f->tiling == VK_IMAGE_TILING_LINEAR)) {
1618 av_log(hwfc, AV_LOG_ERROR, "Unable to map frame, not host visible "
1620 err = AVERROR(EINVAL);
1624 dst->width = src->width;
1625 dst->height = src->height;
1627 for (int i = 0; i < planes; i++) {
1628 ret = vkMapMemory(hwctx->act_dev, f->mem[i], 0,
1629 VK_WHOLE_SIZE, 0, (void **)&dst->data[i]);
1630 if (ret != VK_SUCCESS) {
1631 av_log(hwfc, AV_LOG_ERROR, "Failed to map image memory: %s\n",
1633 err = AVERROR_EXTERNAL;
1639 /* Check if the memory contents matter */
1640 if (((flags & AV_HWFRAME_MAP_READ) || !(flags & AV_HWFRAME_MAP_OVERWRITE)) &&
1641 !(f->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1642 VkMappedMemoryRange map_mem_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1643 for (int i = 0; i < planes; i++) {
1644 map_mem_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1645 map_mem_ranges[i].size = VK_WHOLE_SIZE;
1646 map_mem_ranges[i].memory = f->mem[i];
1649 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, planes,
1651 if (ret != VK_SUCCESS) {
1652 av_log(hwfc, AV_LOG_ERROR, "Failed to invalidate memory: %s\n",
1654 err = AVERROR_EXTERNAL;
1659 for (int i = 0; i < planes; i++) {
1660 VkImageSubresource sub = {
1661 .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
1663 VkSubresourceLayout layout;
1664 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
1665 dst->linesize[i] = layout.rowPitch;
1671 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src,
1672 &vulkan_unmap_frame, map);
1679 for (int i = 0; i < mapped_mem_count; i++)
1680 vkUnmapMemory(hwctx->act_dev, f->mem[i]);
1687 static void vulkan_unmap_from(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1689 VulkanMapping *map = hwmap->priv;
1690 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1691 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1693 for (int i = 0; i < planes; i++) {
1694 vkDestroyImage(hwctx->act_dev, map->frame->img[i], hwctx->alloc);
1695 vkFreeMemory(hwctx->act_dev, map->frame->mem[i], hwctx->alloc);
1698 vkDestroySemaphore(hwctx->act_dev, map->frame->sem, hwctx->alloc);
1700 av_freep(&map->frame);
1703 static const struct {
1704 uint32_t drm_fourcc;
1706 } vulkan_drm_format_map[] = {
1707 { DRM_FORMAT_R8, VK_FORMAT_R8_UNORM },
1708 { DRM_FORMAT_R16, VK_FORMAT_R16_UNORM },
1709 { DRM_FORMAT_GR88, VK_FORMAT_R8G8_UNORM },
1710 { DRM_FORMAT_RG88, VK_FORMAT_R8G8_UNORM },
1711 { DRM_FORMAT_GR1616, VK_FORMAT_R16G16_UNORM },
1712 { DRM_FORMAT_RG1616, VK_FORMAT_R16G16_UNORM },
1713 { DRM_FORMAT_ARGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1714 { DRM_FORMAT_XRGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1715 { DRM_FORMAT_ABGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1716 { DRM_FORMAT_XBGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1719 static inline VkFormat drm_to_vulkan_fmt(uint32_t drm_fourcc)
1721 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
1722 if (vulkan_drm_format_map[i].drm_fourcc == drm_fourcc)
1723 return vulkan_drm_format_map[i].vk_format;
1724 return VK_FORMAT_UNDEFINED;
1727 static int vulkan_map_from_drm_frame_desc(AVHWFramesContext *hwfc, AVVkFrame **frame,
1728 AVDRMFrameDescriptor *desc)
1733 int bind_counts = 0;
1734 AVHWDeviceContext *ctx = hwfc->device_ctx;
1735 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1736 VulkanDevicePriv *p = ctx->internal->priv;
1737 const AVPixFmtDescriptor *fmt_desc = av_pix_fmt_desc_get(hwfc->sw_format);
1738 const int has_modifiers = p->extensions & EXT_DRM_MODIFIER_FLAGS;
1739 VkSubresourceLayout plane_data[AV_NUM_DATA_POINTERS] = { 0 };
1740 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { 0 };
1741 VkBindImagePlaneMemoryInfo plane_info[AV_NUM_DATA_POINTERS] = { 0 };
1742 VkExternalMemoryHandleTypeFlagBits htype = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
1743 VkSemaphoreCreateInfo sem_spawn = {
1744 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1747 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdPropertiesKHR);
1749 for (int i = 0; i < desc->nb_layers; i++) {
1750 if (drm_to_vulkan_fmt(desc->layers[i].format) == VK_FORMAT_UNDEFINED) {
1751 av_log(ctx, AV_LOG_ERROR, "Unsupported DMABUF layer format %#08x!\n",
1752 desc->layers[i].format);
1753 return AVERROR(EINVAL);
1757 if (!(f = av_vk_frame_alloc())) {
1758 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1759 err = AVERROR(ENOMEM);
1763 for (int i = 0; i < desc->nb_objects; i++) {
1764 VkMemoryFdPropertiesKHR fdmp = {
1765 .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,
1767 VkMemoryRequirements req = {
1768 .size = desc->objects[i].size,
1770 VkImportMemoryFdInfoKHR idesc = {
1771 .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
1772 .handleType = htype,
1773 .fd = dup(desc->objects[i].fd),
1776 ret = pfn_vkGetMemoryFdPropertiesKHR(hwctx->act_dev, htype,
1778 if (ret != VK_SUCCESS) {
1779 av_log(hwfc, AV_LOG_ERROR, "Failed to get FD properties: %s\n",
1781 err = AVERROR_EXTERNAL;
1786 req.memoryTypeBits = fdmp.memoryTypeBits;
1788 err = alloc_mem(ctx, &req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1789 &idesc, &f->flags, &f->mem[i]);
1795 f->size[i] = desc->objects[i].size;
1798 f->tiling = has_modifiers ? VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT :
1799 desc->objects[0].format_modifier == DRM_FORMAT_MOD_LINEAR ?
1800 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1802 for (int i = 0; i < desc->nb_layers; i++) {
1803 const int planes = desc->layers[i].nb_planes;
1804 const int signal_p = has_modifiers && (planes > 1);
1806 VkImageDrmFormatModifierExplicitCreateInfoEXT drm_info = {
1807 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
1808 .drmFormatModifier = desc->objects[0].format_modifier,
1809 .drmFormatModifierPlaneCount = planes,
1810 .pPlaneLayouts = (const VkSubresourceLayout *)&plane_data,
1813 VkExternalMemoryImageCreateInfo einfo = {
1814 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1815 .pNext = has_modifiers ? &drm_info : NULL,
1816 .handleTypes = htype,
1819 const int p_w = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, fmt_desc->log2_chroma_w) : hwfc->width;
1820 const int p_h = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, fmt_desc->log2_chroma_h) : hwfc->height;
1822 VkImageCreateInfo image_create_info = {
1823 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1825 .imageType = VK_IMAGE_TYPE_2D,
1826 .format = drm_to_vulkan_fmt(desc->layers[i].format),
1827 .extent.width = p_w,
1828 .extent.height = p_h,
1832 .flags = VK_IMAGE_CREATE_ALIAS_BIT |
1833 (signal_p ? VK_IMAGE_CREATE_DISJOINT_BIT : 0x0),
1834 .tiling = f->tiling,
1835 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, /* specs say so */
1836 .usage = DEFAULT_USAGE_FLAGS,
1837 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
1838 .samples = VK_SAMPLE_COUNT_1_BIT,
1841 for (int j = 0; j < planes; j++) {
1842 plane_data[j].offset = desc->layers[i].planes[j].offset;
1843 plane_data[j].rowPitch = desc->layers[i].planes[j].pitch;
1844 plane_data[j].size = 0; /* The specs say so for all 3 */
1845 plane_data[j].arrayPitch = 0;
1846 plane_data[j].depthPitch = 0;
1850 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
1851 hwctx->alloc, &f->img[i]);
1852 if (ret != VK_SUCCESS) {
1853 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1855 err = AVERROR(EINVAL);
1859 f->layout[i] = image_create_info.initialLayout;
1862 for (int j = 0; j < planes; j++) {
1863 VkImageAspectFlagBits aspect = j == 0 ? VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
1864 j == 1 ? VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT :
1865 VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT;
1867 plane_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO;
1868 plane_info[bind_counts].planeAspect = aspect;
1870 bind_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
1871 bind_info[bind_counts].pNext = signal_p ? &plane_info[bind_counts] : NULL;
1872 bind_info[bind_counts].image = f->img[i];
1873 bind_info[bind_counts].memory = f->mem[desc->layers[i].planes[j].object_index];
1874 bind_info[bind_counts].memoryOffset = desc->layers[i].planes[j].offset;
1879 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1880 hwctx->alloc, &f->sem);
1881 if (ret != VK_SUCCESS) {
1882 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1884 return AVERROR_EXTERNAL;
1887 /* We'd import a semaphore onto the one we created using
1888 * vkImportSemaphoreFdKHR but unfortunately neither DRM nor VAAPI
1889 * offer us anything we could import and sync with, so instead
1890 * just signal the semaphore we created. */
1892 /* Bind the allocated memory to the images */
1893 ret = vkBindImageMemory2(hwctx->act_dev, bind_counts, bind_info);
1894 if (ret != VK_SUCCESS) {
1895 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
1897 return AVERROR_EXTERNAL;
1900 /* NOTE: This is completely uneccesary and unneeded once we can import
1901 * semaphores from DRM. Otherwise we have to activate the semaphores.
1902 * We're reusing the exec context that's also used for uploads/downloads. */
1903 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_RO_SHADER);
1912 for (int i = 0; i < desc->nb_layers; i++)
1913 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
1914 for (int i = 0; i < desc->nb_objects; i++)
1915 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
1916 vkDestroySemaphore(hwctx->act_dev, f->sem, hwctx->alloc);
1923 static int vulkan_map_from_drm(AVHWFramesContext *hwfc, AVFrame *dst,
1924 const AVFrame *src, int flags)
1928 VulkanMapping *map = NULL;
1930 err = vulkan_map_from_drm_frame_desc(hwfc, &f,
1931 (AVDRMFrameDescriptor *)src->data[0]);
1935 /* The unmapping function will free this */
1936 dst->data[0] = (uint8_t *)f;
1937 dst->width = src->width;
1938 dst->height = src->height;
1940 map = av_mallocz(sizeof(VulkanMapping));
1947 err = ff_hwframe_map_create(dst->hw_frames_ctx, dst, src,
1948 &vulkan_unmap_from, map);
1952 av_log(hwfc, AV_LOG_DEBUG, "Mapped DRM object to Vulkan!\n");
1957 vulkan_frame_free(hwfc->device_ctx->hwctx, (uint8_t *)f);
1963 static int vulkan_map_from_vaapi(AVHWFramesContext *dst_fc,
1964 AVFrame *dst, const AVFrame *src,
1968 AVFrame *tmp = av_frame_alloc();
1969 AVHWFramesContext *vaapi_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
1970 AVVAAPIDeviceContext *vaapi_ctx = vaapi_fc->device_ctx->hwctx;
1971 VASurfaceID surface_id = (VASurfaceID)(uintptr_t)src->data[3];
1974 return AVERROR(ENOMEM);
1976 /* We have to sync since like the previous comment said, no semaphores */
1977 vaSyncSurface(vaapi_ctx->display, surface_id);
1979 tmp->format = AV_PIX_FMT_DRM_PRIME;
1981 err = av_hwframe_map(tmp, src, flags);
1985 err = vulkan_map_from_drm(dst_fc, dst, tmp, flags);
1989 err = ff_hwframe_map_replace(dst, src);
1992 av_frame_free(&tmp);
1999 static int vulkan_export_to_cuda(AVHWFramesContext *hwfc,
2000 AVBufferRef *cuda_hwfc,
2001 const AVFrame *frame)
2006 AVVkFrameInternal *dst_int;
2007 AVHWDeviceContext *ctx = hwfc->device_ctx;
2008 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2009 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2010 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2011 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2012 VK_LOAD_PFN(hwctx->inst, vkGetSemaphoreFdKHR);
2014 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)cuda_hwfc->data;
2015 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2016 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2017 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2018 CudaFunctions *cu = cu_internal->cuda_dl;
2019 CUarray_format cufmt = desc->comp[0].depth > 8 ? CU_AD_FORMAT_UNSIGNED_INT16 :
2020 CU_AD_FORMAT_UNSIGNED_INT8;
2022 dst_f = (AVVkFrame *)frame->data[0];
2024 dst_int = dst_f->internal;
2025 if (!dst_int || !dst_int->cuda_fc_ref) {
2026 VkSemaphoreGetFdInfoKHR sem_export = {
2027 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR,
2028 .semaphore = dst_f->sem,
2029 .handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
2031 CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC ext_sem_desc = {
2032 .type = CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD,
2035 if (!dst_f->internal)
2036 dst_f->internal = dst_int = av_mallocz(sizeof(*dst_f->internal));
2039 err = AVERROR(ENOMEM);
2043 dst_int->cuda_fc_ref = av_buffer_ref(cuda_hwfc);
2044 if (!dst_int->cuda_fc_ref) {
2045 err = AVERROR(ENOMEM);
2049 for (int i = 0; i < planes; i++) {
2050 CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC tex_desc = {
2053 .Width = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2055 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2059 .NumChannels = 1 + ((planes == 2) && i),
2064 CUDA_EXTERNAL_MEMORY_HANDLE_DESC ext_desc = {
2065 .type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD,
2066 .size = dst_f->size[i],
2068 VkMemoryGetFdInfoKHR export_info = {
2069 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2070 .memory = dst_f->mem[i],
2071 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR,
2074 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2075 &ext_desc.handle.fd);
2076 if (ret != VK_SUCCESS) {
2077 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2078 err = AVERROR_EXTERNAL;
2082 ret = CHECK_CU(cu->cuImportExternalMemory(&dst_int->ext_mem[i], &ext_desc));
2084 err = AVERROR_EXTERNAL;
2088 ret = CHECK_CU(cu->cuExternalMemoryGetMappedMipmappedArray(&dst_int->cu_mma[i],
2089 dst_int->ext_mem[i],
2092 err = AVERROR_EXTERNAL;
2096 ret = CHECK_CU(cu->cuMipmappedArrayGetLevel(&dst_int->cu_array[i],
2097 dst_int->cu_mma[i], 0));
2099 err = AVERROR_EXTERNAL;
2104 ret = pfn_vkGetSemaphoreFdKHR(hwctx->act_dev, &sem_export,
2105 &ext_sem_desc.handle.fd);
2106 if (ret != VK_SUCCESS) {
2107 av_log(ctx, AV_LOG_ERROR, "Failed to export semaphore: %s\n",
2109 err = AVERROR_EXTERNAL;
2113 ret = CHECK_CU(cu->cuImportExternalSemaphore(&dst_int->cu_sem,
2116 err = AVERROR_EXTERNAL;
2127 static int vulkan_transfer_data_from_cuda(AVHWFramesContext *hwfc,
2128 AVFrame *dst, const AVFrame *src)
2134 AVVkFrameInternal *dst_int;
2135 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2136 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2138 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2139 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2140 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2141 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2142 CudaFunctions *cu = cu_internal->cuda_dl;
2143 CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS s_w_par = { 0 };
2144 CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS s_s_par = { 0 };
2146 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2148 err = AVERROR_EXTERNAL;
2152 dst_f = (AVVkFrame *)dst->data[0];
2154 ret = vulkan_export_to_cuda(hwfc, src->hw_frames_ctx, dst);
2158 dst_int = dst_f->internal;
2160 ret = CHECK_CU(cu->cuWaitExternalSemaphoresAsync(&dst_int->cu_sem, &s_w_par,
2161 1, cuda_dev->stream));
2163 err = AVERROR_EXTERNAL;
2167 for (int i = 0; i < planes; i++) {
2168 CUDA_MEMCPY2D cpy = {
2169 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
2170 .srcDevice = (CUdeviceptr)src->data[i],
2171 .srcPitch = src->linesize[i],
2174 .dstMemoryType = CU_MEMORYTYPE_ARRAY,
2175 .dstArray = dst_int->cu_array[i],
2176 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2177 : hwfc->width) * desc->comp[i].step,
2178 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2182 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2184 err = AVERROR_EXTERNAL;
2189 ret = CHECK_CU(cu->cuSignalExternalSemaphoresAsync(&dst_int->cu_sem, &s_s_par,
2190 1, cuda_dev->stream));
2192 err = AVERROR_EXTERNAL;
2196 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2198 av_log(hwfc, AV_LOG_VERBOSE, "Transfered CUDA image to Vulkan!\n");
2203 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2204 vulkan_free_internal(dst_int);
2205 dst_f->internal = NULL;
2206 av_buffer_unref(&dst->buf[0]);
2211 static int vulkan_map_to(AVHWFramesContext *hwfc, AVFrame *dst,
2212 const AVFrame *src, int flags)
2214 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2216 switch (src->format) {
2219 case AV_PIX_FMT_VAAPI:
2220 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2221 return vulkan_map_from_vaapi(hwfc, dst, src, flags);
2223 case AV_PIX_FMT_DRM_PRIME:
2224 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2225 return vulkan_map_from_drm(hwfc, dst, src, flags);
2228 return AVERROR(ENOSYS);
2233 typedef struct VulkanDRMMapping {
2234 AVDRMFrameDescriptor drm_desc;
2238 static void vulkan_unmap_to_drm(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
2240 AVDRMFrameDescriptor *drm_desc = hwmap->priv;
2242 for (int i = 0; i < drm_desc->nb_objects; i++)
2243 close(drm_desc->objects[i].fd);
2248 static inline uint32_t vulkan_fmt_to_drm(VkFormat vkfmt)
2250 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
2251 if (vulkan_drm_format_map[i].vk_format == vkfmt)
2252 return vulkan_drm_format_map[i].drm_fourcc;
2253 return DRM_FORMAT_INVALID;
2256 static int vulkan_map_to_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2257 const AVFrame *src, int flags)
2261 AVVkFrame *f = (AVVkFrame *)src->data[0];
2262 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2263 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
2264 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2265 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2266 VkImageDrmFormatModifierPropertiesEXT drm_mod = {
2267 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT,
2270 AVDRMFrameDescriptor *drm_desc = av_mallocz(sizeof(*drm_desc));
2272 return AVERROR(ENOMEM);
2274 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src, &vulkan_unmap_to_drm, drm_desc);
2278 if (p->extensions & EXT_DRM_MODIFIER_FLAGS) {
2279 VK_LOAD_PFN(hwctx->inst, vkGetImageDrmFormatModifierPropertiesEXT);
2280 ret = pfn_vkGetImageDrmFormatModifierPropertiesEXT(hwctx->act_dev, f->img[0],
2282 if (ret != VK_SUCCESS) {
2283 av_log(hwfc, AV_LOG_ERROR, "Failed to retrieve DRM format modifier!\n");
2284 err = AVERROR_EXTERNAL;
2289 for (int i = 0; (i < planes) && (f->mem[i]); i++) {
2290 VkMemoryGetFdInfoKHR export_info = {
2291 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2292 .memory = f->mem[i],
2293 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,
2296 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2297 &drm_desc->objects[i].fd);
2298 if (ret != VK_SUCCESS) {
2299 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2300 err = AVERROR_EXTERNAL;
2304 drm_desc->nb_objects++;
2305 drm_desc->objects[i].size = f->size[i];
2306 drm_desc->objects[i].format_modifier = drm_mod.drmFormatModifier;
2309 drm_desc->nb_layers = planes;
2310 for (int i = 0; i < drm_desc->nb_layers; i++) {
2311 VkSubresourceLayout layout;
2312 VkImageSubresource sub = {
2313 .aspectMask = p->extensions & EXT_DRM_MODIFIER_FLAGS ?
2314 VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2315 VK_IMAGE_ASPECT_COLOR_BIT,
2317 VkFormat plane_vkfmt = av_vkfmt_from_pixfmt(hwfc->sw_format)[i];
2319 drm_desc->layers[i].format = vulkan_fmt_to_drm(plane_vkfmt);
2320 drm_desc->layers[i].nb_planes = 1;
2322 if (drm_desc->layers[i].format == DRM_FORMAT_INVALID) {
2323 av_log(hwfc, AV_LOG_ERROR, "Cannot map to DRM layer, unsupported!\n");
2324 err = AVERROR_PATCHWELCOME;
2328 drm_desc->layers[i].planes[0].object_index = FFMIN(i, drm_desc->nb_objects - 1);
2330 if (f->tiling != VK_IMAGE_TILING_OPTIMAL)
2333 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
2334 drm_desc->layers[i].planes[0].offset = layout.offset;
2335 drm_desc->layers[i].planes[0].pitch = layout.rowPitch;
2338 dst->width = src->width;
2339 dst->height = src->height;
2340 dst->data[0] = (uint8_t *)drm_desc;
2342 av_log(hwfc, AV_LOG_VERBOSE, "Mapped AVVkFrame to a DRM object!\n");
2352 static int vulkan_map_to_vaapi(AVHWFramesContext *hwfc, AVFrame *dst,
2353 const AVFrame *src, int flags)
2356 AVFrame *tmp = av_frame_alloc();
2358 return AVERROR(ENOMEM);
2360 tmp->format = AV_PIX_FMT_DRM_PRIME;
2362 err = vulkan_map_to_drm(hwfc, tmp, src, flags);
2366 err = av_hwframe_map(dst, tmp, flags);
2370 err = ff_hwframe_map_replace(dst, src);
2373 av_frame_free(&tmp);
2379 static int vulkan_map_from(AVHWFramesContext *hwfc, AVFrame *dst,
2380 const AVFrame *src, int flags)
2382 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2384 switch (dst->format) {
2386 case AV_PIX_FMT_DRM_PRIME:
2387 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2388 return vulkan_map_to_drm(hwfc, dst, src, flags);
2390 case AV_PIX_FMT_VAAPI:
2391 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2392 return vulkan_map_to_vaapi(hwfc, dst, src, flags);
2396 return vulkan_map_frame_to_mem(hwfc, dst, src, flags);
2400 typedef struct ImageBuffer {
2403 VkMemoryPropertyFlagBits flags;
2406 static void free_buf(AVHWDeviceContext *ctx, ImageBuffer *buf)
2408 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2412 vkDestroyBuffer(hwctx->act_dev, buf->buf, hwctx->alloc);
2413 vkFreeMemory(hwctx->act_dev, buf->mem, hwctx->alloc);
2416 static int create_buf(AVHWDeviceContext *ctx, ImageBuffer *buf, int height,
2417 int *stride, VkBufferUsageFlags usage,
2418 VkMemoryPropertyFlagBits flags, void *create_pnext,
2423 VkMemoryRequirements req;
2424 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2425 VulkanDevicePriv *p = ctx->internal->priv;
2427 VkBufferCreateInfo buf_spawn = {
2428 .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
2429 .pNext = create_pnext,
2431 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
2434 *stride = FFALIGN(*stride, p->props.limits.optimalBufferCopyRowPitchAlignment);
2435 buf_spawn.size = height*(*stride);
2437 ret = vkCreateBuffer(hwctx->act_dev, &buf_spawn, NULL, &buf->buf);
2438 if (ret != VK_SUCCESS) {
2439 av_log(ctx, AV_LOG_ERROR, "Failed to create buffer: %s\n",
2441 return AVERROR_EXTERNAL;
2444 vkGetBufferMemoryRequirements(hwctx->act_dev, buf->buf, &req);
2446 err = alloc_mem(ctx, &req, flags, alloc_pnext, &buf->flags, &buf->mem);
2450 ret = vkBindBufferMemory(hwctx->act_dev, buf->buf, buf->mem, 0);
2451 if (ret != VK_SUCCESS) {
2452 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory to buffer: %s\n",
2455 return AVERROR_EXTERNAL;
2461 static int map_buffers(AVHWDeviceContext *ctx, ImageBuffer *buf, uint8_t *mem[],
2462 int nb_buffers, int invalidate)
2465 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2466 VkMappedMemoryRange invalidate_ctx[AV_NUM_DATA_POINTERS];
2467 int invalidate_count = 0;
2469 for (int i = 0; i < nb_buffers; i++) {
2470 ret = vkMapMemory(hwctx->act_dev, buf[i].mem, 0,
2471 VK_WHOLE_SIZE, 0, (void **)&mem[i]);
2472 if (ret != VK_SUCCESS) {
2473 av_log(ctx, AV_LOG_ERROR, "Failed to map buffer memory: %s\n",
2475 return AVERROR_EXTERNAL;
2482 for (int i = 0; i < nb_buffers; i++) {
2483 const VkMappedMemoryRange ival_buf = {
2484 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2485 .memory = buf[i].mem,
2486 .size = VK_WHOLE_SIZE,
2488 if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2490 invalidate_ctx[invalidate_count++] = ival_buf;
2493 if (invalidate_count) {
2494 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, invalidate_count,
2496 if (ret != VK_SUCCESS)
2497 av_log(ctx, AV_LOG_WARNING, "Failed to invalidate memory: %s\n",
2504 static int unmap_buffers(AVHWDeviceContext *ctx, ImageBuffer *buf,
2505 int nb_buffers, int flush)
2509 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2510 VkMappedMemoryRange flush_ctx[AV_NUM_DATA_POINTERS];
2511 int flush_count = 0;
2514 for (int i = 0; i < nb_buffers; i++) {
2515 const VkMappedMemoryRange flush_buf = {
2516 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2517 .memory = buf[i].mem,
2518 .size = VK_WHOLE_SIZE,
2520 if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2522 flush_ctx[flush_count++] = flush_buf;
2527 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, flush_count, flush_ctx);
2528 if (ret != VK_SUCCESS) {
2529 av_log(ctx, AV_LOG_ERROR, "Failed to flush memory: %s\n",
2531 err = AVERROR_EXTERNAL; /* We still want to try to unmap them */
2535 for (int i = 0; i < nb_buffers; i++)
2536 vkUnmapMemory(hwctx->act_dev, buf[i].mem);
2541 static int transfer_image_buf(AVHWDeviceContext *ctx, AVVkFrame *frame,
2542 ImageBuffer *buffer, const int *buf_stride, int w,
2543 int h, enum AVPixelFormat pix_fmt, int to_buf)
2546 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2547 VulkanDevicePriv *s = ctx->internal->priv;
2550 VkPipelineStageFlagBits sem_wait_dst[AV_NUM_DATA_POINTERS];
2552 const int planes = av_pix_fmt_count_planes(pix_fmt);
2553 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2555 VkCommandBufferBeginInfo cmd_start = {
2556 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
2557 .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
2560 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
2562 VkSubmitInfo s_info = {
2563 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
2564 .commandBufferCount = 1,
2565 .pCommandBuffers = &s->cmd.buf,
2566 .pSignalSemaphores = &frame->sem,
2567 .pWaitSemaphores = &frame->sem,
2568 .pWaitDstStageMask = sem_wait_dst,
2569 .signalSemaphoreCount = 1,
2570 .waitSemaphoreCount = 1,
2573 ret = vkBeginCommandBuffer(s->cmd.buf, &cmd_start);
2574 if (ret != VK_SUCCESS) {
2575 av_log(ctx, AV_LOG_ERROR, "Unable to init command buffer: %s\n",
2577 return AVERROR_EXTERNAL;
2580 /* Change the image layout to something more optimal for transfers */
2581 for (int i = 0; i < planes; i++) {
2582 VkImageLayout new_layout = to_buf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL :
2583 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
2584 VkAccessFlags new_access = to_buf ? VK_ACCESS_TRANSFER_READ_BIT :
2585 VK_ACCESS_TRANSFER_WRITE_BIT;
2587 sem_wait_dst[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
2589 /* If the layout matches and we have read access skip the barrier */
2590 if ((frame->layout[i] == new_layout) && (frame->access[i] & new_access))
2593 img_bar[bar_num].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
2594 img_bar[bar_num].srcAccessMask = 0x0;
2595 img_bar[bar_num].dstAccessMask = new_access;
2596 img_bar[bar_num].oldLayout = frame->layout[i];
2597 img_bar[bar_num].newLayout = new_layout;
2598 img_bar[bar_num].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2599 img_bar[bar_num].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2600 img_bar[bar_num].image = frame->img[i];
2601 img_bar[bar_num].subresourceRange.levelCount = 1;
2602 img_bar[bar_num].subresourceRange.layerCount = 1;
2603 img_bar[bar_num].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2605 frame->layout[i] = img_bar[bar_num].newLayout;
2606 frame->access[i] = img_bar[bar_num].dstAccessMask;
2612 vkCmdPipelineBarrier(s->cmd.buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
2613 VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
2614 0, NULL, 0, NULL, bar_num, img_bar);
2616 /* Schedule a copy for each plane */
2617 for (int i = 0; i < planes; i++) {
2618 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
2619 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
2620 VkBufferImageCopy buf_reg = {
2622 /* Buffer stride isn't in bytes, it's in samples, the implementation
2623 * uses the image's VkFormat to know how many bytes per sample
2624 * the buffer has. So we have to convert by dividing. Stupid.
2625 * Won't work with YUVA or other planar formats with alpha. */
2626 .bufferRowLength = buf_stride[i] / desc->comp[i].step,
2627 .bufferImageHeight = p_h,
2628 .imageSubresource.layerCount = 1,
2629 .imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
2630 .imageOffset = { 0, 0, 0, },
2631 .imageExtent = { p_w, p_h, 1, },
2635 vkCmdCopyImageToBuffer(s->cmd.buf, frame->img[i], frame->layout[i],
2636 buffer[i].buf, 1, &buf_reg);
2638 vkCmdCopyBufferToImage(s->cmd.buf, buffer[i].buf, frame->img[i],
2639 frame->layout[i], 1, &buf_reg);
2642 ret = vkEndCommandBuffer(s->cmd.buf);
2643 if (ret != VK_SUCCESS) {
2644 av_log(ctx, AV_LOG_ERROR, "Unable to finish command buffer: %s\n",
2646 return AVERROR_EXTERNAL;
2649 /* Wait for the download/upload to finish if uploading, otherwise the
2650 * semaphore will take care of synchronization when uploading */
2651 ret = vkQueueSubmit(s->cmd.queue, 1, &s_info, s->cmd.fence);
2652 if (ret != VK_SUCCESS) {
2653 av_log(ctx, AV_LOG_ERROR, "Unable to submit command buffer: %s\n",
2655 return AVERROR_EXTERNAL;
2657 vkWaitForFences(hwctx->act_dev, 1, &s->cmd.fence, VK_TRUE, UINT64_MAX);
2658 vkResetFences(hwctx->act_dev, 1, &s->cmd.fence);
2664 /* Technically we can use VK_EXT_external_memory_host to upload and download,
2665 * however the alignment requirements make this unfeasible as both the pointer
2666 * and the size of each plane need to be aligned to the minimum alignment
2667 * requirement, which on all current implementations (anv, radv) is 4096.
2668 * If the requirement gets relaxed (unlikely) this can easily be implemented. */
2669 static int vulkan_transfer_data_from_mem(AVHWFramesContext *hwfc, AVFrame *dst,
2674 AVVkFrame *f = (AVVkFrame *)dst->data[0];
2675 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
2676 ImageBuffer buf[AV_NUM_DATA_POINTERS] = { { 0 } };
2677 const int planes = av_pix_fmt_count_planes(src->format);
2678 int log2_chroma = av_pix_fmt_desc_get(src->format)->log2_chroma_h;
2680 if ((src->format != AV_PIX_FMT_NONE && !av_vkfmt_from_pixfmt(src->format))) {
2681 av_log(hwfc, AV_LOG_ERROR, "Unsupported source pixel format!\n");
2682 return AVERROR(EINVAL);
2685 if (src->width > hwfc->width || src->height > hwfc->height)
2686 return AVERROR(EINVAL);
2688 /* For linear, host visiable images */
2689 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
2690 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
2691 AVFrame *map = av_frame_alloc();
2693 return AVERROR(ENOMEM);
2694 map->format = src->format;
2696 err = vulkan_map_frame_to_mem(hwfc, map, dst, AV_HWFRAME_MAP_WRITE);
2700 err = av_frame_copy(map, src);
2701 av_frame_free(&map);
2705 /* Create buffers */
2706 for (int i = 0; i < planes; i++) {
2707 int h = src->height;
2708 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
2710 tmp.linesize[i] = FFABS(src->linesize[i]);
2711 err = create_buf(dev_ctx, &buf[i], p_height,
2712 &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
2713 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
2718 /* Map, copy image to buffer, unmap */
2719 if ((err = map_buffers(dev_ctx, buf, tmp.data, planes, 0)))
2722 av_image_copy(tmp.data, tmp.linesize, (const uint8_t **)src->data,
2723 src->linesize, src->format, src->width, src->height);
2725 if ((err = unmap_buffers(dev_ctx, buf, planes, 1)))
2728 /* Copy buffers to image */
2729 err = transfer_image_buf(dev_ctx, f, buf, tmp.linesize,
2730 src->width, src->height, src->format, 0);
2733 for (int i = 0; i < planes; i++)
2734 free_buf(dev_ctx, &buf[i]);
2739 static int vulkan_transfer_data_to(AVHWFramesContext *hwfc, AVFrame *dst,
2742 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2744 switch (src->format) {
2746 case AV_PIX_FMT_CUDA:
2747 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
2748 (p->extensions & EXT_EXTERNAL_FD_SEM))
2749 return vulkan_transfer_data_from_cuda(hwfc, dst, src);
2752 if (src->hw_frames_ctx)
2753 return AVERROR(ENOSYS);
2755 return vulkan_transfer_data_from_mem(hwfc, dst, src);
2760 static int vulkan_transfer_data_to_cuda(AVHWFramesContext *hwfc, AVFrame *dst,
2767 AVVkFrameInternal *dst_int;
2768 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2769 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2771 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)dst->hw_frames_ctx->data;
2772 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2773 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2774 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2775 CudaFunctions *cu = cu_internal->cuda_dl;
2777 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2779 err = AVERROR_EXTERNAL;
2783 dst_f = (AVVkFrame *)src->data[0];
2785 err = vulkan_export_to_cuda(hwfc, dst->hw_frames_ctx, src);
2790 dst_int = dst_f->internal;
2792 for (int i = 0; i < planes; i++) {
2793 CUDA_MEMCPY2D cpy = {
2794 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
2795 .dstDevice = (CUdeviceptr)dst->data[i],
2796 .dstPitch = dst->linesize[i],
2799 .srcMemoryType = CU_MEMORYTYPE_ARRAY,
2800 .srcArray = dst_int->cu_array[i],
2801 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2802 : hwfc->width) * desc->comp[i].step,
2803 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2807 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2809 err = AVERROR_EXTERNAL;
2814 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2816 av_log(hwfc, AV_LOG_VERBOSE, "Transfered Vulkan image to CUDA!\n");
2821 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2822 vulkan_free_internal(dst_int);
2823 dst_f->internal = NULL;
2824 av_buffer_unref(&dst->buf[0]);
2829 static int vulkan_transfer_data_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
2834 AVVkFrame *f = (AVVkFrame *)src->data[0];
2835 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
2836 ImageBuffer buf[AV_NUM_DATA_POINTERS] = { { 0 } };
2837 const int planes = av_pix_fmt_count_planes(dst->format);
2838 int log2_chroma = av_pix_fmt_desc_get(dst->format)->log2_chroma_h;
2840 if (dst->width > hwfc->width || dst->height > hwfc->height)
2841 return AVERROR(EINVAL);
2843 /* For linear, host visiable images */
2844 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
2845 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
2846 AVFrame *map = av_frame_alloc();
2848 return AVERROR(ENOMEM);
2849 map->format = dst->format;
2851 err = vulkan_map_frame_to_mem(hwfc, map, src, AV_HWFRAME_MAP_READ);
2855 err = av_frame_copy(dst, map);
2856 av_frame_free(&map);
2860 /* Create buffers */
2861 for (int i = 0; i < planes; i++) {
2862 int h = dst->height;
2863 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
2865 tmp.linesize[i] = FFABS(dst->linesize[i]);
2866 err = create_buf(dev_ctx, &buf[i], p_height,
2867 &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_DST_BIT,
2868 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
2871 /* Copy image to buffer */
2872 if ((err = transfer_image_buf(dev_ctx, f, buf, tmp.linesize,
2873 dst->width, dst->height, dst->format, 1)))
2876 /* Map, copy buffer to frame, unmap */
2877 if ((err = map_buffers(dev_ctx, buf, tmp.data, planes, 1)))
2880 av_image_copy(dst->data, dst->linesize, (const uint8_t **)tmp.data,
2881 tmp.linesize, dst->format, dst->width, dst->height);
2883 err = unmap_buffers(dev_ctx, buf, planes, 0);
2886 for (int i = 0; i < planes; i++)
2887 free_buf(dev_ctx, &buf[i]);
2892 static int vulkan_transfer_data_from(AVHWFramesContext *hwfc, AVFrame *dst,
2895 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2897 switch (dst->format) {
2899 case AV_PIX_FMT_CUDA:
2900 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
2901 (p->extensions & EXT_EXTERNAL_FD_SEM))
2902 return vulkan_transfer_data_to_cuda(hwfc, dst, src);
2905 if (dst->hw_frames_ctx)
2906 return AVERROR(ENOSYS);
2908 return vulkan_transfer_data_to_mem(hwfc, dst, src);
2912 AVVkFrame *av_vk_frame_alloc(void)
2914 return av_mallocz(sizeof(AVVkFrame));
2917 const HWContextType ff_hwcontext_type_vulkan = {
2918 .type = AV_HWDEVICE_TYPE_VULKAN,
2921 .device_hwctx_size = sizeof(AVVulkanDeviceContext),
2922 .device_priv_size = sizeof(VulkanDevicePriv),
2923 .frames_hwctx_size = sizeof(AVVulkanFramesContext),
2924 .frames_priv_size = sizeof(VulkanFramesPriv),
2926 .device_init = &vulkan_device_init,
2927 .device_create = &vulkan_device_create,
2928 .device_derive = &vulkan_device_derive,
2930 .frames_get_constraints = &vulkan_frames_get_constraints,
2931 .frames_init = vulkan_frames_init,
2932 .frames_get_buffer = vulkan_get_buffer,
2933 .frames_uninit = vulkan_frames_uninit,
2935 .transfer_get_formats = vulkan_transfer_get_formats,
2936 .transfer_data_to = vulkan_transfer_data_to,
2937 .transfer_data_from = vulkan_transfer_data_from,
2939 .map_to = vulkan_map_to,
2940 .map_from = vulkan_map_from,
2942 .pix_fmts = (const enum AVPixelFormat []) {