3#if defined(QGC_HAS_GST_D3D12_GPU_PATH)
8#include <gst/d3d12/gstd3d12.h>
9#include <rhi/qrhi_platform.h>
10#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
13#include <QtCore/QMutex>
14#include <QtCore/QMutexLocker>
22#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
31struct D3D12Diagnostics : GstD3DVideoBufferCommon::MapDiagnostics
33 std::atomic<bool> loggedMultiPlane{
false};
34 std::atomic<bool> loggedForeignDevice{
false};
35 std::atomic<bool> loggedArraySlice{
false};
36 std::atomic<bool> loggedNotShared{
false};
40 GstD3DVideoBufferCommon::MapDiagnostics::reset();
41 for (std::atomic<bool>* flag : {&loggedMultiPlane, &loggedForeignDevice, &loggedArraySlice, &loggedNotShared}) {
42 flag->store(
false, std::memory_order_relaxed);
47static_assert(
sizeof(D3D12Diagnostics) ==
48 sizeof(GstD3DVideoBufferCommon::MapDiagnostics) + (4 *
sizeof(std::atomic<bool>)),
49 "D3D12Diagnostics::reset() must list every flag");
51D3D12Diagnostics s_diag;
55bool qtRendersWithD3D12()
61bool d3d12RhiSamples(QVideoFrameFormat::PixelFormat pixelFormat)
63 const auto* description = QVideoTextureHelper::textureDescription(pixelFormat);
64 return description && (description->nplanes == 1);
67#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
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;
86class D3D12PlaneResolver
89 using Handle = ID3D12Resource;
90 using Memory = GstD3D12Memory;
91 using Device = GstD3D12Device;
93 static constexpr const char* kMemoryName =
"GstD3D12Memory";
94 static constexpr const char* kCapsFeature = GST_CAPS_FEATURE_MEMORY_D3D12_MEMORY;
96 static const QLoggingCategory& log() {
return GstD3D12Log(); }
98 static bool isMemory(GstMemory* mem) {
return gst_is_d3d12_memory(mem); }
100 static Device* bridgeDevice() {
return GstD3D12ContextBridge::currentDevice(); }
103 static bool sameDevice(Device* a, Device* b) {
return gst_d3d12_device_is_equal(a, b); }
105 static Handle* resource(Memory* mem) {
return gst_d3d12_memory_get_resource_handle(mem); }
107 static guint subresource(Memory* mem,
int plane)
110 gst_d3d12_memory_get_subresource_index(mem, guint(plane), &subIdx);
114 static bool isArraySlice(Handle* resource, guint subIdx)
116 return subIdx > 0 || resource->GetDesc().DepthOrArraySize > 1;
121 static bool prepare(Memory* mem,
int plane)
123 if (!gst_d3d12_memory_sync(mem)) {
125 "resolve: gst_d3d12_memory_sync failed for plane" << plane);
133 static Handle* copySlice(Handle* , guint subIdx,
int plane)
136 "resolve: plane" << plane <<
"is slice" << subIdx <<
"of a texture array — CPU fallback");
140 static GstBufferPool* newPool(Device* device) {
return gst_d3d12_buffer_pool_new(device); }
145 static void setAllocationParams(GstStructure* config, Device* device,
const GstVideoInfo* vinfo)
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;
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);
170bool onDevice(ID3D12Resource* resource,
void* qrhiDevice)
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))) &&
186#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
192 InteropFence(ID3D11Device* device11, ID3D12Device* device12)
193 : _device11(device11)
194 , _device12(device12)
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));
221 InteropFence(
const InteropFence&) =
delete;
222 InteropFence& operator=(
const InteropFence&) =
delete;
224 bool isValid() const noexcept {
return _fence11 && _fence12; }
226 bool joins(ID3D11Device* device11, ID3D12Device* device12)
const noexcept
228 return (_device11 == device11) && (_device12 == device12);
233 quint64 signal(ID3D11DeviceContext* context)
235 ID3D11DeviceContext4* context4 =
nullptr;
236 if (FAILED(context->QueryInterface(IID_PPV_ARGS(&context4))) || !context4) {
239 const quint64 value = ++_value;
240 const HRESULT signalled = context4->Signal(_fence11, value);
242 if (FAILED(signalled)) {
251 void wait(quint64 value)
const
253 if ((value == 0) || (_fence12->GetCompletedValue() >= value)) {
256 if (
const HANDLE reached = CreateEventW(
nullptr, FALSE, FALSE,
nullptr)) {
257 if (SUCCEEDED(_fence12->SetEventOnCompletion(value, reached))) {
258 (void) WaitForSingleObject(reached, kWaitMs);
260 CloseHandle(reached);
265 static constexpr DWORD kWaitMs = 100;
268 ID3D11Device*
const _device11;
269 ID3D12Device*
const _device12;
270 ID3D11Fence* _fence11 =
nullptr;
271 ID3D12Fence* _fence12 =
nullptr;
275QMutex s_interopFenceMutex;
276std::shared_ptr<InteropFence> s_interopFence;
280std::shared_ptr<InteropFence> interopFence(ID3D11Device* device11, ID3D12Device* device12)
282 const QMutexLocker lock(&s_interopFenceMutex);
283 if (!s_interopFence || !s_interopFence->joins(device11, device12)) {
284 s_interopFence = std::make_shared<InteropFence>(device11, device12);
286 return s_interopFence->isValid() ? s_interopFence :
nullptr;
295class D3D12VideoBuffer final :
public GstD3DVideoBufferCommon::VideoBuffer<D3D12PlaneResolver>
298 D3D12VideoBuffer(GstSample* sample,
const GstVideoInfo& videoInfo,
const QVideoFrameFormat& format)
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");
308 D3D12PlaneResolver resolver;
312#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
313 ~D3D12VideoBuffer()
override
317 _readFence->wait(_readValue);
322 QVideoFrameTexturesUPtr mapTextures(QRhi& rhi, QVideoFrameTexturesUPtr& old)
override
324#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
325 if (rhi.backend() == QRhi::D3D11) {
326 return mapOnD3D11(rhi, old);
329 if (!beginMap(rhi, QRhi::D3D12)) {
332 if (!d3d12RhiSamples(_format.pixelFormat())) {
334 GstD3D12Log, s_diag.loggedMultiPlane,
335 "mapTextures: multi-plane D3D12Memory" << _format.pixelFormat() <<
"can't be sampled by QRhi");
340 const auto* native =
static_cast<const QRhiD3D12NativeHandles*
>(rhi.nativeHandles());
341 if (!native || !onDevice(_handles[0], native->dev)) {
343 "mapTextures: decoder resource is not on QRhi's device — CPU fallback");
346 return finishMap(rhi, old, _handles);
350#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
352 QVideoFrameTexturesUPtr mapOnD3D11(QRhi& rhi, QVideoFrameTexturesUPtr& old)
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) {
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;
369 "mapTextures: the decoder's resource can't be shared with QRhi's Direct3D 11 device "
374 ID3D11Texture2D*
const picture =
375 GstD3D11PictureCopy::copy(device, context, shared, 0, QRect(QPoint(0, 0), _format.frameSize()), old, 0);
378 "mapTextures: CreateTexture2D for the picture copy failed");
382 _readValue = fence->signal(context);
385 .frameSize = _format.frameSize(),
386 .pixelFormat = _format.pixelFormat(),
387 .log = &GstD3D12Log(),
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);
398 std::shared_ptr<InteropFence> _readFence;
399 quint64 _readValue = 0;
403#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
406void probeDevice(QRhi& rhi)
409 (rhi.backend() == QRhi::D3D11) ?
static_cast<const QRhiD3D11NativeHandles*
>(rhi.nativeHandles()) :
nullptr;
410 auto*
device = native ?
static_cast<ID3D11Device*
>(native->dev) : nullptr;
415void resetCachedState() noexcept
417#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
419 const QMutexLocker lock(&s_interopFenceMutex);
420 s_interopFence.reset();
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,
435 .resetCaches = &resetCachedState,
436 .proposePool = &GstD3DVideoBufferCommon::proposePool<D3D12PlaneResolver>,
437 .bridge = &GstD3D12ContextBridge::instance,
HwVideoBufferPath
GPU zero-copy path a frame is imported through; None means the frame takes the CPU 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)
QVideoFrameTexturesUPtr fail(HwVideoBufferPath path) noexcept
Records a map failure for path and returns the empty bundle mapTextures() reports it with.
bool d3d11OpensD3D12() noexcept
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.
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).