QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
GstDmaBufVulkanImport.cc
Go to the documentation of this file.
2
3#if defined(QGC_HAS_GST_DMABUF_VULKAN_IMPORT)
4
5#include <algorithm>
6#include <atomic>
7#include <drm_fourcc.h>
8#include <fcntl.h>
9#include <limits>
10#include <private/qvideotexturehelper_p.h>
11#include <rhi/qrhi.h>
12#include <rhi/qrhi_platform.h>
13#include <unistd.h>
14#include <utility>
15
16#include <QtCore/QByteArray>
17#include <QtCore/QByteArrayList>
18#include <QtCore/QLoggingCategory>
19#include <QtCore/QMutex>
20#include <QtCore/QMutexLocker>
21#include <QtCore/QVersionNumber>
22#include <QtCore/QtEnvironmentVariables>
23#include <QtGui/QVulkanFunctions>
24#include <QtGui/QVulkanInstance>
25
26#include "GstHwPathTelemetry.h"
27#include "GstHwVideoBuffer.h"
28#include "QGCLoggingCategory.h"
29
30QGC_LOGGING_CATEGORY(GstDmaBufVulkanLog, "Video.GStreamer.HwBuffers.GstDmaBufVulkan")
31
32namespace {
33
35
36constexpr char kDeviceExtensionsVariable[] = "QT_VULKAN_DEVICE_EXTENSIONS";
37
38// VK_EXT_image_drm_format_modifier also needs VK_KHR_image_format_list, which is core in the Vulkan 1.2 the import
39// requires.
40constexpr const char* kRequiredDeviceExtensions[] = {
41 VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME,
42 VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME,
43 VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME,
44};
45
48struct PlaneFormat
49{
50 quint32 drmFourcc;
51 QRhiTexture::Format rhiFormat;
52 VkFormat vkFormat;
53};
54
55constexpr PlaneFormat kPlaneFormats[] = {
56 {DRM_FORMAT_R8, QRhiTexture::R8, VK_FORMAT_R8_UNORM},
57 {DRM_FORMAT_GR88, QRhiTexture::RG8, VK_FORMAT_R8G8_UNORM},
58 {DRM_FORMAT_R16, QRhiTexture::R16, VK_FORMAT_R16_UNORM},
59 {DRM_FORMAT_GR1616, QRhiTexture::RG16, VK_FORMAT_R16G16_UNORM},
60 {DRM_FORMAT_ABGR8888, QRhiTexture::RGBA8, VK_FORMAT_R8G8B8A8_UNORM},
61 {DRM_FORMAT_ARGB8888, QRhiTexture::BGRA8, VK_FORMAT_B8G8R8A8_UNORM},
62};
63constexpr std::size_t kPlaneFormatCount = std::size(kPlaneFormats);
64
66template <class Matches>
67std::size_t planeFormatIndex(Matches&& matches)
68{
69 return static_cast<std::size_t>(std::find_if(std::begin(kPlaneFormats), std::end(kPlaneFormats), matches) -
70 std::begin(kPlaneFormats));
71}
72
73constexpr quint64 explicitModifier(quint64 modifier) noexcept
74{
75 return (modifier == DRM_FORMAT_MOD_INVALID) ? DRM_FORMAT_MOD_LINEAR : modifier;
76}
77
79struct ImportDevice
80{
81 const QRhi* rhi = nullptr;
82 VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
84 std::array<std::vector<quint64>, kPlaneFormatCount> modifiers;
85
86 bool imports() const
87 {
88 return std::any_of(modifiers.begin(), modifiers.end(), [](const auto& list) { return !list.empty(); });
89 }
90
91 bool imports(std::size_t planeFormat, quint64 modifier) const
92 {
93 const auto& list = modifiers[planeFormat];
94 return std::find(list.begin(), list.end(), modifier) != list.end();
95 }
96};
97
98QMutex s_deviceMutex;
99ImportDevice s_device;
100// s_device.physicalDevice while that device imports: the streaming threads' check, without the lock.
101std::atomic<void*> s_importDevice{nullptr};
102const char s_deviceCleanupKey = 0;
103
105std::atomic<bool> s_loggedImportFailed{false};
106
110bool deviceExtensionsEnabled(QVulkanFunctions& functions, VkPhysicalDevice physicalDevice, QByteArray& missing)
111{
112 uint32_t count = 0;
113 functions.vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &count, nullptr);
114 std::vector<VkExtensionProperties> supported(count);
115 if (functions.vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &count, supported.data()) !=
116 VK_SUCCESS) {
117 count = 0;
118 }
119 supported.resize(count);
120 const QByteArrayList requested = qgetenv(kDeviceExtensionsVariable).split(';');
121 for (const char* const extension : kRequiredDeviceExtensions) {
122 const bool deviceHasIt = std::any_of(supported.begin(), supported.end(), [extension](const auto& candidate) {
123 return qstrcmp(candidate.extensionName, extension) == 0;
124 });
125 if (!deviceHasIt || !requested.contains(extension)) {
126 missing = QByteArray(extension) + (deviceHasIt ? " (not requested)" : " (not supported)");
127 return false;
128 }
129 }
130 return true;
131}
132
135std::vector<quint64> queryImportableModifiers(QVulkanFunctions& functions, VkPhysicalDevice physicalDevice,
136 VkFormat format)
137{
138 VkDrmFormatModifierPropertiesListEXT list = {};
139 list.sType = VK_STRUCTURE_TYPE_DRM_FORMAT_MODIFIER_PROPERTIES_LIST_EXT;
140 VkFormatProperties2 properties = {};
141 properties.sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2;
142 properties.pNext = &list;
143 functions.vkGetPhysicalDeviceFormatProperties2(physicalDevice, format, &properties);
144 std::vector<VkDrmFormatModifierPropertiesEXT> candidates(list.drmFormatModifierCount);
145 list.pDrmFormatModifierProperties = candidates.data();
146 functions.vkGetPhysicalDeviceFormatProperties2(physicalDevice, format, &properties);
147 candidates.resize(list.drmFormatModifierCount);
148
149 std::vector<quint64> importable;
150 for (const VkDrmFormatModifierPropertiesEXT& candidate : candidates) {
151 if ((candidate.drmFormatModifierPlaneCount != 1) ||
152 !(candidate.drmFormatModifierTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) {
153 continue;
154 }
155 VkPhysicalDeviceImageDrmFormatModifierInfoEXT modifierInfo = {};
156 modifierInfo.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_DRM_FORMAT_MODIFIER_INFO_EXT;
157 modifierInfo.drmFormatModifier = candidate.drmFormatModifier;
158 modifierInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
159 VkPhysicalDeviceExternalImageFormatInfo externalInfo = {};
160 externalInfo.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO;
161 externalInfo.pNext = &modifierInfo;
162 externalInfo.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
163 VkPhysicalDeviceImageFormatInfo2 imageInfo = {};
164 imageInfo.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
165 imageInfo.pNext = &externalInfo;
166 imageInfo.format = format;
167 imageInfo.type = VK_IMAGE_TYPE_2D;
168 imageInfo.tiling = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT;
169 imageInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT;
170 VkExternalImageFormatProperties externalProperties = {};
171 externalProperties.sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES;
172 VkImageFormatProperties2 imageProperties = {};
173 imageProperties.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2;
174 imageProperties.pNext = &externalProperties;
175 if ((functions.vkGetPhysicalDeviceImageFormatProperties2(physicalDevice, &imageInfo, &imageProperties) ==
176 VK_SUCCESS) &&
177 (externalProperties.externalMemoryProperties.externalMemoryFeatures &
178 VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT)) {
179 importable.push_back(candidate.drmFormatModifier);
180 }
181 }
182 return importable;
183}
184
185void forgetDevice(const QRhi* rhi)
186{
187 const QMutexLocker lock(&s_deviceMutex);
188 if (s_device.rhi == rhi) {
189 s_importDevice.store(nullptr, std::memory_order_release);
190 s_device = {};
191 }
192}
193
196struct DeviceFns
197{
198 PFN_vkCreateImage createImage = nullptr;
199 PFN_vkDestroyImage destroyImage = nullptr;
200 PFN_vkAllocateMemory allocateMemory = nullptr;
201 PFN_vkFreeMemory freeMemory = nullptr;
202 PFN_vkBindImageMemory bindImageMemory = nullptr;
203 PFN_vkGetImageMemoryRequirements getImageMemoryRequirements = nullptr;
204 PFN_vkGetMemoryFdPropertiesKHR getMemoryFdProperties = nullptr;
205 PFN_vkGetPhysicalDeviceMemoryProperties getPhysicalDeviceMemoryProperties = nullptr;
206 PFN_vkCreateFence createFence = nullptr;
207 PFN_vkDestroyFence destroyFence = nullptr;
208 PFN_vkGetFenceStatus getFenceStatus = nullptr;
209 PFN_vkWaitForFences waitForFences = nullptr;
210 PFN_vkQueueSubmit queueSubmit = nullptr;
211 PFN_vkQueueWaitIdle queueWaitIdle = nullptr;
212
213 bool ok() const noexcept
214 {
215 return createImage && destroyImage && allocateMemory && freeMemory && bindImageMemory &&
216 getImageMemoryRequirements && getMemoryFdProperties && getPhysicalDeviceMemoryProperties &&
217 createFence && destroyFence && getFenceStatus && waitForFences && queueSubmit && queueWaitIdle;
218 }
219};
220
221// Bumped by resetCachedState() so every render thread re-resolves after a device reset.
222std::atomic<quint64> s_deviceFnsGeneration{0};
223
226const DeviceFns& deviceFns(QVulkanInstance& inst, VkDevice dev)
227{
228 struct CachedFns
229 {
230 VkDevice dev = VK_NULL_HANDLE;
231 quint64 generation = 0;
232 DeviceFns fns;
233 };
234
235 thread_local CachedFns cache;
236
237 const quint64 generation = s_deviceFnsGeneration.load(std::memory_order_acquire);
238 if (cache.dev == dev && cache.generation == generation) {
239 return cache.fns;
240 }
241 const auto getDeviceProcAddr =
242 reinterpret_cast<PFN_vkGetDeviceProcAddr>(inst.getInstanceProcAddr("vkGetDeviceProcAddr"));
243 const auto devFn = [&](const char* name) -> PFN_vkVoidFunction {
244 return getDeviceProcAddr ? getDeviceProcAddr(dev, name) : nullptr;
245 };
246 DeviceFns& fns = cache.fns;
247 fns.createImage = reinterpret_cast<PFN_vkCreateImage>(devFn("vkCreateImage"));
248 fns.destroyImage = reinterpret_cast<PFN_vkDestroyImage>(devFn("vkDestroyImage"));
249 fns.allocateMemory = reinterpret_cast<PFN_vkAllocateMemory>(devFn("vkAllocateMemory"));
250 fns.freeMemory = reinterpret_cast<PFN_vkFreeMemory>(devFn("vkFreeMemory"));
251 fns.bindImageMemory = reinterpret_cast<PFN_vkBindImageMemory>(devFn("vkBindImageMemory"));
252 fns.getImageMemoryRequirements =
253 reinterpret_cast<PFN_vkGetImageMemoryRequirements>(devFn("vkGetImageMemoryRequirements"));
254 fns.getMemoryFdProperties = reinterpret_cast<PFN_vkGetMemoryFdPropertiesKHR>(devFn("vkGetMemoryFdPropertiesKHR"));
255 fns.getPhysicalDeviceMemoryProperties = reinterpret_cast<PFN_vkGetPhysicalDeviceMemoryProperties>(
256 inst.getInstanceProcAddr("vkGetPhysicalDeviceMemoryProperties"));
257 fns.createFence = reinterpret_cast<PFN_vkCreateFence>(devFn("vkCreateFence"));
258 fns.destroyFence = reinterpret_cast<PFN_vkDestroyFence>(devFn("vkDestroyFence"));
259 fns.getFenceStatus = reinterpret_cast<PFN_vkGetFenceStatus>(devFn("vkGetFenceStatus"));
260 fns.waitForFences = reinterpret_cast<PFN_vkWaitForFences>(devFn("vkWaitForFences"));
261 fns.queueSubmit = reinterpret_cast<PFN_vkQueueSubmit>(devFn("vkQueueSubmit"));
262 fns.queueWaitIdle = reinterpret_cast<PFN_vkQueueWaitIdle>(devFn("vkQueueWaitIdle"));
263 cache.dev = dev;
264 cache.generation = generation;
265 return fns;
266}
267
269struct OwnedPlanes
270{
271 VkDevice dev = VK_NULL_HANDLE;
272 std::array<VkImage, kMaxPlanes> images{};
273 std::array<VkDeviceMemory, kMaxPlanes> memories{};
275 GstBuffer* buffer = nullptr;
276 DeviceFns fns;
277};
278
279void destroyPlanes(const OwnedPlanes& owned)
280{
281 for (int i = 0; i < kMaxPlanes; ++i) {
282 if (owned.images[i] != VK_NULL_HANDLE) {
283 owned.fns.destroyImage(owned.dev, owned.images[i], nullptr);
284 }
285 if (owned.memories[i] != VK_NULL_HANDLE) {
286 owned.fns.freeMemory(owned.dev, owned.memories[i], nullptr);
287 }
288 }
289 if (owned.buffer) {
290 gst_buffer_unref(owned.buffer);
291 }
292}
293
294// Render-thread confined, like the QRhi whose queue the fences are submitted to.
295struct RetiredPlanes
296{
297 OwnedPlanes owned;
298 VkFence fence = VK_NULL_HANDLE;
299};
300
301thread_local std::vector<RetiredPlanes> t_retiredPlanes;
302const char s_retiredPlanesCleanupKey = 0;
303
304void destroyRetired(const RetiredPlanes& retired)
305{
306 destroyPlanes(retired.owned);
307 if (retired.fence != VK_NULL_HANDLE) {
308 retired.owned.fns.destroyFence(retired.owned.dev, retired.fence, nullptr);
309 }
310}
311
312// Destroys @p dev's retired planes whose fence signalled; with @p waitAll (QRhi teardown) waits for every fence first.
313void reapRetired(VkDevice dev, bool waitAll)
314{
315 for (auto it = t_retiredPlanes.begin(); it != t_retiredPlanes.end();) {
316 const OwnedPlanes& o = it->owned;
317 if (o.dev != dev) {
318 ++it;
319 continue;
320 }
321 if (waitAll) {
322 (void) o.fns.waitForFences(dev, 1, &it->fence, VK_TRUE, UINT64_MAX);
323 } else if (o.fns.getFenceStatus(dev, it->fence) != VK_SUCCESS) {
324 ++it;
325 continue;
326 }
327 destroyRetired(*it);
328 it = t_retiredPlanes.erase(it);
329 }
330}
331
332void retire(VkQueue queue, const OwnedPlanes& owned)
333{
334 RetiredPlanes retired{owned};
335 const VkFenceCreateInfo fenceInfo = {VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, nullptr, 0};
336 // A submit without batches signals its fence once all work already submitted to the queue has completed.
337 if (owned.fns.createFence(owned.dev, &fenceInfo, nullptr, &retired.fence) != VK_SUCCESS ||
338 owned.fns.queueSubmit(queue, 0, nullptr, retired.fence) != VK_SUCCESS) {
339 (void) owned.fns.queueWaitIdle(queue);
340 destroyRetired(retired);
341 return;
342 }
343 t_retiredPlanes.push_back(retired);
344 reapRetired(owned.dev, /*waitAll=*/false);
345}
346
352std::function<void()> deferredRelease(QRhi& rhi, VkQueue queue, const OwnedPlanes& owned)
353{
354 const VkDevice dev = owned.dev;
355 // Keyed: one teardown hook per QRhi, run while its device is still alive.
356 rhi.addCleanupCallback(&s_retiredPlanesCleanupKey, [dev](QRhi*) { reapRetired(dev, /*waitAll=*/true); });
357 return [queue, owned] { retire(queue, owned); };
358}
359
363bool importPlane(const DeviceFns& fns, VkDevice dev, VkPhysicalDevice physicalDevice,
364 const GstQtDmaBufImport::Plane& plane, VkFormat format, QSize size, VkImage& image,
365 VkDeviceMemory& memory)
366{
367 VkSubresourceLayout layout = {};
368 layout.offset = plane.offset;
369 layout.rowPitch = plane.pitch;
370
371 VkImageDrmFormatModifierExplicitCreateInfoEXT modifierInfo = {};
372 modifierInfo.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT;
373 modifierInfo.drmFormatModifier = explicitModifier(plane.modifier);
374 modifierInfo.drmFormatModifierPlaneCount = 1;
375 modifierInfo.pPlaneLayouts = &layout;
376
377 VkExternalMemoryImageCreateInfo externalInfo = {};
378 externalInfo.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO;
379 externalInfo.pNext = &modifierInfo;
380 externalInfo.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
381
382 VkImageCreateInfo imageInfo = {};
383 imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
384 imageInfo.pNext = &externalInfo;
385 imageInfo.imageType = VK_IMAGE_TYPE_2D;
386 imageInfo.format = format;
387 imageInfo.extent = {static_cast<uint32_t>(size.width()), static_cast<uint32_t>(size.height()), 1};
388 imageInfo.mipLevels = 1;
389 imageInfo.arrayLayers = 1;
390 imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
391 imageInfo.tiling = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT;
392 imageInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT;
393 imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
394 imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
395
396 if (const VkResult result = fns.createImage(dev, &imageInfo, nullptr, &image); result != VK_SUCCESS) {
397 image = VK_NULL_HANDLE;
398 QGC_HW_WARN_ONCE(GstDmaBufVulkanLog, s_loggedImportFailed,
399 "vkCreateImage failed (VkResult=" << result << "format=" << format << "modifier=" << Qt::hex
400 << modifierInfo.drmFormatModifier << Qt::dec << ")");
401 return false;
402 }
403
404 // Vulkan owns an imported fd from a successful allocation on; until then it is ours to close.
405 const int fd = ::fcntl(plane.fd, F_DUPFD_CLOEXEC, 0);
406 if (fd < 0) {
407 return false;
408 }
409 VkMemoryFdPropertiesKHR fdProperties = {};
410 fdProperties.sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR;
411 VkMemoryRequirements requirements = {};
412 fns.getImageMemoryRequirements(dev, image, &requirements);
413 VkPhysicalDeviceMemoryProperties memoryProperties = {};
414 fns.getPhysicalDeviceMemoryProperties(physicalDevice, &memoryProperties);
415 uint32_t memoryType = UINT32_MAX;
416 if (fns.getMemoryFdProperties(dev, VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT, fd, &fdProperties) ==
417 VK_SUCCESS) {
418 const uint32_t allowed = requirements.memoryTypeBits & fdProperties.memoryTypeBits;
419 for (uint32_t i = 0; i < memoryProperties.memoryTypeCount; ++i) {
420 if (allowed & (1u << i)) {
421 memoryType = i;
422 break;
423 }
424 }
425 }
426
427 VkImportMemoryFdInfoKHR importInfo = {};
428 importInfo.sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR;
429 importInfo.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
430 importInfo.fd = fd;
431 VkMemoryDedicatedAllocateInfo dedicatedInfo = {};
432 dedicatedInfo.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO;
433 dedicatedInfo.pNext = &importInfo;
434 dedicatedInfo.image = image;
435 VkMemoryAllocateInfo allocateInfo = {};
436 allocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
437 allocateInfo.pNext = &dedicatedInfo;
438 allocateInfo.allocationSize = requirements.size;
439 allocateInfo.memoryTypeIndex = memoryType;
440
441 const VkResult allocated = (memoryType != UINT32_MAX) ? fns.allocateMemory(dev, &allocateInfo, nullptr, &memory)
442 : VK_ERROR_FORMAT_NOT_SUPPORTED;
443 if (allocated != VK_SUCCESS) {
444 memory = VK_NULL_HANDLE;
445 ::close(fd);
446 QGC_HW_WARN_ONCE(GstDmaBufVulkanLog, s_loggedImportFailed,
447 "importing a dma-buf as image memory failed (VkResult=" << allocated << ")");
448 return false;
449 }
450 if (const VkResult bound = fns.bindImageMemory(dev, image, memory, 0); bound != VK_SUCCESS) {
451 QGC_HW_WARN_ONCE(GstDmaBufVulkanLog, s_loggedImportFailed,
452 "vkBindImageMemory failed (VkResult=" << bound << ")");
453 return false;
454 }
455 return true;
456}
457
458} // namespace
459
460namespace GstDmaBufVulkan {
461
462void requestDeviceExtensions()
463{
464 QByteArrayList extensions = qgetenv(kDeviceExtensionsVariable).split(';');
465 extensions.removeAll(QByteArray());
466 for (const char* const extension : kRequiredDeviceExtensions) {
467 if (!extensions.contains(extension)) {
468 extensions.append(extension);
469 }
470 }
471 (void) qputenv(kDeviceExtensionsVariable, extensions.join(';'));
472}
473
474void probeDevice(QRhi& rhi)
475{
476 if (rhi.backend() != QRhi::Vulkan) {
477 return;
478 }
479 ImportDevice device;
480 device.rhi = &rhi;
481 QByteArray unusable;
482 const auto* handles = static_cast<const QRhiVulkanNativeHandles*>(rhi.nativeHandles());
483 if (!handles || !handles->inst || (handles->physDev == VK_NULL_HANDLE)) {
484 unusable = "QRhi exposes no Vulkan device";
485 } else {
486 device.physicalDevice = handles->physDev;
487 QVulkanFunctions& functions = *handles->inst->functions();
488 VkPhysicalDeviceProperties properties = {};
489 functions.vkGetPhysicalDeviceProperties(handles->physDev, &properties);
490 const QVersionNumber deviceVersion(VK_VERSION_MAJOR(properties.apiVersion),
491 VK_VERSION_MINOR(properties.apiVersion));
492 // The instance's version bounds the device functions an application may call.
493 if (std::min(deviceVersion, handles->inst->apiVersion()) < QVersionNumber(1, 2)) {
494 unusable = "it needs Vulkan 1.2";
495 } else if (QByteArray missing; !deviceExtensionsEnabled(functions, handles->physDev, missing)) {
496 unusable = "device extension " + missing;
497 } else {
498 for (std::size_t i = 0; i < kPlaneFormatCount; ++i) {
499 device.modifiers[i] = queryImportableModifiers(functions, handles->physDev, kPlaneFormats[i].vkFormat);
500 }
501 if (!device.imports()) {
502 unusable = "the device imports no plane format from a dma-buf";
503 }
504 }
505 }
506
507 if (unusable.isEmpty()) {
508 qCDebug(GstDmaBufVulkanLog) << "DMABuf import available on" << rhi.driverInfo().deviceName;
509 } else {
510 qCDebug(GstDmaBufVulkanLog) << "DMABuf frames take the CPU path under this Vulkan device:" << unusable;
511 }
512 {
513 const QMutexLocker lock(&s_deviceMutex);
514 s_importDevice.store(device.imports() ? static_cast<void*>(device.physicalDevice) : nullptr,
515 std::memory_order_release);
516 s_device = std::move(device);
517 }
518 // Keyed, so probing a QRhi again replaces the callback.
519 rhi.addCleanupCallback(&s_deviceCleanupKey, [](QRhi* dying) { forgetDevice(dying); });
520}
521
522void* importDevice() noexcept
523{
524 return s_importDevice.load(std::memory_order_acquire);
525}
526
527bool canImport(const GstQtDmaBufImport::PlaneFourccs& planeFourccs, quint64 modifier)
528{
529 if (planeFourccs.count <= 0) {
530 return false;
531 }
532 const QMutexLocker lock(&s_deviceMutex);
533 for (int plane = 0; plane < planeFourccs.count; ++plane) {
534 const quint32 fourcc = planeFourccs.fourcc[std::size_t(plane)];
535 const std::size_t format =
536 planeFormatIndex([fourcc](const PlaneFormat& candidate) { return candidate.drmFourcc == fourcc; });
537 if ((format == kPlaneFormatCount) || !s_device.imports(format, explicitModifier(modifier))) {
538 return false;
539 }
540 }
541 return true;
542}
543
544std::vector<quint64> importableModifiers(quint32 planeFourcc)
545{
546 const std::size_t format =
547 planeFormatIndex([planeFourcc](const PlaneFormat& candidate) { return candidate.drmFourcc == planeFourcc; });
548 const QMutexLocker lock(&s_deviceMutex);
549 return (format != kPlaneFormatCount) ? s_device.modifiers[format] : std::vector<quint64>();
550}
551
552void resetCachedState() noexcept
553{
554 s_diag.reset();
555 s_loggedImportFailed.store(false, std::memory_order_relaxed);
556 s_deviceFnsGeneration.fetch_add(1, std::memory_order_acq_rel);
557}
558
559QVideoFrameTexturesUPtr importTextures(GstHwVideoBuffer& source, QRhi& rhi, QVideoFrameTexturesUPtr& old,
560 std::span<const GstQtDmaBufImport::Plane> planes,
561 QVideoFrameFormat::PixelFormat pixelFormat, QSize frameSize, GstBuffer* buffer,
562 bool& rejected)
563{
564 rejected = false;
565 const auto* handles = static_cast<const QRhiVulkanNativeHandles*>(rhi.nativeHandles());
566 const auto* description = QVideoTextureHelper::textureDescription(pixelFormat);
567 // Another window's QRhi, whose device wasn't probed, may lack the extensions or the layouts.
568 if (!handles || !handles->inst || (handles->dev == VK_NULL_HANDLE) || (handles->gfxQueue == VK_NULL_HANDLE) ||
569 (handles->physDev != importDevice()) || !description || planes.empty() ||
570 (std::ssize(planes) != description->nplanes) || (planes.size() > std::size_t(kMaxPlanes))) {
572 }
573 const DeviceFns& fns = deviceFns(*handles->inst, handles->dev);
574 if (!fns.ok()) {
576 }
577
578 OwnedPlanes owned;
579 owned.dev = handles->dev;
580 owned.fns = fns;
581 bool imported = true;
582 for (std::size_t i = 0; imported && (i < planes.size()); ++i) {
583 // The format of the image view QRhi creates for the plane, which the image must have too.
584 const QRhiTexture::Format rhiFormat = description->rhiTextureFormat(
585 int(i), &rhi, QVideoTextureHelper::TextureDescription::FallbackPolicy::Disable);
586 const std::size_t format =
587 planeFormatIndex([rhiFormat](const PlaneFormat& candidate) { return candidate.rhiFormat == rhiFormat; });
588 const bool importable = [&] {
589 const QMutexLocker lock(&s_deviceMutex);
590 return (format != kPlaneFormatCount) && s_device.imports(format, explicitModifier(planes[i].modifier));
591 }();
592 if (!importable) {
593 imported = false;
594 break;
595 }
596 imported = importPlane(fns, handles->dev, handles->physDev, planes[i], kPlaneFormats[format].vkFormat,
597 description->rhiPlaneSize(frameSize, int(i), &rhi), owned.images[i], owned.memories[i]);
598 rejected = !imported;
599 }
600 if (!imported) {
601 destroyPlanes(owned);
603 }
604
605 const GstHwMapTail tail{.path = HwVideoBufferPath::DmaBuf,
606 .frameSize = frameSize,
607 .pixelFormat = pixelFormat,
608 .log = &GstDmaBufVulkanLog(),
609 .diag = &s_diag,
610 .preflight = false,
611 .successTag = "DMABuf->Vulkan"};
612 bool adopted = false;
613 QVideoFrameTexturesUPtr textures =
614 GstHwFrameTexturesBase::finishMap<GstVulkanOwnedFrameTextures>(source, rhi, old, tail, nullptr, [&] {
615 auto bundle = std::make_unique<GstVulkanOwnedFrameTextures>(
616 &rhi, frameSize, pixelFormat, std::span<const VkImage>(owned.images.data(), planes.size()));
617 if (bundle->allPlanesValid()) {
618 owned.buffer = gst_buffer_ref(buffer);
619 bundle->adoptVulkanResources(deferredRelease(rhi, handles->gfxQueue, owned));
620 adopted = true;
621 }
622 return bundle;
623 });
624 if (!adopted) {
625 destroyPlanes(owned);
626 }
627 return textures;
628}
629
630} // namespace GstDmaBufVulkan
631
632#endif // QGC_HAS_GST_DMABUF_VULKAN_IMPORT
#define QGC_HW_WARN_ONCE(LOGCAT, FLAG,...)
Logs once via qCWarning(LOGCAT) the first time FLAG flips true; subsequent trips are silent.
#define QGC_LOGGING_CATEGORY(name, categoryStr)
static QVideoFrameTexturesUPtr finishMap(GstHwVideoBuffer &source, QRhi &rhi, QVideoFrameTexturesUPtr &old, const GstHwMapTail &tail, Reuse &&reuse, Make &&make)
static GParamSpec * properties[PROP_LAST]
QVideoFrameTexturesUPtr fail(HwVideoBufferPath path) noexcept
Records a map failure for path and returns the empty bundle mapTextures() reports it with.
constexpr int kMaxPlanes
Matches GST_VIDEO_MAX_PLANES (gst-video pins it at 4); single source of truth for every per-platform ...
QByteArray format(const QList< LogEntry > &entries, int fmt)
bool rejected(const Fields &reply, std::string_view command)
QCameraDevice device(const QString &description)
The attached camera of description description; a null device when none is.
Definition UVCDevices.cc:21
One-shot warning flags per failure cause; paths with extra causes (DMABuf, D3D, IOSurface) derive and...