Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qmaterializingvideobuffer_p.h
Go to the documentation of this file.
1// Copyright (C) 2026 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#ifndef QMATERIALIZINGVIDEOBUFFER_P_H
5#define QMATERIALIZINGVIDEOBUFFER_P_H
6
7//
8// W A R N I N G
9// -------------
10//
11// This file is not part of the Qt API. It exists purely as an
12// implementation detail. This header file may change from version to
13// version without notice, or even be removed.
14//
15// We mean it.
16//
17
18#include <QtMultimedia/qabstractvideobuffer.h>
19#include <QtMultimedia/qvideoframe.h>
20#include <QtMultimedia/qvideoframeformat.h>
21#include <QtMultimedia/private/qcaptureslotregistry_p.h>
22#include <QtMultimedia/private/qhwvideobuffer_p.h>
23
24#include <QtCore/qbytearray.h>
25#include <QtCore/qdebug.h>
26#include <QtCore/qloggingcategory.h>
27
28#include <array>
29#include <cstring>
30#include <memory>
31#include <mutex>
32#include <optional>
33#include <type_traits>
34#include <utility>
35
36#ifdef __cpp_concepts
37# include <concepts>
38#endif
39
40QT_BEGIN_NAMESPACE
41
42namespace QtMultimediaPrivate {
43
44#ifdef __cpp_concepts
45// clang-format off
46template <typename Source>
52 { source.unmap(mapData) } -> std::same_as<void>;
53 };
54
55template <typename Registry>
58 typename Registry::SlotType;
59 typename Registry::Lease;
62 -> std::same_as<std::optional<typename Registry::Lease>>;
63 };
64
65template <typename BufferType>
67// clang-format on
68#endif
69
70#ifdef __cpp_concepts
72#else
73template <typename Source>
74#endif
75class MaterializableSource final
76{
77public:
78 Q_DISABLE_COPY_MOVE(MaterializableSource)
79
80 explicit MaterializableSource(Source source) : m_source(std::move(source)) { }
81
83 {
84 {
85 std::lock_guard lock(m_mutex);
86 if (m_mappingState == MappingState::SourceMapped) {
87 m_source.unmap(m_sourceMapping);
88 m_sourceMapping = {};
89 m_mappingState = MappingState::None;
90 }
91 }
92 }
93
94 QAbstractVideoBuffer::MapData map(QVideoFrame::MapMode mode)
95 {
96 std::lock_guard lock(m_mutex);
97
98 switch (mode) {
99 case QVideoFrame::ReadOnly: {
100 // If already materialized, serve the copy. But keep SourceMapped mapped if it was.
101 if (m_materialized) {
102 qCDebug(qLcCaptureSlotsTrace) << "returning materialized mapping";
103 return materializedMapData(mode);
104 }
105
106 // Map the source on first read-only access, or re-serve if already mapped.
107 if (m_mappingState == MappingState::None) {
108 std::optional<QAbstractVideoBuffer::MapData> mapping = m_source.mapReadOnly();
109 if (!mapping) {
110 qCWarning(qLcCaptureSlots) << "mapping producer memory failed";
111 return {};
112 }
113 m_sourceMapping = *mapping;
114 m_mappingState = MappingState::SourceMapped;
115 qCDebug(qLcCaptureSlotsTrace)
116 << "mapped source:" << m_sourceMapping.planeCount << "planes";
117 } else {
118 Q_ASSERT(m_mappingState == MappingState::SourceMapped);
119 qCDebug(qLcCaptureSlotsTrace) << "returning stored source mapping";
120 }
121 return m_sourceMapping;
122 }
123 case QVideoFrame::WriteOnly:
124 case QVideoFrame::ReadWrite:
125 // Writing into the producer's capture buffer is not on: take a copy first.
126 qCDebug(qLcCaptureSlotsTrace) << "write map: materializing first";
127 materializeLocked();
128 // Never overwrite an outstanding source mapping: unmap() must still end it.
129 if (m_mappingState == MappingState::None)
130 m_mappingState = MappingState::Copy;
131 return materializedMapData(mode);
132
133 default:
134 Q_UNREACHABLE_RETURN({});
135 }
136 }
137
138 void unmap()
139 {
140 std::lock_guard lock(m_mutex);
141 if (m_mappingState == MappingState::SourceMapped) {
142 qCDebug(qLcCaptureSlotsTrace) << "unmapping source mapping";
143 m_source.unmap(m_sourceMapping);
144 m_sourceMapping = {};
145 m_mappingState = MappingState::None;
146 releaseSourceIfUnused();
147 }
148 }
149
150 // Copy the data out, after which the producer's memory is never touched again.
152 {
153 std::lock_guard lock(m_mutex);
154 materializeLocked();
155 }
156
157 bool isMaterialized() const
158 {
159 std::lock_guard lock(m_mutex);
160 return m_materialized;
161 }
162
163private:
164 enum class MappingState : uint8_t {
165 None, // No mapping or materialization yet.
166 SourceMapped, // Source is currently mapped by mapReadOnly().
167 Copy, // Materialized copy is available.
168 };
169
170 void materializeLocked()
171 {
172 if (m_materialized) {
173 qCDebug(qLcCaptureSlotsTrace) << "already materialized";
174 return;
175 }
176
177 // Copy out of the consumer's existing mapping rather than mapping a second time, and leave
178 // it mapped -- they may be holding pointers into it.
179 QAbstractVideoBuffer::MapData source{};
180 std::optional<QAbstractVideoBuffer::MapData> freshMapping;
181 if (m_mappingState == MappingState::SourceMapped) {
182 source = m_sourceMapping;
183 } else {
184 freshMapping = m_source.mapReadOnly();
185 if (freshMapping) {
186 source = *freshMapping;
187 } else {
188 qCWarning(qLcCaptureSlots) << "mapping producer memory for copy-out failed";
189 }
190 }
191
192 qsizetype totalSize = 0;
193 for (int i = 0; i < source.planeCount; ++i)
194 totalSize += source.dataSize[i];
195
196 m_data.resizeForOverwrite(totalSize);
197 m_materializedMapping = {};
198 m_materializedMapping.planeCount = source.planeCount;
199
200 qsizetype offset = 0;
201 for (int i = 0; i < source.planeCount; ++i) {
202 std::memcpy(m_data.data() + offset, source.data[i], size_t(source.dataSize[i]));
203 m_planeOffsets[i] = offset;
204 m_materializedMapping.bytesPerLine[i] = source.bytesPerLine[i];
205 m_materializedMapping.dataSize[i] = source.dataSize[i];
206 offset += source.dataSize[i];
207 }
208 qCDebug(qLcCaptureSlotsTrace)
209 << "materialized" << source.planeCount << "planes," << totalSize << "bytes";
210
211 if (freshMapping)
212 m_source.unmap(*freshMapping);
213
214 m_materialized = true;
215 releaseSourceIfUnused();
216 }
217
218 // The source is only still needed to undo an outstanding mapping.
219 void releaseSourceIfUnused()
220 {
221 if (m_materialized && m_mappingState != MappingState::SourceMapped)
222 m_source = Source{};
223 }
224
225 QAbstractVideoBuffer::MapData materializedMapData(QVideoFrame::MapMode mode)
226 {
227 QAbstractVideoBuffer::MapData mapData = m_materializedMapping;
228 auto *base = mode == QVideoFrame::ReadOnly
229 ? reinterpret_cast<uchar *>(const_cast<char *>(m_data.constData()))
230 : reinterpret_cast<uchar *>(m_data.data());
231 for (int i = 0; i < mapData.planeCount; ++i)
232 mapData.data[i] = base + m_planeOffsets[i];
233 return mapData;
234 }
235
236 mutable QMutex m_mutex;
237
238 Source m_source;
239 QAbstractVideoBuffer::MapData m_sourceMapping;
240 MappingState m_mappingState = MappingState::None;
241
242 bool m_materialized = false;
243 QByteArray m_data;
244 QAbstractVideoBuffer::MapData m_materializedMapping;
245 std::array<qsizetype, 4> m_planeOffsets{};
246};
247
248// A video buffer wrapping producer-owned capture memory, holding the producer's slot for as long
249// as any QVideoFrame references it.
250#ifdef __cpp_concepts
253#else
254template <typename Source, typename Registry, typename Base = QHwVideoBuffer>
255#endif
256class MaterializingVideoBuffer final : public Base
257{
258 static_assert(std::is_base_of_v<QAbstractVideoBuffer, Base>);
259
260public:
261 using State = MaterializableSource<Source>;
262 using SlotType = typename Registry::SlotType;
263 using Lease = typename Registry::Lease;
264
265 // On refusal, slot is left intact for the caller's eager-copy fallback.
266 template <typename SlotArg, typename... BaseArgs>
268 tryCreate(Registry &registry, SlotArg &&slot, Source source, QVideoFrameFormat format = {},
269 BaseArgs &&...baseArgs)
270 {
271 std::optional lease = registry.tryReserveSlot(slot);
272 if (!lease) {
273 qCDebug(qLcCaptureSlotsTrace) << "pool under pressure, caller must copy eagerly";
274 return nullptr;
275 }
276
277 return std::make_unique<MaterializingVideoBuffer>(std::move(*lease), std::move(source),
278 std::move(format),
279 std::forward<BaseArgs>(baseArgs)...);
280 }
281
283
284 template <typename... BaseArgs>
293
299
300 State &state() noexcept { return m_state; }
301
302 template <typename... BaseArgs>
306
307private:
308 const Lease m_lease;
309 State m_state;
310 const QVideoFrameFormat m_format;
311};
312
313// The eager-copy counterpart of MaterializingVideoBuffer: copies the producer's memory up front
314// and holds no capture slot. This is what a producer falls back to when back-pressure refuses a
315// slot, or when the format has to be copied anyway.
316#ifdef __cpp_concepts
318#else
319template <typename Source>
320#endif
321class MaterializedVideoBuffer final : public QAbstractVideoBuffer
322{
323public:
324 Q_DISABLE_COPY_MOVE(MaterializedVideoBuffer)
325
326 explicit MaterializedVideoBuffer(Source source, QVideoFrameFormat format = {})
327 : m_state(std::move(source)), m_format(std::move(format))
328 {
329 m_state.materialize();
330 qCDebug(qLcCaptureSlotsTrace) << "copied producer memory eagerly";
331 }
332
333 MapData map(QVideoFrame::MapMode mode) override { return m_state.map(mode); }
334 void unmap() override { m_state.unmap(); }
335 QVideoFrameFormat format() const override { return m_format; }
336
337private:
338 // Not const: map()/unmap() drive the state machine.
339 MaterializableSource<Source> m_state;
340 const QVideoFrameFormat m_format;
341};
342
343#ifdef __cpp_concepts
345#else
346template <typename Source, typename Registry, typename Base>
347#endif
348template <typename... BaseArgs>
349inline std::unique_ptr<QAbstractVideoBuffer>
350MaterializingVideoBuffer<Source, Registry, Base>::wrapOrMaterialize(Registry &registry,
351 SlotType slot, Source source,
352 QVideoFrameFormat format,
353 BaseArgs &&...baseArgs)
354{
355 if (auto ret = tryCreate(registry, slot, source, format, std::forward<BaseArgs>(baseArgs)...))
356 return ret;
357
358 auto ret =
359 std::make_unique<MaterializedVideoBuffer<Source>>(std::move(source), std::move(format));
360 registry.recycleSlot(std::move(slot));
361 return ret;
362}
363
364} // namespace QtMultimediaPrivate
365
366QT_END_NAMESPACE
367
368#endif // QMATERIALIZINGVIDEOBUFFER_P_H
QAbstractVideoBuffer::MapData map(QVideoFrame::MapMode mode)
QVideoFrameFormat format() const override
Gets \l QVideoFrameFormat of the underlying video buffer.
void unmap() override
Releases the memory mapped by the map() function.
MaterializedVideoBuffer(Source source, QVideoFrameFormat format={})
MapData map(QVideoFrame::MapMode mode) override
Maps the planes of a video buffer to memory.
MaterializingVideoBuffer(Lease lease, Source source, QVideoFrameFormat format={}, BaseArgs &&...baseArgs)
static std::unique_ptr< MaterializingVideoBuffer > tryCreate(Registry &registry, SlotArg &&slot, Source source, QVideoFrameFormat format={}, BaseArgs &&...baseArgs)