testffmpeg_vulkan.c 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  1. /*
  2. Copyright (C) 1997-2026 Sam Lantinga <slouken@libsdl.org>
  3. This software is provided 'as-is', without any express or implied
  4. warranty. In no event will the authors be held liable for any damages
  5. arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it
  8. freely.
  9. */
  10. #include <SDL3/SDL.h>
  11. #include <SDL3/SDL_vulkan.h>
  12. #include "testffmpeg_vulkan.h"
  13. #ifdef FFMPEG_VULKAN_SUPPORT
  14. #ifndef SDL_PLATFORM_WINDOWS
  15. #define FFMPEG_DRMPRIME_SUPPORT
  16. #include <unistd.h>
  17. #define DRM_FORMAT_R8 SDL_FOURCC('R', '8', ' ', ' ')
  18. #define DRM_FORMAT_RG88 SDL_FOURCC('R', 'G', '8', '8')
  19. #define DRM_FORMAT_GR88 SDL_FOURCC('G', 'R', '8', '8')
  20. #define DRM_FORMAT_R16 SDL_FOURCC('R', '1', '6', ' ')
  21. #define DRM_FORMAT_RG1616 SDL_FOURCC('R', 'G', '3', '2')
  22. #define DRM_FORMAT_GR1616 SDL_FOURCC('G', 'R', '3', '2')
  23. #define DRM_FORMAT_NV12 SDL_FOURCC('N', 'V', '1', '2')
  24. #define DRM_FORMAT_P010 SDL_FOURCC('P', '0', '1', '0')
  25. #define DRM_FORMAT_YUYV SDL_FOURCC('Y', 'U', 'Y', 'V')
  26. #define DRM_FORMAT_UYVY SDL_FOURCC('U', 'Y', 'V', 'Y')
  27. #define DRM_FORMAT_ARGB8888 SDL_FOURCC('A', 'R', '2', '4')
  28. #endif
  29. #define VULKAN_FUNCTIONS() \
  30. VULKAN_GLOBAL_FUNCTION(vkCreateInstance) \
  31. VULKAN_GLOBAL_FUNCTION(vkEnumerateInstanceExtensionProperties) \
  32. VULKAN_GLOBAL_FUNCTION(vkEnumerateInstanceLayerProperties) \
  33. VULKAN_INSTANCE_FUNCTION(vkCreateDevice) \
  34. VULKAN_INSTANCE_FUNCTION(vkDestroyInstance) \
  35. VULKAN_INSTANCE_FUNCTION(vkDestroySurfaceKHR) \
  36. VULKAN_INSTANCE_FUNCTION(vkEnumerateDeviceExtensionProperties) \
  37. VULKAN_INSTANCE_FUNCTION(vkEnumeratePhysicalDevices) \
  38. VULKAN_INSTANCE_FUNCTION(vkGetDeviceProcAddr) \
  39. VULKAN_INSTANCE_FUNCTION(vkGetPhysicalDeviceFeatures2) \
  40. VULKAN_INSTANCE_FUNCTION(vkGetPhysicalDeviceMemoryProperties) \
  41. VULKAN_INSTANCE_FUNCTION(vkGetPhysicalDeviceQueueFamilyProperties) \
  42. VULKAN_INSTANCE_FUNCTION(vkGetPhysicalDeviceSurfaceSupportKHR) \
  43. VULKAN_INSTANCE_FUNCTION(vkQueueWaitIdle) \
  44. VULKAN_DEVICE_FUNCTION(vkAllocateCommandBuffers) \
  45. VULKAN_DEVICE_FUNCTION(vkAllocateMemory) \
  46. VULKAN_DEVICE_FUNCTION(vkBeginCommandBuffer) \
  47. VULKAN_DEVICE_FUNCTION(vkBindImageMemory) \
  48. VULKAN_DEVICE_FUNCTION(vkCmdPipelineBarrier2) \
  49. VULKAN_DEVICE_FUNCTION(vkCreateCommandPool) \
  50. VULKAN_DEVICE_FUNCTION(vkCreateImage) \
  51. VULKAN_DEVICE_FUNCTION(vkCreateSemaphore) \
  52. VULKAN_DEVICE_FUNCTION(vkDestroyCommandPool) \
  53. VULKAN_DEVICE_FUNCTION(vkDestroyDevice) \
  54. VULKAN_DEVICE_FUNCTION(vkDestroyImage) \
  55. VULKAN_DEVICE_FUNCTION(vkDestroySemaphore) \
  56. VULKAN_DEVICE_FUNCTION(vkDeviceWaitIdle) \
  57. VULKAN_DEVICE_FUNCTION(vkEndCommandBuffer) \
  58. VULKAN_DEVICE_FUNCTION(vkFreeCommandBuffers) \
  59. VULKAN_DEVICE_FUNCTION(vkFreeMemory) \
  60. VULKAN_DEVICE_FUNCTION(vkGetDeviceQueue) \
  61. VULKAN_DEVICE_FUNCTION(vkGetImageMemoryRequirements) \
  62. VULKAN_DEVICE_FUNCTION(vkQueueSubmit) \
  63. \
  64. VULKAN_INSTANCE_FUNCTION(vkGetPhysicalDeviceVideoFormatPropertiesKHR) \
  65. typedef struct
  66. {
  67. VkPhysicalDeviceFeatures2 device_features;
  68. VkPhysicalDeviceVulkan11Features device_features_1_1;
  69. VkPhysicalDeviceVulkan12Features device_features_1_2;
  70. VkPhysicalDeviceVulkan13Features device_features_1_3;
  71. VkPhysicalDeviceDescriptorBufferFeaturesEXT desc_buf_features;
  72. VkPhysicalDeviceShaderAtomicFloatFeaturesEXT atomic_float_features;
  73. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coop_matrix_features;
  74. } VulkanDeviceFeatures;
  75. struct VulkanVideoContext
  76. {
  77. VkInstance instance;
  78. VkSurfaceKHR surface;
  79. VkPhysicalDevice physicalDevice;
  80. int presentQueueFamilyIndex;
  81. int presentQueueCount;
  82. int graphicsQueueFamilyIndex;
  83. int graphicsQueueCount;
  84. int transferQueueFamilyIndex;
  85. int transferQueueCount;
  86. int computeQueueFamilyIndex;
  87. int computeQueueCount;
  88. int decodeQueueFamilyIndex;
  89. int decodeQueueCount;
  90. VkDevice device;
  91. VkQueue graphicsQueue;
  92. VkCommandPool commandPool;
  93. VkCommandBuffer *commandBuffers;
  94. uint32_t commandBufferCount;
  95. uint32_t commandBufferIndex;
  96. const char **instanceExtensions;
  97. int instanceExtensionsCount;
  98. const char **deviceExtensions;
  99. int deviceExtensionsCount;
  100. VulkanDeviceFeatures features;
  101. PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr;
  102. #define VULKAN_GLOBAL_FUNCTION(name) PFN_##name name;
  103. #define VULKAN_INSTANCE_FUNCTION(name) PFN_##name name;
  104. #define VULKAN_DEVICE_FUNCTION(name) PFN_##name name;
  105. VULKAN_FUNCTIONS()
  106. #undef VULKAN_GLOBAL_FUNCTION
  107. #undef VULKAN_INSTANCE_FUNCTION
  108. #undef VULKAN_DEVICE_FUNCTION
  109. };
  110. static int loadGlobalFunctions(VulkanVideoContext *context)
  111. {
  112. context->vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)SDL_Vulkan_GetVkGetInstanceProcAddr();
  113. if (!context->vkGetInstanceProcAddr) {
  114. return -1;
  115. }
  116. #define VULKAN_GLOBAL_FUNCTION(name) \
  117. context->name = (PFN_##name)context->vkGetInstanceProcAddr(VK_NULL_HANDLE, #name); \
  118. if (!context->name) { \
  119. return SDL_SetError("vkGetInstanceProcAddr(VK_NULL_HANDLE, \"" #name "\") failed"); \
  120. }
  121. #define VULKAN_INSTANCE_FUNCTION(name)
  122. #define VULKAN_DEVICE_FUNCTION(name)
  123. VULKAN_FUNCTIONS()
  124. #undef VULKAN_GLOBAL_FUNCTION
  125. #undef VULKAN_INSTANCE_FUNCTION
  126. #undef VULKAN_DEVICE_FUNCTION
  127. return 0;
  128. }
  129. static int loadInstanceFunctions(VulkanVideoContext *context)
  130. {
  131. #define VULKAN_GLOBAL_FUNCTION(name)
  132. #define VULKAN_INSTANCE_FUNCTION(name) \
  133. context->name = (PFN_##name)context->vkGetInstanceProcAddr(context->instance, #name); \
  134. if (!context->name) { \
  135. return SDL_SetError("vkGetInstanceProcAddr(instance, \"" #name "\") failed"); \
  136. }
  137. #define VULKAN_DEVICE_FUNCTION(name)
  138. VULKAN_FUNCTIONS()
  139. #undef VULKAN_GLOBAL_FUNCTION
  140. #undef VULKAN_INSTANCE_FUNCTION
  141. #undef VULKAN_DEVICE_FUNCTION
  142. return 0;
  143. }
  144. static int loadDeviceFunctions(VulkanVideoContext *context)
  145. {
  146. #define VULKAN_GLOBAL_FUNCTION(name)
  147. #define VULKAN_INSTANCE_FUNCTION(name)
  148. #define VULKAN_DEVICE_FUNCTION(name) \
  149. context->name = (PFN_##name)context->vkGetDeviceProcAddr(context->device, #name); \
  150. if (!context->name) { \
  151. return SDL_SetError("vkGetDeviceProcAddr(device, \"" #name "\") failed"); \
  152. }
  153. VULKAN_FUNCTIONS()
  154. #undef VULKAN_GLOBAL_FUNCTION
  155. #undef VULKAN_INSTANCE_FUNCTION
  156. #undef VULKAN_DEVICE_FUNCTION
  157. return 0;
  158. }
  159. #undef VULKAN_FUNCTIONS
  160. static const char *getVulkanResultString(VkResult result)
  161. {
  162. switch ((int)result) {
  163. #define RESULT_CASE(x) \
  164. case x: \
  165. return #x
  166. RESULT_CASE(VK_SUCCESS);
  167. RESULT_CASE(VK_NOT_READY);
  168. RESULT_CASE(VK_TIMEOUT);
  169. RESULT_CASE(VK_EVENT_SET);
  170. RESULT_CASE(VK_EVENT_RESET);
  171. RESULT_CASE(VK_INCOMPLETE);
  172. RESULT_CASE(VK_ERROR_OUT_OF_HOST_MEMORY);
  173. RESULT_CASE(VK_ERROR_OUT_OF_DEVICE_MEMORY);
  174. RESULT_CASE(VK_ERROR_INITIALIZATION_FAILED);
  175. RESULT_CASE(VK_ERROR_DEVICE_LOST);
  176. RESULT_CASE(VK_ERROR_MEMORY_MAP_FAILED);
  177. RESULT_CASE(VK_ERROR_LAYER_NOT_PRESENT);
  178. RESULT_CASE(VK_ERROR_EXTENSION_NOT_PRESENT);
  179. RESULT_CASE(VK_ERROR_FEATURE_NOT_PRESENT);
  180. RESULT_CASE(VK_ERROR_INCOMPATIBLE_DRIVER);
  181. RESULT_CASE(VK_ERROR_TOO_MANY_OBJECTS);
  182. RESULT_CASE(VK_ERROR_FORMAT_NOT_SUPPORTED);
  183. RESULT_CASE(VK_ERROR_FRAGMENTED_POOL);
  184. RESULT_CASE(VK_ERROR_SURFACE_LOST_KHR);
  185. RESULT_CASE(VK_ERROR_NATIVE_WINDOW_IN_USE_KHR);
  186. RESULT_CASE(VK_SUBOPTIMAL_KHR);
  187. RESULT_CASE(VK_ERROR_OUT_OF_DATE_KHR);
  188. RESULT_CASE(VK_ERROR_INCOMPATIBLE_DISPLAY_KHR);
  189. RESULT_CASE(VK_ERROR_VALIDATION_FAILED_EXT);
  190. RESULT_CASE(VK_ERROR_OUT_OF_POOL_MEMORY_KHR);
  191. RESULT_CASE(VK_ERROR_INVALID_SHADER_NV);
  192. #undef RESULT_CASE
  193. default:
  194. break;
  195. }
  196. return (result < 0) ? "VK_ERROR_<Unknown>" : "VK_<Unknown>";
  197. }
  198. static int createInstance(VulkanVideoContext *context)
  199. {
  200. static const char *optional_extensions[] = {
  201. VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME,
  202. VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME
  203. };
  204. VkApplicationInfo appInfo;
  205. SDL_zero(appInfo);
  206. VkInstanceCreateInfo instanceCreateInfo;
  207. SDL_zero(instanceCreateInfo);
  208. VkResult result;
  209. char const *const *instanceExtensions = SDL_Vulkan_GetInstanceExtensions(&instanceCreateInfo.enabledExtensionCount);
  210. appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
  211. appInfo.apiVersion = VK_API_VERSION_1_3;
  212. instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
  213. instanceCreateInfo.pApplicationInfo = &appInfo;
  214. const char **instanceExtensionsCopy = (const char **)SDL_calloc(instanceCreateInfo.enabledExtensionCount + SDL_arraysize(optional_extensions), sizeof(const char *));
  215. for (uint32_t i = 0; i < instanceCreateInfo.enabledExtensionCount; i++) {
  216. instanceExtensionsCopy[i] = instanceExtensions[i];
  217. }
  218. // Get the rest of the optional extensions
  219. {
  220. uint32_t extensionCount;
  221. if (context->vkEnumerateInstanceExtensionProperties(NULL, &extensionCount, NULL) == VK_SUCCESS && extensionCount > 0) {
  222. VkExtensionProperties *extensionProperties = (VkExtensionProperties *)SDL_calloc(extensionCount, sizeof(VkExtensionProperties));
  223. if (context->vkEnumerateInstanceExtensionProperties(NULL, &extensionCount, extensionProperties) == VK_SUCCESS) {
  224. for (uint32_t i = 0; i < SDL_arraysize(optional_extensions); ++i) {
  225. for (uint32_t j = 0; j < extensionCount; ++j) {
  226. if (SDL_strcmp(extensionProperties[j].extensionName, optional_extensions[i]) == 0) {
  227. instanceExtensionsCopy[instanceCreateInfo.enabledExtensionCount++] = optional_extensions[i];
  228. break;
  229. }
  230. }
  231. }
  232. }
  233. SDL_free(extensionProperties);
  234. }
  235. }
  236. instanceCreateInfo.ppEnabledExtensionNames = instanceExtensionsCopy;
  237. context->instanceExtensions = instanceExtensionsCopy;
  238. context->instanceExtensionsCount = instanceCreateInfo.enabledExtensionCount;
  239. result = context->vkCreateInstance(&instanceCreateInfo, NULL, &context->instance);
  240. if (result != VK_SUCCESS) {
  241. context->instance = VK_NULL_HANDLE;
  242. return SDL_SetError("vkCreateInstance(): %s", getVulkanResultString(result));
  243. }
  244. if (loadInstanceFunctions(context) < 0) {
  245. return -1;
  246. }
  247. return 0;
  248. }
  249. static int createSurface(VulkanVideoContext *context, SDL_Window *window)
  250. {
  251. if (!SDL_Vulkan_CreateSurface(window, context->instance, NULL, &context->surface)) {
  252. context->surface = VK_NULL_HANDLE;
  253. return -1;
  254. }
  255. return 0;
  256. }
  257. // Use the same queue scoring algorithm as ffmpeg to make sure we get the same device configuration
  258. static int selectQueueFamily(VkQueueFamilyProperties *queueFamiliesProperties, uint32_t queueFamiliesCount, VkQueueFlags flags, int *queueCount)
  259. {
  260. uint32_t queueFamilyIndex;
  261. uint32_t selectedQueueFamilyIndex = queueFamiliesCount;
  262. uint32_t min_score = ~0u;
  263. for (queueFamilyIndex = 0; queueFamilyIndex < queueFamiliesCount; ++queueFamilyIndex) {
  264. VkQueueFlags current_flags = queueFamiliesProperties[queueFamilyIndex].queueFlags;
  265. if (current_flags & flags) {
  266. uint32_t score = av_popcount(current_flags) + queueFamiliesProperties[queueFamilyIndex].timestampValidBits;
  267. if (score < min_score) {
  268. selectedQueueFamilyIndex = queueFamilyIndex;
  269. min_score = score;
  270. }
  271. }
  272. }
  273. if (selectedQueueFamilyIndex != queueFamiliesCount) {
  274. VkQueueFamilyProperties *selectedQueueFamily = &queueFamiliesProperties[selectedQueueFamilyIndex];
  275. *queueCount = (int)selectedQueueFamily->queueCount;
  276. ++selectedQueueFamily->timestampValidBits;
  277. return (int)selectedQueueFamilyIndex;
  278. } else {
  279. *queueCount = 0;
  280. return -1;
  281. }
  282. }
  283. static int findPhysicalDevice(VulkanVideoContext *context)
  284. {
  285. uint32_t physicalDeviceCount = 0;
  286. VkPhysicalDevice *physicalDevices;
  287. VkQueueFamilyProperties *queueFamiliesProperties = NULL;
  288. uint32_t queueFamiliesPropertiesAllocatedSize = 0;
  289. VkExtensionProperties *deviceExtensions = NULL;
  290. uint32_t deviceExtensionsAllocatedSize = 0;
  291. uint32_t physicalDeviceIndex;
  292. VkResult result;
  293. result = context->vkEnumeratePhysicalDevices(context->instance, &physicalDeviceCount, NULL);
  294. if (result != VK_SUCCESS) {
  295. return SDL_SetError("vkEnumeratePhysicalDevices(): %s", getVulkanResultString(result));
  296. }
  297. if (physicalDeviceCount == 0) {
  298. return SDL_SetError("vkEnumeratePhysicalDevices(): no physical devices");
  299. }
  300. physicalDevices = (VkPhysicalDevice *)SDL_malloc(sizeof(VkPhysicalDevice) * physicalDeviceCount);
  301. if (!physicalDevices) {
  302. return -1;
  303. }
  304. result = context->vkEnumeratePhysicalDevices(context->instance, &physicalDeviceCount, physicalDevices);
  305. if (result != VK_SUCCESS) {
  306. SDL_free(physicalDevices);
  307. return SDL_SetError("vkEnumeratePhysicalDevices(): %s", getVulkanResultString(result));
  308. }
  309. context->physicalDevice = NULL;
  310. for (physicalDeviceIndex = 0; physicalDeviceIndex < physicalDeviceCount; physicalDeviceIndex++) {
  311. uint32_t queueFamiliesCount = 0;
  312. uint32_t queueFamilyIndex;
  313. uint32_t deviceExtensionCount = 0;
  314. bool hasSwapchainExtension = false;
  315. uint32_t i;
  316. VkPhysicalDevice physicalDevice = physicalDevices[physicalDeviceIndex];
  317. context->vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamiliesCount, NULL);
  318. if (queueFamiliesCount == 0) {
  319. continue;
  320. }
  321. if (queueFamiliesPropertiesAllocatedSize < queueFamiliesCount) {
  322. SDL_free(queueFamiliesProperties);
  323. queueFamiliesPropertiesAllocatedSize = queueFamiliesCount;
  324. queueFamiliesProperties = (VkQueueFamilyProperties *)SDL_malloc(sizeof(VkQueueFamilyProperties) * queueFamiliesPropertiesAllocatedSize);
  325. if (!queueFamiliesProperties) {
  326. SDL_free(physicalDevices);
  327. SDL_free(deviceExtensions);
  328. return -1;
  329. }
  330. }
  331. context->vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamiliesCount, queueFamiliesProperties);
  332. // Initialize timestampValidBits for scoring in selectQueueFamily
  333. for (queueFamilyIndex = 0; queueFamilyIndex < queueFamiliesCount; queueFamilyIndex++) {
  334. queueFamiliesProperties[queueFamilyIndex].timestampValidBits = 0;
  335. }
  336. context->presentQueueFamilyIndex = -1;
  337. context->graphicsQueueFamilyIndex = -1;
  338. for (queueFamilyIndex = 0; queueFamilyIndex < queueFamiliesCount; queueFamilyIndex++) {
  339. VkBool32 supported = 0;
  340. if (queueFamiliesProperties[queueFamilyIndex].queueCount == 0) {
  341. continue;
  342. }
  343. if (queueFamiliesProperties[queueFamilyIndex].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
  344. context->graphicsQueueFamilyIndex = queueFamilyIndex;
  345. }
  346. result = context->vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, queueFamilyIndex, context->surface, &supported);
  347. if (result == VK_SUCCESS) {
  348. if (supported) {
  349. context->presentQueueFamilyIndex = queueFamilyIndex;
  350. if (queueFamiliesProperties[queueFamilyIndex].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
  351. break; // use this queue because it can present and do graphics
  352. }
  353. }
  354. }
  355. }
  356. if (context->presentQueueFamilyIndex < 0 || context->graphicsQueueFamilyIndex < 0) {
  357. // We can't render and present on this device
  358. continue;
  359. }
  360. context->presentQueueCount = queueFamiliesProperties[context->presentQueueFamilyIndex].queueCount;
  361. ++queueFamiliesProperties[context->presentQueueFamilyIndex].timestampValidBits;
  362. context->graphicsQueueCount = queueFamiliesProperties[context->graphicsQueueFamilyIndex].queueCount;
  363. ++queueFamiliesProperties[context->graphicsQueueFamilyIndex].timestampValidBits;
  364. context->transferQueueFamilyIndex = selectQueueFamily(queueFamiliesProperties, queueFamiliesCount, VK_QUEUE_TRANSFER_BIT, &context->transferQueueCount);
  365. context->computeQueueFamilyIndex = selectQueueFamily(queueFamiliesProperties, queueFamiliesCount, VK_QUEUE_COMPUTE_BIT, &context->computeQueueCount);
  366. context->decodeQueueFamilyIndex = selectQueueFamily(queueFamiliesProperties, queueFamiliesCount, VK_QUEUE_VIDEO_DECODE_BIT_KHR, &context->decodeQueueCount);
  367. if (context->transferQueueFamilyIndex < 0) {
  368. // ffmpeg can fall back to the compute or graphics queues for this
  369. context->transferQueueFamilyIndex = selectQueueFamily(queueFamiliesProperties, queueFamiliesCount, VK_QUEUE_COMPUTE_BIT, &context->transferQueueCount);
  370. if (context->transferQueueFamilyIndex < 0) {
  371. context->transferQueueFamilyIndex = selectQueueFamily(queueFamiliesProperties, queueFamiliesCount, VK_QUEUE_GRAPHICS_BIT, &context->transferQueueCount);
  372. }
  373. }
  374. if (context->transferQueueFamilyIndex < 0 ||
  375. context->computeQueueFamilyIndex < 0) {
  376. // This device doesn't have the queues we need for video decoding
  377. continue;
  378. }
  379. result = context->vkEnumerateDeviceExtensionProperties(physicalDevice, NULL, &deviceExtensionCount, NULL);
  380. if (result != VK_SUCCESS) {
  381. SDL_free(physicalDevices);
  382. SDL_free(queueFamiliesProperties);
  383. SDL_free(deviceExtensions);
  384. return SDL_SetError("vkEnumerateDeviceExtensionProperties(): %s", getVulkanResultString(result));
  385. }
  386. if (deviceExtensionCount == 0) {
  387. continue;
  388. }
  389. if (deviceExtensionsAllocatedSize < deviceExtensionCount) {
  390. SDL_free(deviceExtensions);
  391. deviceExtensionsAllocatedSize = deviceExtensionCount;
  392. deviceExtensions = (VkExtensionProperties *)SDL_malloc(sizeof(VkExtensionProperties) * deviceExtensionsAllocatedSize);
  393. if (!deviceExtensions) {
  394. SDL_free(physicalDevices);
  395. SDL_free(queueFamiliesProperties);
  396. return -1;
  397. }
  398. }
  399. result = context->vkEnumerateDeviceExtensionProperties(physicalDevice, NULL, &deviceExtensionCount, deviceExtensions);
  400. if (result != VK_SUCCESS) {
  401. SDL_free(physicalDevices);
  402. SDL_free(queueFamiliesProperties);
  403. SDL_free(deviceExtensions);
  404. return SDL_SetError("vkEnumerateDeviceExtensionProperties(): %s", getVulkanResultString(result));
  405. }
  406. for (i = 0; i < deviceExtensionCount; i++) {
  407. if (SDL_strcmp(deviceExtensions[i].extensionName, VK_KHR_SWAPCHAIN_EXTENSION_NAME) == 0) {
  408. hasSwapchainExtension = true;
  409. break;
  410. }
  411. }
  412. if (!hasSwapchainExtension) {
  413. continue;
  414. }
  415. context->physicalDevice = physicalDevice;
  416. break;
  417. }
  418. SDL_free(physicalDevices);
  419. SDL_free(queueFamiliesProperties);
  420. SDL_free(deviceExtensions);
  421. if (!context->physicalDevice) {
  422. return SDL_SetError("Vulkan: no viable physical devices found");
  423. }
  424. return 0;
  425. }
  426. static void initDeviceFeatures(VulkanDeviceFeatures *features)
  427. {
  428. features->device_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  429. features->device_features.pNext = &features->device_features_1_1;
  430. features->device_features_1_1.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  431. features->device_features_1_1.pNext = &features->device_features_1_2;
  432. features->device_features_1_2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  433. features->device_features_1_2.pNext = &features->device_features_1_3;
  434. features->device_features_1_3.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES;
  435. features->device_features_1_3.pNext = &features->desc_buf_features;
  436. features->desc_buf_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_BUFFER_FEATURES_EXT;
  437. features->desc_buf_features.pNext = &features->atomic_float_features;
  438. features->atomic_float_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_FLOAT_FEATURES_EXT;
  439. features->atomic_float_features.pNext = &features->coop_matrix_features;
  440. features->coop_matrix_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  441. features->coop_matrix_features.pNext = NULL;
  442. }
  443. static void copyDeviceFeatures(VulkanDeviceFeatures *supported_features, VulkanDeviceFeatures *requested_features)
  444. {
  445. #define COPY_OPTIONAL_FEATURE(X) requested_features->X = supported_features->X
  446. COPY_OPTIONAL_FEATURE(device_features.features.shaderImageGatherExtended);
  447. COPY_OPTIONAL_FEATURE(device_features.features.shaderStorageImageReadWithoutFormat);
  448. COPY_OPTIONAL_FEATURE(device_features.features.shaderStorageImageWriteWithoutFormat);
  449. COPY_OPTIONAL_FEATURE(device_features.features.fragmentStoresAndAtomics);
  450. COPY_OPTIONAL_FEATURE(device_features.features.vertexPipelineStoresAndAtomics);
  451. COPY_OPTIONAL_FEATURE(device_features.features.shaderInt64);
  452. COPY_OPTIONAL_FEATURE(device_features.features.shaderInt16);
  453. COPY_OPTIONAL_FEATURE(device_features.features.shaderFloat64);
  454. COPY_OPTIONAL_FEATURE(device_features_1_1.samplerYcbcrConversion);
  455. COPY_OPTIONAL_FEATURE(device_features_1_1.storagePushConstant16);
  456. COPY_OPTIONAL_FEATURE(device_features_1_2.bufferDeviceAddress);
  457. COPY_OPTIONAL_FEATURE(device_features_1_2.hostQueryReset);
  458. COPY_OPTIONAL_FEATURE(device_features_1_2.storagePushConstant8);
  459. COPY_OPTIONAL_FEATURE(device_features_1_2.shaderInt8);
  460. COPY_OPTIONAL_FEATURE(device_features_1_2.storageBuffer8BitAccess);
  461. COPY_OPTIONAL_FEATURE(device_features_1_2.uniformAndStorageBuffer8BitAccess);
  462. COPY_OPTIONAL_FEATURE(device_features_1_2.shaderFloat16);
  463. COPY_OPTIONAL_FEATURE(device_features_1_2.shaderSharedInt64Atomics);
  464. COPY_OPTIONAL_FEATURE(device_features_1_2.vulkanMemoryModel);
  465. COPY_OPTIONAL_FEATURE(device_features_1_2.vulkanMemoryModelDeviceScope);
  466. COPY_OPTIONAL_FEATURE(device_features_1_2.hostQueryReset);
  467. COPY_OPTIONAL_FEATURE(device_features_1_3.dynamicRendering);
  468. COPY_OPTIONAL_FEATURE(device_features_1_3.maintenance4);
  469. COPY_OPTIONAL_FEATURE(device_features_1_3.synchronization2);
  470. COPY_OPTIONAL_FEATURE(device_features_1_3.computeFullSubgroups);
  471. COPY_OPTIONAL_FEATURE(device_features_1_3.shaderZeroInitializeWorkgroupMemory);
  472. COPY_OPTIONAL_FEATURE(desc_buf_features.descriptorBuffer);
  473. COPY_OPTIONAL_FEATURE(desc_buf_features.descriptorBufferPushDescriptors);
  474. COPY_OPTIONAL_FEATURE(atomic_float_features.shaderBufferFloat32Atomics);
  475. COPY_OPTIONAL_FEATURE(atomic_float_features.shaderBufferFloat32AtomicAdd);
  476. COPY_OPTIONAL_FEATURE(coop_matrix_features.cooperativeMatrix);
  477. #undef COPY_OPTIONAL_FEATURE
  478. // timeline semaphores is required by ffmpeg
  479. requested_features->device_features_1_2.timelineSemaphore = 1;
  480. }
  481. static int addQueueFamily(VkDeviceQueueCreateInfo **pQueueCreateInfos, uint32_t *pQueueCreateInfoCount, uint32_t queueFamilyIndex, uint32_t queueCount)
  482. {
  483. VkDeviceQueueCreateInfo *queueCreateInfo;
  484. VkDeviceQueueCreateInfo *queueCreateInfos = *pQueueCreateInfos;
  485. uint32_t queueCreateInfoCount = *pQueueCreateInfoCount;
  486. float *queuePriorities;
  487. if (queueCount == 0) {
  488. return 0;
  489. }
  490. for (uint32_t i = 0; i < queueCreateInfoCount; ++i) {
  491. if (queueCreateInfos[i].queueFamilyIndex == queueFamilyIndex) {
  492. return 0;
  493. }
  494. }
  495. queueCreateInfos = (VkDeviceQueueCreateInfo *)SDL_realloc(queueCreateInfos, (queueCreateInfoCount + 1) * sizeof(*queueCreateInfos));
  496. if (!queueCreateInfos) {
  497. return -1;
  498. }
  499. queuePriorities = (float *)SDL_malloc(queueCount * sizeof(*queuePriorities));
  500. if (!queuePriorities) {
  501. return -1;
  502. }
  503. for (uint32_t i = 0; i < queueCount; ++i) {
  504. queuePriorities[i] = 1.0f / queueCount;
  505. }
  506. queueCreateInfo = &queueCreateInfos[queueCreateInfoCount++];
  507. SDL_zerop(queueCreateInfo);
  508. queueCreateInfo->sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
  509. queueCreateInfo->queueFamilyIndex = queueFamilyIndex;
  510. queueCreateInfo->queueCount = queueCount;
  511. queueCreateInfo->pQueuePriorities = queuePriorities;
  512. *pQueueCreateInfos = queueCreateInfos;
  513. *pQueueCreateInfoCount = queueCreateInfoCount;
  514. return 0;
  515. }
  516. static int createDevice(VulkanVideoContext *context)
  517. {
  518. static const char *const deviceExtensionNames[] = {
  519. VK_KHR_SWAPCHAIN_EXTENSION_NAME,
  520. VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME,
  521. VK_KHR_MAINTENANCE1_EXTENSION_NAME,
  522. VK_KHR_BIND_MEMORY_2_EXTENSION_NAME,
  523. VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME,
  524. };
  525. static const char *optional_extensions[] = {
  526. VK_KHR_VIDEO_QUEUE_EXTENSION_NAME,
  527. VK_KHR_VIDEO_DECODE_QUEUE_EXTENSION_NAME,
  528. VK_KHR_VIDEO_DECODE_H264_EXTENSION_NAME,
  529. VK_KHR_VIDEO_DECODE_H265_EXTENSION_NAME,
  530. VK_KHR_VIDEO_DECODE_AV1_EXTENSION_NAME,
  531. VK_KHR_VIDEO_MAINTENANCE_1_EXTENSION_NAME
  532. };
  533. VkDeviceCreateInfo deviceCreateInfo;
  534. VkDeviceQueueCreateInfo *queueCreateInfos = NULL;
  535. uint32_t queueCreateInfoCount = 0;
  536. VulkanDeviceFeatures supported_features;
  537. const char **deviceExtensionsCopy = NULL;
  538. VkResult result = VK_ERROR_UNKNOWN;
  539. if (addQueueFamily(&queueCreateInfos, &queueCreateInfoCount, context->presentQueueFamilyIndex, context->presentQueueCount) < 0 ||
  540. addQueueFamily(&queueCreateInfos, &queueCreateInfoCount, context->graphicsQueueFamilyIndex, context->graphicsQueueCount) < 0 ||
  541. addQueueFamily(&queueCreateInfos, &queueCreateInfoCount, context->transferQueueFamilyIndex, context->transferQueueCount) < 0 ||
  542. addQueueFamily(&queueCreateInfos, &queueCreateInfoCount, context->computeQueueFamilyIndex, context->computeQueueCount) < 0 ||
  543. addQueueFamily(&queueCreateInfos, &queueCreateInfoCount, context->decodeQueueFamilyIndex, context->decodeQueueCount) < 0) {
  544. goto done;
  545. }
  546. initDeviceFeatures(&supported_features);
  547. initDeviceFeatures(&context->features);
  548. context->vkGetPhysicalDeviceFeatures2(context->physicalDevice, &supported_features.device_features);
  549. copyDeviceFeatures(&supported_features, &context->features);
  550. SDL_zero(deviceCreateInfo);
  551. deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
  552. deviceCreateInfo.queueCreateInfoCount = queueCreateInfoCount;
  553. deviceCreateInfo.pQueueCreateInfos = queueCreateInfos;
  554. deviceCreateInfo.pEnabledFeatures = NULL;
  555. deviceCreateInfo.enabledExtensionCount = SDL_arraysize(deviceExtensionNames);
  556. deviceCreateInfo.pNext = &context->features.device_features;
  557. deviceExtensionsCopy = (const char **)SDL_calloc(deviceCreateInfo.enabledExtensionCount + SDL_arraysize(optional_extensions), sizeof(const char *));
  558. for (uint32_t i = 0; i < deviceCreateInfo.enabledExtensionCount; i++) {
  559. deviceExtensionsCopy[i] = deviceExtensionNames[i];
  560. }
  561. // Get the rest of the optional extensions
  562. {
  563. uint32_t extensionCount;
  564. if (context->vkEnumerateDeviceExtensionProperties(context->physicalDevice, NULL, &extensionCount, NULL) == VK_SUCCESS && extensionCount > 0) {
  565. VkExtensionProperties *extensionProperties = (VkExtensionProperties *)SDL_calloc(extensionCount, sizeof(VkExtensionProperties));
  566. if (context->vkEnumerateDeviceExtensionProperties(context->physicalDevice, NULL, &extensionCount, extensionProperties) == VK_SUCCESS) {
  567. for (uint32_t i = 0; i < SDL_arraysize(optional_extensions); ++i) {
  568. for (uint32_t j = 0; j < extensionCount; ++j) {
  569. if (SDL_strcmp(extensionProperties[j].extensionName, optional_extensions[i]) == 0) {
  570. deviceExtensionsCopy[deviceCreateInfo.enabledExtensionCount++] = optional_extensions[i];
  571. break;
  572. }
  573. }
  574. }
  575. }
  576. SDL_free(extensionProperties);
  577. }
  578. }
  579. deviceCreateInfo.ppEnabledExtensionNames = deviceExtensionsCopy;
  580. context->deviceExtensions = deviceExtensionsCopy;
  581. context->deviceExtensionsCount = deviceCreateInfo.enabledExtensionCount;
  582. result = context->vkCreateDevice(context->physicalDevice, &deviceCreateInfo, NULL, &context->device);
  583. if (result != VK_SUCCESS) {
  584. SDL_SetError("vkCreateDevice(): %s", getVulkanResultString(result));
  585. goto done;
  586. }
  587. if (loadDeviceFunctions(context) < 0) {
  588. result = VK_ERROR_UNKNOWN;
  589. context->device = VK_NULL_HANDLE;
  590. goto done;
  591. }
  592. // Get the graphics queue that SDL will use
  593. context->vkGetDeviceQueue(context->device, context->graphicsQueueFamilyIndex, 0, &context->graphicsQueue);
  594. // Create a command pool
  595. VkCommandPoolCreateInfo commandPoolCreateInfo;
  596. SDL_zero(commandPoolCreateInfo);
  597. commandPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  598. commandPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
  599. commandPoolCreateInfo.queueFamilyIndex = context->graphicsQueueFamilyIndex;
  600. result = context->vkCreateCommandPool(context->device, &commandPoolCreateInfo, NULL, &context->commandPool);
  601. if (result != VK_SUCCESS) {
  602. SDL_SetError("vkCreateCommandPool(): %s", getVulkanResultString(result));
  603. goto done;
  604. }
  605. done:
  606. for (uint32_t i = 0; i < queueCreateInfoCount; ++i) {
  607. SDL_free((void *)queueCreateInfos[i].pQueuePriorities);
  608. }
  609. SDL_free(queueCreateInfos);
  610. if (result != VK_SUCCESS) {
  611. return -1;
  612. }
  613. return 0;
  614. }
  615. VulkanVideoContext *CreateVulkanVideoContext(SDL_Window *window)
  616. {
  617. VulkanVideoContext *context = (VulkanVideoContext *)SDL_calloc(1, sizeof(*context));
  618. if (!context) {
  619. return NULL;
  620. }
  621. if (loadGlobalFunctions(context) < 0 ||
  622. createInstance(context) < 0 ||
  623. createSurface(context, window) < 0 ||
  624. findPhysicalDevice(context) < 0 ||
  625. createDevice(context) < 0) {
  626. DestroyVulkanVideoContext(context);
  627. return NULL;
  628. }
  629. return context;
  630. }
  631. void SetupVulkanRenderProperties(VulkanVideoContext *context, SDL_PropertiesID props)
  632. {
  633. SDL_SetPointerProperty(props, SDL_PROP_RENDERER_CREATE_VULKAN_INSTANCE_POINTER, context->instance);
  634. SDL_SetNumberProperty(props, SDL_PROP_RENDERER_CREATE_VULKAN_SURFACE_NUMBER, (Sint64)context->surface);
  635. SDL_SetPointerProperty(props, SDL_PROP_RENDERER_CREATE_VULKAN_PHYSICAL_DEVICE_POINTER, context->physicalDevice);
  636. SDL_SetPointerProperty(props, SDL_PROP_RENDERER_CREATE_VULKAN_DEVICE_POINTER, context->device);
  637. SDL_SetNumberProperty(props, SDL_PROP_RENDERER_CREATE_VULKAN_PRESENT_QUEUE_FAMILY_INDEX_NUMBER, context->presentQueueFamilyIndex);
  638. SDL_SetNumberProperty(props, SDL_PROP_RENDERER_CREATE_VULKAN_GRAPHICS_QUEUE_FAMILY_INDEX_NUMBER, context->graphicsQueueFamilyIndex);
  639. }
  640. #if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(59, 34, 100)
  641. static void AddQueueFamily(AVVulkanDeviceContext *ctx, int idx, int num, VkQueueFlagBits flags)
  642. {
  643. AVVulkanDeviceQueueFamily *entry = &ctx->qf[ctx->nb_qf++];
  644. entry->idx = idx;
  645. entry->num = num;
  646. entry->flags = flags;
  647. }
  648. #endif /* LIBAVUTIL_VERSION_INT */
  649. void SetupVulkanDeviceContextData(VulkanVideoContext *context, AVVulkanDeviceContext *ctx)
  650. {
  651. ctx->get_proc_addr = context->vkGetInstanceProcAddr;
  652. ctx->inst = context->instance;
  653. ctx->phys_dev = context->physicalDevice;
  654. ctx->act_dev = context->device;
  655. ctx->device_features = context->features.device_features;
  656. ctx->enabled_inst_extensions = context->instanceExtensions;
  657. ctx->nb_enabled_inst_extensions = context->instanceExtensionsCount;
  658. ctx->enabled_dev_extensions = context->deviceExtensions;
  659. ctx->nb_enabled_dev_extensions = context->deviceExtensionsCount;
  660. #if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(59, 34, 100)
  661. AddQueueFamily(ctx, context->graphicsQueueFamilyIndex, context->graphicsQueueCount, VK_QUEUE_GRAPHICS_BIT);
  662. AddQueueFamily(ctx, context->transferQueueFamilyIndex, context->transferQueueCount, VK_QUEUE_TRANSFER_BIT);
  663. AddQueueFamily(ctx, context->computeQueueFamilyIndex, context->computeQueueCount, VK_QUEUE_COMPUTE_BIT);
  664. AddQueueFamily(ctx, context->decodeQueueFamilyIndex, context->decodeQueueCount, VK_QUEUE_VIDEO_DECODE_BIT_KHR);
  665. #else
  666. ctx->queue_family_index = context->graphicsQueueFamilyIndex;
  667. ctx->nb_graphics_queues = context->graphicsQueueCount;
  668. ctx->queue_family_tx_index = context->transferQueueFamilyIndex;
  669. ctx->nb_tx_queues = context->transferQueueCount;
  670. ctx->queue_family_comp_index = context->computeQueueFamilyIndex;
  671. ctx->nb_comp_queues = context->computeQueueCount;
  672. ctx->queue_family_encode_index = -1;
  673. ctx->nb_encode_queues = 0;
  674. ctx->queue_family_decode_index = context->decodeQueueFamilyIndex;
  675. ctx->nb_decode_queues = context->decodeQueueCount;
  676. #endif /* LIBAVUTIL_VERSION_INT */
  677. }
  678. static int CreateCommandBuffers(VulkanVideoContext *context, SDL_Renderer *renderer)
  679. {
  680. uint32_t commandBufferCount = (uint32_t)SDL_GetNumberProperty(SDL_GetRendererProperties(renderer), SDL_PROP_RENDERER_VULKAN_SWAPCHAIN_IMAGE_COUNT_NUMBER, 1);
  681. if (commandBufferCount > context->commandBufferCount) {
  682. uint32_t needed = (commandBufferCount - context->commandBufferCount);
  683. VkCommandBuffer *commandBuffers = (VkCommandBuffer *)SDL_realloc(context->commandBuffers, commandBufferCount * sizeof(*commandBuffers));
  684. if (!commandBuffers) {
  685. return -1;
  686. }
  687. context->commandBuffers = commandBuffers;
  688. VkCommandBufferAllocateInfo commandBufferAllocateInfo;
  689. SDL_zero(commandBufferAllocateInfo);
  690. commandBufferAllocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  691. commandBufferAllocateInfo.commandPool = context->commandPool;
  692. commandBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  693. commandBufferAllocateInfo.commandBufferCount = needed;
  694. VkResult result = context->vkAllocateCommandBuffers(context->device, &commandBufferAllocateInfo, &context->commandBuffers[context->commandBufferCount]);
  695. if (result != VK_SUCCESS) {
  696. SDL_SetError("vkAllocateCommandBuffers(): %s", getVulkanResultString(result));
  697. return -1;
  698. }
  699. context->commandBufferCount = commandBufferCount;
  700. }
  701. return 0;
  702. }
  703. int BeginVulkanFrameRendering(VulkanVideoContext *context, AVFrame *frame, SDL_Renderer *renderer)
  704. {
  705. AVHWFramesContext *frames = (AVHWFramesContext *)(frame->hw_frames_ctx->data);
  706. AVVulkanFramesContext *vk = (AVVulkanFramesContext *)(frames->hwctx);
  707. AVVkFrame *pVkFrame = (AVVkFrame *)frame->data[0];
  708. if (CreateCommandBuffers(context, renderer) < 0) {
  709. return -1;
  710. }
  711. vk->lock_frame(frames, pVkFrame);
  712. VkTimelineSemaphoreSubmitInfo timeline;
  713. SDL_zero(timeline);
  714. timeline.sType = VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO;
  715. timeline.waitSemaphoreValueCount = 1;
  716. timeline.pWaitSemaphoreValues = pVkFrame->sem_value;
  717. VkPipelineStageFlags pipelineStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  718. VkSubmitInfo submitInfo;
  719. SDL_zero(submitInfo);
  720. submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  721. submitInfo.waitSemaphoreCount = 1;
  722. submitInfo.pWaitSemaphores = pVkFrame->sem;
  723. submitInfo.pWaitDstStageMask = &pipelineStageMask;
  724. submitInfo.pNext = &timeline;
  725. if (pVkFrame->layout[0] != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
  726. VkCommandBuffer commandBuffer = context->commandBuffers[context->commandBufferIndex];
  727. VkCommandBufferBeginInfo beginInfo;
  728. SDL_zero(beginInfo);
  729. beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  730. beginInfo.flags = 0;
  731. context->vkBeginCommandBuffer(commandBuffer, &beginInfo);
  732. VkImageMemoryBarrier2 barrier;
  733. SDL_zero(barrier);
  734. barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2;
  735. barrier.srcAccessMask = VK_ACCESS_2_NONE;
  736. barrier.dstAccessMask = VK_ACCESS_2_SHADER_SAMPLED_READ_BIT;
  737. barrier.oldLayout = pVkFrame->layout[0];
  738. barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  739. barrier.image = pVkFrame->img[0];
  740. barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  741. barrier.subresourceRange.levelCount = 1;
  742. barrier.subresourceRange.layerCount = 1;
  743. barrier.srcQueueFamilyIndex = pVkFrame->queue_family[0];
  744. barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  745. barrier.srcStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  746. barrier.dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  747. VkDependencyInfo dep;
  748. SDL_zero(dep);
  749. dep.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO;
  750. dep.dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
  751. dep.imageMemoryBarrierCount = 1;
  752. dep.pImageMemoryBarriers = &barrier;
  753. context->vkCmdPipelineBarrier2(commandBuffer, &dep);
  754. context->vkEndCommandBuffer(commandBuffer);
  755. // Add the image barrier to the submit info
  756. submitInfo.commandBufferCount = 1;
  757. submitInfo.pCommandBuffers = &context->commandBuffers[context->commandBufferIndex];
  758. pVkFrame->layout[0] = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  759. pVkFrame->queue_family[0] = VK_QUEUE_FAMILY_IGNORED;
  760. }
  761. VkResult result = context->vkQueueSubmit(context->graphicsQueue, 1, &submitInfo, 0);
  762. if (result != VK_SUCCESS) {
  763. // Don't return an error here, we need to complete the frame operation
  764. SDL_LogError(SDL_LOG_CATEGORY_APPLICATION , "vkQueueSubmit(): %s", getVulkanResultString(result));
  765. }
  766. return 0;
  767. }
  768. int FinishVulkanFrameRendering(VulkanVideoContext *context, AVFrame *frame, SDL_Renderer *renderer)
  769. {
  770. AVHWFramesContext *frames = (AVHWFramesContext *)(frame->hw_frames_ctx->data);
  771. AVVulkanFramesContext *vk = (AVVulkanFramesContext *)(frames->hwctx);
  772. AVVkFrame *pVkFrame = (AVVkFrame *)frame->data[0];
  773. // Transition the frame back to ffmpeg
  774. ++pVkFrame->sem_value[0];
  775. VkTimelineSemaphoreSubmitInfo timeline;
  776. SDL_zero(timeline);
  777. timeline.sType = VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO;
  778. timeline.signalSemaphoreValueCount = 1;
  779. timeline.pSignalSemaphoreValues = pVkFrame->sem_value;
  780. VkSubmitInfo submitInfo;
  781. SDL_zero(submitInfo);
  782. submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  783. submitInfo.signalSemaphoreCount = 1;
  784. submitInfo.pSignalSemaphores = pVkFrame->sem;
  785. submitInfo.pNext = &timeline;
  786. VkResult result = context->vkQueueSubmit(context->graphicsQueue, 1, &submitInfo, 0);
  787. if (result != VK_SUCCESS) {
  788. // Don't return an error here, we need to complete the frame operation
  789. SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "vkQueueSubmit(): %s", getVulkanResultString(result));
  790. }
  791. vk->unlock_frame(frames, pVkFrame);
  792. context->commandBufferIndex = (context->commandBufferIndex + 1) % context->commandBufferCount;
  793. return 0;
  794. }
  795. static SDL_Texture *CreateVulkanVideoTexturePixFmtVulkan(VulkanVideoContext *context, AVFrame *frame, SDL_Renderer *renderer, SDL_PropertiesID props)
  796. {
  797. AVHWFramesContext *frames = (AVHWFramesContext *)(frame->hw_frames_ctx->data);
  798. AVVulkanFramesContext *vk = (AVVulkanFramesContext *)(frames->hwctx);
  799. AVVkFrame *pVkFrame = (AVVkFrame *)frame->data[0];
  800. Uint32 format;
  801. switch (vk->format[0]) {
  802. case VK_FORMAT_G8B8G8R8_422_UNORM:
  803. format = SDL_PIXELFORMAT_YUY2;
  804. break;
  805. case VK_FORMAT_B8G8R8G8_422_UNORM:
  806. format = SDL_PIXELFORMAT_UYVY;
  807. break;
  808. case VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM:
  809. format = SDL_PIXELFORMAT_IYUV;
  810. break;
  811. case VK_FORMAT_G8_B8R8_2PLANE_420_UNORM:
  812. format = SDL_PIXELFORMAT_NV12;
  813. break;
  814. case VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16:
  815. format = SDL_PIXELFORMAT_P010;
  816. break;
  817. default:
  818. format = SDL_PIXELFORMAT_UNKNOWN;
  819. break;
  820. }
  821. SDL_SetNumberProperty(props, SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER, format);
  822. SDL_SetNumberProperty(props, SDL_PROP_TEXTURE_CREATE_VULKAN_TEXTURE_NUMBER, (Sint64)pVkFrame->img[0]);
  823. return SDL_CreateTextureWithProperties(renderer, props);
  824. }
  825. #ifdef FFMPEG_DRMPRIME_SUPPORT
  826. static bool FindMemoryIndex(VulkanVideoContext *context, uint32_t memoryTypeBits, uint32_t *memoryIndex)
  827. {
  828. VkPhysicalDeviceMemoryProperties mem_properties;
  829. context->vkGetPhysicalDeviceMemoryProperties(context->physicalDevice, &mem_properties);
  830. for (uint32_t i = 0; i < mem_properties.memoryTypeCount; ++i) {
  831. if (memoryTypeBits & (1 << i)) {
  832. *memoryIndex = i;
  833. return true;
  834. }
  835. }
  836. return SDL_SetError("Couldn't find memory index for type %u", memoryTypeBits);
  837. }
  838. static void SDLCALL CleanupExternalVulkanImage(void *userdata, void *value)
  839. {
  840. VulkanVideoContext *context = (VulkanVideoContext *)userdata;
  841. VkImage image = (VkImage)(uintptr_t)value;
  842. context->vkDestroyImage(context->device, image, NULL);
  843. }
  844. static void SDLCALL CleanupExternalVulkanImageMemory(void *userdata, void *value)
  845. {
  846. VulkanVideoContext *context = (VulkanVideoContext *)userdata;
  847. VkDeviceMemory imageMemory = (VkDeviceMemory)(uintptr_t)value;
  848. context->vkFreeMemory(context->device, imageMemory, NULL);
  849. }
  850. #endif /* FFMPEG_DRMPRIME_SUPPORT */
  851. static SDL_Texture *CreateVulkanVideoTexturePixFmtDRMPrime(VulkanVideoContext *context, AVFrame *frame, SDL_Renderer *renderer, SDL_PropertiesID props)
  852. {
  853. #ifdef FFMPEG_DRMPRIME_SUPPORT
  854. const AVDRMFrameDescriptor *drm_desc = (const AVDRMFrameDescriptor *)frame->data[0];
  855. VkFormat format = VK_FORMAT_UNDEFINED;
  856. VkResult result;
  857. VkImage image = 0;
  858. VkDeviceMemory imageMemory = 0;
  859. uint32_t memoryTypeIndex = 0;
  860. SDL_Texture *texture;
  861. if (drm_desc->nb_objects != 1) {
  862. SDL_SetError("DRM frames with %d objects are not currently supported", drm_desc->nb_objects);
  863. return NULL;
  864. }
  865. switch (drm_desc->layers[0].format) {
  866. case DRM_FORMAT_R8:
  867. if (drm_desc->nb_layers == 2) {
  868. switch (drm_desc->layers[1].format) {
  869. case DRM_FORMAT_GR88:
  870. format = VK_FORMAT_G8_B8R8_2PLANE_420_UNORM;
  871. SDL_SetNumberProperty(props, SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER, SDL_PIXELFORMAT_NV12);
  872. break;
  873. case DRM_FORMAT_RG88:
  874. format = VK_FORMAT_G8_B8R8_2PLANE_420_UNORM;
  875. SDL_SetNumberProperty(props, SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER, SDL_PIXELFORMAT_NV21);
  876. break;
  877. default:
  878. break;
  879. }
  880. }
  881. break;
  882. case DRM_FORMAT_R16:
  883. if (drm_desc->nb_layers == 2) {
  884. switch (drm_desc->layers[1].format) {
  885. case DRM_FORMAT_GR1616:
  886. format = VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16;
  887. SDL_SetNumberProperty(props, SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER, SDL_PIXELFORMAT_P010);
  888. break;
  889. default:
  890. break;
  891. }
  892. }
  893. break;
  894. case DRM_FORMAT_NV12:
  895. format = VK_FORMAT_G8_B8R8_2PLANE_420_UNORM;
  896. SDL_SetNumberProperty(props, SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER, SDL_PIXELFORMAT_NV12);
  897. break;
  898. case DRM_FORMAT_P010:
  899. format = VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16;
  900. SDL_SetNumberProperty(props, SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER, SDL_PIXELFORMAT_P010);
  901. break;
  902. case DRM_FORMAT_YUYV:
  903. format = VK_FORMAT_G8B8G8R8_422_UNORM;
  904. SDL_SetNumberProperty(props, SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER, SDL_PIXELFORMAT_YUY2);
  905. break;
  906. case DRM_FORMAT_UYVY:
  907. format = VK_FORMAT_B8G8R8G8_422_UNORM;
  908. SDL_SetNumberProperty(props, SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER, SDL_PIXELFORMAT_UYVY);
  909. break;
  910. case DRM_FORMAT_ARGB8888:
  911. format = VK_FORMAT_B8G8R8A8_UNORM;
  912. SDL_SetNumberProperty(props, SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER, SDL_PIXELFORMAT_BGRA32);
  913. break;
  914. default:
  915. break;
  916. }
  917. if (format == VK_FORMAT_UNDEFINED) {
  918. SDL_SetError("Unsupported DRM format %d", drm_desc->layers[0].format);
  919. return NULL;
  920. }
  921. int dma_buf_fds[AV_DRM_MAX_PLANES];
  922. for (int i = 0; i < drm_desc->nb_objects; i++) {
  923. dma_buf_fds[i] = dup(drm_desc->objects[i].fd);
  924. if (dma_buf_fds[i] < 0) {
  925. while (--i >= 0) {
  926. close(dma_buf_fds[i]);
  927. }
  928. SDL_SetError("Couldn't duplicate file descriptor");
  929. return NULL;
  930. }
  931. }
  932. uint32_t planes = 0;
  933. VkSubresourceLayout plane_layouts[AV_DRM_MAX_PLANES];
  934. SDL_zeroa(plane_layouts);
  935. for (int i = 0; i < drm_desc->nb_layers; ++i) {
  936. for (int j = 0; j < drm_desc->layers[i].nb_planes; ++j) {
  937. const AVDRMPlaneDescriptor *plane = &drm_desc->layers[i].planes[j];
  938. plane_layouts[planes].offset = plane->offset;
  939. plane_layouts[planes].rowPitch = plane->pitch;
  940. ++planes;
  941. }
  942. }
  943. VkImageDrmFormatModifierExplicitCreateInfoEXT modifier_info;
  944. SDL_zero(modifier_info);
  945. modifier_info.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT;
  946. modifier_info.drmFormatModifier = drm_desc->objects[0].format_modifier;
  947. modifier_info.drmFormatModifierPlaneCount = planes;
  948. modifier_info.pPlaneLayouts = plane_layouts;
  949. VkExternalMemoryImageCreateInfo external_info;
  950. SDL_zero(external_info);
  951. external_info.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO;
  952. external_info.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
  953. external_info.pNext = &modifier_info;
  954. VkImageCreateInfo image_info;
  955. SDL_zero(image_info);
  956. image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
  957. image_info.imageType = VK_IMAGE_TYPE_2D;
  958. image_info.format = format;
  959. image_info.extent.width = frame->width;
  960. image_info.extent.height = frame->height;
  961. image_info.extent.depth = 1;
  962. image_info.mipLevels = 1;
  963. image_info.arrayLayers = 1;
  964. image_info.samples = VK_SAMPLE_COUNT_1_BIT;
  965. image_info.tiling = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT;
  966. image_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT;
  967. image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  968. image_info.pNext = &external_info;
  969. result = context->vkCreateImage(context->device, &image_info, NULL, &image);
  970. if (result != VK_SUCCESS) {
  971. SDL_SetError("vkCreateImage(): %s", getVulkanResultString(result));
  972. goto error;
  973. }
  974. SDL_SetNumberProperty(props, SDL_PROP_TEXTURE_CREATE_VULKAN_TEXTURE_NUMBER, (Sint64)image);
  975. // Calculate total memory size from plane requirements
  976. VkMemoryRequirements mem_reqs;
  977. context->vkGetImageMemoryRequirements(context->device, image, &mem_reqs);
  978. VkImportMemoryFdInfoKHR import_fd_info;
  979. SDL_zero(import_fd_info);
  980. import_fd_info.sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR;
  981. import_fd_info.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
  982. import_fd_info.fd = dma_buf_fds[0];
  983. if (!FindMemoryIndex(context, mem_reqs.memoryTypeBits, &memoryTypeIndex)) {
  984. goto error;
  985. }
  986. VkMemoryAllocateInfo alloc_info;
  987. SDL_zero(alloc_info);
  988. alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
  989. alloc_info.allocationSize = mem_reqs.size;
  990. alloc_info.memoryTypeIndex = memoryTypeIndex;
  991. alloc_info.pNext = &import_fd_info;
  992. result = context->vkAllocateMemory(context->device, &alloc_info, NULL, &imageMemory);
  993. if (result != VK_SUCCESS) {
  994. SDL_SetError("vkAllocateMemory(): %s", getVulkanResultString(result));
  995. goto error;
  996. }
  997. result = context->vkBindImageMemory(context->device, image, imageMemory, 0);
  998. if (result != VK_SUCCESS) {
  999. SDL_SetError("vkBindImageMemory(): %s", getVulkanResultString(result));
  1000. goto error;
  1001. }
  1002. texture = SDL_CreateTextureWithProperties(renderer, props);
  1003. if (!texture) {
  1004. goto error;
  1005. }
  1006. // Make sure this image is freed when the texture is destroyed
  1007. props = SDL_GetTextureProperties(texture);
  1008. SDL_SetPointerPropertyWithCleanup(props, "CleanupVulkanImage", (void *)(uintptr_t)image, CleanupExternalVulkanImage, context);
  1009. SDL_SetPointerPropertyWithCleanup(props, "CleanupVulkanImageMemory", (void *)(uintptr_t)imageMemory, CleanupExternalVulkanImageMemory, context);
  1010. return texture;
  1011. error:
  1012. if (image) {
  1013. context->vkDestroyImage(context->device, image, NULL);
  1014. }
  1015. if (imageMemory) {
  1016. context->vkFreeMemory(context->device, imageMemory, NULL);
  1017. } else {
  1018. for (int i = 0; i < drm_desc->nb_objects; i++) {
  1019. close(dma_buf_fds[i]);
  1020. }
  1021. }
  1022. return NULL;
  1023. #else
  1024. SDL_SetError("DRM prime frames not supported");
  1025. return NULL;
  1026. #endif /* FFMPEG_DRMPRIME_SUPPORT */
  1027. }
  1028. SDL_Texture *CreateVulkanVideoTexture(VulkanVideoContext *context, AVFrame *frame, SDL_Renderer *renderer, SDL_PropertiesID props)
  1029. {
  1030. if (frame->format == AV_PIX_FMT_VULKAN) {
  1031. return CreateVulkanVideoTexturePixFmtVulkan(context, frame, renderer, props);
  1032. } else if (frame->format == AV_PIX_FMT_DRM_PRIME) {
  1033. return CreateVulkanVideoTexturePixFmtDRMPrime(context, frame, renderer, props);
  1034. } else {
  1035. SDL_SetError("Unknown hardware frame format");
  1036. return NULL;
  1037. }
  1038. }
  1039. void DestroyVulkanVideoContext(VulkanVideoContext *context)
  1040. {
  1041. if (context) {
  1042. if (context->device) {
  1043. context->vkDeviceWaitIdle(context->device);
  1044. }
  1045. SDL_free(context->instanceExtensions);
  1046. SDL_free(context->deviceExtensions);
  1047. if (context->commandBuffers) {
  1048. context->vkFreeCommandBuffers(context->device, context->commandPool, context->commandBufferCount, context->commandBuffers);
  1049. SDL_free(context->commandBuffers);
  1050. context->commandBuffers = NULL;
  1051. }
  1052. if (context->commandPool) {
  1053. context->vkDestroyCommandPool(context->device, context->commandPool, NULL);
  1054. context->commandPool = VK_NULL_HANDLE;
  1055. }
  1056. if (context->device) {
  1057. context->vkDestroyDevice(context->device, NULL);
  1058. }
  1059. if (context->surface) {
  1060. context->vkDestroySurfaceKHR(context->instance, context->surface, NULL);
  1061. }
  1062. if (context->instance) {
  1063. context->vkDestroyInstance(context->instance, NULL);
  1064. }
  1065. SDL_free(context);
  1066. }
  1067. }
  1068. #else
  1069. VulkanVideoContext *CreateVulkanVideoContext(SDL_Window *window)
  1070. {
  1071. SDL_SetError("testffmpeg not built with Vulkan support");
  1072. return NULL;
  1073. }
  1074. void SetupVulkanRenderProperties(VulkanVideoContext *context, SDL_PropertiesID props)
  1075. {
  1076. }
  1077. void SetupVulkanDeviceContextData(VulkanVideoContext *context, AVVulkanDeviceContext *ctx)
  1078. {
  1079. }
  1080. SDL_Texture *CreateVulkanVideoTexture(VulkanVideoContext *context, AVFrame *frame, SDL_Renderer *renderer, SDL_PropertiesID props)
  1081. {
  1082. return NULL;
  1083. }
  1084. int BeginVulkanFrameRendering(VulkanVideoContext *context, AVFrame *frame, SDL_Renderer *renderer)
  1085. {
  1086. return -1;
  1087. }
  1088. int FinishVulkanFrameRendering(VulkanVideoContext *context, AVFrame *frame, SDL_Renderer *renderer)
  1089. {
  1090. return -1;
  1091. }
  1092. void DestroyVulkanVideoContext(VulkanVideoContext *context)
  1093. {
  1094. }
  1095. #endif /* FFMPEG_VULKAN_SUPPORT */