QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
HwBuffers.cc
Go to the documentation of this file.
1#include "HwBuffers.h"
2
3#include <algorithm>
4#include <atomic>
5#include <optional>
6#include <utility>
7#include <vector>
8
9#include <QtCore/QCoreApplication>
10#include <QtQuick/QQuickWindow>
11#include <QtQuick/QSGRendererInterface>
12
13#include "QGCLoggingCategory.h"
14
15#if defined(QGC_HAS_ANY_GPU_PATH)
17#include "GstHwPathRegistry.h"
18#include "QGCRhiCapture.h"
19#endif
20#if defined(QGC_HAS_GST_DMABUF_GPU_PATH)
21#include <rhi/qrhi.h>
22
25#endif
26#if defined(QGC_UNITTEST_BUILD) && (defined(QGC_HAS_GST_DMABUF_GPU_PATH) || \
27 (defined(QGC_HAS_GST_D3D11_GPU_PATH) && defined(QGC_HAS_GST_D3D12_GPU_PATH)))
28#include "gstqgc/GstQgcCaps.h"
29#endif
30
31namespace HwBuffers {
32
33#if defined(QGC_HAS_ANY_GPU_PATH)
34QGC_LOGGING_CATEGORY(HwBuffersFacadeLog, "Video.GStreamer.HwBuffers.Facade")
35
36namespace {
37
39template <class Fn>
40void forEachCompiledPath(Fn&& fn)
41{
42 for (std::size_t i = 1; i < GstHw::kPathCount; ++i) {
43 const auto path = static_cast<HwVideoBufferPath>(i);
44 if (GstHwPathRegistry::has(path)) {
45 fn(path);
46 }
47 }
48}
49
50} // namespace
51#endif
52
53namespace {
54
55std::atomic<bool> s_softwareRendering{false};
56
57} // namespace
58
59GstBusSyncReply onBusSyncMessage(GstMessage* msg) noexcept
60{
61#if defined(QGC_HAS_ANY_GPU_PATH)
62 // First GST_BUS_DROP wins; bridges answer disjoint context types, so none shadows another.
63 for (const HwPathDescriptor* path : GstHwPathRegistry::paths()) {
64 if (path->bridge && (path->bridge().handleSyncMessage(msg) == GST_BUS_DROP)) {
65 return GST_BUS_DROP;
66 }
67 }
68#else
69 Q_UNUSED(msg);
70#endif
71 return GST_BUS_PASS;
72}
73
75{
76#if defined(QGC_HAS_ANY_GPU_PATH)
77 for (const HwPathDescriptor* path : GstHwPathRegistry::paths()) {
78 if (path->bridge) {
79 path->bridge().rearm();
80 }
81 }
82#endif
83}
84
86{
87#if defined(QGC_HAS_ANY_GPU_PATH)
88 const auto paths = GstHwPathRegistry::paths();
89 for (const HwPathDescriptor* path : paths) {
90 if (path->bridge) {
91 path->bridge().reset();
92 }
93 }
94 for (const HwPathDescriptor* path : paths) {
95 if (path->resetCaches) {
96 path->resetCaches();
97 }
98 }
99#endif
100}
101
103{
104#if defined(QGC_HAS_ANY_GPU_PATH)
105 // Before the reset, which forgets them.
106 std::vector<GStreamer::GstElementPtr> pipelines;
107 for (const HwPathDescriptor* path : GstHwPathRegistry::paths()) {
108 if (!path->bridge) {
109 continue;
110 }
111 for (GStreamer::GstElementPtr& pipeline : path->bridge().takeServed()) {
112 const bool known = std::ranges::any_of(pipelines, [&pipeline](const GStreamer::GstElementPtr& other) {
113 return other.get() == pipeline.get();
114 });
115 if (!known) {
116 pipelines.push_back(std::move(pipeline));
117 }
118 }
119 }
121 for (const GStreamer::GstElementPtr& pipeline : pipelines) {
122 (void) gst_element_post_message(
123 pipeline.get(),
124 gst_message_new_element(GST_OBJECT(pipeline.get()), gst_structure_new_empty(kGraphicsDeviceLostMessage)));
125 }
126#endif
127}
128
129bool graphicsDeviceLost() noexcept
130{
131#if defined(QGC_HAS_ANY_GPU_PATH)
132 for (const HwPathDescriptor* path : GstHwPathRegistry::paths()) {
133 if (path->bridge && path->bridge().deviceLost()) {
134 return true;
135 }
136 }
137#endif
138 return false;
139}
140
141void configureQtGraphics(bool softwareRendering)
142{
143 s_softwareRendering.store(softwareRendering, std::memory_order_release);
144#if defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID) && \
145 (defined(QGC_HAS_GST_GLMEMORY_GPU_PATH) || defined(QGC_HAS_GST_DMABUF_GPU_PATH))
146 // GL takes every desktop-Linux zero-copy path (GLMemory and DMABuf/EGLImage both import into a GL RHI), Vulkan
147 // only DMABuf, in the layouts its device imports: pin GL unless the user chose a backend. GL is always present on
148 // Linux, so no QRhi::probe.
149 if (!softwareRendering && !qEnvironmentVariableIsSet("QSG_RHI_BACKEND")) {
150 QQuickWindow::setGraphicsApi(QSGRendererInterface::OpenGL);
151 }
152 // GStreamer's zero-copy imports need Qt on EGL, but Qt's xcb integration picks GLX first (the AppImage runs xcb
153 // even in Wayland sessions). Qt falls back to GLX when EGL fails to initialize; the user's value wins.
154 if (!qEnvironmentVariableIsSet("QT_XCB_GL_INTEGRATION")) {
155 (void) qputenv("QT_XCB_GL_INTEGRATION", "xcb_egl");
156 }
157#endif
158 // The GL and DMABuf paths both need QOpenGLContext::globalShareContext(), which this attribute enables.
159#if defined(QGC_HAS_GST_GLMEMORY_GPU_PATH) || defined(QGC_HAS_GST_DMABUF_GPU_PATH)
160 QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts);
161#endif
162 // Read only when Qt creates a Vulkan device, as it does with QSG_RHI_BACKEND=vulkan.
163#if defined(QGC_HAS_GST_DMABUF_VULKAN_IMPORT)
164 GstDmaBufVulkan::requestDeviceExtensions();
165#endif
166}
167
169{
170 return s_softwareRendering.load(std::memory_order_acquire);
171}
172
173void connectMainWindow(QQuickWindow* window)
174{
175#if defined(QGC_HAS_ANY_GPU_PATH)
177#else
178 Q_UNUSED(window);
179#endif
180}
181
183{
185#if defined(QGC_HAS_ANY_GPU_PATH)
186 ctx.gpuEnabled = gpuEnabled;
187 if (!gpuEnabled) {
188 return ctx;
189 }
190 QString available;
191 forEachCompiledPath(
192 [&available](HwVideoBufferPath path) { available += QLatin1Char(' ') + QLatin1String(GstHw::toString(path)); });
193 qCDebug(HwBuffersFacadeLog).noquote()
194 << "zero-copy paths compiled:" << available.trimmed() << "— actual path chosen at caps negotiation";
195 for (const HwPathDescriptor* path : GstHwPathRegistry::paths()) {
196 if (path->prepareContext) {
197 path->prepareContext(ctx);
198 }
199 }
200#else
201 Q_UNUSED(gpuEnabled);
202#endif
203 return ctx;
204}
205
206void* dmaBufImportDisplay() noexcept
207{
208#if defined(QGC_HAS_GST_DMABUF_GPU_PATH)
209 if (GstDmaBufVideoBuffer::importDisabled()) {
210 return nullptr;
211 }
212#ifdef QGC_UNITTEST_BUILD
213 if (const std::optional<GstQgc::SinkEnvironment> environment = GstQgc::sinkEnvironmentForTest()) {
214 return environment->dmaBufDisplay;
215 }
216#endif
217 // Qt can have an EGLDisplay under Vulkan too (its global share context), which imports nothing for a Vulkan QRhi.
218 if (QGCRhiCapture::deviceSnapshot().backend.load(std::memory_order_acquire) == static_cast<int>(QRhi::Vulkan)) {
219#if defined(QGC_HAS_GST_DMABUF_VULKAN_IMPORT)
220 return GstDmaBufVulkan::importDevice();
221#else
222 return nullptr;
223#endif
224 }
226#else
227 return nullptr;
228#endif
229}
230
231qint64 graphicsAdapterLuid() noexcept
232{
233#if defined(QGC_HAS_GST_D3D11_GPU_PATH) || defined(QGC_HAS_GST_D3D12_GPU_PATH)
234 return QGCRhiCapture::deviceSnapshot().adapterLuid.load(std::memory_order_acquire);
235#else
236 return 0;
237#endif
238}
239
240void setGraphicsDevicePublishedHandler([[maybe_unused]] void (*handler)()) noexcept
241{
242#if defined(QGC_HAS_ANY_GPU_PATH)
244#endif
245}
246
247bool d3d11OpensD3D12() noexcept
248{
249#if defined(QGC_HAS_GST_D3D11_GPU_PATH) && defined(QGC_HAS_GST_D3D12_GPU_PATH)
250#ifdef QGC_UNITTEST_BUILD
251 if (const std::optional<GstQgc::SinkEnvironment> environment = GstQgc::sinkEnvironmentForTest()) {
252 return environment->d3d11OpensD3D12;
253 }
254#endif
255 return QGCRhiCapture::deviceSnapshot().d3d11OpensD3D12.load(std::memory_order_acquire);
256#else
257 return false;
258#endif
259}
260
261bool answerSinkBinContextQuery(GstQuery* query, [[maybe_unused]] GstElement* sink) noexcept
262{
263#if defined(QGC_HAS_ANY_GPU_PATH)
264 for (const HwPathDescriptor* path : GstHwPathRegistry::paths()) {
265 if (path->bridge && path->bridge().answerContextQuery(query, sink)) {
266 return true;
267 }
268 }
269#else
270 Q_UNUSED(query);
271#endif
272 return false;
273}
274
275bool proposeDeviceBoundPool(GstQuery* query, GstCaps* caps, const GstVideoInfo* vinfo, gsize size,
276 guint minBuffers) noexcept
277{
278#if defined(QGC_HAS_ANY_GPU_PATH)
279 for (const HwPathDescriptor* path : GstHwPathRegistry::paths()) {
280 if (path->proposePool && path->proposePool(query, caps, vinfo, size, minBuffers)) {
281 return true;
282 }
283 }
284#else
285 Q_UNUSED(query);
286 Q_UNUSED(caps);
287 Q_UNUSED(vinfo);
288 Q_UNUSED(size);
289 Q_UNUSED(minBuffers);
290#endif
291 return false;
292}
293
295{
296 QString out;
297#if defined(QGC_HAS_ANY_GPU_PATH)
300 const auto delta = [&now, &baseline](HwVideoBufferPath path, auto key) {
301 return now.count(path, key) - baseline.count(path, key);
302 };
303
304 // "<path>-<label>:<count>", or "<count>/<count>" for a pair, when any count is nonzero.
305 struct CounterField
306 {
307 const char* label;
308 Counter first;
309 std::optional<Counter> second = std::nullopt;
310 };
311
312 static constexpr CounterField kCounterFields[] = {
313 {"failures", Counter::MapFailures},
314 {"reuse", Counter::TextureReuse},
315 {"wait[gpu/cpu]", Counter::GpuWaits, Counter::CpuWaits},
316 {"fence-timeouts", Counter::ProducerFenceTimeouts},
317 {"image-cache[hit/miss]", Counter::ImageCacheHits, Counter::ImageCacheMisses},
318 };
319 static constexpr std::pair<GstHwPathTelemetry::HwFallbackReason, const char*> kReasons[] = {
327 };
328 forEachCompiledPath([&out, &delta](HwVideoBufferPath path) {
329 const QLatin1String pathLabel(GstHw::toString(path));
330 for (const CounterField& field : kCounterFields) {
331 const quint64 first = delta(path, field.first);
332 bool nonzero = (first > 0);
333 QString counts = QString::number(first);
334 if (field.second) {
335 const quint64 second = delta(path, *field.second);
336 nonzero = nonzero || (second > 0);
337 counts += u'/' + QString::number(second);
338 }
339 if (nonzero) {
340 out += QStringLiteral(" %1-%2:%3").arg(pathLabel, QLatin1String(field.label), counts);
341 }
342 }
343 const quint64 ewmaUs = GstHwPathTelemetry::peekMapDurationUsEwma(path);
344 if (ewmaUs > 0) {
345 out += QStringLiteral(" %1-map-us:%2").arg(pathLabel).arg(ewmaUs);
346 }
347 QString reasonBreakdown;
348 for (const auto& [reason, label] : kReasons) {
349 const quint64 n = delta(path, reason);
350 if (n > 0) {
351 reasonBreakdown += QStringLiteral("%1=%2,").arg(QLatin1String(label)).arg(n);
352 }
353 }
354 if (!reasonBreakdown.isEmpty()) {
355 reasonBreakdown.chop(1);
356 out += QStringLiteral(" %1-fallback[%2]").arg(pathLabel).arg(reasonBreakdown);
357 }
358 });
359 // None-path accumulates UnknownMemType (no allocator matched any compiled path).
361 if (unknownMem > 0) {
362 out += QStringLiteral(" None-fallback[unknown-mem=%1]").arg(unknownMem);
363 }
364#else
365 Q_UNUSED(baseline);
366#endif
367 return out;
368}
369
370} // namespace HwBuffers
HwVideoBufferPath
GPU zero-copy path a frame is imported through; None means the frame takes the CPU path.
Definition GstHwTypes.h:7
struct _GstElement GstElement
#define QGC_LOGGING_CATEGORY(name, categoryStr)
std::unique_ptr< GstElement, GstObjectDeleter > GstElementPtr
Definition GstScoped.h:60
bool has(HwVideoBufferPath path) noexcept
std::span< const HwPathDescriptor *const > paths() noexcept
Counter
Per-path event counts.
quint64 peekMapDurationUsEwma(HwVideoBufferPath path) noexcept
Snapshot snapshot() noexcept
constexpr std::size_t kPathCount
Definition GstHwTypes.h:33
constexpr const char * toString(HwVideoBufferPath path) noexcept
Definition GstHwTypes.h:37
qint64 graphicsAdapterLuid() noexcept
Definition HwBuffers.cc:231
bool d3d11OpensD3D12() noexcept
Definition HwBuffers.cc:247
bool proposeDeviceBoundPool(GstQuery *query, GstCaps *caps, const GstVideoInfo *vinfo, gsize size, guint minBuffers) noexcept
Definition HwBuffers.cc:275
constexpr char kGraphicsDeviceLostMessage[]
Definition HwBuffers.h:27
GstBusSyncReply onBusSyncMessage(GstMessage *msg) noexcept
Definition HwBuffers.cc:59
void onGraphicsDeviceRemoved()
Definition HwBuffers.cc:102
void setGraphicsDevicePublishedHandler(void(*handler)()) noexcept
Definition HwBuffers.cc:240
void * dmaBufImportDisplay() noexcept
Definition HwBuffers.cc:206
void resetCachedGpuResources()
Definition HwBuffers.cc:85
void connectMainWindow(QQuickWindow *window)
Definition HwBuffers.cc:173
void configureQtGraphics(bool softwareRendering)
Definition HwBuffers.cc:141
QString extraPathStatsSince(const GstHwPathTelemetry::Snapshot &baseline)
Definition HwBuffers.cc:294
bool graphicsDeviceLost() noexcept
Definition HwBuffers.cc:129
void onPipelineRestart()
Definition HwBuffers.cc:74
bool answerSinkBinContextQuery(GstQuery *query, GstElement *sink) noexcept
Definition HwBuffers.cc:261
bool softwareRenderingRequested() noexcept
What configureQtGraphics() was told: the user asked for software rendering (–swrast)....
Definition HwBuffers.cc:168
HwVideoBufferContext makeAdapterContext(bool gpuEnabled) noexcept
Definition HwBuffers.cc:182
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.
Every counter and fallback reason at one instant; a reader's baseline for counts since then.
quint64 count(HwVideoBufferPath path, Counter counter) const noexcept
std::atomic< bool > d3d11OpensD3D12
std::atomic< qint64 > adapterLuid