]> git.sesse.net Git - ffmpeg/blob - libavutil/hwcontext_vulkan.c
hwcontext_vulkan: do not segfault when failing to init a AVHWFramesContext
[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 int create_frame(AVHWFramesContext *hwfc, AVVkFrame **frame,
1513                         VkImageTiling tiling, VkImageUsageFlagBits usage,
1514                         void *create_pnext)
1515 {
1516     int err;
1517     VkResult ret;
1518     AVHWDeviceContext *ctx = hwfc->device_ctx;
1519     VulkanDevicePriv *p = ctx->internal->priv;
1520     AVVulkanDeviceContext *hwctx = ctx->hwctx;
1521     enum AVPixelFormat format = hwfc->sw_format;
1522     const VkFormat *img_fmts = av_vkfmt_from_pixfmt(format);
1523     const int planes = av_pix_fmt_count_planes(format);
1524
1525     VkExportSemaphoreCreateInfo ext_sem_info = {
1526         .sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO,
1527         .handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
1528     };
1529
1530     VkSemaphoreCreateInfo sem_spawn = {
1531         .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1532         .pNext = p->extensions & EXT_EXTERNAL_FD_SEM ? &ext_sem_info : NULL,
1533     };
1534
1535     AVVkFrame *f = av_vk_frame_alloc();
1536     if (!f) {
1537         av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1538         return AVERROR(ENOMEM);
1539     }
1540
1541     /* Create the images */
1542     for (int i = 0; i < planes; i++) {
1543         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
1544         int w = hwfc->width;
1545         int h = hwfc->height;
1546         const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
1547         const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
1548
1549         VkImageCreateInfo image_create_info = {
1550             .sType                 = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1551             .pNext                 = create_pnext,
1552             .imageType             = VK_IMAGE_TYPE_2D,
1553             .format                = img_fmts[i],
1554             .extent.width          = p_w,
1555             .extent.height         = p_h,
1556             .extent.depth          = 1,
1557             .mipLevels             = 1,
1558             .arrayLayers           = 1,
1559             .flags                 = VK_IMAGE_CREATE_ALIAS_BIT,
1560             .tiling                = tiling,
1561             .initialLayout         = VK_IMAGE_LAYOUT_UNDEFINED,
1562             .usage                 = usage,
1563             .samples               = VK_SAMPLE_COUNT_1_BIT,
1564             .pQueueFamilyIndices   = p->qfs,
1565             .queueFamilyIndexCount = p->num_qfs,
1566             .sharingMode           = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
1567                                                       VK_SHARING_MODE_EXCLUSIVE,
1568         };
1569
1570         ret = vkCreateImage(hwctx->act_dev, &image_create_info,
1571                             hwctx->alloc, &f->img[i]);
1572         if (ret != VK_SUCCESS) {
1573             av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
1574                    vk_ret2str(ret));
1575             err = AVERROR(EINVAL);
1576             goto fail;
1577         }
1578
1579         /* Create semaphore */
1580         ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
1581                                 hwctx->alloc, &f->sem[i]);
1582         if (ret != VK_SUCCESS) {
1583             av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
1584                    vk_ret2str(ret));
1585             return AVERROR_EXTERNAL;
1586         }
1587
1588         f->layout[i] = image_create_info.initialLayout;
1589         f->access[i] = 0x0;
1590     }
1591
1592     f->flags     = 0x0;
1593     f->tiling    = tiling;
1594
1595     *frame = f;
1596     return 0;
1597
1598 fail:
1599     vulkan_frame_free(hwfc, (uint8_t *)f);
1600     return err;
1601 }
1602
1603 /* Checks if an export flag is enabled, and if it is ORs it with *iexp */
1604 static void try_export_flags(AVHWFramesContext *hwfc,
1605                              VkExternalMemoryHandleTypeFlags *comp_handle_types,
1606                              VkExternalMemoryHandleTypeFlagBits *iexp,
1607                              VkExternalMemoryHandleTypeFlagBits exp)
1608 {
1609     VkResult ret;
1610     AVVulkanFramesContext *hwctx = hwfc->hwctx;
1611     AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1612     VkExternalImageFormatProperties eprops = {
1613         .sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES_KHR,
1614     };
1615     VkImageFormatProperties2 props = {
1616         .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,
1617         .pNext = &eprops,
1618     };
1619     VkPhysicalDeviceExternalImageFormatInfo enext = {
1620         .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
1621         .handleType = exp,
1622     };
1623     VkPhysicalDeviceImageFormatInfo2 pinfo = {
1624         .sType  = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1625         .pNext  = !exp ? NULL : &enext,
1626         .format = av_vkfmt_from_pixfmt(hwfc->sw_format)[0],
1627         .type   = VK_IMAGE_TYPE_2D,
1628         .tiling = hwctx->tiling,
1629         .usage  = hwctx->usage,
1630         .flags  = VK_IMAGE_CREATE_ALIAS_BIT,
1631     };
1632
1633     ret = vkGetPhysicalDeviceImageFormatProperties2(dev_hwctx->phys_dev,
1634                                                     &pinfo, &props);
1635     if (ret == VK_SUCCESS) {
1636         *iexp |= exp;
1637         *comp_handle_types |= eprops.externalMemoryProperties.compatibleHandleTypes;
1638     }
1639 }
1640
1641 static AVBufferRef *vulkan_pool_alloc(void *opaque, int size)
1642 {
1643     int err;
1644     AVVkFrame *f;
1645     AVBufferRef *avbuf = NULL;
1646     AVHWFramesContext *hwfc = opaque;
1647     AVVulkanFramesContext *hwctx = hwfc->hwctx;
1648     VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1649     VulkanFramesPriv *fp = hwfc->internal->priv;
1650     VkExportMemoryAllocateInfo eminfo[AV_NUM_DATA_POINTERS];
1651     VkExternalMemoryHandleTypeFlags e = 0x0;
1652
1653     VkExternalMemoryImageCreateInfo eiinfo = {
1654         .sType       = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
1655         .pNext       = hwctx->create_pnext,
1656     };
1657
1658     if (p->extensions & EXT_EXTERNAL_FD_MEMORY)
1659         try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1660                          VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT);
1661
1662     if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
1663         try_export_flags(hwfc, &eiinfo.handleTypes, &e,
1664                          VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
1665
1666     for (int i = 0; i < av_pix_fmt_count_planes(hwfc->sw_format); i++) {
1667         eminfo[i].sType       = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO;
1668         eminfo[i].pNext       = hwctx->alloc_pnext[i];
1669         eminfo[i].handleTypes = e;
1670     }
1671
1672     err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1673                        eiinfo.handleTypes ? &eiinfo : NULL);
1674     if (err)
1675         return NULL;
1676
1677     err = alloc_bind_mem(hwfc, f, eminfo, sizeof(*eminfo));
1678     if (err)
1679         goto fail;
1680
1681     err = prepare_frame(hwfc, &fp->conv_ctx, f, PREP_MODE_WRITE);
1682     if (err)
1683         goto fail;
1684
1685     avbuf = av_buffer_create((uint8_t *)f, sizeof(AVVkFrame),
1686                              vulkan_frame_free, hwfc, 0);
1687     if (!avbuf)
1688         goto fail;
1689
1690     return avbuf;
1691
1692 fail:
1693     vulkan_frame_free(hwfc, (uint8_t *)f);
1694     return NULL;
1695 }
1696
1697 static void vulkan_frames_uninit(AVHWFramesContext *hwfc)
1698 {
1699     VulkanFramesPriv *fp = hwfc->internal->priv;
1700
1701     free_exec_ctx(hwfc, &fp->conv_ctx);
1702     free_exec_ctx(hwfc, &fp->upload_ctx);
1703     free_exec_ctx(hwfc, &fp->download_ctx);
1704 }
1705
1706 static int vulkan_frames_init(AVHWFramesContext *hwfc)
1707 {
1708     int err;
1709     AVVkFrame *f;
1710     AVVulkanFramesContext *hwctx = hwfc->hwctx;
1711     VulkanFramesPriv *fp = hwfc->internal->priv;
1712     AVVulkanDeviceContext *dev_hwctx = hwfc->device_ctx->hwctx;
1713     VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
1714
1715     /* Default pool flags */
1716     hwctx->tiling = hwctx->tiling ? hwctx->tiling : p->use_linear_images ?
1717                     VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1718
1719     if (!hwctx->usage)
1720         hwctx->usage = DEFAULT_USAGE_FLAGS;
1721
1722     err = create_exec_ctx(hwfc, &fp->conv_ctx,
1723                           dev_hwctx->queue_family_comp_index,
1724                           GET_QUEUE_COUNT(dev_hwctx, 0, 1, 0));
1725     if (err)
1726         return err;
1727
1728     err = create_exec_ctx(hwfc, &fp->upload_ctx,
1729                           dev_hwctx->queue_family_tx_index,
1730                           GET_QUEUE_COUNT(dev_hwctx, 0, 0, 1));
1731     if (err)
1732         return err;
1733
1734     err = create_exec_ctx(hwfc, &fp->download_ctx,
1735                           dev_hwctx->queue_family_tx_index, 1);
1736     if (err)
1737         return err;
1738
1739     /* Test to see if allocation will fail */
1740     err = create_frame(hwfc, &f, hwctx->tiling, hwctx->usage,
1741                        hwctx->create_pnext);
1742     if (err)
1743         return err;
1744
1745     vulkan_frame_free(hwfc, (uint8_t *)f);
1746
1747     /* If user did not specify a pool, hwfc->pool will be set to the internal one
1748      * in hwcontext.c just after this gets called */
1749     if (!hwfc->pool) {
1750         hwfc->internal->pool_internal = av_buffer_pool_init2(sizeof(AVVkFrame),
1751                                                              hwfc, vulkan_pool_alloc,
1752                                                              NULL);
1753         if (!hwfc->internal->pool_internal)
1754             return AVERROR(ENOMEM);
1755     }
1756
1757     return 0;
1758 }
1759
1760 static int vulkan_get_buffer(AVHWFramesContext *hwfc, AVFrame *frame)
1761 {
1762     frame->buf[0] = av_buffer_pool_get(hwfc->pool);
1763     if (!frame->buf[0])
1764         return AVERROR(ENOMEM);
1765
1766     frame->data[0] = frame->buf[0]->data;
1767     frame->format  = AV_PIX_FMT_VULKAN;
1768     frame->width   = hwfc->width;
1769     frame->height  = hwfc->height;
1770
1771     return 0;
1772 }
1773
1774 static int vulkan_transfer_get_formats(AVHWFramesContext *hwfc,
1775                                        enum AVHWFrameTransferDirection dir,
1776                                        enum AVPixelFormat **formats)
1777 {
1778     enum AVPixelFormat *fmts = av_malloc_array(2, sizeof(*fmts));
1779     if (!fmts)
1780         return AVERROR(ENOMEM);
1781
1782     fmts[0] = hwfc->sw_format;
1783     fmts[1] = AV_PIX_FMT_NONE;
1784
1785     *formats = fmts;
1786     return 0;
1787 }
1788
1789 typedef struct VulkanMapping {
1790     AVVkFrame *frame;
1791     int flags;
1792 } VulkanMapping;
1793
1794 static void vulkan_unmap_frame(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1795 {
1796     VulkanMapping *map = hwmap->priv;
1797     AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1798     const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1799
1800     /* Check if buffer needs flushing */
1801     if ((map->flags & AV_HWFRAME_MAP_WRITE) &&
1802         !(map->frame->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1803         VkResult ret;
1804         VkMappedMemoryRange flush_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1805
1806         for (int i = 0; i < planes; i++) {
1807             flush_ranges[i].sType  = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1808             flush_ranges[i].memory = map->frame->mem[i];
1809             flush_ranges[i].size   = VK_WHOLE_SIZE;
1810         }
1811
1812         ret = vkFlushMappedMemoryRanges(hwctx->act_dev, planes,
1813                                         flush_ranges);
1814         if (ret != VK_SUCCESS) {
1815             av_log(hwfc, AV_LOG_ERROR, "Failed to flush memory: %s\n",
1816                    vk_ret2str(ret));
1817         }
1818     }
1819
1820     for (int i = 0; i < planes; i++)
1821         vkUnmapMemory(hwctx->act_dev, map->frame->mem[i]);
1822
1823     av_free(map);
1824 }
1825
1826 static int vulkan_map_frame_to_mem(AVHWFramesContext *hwfc, AVFrame *dst,
1827                                    const AVFrame *src, int flags)
1828 {
1829     VkResult ret;
1830     int err, mapped_mem_count = 0;
1831     AVVkFrame *f = (AVVkFrame *)src->data[0];
1832     AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1833     const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1834
1835     VulkanMapping *map = av_mallocz(sizeof(VulkanMapping));
1836     if (!map)
1837         return AVERROR(EINVAL);
1838
1839     if (src->format != AV_PIX_FMT_VULKAN) {
1840         av_log(hwfc, AV_LOG_ERROR, "Cannot map from pixel format %s!\n",
1841                av_get_pix_fmt_name(src->format));
1842         err = AVERROR(EINVAL);
1843         goto fail;
1844     }
1845
1846     if (!(f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ||
1847         !(f->tiling == VK_IMAGE_TILING_LINEAR)) {
1848         av_log(hwfc, AV_LOG_ERROR, "Unable to map frame, not host visible "
1849                "and linear!\n");
1850         err = AVERROR(EINVAL);
1851         goto fail;
1852     }
1853
1854     dst->width  = src->width;
1855     dst->height = src->height;
1856
1857     for (int i = 0; i < planes; i++) {
1858         ret = vkMapMemory(hwctx->act_dev, f->mem[i], 0,
1859                           VK_WHOLE_SIZE, 0, (void **)&dst->data[i]);
1860         if (ret != VK_SUCCESS) {
1861             av_log(hwfc, AV_LOG_ERROR, "Failed to map image memory: %s\n",
1862                 vk_ret2str(ret));
1863             err = AVERROR_EXTERNAL;
1864             goto fail;
1865         }
1866         mapped_mem_count++;
1867     }
1868
1869     /* Check if the memory contents matter */
1870     if (((flags & AV_HWFRAME_MAP_READ) || !(flags & AV_HWFRAME_MAP_OVERWRITE)) &&
1871         !(f->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
1872         VkMappedMemoryRange map_mem_ranges[AV_NUM_DATA_POINTERS] = { { 0 } };
1873         for (int i = 0; i < planes; i++) {
1874             map_mem_ranges[i].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1875             map_mem_ranges[i].size = VK_WHOLE_SIZE;
1876             map_mem_ranges[i].memory = f->mem[i];
1877         }
1878
1879         ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, planes,
1880                                              map_mem_ranges);
1881         if (ret != VK_SUCCESS) {
1882             av_log(hwfc, AV_LOG_ERROR, "Failed to invalidate memory: %s\n",
1883                    vk_ret2str(ret));
1884             err = AVERROR_EXTERNAL;
1885             goto fail;
1886         }
1887     }
1888
1889     for (int i = 0; i < planes; i++) {
1890         VkImageSubresource sub = {
1891             .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
1892         };
1893         VkSubresourceLayout layout;
1894         vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
1895         dst->linesize[i] = layout.rowPitch;
1896     }
1897
1898     map->frame = f;
1899     map->flags = flags;
1900
1901     err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src,
1902                                 &vulkan_unmap_frame, map);
1903     if (err < 0)
1904         goto fail;
1905
1906     return 0;
1907
1908 fail:
1909     for (int i = 0; i < mapped_mem_count; i++)
1910         vkUnmapMemory(hwctx->act_dev, f->mem[i]);
1911
1912     av_free(map);
1913     return err;
1914 }
1915
1916 #if CONFIG_LIBDRM
1917 static void vulkan_unmap_from(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
1918 {
1919     VulkanMapping *map = hwmap->priv;
1920     AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
1921     const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
1922
1923     for (int i = 0; i < planes; i++) {
1924         vkDestroyImage(hwctx->act_dev, map->frame->img[i], hwctx->alloc);
1925         vkFreeMemory(hwctx->act_dev, map->frame->mem[i], hwctx->alloc);
1926         vkDestroySemaphore(hwctx->act_dev, map->frame->sem[i], hwctx->alloc);
1927     }
1928
1929     av_freep(&map->frame);
1930 }
1931
1932 static const struct {
1933     uint32_t drm_fourcc;
1934     VkFormat vk_format;
1935 } vulkan_drm_format_map[] = {
1936     { DRM_FORMAT_R8,       VK_FORMAT_R8_UNORM       },
1937     { DRM_FORMAT_R16,      VK_FORMAT_R16_UNORM      },
1938     { DRM_FORMAT_GR88,     VK_FORMAT_R8G8_UNORM     },
1939     { DRM_FORMAT_RG88,     VK_FORMAT_R8G8_UNORM     },
1940     { DRM_FORMAT_GR1616,   VK_FORMAT_R16G16_UNORM   },
1941     { DRM_FORMAT_RG1616,   VK_FORMAT_R16G16_UNORM   },
1942     { DRM_FORMAT_ARGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1943     { DRM_FORMAT_XRGB8888, VK_FORMAT_B8G8R8A8_UNORM },
1944     { DRM_FORMAT_ABGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1945     { DRM_FORMAT_XBGR8888, VK_FORMAT_R8G8B8A8_UNORM },
1946 };
1947
1948 static inline VkFormat drm_to_vulkan_fmt(uint32_t drm_fourcc)
1949 {
1950     for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
1951         if (vulkan_drm_format_map[i].drm_fourcc == drm_fourcc)
1952             return vulkan_drm_format_map[i].vk_format;
1953     return VK_FORMAT_UNDEFINED;
1954 }
1955
1956 static int vulkan_map_from_drm_frame_desc(AVHWFramesContext *hwfc, AVVkFrame **frame,
1957                                           AVDRMFrameDescriptor *desc)
1958 {
1959     int err = 0;
1960     VkResult ret;
1961     AVVkFrame *f;
1962     int bind_counts = 0;
1963     AVHWDeviceContext *ctx = hwfc->device_ctx;
1964     AVVulkanDeviceContext *hwctx = ctx->hwctx;
1965     VulkanDevicePriv *p = ctx->internal->priv;
1966     VulkanFramesPriv *fp = hwfc->internal->priv;
1967     AVVulkanFramesContext *frames_hwctx = hwfc->hwctx;
1968     const AVPixFmtDescriptor *fmt_desc = av_pix_fmt_desc_get(hwfc->sw_format);
1969     const int has_modifiers = !!(p->extensions & EXT_DRM_MODIFIER_FLAGS);
1970     VkSubresourceLayout plane_data[AV_NUM_DATA_POINTERS] = { 0 };
1971     VkBindImageMemoryInfo bind_info[AV_NUM_DATA_POINTERS] = { 0 };
1972     VkBindImagePlaneMemoryInfo plane_info[AV_NUM_DATA_POINTERS] = { 0 };
1973     VkExternalMemoryHandleTypeFlagBits htype = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
1974
1975     VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdPropertiesKHR);
1976
1977     for (int i = 0; i < desc->nb_layers; i++) {
1978         if (drm_to_vulkan_fmt(desc->layers[i].format) == VK_FORMAT_UNDEFINED) {
1979             av_log(ctx, AV_LOG_ERROR, "Unsupported DMABUF layer format %#08x!\n",
1980                    desc->layers[i].format);
1981             return AVERROR(EINVAL);
1982         }
1983     }
1984
1985     if (!(f = av_vk_frame_alloc())) {
1986         av_log(ctx, AV_LOG_ERROR, "Unable to allocate memory for AVVkFrame!\n");
1987         err = AVERROR(ENOMEM);
1988         goto fail;
1989     }
1990
1991     f->tiling = has_modifiers ? VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT :
1992                 desc->objects[0].format_modifier == DRM_FORMAT_MOD_LINEAR ?
1993                 VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
1994
1995     for (int i = 0; i < desc->nb_layers; i++) {
1996         const int planes = desc->layers[i].nb_planes;
1997         VkImageDrmFormatModifierExplicitCreateInfoEXT drm_info = {
1998             .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
1999             .drmFormatModifier = desc->objects[0].format_modifier,
2000             .drmFormatModifierPlaneCount = planes,
2001             .pPlaneLayouts = (const VkSubresourceLayout *)&plane_data,
2002         };
2003
2004         VkExternalMemoryImageCreateInfo einfo = {
2005             .sType       = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
2006             .pNext       = has_modifiers ? &drm_info : NULL,
2007             .handleTypes = htype,
2008         };
2009
2010         VkSemaphoreCreateInfo sem_spawn = {
2011             .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
2012         };
2013
2014         const int p_w = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, fmt_desc->log2_chroma_w) : hwfc->width;
2015         const int p_h = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, fmt_desc->log2_chroma_h) : hwfc->height;
2016
2017         VkImageCreateInfo image_create_info = {
2018             .sType                 = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
2019             .pNext                 = &einfo,
2020             .imageType             = VK_IMAGE_TYPE_2D,
2021             .format                = drm_to_vulkan_fmt(desc->layers[i].format),
2022             .extent.width          = p_w,
2023             .extent.height         = p_h,
2024             .extent.depth          = 1,
2025             .mipLevels             = 1,
2026             .arrayLayers           = 1,
2027             .flags                 = VK_IMAGE_CREATE_ALIAS_BIT,
2028             .tiling                = f->tiling,
2029             .initialLayout         = VK_IMAGE_LAYOUT_UNDEFINED, /* specs say so */
2030             .usage                 = frames_hwctx->usage,
2031             .samples               = VK_SAMPLE_COUNT_1_BIT,
2032             .pQueueFamilyIndices   = p->qfs,
2033             .queueFamilyIndexCount = p->num_qfs,
2034             .sharingMode           = p->num_qfs > 1 ? VK_SHARING_MODE_CONCURRENT :
2035                                                       VK_SHARING_MODE_EXCLUSIVE,
2036         };
2037
2038         for (int j = 0; j < planes; j++) {
2039             plane_data[j].offset     = desc->layers[i].planes[j].offset;
2040             plane_data[j].rowPitch   = desc->layers[i].planes[j].pitch;
2041             plane_data[j].size       = 0; /* The specs say so for all 3 */
2042             plane_data[j].arrayPitch = 0;
2043             plane_data[j].depthPitch = 0;
2044         }
2045
2046         /* Create image */
2047         ret = vkCreateImage(hwctx->act_dev, &image_create_info,
2048                             hwctx->alloc, &f->img[i]);
2049         if (ret != VK_SUCCESS) {
2050             av_log(ctx, AV_LOG_ERROR, "Image creation failure: %s\n",
2051                    vk_ret2str(ret));
2052             err = AVERROR(EINVAL);
2053             goto fail;
2054         }
2055
2056         ret = vkCreateSemaphore(hwctx->act_dev, &sem_spawn,
2057                                 hwctx->alloc, &f->sem[i]);
2058         if (ret != VK_SUCCESS) {
2059             av_log(hwctx, AV_LOG_ERROR, "Failed to create semaphore: %s\n",
2060                    vk_ret2str(ret));
2061             return AVERROR_EXTERNAL;
2062         }
2063
2064         /* We'd import a semaphore onto the one we created using
2065          * vkImportSemaphoreFdKHR but unfortunately neither DRM nor VAAPI
2066          * offer us anything we could import and sync with, so instead
2067          * just signal the semaphore we created. */
2068
2069         f->layout[i] = image_create_info.initialLayout;
2070         f->access[i] = 0x0;
2071     }
2072
2073     for (int i = 0; i < desc->nb_objects; i++) {
2074         int use_ded_mem = 0;
2075         VkMemoryFdPropertiesKHR fdmp = {
2076             .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,
2077         };
2078         VkMemoryRequirements req = {
2079             .size = desc->objects[i].size,
2080         };
2081         VkImportMemoryFdInfoKHR idesc = {
2082             .sType      = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
2083             .handleType = htype,
2084             .fd         = dup(desc->objects[i].fd),
2085         };
2086         VkMemoryDedicatedAllocateInfo ded_alloc = {
2087             .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
2088             .pNext = &idesc,
2089         };
2090
2091         ret = pfn_vkGetMemoryFdPropertiesKHR(hwctx->act_dev, htype,
2092                                              idesc.fd, &fdmp);
2093         if (ret != VK_SUCCESS) {
2094             av_log(hwfc, AV_LOG_ERROR, "Failed to get FD properties: %s\n",
2095                    vk_ret2str(ret));
2096             err = AVERROR_EXTERNAL;
2097             close(idesc.fd);
2098             goto fail;
2099         }
2100
2101         req.memoryTypeBits = fdmp.memoryTypeBits;
2102
2103         /* Dedicated allocation only makes sense if there's a one to one mapping
2104          * between images and the memory backing them, so only check in this
2105          * case. */
2106         if (desc->nb_layers == desc->nb_objects) {
2107             VkImageMemoryRequirementsInfo2 req_desc = {
2108                 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
2109                 .image = f->img[i],
2110             };
2111             VkMemoryDedicatedRequirements ded_req = {
2112                 .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
2113             };
2114             VkMemoryRequirements2 req2 = {
2115                 .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
2116                 .pNext = &ded_req,
2117             };
2118
2119             vkGetImageMemoryRequirements2(hwctx->act_dev, &req_desc, &req2);
2120
2121             use_ded_mem = ded_req.prefersDedicatedAllocation |
2122                           ded_req.requiresDedicatedAllocation;
2123             if (use_ded_mem)
2124                 ded_alloc.image = f->img[i];
2125         }
2126
2127         err = alloc_mem(ctx, &req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
2128                         use_ded_mem ? &ded_alloc : ded_alloc.pNext,
2129                         &f->flags, &f->mem[i]);
2130         if (err) {
2131             close(idesc.fd);
2132             return err;
2133         }
2134
2135         f->size[i] = desc->objects[i].size;
2136     }
2137
2138     for (int i = 0; i < desc->nb_layers; i++) {
2139         const int planes = desc->layers[i].nb_planes;
2140         const int signal_p = has_modifiers && (planes > 1);
2141         for (int j = 0; j < planes; j++) {
2142             VkImageAspectFlagBits aspect = j == 0 ? VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2143                                            j == 1 ? VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT :
2144                                                     VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT;
2145
2146             plane_info[bind_counts].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO;
2147             plane_info[bind_counts].planeAspect = aspect;
2148
2149             bind_info[bind_counts].sType  = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
2150             bind_info[bind_counts].pNext  = signal_p ? &plane_info[bind_counts] : NULL;
2151             bind_info[bind_counts].image  = f->img[i];
2152             bind_info[bind_counts].memory = f->mem[desc->layers[i].planes[j].object_index];
2153             bind_info[bind_counts].memoryOffset = desc->layers[i].planes[j].offset;
2154             bind_counts++;
2155         }
2156     }
2157
2158     /* Bind the allocated memory to the images */
2159     ret = vkBindImageMemory2(hwctx->act_dev, bind_counts, bind_info);
2160     if (ret != VK_SUCCESS) {
2161         av_log(ctx, AV_LOG_ERROR, "Failed to bind memory: %s\n",
2162                vk_ret2str(ret));
2163         return AVERROR_EXTERNAL;
2164     }
2165
2166     /* NOTE: This is completely uneccesary and unneeded once we can import
2167      * semaphores from DRM. Otherwise we have to activate the semaphores.
2168      * We're reusing the exec context that's also used for uploads/downloads. */
2169     err = prepare_frame(hwfc, &fp->conv_ctx, f, PREP_MODE_RO_SHADER);
2170     if (err)
2171         goto fail;
2172
2173     *frame = f;
2174
2175     return 0;
2176
2177 fail:
2178     for (int i = 0; i < desc->nb_layers; i++) {
2179         vkDestroyImage(hwctx->act_dev, f->img[i], hwctx->alloc);
2180         vkDestroySemaphore(hwctx->act_dev, f->sem[i], hwctx->alloc);
2181     }
2182     for (int i = 0; i < desc->nb_objects; i++)
2183         vkFreeMemory(hwctx->act_dev, f->mem[i], hwctx->alloc);
2184
2185     av_free(f);
2186
2187     return err;
2188 }
2189
2190 static int vulkan_map_from_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2191                                const AVFrame *src, int flags)
2192 {
2193     int err = 0;
2194     AVVkFrame *f;
2195     VulkanMapping *map = NULL;
2196
2197     err = vulkan_map_from_drm_frame_desc(hwfc, &f,
2198                                          (AVDRMFrameDescriptor *)src->data[0]);
2199     if (err)
2200         return err;
2201
2202     /* The unmapping function will free this */
2203     dst->data[0] = (uint8_t *)f;
2204     dst->width   = src->width;
2205     dst->height  = src->height;
2206
2207     map = av_mallocz(sizeof(VulkanMapping));
2208     if (!map)
2209         goto fail;
2210
2211     map->frame = f;
2212     map->flags = flags;
2213
2214     err = ff_hwframe_map_create(dst->hw_frames_ctx, dst, src,
2215                                 &vulkan_unmap_from, map);
2216     if (err < 0)
2217         goto fail;
2218
2219     av_log(hwfc, AV_LOG_DEBUG, "Mapped DRM object to Vulkan!\n");
2220
2221     return 0;
2222
2223 fail:
2224     vulkan_frame_free(hwfc->device_ctx->hwctx, (uint8_t *)f);
2225     av_free(map);
2226     return err;
2227 }
2228
2229 #if CONFIG_VAAPI
2230 static int vulkan_map_from_vaapi(AVHWFramesContext *dst_fc,
2231                                  AVFrame *dst, const AVFrame *src,
2232                                  int flags)
2233 {
2234     int err;
2235     AVFrame *tmp = av_frame_alloc();
2236     AVHWFramesContext *vaapi_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2237     AVVAAPIDeviceContext *vaapi_ctx = vaapi_fc->device_ctx->hwctx;
2238     VASurfaceID surface_id = (VASurfaceID)(uintptr_t)src->data[3];
2239
2240     if (!tmp)
2241         return AVERROR(ENOMEM);
2242
2243     /* We have to sync since like the previous comment said, no semaphores */
2244     vaSyncSurface(vaapi_ctx->display, surface_id);
2245
2246     tmp->format = AV_PIX_FMT_DRM_PRIME;
2247
2248     err = av_hwframe_map(tmp, src, flags);
2249     if (err < 0)
2250         goto fail;
2251
2252     err = vulkan_map_from_drm(dst_fc, dst, tmp, flags);
2253     if (err < 0)
2254         goto fail;
2255
2256     err = ff_hwframe_map_replace(dst, src);
2257
2258 fail:
2259     av_frame_free(&tmp);
2260     return err;
2261 }
2262 #endif
2263 #endif
2264
2265 #if CONFIG_CUDA
2266 static int vulkan_export_to_cuda(AVHWFramesContext *hwfc,
2267                                  AVBufferRef *cuda_hwfc,
2268                                  const AVFrame *frame)
2269 {
2270     int err;
2271     VkResult ret;
2272     AVVkFrame *dst_f;
2273     AVVkFrameInternal *dst_int;
2274     AVHWDeviceContext *ctx = hwfc->device_ctx;
2275     AVVulkanDeviceContext *hwctx = ctx->hwctx;
2276     const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2277     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2278     VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2279     VK_LOAD_PFN(hwctx->inst, vkGetSemaphoreFdKHR);
2280
2281     AVHWFramesContext *cuda_fc = (AVHWFramesContext*)cuda_hwfc->data;
2282     AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2283     AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2284     AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2285     CudaFunctions *cu = cu_internal->cuda_dl;
2286     CUarray_format cufmt = desc->comp[0].depth > 8 ? CU_AD_FORMAT_UNSIGNED_INT16 :
2287                                                      CU_AD_FORMAT_UNSIGNED_INT8;
2288
2289     dst_f = (AVVkFrame *)frame->data[0];
2290
2291     dst_int = dst_f->internal;
2292     if (!dst_int || !dst_int->cuda_fc_ref) {
2293         if (!dst_f->internal)
2294             dst_f->internal = dst_int = av_mallocz(sizeof(*dst_f->internal));
2295
2296         if (!dst_int) {
2297             err = AVERROR(ENOMEM);
2298             goto fail;
2299         }
2300
2301         dst_int->cuda_fc_ref = av_buffer_ref(cuda_hwfc);
2302         if (!dst_int->cuda_fc_ref) {
2303             err = AVERROR(ENOMEM);
2304             goto fail;
2305         }
2306
2307         for (int i = 0; i < planes; i++) {
2308             CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC tex_desc = {
2309                 .offset = 0,
2310                 .arrayDesc = {
2311                     .Width  = i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2312                                     : hwfc->width,
2313                     .Height = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2314                                     : hwfc->height,
2315                     .Depth = 0,
2316                     .Format = cufmt,
2317                     .NumChannels = 1 + ((planes == 2) && i),
2318                     .Flags = 0,
2319                 },
2320                 .numLevels = 1,
2321             };
2322             CUDA_EXTERNAL_MEMORY_HANDLE_DESC ext_desc = {
2323                 .type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD,
2324                 .size = dst_f->size[i],
2325             };
2326             VkMemoryGetFdInfoKHR export_info = {
2327                 .sType      = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2328                 .memory     = dst_f->mem[i],
2329                 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR,
2330             };
2331             VkSemaphoreGetFdInfoKHR sem_export = {
2332                 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR,
2333                 .semaphore = dst_f->sem[i],
2334                 .handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT,
2335             };
2336             CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC ext_sem_desc = {
2337                 .type = CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD,
2338             };
2339
2340             ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2341                                        &ext_desc.handle.fd);
2342             if (ret != VK_SUCCESS) {
2343                 av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2344                 err = AVERROR_EXTERNAL;
2345                 goto fail;
2346             }
2347
2348             ret = CHECK_CU(cu->cuImportExternalMemory(&dst_int->ext_mem[i], &ext_desc));
2349             if (ret < 0) {
2350                 err = AVERROR_EXTERNAL;
2351                 goto fail;
2352             }
2353
2354             ret = CHECK_CU(cu->cuExternalMemoryGetMappedMipmappedArray(&dst_int->cu_mma[i],
2355                                                                        dst_int->ext_mem[i],
2356                                                                        &tex_desc));
2357             if (ret < 0) {
2358                 err = AVERROR_EXTERNAL;
2359                 goto fail;
2360             }
2361
2362             ret = CHECK_CU(cu->cuMipmappedArrayGetLevel(&dst_int->cu_array[i],
2363                                                         dst_int->cu_mma[i], 0));
2364             if (ret < 0) {
2365                 err = AVERROR_EXTERNAL;
2366                 goto fail;
2367             }
2368
2369             ret = pfn_vkGetSemaphoreFdKHR(hwctx->act_dev, &sem_export,
2370                                           &ext_sem_desc.handle.fd);
2371             if (ret != VK_SUCCESS) {
2372                 av_log(ctx, AV_LOG_ERROR, "Failed to export semaphore: %s\n",
2373                        vk_ret2str(ret));
2374                 err = AVERROR_EXTERNAL;
2375                 goto fail;
2376             }
2377
2378             ret = CHECK_CU(cu->cuImportExternalSemaphore(&dst_int->cu_sem[i],
2379                                                          &ext_sem_desc));
2380             if (ret < 0) {
2381                 err = AVERROR_EXTERNAL;
2382                 goto fail;
2383             }
2384         }
2385     }
2386
2387     return 0;
2388
2389 fail:
2390     return err;
2391 }
2392
2393 static int vulkan_transfer_data_from_cuda(AVHWFramesContext *hwfc,
2394                                           AVFrame *dst, const AVFrame *src)
2395 {
2396     int err;
2397     VkResult ret;
2398     CUcontext dummy;
2399     AVVkFrame *dst_f;
2400     AVVkFrameInternal *dst_int;
2401     const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2402     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
2403
2404     AVHWFramesContext *cuda_fc = (AVHWFramesContext*)src->hw_frames_ctx->data;
2405     AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
2406     AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
2407     AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
2408     CudaFunctions *cu = cu_internal->cuda_dl;
2409     CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS s_w_par[AV_NUM_DATA_POINTERS] = { 0 };
2410     CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS s_s_par[AV_NUM_DATA_POINTERS] = { 0 };
2411
2412     ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
2413     if (ret < 0)
2414         return AVERROR_EXTERNAL;
2415
2416     dst_f = (AVVkFrame *)dst->data[0];
2417
2418     ret = vulkan_export_to_cuda(hwfc, src->hw_frames_ctx, dst);
2419     if (ret < 0) {
2420         CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2421         return ret;
2422     }
2423
2424     dst_int = dst_f->internal;
2425
2426     ret = CHECK_CU(cu->cuWaitExternalSemaphoresAsync(dst_int->cu_sem, s_w_par,
2427                                                      planes, cuda_dev->stream));
2428     if (ret < 0) {
2429         err = AVERROR_EXTERNAL;
2430         goto fail;
2431     }
2432
2433     for (int i = 0; i < planes; i++) {
2434         CUDA_MEMCPY2D cpy = {
2435             .srcMemoryType = CU_MEMORYTYPE_DEVICE,
2436             .srcDevice     = (CUdeviceptr)src->data[i],
2437             .srcPitch      = src->linesize[i],
2438             .srcY          = 0,
2439
2440             .dstMemoryType = CU_MEMORYTYPE_ARRAY,
2441             .dstArray      = dst_int->cu_array[i],
2442             .WidthInBytes  = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
2443                                     : hwfc->width) * desc->comp[i].step,
2444             .Height        = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
2445                                    : hwfc->height,
2446         };
2447
2448         ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
2449         if (ret < 0) {
2450             err = AVERROR_EXTERNAL;
2451             goto fail;
2452         }
2453     }
2454
2455     ret = CHECK_CU(cu->cuSignalExternalSemaphoresAsync(dst_int->cu_sem, s_s_par,
2456                                                        planes, cuda_dev->stream));
2457     if (ret < 0) {
2458         err = AVERROR_EXTERNAL;
2459         goto fail;
2460     }
2461
2462     CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2463
2464     av_log(hwfc, AV_LOG_VERBOSE, "Transfered CUDA image to Vulkan!\n");
2465
2466     return 0;
2467
2468 fail:
2469     CHECK_CU(cu->cuCtxPopCurrent(&dummy));
2470     vulkan_free_internal(dst_int);
2471     dst_f->internal = NULL;
2472     av_buffer_unref(&dst->buf[0]);
2473     return err;
2474 }
2475 #endif
2476
2477 static int vulkan_map_to(AVHWFramesContext *hwfc, AVFrame *dst,
2478                          const AVFrame *src, int flags)
2479 {
2480     av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2481
2482     switch (src->format) {
2483 #if CONFIG_LIBDRM
2484 #if CONFIG_VAAPI
2485     case AV_PIX_FMT_VAAPI:
2486         if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2487             return vulkan_map_from_vaapi(hwfc, dst, src, flags);
2488 #endif
2489     case AV_PIX_FMT_DRM_PRIME:
2490         if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2491             return vulkan_map_from_drm(hwfc, dst, src, flags);
2492 #endif
2493     default:
2494         return AVERROR(ENOSYS);
2495     }
2496 }
2497
2498 #if CONFIG_LIBDRM
2499 typedef struct VulkanDRMMapping {
2500     AVDRMFrameDescriptor drm_desc;
2501     AVVkFrame *source;
2502 } VulkanDRMMapping;
2503
2504 static void vulkan_unmap_to_drm(AVHWFramesContext *hwfc, HWMapDescriptor *hwmap)
2505 {
2506     AVDRMFrameDescriptor *drm_desc = hwmap->priv;
2507
2508     for (int i = 0; i < drm_desc->nb_objects; i++)
2509         close(drm_desc->objects[i].fd);
2510
2511     av_free(drm_desc);
2512 }
2513
2514 static inline uint32_t vulkan_fmt_to_drm(VkFormat vkfmt)
2515 {
2516     for (int i = 0; i < FF_ARRAY_ELEMS(vulkan_drm_format_map); i++)
2517         if (vulkan_drm_format_map[i].vk_format == vkfmt)
2518             return vulkan_drm_format_map[i].drm_fourcc;
2519     return DRM_FORMAT_INVALID;
2520 }
2521
2522 static int vulkan_map_to_drm(AVHWFramesContext *hwfc, AVFrame *dst,
2523                              const AVFrame *src, int flags)
2524 {
2525     int err = 0;
2526     VkResult ret;
2527     AVVkFrame *f = (AVVkFrame *)src->data[0];
2528     VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2529     VulkanFramesPriv *fp = hwfc->internal->priv;
2530     AVVulkanDeviceContext *hwctx = hwfc->device_ctx->hwctx;
2531     const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
2532     VK_LOAD_PFN(hwctx->inst, vkGetMemoryFdKHR);
2533     VkImageDrmFormatModifierPropertiesEXT drm_mod = {
2534         .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT,
2535     };
2536
2537     AVDRMFrameDescriptor *drm_desc = av_mallocz(sizeof(*drm_desc));
2538     if (!drm_desc)
2539         return AVERROR(ENOMEM);
2540
2541     err = prepare_frame(hwfc, &fp->conv_ctx, f, PREP_MODE_EXTERNAL_EXPORT);
2542     if (err < 0)
2543         goto end;
2544
2545     err = ff_hwframe_map_create(src->hw_frames_ctx, dst, src, &vulkan_unmap_to_drm, drm_desc);
2546     if (err < 0)
2547         goto end;
2548
2549     if (p->extensions & EXT_DRM_MODIFIER_FLAGS) {
2550         VK_LOAD_PFN(hwctx->inst, vkGetImageDrmFormatModifierPropertiesEXT);
2551         ret = pfn_vkGetImageDrmFormatModifierPropertiesEXT(hwctx->act_dev, f->img[0],
2552                                                            &drm_mod);
2553         if (ret != VK_SUCCESS) {
2554             av_log(hwfc, AV_LOG_ERROR, "Failed to retrieve DRM format modifier!\n");
2555             err = AVERROR_EXTERNAL;
2556             goto end;
2557         }
2558     }
2559
2560     for (int i = 0; (i < planes) && (f->mem[i]); i++) {
2561         VkMemoryGetFdInfoKHR export_info = {
2562             .sType      = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,
2563             .memory     = f->mem[i],
2564             .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,
2565         };
2566
2567         ret = pfn_vkGetMemoryFdKHR(hwctx->act_dev, &export_info,
2568                                    &drm_desc->objects[i].fd);
2569         if (ret != VK_SUCCESS) {
2570             av_log(hwfc, AV_LOG_ERROR, "Unable to export the image as a FD!\n");
2571             err = AVERROR_EXTERNAL;
2572             goto end;
2573         }
2574
2575         drm_desc->nb_objects++;
2576         drm_desc->objects[i].size = f->size[i];
2577         drm_desc->objects[i].format_modifier = drm_mod.drmFormatModifier;
2578     }
2579
2580     drm_desc->nb_layers = planes;
2581     for (int i = 0; i < drm_desc->nb_layers; i++) {
2582         VkSubresourceLayout layout;
2583         VkImageSubresource sub = {
2584             .aspectMask = p->extensions & EXT_DRM_MODIFIER_FLAGS ?
2585                           VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT :
2586                           VK_IMAGE_ASPECT_COLOR_BIT,
2587         };
2588         VkFormat plane_vkfmt = av_vkfmt_from_pixfmt(hwfc->sw_format)[i];
2589
2590         drm_desc->layers[i].format    = vulkan_fmt_to_drm(plane_vkfmt);
2591         drm_desc->layers[i].nb_planes = 1;
2592
2593         if (drm_desc->layers[i].format == DRM_FORMAT_INVALID) {
2594             av_log(hwfc, AV_LOG_ERROR, "Cannot map to DRM layer, unsupported!\n");
2595             err = AVERROR_PATCHWELCOME;
2596             goto end;
2597         }
2598
2599         drm_desc->layers[i].planes[0].object_index = FFMIN(i, drm_desc->nb_objects - 1);
2600
2601         if (f->tiling == VK_IMAGE_TILING_OPTIMAL)
2602             continue;
2603
2604         vkGetImageSubresourceLayout(hwctx->act_dev, f->img[i], &sub, &layout);
2605         drm_desc->layers[i].planes[0].offset       = layout.offset;
2606         drm_desc->layers[i].planes[0].pitch        = layout.rowPitch;
2607     }
2608
2609     dst->width   = src->width;
2610     dst->height  = src->height;
2611     dst->data[0] = (uint8_t *)drm_desc;
2612
2613     av_log(hwfc, AV_LOG_VERBOSE, "Mapped AVVkFrame to a DRM object!\n");
2614
2615     return 0;
2616
2617 end:
2618     av_free(drm_desc);
2619     return err;
2620 }
2621
2622 #if CONFIG_VAAPI
2623 static int vulkan_map_to_vaapi(AVHWFramesContext *hwfc, AVFrame *dst,
2624                                const AVFrame *src, int flags)
2625 {
2626     int err;
2627     AVFrame *tmp = av_frame_alloc();
2628     if (!tmp)
2629         return AVERROR(ENOMEM);
2630
2631     tmp->format = AV_PIX_FMT_DRM_PRIME;
2632
2633     err = vulkan_map_to_drm(hwfc, tmp, src, flags);
2634     if (err < 0)
2635         goto fail;
2636
2637     err = av_hwframe_map(dst, tmp, flags);
2638     if (err < 0)
2639         goto fail;
2640
2641     err = ff_hwframe_map_replace(dst, src);
2642
2643 fail:
2644     av_frame_free(&tmp);
2645     return err;
2646 }
2647 #endif
2648 #endif
2649
2650 static int vulkan_map_from(AVHWFramesContext *hwfc, AVFrame *dst,
2651                            const AVFrame *src, int flags)
2652 {
2653     av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
2654
2655     switch (dst->format) {
2656 #if CONFIG_LIBDRM
2657     case AV_PIX_FMT_DRM_PRIME:
2658         if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2659             return vulkan_map_to_drm(hwfc, dst, src, flags);
2660 #if CONFIG_VAAPI
2661     case AV_PIX_FMT_VAAPI:
2662         if (p->extensions & EXT_EXTERNAL_DMABUF_MEMORY)
2663             return vulkan_map_to_vaapi(hwfc, dst, src, flags);
2664 #endif
2665 #endif
2666     default:
2667         return vulkan_map_frame_to_mem(hwfc, dst, src, flags);
2668     }
2669 }
2670
2671 typedef struct ImageBuffer {
2672     VkBuffer buf;
2673     VkDeviceMemory mem;
2674     VkMemoryPropertyFlagBits flags;
2675     int mapped_mem;
2676 } ImageBuffer;
2677
2678 static void free_buf(void *opaque, uint8_t *data)
2679 {
2680     AVHWDeviceContext *ctx = opaque;
2681     AVVulkanDeviceContext *hwctx = ctx->hwctx;
2682     ImageBuffer *vkbuf = (ImageBuffer *)data;
2683
2684     if (vkbuf->buf)
2685         vkDestroyBuffer(hwctx->act_dev, vkbuf->buf, hwctx->alloc);
2686     if (vkbuf->mem)
2687         vkFreeMemory(hwctx->act_dev, vkbuf->mem, hwctx->alloc);
2688
2689     av_free(data);
2690 }
2691
2692 static size_t get_req_buffer_size(VulkanDevicePriv *p, int *stride, int height)
2693 {
2694     size_t size;
2695     *stride = FFALIGN(*stride, p->props.properties.limits.optimalBufferCopyRowPitchAlignment);
2696     size = height*(*stride);
2697     size = FFALIGN(size, p->props.properties.limits.minMemoryMapAlignment);
2698     return size;
2699 }
2700
2701 static int create_buf(AVHWDeviceContext *ctx, AVBufferRef **buf,
2702                       VkBufferUsageFlags usage, VkMemoryPropertyFlagBits flags,
2703                       size_t size, uint32_t req_memory_bits, int host_mapped,
2704                       void *create_pnext, void *alloc_pnext)
2705 {
2706     int err;
2707     VkResult ret;
2708     int use_ded_mem;
2709     AVVulkanDeviceContext *hwctx = ctx->hwctx;
2710
2711     VkBufferCreateInfo buf_spawn = {
2712         .sType       = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
2713         .pNext       = create_pnext,
2714         .usage       = usage,
2715         .size        = size,
2716         .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
2717     };
2718
2719     VkBufferMemoryRequirementsInfo2 req_desc = {
2720         .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2,
2721     };
2722     VkMemoryDedicatedAllocateInfo ded_alloc = {
2723         .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
2724         .pNext = alloc_pnext,
2725     };
2726     VkMemoryDedicatedRequirements ded_req = {
2727         .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
2728     };
2729     VkMemoryRequirements2 req = {
2730         .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
2731         .pNext = &ded_req,
2732     };
2733
2734     ImageBuffer *vkbuf = av_mallocz(sizeof(*vkbuf));
2735     if (!vkbuf)
2736         return AVERROR(ENOMEM);
2737
2738     vkbuf->mapped_mem = host_mapped;
2739
2740     ret = vkCreateBuffer(hwctx->act_dev, &buf_spawn, NULL, &vkbuf->buf);
2741     if (ret != VK_SUCCESS) {
2742         av_log(ctx, AV_LOG_ERROR, "Failed to create buffer: %s\n",
2743                vk_ret2str(ret));
2744         err = AVERROR_EXTERNAL;
2745         goto fail;
2746     }
2747
2748     req_desc.buffer = vkbuf->buf;
2749
2750     vkGetBufferMemoryRequirements2(hwctx->act_dev, &req_desc, &req);
2751
2752     /* In case the implementation prefers/requires dedicated allocation */
2753     use_ded_mem = ded_req.prefersDedicatedAllocation |
2754                   ded_req.requiresDedicatedAllocation;
2755     if (use_ded_mem)
2756         ded_alloc.buffer = vkbuf->buf;
2757
2758     /* Additional requirements imposed on us */
2759     if (req_memory_bits)
2760         req.memoryRequirements.memoryTypeBits &= req_memory_bits;
2761
2762     err = alloc_mem(ctx, &req.memoryRequirements, flags,
2763                     use_ded_mem ? &ded_alloc : (void *)ded_alloc.pNext,
2764                     &vkbuf->flags, &vkbuf->mem);
2765     if (err)
2766         goto fail;
2767
2768     ret = vkBindBufferMemory(hwctx->act_dev, vkbuf->buf, vkbuf->mem, 0);
2769     if (ret != VK_SUCCESS) {
2770         av_log(ctx, AV_LOG_ERROR, "Failed to bind memory to buffer: %s\n",
2771                vk_ret2str(ret));
2772         err = AVERROR_EXTERNAL;
2773         goto fail;
2774     }
2775
2776     *buf = av_buffer_create((uint8_t *)vkbuf, sizeof(*vkbuf), free_buf, ctx, 0);
2777     if (!(*buf)) {
2778         err = AVERROR(ENOMEM);
2779         goto fail;
2780     }
2781
2782     return 0;
2783
2784 fail:
2785     free_buf(ctx, (uint8_t *)vkbuf);
2786     return err;
2787 }
2788
2789 /* Skips mapping of host mapped buffers but still invalidates them */
2790 static int map_buffers(AVHWDeviceContext *ctx, AVBufferRef **bufs, uint8_t *mem[],
2791                        int nb_buffers, int invalidate)
2792 {
2793     VkResult ret;
2794     AVVulkanDeviceContext *hwctx = ctx->hwctx;
2795     VkMappedMemoryRange invalidate_ctx[AV_NUM_DATA_POINTERS];
2796     int invalidate_count = 0;
2797
2798     for (int i = 0; i < nb_buffers; i++) {
2799         ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2800         if (vkbuf->mapped_mem)
2801             continue;
2802
2803         ret = vkMapMemory(hwctx->act_dev, vkbuf->mem, 0,
2804                           VK_WHOLE_SIZE, 0, (void **)&mem[i]);
2805         if (ret != VK_SUCCESS) {
2806             av_log(ctx, AV_LOG_ERROR, "Failed to map buffer memory: %s\n",
2807                    vk_ret2str(ret));
2808             return AVERROR_EXTERNAL;
2809         }
2810     }
2811
2812     if (!invalidate)
2813         return 0;
2814
2815     for (int i = 0; i < nb_buffers; i++) {
2816         ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2817         const VkMappedMemoryRange ival_buf = {
2818             .sType  = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2819             .memory = vkbuf->mem,
2820             .size   = VK_WHOLE_SIZE,
2821         };
2822
2823         /* For host imported memory Vulkan says to use platform-defined
2824          * sync methods, but doesn't really say not to call flush or invalidate
2825          * on original host pointers. It does explicitly allow to do that on
2826          * host-mapped pointers which are then mapped again using vkMapMemory,
2827          * but known implementations return the original pointers when mapped
2828          * again. */
2829         if (vkbuf->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2830             continue;
2831
2832         invalidate_ctx[invalidate_count++] = ival_buf;
2833     }
2834
2835     if (invalidate_count) {
2836         ret = vkInvalidateMappedMemoryRanges(hwctx->act_dev, invalidate_count,
2837                                              invalidate_ctx);
2838         if (ret != VK_SUCCESS)
2839             av_log(ctx, AV_LOG_WARNING, "Failed to invalidate memory: %s\n",
2840                    vk_ret2str(ret));
2841     }
2842
2843     return 0;
2844 }
2845
2846 static int unmap_buffers(AVHWDeviceContext *ctx, AVBufferRef **bufs,
2847                          int nb_buffers, int flush)
2848 {
2849     int err = 0;
2850     VkResult ret;
2851     AVVulkanDeviceContext *hwctx = ctx->hwctx;
2852     VkMappedMemoryRange flush_ctx[AV_NUM_DATA_POINTERS];
2853     int flush_count = 0;
2854
2855     if (flush) {
2856         for (int i = 0; i < nb_buffers; i++) {
2857             ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2858             const VkMappedMemoryRange flush_buf = {
2859                 .sType  = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
2860                 .memory = vkbuf->mem,
2861                 .size   = VK_WHOLE_SIZE,
2862             };
2863
2864             if (vkbuf->flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
2865                 continue;
2866
2867             flush_ctx[flush_count++] = flush_buf;
2868         }
2869     }
2870
2871     if (flush_count) {
2872         ret = vkFlushMappedMemoryRanges(hwctx->act_dev, flush_count, flush_ctx);
2873         if (ret != VK_SUCCESS) {
2874             av_log(ctx, AV_LOG_ERROR, "Failed to flush memory: %s\n",
2875                     vk_ret2str(ret));
2876             err = AVERROR_EXTERNAL; /* We still want to try to unmap them */
2877         }
2878     }
2879
2880     for (int i = 0; i < nb_buffers; i++) {
2881         ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2882         if (vkbuf->mapped_mem)
2883             continue;
2884
2885         vkUnmapMemory(hwctx->act_dev, vkbuf->mem);
2886     }
2887
2888     return err;
2889 }
2890
2891 static int transfer_image_buf(AVHWFramesContext *hwfc, const AVFrame *f,
2892                               AVBufferRef **bufs, size_t *buf_offsets,
2893                               const int *buf_stride, int w,
2894                               int h, enum AVPixelFormat pix_fmt, int to_buf)
2895 {
2896     int err;
2897     AVVkFrame *frame = (AVVkFrame *)f->data[0];
2898     VulkanFramesPriv *fp = hwfc->internal->priv;
2899
2900     int bar_num = 0;
2901     VkPipelineStageFlagBits sem_wait_dst[AV_NUM_DATA_POINTERS];
2902
2903     const int planes = av_pix_fmt_count_planes(pix_fmt);
2904     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2905
2906     VkImageMemoryBarrier img_bar[AV_NUM_DATA_POINTERS] = { 0 };
2907     VulkanExecCtx *ectx = to_buf ? &fp->download_ctx : &fp->upload_ctx;
2908     VkCommandBuffer cmd_buf = get_buf_exec_ctx(hwfc, ectx);
2909
2910     VkSubmitInfo s_info = {
2911         .sType                = VK_STRUCTURE_TYPE_SUBMIT_INFO,
2912         .pSignalSemaphores    = frame->sem,
2913         .pWaitSemaphores      = frame->sem,
2914         .pWaitDstStageMask    = sem_wait_dst,
2915         .signalSemaphoreCount = planes,
2916         .waitSemaphoreCount   = planes,
2917     };
2918
2919     if ((err = wait_start_exec_ctx(hwfc, ectx)))
2920         return err;
2921
2922     /* Change the image layout to something more optimal for transfers */
2923     for (int i = 0; i < planes; i++) {
2924         VkImageLayout new_layout = to_buf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL :
2925                                             VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
2926         VkAccessFlags new_access = to_buf ? VK_ACCESS_TRANSFER_READ_BIT :
2927                                             VK_ACCESS_TRANSFER_WRITE_BIT;
2928
2929         sem_wait_dst[i] = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
2930
2931         /* If the layout matches and we have read access skip the barrier */
2932         if ((frame->layout[i] == new_layout) && (frame->access[i] & new_access))
2933             continue;
2934
2935         img_bar[bar_num].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
2936         img_bar[bar_num].srcAccessMask = 0x0;
2937         img_bar[bar_num].dstAccessMask = new_access;
2938         img_bar[bar_num].oldLayout = frame->layout[i];
2939         img_bar[bar_num].newLayout = new_layout;
2940         img_bar[bar_num].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2941         img_bar[bar_num].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2942         img_bar[bar_num].image = frame->img[i];
2943         img_bar[bar_num].subresourceRange.levelCount = 1;
2944         img_bar[bar_num].subresourceRange.layerCount = 1;
2945         img_bar[bar_num].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2946
2947         frame->layout[i] = img_bar[bar_num].newLayout;
2948         frame->access[i] = img_bar[bar_num].dstAccessMask;
2949
2950         bar_num++;
2951     }
2952
2953     if (bar_num)
2954         vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
2955                              VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
2956                              0, NULL, 0, NULL, bar_num, img_bar);
2957
2958     /* Schedule a copy for each plane */
2959     for (int i = 0; i < planes; i++) {
2960         ImageBuffer *vkbuf = (ImageBuffer *)bufs[i]->data;
2961         const int p_w = i > 0 ? AV_CEIL_RSHIFT(w, desc->log2_chroma_w) : w;
2962         const int p_h = i > 0 ? AV_CEIL_RSHIFT(h, desc->log2_chroma_h) : h;
2963         VkBufferImageCopy buf_reg = {
2964             .bufferOffset = buf_offsets[i],
2965             /* Buffer stride isn't in bytes, it's in samples, the implementation
2966              * uses the image's VkFormat to know how many bytes per sample
2967              * the buffer has. So we have to convert by dividing. Stupid.
2968              * Won't work with YUVA or other planar formats with alpha. */
2969             .bufferRowLength = buf_stride[i] / desc->comp[i].step,
2970             .bufferImageHeight = p_h,
2971             .imageSubresource.layerCount = 1,
2972             .imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
2973             .imageOffset = { 0, 0, 0, },
2974             .imageExtent = { p_w, p_h, 1, },
2975         };
2976
2977         if (to_buf)
2978             vkCmdCopyImageToBuffer(cmd_buf, frame->img[i], frame->layout[i],
2979                                    vkbuf->buf, 1, &buf_reg);
2980         else
2981             vkCmdCopyBufferToImage(cmd_buf, vkbuf->buf, frame->img[i],
2982                                    frame->layout[i], 1, &buf_reg);
2983     }
2984
2985     /* When uploading, do this asynchronously if the source is refcounted by
2986      * keeping the buffers as a submission dependency.
2987      * The hwcontext is guaranteed to not be freed until all frames are freed
2988      * in the frames_unint function.
2989      * When downloading to buffer, do this synchronously and wait for the
2990      * queue submission to finish executing */
2991     if (!to_buf) {
2992         int ref;
2993         for (ref = 0; ref < AV_NUM_DATA_POINTERS; ref++) {
2994             if (!f->buf[ref])
2995                 break;
2996             if ((err = add_buf_dep_exec_ctx(hwfc, ectx, &f->buf[ref], 1)))
2997                 return err;
2998         }
2999         if (ref && (err = add_buf_dep_exec_ctx(hwfc, ectx, bufs, planes)))
3000             return err;
3001         return submit_exec_ctx(hwfc, ectx, &s_info, !ref);
3002     } else {
3003         return submit_exec_ctx(hwfc, ectx, &s_info,    1);
3004     }
3005 }
3006
3007 static int vulkan_transfer_data(AVHWFramesContext *hwfc, const AVFrame *vkf,
3008                                 const AVFrame *swf, int from)
3009 {
3010     int err = 0;
3011     VkResult ret;
3012     AVVkFrame *f = (AVVkFrame *)vkf->data[0];
3013     AVHWDeviceContext *dev_ctx = hwfc->device_ctx;
3014     AVVulkanDeviceContext *hwctx = dev_ctx->hwctx;
3015     VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
3016
3017     AVFrame tmp;
3018     AVBufferRef *bufs[AV_NUM_DATA_POINTERS] = { 0 };
3019     size_t buf_offsets[AV_NUM_DATA_POINTERS] = { 0 };
3020
3021     const int planes = av_pix_fmt_count_planes(swf->format);
3022     int log2_chroma = av_pix_fmt_desc_get(swf->format)->log2_chroma_h;
3023
3024     int host_mapped[AV_NUM_DATA_POINTERS] = { 0 };
3025     const int map_host = !!(p->extensions & EXT_EXTERNAL_HOST_MEMORY);
3026
3027     VK_LOAD_PFN(hwctx->inst, vkGetMemoryHostPointerPropertiesEXT);
3028
3029     if ((swf->format != AV_PIX_FMT_NONE && !av_vkfmt_from_pixfmt(swf->format))) {
3030         av_log(hwfc, AV_LOG_ERROR, "Unsupported software frame pixel format!\n");
3031         return AVERROR(EINVAL);
3032     }
3033
3034     if (swf->width > hwfc->width || swf->height > hwfc->height)
3035         return AVERROR(EINVAL);
3036
3037     /* For linear, host visiable images */
3038     if (f->tiling == VK_IMAGE_TILING_LINEAR &&
3039         f->flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
3040         AVFrame *map = av_frame_alloc();
3041         if (!map)
3042             return AVERROR(ENOMEM);
3043         map->format = swf->format;
3044
3045         err = vulkan_map_frame_to_mem(hwfc, map, vkf, AV_HWFRAME_MAP_WRITE);
3046         if (err)
3047             return err;
3048
3049         err = av_frame_copy((AVFrame *)(from ? swf : map), from ? map : swf);
3050         av_frame_free(&map);
3051         return err;
3052     }
3053
3054     /* Create buffers */
3055     for (int i = 0; i < planes; i++) {
3056         size_t req_size;
3057         int h = swf->height;
3058         int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
3059
3060         VkExternalMemoryBufferCreateInfo create_desc = {
3061             .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO,
3062             .handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT,
3063         };
3064
3065         VkImportMemoryHostPointerInfoEXT import_desc = {
3066             .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT,
3067             .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT,
3068         };
3069
3070         VkMemoryHostPointerPropertiesEXT p_props = {
3071             .sType = VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT,
3072         };
3073
3074         tmp.linesize[i] = FFABS(swf->linesize[i]);
3075
3076         /* Do not map images with a negative stride */
3077         if (map_host && swf->linesize[i] > 0) {
3078             size_t offs;
3079             offs = (uintptr_t)swf->data[i] % p->hprops.minImportedHostPointerAlignment;
3080             import_desc.pHostPointer = swf->data[i] - offs;
3081
3082             /* We have to compensate for the few extra bytes of padding we
3083              * completely ignore at the start */
3084             req_size = FFALIGN(offs + tmp.linesize[i] * p_height,
3085                                p->hprops.minImportedHostPointerAlignment);
3086
3087             ret = pfn_vkGetMemoryHostPointerPropertiesEXT(hwctx->act_dev,
3088                                                           import_desc.handleType,
3089                                                           import_desc.pHostPointer,
3090                                                           &p_props);
3091
3092             if (ret == VK_SUCCESS) {
3093                 host_mapped[i] = 1;
3094                 buf_offsets[i] = offs;
3095             }
3096         }
3097
3098         if (!host_mapped[i])
3099             req_size = get_req_buffer_size(p, &tmp.linesize[i], p_height);
3100
3101         err = create_buf(dev_ctx, &bufs[i],
3102                          from ? VK_BUFFER_USAGE_TRANSFER_DST_BIT :
3103                                 VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
3104                          VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
3105                          req_size, p_props.memoryTypeBits, host_mapped[i],
3106                          host_mapped[i] ? &create_desc : NULL,
3107                          host_mapped[i] ? &import_desc : NULL);
3108         if (err)
3109             goto end;
3110     }
3111
3112     if (!from) {
3113         /* Map, copy image to buffer, unmap */
3114         if ((err = map_buffers(dev_ctx, bufs, tmp.data, planes, 0)))
3115             goto end;
3116
3117         for (int i = 0; i < planes; i++) {
3118             int h = swf->height;
3119             int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
3120
3121             if (host_mapped[i])
3122                 continue;
3123
3124             av_image_copy_plane(tmp.data[i], tmp.linesize[i],
3125                                 (const uint8_t *)swf->data[i], swf->linesize[i],
3126                                 FFMIN(tmp.linesize[i], FFABS(swf->linesize[i])),
3127                                 p_height);
3128         }
3129
3130         if ((err = unmap_buffers(dev_ctx, bufs, planes, 1)))
3131             goto end;
3132     }
3133
3134     /* Copy buffers into/from image */
3135     err = transfer_image_buf(hwfc, vkf, bufs, buf_offsets, tmp.linesize,
3136                              swf->width, swf->height, swf->format, from);
3137
3138     if (from) {
3139         /* Map, copy image to buffer, unmap */
3140         if ((err = map_buffers(dev_ctx, bufs, tmp.data, planes, 0)))
3141             goto end;
3142
3143         for (int i = 0; i < planes; i++) {
3144             int h = swf->height;
3145             int p_height = i > 0 ? AV_CEIL_RSHIFT(h, log2_chroma) : h;
3146
3147             if (host_mapped[i])
3148                 continue;
3149
3150             av_image_copy_plane(swf->data[i], swf->linesize[i],
3151                                 (const uint8_t *)tmp.data[i], tmp.linesize[i],
3152                                 FFMIN(tmp.linesize[i], FFABS(swf->linesize[i])),
3153                                 p_height);
3154         }
3155
3156         if ((err = unmap_buffers(dev_ctx, bufs, planes, 1)))
3157             goto end;
3158     }
3159
3160 end:
3161     for (int i = 0; i < planes; i++)
3162         av_buffer_unref(&bufs[i]);
3163
3164     return err;
3165 }
3166
3167 static int vulkan_transfer_data_to(AVHWFramesContext *hwfc, AVFrame *dst,
3168                                    const AVFrame *src)
3169 {
3170     av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
3171
3172     switch (src->format) {
3173 #if CONFIG_CUDA
3174     case AV_PIX_FMT_CUDA:
3175         if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
3176             (p->extensions & EXT_EXTERNAL_FD_SEM))
3177             return vulkan_transfer_data_from_cuda(hwfc, dst, src);
3178 #endif
3179     default:
3180         if (src->hw_frames_ctx)
3181             return AVERROR(ENOSYS);
3182         else
3183             return vulkan_transfer_data(hwfc, dst, src, 0);
3184     }
3185 }
3186
3187 #if CONFIG_CUDA
3188 static int vulkan_transfer_data_to_cuda(AVHWFramesContext *hwfc, AVFrame *dst,
3189                                         const AVFrame *src)
3190 {
3191     int err;
3192     VkResult ret;
3193     CUcontext dummy;
3194     AVVkFrame *dst_f;
3195     AVVkFrameInternal *dst_int;
3196     const int planes = av_pix_fmt_count_planes(hwfc->sw_format);
3197     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwfc->sw_format);
3198
3199     AVHWFramesContext *cuda_fc = (AVHWFramesContext*)dst->hw_frames_ctx->data;
3200     AVHWDeviceContext *cuda_cu = cuda_fc->device_ctx;
3201     AVCUDADeviceContext *cuda_dev = cuda_cu->hwctx;
3202     AVCUDADeviceContextInternal *cu_internal = cuda_dev->internal;
3203     CudaFunctions *cu = cu_internal->cuda_dl;
3204
3205     ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_dev->cuda_ctx));
3206     if (ret < 0)
3207         return AVERROR_EXTERNAL;
3208
3209     dst_f = (AVVkFrame *)src->data[0];
3210
3211     err = vulkan_export_to_cuda(hwfc, dst->hw_frames_ctx, src);
3212     if (err < 0) {
3213         CHECK_CU(cu->cuCtxPopCurrent(&dummy));
3214         return err;
3215     }
3216
3217     dst_int = dst_f->internal;
3218
3219     for (int i = 0; i < planes; i++) {
3220         CUDA_MEMCPY2D cpy = {
3221             .dstMemoryType = CU_MEMORYTYPE_DEVICE,
3222             .dstDevice     = (CUdeviceptr)dst->data[i],
3223             .dstPitch      = dst->linesize[i],
3224             .dstY          = 0,
3225
3226             .srcMemoryType = CU_MEMORYTYPE_ARRAY,
3227             .srcArray      = dst_int->cu_array[i],
3228             .WidthInBytes  = (i > 0 ? AV_CEIL_RSHIFT(hwfc->width, desc->log2_chroma_w)
3229                                     : hwfc->width) * desc->comp[i].step,
3230             .Height        = i > 0 ? AV_CEIL_RSHIFT(hwfc->height, desc->log2_chroma_h)
3231                                    : hwfc->height,
3232         };
3233
3234         ret = CHECK_CU(cu->cuMemcpy2DAsync(&cpy, cuda_dev->stream));
3235         if (ret < 0) {
3236             err = AVERROR_EXTERNAL;
3237             goto fail;
3238         }
3239     }
3240
3241     CHECK_CU(cu->cuCtxPopCurrent(&dummy));
3242
3243     av_log(hwfc, AV_LOG_VERBOSE, "Transfered Vulkan image to CUDA!\n");
3244
3245     return 0;
3246
3247 fail:
3248     CHECK_CU(cu->cuCtxPopCurrent(&dummy));
3249     vulkan_free_internal(dst_int);
3250     dst_f->internal = NULL;
3251     av_buffer_unref(&dst->buf[0]);
3252     return err;
3253 }
3254 #endif
3255
3256 static int vulkan_transfer_data_from(AVHWFramesContext *hwfc, AVFrame *dst,
3257                                      const AVFrame *src)
3258 {
3259     av_unused VulkanDevicePriv *p = hwfc->device_ctx->internal->priv;
3260
3261     switch (dst->format) {
3262 #if CONFIG_CUDA
3263     case AV_PIX_FMT_CUDA:
3264         if ((p->extensions & EXT_EXTERNAL_FD_MEMORY) &&
3265             (p->extensions & EXT_EXTERNAL_FD_SEM))
3266             return vulkan_transfer_data_to_cuda(hwfc, dst, src);
3267 #endif
3268     default:
3269         if (dst->hw_frames_ctx)
3270             return AVERROR(ENOSYS);
3271         else
3272             return vulkan_transfer_data(hwfc, src, dst, 1);
3273     }
3274 }
3275
3276 static int vulkan_frames_derive_to(AVHWFramesContext *dst_fc,
3277                                    AVHWFramesContext *src_fc, int flags)
3278 {
3279     return vulkan_frames_init(dst_fc);
3280 }
3281
3282 AVVkFrame *av_vk_frame_alloc(void)
3283 {
3284     return av_mallocz(sizeof(AVVkFrame));
3285 }
3286
3287 const HWContextType ff_hwcontext_type_vulkan = {
3288     .type                   = AV_HWDEVICE_TYPE_VULKAN,
3289     .name                   = "Vulkan",
3290
3291     .device_hwctx_size      = sizeof(AVVulkanDeviceContext),
3292     .device_priv_size       = sizeof(VulkanDevicePriv),
3293     .frames_hwctx_size      = sizeof(AVVulkanFramesContext),
3294     .frames_priv_size       = sizeof(VulkanFramesPriv),
3295
3296     .device_init            = &vulkan_device_init,
3297     .device_create          = &vulkan_device_create,
3298     .device_derive          = &vulkan_device_derive,
3299
3300     .frames_get_constraints = &vulkan_frames_get_constraints,
3301     .frames_init            = vulkan_frames_init,
3302     .frames_get_buffer      = vulkan_get_buffer,
3303     .frames_uninit          = vulkan_frames_uninit,
3304
3305     .transfer_get_formats   = vulkan_transfer_get_formats,
3306     .transfer_data_to       = vulkan_transfer_data_to,
3307     .transfer_data_from     = vulkan_transfer_data_from,
3308
3309     .map_to                 = vulkan_map_to,
3310     .map_from               = vulkan_map_from,
3311     .frames_derive_to       = &vulkan_frames_derive_to,
3312
3313     .pix_fmts = (const enum AVPixelFormat []) {
3314         AV_PIX_FMT_VULKAN,
3315         AV_PIX_FMT_NONE
3316     },
3317 };