QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
GstD3DVideoBufferCommon.h
Go to the documentation of this file.
1#pragma once
2
3#include <QtCore/qglobal.h>
4
5#if defined(QGC_HAS_GST_D3D11_GPU_PATH) || defined(QGC_HAS_GST_D3D12_GPU_PATH)
6
7#include <algorithm>
8#include <array>
9#include <atomic>
10#include <cstddef>
11#include <gst/gst.h>
12// Not <gst/video/gstvideopool.h>. GStreamer defect, seen in GStreamer 1.28: it must not be the first video header
13// (include cycle).
14#include <gst/video/video.h>
15#include <memory>
16#include <private/qhwvideobuffer_p.h>
17#include <private/qvideotexturehelper_p.h>
18#include <rhi/qrhi.h>
19#include <span>
20
21#include <QtCore/QLoggingCategory>
22#include <QtCore/QSize>
23#include <QtMultimedia/QVideoFrame>
24#include <QtMultimedia/QVideoFrameFormat>
25
26#include "GstD3DContextBridge.h"
28#include "GstHwPathTelemetry.h"
29#include "GstHwVideoBuffer.h"
30
32namespace GstD3DVideoBufferCommon {
33
35
36inline bool canAliasSingleResourceAcrossPlanes(QVideoFrameFormat::PixelFormat pixelFormat) noexcept
37{
38 switch (pixelFormat) {
39 case QVideoFrameFormat::Format_NV12:
40 case QVideoFrameFormat::Format_NV21:
41 case QVideoFrameFormat::Format_P010:
42 case QVideoFrameFormat::Format_P016:
43 return true;
44 default:
45 return false;
46 }
47}
48
51struct MapDiagnostics : GstHw::MapDiagnostics
52{
53 std::atomic<bool> loggedNonD3DMemory{false};
54 std::atomic<bool> loggedNullResource{false};
55 // Tripped when GstD3DXMemory carries a device that doesn't match the bridge's shared device — a NEED_CONTEXT race
56 // the bridge lost.
57 std::atomic<bool> loggedDeviceMismatch{false};
58
61 void reset() noexcept
62 {
64 for (std::atomic<bool>* flag : {&loggedNonD3DMemory, &loggedNullResource, &loggedDeviceMismatch}) {
65 flag->store(false, std::memory_order_relaxed);
66 }
67 }
68};
69
70static_assert(sizeof(MapDiagnostics) == sizeof(GstHw::MapDiagnostics) + (3 * sizeof(std::atomic<bool>)),
71 "MapDiagnostics::reset() must list every flag");
72
75template <class HandleT>
76struct PlaneResourceGuard
77{
78 std::array<HandleT*, kMaxPlanes> handles{};
79 int owned = 0;
80
81 PlaneResourceGuard() = default;
82 PlaneResourceGuard(const PlaneResourceGuard&) = delete;
83 PlaneResourceGuard& operator=(const PlaneResourceGuard&) = delete;
84
85 ~PlaneResourceGuard()
86 {
87 for (int j = 0; j < owned; ++j) {
88 if (handles[j])
89 handles[j]->Release();
90 }
91 }
92
95 void commit() noexcept { owned = 0; }
96};
97
111template <class Api>
112int resolvePlanes(GstBuffer* buffer, Api& api, MapDiagnostics& diag, PlaneResourceGuard<typename Api::Handle>& guard)
113{
114 using Memory = typename Api::Memory;
115 using Device = typename Api::Device;
116
117 const int memCount = (std::min) (int(gst_buffer_n_memory(buffer)), kMaxPlanes);
118 for (int i = 0; i < memCount; ++i) {
119 GstMemory* mem = gst_buffer_peek_memory(buffer, guint(i));
120 if (!mem || !Api::isMemory(mem)) {
121 QGC_HW_WARN_ONCE(Api::log, diag.loggedNonD3DMemory,
122 "resolve: plane" << i << "memory is not" << Api::kMemoryName << "(allocator="
123 << (mem && mem->allocator ? mem->allocator->mem_type : "null") << ")");
124 return 0;
125 }
126 auto* d3dmem = reinterpret_cast<Memory*>(mem);
127 // gst-d3d may land on an isolated device when NEED_CONTEXT was preempted; sampling a foreign-device resource
128 // from QRhi corrupts silently.
129 if (i == 0) {
130 // currentDevice() is transfer-full — unref on every branch to avoid UAF after reset().
131 Device* bridgeDev = Api::bridgeDevice();
132 if (bridgeDev && !Api::sameDevice(d3dmem->device, bridgeDev)) {
133 const gint64 bridgeLuid = GstD3DContextBridge::readAdapterLuid(bridgeDev);
134 const gint64 bufLuid = GstD3DContextBridge::readAdapterLuid(d3dmem->device);
135 gst_object_unref(bridgeDev);
136 QGC_HW_WARN_ONCE(Api::log, diag.loggedDeviceMismatch,
137 "resolve:" << Api::kMemoryName << "on foreign device (bridge LUID=" << bridgeLuid
138 << "buffer LUID=" << bufLuid
139 << "); bridge missed NEED_CONTEXT race — rejecting frame");
140 return 0;
141 }
142 if (bridgeDev) {
143 gst_object_unref(bridgeDev);
144 }
145 }
146 if (!api.prepare(d3dmem, i)) {
147 return 0;
148 }
149 auto* resource = Api::resource(d3dmem);
150 if (!resource) {
151 QGC_HW_WARN_ONCE(Api::log, diag.loggedNullResource,
152 "resolve:" << Api::kMemoryName << "has no resource handle for plane" << i);
153 return 0;
154 }
155 const guint subIdx = Api::subresource(d3dmem, i);
156 if (Api::isArraySlice(resource, subIdx)) {
157 auto* slice = api.copySlice(resource, subIdx, i);
158 if (!slice) {
159 return 0;
160 }
161 guard.handles[i] = slice;
162 } else {
163 resource->AddRef();
164 guard.handles[i] = resource;
165 }
166 guard.owned = i + 1;
167 }
168 return memCount;
169}
170
173template <class HandleT>
174class FrameTextures final : public GstHwFrameTexturesBase
175{
176public:
177 FrameTextures(QRhi* rhi, QSize size, QVideoFrameFormat::PixelFormat pixelFormat,
178 std::array<HandleT*, kMaxPlanes> handles, int count)
179 : _handles(handles)
180 {
181 wrapPlanes(rhi, size, pixelFormat,
182 std::span<HandleT* const>(_handles.data(), std::size_t(std::clamp(count, 0, kMaxPlanes))));
183 }
184
185 ~FrameTextures() override
186 {
187 for (int i = 0; i < _count; ++i) {
188 if (_handles[i])
189 _handles[i]->Release();
190 }
191 }
192
194 HandleT* handle(int plane) const noexcept { return (plane >= 0 && plane < _count) ? _handles[plane] : nullptr; }
195
196private:
197 std::array<HandleT*, kMaxPlanes> _handles;
198};
199
203template <class HandleT>
204QVideoFrameTexturesUPtr mapResolvedTextures(GstHwVideoBuffer& self, QRhi& rhi, QVideoFrameTexturesUPtr& old,
205 const GstHwMapTail& tail,
206 const std::array<HandleT*, kMaxPlanes>& resolvedHandles, int resolvedCount)
207{
208 using BundleT = FrameTextures<HandleT>;
209
210 const auto* desc = QVideoTextureHelper::textureDescription(tail.pixelFormat);
211 if (!desc || desc->nplanes <= 0) {
212 return GstHwPathTelemetry::fail(tail.path);
213 }
214
215 const int textureCount = (std::min) (desc->nplanes, kMaxPlanes);
216 if (resolvedCount <= 0 || resolvedCount > kMaxPlanes) {
217 return GstHwPathTelemetry::fail(tail.path);
218 }
219
220 std::array<HandleT*, kMaxPlanes> handles{};
221 for (int i = 0; i < (std::min) (resolvedCount, textureCount); ++i) {
222 handles[i] = resolvedHandles[i];
223 }
224
225 if (resolvedCount < textureCount) {
226 if (resolvedCount != 1 || !handles[0] || !canAliasSingleResourceAcrossPlanes(tail.pixelFormat)) {
227 return GstHwPathTelemetry::fail(tail.path);
228 }
229 // D3D NV12/P010 output can expose one texture with multiple shader-resource planes.
230 for (int i = resolvedCount; i < textureCount; ++i) {
231 handles[i] = handles[0];
232 }
233 }
234
235 // Reuse-eligible when the handles are identical: a decoder's pool and a path's copy targets rotate a stable set of
236 // resources, so the existing QRhiTexture views sample the new frame.
238 self, rhi, old, tail,
239 [&](BundleT& prev) {
240 return prev.matchesImport(&rhi, tail.frameSize, tail.pixelFormat,
241 std::span<HandleT* const>(handles.data(), std::size_t(textureCount)));
242 },
243 [&] {
244 // The bundle owns these AddRef'd refs; the buffer dtor releases the originals independently.
245 for (int i = 0; i < textureCount; ++i) {
246 if (handles[i])
247 handles[i]->AddRef();
248 }
249 return std::make_unique<BundleT>(&rhi, tail.frameSize, tail.pixelFormat, handles, textureCount);
250 });
251}
252
256template <class Resolver>
257class VideoBuffer : public GstHwVideoBuffer
258{
259public:
260 using Handle = typename Resolver::Handle;
261
262 ~VideoBuffer() override
263 {
264 for (int i = 0; i < _count; ++i) {
265 if (_handles[std::size_t(i)]) {
266 _handles[std::size_t(i)]->Release();
267 }
268 }
269 }
270
271 bool validatePlaneHandles() const override
272 {
273 // A failed constructor-time resolve (device mismatch, missing resource, sync or copy failure) sends the frame
274 // to the CPU.
275 if (_count == 0) {
276 return false;
277 }
278 return validatePlanes([](GstMemory* mem) {
279 return mem && Resolver::isMemory(mem) &&
280 (Resolver::resource(reinterpret_cast<typename Resolver::Memory*>(mem)) != nullptr);
281 });
282 }
283
284protected:
285 VideoBuffer(GstSample* sample, const GstVideoInfo& videoInfo, const QVideoFrameFormat& format,
286 HwVideoBufferPath path, MapDiagnostics& diag)
287 : GstHwVideoBuffer(sample, videoInfo, format)
288 , _path(path)
289 , _diag(diag)
290 {}
291
293 bool resolve(Resolver& resolver)
294 {
295 GstBuffer* const buffer = _sample ? gst_sample_get_buffer(_sample) : nullptr;
296 if (!buffer) {
297 return false;
298 }
299 PlaneResourceGuard<Handle> guard;
300 const int count = resolvePlanes(buffer, resolver, _diag, guard);
301 if (count == 0) {
302 return false;
303 }
304 _handles = guard.handles;
305 _count = count;
306 guard.commit();
307 return true;
308 }
309
311 GstBuffer* beginMap(QRhi& rhi, QRhi::Implementation backend)
312 {
313 GstBuffer* buffer = nullptr;
314 if (!checkMapPreconditions(rhi, static_cast<int>(backend), Resolver::log(), _diag, buffer) || (_count == 0)) {
315 return nullptr;
316 }
317 return buffer;
318 }
319
321 QVideoFrameTexturesUPtr finishMap(QRhi& rhi, QVideoFrameTexturesUPtr& old,
322 const std::array<Handle*, kMaxPlanes>& planes)
323 {
324 const GstHwMapTail tail{.path = _path,
325 .frameSize = _format.frameSize(),
326 .pixelFormat = _format.pixelFormat(),
327 .log = &Resolver::log(),
328 .diag = &_diag,
329 .successTag = GstHw::toString(_path)};
330 return mapResolvedTextures(*this, rhi, old, tail, planes, _count);
331 }
332
333 std::array<Handle*, kMaxPlanes> _handles{};
334 int _count = 0;
335
336private:
337 const HwVideoBufferPath _path;
338 MapDiagnostics& _diag;
339};
340
343template <class Api>
344bool proposePool(GstQuery* query, GstCaps* caps, const GstVideoInfo* vinfo, gsize size, guint minBuffers)
345{
346 GstCapsFeatures* features = gst_caps_get_features(caps, 0);
347 if (!features || !gst_caps_features_contains(features, Api::kCapsFeature)) {
348 return false;
349 }
350 typename Api::Device* device = Api::bridgeDevice();
351 if (!device) {
352 return false;
353 }
354 bool proposed = false;
355 if (GstBufferPool* pool = Api::newPool(device)) {
356 GstStructure* config = gst_buffer_pool_get_config(pool);
357 gst_buffer_pool_config_set_params(config, caps, size, minBuffers, 0);
358 gst_buffer_pool_config_add_option(config, GST_BUFFER_POOL_OPTION_VIDEO_META);
359 Api::setAllocationParams(config, device, vinfo);
360 if (gst_buffer_pool_set_config(pool, config)) {
361 // The pool may grow the buffer size to the allocated texture's pitch; re-read it.
362 GstStructure* updated = gst_buffer_pool_get_config(pool);
363 guint poolSize = static_cast<guint>(size);
364 gst_buffer_pool_config_get_params(updated, nullptr, &poolSize, nullptr, nullptr);
365 gst_structure_free(updated);
366 gst_query_add_allocation_pool(query, pool, poolSize, minBuffers, 0);
367 proposed = true;
368 }
369 gst_object_unref(pool);
370 }
371 gst_object_unref(device); // bridgeDevice() returns a transfer-full ref.
372 return proposed;
373}
374
375} // namespace GstD3DVideoBufferCommon
376
377#endif // QGC_HAS_GST_D3D11_GPU_PATH || QGC_HAS_GST_D3D12_GPU_PATH
HwVideoBufferPath
GPU zero-copy path a frame is imported through; None means the frame takes the CPU path.
Definition GstHwTypes.h:7
#define QGC_HW_WARN_ONCE(LOGCAT, FLAG,...)
Logs once via qCWarning(LOGCAT) the first time FLAG flips true; subsequent trips are silent.
static QVideoFrameTexturesUPtr finishMap(GstHwVideoBuffer &source, QRhi &rhi, QVideoFrameTexturesUPtr &old, const GstHwMapTail &tail, Reuse &&reuse, Make &&make)
QVideoFrameTexturesUPtr fail(HwVideoBufferPath path) noexcept
Records a map failure for path and returns the empty bundle mapTextures() reports it with.
constexpr int kMaxPlanes
Matches GST_VIDEO_MAX_PLANES (gst-video pins it at 4); single source of truth for every per-platform ...
constexpr const char * toString(HwVideoBufferPath path) noexcept
Definition GstHwTypes.h:37
QByteArray format(const QList< LogEntry > &entries, int fmt)
QCameraDevice device(const QString &description)
The attached camera of description description; a null device when none is.
Definition UVCDevices.cc:21
std::optional< VideoReceiver::Config > resolve(const Settings &settings, const QGCVideoStreamInfo *streamInfo, Role role)
QVideoFrameFormat::PixelFormat pixelFormat
HwVideoBufferPath path