QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
CpuVideoFramePool.cc
Go to the documentation of this file.
1#include "CpuVideoFramePool.h"
2
3#include <algorithm>
4#include <atomic>
5#include <cstring>
6#include <gst/video/video.h>
7#include <memory>
8#include <utility>
9
10#include <QtCore/QLoggingCategory>
11#include <QtMultimedia/QAbstractVideoBuffer>
12
13#include "GstHwVideoInfo.h"
14#include "QGCLoggingCategory.h"
15
16QGC_LOGGING_CATEGORY(CpuVideoFramePoolLog, "Video.GStreamer.HwBuffers.CpuPool")
17
18namespace {
19
20class PooledCpuVideoBuffer final : public QAbstractVideoBuffer
21{
22public:
23 PooledCpuVideoBuffer(QVideoFrameFormat format, CpuVideoFramePool::PlaneLayout layout, QByteArray backing)
24 : _format(std::move(format))
25 , _layout(layout)
26 , _backing(std::move(backing))
27 {}
28
29 ~PooledCpuVideoBuffer() override
30 {
31 if (!_backing.isEmpty()) {
32 CpuVideoFramePool::instance().releaseBacking(_format.frameSize(), _format.pixelFormat(),
33 std::move(_backing));
34 }
35 }
36
37 MapData map(QVideoFrame::MapMode mode) override
38 {
39 if (mode == QVideoFrame::NotMapped) {
40 return {};
41 }
42 MapData data;
43 data.planeCount = _layout.planeCount;
44 uchar* base = reinterpret_cast<uchar*>(_backing.data());
45 for (int i = 0; i < _layout.planeCount; ++i) {
46 data.data[i] = base + _layout.planeOffset[i];
47 data.bytesPerLine[i] = _layout.bytesPerLine[i];
48 data.dataSize[i] = static_cast<qsizetype>(_layout.bytesPerLine[i]) * _layout.height[i];
49 }
50 return data;
51 }
52
53 QVideoFrameFormat format() const override { return _format; }
54
55private:
56 QVideoFrameFormat _format;
57 CpuVideoFramePool::PlaneLayout _layout;
58 QByteArray _backing;
59};
60
61// Refs the source GstBuffer and maps its system memory through to Qt with no copy. The decoder buffer stays pinned for
62// the frame's lifetime — the same tradeoff the GPU paths already make by anchoring the sample.
63class MapThroughGstVideoBuffer final : public QAbstractVideoBuffer
64{
65public:
67 MapThroughGstVideoBuffer(GstBuffer* buffer, const GstVideoInfo& info, QVideoFrameFormat format,
69 : _buffer(gst_buffer_ref(buffer))
70 , _info(info)
71 , _format(std::move(format))
72 , _pinned(std::move(pinned))
73 {}
74
75 ~MapThroughGstVideoBuffer() override
76 {
77 _cpuView.unmap();
78 gst_buffer_unref(_buffer);
79 _pinned->fetch_sub(1, std::memory_order_relaxed);
80 }
81
82 MapData map(QVideoFrame::MapMode mode) override
83 {
84 return (mode == QVideoFrame::ReadOnly) ? _cpuView.map(_buffer, _info) : MapData{};
85 }
86
87 void unmap() override { _cpuView.unmap(); }
88
89 QVideoFrameFormat format() const override { return _format; }
90
91private:
92 GstBuffer* _buffer;
93 GstVideoInfo _info;
94 QVideoFrameFormat _format;
96 CpuVideoFramePool::FrameMapping _cpuView;
97};
98
99// Check-and-increment in one step so concurrent callers can never overshoot the cap.
100bool tryReservePinnedFrame(std::atomic<int>& pinned) noexcept
101{
102 int live = pinned.load(std::memory_order_relaxed);
103 do {
105 return false;
106 }
107 } while (!pinned.compare_exchange_weak(live, live + 1, std::memory_order_relaxed));
108 return true;
109}
110
111} // namespace
112
113CpuVideoFramePool& CpuVideoFramePool::instance()
114{
115 static CpuVideoFramePool s_pool;
116 return s_pool;
117}
118
120{
121 PlaneLayout L = {};
122 const int n = GST_VIDEO_INFO_N_PLANES(&info);
123 if (n <= 0 || n > 4) {
124 return L;
125 }
126 L.planeCount = n;
127 for (int i = 0; i < n; ++i) {
128 L.bytesPerLine[i] = GST_VIDEO_INFO_PLANE_STRIDE(&info, i);
129 L.planeOffset[i] = static_cast<qsizetype>(GST_VIDEO_INFO_PLANE_OFFSET(&info, i));
130 L.height[i] = GstHw::planeHeight(info, i);
131 }
132 L.byteSize = static_cast<qsizetype>(GST_VIDEO_INFO_SIZE(&info));
133 return L;
134}
135
136QAbstractVideoBuffer::MapData CpuVideoFramePool::mapDataFor(const GstVideoFrame& frame)
137{
138 QAbstractVideoBuffer::MapData data;
139 data.planeCount = static_cast<int>(GST_VIDEO_FRAME_N_PLANES(&frame));
140 for (int i = 0; i < data.planeCount; ++i) {
141 data.data[i] = static_cast<uchar*>(GST_VIDEO_FRAME_PLANE_DATA(&frame, i));
142 data.bytesPerLine[i] = GST_VIDEO_FRAME_PLANE_STRIDE(&frame, i);
143 data.dataSize[i] =
144 static_cast<qsizetype>(GST_VIDEO_FRAME_PLANE_STRIDE(&frame, i)) * GstHw::planeHeight(frame.info, i);
145 }
146 return data;
147}
148
149bool CpuVideoFramePool::FrameMapping::mapFrame(GstBuffer* buffer, const GstVideoInfo& info, GstMapFlags flags)
150{
151 if (!_mapped) {
152 _mapped = buffer && gst_video_frame_map(&_frame, &info, buffer, flags);
153 }
154 return _mapped;
155}
156
157QAbstractVideoBuffer::MapData CpuVideoFramePool::FrameMapping::map(GstBuffer* buffer, const GstVideoInfo& info)
158{
159 if (!mapFrame(buffer, info)) {
160 return {};
161 }
162 return mapDataFor(_frame);
163}
164
166{
167 if (_mapped) {
168 gst_video_frame_unmap(&_frame);
169 _mapped = false;
170 }
171}
172
173QByteArray CpuVideoFramePool::acquireBacking(const PlaneLayout& layout, QSize size,
174 QVideoFrameFormat::PixelFormat format)
175{
176 QMutexLocker lock(&_mutex);
177 for (std::size_t i = 0; i < _slots.size(); ++i) {
178 auto& slot = _slots[i];
179 if (slot.size == size && slot.format == format) {
180 // (size,format) implies a fixed byteSize; discard any stale mis-sized backing and keep scanning rather
181 // than stranding it, which would force a permanent miss loop.
182 while (slot.availableCount > 0) {
183 QByteArray b = std::move(slot.available[--slot.availableCount]);
184 if (b.size() == layout.byteSize) {
185 return b;
186 }
187 }
188 break;
189 }
190 }
191 // Qt::Uninitialized skips the value-init memset; caller overwrites every plane.
192 return QByteArray(layout.byteSize, Qt::Uninitialized);
193}
194
195void CpuVideoFramePool::releaseBacking(QSize size, QVideoFrameFormat::PixelFormat format, QByteArray&& backing)
196{
197 QMutexLocker lock(&_mutex);
198 for (std::size_t i = 0; i < _slots.size(); ++i) {
199 auto& slot = _slots[i];
200 if (slot.size == size && slot.format == format) {
201 if (slot.availableCount < kMaxPerSlot) {
202 slot.available[slot.availableCount++] = std::move(backing);
203 }
204 return;
205 }
206 }
207 // No slot for this (size,format): claim an empty slot or round-robin evict to stay bounded.
208 Slot* target = nullptr;
209 for (std::size_t i = 0; i < _slots.size(); ++i) {
210 auto& slot = _slots[i];
211 if (slot.format == QVideoFrameFormat::Format_Invalid) {
212 target = &slot;
213 break;
214 }
215 }
216 if (!target) {
217 target = &_slots[_evictCursor];
218 _evictCursor = (_evictCursor + 1) % kMaxSlots;
219 *target = Slot{};
220 }
221 target->size = size;
222 target->format = format;
223 target->available[0] = std::move(backing);
224 target->availableCount = 1;
225}
226
227QVideoFrame CpuVideoFramePool::acquireFrame(const QVideoFrameFormat& format, const GstVideoInfo& info)
228{
229 const PlaneLayout layout = computeLayout(info);
230 if (layout.planeCount == 0 || layout.byteSize <= 0) {
231 return {};
232 }
233 QByteArray backing = acquireBacking(layout, format.frameSize(), format.pixelFormat());
234 auto buffer = std::make_unique<PooledCpuVideoBuffer>(format, layout, std::move(backing));
235 return QVideoFrame(std::move(buffer));
236}
237
238std::unique_ptr<QAbstractVideoBuffer> CpuVideoFramePool::wrapZeroCopy(GstBuffer* buffer, const GstVideoInfo& info,
239 const QVideoFrameFormat& format,
240 const PinnedFrameCounter& pinned)
241{
242 if (!buffer || !format.isValid() || !pinned) {
243 return nullptr;
244 }
245 // Each zero-copy frame pins a decoder buffer; past the cap copy instead so a GUI stall can't drain a fixed-size
246 // decoder pool.
247 if (!tryReservePinnedFrame(*pinned)) {
248 return nullptr;
249 }
250 auto buf = std::make_unique<MapThroughGstVideoBuffer>(buffer, info, format, pinned);
251 // Probe mappability: system memory always maps, GPU memory that slipped past the factory does not (caller copies).
252 // Keep the mapping rather than unmapping — the sink's subsequent map() reuses it instead of re-running the map.
253 const auto probe = buf->map(QVideoFrame::ReadOnly);
254 if (probe.planeCount <= 0) {
255 return nullptr;
256 }
257 return buf;
258}
259
260QVideoFrame CpuVideoFramePool::copyFromBuffer(GstBuffer* buffer, const GstVideoInfo& videoInfo,
261 const QVideoFrameFormat& format)
262{
263 if (!buffer || !format.isValid()) {
264 return {};
265 }
266
267 FrameMapping source;
268 if (!source.mapFrame(buffer, videoInfo)) {
269 static std::atomic<quint64> s_failCount{0};
270 const quint64 count = s_failCount.fetch_add(1, std::memory_order_relaxed) + 1;
271 if ((count & 0x3F) == 1) {
272 qCWarning(CpuVideoFramePoolLog) << "copyFromBuffer: gst_video_frame_map failed (count=" << count << ")";
273 }
274 return {};
275 }
276
277 const GstVideoFrame& gstFrame = source.frame();
278
279 // Qt reads a frame of the format's size: the buffer's whole frame when its GstVideoMeta is larger than the caps.
280 GstVideoInfo frameInfo = videoInfo;
281 if (!GstHw::setFrameSize(frameInfo, format.frameWidth(), format.frameHeight()) ||
282 (GST_VIDEO_INFO_WIDTH(&frameInfo) > GST_VIDEO_FRAME_WIDTH(&gstFrame)) ||
283 (GST_VIDEO_INFO_HEIGHT(&frameInfo) > GST_VIDEO_FRAME_HEIGHT(&gstFrame))) {
284 static std::atomic<bool> s_warnedFrameSize{false};
285 if (!s_warnedFrameSize.exchange(true, std::memory_order_relaxed)) {
286 qCWarning(CpuVideoFramePoolLog)
287 << "copyFromBuffer: no" << format.frameSize() << "frame in a buffer of"
288 << GST_VIDEO_FRAME_WIDTH(&gstFrame) << "x" << GST_VIDEO_FRAME_HEIGHT(&gstFrame) << "— dropping frame";
289 }
290 return {};
291 }
292
293 QVideoFrame videoFrame = instance().acquireFrame(format, frameInfo);
294 if (!videoFrame.isValid() || !videoFrame.map(QVideoFrame::WriteOnly)) {
295 return {};
296 }
297
298 const int srcPlanes = GST_VIDEO_INFO_N_PLANES(&frameInfo);
299 if (srcPlanes != videoFrame.planeCount()) {
300 static std::atomic<bool> s_warnedPlaneMismatch{false};
301 if (!s_warnedPlaneMismatch.exchange(true, std::memory_order_relaxed)) {
302 qCWarning(CpuVideoFramePoolLog) << "copyFromBuffer: plane-count mismatch src" << srcPlanes << "dst"
303 << videoFrame.planeCount() << "— dropping frame";
304 }
305 videoFrame.unmap();
306 return {};
307 }
308
309 for (int p = 0; p < srcPlanes; ++p) {
310 const int dstStride = videoFrame.bytesPerLine(p);
311 const int srcStride = GST_VIDEO_FRAME_PLANE_STRIDE(&gstFrame, p);
312 // The destination's rows, as gst_video_frame_copy_plane() copies: the mapped frame has the size of the buffer's
313 // GstVideoMeta, which a decoder pads beyond the size the destination has (1088 rows for 1080).
314 const int rows = GstHw::planeHeight(frameInfo, p);
315 const int activeRowBytes = GstHw::planeRowBytes(frameInfo, p);
316 // Reject before copy: a stride too narrow for a row would tear the plane, or read past the source.
317 if (activeRowBytes > (std::min) (srcStride, dstStride)) {
318 static std::atomic<bool> s_warnedStrideOverflow{false};
319 if (!s_warnedStrideOverflow.exchange(true, std::memory_order_relaxed)) {
320 qCWarning(CpuVideoFramePoolLog)
321 << "copyFromBuffer: plane" << p << "activeRowBytes" << activeRowBytes << "> srcStride" << srcStride
322 << "or dstStride" << dstStride << "— dropping frame";
323 }
324 videoFrame.unmap();
325 return {};
326 }
327 const uchar* src = static_cast<const uchar*>(GST_VIDEO_FRAME_PLANE_DATA(&gstFrame, p));
328 uchar* dst = videoFrame.bits(p);
329 if (!dst) {
330 continue;
331 }
332 if (srcStride == dstStride && activeRowBytes == srcStride) {
333 std::memcpy(dst, src, static_cast<size_t>(rows) * srcStride);
334 } else {
335 for (int y = 0; y < rows; ++y) {
336 std::memcpy(dst + y * dstStride, src + y * srcStride, static_cast<size_t>(activeRowBytes));
337 }
338 }
339 }
340
341 videoFrame.unmap();
342 return videoFrame;
343}
#define QGC_LOGGING_CATEGORY(name, categoryStr)
bool mapFrame(GstBuffer *buffer, const GstVideoInfo &info, GstMapFlags flags=GST_MAP_READ)
Maps buffer with flags on the first call; false when that fails.
const GstVideoFrame & frame() const
The mapped frame; valid while mapFrame() succeeded and unmap() hasn't run.
QAbstractVideoBuffer::MapData map(GstBuffer *buffer, const GstVideoInfo &info)
mapFrame() for reading, as Qt map data; empty when the map fails.
static std::unique_ptr< QAbstractVideoBuffer > wrapZeroCopy(GstBuffer *buffer, const GstVideoInfo &info, const QVideoFrameFormat &format, const PinnedFrameCounter &pinned)
std::shared_ptr< std::atomic< int > > PinnedFrameCounter
Live zero-copy frames of one sink; shared so frames Qt still holds after the sink is gone can release...
static CpuVideoFramePool & instance()
static QVideoFrame copyFromBuffer(GstBuffer *buffer, const GstVideoInfo &videoInfo, const QVideoFrameFormat &format)
static constexpr int kMaxPinnedFrames
void releaseBacking(QSize size, QVideoFrameFormat::PixelFormat format, QByteArray &&backing)
Return a backing array to the pool; called by PooledCpuVideoBuffer's destructor only.
static PlaneLayout computeLayout(const GstVideoInfo &info)
Destination plane layout mirroring info (strides/offsets from the decoder). planeCount==0 means unsup...
QVideoFrame acquireFrame(const QVideoFrameFormat &format, const GstVideoInfo &info)
Returns a pool-backed frame sized to info, or freshly allocates on a pool miss; invalid if unsupporte...
static QAbstractVideoBuffer::MapData mapDataFor(const GstVideoFrame &frame)
Qt map data for a frame mapped with gst_video_frame_map, each plane sized by its own row count.
int planeHeight(const GstVideoInfo &info, int plane)
int planeRowBytes(const GstVideoInfo &info, int plane)
bool setFrameSize(GstVideoInfo &info, int width, int height)
QByteArray format(const QList< LogEntry > &entries, int fmt)
GPSCommandSequence base(QByteArrayView port, const GPSBaseStationConfig &base)
Streams RTCM3 corrections and the PVTGeodetic survey status over port in the mode base selects.
Definition SBFPlan.cc:49