QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
GstD3D12VideoBuffer.cc
Go to the documentation of this file.
2
3#if defined(QGC_HAS_GST_D3D12_GPU_PATH)
4
5#include <array>
6#include <atomic>
7#include <d3d12.h>
8#include <gst/d3d12/gstd3d12.h>
9#include <rhi/qrhi_platform.h>
10#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
11#include <d3d11_4.h> // ID3D11Device5, ID3D11DeviceContext4, ID3D11Fence
12
13#include <QtCore/QMutex>
14#include <QtCore/QMutexLocker>
15#endif
16
18#include "GstHwPathRegistry.h"
19#include "GstHwPathTelemetry.h"
20#include "QGCLoggingCategory.h"
21#include "QGCRhiCapture.h"
22#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
23#include "GstD3D11PictureCopy.h"
24#endif
25
26QGC_LOGGING_CATEGORY(GstD3D12Log, "Video.GStreamer.HwBuffers.GstD3D12Buf")
27
28namespace {
29
31struct D3D12Diagnostics : GstD3DVideoBufferCommon::MapDiagnostics
32{
33 std::atomic<bool> loggedMultiPlane{false};
34 std::atomic<bool> loggedForeignDevice{false};
35 std::atomic<bool> loggedArraySlice{false};
36 std::atomic<bool> loggedNotShared{false};
37
38 void reset() noexcept
39 {
40 GstD3DVideoBufferCommon::MapDiagnostics::reset();
41 for (std::atomic<bool>* flag : {&loggedMultiPlane, &loggedForeignDevice, &loggedArraySlice, &loggedNotShared}) {
42 flag->store(false, std::memory_order_relaxed);
43 }
44 }
45};
46
47static_assert(sizeof(D3D12Diagnostics) ==
48 sizeof(GstD3DVideoBufferCommon::MapDiagnostics) + (4 * sizeof(std::atomic<bool>)),
49 "D3D12Diagnostics::reset() must list every flag");
50
51D3D12Diagnostics s_diag;
52
55bool qtRendersWithD3D12()
56{
57 return QGCRhiCapture::deviceSnapshot().backend.load(std::memory_order_acquire) == static_cast<int>(QRhi::D3D12);
58}
59
61bool d3d12RhiSamples(QVideoFrameFormat::PixelFormat pixelFormat)
62{
63 const auto* description = QVideoTextureHelper::textureDescription(pixelFormat);
64 return description && (description->nplanes == 1);
65}
66
67#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
71bool d3d11OpensD3D12(ID3D11Device* device)
72{
73 D3D11_FEATURE_DATA_D3D11_OPTIONS options = {};
74 D3D11_FEATURE_DATA_D3D11_OPTIONS4 options4 = {};
75 D3D11_FEATURE_DATA_D3D11_OPTIONS5 options5 = {};
76 return SUCCEEDED(device->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS5, &options5, sizeof(options5))) &&
77 (options5.SharedResourceTier >= D3D11_SHARED_RESOURCE_TIER_2) &&
78 SUCCEEDED(device->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS, &options, sizeof(options))) &&
79 options.ExtendedResourceSharing &&
80 SUCCEEDED(device->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS4, &options4, sizeof(options4))) &&
81 options4.ExtendedNV12SharedTextureSupported;
82}
83#endif
84
86class D3D12PlaneResolver
87{
88public:
89 using Handle = ID3D12Resource;
90 using Memory = GstD3D12Memory;
91 using Device = GstD3D12Device;
92
93 static constexpr const char* kMemoryName = "GstD3D12Memory";
94 static constexpr const char* kCapsFeature = GST_CAPS_FEATURE_MEMORY_D3D12_MEMORY;
95
96 static const QLoggingCategory& log() { return GstD3D12Log(); }
97
98 static bool isMemory(GstMemory* mem) { return gst_is_d3d12_memory(mem); }
99
100 static Device* bridgeDevice() { return GstD3D12ContextBridge::currentDevice(); }
101
102 // Compare the underlying device, not the wrapper: each bridge prime creates a new GstD3D12Device.
103 static bool sameDevice(Device* a, Device* b) { return gst_d3d12_device_is_equal(a, b); }
104
105 static Handle* resource(Memory* mem) { return gst_d3d12_memory_get_resource_handle(mem); }
106
107 static guint subresource(Memory* mem, int plane)
108 {
109 guint subIdx = 0;
110 gst_d3d12_memory_get_subresource_index(mem, guint(plane), &subIdx);
111 return subIdx;
112 }
113
114 static bool isArraySlice(Handle* resource, guint subIdx)
115 {
116 return subIdx > 0 || resource->GetDesc().DepthOrArraySize > 1;
117 }
118
119 // Block on the decoder's fence before reading, else QRhi samples mid-write while the decoder is still writing this
120 // resource.
121 static bool prepare(Memory* mem, int plane)
122 {
123 if (!gst_d3d12_memory_sync(mem)) {
124 QGC_HW_WARN_ONCE(GstD3D12Log, s_diag.loggedNullResource,
125 "resolve: gst_d3d12_memory_sync failed for plane" << plane);
126 return false;
127 }
128 return true;
129 }
130
131 // QRhi can't sample one slice of a texture array, and none reaches the sink: gst-d3d12's pools hold single
132 // textures, and its decoders copy a frame out of a reference-only array before they hand it on.
133 static Handle* copySlice(Handle* /*resource*/, guint subIdx, int plane)
134 {
135 QGC_HW_WARN_ONCE(GstD3D12Log, s_diag.loggedArraySlice,
136 "resolve: plane" << plane << "is slice" << subIdx << "of a texture array — CPU fallback");
137 return nullptr;
138 }
139
140 static GstBufferPool* newPool(Device* device) { return gst_d3d12_buffer_pool_new(device); }
141
142 // gst_d3d12_memory_get_d3d11_texture() opens a resource on a Direct3D 11 device only from a shared heap, and with
143 // a render-target binding. A decoder that copies its frames into the downstream pool allocates them as that pool
144 // says.
145 static void setAllocationParams(GstStructure* config, Device* device, const GstVideoInfo* vinfo)
146 {
147 D3D12_RESOURCE_FLAGS resourceFlags = D3D12_RESOURCE_FLAG_NONE;
148 D3D12_HEAP_FLAGS heapFlags = D3D12_HEAP_FLAG_NONE;
149#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
150 if (!qtRendersWithD3D12()) {
151 resourceFlags = D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS;
152 heapFlags = D3D12_HEAP_FLAG_SHARED;
153 GstD3D12Format deviceFormat = {};
154 if (gst_d3d12_device_get_format(device, GST_VIDEO_INFO_FORMAT(vinfo), &deviceFormat) &&
155 ((deviceFormat.support1 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET) != 0)) {
156 resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
157 }
158 }
159#endif
160 if (GstD3D12AllocationParams* params = gst_d3d12_allocation_params_new(
161 device, vinfo, GST_D3D12_ALLOCATION_FLAG_DEFAULT, resourceFlags, heapFlags)) {
162 gst_buffer_pool_config_set_d3d12_allocation_params(config, params);
163 gst_d3d12_allocation_params_free(params);
164 }
165 }
166};
167
170bool onDevice(ID3D12Resource* resource, void* qrhiDevice)
171{
172 IUnknown* owner = nullptr;
173 IUnknown* device = nullptr;
174 const bool same = qrhiDevice && SUCCEEDED(resource->GetDevice(IID_PPV_ARGS(&owner))) &&
175 SUCCEEDED(static_cast<IUnknown*>(qrhiDevice)->QueryInterface(IID_PPV_ARGS(&device))) &&
176 (owner == device);
177 if (owner) {
178 owner->Release();
179 }
180 if (device) {
181 device->Release();
182 }
183 return same;
184}
185
186#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
189class InteropFence
190{
191public:
192 InteropFence(ID3D11Device* device11, ID3D12Device* device12)
193 : _device11(device11)
194 , _device12(device12)
195 {
196 ID3D11Device5* device5 = nullptr;
197 HANDLE shared = nullptr;
198 if (d3d11OpensD3D12(device11) && SUCCEEDED(device11->QueryInterface(IID_PPV_ARGS(&device5))) && device5 &&
199 SUCCEEDED(device5->CreateFence(0, D3D11_FENCE_FLAG_SHARED, IID_PPV_ARGS(&_fence11))) && _fence11 &&
200 SUCCEEDED(_fence11->CreateSharedHandle(nullptr, GENERIC_ALL, nullptr, &shared)) && shared) {
201 (void) device12->OpenSharedHandle(shared, IID_PPV_ARGS(&_fence12));
202 }
203 if (shared) {
204 CloseHandle(shared);
205 }
206 if (device5) {
207 device5->Release();
208 }
209 }
210
211 ~InteropFence()
212 {
213 if (_fence12) {
214 _fence12->Release();
215 }
216 if (_fence11) {
217 _fence11->Release();
218 }
219 }
220
221 InteropFence(const InteropFence&) = delete;
222 InteropFence& operator=(const InteropFence&) = delete;
223
224 bool isValid() const noexcept { return _fence11 && _fence12; }
225
226 bool joins(ID3D11Device* device11, ID3D12Device* device12) const noexcept
227 {
228 return (_device11 == device11) && (_device12 == device12);
229 }
230
233 quint64 signal(ID3D11DeviceContext* context)
234 {
235 ID3D11DeviceContext4* context4 = nullptr;
236 if (FAILED(context->QueryInterface(IID_PPV_ARGS(&context4))) || !context4) {
237 return 0;
238 }
239 const quint64 value = ++_value;
240 const HRESULT signalled = context4->Signal(_fence11, value);
241 context4->Release();
242 if (FAILED(signalled)) {
243 return 0;
244 }
245 // Qt submits only when it presents: without this the fence would follow the next frame's pace.
246 context->Flush();
247 return value;
248 }
249
251 void wait(quint64 value) const
252 {
253 if ((value == 0) || (_fence12->GetCompletedValue() >= value)) {
254 return;
255 }
256 if (const HANDLE reached = CreateEventW(nullptr, FALSE, FALSE, nullptr)) {
257 if (SUCCEEDED(_fence12->SetEventOnCompletion(value, reached))) {
258 (void) WaitForSingleObject(reached, kWaitMs);
259 }
260 CloseHandle(reached);
261 }
262 }
263
264private:
265 static constexpr DWORD kWaitMs = 100;
266
267 // Identities only: the fences hold their devices.
268 ID3D11Device* const _device11;
269 ID3D12Device* const _device12;
270 ID3D11Fence* _fence11 = nullptr;
271 ID3D12Fence* _fence12 = nullptr;
272 quint64 _value = 0;
273};
274
275QMutex s_interopFenceMutex;
276std::shared_ptr<InteropFence> s_interopFence;
277
280std::shared_ptr<InteropFence> interopFence(ID3D11Device* device11, ID3D12Device* device12)
281{
282 const QMutexLocker lock(&s_interopFenceMutex);
283 if (!s_interopFence || !s_interopFence->joins(device11, device12)) {
284 s_interopFence = std::make_shared<InteropFence>(device11, device12);
285 }
286 return s_interopFence->isValid() ? s_interopFence : nullptr;
287}
288#endif
289
295class D3D12VideoBuffer final : public GstD3DVideoBufferCommon::VideoBuffer<D3D12PlaneResolver>
296{
297public:
298 D3D12VideoBuffer(GstSample* sample, const GstVideoInfo& videoInfo, const QVideoFrameFormat& format)
299 : VideoBuffer(sample, videoInfo, format, HwVideoBufferPath::D3D12, s_diag)
300 {
301 // The D3D12Convert bin negotiates single-plane formats only; anything else takes the CPU path, here for the
302 // whole stream rather than frame by frame in mapTextures().
303 if (qtRendersWithD3D12() && !d3d12RhiSamples(format.pixelFormat())) {
304 QGC_HW_WARN_ONCE(GstD3D12Log, s_diag.loggedMultiPlane,
305 "resolve: multi-plane D3D12Memory" << format.pixelFormat() << "can't be sampled by QRhi");
306 return;
307 }
308 D3D12PlaneResolver resolver;
309 (void) resolve(resolver);
310 }
311
312#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
313 ~D3D12VideoBuffer() override
314 {
315 // The decoder writes its next frame into this resource once the sample goes: not before Direct3D 11 copied it.
316 if (_readFence) {
317 _readFence->wait(_readValue);
318 }
319 }
320#endif
321
322 QVideoFrameTexturesUPtr mapTextures(QRhi& rhi, QVideoFrameTexturesUPtr& old) override
323 {
324#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
325 if (rhi.backend() == QRhi::D3D11) {
326 return mapOnD3D11(rhi, old);
327 }
328#endif
329 if (!beginMap(rhi, QRhi::D3D12)) {
331 }
332 if (!d3d12RhiSamples(_format.pixelFormat())) {
334 GstD3D12Log, s_diag.loggedMultiPlane,
335 "mapTextures: multi-plane D3D12Memory" << _format.pixelFormat() << "can't be sampled by QRhi");
337 }
338 // Also catches an unprimed bridge, which skips resolvePlanes()'s device guard: a resource of another device
339 // imports fine but renders corrupt.
340 const auto* native = static_cast<const QRhiD3D12NativeHandles*>(rhi.nativeHandles());
341 if (!native || !onDevice(_handles[0], native->dev)) {
342 QGC_HW_WARN_ONCE(GstD3D12Log, s_diag.loggedForeignDevice,
343 "mapTextures: decoder resource is not on QRhi's device — CPU fallback");
345 }
346 return finishMap(rhi, old, _handles);
347 }
348
349private:
350#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
352 QVideoFrameTexturesUPtr mapOnD3D11(QRhi& rhi, QVideoFrameTexturesUPtr& old)
353 {
354 GstBuffer* const buffer = beginMap(rhi, QRhi::D3D11);
355 const auto* native = static_cast<const QRhiD3D11NativeHandles*>(rhi.nativeHandles());
356 auto* device = native ? static_cast<ID3D11Device*>(native->dev) : nullptr;
357 auto* context = native ? static_cast<ID3D11DeviceContext*>(native->context) : nullptr;
358 if (!buffer || !device || !context) {
360 }
361 // One NV12/P010 resource holds every plane. Its Direct3D 11 view belongs to the memory, which keeps one per
362 // device; none opens for a resource on another adapter, or one whose heap isn't shared.
363 auto* memory = reinterpret_cast<GstD3D12Memory*>(gst_buffer_peek_memory(buffer, 0));
364 ID3D11Texture2D* const shared = gst_d3d12_memory_get_d3d11_texture(memory, device);
365 const std::shared_ptr<InteropFence> fence =
366 shared ? interopFence(device, gst_d3d12_device_get_device_handle(memory->device)) : nullptr;
367 if (!fence) {
368 QGC_HW_WARN_ONCE(GstD3D12Log, s_diag.loggedNotShared,
369 "mapTextures: the decoder's resource can't be shared with QRhi's Direct3D 11 device "
370 "— CPU fallback");
372 }
373
374 ID3D11Texture2D* const picture =
375 GstD3D11PictureCopy::copy(device, context, shared, 0, QRect(QPoint(0, 0), _format.frameSize()), old, 0);
376 if (!picture) {
377 QGC_HW_WARN_ONCE(GstD3D12Log, s_diag.loggedTextureCreateFail,
378 "mapTextures: CreateTexture2D for the picture copy failed");
380 }
381 _readFence = fence;
382 _readValue = fence->signal(context);
383
384 const GstHwMapTail tail{.path = HwVideoBufferPath::D3D12,
385 .frameSize = _format.frameSize(),
386 .pixelFormat = _format.pixelFormat(),
387 .log = &GstD3D12Log(),
388 .diag = &s_diag,
389 .successTag = "D3D12 on D3D11"};
390 const std::array<ID3D11Texture2D*, GstHw::kMaxPlanes> planes{picture};
391 QVideoFrameTexturesUPtr textures =
392 GstD3DVideoBufferCommon::mapResolvedTextures(*this, rhi, old, tail, planes, 1);
393 picture->Release();
394 return textures;
395 }
396
398 std::shared_ptr<InteropFence> _readFence;
399 quint64 _readValue = 0;
400#endif
401};
402
403#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
406void probeDevice(QRhi& rhi)
407{
408 const auto* native =
409 (rhi.backend() == QRhi::D3D11) ? static_cast<const QRhiD3D11NativeHandles*>(rhi.nativeHandles()) : nullptr;
410 auto* device = native ? static_cast<ID3D11Device*>(native->dev) : nullptr;
411 QGCRhiCapture::deviceSnapshot().d3d11OpensD3D12.store(device && d3d11OpensD3D12(device), std::memory_order_release);
412}
413#endif
414
415void resetCachedState() noexcept
416{
417#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
418 {
419 const QMutexLocker lock(&s_interopFenceMutex);
420 s_interopFence.reset();
421 }
422#endif
423 s_diag.reset();
424}
425
426} // namespace
427
428constinit const HwPathDescriptor GstHwPaths::kD3D12 = {
430 .matches = [](GstMemory* mem) -> bool { return gst_is_d3d12_memory(mem); },
431 .construct = &GstHwPaths::construct<D3D12VideoBuffer>,
432#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
433 .probeDevice = &probeDevice,
434#endif
435 .resetCaches = &resetCachedState,
436 .proposePool = &GstD3DVideoBufferCommon::proposePool<D3D12PlaneResolver>,
437 .bridge = &GstD3D12ContextBridge::instance,
438};
439
440#endif // 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.
#define QGC_LOGGING_CATEGORY(name, categoryStr)
QVideoFrameTexturesUPtr fail(HwVideoBufferPath path) noexcept
Records a map failure for path and returns the empty bundle mapTextures() reports it with.
bool d3d11OpensD3D12() noexcept
Definition HwBuffers.cc:247
QByteArray format(const QList< LogEntry > &entries, int fmt)
DeviceSnapshot & deviceSnapshot() noexcept
Returns the global snapshot. Atomic fields make individual reads thread-safe.
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)
std::atomic< bool > d3d11OpensD3D12
std::atomic< int > backend
QRhi::Implementation cast to int (-1 = unset).