QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
GstDmaBufVideoBuffer.cc
Go to the documentation of this file.
2
4#include "GstEglHelpers.h"
6#include "GstHwPathRegistry.h"
8#include "GstHwVideoBuffer.h"
9#include "GstQtDmaBufImport.h"
10#include "QGCRhiCapture.h"
11
12#if defined(QGC_HAS_GST_DMABUF_GPU_PATH)
13
14#include <gst/allocators/gstdmabuf.h>
15#include <gst/video/video.h>
16#include <rhi/qrhi.h>
17
18#include <QtCore/QLoggingCategory>
19#include <QtCore/QMutex>
20#include <QtCore/QMutexLocker>
21#include <QtGui/QGuiApplication>
22#include <QtGui/QOpenGLContext>
23#include <QtGui/QOpenGLFunctions>
24
25#include "QGCLoggingCategory.h"
26#if GST_CHECK_VERSION(1, 24, 0)
27#include <gst/video/video-info-dma.h>
28#endif
29
30#include <algorithm>
31#include <array>
32#include <atomic>
33#include <cerrno>
34#include <drm_fourcc.h>
35#include <limits>
36#include <memory>
37#include <poll.h>
38#include <span>
39#include <sys/vfs.h>
40#include <unistd.h>
41
42// Producer dma-buf fence export: optional. The header exists on Ubuntu 22.04 but predates the
43// EXPORT_SYNC_FILE uAPI (kernel ~6.0), so gate on the ioctl token, not just header presence.
44#if __has_include(<linux/dma-buf.h>)
45#include <linux/dma-buf.h>
46#include <sys/ioctl.h>
47#ifdef DMA_BUF_IOCTL_EXPORT_SYNC_FILE
48#define QGC_HAS_DMABUF_EXPORT_SYNC 1
49#endif
50#endif
51
52#ifndef EGL_ANDROID_native_fence_sync
53#define EGL_SYNC_NATIVE_FENCE_ANDROID 0x3144
54#define EGL_SYNC_NATIVE_FENCE_FD_ANDROID 0x3145
55#define EGL_NO_NATIVE_FENCE_FD_ANDROID -1
56#endif
57
58QGC_LOGGING_CATEGORY(GstDmaBufLog, "Video.GStreamer.HwBuffers.GstDmaBuf")
59
60namespace {
61
63
65struct DmaBufDiagnostics : GstHw::MapDiagnostics
66{
67 std::atomic<bool> loggedNoEglContext{false};
68 std::atomic<bool> loggedLayoutRejected{false};
69 std::atomic<bool> loggedTiledCpuMap{false};
70 std::atomic<bool> loggedProducerWaitTimeout{false};
71 std::atomic<bool> loggedExplicitFence{false};
72 std::atomic<bool> loggedVulkanSyncRefused{false};
73
74 void reset() noexcept
75 {
77 for (std::atomic<bool>* flag : {&loggedNoEglContext, &loggedLayoutRejected, &loggedTiledCpuMap,
78 &loggedProducerWaitTimeout, &loggedExplicitFence, &loggedVulkanSyncRefused}) {
79 flag->store(false, std::memory_order_relaxed);
80 }
81 }
82};
83
84static_assert(sizeof(DmaBufDiagnostics) == sizeof(GstHw::MapDiagnostics) + (6 * sizeof(std::atomic<bool>)),
85 "DmaBufDiagnostics::reset() must list every flag");
86
87DmaBufDiagnostics s_diag;
88
89// Set when an import fails in a way no later frame avoids: EGL_BAD_MATCH from a broken EGL/VA-API combination
90// (QTBUG-112312), or a driver rejecting the stream's layout frame after frame. Qt's importer warns on every failed
91// frame, so the latch also bounds that log. Short-circuits mapTextures() and validatePlaneHandles().
92std::atomic<bool> s_importDisabled{false};
93
95struct ImportLayout
96{
97 guint64 modifier = 0;
98 QVideoFrameFormat::PixelFormat pixelFormat = QVideoFrameFormat::Format_Invalid;
99 QSize size;
100
101 friend bool operator==(const ImportLayout&, const ImportLayout&) = default;
102};
103
106class ImportFailureRuns
107{
108public:
110 int noteFailure(const ImportLayout& layout)
111 {
112 const QMutexLocker lock(&_mutex);
113 Run* run = find(layout);
114 if (!run) {
115 // A free slot, else the shortest of the other layouts' runs.
116 run = std::min_element(_runs.begin(), _runs.end(),
117 [](const Run& a, const Run& b) { return a.failures < b.failures; });
118 *run = {.layout = layout};
119 }
120 return ++run->failures;
121 }
122
123 void noteSuccess(const ImportLayout& layout)
124 {
125 const QMutexLocker lock(&_mutex);
126 if (Run* run = find(layout)) {
127 run->failures = 0;
128 }
129 }
130
131 void clear()
132 {
133 const QMutexLocker lock(&_mutex);
134 _runs = {};
135 }
136
137private:
138 struct Run
139 {
140 ImportLayout layout;
141 int failures = 0;
142 };
143
144 Run* find(const ImportLayout& layout)
145 {
146 const auto run = std::find_if(_runs.begin(), _runs.end(), [&layout](const Run& candidate) {
147 return (candidate.failures > 0) && (candidate.layout == layout);
148 });
149 return (run != _runs.end()) ? run : nullptr;
150 }
151
152 QMutex _mutex;
153 std::array<Run, 4> _runs{};
154};
155
156ImportFailureRuns s_importFailures;
157
158constexpr const char* kModifiersExt = "EGL_EXT_image_dma_buf_import_modifiers";
159constexpr const char* kNativeFenceExt = "EGL_ANDROID_native_fence_sync";
160
161void disableImport(GstHwPathTelemetry::HwFallbackReason reason, const char* cause)
162{
163 if (!s_importDisabled.exchange(true, std::memory_order_relaxed)) {
165 qCWarning(GstDmaBufLog) << cause << "— DMABuf zero-copy disabled until the scene graph is recreated";
166 }
167}
168
171void noteLayoutImportOutcome(const ImportLayout& layout, bool tiled, GstDmaBufVideoBuffer::ImportOutcome outcome)
172{
173 using ImportOutcome = GstDmaBufVideoBuffer::ImportOutcome;
174 switch (outcome) {
175 case ImportOutcome::Imported:
176 s_importFailures.noteSuccess(layout);
177 return;
178 case ImportOutcome::Unrecoverable:
180 "Qt's DMABuf importer hit EGL_BAD_MATCH (broken EGL/driver combination)");
181 return;
182 case ImportOutcome::Rejected:
185 break;
186 case ImportOutcome::NotImportable:
187 // Qt shows a LINEAR frame through map() instead, and another QRhi may import it. A tiled one is not shown
188 // at all, so only renegotiating without DMABuf brings its stream back.
189 if (!tiled) {
190 return;
191 }
192 break;
193 }
194 if (s_importFailures.noteFailure(layout) >= GstDmaBufVideoBuffer::kMaxConsecutiveImportFailures) {
195 disableImport(GstHwPathTelemetry::HwFallbackReason::MapFailed, "Every recent DMABuf import of a stream failed");
196 }
197}
198
199// RPi eglfs quirk: V3D EGL implicitly converts YUYV/UYVY DMABuf to RGBA, so declare RGBA8888 to pick Qt's RGB shader
200// and avoid a double YUV->RGB (mirrors Qt's eglfs branch). The import then uses the packed-YUV fourcc for the whole
201// image.
202quint32 eglfsPackedYuvFourcc(QVideoFrameFormat::PixelFormat format)
203{
204 static const bool isEglfsQPA = QGuiApplication::platformName() == QLatin1String("eglfs");
205 if (!isEglfsQPA) {
206 return 0;
207 }
208 if (format == QVideoFrameFormat::Format_YUYV) {
209 return DRM_FORMAT_YUYV;
210 }
211 if (format == QVideoFrameFormat::Format_UYVY) {
212 return DRM_FORMAT_UYVY;
213 }
214 return 0;
215}
216
217QVideoFrameFormat withPixelFormat(const QVideoFrameFormat& format, QVideoFrameFormat::PixelFormat pixelFormat)
218{
219 QVideoFrameFormat out(format.frameSize(), pixelFormat);
220 out.setStreamFrameRate(format.streamFrameRate());
221 out.setColorRange(format.colorRange());
222 out.setColorSpace(format.colorSpace());
223 out.setColorTransfer(format.colorTransfer());
224 out.setViewport(format.viewport());
225 return out;
226}
227
228// Best-effort GPU-side wait on the producer's fences: export a sync_file from each dma-buf, import it as an
229// EGL_SYNC_NATIVE_FENCE_ANDROID sync and eglWaitSyncKHR in Qt's (current) context. True only when every plane's
230// dma-buf got a confirmed server-side wait, which makes the CPU barrier redundant.
231bool tryExplicitFenceWait(EGLDisplay eglDpy, GstBuffer* buffer)
232{
233#if defined(QGC_HAS_DMABUF_EXPORT_SYNC)
234 if (!GstEglHelpers::displaySupportsExtension(eglDpy, kNativeFenceExt)) {
235 return false;
236 }
237 static const auto createSyncKHR = reinterpret_cast<PFNEGLCREATESYNCKHRPROC>(eglGetProcAddress("eglCreateSyncKHR"));
238 static const auto waitSyncKHR = reinterpret_cast<PFNEGLWAITSYNCKHRPROC>(eglGetProcAddress("eglWaitSyncKHR"));
239 static const auto destroySyncKHR =
240 reinterpret_cast<PFNEGLDESTROYSYNCKHRPROC>(eglGetProcAddress("eglDestroySyncKHR"));
241 if (!createSyncKHR || !waitSyncKHR || !destroySyncKHR) {
242 return false;
243 }
244
245 int lastFd = -1;
246 for (guint i = 0; i < gst_buffer_n_memory(buffer); ++i) {
247 const int dmaFd = gst_dmabuf_memory_get_fd(gst_buffer_peek_memory(buffer, i));
248 if (dmaFd < 0 || dmaFd == lastFd) {
249 continue;
250 }
251 lastFd = dmaFd;
252 dma_buf_export_sync_file req = {};
253 req.flags = DMA_BUF_SYNC_READ; // wait only on writers (the decoder), not on prior readers
254 req.fd = -1;
255 if (ioctl(dmaFd, DMA_BUF_IOCTL_EXPORT_SYNC_FILE, &req) != 0 || req.fd < 0) {
256 return false;
257 }
258 // EGL owns req.fd once the sync is created (closed by eglDestroySync); close it ourselves only on failure.
259 const EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, req.fd, EGL_NONE};
260 EGLSyncKHR sync = createSyncKHR(eglDpy, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
261 if (sync == EGL_NO_SYNC_KHR) {
262 ::close(req.fd);
263 return false;
264 }
265 const EGLint waited = waitSyncKHR(eglDpy, sync, 0);
266 destroySyncKHR(eglDpy, sync);
267 if (waited != EGL_TRUE) {
268 return false;
269 }
270 }
271 if (!s_diag.loggedExplicitFence.exchange(true, std::memory_order_relaxed)) {
272 qCDebug(GstDmaBufLog) << "waiting on the producer's dma-buf fences GPU-side (CPU barrier skipped)";
273 }
275 return true;
276#else
277 Q_UNUSED(eglDpy);
278 Q_UNUSED(buffer);
279 return false;
280#endif
281}
282
283// Bounded so a GPU hang cannot wedge Qt's render thread.
284constexpr int kProducerWaitTimeoutMs = 100;
285
286// CPU-side barrier on the producer's implicit write fences: poll(POLLIN) on a dma-buf fd returns once its write fences
287// signal (the wait linux/dma-buf.h documents). Unlike mmap/DMA_BUF_IOCTL_SYNC it triggers no exporter cache maintenance
288// or buffer migration. False when a wait timed out or failed, or the fd reported anything but POLLIN: poll() also
289// returns for POLLERR, POLLHUP and POLLNVAL, which say nothing about the writes.
290bool waitForProducerWrites(GstBuffer* buffer)
291{
292 int lastFd = -1;
293 for (guint i = 0; i < gst_buffer_n_memory(buffer); ++i) {
294 GstMemory* mem = gst_buffer_peek_memory(buffer, i);
295 const int fd = (mem && gst_is_dmabuf_memory(mem)) ? gst_dmabuf_memory_get_fd(mem) : -1;
296 if (fd < 0 || fd == lastFd) {
297 continue;
298 }
299 lastFd = fd;
300 pollfd pfd = {fd, POLLIN, 0};
301 int ret = 0;
302 do {
303 ret = ::poll(&pfd, 1, kProducerWaitTimeoutMs);
304 } while (ret < 0 && (errno == EINTR || errno == EAGAIN));
305 const bool writesDone = (ret > 0) && (pfd.revents & POLLIN) && !(pfd.revents & (POLLERR | POLLHUP | POLLNVAL));
306 if (!writesDone) {
307 const int pollError = (ret < 0) ? errno : 0;
309 QGC_HW_WARN_ONCE(GstDmaBufLog, s_diag.loggedProducerWaitTimeout,
310 "dma-buf producer fence wait" << (ret == 0 ? "timed out" : "failed") << "errno="
311 << pollError << "revents=" << Qt::hex << pfd.revents
312 << Qt::dec << "— no producer barrier for this frame");
313 return false;
314 }
315 }
317 return true;
318}
319
320// Qt's importer has no producer barrier, and Intel iHD's LINEAR exports aren't implicitly fenced by the EGL import:
321// prefer a GPU-side wait on the exported fences, else block on the implicit ones.
322void waitForProducer(EGLDisplay eglDpy, GstBuffer* buffer)
323{
324 if (!tryExplicitFenceWait(eglDpy, buffer)) {
325 waitForProducerWrites(buffer);
326 }
327}
328
329// Bounded so a GPU that hangs can't keep a decoder's buffer for good.
330constexpr int kGpuReadsTimeoutMs = 1000;
331
332#ifdef QGC_UNITTEST_BUILD
333std::atomic<int> s_gpuFenceForTest{-1};
334#endif
335
338int exportGpuFence(EGLDisplay eglDpy)
339{
340#ifdef QGC_UNITTEST_BUILD
341 if (const int fd = s_gpuFenceForTest.load(std::memory_order_relaxed); fd >= 0) {
342 return ::dup(fd);
343 }
344#endif
345 QOpenGLContext* const context = QOpenGLContext::currentContext();
346 if (!context || !GstEglHelpers::displaySupportsExtension(eglDpy, kNativeFenceExt)) {
347 return -1;
348 }
349 using DupNativeFenceFd = EGLint(EGLAPIENTRY*)(EGLDisplay, EGLSyncKHR);
350 static const auto createSyncKHR = reinterpret_cast<PFNEGLCREATESYNCKHRPROC>(eglGetProcAddress("eglCreateSyncKHR"));
351 static const auto destroySyncKHR =
352 reinterpret_cast<PFNEGLDESTROYSYNCKHRPROC>(eglGetProcAddress("eglDestroySyncKHR"));
353 static const auto dupNativeFenceFd =
354 reinterpret_cast<DupNativeFenceFd>(eglGetProcAddress("eglDupNativeFenceFDANDROID"));
355 if (!createSyncKHR || !destroySyncKHR || !dupNativeFenceFd) {
356 return -1;
357 }
358 const EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, EGL_NO_NATIVE_FENCE_FD_ANDROID, EGL_NONE};
359 const EGLSyncKHR sync = createSyncKHR(eglDpy, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
360 if (sync == EGL_NO_SYNC_KHR) {
361 return -1;
362 }
363 // The sync gets its fence when the commands before it are flushed.
364 context->functions()->glFlush();
365 const int fence = dupNativeFenceFd(eglDpy, sync);
366 destroySyncKHR(eglDpy, sync);
367 return fence;
368}
369
371struct PendingGpuReads
372{
373 int fence = -1;
374 GstBuffer* buffer = nullptr;
375};
376
378void waitForGpuReads(gpointer data, gpointer /*userData*/)
379{
380 const std::unique_ptr<PendingGpuReads> pending(static_cast<PendingGpuReads*>(data));
381 pollfd pfd = {pending->fence, POLLIN, 0};
382 int ret = 0;
383 do {
384 ret = ::poll(&pfd, 1, kGpuReadsTimeoutMs);
385 } while (ret < 0 && (errno == EINTR || errno == EAGAIN));
386 ::close(pending->fence);
387 gst_buffer_unref(pending->buffer);
388}
389
394void unrefAfterGpuReads(EGLDisplay eglDpy, GstBuffer* buffer)
395{
396 // GLib's threads, as many as there are buffers waiting: the decoder needs these buffers back, and QGC's long jobs
397 // can keep every thread of Qt's global pool busy.
398 static GThreadPool* const waiters = g_thread_pool_new(&waitForGpuReads, nullptr, -1, FALSE, nullptr);
399 const int fence = waiters ? exportGpuFence(eglDpy) : -1;
400 if (fence < 0) {
401 gst_buffer_unref(buffer);
402 return;
403 }
404 // A false return only says no thread could be started now: the wait stays queued.
405 (void) g_thread_pool_push(waiters, new PendingGpuReads{.fence = fence, .buffer = buffer}, nullptr);
406}
407
411bool locatePlanes(GstBuffer* buffer, const GstVideoInfo& info, const GstQtDmaBufImport::PlaneFourccs& fourccs,
412 quint64 modifier, std::span<GstQtDmaBufImport::Plane> planes)
413{
414 const GstVideoMeta* vmeta = gst_buffer_get_video_meta(buffer);
415 for (int i = 0; i < fourccs.count; ++i) {
416 // The meta's layout when present: decoders pad rows and planes beyond the caps' layout.
417 const gsize offset = vmeta ? vmeta->offset[i] : GST_VIDEO_INFO_PLANE_OFFSET(&info, i);
418 const gint stride = vmeta ? vmeta->stride[i] : GST_VIDEO_INFO_PLANE_STRIDE(&info, i);
419 guint memIdx = 0;
420 guint length = 0;
421 gsize skip = 0;
422 if (!gst_buffer_find_memory(buffer, offset, 1, &memIdx, &length, &skip) || (length != 1)) {
423 return false;
424 }
425 GstMemory* mem = gst_buffer_peek_memory(buffer, memIdx);
426 const quint64 fdOffset = static_cast<quint64>(mem->offset) + skip;
427 constexpr quint64 kMaxAttrib = (std::numeric_limits<EGLint>::max)();
428 if (!gst_is_dmabuf_memory(mem) || (stride <= 0) || (fdOffset > kMaxAttrib)) {
429 return false;
430 }
431 planes[std::size_t(i)] = {.fd = gst_dmabuf_memory_get_fd(mem),
432 .offset = static_cast<quint32>(fdOffset),
433 .pitch = static_cast<quint32>(stride),
434 .drmFourcc = fourccs.fourcc[std::size_t(i)],
435 .modifier = modifier};
436 if (planes[std::size_t(i)].fd < 0) {
437 return false;
438 }
439 }
440 return true;
441}
442
444bool locateImportPlanes(GstBuffer* buffer, const GstVideoInfo& info, const GstQtDmaBufImport::PlaneFourccs& fourccs,
445 quint64 modifier, std::span<GstQtDmaBufImport::Plane> planes)
446{
447 if ((fourccs.count != 0) && (fourccs.count == int(GST_VIDEO_INFO_N_PLANES(&info))) &&
448 locatePlanes(buffer, info, fourccs, modifier, planes)) {
449 return true;
450 }
451 QGC_HW_WARN_ONCE(GstDmaBufLog, s_diag.loggedLayoutRejected,
452 "DMABuf layout not importable (format" << gst_video_format_to_string(GST_VIDEO_INFO_FORMAT(&info))
453 << "memories" << gst_buffer_n_memory(buffer)
454 << ") — CPU fallback");
457 return false;
458}
459
460} // namespace
461
462GstDmaBufVideoBuffer::GstDmaBufVideoBuffer(GstSample* sample, const GstVideoInfo& videoInfo,
463 const QVideoFrameFormat& format, EGLDisplay eglDisplay)
464 : GstHwVideoBuffer(sample, videoInfo, format)
465 , _eglDisplay(eglDisplay)
466 , _drmModifier(DRM_FORMAT_MOD_INVALID)
467 , _packedYuvFourcc(eglfsPackedYuvFourcc(format.pixelFormat()))
468{
469 // Advertised for the GPU import only; the base class keeps the memory's format, so map() refuses the CPU upload Qt
470 // would otherwise read as RGBA.
471 if (_packedYuvFourcc != 0) {
472 _format = withPixelFormat(_format, QVideoFrameFormat::Format_RGBA8888);
473 }
474#if GST_CHECK_VERSION(1, 24, 0)
475 if (GstCaps* caps = gst_sample_get_caps(sample); caps && gst_video_is_dma_drm_caps(caps)) {
476 GstVideoInfoDmaDrm drmInfo = {};
477 gst_video_info_dma_drm_init(&drmInfo);
478 if (gst_video_info_dma_drm_from_caps(&drmInfo, caps)) {
479 _drmModifier = drmInfo.drm_modifier;
480 }
481 }
482#endif
483}
484
485EGLDisplay GstDmaBufVideoBuffer::eglDisplayFor(const HwVideoBufferContext& context)
486{
487 return (context.dmaBufImporter == QGCRhiCapture::qtEglDisplay()) ? context.dmaBufImporter : EGL_NO_DISPLAY;
488}
489
490bool GstDmaBufVideoBuffer::isDmaBufFd(int fd) noexcept
491{
492 // DMA_BUF_MAGIC of <linux/magic.h>: dma-bufs are files of a filesystem of their own since Linux 5.3. An older
493 // kernel has them on the anonymous-inode filesystem, among other fds, and none is recognized.
494 constexpr quint32 kDmaBufFsMagic = 0x444d4142;
495 struct statfs filesystem = {};
496 return (fd >= 0) && (::fstatfs(fd, &filesystem) == 0) &&
497 (static_cast<quint32>(filesystem.f_type) == kDmaBufFsMagic);
498}
499
500bool GstDmaBufVideoBuffer::isTiled() const noexcept
501{
502 return (_drmModifier != DRM_FORMAT_MOD_INVALID) && (_drmModifier != DRM_FORMAT_MOD_LINEAR);
503}
504
505bool GstDmaBufVideoBuffer::importDisabled() noexcept
506{
507 return s_importDisabled.load(std::memory_order_relaxed);
508}
509
510void GstDmaBufVideoBuffer::noteImportOutcome(ImportOutcome outcome) const
511{
512 noteLayoutImportOutcome(
513 {.modifier = _drmModifier, .pixelFormat = _format.pixelFormat(), .size = _format.frameSize()}, isTiled(),
514 outcome);
515}
516
517void GstDmaBufVideoBuffer::resetCachedState() noexcept
518{
519 s_importDisabled.store(false, std::memory_order_relaxed);
520 s_importFailures.clear();
521 s_diag.reset();
522#if defined(QGC_HAS_GST_DMABUF_VULKAN_IMPORT)
523 GstDmaBufVulkan::resetCachedState();
524#endif
525}
526
527namespace {
528
529// Streaming thread (sink start). Only the EGLDisplay Qt itself renders with can import for it, and Qt has none under
530// GLX; under Vulkan its device imports. qgcqvideosink puts the current one (HwBuffers::dmaBufImportDisplay()) into
531// each frame's context. Without one the path admits no frame, so DMABuf frames take the CPU path up front instead of
532// failing every import.
533void prepareDmaBufContext(HwVideoBufferContext&)
534{
535 static std::atomic<bool> s_logged{false};
536 if (!s_logged.exchange(true, std::memory_order_relaxed)) {
538 qCDebug(GstDmaBufLog) << "Qt renders without EGL on" << QGuiApplication::platformName()
539 << "— DMABuf frames take the CPU path (xcb: QT_XCB_GL_INTEGRATION=xcb_egl)";
540 } else {
541 qCDebug(GstDmaBufLog) << "DMABuf zero-copy available on" << QGuiApplication::platformName();
542 }
543 }
544}
545
546// The importer comes and goes within a caps epoch (Qt's EGLDisplay or Vulkan device becomes known, an import failure
547// disables the path until the scene graph is recreated), so it is asked for every frame rather than deciding whether
548// the path matches.
549bool admitDmaBuf(GstMemory*, const HwVideoBufferContext& context)
550{
551 if (context.dmaBufImporter) {
552 return true;
553 }
555 return false;
556}
557
558} // namespace
559
560constinit const HwPathDescriptor GstHwPaths::kDmaBuf = {
562 .matches = [](GstMemory* mem) -> bool { return gst_is_dmabuf_memory(mem); },
563 .admits = &admitDmaBuf,
564 .construct = [](GstSample* sample, const GstVideoInfo& info, QVideoFrameFormat format,
565 const HwVideoBufferContext& context) -> std::unique_ptr<GstHwVideoBuffer> {
566 return std::make_unique<GstDmaBufVideoBuffer>(sample, info, format,
567 GstDmaBufVideoBuffer::eglDisplayFor(context));
568 },
569 .prepareContext = &prepareDmaBufContext,
570#if defined(QGC_HAS_GST_DMABUF_VULKAN_IMPORT)
571 .probeDevice = &GstDmaBufVulkan::probeDevice,
572#endif
573 .resetCaches =
574 [] {
575 GstDmaBufVideoBuffer::resetCachedState();
576 GstEglHelpers::resetExtensionCache();
577 },
578};
579
580#ifdef QGC_UNITTEST_BUILD
581void GstDmaBufVideoBuffer::recordImportFailureForTest(bool unrecoverable)
582{
583 noteLayoutImportOutcome({}, /*tiled=*/false,
584 unrecoverable ? ImportOutcome::Unrecoverable : ImportOutcome::Rejected);
585}
586
587void GstDmaBufVideoBuffer::noteImportOutcomeForTest(ImportOutcome outcome) const
588{
589 noteImportOutcome(outcome);
590}
591
592bool GstDmaBufVideoBuffer::waitForProducerWritesForTest(GstBuffer* buffer)
593{
594 return waitForProducerWrites(buffer);
595}
596
597void GstDmaBufVideoBuffer::setGpuFenceForTest(int fd)
598{
599 s_gpuFenceForTest.store(fd, std::memory_order_relaxed);
600}
601#endif
602
603bool GstDmaBufVideoBuffer::validatePlaneHandles() const
604{
605 if (importDisabled()) {
606 return false;
607 }
608 const bool planesOk = validatePlanes(
609 [](GstMemory* mem) { return mem && gst_is_dmabuf_memory(mem) && (gst_dmabuf_memory_get_fd(mem) >= 0); });
610 if (!planesOk) {
611 return false;
612 }
613#if defined(QGC_HAS_GST_DMABUF_VULKAN_IMPORT)
614 // Qt's Vulkan device takes the layouts it reported when it was probed, and no others.
615 if (QGCRhiCapture::deviceSnapshot().backend.load(std::memory_order_acquire) == static_cast<int>(QRhi::Vulkan)) {
616 return GstDmaBufVulkan::canImport(GstQtDmaBufImport::planeFourccs(_format.pixelFormat()), _drmModifier);
617 }
618#endif
619 // A tiled layout imports only through the modifier attributes.
620 return !isTiled() ||
621 ((_eglDisplay != EGL_NO_DISPLAY) && GstEglHelpers::displaySupportsExtension(_eglDisplay, kModifiersExt));
622}
623
624QAbstractVideoBuffer::MapData GstDmaBufVideoBuffer::map(QVideoFrame::MapMode mode)
625{
626 if (isTiled()) {
628 GstDmaBufLog, s_diag.loggedTiledCpuMap,
629 "tiled DMABuf frame has no CPU layout (modifier" << Qt::hex << _drmModifier << ") — frame not shown");
630 return {};
631 }
632 return GstHwVideoBuffer::map(mode);
633}
634
635QVideoFrameTexturesUPtr GstDmaBufVideoBuffer::mapTextures(QRhi& rhi, QVideoFrameTexturesUPtr& old)
636{
638 if (importDisabled()) {
640 }
641 ImportOutcome failure = ImportOutcome::NotImportable;
642 QVideoFrameTexturesUPtr textures = importFrame(rhi, old, failure);
643 noteImportOutcome(textures ? ImportOutcome::Imported : failure);
644 return textures;
645}
646
647QVideoFrameTexturesUPtr GstDmaBufVideoBuffer::importFrame(QRhi& rhi, QVideoFrameTexturesUPtr& old,
648 ImportOutcome& failure)
649{
650#if defined(QGC_HAS_GST_DMABUF_VULKAN_IMPORT)
651 const bool vulkan = (rhi.backend() == QRhi::Vulkan);
652#else
653 constexpr bool vulkan = false;
654 Q_UNUSED(old);
655#endif
656 GstBuffer* buffer = nullptr;
657 if (!checkMapPreconditions(rhi, static_cast<int>(vulkan ? QRhi::Vulkan : QRhi::OpenGLES2), GstDmaBufLog(), s_diag,
658 buffer)) {
660 }
661
662#if defined(QGC_HAS_GST_DMABUF_VULKAN_IMPORT)
663 if (vulkan) {
664 return importVulkan(rhi, buffer, old, failure);
665 }
666#endif
667 return importGl(rhi, buffer, failure);
668}
669
670#if defined(QGC_HAS_GST_DMABUF_VULKAN_IMPORT)
671QVideoFrameTexturesUPtr GstDmaBufVideoBuffer::importVulkan(QRhi& rhi, GstBuffer* buffer, QVideoFrameTexturesUPtr& old,
672 ImportOutcome& failure)
673{
674 const QVideoFrameFormat::PixelFormat pixelFormat = _format.pixelFormat();
675 const GstQtDmaBufImport::PlaneFourccs fourccs = GstQtDmaBufImport::planeFourccs(pixelFormat);
676 std::array<GstQtDmaBufImport::Plane, kMaxPlanes> planes{};
677 if (!locateImportPlanes(buffer, _videoInfo, fourccs, _drmModifier, planes)) {
679 }
680 if (!GstHwImportPreflight::preflightOrRecord(rhi, HwVideoBufferPath::DmaBuf, pixelFormat, _format.frameSize())) {
682 }
683
684 // Vulkan does not wait on the implicit fences of imported dma-buf memory, and QRhi's submission can't be given the
685 // producer's fence: import only once the poll() barrier confirms the producer's writes completed.
686 if (!waitForProducerWrites(buffer)) {
689 QGC_HW_WARN_ONCE(GstDmaBufLog, s_diag.loggedVulkanSyncRefused,
690 "Vulkan import refused: producer writes not known complete — CPU fallback");
692 }
693
694 bool rejected = false;
695 QVideoFrameTexturesUPtr textures =
696 GstDmaBufVulkan::importTextures(*this, rhi, old, std::span(planes.data(), std::size_t(fourccs.count)),
697 pixelFormat, _format.frameSize(), buffer, rejected);
698 if (rejected) {
699 failure = ImportOutcome::Rejected;
700 }
701 return textures;
702}
703#endif
704
705QVideoFrameTexturesUPtr GstDmaBufVideoBuffer::importGl(QRhi& rhi, GstBuffer* buffer, ImportOutcome& failure)
706{
707 const EGLDisplay eglDpy = GstQtDmaBufImport::importDisplay(rhi);
708 if (eglDpy == EGL_NO_DISPLAY) {
709 QGC_HW_WARN_ONCE(GstDmaBufLog, s_diag.loggedNoEglContext,
710 "Qt's GL context is not EGL or can't bind EGLImages — DMABuf frames take the CPU path");
714 }
715
716 const QVideoFrameFormat::PixelFormat pixelFormat = _format.pixelFormat();
717 GstQtDmaBufImport::PlaneFourccs fourccs = GstQtDmaBufImport::planeFourccs(pixelFormat);
718 if (_packedYuvFourcc != 0) {
719 fourccs = {.fourcc = {_packedYuvFourcc}, .count = 1};
720 }
721 const quint64 modifier =
722 ((_drmModifier != DRM_FORMAT_MOD_INVALID) && GstEglHelpers::displaySupportsExtension(eglDpy, kModifiersExt))
723 ? _drmModifier
724 : GstQtDmaBufImport::kImplicitModifier;
725 std::array<GstQtDmaBufImport::Plane, kMaxPlanes> planes{};
726 if (!locateImportPlanes(buffer, _videoInfo, fourccs, modifier, planes)) {
728 }
729
730 if (!GstHwImportPreflight::preflightOrRecord(rhi, HwVideoBufferPath::DmaBuf, pixelFormat, _format.frameSize())) {
732 }
733
734 waitForProducer(eglDpy, buffer);
735
736 // The textures sample the dma-bufs directly: keep the decoder from recycling them until Qt has dropped the
737 // textures and the GPU has drawn with them.
738 std::shared_ptr<void> keepAlive(gst_buffer_ref(buffer),
739 [eglDpy](void* ref) { unrefAfterGpuReads(eglDpy, static_cast<GstBuffer*>(ref)); });
740 GstQtDmaBufImport::ImportResult imported =
741 GstQtDmaBufImport::importTextures(rhi, std::span(planes.data(), std::size_t(fourccs.count)), pixelFormat,
742 _format.frameSize(), std::move(keepAlive));
743 if (!imported.textures) {
744 failure = imported.unrecoverable ? ImportOutcome::Unrecoverable : ImportOutcome::Rejected;
746 }
747 if (!s_diag.loggedFirstSuccess.exchange(true, std::memory_order_relaxed)) {
748 qCDebug(GstDmaBufLog) << "First DMABuf import: size=" << _format.frameSize() << "format=" << pixelFormat
749 << "modifier=" << Qt::hex << modifier;
750 }
751 return std::move(imported.textures);
752}
753
754#endif // QGC_HAS_GST_DMABUF_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)
RAII timer: records mapTextures() wall time into the path's EWMA on scope exit.
Common base for GStreamer-backed QHwVideoBuffer subclasses.
MapData map(QVideoFrame::MapMode mode) override
bool run(const Environment::BundledRuntime &runtime)
bool preflightOrRecord(QRhi &rhi, HwVideoBufferPath path, QVideoFrameFormat::PixelFormat pixelFormat, const QSize &size, QRhiTexture::Flags flags)
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
HwFallbackReason
Specific cause a GPU path was rejected for a sample; surfaced as a per-(path,reason) breakdown.
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)
void * qtEglDisplay()
DeviceSnapshot & deviceSnapshot() noexcept
Returns the global snapshot. Atomic fields make individual reads thread-safe.
bool rejected(const Fields &reply, std::string_view command)
One-shot warning flags per failure cause; paths with extra causes (DMABuf, D3D, IOSurface) derive and...