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
framegrabber.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3
5
7
8#include <QtTest/qtest.h>
9#include <QtTest/private/qtestblacklist_p.h>
10#include <QtMultimedia/qvideoframe.h>
11#include <QtCore/q20vector.h>
12#include <QtCore/qcoreapplication.h>
13#include <QtCore/qelapsedtimer.h>
14#include <QtCore/qscopeguard.h>
15
16#include <utility>
17
18QT_BEGIN_NAMESPACE
19
21
22using namespace Qt::StringLiterals;
23
24std::chrono::milliseconds surfaceCaptureTestTimeout()
25{
26 // A blacklisted test is expected to fail, so don't make it wait for the full
27 // timeout to do so.
28 if (const char *testFunction = QTest::currentTestFunction();
29 testFunction && QTestPrivate::checkBlackLists(testFunction, QTest::currentDataTag())) {
30 return std::chrono::seconds(1);
31 }
32
33 if (isCI())
34 return std::chrono::seconds(60);
35 return std::chrono::seconds(5);
36}
37
38[[nodiscard]] static std::optional<std::chrono::milliseconds> maxFrameInterval(std::optional<qreal> frameRate)
39{
40 if (!frameRate || *frameRate <= 0)
41 return std::nullopt;
42
43 // Slightly longer than the nominal interval. More forgiving on loaded CI machines.
44 const qreal margin = isCI() ? 3.0 : 1.5;
45 return std::chrono::milliseconds(qRound64(1000.0 / *frameRate * margin));
46}
47
48QString frameTimeToString(std::optional<std::chrono::microseconds> time)
49{
50 if (!time)
51 return u"unset"_s;
52 return u"%1us"_s.arg(time->count());
53}
54
55// QVideoFrame reports an unset time as -1
56[[nodiscard]] static std::optional<std::chrono::microseconds> toFrameTime(qint64 time)
57{
58 if (time < 0)
59 return std::nullopt;
60 return std::chrono::microseconds(time);
61}
62
63[[nodiscard]] static std::optional<std::chrono::microseconds> startTimeOf(const QVideoFrame &frame)
64{
65 return toFrameTime(frame.startTime());
66}
67
68[[nodiscard]] static std::optional<std::chrono::microseconds> startTimeOf(const VideoFrameInfo &info)
69{
70 return info.startTime;
71}
72
73static VideoFrameInfo makeVideoFrameInfo(const QVideoFrame &frame)
74{
75 return VideoFrameInfo{
76 frame.isValid(),
77 frame.size(),
78 frame.pixelFormat(),
79 toFrameTime(frame.startTime()),
80 toFrameTime(frame.endTime()),
81 frame.streamFrameRate(),
82 };
83}
84
85FrameGrabber::FrameGrabber()
86{
87 connect(this, &QVideoSink::videoFrameChanged, this, &FrameGrabber::onFrameReceived);
88}
89
90void FrameGrabber::onFrameReceived(const QVideoFrame &frame)
91{
92 m_frameInfos.push_back(makeVideoFrameInfo(frame));
93 if (m_retainVideoFrames)
94 m_videoFrames.push_back(frame);
95
96 if (!frame.isValid()) {
97 // A null-frame ends the stream, and the next valid frame starts a new one.
98 resetFirstFrame();
99 m_streamStarted = false;
100 } else if (!m_streamStarted) {
101 m_firstFrameInfo = m_frameInfos.back();
102 if (m_retainFirstVideoFrame)
103 m_firstVideoFrame = frame;
104 m_streamStarted = true;
105 }
106}
107
109{
110 return m_frameInfos;
111}
112
114 size_t minCount,
115 std::optional<qreal> expectedFrameRate,
116 std::optional<std::chrono::microseconds> noOlderThanTime)
117{
118 return waitAndTake(m_frameInfos, minCount, expectedFrameRate, noOlderThanTime);
119}
120
122 size_t minCount,
123 std::optional<qreal> expectedFrameRate,
124 std::optional<std::chrono::microseconds> noOlderThanTime)
125{
126 // Holding on to QVideoFrames can stall backends that use a fixed-size
127 // frame pool, so only retain them while the caller is waiting for them.
128 m_retainVideoFrames = true;
129 const auto stopRetaining = qScopeGuard([this] {
130 m_retainVideoFrames = false;
131 m_videoFrames.clear();
132 });
133
134 return waitAndTake(m_videoFrames, minCount, expectedFrameRate, noOlderThanTime);
135}
136
137template <typename Frame>
138std::vector<Frame> FrameGrabber::waitAndTake(
139 std::vector<Frame> &frames,
140 size_t minCount,
141 std::optional<qreal> expectedFrameRate,
142 std::optional<std::chrono::microseconds> noOlderThanTime)
143{
144 m_frameInfos.clear();
145 m_videoFrames.clear();
146
147 const auto enoughFramesOrStopped = [this, &frames, minCount, noOlderThanTime]() -> bool {
148 if (m_stopped)
149 return true; // Stop waiting
150
151 // ensure that all signals &QVideoSink::videoFrameChanged have been processed
152 QCoreApplication::processEvents(QEventLoop::AllEvents);
153
154 if (noOlderThanTime) {
155 // Reject frames older than noOlderThanTime
156 q20::erase_if(frames, [noOlderThanTime](const Frame &frame) {
157 return startTimeOf(frame) <= noOlderThanTime;
158 });
159 }
160
161 return frames.size() >= minCount;
162 };
163
164 // The first frame may be delayed by initialization. Beyond that, each
165 // frame is due within the frame interval.
166 std::chrono::milliseconds timeout = surfaceCaptureTestTimeout();
167 std::optional<std::chrono::milliseconds> interval = maxFrameInterval(expectedFrameRate);
168 if (interval)
169 timeout += *interval * qint64(minCount);
170
171 if (!QTest::qWaitFor(enoughFramesOrStopped, timeout))
172 return {};
173
174 if (m_stopped)
175 return {};
176
177 return std::exchange(frames, {});
178}
179
180bool FrameGrabber::waitForFirstFrame()
181{
182 const auto firstFrameReceivedOrStopped = [this] {
183 return m_stopped || m_firstFrameInfo;
184 };
185
186 if (!QTest::qWaitFor(firstFrameReceivedOrStopped, surfaceCaptureTestTimeout()))
187 return false;
188
189 return !m_stopped;
190}
191
193{
194 if (!waitForFirstFrame())
195 return std::nullopt;
196
197 return m_firstFrameInfo;
198}
199
201{
202 Q_ASSERT_X(
203 m_retainFirstVideoFrame,
204 "FrameGrabber::consumeFirstVideoFrame",
205 "setRetainFirstVideoFrame() must be enabled before the stream starts");
206
207 if (!waitForFirstFrame())
208 return std::nullopt;
209
210 return std::exchange(m_firstVideoFrame, std::nullopt);
211}
212
214{
215 m_retainFirstVideoFrame = retain;
216 if (!retain)
217 m_firstVideoFrame.reset();
218}
219
220void FrameGrabber::resetFirstFrame()
221{
222 m_firstFrameInfo.reset();
223 m_firstVideoFrame.reset();
224}
225
226std::optional<std::chrono::milliseconds> FrameGrabber::durationBetweenFrames(
227 qsizetype frameCount,
228 std::optional<qreal> expectedFrameRate)
229{
230 Q_ASSERT(frameCount > 0);
231
232 using namespace std::chrono;
233
234 QElapsedTimer timer;
235 QElapsedTimer sinceLastFrame;
236 qsizetype framesReceived = 0;
237
238 QObject context;
239 connect(this, &QVideoSink::videoFrameChanged, &context, [&]() {
240 if (framesReceived++ == 0)
241 timer.start();
242 sinceLastFrame.start();
243 });
244
245 std::optional<milliseconds> maxInterval = maxFrameInterval(expectedFrameRate);
246
247 // Fails early if the frames stop coming at the expected rate.
248 auto allFramesReceivedOrStalled = [&]() {
249 if (framesReceived > frameCount)
250 return true;
251 return maxInterval && framesReceived > 0 && sinceLastFrame.hasExpired(maxInterval->count());
252 };
253
254 // Without an expected frame rate, assume the stream runs at 1 FPS minimum.
255 // With one, the first frame gets the global timeout, and each of the rest are
256 // checked against the frame interval above.
257 milliseconds timeout = surfaceCaptureTestTimeout();
258 if (maxInterval)
259 timeout += *maxInterval * frameCount;
260 else
261 timeout = isCI() ? 10s * frameCount : 2s * frameCount;
262
263 if (!QTest::qWaitFor(allFramesReceivedOrStalled, timeout) || framesReceived <= frameCount)
264 return std::nullopt;
265
266 return milliseconds(timer.elapsed() / frameCount);
267}
268
270{
271 return m_stopped;
272}
273
275{
276 // Not all backends end the stream with a null-frame, so treat activation
277 // as the start of a new stream as well.
278 if (active) {
279 resetFirstFrame();
280 m_streamStarted = false;
281 }
282}
283
284void FrameGrabber::stop()
285{
286 m_stopped = true;
287}
288
289} // namespace QtMultimediaTest
290
291QT_END_NAMESPACE
292
293#include "moc_framegrabber_p.cpp"
The FrameGrabber stores frames that arrive from a surface capture, and is used to inspect captured fr...
void onCaptureActiveChanged(bool active)
Starts tracking a new stream when the capture becomes active, so that tryWaitForFirstFrameInfo() wait...
void setRetainFirstVideoFrame(bool retain)
std::optional< std::chrono::milliseconds > durationBetweenFrames(qsizetype frameCount=1, std::optional< qreal > expectedFrameRate=std::nullopt)
Measures the average duration between frameCount consecutive frames.
const std::vector< VideoFrameInfo > & getFrameInfos() const
std::optional< QVideoFrame > consumeFirstVideoFrame()
Same as tryWaitForFirstFrameInfo(), but returns the video frame itself, and consumes it.
std::vector< QVideoFrame > waitAndTakeVideoFrames(size_t minCount, std::optional< qreal > expectedFrameRate=std::nullopt, std::optional< std::chrono::microseconds > noOlderThanTime=std::nullopt)
Same as waitAndTakeFrameInfos(), but returns the video frames themselves.
std::optional< VideoFrameInfo > tryWaitForFirstFrameInfo()
Waits for the first frame of the current stream, and returns a copy of its info.
std::vector< VideoFrameInfo > waitAndTakeFrameInfos(size_t minCount, std::optional< qreal > expectedFrameRate=std::nullopt, std::optional< std::chrono::microseconds > noOlderThanTime=std::nullopt)
Wait for at least minCount frames that are no older than noOlderThanTime.
static std::optional< std::chrono::milliseconds > maxFrameInterval(std::optional< qreal > frameRate)
static std::optional< std::chrono::microseconds > startTimeOf(const QVideoFrame &frame)
static std::optional< std::chrono::microseconds > startTimeOf(const VideoFrameInfo &info)
static VideoFrameInfo makeVideoFrameInfo(const QVideoFrame &frame)
std::chrono::milliseconds surfaceCaptureTestTimeout()
QString frameTimeToString(std::optional< std::chrono::microseconds > time)
static std::optional< std::chrono::microseconds > toFrameTime(qint64 time)