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