]> git.sesse.net Git - ffmpeg/blob - libavutil/hwcontext_vulkan.c
hwcontext_vulkan: use all enabled queues for transfers, make uploads async
[ffmpeg] / libavutil / hwcontext_vulkan.c
1 /*
2  * This file is part of FFmpeg.
3  *
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.
8  *
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.
13  *
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
17  */
18
19 #include "config.h"
20 #include "pixdesc.h"
21 #include "avstring.h"
22 #include "imgutils.h"
23 #include "hwcontext.h"
24 #include "hwcontext_internal.h"
25 #include "hwcontext_vulkan.h"
26
27 #if CONFIG_LIBDRM
28 #include <unistd.h>
29 #include <xf86drm.h>
30 #include <drm_fourcc.h>
31 #include "hwcontext_drm.h"
32 #if CONFIG_VAAPI
33 #include <va/va_drmcommon.h>
34 #include "hwcontext_vaapi.h"
35 #endif
36 #endif
37
38 #if CONFIG_CUDA
39 #include "hwcontext_cuda_internal.h"
40 #include "cuda_check.h"
41 #define CHECK_CU(x) FF_CUDA_CHECK_DL(cuda_cu, cu, x)
42 #endif
43
44 typedef struct VulkanQueueCtx {
45     VkFence fence;
46     VkQueue queue;
47     int was_synchronous;
48
49     /* Buffer dependencies */
50     AVBufferRef **buf_deps;
51     int nb_buf_deps;
52     int buf_deps_alloc_size;
53 } VulkanQueueCtx;
54
55 typedef struct VulkanExecCtx {
56     VkCommandPool pool;
57     VkCommandBuffer *bufs;
58     VulkanQueueCtx *queues;
59     int nb_queues;
60     int cur_queue_idx;
61 } VulkanExecCtx;
62
63 typedef struct VulkanDevicePriv {
64     /* Properties */
65     VkPhysicalDeviceProperties props;
66     VkPhysicalDeviceMemoryProperties mprops;
67
68     /* Queues */
69     uint32_t qfs[3];
70     int num_qfs;
71
72     /* Debug callback */
73     VkDebugUtilsMessengerEXT debug_ctx;
74
75     /* Image transfers */
76     VulkanExecCtx upload_ctx;
77     VulkanExecCtx download_ctx;
78
79     /* Extensions */
80     uint64_t extensions;
81
82     /* Settings */
83     int use_linear_images;
84
85     /* Nvidia */
86     int dev_is_nvidia;
87 } VulkanDevicePriv;
88
89 typedef struct VulkanFramesPriv {
90     VulkanExecCtx cmd;
91 } VulkanFramesPriv;
92
93 typedef struct AVVkFrameInternal {
94 #if CONFIG_CUDA
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];
102 #endif
103 } AVVkFrameInternal;
104
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)) : \
112     0                                                               \
113 )
114
115 #define VK_LOAD_PFN(inst, name) PFN_##name pfn_##name = (PFN_##name)           \
116                                               vkGetInstanceProcAddr(inst, #name)
117
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)
122
123 #define ADD_VAL_TO_LIST(list, count, val)                                      \
124     do {                                                                       \
125         list = av_realloc_array(list, sizeof(*list), ++count);                 \
126         if (!list) {                                                           \
127             err = AVERROR(ENOMEM);                                             \
128             goto fail;                                                         \
129         }                                                                      \
130         list[count - 1] = av_strdup(val);                                      \
131         if (!list[count - 1]) {                                                \
132             err = AVERROR(ENOMEM);                                             \
133             goto fail;                                                         \
134         }                                                                      \
135     } while(0)
136
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 } },
144
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 } },
148
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 } },
152
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 } },
156
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 } },
169
170     { AV_PIX_FMT_GBRPF32, { VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32_SFLOAT } },
171 };
172
173 const VkFormat *av_vkfmt_from_pixfmt(enum AVPixelFormat p)
174 {
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;
178     return NULL;
179 }
180
181 static int pixfmt_is_supported(AVVulkanDeviceContext *hwctx, enum AVPixelFormat p,
182                                int linear)
183 {
184     const VkFormat *fmt = av_vkfmt_from_pixfmt(p);
185     int planes = av_pix_fmt_count_planes(p);
186
187     if (!fmt)
188         return 0;
189
190     for (int i = 0; i < planes; i++) {
191         VkFormatFeatureFlags flags;
192         VkFormatProperties2 prop = {
193             .sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2,
194         };
195         vkGetPhysicalDeviceFormatProperties2(hwctx->phys_dev, fmt[i], &prop);
196         flags = linear ? prop.formatProperties.linearTilingFeatures :
197                          prop.formatProperties.optimalTilingFeatures;
198         if (!(flags & DEFAULT_USAGE_FLAGS))
199             return 0;
200     }
201
202     return 1;
203 }
204
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 */
210
211     EXT_NO_FLAG                = 1ULL << 63,
212 };
213
214 typedef struct VulkanOptExtension {
215     const char *name;
216     uint64_t flag;
217 } VulkanOptExtension;
218
219 static const VulkanOptExtension optional_instance_exts[] = {
220     /* For future use */
221 };
222
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,        },
228 };
229
230 /* Converts return values to strings */
231 static const char *vk_ret2str(VkResult res)
232 {
233 #define CASE(VAL) case VAL: return #VAL
234     switch (res) {
235     CASE(VK_SUCCESS);
236     CASE(VK_NOT_READY);
237     CASE(VK_TIMEOUT);
238     CASE(VK_EVENT_SET);
239     CASE(VK_EVENT_RESET);
240     CASE(VK_INCOMPLETE);
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";
267     }
268 #undef CASE
269 }
270
271 static VkBool32 vk_dbg_callback(VkDebugUtilsMessageSeverityFlagBitsEXT severity,
272                                 VkDebugUtilsMessageTypeFlagsEXT messageType,
273                                 const VkDebugUtilsMessengerCallbackDataEXT *data,
274                                 void *priv)
275 {
276     int l;
277     AVHWDeviceContext *ctx = priv;
278
279     switch (severity) {
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;
285     }
286
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);
290
291     return 0;
292 }
293
294 static int check_extensions(AVHWDeviceContext *ctx, int dev, AVDictionary *opts,
295                             const char * const **dst, uint32_t *num, int debug)
296 {
297     const char *tstr;
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;
302
303     const char *mod;
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;
310
311     if (!dev) {
312         mod = "instance";
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);
316         if (user_exts) {
317             user_exts_str = av_strdup(user_exts->value);
318             if (!user_exts_str) {
319                 err = AVERROR(ENOMEM);
320                 goto fail;
321             }
322         }
323         vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, NULL);
324         sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
325         if (!sup_ext)
326             return AVERROR(ENOMEM);
327         vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, sup_ext);
328     } else {
329         mod = "device";
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);
333         if (user_exts) {
334             user_exts_str = av_strdup(user_exts->value);
335             if (!user_exts_str) {
336                 err = AVERROR(ENOMEM);
337                 goto fail;
338             }
339         }
340         vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
341                                              &sup_ext_count, NULL);
342         sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
343         if (!sup_ext)
344             return AVERROR(ENOMEM);
345         vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
346                                              &sup_ext_count, sup_ext);
347     }
348
349     for (int i = 0; i < optional_exts_num; i++) {
350         tstr = optional_exts[i].name;
351         found = 0;
352         for (int j = 0; j < sup_ext_count; j++) {
353             if (!strcmp(tstr, sup_ext[j].extensionName)) {
354                 found = 1;
355                 break;
356             }
357         }
358         if (!found)
359             continue;
360
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);
364     }
365
366     if (debug && !dev) {
367         tstr = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
368         found = 0;
369         for (int j = 0; j < sup_ext_count; j++) {
370             if (!strcmp(tstr, sup_ext[j].extensionName)) {
371                 found = 1;
372                 break;
373             }
374         }
375         if (found) {
376             av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
377             ADD_VAL_TO_LIST(extension_names, extensions_found, tstr);
378         } else {
379             av_log(ctx, AV_LOG_ERROR, "Debug extension \"%s\" not found!\n",
380                    tstr);
381             err = AVERROR(EINVAL);
382             goto fail;
383         }
384     }
385
386     if (user_exts_str) {
387         char *save, *token = av_strtok(user_exts_str, "+", &save);
388         while (token) {
389             found = 0;
390             for (int j = 0; j < sup_ext_count; j++) {
391                 if (!strcmp(token, sup_ext[j].extensionName)) {
392                     found = 1;
393                     break;
394                 }
395             }
396             if (found) {
397                 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, token);
398                 ADD_VAL_TO_LIST(extension_names, extensions_found, token);
399             } else {
400                 av_log(ctx, AV_LOG_WARNING, "%s extension \"%s\" not found, excluding.\n",
401                        mod, token);
402             }
403             token = av_strtok(NULL, "+", &save);
404         }
405     }
406
407     *dst = extension_names;
408     *num = extensions_found;
409
410     av_free(user_exts_str);
411     av_free(sup_ext);
412     return 0;
413
414 fail:
415     if (extension_names)
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);
420     av_free(sup_ext);
421     return err;
422 }
423
424 /* Creates a VkInstance */
425 static int create_instance(AVHWDeviceContext *ctx, AVDictionary *opts)
426 {
427     int err = 0;
428     VkResult ret;
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),
440     };
441     VkInstanceCreateInfo inst_props = {
442         .sType            = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
443         .pApplicationInfo = &application_info,
444     };
445
446     /* Check for present/missing extensions */
447     err = check_extensions(ctx, 0, opts, &inst_props.ppEnabledExtensionNames,
448                            &inst_props.enabledExtensionCount, debug_mode);
449     if (err < 0)
450         return err;
451
452     if (debug_mode) {
453         static const char *layers[] = { "VK_LAYER_KHRONOS_validation" };
454         inst_props.ppEnabledLayerNames = layers;
455         inst_props.enabledLayerCount = FF_ARRAY_ELEMS(layers);
456     }
457
458     /* Try to create the instance */
459     ret = vkCreateInstance(&inst_props, hwctx->alloc, &hwctx->inst);
460
461     /* Check for errors */
462     if (ret != VK_SUCCESS) {
463         av_log(ctx, AV_LOG_ERROR, "Instance creation failure: %s\n",
464                vk_ret2str(ret));
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;
469     }
470
471     if (debug_mode) {
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,
482             .pUserData = ctx,
483         };
484         VK_LOAD_PFN(hwctx->inst, vkCreateDebugUtilsMessengerEXT);
485
486         pfn_vkCreateDebugUtilsMessengerEXT(hwctx->inst, &dbg,
487                                            hwctx->alloc, &p->debug_ctx);
488     }
489
490     hwctx->enabled_inst_extensions = inst_props.ppEnabledExtensionNames;
491     hwctx->nb_enabled_inst_extensions = inst_props.enabledExtensionCount;
492
493     return 0;
494 }
495
496 typedef struct VulkanDeviceSelection {
497     uint8_t uuid[VK_UUID_SIZE]; /* Will use this first unless !has_uuid */
498     int 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;
504
505 static const char *vk_dev_type(enum VkPhysicalDeviceType type)
506 {
507     switch (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";
513     }
514 }
515
516 /* Finds a device */
517 static int find_device(AVHWDeviceContext *ctx, VulkanDeviceSelection *select)
518 {
519     int err = 0, choice = -1;
520     uint32_t num;
521     VkResult ret;
522     VkPhysicalDevice *devices = NULL;
523     VkPhysicalDeviceIDProperties *idp = NULL;
524     VkPhysicalDeviceProperties2 *prop = NULL;
525     VulkanDevicePriv *p = ctx->internal->priv;
526     AVVulkanDeviceContext *hwctx = ctx->hwctx;
527
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);
532     }
533
534     devices = av_malloc_array(num, sizeof(VkPhysicalDevice));
535     if (!devices)
536         return AVERROR(ENOMEM);
537
538     ret = vkEnumeratePhysicalDevices(hwctx->inst, &num, devices);
539     if (ret != VK_SUCCESS) {
540         av_log(ctx, AV_LOG_ERROR, "Failed enumerating devices: %s\n",
541                vk_ret2str(ret));
542         err = AVERROR(ENODEV);
543         goto end;
544     }
545
546     prop = av_mallocz_array(num, sizeof(*prop));
547     if (!prop) {
548         err = AVERROR(ENOMEM);
549         goto end;
550     }
551
552     idp = av_mallocz_array(num, sizeof(*idp));
553     if (!idp) {
554         err = AVERROR(ENOMEM);
555         goto end;
556     }
557
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];
563
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);
569     }
570
571     if (select->has_uuid) {
572         for (int i = 0; i < num; i++) {
573             if (!strncmp(idp[i].deviceUUID, select->uuid, VK_UUID_SIZE)) {
574                 choice = i;
575                 goto end;
576              }
577         }
578         av_log(ctx, AV_LOG_ERROR, "Unable to find device by given UUID!\n");
579         err = AVERROR(ENODEV);
580         goto end;
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)) {
585                 choice = i;
586                 goto end;
587              }
588         }
589         av_log(ctx, AV_LOG_ERROR, "Unable to find device \"%s\"!\n",
590                select->name);
591         err = AVERROR(ENODEV);
592         goto end;
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) {
597                 choice = i;
598                 goto end;
599             }
600         }
601         av_log(ctx, AV_LOG_ERROR, "Unable to find device with PCI ID 0x%x!\n",
602                select->pci_device);
603         err = AVERROR(EINVAL);
604         goto end;
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) {
609                 choice = i;
610                 goto end;
611             }
612         }
613         av_log(ctx, AV_LOG_ERROR, "Unable to find device with Vendor ID 0x%x!\n",
614                select->vendor_id);
615         err = AVERROR(ENODEV);
616         goto end;
617     } else {
618         if (select->index < num) {
619             choice = select->index;
620             goto end;
621         }
622         av_log(ctx, AV_LOG_ERROR, "Unable to find device with index %i!\n",
623                select->index);
624         err = AVERROR(ENODEV);
625         goto end;
626     }
627
628 end:
629     if (choice > -1) {
630         p->dev_is_nvidia = (prop[choice].properties.vendorID == 0x10de);
631         hwctx->phys_dev = devices[choice];
632     }
633     av_free(devices);
634     av_free(prop);
635     av_free(idp);
636
637     return err;
638 }
639
640 static int search_queue_families(AVHWDeviceContext *ctx, VkDeviceCreateInfo *cd)
641 {
642     uint32_t num;
643     float *weights;
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;
648
649     /* First get the number of queue families */
650     vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, NULL);
651     if (!num) {
652         av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
653         return AVERROR_EXTERNAL;
654     }
655
656     /* Then allocate memory */
657     qs = av_malloc_array(num, sizeof(VkQueueFamilyProperties));
658     if (!qs)
659         return AVERROR(ENOMEM);
660
661     /* Finally retrieve the queue families */
662     vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, qs);
663
664 #define SEARCH_FLAGS(expr, out)                                                \
665     for (int i = 0; i < num; i++) {                                            \
666         const VkQueueFlagBits flags = qs[i].queueFlags;                        \
667         if (expr) {                                                            \
668             out = i;                                                           \
669             break;                                                             \
670         }                                                                      \
671     }
672
673     SEARCH_FLAGS(flags & VK_QUEUE_GRAPHICS_BIT, graph_index)
674
675     SEARCH_FLAGS((flags &  VK_QUEUE_COMPUTE_BIT) && (i != graph_index),
676                  comp_index)
677
678     SEARCH_FLAGS((flags & VK_QUEUE_TRANSFER_BIT) && (i != graph_index) &&
679                  (i != comp_index), tx_index)
680
681 #undef SEARCH_FLAGS
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;                             \
695     if (!weights)                                                                        \
696         goto fail;                                                                       \
697     for (int i = 0; i < qs[fidx].queueCount; i++)                                        \
698         weights[i] = 1.0f;                                                               \
699     cd->queueCreateInfoCount++;
700
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;
706
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;
712     }
713
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;
718     }
719
720 #undef ADD_QUEUE
721     av_free(qs);
722
723     return 0;
724
725 fail:
726     av_freep(&pc[0].pQueuePriorities);
727     av_freep(&pc[1].pQueuePriorities);
728     av_freep(&pc[2].pQueuePriorities);
729     av_free(qs);
730
731     return AVERROR(ENOMEM);
732 }
733
734 static int create_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd,
735                            int queue_family_index, int num_queues)
736 {
737     VkResult ret;
738     AVVulkanDeviceContext *hwctx = ctx->hwctx;
739
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,
744     };
745     VkCommandBufferAllocateInfo cbuf_create = {
746         .sType              = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
747         .level              = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
748         .commandBufferCount = num_queues,
749     };
750
751     cmd->nb_queues = num_queues;
752
753     cmd->queues = av_mallocz(num_queues * sizeof(*cmd->queues));
754     if (!cmd->queues)
755         return AVERROR(ENOMEM);
756
757     cmd->bufs = av_mallocz(num_queues * sizeof(*cmd->bufs));
758     if (!cmd->bufs)
759         return AVERROR(ENOMEM);
760
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",
766                vk_ret2str(ret));
767         return AVERROR_EXTERNAL;
768     }
769
770     cbuf_create.commandPool = cmd->pool;
771
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",
776                vk_ret2str(ret));
777         return AVERROR_EXTERNAL;
778     }
779
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;
784     }
785
786     return 0;
787 }
788
789 static void free_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd)
790 {
791     AVVulkanDeviceContext *hwctx = ctx->hwctx;
792
793     /* Make sure all queues have finished executing */
794     for (int i = 0; i < cmd->nb_queues; i++) {
795         VulkanQueueCtx *q = &cmd->queues[i];
796
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);
800         }
801
802         /* Free the fence */
803         if (q->fence)
804             vkDestroyFence(hwctx->act_dev, q->fence, hwctx->alloc);
805
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);
810     }
811
812     if (cmd->bufs)
813         vkFreeCommandBuffers(hwctx->act_dev, cmd->pool, cmd->nb_queues, cmd->bufs);
814     if (cmd->pool)
815         vkDestroyCommandPool(hwctx->act_dev, cmd->pool, hwctx->alloc);
816
817     av_freep(&cmd->bufs);
818     av_freep(&cmd->queues);
819 }
820
821 static VkCommandBuffer get_buf_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd)
822 {
823     return cmd->bufs[cmd->cur_queue_idx];
824 }
825
826 static void unref_exec_ctx_deps(AVHWDeviceContext *ctx, VulkanExecCtx *cmd)
827 {
828     VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
829
830     for (int j = 0; j < q->nb_buf_deps; j++)
831         av_buffer_unref(&q->buf_deps[j]);
832     q->nb_buf_deps = 0;
833 }
834
835 static int wait_start_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd)
836 {
837     VkResult ret;
838     AVVulkanDeviceContext *hwctx = ctx->hwctx;
839     VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
840
841     VkCommandBufferBeginInfo cmd_start = {
842         .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
843         .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
844     };
845
846     /* Create the fence and don't wait for it initially */
847     if (!q->fence) {
848         VkFenceCreateInfo fence_spawn = {
849             .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
850         };
851         ret = vkCreateFence(hwctx->act_dev, &fence_spawn, hwctx->alloc,
852                             &q->fence);
853         if (ret != VK_SUCCESS) {
854             av_log(ctx, AV_LOG_ERROR, "Failed to queue frame fence: %s\n",
855                    vk_ret2str(ret));
856             return AVERROR_EXTERNAL;
857         }
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);
861     }
862
863     /* Discard queue dependencies */
864     unref_exec_ctx_deps(ctx, cmd);
865
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",
869                vk_ret2str(ret));
870         return AVERROR_EXTERNAL;
871     }
872
873     return 0;
874 }
875
876 static int add_buf_dep_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd,
877                                 AVBufferRef * const *deps, int nb_deps)
878 {
879     AVBufferRef **dst;
880     VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
881
882     if (!deps || !nb_deps)
883         return 0;
884
885     dst = av_fast_realloc(q->buf_deps, &q->buf_deps_alloc_size,
886                           (q->nb_buf_deps + nb_deps) * sizeof(*dst));
887     if (!dst)
888         goto err;
889
890     q->buf_deps = dst;
891
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])
895             goto err;
896         q->nb_buf_deps++;
897     }
898
899     return 0;
900
901 err:
902     unref_exec_ctx_deps(ctx, cmd);
903     return AVERROR(ENOMEM);
904 }
905
906 static int submit_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd,
907                            VkSubmitInfo *s_info, int synchronous)
908 {
909     VkResult ret;
910     VulkanQueueCtx *q = &cmd->queues[cmd->cur_queue_idx];
911
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",
915                vk_ret2str(ret));
916         unref_exec_ctx_deps(ctx, cmd);
917         return AVERROR_EXTERNAL;
918     }
919
920     s_info->pCommandBuffers = &cmd->bufs[cmd->cur_queue_idx];
921     s_info->commandBufferCount = 1;
922
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;
927     }
928
929     q->was_synchronous = synchronous;
930
931     if (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;
938     }
939
940     return 0;
941 }
942
943 static void vulkan_device_free(AVHWDeviceContext *ctx)
944 {
945     VulkanDevicePriv *p = ctx->internal->priv;
946     AVVulkanDeviceContext *hwctx = ctx->hwctx;
947
948     free_exec_ctx(ctx, &p->cmd);
949
950     vkDestroyDevice(hwctx->act_dev, hwctx->alloc);
951
952     if (p->debug_ctx) {
953         VK_LOAD_PFN(hwctx->inst, vkDestroyDebugUtilsMessengerEXT);
954         pfn_vkDestroyDebugUtilsMessengerEXT(hwctx->inst, p->debug_ctx,
955                                             hwctx->alloc);
956     }
957
958     vkDestroyInstance(hwctx->inst, hwctx->alloc);
959
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);
963
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);
967 }
968
969 static int vulkan_device_create_internal(AVHWDeviceContext *ctx,
970                                          VulkanDeviceSelection *dev_select,
971                                          AVDictionary *opts, int flags)
972 {
973     int err = 0;
974     VkResult ret;
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, },
983     };
984
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,
990     };
991
992     hwctx->device_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
993     ctx->free = vulkan_device_free;
994
995     /* Create an instance if not given one */
996     if ((err = create_instance(ctx, opts)))
997         goto end;
998
999     /* Find a device (if not given one) */
1000     if ((err = find_device(ctx, dev_select)))
1001         goto end;
1002
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);
1012
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)
1019 #undef COPY_FEATURE
1020
1021     /* Search queue family */
1022     if ((err = search_queue_families(ctx, &dev_info)))
1023         goto end;
1024
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);
1030         goto end;
1031     }
1032
1033     ret = vkCreateDevice(hwctx->phys_dev, &dev_info, hwctx->alloc,
1034                          &hwctx->act_dev);
1035
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);
1039
1040     if (ret != VK_SUCCESS) {
1041         av_log(ctx, AV_LOG_ERROR, "Device creation failure: %s\n",
1042                vk_ret2str(ret));
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;
1047         goto end;
1048     }
1049
1050     /* Tiled images setting, use them by default */
1051     opt_d = av_dict_get(opts, "linear_images", NULL, 0);
1052     if (opt_d)
1053         p->use_linear_images = strtol(opt_d->value, NULL, 10);
1054
1055     hwctx->enabled_dev_extensions = dev_info.ppEnabledExtensionNames;
1056     hwctx->nb_enabled_dev_extensions = dev_info.enabledExtensionCount;
1057
1058 end:
1059     return err;
1060 }
1061
1062 static int vulkan_device_init(AVHWDeviceContext *ctx)
1063 {
1064     int err;
1065     uint32_t queue_num;
1066     AVVulkanDeviceContext *hwctx = ctx->hwctx;
1067     VulkanDevicePriv *p = ctx->internal->priv;
1068
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;
1075                 break;
1076             }
1077         }
1078     }
1079
1080     vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &queue_num, NULL);
1081     if (!queue_num) {
1082         av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
1083         return AVERROR_EXTERNAL;
1084     }
1085
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);                                                          \
1091 }
1092
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)
1096
1097 #undef CHECK_QUEUE
1098
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;
1106
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));
1110     if (err)
1111         return err;
1112
1113     /* Get device capabilities */
1114     vkGetPhysicalDeviceMemoryProperties(hwctx->phys_dev, &p->mprops);
1115
1116     return 0;
1117 }
1118
1119 static int vulkan_device_create(AVHWDeviceContext *ctx, const char *device,
1120                                 AVDictionary *opts, int flags)
1121 {
1122     VulkanDeviceSelection dev_select = { 0 };
1123     if (device && device[0]) {
1124         char *end = NULL;
1125         dev_select.index = strtol(device, &end, 10);
1126         if (end == device) {
1127             dev_select.index = 0;
1128             dev_select.name  = device;
1129         }
1130     }
1131
1132     return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1133 }
1134
1135 static int vulkan_device_derive(AVHWDeviceContext *ctx,
1136                                 AVHWDeviceContext *src_ctx,
1137                                 AVDictionary *opts, int flags)
1138 {
1139     av_unused VulkanDeviceSelection dev_select = { 0 };
1140
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) {
1145 #if CONFIG_LIBDRM
1146 #if CONFIG_VAAPI
1147     case AV_HWDEVICE_TYPE_VAAPI: {
1148         AVVAAPIDeviceContext *src_hwctx = src_ctx->hwctx;
1149
1150         const char *vendor = vaQueryVendorString(src_hwctx->display);
1151         if (!vendor) {
1152             av_log(ctx, AV_LOG_ERROR, "Unable to get device info from VAAPI!\n");
1153             return AVERROR_EXTERNAL;
1154         }
1155
1156         if (strstr(vendor, "Intel"))
1157             dev_select.vendor_id = 0x8086;
1158         if (strstr(vendor, "AMD"))
1159             dev_select.vendor_id = 0x1002;
1160
1161         return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1162     }
1163 #endif
1164     case AV_HWDEVICE_TYPE_DRM: {
1165         AVDRMDeviceContext *src_hwctx = src_ctx->hwctx;
1166
1167         drmDevice *drm_dev_info;
1168         int err = drmGetDevice(src_hwctx->fd, &drm_dev_info);
1169         if (err) {
1170             av_log(ctx, AV_LOG_ERROR, "Unable to get device info from DRM fd!\n");
1171             return AVERROR_EXTERNAL;
1172         }
1173
1174         if (drm_dev_info->bustype == DRM_BUS_PCI)
1175             dev_select.pci_device = drm_dev_info->deviceinfo.pci->device_id;
1176
1177         drmFreeDevice(&drm_dev_info);
1178
1179         return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1180     }
1181 #endif
1182 #if CONFIG_CUDA
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;
1188
1189         int ret = CHECK_CU(cu->cuDeviceGetUuid((CUuuid *)&dev_select.uuid,
1190                                                cu_internal->cuda_device));
1191         if (ret < 0) {
1192             av_log(ctx, AV_LOG_ERROR, "Unable to get UUID from CUDA!\n");
1193             return AVERROR_EXTERNAL;
1194         }
1195
1196         dev_select.has_uuid = 1;
1197
1198         return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
1199     }
1200 #endif
1201     default:
1202         return AVERROR(ENOSYS);
1203     }
1204 }
1205
1206 static int vulkan_frames_get_constraints(AVHWDeviceContext *ctx,
1207                                          const void *hwconfig,
1208                                          AVHWFramesConstraints *constraints)
1209 {
1210     int count = 0;
1211     AVVulkanDeviceContext *hwctx = ctx->hwctx;
1212     VulkanDevicePriv *p = ctx->internal->priv;
1213
1214     for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
1215         count += pixfmt_is_supported(hwctx, i, p->use_linear_images);
1216
1217 #if CONFIG_CUDA
1218     if (p->dev_is_nvidia)
1219         count++;
1220 #endif
1221
1222     constraints->valid_sw_formats = av_malloc_array(count + 1,
1223                                                     sizeof(enum AVPixelFormat));
1224     if (!constraints->valid_sw_formats)
1225         return AVERROR(ENOMEM);
1226
1227     count = 0;
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;
1231
1232 #if CONFIG_CUDA
1233     if (p->dev_is_nvidia)
1234         constraints->valid_sw_formats[count++] = AV_PIX_FMT_CUDA;
1235 #endif
1236     constraints->valid_sw_formats[count++] = AV_PIX_FMT_NONE;
1237
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;
1242
1243     constraints->valid_hw_formats = av_malloc_array(2, sizeof(enum AVPixelFormat));
1244     if (!constraints->valid_hw_formats)
1245         return AVERROR(ENOMEM);
1246
1247     constraints->valid_hw_formats[0] = AV_PIX_FMT_VULKAN;
1248     constraints->valid_hw_formats[1] = AV_PIX_FMT_NONE;
1249
1250     return 0;
1251 }
1252
1253 static int alloc_mem(AVHWDeviceContext *ctx, VkMemoryRequirements *req,
1254                      VkMemoryPropertyFlagBits req_flags, void *alloc_extension,
1255                      VkMemoryPropertyFlagBits *mem_flags, VkDeviceMemory *mem)
1256 {
1257     VkResult ret;
1258     int index = -1;
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,
1264     };
1265
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);
1269
1270     alloc_info.allocationSize = req->size;
1271
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)))
1277             continue;
1278
1279         /* The memory type flags must include our properties */
1280         if ((p->mprops.memoryTypes[i].propertyFlags & req_flags) != req_flags)
1281             continue;
1282
1283         /* Found a suitable memory type */
1284         index = i;
1285         break;
1286     }
1287
1288     if (index < 0) {
1289         av_log(ctx, AV_LOG_ERROR, "No memory type found for flags 0x%x\n",
1290                req_flags);
1291         return AVERROR(EINVAL);
1292     }
1293
1294     alloc_info.memoryTypeIndex = index;
1295
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",
1300                vk_ret2str(ret));
1301         return AVERROR(ENOMEM);
1302     }
1303
1304     *mem_flags |= p->mprops.memoryTypes[index].propertyFlags;
1305
1306     return 0;
1307 }
1308
1309 static void vulkan_free_internal(AVVkFrameInternal *internal)
1310 {
1311     if (!internal)
1312         return;
1313
1314 #if CONFIG_CUDA
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;
1322
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]));
1330         }
1331
1332         av_buffer_unref(&internal->cuda_fc_ref);
1333     }
1334 #endif
1335
1336     av_free(internal);
1337 }
1338
1339 static void vulkan_frame_free(void *opaque, uint8_t *data)
1340 {
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);
1345
1346     vulkan_free_internal(f->internal);
1347
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);
1352     }
1353
1354     av_free(f);
1355 }
1356
1357 static int alloc_bind_mem(AVHWFramesContext *hwfc, AVVkFrame *f,
1358                           void *alloc_pnext, size_t alloc_pnext_stride)
1359 {
1360     int err;
1361     VkResult ret;
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 } };
1365
1366     AVVulkanDeviceContext *hwctx = ctx->hwctx;
1367
1368     for (int i = 0; i < planes; i++) {
1369         int use_ded_mem;
1370         VkImageMemoryRequirementsInfo2 req_desc = {
1371             .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
1372             .image = f->img[i],
1373         };
1374         VkMemoryDedicatedAllocateInfo ded_alloc = {
1375             .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
1376             .pNext = (void *)(((uint8_t *)alloc_pnext) + i*alloc_pnext_stride),
1377         };
1378         VkMemoryDedicatedRequirements ded_req = {
1379             .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
1380         };
1381         VkMemoryRequirements2 req = {
1382             .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
1383             .pNext = &ded_req,
1384         };
1385
1386         vkGetImageMemoryRequirements2(hwctx->act_dev, &req_desc, &req);
1387
1388         /* In case the implementation prefers/requires dedicated allocation */
1389         use_ded_mem = ded_req.prefersDedicatedAllocation |
1390                       ded_req.requiresDedicatedAllocation;
1391         if (use_ded_mem)
1392             ded_alloc.image = f->img[i];
1393
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])))
1401             return err;
1402
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];
1407     }
1408
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",
1413                vk_ret2str(ret));
1414         return AVERROR_EXTERNAL;
1415     }
1416
1417     return 0;
1418 }
1419
1420 enum PrepMode {
1421     PREP_MODE_WRITE,
1422     PREP_MODE_RO_SHADER,
1423     PREP_MODE_EXTERNAL_EXPORT,
1424 };
1425
1426 static int prepare_frame(AVHWFramesContext *hwfc, VulkanExecCtx *ectx,
1427                          AVVkFrame *frame, enum PrepMode pmode)
1428 {
1429     int err;
1430     uint32_t dst_qf;
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);
1435
1436     VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
1437
1438     VkSubmitInfo s_info = {
1439         .sType                = VK_STRUCTURE_TYPE_SUBMIT_INFO,
1440         .pSignalSemaphores    = frame->sem,
1441         .signalSemaphoreCount = planes,
1442     };
1443
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;
1447
1448     switch (pmode) {
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;
1453         break;
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;
1458         break;
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;
1466         break;
1467     }
1468
1469     if ((err = wait_start_exec_ctx(ctx, ectx)))
1470         return err;
1471
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;
1487
1488         frame->layout[i] = img_bar[i].newLayout;
1489         frame->access[i] = img_bar[i].dstAccessMask;
1490     }
1491
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);
1496
1497     return submit_exec_ctx(ctx, ectx, &s_info, 0);
1498 }
1499
1500 static int create_frame(AVHWFramesContext *hwfc, AVVkFrame **frame,
1501                         VkImageTiling tiling, VkImageUsageFlagBits usage,
1502                         void *create_pnext)
1503 {
1504     int err;
1505     VkResult ret;
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);
1512
1513     VkExportSemaphoreCreateInfo ext_sem_info = {
1514         .sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO,
1515         .handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
1516     };
1517
1518     VkSemaphoreCreateInfo sem_spawn = {
1519         .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1520         .pNext = p->extensions & EXT_EXTERNAL_FD_SEM ? &ext_sem_info : NULL,
1521     };
1522
1523     AVVkFrame *f = av_vk_frame_alloc();
1524     if (!f) {
1525         av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1526         return AVERROR(ENOMEM);
1527     }
1528
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;
1536
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,
1544             .extent.depth          = 1,
1545             .mipLevels             = 1,
1546             .arrayLayers           = 1,
1547             .flags                 = VK_IMAGE_CREATE_ALIAS_BIT,
1548             .tiling                = tiling,
1549             .initialLayout         = VK_IMAGE_LAYOUT_UNDEFINED,
1550             .usage                 = usage,
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,
1556         };
1557
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",
1562                    vk_ret2str(ret));
1563             err = AVERROR(EINVAL);
1564             goto fail;
1565         }
1566
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",
1572                    vk_ret2str(ret));
1573             return AVERROR_EXTERNAL;
1574         }
1575
1576         f->layout[i] = image_create_info.initialLayout;
1577         f->access[i] = 0x0;
1578     }
1579
1580     f->flags     = 0x0;
1581     f->tiling    = tiling;
1582
1583     *frame = f;
1584     return 0;
1585
1586 fail:
1587     vulkan_frame_free(hwfc, (uint8_t *)f);
1588     return err;
1589 }
1590
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)
1596 {
1597     VkResult ret;
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,
1602     };
1603     VkImageFormatProperties2 props = {
1604         .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,
1605         .pNext = &eprops,
1606     };
1607     VkPhysicalDeviceExternalImageFormatInfo enext = {
1608         .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
1609         .handleType = exp,
1610     };
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,
1619     };
1620
1621     ret = vkGetPhysicalDeviceImageFormatProperties2(dev_hwctx->phys_dev,
1622                                                     &pinfo, &props);
1623     if (ret == VK_SUCCESS) {
1624         *iexp |= exp;
1625         *comp_handle_types |= eprops.externalMemoryProperties.compatibleHandleTypes;
1626     }
1627 }
1628
1629 static AVBufferRef *vulkan_pool_alloc(void *opaque, int size)
1630 {
1631     int err;
1632     AVVkFrame *f;
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;
1639
1640     VkExternalMemoryImageCreateInfo eiinfo = {
1641         .sType       = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1642         .pNext       = hwctx->create_pnext,
1643     };
1644
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);
1648
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);
1652
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;
1657     }
1658
1659     err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1660                        eiinfo.handleTypes ? &eiinfo : NULL);
1661     if (err)
1662         return NULL;
1663
1664     err = alloc_bind_mem(hwfc, f, eminfo, sizeof(*eminfo));
1665     if (err)
1666         goto fail;
1667
1668     err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_WRITE);
1669     if (err)
1670         goto fail;
1671
1672     avbuf = av_buffer_create((uint8_t *)f, sizeof(AVVkFrame),
1673                              vulkan_frame_free, hwfc, 0);
1674     if (!avbuf)
1675         goto fail;
1676
1677     return avbuf;
1678
1679 fail:
1680     vulkan_frame_free(hwfc, (uint8_t *)f);
1681     return NULL;
1682 }
1683
1684 static void vulkan_frames_uninit(AVHWFramesContext *hwfc)
1685 {
1686     VulkanFramesPriv *fp = hwfc->internal->priv;
1687
1688     free_exec_ctx(hwfc->device_ctx, &fp->cmd);
1689 }
1690
1691 static int vulkan_frames_init(AVHWFramesContext *hwfc)
1692 {
1693     int err;
1694     AVVkFrame *f;
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;
1699
1700     if (hwfc->pool)
1701         return 0;
1702
1703     /* Default pool flags */
1704     hwctx->tiling = hwctx->tiling ? hwctx->tiling : p->use_linear_images ?
1705                     VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1706
1707     hwctx->usage |= DEFAULT_USAGE_FLAGS;
1708
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));
1712     if (err)
1713         return err;
1714
1715     /* Test to see if allocation will fail */
1716     err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1717                        hwctx->create_pnext);
1718     if (err) {
1719         free_exec_ctx(hwfc->device_ctx, &p->cmd);
1720         return err;
1721     }
1722
1723     vulkan_frame_free(hwfc, (uint8_t *)f);
1724
1725     hwfc->internal->pool_internal = av_buffer_pool_init2(sizeof(AVVkFrame),
1726                                                          hwfc, vulkan_pool_alloc,
1727                                                          NULL);
1728     if (!hwfc->internal->pool_internal) {
1729         free_exec_ctx(hwfc->device_ctx, &p->cmd);
1730         return AVERROR(ENOMEM);
1731     }
1732
1733     return 0;
1734 }
1735
1736 static int vulkan_get_buffer(AVHWFramesContext *hwfc, AVFrame *frame)
1737 {
1738     frame->buf[0] = av_buffer_pool_get(hwfc->pool);
1739     if (!frame->buf[0])
1740         return AVERROR(ENOMEM);
1741
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;
1746
1747     return 0;
1748 }
1749
1750 static int vulkan_transfer_get_formats(AVHWFramesContext *hwfc,
1751                                        enum AVHWFrameTransferDirection dir,
1752                                        enum AVPixelFormat **formats)
1753 {
1754     enum AVPixelFormat *fmts = av_malloc_array(2, sizeof(*fmts));
1755     if (!fmts)
1756         return AVERROR(ENOMEM);
1757
1758     fmts[0] = hwfc->sw_format;
1759     fmts[1] = AV_PIX_FMT_NONE;
1760
1761     *formats = fmts;
1762     return 0;
1763 }
1764
1765 typedef struct VulkanMapping {
1766     AVVkFrame *frame;
1767     int flags;
1768 } VulkanMapping;
1769
1770 static void vulkan_unmap_frame(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1771 {
1772     VulkanMapping *map = hwmap->priv;
1773     AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1774     const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1775
1776     /* Check if buffer needs flushing */
1777     if ((map->flags & AV_HWFRAME_MAP_WRITE) &&
1778         !(map->frame->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1779         VkResult ret;
1780         VkMappedMemoryRange flush_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1781
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;
1786         }
1787
1788         ret = vkFlushMappedMemoryRanges(hwctx->act_dev, planes,
1789                                         flush_ranges);
1790         if (ret != VK_SUCCESS) {
1791             av_log(hwfc, AV_LOG_ERROR, "Failed to flush memory: %s\n",
1792                    vk_ret2str(ret));
1793         }
1794     }
1795
1796     for (int i = 0; i < planes; i++)
1797         vkUnmapMemory(hwctx->act_dev, map->frame->mem[i]);
1798
1799     av_free(map);
1800 }
1801
1802 static int vulkan_map_frame_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
1803                                    const AVFrame *src, int flags)
1804 {
1805     VkResult ret;
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);
1810
1811     VulkanMapping *map = av_mallocz(sizeof(VulkanMapping));
1812     if (!map)
1813         return AVERROR(EINVAL);
1814
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);
1819         goto fail;
1820     }
1821
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 "
1825                "and linear!\n");
1826         err = AVERROR(EINVAL);
1827         goto fail;
1828     }
1829
1830     dst->width  = src->width;
1831     dst->height = src->height;
1832
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",
1838                 vk_ret2str(ret));
1839             err = AVERROR_EXTERNAL;
1840             goto fail;
1841         }
1842         mapped_mem_count++;
1843     }
1844
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];
1853         }
1854
1855         ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, planes,
1856                                              map_mem_ranges);
1857         if (ret != VK_SUCCESS) {
1858             av_log(hwfc, AV_LOG_ERROR, "Failed to invalidate memory: %s\n",
1859                    vk_ret2str(ret));
1860             err = AVERROR_EXTERNAL;
1861             goto fail;
1862         }
1863     }
1864
1865     for (int i = 0; i < planes; i++) {
1866         VkImageSubresource sub = {
1867             .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
1868         };
1869         VkSubresourceLayout layout;
1870         vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
1871         dst->linesize[i] = layout.rowPitch;
1872     }
1873
1874     map->frame = f;
1875     map->flags = flags;
1876
1877     err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src,
1878                                 &vulkan_unmap_frame, map);
1879     if (err < 0)
1880         goto fail;
1881
1882     return 0;
1883
1884 fail:
1885     for (int i = 0; i < mapped_mem_count; i++)
1886         vkUnmapMemory(hwctx->act_dev, f->mem[i]);
1887
1888     av_free(map);
1889     return err;
1890 }
1891
1892 #if CONFIG_LIBDRM
1893 static void vulkan_unmap_from(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1894 {
1895     VulkanMapping *map = hwmap->priv;
1896     AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1897     const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1898
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);
1903     }
1904
1905     av_freep(&map->frame);
1906 }
1907
1908 static const struct {
1909     uint32_t drm_fourcc;
1910     VkFormat vk_format;
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 },
1922 };
1923
1924 static inline VkFormat drm_to_vulkan_fmt(uint32_t drm_fourcc)
1925 {
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;
1930 }
1931
1932 static int vulkan_map_from_drm_frame_desc(AVHWFramesContext *hwfc, AVVkFrame **frame,
1933                                           AVDRMFrameDescriptor *desc)
1934 {
1935     int err = 0;
1936     VkResult ret;
1937     AVVkFrame *f;
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;
1948
1949     VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdPropertiesKHR);
1950
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);
1956         }
1957     }
1958
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);
1962         goto fail;
1963     }
1964
1965     for (int i = 0; i < desc->nb_objects; i++) {
1966         VkMemoryFdPropertiesKHR fdmp = {
1967             .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,
1968         };
1969         VkMemoryRequirements req = {
1970             .size = desc->objects[i].size,
1971         };
1972         VkImportMemoryFdInfoKHR idesc = {
1973             .sType      = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
1974             .handleType = htype,
1975             .fd         = dup(desc->objects[i].fd),
1976         };
1977
1978         ret = pfn_vkGetMemoryFdPropertiesKHR(hwctx->act_dev, htype,
1979                                              idesc.fd, &fdmp);
1980         if (ret != VK_SUCCESS) {
1981             av_log(hwfc, AV_LOG_ERROR, "Failed to get FD properties: %s\n",
1982                    vk_ret2str(ret));
1983             err = AVERROR_EXTERNAL;
1984             close(idesc.fd);
1985             goto fail;
1986         }
1987
1988         req.memoryTypeBits = fdmp.memoryTypeBits;
1989
1990         err = alloc_mem(ctx, &req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1991                         &idesc, &f->flags, &f->mem[i]);
1992         if (err) {
1993             close(idesc.fd);
1994             return err;
1995         }
1996
1997         f->size[i] = desc->objects[i].size;
1998     }
1999
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;
2003
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);
2007
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,
2013         };
2014
2015         VkExternalMemoryImageCreateInfo einfo = {
2016             .sType       = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
2017             .pNext       = has_modifiers ? &drm_info : NULL,
2018             .handleTypes = htype,
2019         };
2020
2021         VkSemaphoreCreateInfo sem_spawn = {
2022             .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
2023         };
2024
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;
2027
2028         VkImageCreateInfo image_create_info = {
2029             .sType                 = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
2030             .pNext                 = &einfo,
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,
2035             .extent.depth          = 1,
2036             .mipLevels             = 1,
2037             .arrayLayers           = 1,
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,
2047         };
2048
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;
2055         }
2056
2057         /* Create image */
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",
2062                    vk_ret2str(ret));
2063             err = AVERROR(EINVAL);
2064             goto fail;
2065         }
2066
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",
2071                    vk_ret2str(ret));
2072             return AVERROR_EXTERNAL;
2073         }
2074
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. */
2079
2080         f->layout[i] = image_create_info.initialLayout;
2081         f->access[i] = 0x0;
2082
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;
2087
2088             plane_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO;
2089             plane_info[bind_counts].planeAspect = aspect;
2090
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;
2096             bind_counts++;
2097         }
2098     }
2099
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",
2104                vk_ret2str(ret));
2105         return AVERROR_EXTERNAL;
2106     }
2107
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);
2112     if (err)
2113         goto fail;
2114
2115     *frame = f;
2116
2117     return 0;
2118
2119 fail:
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);
2123     }
2124     for (int i = 0; i < desc->nb_objects; i++)
2125         vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
2126
2127     av_free(f);
2128
2129     return err;
2130 }
2131
2132 static int vulkan_map_from_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2133                                const AVFrame *src, int flags)
2134 {
2135     int err = 0;
2136     AVVkFrame *f;
2137     VulkanMapping *map = NULL;
2138
2139     err = vulkan_map_from_drm_frame_desc(hwfc, &f,
2140                                          (AVDRMFrameDescriptor *)src->data[0]);
2141     if (err)
2142         return err;
2143
2144     /* The unmapping function will free this */
2145     dst->data[0] = (uint8_t *)f;
2146     dst->width   = src->width;
2147     dst->height  = src->height;
2148
2149     map = av_mallocz(sizeof(VulkanMapping));
2150     if (!map)
2151         goto fail;
2152
2153     map->frame = f;
2154     map->flags = flags;
2155
2156     err = ff_hwframe_map_create(dst->hw_frames_ctx, dst, src,
2157                                 &vulkan_unmap_from, map);
2158     if (err < 0)
2159         goto fail;
2160
2161     av_log(hwfc, AV_LOG_DEBUG, "Mapped DRM object to Vulkan!\n");
2162
2163     return 0;
2164
2165 fail:
2166     vulkan_frame_free(hwfc->device_ctx->hwctx, (uint8_t *)f);
2167     av_free(map);
2168     return err;
2169 }
2170
2171 #if CONFIG_VAAPI
2172 static int vulkan_map_from_vaapi(AVHWFramesContext *dst_fc,
2173                                  AVFrame *dst, const AVFrame *src,
2174                                  int flags)
2175 {
2176     int err;
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];
2181
2182     if (!tmp)
2183         return AVERROR(ENOMEM);
2184
2185     /* We have to sync since like the previous comment said, no semaphores */
2186     vaSyncSurface(vaapi_ctx->display, surface_id);
2187
2188     tmp->format = AV_PIX_FMT_DRM_PRIME;
2189
2190     err = av_hwframe_map(tmp, src, flags);
2191     if (err < 0)
2192         goto fail;
2193
2194     err = vulkan_map_from_drm(dst_fc, dst, tmp, flags);
2195     if (err < 0)
2196         goto fail;
2197
2198     err = ff_hwframe_map_replace(dst, src);
2199
2200 fail:
2201     av_frame_free(&tmp);
2202     return err;
2203 }
2204 #endif
2205 #endif
2206
2207 #if CONFIG_CUDA
2208 static int vulkan_export_to_cuda(AVHWFramesContext *hwfc,
2209                                  AVBufferRef *cuda_hwfc,
2210                                  const AVFrame *frame)
2211 {
2212     int err;
2213     VkResult ret;
2214     AVVkFrame *dst_f;
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);
2222
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;
2230
2231     dst_f = (AVVkFrame *)frame->data[0];
2232
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));
2237
2238         if (!dst_int) {
2239             err = AVERROR(ENOMEM);
2240             goto fail;
2241         }
2242
2243         dst_int->cuda_fc_ref = av_buffer_ref(cuda_hwfc);
2244         if (!dst_int->cuda_fc_ref) {
2245             err = AVERROR(ENOMEM);
2246             goto fail;
2247         }
2248
2249         for (int i = 0; i < planes; i++) {
2250             CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC tex_desc = {
2251                 .offset = 0,
2252                 .arrayDesc = {
2253                     .Width  = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2254                                     : hwfc->width,
2255                     .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2256                                     : hwfc->height,
2257                     .Depth = 0,
2258                     .Format = cufmt,
2259                     .NumChannels = 1 + ((planes == 2) && i),
2260                     .Flags = 0,
2261                 },
2262                 .numLevels = 1,
2263             };
2264             CUDA_EXTERNAL_MEMORY_HANDLE_DESC ext_desc = {
2265                 .type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD,
2266                 .size = dst_f->size[i],
2267             };
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,
2272             };
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,
2277             };
2278             CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC ext_sem_desc = {
2279                 .type = CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD,
2280             };
2281
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;
2287                 goto fail;
2288             }
2289
2290             ret = CHECK_CU(cu->cuImportExternalMemory(&dst_int->ext_mem[i], &ext_desc));
2291             if (ret < 0) {
2292                 err = AVERROR_EXTERNAL;
2293                 goto fail;
2294             }
2295
2296             ret = CHECK_CU(cu->cuExternalMemoryGetMappedMipmappedArray(&dst_int->cu_mma[i],
2297                                                                        dst_int->ext_mem[i],
2298                                                                        &tex_desc));
2299             if (ret < 0) {
2300                 err = AVERROR_EXTERNAL;
2301                 goto fail;
2302             }
2303
2304             ret = CHECK_CU(cu->cuMipmappedArrayGetLevel(&dst_int->cu_array[i],
2305                                                         dst_int->cu_mma[i], 0));
2306             if (ret < 0) {
2307                 err = AVERROR_EXTERNAL;
2308                 goto fail;
2309             }
2310
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",
2315                        vk_ret2str(ret));
2316                 err = AVERROR_EXTERNAL;
2317                 goto fail;
2318             }
2319
2320             ret = CHECK_CU(cu->cuImportExternalSemaphore(&dst_int->cu_sem[i],
2321                                                          &ext_sem_desc));
2322             if (ret < 0) {
2323                 err = AVERROR_EXTERNAL;
2324                 goto fail;
2325             }
2326         }
2327     }
2328
2329     return 0;
2330
2331 fail:
2332     return err;
2333 }
2334
2335 static int vulkan_transfer_data_from_cuda(AVHWFramesContext *hwfc,
2336                                           AVFrame *dst, const AVFrame *src)
2337 {
2338     int err;
2339     VkResult ret;
2340     CUcontext dummy;
2341     AVVkFrame *dst_f;
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);
2345
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 };
2353
2354     ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2355     if (ret < 0) {
2356         err = AVERROR_EXTERNAL;
2357         goto fail;
2358     }
2359
2360     dst_f = (AVVkFrame *)dst->data[0];
2361
2362     ret = vulkan_export_to_cuda(hwfc, src->hw_frames_ctx, dst);
2363     if (ret < 0) {
2364         goto fail;
2365     }
2366     dst_int = dst_f->internal;
2367
2368     ret = CHECK_CU(cu->cuWaitExternalSemaphoresAsync(dst_int->cu_sem, s_w_par,
2369                                                      planes, cuda_dev->stream));
2370     if (ret < 0) {
2371         err = AVERROR_EXTERNAL;
2372         goto fail;
2373     }
2374
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],
2380             .srcY          = 0,
2381
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)
2387                                    : hwfc->height,
2388         };
2389
2390         ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2391         if (ret < 0) {
2392             err = AVERROR_EXTERNAL;
2393             goto fail;
2394         }
2395     }
2396
2397     ret = CHECK_CU(cu->cuSignalExternalSemaphoresAsync(dst_int->cu_sem, s_s_par,
2398                                                        planes, cuda_dev->stream));
2399     if (ret < 0) {
2400         err = AVERROR_EXTERNAL;
2401         goto fail;
2402     }
2403
2404     CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2405
2406     av_log(hwfc, AV_LOG_VERBOSE, "Transfered CUDA image to Vulkan!\n");
2407
2408     return 0;
2409
2410 fail:
2411     CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2412     vulkan_free_internal(dst_int);
2413     dst_f->internal = NULL;
2414     av_buffer_unref(&dst->buf[0]);
2415     return err;
2416 }
2417 #endif
2418
2419 static int vulkan_map_to(AVHWFramesContext *hwfc, AVFrame *dst,
2420                          const AVFrame *src, int flags)
2421 {
2422     av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2423
2424     switch (src->format) {
2425 #if CONFIG_LIBDRM
2426 #if CONFIG_VAAPI
2427     case AV_PIX_FMT_VAAPI:
2428         if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2429             return vulkan_map_from_vaapi(hwfc, dst, src, flags);
2430 #endif
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);
2434 #endif
2435     default:
2436         return AVERROR(ENOSYS);
2437     }
2438 }
2439
2440 #if CONFIG_LIBDRM
2441 typedef struct VulkanDRMMapping {
2442     AVDRMFrameDescriptor drm_desc;
2443     AVVkFrame *source;
2444 } VulkanDRMMapping;
2445
2446 static void vulkan_unmap_to_drm(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
2447 {
2448     AVDRMFrameDescriptor *drm_desc = hwmap->priv;
2449
2450     for (int i = 0; i < drm_desc->nb_objects; i++)
2451         close(drm_desc->objects[i].fd);
2452
2453     av_free(drm_desc);
2454 }
2455
2456 static inline uint32_t vulkan_fmt_to_drm(VkFormat vkfmt)
2457 {
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;
2462 }
2463
2464 static int vulkan_map_to_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2465                              const AVFrame *src, int flags)
2466 {
2467     int err = 0;
2468     VkResult ret;
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,
2476     };
2477
2478     AVDRMFrameDescriptor *drm_desc = av_mallocz(sizeof(*drm_desc));
2479     if (!drm_desc)
2480         return AVERROR(ENOMEM);
2481
2482     err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_EXTERNAL_EXPORT);
2483     if (err < 0)
2484         goto end;
2485
2486     err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src, &vulkan_unmap_to_drm, drm_desc);
2487     if (err < 0)
2488         goto end;
2489
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],
2493                                                            &drm_mod);
2494         if (ret != VK_SUCCESS) {
2495             av_log(hwfc, AV_LOG_ERROR, "Failed to retrieve DRM format modifier!\n");
2496             err = AVERROR_EXTERNAL;
2497             goto end;
2498         }
2499     }
2500
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,
2506         };
2507
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;
2513             goto end;
2514         }
2515
2516         drm_desc->nb_objects++;
2517         drm_desc->objects[i].size = f->size[i];
2518         drm_desc->objects[i].format_modifier = drm_mod.drmFormatModifier;
2519     }
2520
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,
2528         };
2529         VkFormat plane_vkfmt = av_vkfmt_from_pixfmt(hwfc->sw_format)[i];
2530
2531         drm_desc->layers[i].format    = vulkan_fmt_to_drm(plane_vkfmt);
2532         drm_desc->layers[i].nb_planes = 1;
2533
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;
2537             goto end;
2538         }
2539
2540         drm_desc->layers[i].planes[0].object_index = FFMIN(i, drm_desc->nb_objects - 1);
2541
2542         if (f->tiling == VK_IMAGE_TILING_OPTIMAL)
2543             continue;
2544
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;
2548     }
2549
2550     dst->width   = src->width;
2551     dst->height  = src->height;
2552     dst->data[0] = (uint8_t *)drm_desc;
2553
2554     av_log(hwfc, AV_LOG_VERBOSE, "Mapped AVVkFrame to a DRM object!\n");
2555
2556     return 0;
2557
2558 end:
2559     av_free(drm_desc);
2560     return err;
2561 }
2562
2563 #if CONFIG_VAAPI
2564 static int vulkan_map_to_vaapi(AVHWFramesContext *hwfc, AVFrame *dst,
2565                                const AVFrame *src, int flags)
2566 {
2567     int err;
2568     AVFrame *tmp = av_frame_alloc();
2569     if (!tmp)
2570         return AVERROR(ENOMEM);
2571
2572     tmp->format = AV_PIX_FMT_DRM_PRIME;
2573
2574     err = vulkan_map_to_drm(hwfc, tmp, src, flags);
2575     if (err < 0)
2576         goto fail;
2577
2578     err = av_hwframe_map(dst, tmp, flags);
2579     if (err < 0)
2580         goto fail;
2581
2582     err = ff_hwframe_map_replace(dst, src);
2583
2584 fail:
2585     av_frame_free(&tmp);
2586     return err;
2587 }
2588 #endif
2589 #endif
2590
2591 static int vulkan_map_from(AVHWFramesContext *hwfc, AVFrame *dst,
2592                            const AVFrame *src, int flags)
2593 {
2594     av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2595
2596     switch (dst->format) {
2597 #if CONFIG_LIBDRM
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);
2601 #if CONFIG_VAAPI
2602     case AV_PIX_FMT_VAAPI:
2603         if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2604             return vulkan_map_to_vaapi(hwfc, dst, src, flags);
2605 #endif
2606 #endif
2607     default:
2608         return vulkan_map_frame_to_mem(hwfc, dst, src, flags);
2609     }
2610 }
2611
2612 typedef struct ImageBuffer {
2613     VkBuffer buf;
2614     VkDeviceMemory mem;
2615     VkMemoryPropertyFlagBits flags;
2616 } ImageBuffer;
2617
2618 static void free_buf(void *opaque, uint8_t *data)
2619 {
2620     AVHWDeviceContext *ctx = opaque;
2621     AVVulkanDeviceContext *hwctx = ctx->hwctx;
2622     ImageBuffer *vkbuf = (ImageBuffer *)data;
2623
2624     if (vkbuf->buf)
2625         vkDestroyBuffer(hwctx->act_dev, vkbuf->buf, hwctx->alloc);
2626     if (vkbuf->mem)
2627         vkFreeMemory(hwctx->act_dev, vkbuf->mem, hwctx->alloc);
2628
2629     av_free(data);
2630 }
2631
2632 static int create_buf(AVHWDeviceContext *ctx, AVBufferRef **buf,
2633                       int height, int *stride, VkBufferUsageFlags usage,
2634                       VkMemoryPropertyFlagBits flags, void *create_pnext,
2635                       void *alloc_pnext)
2636 {
2637     int err;
2638     VkResult ret;
2639     VkMemoryRequirements req;
2640     AVVulkanDeviceContext *hwctx = ctx->hwctx;
2641     VulkanDevicePriv *p = ctx->internal->priv;
2642
2643     VkBufferCreateInfo buf_spawn = {
2644         .sType       = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
2645         .pNext       = create_pnext,
2646         .usage       = usage,
2647         .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
2648     };
2649
2650     ImageBuffer *vkbuf = av_mallocz(sizeof(*vkbuf));
2651     if (!vkbuf)
2652         return AVERROR(ENOMEM);
2653
2654     *stride = FFALIGN(*stride, p->props.limits.optimalBufferCopyRowPitchAlignment);
2655     buf_spawn.size = height*(*stride);
2656
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",
2660                vk_ret2str(ret));
2661         return AVERROR_EXTERNAL;
2662     }
2663
2664     vkGetBufferMemoryRequirements(hwctx->act_dev, vkbuf->buf, &req);
2665
2666     err = alloc_mem(ctx, &req, flags, alloc_pnext, &vkbuf->flags, &vkbuf->mem);
2667     if (err)
2668         return err;
2669
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",
2673                vk_ret2str(ret));
2674         free_buf(ctx, (uint8_t *)vkbuf);
2675         return AVERROR_EXTERNAL;
2676     }
2677
2678     *buf = av_buffer_create((uint8_t *)vkbuf, sizeof(*vkbuf), free_buf, ctx, 0);
2679     if (!(*buf)) {
2680         free_buf(ctx, (uint8_t *)vkbuf);
2681         return AVERROR(ENOMEM);
2682     }
2683
2684     return 0;
2685 }
2686
2687 static int map_buffers(AVHWDeviceContext *ctx, AVBufferRef **bufs, uint8_t *mem[],
2688                        int nb_buffers, int invalidate)
2689 {
2690     VkResult ret;
2691     AVVulkanDeviceContext *hwctx = ctx->hwctx;
2692     VkMappedMemoryRange invalidate_ctx[AV_NUM_DATA_POINTERS];
2693     int invalidate_count = 0;
2694
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",
2701                    vk_ret2str(ret));
2702             return AVERROR_EXTERNAL;
2703         }
2704     }
2705
2706     if (!invalidate)
2707         return 0;
2708
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,
2715         };
2716         if (vkbuf->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2717             continue;
2718         invalidate_ctx[invalidate_count++] = ival_buf;
2719     }
2720
2721     if (invalidate_count) {
2722         ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, invalidate_count,
2723                                              invalidate_ctx);
2724         if (ret != VK_SUCCESS)
2725             av_log(ctx, AV_LOG_WARNING, "Failed to invalidate memory: %s\n",
2726                    vk_ret2str(ret));
2727     }
2728
2729     return 0;
2730 }
2731
2732 static int unmap_buffers(AVHWDeviceContext *ctx, AVBufferRef **bufs,
2733                          int nb_buffers, int flush)
2734 {
2735     int err = 0;
2736     VkResult ret;
2737     AVVulkanDeviceContext *hwctx = ctx->hwctx;
2738     VkMappedMemoryRange flush_ctx[AV_NUM_DATA_POINTERS];
2739     int flush_count = 0;
2740
2741     if (flush) {
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,
2748             };
2749             if (vkbuf->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2750                 continue;
2751             flush_ctx[flush_count++] = flush_buf;
2752         }
2753     }
2754
2755     if (flush_count) {
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",
2759                     vk_ret2str(ret));
2760             err = AVERROR_EXTERNAL; /* We still want to try to unmap them */
2761         }
2762     }
2763
2764     for (int i = 0; i < nb_buffers; i++) {
2765         ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2766         vkUnmapMemory(hwctx->act_dev, vkbuf->mem);
2767     }
2768
2769     return err;
2770 }
2771
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)
2775 {
2776     int err;
2777     AVVkFrame *frame = (AVVkFrame *)f->data[0];
2778     VulkanDevicePriv *s = ctx->internal->priv;
2779
2780     int bar_num = 0;
2781     VkPipelineStageFlagBits sem_wait_dst[AV_NUM_DATA_POINTERS];
2782
2783     const int planes = av_pix_fmt_count_planes(pix_fmt);
2784     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2785
2786     VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
2787     VkCommandBuffer cmd_buf = get_buf_exec_ctx(ctx, &s->cmd);
2788
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,
2796     };
2797
2798     if ((err = wait_start_exec_ctx(ctx, &s->cmd)))
2799         return err;
2800
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;
2807
2808         sem_wait_dst[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
2809
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))
2812             continue;
2813
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;
2825
2826         frame->layout[i] = img_bar[bar_num].newLayout;
2827         frame->access[i] = img_bar[bar_num].dstAccessMask;
2828
2829         bar_num++;
2830     }
2831
2832     if (bar_num)
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);
2836
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 = {
2843             .bufferOffset = 0,
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, },
2854         };
2855
2856         if (to_buf)
2857             vkCmdCopyImageToBuffer(cmd_buf, frame->img[i], frame->layout[i],
2858                                    vkbuf->buf, 1, &buf_reg);
2859         else
2860             vkCmdCopyBufferToImage(cmd_buf, vkbuf->buf, frame->img[i],
2861                                    frame->layout[i], 1, &buf_reg);
2862     }
2863
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 */
2870     if (!to_buf) {
2871         int ref;
2872         for (ref = 0; ref < AV_NUM_DATA_POINTERS; ref++) {
2873             if (!f->buf[ref])
2874                 break;
2875             if ((err = add_buf_dep_exec_ctx(hwfc, &s->cmd, &f->buf[ref], 1)))
2876                 return err;
2877         }
2878         if (ref && (err = add_buf_dep_exec_ctx(hwfc, &s->cmd, bufs, planes)))
2879             return err;
2880         return submit_exec_ctx(hwfc, &s->cmd, &s_info, !ref);
2881     } else {
2882         return submit_exec_ctx(hwfc, &s->cmd, &s_info,    1);
2883     }
2884 }
2885
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,
2892                                          const AVFrame *src)
2893 {
2894     int err = 0;
2895     AVFrame tmp;
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;
2901
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);
2905     }
2906
2907     if (src->width > hwfc->width || src->height > hwfc->height)
2908         return AVERROR(EINVAL);
2909
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();
2914         if (!map)
2915             return AVERROR(ENOMEM);
2916         map->format = src->format;
2917
2918         err = vulkan_map_frame_to_mem(hwfc, map, dst, AV_HWFRAME_MAP_WRITE);
2919         if (err)
2920             return err;
2921
2922         err = av_frame_copy(map, src);
2923         av_frame_free(&map);
2924         return err;
2925     }
2926
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;
2931
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);
2936         if (err)
2937             goto end;
2938     }
2939
2940     /* Map, copy image to buffer, unmap */
2941     if ((err = map_buffers(dev_ctx, bufs, tmp.data, planes, 0)))
2942         goto end;
2943
2944     av_image_copy(tmp.data, tmp.linesize, (const uint8_t **)src->data,
2945                   src->linesize, src->format, src->width, src->height);
2946
2947     if ((err = unmap_buffers(dev_ctx, bufs, planes, 1)))
2948         goto end;
2949
2950     /* Copy buffers to image */
2951     err = transfer_image_buf(dev_ctx, dst, bufs, tmp.linesize,
2952                              src->width, src->height, src->format, 0);
2953
2954 end:
2955     for (int i = 0; i < planes; i++)
2956         av_buffer_unref(&bufs[i]);
2957
2958     return err;
2959 }
2960
2961 static int vulkan_transfer_data_to(AVHWFramesContext *hwfc, AVFrame *dst,
2962                                         const AVFrame *src)
2963 {
2964     av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2965
2966     switch (src->format) {
2967 #if CONFIG_CUDA
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);
2972 #endif
2973     default:
2974         if (src->hw_frames_ctx)
2975             return AVERROR(ENOSYS);
2976         else
2977             return vulkan_transfer_data_from_mem(hwfc, dst, src);
2978     }
2979 }
2980
2981 #if CONFIG_CUDA
2982 static int vulkan_transfer_data_to_cuda(AVHWFramesContext *hwfc, AVFrame *dst,
2983                                       const AVFrame *src)
2984 {
2985     int err;
2986     VkResult ret;
2987     CUcontext dummy;
2988     AVVkFrame *dst_f;
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);
2992
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;
2998
2999     ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
3000     if (ret < 0) {
3001         err = AVERROR_EXTERNAL;
3002         goto fail;
3003     }
3004
3005     dst_f = (AVVkFrame *)src->data[0];
3006
3007     err = vulkan_export_to_cuda(hwfc, dst->hw_frames_ctx, src);
3008     if (err < 0) {
3009         goto fail;
3010     }
3011
3012     dst_int = dst_f->internal;
3013
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],
3019             .dstY          = 0,
3020
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)
3026                                    : hwfc->height,
3027         };
3028
3029         ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
3030         if (ret < 0) {
3031             err = AVERROR_EXTERNAL;
3032             goto fail;
3033         }
3034     }
3035
3036     CHECK_CU(cu->cuCtxPopCurrent(&dummy));
3037
3038     av_log(hwfc, AV_LOG_VERBOSE, "Transfered Vulkan image to CUDA!\n");
3039
3040     return 0;
3041
3042 fail:
3043     CHECK_CU(cu->cuCtxPopCurrent(&dummy));
3044     vulkan_free_internal(dst_int);
3045     dst_f->internal = NULL;
3046     av_buffer_unref(&dst->buf[0]);
3047     return err;
3048 }
3049 #endif
3050
3051 static int vulkan_transfer_data_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
3052                                        const AVFrame *src)
3053 {
3054     int err = 0;
3055     AVFrame tmp;
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;
3061
3062     if (dst->width > hwfc->width || dst->height > hwfc->height)
3063         return AVERROR(EINVAL);
3064
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();
3069         if (!map)
3070             return AVERROR(ENOMEM);
3071         map->format = dst->format;
3072
3073         err = vulkan_map_frame_to_mem(hwfc, map, src, AV_HWFRAME_MAP_READ);
3074         if (err)
3075             return err;
3076
3077         err = av_frame_copy(dst, map);
3078         av_frame_free(&map);
3079         return err;
3080     }
3081
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;
3086
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);
3091         if (err)
3092             goto end;
3093     }
3094
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)))
3098         goto end;
3099
3100     /* Map, copy buffer to frame, unmap */
3101     if ((err = map_buffers(dev_ctx, bufs, tmp.data, planes, 1)))
3102         goto end;
3103
3104     av_image_copy(dst->data, dst->linesize, (const uint8_t **)tmp.data,
3105                   tmp.linesize, dst->format, dst->width, dst->height);
3106
3107     err = unmap_buffers(dev_ctx, bufs, planes, 0);
3108
3109 end:
3110     for (int i = 0; i < planes; i++)
3111         av_buffer_unref(&bufs[i]);
3112
3113     return err;
3114 }
3115
3116 static int vulkan_transfer_data_from(AVHWFramesContext *hwfc, AVFrame *dst,
3117                                      const AVFrame *src)
3118 {
3119     av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
3120
3121     switch (dst->format) {
3122 #if CONFIG_CUDA
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);
3127 #endif
3128     default:
3129         if (dst->hw_frames_ctx)
3130             return AVERROR(ENOSYS);
3131         else
3132             return vulkan_transfer_data_to_mem(hwfc, dst, src);
3133     }
3134 }
3135
3136 AVVkFrame *av_vk_frame_alloc(void)
3137 {
3138     return av_mallocz(sizeof(AVVkFrame));
3139 }
3140
3141 const HWContextType ff_hwcontext_type_vulkan = {
3142     .type                   = AV_HWDEVICE_TYPE_VULKAN,
3143     .name                   = "Vulkan",
3144
3145     .device_hwctx_size      = sizeof(AVVulkanDeviceContext),
3146     .device_priv_size       = sizeof(VulkanDevicePriv),
3147     .frames_hwctx_size      = sizeof(AVVulkanFramesContext),
3148     .frames_priv_size       = sizeof(VulkanFramesPriv),
3149
3150     .device_init            = &vulkan_device_init,
3151     .device_create          = &vulkan_device_create,
3152     .device_derive          = &vulkan_device_derive,
3153
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,
3158
3159     .transfer_get_formats   = vulkan_transfer_get_formats,
3160     .transfer_data_to       = vulkan_transfer_data_to,
3161     .transfer_data_from     = vulkan_transfer_data_from,
3162
3163     .map_to                 = vulkan_map_to,
3164     .map_from               = vulkan_map_from,
3165
3166     .pix_fmts = (const enum AVPixelFormat []) {
3167         AV_PIX_FMT_VULKAN,
3168         AV_PIX_FMT_NONE
3169     },
3170 };