QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
QtMultimediaVideoReceiver.cc
Go to the documentation of this file.
2
3#include <algorithm>
4
5#include <QtCore/QBuffer>
6#include <QtMultimedia/QMediaCaptureSession>
7#include <QtMultimedia/QMediaFormat>
8#include <QtMultimedia/QMediaMetaData>
9#include <QtMultimedia/QPlaybackOptions>
10#include <QtMultimedia/QVideoFrame>
11#include <QtMultimedia/QVideoFrameInput>
12#include <QtMultimedia/QVideoSink>
13
14#include "QGCLoggingCategory.h"
15#include "QtVideoRecorder.h"
16#include "SharedVideoFrame.h"
17#include "VideoStreamStats.h"
18#include "VideoStreamUri.h"
19
20QGC_LOGGING_CATEGORY(QtMultimediaVideoReceiverLog, "Video.QtMultimediaVideoReceiver")
21
22namespace {
23
24constexpr int kSampleIntervalMs = 1000;
27constexpr qint64 kFirstFrameGraceMs = 5000;
29constexpr qint64 kMinFrameStepUs = 1000;
31constexpr qint64 kMaxStreamStepUs = 1000000;
32
38constexpr int kDescribedStreamProbeBytes = 8192;
41#ifdef Q_OS_ANDROID
42constexpr bool kShortProbe = false;
43#else
44constexpr bool kShortProbe = true;
45#endif
46
47constexpr const char* kRtspTransportEnv = "QT_FFMPEG_RTSP_TRANSPORT";
48
54void setRtspTransport(bool overTcp)
55{
56 static const QByteArray userTransport = qgetenv(kRtspTransportEnv);
57 const QByteArray transport = overTcp ? QByteArrayLiteral("tcp") : userTransport;
58 // Written only to change it: a write races with any thread that reads the environment.
59 if (qgetenv(kRtspTransportEnv) == transport) {
60 return;
61 }
62 if (transport.isNull()) {
63 (void) qunsetenv(kRtspTransportEnv);
64 } else {
65 (void) qputenv(kRtspTransportEnv, transport);
66 }
67}
68
70QByteArray rtpSdp(const QString& host, int port, QByteArrayView encoding)
71{
72 const QByteArray address = (host.isEmpty() ? QStringLiteral("0.0.0.0") : host).toLatin1();
73 return QByteArrayLiteral("v=0\r\n") + "o=- 0 0 IN IP4 " + address + "\r\ns=QGroundControl\r\nc=IN IP4 " + address +
74 "\r\nt=0 0\r\nm=video " + QByteArray::number(port) + " RTP/AVP 96\r\na=rtpmap:96 " + encoding + "/90000\r\n";
75}
76
77} // namespace
78
80 : VideoReceiver(parent)
81 , _supervisor(new StreamSupervisor(this))
82 , _statsSampler(*_supervisor)
83 , _recorder(new QtVideoRecorder(this))
84{
85 (void) connect(_supervisor, &StreamSupervisor::stateChanged, this, &QtMultimediaVideoReceiver::setState);
89 // Each file's times start at its first frame, also after a format that failed to encode.
90 (void) connect(_recorder->mediaRecorder(), &QMediaRecorder::recorderStateChanged, this,
91 [this](QMediaRecorder::RecorderState state) {
92 if (state == QMediaRecorder::RecordingState) {
93 _sinceRecordingStarted.invalidate();
94 _lastRecordedUs = -1;
95 _lastStreamUs = -1;
96 }
97 });
98 (void) connect(_supervisor, &StreamSupervisor::reconnectDue, this, &QtMultimediaVideoReceiver::_start);
99 _sampleTimer.setInterval(kSampleIntervalMs);
100 (void) connect(&_sampleTimer, &QTimer::timeout, this, &QtMultimediaVideoReceiver::_sample);
101}
102
104{
105 _closing = true;
106 _sampleTimer.stop();
107 // Qt writes the file on a thread of its own, which the application's exit would cut short.
108 _recorder->stopAndWait();
109 // As _stopSession(): unloaded first, so that its destruction doesn't wait out a network read.
110 if (_player) {
111 _player->setSource(QUrl());
112 }
113}
114
115std::optional<QtMultimediaVideoReceiver::Source> QtMultimediaVideoReceiver::playerSource(const QString& uri)
116{
117 const QUrl url(uri);
118 if (uri.isEmpty() || !url.isValid() || url.scheme().isEmpty()) {
119 return std::nullopt;
120 }
121
123 const std::optional<Transport> transport = VideoStreamUri::transportFor(url);
124 if ((transport == Transport::RtpUdpH264) || (transport == Transport::RtpUdpH265)) {
125 if (url.port() <= 0) {
126 return std::nullopt;
127 }
128 const QByteArrayView encoding = (transport == Transport::RtpUdpH265) ? "H265" : "H264";
129 return Source{.url = QUrl(QStringLiteral("stream.sdp")),
130 .sdp = rtpSdp(url.host(), url.port(), encoding),
131 .streamsDescribed = true};
132 }
133 if (transport == Transport::MpegTsUdp) {
134 QUrl udp(url);
135 udp.setScheme(QStringLiteral("udp"));
136 return Source{udp, {}};
137 }
138 if ((transport == Transport::Rtsp) && (url.scheme().compare(QStringLiteral("rtspt"), Qt::CaseInsensitive) == 0)) {
139 QUrl rtsp(url);
140 rtsp.setScheme(QStringLiteral("rtsp"));
141 return Source{.url = rtsp, .sdp = {}, .rtspOverTcp = true, .streamsDescribed = true};
142 }
143 return Source{.url = url, .sdp = {}, .streamsDescribed = (transport == Transport::Rtsp)};
144}
145
147{
148 // autoReconnect alone applies at once: a reconnect it no longer allows is dropped.
149 if (_player || _supervisor->reconnectPending()) {
150 Config previous = _sessionConfig;
152 if (previous == config()) {
153 (void) _supervisor->autoReconnectChanged(config().autoReconnect);
154 return;
155 }
156 }
157 _startOver();
158}
159
161{
162 if (!active()) {
163 _recorder->stop();
164 }
165 _startOver();
166}
167
169{
170 _startOver();
171}
172
174{
175 _supervisor->reconnectNow();
176}
177
178void QtMultimediaVideoReceiver::_startOver()
179{
180 _supervisor->startOver();
181 _start();
182}
183
185{
186 // Taking its output from a playing player waits out its network read on this thread, as stopping it would (Qt
187 // joins the demuxer's thread uncancelled): the session starts over without one instead.
188 if (_player && _player->videoSink() && !videoSink()) {
189 _startOver();
190 }
191 _bindVideoSink();
192 // The watchdog counts from now: no frame reached an output while there was none.
193 _sinceFrame.start();
194}
195
197{
198 if (_recorder->active()) {
199 qCWarning(QtMultimediaVideoReceiverLog) << "Not recording" << name() << "to" << file << "- recording already";
200 return;
201 }
202 if (!_recordingSession) {
203 _recordingSession = new QMediaCaptureSession(this);
204 _frameInput = new QVideoFrameInput(this);
205 _recordingSession->setVideoFrameInput(_frameInput);
206 _recordingSession->setRecorder(_recorder->mediaRecorder());
207 }
208 qCDebug(QtMultimediaVideoReceiverLog) << name() << "recording to" << file;
209 _recorder->start(file, QtVideoRecorder::container(format), recordingEncoding().codec, recordingEncoding().quality);
210}
211
213{
214 _recorder->stop();
215}
216
217void QtMultimediaVideoReceiver::_start()
218{
219 _stopSession();
220 if (!active() || config().uri.isEmpty()) {
221 _supervisor->stop();
222 return;
223 }
224 if (!playerSource(config().uri)) {
225 qCWarning(QtMultimediaVideoReceiverLog) << name() << "can't play" << config().uri;
226 _supervisor->stop();
227 emit errorOccurred(tr("Unable to play the video stream %1.").arg(config().uri));
228 return;
229 }
230 _supervisor->sessionStarted();
231 // Queued after the replaced player's unloading (_stopSession()): Windows doesn't let the new player bind a UDP port
232 // the old one still holds.
233 if (!_openPending) {
234 _openPending = true;
235 QMetaObject::invokeMethod(this, &QtMultimediaVideoReceiver::_open, Qt::QueuedConnection);
236 }
237}
238
239void QtMultimediaVideoReceiver::_open()
240{
241 _openPending = false;
242 // Stopped or restarted meanwhile: that _start() reported or opens it.
243 const std::optional<Source> source = playerSource(config().uri);
244 if (_player || !active() || !source || _closing) {
245 return;
246 }
247
248 _sessionConfig = config();
249 // Before the player opens its sockets, so its own timeout can't run out sooner than this one.
250 _sinceOpened.start();
251 _player = new QMediaPlayer(this);
252 QPlaybackOptions options;
253 options.setNetworkTimeout(config().timeout);
254 if (config().lowLatency) {
255 options.setPlaybackIntent(QPlaybackOptions::PlaybackIntent::LowLatencyStreaming);
256 }
257 if (kShortProbe && source->streamsDescribed) {
258 options.setProbeSize(kDescribedStreamProbeBytes);
259 }
260 _player->setPlaybackOptions(options);
261 (void) connect(_player, &QMediaPlayer::mediaStatusChanged, this, &QtMultimediaVideoReceiver::_onMediaStatusChanged);
262 (void) connect(_player, &QMediaPlayer::errorOccurred, this,
263 [this](QMediaPlayer::Error, const QString& errorString) { _fail(errorString); });
264 _bindVideoSink();
265 if (source->url.scheme().compare(QStringLiteral("rtsp"), Qt::CaseInsensitive) == 0) {
266 setRtspTransport(source->rtspOverTcp);
267 }
268 if (source->sdp.isEmpty()) {
269 _player->setSource(source->url);
270 } else {
271 auto* const sdp = new QBuffer(_player);
272 sdp->setData(source->sdp);
273 (void) sdp->open(QIODevice::ReadOnly);
274 _player->setSourceDevice(sdp, source->url);
275 }
276 qCDebug(QtMultimediaVideoReceiverLog) << name() << "playing" << config().uri;
277 _sinceFrame.start();
278 _sampleTimer.start();
279 _player->play();
280}
281
282void QtMultimediaVideoReceiver::_stopSession()
283{
284 _sampleTimer.stop();
285 if (_player) {
286 QMediaPlayer* const player = std::exchange(_player, nullptr);
287 (void) disconnect(player, nullptr, this, nullptr);
288 // Unloaded before it goes: that cancels a network read first, which stopping it or detaching its sink would
289 // wait out on this thread, for up to the network timeout per socket. Later, as this may run in one of its
290 // signals. The output keeps the last frame (VideoOutput.KeepLastFrame).
291 QMetaObject::invokeMethod(
292 player,
293 [player] {
294 player->setSource(QUrl());
295 delete player;
296 },
297 Qt::QueuedConnection);
298 }
299 (void) _statsSampler.reset();
300 _frames = 0;
301 _gpuFrames = false;
302 setDecoding(false);
303 setStats(_statsSampler.stats());
304}
305
306bool QtMultimediaVideoReceiver::_awaitingSender() const
307{
308 const std::optional<VideoStreamUri::Transport> transport = VideoStreamUri::transportFor(QUrl(_sessionConfig.uri));
309 // A session that ends sooner than its timeout didn't run out of patience: its port is taken, or it can't play.
310 return transport && VideoStreamUri::listens(*transport) &&
311 (_supervisor->phase() == StreamSupervisor::Phase::Connecting) &&
312 (_sinceOpened.durationElapsed() >= _sessionConfig.timeout);
313}
314
315void QtMultimediaVideoReceiver::_fail(const QString& reason)
316{
317 if (!_player) {
318 return;
319 }
320 if (_awaitingSender()) {
321 // FFmpeg gives up on a silent port; a backoff would leave it unbound when the stream starts.
322 qCDebug(QtMultimediaVideoReceiverLog) << name() << "no stream yet, listening on:" << reason;
323 _start();
324 return;
325 }
326 _stopSession();
327 const StreamSupervisor::FailureOutcome outcome =
328 _supervisor->sessionFailed(reason, StreamSupervisor::Failure::Transient, config().autoReconnect);
329 if (outcome.halted) {
330 qCDebug(QtMultimediaVideoReceiverLog) << name() << "failed:" << reason;
331 emit errorOccurred(tr("Video stream failed: %1").arg(reason));
332 } else {
333 qCDebug(QtMultimediaVideoReceiverLog)
334 << name() << "failed, reconnecting in" << outcome.reconnectDelay << ":" << reason;
335 }
336}
337
338void QtMultimediaVideoReceiver::_bindVideoSink()
339{
340 QVideoSink* const sink = videoSink();
341 (void) disconnect(_frameConnection);
342 if (sink) {
343 _frameConnection =
344 connect(sink, &QVideoSink::videoFrameChanged, this, &QtMultimediaVideoReceiver::_onVideoFrame);
345 }
346 if (_player) {
347 _player->setVideoSink(sink);
348 }
349 if (!sink) {
350 setDecoding(false);
351 }
352}
353
354void QtMultimediaVideoReceiver::_onMediaStatusChanged(QMediaPlayer::MediaStatus status)
355{
356 switch (status) {
357 case QMediaPlayer::BufferedMedia:
358 _supervisor->sessionStreaming();
359 break;
360 case QMediaPlayer::EndOfMedia:
361 _fail(tr("the stream ended"));
362 break;
363 case QMediaPlayer::InvalidMedia:
364 _fail(_player ? _player->errorString() : QString());
365 break;
366 default:
367 break;
368 }
369}
370
371void QtMultimediaVideoReceiver::_onVideoFrame(const QVideoFrame& frame)
372{
373 // An invalid frame clears the display; frames can also arrive queued from a session that ended.
374 if (!_player || !frame.isValid()) {
375 return;
376 }
377 _sinceFrame.restart();
378 ++_frames;
379 _gpuFrames = (frame.handleType() != QVideoFrame::NoHandle);
381 _supervisor->sessionStreaming();
382 setDecoding(true);
383 _recordFrame(frame);
384}
385
386void QtMultimediaVideoReceiver::_recordFrame(const QVideoFrame& frame)
387{
388 if (!_frameInput || !_recorder->active()) {
389 return;
390 }
391 if (!_sinceRecordingStarted.isValid()) {
392 _sinceRecordingStarted.start();
393 }
394 // A frame of its own: its times are the recording's, not the stream's, and copies of a frame share them.
395 QVideoFrame recorded = SharedVideoFrame::withOwnMetadata(frame);
396 const qint64 recordedUs = recordingTimeUs(_lastRecordedUs, _lastStreamUs, frame.startTime(),
397 _sinceRecordingStarted.nsecsElapsed() / 1000);
398 recorded.setStartTime(recordedUs);
399 recorded.setEndTime(-1);
400 // One the encoder can't take yet is dropped, as the display drops a frame it can't show in time.
401 if (_frameInput->sendVideoFrame(recorded)) {
402 _lastRecordedUs = recordedUs;
403 _lastStreamUs = frame.startTime();
404 }
405}
406
407qint64 QtMultimediaVideoReceiver::recordingTimeUs(qint64 lastRecordedUs, qint64 lastStreamUs, qint64 streamUs,
408 qint64 arrivalUs)
409{
410 if (lastRecordedUs < 0) {
411 return arrivalUs;
412 }
413 // Frames queued while the GUI thread was busy arrive together, so they take the stream's spacing.
414 const qint64 streamStepUs = ((streamUs >= 0) && (lastStreamUs >= 0)) ? (streamUs - lastStreamUs) : -1;
415 const qint64 timeUs =
416 ((streamStepUs > 0) && (streamStepUs < kMaxStreamStepUs)) ? (lastRecordedUs + streamStepUs) : arrivalUs;
417 return std::max(timeUs, lastRecordedUs + kMinFrameStepUs);
418}
419
420void QtMultimediaVideoReceiver::_sample()
421{
422 if (!_player) {
423 return;
424 }
425 const qint64 timeoutMs = std::chrono::duration_cast<std::chrono::milliseconds>(config().timeout).count() +
426 ((_frames == 0) ? kFirstFrameGraceMs : 0);
427 if (videoSink() && (_sinceFrame.elapsed() > timeoutMs)) {
428 _fail(tr("no video for %1 s").arg(timeoutMs / 1000));
429 return;
430 }
431 if (_frames == 0) {
432 return;
433 }
434
435 VideoStreamStats stats = _statsSampler.stats();
436 stats.decoder = QStringLiteral("Qt Multimedia");
437 // Qt's FFmpeg backend hands over GPU frames only from a hardware decoder; a hardware decoder's frames copied to
438 // memory read as software.
439 stats.hardwareDecoder = _gpuFrames;
440 stats.gpuPath = _gpuFrames ? QStringLiteral("GPU") : QStringLiteral("CPU");
441 const auto codec = _player->metaData().value(QMediaMetaData::VideoCodec).value<QMediaFormat::VideoCodec>();
442 stats.codec =
443 (codec == QMediaFormat::VideoCodec::Unspecified) ? QString() : QMediaFormat::videoCodecDescription(codec);
444 // The player doesn't tell how many bytes it received, so there is no bitrate.
445 VideoStreamStatsMeter::Counters counters;
446 counters.framesDisplayed = _frames;
447 if (_statsSampler.sample(counters, stats, nullptr)) {
448 setStats(_statsSampler.stats());
449 }
450}
#define QGC_LOGGING_CATEGORY(name, categoryStr)
QtMultimediaVideoReceiver(QObject *parent=nullptr)
void onVideoOutputChanged() override
Also called when the current output is set again.
void onStartRecording(const QString &file, FileFormat format) override
static std::optional< Source > playerSource(const QString &uri)
void recordingChanged(bool recording)
static QMediaFormat::FileFormat container(VideoReceiver::FileFormat format)
The container of format.
void recordingFinished(const QString &file, const QString &error)
error is empty for a recording that finished normally.
void recordingStarted(const QString &file)
The reconnect policy both receivers share: the phase a stream is in, when a failed one connects again...
void reconnectDue()
A failure's backoff has passed, or reconnectNow() cut it short: the receiver starts the next session.
void stop()
The stream isn't wanted (anymore): Idle, without a reconnect.
@ Transient
It may, so reconnecting is worth it.
@ Connecting
A session runs, without data yet.
void stateChanged(VideoReceiver::State state)
void setVideoSize(QSize size)
State state() const
VideoReceiver(QObject *parent=nullptr)
void setStats(const VideoStreamStats &stats)
Backends publish a new measurement, and an invalid one once the stream stops or reconnects.
QVideoSink * videoSink() const
The VideoOutput's QVideoSink, or nullptr.
void recordingFinished(const QString &file, const QString &error)
A recording file closed. error is empty when the file was finalized cleanly.
static QSize presentedSize(const QVideoFrame &frame, QSize pictureSize={})
QString name() const
FileFormat
Values are persisted by VideoSettings::recordingFormat.
void recordingStarted(const QString &file)
A recording file opened: the first one after startRecording(), or the recording's next part.
void setDecoding(bool decoding)
const RecordingEncoding & recordingEncoding() const
void setRecording(bool recording)
void setState(State state)
VideoStreamStats stats() const
The stream's health, measured about once a second while it streams; invalid while it doesn't.
const Config & config() const
bool active() const
void errorOccurred(const QString &message)
std::optional< Frame > frame(std::string_view text)
QVideoFrame withOwnMetadata(const QVideoFrame &frame)
constexpr bool listens(Transport transport)
The receiver listens on a local UDP port for transport, rather than connect to a server.
std::optional< Transport > transportFor(const QUrl &url)
The transport url's scheme selects, case-insensitively; nullopt for any other scheme.
What QMediaPlayer plays for a stream URI: a URL, or for RTP over UDP an SDP description of it.
std::chrono::milliseconds reconnectDelay
Until reconnectDue(), when not halted.
bool autoReconnect
Reconnect with backoff after a failure. Applies at once; changing any other field restarts the stream...