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