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