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