QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
GstD3D11VideoBuffer.cc
Go to the documentation of this file.
2
3#if defined(QGC_HAS_GST_D3D11_GPU_PATH)
4
5#include <algorithm>
6#include <array>
7#include <atomic>
8#include <d3d11.h>
9#include <gst/d3d11/gstd3d11.h>
10#include <rhi/qrhi_platform.h>
11
12#include <QtCore/QScopeGuard>
13
15#include "GstD3D11PictureCopy.h"
16#include "GstHwPathRegistry.h"
17#include "GstHwPathTelemetry.h"
18#include "QGCLoggingCategory.h"
19#include "QGCRhiCapture.h"
20
21QGC_LOGGING_CATEGORY(GstD3D11Log, "Video.GStreamer.HwBuffers.GstD3D11Buf")
22
23namespace {
24
25using GstD3DVideoBufferCommon::MapDiagnostics;
27
28MapDiagnostics s_diag;
29std::atomic<bool> s_loggedForeignDevice{false};
30
33class D3D11PlaneResolver
34{
35public:
36 using Handle = ID3D11Texture2D;
37 using Memory = GstD3D11Memory;
38 using Device = GstD3D11Device;
39
40 static constexpr const char* kMemoryName = "GstD3D11Memory";
41 static constexpr const char* kCapsFeature = GST_CAPS_FEATURE_MEMORY_D3D11_MEMORY;
42
43 static const QLoggingCategory& log() { return GstD3D11Log(); }
44
45 static bool isMemory(GstMemory* mem) { return gst_is_d3d11_memory(mem); }
46
47 static Device* bridgeDevice() { return GstD3D11ContextBridge::currentDevice(); }
48
49 // Compare the wrapped ID3D11Device, not the wrapper: each bridge prime wraps QRhi's device anew.
50 static bool sameDevice(Device* a, Device* b)
51 {
52 return gst_d3d11_device_get_device_handle(a) == gst_d3d11_device_get_device_handle(b);
53 }
54
55 static Handle* resource(Memory* mem)
56 {
57 return reinterpret_cast<ID3D11Texture2D*>(gst_d3d11_memory_get_resource_handle(mem));
58 }
59
60 static guint subresource(Memory* mem, int /*plane*/) { return gst_d3d11_memory_get_subresource_index(mem); }
61
62 static bool isArraySlice(Handle* tex, guint subIdx)
63 {
64 D3D11_TEXTURE2D_DESC desc = {};
65 tex->GetDesc(&desc);
66 return subIdx > 0 || desc.ArraySize > 1;
67 }
68
69 // A frame written through the CPU, as d3d11upload writes system memory, reaches the texture only when its memory
70 // is mapped for D3D11; a decoder's frame has no such upload pending.
71 static bool prepare(Memory* mem, int plane)
72 {
73 GstMapInfo info;
74 if (!gst_memory_map(GST_MEMORY_CAST(mem), &info, static_cast<GstMapFlags>(GST_MAP_READ | GST_MAP_D3D11))) {
75 QGC_HW_WARN_ONCE(GstD3D11Log, s_diag.loggedNullResource,
76 "resolve: mapping the GstD3D11Memory for D3D11 failed for plane" << plane);
77 return false;
78 }
79 gst_memory_unmap(GST_MEMORY_CAST(mem), &info);
80 return true;
81 }
82
83 Handle* copySlice(Handle* tex, guint subIdx, int plane)
84 {
85 tex->AddRef();
86 _slices[std::size_t(plane)] = subIdx;
87 _copied[std::size_t(plane)] = true;
88 return tex;
89 }
90
91 const std::array<guint, kMaxPlanes>& slices() const noexcept { return _slices; }
92
93 const std::array<bool, kMaxPlanes>& copied() const noexcept { return _copied; }
94
95 static GstBufferPool* newPool(Device* device) { return gst_d3d11_buffer_pool_new(device); }
96
97 // SHADER_RESOURCE matches the importer's sampled texture.
98 static void setAllocationParams(GstStructure* config, Device* device, const GstVideoInfo* vinfo)
99 {
100 if (GstD3D11AllocationParams* params = gst_d3d11_allocation_params_new(
101 device, vinfo, GST_D3D11_ALLOCATION_FLAG_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0)) {
102 gst_buffer_pool_config_set_d3d11_allocation_params(config, params);
103 gst_d3d11_allocation_params_free(params);
104 }
105 }
106
107private:
108 std::array<guint, kMaxPlanes> _slices{};
109 std::array<bool, kMaxPlanes> _copied{};
110};
111
115class D3D11VideoBuffer final : public GstD3DVideoBufferCommon::VideoBuffer<D3D11PlaneResolver>
116{
117public:
118 D3D11VideoBuffer(GstSample* sample, const GstVideoInfo& videoInfo, const QVideoFrameFormat& format)
119 : VideoBuffer(sample, videoInfo, format, HwVideoBufferPath::D3D11, s_diag)
120 {
121 D3D11PlaneResolver resolver;
122 if (!resolve(resolver)) {
123 return;
124 }
125 _slices = resolver.slices();
126 _copied = resolver.copied();
127
128 // Decoders pad their textures to their alignment (16 rows for H.264, 128 for HEVC/AV1) with no crop meta. The
129 // picture is copied out like an array slice's, so the frame keeps the picture's size and its CPU layout: Qt
130 // maps it to the CPU for a window on another device and for screenshots.
131 D3D11_TEXTURE2D_DESC desc = {};
132 _handles[0]->GetDesc(&desc);
133 if (GstHw::texturePadsPicture(QSize(int(desc.Width), int(desc.Height)), _format.frameSize(),
134 GstD3D11PictureCopy::hasEvenSizes(desc.Format))) {
135 std::fill_n(_copied.begin(), _count, true);
136 }
137 }
138
139 QVideoFrameTexturesUPtr mapTextures(QRhi& rhi, QVideoFrameTexturesUPtr& old) override
140 {
141 GstBuffer* const buffer = beginMap(rhi, QRhi::D3D11);
142 if (!buffer) {
144 }
145 // Also catches an unprimed bridge, which skips resolvePlanes()'s device guard: QRhi can't sample another
146 // device's texture.
147 const auto* native = static_cast<const QRhiD3D11NativeHandles*>(rhi.nativeHandles());
148 auto* device = native ? static_cast<ID3D11Device*>(native->dev) : nullptr;
149 auto* context = native ? static_cast<ID3D11DeviceContext*>(native->context) : nullptr;
150 if (!device || !context || !GstD3D11PictureCopy::onDevice(_handles[0], device)) {
151 QGC_HW_WARN_ONCE(GstD3D11Log, s_loggedForeignDevice,
152 "mapTextures: decoder texture is not on QRhi's device — CPU fallback");
154 }
155
156 std::array<ID3D11Texture2D*, kMaxPlanes> planes = _handles;
157 std::array<ID3D11Texture2D*, kMaxPlanes> copies{};
158 const auto releaseCopies = qScopeGuard([&copies] {
159 for (ID3D11Texture2D* copy : copies) {
160 if (copy) {
161 copy->Release();
162 }
163 }
164 });
165 for (int i = 0; i < _count; ++i) {
166 if (!_copied[std::size_t(i)]) {
167 continue;
168 }
169 copies[std::size_t(i)] = copyPicture(rhi, device, context, buffer, i, old);
170 if (!copies[std::size_t(i)]) {
172 }
173 planes[std::size_t(i)] = copies[std::size_t(i)];
174 }
175
176 return finishMap(rhi, old, planes);
177 }
178
179private:
182 ID3D11Texture2D* copyPicture(QRhi& rhi, ID3D11Device* device, ID3D11DeviceContext* context, GstBuffer* buffer,
183 int plane, QVideoFrameTexturesUPtr& old)
184 {
185 // One texture holds every plane (NV12, P010), else this plane's texture holds only its own share of the frame.
186 const auto* textureDescription = QVideoTextureHelper::textureDescription(_format.pixelFormat());
187 const QSize picture = ((_count > 1) && textureDescription)
188 ? textureDescription->rhiPlaneSize(_format.frameSize(), plane, &rhi)
189 : _format.frameSize();
190
191 // Serializes with GStreamer's own use of this immediate context (the decoder, on the streaming thread).
192 auto* memory = reinterpret_cast<GstD3D11Memory*>(gst_buffer_peek_memory(buffer, guint(plane)));
193 gst_d3d11_device_lock(memory->device);
194 ID3D11Texture2D* const target =
195 GstD3D11PictureCopy::copy(device, context, _handles[std::size_t(plane)], _slices[std::size_t(plane)],
196 QRect(QPoint(0, 0), picture), old, plane);
197 gst_d3d11_device_unlock(memory->device);
198 if (!target) {
199 QGC_HW_WARN_ONCE(GstD3D11Log, s_diag.loggedTextureCreateFail,
200 "mapTextures: CreateTexture2D for the slice copy failed (plane=" << plane << ")");
201 }
202 return target;
203 }
204
205 std::array<guint, kMaxPlanes> _slices{};
206 std::array<bool, kMaxPlanes> _copied{};
207};
208
209void resetCachedState() noexcept
210{
211 s_diag.reset();
212 s_loggedForeignDevice.store(false, std::memory_order_relaxed);
213}
214
215} // namespace
216
217constinit const HwPathDescriptor GstHwPaths::kD3D11 = {
219 .matches = [](GstMemory* mem) -> bool { return gst_is_d3d11_memory(mem); },
220 .construct = &GstHwPaths::construct<D3D11VideoBuffer>,
221 .resetCaches = &resetCachedState,
222 .proposePool = &GstD3DVideoBufferCommon::proposePool<D3D11PlaneResolver>,
223 .bridge = &GstD3D11ContextBridge::instance,
224};
225
226#endif // QGC_HAS_GST_D3D11_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 texturePadsPicture(QSize textureSize, QSize picture, bool evenSizes)
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)
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)