QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
GstAHardwareBufferVideoBuffer.cc
Go to the documentation of this file.
2
3#if defined(QGC_HAS_GST_AHARDWAREBUFFER_GPU_PATH)
4
5#include <android/hardware_buffer.h>
6#include <array>
7#include <atomic>
8#include <gst/android/gstandroid.h>
9#include <gst/gl/gstglsyncmeta.h>
10#include <gst/video/video.h>
11#include <limits>
12#include <private/qvideotexturehelper_p.h>
13#include <rhi/qrhi.h>
14#include <rhi/qrhi_platform.h>
15#include <span>
16
17#include <QtCore/QLoggingCategory>
18#include <QtCore/QMutex>
19#include <QtCore/QMutexLocker>
20#include <QtCore/QScopeGuard>
21#include <QtCore/QSize>
22#include <QtGui/QOpenGLContext>
23#include <QtGui/QOpenGLFunctions>
24
25#include "GstEglHelpers.h"
27#include "GstHwImportCache.h"
28#include "GstHwPathRegistry.h"
29#include "GstHwPathTelemetry.h"
30#include "GstHwVideoBuffer.h"
31#include "QGCLoggingCategory.h"
32#include "QGCRhiCapture.h"
33#include <EGL/eglext.h>
34#include <GLES2/gl2.h>
35#include <GLES2/gl2ext.h>
36
37QGC_LOGGING_CATEGORY(GstAHWBufLog, "Video.GStreamer.HwBuffers.GstAHWBuf")
38
39namespace {
40
42struct AhbDiagnostics : GstHw::MapDiagnostics
43{
44 std::atomic<bool> loggedNoFenceSync{false};
45 std::atomic<bool> loggedNoGlContext{false};
46 std::atomic<bool> loggedClientBufferFailed{false};
47 std::atomic<bool> loggedCreateImageFailed{false};
48 std::atomic<bool> loggedImageTargetFailed{false};
49
50 void reset() noexcept
51 {
53 for (std::atomic<bool>* flag : {&loggedNoFenceSync, &loggedNoGlContext, &loggedClientBufferFailed,
54 &loggedCreateImageFailed, &loggedImageTargetFailed}) {
55 flag->store(false, std::memory_order_relaxed);
56 }
57 }
58};
59
60static_assert(sizeof(AhbDiagnostics) == sizeof(GstHw::MapDiagnostics) + (5 * sizeof(std::atomic<bool>)),
61 "AhbDiagnostics::reset() must list every flag");
62
63AhbDiagnostics s_diag;
64
65constexpr const char* kNativeBufferExt = "EGL_ANDROID_image_native_buffer";
66
68constexpr int kMaxConsecutiveImportFailures = 30;
69
70// Set when the import can't work until the scene graph's device changes: the EGL display or the GL implementation
71// lacks what it needs, or the driver refused frame after frame. A frame of this path is external-OES, without a CPU
72// layout Qt could show instead, so admitAhb() then keeps frames off the path. Cleared by rearmImport().
73std::atomic<bool> s_importDisabled{false};
74std::atomic<int> s_consecutiveImportFailures{0};
75
76void disableImport(const char* why)
77{
78 if (!s_importDisabled.exchange(true, std::memory_order_relaxed)) {
79 qCWarning(GstAHWBufLog) << "AHardwareBuffer import disabled:" << why;
80 }
81}
82
83void noteImportRefused()
84{
85 if ((s_consecutiveImportFailures.fetch_add(1, std::memory_order_relaxed) + 1) >= kMaxConsecutiveImportFailures) {
86 disableImport("the driver refused frame after frame");
87 }
88}
89
90void rearmImport()
91{
92 s_importDisabled.store(false, std::memory_order_relaxed);
93 s_consecutiveImportFailures.store(0, std::memory_order_relaxed);
94 s_diag.reset();
95}
96
97// LRU cache (QRhi, AHardwareBuffer, EGLDisplay) -> (EGLImage, GL texture): MediaCodec recycles the same AHB so the
98// import stays valid, saving ~50-200 us/frame on Mali/Adreno.
99struct AhbCacheKey
100{
101 QRhi* rhi = nullptr;
102 AHardwareBuffer* ahb = nullptr;
103 EGLDisplay display = EGL_NO_DISPLAY;
104
105 bool operator==(const AhbCacheKey&) const noexcept = default;
106};
107
108struct AhbImport
109{
110 QOpenGLContext* context = nullptr; // context the texture name was generated in
111 AHardwareBuffer* ahb = nullptr; // acquired ref
112 EGLDisplay display = EGL_NO_DISPLAY;
113 EGLImageKHR image = EGL_NO_IMAGE_KHR;
114 GLuint textureName = 0;
115};
116
117void destroyAhbImport(AhbImport& e)
118{
119 if (e.image != EGL_NO_IMAGE_KHR && e.display != EGL_NO_DISPLAY && GstEglHelpers::destroyImageKHR()) {
120 GstEglHelpers::destroyImageKHR()(e.display, e.image);
121 }
122 if (e.textureName != 0) {
123 if (QOpenGLContext* ctx = QOpenGLContext::currentContext()) {
124 ctx->functions()->glDeleteTextures(1, &e.textureName);
125 }
126 }
127 if (e.ahb) {
128 AHardwareBuffer_release(e.ahb);
129 }
130}
131
132// glDeleteTextures off the owning context leaks the name (or deletes another context's), so entries removed elsewhere
133// (a reset from a non-render thread) are parked until that context is current again.
134bool ownerContextCurrent(const AhbImport& e)
135{
136 return QOpenGLContext::currentContext() == e.context;
137}
138
139constexpr std::size_t kImageCacheCapacity = 4;
141
142// Live FrameTextures pin the entry whose texture they wrap, so eviction or reset never frees a name still sampled.
143QMutex s_imageCacheMutex;
144AhbImportCache s_imageCache{destroyAhbImport, ownerContextCurrent};
145
146// QRhi cleanup callback (runs in ~QRhi on its render thread while its GL context still exists, after Qt destroyed the
147// frame bundles holding pins): drop every entry keyed on @p rhi, so a QRhi later allocated at the same address can
148// never hit a texture name from the dead context.
149void purgeImageCacheForRhi(QRhi* rhi)
150{
151 rhi->makeThreadLocalNativeContextCurrent();
152 const QMutexLocker lock(&s_imageCacheMutex);
153 s_imageCache.eraseIf([rhi](const AhbCacheKey& key, const AhbImport&) { return key.rhi == rhi; });
154 s_imageCache.drainDeferred();
155}
156
157class FrameTextures final : public GstHwFrameTexturesBase
158{
159public:
160 // Always single-plane external-OES; the GL texture name is owned by the process-wide import cache entry @p entry,
161 // which this bundle pins (shared across frames on AHB recycle).
162 FrameTextures(QRhi* rhi, QSize size, QVideoFrameFormat::PixelFormat pixelFormat, GLuint name,
163 AhbImportCache::EntryId entry)
164 : _entry(entry)
165 {
166 {
167 const QMutexLocker lock(&s_imageCacheMutex);
168 s_imageCache.pin(_entry);
169 }
170 // ExternalOES: bind GL_TEXTURE_EXTERNAL_OES + emit SamplerExternalOES, else OES_EGL_image_external samples
171 // black on GLES2.
172 wrapPlanes(rhi, size, pixelFormat, std::span<const GLuint>(&name, 1), 0, QRhiTexture::ExternalOES);
173 }
174
175 ~FrameTextures() override
176 {
177 if (_rhi) {
178 _rhi->makeThreadLocalNativeContextCurrent();
179 }
180 const QMutexLocker lock(&s_imageCacheMutex);
181 s_imageCache.unpin(_entry);
182 s_imageCache.drainDeferred();
183 }
184
185private:
186 AhbImportCache::EntryId _entry = 0;
187};
188
189// MediaCodec writes the AHB asynchronously; without a producer-side wait the EGLImage import can sample a half-written,
190// recycled buffer (tearing). MediaCodec AHB buffers carry no GstGLSyncMeta and the gstandroid memory API exposes no
191// acquire fence, so in practice no producer wait happens here; a sync meta is only present when a gst-gl element
192// produced the buffer. A consumer-side EGL fence cannot observe MediaCodec's write, so none is used.
193void waitProducerComplete(GstBuffer* buffer)
194{
195 if (GstGLSyncMeta* syncMeta = buffer ? gst_buffer_get_gl_sync_meta(buffer) : nullptr) {
196 if (GstGLContext* glObj = syncMeta->context) {
197 // CPU wait: gst_gl_sync_meta_wait() would only order the producer's own context, not Qt's.
198 gst_gl_sync_meta_wait_cpu(syncMeta, glObj);
199 return;
200 }
201 }
202
203 QGC_HW_WARN_ONCE(GstAHWBufLog, s_diag.loggedNoFenceSync,
204 "AHardwareBuffer: no GstGLSyncMeta producer fence; frames may tear on recycle (no consumer-side "
205 "barrier can substitute)");
206}
207
208} // namespace
209
210GstAHardwareBufferVideoBuffer::GstAHardwareBufferVideoBuffer(GstSample* sample, const GstVideoInfo& videoInfo,
211 const QVideoFrameFormat& format, EGLDisplay eglDisplay)
212 : GstHwVideoBuffer(sample, videoInfo, format)
213 , _eglDisplay(eglDisplay)
214{}
215
216// The AHB is imported directly as an EGLImage (no SurfaceTexture::updateTexImage()), so no per-buffer
217// getTransformMatrix() exists here; external-OES sampling of a directly-imported buffer is top-left origin while GL
218// texcoords are bottom-left, so apply the static Y-flip Qt's SurfaceTexture path also applies (flipV, row-major).
219QMatrix4x4 GstAHardwareBufferVideoBuffer::externalTextureMatrix() const
220{
221 // GStreamer exposes no per-buffer decoder transform at this layer, so we apply the static external-OES Y-flip
222 // (top-left vs GL bottom-left origin). If a device ever needs crop-inset/rotation, source it from GstVideoCropMeta.
223 static const QMatrix4x4 flipV(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
224 0.0f, 1.0f);
225 return flipV;
226}
227
228bool GstAHardwareBufferVideoBuffer::validatePlaneHandles() const
229{
230 // Qt 6.10-6.12 has the right ExternalOES rendering path, but upstream GStreamer still does not expose this
231 // AHardwareBuffer memory API. If a future GStreamer/Qt release grows an official API, replace these vendor hooks.
232 return validatePlanes([](GstMemory* mem) {
233 if (!mem || !gst_is_ahardware_buffer_memory(mem))
234 return false;
235 return gst_ahardware_buffer_memory_get_buffer(GST_AHARDWARE_BUFFER_MEMORY_CAST(mem)) != nullptr;
236 });
237}
238
239// Callable from any thread: entries whose context is not current here are destroyed on its render thread later.
240void GstAHardwareBufferVideoBuffer::resetImageCache()
241{
242 const QMutexLocker lock(&s_imageCacheMutex);
243 s_imageCache.clear();
244 s_imageCache.drainDeferred();
245}
246
247QVideoFrameTexturesUPtr GstAHardwareBufferVideoBuffer::mapTextures(QRhi& rhi, QVideoFrameTexturesUPtr& old)
248{
249 GstBuffer* buffer = nullptr;
250 if (!checkMapPreconditions(rhi, static_cast<int>(QRhi::OpenGLES2), GstAHWBufLog(), s_diag, buffer)) {
252 }
253
254 QOpenGLContext* glContext = GstEglHelpers::bindRhiContext(rhi);
255 if (!glContext) {
256 QGC_HW_WARN_ONCE(GstAHWBufLog, s_diag.loggedNoGlContext,
257 "QRhi's GL context can't be made current; frame not shown");
259 }
260 // Sampling an EGLImage created on a foreign display silently returns black.
261 const EGLDisplay eglDpy = GstEglHelpers::renderDisplay(glContext, _eglDisplay);
262 if (eglDpy == EGL_NO_DISPLAY) {
264 }
265
266 GstMemory* mem0 = gst_buffer_peek_memory(buffer, 0);
267 if (!mem0 || !gst_is_ahardware_buffer_memory(mem0)) {
269 }
270
271 if (!GstEglHelpers::displaySupportsExtension(eglDpy, kNativeBufferExt)) {
272 disableImport("EGL_ANDROID_image_native_buffer unavailable");
274 }
275
276 static const auto eglGetNativeClientBufferANDROID_ =
277 reinterpret_cast<PFNEGLGETNATIVECLIENTBUFFERANDROIDPROC>(eglGetProcAddress("eglGetNativeClientBufferANDROID"));
278 static const auto eglCreateImageKHR_ =
279 reinterpret_cast<PFNEGLCREATEIMAGEKHRPROC>(eglGetProcAddress("eglCreateImageKHR"));
280 const auto eglDestroyImageKHR_ = GstEglHelpers::destroyImageKHR();
281 const auto glEGLImageTargetTexture2DOES_ = GstEglHelpers::imageTargetTexture2D();
282
283 if (!eglGetNativeClientBufferANDROID_ || !eglCreateImageKHR_ || !eglDestroyImageKHR_ ||
284 !glEGLImageTargetTexture2DOES_) {
285 disableImport("required EGL/GL functions unavailable");
287 }
288
289 AHardwareBuffer* ahwb = gst_ahardware_buffer_memory_get_buffer(GST_AHARDWARE_BUFFER_MEMORY_CAST(mem0));
290 if (!ahwb) {
291 qCWarning(GstAHWBufLog) << "gst_ahardware_buffer_memory_get_buffer returned null";
293 }
294
295 // Block until the producer's GPU write completes before importing/sampling the recycled AHB.
296 waitProducerComplete(buffer);
297
298 QOpenGLFunctions functions(glContext);
299
300 const AhbCacheKey key{&rhi, ahwb, eglDpy};
301 GLuint name = 0;
302 AhbImportCache::EntryId entry = 0;
303 {
304 const QMutexLocker lock(&s_imageCacheMutex);
305 if (const auto hit = s_imageCache.find(key)) {
306 name = hit.resource->textureName;
307 entry = hit.id;
308 s_imageCache.pin(entry); // provisional pin: hold the entry across the unlocked gap below
310 }
311 }
312
313 if (name == 0) {
315
316 EGLClientBuffer clientBuffer = eglGetNativeClientBufferANDROID_(ahwb);
317 if (!clientBuffer) {
318 QGC_HW_WARN_ONCE(GstAHWBufLog, s_diag.loggedClientBufferFailed,
319 "eglGetNativeClientBufferANDROID returned null; frame not shown");
320 noteImportRefused();
322 }
323
324 const EGLint attribs[] = {EGL_NONE};
325 EGLImageKHR image =
326 eglCreateImageKHR_(eglDpy, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID, clientBuffer, attribs);
327 if (image == EGL_NO_IMAGE_KHR) {
328 QGC_HW_WARN_ONCE(GstAHWBufLog, s_diag.loggedCreateImageFailed,
329 "eglCreateImageKHR failed, err=" << Qt::hex << eglGetError() << "; frame not shown");
330 noteImportRefused();
332 }
333
334 // Errors still pending from earlier GL calls would read as this import failing. Bounded: a lost context
335 // reports an error forever.
336 for (int i = 0; (i < 8) && (functions.glGetError() != GL_NO_ERROR); ++i) {
337 }
338 functions.glGenTextures(1, &name);
339 functions.glBindTexture(GL_TEXTURE_EXTERNAL_OES, name);
340 glEGLImageTargetTexture2DOES_(GL_TEXTURE_EXTERNAL_OES, image);
341 // A failed bind leaves an empty texture; cached, it would show black whenever the decoder recycles this AHB.
342 if (const GLenum glErr = functions.glGetError(); glErr != GL_NO_ERROR) {
343 QGC_HW_WARN_ONCE(GstAHWBufLog, s_diag.loggedImageTargetFailed,
344 "glEGLImageTargetTexture2DOES failed, glError=" << Qt::hex << glErr << "eglError="
345 << eglGetError() << "; frame not shown");
346 functions.glDeleteTextures(1, &name);
347 eglDestroyImageKHR_(eglDpy, image);
348 noteImportRefused();
350 }
351
352 const QMutexLocker lock(&s_imageCacheMutex);
353 // Real race: s_imageCache is process-wide and each window's render thread can import the same recycled ahb, so
354 // re-check and reuse theirs if present.
355 if (const auto existing = s_imageCache.find(key)) {
356 eglDestroyImageKHR_(eglDpy, image);
357 functions.glDeleteTextures(1, &name);
358 name = existing.resource->textureName;
359 entry = existing.id;
360 } else {
361 AHardwareBuffer_acquire(ahwb);
362 const auto inserted = s_imageCache.insert(key, AhbImport{glContext, ahwb, eglDpy, image, name});
363 if (inserted) {
364 entry = inserted.id;
365 // Keyed: registered once per QRhi however many entries it inserts.
366 rhi.addCleanupCallback(&s_imageCache, purgeImageCacheForRhi);
367 } else {
368 // Every entry is pinned by a live frame; insert() already released this import.
369 qCWarning(GstAHWBufLog) << "AHB texture cache full and all entries in use; skipping frame";
370 name = 0;
371 }
372 }
373 s_imageCache.pin(entry); // provisional pin (no-op if entry == 0)
374 }
375
376 if (name == 0) {
378 }
379 s_consecutiveImportFailures.store(0, std::memory_order_relaxed);
380
381 // Provisional pin keeps LRU eviction from freeing the name before FrameTextures takes its own pin.
382 const auto pinGuard = qScopeGuard([&] {
383 const QMutexLocker lock(&s_imageCacheMutex);
384 s_imageCache.unpin(entry);
385 s_imageCache.drainDeferred();
386 });
387
389 .frameSize = _format.frameSize(),
390 .pixelFormat = QVideoFrameFormat::Format_SamplerExternalOES,
391 .textureFlags = QRhiTexture::ExternalOES,
392 .log = &GstAHWBufLog(),
393 .diag = &s_diag};
394 // The import cache returns the same texture name when MediaCodec recycles an AHB.
396 *this, rhi, old, tail,
397 [&](const FrameTextures& prev) {
398 return prev.matchesImport(&rhi, tail.frameSize, tail.pixelFormat, std::span<const GLuint>(&name, 1));
399 },
400 [&] { return std::make_unique<FrameTextures>(&rhi, tail.frameSize, tail.pixelFormat, name, entry); });
401}
402
403namespace {
404
405// GL_TEXTURE_EXTERNAL_OES needs the SamplerExternalOES pixel format for Qt's shader path. QVideoFrameFormat has no
406// pixel-format setter, so rebuild the format around it.
407QVideoFrameFormat externalOesFormat(const QVideoFrameFormat& format)
408{
409 QVideoFrameFormat external(format.frameSize(), QVideoFrameFormat::Format_SamplerExternalOES);
410 external.setViewport(format.viewport());
411 external.setScanLineDirection(format.scanLineDirection());
412 external.setStreamFrameRate(format.streamFrameRate());
413 external.setColorSpace(format.colorSpace());
414 external.setColorTransfer(format.colorTransfer());
415 external.setColorRange(format.colorRange());
416 external.setMirrored(format.isMirrored());
417 external.setRotation(format.rotation());
418 external.setMaxLuminance(format.maxLuminance());
419 return external;
420}
421
422void prepareAhbContext(HwVideoBufferContext& context)
423{
424 context.ahbEglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
425 if (context.ahbEglDisplay == EGL_NO_DISPLAY) {
426 qCWarning(GstAHWBufLog) << "AHardwareBuffer path: EGLDisplay unavailable";
427 }
428}
429
430// Streaming thread, for every frame. A frame kept off the path goes to the sink's CPU path, which shows it only if
431// its memory maps on the CPU; wrapped, a frame that then fails to import isn't shown at all.
432bool admitAhb(GstMemory*, const HwVideoBufferContext& context)
433{
435 // The import binds an external-OES texture in Qt's OpenGL context: nothing to import into under another QRhi.
436 const int backend = QGCRhiCapture::deviceSnapshot().backend.load(std::memory_order_acquire);
437 const bool otherRenderer = (backend >= 0) && (backend != static_cast<int>(QRhi::OpenGLES2));
438 if ((context.ahbEglDisplay != EGL_NO_DISPLAY) && !otherRenderer &&
439 !s_importDisabled.load(std::memory_order_relaxed)) {
440 return true;
441 }
444 (context.ahbEglDisplay == EGL_NO_DISPLAY) ? HwFallbackReason::NoExt : HwFallbackReason::ImportUnsupported);
445 return false;
446}
447
448} // namespace
449
450constinit const HwPathDescriptor GstHwPaths::kAHardwareBuffer = {
452 .matches = [](GstMemory* mem) -> bool { return gst_is_ahardware_buffer_memory(mem); },
453 .admits = &admitAhb,
454 .construct = [](GstSample* sample, const GstVideoInfo& info, QVideoFrameFormat format,
455 const HwVideoBufferContext& context) -> std::unique_ptr<GstHwVideoBuffer> {
456 return std::make_unique<GstAHardwareBufferVideoBuffer>(sample, info, externalOesFormat(format),
457 context.ahbEglDisplay);
458 },
459 .prepareContext = &prepareAhbContext,
460 .resetCaches =
461 [] {
462 GstAHardwareBufferVideoBuffer::resetImageCache();
463 GstEglHelpers::resetExtensionCache();
464 rearmImport();
465 },
466};
467
468#endif // QGC_HAS_GST_AHARDWAREBUFFER_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)
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)
Common base for GStreamer-backed QHwVideoBuffer subclasses.
QVideoFrameTexturesUPtr fail(HwVideoBufferPath path) noexcept
Records a map failure for path and returns the empty bundle mapTextures() reports it with.
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
HwFallbackReason
Specific cause a GPU path was rejected for a sample; surfaced as a per-(path,reason) breakdown.
QByteArray format(const QList< LogEntry > &entries, int fmt)
DeviceSnapshot & deviceSnapshot() noexcept
Returns the global snapshot. Atomic fields make individual reads thread-safe.
Per-call inputs of GstHwFrameTexturesBase::finishMap().
One-shot warning flags per failure cause; paths with extra causes (DMABuf, D3D, IOSurface) derive and...
void * ahbEglDisplay
EGLDisplay for the AHardwareBuffer path.
Definition GstHwTypes.h:28
std::atomic< int > backend
QRhi::Implementation cast to int (-1 = unset).