QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
QGCRhiCapture.cc
Go to the documentation of this file.
1#include "QGCRhiCapture.h"
2
3#include <rhi/qrhi.h>
4
5#include <QtCore/QRunnable>
6#include <QtQuick/QQuickWindow>
7
9#include "GstHwPathRegistry.h"
10#include "HwBuffers.h"
11#if QT_CONFIG(opengl) && QT_CONFIG(egl)
12#include <QtCore/QThread>
13#include <QtGui/QGuiApplication>
14#include <QtGui/QOpenGLContext>
15#include <QtGui/qopenglcontext_platform.h>
16#include <qpa/qplatformnativeinterface.h>
17#define QGC_RHI_CAPTURE_PROBES_EGL 1
18#endif
19#if defined(QGC_HAS_GST_D3D11_GPU_PATH) || defined(QGC_HAS_GST_D3D12_GPU_PATH) || \
20 (defined(QGC_HAS_GST_VULKAN_GPU_PATH) && QT_CONFIG(vulkan)) || defined(QGC_RHI_CAPTURE_PROBES_EGL)
21#include <rhi/qrhi_platform.h>
22#endif
23#if defined(QGC_HAS_GST_VULKAN_GPU_PATH) && QT_CONFIG(vulkan)
24#include <QtGui/QVulkanFunctions>
25#include <QtGui/QVulkanInstance>
26#endif
27#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
28#include <d3d11.h>
29#include <d3d11_4.h> // ID3D11Multithread
30
31#include "QGCLoggingCategory.h"
32#endif
33
34#include <array>
35#include <atomic>
36#include <cstring>
37
38#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
39QGC_LOGGING_CATEGORY(QGCRhiCaptureLog, "Video.GStreamer.HwBuffers.RhiCapture")
40#endif
41
42namespace QGCRhiCapture {
43
44namespace {
45// The connected window (or null after it is destroyed); read only by connectWindow's idempotency
46// guard. Atomic because the destroyed lambda nulls it on the window's thread.
47std::atomic<QQuickWindow*> s_connectedWindow{nullptr};
48DeviceSnapshot s_snapshot;
49// Per-connection so a window swap (e.g. popout video) can disconnect the prior window's lambdas before they clobber the
50// new window's snapshot.
51std::array<QMetaObject::Connection, 3> s_connections;
52// Qt's EGLDisplay once found; Qt keeps it for the application's lifetime.
53std::atomic<void*> s_qtEglDisplay{nullptr};
54std::atomic<void (*)()> s_publishedHandler{nullptr};
55
56#if defined(QGC_RHI_CAPTURE_PROBES_EGL)
57void* eglDisplayOf(const QOpenGLContext* context)
58{
59 const auto* egl = context ? context->nativeInterface<QNativeInterface::QEGLContext>() : nullptr;
60 return egl ? static_cast<void*>(egl->display()) : nullptr;
61}
62#endif
63
64void clearSnapshot()
65{
66 s_snapshot.backend.store(-1, std::memory_order_release);
67 s_snapshot.d3d11Device.store(nullptr, std::memory_order_release);
68 s_snapshot.adapterLuid.store(0, std::memory_order_release);
69 s_snapshot.d3d11OpensD3D12.store(false, std::memory_order_release);
70 s_snapshot.vkVendorId.store(0, std::memory_order_release);
71 s_snapshot.vkDeviceId.store(0, std::memory_order_release);
72 for (std::atomic<quint64>& half : s_snapshot.vkPipelineCacheUuid) {
73 half.store(0, std::memory_order_release);
74 }
75}
76
77#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
78// QRhi creates its D3D11 device without multithread protection (qrhid3d11.cpp), but GStreamer's D3D11 elements share
79// its immediate context from their streaming threads. Turned on here, on the render thread, before the device is
80// published to them: switching it while another thread is inside the context isn't safe. Idempotent. Returns whether
81// the context is protected now; an unprotected device must not be published.
82bool protectImmediateContext(ID3D11DeviceContext* context)
83{
84 ID3D11Multithread* multithread = nullptr;
85 if (!context ||
86 FAILED(context->QueryInterface(__uuidof(ID3D11Multithread), reinterpret_cast<void**>(&multithread))) ||
87 !multithread) {
88 return false;
89 }
90 (void) multithread->SetMultithreadProtected(TRUE);
91 const bool isProtected = multithread->GetMultithreadProtected();
92 multithread->Release();
93 return isProtected;
94}
95#endif
96
97void populateSnapshot(QRhi* rhi)
98{
99 if (!rhi) {
100 clearSnapshot();
101 return;
102 }
103 const int backend = static_cast<int>(rhi->backend());
104 void* d3d11 = nullptr;
105 qint64 luid = 0;
106 quint32 vkVendorId = 0;
107 quint32 vkDeviceId = 0;
108 std::array<quint64, 2> vkPipelineCacheUuid{};
109
110#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
111 if (rhi->backend() == QRhi::D3D11) {
112 if (auto* h = static_cast<const QRhiD3D11NativeHandles*>(rhi->nativeHandles())) {
113 if (protectImmediateContext(static_cast<ID3D11DeviceContext*>(h->context))) {
114 d3d11 = h->dev;
115 } else {
116 qCWarning(QGCRhiCaptureLog)
117 << "Qt's D3D11 immediate context isn't multithread-protected; GStreamer gets its own device";
118 }
119 // Sign-extend qint32 HighPart so it matches LARGE_INTEGER::QuadPart bit-for-bit.
120 luid = (static_cast<qint64>(h->adapterLuidHigh) << 32) |
121 (static_cast<qint64>(h->adapterLuidLow) & 0xFFFFFFFFLL);
122 }
123 }
124#endif
125#if defined(QGC_HAS_GST_D3D12_GPU_PATH)
126 if (rhi->backend() == QRhi::D3D12) {
127 if (auto* h = static_cast<const QRhiD3D12NativeHandles*>(rhi->nativeHandles())) {
128 luid = (static_cast<qint64>(h->adapterLuidHigh) << 32) |
129 (static_cast<qint64>(h->adapterLuidLow) & 0xFFFFFFFFLL);
130 }
131 }
132#endif
133#if defined(QGC_RHI_CAPTURE_PROBES_EGL)
134 if (rhi->backend() == QRhi::OpenGLES2) {
135 if (auto* h = static_cast<const QRhiGles2NativeHandles*>(rhi->nativeHandles())) {
136 if (void* const display = eglDisplayOf(h->context)) {
137 s_qtEglDisplay.store(display, std::memory_order_release);
138 }
139 }
140 }
141#endif
142#if defined(QGC_HAS_GST_VULKAN_GPU_PATH) && QT_CONFIG(vulkan)
143 if (rhi->backend() == QRhi::Vulkan) {
144 const auto* h = static_cast<const QRhiVulkanNativeHandles*>(rhi->nativeHandles());
145 if (h && h->inst && (h->physDev != VK_NULL_HANDLE)) {
146 VkPhysicalDeviceProperties properties{};
147 h->inst->functions()->vkGetPhysicalDeviceProperties(h->physDev, &properties);
148 vkVendorId = properties.vendorID;
149 vkDeviceId = properties.deviceID;
150 static_assert(sizeof(vkPipelineCacheUuid) == sizeof(properties.pipelineCacheUUID));
151 std::memcpy(vkPipelineCacheUuid.data(), properties.pipelineCacheUUID, sizeof(vkPipelineCacheUuid));
152 }
153 }
154#endif
155
156 for (const HwPathDescriptor* path : GstHwPathRegistry::paths()) {
157 if (path->probeDevice) {
158 path->probeDevice(*rhi);
159 }
160 }
161
162 // Publish device pointers, and what the paths learned of the device, before the backend tag so a consumer's
163 // acquire-load on backend != -1 is guaranteed to see them.
164 s_snapshot.d3d11Device.store(d3d11, std::memory_order_release);
165 s_snapshot.adapterLuid.store(luid, std::memory_order_release);
166 s_snapshot.vkVendorId.store(vkVendorId, std::memory_order_release);
167 s_snapshot.vkDeviceId.store(vkDeviceId, std::memory_order_release);
168 for (std::size_t i = 0; i < vkPipelineCacheUuid.size(); ++i) {
169 s_snapshot.vkPipelineCacheUuid[i].store(vkPipelineCacheUuid[i], std::memory_order_release);
170 }
171 s_snapshot.backend.store(backend, std::memory_order_release);
172
173 // A pipeline that asked a bridge for this device before it was published has it from now on.
174 for (const HwPathDescriptor* path : GstHwPathRegistry::paths()) {
175 if (path->bridge) {
176 path->bridge().serveWaitingPipelines();
177 }
178 }
179 if (void (*const handler)() = s_publishedHandler.load(std::memory_order_acquire)) {
180 handler();
181 }
182}
183
185void publishRhi(QQuickWindow* window)
186{
187 populateSnapshot(window->rhi());
188}
189
191void unpublishRhi()
192{
193 clearSnapshot();
195}
196
197} // namespace
198
200{
201 return s_snapshot;
202}
203
204#ifdef QGC_UNITTEST_BUILD
205void publishDeviceSnapshotForTest(QRhi* rhi)
206{
207 populateSnapshot(rhi);
208}
209#endif
210
212{
213 void* display = s_qtEglDisplay.load(std::memory_order_acquire);
214#if defined(QGC_RHI_CAPTURE_PROBES_EGL)
215 if (display) {
216 return display;
217 }
218 // Qt Quick's OpenGL shares with the global share context (Qt::AA_ShareOpenGLContexts): it tells EGL from GLX
219 // without creating anything, from any thread.
220 if (const QOpenGLContext* const shareContext = QOpenGLContext::globalShareContext()) {
221 display = eglDisplayOf(shareContext);
222 } else if (QThread::isMainThread() && qGuiApp) {
223 if (QPlatformNativeInterface* const native = QGuiApplication::platformNativeInterface()) {
224 display = native->nativeResourceForIntegration(QByteArrayLiteral("egldisplay"));
225 }
226 }
227 if (display) {
228 s_qtEglDisplay.store(display, std::memory_order_release);
229 }
230#endif
231 return display;
232}
233
234void setPublishedHandler(void (*handler)()) noexcept
235{
236 s_publishedHandler.store(handler, std::memory_order_release);
237}
238
239void connectWindow(QQuickWindow* window)
240{
241 if (!window)
242 return;
243 if (s_connectedWindow.load(std::memory_order_acquire) == window)
244 return; // idempotent — avoid duplicate connections
245
246 // Window swap: the old window's QRhi can be torn down before the new window's SG initializes; withdraw it now so
247 // bus-sync threads never dereference a dead device across the gap.
248 if (s_connectedWindow.load(std::memory_order_acquire) != nullptr) {
249 unpublishRhi();
250 }
251
252 // Detach the prior window's signals first, else its destroyed/invalidated lambdas later wipe the snapshot and reset
253 // bridges the new window is using.
254 for (std::size_t i = 0; i < s_connections.size(); ++i) {
255 auto& conn = s_connections[i];
256 QObject::disconnect(conn);
257 conn = QMetaObject::Connection();
258 }
259
260 s_connectedWindow.store(window, std::memory_order_release);
261 // sceneGraphInitialized fires on the render thread where rhi() is valid — snapshot native device pointers here so
262 // bus-sync callbacks never deref QRhi* cross-thread.
263 s_connections[0] = QObject::connect(
264 window, &QQuickWindow::sceneGraphInitialized, window, [window]() { publishRhi(window); }, Qt::DirectConnection);
265 s_connections[1] =
266 QObject::connect(window, &QQuickWindow::sceneGraphInvalidated, window, &unpublishRhi, Qt::DirectConnection);
267 // Withdraw the snapshot when window is destroyed so a stale device is never handed out.
268 s_connections[2] = QObject::connect(
269 window, &QQuickWindow::destroyed, window,
270 [](QObject*) {
271 s_connectedWindow.store(nullptr, std::memory_order_release);
272 unpublishRhi();
273 },
274 Qt::DirectConnection);
275
276 // SG already initialized (video init runs after first render) — publish on the render thread.
277 if (window->isSceneGraphInitialized()) {
278 window->scheduleRenderJob(QRunnable::create([window]() { publishRhi(window); }),
279 QQuickWindow::BeforeSynchronizingStage);
280 window->update();
281 }
282}
283
284} // namespace QGCRhiCapture
#define qGuiApp
#define QGC_LOGGING_CATEGORY(name, categoryStr)
static GParamSpec * properties[PROP_LAST]
std::span< const HwPathDescriptor *const > paths() noexcept
void resetCachedGpuResources()
Definition HwBuffers.cc:85
Publishes the native device of the QRhi driving QGC's main scene graph; Qt has no global RHI accessor...
void setPublishedHandler(void(*handler)()) noexcept
void * qtEglDisplay()
void connectWindow(QQuickWindow *window)
DeviceSnapshot & deviceSnapshot() noexcept
Returns the global snapshot. Atomic fields make individual reads thread-safe.
std::atomic< bool > d3d11OpensD3D12
std::atomic< quint32 > vkDeviceId
deviceID
std::atomic< int > backend
QRhi::Implementation cast to int (-1 = unset).
std::array< std::atomic< quint64 >, 2 > vkPipelineCacheUuid
pipelineCacheUUID, 8 bytes each in memory order
std::atomic< void * > d3d11Device
ID3D11Device* (Windows only).
std::atomic< qint64 > adapterLuid
std::atomic< quint32 > vkVendorId
vendorID