2 * This file is part of FFmpeg.
4 * FFmpeg is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * FFmpeg is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with FFmpeg; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 #include "hwcontext.h"
24 #include "hwcontext_internal.h"
25 #include "hwcontext_vulkan.h"
30 #include <drm_fourcc.h>
31 #include "hwcontext_drm.h"
33 #include <va/va_drmcommon.h>
34 #include "hwcontext_vaapi.h"
39 #include "hwcontext_cuda_internal.h"
40 #include "cuda_check.h"
41 #define CHECK_CU(x) FF_CUDA_CHECK_DL(cuda_cu, cu, x)
44 typedef struct VulkanExecCtx {
51 typedef struct VulkanDevicePriv {
53 VkPhysicalDeviceProperties props;
54 VkPhysicalDeviceMemoryProperties mprops;
61 VkDebugUtilsMessengerEXT debug_ctx;
70 int use_linear_images;
76 typedef struct VulkanFramesPriv {
80 typedef struct AVVkFrameInternal {
82 /* Importing external memory into cuda is really expensive so we keep the
83 * memory imported all the time */
84 AVBufferRef *cuda_fc_ref; /* Need to keep it around for uninit */
85 CUexternalMemory ext_mem[AV_NUM_DATA_POINTERS];
86 CUmipmappedArray cu_mma[AV_NUM_DATA_POINTERS];
87 CUarray cu_array[AV_NUM_DATA_POINTERS];
88 CUexternalSemaphore cu_sem[AV_NUM_DATA_POINTERS];
92 #define VK_LOAD_PFN(inst, name) PFN_##name pfn_##name = (PFN_##name) \
93 vkGetInstanceProcAddr(inst, #name)
95 #define DEFAULT_USAGE_FLAGS (VK_IMAGE_USAGE_SAMPLED_BIT | \
96 VK_IMAGE_USAGE_STORAGE_BIT | \
97 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | \
98 VK_IMAGE_USAGE_TRANSFER_DST_BIT)
100 #define ADD_VAL_TO_LIST(list, count, val) \
102 list = av_realloc_array(list, sizeof(*list), ++count); \
104 err = AVERROR(ENOMEM); \
107 list[count - 1] = av_strdup(val); \
108 if (!list[count - 1]) { \
109 err = AVERROR(ENOMEM); \
114 static const struct {
115 enum AVPixelFormat pixfmt;
116 const VkFormat vkfmts[3];
117 } vk_pixfmt_map[] = {
118 { AV_PIX_FMT_GRAY8, { VK_FORMAT_R8_UNORM } },
119 { AV_PIX_FMT_GRAY16, { VK_FORMAT_R16_UNORM } },
120 { AV_PIX_FMT_GRAYF32, { VK_FORMAT_R32_SFLOAT } },
122 { AV_PIX_FMT_NV12, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8G8_UNORM } },
123 { AV_PIX_FMT_P010, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16G16_UNORM } },
124 { AV_PIX_FMT_P016, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16G16_UNORM } },
126 { AV_PIX_FMT_YUV420P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
127 { AV_PIX_FMT_YUV422P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
128 { AV_PIX_FMT_YUV444P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
130 { AV_PIX_FMT_YUV420P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
131 { AV_PIX_FMT_YUV422P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
132 { AV_PIX_FMT_YUV444P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
134 { AV_PIX_FMT_ABGR, { VK_FORMAT_A8B8G8R8_UNORM_PACK32 } },
135 { AV_PIX_FMT_BGRA, { VK_FORMAT_B8G8R8A8_UNORM } },
136 { AV_PIX_FMT_RGBA, { VK_FORMAT_R8G8B8A8_UNORM } },
137 { AV_PIX_FMT_RGB24, { VK_FORMAT_R8G8B8_UNORM } },
138 { AV_PIX_FMT_BGR24, { VK_FORMAT_B8G8R8_UNORM } },
139 { AV_PIX_FMT_RGB48, { VK_FORMAT_R16G16B16_UNORM } },
140 { AV_PIX_FMT_RGBA64, { VK_FORMAT_R16G16B16A16_UNORM } },
141 { AV_PIX_FMT_RGB565, { VK_FORMAT_R5G6B5_UNORM_PACK16 } },
142 { AV_PIX_FMT_BGR565, { VK_FORMAT_B5G6R5_UNORM_PACK16 } },
143 { AV_PIX_FMT_BGR0, { VK_FORMAT_B8G8R8A8_UNORM } },
144 { AV_PIX_FMT_0BGR, { VK_FORMAT_A8B8G8R8_UNORM_PACK32 } },
145 { AV_PIX_FMT_RGB0, { VK_FORMAT_R8G8B8A8_UNORM } },
147 { AV_PIX_FMT_GBRPF32, { VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32_SFLOAT } },
150 const VkFormat *av_vkfmt_from_pixfmt(enum AVPixelFormat p)
152 for (enum AVPixelFormat i = 0; i < FF_ARRAY_ELEMS(vk_pixfmt_map); i++)
153 if (vk_pixfmt_map[i].pixfmt == p)
154 return vk_pixfmt_map[i].vkfmts;
158 static int pixfmt_is_supported(AVVulkanDeviceContext *hwctx, enum AVPixelFormat p,
161 const VkFormat *fmt = av_vkfmt_from_pixfmt(p);
162 int planes = av_pix_fmt_count_planes(p);
167 for (int i = 0; i < planes; i++) {
168 VkFormatFeatureFlags flags;
169 VkFormatProperties2 prop = {
170 .sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2,
172 vkGetPhysicalDeviceFormatProperties2(hwctx->phys_dev, fmt[i], &prop);
173 flags = linear ? prop.formatProperties.linearTilingFeatures :
174 prop.formatProperties.optimalTilingFeatures;
175 if (!(flags & DEFAULT_USAGE_FLAGS))
182 enum VulkanExtensions {
183 EXT_EXTERNAL_DMABUF_MEMORY = 1ULL << 0, /* VK_EXT_external_memory_dma_buf */
184 EXT_DRM_MODIFIER_FLAGS = 1ULL << 1, /* VK_EXT_image_drm_format_modifier */
185 EXT_EXTERNAL_FD_MEMORY = 1ULL << 2, /* VK_KHR_external_memory_fd */
186 EXT_EXTERNAL_FD_SEM = 1ULL << 3, /* VK_KHR_external_semaphore_fd */
188 EXT_NO_FLAG = 1ULL << 63,
191 typedef struct VulkanOptExtension {
194 } VulkanOptExtension;
196 static const VulkanOptExtension optional_instance_exts[] = {
200 static const VulkanOptExtension optional_device_exts[] = {
201 { VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME, EXT_EXTERNAL_FD_MEMORY, },
202 { VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME, EXT_EXTERNAL_DMABUF_MEMORY, },
203 { VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME, EXT_DRM_MODIFIER_FLAGS, },
204 { VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME, EXT_EXTERNAL_FD_SEM, },
207 /* Converts return values to strings */
208 static const char *vk_ret2str(VkResult res)
210 #define CASE(VAL) case VAL: return #VAL
216 CASE(VK_EVENT_RESET);
218 CASE(VK_ERROR_OUT_OF_HOST_MEMORY);
219 CASE(VK_ERROR_OUT_OF_DEVICE_MEMORY);
220 CASE(VK_ERROR_INITIALIZATION_FAILED);
221 CASE(VK_ERROR_DEVICE_LOST);
222 CASE(VK_ERROR_MEMORY_MAP_FAILED);
223 CASE(VK_ERROR_LAYER_NOT_PRESENT);
224 CASE(VK_ERROR_EXTENSION_NOT_PRESENT);
225 CASE(VK_ERROR_FEATURE_NOT_PRESENT);
226 CASE(VK_ERROR_INCOMPATIBLE_DRIVER);
227 CASE(VK_ERROR_TOO_MANY_OBJECTS);
228 CASE(VK_ERROR_FORMAT_NOT_SUPPORTED);
229 CASE(VK_ERROR_FRAGMENTED_POOL);
230 CASE(VK_ERROR_SURFACE_LOST_KHR);
231 CASE(VK_ERROR_NATIVE_WINDOW_IN_USE_KHR);
232 CASE(VK_SUBOPTIMAL_KHR);
233 CASE(VK_ERROR_OUT_OF_DATE_KHR);
234 CASE(VK_ERROR_INCOMPATIBLE_DISPLAY_KHR);
235 CASE(VK_ERROR_VALIDATION_FAILED_EXT);
236 CASE(VK_ERROR_INVALID_SHADER_NV);
237 CASE(VK_ERROR_OUT_OF_POOL_MEMORY);
238 CASE(VK_ERROR_INVALID_EXTERNAL_HANDLE);
239 CASE(VK_ERROR_NOT_PERMITTED_EXT);
240 CASE(VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT);
241 CASE(VK_ERROR_INVALID_DEVICE_ADDRESS_EXT);
242 CASE(VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT);
243 default: return "Unknown error";
248 static VkBool32 vk_dbg_callback(VkDebugUtilsMessageSeverityFlagBitsEXT severity,
249 VkDebugUtilsMessageTypeFlagsEXT messageType,
250 const VkDebugUtilsMessengerCallbackDataEXT *data,
254 AVHWDeviceContext *ctx = priv;
257 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT: l = AV_LOG_VERBOSE; break;
258 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT: l = AV_LOG_INFO; break;
259 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT: l = AV_LOG_WARNING; break;
260 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT: l = AV_LOG_ERROR; break;
261 default: l = AV_LOG_DEBUG; break;
264 av_log(ctx, l, "%s\n", data->pMessage);
265 for (int i = 0; i < data->cmdBufLabelCount; i++)
266 av_log(ctx, l, "\t%i: %s\n", i, data->pCmdBufLabels[i].pLabelName);
271 static int check_extensions(AVHWDeviceContext *ctx, int dev, AVDictionary *opts,
272 const char * const **dst, uint32_t *num, int debug)
275 const char **extension_names = NULL;
276 VulkanDevicePriv *p = ctx->internal->priv;
277 AVVulkanDeviceContext *hwctx = ctx->hwctx;
278 int err = 0, found, extensions_found = 0;
281 int optional_exts_num;
282 uint32_t sup_ext_count;
283 char *user_exts_str = NULL;
284 AVDictionaryEntry *user_exts;
285 VkExtensionProperties *sup_ext;
286 const VulkanOptExtension *optional_exts;
290 optional_exts = optional_instance_exts;
291 optional_exts_num = FF_ARRAY_ELEMS(optional_instance_exts);
292 user_exts = av_dict_get(opts, "instance_extensions", NULL, 0);
294 user_exts_str = av_strdup(user_exts->value);
295 if (!user_exts_str) {
296 err = AVERROR(ENOMEM);
300 vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, NULL);
301 sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
303 return AVERROR(ENOMEM);
304 vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, sup_ext);
307 optional_exts = optional_device_exts;
308 optional_exts_num = FF_ARRAY_ELEMS(optional_device_exts);
309 user_exts = av_dict_get(opts, "device_extensions", NULL, 0);
311 user_exts_str = av_strdup(user_exts->value);
312 if (!user_exts_str) {
313 err = AVERROR(ENOMEM);
317 vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
318 &sup_ext_count, NULL);
319 sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
321 return AVERROR(ENOMEM);
322 vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
323 &sup_ext_count, sup_ext);
326 for (int i = 0; i < optional_exts_num; i++) {
327 tstr = optional_exts[i].name;
329 for (int j = 0; j < sup_ext_count; j++) {
330 if (!strcmp(tstr, sup_ext[j].extensionName)) {
338 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
339 p->extensions |= optional_exts[i].flag;
340 ADD_VAL_TO_LIST(extension_names, extensions_found, tstr);
344 tstr = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
346 for (int j = 0; j < sup_ext_count; j++) {
347 if (!strcmp(tstr, sup_ext[j].extensionName)) {
353 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
354 ADD_VAL_TO_LIST(extension_names, extensions_found, tstr);
356 av_log(ctx, AV_LOG_ERROR, "Debug extension \"%s\" not found!\n",
358 err = AVERROR(EINVAL);
364 char *save, *token = av_strtok(user_exts_str, "+", &save);
367 for (int j = 0; j < sup_ext_count; j++) {
368 if (!strcmp(token, sup_ext[j].extensionName)) {
374 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, token);
375 ADD_VAL_TO_LIST(extension_names, extensions_found, token);
377 av_log(ctx, AV_LOG_WARNING, "%s extension \"%s\" not found, excluding.\n",
380 token = av_strtok(NULL, "+", &save);
384 *dst = extension_names;
385 *num = extensions_found;
387 av_free(user_exts_str);
393 for (int i = 0; i < extensions_found; i++)
394 av_free((void *)extension_names[i]);
395 av_free(extension_names);
396 av_free(user_exts_str);
401 /* Creates a VkInstance */
402 static int create_instance(AVHWDeviceContext *ctx, AVDictionary *opts)
406 VulkanDevicePriv *p = ctx->internal->priv;
407 AVVulkanDeviceContext *hwctx = ctx->hwctx;
408 AVDictionaryEntry *debug_opt = av_dict_get(opts, "debug", NULL, 0);
409 const int debug_mode = debug_opt && strtol(debug_opt->value, NULL, 10);
410 VkApplicationInfo application_info = {
411 .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
412 .pEngineName = "libavutil",
413 .apiVersion = VK_API_VERSION_1_1,
414 .engineVersion = VK_MAKE_VERSION(LIBAVUTIL_VERSION_MAJOR,
415 LIBAVUTIL_VERSION_MINOR,
416 LIBAVUTIL_VERSION_MICRO),
418 VkInstanceCreateInfo inst_props = {
419 .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
420 .pApplicationInfo = &application_info,
423 /* Check for present/missing extensions */
424 err = check_extensions(ctx, 0, opts, &inst_props.ppEnabledExtensionNames,
425 &inst_props.enabledExtensionCount, debug_mode);
430 static const char *layers[] = { "VK_LAYER_KHRONOS_validation" };
431 inst_props.ppEnabledLayerNames = layers;
432 inst_props.enabledLayerCount = FF_ARRAY_ELEMS(layers);
435 /* Try to create the instance */
436 ret = vkCreateInstance(&inst_props, hwctx->alloc, &hwctx->inst);
438 /* Check for errors */
439 if (ret != VK_SUCCESS) {
440 av_log(ctx, AV_LOG_ERROR, "Instance creation failure: %s\n",
442 for (int i = 0; i < inst_props.enabledExtensionCount; i++)
443 av_free((void *)inst_props.ppEnabledExtensionNames[i]);
444 av_free((void *)inst_props.ppEnabledExtensionNames);
445 return AVERROR_EXTERNAL;
449 VkDebugUtilsMessengerCreateInfoEXT dbg = {
450 .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT,
451 .messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT |
452 VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT |
453 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
454 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT,
455 .messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
456 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
457 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT,
458 .pfnUserCallback = vk_dbg_callback,
461 VK_LOAD_PFN(hwctx->inst, vkCreateDebugUtilsMessengerEXT);
463 pfn_vkCreateDebugUtilsMessengerEXT(hwctx->inst, &dbg,
464 hwctx->alloc, &p->debug_ctx);
467 hwctx->enabled_inst_extensions = inst_props.ppEnabledExtensionNames;
468 hwctx->nb_enabled_inst_extensions = inst_props.enabledExtensionCount;
473 typedef struct VulkanDeviceSelection {
474 uint8_t uuid[VK_UUID_SIZE]; /* Will use this first unless !has_uuid */
476 const char *name; /* Will use this second unless NULL */
477 uint32_t pci_device; /* Will use this third unless 0x0 */
478 uint32_t vendor_id; /* Last resort to find something deterministic */
479 int index; /* Finally fall back to index */
480 } VulkanDeviceSelection;
482 static const char *vk_dev_type(enum VkPhysicalDeviceType type)
485 case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: return "integrated";
486 case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: return "discrete";
487 case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: return "virtual";
488 case VK_PHYSICAL_DEVICE_TYPE_CPU: return "software";
489 default: return "unknown";
494 static int find_device(AVHWDeviceContext *ctx, VulkanDeviceSelection *select)
496 int err = 0, choice = -1;
499 VkPhysicalDevice *devices = NULL;
500 VkPhysicalDeviceIDProperties *idp = NULL;
501 VkPhysicalDeviceProperties2 *prop = NULL;
502 VulkanDevicePriv *p = ctx->internal->priv;
503 AVVulkanDeviceContext *hwctx = ctx->hwctx;
505 ret = vkEnumeratePhysicalDevices(hwctx->inst, &num, NULL);
506 if (ret != VK_SUCCESS || !num) {
507 av_log(ctx, AV_LOG_ERROR, "No devices found: %s!\n", vk_ret2str(ret));
508 return AVERROR(ENODEV);
511 devices = av_malloc_array(num, sizeof(VkPhysicalDevice));
513 return AVERROR(ENOMEM);
515 ret = vkEnumeratePhysicalDevices(hwctx->inst, &num, devices);
516 if (ret != VK_SUCCESS) {
517 av_log(ctx, AV_LOG_ERROR, "Failed enumerating devices: %s\n",
519 err = AVERROR(ENODEV);
523 prop = av_mallocz_array(num, sizeof(*prop));
525 err = AVERROR(ENOMEM);
529 idp = av_mallocz_array(num, sizeof(*idp));
531 err = AVERROR(ENOMEM);
535 av_log(ctx, AV_LOG_VERBOSE, "GPU listing:\n");
536 for (int i = 0; i < num; i++) {
537 idp[i].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES;
538 prop[i].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
539 prop[i].pNext = &idp[i];
541 vkGetPhysicalDeviceProperties2(devices[i], &prop[i]);
542 av_log(ctx, AV_LOG_VERBOSE, " %d: %s (%s) (0x%x)\n", i,
543 prop[i].properties.deviceName,
544 vk_dev_type(prop[i].properties.deviceType),
545 prop[i].properties.deviceID);
548 if (select->has_uuid) {
549 for (int i = 0; i < num; i++) {
550 if (!strncmp(idp[i].deviceUUID, select->uuid, VK_UUID_SIZE)) {
555 av_log(ctx, AV_LOG_ERROR, "Unable to find device by given UUID!\n");
556 err = AVERROR(ENODEV);
558 } else if (select->name) {
559 av_log(ctx, AV_LOG_VERBOSE, "Requested device: %s\n", select->name);
560 for (int i = 0; i < num; i++) {
561 if (strstr(prop[i].properties.deviceName, select->name)) {
566 av_log(ctx, AV_LOG_ERROR, "Unable to find device \"%s\"!\n",
568 err = AVERROR(ENODEV);
570 } else if (select->pci_device) {
571 av_log(ctx, AV_LOG_VERBOSE, "Requested device: 0x%x\n", select->pci_device);
572 for (int i = 0; i < num; i++) {
573 if (select->pci_device == prop[i].properties.deviceID) {
578 av_log(ctx, AV_LOG_ERROR, "Unable to find device with PCI ID 0x%x!\n",
580 err = AVERROR(EINVAL);
582 } else if (select->vendor_id) {
583 av_log(ctx, AV_LOG_VERBOSE, "Requested vendor: 0x%x\n", select->vendor_id);
584 for (int i = 0; i < num; i++) {
585 if (select->vendor_id == prop[i].properties.vendorID) {
590 av_log(ctx, AV_LOG_ERROR, "Unable to find device with Vendor ID 0x%x!\n",
592 err = AVERROR(ENODEV);
595 if (select->index < num) {
596 choice = select->index;
599 av_log(ctx, AV_LOG_ERROR, "Unable to find device with index %i!\n",
601 err = AVERROR(ENODEV);
607 p->dev_is_nvidia = (prop[choice].properties.vendorID == 0x10de);
608 hwctx->phys_dev = devices[choice];
617 static int search_queue_families(AVHWDeviceContext *ctx, VkDeviceCreateInfo *cd)
621 VkQueueFamilyProperties *qs = NULL;
622 AVVulkanDeviceContext *hwctx = ctx->hwctx;
623 int graph_index = -1, comp_index = -1, tx_index = -1;
624 VkDeviceQueueCreateInfo *pc = (VkDeviceQueueCreateInfo *)cd->pQueueCreateInfos;
626 /* First get the number of queue families */
627 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, NULL);
629 av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
630 return AVERROR_EXTERNAL;
633 /* Then allocate memory */
634 qs = av_malloc_array(num, sizeof(VkQueueFamilyProperties));
636 return AVERROR(ENOMEM);
638 /* Finally retrieve the queue families */
639 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, qs);
641 #define SEARCH_FLAGS(expr, out) \
642 for (int i = 0; i < num; i++) { \
643 const VkQueueFlagBits flags = qs[i].queueFlags; \
650 SEARCH_FLAGS(flags & VK_QUEUE_GRAPHICS_BIT, graph_index)
652 SEARCH_FLAGS((flags & VK_QUEUE_COMPUTE_BIT) && (i != graph_index),
655 SEARCH_FLAGS((flags & VK_QUEUE_TRANSFER_BIT) && (i != graph_index) &&
656 (i != comp_index), tx_index)
659 #define ADD_QUEUE(fidx, graph, comp, tx) \
660 av_log(ctx, AV_LOG_VERBOSE, "Using queue family %i (total queues: %i) for %s%s%s\n", \
661 fidx, qs[fidx].queueCount, graph ? "graphics " : "", \
662 comp ? "compute " : "", tx ? "transfers " : ""); \
663 av_log(ctx, AV_LOG_VERBOSE, " QF %i flags: %s%s%s%s\n", fidx, \
664 ((qs[fidx].queueFlags) & VK_QUEUE_GRAPHICS_BIT) ? "(graphics) " : "", \
665 ((qs[fidx].queueFlags) & VK_QUEUE_COMPUTE_BIT) ? "(compute) " : "", \
666 ((qs[fidx].queueFlags) & VK_QUEUE_TRANSFER_BIT) ? "(transfers) " : "", \
667 ((qs[fidx].queueFlags) & VK_QUEUE_SPARSE_BINDING_BIT) ? "(sparse) " : ""); \
668 pc[cd->queueCreateInfoCount].queueFamilyIndex = fidx; \
669 pc[cd->queueCreateInfoCount].queueCount = qs[fidx].queueCount; \
670 weights = av_malloc(qs[fidx].queueCount * sizeof(float)); \
671 pc[cd->queueCreateInfoCount].pQueuePriorities = weights; \
674 for (int i = 0; i < qs[fidx].queueCount; i++) \
676 cd->queueCreateInfoCount++;
678 ADD_QUEUE(graph_index, 1, comp_index < 0, tx_index < 0 && comp_index < 0)
679 hwctx->queue_family_index = graph_index;
680 hwctx->queue_family_comp_index = graph_index;
681 hwctx->queue_family_tx_index = graph_index;
682 hwctx->nb_graphics_queues = qs[graph_index].queueCount;
684 if (comp_index != -1) {
685 ADD_QUEUE(comp_index, 0, 1, tx_index < 0)
686 hwctx->queue_family_tx_index = comp_index;
687 hwctx->queue_family_comp_index = comp_index;
688 hwctx->nb_comp_queues = qs[comp_index].queueCount;
691 if (tx_index != -1) {
692 ADD_QUEUE(tx_index, 0, 0, 1)
693 hwctx->queue_family_tx_index = tx_index;
694 hwctx->nb_tx_queues = qs[tx_index].queueCount;
703 av_freep(&pc[0].pQueuePriorities);
704 av_freep(&pc[1].pQueuePriorities);
705 av_freep(&pc[2].pQueuePriorities);
708 return AVERROR(ENOMEM);
711 static int create_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd,
712 int queue_family_index)
715 AVVulkanDeviceContext *hwctx = ctx->hwctx;
717 VkCommandPoolCreateInfo cqueue_create = {
718 .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
719 .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
720 .queueFamilyIndex = queue_family_index,
722 VkCommandBufferAllocateInfo cbuf_create = {
723 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
724 .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
725 .commandBufferCount = 1,
728 VkFenceCreateInfo fence_spawn = {
729 .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
732 ret = vkCreateFence(hwctx->act_dev, &fence_spawn,
733 hwctx->alloc, &cmd->fence);
734 if (ret != VK_SUCCESS) {
735 av_log(ctx, AV_LOG_ERROR, "Failed to create frame fence: %s\n",
737 return AVERROR_EXTERNAL;
740 ret = vkCreateCommandPool(hwctx->act_dev, &cqueue_create,
741 hwctx->alloc, &cmd->pool);
742 if (ret != VK_SUCCESS) {
743 av_log(ctx, AV_LOG_ERROR, "Command pool creation failure: %s\n",
745 return AVERROR_EXTERNAL;
748 cbuf_create.commandPool = cmd->pool;
750 ret = vkAllocateCommandBuffers(hwctx->act_dev, &cbuf_create, &cmd->buf);
751 if (ret != VK_SUCCESS) {
752 av_log(ctx, AV_LOG_ERROR, "Command buffer alloc failure: %s\n",
754 return AVERROR_EXTERNAL;
757 vkGetDeviceQueue(hwctx->act_dev, cqueue_create.queueFamilyIndex, 0,
763 static void free_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd)
765 AVVulkanDeviceContext *hwctx = ctx->hwctx;
768 vkDestroyFence(hwctx->act_dev, cmd->fence, hwctx->alloc);
770 vkFreeCommandBuffers(hwctx->act_dev, cmd->pool, 1, &cmd->buf);
772 vkDestroyCommandPool(hwctx->act_dev, cmd->pool, hwctx->alloc);
775 static void vulkan_device_free(AVHWDeviceContext *ctx)
777 VulkanDevicePriv *p = ctx->internal->priv;
778 AVVulkanDeviceContext *hwctx = ctx->hwctx;
780 free_exec_ctx(ctx, &p->cmd);
782 vkDestroyDevice(hwctx->act_dev, hwctx->alloc);
785 VK_LOAD_PFN(hwctx->inst, vkDestroyDebugUtilsMessengerEXT);
786 pfn_vkDestroyDebugUtilsMessengerEXT(hwctx->inst, p->debug_ctx,
790 vkDestroyInstance(hwctx->inst, hwctx->alloc);
792 for (int i = 0; i < hwctx->nb_enabled_inst_extensions; i++)
793 av_free((void *)hwctx->enabled_inst_extensions[i]);
794 av_free((void *)hwctx->enabled_inst_extensions);
796 for (int i = 0; i < hwctx->nb_enabled_dev_extensions; i++)
797 av_free((void *)hwctx->enabled_dev_extensions[i]);
798 av_free((void *)hwctx->enabled_dev_extensions);
801 static int vulkan_device_create_internal(AVHWDeviceContext *ctx,
802 VulkanDeviceSelection *dev_select,
803 AVDictionary *opts, int flags)
807 AVDictionaryEntry *opt_d;
808 VulkanDevicePriv *p = ctx->internal->priv;
809 AVVulkanDeviceContext *hwctx = ctx->hwctx;
810 VkPhysicalDeviceFeatures dev_features = { 0 };
811 VkDeviceQueueCreateInfo queue_create_info[3] = {
812 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, },
813 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, },
814 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, },
817 VkDeviceCreateInfo dev_info = {
818 .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
819 .pNext = &hwctx->device_features,
820 .pQueueCreateInfos = queue_create_info,
821 .queueCreateInfoCount = 0,
824 hwctx->device_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
825 ctx->free = vulkan_device_free;
827 /* Create an instance if not given one */
828 if ((err = create_instance(ctx, opts)))
831 /* Find a device (if not given one) */
832 if ((err = find_device(ctx, dev_select)))
835 vkGetPhysicalDeviceProperties(hwctx->phys_dev, &p->props);
836 av_log(ctx, AV_LOG_VERBOSE, "Using device: %s\n", p->props.deviceName);
837 av_log(ctx, AV_LOG_VERBOSE, "Alignments:\n");
838 av_log(ctx, AV_LOG_VERBOSE, " optimalBufferCopyOffsetAlignment: %li\n",
839 p->props.limits.optimalBufferCopyOffsetAlignment);
840 av_log(ctx, AV_LOG_VERBOSE, " optimalBufferCopyRowPitchAlignment: %li\n",
841 p->props.limits.optimalBufferCopyRowPitchAlignment);
842 av_log(ctx, AV_LOG_VERBOSE, " minMemoryMapAlignment: %li\n",
843 p->props.limits.minMemoryMapAlignment);
845 vkGetPhysicalDeviceFeatures(hwctx->phys_dev, &dev_features);
846 #define COPY_FEATURE(DST, NAME) (DST).features.NAME = dev_features.NAME;
847 COPY_FEATURE(hwctx->device_features, shaderImageGatherExtended)
848 COPY_FEATURE(hwctx->device_features, fragmentStoresAndAtomics)
849 COPY_FEATURE(hwctx->device_features, vertexPipelineStoresAndAtomics)
850 COPY_FEATURE(hwctx->device_features, shaderInt64)
853 /* Search queue family */
854 if ((err = search_queue_families(ctx, &dev_info)))
857 if ((err = check_extensions(ctx, 1, opts, &dev_info.ppEnabledExtensionNames,
858 &dev_info.enabledExtensionCount, 0))) {
859 av_free((void *)queue_create_info[0].pQueuePriorities);
860 av_free((void *)queue_create_info[1].pQueuePriorities);
861 av_free((void *)queue_create_info[2].pQueuePriorities);
865 ret = vkCreateDevice(hwctx->phys_dev, &dev_info, hwctx->alloc,
868 av_free((void *)queue_create_info[0].pQueuePriorities);
869 av_free((void *)queue_create_info[1].pQueuePriorities);
870 av_free((void *)queue_create_info[2].pQueuePriorities);
872 if (ret != VK_SUCCESS) {
873 av_log(ctx, AV_LOG_ERROR, "Device creation failure: %s\n",
875 for (int i = 0; i < dev_info.enabledExtensionCount; i++)
876 av_free((void *)dev_info.ppEnabledExtensionNames[i]);
877 av_free((void *)dev_info.ppEnabledExtensionNames);
878 err = AVERROR_EXTERNAL;
882 /* Tiled images setting, use them by default */
883 opt_d = av_dict_get(opts, "linear_images", NULL, 0);
885 p->use_linear_images = strtol(opt_d->value, NULL, 10);
887 hwctx->enabled_dev_extensions = dev_info.ppEnabledExtensionNames;
888 hwctx->nb_enabled_dev_extensions = dev_info.enabledExtensionCount;
894 static int vulkan_device_init(AVHWDeviceContext *ctx)
898 AVVulkanDeviceContext *hwctx = ctx->hwctx;
899 VulkanDevicePriv *p = ctx->internal->priv;
901 /* Set device extension flags */
902 for (int i = 0; i < hwctx->nb_enabled_dev_extensions; i++) {
903 for (int j = 0; j < FF_ARRAY_ELEMS(optional_device_exts); j++) {
904 if (!strcmp(hwctx->enabled_dev_extensions[i],
905 optional_device_exts[j].name)) {
906 p->extensions |= optional_device_exts[j].flag;
912 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &queue_num, NULL);
914 av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
915 return AVERROR_EXTERNAL;
918 #define CHECK_QUEUE(type, n) \
919 if (n >= queue_num) { \
920 av_log(ctx, AV_LOG_ERROR, "Invalid %s queue index %i (device has %i queues)!\n", \
921 type, n, queue_num); \
922 return AVERROR(EINVAL); \
925 CHECK_QUEUE("graphics", hwctx->queue_family_index)
926 CHECK_QUEUE("upload", hwctx->queue_family_tx_index)
927 CHECK_QUEUE("compute", hwctx->queue_family_comp_index)
931 p->qfs[p->num_qfs++] = hwctx->queue_family_index;
932 if ((hwctx->queue_family_tx_index != hwctx->queue_family_index) &&
933 (hwctx->queue_family_tx_index != hwctx->queue_family_comp_index))
934 p->qfs[p->num_qfs++] = hwctx->queue_family_tx_index;
935 if ((hwctx->queue_family_comp_index != hwctx->queue_family_index) &&
936 (hwctx->queue_family_comp_index != hwctx->queue_family_tx_index))
937 p->qfs[p->num_qfs++] = hwctx->queue_family_comp_index;
939 /* Create exec context - if there's something invalid this will error out */
940 err = create_exec_ctx(ctx, &p->cmd, hwctx->queue_family_tx_index);
944 /* Get device capabilities */
945 vkGetPhysicalDeviceMemoryProperties(hwctx->phys_dev, &p->mprops);
950 static int vulkan_device_create(AVHWDeviceContext *ctx, const char *device,
951 AVDictionary *opts, int flags)
953 VulkanDeviceSelection dev_select = { 0 };
954 if (device && device[0]) {
956 dev_select.index = strtol(device, &end, 10);
958 dev_select.index = 0;
959 dev_select.name = device;
963 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
966 static int vulkan_device_derive(AVHWDeviceContext *ctx,
967 AVHWDeviceContext *src_ctx,
968 AVDictionary *opts, int flags)
970 av_unused VulkanDeviceSelection dev_select = { 0 };
972 /* If there's only one device on the system, then even if its not covered
973 * by the following checks (e.g. non-PCIe ARM GPU), having an empty
974 * dev_select will mean it'll get picked. */
975 switch(src_ctx->type) {
978 case AV_HWDEVICE_TYPE_VAAPI: {
979 AVVAAPIDeviceContext *src_hwctx = src_ctx->hwctx;
981 const char *vendor = vaQueryVendorString(src_hwctx->display);
983 av_log(ctx, AV_LOG_ERROR, "Unable to get device info from VAAPI!\n");
984 return AVERROR_EXTERNAL;
987 if (strstr(vendor, "Intel"))
988 dev_select.vendor_id = 0x8086;
989 if (strstr(vendor, "AMD"))
990 dev_select.vendor_id = 0x1002;
992 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
995 case AV_HWDEVICE_TYPE_DRM: {
996 AVDRMDeviceContext *src_hwctx = src_ctx->hwctx;
998 drmDevice *drm_dev_info;
999 int err = drmGetDevice(src_hwctx->fd, &drm_dev_info);
1001 av_log(ctx, AV_LOG_ERROR, "Unable to get device info from DRM fd!\n");
1002 return AVERROR_EXTERNAL;
1005 if (drm_dev_info->bustype == DRM_BUS_PCI)
1006 dev_select.pci_device = drm_dev_info->deviceinfo.pci->device_id;
1008 drmFreeDevice(&drm_dev_info);
1010 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1014 case AV_HWDEVICE_TYPE_CUDA: {
1015 AVHWDeviceContext *cuda_cu = src_ctx;
1016 AVCUDADeviceContext *src_hwctx = src_ctx->hwctx;
1017 AVCUDADeviceContextInternal *cu_internal = src_hwctx->internal;
1018 CudaFunctions *cu = cu_internal->cuda_dl;
1020 int ret = CHECK_CU(cu->cuDeviceGetUuid((CUuuid *)&dev_select.uuid,
1021 cu_internal->cuda_device));
1023 av_log(ctx, AV_LOG_ERROR, "Unable to get UUID from CUDA!\n");
1024 return AVERROR_EXTERNAL;
1027 dev_select.has_uuid = 1;
1029 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1033 return AVERROR(ENOSYS);
1037 static int vulkan_frames_get_constraints(AVHWDeviceContext *ctx,
1038 const void *hwconfig,
1039 AVHWFramesConstraints *constraints)
1042 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1043 VulkanDevicePriv *p = ctx->internal->priv;
1045 for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
1046 count += pixfmt_is_supported(hwctx, i, p->use_linear_images);
1049 if (p->dev_is_nvidia)
1053 constraints->valid_sw_formats = av_malloc_array(count + 1,
1054 sizeof(enum AVPixelFormat));
1055 if (!constraints->valid_sw_formats)
1056 return AVERROR(ENOMEM);
1059 for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
1060 if (pixfmt_is_supported(hwctx, i, p->use_linear_images))
1061 constraints->valid_sw_formats[count++] = i;
1064 if (p->dev_is_nvidia)
1065 constraints->valid_sw_formats[count++] = AV_PIX_FMT_CUDA;
1067 constraints->valid_sw_formats[count++] = AV_PIX_FMT_NONE;
1069 constraints->min_width = 0;
1070 constraints->min_height = 0;
1071 constraints->max_width = p->props.limits.maxImageDimension2D;
1072 constraints->max_height = p->props.limits.maxImageDimension2D;
1074 constraints->valid_hw_formats = av_malloc_array(2, sizeof(enum AVPixelFormat));
1075 if (!constraints->valid_hw_formats)
1076 return AVERROR(ENOMEM);
1078 constraints->valid_hw_formats[0] = AV_PIX_FMT_VULKAN;
1079 constraints->valid_hw_formats[1] = AV_PIX_FMT_NONE;
1084 static int alloc_mem(AVHWDeviceContext *ctx, VkMemoryRequirements *req,
1085 VkMemoryPropertyFlagBits req_flags, void *alloc_extension,
1086 VkMemoryPropertyFlagBits *mem_flags, VkDeviceMemory *mem)
1090 VulkanDevicePriv *p = ctx->internal->priv;
1091 AVVulkanDeviceContext *dev_hwctx = ctx->hwctx;
1092 VkMemoryAllocateInfo alloc_info = {
1093 .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
1094 .pNext = alloc_extension,
1097 /* Align if we need to */
1098 if (req_flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)
1099 req->size = FFALIGN(req->size, p->props.limits.minMemoryMapAlignment);
1101 alloc_info.allocationSize = req->size;
1103 /* The vulkan spec requires memory types to be sorted in the "optimal"
1104 * order, so the first matching type we find will be the best/fastest one */
1105 for (int i = 0; i < p->mprops.memoryTypeCount; i++) {
1106 /* The memory type must be supported by the requirements (bitfield) */
1107 if (!(req->memoryTypeBits & (1 << i)))
1110 /* The memory type flags must include our properties */
1111 if ((p->mprops.memoryTypes[i].propertyFlags & req_flags) != req_flags)
1114 /* Found a suitable memory type */
1120 av_log(ctx, AV_LOG_ERROR, "No memory type found for flags 0x%x\n",
1122 return AVERROR(EINVAL);
1125 alloc_info.memoryTypeIndex = index;
1127 ret = vkAllocateMemory(dev_hwctx->act_dev, &alloc_info,
1128 dev_hwctx->alloc, mem);
1129 if (ret != VK_SUCCESS) {
1130 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory: %s\n",
1132 return AVERROR(ENOMEM);
1135 *mem_flags |= p->mprops.memoryTypes[index].propertyFlags;
1140 static void vulkan_free_internal(AVVkFrameInternal *internal)
1146 if (internal->cuda_fc_ref) {
1147 AVHWFramesContext *cuda_fc = (AVHWFramesContext *)internal->cuda_fc_ref->data;
1148 int planes = av_pix_fmt_count_planes(cuda_fc->sw_format);
1149 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
1150 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
1151 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
1152 CudaFunctions *cu = cu_internal->cuda_dl;
1154 for (int i = 0; i < planes; i++) {
1155 if (internal->cu_sem[i])
1156 CHECK_CU(cu->cuDestroyExternalSemaphore(internal->cu_sem[i]));
1157 if (internal->cu_mma[i])
1158 CHECK_CU(cu->cuMipmappedArrayDestroy(internal->cu_mma[i]));
1159 if (internal->ext_mem[i])
1160 CHECK_CU(cu->cuDestroyExternalMemory(internal->ext_mem[i]));
1163 av_buffer_unref(&internal->cuda_fc_ref);
1170 static void vulkan_frame_free(void *opaque, uint8_t *data)
1172 AVVkFrame *f = (AVVkFrame *)data;
1173 AVHWFramesContext *hwfc = opaque;
1174 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1175 int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1177 vulkan_free_internal(f->internal);
1179 for (int i = 0; i < planes; i++) {
1180 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
1181 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
1182 vkDestroySemaphore(hwctx->act_dev, f->sem[i], hwctx->alloc);
1188 static int alloc_bind_mem(AVHWFramesContext *hwfc, AVVkFrame *f,
1189 void *alloc_pnext, size_t alloc_pnext_stride)
1193 AVHWDeviceContext *ctx = hwfc->device_ctx;
1194 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1195 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { { 0 } };
1197 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1199 for (int i = 0; i < planes; i++) {
1201 VkImageMemoryRequirementsInfo2 req_desc = {
1202 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
1205 VkMemoryDedicatedAllocateInfo ded_alloc = {
1206 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
1207 .pNext = (void *)(((uint8_t *)alloc_pnext) + i*alloc_pnext_stride),
1209 VkMemoryDedicatedRequirements ded_req = {
1210 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
1212 VkMemoryRequirements2 req = {
1213 .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
1217 vkGetImageMemoryRequirements2(hwctx->act_dev, &req_desc, &req);
1219 /* In case the implementation prefers/requires dedicated allocation */
1220 use_ded_mem = ded_req.prefersDedicatedAllocation |
1221 ded_req.requiresDedicatedAllocation;
1223 ded_alloc.image = f->img[i];
1225 /* Allocate memory */
1226 if ((err = alloc_mem(ctx, &req.memoryRequirements,
1227 f->tiling == VK_IMAGE_TILING_LINEAR ?
1228 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT :
1229 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1230 use_ded_mem ? &ded_alloc : (void *)ded_alloc.pNext,
1231 &f->flags, &f->mem[i])))
1234 f->size[i] = req.memoryRequirements.size;
1235 bind_info[i].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
1236 bind_info[i].image = f->img[i];
1237 bind_info[i].memory = f->mem[i];
1240 /* Bind the allocated memory to the images */
1241 ret = vkBindImageMemory2(hwctx->act_dev, planes, bind_info);
1242 if (ret != VK_SUCCESS) {
1243 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
1245 return AVERROR_EXTERNAL;
1253 PREP_MODE_RO_SHADER,
1254 PREP_MODE_EXTERNAL_EXPORT,
1257 static int prepare_frame(AVHWFramesContext *hwfc, VulkanExecCtx *ectx,
1258 AVVkFrame *frame, enum PrepMode pmode)
1262 VkImageLayout new_layout;
1263 VkAccessFlags new_access;
1264 AVHWDeviceContext *ctx = hwfc->device_ctx;
1265 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1266 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1268 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
1270 VkCommandBufferBeginInfo cmd_start = {
1271 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
1272 .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
1275 VkSubmitInfo s_info = {
1276 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
1277 .commandBufferCount = 1,
1278 .pCommandBuffers = &ectx->buf,
1280 .pSignalSemaphores = frame->sem,
1281 .signalSemaphoreCount = planes,
1284 VkPipelineStageFlagBits wait_st[AV_NUM_DATA_POINTERS];
1285 for (int i = 0; i < planes; i++)
1286 wait_st[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
1289 case PREP_MODE_WRITE:
1290 new_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
1291 new_access = VK_ACCESS_TRANSFER_WRITE_BIT;
1292 dst_qf = VK_QUEUE_FAMILY_IGNORED;
1294 case PREP_MODE_RO_SHADER:
1295 new_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
1296 new_access = VK_ACCESS_TRANSFER_READ_BIT;
1297 dst_qf = VK_QUEUE_FAMILY_IGNORED;
1299 case PREP_MODE_EXTERNAL_EXPORT:
1300 new_layout = VK_IMAGE_LAYOUT_GENERAL;
1301 new_access = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
1302 dst_qf = VK_QUEUE_FAMILY_EXTERNAL_KHR;
1303 s_info.pWaitSemaphores = frame->sem;
1304 s_info.pWaitDstStageMask = wait_st;
1305 s_info.waitSemaphoreCount = planes;
1309 ret = vkBeginCommandBuffer(ectx->buf, &cmd_start);
1310 if (ret != VK_SUCCESS)
1311 return AVERROR_EXTERNAL;
1313 /* Change the image layout to something more optimal for writes.
1314 * This also signals the newly created semaphore, making it usable
1315 * for synchronization */
1316 for (int i = 0; i < planes; i++) {
1317 img_bar[i].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1318 img_bar[i].srcAccessMask = 0x0;
1319 img_bar[i].dstAccessMask = new_access;
1320 img_bar[i].oldLayout = frame->layout[i];
1321 img_bar[i].newLayout = new_layout;
1322 img_bar[i].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1323 img_bar[i].dstQueueFamilyIndex = dst_qf;
1324 img_bar[i].image = frame->img[i];
1325 img_bar[i].subresourceRange.levelCount = 1;
1326 img_bar[i].subresourceRange.layerCount = 1;
1327 img_bar[i].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1329 frame->layout[i] = img_bar[i].newLayout;
1330 frame->access[i] = img_bar[i].dstAccessMask;
1333 vkCmdPipelineBarrier(ectx->buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
1334 VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
1335 0, NULL, 0, NULL, planes, img_bar);
1337 ret = vkEndCommandBuffer(ectx->buf);
1338 if (ret != VK_SUCCESS)
1339 return AVERROR_EXTERNAL;
1341 ret = vkQueueSubmit(ectx->queue, 1, &s_info, ectx->fence);
1342 if (ret != VK_SUCCESS) {
1343 return AVERROR_EXTERNAL;
1345 vkWaitForFences(hwctx->act_dev, 1, &ectx->fence, VK_TRUE, UINT64_MAX);
1346 vkResetFences(hwctx->act_dev, 1, &ectx->fence);
1352 static int create_frame(AVHWFramesContext *hwfc, AVVkFrame **frame,
1353 VkImageTiling tiling, VkImageUsageFlagBits usage,
1358 AVHWDeviceContext *ctx = hwfc->device_ctx;
1359 VulkanDevicePriv *p = ctx->internal->priv;
1360 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1361 enum AVPixelFormat format = hwfc->sw_format;
1362 const VkFormat *img_fmts = av_vkfmt_from_pixfmt(format);
1363 const int planes = av_pix_fmt_count_planes(format);
1365 VkExportSemaphoreCreateInfo ext_sem_info = {
1366 .sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO,
1367 .handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
1370 VkSemaphoreCreateInfo sem_spawn = {
1371 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1372 .pNext = p->extensions & EXT_EXTERNAL_FD_SEM ? &ext_sem_info : NULL,
1375 AVVkFrame *f = av_vk_frame_alloc();
1377 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1378 return AVERROR(ENOMEM);
1381 /* Create the images */
1382 for (int i = 0; i < planes; i++) {
1383 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
1384 int w = hwfc->width;
1385 int h = hwfc->height;
1386 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
1387 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
1389 VkImageCreateInfo image_create_info = {
1390 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1391 .pNext = create_pnext,
1392 .imageType = VK_IMAGE_TYPE_2D,
1393 .format = img_fmts[i],
1394 .extent.width = p_w,
1395 .extent.height = p_h,
1399 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1401 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1403 .samples = VK_SAMPLE_COUNT_1_BIT,
1404 .pQueueFamilyIndices = p->qfs,
1405 .queueFamilyIndexCount = p->num_qfs,
1406 .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
1407 VK_SHARING_MODE_EXCLUSIVE,
1410 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
1411 hwctx->alloc, &f->img[i]);
1412 if (ret != VK_SUCCESS) {
1413 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1415 err = AVERROR(EINVAL);
1419 /* Create semaphore */
1420 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1421 hwctx->alloc, &f->sem[i]);
1422 if (ret != VK_SUCCESS) {
1423 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1425 return AVERROR_EXTERNAL;
1428 f->layout[i] = image_create_info.initialLayout;
1439 vulkan_frame_free(hwfc, (uint8_t *)f);
1443 /* Checks if an export flag is enabled, and if it is ORs it with *iexp */
1444 static void try_export_flags(AVHWFramesContext *hwfc,
1445 VkExternalMemoryHandleTypeFlags *comp_handle_types,
1446 VkExternalMemoryHandleTypeFlagBits *iexp,
1447 VkExternalMemoryHandleTypeFlagBits exp)
1450 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1451 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1452 VkExternalImageFormatProperties eprops = {
1453 .sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES_KHR,
1455 VkImageFormatProperties2 props = {
1456 .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,
1459 VkPhysicalDeviceExternalImageFormatInfo enext = {
1460 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
1463 VkPhysicalDeviceImageFormatInfo2 pinfo = {
1464 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1465 .pNext = !exp ? NULL : &enext,
1466 .format = av_vkfmt_from_pixfmt(hwfc->sw_format)[0],
1467 .type = VK_IMAGE_TYPE_2D,
1468 .tiling = hwctx->tiling,
1469 .usage = hwctx->usage,
1470 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1473 ret = vkGetPhysicalDeviceImageFormatProperties2(dev_hwctx->phys_dev,
1475 if (ret == VK_SUCCESS) {
1477 *comp_handle_types |= eprops.externalMemoryProperties.compatibleHandleTypes;
1481 static AVBufferRef *vulkan_pool_alloc(void *opaque, int size)
1485 AVBufferRef *avbuf = NULL;
1486 AVHWFramesContext *hwfc = opaque;
1487 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1488 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1489 VkExportMemoryAllocateInfo eminfo[AV_NUM_DATA_POINTERS];
1490 VkExternalMemoryHandleTypeFlags e = 0x0;
1492 VkExternalMemoryImageCreateInfo eiinfo = {
1493 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1494 .pNext = hwctx->create_pnext,
1497 if (p->extensions & EXT_EXTERNAL_FD_MEMORY)
1498 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1499 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT);
1501 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
1502 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1503 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
1505 for (int i = 0; i < av_pix_fmt_count_planes(hwfc->sw_format); i++) {
1506 eminfo[i].sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO;
1507 eminfo[i].pNext = hwctx->alloc_pnext[i];
1508 eminfo[i].handleTypes = e;
1511 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1512 eiinfo.handleTypes ? &eiinfo : NULL);
1516 err = alloc_bind_mem(hwfc, f, eminfo, sizeof(*eminfo));
1520 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_WRITE);
1524 avbuf = av_buffer_create((uint8_t *)f, sizeof(AVVkFrame),
1525 vulkan_frame_free, hwfc, 0);
1532 vulkan_frame_free(hwfc, (uint8_t *)f);
1536 static void vulkan_frames_uninit(AVHWFramesContext *hwfc)
1538 VulkanFramesPriv *fp = hwfc->internal->priv;
1540 free_exec_ctx(hwfc->device_ctx, &fp->cmd);
1543 static int vulkan_frames_init(AVHWFramesContext *hwfc)
1547 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1548 VulkanFramesPriv *fp = hwfc->internal->priv;
1549 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1550 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1555 /* Default pool flags */
1556 hwctx->tiling = hwctx->tiling ? hwctx->tiling : p->use_linear_images ?
1557 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1559 hwctx->usage |= DEFAULT_USAGE_FLAGS;
1561 err = create_exec_ctx(hwfc->device_ctx, &fp->cmd,
1562 dev_hwctx->queue_family_tx_index);
1566 /* Test to see if allocation will fail */
1567 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1568 hwctx->create_pnext);
1570 free_exec_ctx(hwfc->device_ctx, &p->cmd);
1574 vulkan_frame_free(hwfc, (uint8_t *)f);
1576 hwfc->internal->pool_internal = av_buffer_pool_init2(sizeof(AVVkFrame),
1577 hwfc, vulkan_pool_alloc,
1579 if (!hwfc->internal->pool_internal) {
1580 free_exec_ctx(hwfc->device_ctx, &p->cmd);
1581 return AVERROR(ENOMEM);
1587 static int vulkan_get_buffer(AVHWFramesContext *hwfc, AVFrame *frame)
1589 frame->buf[0] = av_buffer_pool_get(hwfc->pool);
1591 return AVERROR(ENOMEM);
1593 frame->data[0] = frame->buf[0]->data;
1594 frame->format = AV_PIX_FMT_VULKAN;
1595 frame->width = hwfc->width;
1596 frame->height = hwfc->height;
1601 static int vulkan_transfer_get_formats(AVHWFramesContext *hwfc,
1602 enum AVHWFrameTransferDirection dir,
1603 enum AVPixelFormat **formats)
1605 enum AVPixelFormat *fmts = av_malloc_array(2, sizeof(*fmts));
1607 return AVERROR(ENOMEM);
1609 fmts[0] = hwfc->sw_format;
1610 fmts[1] = AV_PIX_FMT_NONE;
1616 typedef struct VulkanMapping {
1621 static void vulkan_unmap_frame(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1623 VulkanMapping *map = hwmap->priv;
1624 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1625 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1627 /* Check if buffer needs flushing */
1628 if ((map->flags & AV_HWFRAME_MAP_WRITE) &&
1629 !(map->frame->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1631 VkMappedMemoryRange flush_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1633 for (int i = 0; i < planes; i++) {
1634 flush_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1635 flush_ranges[i].memory = map->frame->mem[i];
1636 flush_ranges[i].size = VK_WHOLE_SIZE;
1639 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, planes,
1641 if (ret != VK_SUCCESS) {
1642 av_log(hwfc, AV_LOG_ERROR, "Failed to flush memory: %s\n",
1647 for (int i = 0; i < planes; i++)
1648 vkUnmapMemory(hwctx->act_dev, map->frame->mem[i]);
1653 static int vulkan_map_frame_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
1654 const AVFrame *src, int flags)
1657 int err, mapped_mem_count = 0;
1658 AVVkFrame *f = (AVVkFrame *)src->data[0];
1659 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1660 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1662 VulkanMapping *map = av_mallocz(sizeof(VulkanMapping));
1664 return AVERROR(EINVAL);
1666 if (src->format != AV_PIX_FMT_VULKAN) {
1667 av_log(hwfc, AV_LOG_ERROR, "Cannot map from pixel format %s!\n",
1668 av_get_pix_fmt_name(src->format));
1669 err = AVERROR(EINVAL);
1673 if (!(f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ||
1674 !(f->tiling == VK_IMAGE_TILING_LINEAR)) {
1675 av_log(hwfc, AV_LOG_ERROR, "Unable to map frame, not host visible "
1677 err = AVERROR(EINVAL);
1681 dst->width = src->width;
1682 dst->height = src->height;
1684 for (int i = 0; i < planes; i++) {
1685 ret = vkMapMemory(hwctx->act_dev, f->mem[i], 0,
1686 VK_WHOLE_SIZE, 0, (void **)&dst->data[i]);
1687 if (ret != VK_SUCCESS) {
1688 av_log(hwfc, AV_LOG_ERROR, "Failed to map image memory: %s\n",
1690 err = AVERROR_EXTERNAL;
1696 /* Check if the memory contents matter */
1697 if (((flags & AV_HWFRAME_MAP_READ) || !(flags & AV_HWFRAME_MAP_OVERWRITE)) &&
1698 !(f->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1699 VkMappedMemoryRange map_mem_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1700 for (int i = 0; i < planes; i++) {
1701 map_mem_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1702 map_mem_ranges[i].size = VK_WHOLE_SIZE;
1703 map_mem_ranges[i].memory = f->mem[i];
1706 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, planes,
1708 if (ret != VK_SUCCESS) {
1709 av_log(hwfc, AV_LOG_ERROR, "Failed to invalidate memory: %s\n",
1711 err = AVERROR_EXTERNAL;
1716 for (int i = 0; i < planes; i++) {
1717 VkImageSubresource sub = {
1718 .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
1720 VkSubresourceLayout layout;
1721 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
1722 dst->linesize[i] = layout.rowPitch;
1728 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src,
1729 &vulkan_unmap_frame, map);
1736 for (int i = 0; i < mapped_mem_count; i++)
1737 vkUnmapMemory(hwctx->act_dev, f->mem[i]);
1744 static void vulkan_unmap_from(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1746 VulkanMapping *map = hwmap->priv;
1747 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1748 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1750 for (int i = 0; i < planes; i++) {
1751 vkDestroyImage(hwctx->act_dev, map->frame->img[i], hwctx->alloc);
1752 vkFreeMemory(hwctx->act_dev, map->frame->mem[i], hwctx->alloc);
1753 vkDestroySemaphore(hwctx->act_dev, map->frame->sem[i], hwctx->alloc);
1756 av_freep(&map->frame);
1759 static const struct {
1760 uint32_t drm_fourcc;
1762 } vulkan_drm_format_map[] = {
1763 { DRM_FORMAT_R8, VK_FORMAT_R8_UNORM },
1764 { DRM_FORMAT_R16, VK_FORMAT_R16_UNORM },
1765 { DRM_FORMAT_GR88, VK_FORMAT_R8G8_UNORM },
1766 { DRM_FORMAT_RG88, VK_FORMAT_R8G8_UNORM },
1767 { DRM_FORMAT_GR1616, VK_FORMAT_R16G16_UNORM },
1768 { DRM_FORMAT_RG1616, VK_FORMAT_R16G16_UNORM },
1769 { DRM_FORMAT_ARGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1770 { DRM_FORMAT_XRGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1771 { DRM_FORMAT_ABGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1772 { DRM_FORMAT_XBGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1775 static inline VkFormat drm_to_vulkan_fmt(uint32_t drm_fourcc)
1777 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
1778 if (vulkan_drm_format_map[i].drm_fourcc == drm_fourcc)
1779 return vulkan_drm_format_map[i].vk_format;
1780 return VK_FORMAT_UNDEFINED;
1783 static int vulkan_map_from_drm_frame_desc(AVHWFramesContext *hwfc, AVVkFrame **frame,
1784 AVDRMFrameDescriptor *desc)
1789 int bind_counts = 0;
1790 AVHWDeviceContext *ctx = hwfc->device_ctx;
1791 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1792 VulkanDevicePriv *p = ctx->internal->priv;
1793 const AVPixFmtDescriptor *fmt_desc = av_pix_fmt_desc_get(hwfc->sw_format);
1794 const int has_modifiers = p->extensions & EXT_DRM_MODIFIER_FLAGS;
1795 VkSubresourceLayout plane_data[AV_NUM_DATA_POINTERS] = { 0 };
1796 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { 0 };
1797 VkBindImagePlaneMemoryInfo plane_info[AV_NUM_DATA_POINTERS] = { 0 };
1798 VkExternalMemoryHandleTypeFlagBits htype = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
1800 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdPropertiesKHR);
1802 for (int i = 0; i < desc->nb_layers; i++) {
1803 if (drm_to_vulkan_fmt(desc->layers[i].format) == VK_FORMAT_UNDEFINED) {
1804 av_log(ctx, AV_LOG_ERROR, "Unsupported DMABUF layer format %#08x!\n",
1805 desc->layers[i].format);
1806 return AVERROR(EINVAL);
1810 if (!(f = av_vk_frame_alloc())) {
1811 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1812 err = AVERROR(ENOMEM);
1816 for (int i = 0; i < desc->nb_objects; i++) {
1817 VkMemoryFdPropertiesKHR fdmp = {
1818 .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,
1820 VkMemoryRequirements req = {
1821 .size = desc->objects[i].size,
1823 VkImportMemoryFdInfoKHR idesc = {
1824 .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
1825 .handleType = htype,
1826 .fd = dup(desc->objects[i].fd),
1829 ret = pfn_vkGetMemoryFdPropertiesKHR(hwctx->act_dev, htype,
1831 if (ret != VK_SUCCESS) {
1832 av_log(hwfc, AV_LOG_ERROR, "Failed to get FD properties: %s\n",
1834 err = AVERROR_EXTERNAL;
1839 req.memoryTypeBits = fdmp.memoryTypeBits;
1841 err = alloc_mem(ctx, &req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1842 &idesc, &f->flags, &f->mem[i]);
1848 f->size[i] = desc->objects[i].size;
1851 f->tiling = has_modifiers ? VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT :
1852 desc->objects[0].format_modifier == DRM_FORMAT_MOD_LINEAR ?
1853 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1855 for (int i = 0; i < desc->nb_layers; i++) {
1856 const int planes = desc->layers[i].nb_planes;
1857 const int signal_p = has_modifiers && (planes > 1);
1859 VkImageDrmFormatModifierExplicitCreateInfoEXT drm_info = {
1860 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
1861 .drmFormatModifier = desc->objects[0].format_modifier,
1862 .drmFormatModifierPlaneCount = planes,
1863 .pPlaneLayouts = (const VkSubresourceLayout *)&plane_data,
1866 VkExternalMemoryImageCreateInfo einfo = {
1867 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1868 .pNext = has_modifiers ? &drm_info : NULL,
1869 .handleTypes = htype,
1872 VkSemaphoreCreateInfo sem_spawn = {
1873 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1876 const int p_w = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, fmt_desc->log2_chroma_w) : hwfc->width;
1877 const int p_h = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, fmt_desc->log2_chroma_h) : hwfc->height;
1879 VkImageCreateInfo image_create_info = {
1880 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1882 .imageType = VK_IMAGE_TYPE_2D,
1883 .format = drm_to_vulkan_fmt(desc->layers[i].format),
1884 .extent.width = p_w,
1885 .extent.height = p_h,
1889 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1890 .tiling = f->tiling,
1891 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, /* specs say so */
1892 .usage = DEFAULT_USAGE_FLAGS,
1893 .samples = VK_SAMPLE_COUNT_1_BIT,
1894 .pQueueFamilyIndices = p->qfs,
1895 .queueFamilyIndexCount = p->num_qfs,
1896 .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
1897 VK_SHARING_MODE_EXCLUSIVE,
1900 for (int j = 0; j < planes; j++) {
1901 plane_data[j].offset = desc->layers[i].planes[j].offset;
1902 plane_data[j].rowPitch = desc->layers[i].planes[j].pitch;
1903 plane_data[j].size = 0; /* The specs say so for all 3 */
1904 plane_data[j].arrayPitch = 0;
1905 plane_data[j].depthPitch = 0;
1909 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
1910 hwctx->alloc, &f->img[i]);
1911 if (ret != VK_SUCCESS) {
1912 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1914 err = AVERROR(EINVAL);
1918 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1919 hwctx->alloc, &f->sem[i]);
1920 if (ret != VK_SUCCESS) {
1921 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1923 return AVERROR_EXTERNAL;
1926 /* We'd import a semaphore onto the one we created using
1927 * vkImportSemaphoreFdKHR but unfortunately neither DRM nor VAAPI
1928 * offer us anything we could import and sync with, so instead
1929 * just signal the semaphore we created. */
1931 f->layout[i] = image_create_info.initialLayout;
1934 for (int j = 0; j < planes; j++) {
1935 VkImageAspectFlagBits aspect = j == 0 ? VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
1936 j == 1 ? VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT :
1937 VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT;
1939 plane_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO;
1940 plane_info[bind_counts].planeAspect = aspect;
1942 bind_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
1943 bind_info[bind_counts].pNext = signal_p ? &plane_info[bind_counts] : NULL;
1944 bind_info[bind_counts].image = f->img[i];
1945 bind_info[bind_counts].memory = f->mem[desc->layers[i].planes[j].object_index];
1946 bind_info[bind_counts].memoryOffset = desc->layers[i].planes[j].offset;
1951 /* Bind the allocated memory to the images */
1952 ret = vkBindImageMemory2(hwctx->act_dev, bind_counts, bind_info);
1953 if (ret != VK_SUCCESS) {
1954 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
1956 return AVERROR_EXTERNAL;
1959 /* NOTE: This is completely uneccesary and unneeded once we can import
1960 * semaphores from DRM. Otherwise we have to activate the semaphores.
1961 * We're reusing the exec context that's also used for uploads/downloads. */
1962 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_RO_SHADER);
1971 for (int i = 0; i < desc->nb_layers; i++) {
1972 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
1973 vkDestroySemaphore(hwctx->act_dev, f->sem[i], hwctx->alloc);
1975 for (int i = 0; i < desc->nb_objects; i++)
1976 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
1983 static int vulkan_map_from_drm(AVHWFramesContext *hwfc, AVFrame *dst,
1984 const AVFrame *src, int flags)
1988 VulkanMapping *map = NULL;
1990 err = vulkan_map_from_drm_frame_desc(hwfc, &f,
1991 (AVDRMFrameDescriptor *)src->data[0]);
1995 /* The unmapping function will free this */
1996 dst->data[0] = (uint8_t *)f;
1997 dst->width = src->width;
1998 dst->height = src->height;
2000 map = av_mallocz(sizeof(VulkanMapping));
2007 err = ff_hwframe_map_create(dst->hw_frames_ctx, dst, src,
2008 &vulkan_unmap_from, map);
2012 av_log(hwfc, AV_LOG_DEBUG, "Mapped DRM object to Vulkan!\n");
2017 vulkan_frame_free(hwfc->device_ctx->hwctx, (uint8_t *)f);
2023 static int vulkan_map_from_vaapi(AVHWFramesContext *dst_fc,
2024 AVFrame *dst, const AVFrame *src,
2028 AVFrame *tmp = av_frame_alloc();
2029 AVHWFramesContext *vaapi_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2030 AVVAAPIDeviceContext *vaapi_ctx = vaapi_fc->device_ctx->hwctx;
2031 VASurfaceID surface_id = (VASurfaceID)(uintptr_t)src->data[3];
2034 return AVERROR(ENOMEM);
2036 /* We have to sync since like the previous comment said, no semaphores */
2037 vaSyncSurface(vaapi_ctx->display, surface_id);
2039 tmp->format = AV_PIX_FMT_DRM_PRIME;
2041 err = av_hwframe_map(tmp, src, flags);
2045 err = vulkan_map_from_drm(dst_fc, dst, tmp, flags);
2049 err = ff_hwframe_map_replace(dst, src);
2052 av_frame_free(&tmp);
2059 static int vulkan_export_to_cuda(AVHWFramesContext *hwfc,
2060 AVBufferRef *cuda_hwfc,
2061 const AVFrame *frame)
2066 AVVkFrameInternal *dst_int;
2067 AVHWDeviceContext *ctx = hwfc->device_ctx;
2068 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2069 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2070 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2071 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2072 VK_LOAD_PFN(hwctx->inst, vkGetSemaphoreFdKHR);
2074 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)cuda_hwfc->data;
2075 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2076 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2077 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2078 CudaFunctions *cu = cu_internal->cuda_dl;
2079 CUarray_format cufmt = desc->comp[0].depth > 8 ? CU_AD_FORMAT_UNSIGNED_INT16 :
2080 CU_AD_FORMAT_UNSIGNED_INT8;
2082 dst_f = (AVVkFrame *)frame->data[0];
2084 dst_int = dst_f->internal;
2085 if (!dst_int || !dst_int->cuda_fc_ref) {
2086 if (!dst_f->internal)
2087 dst_f->internal = dst_int = av_mallocz(sizeof(*dst_f->internal));
2090 err = AVERROR(ENOMEM);
2094 dst_int->cuda_fc_ref = av_buffer_ref(cuda_hwfc);
2095 if (!dst_int->cuda_fc_ref) {
2096 err = AVERROR(ENOMEM);
2100 for (int i = 0; i < planes; i++) {
2101 CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC tex_desc = {
2104 .Width = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2106 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2110 .NumChannels = 1 + ((planes == 2) && i),
2115 CUDA_EXTERNAL_MEMORY_HANDLE_DESC ext_desc = {
2116 .type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD,
2117 .size = dst_f->size[i],
2119 VkMemoryGetFdInfoKHR export_info = {
2120 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2121 .memory = dst_f->mem[i],
2122 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR,
2124 VkSemaphoreGetFdInfoKHR sem_export = {
2125 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR,
2126 .semaphore = dst_f->sem[i],
2127 .handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
2129 CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC ext_sem_desc = {
2130 .type = CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD,
2133 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2134 &ext_desc.handle.fd);
2135 if (ret != VK_SUCCESS) {
2136 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2137 err = AVERROR_EXTERNAL;
2141 ret = CHECK_CU(cu->cuImportExternalMemory(&dst_int->ext_mem[i], &ext_desc));
2143 err = AVERROR_EXTERNAL;
2147 ret = CHECK_CU(cu->cuExternalMemoryGetMappedMipmappedArray(&dst_int->cu_mma[i],
2148 dst_int->ext_mem[i],
2151 err = AVERROR_EXTERNAL;
2155 ret = CHECK_CU(cu->cuMipmappedArrayGetLevel(&dst_int->cu_array[i],
2156 dst_int->cu_mma[i], 0));
2158 err = AVERROR_EXTERNAL;
2162 ret = pfn_vkGetSemaphoreFdKHR(hwctx->act_dev, &sem_export,
2163 &ext_sem_desc.handle.fd);
2164 if (ret != VK_SUCCESS) {
2165 av_log(ctx, AV_LOG_ERROR, "Failed to export semaphore: %s\n",
2167 err = AVERROR_EXTERNAL;
2171 ret = CHECK_CU(cu->cuImportExternalSemaphore(&dst_int->cu_sem[i],
2174 err = AVERROR_EXTERNAL;
2186 static int vulkan_transfer_data_from_cuda(AVHWFramesContext *hwfc,
2187 AVFrame *dst, const AVFrame *src)
2193 AVVkFrameInternal *dst_int;
2194 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2195 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2197 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2198 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2199 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2200 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2201 CudaFunctions *cu = cu_internal->cuda_dl;
2202 CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS s_w_par[AV_NUM_DATA_POINTERS] = { 0 };
2203 CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS s_s_par[AV_NUM_DATA_POINTERS] = { 0 };
2205 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2207 err = AVERROR_EXTERNAL;
2211 dst_f = (AVVkFrame *)dst->data[0];
2213 ret = vulkan_export_to_cuda(hwfc, src->hw_frames_ctx, dst);
2217 dst_int = dst_f->internal;
2219 ret = CHECK_CU(cu->cuWaitExternalSemaphoresAsync(dst_int->cu_sem, s_w_par,
2220 planes, cuda_dev->stream));
2222 err = AVERROR_EXTERNAL;
2226 for (int i = 0; i < planes; i++) {
2227 CUDA_MEMCPY2D cpy = {
2228 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
2229 .srcDevice = (CUdeviceptr)src->data[i],
2230 .srcPitch = src->linesize[i],
2233 .dstMemoryType = CU_MEMORYTYPE_ARRAY,
2234 .dstArray = dst_int->cu_array[i],
2235 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2236 : hwfc->width) * desc->comp[i].step,
2237 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2241 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2243 err = AVERROR_EXTERNAL;
2248 ret = CHECK_CU(cu->cuSignalExternalSemaphoresAsync(dst_int->cu_sem, s_s_par,
2249 planes, cuda_dev->stream));
2251 err = AVERROR_EXTERNAL;
2255 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2257 av_log(hwfc, AV_LOG_VERBOSE, "Transfered CUDA image to Vulkan!\n");
2262 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2263 vulkan_free_internal(dst_int);
2264 dst_f->internal = NULL;
2265 av_buffer_unref(&dst->buf[0]);
2270 static int vulkan_map_to(AVHWFramesContext *hwfc, AVFrame *dst,
2271 const AVFrame *src, int flags)
2273 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2275 switch (src->format) {
2278 case AV_PIX_FMT_VAAPI:
2279 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2280 return vulkan_map_from_vaapi(hwfc, dst, src, flags);
2282 case AV_PIX_FMT_DRM_PRIME:
2283 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2284 return vulkan_map_from_drm(hwfc, dst, src, flags);
2287 return AVERROR(ENOSYS);
2292 typedef struct VulkanDRMMapping {
2293 AVDRMFrameDescriptor drm_desc;
2297 static void vulkan_unmap_to_drm(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
2299 AVDRMFrameDescriptor *drm_desc = hwmap->priv;
2301 for (int i = 0; i < drm_desc->nb_objects; i++)
2302 close(drm_desc->objects[i].fd);
2307 static inline uint32_t vulkan_fmt_to_drm(VkFormat vkfmt)
2309 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
2310 if (vulkan_drm_format_map[i].vk_format == vkfmt)
2311 return vulkan_drm_format_map[i].drm_fourcc;
2312 return DRM_FORMAT_INVALID;
2315 static int vulkan_map_to_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2316 const AVFrame *src, int flags)
2320 AVVkFrame *f = (AVVkFrame *)src->data[0];
2321 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2322 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
2323 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2324 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2325 VkImageDrmFormatModifierPropertiesEXT drm_mod = {
2326 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT,
2329 AVDRMFrameDescriptor *drm_desc = av_mallocz(sizeof(*drm_desc));
2331 return AVERROR(ENOMEM);
2333 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_EXTERNAL_EXPORT);
2337 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src, &vulkan_unmap_to_drm, drm_desc);
2341 if (p->extensions & EXT_DRM_MODIFIER_FLAGS) {
2342 VK_LOAD_PFN(hwctx->inst, vkGetImageDrmFormatModifierPropertiesEXT);
2343 ret = pfn_vkGetImageDrmFormatModifierPropertiesEXT(hwctx->act_dev, f->img[0],
2345 if (ret != VK_SUCCESS) {
2346 av_log(hwfc, AV_LOG_ERROR, "Failed to retrieve DRM format modifier!\n");
2347 err = AVERROR_EXTERNAL;
2352 for (int i = 0; (i < planes) && (f->mem[i]); i++) {
2353 VkMemoryGetFdInfoKHR export_info = {
2354 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2355 .memory = f->mem[i],
2356 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,
2359 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2360 &drm_desc->objects[i].fd);
2361 if (ret != VK_SUCCESS) {
2362 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2363 err = AVERROR_EXTERNAL;
2367 drm_desc->nb_objects++;
2368 drm_desc->objects[i].size = f->size[i];
2369 drm_desc->objects[i].format_modifier = drm_mod.drmFormatModifier;
2372 drm_desc->nb_layers = planes;
2373 for (int i = 0; i < drm_desc->nb_layers; i++) {
2374 VkSubresourceLayout layout;
2375 VkImageSubresource sub = {
2376 .aspectMask = p->extensions & EXT_DRM_MODIFIER_FLAGS ?
2377 VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2378 VK_IMAGE_ASPECT_COLOR_BIT,
2380 VkFormat plane_vkfmt = av_vkfmt_from_pixfmt(hwfc->sw_format)[i];
2382 drm_desc->layers[i].format = vulkan_fmt_to_drm(plane_vkfmt);
2383 drm_desc->layers[i].nb_planes = 1;
2385 if (drm_desc->layers[i].format == DRM_FORMAT_INVALID) {
2386 av_log(hwfc, AV_LOG_ERROR, "Cannot map to DRM layer, unsupported!\n");
2387 err = AVERROR_PATCHWELCOME;
2391 drm_desc->layers[i].planes[0].object_index = FFMIN(i, drm_desc->nb_objects - 1);
2393 if (f->tiling == VK_IMAGE_TILING_OPTIMAL)
2396 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
2397 drm_desc->layers[i].planes[0].offset = layout.offset;
2398 drm_desc->layers[i].planes[0].pitch = layout.rowPitch;
2401 dst->width = src->width;
2402 dst->height = src->height;
2403 dst->data[0] = (uint8_t *)drm_desc;
2405 av_log(hwfc, AV_LOG_VERBOSE, "Mapped AVVkFrame to a DRM object!\n");
2415 static int vulkan_map_to_vaapi(AVHWFramesContext *hwfc, AVFrame *dst,
2416 const AVFrame *src, int flags)
2419 AVFrame *tmp = av_frame_alloc();
2421 return AVERROR(ENOMEM);
2423 tmp->format = AV_PIX_FMT_DRM_PRIME;
2425 err = vulkan_map_to_drm(hwfc, tmp, src, flags);
2429 err = av_hwframe_map(dst, tmp, flags);
2433 err = ff_hwframe_map_replace(dst, src);
2436 av_frame_free(&tmp);
2442 static int vulkan_map_from(AVHWFramesContext *hwfc, AVFrame *dst,
2443 const AVFrame *src, int flags)
2445 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2447 switch (dst->format) {
2449 case AV_PIX_FMT_DRM_PRIME:
2450 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2451 return vulkan_map_to_drm(hwfc, dst, src, flags);
2453 case AV_PIX_FMT_VAAPI:
2454 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2455 return vulkan_map_to_vaapi(hwfc, dst, src, flags);
2459 return vulkan_map_frame_to_mem(hwfc, dst, src, flags);
2463 typedef struct ImageBuffer {
2466 VkMemoryPropertyFlagBits flags;
2469 static void free_buf(AVHWDeviceContext *ctx, ImageBuffer *buf)
2471 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2475 vkDestroyBuffer(hwctx->act_dev, buf->buf, hwctx->alloc);
2476 vkFreeMemory(hwctx->act_dev, buf->mem, hwctx->alloc);
2479 static int create_buf(AVHWDeviceContext *ctx, ImageBuffer *buf, int height,
2480 int *stride, VkBufferUsageFlags usage,
2481 VkMemoryPropertyFlagBits flags, void *create_pnext,
2486 VkMemoryRequirements req;
2487 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2488 VulkanDevicePriv *p = ctx->internal->priv;
2490 VkBufferCreateInfo buf_spawn = {
2491 .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
2492 .pNext = create_pnext,
2494 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
2497 *stride = FFALIGN(*stride, p->props.limits.optimalBufferCopyRowPitchAlignment);
2498 buf_spawn.size = height*(*stride);
2500 ret = vkCreateBuffer(hwctx->act_dev, &buf_spawn, NULL, &buf->buf);
2501 if (ret != VK_SUCCESS) {
2502 av_log(ctx, AV_LOG_ERROR, "Failed to create buffer: %s\n",
2504 return AVERROR_EXTERNAL;
2507 vkGetBufferMemoryRequirements(hwctx->act_dev, buf->buf, &req);
2509 err = alloc_mem(ctx, &req, flags, alloc_pnext, &buf->flags, &buf->mem);
2513 ret = vkBindBufferMemory(hwctx->act_dev, buf->buf, buf->mem, 0);
2514 if (ret != VK_SUCCESS) {
2515 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory to buffer: %s\n",
2518 return AVERROR_EXTERNAL;
2524 static int map_buffers(AVHWDeviceContext *ctx, ImageBuffer *buf, uint8_t *mem[],
2525 int nb_buffers, int invalidate)
2528 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2529 VkMappedMemoryRange invalidate_ctx[AV_NUM_DATA_POINTERS];
2530 int invalidate_count = 0;
2532 for (int i = 0; i < nb_buffers; i++) {
2533 ret = vkMapMemory(hwctx->act_dev, buf[i].mem, 0,
2534 VK_WHOLE_SIZE, 0, (void **)&mem[i]);
2535 if (ret != VK_SUCCESS) {
2536 av_log(ctx, AV_LOG_ERROR, "Failed to map buffer memory: %s\n",
2538 return AVERROR_EXTERNAL;
2545 for (int i = 0; i < nb_buffers; i++) {
2546 const VkMappedMemoryRange ival_buf = {
2547 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2548 .memory = buf[i].mem,
2549 .size = VK_WHOLE_SIZE,
2551 if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2553 invalidate_ctx[invalidate_count++] = ival_buf;
2556 if (invalidate_count) {
2557 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, invalidate_count,
2559 if (ret != VK_SUCCESS)
2560 av_log(ctx, AV_LOG_WARNING, "Failed to invalidate memory: %s\n",
2567 static int unmap_buffers(AVHWDeviceContext *ctx, ImageBuffer *buf,
2568 int nb_buffers, int flush)
2572 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2573 VkMappedMemoryRange flush_ctx[AV_NUM_DATA_POINTERS];
2574 int flush_count = 0;
2577 for (int i = 0; i < nb_buffers; i++) {
2578 const VkMappedMemoryRange flush_buf = {
2579 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2580 .memory = buf[i].mem,
2581 .size = VK_WHOLE_SIZE,
2583 if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2585 flush_ctx[flush_count++] = flush_buf;
2590 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, flush_count, flush_ctx);
2591 if (ret != VK_SUCCESS) {
2592 av_log(ctx, AV_LOG_ERROR, "Failed to flush memory: %s\n",
2594 err = AVERROR_EXTERNAL; /* We still want to try to unmap them */
2598 for (int i = 0; i < nb_buffers; i++)
2599 vkUnmapMemory(hwctx->act_dev, buf[i].mem);
2604 static int transfer_image_buf(AVHWDeviceContext *ctx, AVVkFrame *frame,
2605 ImageBuffer *buffer, const int *buf_stride, int w,
2606 int h, enum AVPixelFormat pix_fmt, int to_buf)
2609 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2610 VulkanDevicePriv *s = ctx->internal->priv;
2613 VkPipelineStageFlagBits sem_wait_dst[AV_NUM_DATA_POINTERS];
2615 const int planes = av_pix_fmt_count_planes(pix_fmt);
2616 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2618 VkCommandBufferBeginInfo cmd_start = {
2619 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
2620 .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
2623 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
2625 VkSubmitInfo s_info = {
2626 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
2627 .commandBufferCount = 1,
2628 .pCommandBuffers = &s->cmd.buf,
2629 .pSignalSemaphores = frame->sem,
2630 .pWaitSemaphores = frame->sem,
2631 .pWaitDstStageMask = sem_wait_dst,
2632 .signalSemaphoreCount = planes,
2633 .waitSemaphoreCount = planes,
2636 ret = vkBeginCommandBuffer(s->cmd.buf, &cmd_start);
2637 if (ret != VK_SUCCESS) {
2638 av_log(ctx, AV_LOG_ERROR, "Unable to init command buffer: %s\n",
2640 return AVERROR_EXTERNAL;
2643 /* Change the image layout to something more optimal for transfers */
2644 for (int i = 0; i < planes; i++) {
2645 VkImageLayout new_layout = to_buf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL :
2646 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
2647 VkAccessFlags new_access = to_buf ? VK_ACCESS_TRANSFER_READ_BIT :
2648 VK_ACCESS_TRANSFER_WRITE_BIT;
2650 sem_wait_dst[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
2652 /* If the layout matches and we have read access skip the barrier */
2653 if ((frame->layout[i] == new_layout) && (frame->access[i] & new_access))
2656 img_bar[bar_num].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
2657 img_bar[bar_num].srcAccessMask = 0x0;
2658 img_bar[bar_num].dstAccessMask = new_access;
2659 img_bar[bar_num].oldLayout = frame->layout[i];
2660 img_bar[bar_num].newLayout = new_layout;
2661 img_bar[bar_num].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2662 img_bar[bar_num].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2663 img_bar[bar_num].image = frame->img[i];
2664 img_bar[bar_num].subresourceRange.levelCount = 1;
2665 img_bar[bar_num].subresourceRange.layerCount = 1;
2666 img_bar[bar_num].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2668 frame->layout[i] = img_bar[bar_num].newLayout;
2669 frame->access[i] = img_bar[bar_num].dstAccessMask;
2675 vkCmdPipelineBarrier(s->cmd.buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
2676 VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
2677 0, NULL, 0, NULL, bar_num, img_bar);
2679 /* Schedule a copy for each plane */
2680 for (int i = 0; i < planes; i++) {
2681 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
2682 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
2683 VkBufferImageCopy buf_reg = {
2685 /* Buffer stride isn't in bytes, it's in samples, the implementation
2686 * uses the image's VkFormat to know how many bytes per sample
2687 * the buffer has. So we have to convert by dividing. Stupid.
2688 * Won't work with YUVA or other planar formats with alpha. */
2689 .bufferRowLength = buf_stride[i] / desc->comp[i].step,
2690 .bufferImageHeight = p_h,
2691 .imageSubresource.layerCount = 1,
2692 .imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
2693 .imageOffset = { 0, 0, 0, },
2694 .imageExtent = { p_w, p_h, 1, },
2698 vkCmdCopyImageToBuffer(s->cmd.buf, frame->img[i], frame->layout[i],
2699 buffer[i].buf, 1, &buf_reg);
2701 vkCmdCopyBufferToImage(s->cmd.buf, buffer[i].buf, frame->img[i],
2702 frame->layout[i], 1, &buf_reg);
2705 ret = vkEndCommandBuffer(s->cmd.buf);
2706 if (ret != VK_SUCCESS) {
2707 av_log(ctx, AV_LOG_ERROR, "Unable to finish command buffer: %s\n",
2709 return AVERROR_EXTERNAL;
2712 /* Wait for the download/upload to finish if uploading, otherwise the
2713 * semaphore will take care of synchronization when uploading */
2714 ret = vkQueueSubmit(s->cmd.queue, 1, &s_info, s->cmd.fence);
2715 if (ret != VK_SUCCESS) {
2716 av_log(ctx, AV_LOG_ERROR, "Unable to submit command buffer: %s\n",
2718 return AVERROR_EXTERNAL;
2720 vkWaitForFences(hwctx->act_dev, 1, &s->cmd.fence, VK_TRUE, UINT64_MAX);
2721 vkResetFences(hwctx->act_dev, 1, &s->cmd.fence);
2727 /* Technically we can use VK_EXT_external_memory_host to upload and download,
2728 * however the alignment requirements make this unfeasible as both the pointer
2729 * and the size of each plane need to be aligned to the minimum alignment
2730 * requirement, which on all current implementations (anv, radv) is 4096.
2731 * If the requirement gets relaxed (unlikely) this can easily be implemented. */
2732 static int vulkan_transfer_data_from_mem(AVHWFramesContext *hwfc, AVFrame *dst,
2737 AVVkFrame *f = (AVVkFrame *)dst->data[0];
2738 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
2739 ImageBuffer buf[AV_NUM_DATA_POINTERS] = { { 0 } };
2740 const int planes = av_pix_fmt_count_planes(src->format);
2741 int log2_chroma = av_pix_fmt_desc_get(src->format)->log2_chroma_h;
2743 if ((src->format != AV_PIX_FMT_NONE && !av_vkfmt_from_pixfmt(src->format))) {
2744 av_log(hwfc, AV_LOG_ERROR, "Unsupported source pixel format!\n");
2745 return AVERROR(EINVAL);
2748 if (src->width > hwfc->width || src->height > hwfc->height)
2749 return AVERROR(EINVAL);
2751 /* For linear, host visiable images */
2752 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
2753 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
2754 AVFrame *map = av_frame_alloc();
2756 return AVERROR(ENOMEM);
2757 map->format = src->format;
2759 err = vulkan_map_frame_to_mem(hwfc, map, dst, AV_HWFRAME_MAP_WRITE);
2763 err = av_frame_copy(map, src);
2764 av_frame_free(&map);
2768 /* Create buffers */
2769 for (int i = 0; i < planes; i++) {
2770 int h = src->height;
2771 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
2773 tmp.linesize[i] = FFABS(src->linesize[i]);
2774 err = create_buf(dev_ctx, &buf[i], p_height,
2775 &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
2776 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
2781 /* Map, copy image to buffer, unmap */
2782 if ((err = map_buffers(dev_ctx, buf, tmp.data, planes, 0)))
2785 av_image_copy(tmp.data, tmp.linesize, (const uint8_t **)src->data,
2786 src->linesize, src->format, src->width, src->height);
2788 if ((err = unmap_buffers(dev_ctx, buf, planes, 1)))
2791 /* Copy buffers to image */
2792 err = transfer_image_buf(dev_ctx, f, buf, tmp.linesize,
2793 src->width, src->height, src->format, 0);
2796 for (int i = 0; i < planes; i++)
2797 free_buf(dev_ctx, &buf[i]);
2802 static int vulkan_transfer_data_to(AVHWFramesContext *hwfc, AVFrame *dst,
2805 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2807 switch (src->format) {
2809 case AV_PIX_FMT_CUDA:
2810 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
2811 (p->extensions & EXT_EXTERNAL_FD_SEM))
2812 return vulkan_transfer_data_from_cuda(hwfc, dst, src);
2815 if (src->hw_frames_ctx)
2816 return AVERROR(ENOSYS);
2818 return vulkan_transfer_data_from_mem(hwfc, dst, src);
2823 static int vulkan_transfer_data_to_cuda(AVHWFramesContext *hwfc, AVFrame *dst,
2830 AVVkFrameInternal *dst_int;
2831 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2832 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2834 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)dst->hw_frames_ctx->data;
2835 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2836 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2837 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2838 CudaFunctions *cu = cu_internal->cuda_dl;
2840 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2842 err = AVERROR_EXTERNAL;
2846 dst_f = (AVVkFrame *)src->data[0];
2848 err = vulkan_export_to_cuda(hwfc, dst->hw_frames_ctx, src);
2853 dst_int = dst_f->internal;
2855 for (int i = 0; i < planes; i++) {
2856 CUDA_MEMCPY2D cpy = {
2857 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
2858 .dstDevice = (CUdeviceptr)dst->data[i],
2859 .dstPitch = dst->linesize[i],
2862 .srcMemoryType = CU_MEMORYTYPE_ARRAY,
2863 .srcArray = dst_int->cu_array[i],
2864 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2865 : hwfc->width) * desc->comp[i].step,
2866 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2870 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2872 err = AVERROR_EXTERNAL;
2877 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2879 av_log(hwfc, AV_LOG_VERBOSE, "Transfered Vulkan image to CUDA!\n");
2884 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2885 vulkan_free_internal(dst_int);
2886 dst_f->internal = NULL;
2887 av_buffer_unref(&dst->buf[0]);
2892 static int vulkan_transfer_data_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
2897 AVVkFrame *f = (AVVkFrame *)src->data[0];
2898 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
2899 ImageBuffer buf[AV_NUM_DATA_POINTERS] = { { 0 } };
2900 const int planes = av_pix_fmt_count_planes(dst->format);
2901 int log2_chroma = av_pix_fmt_desc_get(dst->format)->log2_chroma_h;
2903 if (dst->width > hwfc->width || dst->height > hwfc->height)
2904 return AVERROR(EINVAL);
2906 /* For linear, host visiable images */
2907 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
2908 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
2909 AVFrame *map = av_frame_alloc();
2911 return AVERROR(ENOMEM);
2912 map->format = dst->format;
2914 err = vulkan_map_frame_to_mem(hwfc, map, src, AV_HWFRAME_MAP_READ);
2918 err = av_frame_copy(dst, map);
2919 av_frame_free(&map);
2923 /* Create buffers */
2924 for (int i = 0; i < planes; i++) {
2925 int h = dst->height;
2926 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
2928 tmp.linesize[i] = FFABS(dst->linesize[i]);
2929 err = create_buf(dev_ctx, &buf[i], p_height,
2930 &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_DST_BIT,
2931 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
2934 /* Copy image to buffer */
2935 if ((err = transfer_image_buf(dev_ctx, f, buf, tmp.linesize,
2936 dst->width, dst->height, dst->format, 1)))
2939 /* Map, copy buffer to frame, unmap */
2940 if ((err = map_buffers(dev_ctx, buf, tmp.data, planes, 1)))
2943 av_image_copy(dst->data, dst->linesize, (const uint8_t **)tmp.data,
2944 tmp.linesize, dst->format, dst->width, dst->height);
2946 err = unmap_buffers(dev_ctx, buf, planes, 0);
2949 for (int i = 0; i < planes; i++)
2950 free_buf(dev_ctx, &buf[i]);
2955 static int vulkan_transfer_data_from(AVHWFramesContext *hwfc, AVFrame *dst,
2958 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2960 switch (dst->format) {
2962 case AV_PIX_FMT_CUDA:
2963 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
2964 (p->extensions & EXT_EXTERNAL_FD_SEM))
2965 return vulkan_transfer_data_to_cuda(hwfc, dst, src);
2968 if (dst->hw_frames_ctx)
2969 return AVERROR(ENOSYS);
2971 return vulkan_transfer_data_to_mem(hwfc, dst, src);
2975 AVVkFrame *av_vk_frame_alloc(void)
2977 return av_mallocz(sizeof(AVVkFrame));
2980 const HWContextType ff_hwcontext_type_vulkan = {
2981 .type = AV_HWDEVICE_TYPE_VULKAN,
2984 .device_hwctx_size = sizeof(AVVulkanDeviceContext),
2985 .device_priv_size = sizeof(VulkanDevicePriv),
2986 .frames_hwctx_size = sizeof(AVVulkanFramesContext),
2987 .frames_priv_size = sizeof(VulkanFramesPriv),
2989 .device_init = &vulkan_device_init,
2990 .device_create = &vulkan_device_create,
2991 .device_derive = &vulkan_device_derive,
2993 .frames_get_constraints = &vulkan_frames_get_constraints,
2994 .frames_init = vulkan_frames_init,
2995 .frames_get_buffer = vulkan_get_buffer,
2996 .frames_uninit = vulkan_frames_uninit,
2998 .transfer_get_formats = vulkan_transfer_get_formats,
2999 .transfer_data_to = vulkan_transfer_data_to,
3000 .transfer_data_from = vulkan_transfer_data_from,
3002 .map_to = vulkan_map_to,
3003 .map_from = vulkan_map_from,
3005 .pix_fmts = (const enum AVPixelFormat []) {