3#if defined(QGC_HAS_GST_AHARDWAREBUFFER_GPU_PATH)
5#include <android/hardware_buffer.h>
8#include <gst/android/gstandroid.h>
9#include <gst/gl/gstglsyncmeta.h>
10#include <gst/video/video.h>
12#include <private/qvideotexturehelper_p.h>
14#include <rhi/qrhi_platform.h>
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>
33#include <EGL/eglext.h>
35#include <GLES2/gl2ext.h>
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};
53 for (std::atomic<bool>* flag : {&loggedNoFenceSync, &loggedNoGlContext, &loggedClientBufferFailed,
54 &loggedCreateImageFailed, &loggedImageTargetFailed}) {
55 flag->store(
false, std::memory_order_relaxed);
60static_assert(
sizeof(AhbDiagnostics) ==
sizeof(
GstHw::MapDiagnostics) + (5 *
sizeof(std::atomic<bool>)),
61 "AhbDiagnostics::reset() must list every flag");
65constexpr const char* kNativeBufferExt =
"EGL_ANDROID_image_native_buffer";
68constexpr int kMaxConsecutiveImportFailures = 30;
73std::atomic<bool> s_importDisabled{
false};
74std::atomic<int> s_consecutiveImportFailures{0};
76void disableImport(
const char* why)
78 if (!s_importDisabled.exchange(
true, std::memory_order_relaxed)) {
79 qCWarning(GstAHWBufLog) <<
"AHardwareBuffer import disabled:" << why;
83void noteImportRefused()
85 if ((s_consecutiveImportFailures.fetch_add(1, std::memory_order_relaxed) + 1) >= kMaxConsecutiveImportFailures) {
86 disableImport(
"the driver refused frame after frame");
92 s_importDisabled.store(
false, std::memory_order_relaxed);
93 s_consecutiveImportFailures.store(0, std::memory_order_relaxed);
103 EGLDisplay display = EGL_NO_DISPLAY;
105 bool operator==(
const AhbCacheKey&)
const noexcept =
default;
110 QOpenGLContext* context =
nullptr;
112 EGLDisplay display = EGL_NO_DISPLAY;
113 EGLImageKHR image = EGL_NO_IMAGE_KHR;
114 GLuint textureName = 0;
117void destroyAhbImport(AhbImport& e)
119 if (e.image != EGL_NO_IMAGE_KHR && e.display != EGL_NO_DISPLAY && GstEglHelpers::destroyImageKHR()) {
120 GstEglHelpers::destroyImageKHR()(e.display, e.image);
122 if (e.textureName != 0) {
123 if (QOpenGLContext* ctx = QOpenGLContext::currentContext()) {
124 ctx->functions()->glDeleteTextures(1, &e.textureName);
128 AHardwareBuffer_release(e.ahb);
134bool ownerContextCurrent(
const AhbImport& e)
136 return QOpenGLContext::currentContext() == e.context;
139constexpr std::size_t kImageCacheCapacity = 4;
143QMutex s_imageCacheMutex;
144AhbImportCache s_imageCache{destroyAhbImport, ownerContextCurrent};
149void purgeImageCacheForRhi(QRhi* rhi)
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();
162 FrameTextures(QRhi* rhi, QSize size, QVideoFrameFormat::PixelFormat pixelFormat, GLuint name,
163 AhbImportCache::EntryId entry)
167 const QMutexLocker lock(&s_imageCacheMutex);
168 s_imageCache.pin(_entry);
172 wrapPlanes(rhi, size, pixelFormat, std::span<const GLuint>(&name, 1), 0, QRhiTexture::ExternalOES);
175 ~FrameTextures()
override
178 _rhi->makeThreadLocalNativeContextCurrent();
180 const QMutexLocker lock(&s_imageCacheMutex);
181 s_imageCache.unpin(_entry);
182 s_imageCache.drainDeferred();
186 AhbImportCache::EntryId _entry = 0;
193void waitProducerComplete(GstBuffer* buffer)
195 if (GstGLSyncMeta* syncMeta = buffer ? gst_buffer_get_gl_sync_meta(buffer) :
nullptr) {
196 if (GstGLContext* glObj = syncMeta->context) {
198 gst_gl_sync_meta_wait_cpu(syncMeta, glObj);
204 "AHardwareBuffer: no GstGLSyncMeta producer fence; frames may tear on recycle (no consumer-side "
205 "barrier can substitute)");
210GstAHardwareBufferVideoBuffer::GstAHardwareBufferVideoBuffer(GstSample* sample,
const GstVideoInfo& videoInfo,
211 const QVideoFrameFormat& format, EGLDisplay eglDisplay)
213 , _eglDisplay(eglDisplay)
219QMatrix4x4 GstAHardwareBufferVideoBuffer::externalTextureMatrix()
const
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,
228bool GstAHardwareBufferVideoBuffer::validatePlaneHandles()
const
232 return validatePlanes([](GstMemory* mem) {
233 if (!mem || !gst_is_ahardware_buffer_memory(mem))
235 return gst_ahardware_buffer_memory_get_buffer(GST_AHARDWARE_BUFFER_MEMORY_CAST(mem)) !=
nullptr;
240void GstAHardwareBufferVideoBuffer::resetImageCache()
242 const QMutexLocker lock(&s_imageCacheMutex);
243 s_imageCache.clear();
244 s_imageCache.drainDeferred();
247QVideoFrameTexturesUPtr GstAHardwareBufferVideoBuffer::mapTextures(QRhi& rhi, QVideoFrameTexturesUPtr& old)
249 GstBuffer* buffer =
nullptr;
250 if (!checkMapPreconditions(rhi,
static_cast<int>(QRhi::OpenGLES2), GstAHWBufLog(), s_diag, buffer)) {
254 QOpenGLContext* glContext = GstEglHelpers::bindRhiContext(rhi);
257 "QRhi's GL context can't be made current; frame not shown");
261 const EGLDisplay eglDpy = GstEglHelpers::renderDisplay(glContext, _eglDisplay);
262 if (eglDpy == EGL_NO_DISPLAY) {
266 GstMemory* mem0 = gst_buffer_peek_memory(buffer, 0);
267 if (!mem0 || !gst_is_ahardware_buffer_memory(mem0)) {
271 if (!GstEglHelpers::displaySupportsExtension(eglDpy, kNativeBufferExt)) {
272 disableImport(
"EGL_ANDROID_image_native_buffer unavailable");
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();
283 if (!eglGetNativeClientBufferANDROID_ || !eglCreateImageKHR_ || !eglDestroyImageKHR_ ||
284 !glEGLImageTargetTexture2DOES_) {
285 disableImport(
"required EGL/GL functions unavailable");
289 AHardwareBuffer* ahwb = gst_ahardware_buffer_memory_get_buffer(GST_AHARDWARE_BUFFER_MEMORY_CAST(mem0));
291 qCWarning(GstAHWBufLog) <<
"gst_ahardware_buffer_memory_get_buffer returned null";
296 waitProducerComplete(buffer);
298 QOpenGLFunctions functions(glContext);
300 const AhbCacheKey key{&rhi, ahwb, eglDpy};
302 AhbImportCache::EntryId entry = 0;
304 const QMutexLocker lock(&s_imageCacheMutex);
305 if (
const auto hit = s_imageCache.find(key)) {
306 name = hit.resource->textureName;
308 s_imageCache.pin(entry);
316 EGLClientBuffer clientBuffer = eglGetNativeClientBufferANDROID_(ahwb);
319 "eglGetNativeClientBufferANDROID returned null; frame not shown");
324 const EGLint attribs[] = {EGL_NONE};
326 eglCreateImageKHR_(eglDpy, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID, clientBuffer, attribs);
327 if (image == EGL_NO_IMAGE_KHR) {
329 "eglCreateImageKHR failed, err=" << Qt::hex << eglGetError() <<
"; frame not shown");
336 for (
int i = 0; (i < 8) && (functions.glGetError() != GL_NO_ERROR); ++i) {
338 functions.glGenTextures(1, &name);
339 functions.glBindTexture(GL_TEXTURE_EXTERNAL_OES, name);
340 glEGLImageTargetTexture2DOES_(GL_TEXTURE_EXTERNAL_OES, image);
342 if (
const GLenum glErr = functions.glGetError(); glErr != GL_NO_ERROR) {
344 "glEGLImageTargetTexture2DOES failed, glError=" << Qt::hex << glErr <<
"eglError="
345 << eglGetError() <<
"; frame not shown");
346 functions.glDeleteTextures(1, &name);
347 eglDestroyImageKHR_(eglDpy, image);
352 const QMutexLocker lock(&s_imageCacheMutex);
355 if (
const auto existing = s_imageCache.find(key)) {
356 eglDestroyImageKHR_(eglDpy, image);
357 functions.glDeleteTextures(1, &name);
358 name = existing.resource->textureName;
361 AHardwareBuffer_acquire(ahwb);
362 const auto inserted = s_imageCache.insert(key, AhbImport{glContext, ahwb, eglDpy, image, name});
366 rhi.addCleanupCallback(&s_imageCache, purgeImageCacheForRhi);
369 qCWarning(GstAHWBufLog) <<
"AHB texture cache full and all entries in use; skipping frame";
373 s_imageCache.pin(entry);
379 s_consecutiveImportFailures.store(0, std::memory_order_relaxed);
382 const auto pinGuard = qScopeGuard([&] {
383 const QMutexLocker lock(&s_imageCacheMutex);
384 s_imageCache.unpin(entry);
385 s_imageCache.drainDeferred();
389 .frameSize = _format.frameSize(),
390 .pixelFormat = QVideoFrameFormat::Format_SamplerExternalOES,
391 .textureFlags = QRhiTexture::ExternalOES,
392 .log = &GstAHWBufLog(),
396 *
this, rhi, old, tail,
397 [&](
const FrameTextures& prev) {
398 return prev.matchesImport(&rhi, tail.frameSize, tail.pixelFormat, std::span<const GLuint>(&name, 1));
400 [&] {
return std::make_unique<FrameTextures>(&rhi, tail.frameSize, tail.pixelFormat, name, entry); });
407QVideoFrameFormat externalOesFormat(
const QVideoFrameFormat& format)
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());
426 qCWarning(GstAHWBufLog) <<
"AHardwareBuffer path: EGLDisplay unavailable";
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)) {
444 (context.
ahbEglDisplay == EGL_NO_DISPLAY) ? HwFallbackReason::NoExt : HwFallbackReason::ImportUnsupported);
450constinit const HwPathDescriptor GstHwPaths::kAHardwareBuffer = {
452 .matches = [](GstMemory* mem) ->
bool {
return gst_is_ahardware_buffer_memory(mem); },
454 .construct = [](GstSample* sample,
const GstVideoInfo& info, QVideoFrameFormat
format,
456 return std::make_unique<GstAHardwareBufferVideoBuffer>(sample, info, externalOesFormat(format),
459 .prepareContext = &prepareAhbContext,
462 GstAHardwareBufferVideoBuffer::resetImageCache();
463 GstEglHelpers::resetExtensionCache();
#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.
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.
std::atomic< int > backend
QRhi::Implementation cast to int (-1 = unset).