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