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