QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
GstGlVideoBuffer.cc
Go to the documentation of this file.
1#include "GstGlVideoBuffer.h"
2
3#include "CpuVideoFramePool.h"
7#include "GstHwPathRegistry.h"
9#include "GstHwVideoBuffer.h"
10#include "QGCRhiCapture.h"
11
12#if defined(QGC_HAS_GST_GLMEMORY_GPU_PATH)
13
14#include <gst/gl/gl.h>
15#include <gst/gl/gstglbasememory.h>
16#include <gst/gl/gstglmemory.h>
17#include <gst/gl/gstglsyncmeta.h>
18#include <gst/video/video.h>
19#include <private/qvideotexturehelper_p.h>
20#include <rhi/qrhi.h>
21
22#include <QtCore/QLoggingCategory>
23#include <QtCore/QScopeGuard>
24#include <QtCore/QSize>
25
26#include "QGCLoggingCategory.h"
27
28// Qt's portable GL types (GLuint et al.) — works on Linux/macOS/Android without GLES2 SDK headers.
29#include <algorithm>
30#include <array>
31#include <atomic>
32#include <utility>
33
34#include <QtGui/qopengl.h>
35
36#ifndef GL_TIMEOUT_IGNORED
37#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFFull
38#endif
39
40#include <QtGui/QOpenGLContext>
41#include <QtGui/QOpenGLExtraFunctions>
42
43QGC_LOGGING_CATEGORY(GstGlBufLog, "Video.GStreamer.HwBuffers.GstGlBuf")
44
45namespace {
46
48
49class FrameTextures final : public GstHwFrameTexturesBase
50{
51public:
52 FrameTextures(QRhi* rhi, QSize size, QVideoFrameFormat::PixelFormat pixelFormat, std::span<const GLuint> names)
53 {
54 wrapPlanes(rhi, size, pixelFormat, names);
55 }
56
57 ~FrameTextures() override { gst_clear_buffer(&_syncBuffer); }
58
60 void setSyncBuffer(GstBuffer* buffer) noexcept
61 {
62 gst_clear_buffer(&_syncBuffer);
63 _syncBuffer = buffer;
64 }
65
67 GstBuffer* releaseSyncBuffer() noexcept { return std::exchange(_syncBuffer, nullptr); }
68
69private:
70 GstBuffer* _syncBuffer = nullptr;
71};
72
74
75// An empty buffer of this path's own with a GL sync meta for @p context, as upstream's Qt sink keeps one
76// (gstqsg6material.cc): the one @p old was mapped with, when that is a bundle of this path on the same context, else a
77// new one. The frame's own buffer may carry a sync meta too, but other elements and other windows showing the frame
78// share that buffer, and setting a sync point deletes the fence the meta holds. Null when the meta can't be added.
79GstBuffer* takeSyncBuffer(QVideoFrameTexturesUPtr& old, GstGLContext* context)
80{
81 if (auto* const previous = GstHwFrameTexturesBase::reusableBundle<FrameTextures>(old)) {
82 GstBuffer* buffer = previous->releaseSyncBuffer();
83 const GstGLSyncMeta* const meta = buffer ? gst_buffer_get_gl_sync_meta(buffer) : nullptr;
84 if (meta && (meta->context == context)) {
85 return buffer;
86 }
87 gst_clear_buffer(&buffer);
88 }
89 GstBuffer* buffer = gst_buffer_new();
90 if (!gst_buffer_add_gl_sync_meta(context, buffer)) {
91 gst_clear_buffer(&buffer);
92 }
93 return buffer;
94}
95
96// Orders Qt's context after gst-gl's fence. gst_gl_sync_meta_wait() would wait inside gst-gl's own context and leave
97// Qt's unordered; GL sync objects are shared across the share group, so Qt's context waits on the GLsync server-side.
98// CPU wait when Qt's context has no sync objects or the meta carries no GLsync (gst-gl without fences).
99void waitInQtContext(GstGLSyncMeta* syncMeta, GstGLContext* glCtx)
100{
101 QOpenGLContext* qtCtx = QOpenGLContext::currentContext();
102 const auto sync = static_cast<GLsync>(syncMeta->data);
103 if (qtCtx && sync) {
104 const QSurfaceFormat format = qtCtx->format();
105 const bool hasSyncObjects = qtCtx->isOpenGLES() ? format.majorVersion() >= 3
106 : (format.version() >= qMakePair(3, 2) ||
107 qtCtx->hasExtension(QByteArrayLiteral("GL_ARB_sync")));
108 QOpenGLExtraFunctions* gl = hasSyncObjects ? qtCtx->extraFunctions() : nullptr;
109 if (gl && gl->glIsSync(sync)) {
110 gl->glWaitSync(sync, 0, GL_TIMEOUT_IGNORED);
112 return;
113 }
114 }
115 gst_gl_sync_meta_wait_cpu(syncMeta, glCtx);
117}
118
119// mapTextures() binds GLMemory only under Qt's OpenGL(ES2) QRhi, but the glupload bin still emits GLMemory under a
120// non-GL RHI (forced Vulkan): those frames take the CPU path. Streaming thread, so read the published backend rather
121// than the render-thread-owned QRhi. So do frames from a GL context outside Qt's share group, which gst-gl creates
122// when no element got the bridge's: their texture names mean nothing in Qt's context, which would sample another
123// texture or black. Records each rejected frame.
124bool admitGlMemory(GstMemory* mem, const HwVideoBufferContext&)
125{
126 const int backend = QGCRhiCapture::deviceSnapshot().backend.load(std::memory_order_acquire);
127 if ((backend >= 0) && (backend != static_cast<int>(QRhi::OpenGLES2))) {
128 static std::atomic<bool> s_warned{false};
129 QGC_HW_WARN_ONCE(GstGlBufLog, s_warned, "GLMemory frame but QRhi backend is not OpenGL — routing to CPU pool");
130 } else if (!GstGlContextBridge::sharesQtContext(GST_GL_BASE_MEMORY_CAST(mem)->context)) {
131 static std::atomic<bool> s_warnedUnshared{false};
132 QGC_HW_WARN_ONCE(GstGlBufLog, s_warnedUnshared,
133 "GLMemory from a GL context that doesn't share with Qt's — routing to CPU pool");
134 } else {
135 return true;
136 }
139 return false;
140}
141
142} // namespace
143
144bool GstGlVideoBuffer::validatePlaneHandles() const
145{
146 // Allocator-only — GLuint check needs GST_MAP_GL, too expensive on streaming thread.
147 return validatePlanes([](GstMemory* mem) { return mem && gst_is_gl_memory(mem); });
148}
149
150QVideoFrameTexturesUPtr GstGlVideoBuffer::mapTextures(QRhi& rhi, QVideoFrameTexturesUPtr& old)
151{
153 // QRhi::OpenGLES2 covers both desktop GL and GLES — Qt collapses both; there is no separate QRhi::OpenGL.
154 GstBuffer* buffer = nullptr;
155 if (!checkMapPreconditions(rhi, static_cast<int>(QRhi::OpenGLES2), GstGlBufLog(), s_diag, buffer)) {
157 }
158
159 // Defensive: custom RHI integrations may not have Qt's GL context current on QSGRenderThread entry.
160 rhi.makeThreadLocalNativeContextCurrent();
161
162 GstMemory* mem0 = gst_buffer_peek_memory(buffer, 0);
163 if (!mem0 || !gst_is_gl_memory(mem0)) {
165 }
166
168 // GST_MAP_GL (a gst-gl extension flag) OR'd with GST_MAP_READ triggers GstGLMemory upload.
169 if (!mapping.mapFrame(buffer, _videoInfo, static_cast<GstMapFlags>(GST_MAP_READ | GST_MAP_GL))) {
170 qCWarning(GstGlBufLog) << "gst_video_frame_map(GST_MAP_READ | GST_MAP_GL) failed";
174 }
175
176 // A sync point of our own, set after the GST_MAP_GL map above: glupload uploads lazily on that map, so a sync point
177 // its producer set would predate the upload.
178 GstGLContext* glCtx = GST_GL_BASE_MEMORY_CAST(mem0)->context;
179 GstBuffer* syncBuffer = glCtx ? takeSyncBuffer(old, glCtx) : nullptr;
180 const auto dropSyncBuffer = qScopeGuard([&syncBuffer] { gst_clear_buffer(&syncBuffer); });
181 if (syncBuffer) {
182 GstGLSyncMeta* const syncMeta = gst_buffer_get_gl_sync_meta(syncBuffer);
183 gst_gl_sync_meta_set_sync_point(syncMeta, glCtx);
184 waitInQtContext(syncMeta, glCtx);
185 }
186
187 const GstVideoFrame& frame = mapping.frame();
188 const int planeCount = std::clamp(int(GST_VIDEO_FRAME_N_PLANES(&frame)), 1, kMaxPlanes);
189 std::array<GLuint, kMaxPlanes> names{};
190 for (int i = 0; i < planeCount; ++i) {
191 // GST_MAP_GL maps return a *pointer to* the GLuint texture id, not the id itself.
192 const GLuint* texIdPtr = static_cast<const GLuint*>(GST_VIDEO_FRAME_PLANE_DATA(&frame, i));
193 names[i] = texIdPtr ? *texIdPtr : 0;
194 }
195
196 mapping.unmap();
197 const std::span<const GLuint> planeNames(names.data(), std::size_t(planeCount));
198
199 const GstHwMapTail tail{.path = HwVideoBufferPath::GlMemory,
200 .frameSize = _format.frameSize(),
201 .pixelFormat = _format.pixelFormat(),
202 .log = &GstGlBufLog(),
203 .diag = &s_diag};
204 // gst-gl rotates texture ids within a fixed pool: a bundle over the same ids samples the new frame unchanged.
205 QVideoFrameTexturesUPtr textures = GstHwFrameTexturesBase::finishMap<FrameTextures>(
206 *this, rhi, old, tail,
207 [&](const FrameTextures& prev) {
208 return prev.matchesImport(&rhi, tail.frameSize, tail.pixelFormat, planeNames);
209 },
210 [&] { return std::make_unique<FrameTextures>(&rhi, tail.frameSize, tail.pixelFormat, planeNames); });
211 if (auto* const bundle = GstHwFrameTexturesBase::reusableBundle<FrameTextures>(textures)) {
212 bundle->setSyncBuffer(std::exchange(syncBuffer, nullptr));
213 }
214 return textures;
215}
216
217constinit const HwPathDescriptor GstHwPaths::kGlMemory = {
219 .matches = [](GstMemory* mem) -> bool { return gst_is_gl_memory(mem); },
220 .admits = &admitGlMemory,
221 .construct = &GstHwPaths::construct<GstGlVideoBuffer>,
222 .bridge = &GstGlContextBridge::instance,
223};
224
225#endif // QGC_HAS_GST_GLMEMORY_GPU_PATH
#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)
bool mapFrame(GstBuffer *buffer, const GstVideoInfo &info, GstMapFlags flags=GST_MAP_READ)
Maps buffer with flags on the first call; false when that fails.
const GstVideoFrame & frame() const
The mapped frame; valid while mapFrame() succeeded and unmap() hasn't run.
void wrapPlanes(QRhi *rhi, QSize size, QVideoFrameFormat::PixelFormat pixelFormat, const Handles &handles, int layout=0, QRhiTexture::Flags flags={})
static QVideoFrameTexturesUPtr finishMap(GstHwVideoBuffer &source, QRhi &rhi, QVideoFrameTexturesUPtr &old, const GstHwMapTail &tail, Reuse &&reuse, Make &&make)
static FT * reusableBundle(QVideoFrameTexturesUPtr &old)
RAII timer: records mapTextures() wall time into the path's EWMA on scope exit.
QVideoFrameTexturesUPtr fail(HwVideoBufferPath path) noexcept
Records a map failure for path and returns the empty bundle mapTextures() reports it with.
@ GpuWaits
GPU-side waits on the producer's writes before sampling a frame.
@ CpuWaits
CPU-blocking waits on the producer's writes before sampling a frame.
void recordFallbackReason(HwVideoBufferPath attemptedPath, HwFallbackReason reason) noexcept
Per-(path,reason) fallback accounting; lets a bug report show why a path demoted to CPU.
void record(HwVideoBufferPath path, Counter counter) noexcept
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)
std::optional< Frame > frame(std::string_view text)
DeviceSnapshot & deviceSnapshot() noexcept
Returns the global snapshot. Atomic fields make individual reads thread-safe.
Per-call inputs of GstHwFrameTexturesBase::finishMap().
QVideoFrameFormat::PixelFormat pixelFormat
One-shot warning flags per failure cause; paths with extra causes (DMABuf, D3D, IOSurface) derive and...
std::atomic< int > backend
QRhi::Implementation cast to int (-1 = unset).