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 VulkanQueueCtx {
49 /* Buffer dependencies */
50 AVBufferRef **buf_deps;
52 int buf_deps_alloc_size;
55 typedef struct VulkanExecCtx {
57 VkCommandBuffer *bufs;
58 VulkanQueueCtx *queues;
63 typedef struct VulkanDevicePriv {
65 VkPhysicalDeviceProperties props;
66 VkPhysicalDeviceMemoryProperties mprops;
73 VkDebugUtilsMessengerEXT debug_ctx;
79 int use_linear_images;
85 typedef struct VulkanFramesPriv {
86 /* Image conversions */
87 VulkanExecCtx conv_ctx;
90 VulkanExecCtx upload_ctx;
91 VulkanExecCtx download_ctx;
94 typedef struct AVVkFrameInternal {
96 /* Importing external memory into cuda is really expensive so we keep the
97 * memory imported all the time */
98 AVBufferRef *cuda_fc_ref; /* Need to keep it around for uninit */
99 CUexternalMemory ext_mem[AV_NUM_DATA_POINTERS];
100 CUmipmappedArray cu_mma[AV_NUM_DATA_POINTERS];
101 CUarray cu_array[AV_NUM_DATA_POINTERS];
102 CUexternalSemaphore cu_sem[AV_NUM_DATA_POINTERS];
106 #define GET_QUEUE_COUNT(hwctx, graph, comp, tx) ( \
107 graph ? hwctx->nb_graphics_queues : \
108 comp ? (hwctx->nb_comp_queues ? \
109 hwctx->nb_comp_queues : hwctx->nb_graphics_queues) : \
110 tx ? (hwctx->nb_tx_queues ? hwctx->nb_tx_queues : \
111 (hwctx->nb_comp_queues ? \
112 hwctx->nb_comp_queues : hwctx->nb_graphics_queues)) : \
116 #define VK_LOAD_PFN(inst, name) PFN_##name pfn_##name = (PFN_##name) \
117 vkGetInstanceProcAddr(inst, #name)
119 #define DEFAULT_USAGE_FLAGS (VK_IMAGE_USAGE_SAMPLED_BIT | \
120 VK_IMAGE_USAGE_STORAGE_BIT | \
121 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | \
122 VK_IMAGE_USAGE_TRANSFER_DST_BIT)
124 #define ADD_VAL_TO_LIST(list, count, val) \
126 list = av_realloc_array(list, sizeof(*list), ++count); \
128 err = AVERROR(ENOMEM); \
131 list[count - 1] = av_strdup(val); \
132 if (!list[count - 1]) { \
133 err = AVERROR(ENOMEM); \
138 static const struct {
139 enum AVPixelFormat pixfmt;
140 const VkFormat vkfmts[3];
141 } vk_pixfmt_map[] = {
142 { AV_PIX_FMT_GRAY8, { VK_FORMAT_R8_UNORM } },
143 { AV_PIX_FMT_GRAY16, { VK_FORMAT_R16_UNORM } },
144 { AV_PIX_FMT_GRAYF32, { VK_FORMAT_R32_SFLOAT } },
146 { AV_PIX_FMT_NV12, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8G8_UNORM } },
147 { AV_PIX_FMT_P010, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16G16_UNORM } },
148 { AV_PIX_FMT_P016, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16G16_UNORM } },
150 { AV_PIX_FMT_YUV420P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
151 { AV_PIX_FMT_YUV422P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
152 { AV_PIX_FMT_YUV444P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
154 { AV_PIX_FMT_YUV420P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
155 { AV_PIX_FMT_YUV422P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
156 { AV_PIX_FMT_YUV444P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
158 { AV_PIX_FMT_ABGR, { VK_FORMAT_A8B8G8R8_UNORM_PACK32 } },
159 { AV_PIX_FMT_BGRA, { VK_FORMAT_B8G8R8A8_UNORM } },
160 { AV_PIX_FMT_RGBA, { VK_FORMAT_R8G8B8A8_UNORM } },
161 { AV_PIX_FMT_RGB24, { VK_FORMAT_R8G8B8_UNORM } },
162 { AV_PIX_FMT_BGR24, { VK_FORMAT_B8G8R8_UNORM } },
163 { AV_PIX_FMT_RGB48, { VK_FORMAT_R16G16B16_UNORM } },
164 { AV_PIX_FMT_RGBA64, { VK_FORMAT_R16G16B16A16_UNORM } },
165 { AV_PIX_FMT_RGB565, { VK_FORMAT_R5G6B5_UNORM_PACK16 } },
166 { AV_PIX_FMT_BGR565, { VK_FORMAT_B5G6R5_UNORM_PACK16 } },
167 { AV_PIX_FMT_BGR0, { VK_FORMAT_B8G8R8A8_UNORM } },
168 { AV_PIX_FMT_0BGR, { VK_FORMAT_A8B8G8R8_UNORM_PACK32 } },
169 { AV_PIX_FMT_RGB0, { VK_FORMAT_R8G8B8A8_UNORM } },
171 { AV_PIX_FMT_GBRPF32, { VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32_SFLOAT } },
174 const VkFormat *av_vkfmt_from_pixfmt(enum AVPixelFormat p)
176 for (enum AVPixelFormat i = 0; i < FF_ARRAY_ELEMS(vk_pixfmt_map); i++)
177 if (vk_pixfmt_map[i].pixfmt == p)
178 return vk_pixfmt_map[i].vkfmts;
182 static int pixfmt_is_supported(AVVulkanDeviceContext *hwctx, enum AVPixelFormat p,
185 const VkFormat *fmt = av_vkfmt_from_pixfmt(p);
186 int planes = av_pix_fmt_count_planes(p);
191 for (int i = 0; i < planes; i++) {
192 VkFormatFeatureFlags flags;
193 VkFormatProperties2 prop = {
194 .sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2,
196 vkGetPhysicalDeviceFormatProperties2(hwctx->phys_dev, fmt[i], &prop);
197 flags = linear ? prop.formatProperties.linearTilingFeatures :
198 prop.formatProperties.optimalTilingFeatures;
199 if (!(flags & DEFAULT_USAGE_FLAGS))
206 enum VulkanExtensions {
207 EXT_EXTERNAL_DMABUF_MEMORY = 1ULL << 0, /* VK_EXT_external_memory_dma_buf */
208 EXT_DRM_MODIFIER_FLAGS = 1ULL << 1, /* VK_EXT_image_drm_format_modifier */
209 EXT_EXTERNAL_FD_MEMORY = 1ULL << 2, /* VK_KHR_external_memory_fd */
210 EXT_EXTERNAL_FD_SEM = 1ULL << 3, /* VK_KHR_external_semaphore_fd */
212 EXT_NO_FLAG = 1ULL << 63,
215 typedef struct VulkanOptExtension {
218 } VulkanOptExtension;
220 static const VulkanOptExtension optional_instance_exts[] = {
224 static const VulkanOptExtension optional_device_exts[] = {
225 { VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME, EXT_EXTERNAL_FD_MEMORY, },
226 { VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME, EXT_EXTERNAL_DMABUF_MEMORY, },
227 { VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME, EXT_DRM_MODIFIER_FLAGS, },
228 { VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME, EXT_EXTERNAL_FD_SEM, },
231 /* Converts return values to strings */
232 static const char *vk_ret2str(VkResult res)
234 #define CASE(VAL) case VAL: return #VAL
240 CASE(VK_EVENT_RESET);
242 CASE(VK_ERROR_OUT_OF_HOST_MEMORY);
243 CASE(VK_ERROR_OUT_OF_DEVICE_MEMORY);
244 CASE(VK_ERROR_INITIALIZATION_FAILED);
245 CASE(VK_ERROR_DEVICE_LOST);
246 CASE(VK_ERROR_MEMORY_MAP_FAILED);
247 CASE(VK_ERROR_LAYER_NOT_PRESENT);
248 CASE(VK_ERROR_EXTENSION_NOT_PRESENT);
249 CASE(VK_ERROR_FEATURE_NOT_PRESENT);
250 CASE(VK_ERROR_INCOMPATIBLE_DRIVER);
251 CASE(VK_ERROR_TOO_MANY_OBJECTS);
252 CASE(VK_ERROR_FORMAT_NOT_SUPPORTED);
253 CASE(VK_ERROR_FRAGMENTED_POOL);
254 CASE(VK_ERROR_SURFACE_LOST_KHR);
255 CASE(VK_ERROR_NATIVE_WINDOW_IN_USE_KHR);
256 CASE(VK_SUBOPTIMAL_KHR);
257 CASE(VK_ERROR_OUT_OF_DATE_KHR);
258 CASE(VK_ERROR_INCOMPATIBLE_DISPLAY_KHR);
259 CASE(VK_ERROR_VALIDATION_FAILED_EXT);
260 CASE(VK_ERROR_INVALID_SHADER_NV);
261 CASE(VK_ERROR_OUT_OF_POOL_MEMORY);
262 CASE(VK_ERROR_INVALID_EXTERNAL_HANDLE);
263 CASE(VK_ERROR_NOT_PERMITTED_EXT);
264 CASE(VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT);
265 CASE(VK_ERROR_INVALID_DEVICE_ADDRESS_EXT);
266 CASE(VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT);
267 default: return "Unknown error";
272 static VkBool32 vk_dbg_callback(VkDebugUtilsMessageSeverityFlagBitsEXT severity,
273 VkDebugUtilsMessageTypeFlagsEXT messageType,
274 const VkDebugUtilsMessengerCallbackDataEXT *data,
278 AVHWDeviceContext *ctx = priv;
281 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT: l = AV_LOG_VERBOSE; break;
282 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT: l = AV_LOG_INFO; break;
283 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT: l = AV_LOG_WARNING; break;
284 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT: l = AV_LOG_ERROR; break;
285 default: l = AV_LOG_DEBUG; break;
288 av_log(ctx, l, "%s\n", data->pMessage);
289 for (int i = 0; i < data->cmdBufLabelCount; i++)
290 av_log(ctx, l, "\t%i: %s\n", i, data->pCmdBufLabels[i].pLabelName);
295 static int check_extensions(AVHWDeviceContext *ctx, int dev, AVDictionary *opts,
296 const char * const **dst, uint32_t *num, int debug)
299 const char **extension_names = NULL;
300 VulkanDevicePriv *p = ctx->internal->priv;
301 AVVulkanDeviceContext *hwctx = ctx->hwctx;
302 int err = 0, found, extensions_found = 0;
305 int optional_exts_num;
306 uint32_t sup_ext_count;
307 char *user_exts_str = NULL;
308 AVDictionaryEntry *user_exts;
309 VkExtensionProperties *sup_ext;
310 const VulkanOptExtension *optional_exts;
314 optional_exts = optional_instance_exts;
315 optional_exts_num = FF_ARRAY_ELEMS(optional_instance_exts);
316 user_exts = av_dict_get(opts, "instance_extensions", NULL, 0);
318 user_exts_str = av_strdup(user_exts->value);
319 if (!user_exts_str) {
320 err = AVERROR(ENOMEM);
324 vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, NULL);
325 sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
327 return AVERROR(ENOMEM);
328 vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, sup_ext);
331 optional_exts = optional_device_exts;
332 optional_exts_num = FF_ARRAY_ELEMS(optional_device_exts);
333 user_exts = av_dict_get(opts, "device_extensions", NULL, 0);
335 user_exts_str = av_strdup(user_exts->value);
336 if (!user_exts_str) {
337 err = AVERROR(ENOMEM);
341 vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
342 &sup_ext_count, NULL);
343 sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
345 return AVERROR(ENOMEM);
346 vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
347 &sup_ext_count, sup_ext);
350 for (int i = 0; i < optional_exts_num; i++) {
351 tstr = optional_exts[i].name;
353 for (int j = 0; j < sup_ext_count; j++) {
354 if (!strcmp(tstr, sup_ext[j].extensionName)) {
362 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
363 p->extensions |= optional_exts[i].flag;
364 ADD_VAL_TO_LIST(extension_names, extensions_found, tstr);
368 tstr = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
370 for (int j = 0; j < sup_ext_count; j++) {
371 if (!strcmp(tstr, sup_ext[j].extensionName)) {
377 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
378 ADD_VAL_TO_LIST(extension_names, extensions_found, tstr);
380 av_log(ctx, AV_LOG_ERROR, "Debug extension \"%s\" not found!\n",
382 err = AVERROR(EINVAL);
388 char *save, *token = av_strtok(user_exts_str, "+", &save);
391 for (int j = 0; j < sup_ext_count; j++) {
392 if (!strcmp(token, sup_ext[j].extensionName)) {
398 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, token);
399 ADD_VAL_TO_LIST(extension_names, extensions_found, token);
401 av_log(ctx, AV_LOG_WARNING, "%s extension \"%s\" not found, excluding.\n",
404 token = av_strtok(NULL, "+", &save);
408 *dst = extension_names;
409 *num = extensions_found;
411 av_free(user_exts_str);
417 for (int i = 0; i < extensions_found; i++)
418 av_free((void *)extension_names[i]);
419 av_free(extension_names);
420 av_free(user_exts_str);
425 /* Creates a VkInstance */
426 static int create_instance(AVHWDeviceContext *ctx, AVDictionary *opts)
430 VulkanDevicePriv *p = ctx->internal->priv;
431 AVVulkanDeviceContext *hwctx = ctx->hwctx;
432 AVDictionaryEntry *debug_opt = av_dict_get(opts, "debug", NULL, 0);
433 const int debug_mode = debug_opt && strtol(debug_opt->value, NULL, 10);
434 VkApplicationInfo application_info = {
435 .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
436 .pEngineName = "libavutil",
437 .apiVersion = VK_API_VERSION_1_1,
438 .engineVersion = VK_MAKE_VERSION(LIBAVUTIL_VERSION_MAJOR,
439 LIBAVUTIL_VERSION_MINOR,
440 LIBAVUTIL_VERSION_MICRO),
442 VkInstanceCreateInfo inst_props = {
443 .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
444 .pApplicationInfo = &application_info,
447 /* Check for present/missing extensions */
448 err = check_extensions(ctx, 0, opts, &inst_props.ppEnabledExtensionNames,
449 &inst_props.enabledExtensionCount, debug_mode);
454 static const char *layers[] = { "VK_LAYER_KHRONOS_validation" };
455 inst_props.ppEnabledLayerNames = layers;
456 inst_props.enabledLayerCount = FF_ARRAY_ELEMS(layers);
459 /* Try to create the instance */
460 ret = vkCreateInstance(&inst_props, hwctx->alloc, &hwctx->inst);
462 /* Check for errors */
463 if (ret != VK_SUCCESS) {
464 av_log(ctx, AV_LOG_ERROR, "Instance creation failure: %s\n",
466 for (int i = 0; i < inst_props.enabledExtensionCount; i++)
467 av_free((void *)inst_props.ppEnabledExtensionNames[i]);
468 av_free((void *)inst_props.ppEnabledExtensionNames);
469 return AVERROR_EXTERNAL;
473 VkDebugUtilsMessengerCreateInfoEXT dbg = {
474 .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT,
475 .messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT |
476 VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT |
477 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
478 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT,
479 .messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
480 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
481 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT,
482 .pfnUserCallback = vk_dbg_callback,
485 VK_LOAD_PFN(hwctx->inst, vkCreateDebugUtilsMessengerEXT);
487 pfn_vkCreateDebugUtilsMessengerEXT(hwctx->inst, &dbg,
488 hwctx->alloc, &p->debug_ctx);
491 hwctx->enabled_inst_extensions = inst_props.ppEnabledExtensionNames;
492 hwctx->nb_enabled_inst_extensions = inst_props.enabledExtensionCount;
497 typedef struct VulkanDeviceSelection {
498 uint8_t uuid[VK_UUID_SIZE]; /* Will use this first unless !has_uuid */
500 const char *name; /* Will use this second unless NULL */
501 uint32_t pci_device; /* Will use this third unless 0x0 */
502 uint32_t vendor_id; /* Last resort to find something deterministic */
503 int index; /* Finally fall back to index */
504 } VulkanDeviceSelection;
506 static const char *vk_dev_type(enum VkPhysicalDeviceType type)
509 case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: return "integrated";
510 case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: return "discrete";
511 case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: return "virtual";
512 case VK_PHYSICAL_DEVICE_TYPE_CPU: return "software";
513 default: return "unknown";
518 static int find_device(AVHWDeviceContext *ctx, VulkanDeviceSelection *select)
520 int err = 0, choice = -1;
523 VkPhysicalDevice *devices = NULL;
524 VkPhysicalDeviceIDProperties *idp = NULL;
525 VkPhysicalDeviceProperties2 *prop = NULL;
526 VulkanDevicePriv *p = ctx->internal->priv;
527 AVVulkanDeviceContext *hwctx = ctx->hwctx;
529 ret = vkEnumeratePhysicalDevices(hwctx->inst, &num, NULL);
530 if (ret != VK_SUCCESS || !num) {
531 av_log(ctx, AV_LOG_ERROR, "No devices found: %s!\n", vk_ret2str(ret));
532 return AVERROR(ENODEV);
535 devices = av_malloc_array(num, sizeof(VkPhysicalDevice));
537 return AVERROR(ENOMEM);
539 ret = vkEnumeratePhysicalDevices(hwctx->inst, &num, devices);
540 if (ret != VK_SUCCESS) {
541 av_log(ctx, AV_LOG_ERROR, "Failed enumerating devices: %s\n",
543 err = AVERROR(ENODEV);
547 prop = av_mallocz_array(num, sizeof(*prop));
549 err = AVERROR(ENOMEM);
553 idp = av_mallocz_array(num, sizeof(*idp));
555 err = AVERROR(ENOMEM);
559 av_log(ctx, AV_LOG_VERBOSE, "GPU listing:\n");
560 for (int i = 0; i < num; i++) {
561 idp[i].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES;
562 prop[i].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
563 prop[i].pNext = &idp[i];
565 vkGetPhysicalDeviceProperties2(devices[i], &prop[i]);
566 av_log(ctx, AV_LOG_VERBOSE, " %d: %s (%s) (0x%x)\n", i,
567 prop[i].properties.deviceName,
568 vk_dev_type(prop[i].properties.deviceType),
569 prop[i].properties.deviceID);
572 if (select->has_uuid) {
573 for (int i = 0; i < num; i++) {
574 if (!strncmp(idp[i].deviceUUID, select->uuid, VK_UUID_SIZE)) {
579 av_log(ctx, AV_LOG_ERROR, "Unable to find device by given UUID!\n");
580 err = AVERROR(ENODEV);
582 } else if (select->name) {
583 av_log(ctx, AV_LOG_VERBOSE, "Requested device: %s\n", select->name);
584 for (int i = 0; i < num; i++) {
585 if (strstr(prop[i].properties.deviceName, select->name)) {
590 av_log(ctx, AV_LOG_ERROR, "Unable to find device \"%s\"!\n",
592 err = AVERROR(ENODEV);
594 } else if (select->pci_device) {
595 av_log(ctx, AV_LOG_VERBOSE, "Requested device: 0x%x\n", select->pci_device);
596 for (int i = 0; i < num; i++) {
597 if (select->pci_device == prop[i].properties.deviceID) {
602 av_log(ctx, AV_LOG_ERROR, "Unable to find device with PCI ID 0x%x!\n",
604 err = AVERROR(EINVAL);
606 } else if (select->vendor_id) {
607 av_log(ctx, AV_LOG_VERBOSE, "Requested vendor: 0x%x\n", select->vendor_id);
608 for (int i = 0; i < num; i++) {
609 if (select->vendor_id == prop[i].properties.vendorID) {
614 av_log(ctx, AV_LOG_ERROR, "Unable to find device with Vendor ID 0x%x!\n",
616 err = AVERROR(ENODEV);
619 if (select->index < num) {
620 choice = select->index;
623 av_log(ctx, AV_LOG_ERROR, "Unable to find device with index %i!\n",
625 err = AVERROR(ENODEV);
631 p->dev_is_nvidia = (prop[choice].properties.vendorID == 0x10de);
632 hwctx->phys_dev = devices[choice];
641 static int search_queue_families(AVHWDeviceContext *ctx, VkDeviceCreateInfo *cd)
645 VkQueueFamilyProperties *qs = NULL;
646 AVVulkanDeviceContext *hwctx = ctx->hwctx;
647 int graph_index = -1, comp_index = -1, tx_index = -1;
648 VkDeviceQueueCreateInfo *pc = (VkDeviceQueueCreateInfo *)cd->pQueueCreateInfos;
650 /* First get the number of queue families */
651 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, NULL);
653 av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
654 return AVERROR_EXTERNAL;
657 /* Then allocate memory */
658 qs = av_malloc_array(num, sizeof(VkQueueFamilyProperties));
660 return AVERROR(ENOMEM);
662 /* Finally retrieve the queue families */
663 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, qs);
665 #define SEARCH_FLAGS(expr, out) \
666 for (int i = 0; i < num; i++) { \
667 const VkQueueFlagBits flags = qs[i].queueFlags; \
674 SEARCH_FLAGS(flags & VK_QUEUE_GRAPHICS_BIT, graph_index)
676 SEARCH_FLAGS((flags & VK_QUEUE_COMPUTE_BIT) && (i != graph_index),
679 SEARCH_FLAGS((flags & VK_QUEUE_TRANSFER_BIT) && (i != graph_index) &&
680 (i != comp_index), tx_index)
683 #define ADD_QUEUE(fidx, graph, comp, tx) \
684 av_log(ctx, AV_LOG_VERBOSE, "Using queue family %i (total queues: %i) for %s%s%s\n", \
685 fidx, qs[fidx].queueCount, graph ? "graphics " : "", \
686 comp ? "compute " : "", tx ? "transfers " : ""); \
687 av_log(ctx, AV_LOG_VERBOSE, " QF %i flags: %s%s%s%s\n", fidx, \
688 ((qs[fidx].queueFlags) & VK_QUEUE_GRAPHICS_BIT) ? "(graphics) " : "", \
689 ((qs[fidx].queueFlags) & VK_QUEUE_COMPUTE_BIT) ? "(compute) " : "", \
690 ((qs[fidx].queueFlags) & VK_QUEUE_TRANSFER_BIT) ? "(transfers) " : "", \
691 ((qs[fidx].queueFlags) & VK_QUEUE_SPARSE_BINDING_BIT) ? "(sparse) " : ""); \
692 pc[cd->queueCreateInfoCount].queueFamilyIndex = fidx; \
693 pc[cd->queueCreateInfoCount].queueCount = qs[fidx].queueCount; \
694 weights = av_malloc(qs[fidx].queueCount * sizeof(float)); \
695 pc[cd->queueCreateInfoCount].pQueuePriorities = weights; \
698 for (int i = 0; i < qs[fidx].queueCount; i++) \
700 cd->queueCreateInfoCount++;
702 ADD_QUEUE(graph_index, 1, comp_index < 0, tx_index < 0 && comp_index < 0)
703 hwctx->queue_family_index = graph_index;
704 hwctx->queue_family_comp_index = graph_index;
705 hwctx->queue_family_tx_index = graph_index;
706 hwctx->nb_graphics_queues = qs[graph_index].queueCount;
708 if (comp_index != -1) {
709 ADD_QUEUE(comp_index, 0, 1, tx_index < 0)
710 hwctx->queue_family_tx_index = comp_index;
711 hwctx->queue_family_comp_index = comp_index;
712 hwctx->nb_comp_queues = qs[comp_index].queueCount;
715 if (tx_index != -1) {
716 ADD_QUEUE(tx_index, 0, 0, 1)
717 hwctx->queue_family_tx_index = tx_index;
718 hwctx->nb_tx_queues = qs[tx_index].queueCount;
727 av_freep(&pc[0].pQueuePriorities);
728 av_freep(&pc[1].pQueuePriorities);
729 av_freep(&pc[2].pQueuePriorities);
732 return AVERROR(ENOMEM);
735 static int create_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd,
736 int queue_family_index, int num_queues)
739 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
741 VkCommandPoolCreateInfo cqueue_create = {
742 .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
743 .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
744 .queueFamilyIndex = queue_family_index,
746 VkCommandBufferAllocateInfo cbuf_create = {
747 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
748 .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
749 .commandBufferCount = num_queues,
752 cmd->nb_queues = num_queues;
754 cmd->queues = av_mallocz(num_queues * sizeof(*cmd->queues));
756 return AVERROR(ENOMEM);
758 cmd->bufs = av_mallocz(num_queues * sizeof(*cmd->bufs));
760 return AVERROR(ENOMEM);
762 /* Create command pool */
763 ret = vkCreateCommandPool(hwctx->act_dev, &cqueue_create,
764 hwctx->alloc, &cmd->pool);
765 if (ret != VK_SUCCESS) {
766 av_log(hwfc, AV_LOG_ERROR, "Command pool creation failure: %s\n",
768 return AVERROR_EXTERNAL;
771 cbuf_create.commandPool = cmd->pool;
773 /* Allocate command buffer */
774 ret = vkAllocateCommandBuffers(hwctx->act_dev, &cbuf_create, cmd->bufs);
775 if (ret != VK_SUCCESS) {
776 av_log(hwfc, AV_LOG_ERROR, "Command buffer alloc failure: %s\n",
778 return AVERROR_EXTERNAL;
781 for (int i = 0; i < num_queues; i++) {
782 VulkanQueueCtx *q = &cmd->queues[i];
783 vkGetDeviceQueue(hwctx->act_dev, queue_family_index, i, &q->queue);
784 q->was_synchronous = 1;
790 static void free_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd)
792 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
794 /* Make sure all queues have finished executing */
795 for (int i = 0; i < cmd->nb_queues; i++) {
796 VulkanQueueCtx *q = &cmd->queues[i];
798 if (q->fence && !q->was_synchronous) {
799 vkWaitForFences(hwctx->act_dev, 1, &q->fence, VK_TRUE, UINT64_MAX);
800 vkResetFences(hwctx->act_dev, 1, &q->fence);
805 vkDestroyFence(hwctx->act_dev, q->fence, hwctx->alloc);
807 /* Free buffer dependencies */
808 for (int j = 0; j < q->nb_buf_deps; j++)
809 av_buffer_unref(&q->buf_deps[j]);
810 av_free(q->buf_deps);
814 vkFreeCommandBuffers(hwctx->act_dev, cmd->pool, cmd->nb_queues, cmd->bufs);
816 vkDestroyCommandPool(hwctx->act_dev, cmd->pool, hwctx->alloc);
818 av_freep(&cmd->bufs);
819 av_freep(&cmd->queues);
822 static VkCommandBuffer get_buf_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd)
824 return cmd->bufs[cmd->cur_queue_idx];
827 static void unref_exec_ctx_deps(AVHWFramesContext *hwfc, VulkanExecCtx *cmd)
829 VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
831 for (int j = 0; j < q->nb_buf_deps; j++)
832 av_buffer_unref(&q->buf_deps[j]);
836 static int wait_start_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd)
839 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
840 VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
842 VkCommandBufferBeginInfo cmd_start = {
843 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
844 .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
847 /* Create the fence and don't wait for it initially */
849 VkFenceCreateInfo fence_spawn = {
850 .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
852 ret = vkCreateFence(hwctx->act_dev, &fence_spawn, hwctx->alloc,
854 if (ret != VK_SUCCESS) {
855 av_log(hwfc, AV_LOG_ERROR, "Failed to queue frame fence: %s\n",
857 return AVERROR_EXTERNAL;
859 } else if (!q->was_synchronous) {
860 vkWaitForFences(hwctx->act_dev, 1, &q->fence, VK_TRUE, UINT64_MAX);
861 vkResetFences(hwctx->act_dev, 1, &q->fence);
864 /* Discard queue dependencies */
865 unref_exec_ctx_deps(hwfc, cmd);
867 ret = vkBeginCommandBuffer(cmd->bufs[cmd->cur_queue_idx], &cmd_start);
868 if (ret != VK_SUCCESS) {
869 av_log(hwfc, AV_LOG_ERROR, "Unable to init command buffer: %s\n",
871 return AVERROR_EXTERNAL;
877 static int add_buf_dep_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd,
878 AVBufferRef * const *deps, int nb_deps)
881 VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
883 if (!deps || !nb_deps)
886 dst = av_fast_realloc(q->buf_deps, &q->buf_deps_alloc_size,
887 (q->nb_buf_deps + nb_deps) * sizeof(*dst));
893 for (int i = 0; i < nb_deps; i++) {
894 q->buf_deps[q->nb_buf_deps] = av_buffer_ref(deps[i]);
895 if (!q->buf_deps[q->nb_buf_deps])
903 unref_exec_ctx_deps(hwfc, cmd);
904 return AVERROR(ENOMEM);
907 static int submit_exec_ctx(AVHWFramesContext *hwfc, VulkanExecCtx *cmd,
908 VkSubmitInfo *s_info, int synchronous)
911 VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
913 ret = vkEndCommandBuffer(cmd->bufs[cmd->cur_queue_idx]);
914 if (ret != VK_SUCCESS) {
915 av_log(hwfc, AV_LOG_ERROR, "Unable to finish command buffer: %s\n",
917 unref_exec_ctx_deps(hwfc, cmd);
918 return AVERROR_EXTERNAL;
921 s_info->pCommandBuffers = &cmd->bufs[cmd->cur_queue_idx];
922 s_info->commandBufferCount = 1;
924 ret = vkQueueSubmit(q->queue, 1, s_info, q->fence);
925 if (ret != VK_SUCCESS) {
926 unref_exec_ctx_deps(hwfc, cmd);
927 return AVERROR_EXTERNAL;
930 q->was_synchronous = synchronous;
933 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
934 vkWaitForFences(hwctx->act_dev, 1, &q->fence, VK_TRUE, UINT64_MAX);
935 vkResetFences(hwctx->act_dev, 1, &q->fence);
936 unref_exec_ctx_deps(hwfc, cmd);
937 } else { /* Rotate queues */
938 cmd->cur_queue_idx = (cmd->cur_queue_idx + 1) % cmd->nb_queues;
944 static void vulkan_device_free(AVHWDeviceContext *ctx)
946 VulkanDevicePriv *p = ctx->internal->priv;
947 AVVulkanDeviceContext *hwctx = ctx->hwctx;
949 vkDestroyDevice(hwctx->act_dev, hwctx->alloc);
952 VK_LOAD_PFN(hwctx->inst, vkDestroyDebugUtilsMessengerEXT);
953 pfn_vkDestroyDebugUtilsMessengerEXT(hwctx->inst, p->debug_ctx,
957 vkDestroyInstance(hwctx->inst, hwctx->alloc);
959 for (int i = 0; i < hwctx->nb_enabled_inst_extensions; i++)
960 av_free((void *)hwctx->enabled_inst_extensions[i]);
961 av_free((void *)hwctx->enabled_inst_extensions);
963 for (int i = 0; i < hwctx->nb_enabled_dev_extensions; i++)
964 av_free((void *)hwctx->enabled_dev_extensions[i]);
965 av_free((void *)hwctx->enabled_dev_extensions);
968 static int vulkan_device_create_internal(AVHWDeviceContext *ctx,
969 VulkanDeviceSelection *dev_select,
970 AVDictionary *opts, int flags)
974 AVDictionaryEntry *opt_d;
975 VulkanDevicePriv *p = ctx->internal->priv;
976 AVVulkanDeviceContext *hwctx = ctx->hwctx;
977 VkPhysicalDeviceFeatures dev_features = { 0 };
978 VkDeviceQueueCreateInfo queue_create_info[3] = {
979 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, },
980 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, },
981 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, },
984 VkDeviceCreateInfo dev_info = {
985 .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
986 .pNext = &hwctx->device_features,
987 .pQueueCreateInfos = queue_create_info,
988 .queueCreateInfoCount = 0,
991 hwctx->device_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
992 ctx->free = vulkan_device_free;
994 /* Create an instance if not given one */
995 if ((err = create_instance(ctx, opts)))
998 /* Find a device (if not given one) */
999 if ((err = find_device(ctx, dev_select)))
1002 vkGetPhysicalDeviceProperties(hwctx->phys_dev, &p->props);
1003 av_log(ctx, AV_LOG_VERBOSE, "Using device: %s\n", p->props.deviceName);
1004 av_log(ctx, AV_LOG_VERBOSE, "Alignments:\n");
1005 av_log(ctx, AV_LOG_VERBOSE, " optimalBufferCopyOffsetAlignment: %li\n",
1006 p->props.limits.optimalBufferCopyOffsetAlignment);
1007 av_log(ctx, AV_LOG_VERBOSE, " optimalBufferCopyRowPitchAlignment: %li\n",
1008 p->props.limits.optimalBufferCopyRowPitchAlignment);
1009 av_log(ctx, AV_LOG_VERBOSE, " minMemoryMapAlignment: %li\n",
1010 p->props.limits.minMemoryMapAlignment);
1012 vkGetPhysicalDeviceFeatures(hwctx->phys_dev, &dev_features);
1013 #define COPY_FEATURE(DST, NAME) (DST).features.NAME = dev_features.NAME;
1014 COPY_FEATURE(hwctx->device_features, shaderImageGatherExtended)
1015 COPY_FEATURE(hwctx->device_features, fragmentStoresAndAtomics)
1016 COPY_FEATURE(hwctx->device_features, vertexPipelineStoresAndAtomics)
1017 COPY_FEATURE(hwctx->device_features, shaderInt64)
1020 /* Search queue family */
1021 if ((err = search_queue_families(ctx, &dev_info)))
1024 if ((err = check_extensions(ctx, 1, opts, &dev_info.ppEnabledExtensionNames,
1025 &dev_info.enabledExtensionCount, 0))) {
1026 av_free((void *)queue_create_info[0].pQueuePriorities);
1027 av_free((void *)queue_create_info[1].pQueuePriorities);
1028 av_free((void *)queue_create_info[2].pQueuePriorities);
1032 ret = vkCreateDevice(hwctx->phys_dev, &dev_info, hwctx->alloc,
1035 av_free((void *)queue_create_info[0].pQueuePriorities);
1036 av_free((void *)queue_create_info[1].pQueuePriorities);
1037 av_free((void *)queue_create_info[2].pQueuePriorities);
1039 if (ret != VK_SUCCESS) {
1040 av_log(ctx, AV_LOG_ERROR, "Device creation failure: %s\n",
1042 for (int i = 0; i < dev_info.enabledExtensionCount; i++)
1043 av_free((void *)dev_info.ppEnabledExtensionNames[i]);
1044 av_free((void *)dev_info.ppEnabledExtensionNames);
1045 err = AVERROR_EXTERNAL;
1049 /* Tiled images setting, use them by default */
1050 opt_d = av_dict_get(opts, "linear_images", NULL, 0);
1052 p->use_linear_images = strtol(opt_d->value, NULL, 10);
1054 hwctx->enabled_dev_extensions = dev_info.ppEnabledExtensionNames;
1055 hwctx->nb_enabled_dev_extensions = dev_info.enabledExtensionCount;
1061 static int vulkan_device_init(AVHWDeviceContext *ctx)
1064 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1065 VulkanDevicePriv *p = ctx->internal->priv;
1067 /* Set device extension flags */
1068 for (int i = 0; i < hwctx->nb_enabled_dev_extensions; i++) {
1069 for (int j = 0; j < FF_ARRAY_ELEMS(optional_device_exts); j++) {
1070 if (!strcmp(hwctx->enabled_dev_extensions[i],
1071 optional_device_exts[j].name)) {
1072 p->extensions |= optional_device_exts[j].flag;
1078 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &queue_num, NULL);
1080 av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
1081 return AVERROR_EXTERNAL;
1084 #define CHECK_QUEUE(type, n) \
1085 if (n >= queue_num) { \
1086 av_log(ctx, AV_LOG_ERROR, "Invalid %s queue index %i (device has %i queues)!\n", \
1087 type, n, queue_num); \
1088 return AVERROR(EINVAL); \
1091 CHECK_QUEUE("graphics", hwctx->queue_family_index)
1092 CHECK_QUEUE("upload", hwctx->queue_family_tx_index)
1093 CHECK_QUEUE("compute", hwctx->queue_family_comp_index)
1097 p->qfs[p->num_qfs++] = hwctx->queue_family_index;
1098 if ((hwctx->queue_family_tx_index != hwctx->queue_family_index) &&
1099 (hwctx->queue_family_tx_index != hwctx->queue_family_comp_index))
1100 p->qfs[p->num_qfs++] = hwctx->queue_family_tx_index;
1101 if ((hwctx->queue_family_comp_index != hwctx->queue_family_index) &&
1102 (hwctx->queue_family_comp_index != hwctx->queue_family_tx_index))
1103 p->qfs[p->num_qfs++] = hwctx->queue_family_comp_index;
1105 /* Get device capabilities */
1106 vkGetPhysicalDeviceMemoryProperties(hwctx->phys_dev, &p->mprops);
1111 static int vulkan_device_create(AVHWDeviceContext *ctx, const char *device,
1112 AVDictionary *opts, int flags)
1114 VulkanDeviceSelection dev_select = { 0 };
1115 if (device && device[0]) {
1117 dev_select.index = strtol(device, &end, 10);
1118 if (end == device) {
1119 dev_select.index = 0;
1120 dev_select.name = device;
1124 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1127 static int vulkan_device_derive(AVHWDeviceContext *ctx,
1128 AVHWDeviceContext *src_ctx,
1129 AVDictionary *opts, int flags)
1131 av_unused VulkanDeviceSelection dev_select = { 0 };
1133 /* If there's only one device on the system, then even if its not covered
1134 * by the following checks (e.g. non-PCIe ARM GPU), having an empty
1135 * dev_select will mean it'll get picked. */
1136 switch(src_ctx->type) {
1139 case AV_HWDEVICE_TYPE_VAAPI: {
1140 AVVAAPIDeviceContext *src_hwctx = src_ctx->hwctx;
1142 const char *vendor = vaQueryVendorString(src_hwctx->display);
1144 av_log(ctx, AV_LOG_ERROR, "Unable to get device info from VAAPI!\n");
1145 return AVERROR_EXTERNAL;
1148 if (strstr(vendor, "Intel"))
1149 dev_select.vendor_id = 0x8086;
1150 if (strstr(vendor, "AMD"))
1151 dev_select.vendor_id = 0x1002;
1153 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1156 case AV_HWDEVICE_TYPE_DRM: {
1157 AVDRMDeviceContext *src_hwctx = src_ctx->hwctx;
1159 drmDevice *drm_dev_info;
1160 int err = drmGetDevice(src_hwctx->fd, &drm_dev_info);
1162 av_log(ctx, AV_LOG_ERROR, "Unable to get device info from DRM fd!\n");
1163 return AVERROR_EXTERNAL;
1166 if (drm_dev_info->bustype == DRM_BUS_PCI)
1167 dev_select.pci_device = drm_dev_info->deviceinfo.pci->device_id;
1169 drmFreeDevice(&drm_dev_info);
1171 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1175 case AV_HWDEVICE_TYPE_CUDA: {
1176 AVHWDeviceContext *cuda_cu = src_ctx;
1177 AVCUDADeviceContext *src_hwctx = src_ctx->hwctx;
1178 AVCUDADeviceContextInternal *cu_internal = src_hwctx->internal;
1179 CudaFunctions *cu = cu_internal->cuda_dl;
1181 int ret = CHECK_CU(cu->cuDeviceGetUuid((CUuuid *)&dev_select.uuid,
1182 cu_internal->cuda_device));
1184 av_log(ctx, AV_LOG_ERROR, "Unable to get UUID from CUDA!\n");
1185 return AVERROR_EXTERNAL;
1188 dev_select.has_uuid = 1;
1190 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1194 return AVERROR(ENOSYS);
1198 static int vulkan_frames_get_constraints(AVHWDeviceContext *ctx,
1199 const void *hwconfig,
1200 AVHWFramesConstraints *constraints)
1203 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1204 VulkanDevicePriv *p = ctx->internal->priv;
1206 for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
1207 count += pixfmt_is_supported(hwctx, i, p->use_linear_images);
1210 if (p->dev_is_nvidia)
1214 constraints->valid_sw_formats = av_malloc_array(count + 1,
1215 sizeof(enum AVPixelFormat));
1216 if (!constraints->valid_sw_formats)
1217 return AVERROR(ENOMEM);
1220 for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
1221 if (pixfmt_is_supported(hwctx, i, p->use_linear_images))
1222 constraints->valid_sw_formats[count++] = i;
1225 if (p->dev_is_nvidia)
1226 constraints->valid_sw_formats[count++] = AV_PIX_FMT_CUDA;
1228 constraints->valid_sw_formats[count++] = AV_PIX_FMT_NONE;
1230 constraints->min_width = 0;
1231 constraints->min_height = 0;
1232 constraints->max_width = p->props.limits.maxImageDimension2D;
1233 constraints->max_height = p->props.limits.maxImageDimension2D;
1235 constraints->valid_hw_formats = av_malloc_array(2, sizeof(enum AVPixelFormat));
1236 if (!constraints->valid_hw_formats)
1237 return AVERROR(ENOMEM);
1239 constraints->valid_hw_formats[0] = AV_PIX_FMT_VULKAN;
1240 constraints->valid_hw_formats[1] = AV_PIX_FMT_NONE;
1245 static int alloc_mem(AVHWDeviceContext *ctx, VkMemoryRequirements *req,
1246 VkMemoryPropertyFlagBits req_flags, void *alloc_extension,
1247 VkMemoryPropertyFlagBits *mem_flags, VkDeviceMemory *mem)
1251 VulkanDevicePriv *p = ctx->internal->priv;
1252 AVVulkanDeviceContext *dev_hwctx = ctx->hwctx;
1253 VkMemoryAllocateInfo alloc_info = {
1254 .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
1255 .pNext = alloc_extension,
1258 /* Align if we need to */
1259 if (req_flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)
1260 req->size = FFALIGN(req->size, p->props.limits.minMemoryMapAlignment);
1262 alloc_info.allocationSize = req->size;
1264 /* The vulkan spec requires memory types to be sorted in the "optimal"
1265 * order, so the first matching type we find will be the best/fastest one */
1266 for (int i = 0; i < p->mprops.memoryTypeCount; i++) {
1267 /* The memory type must be supported by the requirements (bitfield) */
1268 if (!(req->memoryTypeBits & (1 << i)))
1271 /* The memory type flags must include our properties */
1272 if ((p->mprops.memoryTypes[i].propertyFlags & req_flags) != req_flags)
1275 /* Found a suitable memory type */
1281 av_log(ctx, AV_LOG_ERROR, "No memory type found for flags 0x%x\n",
1283 return AVERROR(EINVAL);
1286 alloc_info.memoryTypeIndex = index;
1288 ret = vkAllocateMemory(dev_hwctx->act_dev, &alloc_info,
1289 dev_hwctx->alloc, mem);
1290 if (ret != VK_SUCCESS) {
1291 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory: %s\n",
1293 return AVERROR(ENOMEM);
1296 *mem_flags |= p->mprops.memoryTypes[index].propertyFlags;
1301 static void vulkan_free_internal(AVVkFrameInternal *internal)
1307 if (internal->cuda_fc_ref) {
1308 AVHWFramesContext *cuda_fc = (AVHWFramesContext *)internal->cuda_fc_ref->data;
1309 int planes = av_pix_fmt_count_planes(cuda_fc->sw_format);
1310 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
1311 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
1312 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
1313 CudaFunctions *cu = cu_internal->cuda_dl;
1315 for (int i = 0; i < planes; i++) {
1316 if (internal->cu_sem[i])
1317 CHECK_CU(cu->cuDestroyExternalSemaphore(internal->cu_sem[i]));
1318 if (internal->cu_mma[i])
1319 CHECK_CU(cu->cuMipmappedArrayDestroy(internal->cu_mma[i]));
1320 if (internal->ext_mem[i])
1321 CHECK_CU(cu->cuDestroyExternalMemory(internal->ext_mem[i]));
1324 av_buffer_unref(&internal->cuda_fc_ref);
1331 static void vulkan_frame_free(void *opaque, uint8_t *data)
1333 AVVkFrame *f = (AVVkFrame *)data;
1334 AVHWFramesContext *hwfc = opaque;
1335 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1336 int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1338 vulkan_free_internal(f->internal);
1340 for (int i = 0; i < planes; i++) {
1341 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
1342 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
1343 vkDestroySemaphore(hwctx->act_dev, f->sem[i], hwctx->alloc);
1349 static int alloc_bind_mem(AVHWFramesContext *hwfc, AVVkFrame *f,
1350 void *alloc_pnext, size_t alloc_pnext_stride)
1354 AVHWDeviceContext *ctx = hwfc->device_ctx;
1355 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1356 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { { 0 } };
1358 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1360 for (int i = 0; i < planes; i++) {
1362 VkImageMemoryRequirementsInfo2 req_desc = {
1363 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
1366 VkMemoryDedicatedAllocateInfo ded_alloc = {
1367 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
1368 .pNext = (void *)(((uint8_t *)alloc_pnext) + i*alloc_pnext_stride),
1370 VkMemoryDedicatedRequirements ded_req = {
1371 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
1373 VkMemoryRequirements2 req = {
1374 .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
1378 vkGetImageMemoryRequirements2(hwctx->act_dev, &req_desc, &req);
1380 /* In case the implementation prefers/requires dedicated allocation */
1381 use_ded_mem = ded_req.prefersDedicatedAllocation |
1382 ded_req.requiresDedicatedAllocation;
1384 ded_alloc.image = f->img[i];
1386 /* Allocate memory */
1387 if ((err = alloc_mem(ctx, &req.memoryRequirements,
1388 f->tiling == VK_IMAGE_TILING_LINEAR ?
1389 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT :
1390 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1391 use_ded_mem ? &ded_alloc : (void *)ded_alloc.pNext,
1392 &f->flags, &f->mem[i])))
1395 f->size[i] = req.memoryRequirements.size;
1396 bind_info[i].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
1397 bind_info[i].image = f->img[i];
1398 bind_info[i].memory = f->mem[i];
1401 /* Bind the allocated memory to the images */
1402 ret = vkBindImageMemory2(hwctx->act_dev, planes, bind_info);
1403 if (ret != VK_SUCCESS) {
1404 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
1406 return AVERROR_EXTERNAL;
1414 PREP_MODE_RO_SHADER,
1415 PREP_MODE_EXTERNAL_EXPORT,
1418 static int prepare_frame(AVHWFramesContext *hwfc, VulkanExecCtx *ectx,
1419 AVVkFrame *frame, enum PrepMode pmode)
1423 VkImageLayout new_layout;
1424 VkAccessFlags new_access;
1425 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1427 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
1429 VkSubmitInfo s_info = {
1430 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
1431 .pSignalSemaphores = frame->sem,
1432 .signalSemaphoreCount = planes,
1435 VkPipelineStageFlagBits wait_st[AV_NUM_DATA_POINTERS];
1436 for (int i = 0; i < planes; i++)
1437 wait_st[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
1440 case PREP_MODE_WRITE:
1441 new_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
1442 new_access = VK_ACCESS_TRANSFER_WRITE_BIT;
1443 dst_qf = VK_QUEUE_FAMILY_IGNORED;
1445 case PREP_MODE_RO_SHADER:
1446 new_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
1447 new_access = VK_ACCESS_TRANSFER_READ_BIT;
1448 dst_qf = VK_QUEUE_FAMILY_IGNORED;
1450 case PREP_MODE_EXTERNAL_EXPORT:
1451 new_layout = VK_IMAGE_LAYOUT_GENERAL;
1452 new_access = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
1453 dst_qf = VK_QUEUE_FAMILY_EXTERNAL_KHR;
1454 s_info.pWaitSemaphores = frame->sem;
1455 s_info.pWaitDstStageMask = wait_st;
1456 s_info.waitSemaphoreCount = planes;
1460 if ((err = wait_start_exec_ctx(hwfc, ectx)))
1463 /* Change the image layout to something more optimal for writes.
1464 * This also signals the newly created semaphore, making it usable
1465 * for synchronization */
1466 for (int i = 0; i < planes; i++) {
1467 img_bar[i].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1468 img_bar[i].srcAccessMask = 0x0;
1469 img_bar[i].dstAccessMask = new_access;
1470 img_bar[i].oldLayout = frame->layout[i];
1471 img_bar[i].newLayout = new_layout;
1472 img_bar[i].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1473 img_bar[i].dstQueueFamilyIndex = dst_qf;
1474 img_bar[i].image = frame->img[i];
1475 img_bar[i].subresourceRange.levelCount = 1;
1476 img_bar[i].subresourceRange.layerCount = 1;
1477 img_bar[i].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1479 frame->layout[i] = img_bar[i].newLayout;
1480 frame->access[i] = img_bar[i].dstAccessMask;
1483 vkCmdPipelineBarrier(get_buf_exec_ctx(hwfc, ectx),
1484 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
1485 VK_PIPELINE_STAGE_TRANSFER_BIT,
1486 0, 0, NULL, 0, NULL, planes, img_bar);
1488 return submit_exec_ctx(hwfc, ectx, &s_info, 0);
1491 static int create_frame(AVHWFramesContext *hwfc, AVVkFrame **frame,
1492 VkImageTiling tiling, VkImageUsageFlagBits usage,
1497 AVHWDeviceContext *ctx = hwfc->device_ctx;
1498 VulkanDevicePriv *p = ctx->internal->priv;
1499 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1500 enum AVPixelFormat format = hwfc->sw_format;
1501 const VkFormat *img_fmts = av_vkfmt_from_pixfmt(format);
1502 const int planes = av_pix_fmt_count_planes(format);
1504 VkExportSemaphoreCreateInfo ext_sem_info = {
1505 .sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO,
1506 .handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
1509 VkSemaphoreCreateInfo sem_spawn = {
1510 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1511 .pNext = p->extensions & EXT_EXTERNAL_FD_SEM ? &ext_sem_info : NULL,
1514 AVVkFrame *f = av_vk_frame_alloc();
1516 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1517 return AVERROR(ENOMEM);
1520 /* Create the images */
1521 for (int i = 0; i < planes; i++) {
1522 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
1523 int w = hwfc->width;
1524 int h = hwfc->height;
1525 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
1526 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
1528 VkImageCreateInfo image_create_info = {
1529 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1530 .pNext = create_pnext,
1531 .imageType = VK_IMAGE_TYPE_2D,
1532 .format = img_fmts[i],
1533 .extent.width = p_w,
1534 .extent.height = p_h,
1538 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1540 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1542 .samples = VK_SAMPLE_COUNT_1_BIT,
1543 .pQueueFamilyIndices = p->qfs,
1544 .queueFamilyIndexCount = p->num_qfs,
1545 .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
1546 VK_SHARING_MODE_EXCLUSIVE,
1549 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
1550 hwctx->alloc, &f->img[i]);
1551 if (ret != VK_SUCCESS) {
1552 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1554 err = AVERROR(EINVAL);
1558 /* Create semaphore */
1559 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1560 hwctx->alloc, &f->sem[i]);
1561 if (ret != VK_SUCCESS) {
1562 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1564 return AVERROR_EXTERNAL;
1567 f->layout[i] = image_create_info.initialLayout;
1578 vulkan_frame_free(hwfc, (uint8_t *)f);
1582 /* Checks if an export flag is enabled, and if it is ORs it with *iexp */
1583 static void try_export_flags(AVHWFramesContext *hwfc,
1584 VkExternalMemoryHandleTypeFlags *comp_handle_types,
1585 VkExternalMemoryHandleTypeFlagBits *iexp,
1586 VkExternalMemoryHandleTypeFlagBits exp)
1589 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1590 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1591 VkExternalImageFormatProperties eprops = {
1592 .sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES_KHR,
1594 VkImageFormatProperties2 props = {
1595 .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,
1598 VkPhysicalDeviceExternalImageFormatInfo enext = {
1599 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
1602 VkPhysicalDeviceImageFormatInfo2 pinfo = {
1603 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1604 .pNext = !exp ? NULL : &enext,
1605 .format = av_vkfmt_from_pixfmt(hwfc->sw_format)[0],
1606 .type = VK_IMAGE_TYPE_2D,
1607 .tiling = hwctx->tiling,
1608 .usage = hwctx->usage,
1609 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1612 ret = vkGetPhysicalDeviceImageFormatProperties2(dev_hwctx->phys_dev,
1614 if (ret == VK_SUCCESS) {
1616 *comp_handle_types |= eprops.externalMemoryProperties.compatibleHandleTypes;
1620 static AVBufferRef *vulkan_pool_alloc(void *opaque, int size)
1624 AVBufferRef *avbuf = NULL;
1625 AVHWFramesContext *hwfc = opaque;
1626 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1627 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1628 VulkanFramesPriv *fp = hwfc->internal->priv;
1629 VkExportMemoryAllocateInfo eminfo[AV_NUM_DATA_POINTERS];
1630 VkExternalMemoryHandleTypeFlags e = 0x0;
1632 VkExternalMemoryImageCreateInfo eiinfo = {
1633 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1634 .pNext = hwctx->create_pnext,
1637 if (p->extensions & EXT_EXTERNAL_FD_MEMORY)
1638 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1639 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT);
1641 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
1642 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1643 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
1645 for (int i = 0; i < av_pix_fmt_count_planes(hwfc->sw_format); i++) {
1646 eminfo[i].sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO;
1647 eminfo[i].pNext = hwctx->alloc_pnext[i];
1648 eminfo[i].handleTypes = e;
1651 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1652 eiinfo.handleTypes ? &eiinfo : NULL);
1656 err = alloc_bind_mem(hwfc, f, eminfo, sizeof(*eminfo));
1660 err = prepare_frame(hwfc, &fp->conv_ctx, f, PREP_MODE_WRITE);
1664 avbuf = av_buffer_create((uint8_t *)f, sizeof(AVVkFrame),
1665 vulkan_frame_free, hwfc, 0);
1672 vulkan_frame_free(hwfc, (uint8_t *)f);
1676 static void vulkan_frames_uninit(AVHWFramesContext *hwfc)
1678 VulkanFramesPriv *fp = hwfc->internal->priv;
1680 free_exec_ctx(hwfc, &fp->conv_ctx);
1681 free_exec_ctx(hwfc, &fp->upload_ctx);
1682 free_exec_ctx(hwfc, &fp->download_ctx);
1685 static int vulkan_frames_init(AVHWFramesContext *hwfc)
1689 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1690 VulkanFramesPriv *fp = hwfc->internal->priv;
1691 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1692 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1694 /* Default pool flags */
1695 hwctx->tiling = hwctx->tiling ? hwctx->tiling : p->use_linear_images ?
1696 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1699 hwctx->usage = DEFAULT_USAGE_FLAGS;
1701 err = create_exec_ctx(hwfc, &fp->conv_ctx,
1702 dev_hwctx->queue_family_comp_index,
1703 GET_QUEUE_COUNT(dev_hwctx, 0, 1, 0));
1707 err = create_exec_ctx(hwfc, &fp->upload_ctx,
1708 dev_hwctx->queue_family_tx_index,
1709 GET_QUEUE_COUNT(dev_hwctx, 0, 0, 1));
1713 err = create_exec_ctx(hwfc, &fp->download_ctx,
1714 dev_hwctx->queue_family_tx_index, 1);
1718 /* Test to see if allocation will fail */
1719 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1720 hwctx->create_pnext);
1724 vulkan_frame_free(hwfc, (uint8_t *)f);
1726 /* If user did not specify a pool, hwfc->pool will be set to the internal one
1727 * in hwcontext.c just after this gets called */
1729 hwfc->internal->pool_internal = av_buffer_pool_init2(sizeof(AVVkFrame),
1730 hwfc, vulkan_pool_alloc,
1732 if (!hwfc->internal->pool_internal) {
1733 err = AVERROR(ENOMEM);
1741 free_exec_ctx(hwfc, &fp->conv_ctx);
1742 free_exec_ctx(hwfc, &fp->upload_ctx);
1743 free_exec_ctx(hwfc, &fp->download_ctx);
1748 static int vulkan_get_buffer(AVHWFramesContext *hwfc, AVFrame *frame)
1750 frame->buf[0] = av_buffer_pool_get(hwfc->pool);
1752 return AVERROR(ENOMEM);
1754 frame->data[0] = frame->buf[0]->data;
1755 frame->format = AV_PIX_FMT_VULKAN;
1756 frame->width = hwfc->width;
1757 frame->height = hwfc->height;
1762 static int vulkan_transfer_get_formats(AVHWFramesContext *hwfc,
1763 enum AVHWFrameTransferDirection dir,
1764 enum AVPixelFormat **formats)
1766 enum AVPixelFormat *fmts = av_malloc_array(2, sizeof(*fmts));
1768 return AVERROR(ENOMEM);
1770 fmts[0] = hwfc->sw_format;
1771 fmts[1] = AV_PIX_FMT_NONE;
1777 typedef struct VulkanMapping {
1782 static void vulkan_unmap_frame(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1784 VulkanMapping *map = hwmap->priv;
1785 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1786 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1788 /* Check if buffer needs flushing */
1789 if ((map->flags & AV_HWFRAME_MAP_WRITE) &&
1790 !(map->frame->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1792 VkMappedMemoryRange flush_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1794 for (int i = 0; i < planes; i++) {
1795 flush_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1796 flush_ranges[i].memory = map->frame->mem[i];
1797 flush_ranges[i].size = VK_WHOLE_SIZE;
1800 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, planes,
1802 if (ret != VK_SUCCESS) {
1803 av_log(hwfc, AV_LOG_ERROR, "Failed to flush memory: %s\n",
1808 for (int i = 0; i < planes; i++)
1809 vkUnmapMemory(hwctx->act_dev, map->frame->mem[i]);
1814 static int vulkan_map_frame_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
1815 const AVFrame *src, int flags)
1818 int err, mapped_mem_count = 0;
1819 AVVkFrame *f = (AVVkFrame *)src->data[0];
1820 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1821 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1823 VulkanMapping *map = av_mallocz(sizeof(VulkanMapping));
1825 return AVERROR(EINVAL);
1827 if (src->format != AV_PIX_FMT_VULKAN) {
1828 av_log(hwfc, AV_LOG_ERROR, "Cannot map from pixel format %s!\n",
1829 av_get_pix_fmt_name(src->format));
1830 err = AVERROR(EINVAL);
1834 if (!(f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ||
1835 !(f->tiling == VK_IMAGE_TILING_LINEAR)) {
1836 av_log(hwfc, AV_LOG_ERROR, "Unable to map frame, not host visible "
1838 err = AVERROR(EINVAL);
1842 dst->width = src->width;
1843 dst->height = src->height;
1845 for (int i = 0; i < planes; i++) {
1846 ret = vkMapMemory(hwctx->act_dev, f->mem[i], 0,
1847 VK_WHOLE_SIZE, 0, (void **)&dst->data[i]);
1848 if (ret != VK_SUCCESS) {
1849 av_log(hwfc, AV_LOG_ERROR, "Failed to map image memory: %s\n",
1851 err = AVERROR_EXTERNAL;
1857 /* Check if the memory contents matter */
1858 if (((flags & AV_HWFRAME_MAP_READ) || !(flags & AV_HWFRAME_MAP_OVERWRITE)) &&
1859 !(f->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1860 VkMappedMemoryRange map_mem_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1861 for (int i = 0; i < planes; i++) {
1862 map_mem_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1863 map_mem_ranges[i].size = VK_WHOLE_SIZE;
1864 map_mem_ranges[i].memory = f->mem[i];
1867 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, planes,
1869 if (ret != VK_SUCCESS) {
1870 av_log(hwfc, AV_LOG_ERROR, "Failed to invalidate memory: %s\n",
1872 err = AVERROR_EXTERNAL;
1877 for (int i = 0; i < planes; i++) {
1878 VkImageSubresource sub = {
1879 .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
1881 VkSubresourceLayout layout;
1882 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
1883 dst->linesize[i] = layout.rowPitch;
1889 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src,
1890 &vulkan_unmap_frame, map);
1897 for (int i = 0; i < mapped_mem_count; i++)
1898 vkUnmapMemory(hwctx->act_dev, f->mem[i]);
1905 static void vulkan_unmap_from(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1907 VulkanMapping *map = hwmap->priv;
1908 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1909 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1911 for (int i = 0; i < planes; i++) {
1912 vkDestroyImage(hwctx->act_dev, map->frame->img[i], hwctx->alloc);
1913 vkFreeMemory(hwctx->act_dev, map->frame->mem[i], hwctx->alloc);
1914 vkDestroySemaphore(hwctx->act_dev, map->frame->sem[i], hwctx->alloc);
1917 av_freep(&map->frame);
1920 static const struct {
1921 uint32_t drm_fourcc;
1923 } vulkan_drm_format_map[] = {
1924 { DRM_FORMAT_R8, VK_FORMAT_R8_UNORM },
1925 { DRM_FORMAT_R16, VK_FORMAT_R16_UNORM },
1926 { DRM_FORMAT_GR88, VK_FORMAT_R8G8_UNORM },
1927 { DRM_FORMAT_RG88, VK_FORMAT_R8G8_UNORM },
1928 { DRM_FORMAT_GR1616, VK_FORMAT_R16G16_UNORM },
1929 { DRM_FORMAT_RG1616, VK_FORMAT_R16G16_UNORM },
1930 { DRM_FORMAT_ARGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1931 { DRM_FORMAT_XRGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1932 { DRM_FORMAT_ABGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1933 { DRM_FORMAT_XBGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1936 static inline VkFormat drm_to_vulkan_fmt(uint32_t drm_fourcc)
1938 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
1939 if (vulkan_drm_format_map[i].drm_fourcc == drm_fourcc)
1940 return vulkan_drm_format_map[i].vk_format;
1941 return VK_FORMAT_UNDEFINED;
1944 static int vulkan_map_from_drm_frame_desc(AVHWFramesContext *hwfc, AVVkFrame **frame,
1945 AVDRMFrameDescriptor *desc)
1950 int bind_counts = 0;
1951 AVHWDeviceContext *ctx = hwfc->device_ctx;
1952 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1953 VulkanDevicePriv *p = ctx->internal->priv;
1954 VulkanFramesPriv *fp = hwfc->internal->priv;
1955 AVVulkanFramesContext *frames_hwctx = hwfc->hwctx;
1956 const AVPixFmtDescriptor *fmt_desc = av_pix_fmt_desc_get(hwfc->sw_format);
1957 const int has_modifiers = p->extensions & EXT_DRM_MODIFIER_FLAGS;
1958 VkSubresourceLayout plane_data[AV_NUM_DATA_POINTERS] = { 0 };
1959 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { 0 };
1960 VkBindImagePlaneMemoryInfo plane_info[AV_NUM_DATA_POINTERS] = { 0 };
1961 VkExternalMemoryHandleTypeFlagBits htype = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
1963 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdPropertiesKHR);
1965 for (int i = 0; i < desc->nb_layers; i++) {
1966 if (drm_to_vulkan_fmt(desc->layers[i].format) == VK_FORMAT_UNDEFINED) {
1967 av_log(ctx, AV_LOG_ERROR, "Unsupported DMABUF layer format %#08x!\n",
1968 desc->layers[i].format);
1969 return AVERROR(EINVAL);
1973 if (!(f = av_vk_frame_alloc())) {
1974 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1975 err = AVERROR(ENOMEM);
1979 for (int i = 0; i < desc->nb_objects; i++) {
1980 VkMemoryFdPropertiesKHR fdmp = {
1981 .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,
1983 VkMemoryRequirements req = {
1984 .size = desc->objects[i].size,
1986 VkImportMemoryFdInfoKHR idesc = {
1987 .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
1988 .handleType = htype,
1989 .fd = dup(desc->objects[i].fd),
1992 ret = pfn_vkGetMemoryFdPropertiesKHR(hwctx->act_dev, htype,
1994 if (ret != VK_SUCCESS) {
1995 av_log(hwfc, AV_LOG_ERROR, "Failed to get FD properties: %s\n",
1997 err = AVERROR_EXTERNAL;
2002 req.memoryTypeBits = fdmp.memoryTypeBits;
2004 err = alloc_mem(ctx, &req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
2005 &idesc, &f->flags, &f->mem[i]);
2011 f->size[i] = desc->objects[i].size;
2014 f->tiling = has_modifiers ? VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT :
2015 desc->objects[0].format_modifier == DRM_FORMAT_MOD_LINEAR ?
2016 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
2018 for (int i = 0; i < desc->nb_layers; i++) {
2019 const int planes = desc->layers[i].nb_planes;
2020 const int signal_p = has_modifiers && (planes > 1);
2022 VkImageDrmFormatModifierExplicitCreateInfoEXT drm_info = {
2023 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
2024 .drmFormatModifier = desc->objects[0].format_modifier,
2025 .drmFormatModifierPlaneCount = planes,
2026 .pPlaneLayouts = (const VkSubresourceLayout *)&plane_data,
2029 VkExternalMemoryImageCreateInfo einfo = {
2030 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
2031 .pNext = has_modifiers ? &drm_info : NULL,
2032 .handleTypes = htype,
2035 VkSemaphoreCreateInfo sem_spawn = {
2036 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
2039 const int p_w = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, fmt_desc->log2_chroma_w) : hwfc->width;
2040 const int p_h = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, fmt_desc->log2_chroma_h) : hwfc->height;
2042 VkImageCreateInfo image_create_info = {
2043 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
2045 .imageType = VK_IMAGE_TYPE_2D,
2046 .format = drm_to_vulkan_fmt(desc->layers[i].format),
2047 .extent.width = p_w,
2048 .extent.height = p_h,
2052 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
2053 .tiling = f->tiling,
2054 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, /* specs say so */
2055 .usage = frames_hwctx->usage,
2056 .samples = VK_SAMPLE_COUNT_1_BIT,
2057 .pQueueFamilyIndices = p->qfs,
2058 .queueFamilyIndexCount = p->num_qfs,
2059 .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
2060 VK_SHARING_MODE_EXCLUSIVE,
2063 for (int j = 0; j < planes; j++) {
2064 plane_data[j].offset = desc->layers[i].planes[j].offset;
2065 plane_data[j].rowPitch = desc->layers[i].planes[j].pitch;
2066 plane_data[j].size = 0; /* The specs say so for all 3 */
2067 plane_data[j].arrayPitch = 0;
2068 plane_data[j].depthPitch = 0;
2072 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
2073 hwctx->alloc, &f->img[i]);
2074 if (ret != VK_SUCCESS) {
2075 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
2077 err = AVERROR(EINVAL);
2081 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
2082 hwctx->alloc, &f->sem[i]);
2083 if (ret != VK_SUCCESS) {
2084 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
2086 return AVERROR_EXTERNAL;
2089 /* We'd import a semaphore onto the one we created using
2090 * vkImportSemaphoreFdKHR but unfortunately neither DRM nor VAAPI
2091 * offer us anything we could import and sync with, so instead
2092 * just signal the semaphore we created. */
2094 f->layout[i] = image_create_info.initialLayout;
2097 for (int j = 0; j < planes; j++) {
2098 VkImageAspectFlagBits aspect = j == 0 ? VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2099 j == 1 ? VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT :
2100 VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT;
2102 plane_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO;
2103 plane_info[bind_counts].planeAspect = aspect;
2105 bind_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
2106 bind_info[bind_counts].pNext = signal_p ? &plane_info[bind_counts] : NULL;
2107 bind_info[bind_counts].image = f->img[i];
2108 bind_info[bind_counts].memory = f->mem[desc->layers[i].planes[j].object_index];
2109 bind_info[bind_counts].memoryOffset = desc->layers[i].planes[j].offset;
2114 /* Bind the allocated memory to the images */
2115 ret = vkBindImageMemory2(hwctx->act_dev, bind_counts, bind_info);
2116 if (ret != VK_SUCCESS) {
2117 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
2119 return AVERROR_EXTERNAL;
2122 /* NOTE: This is completely uneccesary and unneeded once we can import
2123 * semaphores from DRM. Otherwise we have to activate the semaphores.
2124 * We're reusing the exec context that's also used for uploads/downloads. */
2125 err = prepare_frame(hwfc, &fp->conv_ctx, f, PREP_MODE_RO_SHADER);
2134 for (int i = 0; i < desc->nb_layers; i++) {
2135 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
2136 vkDestroySemaphore(hwctx->act_dev, f->sem[i], hwctx->alloc);
2138 for (int i = 0; i < desc->nb_objects; i++)
2139 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
2146 static int vulkan_map_from_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2147 const AVFrame *src, int flags)
2151 VulkanMapping *map = NULL;
2153 err = vulkan_map_from_drm_frame_desc(hwfc, &f,
2154 (AVDRMFrameDescriptor *)src->data[0]);
2158 /* The unmapping function will free this */
2159 dst->data[0] = (uint8_t *)f;
2160 dst->width = src->width;
2161 dst->height = src->height;
2163 map = av_mallocz(sizeof(VulkanMapping));
2170 err = ff_hwframe_map_create(dst->hw_frames_ctx, dst, src,
2171 &vulkan_unmap_from, map);
2175 av_log(hwfc, AV_LOG_DEBUG, "Mapped DRM object to Vulkan!\n");
2180 vulkan_frame_free(hwfc->device_ctx->hwctx, (uint8_t *)f);
2186 static int vulkan_map_from_vaapi(AVHWFramesContext *dst_fc,
2187 AVFrame *dst, const AVFrame *src,
2191 AVFrame *tmp = av_frame_alloc();
2192 AVHWFramesContext *vaapi_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2193 AVVAAPIDeviceContext *vaapi_ctx = vaapi_fc->device_ctx->hwctx;
2194 VASurfaceID surface_id = (VASurfaceID)(uintptr_t)src->data[3];
2197 return AVERROR(ENOMEM);
2199 /* We have to sync since like the previous comment said, no semaphores */
2200 vaSyncSurface(vaapi_ctx->display, surface_id);
2202 tmp->format = AV_PIX_FMT_DRM_PRIME;
2204 err = av_hwframe_map(tmp, src, flags);
2208 err = vulkan_map_from_drm(dst_fc, dst, tmp, flags);
2212 err = ff_hwframe_map_replace(dst, src);
2215 av_frame_free(&tmp);
2222 static int vulkan_export_to_cuda(AVHWFramesContext *hwfc,
2223 AVBufferRef *cuda_hwfc,
2224 const AVFrame *frame)
2229 AVVkFrameInternal *dst_int;
2230 AVHWDeviceContext *ctx = hwfc->device_ctx;
2231 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2232 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2233 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2234 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2235 VK_LOAD_PFN(hwctx->inst, vkGetSemaphoreFdKHR);
2237 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)cuda_hwfc->data;
2238 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2239 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2240 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2241 CudaFunctions *cu = cu_internal->cuda_dl;
2242 CUarray_format cufmt = desc->comp[0].depth > 8 ? CU_AD_FORMAT_UNSIGNED_INT16 :
2243 CU_AD_FORMAT_UNSIGNED_INT8;
2245 dst_f = (AVVkFrame *)frame->data[0];
2247 dst_int = dst_f->internal;
2248 if (!dst_int || !dst_int->cuda_fc_ref) {
2249 if (!dst_f->internal)
2250 dst_f->internal = dst_int = av_mallocz(sizeof(*dst_f->internal));
2253 err = AVERROR(ENOMEM);
2257 dst_int->cuda_fc_ref = av_buffer_ref(cuda_hwfc);
2258 if (!dst_int->cuda_fc_ref) {
2259 err = AVERROR(ENOMEM);
2263 for (int i = 0; i < planes; i++) {
2264 CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC tex_desc = {
2267 .Width = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2269 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2273 .NumChannels = 1 + ((planes == 2) && i),
2278 CUDA_EXTERNAL_MEMORY_HANDLE_DESC ext_desc = {
2279 .type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD,
2280 .size = dst_f->size[i],
2282 VkMemoryGetFdInfoKHR export_info = {
2283 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2284 .memory = dst_f->mem[i],
2285 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR,
2287 VkSemaphoreGetFdInfoKHR sem_export = {
2288 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR,
2289 .semaphore = dst_f->sem[i],
2290 .handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
2292 CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC ext_sem_desc = {
2293 .type = CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD,
2296 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2297 &ext_desc.handle.fd);
2298 if (ret != VK_SUCCESS) {
2299 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2300 err = AVERROR_EXTERNAL;
2304 ret = CHECK_CU(cu->cuImportExternalMemory(&dst_int->ext_mem[i], &ext_desc));
2306 err = AVERROR_EXTERNAL;
2310 ret = CHECK_CU(cu->cuExternalMemoryGetMappedMipmappedArray(&dst_int->cu_mma[i],
2311 dst_int->ext_mem[i],
2314 err = AVERROR_EXTERNAL;
2318 ret = CHECK_CU(cu->cuMipmappedArrayGetLevel(&dst_int->cu_array[i],
2319 dst_int->cu_mma[i], 0));
2321 err = AVERROR_EXTERNAL;
2325 ret = pfn_vkGetSemaphoreFdKHR(hwctx->act_dev, &sem_export,
2326 &ext_sem_desc.handle.fd);
2327 if (ret != VK_SUCCESS) {
2328 av_log(ctx, AV_LOG_ERROR, "Failed to export semaphore: %s\n",
2330 err = AVERROR_EXTERNAL;
2334 ret = CHECK_CU(cu->cuImportExternalSemaphore(&dst_int->cu_sem[i],
2337 err = AVERROR_EXTERNAL;
2349 static int vulkan_transfer_data_from_cuda(AVHWFramesContext *hwfc,
2350 AVFrame *dst, const AVFrame *src)
2356 AVVkFrameInternal *dst_int;
2357 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2358 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2360 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2361 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2362 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2363 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2364 CudaFunctions *cu = cu_internal->cuda_dl;
2365 CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS s_w_par[AV_NUM_DATA_POINTERS] = { 0 };
2366 CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS s_s_par[AV_NUM_DATA_POINTERS] = { 0 };
2368 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2370 err = AVERROR_EXTERNAL;
2374 dst_f = (AVVkFrame *)dst->data[0];
2376 ret = vulkan_export_to_cuda(hwfc, src->hw_frames_ctx, dst);
2380 dst_int = dst_f->internal;
2382 ret = CHECK_CU(cu->cuWaitExternalSemaphoresAsync(dst_int->cu_sem, s_w_par,
2383 planes, cuda_dev->stream));
2385 err = AVERROR_EXTERNAL;
2389 for (int i = 0; i < planes; i++) {
2390 CUDA_MEMCPY2D cpy = {
2391 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
2392 .srcDevice = (CUdeviceptr)src->data[i],
2393 .srcPitch = src->linesize[i],
2396 .dstMemoryType = CU_MEMORYTYPE_ARRAY,
2397 .dstArray = dst_int->cu_array[i],
2398 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2399 : hwfc->width) * desc->comp[i].step,
2400 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2404 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2406 err = AVERROR_EXTERNAL;
2411 ret = CHECK_CU(cu->cuSignalExternalSemaphoresAsync(dst_int->cu_sem, s_s_par,
2412 planes, cuda_dev->stream));
2414 err = AVERROR_EXTERNAL;
2418 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2420 av_log(hwfc, AV_LOG_VERBOSE, "Transfered CUDA image to Vulkan!\n");
2425 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2426 vulkan_free_internal(dst_int);
2427 dst_f->internal = NULL;
2428 av_buffer_unref(&dst->buf[0]);
2433 static int vulkan_map_to(AVHWFramesContext *hwfc, AVFrame *dst,
2434 const AVFrame *src, int flags)
2436 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2438 switch (src->format) {
2441 case AV_PIX_FMT_VAAPI:
2442 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2443 return vulkan_map_from_vaapi(hwfc, dst, src, flags);
2445 case AV_PIX_FMT_DRM_PRIME:
2446 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2447 return vulkan_map_from_drm(hwfc, dst, src, flags);
2450 return AVERROR(ENOSYS);
2455 typedef struct VulkanDRMMapping {
2456 AVDRMFrameDescriptor drm_desc;
2460 static void vulkan_unmap_to_drm(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
2462 AVDRMFrameDescriptor *drm_desc = hwmap->priv;
2464 for (int i = 0; i < drm_desc->nb_objects; i++)
2465 close(drm_desc->objects[i].fd);
2470 static inline uint32_t vulkan_fmt_to_drm(VkFormat vkfmt)
2472 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
2473 if (vulkan_drm_format_map[i].vk_format == vkfmt)
2474 return vulkan_drm_format_map[i].drm_fourcc;
2475 return DRM_FORMAT_INVALID;
2478 static int vulkan_map_to_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2479 const AVFrame *src, int flags)
2483 AVVkFrame *f = (AVVkFrame *)src->data[0];
2484 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2485 VulkanFramesPriv *fp = hwfc->internal->priv;
2486 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
2487 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2488 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2489 VkImageDrmFormatModifierPropertiesEXT drm_mod = {
2490 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT,
2493 AVDRMFrameDescriptor *drm_desc = av_mallocz(sizeof(*drm_desc));
2495 return AVERROR(ENOMEM);
2497 err = prepare_frame(hwfc, &fp->conv_ctx, f, PREP_MODE_EXTERNAL_EXPORT);
2501 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src, &vulkan_unmap_to_drm, drm_desc);
2505 if (p->extensions & EXT_DRM_MODIFIER_FLAGS) {
2506 VK_LOAD_PFN(hwctx->inst, vkGetImageDrmFormatModifierPropertiesEXT);
2507 ret = pfn_vkGetImageDrmFormatModifierPropertiesEXT(hwctx->act_dev, f->img[0],
2509 if (ret != VK_SUCCESS) {
2510 av_log(hwfc, AV_LOG_ERROR, "Failed to retrieve DRM format modifier!\n");
2511 err = AVERROR_EXTERNAL;
2516 for (int i = 0; (i < planes) && (f->mem[i]); i++) {
2517 VkMemoryGetFdInfoKHR export_info = {
2518 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2519 .memory = f->mem[i],
2520 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,
2523 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2524 &drm_desc->objects[i].fd);
2525 if (ret != VK_SUCCESS) {
2526 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2527 err = AVERROR_EXTERNAL;
2531 drm_desc->nb_objects++;
2532 drm_desc->objects[i].size = f->size[i];
2533 drm_desc->objects[i].format_modifier = drm_mod.drmFormatModifier;
2536 drm_desc->nb_layers = planes;
2537 for (int i = 0; i < drm_desc->nb_layers; i++) {
2538 VkSubresourceLayout layout;
2539 VkImageSubresource sub = {
2540 .aspectMask = p->extensions & EXT_DRM_MODIFIER_FLAGS ?
2541 VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2542 VK_IMAGE_ASPECT_COLOR_BIT,
2544 VkFormat plane_vkfmt = av_vkfmt_from_pixfmt(hwfc->sw_format)[i];
2546 drm_desc->layers[i].format = vulkan_fmt_to_drm(plane_vkfmt);
2547 drm_desc->layers[i].nb_planes = 1;
2549 if (drm_desc->layers[i].format == DRM_FORMAT_INVALID) {
2550 av_log(hwfc, AV_LOG_ERROR, "Cannot map to DRM layer, unsupported!\n");
2551 err = AVERROR_PATCHWELCOME;
2555 drm_desc->layers[i].planes[0].object_index = FFMIN(i, drm_desc->nb_objects - 1);
2557 if (f->tiling == VK_IMAGE_TILING_OPTIMAL)
2560 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
2561 drm_desc->layers[i].planes[0].offset = layout.offset;
2562 drm_desc->layers[i].planes[0].pitch = layout.rowPitch;
2565 dst->width = src->width;
2566 dst->height = src->height;
2567 dst->data[0] = (uint8_t *)drm_desc;
2569 av_log(hwfc, AV_LOG_VERBOSE, "Mapped AVVkFrame to a DRM object!\n");
2579 static int vulkan_map_to_vaapi(AVHWFramesContext *hwfc, AVFrame *dst,
2580 const AVFrame *src, int flags)
2583 AVFrame *tmp = av_frame_alloc();
2585 return AVERROR(ENOMEM);
2587 tmp->format = AV_PIX_FMT_DRM_PRIME;
2589 err = vulkan_map_to_drm(hwfc, tmp, src, flags);
2593 err = av_hwframe_map(dst, tmp, flags);
2597 err = ff_hwframe_map_replace(dst, src);
2600 av_frame_free(&tmp);
2606 static int vulkan_map_from(AVHWFramesContext *hwfc, AVFrame *dst,
2607 const AVFrame *src, int flags)
2609 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2611 switch (dst->format) {
2613 case AV_PIX_FMT_DRM_PRIME:
2614 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2615 return vulkan_map_to_drm(hwfc, dst, src, flags);
2617 case AV_PIX_FMT_VAAPI:
2618 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2619 return vulkan_map_to_vaapi(hwfc, dst, src, flags);
2623 return vulkan_map_frame_to_mem(hwfc, dst, src, flags);
2627 typedef struct ImageBuffer {
2630 VkMemoryPropertyFlagBits flags;
2633 static void free_buf(void *opaque, uint8_t *data)
2635 AVHWDeviceContext *ctx = opaque;
2636 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2637 ImageBuffer *vkbuf = (ImageBuffer *)data;
2640 vkDestroyBuffer(hwctx->act_dev, vkbuf->buf, hwctx->alloc);
2642 vkFreeMemory(hwctx->act_dev, vkbuf->mem, hwctx->alloc);
2647 static int create_buf(AVHWDeviceContext *ctx, AVBufferRef **buf,
2648 int height, int *stride, VkBufferUsageFlags usage,
2649 VkMemoryPropertyFlagBits flags, void *create_pnext,
2654 VkMemoryRequirements req;
2655 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2656 VulkanDevicePriv *p = ctx->internal->priv;
2658 VkBufferCreateInfo buf_spawn = {
2659 .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
2660 .pNext = create_pnext,
2662 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
2665 ImageBuffer *vkbuf = av_mallocz(sizeof(*vkbuf));
2667 return AVERROR(ENOMEM);
2669 *stride = FFALIGN(*stride, p->props.limits.optimalBufferCopyRowPitchAlignment);
2670 buf_spawn.size = height*(*stride);
2672 ret = vkCreateBuffer(hwctx->act_dev, &buf_spawn, NULL, &vkbuf->buf);
2673 if (ret != VK_SUCCESS) {
2674 av_log(ctx, AV_LOG_ERROR, "Failed to create buffer: %s\n",
2676 return AVERROR_EXTERNAL;
2679 vkGetBufferMemoryRequirements(hwctx->act_dev, vkbuf->buf, &req);
2681 err = alloc_mem(ctx, &req, flags, alloc_pnext, &vkbuf->flags, &vkbuf->mem);
2685 ret = vkBindBufferMemory(hwctx->act_dev, vkbuf->buf, vkbuf->mem, 0);
2686 if (ret != VK_SUCCESS) {
2687 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory to buffer: %s\n",
2689 free_buf(ctx, (uint8_t *)vkbuf);
2690 return AVERROR_EXTERNAL;
2693 *buf = av_buffer_create((uint8_t *)vkbuf, sizeof(*vkbuf), free_buf, ctx, 0);
2695 free_buf(ctx, (uint8_t *)vkbuf);
2696 return AVERROR(ENOMEM);
2702 static int map_buffers(AVHWDeviceContext *ctx, AVBufferRef **bufs, uint8_t *mem[],
2703 int nb_buffers, int invalidate)
2706 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2707 VkMappedMemoryRange invalidate_ctx[AV_NUM_DATA_POINTERS];
2708 int invalidate_count = 0;
2710 for (int i = 0; i < nb_buffers; i++) {
2711 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2712 ret = vkMapMemory(hwctx->act_dev, vkbuf->mem, 0,
2713 VK_WHOLE_SIZE, 0, (void **)&mem[i]);
2714 if (ret != VK_SUCCESS) {
2715 av_log(ctx, AV_LOG_ERROR, "Failed to map buffer memory: %s\n",
2717 return AVERROR_EXTERNAL;
2724 for (int i = 0; i < nb_buffers; i++) {
2725 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2726 const VkMappedMemoryRange ival_buf = {
2727 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2728 .memory = vkbuf->mem,
2729 .size = VK_WHOLE_SIZE,
2731 if (vkbuf->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2733 invalidate_ctx[invalidate_count++] = ival_buf;
2736 if (invalidate_count) {
2737 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, invalidate_count,
2739 if (ret != VK_SUCCESS)
2740 av_log(ctx, AV_LOG_WARNING, "Failed to invalidate memory: %s\n",
2747 static int unmap_buffers(AVHWDeviceContext *ctx, AVBufferRef **bufs,
2748 int nb_buffers, int flush)
2752 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2753 VkMappedMemoryRange flush_ctx[AV_NUM_DATA_POINTERS];
2754 int flush_count = 0;
2757 for (int i = 0; i < nb_buffers; i++) {
2758 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2759 const VkMappedMemoryRange flush_buf = {
2760 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2761 .memory = vkbuf->mem,
2762 .size = VK_WHOLE_SIZE,
2764 if (vkbuf->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2766 flush_ctx[flush_count++] = flush_buf;
2771 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, flush_count, flush_ctx);
2772 if (ret != VK_SUCCESS) {
2773 av_log(ctx, AV_LOG_ERROR, "Failed to flush memory: %s\n",
2775 err = AVERROR_EXTERNAL; /* We still want to try to unmap them */
2779 for (int i = 0; i < nb_buffers; i++) {
2780 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2781 vkUnmapMemory(hwctx->act_dev, vkbuf->mem);
2787 static int transfer_image_buf(AVHWFramesContext *hwfc, const AVFrame *f,
2788 AVBufferRef **bufs, const int *buf_stride, int w,
2789 int h, enum AVPixelFormat pix_fmt, int to_buf)
2792 AVVkFrame *frame = (AVVkFrame *)f->data[0];
2793 VulkanFramesPriv *fp = hwfc->internal->priv;
2796 VkPipelineStageFlagBits sem_wait_dst[AV_NUM_DATA_POINTERS];
2798 const int planes = av_pix_fmt_count_planes(pix_fmt);
2799 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2801 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
2802 VulkanExecCtx *ectx = to_buf ? &fp->download_ctx : &fp->upload_ctx;
2803 VkCommandBuffer cmd_buf = get_buf_exec_ctx(hwfc, ectx);
2805 VkSubmitInfo s_info = {
2806 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
2807 .pSignalSemaphores = frame->sem,
2808 .pWaitSemaphores = frame->sem,
2809 .pWaitDstStageMask = sem_wait_dst,
2810 .signalSemaphoreCount = planes,
2811 .waitSemaphoreCount = planes,
2814 if ((err = wait_start_exec_ctx(hwfc, ectx)))
2817 /* Change the image layout to something more optimal for transfers */
2818 for (int i = 0; i < planes; i++) {
2819 VkImageLayout new_layout = to_buf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL :
2820 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
2821 VkAccessFlags new_access = to_buf ? VK_ACCESS_TRANSFER_READ_BIT :
2822 VK_ACCESS_TRANSFER_WRITE_BIT;
2824 sem_wait_dst[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
2826 /* If the layout matches and we have read access skip the barrier */
2827 if ((frame->layout[i] == new_layout) && (frame->access[i] & new_access))
2830 img_bar[bar_num].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
2831 img_bar[bar_num].srcAccessMask = 0x0;
2832 img_bar[bar_num].dstAccessMask = new_access;
2833 img_bar[bar_num].oldLayout = frame->layout[i];
2834 img_bar[bar_num].newLayout = new_layout;
2835 img_bar[bar_num].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2836 img_bar[bar_num].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2837 img_bar[bar_num].image = frame->img[i];
2838 img_bar[bar_num].subresourceRange.levelCount = 1;
2839 img_bar[bar_num].subresourceRange.layerCount = 1;
2840 img_bar[bar_num].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2842 frame->layout[i] = img_bar[bar_num].newLayout;
2843 frame->access[i] = img_bar[bar_num].dstAccessMask;
2849 vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
2850 VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
2851 0, NULL, 0, NULL, bar_num, img_bar);
2853 /* Schedule a copy for each plane */
2854 for (int i = 0; i < planes; i++) {
2855 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2856 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
2857 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
2858 VkBufferImageCopy buf_reg = {
2860 /* Buffer stride isn't in bytes, it's in samples, the implementation
2861 * uses the image's VkFormat to know how many bytes per sample
2862 * the buffer has. So we have to convert by dividing. Stupid.
2863 * Won't work with YUVA or other planar formats with alpha. */
2864 .bufferRowLength = buf_stride[i] / desc->comp[i].step,
2865 .bufferImageHeight = p_h,
2866 .imageSubresource.layerCount = 1,
2867 .imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
2868 .imageOffset = { 0, 0, 0, },
2869 .imageExtent = { p_w, p_h, 1, },
2873 vkCmdCopyImageToBuffer(cmd_buf, frame->img[i], frame->layout[i],
2874 vkbuf->buf, 1, &buf_reg);
2876 vkCmdCopyBufferToImage(cmd_buf, vkbuf->buf, frame->img[i],
2877 frame->layout[i], 1, &buf_reg);
2880 /* When uploading, do this asynchronously if the source is refcounted by
2881 * keeping the buffers as a submission dependency.
2882 * The hwcontext is guaranteed to not be freed until all frames are freed
2883 * in the frames_unint function.
2884 * When downloading to buffer, do this synchronously and wait for the
2885 * queue submission to finish executing */
2888 for (ref = 0; ref < AV_NUM_DATA_POINTERS; ref++) {
2891 if ((err = add_buf_dep_exec_ctx(hwfc, ectx, &f->buf[ref], 1)))
2894 if (ref && (err = add_buf_dep_exec_ctx(hwfc, ectx, bufs, planes)))
2896 return submit_exec_ctx(hwfc, ectx, &s_info, !ref);
2898 return submit_exec_ctx(hwfc, ectx, &s_info, 1);
2902 /* Technically we can use VK_EXT_external_memory_host to upload and download,
2903 * however the alignment requirements make this unfeasible as both the pointer
2904 * and the size of each plane need to be aligned to the minimum alignment
2905 * requirement, which on all current implementations (anv, radv) is 4096.
2906 * If the requirement gets relaxed (unlikely) this can easily be implemented. */
2907 static int vulkan_transfer_data_from_mem(AVHWFramesContext *hwfc, AVFrame *dst,
2912 AVVkFrame *f = (AVVkFrame *)dst->data[0];
2913 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
2914 AVBufferRef *bufs[AV_NUM_DATA_POINTERS] = { 0 };
2915 const int planes = av_pix_fmt_count_planes(src->format);
2916 int log2_chroma = av_pix_fmt_desc_get(src->format)->log2_chroma_h;
2918 if ((src->format != AV_PIX_FMT_NONE && !av_vkfmt_from_pixfmt(src->format))) {
2919 av_log(hwfc, AV_LOG_ERROR, "Unsupported source pixel format!\n");
2920 return AVERROR(EINVAL);
2923 if (src->width > hwfc->width || src->height > hwfc->height)
2924 return AVERROR(EINVAL);
2926 /* For linear, host visiable images */
2927 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
2928 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
2929 AVFrame *map = av_frame_alloc();
2931 return AVERROR(ENOMEM);
2932 map->format = src->format;
2934 err = vulkan_map_frame_to_mem(hwfc, map, dst, AV_HWFRAME_MAP_WRITE);
2938 err = av_frame_copy(map, src);
2939 av_frame_free(&map);
2943 /* Create buffers */
2944 for (int i = 0; i < planes; i++) {
2945 int h = src->height;
2946 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
2948 tmp.linesize[i] = FFABS(src->linesize[i]);
2949 err = create_buf(dev_ctx, &bufs[i], p_height,
2950 &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
2951 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
2956 /* Map, copy image to buffer, unmap */
2957 if ((err = map_buffers(dev_ctx, bufs, tmp.data, planes, 0)))
2960 av_image_copy(tmp.data, tmp.linesize, (const uint8_t **)src->data,
2961 src->linesize, src->format, src->width, src->height);
2963 if ((err = unmap_buffers(dev_ctx, bufs, planes, 1)))
2966 /* Copy buffers to image */
2967 err = transfer_image_buf(hwfc, dst, bufs, tmp.linesize,
2968 src->width, src->height, src->format, 0);
2971 for (int i = 0; i < planes; i++)
2972 av_buffer_unref(&bufs[i]);
2977 static int vulkan_transfer_data_to(AVHWFramesContext *hwfc, AVFrame *dst,
2980 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2982 switch (src->format) {
2984 case AV_PIX_FMT_CUDA:
2985 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
2986 (p->extensions & EXT_EXTERNAL_FD_SEM))
2987 return vulkan_transfer_data_from_cuda(hwfc, dst, src);
2990 if (src->hw_frames_ctx)
2991 return AVERROR(ENOSYS);
2993 return vulkan_transfer_data_from_mem(hwfc, dst, src);
2998 static int vulkan_transfer_data_to_cuda(AVHWFramesContext *hwfc, AVFrame *dst,
3005 AVVkFrameInternal *dst_int;
3006 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
3007 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
3009 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)dst->hw_frames_ctx->data;
3010 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
3011 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
3012 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
3013 CudaFunctions *cu = cu_internal->cuda_dl;
3015 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
3017 err = AVERROR_EXTERNAL;
3021 dst_f = (AVVkFrame *)src->data[0];
3023 err = vulkan_export_to_cuda(hwfc, dst->hw_frames_ctx, src);
3028 dst_int = dst_f->internal;
3030 for (int i = 0; i < planes; i++) {
3031 CUDA_MEMCPY2D cpy = {
3032 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
3033 .dstDevice = (CUdeviceptr)dst->data[i],
3034 .dstPitch = dst->linesize[i],
3037 .srcMemoryType = CU_MEMORYTYPE_ARRAY,
3038 .srcArray = dst_int->cu_array[i],
3039 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
3040 : hwfc->width) * desc->comp[i].step,
3041 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
3045 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
3047 err = AVERROR_EXTERNAL;
3052 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
3054 av_log(hwfc, AV_LOG_VERBOSE, "Transfered Vulkan image to CUDA!\n");
3059 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
3060 vulkan_free_internal(dst_int);
3061 dst_f->internal = NULL;
3062 av_buffer_unref(&dst->buf[0]);
3067 static int vulkan_transfer_data_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
3072 AVVkFrame *f = (AVVkFrame *)src->data[0];
3073 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
3074 AVBufferRef *bufs[AV_NUM_DATA_POINTERS] = { 0 };
3075 const int planes = av_pix_fmt_count_planes(dst->format);
3076 int log2_chroma = av_pix_fmt_desc_get(dst->format)->log2_chroma_h;
3078 if (dst->width > hwfc->width || dst->height > hwfc->height)
3079 return AVERROR(EINVAL);
3081 /* For linear, host visiable images */
3082 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
3083 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
3084 AVFrame *map = av_frame_alloc();
3086 return AVERROR(ENOMEM);
3087 map->format = dst->format;
3089 err = vulkan_map_frame_to_mem(hwfc, map, src, AV_HWFRAME_MAP_READ);
3093 err = av_frame_copy(dst, map);
3094 av_frame_free(&map);
3098 /* Create buffers */
3099 for (int i = 0; i < planes; i++) {
3100 int h = dst->height;
3101 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
3103 tmp.linesize[i] = FFABS(dst->linesize[i]);
3104 err = create_buf(dev_ctx, &bufs[i], p_height,
3105 &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_DST_BIT,
3106 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
3111 /* Copy image to buffer */
3112 if ((err = transfer_image_buf(hwfc, src, bufs, tmp.linesize,
3113 dst->width, dst->height, dst->format, 1)))
3116 /* Map, copy buffer to frame, unmap */
3117 if ((err = map_buffers(dev_ctx, bufs, tmp.data, planes, 1)))
3120 av_image_copy(dst->data, dst->linesize, (const uint8_t **)tmp.data,
3121 tmp.linesize, dst->format, dst->width, dst->height);
3123 err = unmap_buffers(dev_ctx, bufs, planes, 0);
3126 for (int i = 0; i < planes; i++)
3127 av_buffer_unref(&bufs[i]);
3132 static int vulkan_transfer_data_from(AVHWFramesContext *hwfc, AVFrame *dst,
3135 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
3137 switch (dst->format) {
3139 case AV_PIX_FMT_CUDA:
3140 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
3141 (p->extensions & EXT_EXTERNAL_FD_SEM))
3142 return vulkan_transfer_data_to_cuda(hwfc, dst, src);
3145 if (dst->hw_frames_ctx)
3146 return AVERROR(ENOSYS);
3148 return vulkan_transfer_data_to_mem(hwfc, dst, src);
3152 AVVkFrame *av_vk_frame_alloc(void)
3154 return av_mallocz(sizeof(AVVkFrame));
3157 const HWContextType ff_hwcontext_type_vulkan = {
3158 .type = AV_HWDEVICE_TYPE_VULKAN,
3161 .device_hwctx_size = sizeof(AVVulkanDeviceContext),
3162 .device_priv_size = sizeof(VulkanDevicePriv),
3163 .frames_hwctx_size = sizeof(AVVulkanFramesContext),
3164 .frames_priv_size = sizeof(VulkanFramesPriv),
3166 .device_init = &vulkan_device_init,
3167 .device_create = &vulkan_device_create,
3168 .device_derive = &vulkan_device_derive,
3170 .frames_get_constraints = &vulkan_frames_get_constraints,
3171 .frames_init = vulkan_frames_init,
3172 .frames_get_buffer = vulkan_get_buffer,
3173 .frames_uninit = vulkan_frames_uninit,
3175 .transfer_get_formats = vulkan_transfer_get_formats,
3176 .transfer_data_to = vulkan_transfer_data_to,
3177 .transfer_data_from = vulkan_transfer_data_from,
3179 .map_to = vulkan_map_to,
3180 .map_from = vulkan_map_from,
3182 .pix_fmts = (const enum AVPixelFormat []) {