]> git.sesse.net Git - ffmpeg/blob - libavutil/hwcontext_vulkan.c
hwcontext_vulkan: update debugging layer name
[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 VulkanExecCtx {
45     VkCommandPool pool;
46     VkCommandBuffer buf;
47     VkQueue queue;
48     VkFence fence;
49 } VulkanExecCtx;
50
51 typedef struct VulkanDevicePriv {
52     /* Properties */
53     VkPhysicalDeviceProperties props;
54     VkPhysicalDeviceMemoryProperties mprops;
55
56     /* Debug callback */
57     VkDebugUtilsMessengerEXT debug_ctx;
58
59     /* Image uploading */
60     VulkanExecCtx cmd;
61
62     /* Extensions */
63     uint64_t extensions;
64
65     /* Settings */
66     int use_linear_images;
67
68     /* Nvidia */
69     int dev_is_nvidia;
70 } VulkanDevicePriv;
71
72 typedef struct VulkanFramesPriv {
73     VulkanExecCtx cmd;
74 } VulkanFramesPriv;
75
76 typedef struct AVVkFrameInternal {
77 #if CONFIG_CUDA
78     /* Importing external memory into cuda is really expensive so we keep the
79      * memory imported all the time */
80     AVBufferRef *cuda_fc_ref; /* Need to keep it around for uninit */
81     CUexternalMemory ext_mem[AV_NUM_DATA_POINTERS];
82     CUmipmappedArray cu_mma[AV_NUM_DATA_POINTERS];
83     CUarray cu_array[AV_NUM_DATA_POINTERS];
84     CUexternalSemaphore cu_sem;
85 #endif
86 } AVVkFrameInternal;
87
88 #define VK_LOAD_PFN(inst, name) PFN_##name pfn_##name = (PFN_##name)           \
89                                               vkGetInstanceProcAddr(inst, #name)
90
91 #define DEFAULT_USAGE_FLAGS (VK_IMAGE_USAGE_SAMPLED_BIT      |                 \
92                              VK_IMAGE_USAGE_STORAGE_BIT      |                 \
93                              VK_IMAGE_USAGE_TRANSFER_SRC_BIT |                 \
94                              VK_IMAGE_USAGE_TRANSFER_DST_BIT)
95
96 #define ADD_VAL_TO_LIST(list, count, val)                                      \
97     do {                                                                       \
98         list = av_realloc_array(list, sizeof(*list), ++count);                 \
99         if (!list) {                                                           \
100             err = AVERROR(ENOMEM);                                             \
101             goto fail;                                                         \
102         }                                                                      \
103         list[count - 1] = av_strdup(val);                                      \
104         if (!list[count - 1]) {                                                \
105             err = AVERROR(ENOMEM);                                             \
106             goto fail;                                                         \
107         }                                                                      \
108     } while(0)
109
110 static const struct {
111     enum AVPixelFormat pixfmt;
112     const VkFormat vkfmts[3];
113 } vk_pixfmt_map[] = {
114     { AV_PIX_FMT_GRAY8,   { VK_FORMAT_R8_UNORM } },
115     { AV_PIX_FMT_GRAY16,  { VK_FORMAT_R16_UNORM } },
116     { AV_PIX_FMT_GRAYF32, { VK_FORMAT_R32_SFLOAT } },
117
118     { AV_PIX_FMT_NV12, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8G8_UNORM } },
119     { AV_PIX_FMT_P010, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16G16_UNORM } },
120     { AV_PIX_FMT_P016, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16G16_UNORM } },
121
122     { AV_PIX_FMT_YUV420P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
123     { AV_PIX_FMT_YUV422P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
124     { AV_PIX_FMT_YUV444P, { VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM } },
125
126     { AV_PIX_FMT_YUV420P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
127     { AV_PIX_FMT_YUV422P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
128     { AV_PIX_FMT_YUV444P16, { VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM } },
129
130     { AV_PIX_FMT_ABGR,   { VK_FORMAT_A8B8G8R8_UNORM_PACK32 } },
131     { AV_PIX_FMT_BGRA,   { VK_FORMAT_B8G8R8A8_UNORM } },
132     { AV_PIX_FMT_RGBA,   { VK_FORMAT_R8G8B8A8_UNORM } },
133     { AV_PIX_FMT_RGB24,  { VK_FORMAT_R8G8B8_UNORM } },
134     { AV_PIX_FMT_BGR24,  { VK_FORMAT_B8G8R8_UNORM } },
135     { AV_PIX_FMT_RGB48,  { VK_FORMAT_R16G16B16_UNORM } },
136     { AV_PIX_FMT_RGBA64, { VK_FORMAT_R16G16B16A16_UNORM } },
137     { AV_PIX_FMT_RGB565, { VK_FORMAT_R5G6B5_UNORM_PACK16 } },
138     { AV_PIX_FMT_BGR565, { VK_FORMAT_B5G6R5_UNORM_PACK16 } },
139     { AV_PIX_FMT_BGR0,   { VK_FORMAT_B8G8R8A8_UNORM } },
140     { AV_PIX_FMT_0BGR,   { VK_FORMAT_A8B8G8R8_UNORM_PACK32 } },
141     { AV_PIX_FMT_RGB0,   { VK_FORMAT_R8G8B8A8_UNORM } },
142
143     { AV_PIX_FMT_GBRPF32, { VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32_SFLOAT } },
144 };
145
146 const VkFormat *av_vkfmt_from_pixfmt(enum AVPixelFormat p)
147 {
148     for (enum AVPixelFormat i = 0; i < FF_ARRAY_ELEMS(vk_pixfmt_map); i++)
149         if (vk_pixfmt_map[i].pixfmt == p)
150             return vk_pixfmt_map[i].vkfmts;
151     return NULL;
152 }
153
154 static int pixfmt_is_supported(AVVulkanDeviceContext *hwctx, enum AVPixelFormat p,
155                                int linear)
156 {
157     const VkFormat *fmt = av_vkfmt_from_pixfmt(p);
158     int planes = av_pix_fmt_count_planes(p);
159
160     if (!fmt)
161         return 0;
162
163     for (int i = 0; i < planes; i++) {
164         VkFormatFeatureFlags flags;
165         VkFormatProperties2 prop = {
166             .sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2,
167         };
168         vkGetPhysicalDeviceFormatProperties2(hwctx->phys_dev, fmt[i], &prop);
169         flags = linear ? prop.formatProperties.linearTilingFeatures :
170                          prop.formatProperties.optimalTilingFeatures;
171         if (!(flags & DEFAULT_USAGE_FLAGS))
172             return 0;
173     }
174
175     return 1;
176 }
177
178 enum VulkanExtensions {
179     EXT_EXTERNAL_DMABUF_MEMORY = 1ULL <<  0, /* VK_EXT_external_memory_dma_buf */
180     EXT_DRM_MODIFIER_FLAGS     = 1ULL <<  1, /* VK_EXT_image_drm_format_modifier */
181     EXT_EXTERNAL_FD_MEMORY     = 1ULL <<  2, /* VK_KHR_external_memory_fd */
182     EXT_EXTERNAL_FD_SEM        = 1ULL <<  3, /* VK_KHR_external_semaphore_fd */
183
184     EXT_NO_FLAG                = 1ULL << 63,
185 };
186
187 typedef struct VulkanOptExtension {
188     const char *name;
189     uint64_t flag;
190 } VulkanOptExtension;
191
192 static const VulkanOptExtension optional_instance_exts[] = {
193     { VK_KHR_SURFACE_EXTENSION_NAME, EXT_NO_FLAG },
194 };
195
196 static const VulkanOptExtension optional_device_exts[] = {
197     { VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME,               EXT_EXTERNAL_FD_MEMORY,     },
198     { VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME,          EXT_EXTERNAL_DMABUF_MEMORY, },
199     { VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME,        EXT_DRM_MODIFIER_FLAGS,     },
200     { VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME,            EXT_EXTERNAL_FD_SEM,        },
201 };
202
203 /* Converts return values to strings */
204 static const char *vk_ret2str(VkResult res)
205 {
206 #define CASE(VAL) case VAL: return #VAL
207     switch (res) {
208     CASE(VK_SUCCESS);
209     CASE(VK_NOT_READY);
210     CASE(VK_TIMEOUT);
211     CASE(VK_EVENT_SET);
212     CASE(VK_EVENT_RESET);
213     CASE(VK_INCOMPLETE);
214     CASE(VK_ERROR_OUT_OF_HOST_MEMORY);
215     CASE(VK_ERROR_OUT_OF_DEVICE_MEMORY);
216     CASE(VK_ERROR_INITIALIZATION_FAILED);
217     CASE(VK_ERROR_DEVICE_LOST);
218     CASE(VK_ERROR_MEMORY_MAP_FAILED);
219     CASE(VK_ERROR_LAYER_NOT_PRESENT);
220     CASE(VK_ERROR_EXTENSION_NOT_PRESENT);
221     CASE(VK_ERROR_FEATURE_NOT_PRESENT);
222     CASE(VK_ERROR_INCOMPATIBLE_DRIVER);
223     CASE(VK_ERROR_TOO_MANY_OBJECTS);
224     CASE(VK_ERROR_FORMAT_NOT_SUPPORTED);
225     CASE(VK_ERROR_FRAGMENTED_POOL);
226     CASE(VK_ERROR_SURFACE_LOST_KHR);
227     CASE(VK_ERROR_NATIVE_WINDOW_IN_USE_KHR);
228     CASE(VK_SUBOPTIMAL_KHR);
229     CASE(VK_ERROR_OUT_OF_DATE_KHR);
230     CASE(VK_ERROR_INCOMPATIBLE_DISPLAY_KHR);
231     CASE(VK_ERROR_VALIDATION_FAILED_EXT);
232     CASE(VK_ERROR_INVALID_SHADER_NV);
233     CASE(VK_ERROR_OUT_OF_POOL_MEMORY);
234     CASE(VK_ERROR_INVALID_EXTERNAL_HANDLE);
235     CASE(VK_ERROR_NOT_PERMITTED_EXT);
236     CASE(VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT);
237     CASE(VK_ERROR_INVALID_DEVICE_ADDRESS_EXT);
238     CASE(VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT);
239     default: return "Unknown error";
240     }
241 #undef CASE
242 }
243
244 static VkBool32 vk_dbg_callback(VkDebugUtilsMessageSeverityFlagBitsEXT severity,
245                                 VkDebugUtilsMessageTypeFlagsEXT messageType,
246                                 const VkDebugUtilsMessengerCallbackDataEXT *data,
247                                 void *priv)
248 {
249     int l;
250     AVHWDeviceContext *ctx = priv;
251
252     switch (severity) {
253     case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT: l = AV_LOG_VERBOSE; break;
254     case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT:    l = AV_LOG_INFO;    break;
255     case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT: l = AV_LOG_WARNING; break;
256     case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT:   l = AV_LOG_ERROR;   break;
257     default:                                              l = AV_LOG_DEBUG;   break;
258     }
259
260     av_log(ctx, l, "%s\n", data->pMessage);
261     for (int i = 0; i < data->cmdBufLabelCount; i++)
262         av_log(ctx, l, "\t%i: %s\n", i, data->pCmdBufLabels[i].pLabelName);
263
264     return 0;
265 }
266
267 static int check_extensions(AVHWDeviceContext *ctx, int dev, AVDictionary *opts,
268                             const char * const **dst, uint32_t *num, int debug)
269 {
270     const char *tstr;
271     const char **extension_names = NULL;
272     VulkanDevicePriv *p = ctx->internal->priv;
273     AVVulkanDeviceContext *hwctx = ctx->hwctx;
274     int err = 0, found, extensions_found = 0;
275
276     const char *mod;
277     int optional_exts_num;
278     uint32_t sup_ext_count;
279     char *user_exts_str = NULL;
280     AVDictionaryEntry *user_exts;
281     VkExtensionProperties *sup_ext;
282     const VulkanOptExtension *optional_exts;
283
284     if (!dev) {
285         mod = "instance";
286         optional_exts = optional_instance_exts;
287         optional_exts_num = FF_ARRAY_ELEMS(optional_instance_exts);
288         user_exts = av_dict_get(opts, "instance_extensions", NULL, 0);
289         if (user_exts) {
290             user_exts_str = av_strdup(user_exts->value);
291             if (!user_exts_str) {
292                 err = AVERROR(ENOMEM);
293                 goto fail;
294             }
295         }
296         vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, NULL);
297         sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
298         if (!sup_ext)
299             return AVERROR(ENOMEM);
300         vkEnumerateInstanceExtensionProperties(NULL, &sup_ext_count, sup_ext);
301     } else {
302         mod = "device";
303         optional_exts = optional_device_exts;
304         optional_exts_num = FF_ARRAY_ELEMS(optional_device_exts);
305         user_exts = av_dict_get(opts, "device_extensions", NULL, 0);
306         if (user_exts) {
307             user_exts_str = av_strdup(user_exts->value);
308             if (!user_exts_str) {
309                 err = AVERROR(ENOMEM);
310                 goto fail;
311             }
312         }
313         vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
314                                              &sup_ext_count, NULL);
315         sup_ext = av_malloc_array(sup_ext_count, sizeof(VkExtensionProperties));
316         if (!sup_ext)
317             return AVERROR(ENOMEM);
318         vkEnumerateDeviceExtensionProperties(hwctx->phys_dev, NULL,
319                                              &sup_ext_count, sup_ext);
320     }
321
322     for (int i = 0; i < optional_exts_num; i++) {
323         tstr = optional_exts[i].name;
324         found = 0;
325         for (int j = 0; j < sup_ext_count; j++) {
326             if (!strcmp(tstr, sup_ext[j].extensionName)) {
327                 found = 1;
328                 break;
329             }
330         }
331         if (!found)
332             continue;
333
334         av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
335         p->extensions |= optional_exts[i].flag;
336         ADD_VAL_TO_LIST(extension_names, extensions_found, tstr);
337     }
338
339     if (debug && !dev) {
340         tstr = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
341         found = 0;
342         for (int j = 0; j < sup_ext_count; j++) {
343             if (!strcmp(tstr, sup_ext[j].extensionName)) {
344                 found = 1;
345                 break;
346             }
347         }
348         if (found) {
349             av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
350             ADD_VAL_TO_LIST(extension_names, extensions_found, tstr);
351         } else {
352             av_log(ctx, AV_LOG_ERROR, "Debug extension \"%s\" not found!\n",
353                    tstr);
354             err = AVERROR(EINVAL);
355             goto fail;
356         }
357     }
358
359     if (user_exts_str) {
360         char *save, *token = av_strtok(user_exts_str, "+", &save);
361         while (token) {
362             found = 0;
363             for (int j = 0; j < sup_ext_count; j++) {
364                 if (!strcmp(token, sup_ext[j].extensionName)) {
365                     found = 1;
366                     break;
367                 }
368             }
369             if (found) {
370                 av_log(ctx, AV_LOG_VERBOSE, "Using %s extension \"%s\"\n", mod, tstr);
371                 ADD_VAL_TO_LIST(extension_names, extensions_found, token);
372             } else {
373                 av_log(ctx, AV_LOG_ERROR, "%s extension \"%s\" not found!\n",
374                        mod, token);
375                 err = AVERROR(EINVAL);
376                 goto fail;
377             }
378             token = av_strtok(NULL, "+", &save);
379         }
380     }
381
382     *dst = extension_names;
383     *num = extensions_found;
384
385     av_free(user_exts_str);
386     av_free(sup_ext);
387     return 0;
388
389 fail:
390     if (extension_names)
391         for (int i = 0; i < extensions_found; i++)
392             av_free((void *)extension_names[i]);
393     av_free(extension_names);
394     av_free(user_exts_str);
395     av_free(sup_ext);
396     return err;
397 }
398
399 /* Creates a VkInstance */
400 static int create_instance(AVHWDeviceContext *ctx, AVDictionary *opts)
401 {
402     int err = 0;
403     VkResult ret;
404     VulkanDevicePriv *p = ctx->internal->priv;
405     AVVulkanDeviceContext *hwctx = ctx->hwctx;
406     AVDictionaryEntry *debug_opt = av_dict_get(opts, "debug", NULL, 0);
407     const int debug_mode = debug_opt && strtol(debug_opt->value, NULL, 10);
408     VkApplicationInfo application_info = {
409         .sType              = VK_STRUCTURE_TYPE_APPLICATION_INFO,
410         .pEngineName        = "libavutil",
411         .apiVersion         = VK_API_VERSION_1_1,
412         .engineVersion      = VK_MAKE_VERSION(LIBAVUTIL_VERSION_MAJOR,
413                                               LIBAVUTIL_VERSION_MINOR,
414                                               LIBAVUTIL_VERSION_MICRO),
415     };
416     VkInstanceCreateInfo inst_props = {
417         .sType            = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
418         .pApplicationInfo = &application_info,
419     };
420
421     /* Check for present/missing extensions */
422     err = check_extensions(ctx, 0, opts, &inst_props.ppEnabledExtensionNames,
423                            &inst_props.enabledExtensionCount, debug_mode);
424     if (err < 0)
425         return err;
426
427     if (debug_mode) {
428         static const char *layers[] = { "VK_LAYER_KHRONOS_validation" };
429         inst_props.ppEnabledLayerNames = layers;
430         inst_props.enabledLayerCount = FF_ARRAY_ELEMS(layers);
431     }
432
433     /* Try to create the instance */
434     ret = vkCreateInstance(&inst_props, hwctx->alloc, &hwctx->inst);
435
436     /* Check for errors */
437     if (ret != VK_SUCCESS) {
438         av_log(ctx, AV_LOG_ERROR, "Instance creation failure: %s\n",
439                vk_ret2str(ret));
440         for (int i = 0; i < inst_props.enabledExtensionCount; i++)
441             av_free((void *)inst_props.ppEnabledExtensionNames[i]);
442         av_free((void *)inst_props.ppEnabledExtensionNames);
443         return AVERROR_EXTERNAL;
444     }
445
446     if (debug_mode) {
447         VkDebugUtilsMessengerCreateInfoEXT dbg = {
448             .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT,
449             .messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT |
450                                VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT    |
451                                VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
452                                VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT,
453             .messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT    |
454                            VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
455                            VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT,
456             .pfnUserCallback = vk_dbg_callback,
457             .pUserData = ctx,
458         };
459         VK_LOAD_PFN(hwctx->inst, vkCreateDebugUtilsMessengerEXT);
460
461         pfn_vkCreateDebugUtilsMessengerEXT(hwctx->inst, &dbg,
462                                            hwctx->alloc, &p->debug_ctx);
463     }
464
465     hwctx->enabled_inst_extensions = inst_props.ppEnabledExtensionNames;
466     hwctx->nb_enabled_inst_extensions = inst_props.enabledExtensionCount;
467
468     return 0;
469 }
470
471 typedef struct VulkanDeviceSelection {
472     uint8_t uuid[VK_UUID_SIZE]; /* Will use this first unless !has_uuid */
473     int has_uuid;
474     const char *name; /* Will use this second unless NULL */
475     uint32_t pci_device; /* Will use this third unless 0x0 */
476     uint32_t vendor_id; /* Last resort to find something deterministic */
477     int index; /* Finally fall back to index */
478 } VulkanDeviceSelection;
479
480 static const char *vk_dev_type(enum VkPhysicalDeviceType type)
481 {
482     switch (type) {
483     case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: return "integrated";
484     case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU:   return "discrete";
485     case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU:    return "virtual";
486     case VK_PHYSICAL_DEVICE_TYPE_CPU:            return "software";
487     default:                                     return "unknown";
488     }
489 }
490
491 /* Finds a device */
492 static int find_device(AVHWDeviceContext *ctx, VulkanDeviceSelection *select)
493 {
494     int err = 0, choice = -1;
495     uint32_t num;
496     VkResult ret;
497     VkPhysicalDevice *devices = NULL;
498     VkPhysicalDeviceIDProperties *idp = NULL;
499     VkPhysicalDeviceProperties2 *prop = NULL;
500     VulkanDevicePriv *p = ctx->internal->priv;
501     AVVulkanDeviceContext *hwctx = ctx->hwctx;
502
503     ret = vkEnumeratePhysicalDevices(hwctx->inst, &num, NULL);
504     if (ret != VK_SUCCESS || !num) {
505         av_log(ctx, AV_LOG_ERROR, "No devices found: %s!\n", vk_ret2str(ret));
506         return AVERROR(ENODEV);
507     }
508
509     devices = av_malloc_array(num, sizeof(VkPhysicalDevice));
510     if (!devices)
511         return AVERROR(ENOMEM);
512
513     ret = vkEnumeratePhysicalDevices(hwctx->inst, &num, devices);
514     if (ret != VK_SUCCESS) {
515         av_log(ctx, AV_LOG_ERROR, "Failed enumerating devices: %s\n",
516                vk_ret2str(ret));
517         err = AVERROR(ENODEV);
518         goto end;
519     }
520
521     prop = av_mallocz_array(num, sizeof(*prop));
522     if (!prop) {
523         err = AVERROR(ENOMEM);
524         goto end;
525     }
526
527     idp = av_mallocz_array(num, sizeof(*idp));
528     if (!idp) {
529         err = AVERROR(ENOMEM);
530         goto end;
531     }
532
533     av_log(ctx, AV_LOG_VERBOSE, "GPU listing:\n");
534     for (int i = 0; i < num; i++) {
535         idp[i].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES;
536         prop[i].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
537         prop[i].pNext = &idp[i];
538
539         vkGetPhysicalDeviceProperties2(devices[i], &prop[i]);
540         av_log(ctx, AV_LOG_VERBOSE, "    %d: %s (%s) (0x%x)\n", i,
541                prop[i].properties.deviceName,
542                vk_dev_type(prop[i].properties.deviceType),
543                prop[i].properties.deviceID);
544     }
545
546     if (select->has_uuid) {
547         for (int i = 0; i < num; i++) {
548             if (!strncmp(idp[i].deviceUUID, select->uuid, VK_UUID_SIZE)) {
549                 choice = i;
550                 goto end;
551              }
552         }
553         av_log(ctx, AV_LOG_ERROR, "Unable to find device by given UUID!\n");
554         err = AVERROR(ENODEV);
555         goto end;
556     } else if (select->name) {
557         av_log(ctx, AV_LOG_VERBOSE, "Requested device: %s\n", select->name);
558         for (int i = 0; i < num; i++) {
559             if (strstr(prop[i].properties.deviceName, select->name)) {
560                 choice = i;
561                 goto end;
562              }
563         }
564         av_log(ctx, AV_LOG_ERROR, "Unable to find device \"%s\"!\n",
565                select->name);
566         err = AVERROR(ENODEV);
567         goto end;
568     } else if (select->pci_device) {
569         av_log(ctx, AV_LOG_VERBOSE, "Requested device: 0x%x\n", select->pci_device);
570         for (int i = 0; i < num; i++) {
571             if (select->pci_device == prop[i].properties.deviceID) {
572                 choice = i;
573                 goto end;
574             }
575         }
576         av_log(ctx, AV_LOG_ERROR, "Unable to find device with PCI ID 0x%x!\n",
577                select->pci_device);
578         err = AVERROR(EINVAL);
579         goto end;
580     } else if (select->vendor_id) {
581         av_log(ctx, AV_LOG_VERBOSE, "Requested vendor: 0x%x\n", select->vendor_id);
582         for (int i = 0; i < num; i++) {
583             if (select->vendor_id == prop[i].properties.vendorID) {
584                 choice = i;
585                 goto end;
586             }
587         }
588         av_log(ctx, AV_LOG_ERROR, "Unable to find device with Vendor ID 0x%x!\n",
589                select->vendor_id);
590         err = AVERROR(ENODEV);
591         goto end;
592     } else {
593         if (select->index < num) {
594             choice = select->index;
595             goto end;
596         }
597         av_log(ctx, AV_LOG_ERROR, "Unable to find device with index %i!\n",
598                select->index);
599         err = AVERROR(ENODEV);
600         goto end;
601     }
602
603 end:
604     if (choice > -1) {
605         p->dev_is_nvidia = (prop[choice].properties.vendorID == 0x10de);
606         hwctx->phys_dev = devices[choice];
607     }
608     av_free(devices);
609     av_free(prop);
610     av_free(idp);
611
612     return err;
613 }
614
615 static int search_queue_families(AVHWDeviceContext *ctx, VkDeviceCreateInfo *cd)
616 {
617     uint32_t num;
618     VkQueueFamilyProperties *qs = NULL;
619     AVVulkanDeviceContext *hwctx = ctx->hwctx;
620     int graph_index = -1, comp_index = -1, tx_index = -1;
621     VkDeviceQueueCreateInfo *pc = (VkDeviceQueueCreateInfo *)cd->pQueueCreateInfos;
622
623     /* First get the number of queue families */
624     vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, NULL);
625     if (!num) {
626         av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
627         return AVERROR_EXTERNAL;
628     }
629
630     /* Then allocate memory */
631     qs = av_malloc_array(num, sizeof(VkQueueFamilyProperties));
632     if (!qs)
633         return AVERROR(ENOMEM);
634
635     /* Finally retrieve the queue families */
636     vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &num, qs);
637
638 #define SEARCH_FLAGS(expr, out)                                                \
639     for (int i = 0; i < num; i++) {                                            \
640         const VkQueueFlagBits flags = qs[i].queueFlags;                        \
641         if (expr) {                                                            \
642             out = i;                                                           \
643             break;                                                             \
644         }                                                                      \
645     }
646
647     SEARCH_FLAGS(flags & VK_QUEUE_GRAPHICS_BIT, graph_index)
648
649     SEARCH_FLAGS((flags &  VK_QUEUE_COMPUTE_BIT) && (i != graph_index),
650                  comp_index)
651
652     SEARCH_FLAGS((flags & VK_QUEUE_TRANSFER_BIT) && (i != graph_index) &&
653                  (i != comp_index), tx_index)
654
655 #undef SEARCH_FLAGS
656 #define QF_FLAGS(flags)                                                        \
657     ((flags) & VK_QUEUE_GRAPHICS_BIT      ) ? "(graphics) " : "",              \
658     ((flags) & VK_QUEUE_COMPUTE_BIT       ) ? "(compute) "  : "",              \
659     ((flags) & VK_QUEUE_TRANSFER_BIT      ) ? "(transfer) " : "",              \
660     ((flags) & VK_QUEUE_SPARSE_BINDING_BIT) ? "(sparse) "   : ""
661
662     av_log(ctx, AV_LOG_VERBOSE, "Using queue family %i for graphics, "
663            "flags: %s%s%s%s\n", graph_index, QF_FLAGS(qs[graph_index].queueFlags));
664
665     hwctx->queue_family_index      = graph_index;
666     hwctx->queue_family_tx_index   = graph_index;
667     hwctx->queue_family_comp_index = graph_index;
668
669     pc[cd->queueCreateInfoCount++].queueFamilyIndex = graph_index;
670
671     if (comp_index != -1) {
672         av_log(ctx, AV_LOG_VERBOSE, "Using queue family %i for compute, "
673                "flags: %s%s%s%s\n", comp_index, QF_FLAGS(qs[comp_index].queueFlags));
674         hwctx->queue_family_tx_index                    = comp_index;
675         hwctx->queue_family_comp_index                  = comp_index;
676         pc[cd->queueCreateInfoCount++].queueFamilyIndex = comp_index;
677     }
678
679     if (tx_index != -1) {
680         av_log(ctx, AV_LOG_VERBOSE, "Using queue family %i for transfers, "
681                "flags: %s%s%s%s\n", tx_index, QF_FLAGS(qs[tx_index].queueFlags));
682         hwctx->queue_family_tx_index                    = tx_index;
683         pc[cd->queueCreateInfoCount++].queueFamilyIndex = tx_index;
684     }
685
686 #undef QF_FLAGS
687
688     av_free(qs);
689
690     return 0;
691 }
692
693 static int create_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd,
694                            int queue_family_index)
695 {
696     VkResult ret;
697     AVVulkanDeviceContext *hwctx = ctx->hwctx;
698
699     VkCommandPoolCreateInfo cqueue_create = {
700         .sType              = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
701         .flags              = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
702         .queueFamilyIndex   = queue_family_index,
703     };
704     VkCommandBufferAllocateInfo cbuf_create = {
705         .sType              = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
706         .level              = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
707         .commandBufferCount = 1,
708     };
709
710     VkFenceCreateInfo fence_spawn = {
711         .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
712     };
713
714     ret = vkCreateFence(hwctx->act_dev, &fence_spawn,
715                         hwctx->alloc, &cmd->fence);
716     if (ret != VK_SUCCESS) {
717         av_log(ctx, AV_LOG_ERROR, "Failed to create frame fence: %s\n",
718                vk_ret2str(ret));
719         return AVERROR_EXTERNAL;
720     }
721
722     ret = vkCreateCommandPool(hwctx->act_dev, &cqueue_create,
723                               hwctx->alloc, &cmd->pool);
724     if (ret != VK_SUCCESS) {
725         av_log(ctx, AV_LOG_ERROR, "Command pool creation failure: %s\n",
726                vk_ret2str(ret));
727         return AVERROR_EXTERNAL;
728     }
729
730     cbuf_create.commandPool = cmd->pool;
731
732     ret = vkAllocateCommandBuffers(hwctx->act_dev, &cbuf_create, &cmd->buf);
733     if (ret != VK_SUCCESS) {
734         av_log(ctx, AV_LOG_ERROR, "Command buffer alloc failure: %s\n",
735                vk_ret2str(ret));
736         return AVERROR_EXTERNAL;
737     }
738
739     vkGetDeviceQueue(hwctx->act_dev, cqueue_create.queueFamilyIndex, 0,
740                      &cmd->queue);
741
742     return 0;
743 }
744
745 static void free_exec_ctx(AVHWDeviceContext *ctx, VulkanExecCtx *cmd)
746 {
747     AVVulkanDeviceContext *hwctx = ctx->hwctx;
748
749     if (cmd->fence)
750         vkDestroyFence(hwctx->act_dev, cmd->fence, hwctx->alloc);
751     if (cmd->buf)
752         vkFreeCommandBuffers(hwctx->act_dev, cmd->pool, 1, &cmd->buf);
753     if (cmd->pool)
754         vkDestroyCommandPool(hwctx->act_dev, cmd->pool, hwctx->alloc);
755 }
756
757 static void vulkan_device_free(AVHWDeviceContext *ctx)
758 {
759     VulkanDevicePriv *p = ctx->internal->priv;
760     AVVulkanDeviceContext *hwctx = ctx->hwctx;
761
762     free_exec_ctx(ctx, &p->cmd);
763
764     vkDestroyDevice(hwctx->act_dev, hwctx->alloc);
765
766     if (p->debug_ctx) {
767         VK_LOAD_PFN(hwctx->inst, vkDestroyDebugUtilsMessengerEXT);
768         pfn_vkDestroyDebugUtilsMessengerEXT(hwctx->inst, p->debug_ctx,
769                                             hwctx->alloc);
770     }
771
772     vkDestroyInstance(hwctx->inst, hwctx->alloc);
773
774     for (int i = 0; i < hwctx->nb_enabled_inst_extensions; i++)
775         av_free((void *)hwctx->enabled_inst_extensions[i]);
776     av_free((void *)hwctx->enabled_inst_extensions);
777
778     for (int i = 0; i < hwctx->nb_enabled_dev_extensions; i++)
779         av_free((void *)hwctx->enabled_dev_extensions[i]);
780     av_free((void *)hwctx->enabled_dev_extensions);
781 }
782
783 static int vulkan_device_create_internal(AVHWDeviceContext *ctx,
784                                          VulkanDeviceSelection *dev_select,
785                                          AVDictionary *opts, int flags)
786 {
787     int err = 0;
788     VkResult ret;
789     AVDictionaryEntry *opt_d;
790     VulkanDevicePriv *p = ctx->internal->priv;
791     AVVulkanDeviceContext *hwctx = ctx->hwctx;
792     VkDeviceQueueCreateInfo queue_create_info[3] = {
793         {   .sType            = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
794             .pQueuePriorities = (float []){ 1.0f },
795             .queueCount       = 1, },
796         {   .sType            = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
797             .pQueuePriorities = (float []){ 1.0f },
798             .queueCount       = 1, },
799         {   .sType            = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
800             .pQueuePriorities = (float []){ 1.0f },
801             .queueCount       = 1, },
802     };
803
804     VkDeviceCreateInfo dev_info = {
805         .sType                = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
806         .pQueueCreateInfos    = queue_create_info,
807         .queueCreateInfoCount = 0,
808     };
809
810     ctx->free = vulkan_device_free;
811
812     /* Create an instance if not given one */
813     if ((err = create_instance(ctx, opts)))
814         goto end;
815
816     /* Find a device (if not given one) */
817     if ((err = find_device(ctx, dev_select)))
818         goto end;
819
820     vkGetPhysicalDeviceProperties(hwctx->phys_dev, &p->props);
821     av_log(ctx, AV_LOG_VERBOSE, "Using device: %s\n", p->props.deviceName);
822     av_log(ctx, AV_LOG_VERBOSE, "Alignments:\n");
823     av_log(ctx, AV_LOG_VERBOSE, "    optimalBufferCopyOffsetAlignment:   %li\n",
824            p->props.limits.optimalBufferCopyOffsetAlignment);
825     av_log(ctx, AV_LOG_VERBOSE, "    optimalBufferCopyRowPitchAlignment: %li\n",
826            p->props.limits.optimalBufferCopyRowPitchAlignment);
827     av_log(ctx, AV_LOG_VERBOSE, "    minMemoryMapAlignment:              %li\n",
828            p->props.limits.minMemoryMapAlignment);
829
830     /* Search queue family */
831     if ((err = search_queue_families(ctx, &dev_info)))
832         goto end;
833
834     if ((err = check_extensions(ctx, 1, opts, &dev_info.ppEnabledExtensionNames,
835                                 &dev_info.enabledExtensionCount, 0)))
836         goto end;
837
838     ret = vkCreateDevice(hwctx->phys_dev, &dev_info, hwctx->alloc,
839                          &hwctx->act_dev);
840
841     if (ret != VK_SUCCESS) {
842         av_log(ctx, AV_LOG_ERROR, "Device creation failure: %s\n",
843                vk_ret2str(ret));
844         for (int i = 0; i < dev_info.enabledExtensionCount; i++)
845             av_free((void *)dev_info.ppEnabledExtensionNames[i]);
846         av_free((void *)dev_info.ppEnabledExtensionNames);
847         err = AVERROR_EXTERNAL;
848         goto end;
849     }
850
851     /* Tiled images setting, use them by default */
852     opt_d = av_dict_get(opts, "linear_images", NULL, 0);
853     if (opt_d)
854         p->use_linear_images = strtol(opt_d->value, NULL, 10);
855
856     hwctx->enabled_dev_extensions = dev_info.ppEnabledExtensionNames;
857     hwctx->nb_enabled_dev_extensions = dev_info.enabledExtensionCount;
858
859 end:
860     return err;
861 }
862
863 static int vulkan_device_init(AVHWDeviceContext *ctx)
864 {
865     int err;
866     uint32_t queue_num;
867     AVVulkanDeviceContext *hwctx = ctx->hwctx;
868     VulkanDevicePriv *p = ctx->internal->priv;
869
870     /* Set device extension flags */
871     for (int i = 0; i < hwctx->nb_enabled_dev_extensions; i++) {
872         for (int j = 0; j < FF_ARRAY_ELEMS(optional_device_exts); j++) {
873             if (!strcmp(hwctx->enabled_dev_extensions[i],
874                         optional_device_exts[j].name)) {
875                 p->extensions |= optional_device_exts[j].flag;
876                 break;
877             }
878         }
879     }
880
881     vkGetPhysicalDeviceQueueFamilyProperties(hwctx->phys_dev, &queue_num, NULL);
882     if (!queue_num) {
883         av_log(ctx, AV_LOG_ERROR, "Failed to get queues!\n");
884         return AVERROR_EXTERNAL;
885     }
886
887 #define CHECK_QUEUE(type, n)                                                         \
888 if (n >= queue_num) {                                                                \
889     av_log(ctx, AV_LOG_ERROR, "Invalid %s queue index %i (device has %i queues)!\n", \
890            type, n, queue_num);                                                      \
891     return AVERROR(EINVAL);                                                          \
892 }
893
894     CHECK_QUEUE("graphics", hwctx->queue_family_index)
895     CHECK_QUEUE("upload",   hwctx->queue_family_tx_index)
896     CHECK_QUEUE("compute",  hwctx->queue_family_comp_index)
897
898 #undef CHECK_QUEUE
899
900     /* Create exec context - if there's something invalid this will error out */
901     err = create_exec_ctx(ctx, &p->cmd, hwctx->queue_family_tx_index);
902     if (err)
903         return err;
904
905     /* Get device capabilities */
906     vkGetPhysicalDeviceMemoryProperties(hwctx->phys_dev, &p->mprops);
907
908     return 0;
909 }
910
911 static int vulkan_device_create(AVHWDeviceContext *ctx, const char *device,
912                                 AVDictionary *opts, int flags)
913 {
914     VulkanDeviceSelection dev_select = { 0 };
915     if (device && device[0]) {
916         char *end = NULL;
917         dev_select.index = strtol(device, &end, 10);
918         if (end == device) {
919             dev_select.index = 0;
920             dev_select.name  = device;
921         }
922     }
923
924     return vulkan_device_create_internal(ctx, &dev_select, opts, flags);
925 }
926
927 static int vulkan_device_derive(AVHWDeviceContext *ctx,
928                                 AVHWDeviceContext *src_ctx, int flags)
929 {
930     av_unused VulkanDeviceSelection dev_select = { 0 };
931
932     /* If there's only one device on the system, then even if its not covered
933      * by the following checks (e.g. non-PCIe ARM GPU), having an empty
934      * dev_select will mean it'll get picked. */
935     switch(src_ctx->type) {
936 #if CONFIG_LIBDRM
937 #if CONFIG_VAAPI
938     case AV_HWDEVICE_TYPE_VAAPI: {
939         AVVAAPIDeviceContext *src_hwctx = src_ctx->hwctx;
940
941         const char *vendor = vaQueryVendorString(src_hwctx->display);
942         if (!vendor) {
943             av_log(ctx, AV_LOG_ERROR, "Unable to get device info from VAAPI!\n");
944             return AVERROR_EXTERNAL;
945         }
946
947         if (strstr(vendor, "Intel"))
948             dev_select.vendor_id = 0x8086;
949         if (strstr(vendor, "AMD"))
950             dev_select.vendor_id = 0x1002;
951
952         return vulkan_device_create_internal(ctx, &dev_select, NULL, flags);
953     }
954 #endif
955     case AV_HWDEVICE_TYPE_DRM: {
956         AVDRMDeviceContext *src_hwctx = src_ctx->hwctx;
957
958         drmDevice *drm_dev_info;
959         int err = drmGetDevice(src_hwctx->fd, &drm_dev_info);
960         if (err) {
961             av_log(ctx, AV_LOG_ERROR, "Unable to get device info from DRM fd!\n");
962             return AVERROR_EXTERNAL;
963         }
964
965         if (drm_dev_info->bustype == DRM_BUS_PCI)
966             dev_select.pci_device = drm_dev_info->deviceinfo.pci->device_id;
967
968         drmFreeDevice(&drm_dev_info);
969
970         return vulkan_device_create_internal(ctx, &dev_select, NULL, flags);
971     }
972 #endif
973 #if CONFIG_CUDA
974     case AV_HWDEVICE_TYPE_CUDA: {
975         AVHWDeviceContext *cuda_cu = src_ctx;
976         AVCUDADeviceContext *src_hwctx = src_ctx->hwctx;
977         AVCUDADeviceContextInternal *cu_internal = src_hwctx->internal;
978         CudaFunctions *cu = cu_internal->cuda_dl;
979
980         int ret = CHECK_CU(cu->cuDeviceGetUuid((CUuuid *)&dev_select.uuid,
981                                                cu_internal->cuda_device));
982         if (ret < 0) {
983             av_log(ctx, AV_LOG_ERROR, "Unable to get UUID from CUDA!\n");
984             return AVERROR_EXTERNAL;
985         }
986
987         dev_select.has_uuid = 1;
988
989         return vulkan_device_create_internal(ctx, &dev_select, NULL, flags);
990     }
991 #endif
992     default:
993         return AVERROR(ENOSYS);
994     }
995 }
996
997 static int vulkan_frames_get_constraints(AVHWDeviceContext *ctx,
998                                          const void *hwconfig,
999                                          AVHWFramesConstraints *constraints)
1000 {
1001     int count = 0;
1002     AVVulkanDeviceContext *hwctx = ctx->hwctx;
1003     VulkanDevicePriv *p = ctx->internal->priv;
1004
1005     for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
1006         count += pixfmt_is_supported(hwctx, i, p->use_linear_images);
1007
1008 #if CONFIG_CUDA
1009     if (p->dev_is_nvidia)
1010         count++;
1011 #endif
1012
1013     constraints->valid_sw_formats = av_malloc_array(count + 1,
1014                                                     sizeof(enum AVPixelFormat));
1015     if (!constraints->valid_sw_formats)
1016         return AVERROR(ENOMEM);
1017
1018     count = 0;
1019     for (enum AVPixelFormat i = 0; i < AV_PIX_FMT_NB; i++)
1020         if (pixfmt_is_supported(hwctx, i, p->use_linear_images))
1021             constraints->valid_sw_formats[count++] = i;
1022
1023 #if CONFIG_CUDA
1024     if (p->dev_is_nvidia)
1025         constraints->valid_sw_formats[count++] = AV_PIX_FMT_CUDA;
1026 #endif
1027     constraints->valid_sw_formats[count++] = AV_PIX_FMT_NONE;
1028
1029     constraints->min_width  = 0;
1030     constraints->min_height = 0;
1031     constraints->max_width  = p->props.limits.maxImageDimension2D;
1032     constraints->max_height = p->props.limits.maxImageDimension2D;
1033
1034     constraints->valid_hw_formats = av_malloc_array(2, sizeof(enum AVPixelFormat));
1035     if (!constraints->valid_hw_formats)
1036         return AVERROR(ENOMEM);
1037
1038     constraints->valid_hw_formats[0] = AV_PIX_FMT_VULKAN;
1039     constraints->valid_hw_formats[1] = AV_PIX_FMT_NONE;
1040
1041     return 0;
1042 }
1043
1044 static int alloc_mem(AVHWDeviceContext *ctx, VkMemoryRequirements *req,
1045                      VkMemoryPropertyFlagBits req_flags, void *alloc_extension,
1046                      VkMemoryPropertyFlagBits *mem_flags, VkDeviceMemory *mem)
1047 {
1048     VkResult ret;
1049     int index = -1;
1050     VulkanDevicePriv *p = ctx->internal->priv;
1051     AVVulkanDeviceContext *dev_hwctx = ctx->hwctx;
1052     VkMemoryAllocateInfo alloc_info = {
1053         .sType           = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
1054         .pNext           = alloc_extension,
1055     };
1056
1057     /* Align if we need to */
1058     if (req_flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)
1059         req->size = FFALIGN(req->size, p->props.limits.minMemoryMapAlignment);
1060
1061     alloc_info.allocationSize = req->size;
1062
1063     /* The vulkan spec requires memory types to be sorted in the "optimal"
1064      * order, so the first matching type we find will be the best/fastest one */
1065     for (int i = 0; i < p->mprops.memoryTypeCount; i++) {
1066         /* The memory type must be supported by the requirements (bitfield) */
1067         if (!(req->memoryTypeBits & (1 << i)))
1068             continue;
1069
1070         /* The memory type flags must include our properties */
1071         if ((p->mprops.memoryTypes[i].propertyFlags & req_flags) != req_flags)
1072             continue;
1073
1074         /* Found a suitable memory type */
1075         index = i;
1076         break;
1077     }
1078
1079     if (index < 0) {
1080         av_log(ctx, AV_LOG_ERROR, "No memory type found for flags 0x%x\n",
1081                req_flags);
1082         return AVERROR(EINVAL);
1083     }
1084
1085     alloc_info.memoryTypeIndex = index;
1086
1087     ret = vkAllocateMemory(dev_hwctx->act_dev, &alloc_info,
1088                            dev_hwctx->alloc, mem);
1089     if (ret != VK_SUCCESS) {
1090         av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory: %s\n",
1091                vk_ret2str(ret));
1092         return AVERROR(ENOMEM);
1093     }
1094
1095     *mem_flags |= p->mprops.memoryTypes[index].propertyFlags;
1096
1097     return 0;
1098 }
1099
1100 static void vulkan_free_internal(AVVkFrameInternal *internal)
1101 {
1102     if (!internal)
1103         return;
1104
1105 #if CONFIG_CUDA
1106     if (internal->cuda_fc_ref) {
1107         AVHWFramesContext *cuda_fc = (AVHWFramesContext *)internal->cuda_fc_ref->data;
1108         int planes = av_pix_fmt_count_planes(cuda_fc->sw_format);
1109         AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
1110         AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
1111         AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
1112         CudaFunctions *cu = cu_internal->cuda_dl;
1113
1114         if (internal->cu_sem)
1115             CHECK_CU(cu->cuDestroyExternalSemaphore(internal->cu_sem));
1116
1117         for (int i = 0; i < planes; i++) {
1118             if (internal->cu_mma[i])
1119                 CHECK_CU(cu->cuMipmappedArrayDestroy(internal->cu_mma[i]));
1120             if (internal->ext_mem[i])
1121                 CHECK_CU(cu->cuDestroyExternalMemory(internal->ext_mem[i]));
1122         }
1123
1124         av_buffer_unref(&internal->cuda_fc_ref);
1125     }
1126 #endif
1127
1128     av_free(internal);
1129 }
1130
1131 static void vulkan_frame_free(void *opaque, uint8_t *data)
1132 {
1133     AVVkFrame *f = (AVVkFrame *)data;
1134     AVHWFramesContext *hwfc = opaque;
1135     AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1136     int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1137
1138     vulkan_free_internal(f->internal);
1139
1140     for (int i = 0; i < planes; i++) {
1141         vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
1142         vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
1143     }
1144
1145     vkDestroySemaphore(hwctx->act_dev, f->sem, hwctx->alloc);
1146
1147     av_free(f);
1148 }
1149
1150 static int alloc_bind_mem(AVHWFramesContext *hwfc, AVVkFrame *f,
1151                           void *alloc_pnext, size_t alloc_pnext_stride)
1152 {
1153     int err;
1154     VkResult ret;
1155     AVHWDeviceContext *ctx = hwfc->device_ctx;
1156     const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1157     VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { { 0 } };
1158
1159     AVVulkanDeviceContext *hwctx = ctx->hwctx;
1160
1161     for (int i = 0; i < planes; i++) {
1162         int use_ded_mem;
1163         VkImageMemoryRequirementsInfo2 req_desc = {
1164             .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
1165             .image = f->img[i],
1166         };
1167         VkMemoryDedicatedAllocateInfo ded_alloc = {
1168             .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
1169             .pNext = (void *)(((uint8_t *)alloc_pnext) + i*alloc_pnext_stride),
1170         };
1171         VkMemoryDedicatedRequirements ded_req = {
1172             .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
1173         };
1174         VkMemoryRequirements2 req = {
1175             .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
1176             .pNext = &ded_req,
1177         };
1178
1179         vkGetImageMemoryRequirements2(hwctx->act_dev, &req_desc, &req);
1180
1181         /* In case the implementation prefers/requires dedicated allocation */
1182         use_ded_mem = ded_req.prefersDedicatedAllocation |
1183                       ded_req.requiresDedicatedAllocation;
1184         if (use_ded_mem)
1185             ded_alloc.image = f->img[i];
1186
1187         /* Allocate memory */
1188         if ((err = alloc_mem(ctx, &req.memoryRequirements,
1189                              f->tiling == VK_IMAGE_TILING_LINEAR ?
1190                              VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT :
1191                              VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1192                              use_ded_mem ? &ded_alloc : (void *)ded_alloc.pNext,
1193                              &f->flags, &f->mem[i])))
1194             return err;
1195
1196         f->size[i] = req.memoryRequirements.size;
1197         bind_info[i].sType  = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
1198         bind_info[i].image  = f->img[i];
1199         bind_info[i].memory = f->mem[i];
1200     }
1201
1202     /* Bind the allocated memory to the images */
1203     ret = vkBindImageMemory2(hwctx->act_dev, planes, bind_info);
1204     if (ret != VK_SUCCESS) {
1205         av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
1206                vk_ret2str(ret));
1207         return AVERROR_EXTERNAL;
1208     }
1209
1210     return 0;
1211 }
1212
1213 enum PrepMode {
1214     PREP_MODE_WRITE,
1215     PREP_MODE_RO_SHADER,
1216 };
1217
1218 static int prepare_frame(AVHWFramesContext *hwfc, VulkanExecCtx *ectx,
1219                          AVVkFrame *frame, enum PrepMode pmode)
1220 {
1221     VkResult ret;
1222     VkImageLayout new_layout;
1223     VkAccessFlags new_access;
1224     AVHWDeviceContext *ctx = hwfc->device_ctx;
1225     AVVulkanDeviceContext *hwctx = ctx->hwctx;
1226     const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1227
1228     VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
1229
1230     VkCommandBufferBeginInfo cmd_start = {
1231         .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
1232         .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
1233     };
1234
1235     VkSubmitInfo s_info = {
1236         .sType                = VK_STRUCTURE_TYPE_SUBMIT_INFO,
1237         .commandBufferCount   = 1,
1238         .pCommandBuffers      = &ectx->buf,
1239
1240         .pSignalSemaphores    = &frame->sem,
1241         .signalSemaphoreCount = 1,
1242     };
1243
1244     switch (pmode) {
1245     case PREP_MODE_WRITE:
1246         new_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
1247         new_access = VK_ACCESS_TRANSFER_WRITE_BIT;
1248         break;
1249     case PREP_MODE_RO_SHADER:
1250         new_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
1251         new_access = VK_ACCESS_TRANSFER_READ_BIT;
1252         break;
1253     }
1254
1255     ret = vkBeginCommandBuffer(ectx->buf, &cmd_start);
1256     if (ret != VK_SUCCESS)
1257         return AVERROR_EXTERNAL;
1258
1259     /* Change the image layout to something more optimal for writes.
1260      * This also signals the newly created semaphore, making it usable
1261      * for synchronization */
1262     for (int i = 0; i < planes; i++) {
1263         img_bar[i].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1264         img_bar[i].srcAccessMask = 0x0;
1265         img_bar[i].dstAccessMask = new_access;
1266         img_bar[i].oldLayout = frame->layout[i];
1267         img_bar[i].newLayout = new_layout;
1268         img_bar[i].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1269         img_bar[i].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1270         img_bar[i].image = frame->img[i];
1271         img_bar[i].subresourceRange.levelCount = 1;
1272         img_bar[i].subresourceRange.layerCount = 1;
1273         img_bar[i].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1274
1275         frame->layout[i] = img_bar[i].newLayout;
1276         frame->access[i] = img_bar[i].dstAccessMask;
1277     }
1278
1279     vkCmdPipelineBarrier(ectx->buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
1280                          VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
1281                          0, NULL, 0, NULL, planes, img_bar);
1282
1283     ret = vkEndCommandBuffer(ectx->buf);
1284     if (ret != VK_SUCCESS)
1285         return AVERROR_EXTERNAL;
1286
1287     ret = vkQueueSubmit(ectx->queue, 1, &s_info, ectx->fence);
1288     if (ret != VK_SUCCESS) {
1289         return AVERROR_EXTERNAL;
1290     } else {
1291         vkWaitForFences(hwctx->act_dev, 1, &ectx->fence, VK_TRUE, UINT64_MAX);
1292         vkResetFences(hwctx->act_dev, 1, &ectx->fence);
1293     }
1294
1295     return 0;
1296 }
1297
1298 static int create_frame(AVHWFramesContext *hwfc, AVVkFrame **frame,
1299                         VkImageTiling tiling, VkImageUsageFlagBits usage,
1300                         void *create_pnext)
1301 {
1302     int err;
1303     VkResult ret;
1304     AVHWDeviceContext *ctx = hwfc->device_ctx;
1305     VulkanDevicePriv *p = ctx->internal->priv;
1306     AVVulkanDeviceContext *hwctx = ctx->hwctx;
1307     enum AVPixelFormat format = hwfc->sw_format;
1308     const VkFormat *img_fmts = av_vkfmt_from_pixfmt(format);
1309     const int planes = av_pix_fmt_count_planes(format);
1310
1311     VkExportSemaphoreCreateInfo ext_sem_info = {
1312         .sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO,
1313         .handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
1314     };
1315
1316     VkSemaphoreCreateInfo sem_spawn = {
1317         .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1318         .pNext = p->extensions & EXT_EXTERNAL_FD_SEM ? &ext_sem_info : NULL,
1319     };
1320
1321     AVVkFrame *f = av_vk_frame_alloc();
1322     if (!f) {
1323         av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1324         return AVERROR(ENOMEM);
1325     }
1326
1327     /* Create the images */
1328     for (int i = 0; i < planes; i++) {
1329         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
1330         int w = hwfc->width;
1331         int h = hwfc->height;
1332         const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
1333         const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
1334
1335         VkImageCreateInfo image_create_info = {
1336             .sType         = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1337             .pNext         = create_pnext,
1338             .imageType     = VK_IMAGE_TYPE_2D,
1339             .format        = img_fmts[i],
1340             .extent.width  = p_w,
1341             .extent.height = p_h,
1342             .extent.depth  = 1,
1343             .mipLevels     = 1,
1344             .arrayLayers   = 1,
1345             .flags         = VK_IMAGE_CREATE_ALIAS_BIT,
1346             .tiling        = tiling,
1347             .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1348             .usage         = usage,
1349             .sharingMode   = VK_SHARING_MODE_EXCLUSIVE,
1350             .samples       = VK_SAMPLE_COUNT_1_BIT,
1351         };
1352
1353         ret = vkCreateImage(hwctx->act_dev, &image_create_info,
1354                             hwctx->alloc, &f->img[i]);
1355         if (ret != VK_SUCCESS) {
1356             av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1357                    vk_ret2str(ret));
1358             err = AVERROR(EINVAL);
1359             goto fail;
1360         }
1361
1362         f->layout[i] = image_create_info.initialLayout;
1363         f->access[i] = 0x0;
1364     }
1365
1366     /* Create semaphore */
1367     ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1368                             hwctx->alloc, &f->sem);
1369     if (ret != VK_SUCCESS) {
1370         av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1371                vk_ret2str(ret));
1372         return AVERROR_EXTERNAL;
1373     }
1374
1375     f->flags     = 0x0;
1376     f->tiling    = tiling;
1377
1378     *frame = f;
1379     return 0;
1380
1381 fail:
1382     vulkan_frame_free(hwfc, (uint8_t *)f);
1383     return err;
1384 }
1385
1386 /* Checks if an export flag is enabled, and if it is ORs it with *iexp */
1387 static void try_export_flags(AVHWFramesContext *hwfc,
1388                              VkExternalMemoryHandleTypeFlags *comp_handle_types,
1389                              VkExternalMemoryHandleTypeFlagBits *iexp,
1390                              VkExternalMemoryHandleTypeFlagBits exp)
1391 {
1392     VkResult ret;
1393     AVVulkanFramesContext *hwctx = hwfc->hwctx;
1394     AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1395     VkExternalImageFormatProperties eprops = {
1396         .sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES_KHR,
1397     };
1398     VkImageFormatProperties2 props = {
1399         .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,
1400         .pNext = &eprops,
1401     };
1402     VkPhysicalDeviceExternalImageFormatInfo enext = {
1403         .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
1404         .handleType = exp,
1405     };
1406     VkPhysicalDeviceImageFormatInfo2 pinfo = {
1407         .sType  = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1408         .pNext  = !exp ? NULL : &enext,
1409         .format = av_vkfmt_from_pixfmt(hwfc->sw_format)[0],
1410         .type   = VK_IMAGE_TYPE_2D,
1411         .tiling = hwctx->tiling,
1412         .usage  = hwctx->usage,
1413         .flags  = VK_IMAGE_CREATE_ALIAS_BIT,
1414     };
1415
1416     ret = vkGetPhysicalDeviceImageFormatProperties2(dev_hwctx->phys_dev,
1417                                                     &pinfo, &props);
1418     if (ret == VK_SUCCESS) {
1419         *iexp |= exp;
1420         *comp_handle_types |= eprops.externalMemoryProperties.compatibleHandleTypes;
1421     }
1422 }
1423
1424 static AVBufferRef *vulkan_pool_alloc(void *opaque, int size)
1425 {
1426     int err;
1427     AVVkFrame *f;
1428     AVBufferRef *avbuf = NULL;
1429     AVHWFramesContext *hwfc = opaque;
1430     AVVulkanFramesContext *hwctx = hwfc->hwctx;
1431     VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1432     VkExportMemoryAllocateInfo eminfo[AV_NUM_DATA_POINTERS];
1433     VkExternalMemoryHandleTypeFlags e = 0x0;
1434
1435     VkExternalMemoryImageCreateInfo eiinfo = {
1436         .sType       = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1437         .pNext       = hwctx->create_pnext,
1438     };
1439
1440     if (p->extensions & EXT_EXTERNAL_FD_MEMORY)
1441         try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1442                          VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT);
1443
1444     if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
1445         try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1446                          VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
1447
1448     for (int i = 0; i < av_pix_fmt_count_planes(hwfc->sw_format); i++) {
1449         eminfo[i].sType       = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO;
1450         eminfo[i].pNext       = hwctx->alloc_pnext[i];
1451         eminfo[i].handleTypes = e;
1452     }
1453
1454     err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1455                        eiinfo.handleTypes ? &eiinfo : NULL);
1456     if (err)
1457         return NULL;
1458
1459     err = alloc_bind_mem(hwfc, f, eminfo, sizeof(*eminfo));
1460     if (err)
1461         goto fail;
1462
1463     err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_WRITE);
1464     if (err)
1465         goto fail;
1466
1467     avbuf = av_buffer_create((uint8_t *)f, sizeof(AVVkFrame),
1468                              vulkan_frame_free, hwfc, 0);
1469     if (!avbuf)
1470         goto fail;
1471
1472     return avbuf;
1473
1474 fail:
1475     vulkan_frame_free(hwfc, (uint8_t *)f);
1476     return NULL;
1477 }
1478
1479 static void vulkan_frames_uninit(AVHWFramesContext *hwfc)
1480 {
1481     VulkanFramesPriv *fp = hwfc->internal->priv;
1482
1483     free_exec_ctx(hwfc->device_ctx, &fp->cmd);
1484 }
1485
1486 static int vulkan_frames_init(AVHWFramesContext *hwfc)
1487 {
1488     int err;
1489     AVVkFrame *f;
1490     AVVulkanFramesContext *hwctx = hwfc->hwctx;
1491     VulkanFramesPriv *fp = hwfc->internal->priv;
1492     AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1493     VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1494
1495     if (hwfc->pool)
1496         return 0;
1497
1498     /* Default pool flags */
1499     hwctx->tiling = hwctx->tiling ? hwctx->tiling : p->use_linear_images ?
1500                     VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1501
1502     hwctx->usage |= DEFAULT_USAGE_FLAGS;
1503
1504     err = create_exec_ctx(hwfc->device_ctx, &fp->cmd,
1505                           dev_hwctx->queue_family_tx_index);
1506     if (err)
1507         return err;
1508
1509     /* Test to see if allocation will fail */
1510     err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1511                        hwctx->create_pnext);
1512     if (err) {
1513         free_exec_ctx(hwfc->device_ctx, &p->cmd);
1514         return err;
1515     }
1516
1517     vulkan_frame_free(hwfc, (uint8_t *)f);
1518
1519     hwfc->internal->pool_internal = av_buffer_pool_init2(sizeof(AVVkFrame),
1520                                                          hwfc, vulkan_pool_alloc,
1521                                                          NULL);
1522     if (!hwfc->internal->pool_internal) {
1523         free_exec_ctx(hwfc->device_ctx, &p->cmd);
1524         return AVERROR(ENOMEM);
1525     }
1526
1527     return 0;
1528 }
1529
1530 static int vulkan_get_buffer(AVHWFramesContext *hwfc, AVFrame *frame)
1531 {
1532     frame->buf[0] = av_buffer_pool_get(hwfc->pool);
1533     if (!frame->buf[0])
1534         return AVERROR(ENOMEM);
1535
1536     frame->data[0] = frame->buf[0]->data;
1537     frame->format  = AV_PIX_FMT_VULKAN;
1538     frame->width   = hwfc->width;
1539     frame->height  = hwfc->height;
1540
1541     return 0;
1542 }
1543
1544 static int vulkan_transfer_get_formats(AVHWFramesContext *hwfc,
1545                                        enum AVHWFrameTransferDirection dir,
1546                                        enum AVPixelFormat **formats)
1547 {
1548     enum AVPixelFormat *fmts = av_malloc_array(2, sizeof(*fmts));
1549     if (!fmts)
1550         return AVERROR(ENOMEM);
1551
1552     fmts[0] = hwfc->sw_format;
1553     fmts[1] = AV_PIX_FMT_NONE;
1554
1555     *formats = fmts;
1556     return 0;
1557 }
1558
1559 typedef struct VulkanMapping {
1560     AVVkFrame *frame;
1561     int flags;
1562 } VulkanMapping;
1563
1564 static void vulkan_unmap_frame(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1565 {
1566     VulkanMapping *map = hwmap->priv;
1567     AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1568     const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1569
1570     /* Check if buffer needs flushing */
1571     if ((map->flags & AV_HWFRAME_MAP_WRITE) &&
1572         !(map->frame->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1573         VkResult ret;
1574         VkMappedMemoryRange flush_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1575
1576         for (int i = 0; i < planes; i++) {
1577             flush_ranges[i].sType  = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1578             flush_ranges[i].memory = map->frame->mem[i];
1579             flush_ranges[i].size   = VK_WHOLE_SIZE;
1580         }
1581
1582         ret = vkFlushMappedMemoryRanges(hwctx->act_dev, planes,
1583                                         flush_ranges);
1584         if (ret != VK_SUCCESS) {
1585             av_log(hwfc, AV_LOG_ERROR, "Failed to flush memory: %s\n",
1586                    vk_ret2str(ret));
1587         }
1588     }
1589
1590     for (int i = 0; i < planes; i++)
1591         vkUnmapMemory(hwctx->act_dev, map->frame->mem[i]);
1592
1593     av_free(map);
1594 }
1595
1596 static int vulkan_map_frame_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
1597                                    const AVFrame *src, int flags)
1598 {
1599     VkResult ret;
1600     int err, mapped_mem_count = 0;
1601     AVVkFrame *f = (AVVkFrame *)src->data[0];
1602     AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1603     const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1604
1605     VulkanMapping *map = av_mallocz(sizeof(VulkanMapping));
1606     if (!map)
1607         return AVERROR(EINVAL);
1608
1609     if (src->format != AV_PIX_FMT_VULKAN) {
1610         av_log(hwfc, AV_LOG_ERROR, "Cannot map from pixel format %s!\n",
1611                av_get_pix_fmt_name(src->format));
1612         err = AVERROR(EINVAL);
1613         goto fail;
1614     }
1615
1616     if (!(f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ||
1617         !(f->tiling == VK_IMAGE_TILING_LINEAR)) {
1618         av_log(hwfc, AV_LOG_ERROR, "Unable to map frame, not host visible "
1619                "and linear!\n");
1620         err = AVERROR(EINVAL);
1621         goto fail;
1622     }
1623
1624     dst->width  = src->width;
1625     dst->height = src->height;
1626
1627     for (int i = 0; i < planes; i++) {
1628         ret = vkMapMemory(hwctx->act_dev, f->mem[i], 0,
1629                           VK_WHOLE_SIZE, 0, (void **)&dst->data[i]);
1630         if (ret != VK_SUCCESS) {
1631             av_log(hwfc, AV_LOG_ERROR, "Failed to map image memory: %s\n",
1632                 vk_ret2str(ret));
1633             err = AVERROR_EXTERNAL;
1634             goto fail;
1635         }
1636         mapped_mem_count++;
1637     }
1638
1639     /* Check if the memory contents matter */
1640     if (((flags & AV_HWFRAME_MAP_READ) || !(flags & AV_HWFRAME_MAP_OVERWRITE)) &&
1641         !(f->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1642         VkMappedMemoryRange map_mem_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1643         for (int i = 0; i < planes; i++) {
1644             map_mem_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1645             map_mem_ranges[i].size = VK_WHOLE_SIZE;
1646             map_mem_ranges[i].memory = f->mem[i];
1647         }
1648
1649         ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, planes,
1650                                              map_mem_ranges);
1651         if (ret != VK_SUCCESS) {
1652             av_log(hwfc, AV_LOG_ERROR, "Failed to invalidate memory: %s\n",
1653                    vk_ret2str(ret));
1654             err = AVERROR_EXTERNAL;
1655             goto fail;
1656         }
1657     }
1658
1659     for (int i = 0; i < planes; i++) {
1660         VkImageSubresource sub = {
1661             .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
1662         };
1663         VkSubresourceLayout layout;
1664         vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
1665         dst->linesize[i] = layout.rowPitch;
1666     }
1667
1668     map->frame = f;
1669     map->flags = flags;
1670
1671     err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src,
1672                                 &vulkan_unmap_frame, map);
1673     if (err < 0)
1674         goto fail;
1675
1676     return 0;
1677
1678 fail:
1679     for (int i = 0; i < mapped_mem_count; i++)
1680         vkUnmapMemory(hwctx->act_dev, f->mem[i]);
1681
1682     av_free(map);
1683     return err;
1684 }
1685
1686 #if CONFIG_LIBDRM
1687 static void vulkan_unmap_from(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1688 {
1689     VulkanMapping *map = hwmap->priv;
1690     AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1691     const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1692
1693     for (int i = 0; i < planes; i++) {
1694         vkDestroyImage(hwctx->act_dev, map->frame->img[i], hwctx->alloc);
1695         vkFreeMemory(hwctx->act_dev, map->frame->mem[i], hwctx->alloc);
1696     }
1697
1698     vkDestroySemaphore(hwctx->act_dev, map->frame->sem, hwctx->alloc);
1699
1700     av_freep(&map->frame);
1701 }
1702
1703 static const struct {
1704     uint32_t drm_fourcc;
1705     VkFormat vk_format;
1706 } vulkan_drm_format_map[] = {
1707     { DRM_FORMAT_R8,       VK_FORMAT_R8_UNORM       },
1708     { DRM_FORMAT_R16,      VK_FORMAT_R16_UNORM      },
1709     { DRM_FORMAT_GR88,     VK_FORMAT_R8G8_UNORM     },
1710     { DRM_FORMAT_RG88,     VK_FORMAT_R8G8_UNORM     },
1711     { DRM_FORMAT_GR1616,   VK_FORMAT_R16G16_UNORM   },
1712     { DRM_FORMAT_RG1616,   VK_FORMAT_R16G16_UNORM   },
1713     { DRM_FORMAT_ARGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1714     { DRM_FORMAT_XRGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1715     { DRM_FORMAT_ABGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1716     { DRM_FORMAT_XBGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1717 };
1718
1719 static inline VkFormat drm_to_vulkan_fmt(uint32_t drm_fourcc)
1720 {
1721     for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
1722         if (vulkan_drm_format_map[i].drm_fourcc == drm_fourcc)
1723             return vulkan_drm_format_map[i].vk_format;
1724     return VK_FORMAT_UNDEFINED;
1725 }
1726
1727 static int vulkan_map_from_drm_frame_desc(AVHWFramesContext *hwfc, AVVkFrame **frame,
1728                                           AVDRMFrameDescriptor *desc)
1729 {
1730     int err = 0;
1731     VkResult ret;
1732     AVVkFrame *f;
1733     int bind_counts = 0;
1734     AVHWDeviceContext *ctx = hwfc->device_ctx;
1735     AVVulkanDeviceContext *hwctx = ctx->hwctx;
1736     VulkanDevicePriv *p = ctx->internal->priv;
1737     const AVPixFmtDescriptor *fmt_desc = av_pix_fmt_desc_get(hwfc->sw_format);
1738     const int has_modifiers = p->extensions & EXT_DRM_MODIFIER_FLAGS;
1739     VkSubresourceLayout plane_data[AV_NUM_DATA_POINTERS] = { 0 };
1740     VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { 0 };
1741     VkBindImagePlaneMemoryInfo plane_info[AV_NUM_DATA_POINTERS] = { 0 };
1742     VkExternalMemoryHandleTypeFlagBits htype = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
1743     VkSemaphoreCreateInfo sem_spawn = {
1744         .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1745     };
1746
1747     VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdPropertiesKHR);
1748
1749     for (int i = 0; i < desc->nb_layers; i++) {
1750         if (drm_to_vulkan_fmt(desc->layers[i].format) == VK_FORMAT_UNDEFINED) {
1751             av_log(ctx, AV_LOG_ERROR, "Unsupported DMABUF layer format %#08x!\n",
1752                    desc->layers[i].format);
1753             return AVERROR(EINVAL);
1754         }
1755     }
1756
1757     if (!(f = av_vk_frame_alloc())) {
1758         av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1759         err = AVERROR(ENOMEM);
1760         goto fail;
1761     }
1762
1763     for (int i = 0; i < desc->nb_objects; i++) {
1764         VkMemoryFdPropertiesKHR fdmp = {
1765             .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,
1766         };
1767         VkMemoryRequirements req = {
1768             .size = desc->objects[i].size,
1769         };
1770         VkImportMemoryFdInfoKHR idesc = {
1771             .sType      = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
1772             .handleType = htype,
1773             .fd         = dup(desc->objects[i].fd),
1774         };
1775
1776         ret = pfn_vkGetMemoryFdPropertiesKHR(hwctx->act_dev, htype,
1777                                              idesc.fd, &fdmp);
1778         if (ret != VK_SUCCESS) {
1779             av_log(hwfc, AV_LOG_ERROR, "Failed to get FD properties: %s\n",
1780                    vk_ret2str(ret));
1781             err = AVERROR_EXTERNAL;
1782             close(idesc.fd);
1783             goto fail;
1784         }
1785
1786         req.memoryTypeBits = fdmp.memoryTypeBits;
1787
1788         err = alloc_mem(ctx, &req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1789                         &idesc, &f->flags, &f->mem[i]);
1790         if (err) {
1791             close(idesc.fd);
1792             return err;
1793         }
1794
1795         f->size[i] = desc->objects[i].size;
1796     }
1797
1798     f->tiling = has_modifiers ? VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT :
1799                 desc->objects[0].format_modifier == DRM_FORMAT_MOD_LINEAR ?
1800                 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1801
1802     for (int i = 0; i < desc->nb_layers; i++) {
1803         const int planes = desc->layers[i].nb_planes;
1804         const int signal_p = has_modifiers && (planes > 1);
1805
1806         VkImageDrmFormatModifierExplicitCreateInfoEXT drm_info = {
1807             .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
1808             .drmFormatModifier = desc->objects[0].format_modifier,
1809             .drmFormatModifierPlaneCount = planes,
1810             .pPlaneLayouts = (const VkSubresourceLayout *)&plane_data,
1811         };
1812
1813         VkExternalMemoryImageCreateInfo einfo = {
1814             .sType       = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1815             .pNext       = has_modifiers ? &drm_info : NULL,
1816             .handleTypes = htype,
1817         };
1818
1819         const int p_w = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, fmt_desc->log2_chroma_w) : hwfc->width;
1820         const int p_h = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, fmt_desc->log2_chroma_h) : hwfc->height;
1821
1822         VkImageCreateInfo image_create_info = {
1823             .sType         = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1824             .pNext         = &einfo,
1825             .imageType     = VK_IMAGE_TYPE_2D,
1826             .format        = drm_to_vulkan_fmt(desc->layers[i].format),
1827             .extent.width  = p_w,
1828             .extent.height = p_h,
1829             .extent.depth  = 1,
1830             .mipLevels     = 1,
1831             .arrayLayers   = 1,
1832             .flags         = VK_IMAGE_CREATE_ALIAS_BIT |
1833                              (signal_p ? VK_IMAGE_CREATE_DISJOINT_BIT : 0x0),
1834             .tiling        = f->tiling,
1835             .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, /* specs say so */
1836             .usage         = DEFAULT_USAGE_FLAGS,
1837             .sharingMode   = VK_SHARING_MODE_EXCLUSIVE,
1838             .samples       = VK_SAMPLE_COUNT_1_BIT,
1839         };
1840
1841         for (int j = 0; j < planes; j++) {
1842             plane_data[j].offset     = desc->layers[i].planes[j].offset;
1843             plane_data[j].rowPitch   = desc->layers[i].planes[j].pitch;
1844             plane_data[j].size       = 0; /* The specs say so for all 3 */
1845             plane_data[j].arrayPitch = 0;
1846             plane_data[j].depthPitch = 0;
1847         }
1848
1849         /* Create image */
1850         ret = vkCreateImage(hwctx->act_dev, &image_create_info,
1851                             hwctx->alloc, &f->img[i]);
1852         if (ret != VK_SUCCESS) {
1853             av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1854                    vk_ret2str(ret));
1855             err = AVERROR(EINVAL);
1856             goto fail;
1857         }
1858
1859         f->layout[i] = image_create_info.initialLayout;
1860         f->access[i] = 0x0;
1861
1862         for (int j = 0; j < planes; j++) {
1863             VkImageAspectFlagBits aspect = j == 0 ? VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
1864                                            j == 1 ? VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT :
1865                                                     VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT;
1866
1867             plane_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO;
1868             plane_info[bind_counts].planeAspect = aspect;
1869
1870             bind_info[bind_counts].sType  = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
1871             bind_info[bind_counts].pNext  = signal_p ? &plane_info[bind_counts] : NULL;
1872             bind_info[bind_counts].image  = f->img[i];
1873             bind_info[bind_counts].memory = f->mem[desc->layers[i].planes[j].object_index];
1874             bind_info[bind_counts].memoryOffset = desc->layers[i].planes[j].offset;
1875             bind_counts++;
1876         }
1877     }
1878
1879     ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1880                             hwctx->alloc, &f->sem);
1881     if (ret != VK_SUCCESS) {
1882         av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1883                vk_ret2str(ret));
1884         return AVERROR_EXTERNAL;
1885     }
1886
1887     /* We'd import a semaphore onto the one we created using
1888      * vkImportSemaphoreFdKHR but unfortunately neither DRM nor VAAPI
1889      * offer us anything we could import and sync with, so instead
1890      * just signal the semaphore we created. */
1891
1892     /* Bind the allocated memory to the images */
1893     ret = vkBindImageMemory2(hwctx->act_dev, bind_counts, bind_info);
1894     if (ret != VK_SUCCESS) {
1895         av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
1896                vk_ret2str(ret));
1897         return AVERROR_EXTERNAL;
1898     }
1899
1900     /* NOTE: This is completely uneccesary and unneeded once we can import
1901      * semaphores from DRM. Otherwise we have to activate the semaphores.
1902      * We're reusing the exec context that's also used for uploads/downloads. */
1903     err = prepare_frame(hwfc, &p->cmd, f, PREP_MODE_RO_SHADER);
1904     if (err)
1905         goto fail;
1906
1907     *frame = f;
1908
1909     return 0;
1910
1911 fail:
1912     for (int i = 0; i < desc->nb_layers; i++)
1913         vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
1914     for (int i = 0; i < desc->nb_objects; i++)
1915         vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
1916     vkDestroySemaphore(hwctx->act_dev, f->sem, hwctx->alloc);
1917
1918     av_free(f);
1919
1920     return err;
1921 }
1922
1923 static int vulkan_map_from_drm(AVHWFramesContext *hwfc, AVFrame *dst,
1924                                const AVFrame *src, int flags)
1925 {
1926     int err = 0;
1927     AVVkFrame *f;
1928     VulkanMapping *map = NULL;
1929
1930     err = vulkan_map_from_drm_frame_desc(hwfc, &f,
1931                                          (AVDRMFrameDescriptor *)src->data[0]);
1932     if (err)
1933         return err;
1934
1935     /* The unmapping function will free this */
1936     dst->data[0] = (uint8_t *)f;
1937     dst->width   = src->width;
1938     dst->height  = src->height;
1939
1940     map = av_mallocz(sizeof(VulkanMapping));
1941     if (!map)
1942         goto fail;
1943
1944     map->frame = f;
1945     map->flags = flags;
1946
1947     err = ff_hwframe_map_create(dst->hw_frames_ctx, dst, src,
1948                                 &vulkan_unmap_from, map);
1949     if (err < 0)
1950         goto fail;
1951
1952     av_log(hwfc, AV_LOG_DEBUG, "Mapped DRM object to Vulkan!\n");
1953
1954     return 0;
1955
1956 fail:
1957     vulkan_frame_free(hwfc->device_ctx->hwctx, (uint8_t *)f);
1958     av_free(map);
1959     return err;
1960 }
1961
1962 #if CONFIG_VAAPI
1963 static int vulkan_map_from_vaapi(AVHWFramesContext *dst_fc,
1964                                  AVFrame *dst, const AVFrame *src,
1965                                  int flags)
1966 {
1967     int err;
1968     AVFrame *tmp = av_frame_alloc();
1969     AVHWFramesContext *vaapi_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
1970     AVVAAPIDeviceContext *vaapi_ctx = vaapi_fc->device_ctx->hwctx;
1971     VASurfaceID surface_id = (VASurfaceID)(uintptr_t)src->data[3];
1972
1973     if (!tmp)
1974         return AVERROR(ENOMEM);
1975
1976     /* We have to sync since like the previous comment said, no semaphores */
1977     vaSyncSurface(vaapi_ctx->display, surface_id);
1978
1979     tmp->format = AV_PIX_FMT_DRM_PRIME;
1980
1981     err = av_hwframe_map(tmp, src, flags);
1982     if (err < 0)
1983         goto fail;
1984
1985     err = vulkan_map_from_drm(dst_fc, dst, tmp, flags);
1986     if (err < 0)
1987         goto fail;
1988
1989     err = ff_hwframe_map_replace(dst, src);
1990
1991 fail:
1992     av_frame_free(&tmp);
1993     return err;
1994 }
1995 #endif
1996 #endif
1997
1998 #if CONFIG_CUDA
1999 static int vulkan_export_to_cuda(AVHWFramesContext *hwfc,
2000                                  AVBufferRef *cuda_hwfc,
2001                                  const AVFrame *frame)
2002 {
2003     int err;
2004     VkResult ret;
2005     AVVkFrame *dst_f;
2006     AVVkFrameInternal *dst_int;
2007     AVHWDeviceContext *ctx = hwfc->device_ctx;
2008     AVVulkanDeviceContext *hwctx = ctx->hwctx;
2009     const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2010     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2011     VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2012     VK_LOAD_PFN(hwctx->inst, vkGetSemaphoreFdKHR);
2013
2014     AVHWFramesContext *cuda_fc = (AVHWFramesContext*)cuda_hwfc->data;
2015     AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2016     AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2017     AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2018     CudaFunctions *cu = cu_internal->cuda_dl;
2019     CUarray_format cufmt = desc->comp[0].depth > 8 ? CU_AD_FORMAT_UNSIGNED_INT16 :
2020                                                      CU_AD_FORMAT_UNSIGNED_INT8;
2021
2022     dst_f = (AVVkFrame *)frame->data[0];
2023
2024     dst_int = dst_f->internal;
2025     if (!dst_int || !dst_int->cuda_fc_ref) {
2026         VkSemaphoreGetFdInfoKHR sem_export = {
2027             .sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR,
2028             .semaphore = dst_f->sem,
2029             .handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
2030         };
2031         CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC ext_sem_desc = {
2032             .type = CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD,
2033         };
2034
2035         if (!dst_f->internal)
2036             dst_f->internal = dst_int = av_mallocz(sizeof(*dst_f->internal));
2037
2038         if (!dst_int) {
2039             err = AVERROR(ENOMEM);
2040             goto fail;
2041         }
2042
2043         dst_int->cuda_fc_ref = av_buffer_ref(cuda_hwfc);
2044         if (!dst_int->cuda_fc_ref) {
2045             err = AVERROR(ENOMEM);
2046             goto fail;
2047         }
2048
2049         for (int i = 0; i < planes; i++) {
2050             CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC tex_desc = {
2051                 .offset = 0,
2052                 .arrayDesc = {
2053                     .Width  = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2054                                     : hwfc->width,
2055                     .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2056                                     : hwfc->height,
2057                     .Depth = 0,
2058                     .Format = cufmt,
2059                     .NumChannels = 1 + ((planes == 2) && i),
2060                     .Flags = 0,
2061                 },
2062                 .numLevels = 1,
2063             };
2064             CUDA_EXTERNAL_MEMORY_HANDLE_DESC ext_desc = {
2065                 .type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD,
2066                 .size = dst_f->size[i],
2067             };
2068             VkMemoryGetFdInfoKHR export_info = {
2069                 .sType      = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2070                 .memory     = dst_f->mem[i],
2071                 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR,
2072             };
2073
2074             ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2075                                        &ext_desc.handle.fd);
2076             if (ret != VK_SUCCESS) {
2077                 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2078                 err = AVERROR_EXTERNAL;
2079                 goto fail;
2080             }
2081
2082             ret = CHECK_CU(cu->cuImportExternalMemory(&dst_int->ext_mem[i], &ext_desc));
2083             if (ret < 0) {
2084                 err = AVERROR_EXTERNAL;
2085                 goto fail;
2086             }
2087
2088             ret = CHECK_CU(cu->cuExternalMemoryGetMappedMipmappedArray(&dst_int->cu_mma[i],
2089                                                                        dst_int->ext_mem[i],
2090                                                                        &tex_desc));
2091             if (ret < 0) {
2092                 err = AVERROR_EXTERNAL;
2093                 goto fail;
2094             }
2095
2096             ret = CHECK_CU(cu->cuMipmappedArrayGetLevel(&dst_int->cu_array[i],
2097                                                         dst_int->cu_mma[i], 0));
2098             if (ret < 0) {
2099                 err = AVERROR_EXTERNAL;
2100                 goto fail;
2101             }
2102         }
2103
2104         ret = pfn_vkGetSemaphoreFdKHR(hwctx->act_dev, &sem_export,
2105                                       &ext_sem_desc.handle.fd);
2106         if (ret != VK_SUCCESS) {
2107             av_log(ctx, AV_LOG_ERROR, "Failed to export semaphore: %s\n",
2108                    vk_ret2str(ret));
2109             err = AVERROR_EXTERNAL;
2110             goto fail;
2111         }
2112
2113         ret = CHECK_CU(cu->cuImportExternalSemaphore(&dst_int->cu_sem,
2114                                                      &ext_sem_desc));
2115         if (ret < 0) {
2116             err = AVERROR_EXTERNAL;
2117             goto fail;
2118         }
2119     }
2120
2121     return 0;
2122
2123 fail:
2124     return err;
2125 }
2126
2127 static int vulkan_transfer_data_from_cuda(AVHWFramesContext *hwfc,
2128                                           AVFrame *dst, const AVFrame *src)
2129 {
2130     int err;
2131     VkResult ret;
2132     CUcontext dummy;
2133     AVVkFrame *dst_f;
2134     AVVkFrameInternal *dst_int;
2135     const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2136     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2137
2138     AVHWFramesContext *cuda_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2139     AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2140     AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2141     AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2142     CudaFunctions *cu = cu_internal->cuda_dl;
2143     CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS s_w_par = { 0 };
2144     CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS s_s_par = { 0 };
2145
2146     ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2147     if (ret < 0) {
2148         err = AVERROR_EXTERNAL;
2149         goto fail;
2150     }
2151
2152     dst_f = (AVVkFrame *)dst->data[0];
2153
2154     ret = vulkan_export_to_cuda(hwfc, src->hw_frames_ctx, dst);
2155     if (ret < 0) {
2156         goto fail;
2157     }
2158     dst_int = dst_f->internal;
2159
2160     ret = CHECK_CU(cu->cuWaitExternalSemaphoresAsync(&dst_int->cu_sem, &s_w_par,
2161                                                      1, cuda_dev->stream));
2162     if (ret < 0) {
2163         err = AVERROR_EXTERNAL;
2164         goto fail;
2165     }
2166
2167     for (int i = 0; i < planes; i++) {
2168         CUDA_MEMCPY2D cpy = {
2169             .srcMemoryType = CU_MEMORYTYPE_DEVICE,
2170             .srcDevice     = (CUdeviceptr)src->data[i],
2171             .srcPitch      = src->linesize[i],
2172             .srcY          = 0,
2173
2174             .dstMemoryType = CU_MEMORYTYPE_ARRAY,
2175             .dstArray      = dst_int->cu_array[i],
2176             .WidthInBytes  = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2177                                     : hwfc->width) * desc->comp[i].step,
2178             .Height        = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2179                                    : hwfc->height,
2180         };
2181
2182         ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2183         if (ret < 0) {
2184             err = AVERROR_EXTERNAL;
2185             goto fail;
2186         }
2187     }
2188
2189     ret = CHECK_CU(cu->cuSignalExternalSemaphoresAsync(&dst_int->cu_sem, &s_s_par,
2190                                                        1, cuda_dev->stream));
2191     if (ret < 0) {
2192         err = AVERROR_EXTERNAL;
2193         goto fail;
2194     }
2195
2196     CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2197
2198     av_log(hwfc, AV_LOG_VERBOSE, "Transfered CUDA image to Vulkan!\n");
2199
2200     return 0;
2201
2202 fail:
2203     CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2204     vulkan_free_internal(dst_int);
2205     dst_f->internal = NULL;
2206     av_buffer_unref(&dst->buf[0]);
2207     return err;
2208 }
2209 #endif
2210
2211 static int vulkan_map_to(AVHWFramesContext *hwfc, AVFrame *dst,
2212                          const AVFrame *src, int flags)
2213 {
2214     av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2215
2216     switch (src->format) {
2217 #if CONFIG_LIBDRM
2218 #if CONFIG_VAAPI
2219     case AV_PIX_FMT_VAAPI:
2220         if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2221             return vulkan_map_from_vaapi(hwfc, dst, src, flags);
2222 #endif
2223     case AV_PIX_FMT_DRM_PRIME:
2224         if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2225             return vulkan_map_from_drm(hwfc, dst, src, flags);
2226 #endif
2227     default:
2228         return AVERROR(ENOSYS);
2229     }
2230 }
2231
2232 #if CONFIG_LIBDRM
2233 typedef struct VulkanDRMMapping {
2234     AVDRMFrameDescriptor drm_desc;
2235     AVVkFrame *source;
2236 } VulkanDRMMapping;
2237
2238 static void vulkan_unmap_to_drm(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
2239 {
2240     AVDRMFrameDescriptor *drm_desc = hwmap->priv;
2241
2242     for (int i = 0; i < drm_desc->nb_objects; i++)
2243         close(drm_desc->objects[i].fd);
2244
2245     av_free(drm_desc);
2246 }
2247
2248 static inline uint32_t vulkan_fmt_to_drm(VkFormat vkfmt)
2249 {
2250     for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
2251         if (vulkan_drm_format_map[i].vk_format == vkfmt)
2252             return vulkan_drm_format_map[i].drm_fourcc;
2253     return DRM_FORMAT_INVALID;
2254 }
2255
2256 static int vulkan_map_to_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2257                              const AVFrame *src, int flags)
2258 {
2259     int err = 0;
2260     VkResult ret;
2261     AVVkFrame *f = (AVVkFrame *)src->data[0];
2262     VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2263     AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
2264     const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2265     VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2266     VkImageDrmFormatModifierPropertiesEXT drm_mod = {
2267         .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT,
2268     };
2269
2270     AVDRMFrameDescriptor *drm_desc = av_mallocz(sizeof(*drm_desc));
2271     if (!drm_desc)
2272         return AVERROR(ENOMEM);
2273
2274     err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src, &vulkan_unmap_to_drm, drm_desc);
2275     if (err < 0)
2276         goto end;
2277
2278     if (p->extensions & EXT_DRM_MODIFIER_FLAGS) {
2279         VK_LOAD_PFN(hwctx->inst, vkGetImageDrmFormatModifierPropertiesEXT);
2280         ret = pfn_vkGetImageDrmFormatModifierPropertiesEXT(hwctx->act_dev, f->img[0],
2281                                                            &drm_mod);
2282         if (ret != VK_SUCCESS) {
2283             av_log(hwfc, AV_LOG_ERROR, "Failed to retrieve DRM format modifier!\n");
2284             err = AVERROR_EXTERNAL;
2285             goto end;
2286         }
2287     }
2288
2289     for (int i = 0; (i < planes) && (f->mem[i]); i++) {
2290         VkMemoryGetFdInfoKHR export_info = {
2291             .sType      = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2292             .memory     = f->mem[i],
2293             .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,
2294         };
2295
2296         ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2297                                    &drm_desc->objects[i].fd);
2298         if (ret != VK_SUCCESS) {
2299             av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2300             err = AVERROR_EXTERNAL;
2301             goto end;
2302         }
2303
2304         drm_desc->nb_objects++;
2305         drm_desc->objects[i].size = f->size[i];
2306         drm_desc->objects[i].format_modifier = drm_mod.drmFormatModifier;
2307     }
2308
2309     drm_desc->nb_layers = planes;
2310     for (int i = 0; i < drm_desc->nb_layers; i++) {
2311         VkSubresourceLayout layout;
2312         VkImageSubresource sub = {
2313             .aspectMask = p->extensions & EXT_DRM_MODIFIER_FLAGS ?
2314                           VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2315                           VK_IMAGE_ASPECT_COLOR_BIT,
2316         };
2317         VkFormat plane_vkfmt = av_vkfmt_from_pixfmt(hwfc->sw_format)[i];
2318
2319         drm_desc->layers[i].format    = vulkan_fmt_to_drm(plane_vkfmt);
2320         drm_desc->layers[i].nb_planes = 1;
2321
2322         if (drm_desc->layers[i].format == DRM_FORMAT_INVALID) {
2323             av_log(hwfc, AV_LOG_ERROR, "Cannot map to DRM layer, unsupported!\n");
2324             err = AVERROR_PATCHWELCOME;
2325             goto end;
2326         }
2327
2328         drm_desc->layers[i].planes[0].object_index = FFMIN(i, drm_desc->nb_objects - 1);
2329
2330         if (f->tiling != VK_IMAGE_TILING_OPTIMAL)
2331             continue;
2332
2333         vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
2334         drm_desc->layers[i].planes[0].offset       = layout.offset;
2335         drm_desc->layers[i].planes[0].pitch        = layout.rowPitch;
2336     }
2337
2338     dst->width   = src->width;
2339     dst->height  = src->height;
2340     dst->data[0] = (uint8_t *)drm_desc;
2341
2342     av_log(hwfc, AV_LOG_VERBOSE, "Mapped AVVkFrame to a DRM object!\n");
2343
2344     return 0;
2345
2346 end:
2347     av_free(drm_desc);
2348     return err;
2349 }
2350
2351 #if CONFIG_VAAPI
2352 static int vulkan_map_to_vaapi(AVHWFramesContext *hwfc, AVFrame *dst,
2353                                const AVFrame *src, int flags)
2354 {
2355     int err;
2356     AVFrame *tmp = av_frame_alloc();
2357     if (!tmp)
2358         return AVERROR(ENOMEM);
2359
2360     tmp->format = AV_PIX_FMT_DRM_PRIME;
2361
2362     err = vulkan_map_to_drm(hwfc, tmp, src, flags);
2363     if (err < 0)
2364         goto fail;
2365
2366     err = av_hwframe_map(dst, tmp, flags);
2367     if (err < 0)
2368         goto fail;
2369
2370     err = ff_hwframe_map_replace(dst, src);
2371
2372 fail:
2373     av_frame_free(&tmp);
2374     return err;
2375 }
2376 #endif
2377 #endif
2378
2379 static int vulkan_map_from(AVHWFramesContext *hwfc, AVFrame *dst,
2380                            const AVFrame *src, int flags)
2381 {
2382     av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2383
2384     switch (dst->format) {
2385 #if CONFIG_LIBDRM
2386     case AV_PIX_FMT_DRM_PRIME:
2387         if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2388             return vulkan_map_to_drm(hwfc, dst, src, flags);
2389 #if CONFIG_VAAPI
2390     case AV_PIX_FMT_VAAPI:
2391         if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2392             return vulkan_map_to_vaapi(hwfc, dst, src, flags);
2393 #endif
2394 #endif
2395     default:
2396         return vulkan_map_frame_to_mem(hwfc, dst, src, flags);
2397     }
2398 }
2399
2400 typedef struct ImageBuffer {
2401     VkBuffer buf;
2402     VkDeviceMemory mem;
2403     VkMemoryPropertyFlagBits flags;
2404 } ImageBuffer;
2405
2406 static void free_buf(AVHWDeviceContext *ctx, ImageBuffer *buf)
2407 {
2408     AVVulkanDeviceContext *hwctx = ctx->hwctx;
2409     if (!buf)
2410         return;
2411
2412     vkDestroyBuffer(hwctx->act_dev, buf->buf, hwctx->alloc);
2413     vkFreeMemory(hwctx->act_dev, buf->mem, hwctx->alloc);
2414 }
2415
2416 static int create_buf(AVHWDeviceContext *ctx, ImageBuffer *buf, int height,
2417                       int *stride, VkBufferUsageFlags usage,
2418                       VkMemoryPropertyFlagBits flags, void *create_pnext,
2419                       void *alloc_pnext)
2420 {
2421     int err;
2422     VkResult ret;
2423     VkMemoryRequirements req;
2424     AVVulkanDeviceContext *hwctx = ctx->hwctx;
2425     VulkanDevicePriv *p = ctx->internal->priv;
2426
2427     VkBufferCreateInfo buf_spawn = {
2428         .sType       = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
2429         .pNext       = create_pnext,
2430         .usage       = usage,
2431         .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
2432     };
2433
2434     *stride = FFALIGN(*stride, p->props.limits.optimalBufferCopyRowPitchAlignment);
2435     buf_spawn.size = height*(*stride);
2436
2437     ret = vkCreateBuffer(hwctx->act_dev, &buf_spawn, NULL, &buf->buf);
2438     if (ret != VK_SUCCESS) {
2439         av_log(ctx, AV_LOG_ERROR, "Failed to create buffer: %s\n",
2440                vk_ret2str(ret));
2441         return AVERROR_EXTERNAL;
2442     }
2443
2444     vkGetBufferMemoryRequirements(hwctx->act_dev, buf->buf, &req);
2445
2446     err = alloc_mem(ctx, &req, flags, alloc_pnext, &buf->flags, &buf->mem);
2447     if (err)
2448         return err;
2449
2450     ret = vkBindBufferMemory(hwctx->act_dev, buf->buf, buf->mem, 0);
2451     if (ret != VK_SUCCESS) {
2452         av_log(ctx, AV_LOG_ERROR, "Failed to bind memory to buffer: %s\n",
2453                vk_ret2str(ret));
2454         free_buf(ctx, buf);
2455         return AVERROR_EXTERNAL;
2456     }
2457
2458     return 0;
2459 }
2460
2461 static int map_buffers(AVHWDeviceContext *ctx, ImageBuffer *buf, uint8_t *mem[],
2462                        int nb_buffers, int invalidate)
2463 {
2464     VkResult ret;
2465     AVVulkanDeviceContext *hwctx = ctx->hwctx;
2466     VkMappedMemoryRange invalidate_ctx[AV_NUM_DATA_POINTERS];
2467     int invalidate_count = 0;
2468
2469     for (int i = 0; i < nb_buffers; i++) {
2470         ret = vkMapMemory(hwctx->act_dev, buf[i].mem, 0,
2471                           VK_WHOLE_SIZE, 0, (void **)&mem[i]);
2472         if (ret != VK_SUCCESS) {
2473             av_log(ctx, AV_LOG_ERROR, "Failed to map buffer memory: %s\n",
2474                    vk_ret2str(ret));
2475             return AVERROR_EXTERNAL;
2476         }
2477     }
2478
2479     if (!invalidate)
2480         return 0;
2481
2482     for (int i = 0; i < nb_buffers; i++) {
2483         const VkMappedMemoryRange ival_buf = {
2484             .sType  = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2485             .memory = buf[i].mem,
2486             .size   = VK_WHOLE_SIZE,
2487         };
2488         if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2489             continue;
2490         invalidate_ctx[invalidate_count++] = ival_buf;
2491     }
2492
2493     if (invalidate_count) {
2494         ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, invalidate_count,
2495                                              invalidate_ctx);
2496         if (ret != VK_SUCCESS)
2497             av_log(ctx, AV_LOG_WARNING, "Failed to invalidate memory: %s\n",
2498                    vk_ret2str(ret));
2499     }
2500
2501     return 0;
2502 }
2503
2504 static int unmap_buffers(AVHWDeviceContext *ctx, ImageBuffer *buf,
2505                          int nb_buffers, int flush)
2506 {
2507     int err = 0;
2508     VkResult ret;
2509     AVVulkanDeviceContext *hwctx = ctx->hwctx;
2510     VkMappedMemoryRange flush_ctx[AV_NUM_DATA_POINTERS];
2511     int flush_count = 0;
2512
2513     if (flush) {
2514         for (int i = 0; i < nb_buffers; i++) {
2515             const VkMappedMemoryRange flush_buf = {
2516                 .sType  = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2517                 .memory = buf[i].mem,
2518                 .size   = VK_WHOLE_SIZE,
2519             };
2520             if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2521                 continue;
2522             flush_ctx[flush_count++] = flush_buf;
2523         }
2524     }
2525
2526     if (flush_count) {
2527         ret = vkFlushMappedMemoryRanges(hwctx->act_dev, flush_count, flush_ctx);
2528         if (ret != VK_SUCCESS) {
2529             av_log(ctx, AV_LOG_ERROR, "Failed to flush memory: %s\n",
2530                     vk_ret2str(ret));
2531             err = AVERROR_EXTERNAL; /* We still want to try to unmap them */
2532         }
2533     }
2534
2535     for (int i = 0; i < nb_buffers; i++)
2536         vkUnmapMemory(hwctx->act_dev, buf[i].mem);
2537
2538     return err;
2539 }
2540
2541 static int transfer_image_buf(AVHWDeviceContext *ctx, AVVkFrame *frame,
2542                               ImageBuffer *buffer, const int *buf_stride, int w,
2543                               int h, enum AVPixelFormat pix_fmt, int to_buf)
2544 {
2545     VkResult ret;
2546     AVVulkanDeviceContext *hwctx = ctx->hwctx;
2547     VulkanDevicePriv *s = ctx->internal->priv;
2548
2549     int bar_num = 0;
2550     VkPipelineStageFlagBits sem_wait_dst[AV_NUM_DATA_POINTERS];
2551
2552     const int planes = av_pix_fmt_count_planes(pix_fmt);
2553     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2554
2555     VkCommandBufferBeginInfo cmd_start = {
2556         .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
2557         .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
2558     };
2559
2560     VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
2561
2562     VkSubmitInfo s_info = {
2563         .sType                = VK_STRUCTURE_TYPE_SUBMIT_INFO,
2564         .commandBufferCount   = 1,
2565         .pCommandBuffers      = &s->cmd.buf,
2566         .pSignalSemaphores    = &frame->sem,
2567         .pWaitSemaphores      = &frame->sem,
2568         .pWaitDstStageMask    = sem_wait_dst,
2569         .signalSemaphoreCount = 1,
2570         .waitSemaphoreCount   = 1,
2571     };
2572
2573     ret = vkBeginCommandBuffer(s->cmd.buf, &cmd_start);
2574     if (ret != VK_SUCCESS) {
2575         av_log(ctx, AV_LOG_ERROR, "Unable to init command buffer: %s\n",
2576                vk_ret2str(ret));
2577         return AVERROR_EXTERNAL;
2578     }
2579
2580     /* Change the image layout to something more optimal for transfers */
2581     for (int i = 0; i < planes; i++) {
2582         VkImageLayout new_layout = to_buf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL :
2583                                             VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
2584         VkAccessFlags new_access = to_buf ? VK_ACCESS_TRANSFER_READ_BIT :
2585                                             VK_ACCESS_TRANSFER_WRITE_BIT;
2586
2587         sem_wait_dst[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
2588
2589         /* If the layout matches and we have read access skip the barrier */
2590         if ((frame->layout[i] == new_layout) && (frame->access[i] & new_access))
2591             continue;
2592
2593         img_bar[bar_num].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
2594         img_bar[bar_num].srcAccessMask = 0x0;
2595         img_bar[bar_num].dstAccessMask = new_access;
2596         img_bar[bar_num].oldLayout = frame->layout[i];
2597         img_bar[bar_num].newLayout = new_layout;
2598         img_bar[bar_num].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2599         img_bar[bar_num].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2600         img_bar[bar_num].image = frame->img[i];
2601         img_bar[bar_num].subresourceRange.levelCount = 1;
2602         img_bar[bar_num].subresourceRange.layerCount = 1;
2603         img_bar[bar_num].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2604
2605         frame->layout[i] = img_bar[bar_num].newLayout;
2606         frame->access[i] = img_bar[bar_num].dstAccessMask;
2607
2608         bar_num++;
2609     }
2610
2611     if (bar_num)
2612         vkCmdPipelineBarrier(s->cmd.buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
2613                              VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
2614                              0, NULL, 0, NULL, bar_num, img_bar);
2615
2616     /* Schedule a copy for each plane */
2617     for (int i = 0; i < planes; i++) {
2618         const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
2619         const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
2620         VkBufferImageCopy buf_reg = {
2621             .bufferOffset = 0,
2622             /* Buffer stride isn't in bytes, it's in samples, the implementation
2623              * uses the image's VkFormat to know how many bytes per sample
2624              * the buffer has. So we have to convert by dividing. Stupid.
2625              * Won't work with YUVA or other planar formats with alpha. */
2626             .bufferRowLength = buf_stride[i] / desc->comp[i].step,
2627             .bufferImageHeight = p_h,
2628             .imageSubresource.layerCount = 1,
2629             .imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
2630             .imageOffset = { 0, 0, 0, },
2631             .imageExtent = { p_w, p_h, 1, },
2632         };
2633
2634         if (to_buf)
2635             vkCmdCopyImageToBuffer(s->cmd.buf, frame->img[i], frame->layout[i],
2636                                    buffer[i].buf, 1, &buf_reg);
2637         else
2638             vkCmdCopyBufferToImage(s->cmd.buf, buffer[i].buf, frame->img[i],
2639                                    frame->layout[i], 1, &buf_reg);
2640     }
2641
2642     ret = vkEndCommandBuffer(s->cmd.buf);
2643     if (ret != VK_SUCCESS) {
2644         av_log(ctx, AV_LOG_ERROR, "Unable to finish command buffer: %s\n",
2645                vk_ret2str(ret));
2646         return AVERROR_EXTERNAL;
2647     }
2648
2649     /* Wait for the download/upload to finish if uploading, otherwise the
2650      * semaphore will take care of synchronization when uploading */
2651     ret = vkQueueSubmit(s->cmd.queue, 1, &s_info, s->cmd.fence);
2652     if (ret != VK_SUCCESS) {
2653         av_log(ctx, AV_LOG_ERROR, "Unable to submit command buffer: %s\n",
2654                vk_ret2str(ret));
2655         return AVERROR_EXTERNAL;
2656     } else {
2657         vkWaitForFences(hwctx->act_dev, 1, &s->cmd.fence, VK_TRUE, UINT64_MAX);
2658         vkResetFences(hwctx->act_dev, 1, &s->cmd.fence);
2659     }
2660
2661     return 0;
2662 }
2663
2664 /* Technically we can use VK_EXT_external_memory_host to upload and download,
2665  * however the alignment requirements make this unfeasible as both the pointer
2666  * and the size of each plane need to be aligned to the minimum alignment
2667  * requirement, which on all current implementations (anv, radv) is 4096.
2668  * If the requirement gets relaxed (unlikely) this can easily be implemented. */
2669 static int vulkan_transfer_data_from_mem(AVHWFramesContext *hwfc, AVFrame *dst,
2670                                          const AVFrame *src)
2671 {
2672     int err = 0;
2673     AVFrame tmp;
2674     AVVkFrame *f = (AVVkFrame *)dst->data[0];
2675     AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
2676     ImageBuffer buf[AV_NUM_DATA_POINTERS] = { { 0 } };
2677     const int planes = av_pix_fmt_count_planes(src->format);
2678     int log2_chroma = av_pix_fmt_desc_get(src->format)->log2_chroma_h;
2679
2680     if ((src->format != AV_PIX_FMT_NONE && !av_vkfmt_from_pixfmt(src->format))) {
2681         av_log(hwfc, AV_LOG_ERROR, "Unsupported source pixel format!\n");
2682         return AVERROR(EINVAL);
2683     }
2684
2685     if (src->width > hwfc->width || src->height > hwfc->height)
2686         return AVERROR(EINVAL);
2687
2688     /* For linear, host visiable images */
2689     if (f->tiling == VK_IMAGE_TILING_LINEAR &&
2690         f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
2691         AVFrame *map = av_frame_alloc();
2692         if (!map)
2693             return AVERROR(ENOMEM);
2694         map->format = src->format;
2695
2696         err = vulkan_map_frame_to_mem(hwfc, map, dst, AV_HWFRAME_MAP_WRITE);
2697         if (err)
2698             goto end;
2699
2700         err = av_frame_copy(map, src);
2701         av_frame_free(&map);
2702         goto end;
2703     }
2704
2705     /* Create buffers */
2706     for (int i = 0; i < planes; i++) {
2707         int h = src->height;
2708         int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
2709
2710         tmp.linesize[i] = FFABS(src->linesize[i]);
2711         err = create_buf(dev_ctx, &buf[i], p_height,
2712                          &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
2713                          VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
2714         if (err)
2715             goto end;
2716     }
2717
2718     /* Map, copy image to buffer, unmap */
2719     if ((err = map_buffers(dev_ctx, buf, tmp.data, planes, 0)))
2720         goto end;
2721
2722     av_image_copy(tmp.data, tmp.linesize, (const uint8_t **)src->data,
2723                   src->linesize, src->format, src->width, src->height);
2724
2725     if ((err = unmap_buffers(dev_ctx, buf, planes, 1)))
2726         goto end;
2727
2728     /* Copy buffers to image */
2729     err = transfer_image_buf(dev_ctx, f, buf, tmp.linesize,
2730                              src->width, src->height, src->format, 0);
2731
2732 end:
2733     for (int i = 0; i < planes; i++)
2734         free_buf(dev_ctx, &buf[i]);
2735
2736     return err;
2737 }
2738
2739 static int vulkan_transfer_data_to(AVHWFramesContext *hwfc, AVFrame *dst,
2740                                         const AVFrame *src)
2741 {
2742     av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2743
2744     switch (src->format) {
2745 #if CONFIG_CUDA
2746     case AV_PIX_FMT_CUDA:
2747         if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
2748             (p->extensions & EXT_EXTERNAL_FD_SEM))
2749             return vulkan_transfer_data_from_cuda(hwfc, dst, src);
2750 #endif
2751     default:
2752         if (src->hw_frames_ctx)
2753             return AVERROR(ENOSYS);
2754         else
2755             return vulkan_transfer_data_from_mem(hwfc, dst, src);
2756     }
2757 }
2758
2759 #if CONFIG_CUDA
2760 static int vulkan_transfer_data_to_cuda(AVHWFramesContext *hwfc, AVFrame *dst,
2761                                       const AVFrame *src)
2762 {
2763     int err;
2764     VkResult ret;
2765     CUcontext dummy;
2766     AVVkFrame *dst_f;
2767     AVVkFrameInternal *dst_int;
2768     const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2769     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2770
2771     AVHWFramesContext *cuda_fc = (AVHWFramesContext*)dst->hw_frames_ctx->data;
2772     AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2773     AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2774     AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2775     CudaFunctions *cu = cu_internal->cuda_dl;
2776
2777     ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2778     if (ret < 0) {
2779         err = AVERROR_EXTERNAL;
2780         goto fail;
2781     }
2782
2783     dst_f = (AVVkFrame *)src->data[0];
2784
2785     err = vulkan_export_to_cuda(hwfc, dst->hw_frames_ctx, src);
2786     if (err < 0) {
2787         goto fail;
2788     }
2789
2790     dst_int = dst_f->internal;
2791
2792     for (int i = 0; i < planes; i++) {
2793         CUDA_MEMCPY2D cpy = {
2794             .dstMemoryType = CU_MEMORYTYPE_DEVICE,
2795             .dstDevice     = (CUdeviceptr)dst->data[i],
2796             .dstPitch      = dst->linesize[i],
2797             .dstY          = 0,
2798
2799             .srcMemoryType = CU_MEMORYTYPE_ARRAY,
2800             .srcArray      = dst_int->cu_array[i],
2801             .WidthInBytes  = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2802                                     : hwfc->width) * desc->comp[i].step,
2803             .Height        = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2804                                    : hwfc->height,
2805         };
2806
2807         ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2808         if (ret < 0) {
2809             err = AVERROR_EXTERNAL;
2810             goto fail;
2811         }
2812     }
2813
2814     CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2815
2816     av_log(hwfc, AV_LOG_VERBOSE, "Transfered Vulkan image to CUDA!\n");
2817
2818     return 0;
2819
2820 fail:
2821     CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2822     vulkan_free_internal(dst_int);
2823     dst_f->internal = NULL;
2824     av_buffer_unref(&dst->buf[0]);
2825     return err;
2826 }
2827 #endif
2828
2829 static int vulkan_transfer_data_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
2830                                        const AVFrame *src)
2831 {
2832     int err = 0;
2833     AVFrame tmp;
2834     AVVkFrame *f = (AVVkFrame *)src->data[0];
2835     AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
2836     ImageBuffer buf[AV_NUM_DATA_POINTERS] = { { 0 } };
2837     const int planes = av_pix_fmt_count_planes(dst->format);
2838     int log2_chroma = av_pix_fmt_desc_get(dst->format)->log2_chroma_h;
2839
2840     if (dst->width > hwfc->width || dst->height > hwfc->height)
2841         return AVERROR(EINVAL);
2842
2843     /* For linear, host visiable images */
2844     if (f->tiling == VK_IMAGE_TILING_LINEAR &&
2845         f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
2846         AVFrame *map = av_frame_alloc();
2847         if (!map)
2848             return AVERROR(ENOMEM);
2849         map->format = dst->format;
2850
2851         err = vulkan_map_frame_to_mem(hwfc, map, src, AV_HWFRAME_MAP_READ);
2852         if (err)
2853             return err;
2854
2855         err = av_frame_copy(dst, map);
2856         av_frame_free(&map);
2857         return err;
2858     }
2859
2860     /* Create buffers */
2861     for (int i = 0; i < planes; i++) {
2862         int h = dst->height;
2863         int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
2864
2865         tmp.linesize[i] = FFABS(dst->linesize[i]);
2866         err = create_buf(dev_ctx, &buf[i], p_height,
2867                          &tmp.linesize[i], VK_BUFFER_USAGE_TRANSFER_DST_BIT,
2868                          VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, NULL, NULL);
2869     }
2870
2871     /* Copy image to buffer */
2872     if ((err = transfer_image_buf(dev_ctx, f, buf, tmp.linesize,
2873                                   dst->width, dst->height, dst->format, 1)))
2874         goto end;
2875
2876     /* Map, copy buffer to frame, unmap */
2877     if ((err = map_buffers(dev_ctx, buf, tmp.data, planes, 1)))
2878         goto end;
2879
2880     av_image_copy(dst->data, dst->linesize, (const uint8_t **)tmp.data,
2881                   tmp.linesize, dst->format, dst->width, dst->height);
2882
2883     err = unmap_buffers(dev_ctx, buf, planes, 0);
2884
2885 end:
2886     for (int i = 0; i < planes; i++)
2887         free_buf(dev_ctx, &buf[i]);
2888
2889     return err;
2890 }
2891
2892 static int vulkan_transfer_data_from(AVHWFramesContext *hwfc, AVFrame *dst,
2893                                      const AVFrame *src)
2894 {
2895     av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2896
2897     switch (dst->format) {
2898 #if CONFIG_CUDA
2899     case AV_PIX_FMT_CUDA:
2900         if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
2901             (p->extensions & EXT_EXTERNAL_FD_SEM))
2902             return vulkan_transfer_data_to_cuda(hwfc, dst, src);
2903 #endif
2904     default:
2905         if (dst->hw_frames_ctx)
2906             return AVERROR(ENOSYS);
2907         else
2908             return vulkan_transfer_data_to_mem(hwfc, dst, src);
2909     }
2910 }
2911
2912 AVVkFrame *av_vk_frame_alloc(void)
2913 {
2914     return av_mallocz(sizeof(AVVkFrame));
2915 }
2916
2917 const HWContextType ff_hwcontext_type_vulkan = {
2918     .type                   = AV_HWDEVICE_TYPE_VULKAN,
2919     .name                   = "Vulkan",
2920
2921     .device_hwctx_size      = sizeof(AVVulkanDeviceContext),
2922     .device_priv_size       = sizeof(VulkanDevicePriv),
2923     .frames_hwctx_size      = sizeof(AVVulkanFramesContext),
2924     .frames_priv_size       = sizeof(VulkanFramesPriv),
2925
2926     .device_init            = &vulkan_device_init,
2927     .device_create          = &vulkan_device_create,
2928     .device_derive          = &vulkan_device_derive,
2929
2930     .frames_get_constraints = &vulkan_frames_get_constraints,
2931     .frames_init            = vulkan_frames_init,
2932     .frames_get_buffer      = vulkan_get_buffer,
2933     .frames_uninit          = vulkan_frames_uninit,
2934
2935     .transfer_get_formats   = vulkan_transfer_get_formats,
2936     .transfer_data_to       = vulkan_transfer_data_to,
2937     .transfer_data_from     = vulkan_transfer_data_from,
2938
2939     .map_to                 = vulkan_map_to,
2940     .map_from               = vulkan_map_from,
2941
2942     .pix_fmts = (const enum AVPixelFormat []) {
2943         AV_PIX_FMT_VULKAN,
2944         AV_PIX_FMT_NONE
2945     },
2946 };