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;
76 VulkanExecCtx upload_ctx;
77 VulkanExecCtx download_ctx;
83 int use_linear_images;
89 typedef struct VulkanFramesPriv {
93 typedef struct AVVkFrameInternal {
95 /* Importing external memory into cuda is really expensive so we keep the
96 * memory imported all the time */
97 AVBufferRef *cuda_fc_ref; /* Need to keep it around for uninit */
98 CUexternalMemory ext_mem[AV_NUM_DATA_POINTERS];
99 CUmipmappedArray cu_mma[AV_NUM_DATA_POINTERS];
100 CUarray cu_array[AV_NUM_DATA_POINTERS];
101 CUexternalSemaphore cu_sem[AV_NUM_DATA_POINTERS];
105 #define GET_QUEUE_COUNT(hwctx, graph, comp, tx) ( \
106 graph ? hwctx->nb_graphics_queues : \
107 comp ? (hwctx->nb_comp_queues ? \
108 hwctx->nb_comp_queues : hwctx->nb_graphics_queues) : \
109 tx ? (hwctx->nb_tx_queues ? hwctx->nb_tx_queues : \
110 (hwctx->nb_comp_queues ? \
111 hwctx->nb_comp_queues : hwctx->nb_graphics_queues)) : \
115 #define VK_LOAD_PFN(inst, name) PFN_##name pfn_##name = (PFN_##name) \
116 vkGetInstanceProcAddr(inst, #name)
118 #define DEFAULT_USAGE_FLAGS (VK_IMAGE_USAGE_SAMPLED_BIT | \
119 VK_IMAGE_USAGE_STORAGE_BIT | \
120 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | \
121 VK_IMAGE_USAGE_TRANSFER_DST_BIT)
123 #define ADD_VAL_TO_LIST(list, count, val) \
125 list = av_realloc_array(list, sizeof(*list), ++count); \
127 err = AVERROR(ENOMEM); \
130 list[count - 1] = av_strdup(val); \
131 if (!list[count - 1]) { \
132 err = AVERROR(ENOMEM); \
137 static const struct {
138 enum AVPixelFormat pixfmt;
139 const VkFormat vkfmts[3];
140 } vk_pixfmt_map[] = {
141 { AV_PIX_FMT_GRAY8, { VK_FORMAT_R8_UNORM } },
142 { AV_PIX_FMT_GRAY16, { VK_FORMAT_R16_UNORM } },
143 { AV_PIX_FMT_GRAYF32, { VK_FORMAT_R32_SFLOAT } },
145 { AV_PIX_FMT_NV12, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8G8_UNORM } },
146 { AV_PIX_FMT_P010, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16G16_UNORM } },
147 { AV_PIX_FMT_P016, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16G16_UNORM } },
149 { AV_PIX_FMT_YUV420P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
150 { AV_PIX_FMT_YUV422P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
151 { AV_PIX_FMT_YUV444P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
153 { AV_PIX_FMT_YUV420P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
154 { AV_PIX_FMT_YUV422P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
155 { AV_PIX_FMT_YUV444P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
157 { AV_PIX_FMT_ABGR, { VK_FORMAT_A8B8G8R8_UNORM_PACK32 } },
158 { AV_PIX_FMT_BGRA, { VK_FORMAT_B8G8R8A8_UNORM } },
159 { AV_PIX_FMT_RGBA, { VK_FORMAT_R8G8B8A8_UNORM } },
160 { AV_PIX_FMT_RGB24, { VK_FORMAT_R8G8B8_UNORM } },
161 { AV_PIX_FMT_BGR24, { VK_FORMAT_B8G8R8_UNORM } },
162 { AV_PIX_FMT_RGB48, { VK_FORMAT_R16G16B16_UNORM } },
163 { AV_PIX_FMT_RGBA64, { VK_FORMAT_R16G16B16A16_UNORM } },
164 { AV_PIX_FMT_RGB565, { VK_FORMAT_R5G6B5_UNORM_PACK16 } },
165 { AV_PIX_FMT_BGR565, { VK_FORMAT_B5G6R5_UNORM_PACK16 } },
166 { AV_PIX_FMT_BGR0, { VK_FORMAT_B8G8R8A8_UNORM } },
167 { AV_PIX_FMT_0BGR, { VK_FORMAT_A8B8G8R8_UNORM_PACK32 } },
168 { AV_PIX_FMT_RGB0, { VK_FORMAT_R8G8B8A8_UNORM } },
170 { AV_PIX_FMT_GBRPF32, { VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32_SFLOAT } },
173 const VkFormat *av_vkfmt_from_pixfmt(enum AVPixelFormat p)
175 for (enum AVPixelFormat i = 0; i < FF_ARRAY_ELEMS(vk_pixfmt_map); i++)
176 if (vk_pixfmt_map[i].pixfmt == p)
177 return vk_pixfmt_map[i].vkfmts;
181 static int pixfmt_is_supported(AVVulkanDeviceContext *hwctx, enum AVPixelFormat p,
184 const VkFormat *fmt = av_vkfmt_from_pixfmt(p);
185 int planes = av_pix_fmt_count_planes(p);
190 for (int i = 0; i < planes; i++) {
191 VkFormatFeatureFlags flags;
192 VkFormatProperties2 prop = {
193 .sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2,
195 vkGetPhysicalDeviceFormatProperties2(hwctx->phys_dev, fmt[i], &prop);
196 flags = linear ? prop.formatProperties.linearTilingFeatures :
197 prop.formatProperties.optimalTilingFeatures;
198 if (!(flags & DEFAULT_USAGE_FLAGS))
205 enum VulkanExtensions {
206 EXT_EXTERNAL_DMABUF_MEMORY = 1ULL << 0, /* VK_EXT_external_memory_dma_buf */
207 EXT_DRM_MODIFIER_FLAGS = 1ULL << 1, /* VK_EXT_image_drm_format_modifier */
208 EXT_EXTERNAL_FD_MEMORY = 1ULL << 2, /* VK_KHR_external_memory_fd */
209 EXT_EXTERNAL_FD_SEM = 1ULL << 3, /* VK_KHR_external_semaphore_fd */
211 EXT_NO_FLAG = 1ULL << 63,
214 typedef struct VulkanOptExtension {
217 } VulkanOptExtension;
219 static const VulkanOptExtension optional_instance_exts[] = {
223 static const VulkanOptExtension optional_device_exts[] = {
224 { VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME, EXT_EXTERNAL_FD_MEMORY, },
225 { VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME, EXT_EXTERNAL_DMABUF_MEMORY, },
226 { VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME, EXT_DRM_MODIFIER_FLAGS, },
227 { VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME, EXT_EXTERNAL_FD_SEM, },
230 /* Converts return values to strings */
231 static const char *vk_ret2str(VkResult res)
233 #define CASE(VAL) case VAL: return #VAL
239 CASE(VK_EVENT_RESET);
241 CASE(VK_ERROR_OUT_OF_HOST_MEMORY);
242 CASE(VK_ERROR_OUT_OF_DEVICE_MEMORY);
243 CASE(VK_ERROR_INITIALIZATION_FAILED);
244 CASE(VK_ERROR_DEVICE_LOST);
245 CASE(VK_ERROR_MEMORY_MAP_FAILED);
246 CASE(VK_ERROR_LAYER_NOT_PRESENT);
247 CASE(VK_ERROR_EXTENSION_NOT_PRESENT);
248 CASE(VK_ERROR_FEATURE_NOT_PRESENT);
249 CASE(VK_ERROR_INCOMPATIBLE_DRIVER);
250 CASE(VK_ERROR_TOO_MANY_OBJECTS);
251 CASE(VK_ERROR_FORMAT_NOT_SUPPORTED);
252 CASE(VK_ERROR_FRAGMENTED_POOL);
253 CASE(VK_ERROR_SURFACE_LOST_KHR);
254 CASE(VK_ERROR_NATIVE_WINDOW_IN_USE_KHR);
255 CASE(VK_SUBOPTIMAL_KHR);
256 CASE(VK_ERROR_OUT_OF_DATE_KHR);
257 CASE(VK_ERROR_INCOMPATIBLE_DISPLAY_KHR);
258 CASE(VK_ERROR_VALIDATION_FAILED_EXT);
259 CASE(VK_ERROR_INVALID_SHADER_NV);
260 CASE(VK_ERROR_OUT_OF_POOL_MEMORY);
261 CASE(VK_ERROR_INVALID_EXTERNAL_HANDLE);
262 CASE(VK_ERROR_NOT_PERMITTED_EXT);
263 CASE(VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT);
264 CASE(VK_ERROR_INVALID_DEVICE_ADDRESS_EXT);
265 CASE(VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT);
266 default: return "Unknown error";
271 static VkBool32 vk_dbg_callback(VkDebugUtilsMessageSeverityFlagBitsEXT severity,
272 VkDebugUtilsMessageTypeFlagsEXT messageType,
273 const VkDebugUtilsMessengerCallbackDataEXT *data,
277 AVHWDeviceContext *ctx = priv;
280 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT: l = AV_LOG_VERBOSE; break;
281 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT: l = AV_LOG_INFO; break;
282 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT: l = AV_LOG_WARNING; break;
283 case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT: l = AV_LOG_ERROR; break;
284 default: l = AV_LOG_DEBUG; break;
287 av_log(ctx, l, "%s\n", data->pMessage);
288 for (int i = 0; i < data->cmdBufLabelCount; i++)
289 av_log(ctx, l, "\t%i: %s\n", i, data->pCmdBufLabels[i].pLabelName);
294 static int check_extensions(AVHWDeviceContext *ctx, int dev, AVDictionary *opts,
295 const char * const **dst, uint32_t *num, int debug)
298 const char **extension_names = NULL;
299 VulkanDevicePriv *p = ctx->internal->priv;
300 AVVulkanDeviceContext *hwctx = ctx->hwctx;
301 int err = 0, found, extensions_found = 0;
304 int optional_exts_num;
305 uint32_t sup_ext_count;
306 char *user_exts_str = NULL;
307 AVDictionaryEntry *user_exts;
308 VkExtensionProperties *sup_ext;
309 const VulkanOptExtension *optional_exts;
313 optional_exts = optional_instance_exts;
314 optional_exts_num = FF_ARRAY_ELEMS(optional_instance_exts);
315 user_exts = av_dict_get(opts, "instance_extensions", NULL, 0);
317 user_exts_str = av_strdup(user_exts->value);
318 if (!user_exts_str) {
319 err = AVERROR(ENOMEM);
323 vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, NULL);
324 sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
326 return AVERROR(ENOMEM);
327 vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, sup_ext);
330 optional_exts = optional_device_exts;
331 optional_exts_num = FF_ARRAY_ELEMS(optional_device_exts);
332 user_exts = av_dict_get(opts, "device_extensions", NULL, 0);
334 user_exts_str = av_strdup(user_exts->value);
335 if (!user_exts_str) {
336 err = AVERROR(ENOMEM);
340 vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
341 &sup_ext_count, NULL);
342 sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
344 return AVERROR(ENOMEM);
345 vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
346 &sup_ext_count, sup_ext);
349 for (int i = 0; i < optional_exts_num; i++) {
350 tstr = optional_exts[i].name;
352 for (int j = 0; j < sup_ext_count; j++) {
353 if (!strcmp(tstr, sup_ext[j].extensionName)) {
361 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
362 p->extensions |= optional_exts[i].flag;
363 ADD_VAL_TO_LIST(extension_names, extensions_found, tstr);
367 tstr = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
369 for (int j = 0; j < sup_ext_count; j++) {
370 if (!strcmp(tstr, sup_ext[j].extensionName)) {
376 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
377 ADD_VAL_TO_LIST(extension_names, extensions_found, tstr);
379 av_log(ctx, AV_LOG_ERROR, "Debug extension \"%s\" not found!\n",
381 err = AVERROR(EINVAL);
387 char *save, *token = av_strtok(user_exts_str, "+", &save);
390 for (int j = 0; j < sup_ext_count; j++) {
391 if (!strcmp(token, sup_ext[j].extensionName)) {
397 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, token);
398 ADD_VAL_TO_LIST(extension_names, extensions_found, token);
400 av_log(ctx, AV_LOG_WARNING, "%s extension \"%s\" not found, excluding.\n",
403 token = av_strtok(NULL, "+", &save);
407 *dst = extension_names;
408 *num = extensions_found;
410 av_free(user_exts_str);
416 for (int i = 0; i < extensions_found; i++)
417 av_free((void *)extension_names[i]);
418 av_free(extension_names);
419 av_free(user_exts_str);
424 /* Creates a VkInstance */
425 static int create_instance(AVHWDeviceContext *ctx, AVDictionary *opts)
429 VulkanDevicePriv *p = ctx->internal->priv;
430 AVVulkanDeviceContext *hwctx = ctx->hwctx;
431 AVDictionaryEntry *debug_opt = av_dict_get(opts, "debug", NULL, 0);
432 const int debug_mode = debug_opt && strtol(debug_opt->value, NULL, 10);
433 VkApplicationInfo application_info = {
434 .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
435 .pEngineName = "libavutil",
436 .apiVersion = VK_API_VERSION_1_1,
437 .engineVersion = VK_MAKE_VERSION(LIBAVUTIL_VERSION_MAJOR,
438 LIBAVUTIL_VERSION_MINOR,
439 LIBAVUTIL_VERSION_MICRO),
441 VkInstanceCreateInfo inst_props = {
442 .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
443 .pApplicationInfo = &application_info,
446 /* Check for present/missing extensions */
447 err = check_extensions(ctx, 0, opts, &inst_props.ppEnabledExtensionNames,
448 &inst_props.enabledExtensionCount, debug_mode);
453 static const char *layers[] = { "VK_LAYER_KHRONOS_validation" };
454 inst_props.ppEnabledLayerNames = layers;
455 inst_props.enabledLayerCount = FF_ARRAY_ELEMS(layers);
458 /* Try to create the instance */
459 ret = vkCreateInstance(&inst_props, hwctx->alloc, &hwctx->inst);
461 /* Check for errors */
462 if (ret != VK_SUCCESS) {
463 av_log(ctx, AV_LOG_ERROR, "Instance creation failure: %s\n",
465 for (int i = 0; i < inst_props.enabledExtensionCount; i++)
466 av_free((void *)inst_props.ppEnabledExtensionNames[i]);
467 av_free((void *)inst_props.ppEnabledExtensionNames);
468 return AVERROR_EXTERNAL;
472 VkDebugUtilsMessengerCreateInfoEXT dbg = {
473 .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT,
474 .messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT |
475 VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT |
476 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
477 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT,
478 .messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
479 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
480 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT,
481 .pfnUserCallback = vk_dbg_callback,
484 VK_LOAD_PFN(hwctx->inst, vkCreateDebugUtilsMessengerEXT);
486 pfn_vkCreateDebugUtilsMessengerEXT(hwctx->inst, &dbg,
487 hwctx->alloc, &p->debug_ctx);
490 hwctx->enabled_inst_extensions = inst_props.ppEnabledExtensionNames;
491 hwctx->nb_enabled_inst_extensions = inst_props.enabledExtensionCount;
496 typedef struct VulkanDeviceSelection {
497 uint8_t uuid[VK_UUID_SIZE]; /* Will use this first unless !has_uuid */
499 const char *name; /* Will use this second unless NULL */
500 uint32_t pci_device; /* Will use this third unless 0x0 */
501 uint32_t vendor_id; /* Last resort to find something deterministic */
502 int index; /* Finally fall back to index */
503 } VulkanDeviceSelection;
505 static const char *vk_dev_type(enum VkPhysicalDeviceType type)
508 case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: return "integrated";
509 case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: return "discrete";
510 case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: return "virtual";
511 case VK_PHYSICAL_DEVICE_TYPE_CPU: return "software";
512 default: return "unknown";
517 static int find_device(AVHWDeviceContext *ctx, VulkanDeviceSelection *select)
519 int err = 0, choice = -1;
522 VkPhysicalDevice *devices = NULL;
523 VkPhysicalDeviceIDProperties *idp = NULL;
524 VkPhysicalDeviceProperties2 *prop = NULL;
525 VulkanDevicePriv *p = ctx->internal->priv;
526 AVVulkanDeviceContext *hwctx = ctx->hwctx;
528 ret = vkEnumeratePhysicalDevices(hwctx->inst, &num, NULL);
529 if (ret != VK_SUCCESS || !num) {
530 av_log(ctx, AV_LOG_ERROR, "No devices found: %s!\n", vk_ret2str(ret));
531 return AVERROR(ENODEV);
534 devices = av_malloc_array(num, sizeof(VkPhysicalDevice));
536 return AVERROR(ENOMEM);
538 ret = vkEnumeratePhysicalDevices(hwctx->inst, &num, devices);
539 if (ret != VK_SUCCESS) {
540 av_log(ctx, AV_LOG_ERROR, "Failed enumerating devices: %s\n",
542 err = AVERROR(ENODEV);
546 prop = av_mallocz_array(num, sizeof(*prop));
548 err = AVERROR(ENOMEM);
552 idp = av_mallocz_array(num, sizeof(*idp));
554 err = AVERROR(ENOMEM);
558 av_log(ctx, AV_LOG_VERBOSE, "GPU listing:\n");
559 for (int i = 0; i < num; i++) {
560 idp[i].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES;
561 prop[i].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
562 prop[i].pNext = &idp[i];
564 vkGetPhysicalDeviceProperties2(devices[i], &prop[i]);
565 av_log(ctx, AV_LOG_VERBOSE, " %d: %s (%s) (0x%x)\n", i,
566 prop[i].properties.deviceName,
567 vk_dev_type(prop[i].properties.deviceType),
568 prop[i].properties.deviceID);
571 if (select->has_uuid) {
572 for (int i = 0; i < num; i++) {
573 if (!strncmp(idp[i].deviceUUID, select->uuid, VK_UUID_SIZE)) {
578 av_log(ctx, AV_LOG_ERROR, "Unable to find device by given UUID!\n");
579 err = AVERROR(ENODEV);
581 } else if (select->name) {
582 av_log(ctx, AV_LOG_VERBOSE, "Requested device: %s\n", select->name);
583 for (int i = 0; i < num; i++) {
584 if (strstr(prop[i].properties.deviceName, select->name)) {
589 av_log(ctx, AV_LOG_ERROR, "Unable to find device \"%s\"!\n",
591 err = AVERROR(ENODEV);
593 } else if (select->pci_device) {
594 av_log(ctx, AV_LOG_VERBOSE, "Requested device: 0x%x\n", select->pci_device);
595 for (int i = 0; i < num; i++) {
596 if (select->pci_device == prop[i].properties.deviceID) {
601 av_log(ctx, AV_LOG_ERROR, "Unable to find device with PCI ID 0x%x!\n",
603 err = AVERROR(EINVAL);
605 } else if (select->vendor_id) {
606 av_log(ctx, AV_LOG_VERBOSE, "Requested vendor: 0x%x\n", select->vendor_id);
607 for (int i = 0; i < num; i++) {
608 if (select->vendor_id == prop[i].properties.vendorID) {
613 av_log(ctx, AV_LOG_ERROR, "Unable to find device with Vendor ID 0x%x!\n",
615 err = AVERROR(ENODEV);
618 if (select->index < num) {
619 choice = select->index;
622 av_log(ctx, AV_LOG_ERROR, "Unable to find device with index %i!\n",
624 err = AVERROR(ENODEV);
630 p->dev_is_nvidia = (prop[choice].properties.vendorID == 0x10de);
631 hwctx->phys_dev = devices[choice];
640 static int search_queue_families(AVHWDeviceContext *ctx, VkDeviceCreateInfo *cd)
644 VkQueueFamilyProperties *qs = NULL;
645 AVVulkanDeviceContext *hwctx = ctx->hwctx;
646 int graph_index = -1, comp_index = -1, tx_index = -1;
647 VkDeviceQueueCreateInfo *pc = (VkDeviceQueueCreateInfo *)cd->pQueueCreateInfos;
649 /* First get the number of queue families */
650 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, NULL);
652 av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
653 return AVERROR_EXTERNAL;
656 /* Then allocate memory */
657 qs = av_malloc_array(num, sizeof(VkQueueFamilyProperties));
659 return AVERROR(ENOMEM);
661 /* Finally retrieve the queue families */
662 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, qs);
664 #define SEARCH_FLAGS(expr, out) \
665 for (int i = 0; i < num; i++) { \
666 const VkQueueFlagBits flags = qs[i].queueFlags; \
673 SEARCH_FLAGS(flags & VK_QUEUE_GRAPHICS_BIT, graph_index)
675 SEARCH_FLAGS((flags & VK_QUEUE_COMPUTE_BIT) && (i != graph_index),
678 SEARCH_FLAGS((flags & VK_QUEUE_TRANSFER_BIT) && (i != graph_index) &&
679 (i != comp_index), tx_index)
682 #define ADD_QUEUE(fidx, graph, comp, tx) \
683 av_log(ctx, AV_LOG_VERBOSE, "Using queue family %i (total queues: %i) for %s%s%s\n", \
684 fidx, qs[fidx].queueCount, graph ? "graphics " : "", \
685 comp ? "compute " : "", tx ? "transfers " : ""); \
686 av_log(ctx, AV_LOG_VERBOSE, " QF %i flags: %s%s%s%s\n", fidx, \
687 ((qs[fidx].queueFlags) & VK_QUEUE_GRAPHICS_BIT) ? "(graphics) " : "", \
688 ((qs[fidx].queueFlags) & VK_QUEUE_COMPUTE_BIT) ? "(compute) " : "", \
689 ((qs[fidx].queueFlags) & VK_QUEUE_TRANSFER_BIT) ? "(transfers) " : "", \
690 ((qs[fidx].queueFlags) & VK_QUEUE_SPARSE_BINDING_BIT) ? "(sparse) " : ""); \
691 pc[cd->queueCreateInfoCount].queueFamilyIndex = fidx; \
692 pc[cd->queueCreateInfoCount].queueCount = qs[fidx].queueCount; \
693 weights = av_malloc(qs[fidx].queueCount * sizeof(float)); \
694 pc[cd->queueCreateInfoCount].pQueuePriorities = weights; \
697 for (int i = 0; i < qs[fidx].queueCount; i++) \
699 cd->queueCreateInfoCount++;
701 ADD_QUEUE(graph_index, 1, comp_index < 0, tx_index < 0 && comp_index < 0)
702 hwctx->queue_family_index = graph_index;
703 hwctx->queue_family_comp_index = graph_index;
704 hwctx->queue_family_tx_index = graph_index;
705 hwctx->nb_graphics_queues = qs[graph_index].queueCount;
707 if (comp_index != -1) {
708 ADD_QUEUE(comp_index, 0, 1, tx_index < 0)
709 hwctx->queue_family_tx_index = comp_index;
710 hwctx->queue_family_comp_index = comp_index;
711 hwctx->nb_comp_queues = qs[comp_index].queueCount;
714 if (tx_index != -1) {
715 ADD_QUEUE(tx_index, 0, 0, 1)
716 hwctx->queue_family_tx_index = tx_index;
717 hwctx->nb_tx_queues = qs[tx_index].queueCount;
726 av_freep(&pc[0].pQueuePriorities);
727 av_freep(&pc[1].pQueuePriorities);
728 av_freep(&pc[2].pQueuePriorities);
731 return AVERROR(ENOMEM);
734 static int create_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd,
735 int queue_family_index, int num_queues)
738 AVVulkanDeviceContext *hwctx = ctx->hwctx;
740 VkCommandPoolCreateInfo cqueue_create = {
741 .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
742 .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
743 .queueFamilyIndex = queue_family_index,
745 VkCommandBufferAllocateInfo cbuf_create = {
746 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
747 .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
748 .commandBufferCount = num_queues,
751 cmd->nb_queues = num_queues;
753 cmd->queues = av_mallocz(num_queues * sizeof(*cmd->queues));
755 return AVERROR(ENOMEM);
757 cmd->bufs = av_mallocz(num_queues * sizeof(*cmd->bufs));
759 return AVERROR(ENOMEM);
761 /* Create command pool */
762 ret = vkCreateCommandPool(hwctx->act_dev, &cqueue_create,
763 hwctx->alloc, &cmd->pool);
764 if (ret != VK_SUCCESS) {
765 av_log(ctx, AV_LOG_ERROR, "Command pool creation failure: %s\n",
767 return AVERROR_EXTERNAL;
770 cbuf_create.commandPool = cmd->pool;
772 /* Allocate command buffer */
773 ret = vkAllocateCommandBuffers(hwctx->act_dev, &cbuf_create, cmd->bufs);
774 if (ret != VK_SUCCESS) {
775 av_log(ctx, AV_LOG_ERROR, "Command buffer alloc failure: %s\n",
777 return AVERROR_EXTERNAL;
780 for (int i = 0; i < num_queues; i++) {
781 VulkanQueueCtx *q = &cmd->queues[i];
782 vkGetDeviceQueue(hwctx->act_dev, queue_family_index, i, &q->queue);
783 q->was_synchronous = 1;
789 static void free_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd)
791 AVVulkanDeviceContext *hwctx = ctx->hwctx;
793 /* Make sure all queues have finished executing */
794 for (int i = 0; i < cmd->nb_queues; i++) {
795 VulkanQueueCtx *q = &cmd->queues[i];
797 if (q->fence && !q->was_synchronous) {
798 vkWaitForFences(hwctx->act_dev, 1, &q->fence, VK_TRUE, UINT64_MAX);
799 vkResetFences(hwctx->act_dev, 1, &q->fence);
804 vkDestroyFence(hwctx->act_dev, q->fence, hwctx->alloc);
806 /* Free buffer dependencies */
807 for (int j = 0; j < q->nb_buf_deps; j++)
808 av_buffer_unref(&q->buf_deps[j]);
809 av_free(q->buf_deps);
813 vkFreeCommandBuffers(hwctx->act_dev, cmd->pool, cmd->nb_queues, cmd->bufs);
815 vkDestroyCommandPool(hwctx->act_dev, cmd->pool, hwctx->alloc);
817 av_freep(&cmd->bufs);
818 av_freep(&cmd->queues);
821 static VkCommandBuffer get_buf_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd)
823 return cmd->bufs[cmd->cur_queue_idx];
826 static void unref_exec_ctx_deps(AVHWDeviceContext *ctx, VulkanExecCtx *cmd)
828 VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
830 for (int j = 0; j < q->nb_buf_deps; j++)
831 av_buffer_unref(&q->buf_deps[j]);
835 static int wait_start_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd)
838 AVVulkanDeviceContext *hwctx = ctx->hwctx;
839 VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
841 VkCommandBufferBeginInfo cmd_start = {
842 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
843 .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
846 /* Create the fence and don't wait for it initially */
848 VkFenceCreateInfo fence_spawn = {
849 .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
851 ret = vkCreateFence(hwctx->act_dev, &fence_spawn, hwctx->alloc,
853 if (ret != VK_SUCCESS) {
854 av_log(ctx, AV_LOG_ERROR, "Failed to queue frame fence: %s\n",
856 return AVERROR_EXTERNAL;
858 } else if (!q->was_synchronous) {
859 vkWaitForFences(hwctx->act_dev, 1, &q->fence, VK_TRUE, UINT64_MAX);
860 vkResetFences(hwctx->act_dev, 1, &q->fence);
863 /* Discard queue dependencies */
864 unref_exec_ctx_deps(ctx, cmd);
866 ret = vkBeginCommandBuffer(cmd->bufs[cmd->cur_queue_idx], &cmd_start);
867 if (ret != VK_SUCCESS) {
868 av_log(ctx, AV_LOG_ERROR, "Unable to init command buffer: %s\n",
870 return AVERROR_EXTERNAL;
876 static int add_buf_dep_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd,
877 AVBufferRef * const *deps, int nb_deps)
880 VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
882 if (!deps || !nb_deps)
885 dst = av_fast_realloc(q->buf_deps, &q->buf_deps_alloc_size,
886 (q->nb_buf_deps + nb_deps) * sizeof(*dst));
892 for (int i = 0; i < nb_deps; i++) {
893 q->buf_deps[q->nb_buf_deps] = av_buffer_ref(deps[i]);
894 if (!q->buf_deps[q->nb_buf_deps])
902 unref_exec_ctx_deps(ctx, cmd);
903 return AVERROR(ENOMEM);
906 static int submit_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd,
907 VkSubmitInfo *s_info, int synchronous)
910 VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
912 ret = vkEndCommandBuffer(cmd->bufs[cmd->cur_queue_idx]);
913 if (ret != VK_SUCCESS) {
914 av_log(ctx, AV_LOG_ERROR, "Unable to finish command buffer: %s\n",
916 unref_exec_ctx_deps(ctx, cmd);
917 return AVERROR_EXTERNAL;
920 s_info->pCommandBuffers = &cmd->bufs[cmd->cur_queue_idx];
921 s_info->commandBufferCount = 1;
923 ret = vkQueueSubmit(q->queue, 1, s_info, q->fence);
924 if (ret != VK_SUCCESS) {
925 unref_exec_ctx_deps(ctx, cmd);
926 return AVERROR_EXTERNAL;
929 q->was_synchronous = synchronous;
932 AVVulkanDeviceContext *hwctx = ctx->hwctx;
933 vkWaitForFences(hwctx->act_dev, 1, &q->fence, VK_TRUE, UINT64_MAX);
934 vkResetFences(hwctx->act_dev, 1, &q->fence);
935 unref_exec_ctx_deps(ctx, cmd);
936 } else { /* Rotate queues */
937 cmd->cur_queue_idx = (cmd->cur_queue_idx + 1) % cmd->nb_queues;
943 static void vulkan_device_free(AVHWDeviceContext *ctx)
945 VulkanDevicePriv *p = ctx->internal->priv;
946 AVVulkanDeviceContext *hwctx = ctx->hwctx;
948 free_exec_ctx(ctx, &p->cmd);
950 vkDestroyDevice(hwctx->act_dev, hwctx->alloc);
953 VK_LOAD_PFN(hwctx->inst, vkDestroyDebugUtilsMessengerEXT);
954 pfn_vkDestroyDebugUtilsMessengerEXT(hwctx->inst, p->debug_ctx,
958 vkDestroyInstance(hwctx->inst, hwctx->alloc);
960 for (int i = 0; i < hwctx->nb_enabled_inst_extensions; i++)
961 av_free((void *)hwctx->enabled_inst_extensions[i]);
962 av_free((void *)hwctx->enabled_inst_extensions);
964 for (int i = 0; i < hwctx->nb_enabled_dev_extensions; i++)
965 av_free((void *)hwctx->enabled_dev_extensions[i]);
966 av_free((void *)hwctx->enabled_dev_extensions);
969 static int vulkan_device_create_internal(AVHWDeviceContext *ctx,
970 VulkanDeviceSelection *dev_select,
971 AVDictionary *opts, int flags)
975 AVDictionaryEntry *opt_d;
976 VulkanDevicePriv *p = ctx->internal->priv;
977 AVVulkanDeviceContext *hwctx = ctx->hwctx;
978 VkPhysicalDeviceFeatures dev_features = { 0 };
979 VkDeviceQueueCreateInfo queue_create_info[3] = {
980 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, },
981 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, },
982 { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, },
985 VkDeviceCreateInfo dev_info = {
986 .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
987 .pNext = &hwctx->device_features,
988 .pQueueCreateInfos = queue_create_info,
989 .queueCreateInfoCount = 0,
992 hwctx->device_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
993 ctx->free = vulkan_device_free;
995 /* Create an instance if not given one */
996 if ((err = create_instance(ctx, opts)))
999 /* Find a device (if not given one) */
1000 if ((err = find_device(ctx, dev_select)))
1003 vkGetPhysicalDeviceProperties(hwctx->phys_dev, &p->props);
1004 av_log(ctx, AV_LOG_VERBOSE, "Using device: %s\n", p->props.deviceName);
1005 av_log(ctx, AV_LOG_VERBOSE, "Alignments:\n");
1006 av_log(ctx, AV_LOG_VERBOSE, " optimalBufferCopyOffsetAlignment: %li\n",
1007 p->props.limits.optimalBufferCopyOffsetAlignment);
1008 av_log(ctx, AV_LOG_VERBOSE, " optimalBufferCopyRowPitchAlignment: %li\n",
1009 p->props.limits.optimalBufferCopyRowPitchAlignment);
1010 av_log(ctx, AV_LOG_VERBOSE, " minMemoryMapAlignment: %li\n",
1011 p->props.limits.minMemoryMapAlignment);
1013 vkGetPhysicalDeviceFeatures(hwctx->phys_dev, &dev_features);
1014 #define COPY_FEATURE(DST, NAME) (DST).features.NAME = dev_features.NAME;
1015 COPY_FEATURE(hwctx->device_features, shaderImageGatherExtended)
1016 COPY_FEATURE(hwctx->device_features, fragmentStoresAndAtomics)
1017 COPY_FEATURE(hwctx->device_features, vertexPipelineStoresAndAtomics)
1018 COPY_FEATURE(hwctx->device_features, shaderInt64)
1021 /* Search queue family */
1022 if ((err = search_queue_families(ctx, &dev_info)))
1025 if ((err = check_extensions(ctx, 1, opts, &dev_info.ppEnabledExtensionNames,
1026 &dev_info.enabledExtensionCount, 0))) {
1027 av_free((void *)queue_create_info[0].pQueuePriorities);
1028 av_free((void *)queue_create_info[1].pQueuePriorities);
1029 av_free((void *)queue_create_info[2].pQueuePriorities);
1033 ret = vkCreateDevice(hwctx->phys_dev, &dev_info, hwctx->alloc,
1036 av_free((void *)queue_create_info[0].pQueuePriorities);
1037 av_free((void *)queue_create_info[1].pQueuePriorities);
1038 av_free((void *)queue_create_info[2].pQueuePriorities);
1040 if (ret != VK_SUCCESS) {
1041 av_log(ctx, AV_LOG_ERROR, "Device creation failure: %s\n",
1043 for (int i = 0; i < dev_info.enabledExtensionCount; i++)
1044 av_free((void *)dev_info.ppEnabledExtensionNames[i]);
1045 av_free((void *)dev_info.ppEnabledExtensionNames);
1046 err = AVERROR_EXTERNAL;
1050 /* Tiled images setting, use them by default */
1051 opt_d = av_dict_get(opts, "linear_images", NULL, 0);
1053 p->use_linear_images = strtol(opt_d->value, NULL, 10);
1055 hwctx->enabled_dev_extensions = dev_info.ppEnabledExtensionNames;
1056 hwctx->nb_enabled_dev_extensions = dev_info.enabledExtensionCount;
1062 static int vulkan_device_init(AVHWDeviceContext *ctx)
1066 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1067 VulkanDevicePriv *p = ctx->internal->priv;
1069 /* Set device extension flags */
1070 for (int i = 0; i < hwctx->nb_enabled_dev_extensions; i++) {
1071 for (int j = 0; j < FF_ARRAY_ELEMS(optional_device_exts); j++) {
1072 if (!strcmp(hwctx->enabled_dev_extensions[i],
1073 optional_device_exts[j].name)) {
1074 p->extensions |= optional_device_exts[j].flag;
1080 vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &queue_num, NULL);
1082 av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
1083 return AVERROR_EXTERNAL;
1086 #define CHECK_QUEUE(type, n) \
1087 if (n >= queue_num) { \
1088 av_log(ctx, AV_LOG_ERROR, "Invalid %s queue index %i (device has %i queues)!\n", \
1089 type, n, queue_num); \
1090 return AVERROR(EINVAL); \
1093 CHECK_QUEUE("graphics", hwctx->queue_family_index)
1094 CHECK_QUEUE("upload", hwctx->queue_family_tx_index)
1095 CHECK_QUEUE("compute", hwctx->queue_family_comp_index)
1099 p->qfs[p->num_qfs++] = hwctx->queue_family_index;
1100 if ((hwctx->queue_family_tx_index != hwctx->queue_family_index) &&
1101 (hwctx->queue_family_tx_index != hwctx->queue_family_comp_index))
1102 p->qfs[p->num_qfs++] = hwctx->queue_family_tx_index;
1103 if ((hwctx->queue_family_comp_index != hwctx->queue_family_index) &&
1104 (hwctx->queue_family_comp_index != hwctx->queue_family_tx_index))
1105 p->qfs[p->num_qfs++] = hwctx->queue_family_comp_index;
1107 /* Create exec context - if there's something invalid this will error out */
1108 err = create_exec_ctx(ctx, &p->cmd, hwctx->queue_family_tx_index,
1109 GET_QUEUE_COUNT(hwctx, 0, 0, 1));
1113 /* Get device capabilities */
1114 vkGetPhysicalDeviceMemoryProperties(hwctx->phys_dev, &p->mprops);
1119 static int vulkan_device_create(AVHWDeviceContext *ctx, const char *device,
1120 AVDictionary *opts, int flags)
1122 VulkanDeviceSelection dev_select = { 0 };
1123 if (device && device[0]) {
1125 dev_select.index = strtol(device, &end, 10);
1126 if (end == device) {
1127 dev_select.index = 0;
1128 dev_select.name = device;
1132 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1135 static int vulkan_device_derive(AVHWDeviceContext *ctx,
1136 AVHWDeviceContext *src_ctx,
1137 AVDictionary *opts, int flags)
1139 av_unused VulkanDeviceSelection dev_select = { 0 };
1141 /* If there's only one device on the system, then even if its not covered
1142 * by the following checks (e.g. non-PCIe ARM GPU), having an empty
1143 * dev_select will mean it'll get picked. */
1144 switch(src_ctx->type) {
1147 case AV_HWDEVICE_TYPE_VAAPI: {
1148 AVVAAPIDeviceContext *src_hwctx = src_ctx->hwctx;
1150 const char *vendor = vaQueryVendorString(src_hwctx->display);
1152 av_log(ctx, AV_LOG_ERROR, "Unable to get device info from VAAPI!\n");
1153 return AVERROR_EXTERNAL;
1156 if (strstr(vendor, "Intel"))
1157 dev_select.vendor_id = 0x8086;
1158 if (strstr(vendor, "AMD"))
1159 dev_select.vendor_id = 0x1002;
1161 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1164 case AV_HWDEVICE_TYPE_DRM: {
1165 AVDRMDeviceContext *src_hwctx = src_ctx->hwctx;
1167 drmDevice *drm_dev_info;
1168 int err = drmGetDevice(src_hwctx->fd, &drm_dev_info);
1170 av_log(ctx, AV_LOG_ERROR, "Unable to get device info from DRM fd!\n");
1171 return AVERROR_EXTERNAL;
1174 if (drm_dev_info->bustype == DRM_BUS_PCI)
1175 dev_select.pci_device = drm_dev_info->deviceinfo.pci->device_id;
1177 drmFreeDevice(&drm_dev_info);
1179 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1183 case AV_HWDEVICE_TYPE_CUDA: {
1184 AVHWDeviceContext *cuda_cu = src_ctx;
1185 AVCUDADeviceContext *src_hwctx = src_ctx->hwctx;
1186 AVCUDADeviceContextInternal *cu_internal = src_hwctx->internal;
1187 CudaFunctions *cu = cu_internal->cuda_dl;
1189 int ret = CHECK_CU(cu->cuDeviceGetUuid((CUuuid *)&dev_select.uuid,
1190 cu_internal->cuda_device));
1192 av_log(ctx, AV_LOG_ERROR, "Unable to get UUID from CUDA!\n");
1193 return AVERROR_EXTERNAL;
1196 dev_select.has_uuid = 1;
1198 return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1202 return AVERROR(ENOSYS);
1206 static int vulkan_frames_get_constraints(AVHWDeviceContext *ctx,
1207 const void *hwconfig,
1208 AVHWFramesConstraints *constraints)
1211 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1212 VulkanDevicePriv *p = ctx->internal->priv;
1214 for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
1215 count += pixfmt_is_supported(hwctx, i, p->use_linear_images);
1218 if (p->dev_is_nvidia)
1222 constraints->valid_sw_formats = av_malloc_array(count + 1,
1223 sizeof(enum AVPixelFormat));
1224 if (!constraints->valid_sw_formats)
1225 return AVERROR(ENOMEM);
1228 for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
1229 if (pixfmt_is_supported(hwctx, i, p->use_linear_images))
1230 constraints->valid_sw_formats[count++] = i;
1233 if (p->dev_is_nvidia)
1234 constraints->valid_sw_formats[count++] = AV_PIX_FMT_CUDA;
1236 constraints->valid_sw_formats[count++] = AV_PIX_FMT_NONE;
1238 constraints->min_width = 0;
1239 constraints->min_height = 0;
1240 constraints->max_width = p->props.limits.maxImageDimension2D;
1241 constraints->max_height = p->props.limits.maxImageDimension2D;
1243 constraints->valid_hw_formats = av_malloc_array(2, sizeof(enum AVPixelFormat));
1244 if (!constraints->valid_hw_formats)
1245 return AVERROR(ENOMEM);
1247 constraints->valid_hw_formats[0] = AV_PIX_FMT_VULKAN;
1248 constraints->valid_hw_formats[1] = AV_PIX_FMT_NONE;
1253 static int alloc_mem(AVHWDeviceContext *ctx, VkMemoryRequirements *req,
1254 VkMemoryPropertyFlagBits req_flags, void *alloc_extension,
1255 VkMemoryPropertyFlagBits *mem_flags, VkDeviceMemory *mem)
1259 VulkanDevicePriv *p = ctx->internal->priv;
1260 AVVulkanDeviceContext *dev_hwctx = ctx->hwctx;
1261 VkMemoryAllocateInfo alloc_info = {
1262 .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
1263 .pNext = alloc_extension,
1266 /* Align if we need to */
1267 if (req_flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)
1268 req->size = FFALIGN(req->size, p->props.limits.minMemoryMapAlignment);
1270 alloc_info.allocationSize = req->size;
1272 /* The vulkan spec requires memory types to be sorted in the "optimal"
1273 * order, so the first matching type we find will be the best/fastest one */
1274 for (int i = 0; i < p->mprops.memoryTypeCount; i++) {
1275 /* The memory type must be supported by the requirements (bitfield) */
1276 if (!(req->memoryTypeBits & (1 << i)))
1279 /* The memory type flags must include our properties */
1280 if ((p->mprops.memoryTypes[i].propertyFlags & req_flags) != req_flags)
1283 /* Found a suitable memory type */
1289 av_log(ctx, AV_LOG_ERROR, "No memory type found for flags 0x%x\n",
1291 return AVERROR(EINVAL);
1294 alloc_info.memoryTypeIndex = index;
1296 ret = vkAllocateMemory(dev_hwctx->act_dev, &alloc_info,
1297 dev_hwctx->alloc, mem);
1298 if (ret != VK_SUCCESS) {
1299 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory: %s\n",
1301 return AVERROR(ENOMEM);
1304 *mem_flags |= p->mprops.memoryTypes[index].propertyFlags;
1309 static void vulkan_free_internal(AVVkFrameInternal *internal)
1315 if (internal->cuda_fc_ref) {
1316 AVHWFramesContext *cuda_fc = (AVHWFramesContext *)internal->cuda_fc_ref->data;
1317 int planes = av_pix_fmt_count_planes(cuda_fc->sw_format);
1318 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
1319 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
1320 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
1321 CudaFunctions *cu = cu_internal->cuda_dl;
1323 for (int i = 0; i < planes; i++) {
1324 if (internal->cu_sem[i])
1325 CHECK_CU(cu->cuDestroyExternalSemaphore(internal->cu_sem[i]));
1326 if (internal->cu_mma[i])
1327 CHECK_CU(cu->cuMipmappedArrayDestroy(internal->cu_mma[i]));
1328 if (internal->ext_mem[i])
1329 CHECK_CU(cu->cuDestroyExternalMemory(internal->ext_mem[i]));
1332 av_buffer_unref(&internal->cuda_fc_ref);
1339 static void vulkan_frame_free(void *opaque, uint8_t *data)
1341 AVVkFrame *f = (AVVkFrame *)data;
1342 AVHWFramesContext *hwfc = opaque;
1343 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1344 int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1346 vulkan_free_internal(f->internal);
1348 for (int i = 0; i < planes; i++) {
1349 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
1350 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
1351 vkDestroySemaphore(hwctx->act_dev, f->sem[i], hwctx->alloc);
1357 static int alloc_bind_mem(AVHWFramesContext *hwfc, AVVkFrame *f,
1358 void *alloc_pnext, size_t alloc_pnext_stride)
1362 AVHWDeviceContext *ctx = hwfc->device_ctx;
1363 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1364 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { { 0 } };
1366 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1368 for (int i = 0; i < planes; i++) {
1370 VkImageMemoryRequirementsInfo2 req_desc = {
1371 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
1374 VkMemoryDedicatedAllocateInfo ded_alloc = {
1375 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
1376 .pNext = (void *)(((uint8_t *)alloc_pnext) + i*alloc_pnext_stride),
1378 VkMemoryDedicatedRequirements ded_req = {
1379 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
1381 VkMemoryRequirements2 req = {
1382 .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
1386 vkGetImageMemoryRequirements2(hwctx->act_dev, &req_desc, &req);
1388 /* In case the implementation prefers/requires dedicated allocation */
1389 use_ded_mem = ded_req.prefersDedicatedAllocation |
1390 ded_req.requiresDedicatedAllocation;
1392 ded_alloc.image = f->img[i];
1394 /* Allocate memory */
1395 if ((err = alloc_mem(ctx, &req.memoryRequirements,
1396 f->tiling == VK_IMAGE_TILING_LINEAR ?
1397 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT :
1398 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1399 use_ded_mem ? &ded_alloc : (void *)ded_alloc.pNext,
1400 &f->flags, &f->mem[i])))
1403 f->size[i] = req.memoryRequirements.size;
1404 bind_info[i].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
1405 bind_info[i].image = f->img[i];
1406 bind_info[i].memory = f->mem[i];
1409 /* Bind the allocated memory to the images */
1410 ret = vkBindImageMemory2(hwctx->act_dev, planes, bind_info);
1411 if (ret != VK_SUCCESS) {
1412 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
1414 return AVERROR_EXTERNAL;
1422 PREP_MODE_RO_SHADER,
1423 PREP_MODE_EXTERNAL_EXPORT,
1426 static int prepare_frame(AVHWFramesContext *hwfc, VulkanExecCtx *ectx,
1427 AVVkFrame *frame, enum PrepMode pmode)
1431 VkImageLayout new_layout;
1432 VkAccessFlags new_access;
1433 AVHWDeviceContext *ctx = hwfc->device_ctx;
1434 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1436 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
1438 VkSubmitInfo s_info = {
1439 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
1440 .pSignalSemaphores = frame->sem,
1441 .signalSemaphoreCount = planes,
1444 VkPipelineStageFlagBits wait_st[AV_NUM_DATA_POINTERS];
1445 for (int i = 0; i < planes; i++)
1446 wait_st[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
1449 case PREP_MODE_WRITE:
1450 new_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
1451 new_access = VK_ACCESS_TRANSFER_WRITE_BIT;
1452 dst_qf = VK_QUEUE_FAMILY_IGNORED;
1454 case PREP_MODE_RO_SHADER:
1455 new_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
1456 new_access = VK_ACCESS_TRANSFER_READ_BIT;
1457 dst_qf = VK_QUEUE_FAMILY_IGNORED;
1459 case PREP_MODE_EXTERNAL_EXPORT:
1460 new_layout = VK_IMAGE_LAYOUT_GENERAL;
1461 new_access = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
1462 dst_qf = VK_QUEUE_FAMILY_EXTERNAL_KHR;
1463 s_info.pWaitSemaphores = frame->sem;
1464 s_info.pWaitDstStageMask = wait_st;
1465 s_info.waitSemaphoreCount = planes;
1469 if ((err = wait_start_exec_ctx(ctx, ectx)))
1472 /* Change the image layout to something more optimal for writes.
1473 * This also signals the newly created semaphore, making it usable
1474 * for synchronization */
1475 for (int i = 0; i < planes; i++) {
1476 img_bar[i].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1477 img_bar[i].srcAccessMask = 0x0;
1478 img_bar[i].dstAccessMask = new_access;
1479 img_bar[i].oldLayout = frame->layout[i];
1480 img_bar[i].newLayout = new_layout;
1481 img_bar[i].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1482 img_bar[i].dstQueueFamilyIndex = dst_qf;
1483 img_bar[i].image = frame->img[i];
1484 img_bar[i].subresourceRange.levelCount = 1;
1485 img_bar[i].subresourceRange.layerCount = 1;
1486 img_bar[i].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1488 frame->layout[i] = img_bar[i].newLayout;
1489 frame->access[i] = img_bar[i].dstAccessMask;
1492 vkCmdPipelineBarrier(get_buf_exec_ctx(ctx, ectx),
1493 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
1494 VK_PIPELINE_STAGE_TRANSFER_BIT,
1495 0, 0, NULL, 0, NULL, planes, img_bar);
1497 return submit_exec_ctx(ctx, ectx, &s_info, 0);
1500 static int create_frame(AVHWFramesContext *hwfc, AVVkFrame **frame,
1501 VkImageTiling tiling, VkImageUsageFlagBits usage,
1506 AVHWDeviceContext *ctx = hwfc->device_ctx;
1507 VulkanDevicePriv *p = ctx->internal->priv;
1508 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1509 enum AVPixelFormat format = hwfc->sw_format;
1510 const VkFormat *img_fmts = av_vkfmt_from_pixfmt(format);
1511 const int planes = av_pix_fmt_count_planes(format);
1513 VkExportSemaphoreCreateInfo ext_sem_info = {
1514 .sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO,
1515 .handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
1518 VkSemaphoreCreateInfo sem_spawn = {
1519 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1520 .pNext = p->extensions & EXT_EXTERNAL_FD_SEM ? &ext_sem_info : NULL,
1523 AVVkFrame *f = av_vk_frame_alloc();
1525 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1526 return AVERROR(ENOMEM);
1529 /* Create the images */
1530 for (int i = 0; i < planes; i++) {
1531 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
1532 int w = hwfc->width;
1533 int h = hwfc->height;
1534 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
1535 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
1537 VkImageCreateInfo image_create_info = {
1538 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1539 .pNext = create_pnext,
1540 .imageType = VK_IMAGE_TYPE_2D,
1541 .format = img_fmts[i],
1542 .extent.width = p_w,
1543 .extent.height = p_h,
1547 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1549 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1551 .samples = VK_SAMPLE_COUNT_1_BIT,
1552 .pQueueFamilyIndices = p->qfs,
1553 .queueFamilyIndexCount = p->num_qfs,
1554 .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
1555 VK_SHARING_MODE_EXCLUSIVE,
1558 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
1559 hwctx->alloc, &f->img[i]);
1560 if (ret != VK_SUCCESS) {
1561 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1563 err = AVERROR(EINVAL);
1567 /* Create semaphore */
1568 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1569 hwctx->alloc, &f->sem[i]);
1570 if (ret != VK_SUCCESS) {
1571 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1573 return AVERROR_EXTERNAL;
1576 f->layout[i] = image_create_info.initialLayout;
1587 vulkan_frame_free(hwfc, (uint8_t *)f);
1591 /* Checks if an export flag is enabled, and if it is ORs it with *iexp */
1592 static void try_export_flags(AVHWFramesContext *hwfc,
1593 VkExternalMemoryHandleTypeFlags *comp_handle_types,
1594 VkExternalMemoryHandleTypeFlagBits *iexp,
1595 VkExternalMemoryHandleTypeFlagBits exp)
1598 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1599 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1600 VkExternalImageFormatProperties eprops = {
1601 .sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES_KHR,
1603 VkImageFormatProperties2 props = {
1604 .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,
1607 VkPhysicalDeviceExternalImageFormatInfo enext = {
1608 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
1611 VkPhysicalDeviceImageFormatInfo2 pinfo = {
1612 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1613 .pNext = !exp ? NULL : &enext,
1614 .format = av_vkfmt_from_pixfmt(hwfc->sw_format)[0],
1615 .type = VK_IMAGE_TYPE_2D,
1616 .tiling = hwctx->tiling,
1617 .usage = hwctx->usage,
1618 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
1621 ret = vkGetPhysicalDeviceImageFormatProperties2(dev_hwctx->phys_dev,
1623 if (ret == VK_SUCCESS) {
1625 *comp_handle_types |= eprops.externalMemoryProperties.compatibleHandleTypes;
1629 static AVBufferRef *vulkan_pool_alloc(void *opaque, int size)
1633 AVBufferRef *avbuf = NULL;
1634 AVHWFramesContext *hwfc = opaque;
1635 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1636 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1637 VkExportMemoryAllocateInfo eminfo[AV_NUM_DATA_POINTERS];
1638 VkExternalMemoryHandleTypeFlags e = 0x0;
1640 VkExternalMemoryImageCreateInfo eiinfo = {
1641 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1642 .pNext = hwctx->create_pnext,
1645 if (p->extensions & EXT_EXTERNAL_FD_MEMORY)
1646 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1647 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT);
1649 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
1650 try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1651 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
1653 for (int i = 0; i < av_pix_fmt_count_planes(hwfc->sw_format); i++) {
1654 eminfo[i].sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO;
1655 eminfo[i].pNext = hwctx->alloc_pnext[i];
1656 eminfo[i].handleTypes = e;
1659 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1660 eiinfo.handleTypes ? &eiinfo : NULL);
1664 err = alloc_bind_mem(hwfc, f, eminfo, sizeof(*eminfo));
1668 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_WRITE);
1672 avbuf = av_buffer_create((uint8_t *)f, sizeof(AVVkFrame),
1673 vulkan_frame_free, hwfc, 0);
1680 vulkan_frame_free(hwfc, (uint8_t *)f);
1684 static void vulkan_frames_uninit(AVHWFramesContext *hwfc)
1686 VulkanFramesPriv *fp = hwfc->internal->priv;
1688 free_exec_ctx(hwfc->device_ctx, &fp->cmd);
1691 static int vulkan_frames_init(AVHWFramesContext *hwfc)
1695 AVVulkanFramesContext *hwctx = hwfc->hwctx;
1696 VulkanFramesPriv *fp = hwfc->internal->priv;
1697 AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1698 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1700 /* Default pool flags */
1701 hwctx->tiling = hwctx->tiling ? hwctx->tiling : p->use_linear_images ?
1702 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1704 hwctx->usage |= DEFAULT_USAGE_FLAGS;
1706 err = create_exec_ctx(hwfc->device_ctx, &fp->cmd,
1707 dev_hwctx->queue_family_tx_index,
1708 GET_QUEUE_COUNT(dev_hwctx, 0, 0, 1));
1712 /* Test to see if allocation will fail */
1713 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1714 hwctx->create_pnext);
1716 free_exec_ctx(hwfc->device_ctx, &p->cmd);
1720 vulkan_frame_free(hwfc, (uint8_t *)f);
1722 /* If user did not specify a pool, hwfc->pool will be set to the internal one
1723 * in hwcontext.c just after this gets called */
1725 hwfc->internal->pool_internal = av_buffer_pool_init2(sizeof(AVVkFrame),
1726 hwfc, vulkan_pool_alloc,
1728 if (!hwfc->internal->pool_internal) {
1729 free_exec_ctx(hwfc->device_ctx, &p->cmd);
1730 return AVERROR(ENOMEM);
1737 static int vulkan_get_buffer(AVHWFramesContext *hwfc, AVFrame *frame)
1739 frame->buf[0] = av_buffer_pool_get(hwfc->pool);
1741 return AVERROR(ENOMEM);
1743 frame->data[0] = frame->buf[0]->data;
1744 frame->format = AV_PIX_FMT_VULKAN;
1745 frame->width = hwfc->width;
1746 frame->height = hwfc->height;
1751 static int vulkan_transfer_get_formats(AVHWFramesContext *hwfc,
1752 enum AVHWFrameTransferDirection dir,
1753 enum AVPixelFormat **formats)
1755 enum AVPixelFormat *fmts = av_malloc_array(2, sizeof(*fmts));
1757 return AVERROR(ENOMEM);
1759 fmts[0] = hwfc->sw_format;
1760 fmts[1] = AV_PIX_FMT_NONE;
1766 typedef struct VulkanMapping {
1771 static void vulkan_unmap_frame(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1773 VulkanMapping *map = hwmap->priv;
1774 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1775 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1777 /* Check if buffer needs flushing */
1778 if ((map->flags & AV_HWFRAME_MAP_WRITE) &&
1779 !(map->frame->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1781 VkMappedMemoryRange flush_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1783 for (int i = 0; i < planes; i++) {
1784 flush_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1785 flush_ranges[i].memory = map->frame->mem[i];
1786 flush_ranges[i].size = VK_WHOLE_SIZE;
1789 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, planes,
1791 if (ret != VK_SUCCESS) {
1792 av_log(hwfc, AV_LOG_ERROR, "Failed to flush memory: %s\n",
1797 for (int i = 0; i < planes; i++)
1798 vkUnmapMemory(hwctx->act_dev, map->frame->mem[i]);
1803 static int vulkan_map_frame_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
1804 const AVFrame *src, int flags)
1807 int err, mapped_mem_count = 0;
1808 AVVkFrame *f = (AVVkFrame *)src->data[0];
1809 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1810 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1812 VulkanMapping *map = av_mallocz(sizeof(VulkanMapping));
1814 return AVERROR(EINVAL);
1816 if (src->format != AV_PIX_FMT_VULKAN) {
1817 av_log(hwfc, AV_LOG_ERROR, "Cannot map from pixel format %s!\n",
1818 av_get_pix_fmt_name(src->format));
1819 err = AVERROR(EINVAL);
1823 if (!(f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ||
1824 !(f->tiling == VK_IMAGE_TILING_LINEAR)) {
1825 av_log(hwfc, AV_LOG_ERROR, "Unable to map frame, not host visible "
1827 err = AVERROR(EINVAL);
1831 dst->width = src->width;
1832 dst->height = src->height;
1834 for (int i = 0; i < planes; i++) {
1835 ret = vkMapMemory(hwctx->act_dev, f->mem[i], 0,
1836 VK_WHOLE_SIZE, 0, (void **)&dst->data[i]);
1837 if (ret != VK_SUCCESS) {
1838 av_log(hwfc, AV_LOG_ERROR, "Failed to map image memory: %s\n",
1840 err = AVERROR_EXTERNAL;
1846 /* Check if the memory contents matter */
1847 if (((flags & AV_HWFRAME_MAP_READ) || !(flags & AV_HWFRAME_MAP_OVERWRITE)) &&
1848 !(f->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1849 VkMappedMemoryRange map_mem_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1850 for (int i = 0; i < planes; i++) {
1851 map_mem_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1852 map_mem_ranges[i].size = VK_WHOLE_SIZE;
1853 map_mem_ranges[i].memory = f->mem[i];
1856 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, planes,
1858 if (ret != VK_SUCCESS) {
1859 av_log(hwfc, AV_LOG_ERROR, "Failed to invalidate memory: %s\n",
1861 err = AVERROR_EXTERNAL;
1866 for (int i = 0; i < planes; i++) {
1867 VkImageSubresource sub = {
1868 .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
1870 VkSubresourceLayout layout;
1871 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
1872 dst->linesize[i] = layout.rowPitch;
1878 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src,
1879 &vulkan_unmap_frame, map);
1886 for (int i = 0; i < mapped_mem_count; i++)
1887 vkUnmapMemory(hwctx->act_dev, f->mem[i]);
1894 static void vulkan_unmap_from(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1896 VulkanMapping *map = hwmap->priv;
1897 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1898 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1900 for (int i = 0; i < planes; i++) {
1901 vkDestroyImage(hwctx->act_dev, map->frame->img[i], hwctx->alloc);
1902 vkFreeMemory(hwctx->act_dev, map->frame->mem[i], hwctx->alloc);
1903 vkDestroySemaphore(hwctx->act_dev, map->frame->sem[i], hwctx->alloc);
1906 av_freep(&map->frame);
1909 static const struct {
1910 uint32_t drm_fourcc;
1912 } vulkan_drm_format_map[] = {
1913 { DRM_FORMAT_R8, VK_FORMAT_R8_UNORM },
1914 { DRM_FORMAT_R16, VK_FORMAT_R16_UNORM },
1915 { DRM_FORMAT_GR88, VK_FORMAT_R8G8_UNORM },
1916 { DRM_FORMAT_RG88, VK_FORMAT_R8G8_UNORM },
1917 { DRM_FORMAT_GR1616, VK_FORMAT_R16G16_UNORM },
1918 { DRM_FORMAT_RG1616, VK_FORMAT_R16G16_UNORM },
1919 { DRM_FORMAT_ARGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1920 { DRM_FORMAT_XRGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1921 { DRM_FORMAT_ABGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1922 { DRM_FORMAT_XBGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1925 static inline VkFormat drm_to_vulkan_fmt(uint32_t drm_fourcc)
1927 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
1928 if (vulkan_drm_format_map[i].drm_fourcc == drm_fourcc)
1929 return vulkan_drm_format_map[i].vk_format;
1930 return VK_FORMAT_UNDEFINED;
1933 static int vulkan_map_from_drm_frame_desc(AVHWFramesContext *hwfc, AVVkFrame **frame,
1934 AVDRMFrameDescriptor *desc)
1939 int bind_counts = 0;
1940 AVHWDeviceContext *ctx = hwfc->device_ctx;
1941 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1942 VulkanDevicePriv *p = ctx->internal->priv;
1943 const AVPixFmtDescriptor *fmt_desc = av_pix_fmt_desc_get(hwfc->sw_format);
1944 const int has_modifiers = p->extensions & EXT_DRM_MODIFIER_FLAGS;
1945 VkSubresourceLayout plane_data[AV_NUM_DATA_POINTERS] = { 0 };
1946 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { 0 };
1947 VkBindImagePlaneMemoryInfo plane_info[AV_NUM_DATA_POINTERS] = { 0 };
1948 VkExternalMemoryHandleTypeFlagBits htype = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
1950 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdPropertiesKHR);
1952 for (int i = 0; i < desc->nb_layers; i++) {
1953 if (drm_to_vulkan_fmt(desc->layers[i].format) == VK_FORMAT_UNDEFINED) {
1954 av_log(ctx, AV_LOG_ERROR, "Unsupported DMABUF layer format %#08x!\n",
1955 desc->layers[i].format);
1956 return AVERROR(EINVAL);
1960 if (!(f = av_vk_frame_alloc())) {
1961 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1962 err = AVERROR(ENOMEM);
1966 for (int i = 0; i < desc->nb_objects; i++) {
1967 VkMemoryFdPropertiesKHR fdmp = {
1968 .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,
1970 VkMemoryRequirements req = {
1971 .size = desc->objects[i].size,
1973 VkImportMemoryFdInfoKHR idesc = {
1974 .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
1975 .handleType = htype,
1976 .fd = dup(desc->objects[i].fd),
1979 ret = pfn_vkGetMemoryFdPropertiesKHR(hwctx->act_dev, htype,
1981 if (ret != VK_SUCCESS) {
1982 av_log(hwfc, AV_LOG_ERROR, "Failed to get FD properties: %s\n",
1984 err = AVERROR_EXTERNAL;
1989 req.memoryTypeBits = fdmp.memoryTypeBits;
1991 err = alloc_mem(ctx, &req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1992 &idesc, &f->flags, &f->mem[i]);
1998 f->size[i] = desc->objects[i].size;
2001 f->tiling = has_modifiers ? VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT :
2002 desc->objects[0].format_modifier == DRM_FORMAT_MOD_LINEAR ?
2003 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
2005 for (int i = 0; i < desc->nb_layers; i++) {
2006 const int planes = desc->layers[i].nb_planes;
2007 const int signal_p = has_modifiers && (planes > 1);
2009 VkImageDrmFormatModifierExplicitCreateInfoEXT drm_info = {
2010 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
2011 .drmFormatModifier = desc->objects[0].format_modifier,
2012 .drmFormatModifierPlaneCount = planes,
2013 .pPlaneLayouts = (const VkSubresourceLayout *)&plane_data,
2016 VkExternalMemoryImageCreateInfo einfo = {
2017 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
2018 .pNext = has_modifiers ? &drm_info : NULL,
2019 .handleTypes = htype,
2022 VkSemaphoreCreateInfo sem_spawn = {
2023 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
2026 const int p_w = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, fmt_desc->log2_chroma_w) : hwfc->width;
2027 const int p_h = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, fmt_desc->log2_chroma_h) : hwfc->height;
2029 VkImageCreateInfo image_create_info = {
2030 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
2032 .imageType = VK_IMAGE_TYPE_2D,
2033 .format = drm_to_vulkan_fmt(desc->layers[i].format),
2034 .extent.width = p_w,
2035 .extent.height = p_h,
2039 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
2040 .tiling = f->tiling,
2041 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, /* specs say so */
2042 .usage = DEFAULT_USAGE_FLAGS,
2043 .samples = VK_SAMPLE_COUNT_1_BIT,
2044 .pQueueFamilyIndices = p->qfs,
2045 .queueFamilyIndexCount = p->num_qfs,
2046 .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
2047 VK_SHARING_MODE_EXCLUSIVE,
2050 for (int j = 0; j < planes; j++) {
2051 plane_data[j].offset = desc->layers[i].planes[j].offset;
2052 plane_data[j].rowPitch = desc->layers[i].planes[j].pitch;
2053 plane_data[j].size = 0; /* The specs say so for all 3 */
2054 plane_data[j].arrayPitch = 0;
2055 plane_data[j].depthPitch = 0;
2059 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
2060 hwctx->alloc, &f->img[i]);
2061 if (ret != VK_SUCCESS) {
2062 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
2064 err = AVERROR(EINVAL);
2068 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
2069 hwctx->alloc, &f->sem[i]);
2070 if (ret != VK_SUCCESS) {
2071 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
2073 return AVERROR_EXTERNAL;
2076 /* We'd import a semaphore onto the one we created using
2077 * vkImportSemaphoreFdKHR but unfortunately neither DRM nor VAAPI
2078 * offer us anything we could import and sync with, so instead
2079 * just signal the semaphore we created. */
2081 f->layout[i] = image_create_info.initialLayout;
2084 for (int j = 0; j < planes; j++) {
2085 VkImageAspectFlagBits aspect = j == 0 ? VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2086 j == 1 ? VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT :
2087 VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT;
2089 plane_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO;
2090 plane_info[bind_counts].planeAspect = aspect;
2092 bind_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
2093 bind_info[bind_counts].pNext = signal_p ? &plane_info[bind_counts] : NULL;
2094 bind_info[bind_counts].image = f->img[i];
2095 bind_info[bind_counts].memory = f->mem[desc->layers[i].planes[j].object_index];
2096 bind_info[bind_counts].memoryOffset = desc->layers[i].planes[j].offset;
2101 /* Bind the allocated memory to the images */
2102 ret = vkBindImageMemory2(hwctx->act_dev, bind_counts, bind_info);
2103 if (ret != VK_SUCCESS) {
2104 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
2106 return AVERROR_EXTERNAL;
2109 /* NOTE: This is completely uneccesary and unneeded once we can import
2110 * semaphores from DRM. Otherwise we have to activate the semaphores.
2111 * We're reusing the exec context that's also used for uploads/downloads. */
2112 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_RO_SHADER);
2121 for (int i = 0; i < desc->nb_layers; i++) {
2122 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
2123 vkDestroySemaphore(hwctx->act_dev, f->sem[i], hwctx->alloc);
2125 for (int i = 0; i < desc->nb_objects; i++)
2126 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
2133 static int vulkan_map_from_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2134 const AVFrame *src, int flags)
2138 VulkanMapping *map = NULL;
2140 err = vulkan_map_from_drm_frame_desc(hwfc, &f,
2141 (AVDRMFrameDescriptor *)src->data[0]);
2145 /* The unmapping function will free this */
2146 dst->data[0] = (uint8_t *)f;
2147 dst->width = src->width;
2148 dst->height = src->height;
2150 map = av_mallocz(sizeof(VulkanMapping));
2157 err = ff_hwframe_map_create(dst->hw_frames_ctx, dst, src,
2158 &vulkan_unmap_from, map);
2162 av_log(hwfc, AV_LOG_DEBUG, "Mapped DRM object to Vulkan!\n");
2167 vulkan_frame_free(hwfc->device_ctx->hwctx, (uint8_t *)f);
2173 static int vulkan_map_from_vaapi(AVHWFramesContext *dst_fc,
2174 AVFrame *dst, const AVFrame *src,
2178 AVFrame *tmp = av_frame_alloc();
2179 AVHWFramesContext *vaapi_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2180 AVVAAPIDeviceContext *vaapi_ctx = vaapi_fc->device_ctx->hwctx;
2181 VASurfaceID surface_id = (VASurfaceID)(uintptr_t)src->data[3];
2184 return AVERROR(ENOMEM);
2186 /* We have to sync since like the previous comment said, no semaphores */
2187 vaSyncSurface(vaapi_ctx->display, surface_id);
2189 tmp->format = AV_PIX_FMT_DRM_PRIME;
2191 err = av_hwframe_map(tmp, src, flags);
2195 err = vulkan_map_from_drm(dst_fc, dst, tmp, flags);
2199 err = ff_hwframe_map_replace(dst, src);
2202 av_frame_free(&tmp);
2209 static int vulkan_export_to_cuda(AVHWFramesContext *hwfc,
2210 AVBufferRef *cuda_hwfc,
2211 const AVFrame *frame)
2216 AVVkFrameInternal *dst_int;
2217 AVHWDeviceContext *ctx = hwfc->device_ctx;
2218 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2219 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2220 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2221 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2222 VK_LOAD_PFN(hwctx->inst, vkGetSemaphoreFdKHR);
2224 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)cuda_hwfc->data;
2225 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2226 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2227 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2228 CudaFunctions *cu = cu_internal->cuda_dl;
2229 CUarray_format cufmt = desc->comp[0].depth > 8 ? CU_AD_FORMAT_UNSIGNED_INT16 :
2230 CU_AD_FORMAT_UNSIGNED_INT8;
2232 dst_f = (AVVkFrame *)frame->data[0];
2234 dst_int = dst_f->internal;
2235 if (!dst_int || !dst_int->cuda_fc_ref) {
2236 if (!dst_f->internal)
2237 dst_f->internal = dst_int = av_mallocz(sizeof(*dst_f->internal));
2240 err = AVERROR(ENOMEM);
2244 dst_int->cuda_fc_ref = av_buffer_ref(cuda_hwfc);
2245 if (!dst_int->cuda_fc_ref) {
2246 err = AVERROR(ENOMEM);
2250 for (int i = 0; i < planes; i++) {
2251 CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC tex_desc = {
2254 .Width = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2256 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2260 .NumChannels = 1 + ((planes == 2) && i),
2265 CUDA_EXTERNAL_MEMORY_HANDLE_DESC ext_desc = {
2266 .type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD,
2267 .size = dst_f->size[i],
2269 VkMemoryGetFdInfoKHR export_info = {
2270 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2271 .memory = dst_f->mem[i],
2272 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR,
2274 VkSemaphoreGetFdInfoKHR sem_export = {
2275 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR,
2276 .semaphore = dst_f->sem[i],
2277 .handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
2279 CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC ext_sem_desc = {
2280 .type = CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD,
2283 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2284 &ext_desc.handle.fd);
2285 if (ret != VK_SUCCESS) {
2286 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2287 err = AVERROR_EXTERNAL;
2291 ret = CHECK_CU(cu->cuImportExternalMemory(&dst_int->ext_mem[i], &ext_desc));
2293 err = AVERROR_EXTERNAL;
2297 ret = CHECK_CU(cu->cuExternalMemoryGetMappedMipmappedArray(&dst_int->cu_mma[i],
2298 dst_int->ext_mem[i],
2301 err = AVERROR_EXTERNAL;
2305 ret = CHECK_CU(cu->cuMipmappedArrayGetLevel(&dst_int->cu_array[i],
2306 dst_int->cu_mma[i], 0));
2308 err = AVERROR_EXTERNAL;
2312 ret = pfn_vkGetSemaphoreFdKHR(hwctx->act_dev, &sem_export,
2313 &ext_sem_desc.handle.fd);
2314 if (ret != VK_SUCCESS) {
2315 av_log(ctx, AV_LOG_ERROR, "Failed to export semaphore: %s\n",
2317 err = AVERROR_EXTERNAL;
2321 ret = CHECK_CU(cu->cuImportExternalSemaphore(&dst_int->cu_sem[i],
2324 err = AVERROR_EXTERNAL;
2336 static int vulkan_transfer_data_from_cuda(AVHWFramesContext *hwfc,
2337 AVFrame *dst, const AVFrame *src)
2343 AVVkFrameInternal *dst_int;
2344 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2345 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2347 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2348 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2349 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2350 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2351 CudaFunctions *cu = cu_internal->cuda_dl;
2352 CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS s_w_par[AV_NUM_DATA_POINTERS] = { 0 };
2353 CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS s_s_par[AV_NUM_DATA_POINTERS] = { 0 };
2355 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2357 err = AVERROR_EXTERNAL;
2361 dst_f = (AVVkFrame *)dst->data[0];
2363 ret = vulkan_export_to_cuda(hwfc, src->hw_frames_ctx, dst);
2367 dst_int = dst_f->internal;
2369 ret = CHECK_CU(cu->cuWaitExternalSemaphoresAsync(dst_int->cu_sem, s_w_par,
2370 planes, cuda_dev->stream));
2372 err = AVERROR_EXTERNAL;
2376 for (int i = 0; i < planes; i++) {
2377 CUDA_MEMCPY2D cpy = {
2378 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
2379 .srcDevice = (CUdeviceptr)src->data[i],
2380 .srcPitch = src->linesize[i],
2383 .dstMemoryType = CU_MEMORYTYPE_ARRAY,
2384 .dstArray = dst_int->cu_array[i],
2385 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2386 : hwfc->width) * desc->comp[i].step,
2387 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2391 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2393 err = AVERROR_EXTERNAL;
2398 ret = CHECK_CU(cu->cuSignalExternalSemaphoresAsync(dst_int->cu_sem, s_s_par,
2399 planes, cuda_dev->stream));
2401 err = AVERROR_EXTERNAL;
2405 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2407 av_log(hwfc, AV_LOG_VERBOSE, "Transfered CUDA image to Vulkan!\n");
2412 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2413 vulkan_free_internal(dst_int);
2414 dst_f->internal = NULL;
2415 av_buffer_unref(&dst->buf[0]);
2420 static int vulkan_map_to(AVHWFramesContext *hwfc, AVFrame *dst,
2421 const AVFrame *src, int flags)
2423 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2425 switch (src->format) {
2428 case AV_PIX_FMT_VAAPI:
2429 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2430 return vulkan_map_from_vaapi(hwfc, dst, src, flags);
2432 case AV_PIX_FMT_DRM_PRIME:
2433 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2434 return vulkan_map_from_drm(hwfc, dst, src, flags);
2437 return AVERROR(ENOSYS);
2442 typedef struct VulkanDRMMapping {
2443 AVDRMFrameDescriptor drm_desc;
2447 static void vulkan_unmap_to_drm(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
2449 AVDRMFrameDescriptor *drm_desc = hwmap->priv;
2451 for (int i = 0; i < drm_desc->nb_objects; i++)
2452 close(drm_desc->objects[i].fd);
2457 static inline uint32_t vulkan_fmt_to_drm(VkFormat vkfmt)
2459 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
2460 if (vulkan_drm_format_map[i].vk_format == vkfmt)
2461 return vulkan_drm_format_map[i].drm_fourcc;
2462 return DRM_FORMAT_INVALID;
2465 static int vulkan_map_to_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2466 const AVFrame *src, int flags)
2470 AVVkFrame *f = (AVVkFrame *)src->data[0];
2471 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2472 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
2473 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2474 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2475 VkImageDrmFormatModifierPropertiesEXT drm_mod = {
2476 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT,
2479 AVDRMFrameDescriptor *drm_desc = av_mallocz(sizeof(*drm_desc));
2481 return AVERROR(ENOMEM);
2483 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_EXTERNAL_EXPORT);
2487 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src, &vulkan_unmap_to_drm, drm_desc);
2491 if (p->extensions & EXT_DRM_MODIFIER_FLAGS) {
2492 VK_LOAD_PFN(hwctx->inst, vkGetImageDrmFormatModifierPropertiesEXT);
2493 ret = pfn_vkGetImageDrmFormatModifierPropertiesEXT(hwctx->act_dev, f->img[0],
2495 if (ret != VK_SUCCESS) {
2496 av_log(hwfc, AV_LOG_ERROR, "Failed to retrieve DRM format modifier!\n");
2497 err = AVERROR_EXTERNAL;
2502 for (int i = 0; (i < planes) && (f->mem[i]); i++) {
2503 VkMemoryGetFdInfoKHR export_info = {
2504 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2505 .memory = f->mem[i],
2506 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,
2509 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2510 &drm_desc->objects[i].fd);
2511 if (ret != VK_SUCCESS) {
2512 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2513 err = AVERROR_EXTERNAL;
2517 drm_desc->nb_objects++;
2518 drm_desc->objects[i].size = f->size[i];
2519 drm_desc->objects[i].format_modifier = drm_mod.drmFormatModifier;
2522 drm_desc->nb_layers = planes;
2523 for (int i = 0; i < drm_desc->nb_layers; i++) {
2524 VkSubresourceLayout layout;
2525 VkImageSubresource sub = {
2526 .aspectMask = p->extensions & EXT_DRM_MODIFIER_FLAGS ?
2527 VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2528 VK_IMAGE_ASPECT_COLOR_BIT,
2530 VkFormat plane_vkfmt = av_vkfmt_from_pixfmt(hwfc->sw_format)[i];
2532 drm_desc->layers[i].format = vulkan_fmt_to_drm(plane_vkfmt);
2533 drm_desc->layers[i].nb_planes = 1;
2535 if (drm_desc->layers[i].format == DRM_FORMAT_INVALID) {
2536 av_log(hwfc, AV_LOG_ERROR, "Cannot map to DRM layer, unsupported!\n");
2537 err = AVERROR_PATCHWELCOME;
2541 drm_desc->layers[i].planes[0].object_index = FFMIN(i, drm_desc->nb_objects - 1);
2543 if (f->tiling == VK_IMAGE_TILING_OPTIMAL)
2546 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
2547 drm_desc->layers[i].planes[0].offset = layout.offset;
2548 drm_desc->layers[i].planes[0].pitch = layout.rowPitch;
2551 dst->width = src->width;
2552 dst->height = src->height;
2553 dst->data[0] = (uint8_t *)drm_desc;
2555 av_log(hwfc, AV_LOG_VERBOSE, "Mapped AVVkFrame to a DRM object!\n");
2565 static int vulkan_map_to_vaapi(AVHWFramesContext *hwfc, AVFrame *dst,
2566 const AVFrame *src, int flags)
2569 AVFrame *tmp = av_frame_alloc();
2571 return AVERROR(ENOMEM);
2573 tmp->format = AV_PIX_FMT_DRM_PRIME;
2575 err = vulkan_map_to_drm(hwfc, tmp, src, flags);
2579 err = av_hwframe_map(dst, tmp, flags);
2583 err = ff_hwframe_map_replace(dst, src);
2586 av_frame_free(&tmp);
2592 static int vulkan_map_from(AVHWFramesContext *hwfc, AVFrame *dst,
2593 const AVFrame *src, int flags)
2595 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2597 switch (dst->format) {
2599 case AV_PIX_FMT_DRM_PRIME:
2600 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2601 return vulkan_map_to_drm(hwfc, dst, src, flags);
2603 case AV_PIX_FMT_VAAPI:
2604 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2605 return vulkan_map_to_vaapi(hwfc, dst, src, flags);
2609 return vulkan_map_frame_to_mem(hwfc, dst, src, flags);
2613 typedef struct ImageBuffer {
2616 VkMemoryPropertyFlagBits flags;
2619 static void free_buf(void *opaque, uint8_t *data)
2621 AVHWDeviceContext *ctx = opaque;
2622 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2623 ImageBuffer *vkbuf = (ImageBuffer *)data;
2626 vkDestroyBuffer(hwctx->act_dev, vkbuf->buf, hwctx->alloc);
2628 vkFreeMemory(hwctx->act_dev, vkbuf->mem, hwctx->alloc);
2633 static int create_buf(AVHWDeviceContext *ctx, AVBufferRef **buf,
2634 int height, int *stride, VkBufferUsageFlags usage,
2635 VkMemoryPropertyFlagBits flags, void *create_pnext,
2640 VkMemoryRequirements req;
2641 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2642 VulkanDevicePriv *p = ctx->internal->priv;
2644 VkBufferCreateInfo buf_spawn = {
2645 .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
2646 .pNext = create_pnext,
2648 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
2651 ImageBuffer *vkbuf = av_mallocz(sizeof(*vkbuf));
2653 return AVERROR(ENOMEM);
2655 *stride = FFALIGN(*stride, p->props.limits.optimalBufferCopyRowPitchAlignment);
2656 buf_spawn.size = height*(*stride);
2658 ret = vkCreateBuffer(hwctx->act_dev, &buf_spawn, NULL, &vkbuf->buf);
2659 if (ret != VK_SUCCESS) {
2660 av_log(ctx, AV_LOG_ERROR, "Failed to create buffer: %s\n",
2662 return AVERROR_EXTERNAL;
2665 vkGetBufferMemoryRequirements(hwctx->act_dev, vkbuf->buf, &req);
2667 err = alloc_mem(ctx, &req, flags, alloc_pnext, &vkbuf->flags, &vkbuf->mem);
2671 ret = vkBindBufferMemory(hwctx->act_dev, vkbuf->buf, vkbuf->mem, 0);
2672 if (ret != VK_SUCCESS) {
2673 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory to buffer: %s\n",
2675 free_buf(ctx, (uint8_t *)vkbuf);
2676 return AVERROR_EXTERNAL;
2679 *buf = av_buffer_create((uint8_t *)vkbuf, sizeof(*vkbuf), free_buf, ctx, 0);
2681 free_buf(ctx, (uint8_t *)vkbuf);
2682 return AVERROR(ENOMEM);
2688 static int map_buffers(AVHWDeviceContext *ctx, AVBufferRef **bufs, uint8_t *mem[],
2689 int nb_buffers, int invalidate)
2692 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2693 VkMappedMemoryRange invalidate_ctx[AV_NUM_DATA_POINTERS];
2694 int invalidate_count = 0;
2696 for (int i = 0; i < nb_buffers; i++) {
2697 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2698 ret = vkMapMemory(hwctx->act_dev, vkbuf->mem, 0,
2699 VK_WHOLE_SIZE, 0, (void **)&mem[i]);
2700 if (ret != VK_SUCCESS) {
2701 av_log(ctx, AV_LOG_ERROR, "Failed to map buffer memory: %s\n",
2703 return AVERROR_EXTERNAL;
2710 for (int i = 0; i < nb_buffers; i++) {
2711 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2712 const VkMappedMemoryRange ival_buf = {
2713 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2714 .memory = vkbuf->mem,
2715 .size = VK_WHOLE_SIZE,
2717 if (vkbuf->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2719 invalidate_ctx[invalidate_count++] = ival_buf;
2722 if (invalidate_count) {
2723 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, invalidate_count,
2725 if (ret != VK_SUCCESS)
2726 av_log(ctx, AV_LOG_WARNING, "Failed to invalidate memory: %s\n",
2733 static int unmap_buffers(AVHWDeviceContext *ctx, AVBufferRef **bufs,
2734 int nb_buffers, int flush)
2738 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2739 VkMappedMemoryRange flush_ctx[AV_NUM_DATA_POINTERS];
2740 int flush_count = 0;
2743 for (int i = 0; i < nb_buffers; i++) {
2744 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2745 const VkMappedMemoryRange flush_buf = {
2746 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2747 .memory = vkbuf->mem,
2748 .size = VK_WHOLE_SIZE,
2750 if (vkbuf->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2752 flush_ctx[flush_count++] = flush_buf;
2757 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, flush_count, flush_ctx);
2758 if (ret != VK_SUCCESS) {
2759 av_log(ctx, AV_LOG_ERROR, "Failed to flush memory: %s\n",
2761 err = AVERROR_EXTERNAL; /* We still want to try to unmap them */
2765 for (int i = 0; i < nb_buffers; i++) {
2766 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2767 vkUnmapMemory(hwctx->act_dev, vkbuf->mem);
2773 static int transfer_image_buf(AVHWDeviceContext *ctx, const AVFrame *f,
2774 AVBufferRef **bufs, const int *buf_stride, int w,
2775 int h, enum AVPixelFormat pix_fmt, int to_buf)
2778 AVVkFrame *frame = (AVVkFrame *)f->data[0];
2779 VulkanDevicePriv *s = ctx->internal->priv;
2782 VkPipelineStageFlagBits sem_wait_dst[AV_NUM_DATA_POINTERS];
2784 const int planes = av_pix_fmt_count_planes(pix_fmt);
2785 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2787 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
2788 VkCommandBuffer cmd_buf = get_buf_exec_ctx(ctx, &s->cmd);
2790 VkSubmitInfo s_info = {
2791 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
2792 .pSignalSemaphores = frame->sem,
2793 .pWaitSemaphores = frame->sem,
2794 .pWaitDstStageMask = sem_wait_dst,
2795 .signalSemaphoreCount = planes,
2796 .waitSemaphoreCount = planes,
2799 if ((err = wait_start_exec_ctx(ctx, &s->cmd)))
2802 /* Change the image layout to something more optimal for transfers */
2803 for (int i = 0; i < planes; i++) {
2804 VkImageLayout new_layout = to_buf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL :
2805 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
2806 VkAccessFlags new_access = to_buf ? VK_ACCESS_TRANSFER_READ_BIT :
2807 VK_ACCESS_TRANSFER_WRITE_BIT;
2809 sem_wait_dst[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
2811 /* If the layout matches and we have read access skip the barrier */
2812 if ((frame->layout[i] == new_layout) && (frame->access[i] & new_access))
2815 img_bar[bar_num].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
2816 img_bar[bar_num].srcAccessMask = 0x0;
2817 img_bar[bar_num].dstAccessMask = new_access;
2818 img_bar[bar_num].oldLayout = frame->layout[i];
2819 img_bar[bar_num].newLayout = new_layout;
2820 img_bar[bar_num].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2821 img_bar[bar_num].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2822 img_bar[bar_num].image = frame->img[i];
2823 img_bar[bar_num].subresourceRange.levelCount = 1;
2824 img_bar[bar_num].subresourceRange.layerCount = 1;
2825 img_bar[bar_num].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2827 frame->layout[i] = img_bar[bar_num].newLayout;
2828 frame->access[i] = img_bar[bar_num].dstAccessMask;
2834 vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
2835 VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
2836 0, NULL, 0, NULL, bar_num, img_bar);
2838 /* Schedule a copy for each plane */
2839 for (int i = 0; i < planes; i++) {
2840 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2841 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
2842 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
2843 VkBufferImageCopy buf_reg = {
2845 /* Buffer stride isn't in bytes, it's in samples, the implementation
2846 * uses the image's VkFormat to know how many bytes per sample
2847 * the buffer has. So we have to convert by dividing. Stupid.
2848 * Won't work with YUVA or other planar formats with alpha. */
2849 .bufferRowLength = buf_stride[i] / desc->comp[i].step,
2850 .bufferImageHeight = p_h,
2851 .imageSubresource.layerCount = 1,
2852 .imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
2853 .imageOffset = { 0, 0, 0, },
2854 .imageExtent = { p_w, p_h, 1, },
2858 vkCmdCopyImageToBuffer(cmd_buf, frame->img[i], frame->layout[i],
2859 vkbuf->buf, 1, &buf_reg);
2861 vkCmdCopyBufferToImage(cmd_buf, vkbuf->buf, frame->img[i],
2862 frame->layout[i], 1, &buf_reg);
2865 /* When uploading, do this asynchronously if the source is refcounted by
2866 * keeping the buffers as a submission dependency.
2867 * The hwcontext is guaranteed to not be freed until all frames are freed
2868 * in the frames_unint function.
2869 * When downloading to buffer, do this synchronously and wait for the
2870 * queue submission to finish executing */
2873 for (ref = 0; ref < AV_NUM_DATA_POINTERS; ref++) {
2876 if ((err = add_buf_dep_exec_ctx(hwfc, &s->cmd, &f->buf[ref], 1)))
2879 if (ref && (err = add_buf_dep_exec_ctx(hwfc, &s->cmd, bufs, planes)))
2881 return submit_exec_ctx(hwfc, &s->cmd, &s_info, !ref);
2883 return submit_exec_ctx(hwfc, &s->cmd, &s_info, 1);
2887 /* Technically we can use VK_EXT_external_memory_host to upload and download,
2888 * however the alignment requirements make this unfeasible as both the pointer
2889 * and the size of each plane need to be aligned to the minimum alignment
2890 * requirement, which on all current implementations (anv, radv) is 4096.
2891 * If the requirement gets relaxed (unlikely) this can easily be implemented. */
2892 static int vulkan_transfer_data_from_mem(AVHWFramesContext *hwfc, AVFrame *dst,
2897 AVVkFrame *f = (AVVkFrame *)dst->data[0];
2898 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
2899 AVBufferRef *bufs[AV_NUM_DATA_POINTERS] = { 0 };
2900 const int planes = av_pix_fmt_count_planes(src->format);
2901 int log2_chroma = av_pix_fmt_desc_get(src->format)->log2_chroma_h;
2903 if ((src->format != AV_PIX_FMT_NONE && !av_vkfmt_from_pixfmt(src->format))) {
2904 av_log(hwfc, AV_LOG_ERROR, "Unsupported source pixel format!\n");
2905 return AVERROR(EINVAL);
2908 if (src->width > hwfc->width || src->height > hwfc->height)
2909 return AVERROR(EINVAL);
2911 /* For linear, host visiable images */
2912 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
2913 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
2914 AVFrame *map = av_frame_alloc();
2916 return AVERROR(ENOMEM);
2917 map->format = src->format;
2919 err = vulkan_map_frame_to_mem(hwfc, map, dst, AV_HWFRAME_MAP_WRITE);
2923 err = av_frame_copy(map, src);
2924 av_frame_free(&map);
2928 /* Create buffers */
2929 for (int i = 0; i < planes; i++) {
2930 int h = src->height;
2931 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
2933 tmp.linesize[i] = FFABS(src->linesize[i]);
2934 err = create_buf(dev_ctx, &bufs[i], p_height,
2935 &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
2936 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
2941 /* Map, copy image to buffer, unmap */
2942 if ((err = map_buffers(dev_ctx, bufs, tmp.data, planes, 0)))
2945 av_image_copy(tmp.data, tmp.linesize, (const uint8_t **)src->data,
2946 src->linesize, src->format, src->width, src->height);
2948 if ((err = unmap_buffers(dev_ctx, bufs, planes, 1)))
2951 /* Copy buffers to image */
2952 err = transfer_image_buf(dev_ctx, dst, bufs, tmp.linesize,
2953 src->width, src->height, src->format, 0);
2956 for (int i = 0; i < planes; i++)
2957 av_buffer_unref(&bufs[i]);
2962 static int vulkan_transfer_data_to(AVHWFramesContext *hwfc, AVFrame *dst,
2965 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2967 switch (src->format) {
2969 case AV_PIX_FMT_CUDA:
2970 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
2971 (p->extensions & EXT_EXTERNAL_FD_SEM))
2972 return vulkan_transfer_data_from_cuda(hwfc, dst, src);
2975 if (src->hw_frames_ctx)
2976 return AVERROR(ENOSYS);
2978 return vulkan_transfer_data_from_mem(hwfc, dst, src);
2983 static int vulkan_transfer_data_to_cuda(AVHWFramesContext *hwfc, AVFrame *dst,
2990 AVVkFrameInternal *dst_int;
2991 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2992 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2994 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)dst->hw_frames_ctx->data;
2995 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2996 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2997 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2998 CudaFunctions *cu = cu_internal->cuda_dl;
3000 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
3002 err = AVERROR_EXTERNAL;
3006 dst_f = (AVVkFrame *)src->data[0];
3008 err = vulkan_export_to_cuda(hwfc, dst->hw_frames_ctx, src);
3013 dst_int = dst_f->internal;
3015 for (int i = 0; i < planes; i++) {
3016 CUDA_MEMCPY2D cpy = {
3017 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
3018 .dstDevice = (CUdeviceptr)dst->data[i],
3019 .dstPitch = dst->linesize[i],
3022 .srcMemoryType = CU_MEMORYTYPE_ARRAY,
3023 .srcArray = dst_int->cu_array[i],
3024 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
3025 : hwfc->width) * desc->comp[i].step,
3026 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
3030 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
3032 err = AVERROR_EXTERNAL;
3037 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
3039 av_log(hwfc, AV_LOG_VERBOSE, "Transfered Vulkan image to CUDA!\n");
3044 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
3045 vulkan_free_internal(dst_int);
3046 dst_f->internal = NULL;
3047 av_buffer_unref(&dst->buf[0]);
3052 static int vulkan_transfer_data_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
3057 AVVkFrame *f = (AVVkFrame *)src->data[0];
3058 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
3059 AVBufferRef *bufs[AV_NUM_DATA_POINTERS] = { 0 };
3060 const int planes = av_pix_fmt_count_planes(dst->format);
3061 int log2_chroma = av_pix_fmt_desc_get(dst->format)->log2_chroma_h;
3063 if (dst->width > hwfc->width || dst->height > hwfc->height)
3064 return AVERROR(EINVAL);
3066 /* For linear, host visiable images */
3067 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
3068 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
3069 AVFrame *map = av_frame_alloc();
3071 return AVERROR(ENOMEM);
3072 map->format = dst->format;
3074 err = vulkan_map_frame_to_mem(hwfc, map, src, AV_HWFRAME_MAP_READ);
3078 err = av_frame_copy(dst, map);
3079 av_frame_free(&map);
3083 /* Create buffers */
3084 for (int i = 0; i < planes; i++) {
3085 int h = dst->height;
3086 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
3088 tmp.linesize[i] = FFABS(dst->linesize[i]);
3089 err = create_buf(dev_ctx, &bufs[i], p_height,
3090 &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_DST_BIT,
3091 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
3096 /* Copy image to buffer */
3097 if ((err = transfer_image_buf(dev_ctx, src, bufs, tmp.linesize,
3098 dst->width, dst->height, dst->format, 1)))
3101 /* Map, copy buffer to frame, unmap */
3102 if ((err = map_buffers(dev_ctx, bufs, tmp.data, planes, 1)))
3105 av_image_copy(dst->data, dst->linesize, (const uint8_t **)tmp.data,
3106 tmp.linesize, dst->format, dst->width, dst->height);
3108 err = unmap_buffers(dev_ctx, bufs, planes, 0);
3111 for (int i = 0; i < planes; i++)
3112 av_buffer_unref(&bufs[i]);
3117 static int vulkan_transfer_data_from(AVHWFramesContext *hwfc, AVFrame *dst,
3120 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
3122 switch (dst->format) {
3124 case AV_PIX_FMT_CUDA:
3125 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
3126 (p->extensions & EXT_EXTERNAL_FD_SEM))
3127 return vulkan_transfer_data_to_cuda(hwfc, dst, src);
3130 if (dst->hw_frames_ctx)
3131 return AVERROR(ENOSYS);
3133 return vulkan_transfer_data_to_mem(hwfc, dst, src);
3137 AVVkFrame *av_vk_frame_alloc(void)
3139 return av_mallocz(sizeof(AVVkFrame));
3142 const HWContextType ff_hwcontext_type_vulkan = {
3143 .type = AV_HWDEVICE_TYPE_VULKAN,
3146 .device_hwctx_size = sizeof(AVVulkanDeviceContext),
3147 .device_priv_size = sizeof(VulkanDevicePriv),
3148 .frames_hwctx_size = sizeof(AVVulkanFramesContext),
3149 .frames_priv_size = sizeof(VulkanFramesPriv),
3151 .device_init = &vulkan_device_init,
3152 .device_create = &vulkan_device_create,
3153 .device_derive = &vulkan_device_derive,
3155 .frames_get_constraints = &vulkan_frames_get_constraints,
3156 .frames_init = vulkan_frames_init,
3157 .frames_get_buffer = vulkan_get_buffer,
3158 .frames_uninit = vulkan_frames_uninit,
3160 .transfer_get_formats = vulkan_transfer_get_formats,
3161 .transfer_data_to = vulkan_transfer_data_to,
3162 .transfer_data_from = vulkan_transfer_data_from,
3164 .map_to = vulkan_map_to,
3165 .map_from = vulkan_map_from,
3167 .pix_fmts = (const enum AVPixelFormat []) {