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