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 VkDeviceQueueCreateInfo queue_create_info[3] = {
811 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, },
812 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, },
813 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, },
816 VkDeviceCreateInfo dev_info = {
817 .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
818 .pQueueCreateInfos = queue_create_info,
819 .queueCreateInfoCount = 0,
822 ctx->free = vulkan_device_free;
824 /* Create an instance if not given one */
825 if ((err = create_instance(ctx, opts)))
828 /* Find a device (if not given one) */
829 if ((err = find_device(ctx, dev_select)))
832 vkGetPhysicalDeviceProperties(hwctx->phys_dev, &p->props);
833 av_log(ctx, AV_LOG_VERBOSE, "Using device: %s\n", p->props.deviceName);
834 av_log(ctx, AV_LOG_VERBOSE, "Alignments:\n");
835 av_log(ctx, AV_LOG_VERBOSE, " optimalBufferCopyOffsetAlignment: %li\n",
836 p->props.limits.optimalBufferCopyOffsetAlignment);
837 av_log(ctx, AV_LOG_VERBOSE, " optimalBufferCopyRowPitchAlignment: %li\n",
838 p->props.limits.optimalBufferCopyRowPitchAlignment);
839 av_log(ctx, AV_LOG_VERBOSE, " minMemoryMapAlignment: %li\n",
840 p->props.limits.minMemoryMapAlignment);
842 /* Search queue family */
843 if ((err = search_queue_families(ctx, &dev_info)))
846 if ((err = check_extensions(ctx, 1, opts, &dev_info.ppEnabledExtensionNames,
847 &dev_info.enabledExtensionCount, 0))) {
848 av_free((void *)queue_create_info[0].pQueuePriorities);
849 av_free((void *)queue_create_info[1].pQueuePriorities);
850 av_free((void *)queue_create_info[2].pQueuePriorities);
854 ret = vkCreateDevice(hwctx->phys_dev, &dev_info, hwctx->alloc,
857 av_free((void *)queue_create_info[0].pQueuePriorities);
858 av_free((void *)queue_create_info[1].pQueuePriorities);
859 av_free((void *)queue_create_info[2].pQueuePriorities);
861 if (ret != VK_SUCCESS) {
862 av_log(ctx, AV_LOG_ERROR, "Device creation failure: %s\n",
864 for (int i = 0; i < dev_info.enabledExtensionCount; i++)
865 av_free((void *)dev_info.ppEnabledExtensionNames[i]);
866 av_free((void *)dev_info.ppEnabledExtensionNames);
867 err = AVERROR_EXTERNAL;
871 /* Tiled images setting, use them by default */
872 opt_d = av_dict_get(opts, "linear_images", NULL, 0);
874 p->use_linear_images = strtol(opt_d->value, NULL, 10);
876 hwctx->enabled_dev_extensions = dev_info.ppEnabledExtensionNames;
877 hwctx->nb_enabled_dev_extensions = dev_info.enabledExtensionCount;
883 static int vulkan_device_init(AVHWDeviceContext *ctx)
887 AVVulkanDeviceContext *hwctx = ctx->hwctx;
888 VulkanDevicePriv *p = ctx->internal->priv;
890 /* Set device extension flags */
891 for (int i = 0; i < hwctx->nb_enabled_dev_extensions; i++) {
892 for (int j = 0; j < FF_ARRAY_ELEMS(optional_device_exts); j++) {
893 if (!strcmp(hwctx->enabled_dev_extensions[i],
894 optional_device_exts[j].name)) {
895 p->extensions |= optional_device_exts[j].flag;
901 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &queue_num, NULL);
903 av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
904 return AVERROR_EXTERNAL;
907 #define CHECK_QUEUE(type, n) \
908 if (n >= queue_num) { \
909 av_log(ctx, AV_LOG_ERROR, "Invalid %s queue index %i (device has %i queues)!\n", \
910 type, n, queue_num); \
911 return AVERROR(EINVAL); \
914 CHECK_QUEUE("graphics", hwctx->queue_family_index)
915 CHECK_QUEUE("upload", hwctx->queue_family_tx_index)
916 CHECK_QUEUE("compute", hwctx->queue_family_comp_index)
920 p->qfs[p->num_qfs++] = hwctx->queue_family_index;
921 if ((hwctx->queue_family_tx_index != hwctx->queue_family_index) &&
922 (hwctx->queue_family_tx_index != hwctx->queue_family_comp_index))
923 p->qfs[p->num_qfs++] = hwctx->queue_family_tx_index;
924 if ((hwctx->queue_family_comp_index != hwctx->queue_family_index) &&
925 (hwctx->queue_family_comp_index != hwctx->queue_family_tx_index))
926 p->qfs[p->num_qfs++] = hwctx->queue_family_comp_index;
928 /* Create exec context - if there's something invalid this will error out */
929 err = create_exec_ctx(ctx, &p->cmd, hwctx->queue_family_tx_index);
933 /* Get device capabilities */
934 vkGetPhysicalDeviceMemoryProperties(hwctx->phys_dev, &p->mprops);
939 static int vulkan_device_create(AVHWDeviceContext *ctx, const char *device,
940 AVDictionary *opts, int flags)
942 VulkanDeviceSelection dev_select = { 0 };
943 if (device && device[0]) {
945 dev_select.index = strtol(device, &end, 10);
947 dev_select.index = 0;
948 dev_select.name = device;
952 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
955 static int vulkan_device_derive(AVHWDeviceContext *ctx,
956 AVHWDeviceContext *src_ctx,
957 AVDictionary *opts, int flags)
959 av_unused VulkanDeviceSelection dev_select = { 0 };
961 /* If there's only one device on the system, then even if its not covered
962 * by the following checks (e.g. non-PCIe ARM GPU), having an empty
963 * dev_select will mean it'll get picked. */
964 switch(src_ctx->type) {
967 case AV_HWDEVICE_TYPE_VAAPI: {
968 AVVAAPIDeviceContext *src_hwctx = src_ctx->hwctx;
970 const char *vendor = vaQueryVendorString(src_hwctx->display);
972 av_log(ctx, AV_LOG_ERROR, "Unable to get device info from VAAPI!\n");
973 return AVERROR_EXTERNAL;
976 if (strstr(vendor, "Intel"))
977 dev_select.vendor_id = 0x8086;
978 if (strstr(vendor, "AMD"))
979 dev_select.vendor_id = 0x1002;
981 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
984 case AV_HWDEVICE_TYPE_DRM: {
985 AVDRMDeviceContext *src_hwctx = src_ctx->hwctx;
987 drmDevice *drm_dev_info;
988 int err = drmGetDevice(src_hwctx->fd, &drm_dev_info);
990 av_log(ctx, AV_LOG_ERROR, "Unable to get device info from DRM fd!\n");
991 return AVERROR_EXTERNAL;
994 if (drm_dev_info->bustype == DRM_BUS_PCI)
995 dev_select.pci_device = drm_dev_info->deviceinfo.pci->device_id;
997 drmFreeDevice(&drm_dev_info);
999 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1003 case AV_HWDEVICE_TYPE_CUDA: {
1004 AVHWDeviceContext *cuda_cu = src_ctx;
1005 AVCUDADeviceContext *src_hwctx = src_ctx->hwctx;
1006 AVCUDADeviceContextInternal *cu_internal = src_hwctx->internal;
1007 CudaFunctions *cu = cu_internal->cuda_dl;
1009 int ret = CHECK_CU(cu->cuDeviceGetUuid((CUuuid *)&dev_select.uuid,
1010 cu_internal->cuda_device));
1012 av_log(ctx, AV_LOG_ERROR, "Unable to get UUID from CUDA!\n");
1013 return AVERROR_EXTERNAL;
1016 dev_select.has_uuid = 1;
1018 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1022 return AVERROR(ENOSYS);
1026 static int vulkan_frames_get_constraints(AVHWDeviceContext *ctx,
1027 const void *hwconfig,
1028 AVHWFramesConstraints *constraints)
1031 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1032 VulkanDevicePriv *p = ctx->internal->priv;
1034 for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
1035 count += pixfmt_is_supported(hwctx, i, p->use_linear_images);
1038 if (p->dev_is_nvidia)
1042 constraints->valid_sw_formats = av_malloc_array(count + 1,
1043 sizeof(enum AVPixelFormat));
1044 if (!constraints->valid_sw_formats)
1045 return AVERROR(ENOMEM);
1048 for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
1049 if (pixfmt_is_supported(hwctx, i, p->use_linear_images))
1050 constraints->valid_sw_formats[count++] = i;
1053 if (p->dev_is_nvidia)
1054 constraints->valid_sw_formats[count++] = AV_PIX_FMT_CUDA;
1056 constraints->valid_sw_formats[count++] = AV_PIX_FMT_NONE;
1058 constraints->min_width = 0;
1059 constraints->min_height = 0;
1060 constraints->max_width = p->props.limits.maxImageDimension2D;
1061 constraints->max_height = p->props.limits.maxImageDimension2D;
1063 constraints->valid_hw_formats = av_malloc_array(2, sizeof(enum AVPixelFormat));
1064 if (!constraints->valid_hw_formats)
1065 return AVERROR(ENOMEM);
1067 constraints->valid_hw_formats[0] = AV_PIX_FMT_VULKAN;
1068 constraints->valid_hw_formats[1] = AV_PIX_FMT_NONE;
1073 static int alloc_mem(AVHWDeviceContext *ctx, VkMemoryRequirements *req,
1074 VkMemoryPropertyFlagBits req_flags, void *alloc_extension,
1075 VkMemoryPropertyFlagBits *mem_flags, VkDeviceMemory *mem)
1079 VulkanDevicePriv *p = ctx->internal->priv;
1080 AVVulkanDeviceContext *dev_hwctx = ctx->hwctx;
1081 VkMemoryAllocateInfo alloc_info = {
1082 .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
1083 .pNext = alloc_extension,
1086 /* Align if we need to */
1087 if (req_flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)
1088 req->size = FFALIGN(req->size, p->props.limits.minMemoryMapAlignment);
1090 alloc_info.allocationSize = req->size;
1092 /* The vulkan spec requires memory types to be sorted in the "optimal"
1093 * order, so the first matching type we find will be the best/fastest one */
1094 for (int i = 0; i < p->mprops.memoryTypeCount; i++) {
1095 /* The memory type must be supported by the requirements (bitfield) */
1096 if (!(req->memoryTypeBits & (1 << i)))
1099 /* The memory type flags must include our properties */
1100 if ((p->mprops.memoryTypes[i].propertyFlags & req_flags) != req_flags)
1103 /* Found a suitable memory type */
1109 av_log(ctx, AV_LOG_ERROR, "No memory type found for flags 0x%x\n",
1111 return AVERROR(EINVAL);
1114 alloc_info.memoryTypeIndex = index;
1116 ret = vkAllocateMemory(dev_hwctx->act_dev, &alloc_info,
1117 dev_hwctx->alloc, mem);
1118 if (ret != VK_SUCCESS) {
1119 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory: %s\n",
1121 return AVERROR(ENOMEM);
1124 *mem_flags |= p->mprops.memoryTypes[index].propertyFlags;
1129 static void vulkan_free_internal(AVVkFrameInternal *internal)
1135 if (internal->cuda_fc_ref) {
1136 AVHWFramesContext *cuda_fc = (AVHWFramesContext *)internal->cuda_fc_ref->data;
1137 int planes = av_pix_fmt_count_planes(cuda_fc->sw_format);
1138 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
1139 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
1140 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
1141 CudaFunctions *cu = cu_internal->cuda_dl;
1143 for (int i = 0; i < planes; i++) {
1144 if (internal->cu_sem[i])
1145 CHECK_CU(cu->cuDestroyExternalSemaphore(internal->cu_sem[i]));
1146 if (internal->cu_mma[i])
1147 CHECK_CU(cu->cuMipmappedArrayDestroy(internal->cu_mma[i]));
1148 if (internal->ext_mem[i])
1149 CHECK_CU(cu->cuDestroyExternalMemory(internal->ext_mem[i]));
1152 av_buffer_unref(&internal->cuda_fc_ref);
1159 static void vulkan_frame_free(void *opaque, uint8_t *data)
1161 AVVkFrame *f = (AVVkFrame *)data;
1162 AVHWFramesContext *hwfc = opaque;
1163 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1164 int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1166 vulkan_free_internal(f->internal);
1168 for (int i = 0; i < planes; i++) {
1169 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
1170 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
1171 vkDestroySemaphore(hwctx->act_dev, f->sem[i], hwctx->alloc);
1177 static int alloc_bind_mem(AVHWFramesContext *hwfc, AVVkFrame *f,
1178 void *alloc_pnext, size_t alloc_pnext_stride)
1182 AVHWDeviceContext *ctx = hwfc->device_ctx;
1183 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1184 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { { 0 } };
1186 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1188 for (int i = 0; i < planes; i++) {
1190 VkImageMemoryRequirementsInfo2 req_desc = {
1191 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
1194 VkMemoryDedicatedAllocateInfo ded_alloc = {
1195 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
1196 .pNext = (void *)(((uint8_t *)alloc_pnext) + i*alloc_pnext_stride),
1198 VkMemoryDedicatedRequirements ded_req = {
1199 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
1201 VkMemoryRequirements2 req = {
1202 .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
1206 vkGetImageMemoryRequirements2(hwctx->act_dev, &req_desc, &req);
1208 /* In case the implementation prefers/requires dedicated allocation */
1209 use_ded_mem = ded_req.prefersDedicatedAllocation |
1210 ded_req.requiresDedicatedAllocation;
1212 ded_alloc.image = f->img[i];
1214 /* Allocate memory */
1215 if ((err = alloc_mem(ctx, &req.memoryRequirements,
1216 f->tiling == VK_IMAGE_TILING_LINEAR ?
1217 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT :
1218 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1219 use_ded_mem ? &ded_alloc : (void *)ded_alloc.pNext,
1220 &f->flags, &f->mem[i])))
1223 f->size[i] = req.memoryRequirements.size;
1224 bind_info[i].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
1225 bind_info[i].image = f->img[i];
1226 bind_info[i].memory = f->mem[i];
1229 /* Bind the allocated memory to the images */
1230 ret = vkBindImageMemory2(hwctx->act_dev, planes, bind_info);
1231 if (ret != VK_SUCCESS) {
1232 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
1234 return AVERROR_EXTERNAL;
1242 PREP_MODE_RO_SHADER,
1243 PREP_MODE_EXTERNAL_EXPORT,
1246 static int prepare_frame(AVHWFramesContext *hwfc, VulkanExecCtx *ectx,
1247 AVVkFrame *frame, enum PrepMode pmode)
1251 VkImageLayout new_layout;
1252 VkAccessFlags new_access;
1253 AVHWDeviceContext *ctx = hwfc->device_ctx;
1254 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1255 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1257 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
1259 VkCommandBufferBeginInfo cmd_start = {
1260 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
1261 .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
1264 VkSubmitInfo s_info = {
1265 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
1266 .commandBufferCount = 1,
1267 .pCommandBuffers = &ectx->buf,
1269 .pSignalSemaphores = frame->sem,
1270 .signalSemaphoreCount = planes,
1273 VkPipelineStageFlagBits wait_st[AV_NUM_DATA_POINTERS];
1274 for (int i = 0; i < planes; i++)
1275 wait_st[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
1278 case PREP_MODE_WRITE:
1279 new_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
1280 new_access = VK_ACCESS_TRANSFER_WRITE_BIT;
1281 dst_qf = VK_QUEUE_FAMILY_IGNORED;
1283 case PREP_MODE_RO_SHADER:
1284 new_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
1285 new_access = VK_ACCESS_TRANSFER_READ_BIT;
1286 dst_qf = VK_QUEUE_FAMILY_IGNORED;
1288 case PREP_MODE_EXTERNAL_EXPORT:
1289 new_layout = VK_IMAGE_LAYOUT_GENERAL;
1290 new_access = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
1291 dst_qf = VK_QUEUE_FAMILY_EXTERNAL_KHR;
1292 s_info.pWaitSemaphores = frame->sem;
1293 s_info.pWaitDstStageMask = wait_st;
1294 s_info.waitSemaphoreCount = planes;
1298 ret = vkBeginCommandBuffer(ectx->buf, &cmd_start);
1299 if (ret != VK_SUCCESS)
1300 return AVERROR_EXTERNAL;
1302 /* Change the image layout to something more optimal for writes.
1303 * This also signals the newly created semaphore, making it usable
1304 * for synchronization */
1305 for (int i = 0; i < planes; i++) {
1306 img_bar[i].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1307 img_bar[i].srcAccessMask = 0x0;
1308 img_bar[i].dstAccessMask = new_access;
1309 img_bar[i].oldLayout = frame->layout[i];
1310 img_bar[i].newLayout = new_layout;
1311 img_bar[i].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1312 img_bar[i].dstQueueFamilyIndex = dst_qf;
1313 img_bar[i].image = frame->img[i];
1314 img_bar[i].subresourceRange.levelCount = 1;
1315 img_bar[i].subresourceRange.layerCount = 1;
1316 img_bar[i].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1318 frame->layout[i] = img_bar[i].newLayout;
1319 frame->access[i] = img_bar[i].dstAccessMask;
1322 vkCmdPipelineBarrier(ectx->buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
1323 VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
1324 0, NULL, 0, NULL, planes, img_bar);
1326 ret = vkEndCommandBuffer(ectx->buf);
1327 if (ret != VK_SUCCESS)
1328 return AVERROR_EXTERNAL;
1330 ret = vkQueueSubmit(ectx->queue, 1, &s_info, ectx->fence);
1331 if (ret != VK_SUCCESS) {
1332 return AVERROR_EXTERNAL;
1334 vkWaitForFences(hwctx->act_dev, 1, &ectx->fence, VK_TRUE, UINT64_MAX);
1335 vkResetFences(hwctx->act_dev, 1, &ectx->fence);
1341 static int create_frame(AVHWFramesContext *hwfc, AVVkFrame **frame,
1342 VkImageTiling tiling, VkImageUsageFlagBits usage,
1347 AVHWDeviceContext *ctx = hwfc->device_ctx;
1348 VulkanDevicePriv *p = ctx->internal->priv;
1349 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1350 enum AVPixelFormat format = hwfc->sw_format;
1351 const VkFormat *img_fmts = av_vkfmt_from_pixfmt(format);
1352 const int planes = av_pix_fmt_count_planes(format);
1354 VkExportSemaphoreCreateInfo ext_sem_info = {
1355 .sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO,
1356 .handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
1359 VkSemaphoreCreateInfo sem_spawn = {
1360 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1361 .pNext = p->extensions & EXT_EXTERNAL_FD_SEM ? &ext_sem_info : NULL,
1364 AVVkFrame *f = av_vk_frame_alloc();
1366 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1367 return AVERROR(ENOMEM);
1370 /* Create the images */
1371 for (int i = 0; i < planes; i++) {
1372 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
1373 int w = hwfc->width;
1374 int h = hwfc->height;
1375 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
1376 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
1378 VkImageCreateInfo image_create_info = {
1379 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1380 .pNext = create_pnext,
1381 .imageType = VK_IMAGE_TYPE_2D,
1382 .format = img_fmts[i],
1383 .extent.width = p_w,
1384 .extent.height = p_h,
1388 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1390 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1392 .samples = VK_SAMPLE_COUNT_1_BIT,
1393 .pQueueFamilyIndices = p->qfs,
1394 .queueFamilyIndexCount = p->num_qfs,
1395 .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
1396 VK_SHARING_MODE_EXCLUSIVE,
1399 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
1400 hwctx->alloc, &f->img[i]);
1401 if (ret != VK_SUCCESS) {
1402 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1404 err = AVERROR(EINVAL);
1408 /* Create semaphore */
1409 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1410 hwctx->alloc, &f->sem[i]);
1411 if (ret != VK_SUCCESS) {
1412 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1414 return AVERROR_EXTERNAL;
1417 f->layout[i] = image_create_info.initialLayout;
1428 vulkan_frame_free(hwfc, (uint8_t *)f);
1432 /* Checks if an export flag is enabled, and if it is ORs it with *iexp */
1433 static void try_export_flags(AVHWFramesContext *hwfc,
1434 VkExternalMemoryHandleTypeFlags *comp_handle_types,
1435 VkExternalMemoryHandleTypeFlagBits *iexp,
1436 VkExternalMemoryHandleTypeFlagBits exp)
1439 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1440 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1441 VkExternalImageFormatProperties eprops = {
1442 .sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES_KHR,
1444 VkImageFormatProperties2 props = {
1445 .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,
1448 VkPhysicalDeviceExternalImageFormatInfo enext = {
1449 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
1452 VkPhysicalDeviceImageFormatInfo2 pinfo = {
1453 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1454 .pNext = !exp ? NULL : &enext,
1455 .format = av_vkfmt_from_pixfmt(hwfc->sw_format)[0],
1456 .type = VK_IMAGE_TYPE_2D,
1457 .tiling = hwctx->tiling,
1458 .usage = hwctx->usage,
1459 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1462 ret = vkGetPhysicalDeviceImageFormatProperties2(dev_hwctx->phys_dev,
1464 if (ret == VK_SUCCESS) {
1466 *comp_handle_types |= eprops.externalMemoryProperties.compatibleHandleTypes;
1470 static AVBufferRef *vulkan_pool_alloc(void *opaque, int size)
1474 AVBufferRef *avbuf = NULL;
1475 AVHWFramesContext *hwfc = opaque;
1476 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1477 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1478 VkExportMemoryAllocateInfo eminfo[AV_NUM_DATA_POINTERS];
1479 VkExternalMemoryHandleTypeFlags e = 0x0;
1481 VkExternalMemoryImageCreateInfo eiinfo = {
1482 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1483 .pNext = hwctx->create_pnext,
1486 if (p->extensions & EXT_EXTERNAL_FD_MEMORY)
1487 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1488 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT);
1490 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
1491 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1492 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
1494 for (int i = 0; i < av_pix_fmt_count_planes(hwfc->sw_format); i++) {
1495 eminfo[i].sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO;
1496 eminfo[i].pNext = hwctx->alloc_pnext[i];
1497 eminfo[i].handleTypes = e;
1500 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1501 eiinfo.handleTypes ? &eiinfo : NULL);
1505 err = alloc_bind_mem(hwfc, f, eminfo, sizeof(*eminfo));
1509 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_WRITE);
1513 avbuf = av_buffer_create((uint8_t *)f, sizeof(AVVkFrame),
1514 vulkan_frame_free, hwfc, 0);
1521 vulkan_frame_free(hwfc, (uint8_t *)f);
1525 static void vulkan_frames_uninit(AVHWFramesContext *hwfc)
1527 VulkanFramesPriv *fp = hwfc->internal->priv;
1529 free_exec_ctx(hwfc->device_ctx, &fp->cmd);
1532 static int vulkan_frames_init(AVHWFramesContext *hwfc)
1536 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1537 VulkanFramesPriv *fp = hwfc->internal->priv;
1538 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1539 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1544 /* Default pool flags */
1545 hwctx->tiling = hwctx->tiling ? hwctx->tiling : p->use_linear_images ?
1546 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1548 hwctx->usage |= DEFAULT_USAGE_FLAGS;
1550 err = create_exec_ctx(hwfc->device_ctx, &fp->cmd,
1551 dev_hwctx->queue_family_tx_index);
1555 /* Test to see if allocation will fail */
1556 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1557 hwctx->create_pnext);
1559 free_exec_ctx(hwfc->device_ctx, &p->cmd);
1563 vulkan_frame_free(hwfc, (uint8_t *)f);
1565 hwfc->internal->pool_internal = av_buffer_pool_init2(sizeof(AVVkFrame),
1566 hwfc, vulkan_pool_alloc,
1568 if (!hwfc->internal->pool_internal) {
1569 free_exec_ctx(hwfc->device_ctx, &p->cmd);
1570 return AVERROR(ENOMEM);
1576 static int vulkan_get_buffer(AVHWFramesContext *hwfc, AVFrame *frame)
1578 frame->buf[0] = av_buffer_pool_get(hwfc->pool);
1580 return AVERROR(ENOMEM);
1582 frame->data[0] = frame->buf[0]->data;
1583 frame->format = AV_PIX_FMT_VULKAN;
1584 frame->width = hwfc->width;
1585 frame->height = hwfc->height;
1590 static int vulkan_transfer_get_formats(AVHWFramesContext *hwfc,
1591 enum AVHWFrameTransferDirection dir,
1592 enum AVPixelFormat **formats)
1594 enum AVPixelFormat *fmts = av_malloc_array(2, sizeof(*fmts));
1596 return AVERROR(ENOMEM);
1598 fmts[0] = hwfc->sw_format;
1599 fmts[1] = AV_PIX_FMT_NONE;
1605 typedef struct VulkanMapping {
1610 static void vulkan_unmap_frame(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1612 VulkanMapping *map = hwmap->priv;
1613 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1614 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1616 /* Check if buffer needs flushing */
1617 if ((map->flags & AV_HWFRAME_MAP_WRITE) &&
1618 !(map->frame->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1620 VkMappedMemoryRange flush_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1622 for (int i = 0; i < planes; i++) {
1623 flush_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1624 flush_ranges[i].memory = map->frame->mem[i];
1625 flush_ranges[i].size = VK_WHOLE_SIZE;
1628 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, planes,
1630 if (ret != VK_SUCCESS) {
1631 av_log(hwfc, AV_LOG_ERROR, "Failed to flush memory: %s\n",
1636 for (int i = 0; i < planes; i++)
1637 vkUnmapMemory(hwctx->act_dev, map->frame->mem[i]);
1642 static int vulkan_map_frame_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
1643 const AVFrame *src, int flags)
1646 int err, mapped_mem_count = 0;
1647 AVVkFrame *f = (AVVkFrame *)src->data[0];
1648 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1649 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1651 VulkanMapping *map = av_mallocz(sizeof(VulkanMapping));
1653 return AVERROR(EINVAL);
1655 if (src->format != AV_PIX_FMT_VULKAN) {
1656 av_log(hwfc, AV_LOG_ERROR, "Cannot map from pixel format %s!\n",
1657 av_get_pix_fmt_name(src->format));
1658 err = AVERROR(EINVAL);
1662 if (!(f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ||
1663 !(f->tiling == VK_IMAGE_TILING_LINEAR)) {
1664 av_log(hwfc, AV_LOG_ERROR, "Unable to map frame, not host visible "
1666 err = AVERROR(EINVAL);
1670 dst->width = src->width;
1671 dst->height = src->height;
1673 for (int i = 0; i < planes; i++) {
1674 ret = vkMapMemory(hwctx->act_dev, f->mem[i], 0,
1675 VK_WHOLE_SIZE, 0, (void **)&dst->data[i]);
1676 if (ret != VK_SUCCESS) {
1677 av_log(hwfc, AV_LOG_ERROR, "Failed to map image memory: %s\n",
1679 err = AVERROR_EXTERNAL;
1685 /* Check if the memory contents matter */
1686 if (((flags & AV_HWFRAME_MAP_READ) || !(flags & AV_HWFRAME_MAP_OVERWRITE)) &&
1687 !(f->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1688 VkMappedMemoryRange map_mem_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1689 for (int i = 0; i < planes; i++) {
1690 map_mem_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1691 map_mem_ranges[i].size = VK_WHOLE_SIZE;
1692 map_mem_ranges[i].memory = f->mem[i];
1695 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, planes,
1697 if (ret != VK_SUCCESS) {
1698 av_log(hwfc, AV_LOG_ERROR, "Failed to invalidate memory: %s\n",
1700 err = AVERROR_EXTERNAL;
1705 for (int i = 0; i < planes; i++) {
1706 VkImageSubresource sub = {
1707 .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
1709 VkSubresourceLayout layout;
1710 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
1711 dst->linesize[i] = layout.rowPitch;
1717 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src,
1718 &vulkan_unmap_frame, map);
1725 for (int i = 0; i < mapped_mem_count; i++)
1726 vkUnmapMemory(hwctx->act_dev, f->mem[i]);
1733 static void vulkan_unmap_from(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1735 VulkanMapping *map = hwmap->priv;
1736 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1737 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1739 for (int i = 0; i < planes; i++) {
1740 vkDestroyImage(hwctx->act_dev, map->frame->img[i], hwctx->alloc);
1741 vkFreeMemory(hwctx->act_dev, map->frame->mem[i], hwctx->alloc);
1742 vkDestroySemaphore(hwctx->act_dev, map->frame->sem[i], hwctx->alloc);
1745 av_freep(&map->frame);
1748 static const struct {
1749 uint32_t drm_fourcc;
1751 } vulkan_drm_format_map[] = {
1752 { DRM_FORMAT_R8, VK_FORMAT_R8_UNORM },
1753 { DRM_FORMAT_R16, VK_FORMAT_R16_UNORM },
1754 { DRM_FORMAT_GR88, VK_FORMAT_R8G8_UNORM },
1755 { DRM_FORMAT_RG88, VK_FORMAT_R8G8_UNORM },
1756 { DRM_FORMAT_GR1616, VK_FORMAT_R16G16_UNORM },
1757 { DRM_FORMAT_RG1616, VK_FORMAT_R16G16_UNORM },
1758 { DRM_FORMAT_ARGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1759 { DRM_FORMAT_XRGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1760 { DRM_FORMAT_ABGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1761 { DRM_FORMAT_XBGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1764 static inline VkFormat drm_to_vulkan_fmt(uint32_t drm_fourcc)
1766 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
1767 if (vulkan_drm_format_map[i].drm_fourcc == drm_fourcc)
1768 return vulkan_drm_format_map[i].vk_format;
1769 return VK_FORMAT_UNDEFINED;
1772 static int vulkan_map_from_drm_frame_desc(AVHWFramesContext *hwfc, AVVkFrame **frame,
1773 AVDRMFrameDescriptor *desc)
1778 int bind_counts = 0;
1779 AVHWDeviceContext *ctx = hwfc->device_ctx;
1780 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1781 VulkanDevicePriv *p = ctx->internal->priv;
1782 const AVPixFmtDescriptor *fmt_desc = av_pix_fmt_desc_get(hwfc->sw_format);
1783 const int has_modifiers = p->extensions & EXT_DRM_MODIFIER_FLAGS;
1784 VkSubresourceLayout plane_data[AV_NUM_DATA_POINTERS] = { 0 };
1785 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { 0 };
1786 VkBindImagePlaneMemoryInfo plane_info[AV_NUM_DATA_POINTERS] = { 0 };
1787 VkExternalMemoryHandleTypeFlagBits htype = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
1789 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdPropertiesKHR);
1791 for (int i = 0; i < desc->nb_layers; i++) {
1792 if (drm_to_vulkan_fmt(desc->layers[i].format) == VK_FORMAT_UNDEFINED) {
1793 av_log(ctx, AV_LOG_ERROR, "Unsupported DMABUF layer format %#08x!\n",
1794 desc->layers[i].format);
1795 return AVERROR(EINVAL);
1799 if (!(f = av_vk_frame_alloc())) {
1800 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1801 err = AVERROR(ENOMEM);
1805 for (int i = 0; i < desc->nb_objects; i++) {
1806 VkMemoryFdPropertiesKHR fdmp = {
1807 .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,
1809 VkMemoryRequirements req = {
1810 .size = desc->objects[i].size,
1812 VkImportMemoryFdInfoKHR idesc = {
1813 .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
1814 .handleType = htype,
1815 .fd = dup(desc->objects[i].fd),
1818 ret = pfn_vkGetMemoryFdPropertiesKHR(hwctx->act_dev, htype,
1820 if (ret != VK_SUCCESS) {
1821 av_log(hwfc, AV_LOG_ERROR, "Failed to get FD properties: %s\n",
1823 err = AVERROR_EXTERNAL;
1828 req.memoryTypeBits = fdmp.memoryTypeBits;
1830 err = alloc_mem(ctx, &req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1831 &idesc, &f->flags, &f->mem[i]);
1837 f->size[i] = desc->objects[i].size;
1840 f->tiling = has_modifiers ? VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT :
1841 desc->objects[0].format_modifier == DRM_FORMAT_MOD_LINEAR ?
1842 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1844 for (int i = 0; i < desc->nb_layers; i++) {
1845 const int planes = desc->layers[i].nb_planes;
1846 const int signal_p = has_modifiers && (planes > 1);
1848 VkImageDrmFormatModifierExplicitCreateInfoEXT drm_info = {
1849 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
1850 .drmFormatModifier = desc->objects[0].format_modifier,
1851 .drmFormatModifierPlaneCount = planes,
1852 .pPlaneLayouts = (const VkSubresourceLayout *)&plane_data,
1855 VkExternalMemoryImageCreateInfo einfo = {
1856 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1857 .pNext = has_modifiers ? &drm_info : NULL,
1858 .handleTypes = htype,
1861 VkSemaphoreCreateInfo sem_spawn = {
1862 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1865 const int p_w = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, fmt_desc->log2_chroma_w) : hwfc->width;
1866 const int p_h = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, fmt_desc->log2_chroma_h) : hwfc->height;
1868 VkImageCreateInfo image_create_info = {
1869 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1871 .imageType = VK_IMAGE_TYPE_2D,
1872 .format = drm_to_vulkan_fmt(desc->layers[i].format),
1873 .extent.width = p_w,
1874 .extent.height = p_h,
1878 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1879 .tiling = f->tiling,
1880 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, /* specs say so */
1881 .usage = DEFAULT_USAGE_FLAGS,
1882 .samples = VK_SAMPLE_COUNT_1_BIT,
1883 .pQueueFamilyIndices = p->qfs,
1884 .queueFamilyIndexCount = p->num_qfs,
1885 .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
1886 VK_SHARING_MODE_EXCLUSIVE,
1889 for (int j = 0; j < planes; j++) {
1890 plane_data[j].offset = desc->layers[i].planes[j].offset;
1891 plane_data[j].rowPitch = desc->layers[i].planes[j].pitch;
1892 plane_data[j].size = 0; /* The specs say so for all 3 */
1893 plane_data[j].arrayPitch = 0;
1894 plane_data[j].depthPitch = 0;
1898 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
1899 hwctx->alloc, &f->img[i]);
1900 if (ret != VK_SUCCESS) {
1901 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1903 err = AVERROR(EINVAL);
1907 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1908 hwctx->alloc, &f->sem[i]);
1909 if (ret != VK_SUCCESS) {
1910 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1912 return AVERROR_EXTERNAL;
1915 /* We'd import a semaphore onto the one we created using
1916 * vkImportSemaphoreFdKHR but unfortunately neither DRM nor VAAPI
1917 * offer us anything we could import and sync with, so instead
1918 * just signal the semaphore we created. */
1920 f->layout[i] = image_create_info.initialLayout;
1923 for (int j = 0; j < planes; j++) {
1924 VkImageAspectFlagBits aspect = j == 0 ? VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
1925 j == 1 ? VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT :
1926 VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT;
1928 plane_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO;
1929 plane_info[bind_counts].planeAspect = aspect;
1931 bind_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
1932 bind_info[bind_counts].pNext = signal_p ? &plane_info[bind_counts] : NULL;
1933 bind_info[bind_counts].image = f->img[i];
1934 bind_info[bind_counts].memory = f->mem[desc->layers[i].planes[j].object_index];
1935 bind_info[bind_counts].memoryOffset = desc->layers[i].planes[j].offset;
1940 /* Bind the allocated memory to the images */
1941 ret = vkBindImageMemory2(hwctx->act_dev, bind_counts, bind_info);
1942 if (ret != VK_SUCCESS) {
1943 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
1945 return AVERROR_EXTERNAL;
1948 /* NOTE: This is completely uneccesary and unneeded once we can import
1949 * semaphores from DRM. Otherwise we have to activate the semaphores.
1950 * We're reusing the exec context that's also used for uploads/downloads. */
1951 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_RO_SHADER);
1960 for (int i = 0; i < desc->nb_layers; i++) {
1961 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
1962 vkDestroySemaphore(hwctx->act_dev, f->sem[i], hwctx->alloc);
1964 for (int i = 0; i < desc->nb_objects; i++)
1965 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
1972 static int vulkan_map_from_drm(AVHWFramesContext *hwfc, AVFrame *dst,
1973 const AVFrame *src, int flags)
1977 VulkanMapping *map = NULL;
1979 err = vulkan_map_from_drm_frame_desc(hwfc, &f,
1980 (AVDRMFrameDescriptor *)src->data[0]);
1984 /* The unmapping function will free this */
1985 dst->data[0] = (uint8_t *)f;
1986 dst->width = src->width;
1987 dst->height = src->height;
1989 map = av_mallocz(sizeof(VulkanMapping));
1996 err = ff_hwframe_map_create(dst->hw_frames_ctx, dst, src,
1997 &vulkan_unmap_from, map);
2001 av_log(hwfc, AV_LOG_DEBUG, "Mapped DRM object to Vulkan!\n");
2006 vulkan_frame_free(hwfc->device_ctx->hwctx, (uint8_t *)f);
2012 static int vulkan_map_from_vaapi(AVHWFramesContext *dst_fc,
2013 AVFrame *dst, const AVFrame *src,
2017 AVFrame *tmp = av_frame_alloc();
2018 AVHWFramesContext *vaapi_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2019 AVVAAPIDeviceContext *vaapi_ctx = vaapi_fc->device_ctx->hwctx;
2020 VASurfaceID surface_id = (VASurfaceID)(uintptr_t)src->data[3];
2023 return AVERROR(ENOMEM);
2025 /* We have to sync since like the previous comment said, no semaphores */
2026 vaSyncSurface(vaapi_ctx->display, surface_id);
2028 tmp->format = AV_PIX_FMT_DRM_PRIME;
2030 err = av_hwframe_map(tmp, src, flags);
2034 err = vulkan_map_from_drm(dst_fc, dst, tmp, flags);
2038 err = ff_hwframe_map_replace(dst, src);
2041 av_frame_free(&tmp);
2048 static int vulkan_export_to_cuda(AVHWFramesContext *hwfc,
2049 AVBufferRef *cuda_hwfc,
2050 const AVFrame *frame)
2055 AVVkFrameInternal *dst_int;
2056 AVHWDeviceContext *ctx = hwfc->device_ctx;
2057 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2058 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2059 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2060 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2061 VK_LOAD_PFN(hwctx->inst, vkGetSemaphoreFdKHR);
2063 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)cuda_hwfc->data;
2064 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2065 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2066 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2067 CudaFunctions *cu = cu_internal->cuda_dl;
2068 CUarray_format cufmt = desc->comp[0].depth > 8 ? CU_AD_FORMAT_UNSIGNED_INT16 :
2069 CU_AD_FORMAT_UNSIGNED_INT8;
2071 dst_f = (AVVkFrame *)frame->data[0];
2073 dst_int = dst_f->internal;
2074 if (!dst_int || !dst_int->cuda_fc_ref) {
2075 if (!dst_f->internal)
2076 dst_f->internal = dst_int = av_mallocz(sizeof(*dst_f->internal));
2079 err = AVERROR(ENOMEM);
2083 dst_int->cuda_fc_ref = av_buffer_ref(cuda_hwfc);
2084 if (!dst_int->cuda_fc_ref) {
2085 err = AVERROR(ENOMEM);
2089 for (int i = 0; i < planes; i++) {
2090 CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC tex_desc = {
2093 .Width = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2095 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2099 .NumChannels = 1 + ((planes == 2) && i),
2104 CUDA_EXTERNAL_MEMORY_HANDLE_DESC ext_desc = {
2105 .type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD,
2106 .size = dst_f->size[i],
2108 VkMemoryGetFdInfoKHR export_info = {
2109 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2110 .memory = dst_f->mem[i],
2111 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR,
2113 VkSemaphoreGetFdInfoKHR sem_export = {
2114 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR,
2115 .semaphore = dst_f->sem[i],
2116 .handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
2118 CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC ext_sem_desc = {
2119 .type = CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD,
2122 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2123 &ext_desc.handle.fd);
2124 if (ret != VK_SUCCESS) {
2125 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2126 err = AVERROR_EXTERNAL;
2130 ret = CHECK_CU(cu->cuImportExternalMemory(&dst_int->ext_mem[i], &ext_desc));
2132 err = AVERROR_EXTERNAL;
2136 ret = CHECK_CU(cu->cuExternalMemoryGetMappedMipmappedArray(&dst_int->cu_mma[i],
2137 dst_int->ext_mem[i],
2140 err = AVERROR_EXTERNAL;
2144 ret = CHECK_CU(cu->cuMipmappedArrayGetLevel(&dst_int->cu_array[i],
2145 dst_int->cu_mma[i], 0));
2147 err = AVERROR_EXTERNAL;
2151 ret = pfn_vkGetSemaphoreFdKHR(hwctx->act_dev, &sem_export,
2152 &ext_sem_desc.handle.fd);
2153 if (ret != VK_SUCCESS) {
2154 av_log(ctx, AV_LOG_ERROR, "Failed to export semaphore: %s\n",
2156 err = AVERROR_EXTERNAL;
2160 ret = CHECK_CU(cu->cuImportExternalSemaphore(&dst_int->cu_sem[i],
2163 err = AVERROR_EXTERNAL;
2175 static int vulkan_transfer_data_from_cuda(AVHWFramesContext *hwfc,
2176 AVFrame *dst, const AVFrame *src)
2182 AVVkFrameInternal *dst_int;
2183 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2184 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2186 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2187 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2188 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2189 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2190 CudaFunctions *cu = cu_internal->cuda_dl;
2191 CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS s_w_par[AV_NUM_DATA_POINTERS] = { 0 };
2192 CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS s_s_par[AV_NUM_DATA_POINTERS] = { 0 };
2194 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2196 err = AVERROR_EXTERNAL;
2200 dst_f = (AVVkFrame *)dst->data[0];
2202 ret = vulkan_export_to_cuda(hwfc, src->hw_frames_ctx, dst);
2206 dst_int = dst_f->internal;
2208 ret = CHECK_CU(cu->cuWaitExternalSemaphoresAsync(dst_int->cu_sem, s_w_par,
2209 planes, cuda_dev->stream));
2211 err = AVERROR_EXTERNAL;
2215 for (int i = 0; i < planes; i++) {
2216 CUDA_MEMCPY2D cpy = {
2217 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
2218 .srcDevice = (CUdeviceptr)src->data[i],
2219 .srcPitch = src->linesize[i],
2222 .dstMemoryType = CU_MEMORYTYPE_ARRAY,
2223 .dstArray = dst_int->cu_array[i],
2224 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2225 : hwfc->width) * desc->comp[i].step,
2226 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2230 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2232 err = AVERROR_EXTERNAL;
2237 ret = CHECK_CU(cu->cuSignalExternalSemaphoresAsync(dst_int->cu_sem, s_s_par,
2238 planes, cuda_dev->stream));
2240 err = AVERROR_EXTERNAL;
2244 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2246 av_log(hwfc, AV_LOG_VERBOSE, "Transfered CUDA image to Vulkan!\n");
2251 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2252 vulkan_free_internal(dst_int);
2253 dst_f->internal = NULL;
2254 av_buffer_unref(&dst->buf[0]);
2259 static int vulkan_map_to(AVHWFramesContext *hwfc, AVFrame *dst,
2260 const AVFrame *src, int flags)
2262 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2264 switch (src->format) {
2267 case AV_PIX_FMT_VAAPI:
2268 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2269 return vulkan_map_from_vaapi(hwfc, dst, src, flags);
2271 case AV_PIX_FMT_DRM_PRIME:
2272 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2273 return vulkan_map_from_drm(hwfc, dst, src, flags);
2276 return AVERROR(ENOSYS);
2281 typedef struct VulkanDRMMapping {
2282 AVDRMFrameDescriptor drm_desc;
2286 static void vulkan_unmap_to_drm(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
2288 AVDRMFrameDescriptor *drm_desc = hwmap->priv;
2290 for (int i = 0; i < drm_desc->nb_objects; i++)
2291 close(drm_desc->objects[i].fd);
2296 static inline uint32_t vulkan_fmt_to_drm(VkFormat vkfmt)
2298 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
2299 if (vulkan_drm_format_map[i].vk_format == vkfmt)
2300 return vulkan_drm_format_map[i].drm_fourcc;
2301 return DRM_FORMAT_INVALID;
2304 static int vulkan_map_to_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2305 const AVFrame *src, int flags)
2309 AVVkFrame *f = (AVVkFrame *)src->data[0];
2310 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2311 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
2312 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2313 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2314 VkImageDrmFormatModifierPropertiesEXT drm_mod = {
2315 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT,
2318 AVDRMFrameDescriptor *drm_desc = av_mallocz(sizeof(*drm_desc));
2320 return AVERROR(ENOMEM);
2322 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_EXTERNAL_EXPORT);
2326 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src, &vulkan_unmap_to_drm, drm_desc);
2330 if (p->extensions & EXT_DRM_MODIFIER_FLAGS) {
2331 VK_LOAD_PFN(hwctx->inst, vkGetImageDrmFormatModifierPropertiesEXT);
2332 ret = pfn_vkGetImageDrmFormatModifierPropertiesEXT(hwctx->act_dev, f->img[0],
2334 if (ret != VK_SUCCESS) {
2335 av_log(hwfc, AV_LOG_ERROR, "Failed to retrieve DRM format modifier!\n");
2336 err = AVERROR_EXTERNAL;
2341 for (int i = 0; (i < planes) && (f->mem[i]); i++) {
2342 VkMemoryGetFdInfoKHR export_info = {
2343 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2344 .memory = f->mem[i],
2345 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,
2348 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2349 &drm_desc->objects[i].fd);
2350 if (ret != VK_SUCCESS) {
2351 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2352 err = AVERROR_EXTERNAL;
2356 drm_desc->nb_objects++;
2357 drm_desc->objects[i].size = f->size[i];
2358 drm_desc->objects[i].format_modifier = drm_mod.drmFormatModifier;
2361 drm_desc->nb_layers = planes;
2362 for (int i = 0; i < drm_desc->nb_layers; i++) {
2363 VkSubresourceLayout layout;
2364 VkImageSubresource sub = {
2365 .aspectMask = p->extensions & EXT_DRM_MODIFIER_FLAGS ?
2366 VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2367 VK_IMAGE_ASPECT_COLOR_BIT,
2369 VkFormat plane_vkfmt = av_vkfmt_from_pixfmt(hwfc->sw_format)[i];
2371 drm_desc->layers[i].format = vulkan_fmt_to_drm(plane_vkfmt);
2372 drm_desc->layers[i].nb_planes = 1;
2374 if (drm_desc->layers[i].format == DRM_FORMAT_INVALID) {
2375 av_log(hwfc, AV_LOG_ERROR, "Cannot map to DRM layer, unsupported!\n");
2376 err = AVERROR_PATCHWELCOME;
2380 drm_desc->layers[i].planes[0].object_index = FFMIN(i, drm_desc->nb_objects - 1);
2382 if (f->tiling == VK_IMAGE_TILING_OPTIMAL)
2385 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
2386 drm_desc->layers[i].planes[0].offset = layout.offset;
2387 drm_desc->layers[i].planes[0].pitch = layout.rowPitch;
2390 dst->width = src->width;
2391 dst->height = src->height;
2392 dst->data[0] = (uint8_t *)drm_desc;
2394 av_log(hwfc, AV_LOG_VERBOSE, "Mapped AVVkFrame to a DRM object!\n");
2404 static int vulkan_map_to_vaapi(AVHWFramesContext *hwfc, AVFrame *dst,
2405 const AVFrame *src, int flags)
2408 AVFrame *tmp = av_frame_alloc();
2410 return AVERROR(ENOMEM);
2412 tmp->format = AV_PIX_FMT_DRM_PRIME;
2414 err = vulkan_map_to_drm(hwfc, tmp, src, flags);
2418 err = av_hwframe_map(dst, tmp, flags);
2422 err = ff_hwframe_map_replace(dst, src);
2425 av_frame_free(&tmp);
2431 static int vulkan_map_from(AVHWFramesContext *hwfc, AVFrame *dst,
2432 const AVFrame *src, int flags)
2434 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2436 switch (dst->format) {
2438 case AV_PIX_FMT_DRM_PRIME:
2439 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2440 return vulkan_map_to_drm(hwfc, dst, src, flags);
2442 case AV_PIX_FMT_VAAPI:
2443 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2444 return vulkan_map_to_vaapi(hwfc, dst, src, flags);
2448 return vulkan_map_frame_to_mem(hwfc, dst, src, flags);
2452 typedef struct ImageBuffer {
2455 VkMemoryPropertyFlagBits flags;
2458 static void free_buf(AVHWDeviceContext *ctx, ImageBuffer *buf)
2460 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2464 vkDestroyBuffer(hwctx->act_dev, buf->buf, hwctx->alloc);
2465 vkFreeMemory(hwctx->act_dev, buf->mem, hwctx->alloc);
2468 static int create_buf(AVHWDeviceContext *ctx, ImageBuffer *buf, int height,
2469 int *stride, VkBufferUsageFlags usage,
2470 VkMemoryPropertyFlagBits flags, void *create_pnext,
2475 VkMemoryRequirements req;
2476 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2477 VulkanDevicePriv *p = ctx->internal->priv;
2479 VkBufferCreateInfo buf_spawn = {
2480 .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
2481 .pNext = create_pnext,
2483 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
2486 *stride = FFALIGN(*stride, p->props.limits.optimalBufferCopyRowPitchAlignment);
2487 buf_spawn.size = height*(*stride);
2489 ret = vkCreateBuffer(hwctx->act_dev, &buf_spawn, NULL, &buf->buf);
2490 if (ret != VK_SUCCESS) {
2491 av_log(ctx, AV_LOG_ERROR, "Failed to create buffer: %s\n",
2493 return AVERROR_EXTERNAL;
2496 vkGetBufferMemoryRequirements(hwctx->act_dev, buf->buf, &req);
2498 err = alloc_mem(ctx, &req, flags, alloc_pnext, &buf->flags, &buf->mem);
2502 ret = vkBindBufferMemory(hwctx->act_dev, buf->buf, buf->mem, 0);
2503 if (ret != VK_SUCCESS) {
2504 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory to buffer: %s\n",
2507 return AVERROR_EXTERNAL;
2513 static int map_buffers(AVHWDeviceContext *ctx, ImageBuffer *buf, uint8_t *mem[],
2514 int nb_buffers, int invalidate)
2517 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2518 VkMappedMemoryRange invalidate_ctx[AV_NUM_DATA_POINTERS];
2519 int invalidate_count = 0;
2521 for (int i = 0; i < nb_buffers; i++) {
2522 ret = vkMapMemory(hwctx->act_dev, buf[i].mem, 0,
2523 VK_WHOLE_SIZE, 0, (void **)&mem[i]);
2524 if (ret != VK_SUCCESS) {
2525 av_log(ctx, AV_LOG_ERROR, "Failed to map buffer memory: %s\n",
2527 return AVERROR_EXTERNAL;
2534 for (int i = 0; i < nb_buffers; i++) {
2535 const VkMappedMemoryRange ival_buf = {
2536 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2537 .memory = buf[i].mem,
2538 .size = VK_WHOLE_SIZE,
2540 if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2542 invalidate_ctx[invalidate_count++] = ival_buf;
2545 if (invalidate_count) {
2546 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, invalidate_count,
2548 if (ret != VK_SUCCESS)
2549 av_log(ctx, AV_LOG_WARNING, "Failed to invalidate memory: %s\n",
2556 static int unmap_buffers(AVHWDeviceContext *ctx, ImageBuffer *buf,
2557 int nb_buffers, int flush)
2561 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2562 VkMappedMemoryRange flush_ctx[AV_NUM_DATA_POINTERS];
2563 int flush_count = 0;
2566 for (int i = 0; i < nb_buffers; i++) {
2567 const VkMappedMemoryRange flush_buf = {
2568 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2569 .memory = buf[i].mem,
2570 .size = VK_WHOLE_SIZE,
2572 if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2574 flush_ctx[flush_count++] = flush_buf;
2579 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, flush_count, flush_ctx);
2580 if (ret != VK_SUCCESS) {
2581 av_log(ctx, AV_LOG_ERROR, "Failed to flush memory: %s\n",
2583 err = AVERROR_EXTERNAL; /* We still want to try to unmap them */
2587 for (int i = 0; i < nb_buffers; i++)
2588 vkUnmapMemory(hwctx->act_dev, buf[i].mem);
2593 static int transfer_image_buf(AVHWDeviceContext *ctx, AVVkFrame *frame,
2594 ImageBuffer *buffer, const int *buf_stride, int w,
2595 int h, enum AVPixelFormat pix_fmt, int to_buf)
2598 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2599 VulkanDevicePriv *s = ctx->internal->priv;
2602 VkPipelineStageFlagBits sem_wait_dst[AV_NUM_DATA_POINTERS];
2604 const int planes = av_pix_fmt_count_planes(pix_fmt);
2605 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2607 VkCommandBufferBeginInfo cmd_start = {
2608 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
2609 .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
2612 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
2614 VkSubmitInfo s_info = {
2615 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
2616 .commandBufferCount = 1,
2617 .pCommandBuffers = &s->cmd.buf,
2618 .pSignalSemaphores = frame->sem,
2619 .pWaitSemaphores = frame->sem,
2620 .pWaitDstStageMask = sem_wait_dst,
2621 .signalSemaphoreCount = planes,
2622 .waitSemaphoreCount = planes,
2625 ret = vkBeginCommandBuffer(s->cmd.buf, &cmd_start);
2626 if (ret != VK_SUCCESS) {
2627 av_log(ctx, AV_LOG_ERROR, "Unable to init command buffer: %s\n",
2629 return AVERROR_EXTERNAL;
2632 /* Change the image layout to something more optimal for transfers */
2633 for (int i = 0; i < planes; i++) {
2634 VkImageLayout new_layout = to_buf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL :
2635 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
2636 VkAccessFlags new_access = to_buf ? VK_ACCESS_TRANSFER_READ_BIT :
2637 VK_ACCESS_TRANSFER_WRITE_BIT;
2639 sem_wait_dst[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
2641 /* If the layout matches and we have read access skip the barrier */
2642 if ((frame->layout[i] == new_layout) && (frame->access[i] & new_access))
2645 img_bar[bar_num].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
2646 img_bar[bar_num].srcAccessMask = 0x0;
2647 img_bar[bar_num].dstAccessMask = new_access;
2648 img_bar[bar_num].oldLayout = frame->layout[i];
2649 img_bar[bar_num].newLayout = new_layout;
2650 img_bar[bar_num].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2651 img_bar[bar_num].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2652 img_bar[bar_num].image = frame->img[i];
2653 img_bar[bar_num].subresourceRange.levelCount = 1;
2654 img_bar[bar_num].subresourceRange.layerCount = 1;
2655 img_bar[bar_num].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2657 frame->layout[i] = img_bar[bar_num].newLayout;
2658 frame->access[i] = img_bar[bar_num].dstAccessMask;
2664 vkCmdPipelineBarrier(s->cmd.buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
2665 VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
2666 0, NULL, 0, NULL, bar_num, img_bar);
2668 /* Schedule a copy for each plane */
2669 for (int i = 0; i < planes; i++) {
2670 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
2671 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
2672 VkBufferImageCopy buf_reg = {
2674 /* Buffer stride isn't in bytes, it's in samples, the implementation
2675 * uses the image's VkFormat to know how many bytes per sample
2676 * the buffer has. So we have to convert by dividing. Stupid.
2677 * Won't work with YUVA or other planar formats with alpha. */
2678 .bufferRowLength = buf_stride[i] / desc->comp[i].step,
2679 .bufferImageHeight = p_h,
2680 .imageSubresource.layerCount = 1,
2681 .imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
2682 .imageOffset = { 0, 0, 0, },
2683 .imageExtent = { p_w, p_h, 1, },
2687 vkCmdCopyImageToBuffer(s->cmd.buf, frame->img[i], frame->layout[i],
2688 buffer[i].buf, 1, &buf_reg);
2690 vkCmdCopyBufferToImage(s->cmd.buf, buffer[i].buf, frame->img[i],
2691 frame->layout[i], 1, &buf_reg);
2694 ret = vkEndCommandBuffer(s->cmd.buf);
2695 if (ret != VK_SUCCESS) {
2696 av_log(ctx, AV_LOG_ERROR, "Unable to finish command buffer: %s\n",
2698 return AVERROR_EXTERNAL;
2701 /* Wait for the download/upload to finish if uploading, otherwise the
2702 * semaphore will take care of synchronization when uploading */
2703 ret = vkQueueSubmit(s->cmd.queue, 1, &s_info, s->cmd.fence);
2704 if (ret != VK_SUCCESS) {
2705 av_log(ctx, AV_LOG_ERROR, "Unable to submit command buffer: %s\n",
2707 return AVERROR_EXTERNAL;
2709 vkWaitForFences(hwctx->act_dev, 1, &s->cmd.fence, VK_TRUE, UINT64_MAX);
2710 vkResetFences(hwctx->act_dev, 1, &s->cmd.fence);
2716 /* Technically we can use VK_EXT_external_memory_host to upload and download,
2717 * however the alignment requirements make this unfeasible as both the pointer
2718 * and the size of each plane need to be aligned to the minimum alignment
2719 * requirement, which on all current implementations (anv, radv) is 4096.
2720 * If the requirement gets relaxed (unlikely) this can easily be implemented. */
2721 static int vulkan_transfer_data_from_mem(AVHWFramesContext *hwfc, AVFrame *dst,
2726 AVVkFrame *f = (AVVkFrame *)dst->data[0];
2727 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
2728 ImageBuffer buf[AV_NUM_DATA_POINTERS] = { { 0 } };
2729 const int planes = av_pix_fmt_count_planes(src->format);
2730 int log2_chroma = av_pix_fmt_desc_get(src->format)->log2_chroma_h;
2732 if ((src->format != AV_PIX_FMT_NONE && !av_vkfmt_from_pixfmt(src->format))) {
2733 av_log(hwfc, AV_LOG_ERROR, "Unsupported source pixel format!\n");
2734 return AVERROR(EINVAL);
2737 if (src->width > hwfc->width || src->height > hwfc->height)
2738 return AVERROR(EINVAL);
2740 /* For linear, host visiable images */
2741 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
2742 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
2743 AVFrame *map = av_frame_alloc();
2745 return AVERROR(ENOMEM);
2746 map->format = src->format;
2748 err = vulkan_map_frame_to_mem(hwfc, map, dst, AV_HWFRAME_MAP_WRITE);
2752 err = av_frame_copy(map, src);
2753 av_frame_free(&map);
2757 /* Create buffers */
2758 for (int i = 0; i < planes; i++) {
2759 int h = src->height;
2760 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
2762 tmp.linesize[i] = FFABS(src->linesize[i]);
2763 err = create_buf(dev_ctx, &buf[i], p_height,
2764 &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
2765 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
2770 /* Map, copy image to buffer, unmap */
2771 if ((err = map_buffers(dev_ctx, buf, tmp.data, planes, 0)))
2774 av_image_copy(tmp.data, tmp.linesize, (const uint8_t **)src->data,
2775 src->linesize, src->format, src->width, src->height);
2777 if ((err = unmap_buffers(dev_ctx, buf, planes, 1)))
2780 /* Copy buffers to image */
2781 err = transfer_image_buf(dev_ctx, f, buf, tmp.linesize,
2782 src->width, src->height, src->format, 0);
2785 for (int i = 0; i < planes; i++)
2786 free_buf(dev_ctx, &buf[i]);
2791 static int vulkan_transfer_data_to(AVHWFramesContext *hwfc, AVFrame *dst,
2794 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2796 switch (src->format) {
2798 case AV_PIX_FMT_CUDA:
2799 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
2800 (p->extensions & EXT_EXTERNAL_FD_SEM))
2801 return vulkan_transfer_data_from_cuda(hwfc, dst, src);
2804 if (src->hw_frames_ctx)
2805 return AVERROR(ENOSYS);
2807 return vulkan_transfer_data_from_mem(hwfc, dst, src);
2812 static int vulkan_transfer_data_to_cuda(AVHWFramesContext *hwfc, AVFrame *dst,
2819 AVVkFrameInternal *dst_int;
2820 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2821 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2823 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)dst->hw_frames_ctx->data;
2824 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2825 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2826 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2827 CudaFunctions *cu = cu_internal->cuda_dl;
2829 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2831 err = AVERROR_EXTERNAL;
2835 dst_f = (AVVkFrame *)src->data[0];
2837 err = vulkan_export_to_cuda(hwfc, dst->hw_frames_ctx, src);
2842 dst_int = dst_f->internal;
2844 for (int i = 0; i < planes; i++) {
2845 CUDA_MEMCPY2D cpy = {
2846 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
2847 .dstDevice = (CUdeviceptr)dst->data[i],
2848 .dstPitch = dst->linesize[i],
2851 .srcMemoryType = CU_MEMORYTYPE_ARRAY,
2852 .srcArray = dst_int->cu_array[i],
2853 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2854 : hwfc->width) * desc->comp[i].step,
2855 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2859 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2861 err = AVERROR_EXTERNAL;
2866 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2868 av_log(hwfc, AV_LOG_VERBOSE, "Transfered Vulkan image to CUDA!\n");
2873 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2874 vulkan_free_internal(dst_int);
2875 dst_f->internal = NULL;
2876 av_buffer_unref(&dst->buf[0]);
2881 static int vulkan_transfer_data_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
2886 AVVkFrame *f = (AVVkFrame *)src->data[0];
2887 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
2888 ImageBuffer buf[AV_NUM_DATA_POINTERS] = { { 0 } };
2889 const int planes = av_pix_fmt_count_planes(dst->format);
2890 int log2_chroma = av_pix_fmt_desc_get(dst->format)->log2_chroma_h;
2892 if (dst->width > hwfc->width || dst->height > hwfc->height)
2893 return AVERROR(EINVAL);
2895 /* For linear, host visiable images */
2896 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
2897 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
2898 AVFrame *map = av_frame_alloc();
2900 return AVERROR(ENOMEM);
2901 map->format = dst->format;
2903 err = vulkan_map_frame_to_mem(hwfc, map, src, AV_HWFRAME_MAP_READ);
2907 err = av_frame_copy(dst, map);
2908 av_frame_free(&map);
2912 /* Create buffers */
2913 for (int i = 0; i < planes; i++) {
2914 int h = dst->height;
2915 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
2917 tmp.linesize[i] = FFABS(dst->linesize[i]);
2918 err = create_buf(dev_ctx, &buf[i], p_height,
2919 &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_DST_BIT,
2920 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
2923 /* Copy image to buffer */
2924 if ((err = transfer_image_buf(dev_ctx, f, buf, tmp.linesize,
2925 dst->width, dst->height, dst->format, 1)))
2928 /* Map, copy buffer to frame, unmap */
2929 if ((err = map_buffers(dev_ctx, buf, tmp.data, planes, 1)))
2932 av_image_copy(dst->data, dst->linesize, (const uint8_t **)tmp.data,
2933 tmp.linesize, dst->format, dst->width, dst->height);
2935 err = unmap_buffers(dev_ctx, buf, planes, 0);
2938 for (int i = 0; i < planes; i++)
2939 free_buf(dev_ctx, &buf[i]);
2944 static int vulkan_transfer_data_from(AVHWFramesContext *hwfc, AVFrame *dst,
2947 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2949 switch (dst->format) {
2951 case AV_PIX_FMT_CUDA:
2952 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
2953 (p->extensions & EXT_EXTERNAL_FD_SEM))
2954 return vulkan_transfer_data_to_cuda(hwfc, dst, src);
2957 if (dst->hw_frames_ctx)
2958 return AVERROR(ENOSYS);
2960 return vulkan_transfer_data_to_mem(hwfc, dst, src);
2964 AVVkFrame *av_vk_frame_alloc(void)
2966 return av_mallocz(sizeof(AVVkFrame));
2969 const HWContextType ff_hwcontext_type_vulkan = {
2970 .type = AV_HWDEVICE_TYPE_VULKAN,
2973 .device_hwctx_size = sizeof(AVVulkanDeviceContext),
2974 .device_priv_size = sizeof(VulkanDevicePriv),
2975 .frames_hwctx_size = sizeof(AVVulkanFramesContext),
2976 .frames_priv_size = sizeof(VulkanFramesPriv),
2978 .device_init = &vulkan_device_init,
2979 .device_create = &vulkan_device_create,
2980 .device_derive = &vulkan_device_derive,
2982 .frames_get_constraints = &vulkan_frames_get_constraints,
2983 .frames_init = vulkan_frames_init,
2984 .frames_get_buffer = vulkan_get_buffer,
2985 .frames_uninit = vulkan_frames_uninit,
2987 .transfer_get_formats = vulkan_transfer_get_formats,
2988 .transfer_data_to = vulkan_transfer_data_to,
2989 .transfer_data_from = vulkan_transfer_data_from,
2991 .map_to = vulkan_map_to,
2992 .map_from = vulkan_map_from,
2994 .pix_fmts = (const enum AVPixelFormat []) {