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;
1703 /* Default pool flags */
1704 hwctx->tiling = hwctx->tiling ? hwctx->tiling : p->use_linear_images ?
1705 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1707 hwctx->usage |= DEFAULT_USAGE_FLAGS;
1709 err = create_exec_ctx(hwfc->device_ctx, &fp->cmd,
1710 dev_hwctx->queue_family_tx_index,
1711 GET_QUEUE_COUNT(dev_hwctx, 0, 0, 1));
1715 /* Test to see if allocation will fail */
1716 err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1717 hwctx->create_pnext);
1719 free_exec_ctx(hwfc->device_ctx, &p->cmd);
1723 vulkan_frame_free(hwfc, (uint8_t *)f);
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);
1736 static int vulkan_get_buffer(AVHWFramesContext *hwfc, AVFrame *frame)
1738 frame->buf[0] = av_buffer_pool_get(hwfc->pool);
1740 return AVERROR(ENOMEM);
1742 frame->data[0] = frame->buf[0]->data;
1743 frame->format = AV_PIX_FMT_VULKAN;
1744 frame->width = hwfc->width;
1745 frame->height = hwfc->height;
1750 static int vulkan_transfer_get_formats(AVHWFramesContext *hwfc,
1751 enum AVHWFrameTransferDirection dir,
1752 enum AVPixelFormat **formats)
1754 enum AVPixelFormat *fmts = av_malloc_array(2, sizeof(*fmts));
1756 return AVERROR(ENOMEM);
1758 fmts[0] = hwfc->sw_format;
1759 fmts[1] = AV_PIX_FMT_NONE;
1765 typedef struct VulkanMapping {
1770 static void vulkan_unmap_frame(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1772 VulkanMapping *map = hwmap->priv;
1773 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1774 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1776 /* Check if buffer needs flushing */
1777 if ((map->flags & AV_HWFRAME_MAP_WRITE) &&
1778 !(map->frame->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1780 VkMappedMemoryRange flush_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1782 for (int i = 0; i < planes; i++) {
1783 flush_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1784 flush_ranges[i].memory = map->frame->mem[i];
1785 flush_ranges[i].size = VK_WHOLE_SIZE;
1788 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, planes,
1790 if (ret != VK_SUCCESS) {
1791 av_log(hwfc, AV_LOG_ERROR, "Failed to flush memory: %s\n",
1796 for (int i = 0; i < planes; i++)
1797 vkUnmapMemory(hwctx->act_dev, map->frame->mem[i]);
1802 static int vulkan_map_frame_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
1803 const AVFrame *src, int flags)
1806 int err, mapped_mem_count = 0;
1807 AVVkFrame *f = (AVVkFrame *)src->data[0];
1808 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1809 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1811 VulkanMapping *map = av_mallocz(sizeof(VulkanMapping));
1813 return AVERROR(EINVAL);
1815 if (src->format != AV_PIX_FMT_VULKAN) {
1816 av_log(hwfc, AV_LOG_ERROR, "Cannot map from pixel format %s!\n",
1817 av_get_pix_fmt_name(src->format));
1818 err = AVERROR(EINVAL);
1822 if (!(f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ||
1823 !(f->tiling == VK_IMAGE_TILING_LINEAR)) {
1824 av_log(hwfc, AV_LOG_ERROR, "Unable to map frame, not host visible "
1826 err = AVERROR(EINVAL);
1830 dst->width = src->width;
1831 dst->height = src->height;
1833 for (int i = 0; i < planes; i++) {
1834 ret = vkMapMemory(hwctx->act_dev, f->mem[i], 0,
1835 VK_WHOLE_SIZE, 0, (void **)&dst->data[i]);
1836 if (ret != VK_SUCCESS) {
1837 av_log(hwfc, AV_LOG_ERROR, "Failed to map image memory: %s\n",
1839 err = AVERROR_EXTERNAL;
1845 /* Check if the memory contents matter */
1846 if (((flags & AV_HWFRAME_MAP_READ) || !(flags & AV_HWFRAME_MAP_OVERWRITE)) &&
1847 !(f->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1848 VkMappedMemoryRange map_mem_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1849 for (int i = 0; i < planes; i++) {
1850 map_mem_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1851 map_mem_ranges[i].size = VK_WHOLE_SIZE;
1852 map_mem_ranges[i].memory = f->mem[i];
1855 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, planes,
1857 if (ret != VK_SUCCESS) {
1858 av_log(hwfc, AV_LOG_ERROR, "Failed to invalidate memory: %s\n",
1860 err = AVERROR_EXTERNAL;
1865 for (int i = 0; i < planes; i++) {
1866 VkImageSubresource sub = {
1867 .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
1869 VkSubresourceLayout layout;
1870 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
1871 dst->linesize[i] = layout.rowPitch;
1877 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src,
1878 &vulkan_unmap_frame, map);
1885 for (int i = 0; i < mapped_mem_count; i++)
1886 vkUnmapMemory(hwctx->act_dev, f->mem[i]);
1893 static void vulkan_unmap_from(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1895 VulkanMapping *map = hwmap->priv;
1896 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1897 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1899 for (int i = 0; i < planes; i++) {
1900 vkDestroyImage(hwctx->act_dev, map->frame->img[i], hwctx->alloc);
1901 vkFreeMemory(hwctx->act_dev, map->frame->mem[i], hwctx->alloc);
1902 vkDestroySemaphore(hwctx->act_dev, map->frame->sem[i], hwctx->alloc);
1905 av_freep(&map->frame);
1908 static const struct {
1909 uint32_t drm_fourcc;
1911 } vulkan_drm_format_map[] = {
1912 { DRM_FORMAT_R8, VK_FORMAT_R8_UNORM },
1913 { DRM_FORMAT_R16, VK_FORMAT_R16_UNORM },
1914 { DRM_FORMAT_GR88, VK_FORMAT_R8G8_UNORM },
1915 { DRM_FORMAT_RG88, VK_FORMAT_R8G8_UNORM },
1916 { DRM_FORMAT_GR1616, VK_FORMAT_R16G16_UNORM },
1917 { DRM_FORMAT_RG1616, VK_FORMAT_R16G16_UNORM },
1918 { DRM_FORMAT_ARGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1919 { DRM_FORMAT_XRGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1920 { DRM_FORMAT_ABGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1921 { DRM_FORMAT_XBGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1924 static inline VkFormat drm_to_vulkan_fmt(uint32_t drm_fourcc)
1926 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
1927 if (vulkan_drm_format_map[i].drm_fourcc == drm_fourcc)
1928 return vulkan_drm_format_map[i].vk_format;
1929 return VK_FORMAT_UNDEFINED;
1932 static int vulkan_map_from_drm_frame_desc(AVHWFramesContext *hwfc, AVVkFrame **frame,
1933 AVDRMFrameDescriptor *desc)
1938 int bind_counts = 0;
1939 AVHWDeviceContext *ctx = hwfc->device_ctx;
1940 AVVulkanDeviceContext *hwctx = ctx->hwctx;
1941 VulkanDevicePriv *p = ctx->internal->priv;
1942 const AVPixFmtDescriptor *fmt_desc = av_pix_fmt_desc_get(hwfc->sw_format);
1943 const int has_modifiers = p->extensions & EXT_DRM_MODIFIER_FLAGS;
1944 VkSubresourceLayout plane_data[AV_NUM_DATA_POINTERS] = { 0 };
1945 VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { 0 };
1946 VkBindImagePlaneMemoryInfo plane_info[AV_NUM_DATA_POINTERS] = { 0 };
1947 VkExternalMemoryHandleTypeFlagBits htype = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
1949 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdPropertiesKHR);
1951 for (int i = 0; i < desc->nb_layers; i++) {
1952 if (drm_to_vulkan_fmt(desc->layers[i].format) == VK_FORMAT_UNDEFINED) {
1953 av_log(ctx, AV_LOG_ERROR, "Unsupported DMABUF layer format %#08x!\n",
1954 desc->layers[i].format);
1955 return AVERROR(EINVAL);
1959 if (!(f = av_vk_frame_alloc())) {
1960 av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1961 err = AVERROR(ENOMEM);
1965 for (int i = 0; i < desc->nb_objects; i++) {
1966 VkMemoryFdPropertiesKHR fdmp = {
1967 .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,
1969 VkMemoryRequirements req = {
1970 .size = desc->objects[i].size,
1972 VkImportMemoryFdInfoKHR idesc = {
1973 .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
1974 .handleType = htype,
1975 .fd = dup(desc->objects[i].fd),
1978 ret = pfn_vkGetMemoryFdPropertiesKHR(hwctx->act_dev, htype,
1980 if (ret != VK_SUCCESS) {
1981 av_log(hwfc, AV_LOG_ERROR, "Failed to get FD properties: %s\n",
1983 err = AVERROR_EXTERNAL;
1988 req.memoryTypeBits = fdmp.memoryTypeBits;
1990 err = alloc_mem(ctx, &req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1991 &idesc, &f->flags, &f->mem[i]);
1997 f->size[i] = desc->objects[i].size;
2000 f->tiling = has_modifiers ? VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT :
2001 desc->objects[0].format_modifier == DRM_FORMAT_MOD_LINEAR ?
2002 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
2004 for (int i = 0; i < desc->nb_layers; i++) {
2005 const int planes = desc->layers[i].nb_planes;
2006 const int signal_p = has_modifiers && (planes > 1);
2008 VkImageDrmFormatModifierExplicitCreateInfoEXT drm_info = {
2009 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
2010 .drmFormatModifier = desc->objects[0].format_modifier,
2011 .drmFormatModifierPlaneCount = planes,
2012 .pPlaneLayouts = (const VkSubresourceLayout *)&plane_data,
2015 VkExternalMemoryImageCreateInfo einfo = {
2016 .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
2017 .pNext = has_modifiers ? &drm_info : NULL,
2018 .handleTypes = htype,
2021 VkSemaphoreCreateInfo sem_spawn = {
2022 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
2025 const int p_w = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, fmt_desc->log2_chroma_w) : hwfc->width;
2026 const int p_h = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, fmt_desc->log2_chroma_h) : hwfc->height;
2028 VkImageCreateInfo image_create_info = {
2029 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
2031 .imageType = VK_IMAGE_TYPE_2D,
2032 .format = drm_to_vulkan_fmt(desc->layers[i].format),
2033 .extent.width = p_w,
2034 .extent.height = p_h,
2038 .flags = VK_IMAGE_CREATE_ALIAS_BIT,
2039 .tiling = f->tiling,
2040 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, /* specs say so */
2041 .usage = DEFAULT_USAGE_FLAGS,
2042 .samples = VK_SAMPLE_COUNT_1_BIT,
2043 .pQueueFamilyIndices = p->qfs,
2044 .queueFamilyIndexCount = p->num_qfs,
2045 .sharingMode = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
2046 VK_SHARING_MODE_EXCLUSIVE,
2049 for (int j = 0; j < planes; j++) {
2050 plane_data[j].offset = desc->layers[i].planes[j].offset;
2051 plane_data[j].rowPitch = desc->layers[i].planes[j].pitch;
2052 plane_data[j].size = 0; /* The specs say so for all 3 */
2053 plane_data[j].arrayPitch = 0;
2054 plane_data[j].depthPitch = 0;
2058 ret = vkCreateImage(hwctx->act_dev, &image_create_info,
2059 hwctx->alloc, &f->img[i]);
2060 if (ret != VK_SUCCESS) {
2061 av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
2063 err = AVERROR(EINVAL);
2067 ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
2068 hwctx->alloc, &f->sem[i]);
2069 if (ret != VK_SUCCESS) {
2070 av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
2072 return AVERROR_EXTERNAL;
2075 /* We'd import a semaphore onto the one we created using
2076 * vkImportSemaphoreFdKHR but unfortunately neither DRM nor VAAPI
2077 * offer us anything we could import and sync with, so instead
2078 * just signal the semaphore we created. */
2080 f->layout[i] = image_create_info.initialLayout;
2083 for (int j = 0; j < planes; j++) {
2084 VkImageAspectFlagBits aspect = j == 0 ? VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2085 j == 1 ? VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT :
2086 VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT;
2088 plane_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO;
2089 plane_info[bind_counts].planeAspect = aspect;
2091 bind_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
2092 bind_info[bind_counts].pNext = signal_p ? &plane_info[bind_counts] : NULL;
2093 bind_info[bind_counts].image = f->img[i];
2094 bind_info[bind_counts].memory = f->mem[desc->layers[i].planes[j].object_index];
2095 bind_info[bind_counts].memoryOffset = desc->layers[i].planes[j].offset;
2100 /* Bind the allocated memory to the images */
2101 ret = vkBindImageMemory2(hwctx->act_dev, bind_counts, bind_info);
2102 if (ret != VK_SUCCESS) {
2103 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
2105 return AVERROR_EXTERNAL;
2108 /* NOTE: This is completely uneccesary and unneeded once we can import
2109 * semaphores from DRM. Otherwise we have to activate the semaphores.
2110 * We're reusing the exec context that's also used for uploads/downloads. */
2111 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_RO_SHADER);
2120 for (int i = 0; i < desc->nb_layers; i++) {
2121 vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
2122 vkDestroySemaphore(hwctx->act_dev, f->sem[i], hwctx->alloc);
2124 for (int i = 0; i < desc->nb_objects; i++)
2125 vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
2132 static int vulkan_map_from_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2133 const AVFrame *src, int flags)
2137 VulkanMapping *map = NULL;
2139 err = vulkan_map_from_drm_frame_desc(hwfc, &f,
2140 (AVDRMFrameDescriptor *)src->data[0]);
2144 /* The unmapping function will free this */
2145 dst->data[0] = (uint8_t *)f;
2146 dst->width = src->width;
2147 dst->height = src->height;
2149 map = av_mallocz(sizeof(VulkanMapping));
2156 err = ff_hwframe_map_create(dst->hw_frames_ctx, dst, src,
2157 &vulkan_unmap_from, map);
2161 av_log(hwfc, AV_LOG_DEBUG, "Mapped DRM object to Vulkan!\n");
2166 vulkan_frame_free(hwfc->device_ctx->hwctx, (uint8_t *)f);
2172 static int vulkan_map_from_vaapi(AVHWFramesContext *dst_fc,
2173 AVFrame *dst, const AVFrame *src,
2177 AVFrame *tmp = av_frame_alloc();
2178 AVHWFramesContext *vaapi_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2179 AVVAAPIDeviceContext *vaapi_ctx = vaapi_fc->device_ctx->hwctx;
2180 VASurfaceID surface_id = (VASurfaceID)(uintptr_t)src->data[3];
2183 return AVERROR(ENOMEM);
2185 /* We have to sync since like the previous comment said, no semaphores */
2186 vaSyncSurface(vaapi_ctx->display, surface_id);
2188 tmp->format = AV_PIX_FMT_DRM_PRIME;
2190 err = av_hwframe_map(tmp, src, flags);
2194 err = vulkan_map_from_drm(dst_fc, dst, tmp, flags);
2198 err = ff_hwframe_map_replace(dst, src);
2201 av_frame_free(&tmp);
2208 static int vulkan_export_to_cuda(AVHWFramesContext *hwfc,
2209 AVBufferRef *cuda_hwfc,
2210 const AVFrame *frame)
2215 AVVkFrameInternal *dst_int;
2216 AVHWDeviceContext *ctx = hwfc->device_ctx;
2217 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2218 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2219 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2220 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2221 VK_LOAD_PFN(hwctx->inst, vkGetSemaphoreFdKHR);
2223 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)cuda_hwfc->data;
2224 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2225 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2226 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2227 CudaFunctions *cu = cu_internal->cuda_dl;
2228 CUarray_format cufmt = desc->comp[0].depth > 8 ? CU_AD_FORMAT_UNSIGNED_INT16 :
2229 CU_AD_FORMAT_UNSIGNED_INT8;
2231 dst_f = (AVVkFrame *)frame->data[0];
2233 dst_int = dst_f->internal;
2234 if (!dst_int || !dst_int->cuda_fc_ref) {
2235 if (!dst_f->internal)
2236 dst_f->internal = dst_int = av_mallocz(sizeof(*dst_f->internal));
2239 err = AVERROR(ENOMEM);
2243 dst_int->cuda_fc_ref = av_buffer_ref(cuda_hwfc);
2244 if (!dst_int->cuda_fc_ref) {
2245 err = AVERROR(ENOMEM);
2249 for (int i = 0; i < planes; i++) {
2250 CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC tex_desc = {
2253 .Width = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2255 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2259 .NumChannels = 1 + ((planes == 2) && i),
2264 CUDA_EXTERNAL_MEMORY_HANDLE_DESC ext_desc = {
2265 .type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD,
2266 .size = dst_f->size[i],
2268 VkMemoryGetFdInfoKHR export_info = {
2269 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2270 .memory = dst_f->mem[i],
2271 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR,
2273 VkSemaphoreGetFdInfoKHR sem_export = {
2274 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR,
2275 .semaphore = dst_f->sem[i],
2276 .handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
2278 CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC ext_sem_desc = {
2279 .type = CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD,
2282 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2283 &ext_desc.handle.fd);
2284 if (ret != VK_SUCCESS) {
2285 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2286 err = AVERROR_EXTERNAL;
2290 ret = CHECK_CU(cu->cuImportExternalMemory(&dst_int->ext_mem[i], &ext_desc));
2292 err = AVERROR_EXTERNAL;
2296 ret = CHECK_CU(cu->cuExternalMemoryGetMappedMipmappedArray(&dst_int->cu_mma[i],
2297 dst_int->ext_mem[i],
2300 err = AVERROR_EXTERNAL;
2304 ret = CHECK_CU(cu->cuMipmappedArrayGetLevel(&dst_int->cu_array[i],
2305 dst_int->cu_mma[i], 0));
2307 err = AVERROR_EXTERNAL;
2311 ret = pfn_vkGetSemaphoreFdKHR(hwctx->act_dev, &sem_export,
2312 &ext_sem_desc.handle.fd);
2313 if (ret != VK_SUCCESS) {
2314 av_log(ctx, AV_LOG_ERROR, "Failed to export semaphore: %s\n",
2316 err = AVERROR_EXTERNAL;
2320 ret = CHECK_CU(cu->cuImportExternalSemaphore(&dst_int->cu_sem[i],
2323 err = AVERROR_EXTERNAL;
2335 static int vulkan_transfer_data_from_cuda(AVHWFramesContext *hwfc,
2336 AVFrame *dst, const AVFrame *src)
2342 AVVkFrameInternal *dst_int;
2343 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2344 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2346 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2347 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2348 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2349 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2350 CudaFunctions *cu = cu_internal->cuda_dl;
2351 CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS s_w_par[AV_NUM_DATA_POINTERS] = { 0 };
2352 CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS s_s_par[AV_NUM_DATA_POINTERS] = { 0 };
2354 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2356 err = AVERROR_EXTERNAL;
2360 dst_f = (AVVkFrame *)dst->data[0];
2362 ret = vulkan_export_to_cuda(hwfc, src->hw_frames_ctx, dst);
2366 dst_int = dst_f->internal;
2368 ret = CHECK_CU(cu->cuWaitExternalSemaphoresAsync(dst_int->cu_sem, s_w_par,
2369 planes, cuda_dev->stream));
2371 err = AVERROR_EXTERNAL;
2375 for (int i = 0; i < planes; i++) {
2376 CUDA_MEMCPY2D cpy = {
2377 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
2378 .srcDevice = (CUdeviceptr)src->data[i],
2379 .srcPitch = src->linesize[i],
2382 .dstMemoryType = CU_MEMORYTYPE_ARRAY,
2383 .dstArray = dst_int->cu_array[i],
2384 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2385 : hwfc->width) * desc->comp[i].step,
2386 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2390 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2392 err = AVERROR_EXTERNAL;
2397 ret = CHECK_CU(cu->cuSignalExternalSemaphoresAsync(dst_int->cu_sem, s_s_par,
2398 planes, cuda_dev->stream));
2400 err = AVERROR_EXTERNAL;
2404 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2406 av_log(hwfc, AV_LOG_VERBOSE, "Transfered CUDA image to Vulkan!\n");
2411 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2412 vulkan_free_internal(dst_int);
2413 dst_f->internal = NULL;
2414 av_buffer_unref(&dst->buf[0]);
2419 static int vulkan_map_to(AVHWFramesContext *hwfc, AVFrame *dst,
2420 const AVFrame *src, int flags)
2422 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2424 switch (src->format) {
2427 case AV_PIX_FMT_VAAPI:
2428 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2429 return vulkan_map_from_vaapi(hwfc, dst, src, flags);
2431 case AV_PIX_FMT_DRM_PRIME:
2432 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2433 return vulkan_map_from_drm(hwfc, dst, src, flags);
2436 return AVERROR(ENOSYS);
2441 typedef struct VulkanDRMMapping {
2442 AVDRMFrameDescriptor drm_desc;
2446 static void vulkan_unmap_to_drm(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
2448 AVDRMFrameDescriptor *drm_desc = hwmap->priv;
2450 for (int i = 0; i < drm_desc->nb_objects; i++)
2451 close(drm_desc->objects[i].fd);
2456 static inline uint32_t vulkan_fmt_to_drm(VkFormat vkfmt)
2458 for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
2459 if (vulkan_drm_format_map[i].vk_format == vkfmt)
2460 return vulkan_drm_format_map[i].drm_fourcc;
2461 return DRM_FORMAT_INVALID;
2464 static int vulkan_map_to_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2465 const AVFrame *src, int flags)
2469 AVVkFrame *f = (AVVkFrame *)src->data[0];
2470 VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2471 AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
2472 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2473 VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2474 VkImageDrmFormatModifierPropertiesEXT drm_mod = {
2475 .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT,
2478 AVDRMFrameDescriptor *drm_desc = av_mallocz(sizeof(*drm_desc));
2480 return AVERROR(ENOMEM);
2482 err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_EXTERNAL_EXPORT);
2486 err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src, &vulkan_unmap_to_drm, drm_desc);
2490 if (p->extensions & EXT_DRM_MODIFIER_FLAGS) {
2491 VK_LOAD_PFN(hwctx->inst, vkGetImageDrmFormatModifierPropertiesEXT);
2492 ret = pfn_vkGetImageDrmFormatModifierPropertiesEXT(hwctx->act_dev, f->img[0],
2494 if (ret != VK_SUCCESS) {
2495 av_log(hwfc, AV_LOG_ERROR, "Failed to retrieve DRM format modifier!\n");
2496 err = AVERROR_EXTERNAL;
2501 for (int i = 0; (i < planes) && (f->mem[i]); i++) {
2502 VkMemoryGetFdInfoKHR export_info = {
2503 .sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2504 .memory = f->mem[i],
2505 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,
2508 ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2509 &drm_desc->objects[i].fd);
2510 if (ret != VK_SUCCESS) {
2511 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2512 err = AVERROR_EXTERNAL;
2516 drm_desc->nb_objects++;
2517 drm_desc->objects[i].size = f->size[i];
2518 drm_desc->objects[i].format_modifier = drm_mod.drmFormatModifier;
2521 drm_desc->nb_layers = planes;
2522 for (int i = 0; i < drm_desc->nb_layers; i++) {
2523 VkSubresourceLayout layout;
2524 VkImageSubresource sub = {
2525 .aspectMask = p->extensions & EXT_DRM_MODIFIER_FLAGS ?
2526 VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2527 VK_IMAGE_ASPECT_COLOR_BIT,
2529 VkFormat plane_vkfmt = av_vkfmt_from_pixfmt(hwfc->sw_format)[i];
2531 drm_desc->layers[i].format = vulkan_fmt_to_drm(plane_vkfmt);
2532 drm_desc->layers[i].nb_planes = 1;
2534 if (drm_desc->layers[i].format == DRM_FORMAT_INVALID) {
2535 av_log(hwfc, AV_LOG_ERROR, "Cannot map to DRM layer, unsupported!\n");
2536 err = AVERROR_PATCHWELCOME;
2540 drm_desc->layers[i].planes[0].object_index = FFMIN(i, drm_desc->nb_objects - 1);
2542 if (f->tiling == VK_IMAGE_TILING_OPTIMAL)
2545 vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
2546 drm_desc->layers[i].planes[0].offset = layout.offset;
2547 drm_desc->layers[i].planes[0].pitch = layout.rowPitch;
2550 dst->width = src->width;
2551 dst->height = src->height;
2552 dst->data[0] = (uint8_t *)drm_desc;
2554 av_log(hwfc, AV_LOG_VERBOSE, "Mapped AVVkFrame to a DRM object!\n");
2564 static int vulkan_map_to_vaapi(AVHWFramesContext *hwfc, AVFrame *dst,
2565 const AVFrame *src, int flags)
2568 AVFrame *tmp = av_frame_alloc();
2570 return AVERROR(ENOMEM);
2572 tmp->format = AV_PIX_FMT_DRM_PRIME;
2574 err = vulkan_map_to_drm(hwfc, tmp, src, flags);
2578 err = av_hwframe_map(dst, tmp, flags);
2582 err = ff_hwframe_map_replace(dst, src);
2585 av_frame_free(&tmp);
2591 static int vulkan_map_from(AVHWFramesContext *hwfc, AVFrame *dst,
2592 const AVFrame *src, int flags)
2594 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2596 switch (dst->format) {
2598 case AV_PIX_FMT_DRM_PRIME:
2599 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2600 return vulkan_map_to_drm(hwfc, dst, src, flags);
2602 case AV_PIX_FMT_VAAPI:
2603 if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2604 return vulkan_map_to_vaapi(hwfc, dst, src, flags);
2608 return vulkan_map_frame_to_mem(hwfc, dst, src, flags);
2612 typedef struct ImageBuffer {
2615 VkMemoryPropertyFlagBits flags;
2618 static void free_buf(void *opaque, uint8_t *data)
2620 AVHWDeviceContext *ctx = opaque;
2621 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2622 ImageBuffer *vkbuf = (ImageBuffer *)data;
2625 vkDestroyBuffer(hwctx->act_dev, vkbuf->buf, hwctx->alloc);
2627 vkFreeMemory(hwctx->act_dev, vkbuf->mem, hwctx->alloc);
2632 static int create_buf(AVHWDeviceContext *ctx, AVBufferRef **buf,
2633 int height, int *stride, VkBufferUsageFlags usage,
2634 VkMemoryPropertyFlagBits flags, void *create_pnext,
2639 VkMemoryRequirements req;
2640 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2641 VulkanDevicePriv *p = ctx->internal->priv;
2643 VkBufferCreateInfo buf_spawn = {
2644 .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
2645 .pNext = create_pnext,
2647 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
2650 ImageBuffer *vkbuf = av_mallocz(sizeof(*vkbuf));
2652 return AVERROR(ENOMEM);
2654 *stride = FFALIGN(*stride, p->props.limits.optimalBufferCopyRowPitchAlignment);
2655 buf_spawn.size = height*(*stride);
2657 ret = vkCreateBuffer(hwctx->act_dev, &buf_spawn, NULL, &vkbuf->buf);
2658 if (ret != VK_SUCCESS) {
2659 av_log(ctx, AV_LOG_ERROR, "Failed to create buffer: %s\n",
2661 return AVERROR_EXTERNAL;
2664 vkGetBufferMemoryRequirements(hwctx->act_dev, vkbuf->buf, &req);
2666 err = alloc_mem(ctx, &req, flags, alloc_pnext, &vkbuf->flags, &vkbuf->mem);
2670 ret = vkBindBufferMemory(hwctx->act_dev, vkbuf->buf, vkbuf->mem, 0);
2671 if (ret != VK_SUCCESS) {
2672 av_log(ctx, AV_LOG_ERROR, "Failed to bind memory to buffer: %s\n",
2674 free_buf(ctx, (uint8_t *)vkbuf);
2675 return AVERROR_EXTERNAL;
2678 *buf = av_buffer_create((uint8_t *)vkbuf, sizeof(*vkbuf), free_buf, ctx, 0);
2680 free_buf(ctx, (uint8_t *)vkbuf);
2681 return AVERROR(ENOMEM);
2687 static int map_buffers(AVHWDeviceContext *ctx, AVBufferRef **bufs, uint8_t *mem[],
2688 int nb_buffers, int invalidate)
2691 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2692 VkMappedMemoryRange invalidate_ctx[AV_NUM_DATA_POINTERS];
2693 int invalidate_count = 0;
2695 for (int i = 0; i < nb_buffers; i++) {
2696 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2697 ret = vkMapMemory(hwctx->act_dev, vkbuf->mem, 0,
2698 VK_WHOLE_SIZE, 0, (void **)&mem[i]);
2699 if (ret != VK_SUCCESS) {
2700 av_log(ctx, AV_LOG_ERROR, "Failed to map buffer memory: %s\n",
2702 return AVERROR_EXTERNAL;
2709 for (int i = 0; i < nb_buffers; i++) {
2710 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2711 const VkMappedMemoryRange ival_buf = {
2712 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2713 .memory = vkbuf->mem,
2714 .size = VK_WHOLE_SIZE,
2716 if (vkbuf->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2718 invalidate_ctx[invalidate_count++] = ival_buf;
2721 if (invalidate_count) {
2722 ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, invalidate_count,
2724 if (ret != VK_SUCCESS)
2725 av_log(ctx, AV_LOG_WARNING, "Failed to invalidate memory: %s\n",
2732 static int unmap_buffers(AVHWDeviceContext *ctx, AVBufferRef **bufs,
2733 int nb_buffers, int flush)
2737 AVVulkanDeviceContext *hwctx = ctx->hwctx;
2738 VkMappedMemoryRange flush_ctx[AV_NUM_DATA_POINTERS];
2739 int flush_count = 0;
2742 for (int i = 0; i < nb_buffers; i++) {
2743 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2744 const VkMappedMemoryRange flush_buf = {
2745 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2746 .memory = vkbuf->mem,
2747 .size = VK_WHOLE_SIZE,
2749 if (vkbuf->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2751 flush_ctx[flush_count++] = flush_buf;
2756 ret = vkFlushMappedMemoryRanges(hwctx->act_dev, flush_count, flush_ctx);
2757 if (ret != VK_SUCCESS) {
2758 av_log(ctx, AV_LOG_ERROR, "Failed to flush memory: %s\n",
2760 err = AVERROR_EXTERNAL; /* We still want to try to unmap them */
2764 for (int i = 0; i < nb_buffers; i++) {
2765 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2766 vkUnmapMemory(hwctx->act_dev, vkbuf->mem);
2772 static int transfer_image_buf(AVHWDeviceContext *ctx, const AVFrame *f,
2773 AVBufferRef **bufs, const int *buf_stride, int w,
2774 int h, enum AVPixelFormat pix_fmt, int to_buf)
2777 AVVkFrame *frame = (AVVkFrame *)f->data[0];
2778 VulkanDevicePriv *s = ctx->internal->priv;
2781 VkPipelineStageFlagBits sem_wait_dst[AV_NUM_DATA_POINTERS];
2783 const int planes = av_pix_fmt_count_planes(pix_fmt);
2784 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2786 VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
2787 VkCommandBuffer cmd_buf = get_buf_exec_ctx(ctx, &s->cmd);
2789 VkSubmitInfo s_info = {
2790 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
2791 .pSignalSemaphores = frame->sem,
2792 .pWaitSemaphores = frame->sem,
2793 .pWaitDstStageMask = sem_wait_dst,
2794 .signalSemaphoreCount = planes,
2795 .waitSemaphoreCount = planes,
2798 if ((err = wait_start_exec_ctx(ctx, &s->cmd)))
2801 /* Change the image layout to something more optimal for transfers */
2802 for (int i = 0; i < planes; i++) {
2803 VkImageLayout new_layout = to_buf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL :
2804 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
2805 VkAccessFlags new_access = to_buf ? VK_ACCESS_TRANSFER_READ_BIT :
2806 VK_ACCESS_TRANSFER_WRITE_BIT;
2808 sem_wait_dst[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
2810 /* If the layout matches and we have read access skip the barrier */
2811 if ((frame->layout[i] == new_layout) && (frame->access[i] & new_access))
2814 img_bar[bar_num].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
2815 img_bar[bar_num].srcAccessMask = 0x0;
2816 img_bar[bar_num].dstAccessMask = new_access;
2817 img_bar[bar_num].oldLayout = frame->layout[i];
2818 img_bar[bar_num].newLayout = new_layout;
2819 img_bar[bar_num].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2820 img_bar[bar_num].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2821 img_bar[bar_num].image = frame->img[i];
2822 img_bar[bar_num].subresourceRange.levelCount = 1;
2823 img_bar[bar_num].subresourceRange.layerCount = 1;
2824 img_bar[bar_num].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2826 frame->layout[i] = img_bar[bar_num].newLayout;
2827 frame->access[i] = img_bar[bar_num].dstAccessMask;
2833 vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
2834 VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
2835 0, NULL, 0, NULL, bar_num, img_bar);
2837 /* Schedule a copy for each plane */
2838 for (int i = 0; i < planes; i++) {
2839 ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2840 const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
2841 const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
2842 VkBufferImageCopy buf_reg = {
2844 /* Buffer stride isn't in bytes, it's in samples, the implementation
2845 * uses the image's VkFormat to know how many bytes per sample
2846 * the buffer has. So we have to convert by dividing. Stupid.
2847 * Won't work with YUVA or other planar formats with alpha. */
2848 .bufferRowLength = buf_stride[i] / desc->comp[i].step,
2849 .bufferImageHeight = p_h,
2850 .imageSubresource.layerCount = 1,
2851 .imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
2852 .imageOffset = { 0, 0, 0, },
2853 .imageExtent = { p_w, p_h, 1, },
2857 vkCmdCopyImageToBuffer(cmd_buf, frame->img[i], frame->layout[i],
2858 vkbuf->buf, 1, &buf_reg);
2860 vkCmdCopyBufferToImage(cmd_buf, vkbuf->buf, frame->img[i],
2861 frame->layout[i], 1, &buf_reg);
2864 /* When uploading, do this asynchronously if the source is refcounted by
2865 * keeping the buffers as a submission dependency.
2866 * The hwcontext is guaranteed to not be freed until all frames are freed
2867 * in the frames_unint function.
2868 * When downloading to buffer, do this synchronously and wait for the
2869 * queue submission to finish executing */
2872 for (ref = 0; ref < AV_NUM_DATA_POINTERS; ref++) {
2875 if ((err = add_buf_dep_exec_ctx(hwfc, &s->cmd, &f->buf[ref], 1)))
2878 if (ref && (err = add_buf_dep_exec_ctx(hwfc, &s->cmd, bufs, planes)))
2880 return submit_exec_ctx(hwfc, &s->cmd, &s_info, !ref);
2882 return submit_exec_ctx(hwfc, &s->cmd, &s_info, 1);
2886 /* Technically we can use VK_EXT_external_memory_host to upload and download,
2887 * however the alignment requirements make this unfeasible as both the pointer
2888 * and the size of each plane need to be aligned to the minimum alignment
2889 * requirement, which on all current implementations (anv, radv) is 4096.
2890 * If the requirement gets relaxed (unlikely) this can easily be implemented. */
2891 static int vulkan_transfer_data_from_mem(AVHWFramesContext *hwfc, AVFrame *dst,
2896 AVVkFrame *f = (AVVkFrame *)dst->data[0];
2897 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
2898 AVBufferRef *bufs[AV_NUM_DATA_POINTERS] = { 0 };
2899 const int planes = av_pix_fmt_count_planes(src->format);
2900 int log2_chroma = av_pix_fmt_desc_get(src->format)->log2_chroma_h;
2902 if ((src->format != AV_PIX_FMT_NONE && !av_vkfmt_from_pixfmt(src->format))) {
2903 av_log(hwfc, AV_LOG_ERROR, "Unsupported source pixel format!\n");
2904 return AVERROR(EINVAL);
2907 if (src->width > hwfc->width || src->height > hwfc->height)
2908 return AVERROR(EINVAL);
2910 /* For linear, host visiable images */
2911 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
2912 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
2913 AVFrame *map = av_frame_alloc();
2915 return AVERROR(ENOMEM);
2916 map->format = src->format;
2918 err = vulkan_map_frame_to_mem(hwfc, map, dst, AV_HWFRAME_MAP_WRITE);
2922 err = av_frame_copy(map, src);
2923 av_frame_free(&map);
2927 /* Create buffers */
2928 for (int i = 0; i < planes; i++) {
2929 int h = src->height;
2930 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
2932 tmp.linesize[i] = FFABS(src->linesize[i]);
2933 err = create_buf(dev_ctx, &bufs[i], p_height,
2934 &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
2935 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
2940 /* Map, copy image to buffer, unmap */
2941 if ((err = map_buffers(dev_ctx, bufs, tmp.data, planes, 0)))
2944 av_image_copy(tmp.data, tmp.linesize, (const uint8_t **)src->data,
2945 src->linesize, src->format, src->width, src->height);
2947 if ((err = unmap_buffers(dev_ctx, bufs, planes, 1)))
2950 /* Copy buffers to image */
2951 err = transfer_image_buf(dev_ctx, dst, bufs, tmp.linesize,
2952 src->width, src->height, src->format, 0);
2955 for (int i = 0; i < planes; i++)
2956 av_buffer_unref(&bufs[i]);
2961 static int vulkan_transfer_data_to(AVHWFramesContext *hwfc, AVFrame *dst,
2964 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2966 switch (src->format) {
2968 case AV_PIX_FMT_CUDA:
2969 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
2970 (p->extensions & EXT_EXTERNAL_FD_SEM))
2971 return vulkan_transfer_data_from_cuda(hwfc, dst, src);
2974 if (src->hw_frames_ctx)
2975 return AVERROR(ENOSYS);
2977 return vulkan_transfer_data_from_mem(hwfc, dst, src);
2982 static int vulkan_transfer_data_to_cuda(AVHWFramesContext *hwfc, AVFrame *dst,
2989 AVVkFrameInternal *dst_int;
2990 const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2991 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2993 AVHWFramesContext *cuda_fc = (AVHWFramesContext*)dst->hw_frames_ctx->data;
2994 AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2995 AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2996 AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2997 CudaFunctions *cu = cu_internal->cuda_dl;
2999 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
3001 err = AVERROR_EXTERNAL;
3005 dst_f = (AVVkFrame *)src->data[0];
3007 err = vulkan_export_to_cuda(hwfc, dst->hw_frames_ctx, src);
3012 dst_int = dst_f->internal;
3014 for (int i = 0; i < planes; i++) {
3015 CUDA_MEMCPY2D cpy = {
3016 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
3017 .dstDevice = (CUdeviceptr)dst->data[i],
3018 .dstPitch = dst->linesize[i],
3021 .srcMemoryType = CU_MEMORYTYPE_ARRAY,
3022 .srcArray = dst_int->cu_array[i],
3023 .WidthInBytes = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
3024 : hwfc->width) * desc->comp[i].step,
3025 .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
3029 ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
3031 err = AVERROR_EXTERNAL;
3036 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
3038 av_log(hwfc, AV_LOG_VERBOSE, "Transfered Vulkan image to CUDA!\n");
3043 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
3044 vulkan_free_internal(dst_int);
3045 dst_f->internal = NULL;
3046 av_buffer_unref(&dst->buf[0]);
3051 static int vulkan_transfer_data_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
3056 AVVkFrame *f = (AVVkFrame *)src->data[0];
3057 AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
3058 AVBufferRef *bufs[AV_NUM_DATA_POINTERS] = { 0 };
3059 const int planes = av_pix_fmt_count_planes(dst->format);
3060 int log2_chroma = av_pix_fmt_desc_get(dst->format)->log2_chroma_h;
3062 if (dst->width > hwfc->width || dst->height > hwfc->height)
3063 return AVERROR(EINVAL);
3065 /* For linear, host visiable images */
3066 if (f->tiling == VK_IMAGE_TILING_LINEAR &&
3067 f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
3068 AVFrame *map = av_frame_alloc();
3070 return AVERROR(ENOMEM);
3071 map->format = dst->format;
3073 err = vulkan_map_frame_to_mem(hwfc, map, src, AV_HWFRAME_MAP_READ);
3077 err = av_frame_copy(dst, map);
3078 av_frame_free(&map);
3082 /* Create buffers */
3083 for (int i = 0; i < planes; i++) {
3084 int h = dst->height;
3085 int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
3087 tmp.linesize[i] = FFABS(dst->linesize[i]);
3088 err = create_buf(dev_ctx, &bufs[i], p_height,
3089 &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_DST_BIT,
3090 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
3095 /* Copy image to buffer */
3096 if ((err = transfer_image_buf(dev_ctx, src, bufs, tmp.linesize,
3097 dst->width, dst->height, dst->format, 1)))
3100 /* Map, copy buffer to frame, unmap */
3101 if ((err = map_buffers(dev_ctx, bufs, tmp.data, planes, 1)))
3104 av_image_copy(dst->data, dst->linesize, (const uint8_t **)tmp.data,
3105 tmp.linesize, dst->format, dst->width, dst->height);
3107 err = unmap_buffers(dev_ctx, bufs, planes, 0);
3110 for (int i = 0; i < planes; i++)
3111 av_buffer_unref(&bufs[i]);
3116 static int vulkan_transfer_data_from(AVHWFramesContext *hwfc, AVFrame *dst,
3119 av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
3121 switch (dst->format) {
3123 case AV_PIX_FMT_CUDA:
3124 if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
3125 (p->extensions & EXT_EXTERNAL_FD_SEM))
3126 return vulkan_transfer_data_to_cuda(hwfc, dst, src);
3129 if (dst->hw_frames_ctx)
3130 return AVERROR(ENOSYS);
3132 return vulkan_transfer_data_to_mem(hwfc, dst, src);
3136 AVVkFrame *av_vk_frame_alloc(void)
3138 return av_mallocz(sizeof(AVVkFrame));
3141 const HWContextType ff_hwcontext_type_vulkan = {
3142 .type = AV_HWDEVICE_TYPE_VULKAN,
3145 .device_hwctx_size = sizeof(AVVulkanDeviceContext),
3146 .device_priv_size = sizeof(VulkanDevicePriv),
3147 .frames_hwctx_size = sizeof(AVVulkanFramesContext),
3148 .frames_priv_size = sizeof(VulkanFramesPriv),
3150 .device_init = &vulkan_device_init,
3151 .device_create = &vulkan_device_create,
3152 .device_derive = &vulkan_device_derive,
3154 .frames_get_constraints = &vulkan_frames_get_constraints,
3155 .frames_init = vulkan_frames_init,
3156 .frames_get_buffer = vulkan_get_buffer,
3157 .frames_uninit = vulkan_frames_uninit,
3159 .transfer_get_formats = vulkan_transfer_get_formats,
3160 .transfer_data_to = vulkan_transfer_data_to,
3161 .transfer_data_from = vulkan_transfer_data_from,
3163 .map_to = vulkan_map_to,
3164 .map_from = vulkan_map_from,
3166 .pix_fmts = (const enum AVPixelFormat []) {