QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
GstReceiverWorker.cc
Go to the documentation of this file.
1#include "GstReceiverWorker.h"
2
3#include <chrono>
4#include <utility>
5
6#include <QtCore/QCoreApplication>
7#include <QtCore/QThread>
8#include <QtCore/QTimer>
9
10#include "GstSourceFactory.h"
11#include "GstVideoReceiver.h"
12#include "QGCNetworkHelper.h"
14
15namespace {
16
17constexpr std::chrono::milliseconds kWatchdogInterval{1000};
18// The live GPU path counters are logged every this many watchdog ticks.
19constexpr int kHwStatsLogIntervalTicks = 10;
20
21} // namespace
22
24 : QObject(parent)
25 , _watchdogTimer(new QTimer(this))
26 , _supervisor(new StreamSupervisor(this))
27 , _statsSampler(*_supervisor)
28{
29 _watchdogTimer->setInterval(kWatchdogInterval);
30 (void) connect(_watchdogTimer, &QTimer::timeout, this, [this]() { _onWatchdogTick(); });
31 (void) connect(_supervisor, &StreamSupervisor::stateChanged, this,
32 [this](VideoReceiver::State state) { _updateStatus(&Status::state, state); });
33 (void) connect(_supervisor, &StreamSupervisor::reconnectDue, this, [this]() {
34 qCDebug(GstVideoReceiverLog) << "Reconnecting (attempt" << _supervisor->reconnectAttempts() << ")"
35 << _redactedUri();
36 _reconcile();
37 });
38}
39
41{
42 _stopSession();
43}
44
46{
47 const Request previous = std::exchange(_requested, request);
48
49 // A start, stop or restart takes the config and the video sink as they are now.
50 if (request.active != previous.active) {
51 _onActiveChanged();
52 } else if (request.restarts != previous.restarts) {
53 if (_requested.active) {
54 _restartStream();
55 }
56 } else {
57 if (request.config != previous.config) {
58 _onConfigChanged(previous.config);
59 }
60 if ((request.videoSink != previous.videoSink) && _session) {
61 _session->setVideoSink(_requested.videoSink.get());
62 }
63 if (request.reconnects != previous.reconnects) {
64 _supervisor->reconnectNow();
65 }
66 }
67
68 const quint64 recordingId = request.recording ? request.recording->id : 0;
69 const quint64 previousRecordingId = previous.recording ? previous.recording->id : 0;
70 if (recordingId != previousRecordingId) {
71 if (request.recording) {
72 _startRecording(*request.recording);
73 } else {
74 _stopRecording();
75 }
76 }
77}
78
79void GstReceiverWorker::_onActiveChanged()
80{
81 _supervisor->startOver();
82 if (_requested.active) {
83 _dotDumper.setReceiverName(_requested.name);
84 } else {
85 _endRecording();
86 }
87 _reconcile();
88}
89
90void GstReceiverWorker::_onConfigChanged(const VideoReceiver::Config& previous)
91{
92 if (!_requested.active) {
93 return;
94 }
95 const VideoReceiver::Config& config = _requested.config;
96 VideoReceiver::Config sameStream = previous;
97 sameStream.autoReconnect = config.autoReconnect;
98 if (sameStream != config) {
99 _restartStream();
100 return;
101 }
102
103 // Only autoReconnect changed, which applies at once.
104 switch (_supervisor->autoReconnectChanged(config.autoReconnect)) {
106 _onHalted(_supervisor->lastFailure());
107 break;
109 _reconcile();
110 break;
112 break;
113 }
114}
115
116void GstReceiverWorker::_startRecording(const RecordingRequest& request)
117{
118 if (!_requested.active) {
119 return;
120 }
121 if (_supervisor->halted()) {
122 const QString message =
123 QCoreApplication::translate("GstVideoReceiver", "Unable to record video: the video stream has stopped.");
124 emit errorOccurred(message);
125 return;
126 }
127
128 _recording.emplace(request.file, request.format, _maxRecordingPartDuration);
129 _updateStatus(&Status::recording, true);
130 if (_session) {
131 _session->setRecording(_recordingRequest());
132 }
133}
134
135void GstReceiverWorker::_stopRecording()
136{
137 if (!_recording) {
138 return;
139 }
140 _endRecording();
141 if (_session) {
142 _session->setRecording(std::nullopt);
143 }
144}
145
147{
148 _requested.active = false;
149 _stopSession();
150 _supervisor->stop();
151 thread()->quit();
152}
153
154void GstReceiverWorker::_reconcile()
155{
156 if (!_requested.active || _requested.config.uri.isEmpty()) {
157 _stopSession();
158 _supervisor->stop();
159 return;
160 }
161 if (_session || _supervisor->halted() || _supervisor->reconnectPending()) {
162 return;
163 }
164 _startSession();
165}
166
167void GstReceiverWorker::_restartStream()
168{
169 _supervisor->startOver();
170 _stopSession();
171 _reconcile();
172}
173
174void GstReceiverWorker::_startSession()
175{
176 const PipelineSession::Settings settings{
177 .uri = _requested.config.uri,
178 .redactedUri = _redactedUri(),
179 .lowLatency = _requested.config.lowLatency,
180 .rtpJitterLatencyMs = _requested.config.rtpJitterLatencyMs,
181 };
182 _session = new PipelineSession(settings, *this, _watchdog, _dotDumper, this);
183 _watchdog.start(_requested.config.timeout, GStreamer::SourceFactory::connectGracePeriod(_requested.config.uri));
184
185 if (const std::optional<PipelineSession::Failure> failure = _session->start()) {
186 _stopSession();
187 _recover(*failure);
188 return;
189 }
190
191 _supervisor->sessionStarted();
192 _session->setVideoSink(_requested.videoSink.get());
193 _session->setRecording(_recordingRequest());
194 _statsTicks = 0;
195 _watchdogTimer->start();
196}
197
198void GstReceiverWorker::_stopSession()
199{
200 if (!_session) {
201 return;
202 }
203 _watchdogTimer->stop();
204 if (_statsSampler.reset()) {
205 _updateStatus(&Status::stats, _statsSampler.stats());
206 }
207 PipelineSession* const session = std::exchange(_session, nullptr);
208 session->shutdown();
209 // Deleted from the event loop: this may run inside one of its calls. Its leftover work is dropped with it.
210 session->deleteLater();
211
212 if (_recording) {
213 _recording->nextPart();
214 }
215}
216
217void GstReceiverWorker::_recover(const PipelineSession::Failure& failure)
218{
219 const StreamSupervisor::FailureOutcome outcome = _supervisor->sessionFailed(
220 failure.message,
222 _requested.config.autoReconnect);
223 if (outcome.halted) {
224 _onHalted(failure.message);
225 return;
226 }
227 qCDebug(GstVideoReceiverLog) << "Scheduling reconnect #" << _supervisor->reconnectAttempts() << "in"
228 << outcome.reconnectDelay.count() << "ms after" << failure.reason << _redactedUri();
229}
230
231void GstReceiverWorker::_onHalted(const QString& message)
232{
233 qCWarning(GstVideoReceiverLog) << "Video stream stopped:" << message;
234 _endRecording();
235 emit errorOccurred(message);
236}
237
238void GstReceiverWorker::_endRecording()
239{
240 if (!_recording) {
241 return;
242 }
243 _recording.reset();
244 _updateStatus(&Status::recording, false);
245}
246
247std::optional<RecordingBranch::Request> GstReceiverWorker::_recordingRequest() const
248{
249 if (!_recording) {
250 return std::nullopt;
251 }
252 return RecordingBranch::Request{.file = _recording->currentFile(), .format = _recording->format()};
253}
254
255void GstReceiverWorker::_onWatchdogTick()
256{
257 if (!_session) {
258 return;
259 }
260
261 if (++_statsTicks >= kHwStatsLogIntervalTicks) {
262 _statsTicks = 0;
263 if (const GstQgc::PathStats hwStats = _session->sinkPathStats(); hwStats.totalDelivered > 0) {
264 qCDebug(GstVideoReceiverLog).noquote() << "GPU path live" << _redactedUri() << hwStats.line;
265 }
266 }
267 _sampleStats();
268
269 if (_recording && _recording->partDue()) {
270 _recording->nextPart();
271 qCDebug(GstVideoReceiverLog) << "Recording continues in" << _recording->currentFile();
272 _session->setRecording(_recordingRequest());
273 }
274
275 const StreamWatchdog::Result result = _watchdog.check(StreamWatchdog::now(), _session->displaying());
276 switch (result.stall) {
278 return;
280 qCDebug(GstVideoReceiverLog) << "Video decoder timeout, no frames for" << result.silentMs << "ms"
281 << _redactedUri();
282 _session->snapshot(QStringLiteral("pipeline-decoder-timeout"));
283 _session->restartDecoder("decoder watchdog");
284 return;
286 qCDebug(GstVideoReceiverLog) << "Stream timeout, no frames for" << result.silentMs << "ms"
287 << _redactedUri();
288 _session->snapshot(QStringLiteral("pipeline-watchdog-timeout"));
289 _stopSession();
290 _recover({.reason = QStringLiteral("source watchdog"),
291 .message = QCoreApplication::translate("GstVideoReceiver", "No video received for %1 s.")
292 .arg(result.silentMs / 1000),
293 .permanent = false});
294 return;
295 }
296}
297
298void GstReceiverWorker::_sampleStats()
299{
300 // Rates from before the first frame would only measure the connection's setup.
301 if (_supervisor->phase() != StreamSupervisor::Phase::Streaming) {
302 return;
303 }
304 VideoStreamStatsMeter::Counters counters;
305 VideoStreamStats stats = _statsSampler.stats();
306 _session->sampleStats(counters, stats);
307 if (_statsSampler.sample(counters, stats, _recording ? &*_recording : nullptr)) {
308 _updateStatus(&Status::stats, _statsSampler.stats());
309 }
310}
311
312QString GstReceiverWorker::_redactedUri() const
313{
314 return QGCNetworkHelper::redactedUrlForLogging(_requested.config.uri);
315}
316
318{
319 _supervisor->sessionStreaming();
320}
321
323{
324 emit graphicsDeviceLost();
325}
326
327void GstReceiverWorker::onSessionFailed(const PipelineSession::Failure& failure)
328{
329 qCDebug(GstVideoReceiverLog) << "Stream failed:" << failure.reason << _redactedUri();
330 _stopSession();
331 _recover(failure);
332}
333
334void GstReceiverWorker::onDecodingChanged(bool decoding)
335{
336 _updateStatus(&Status::decoding, decoding);
337}
338
339void GstReceiverWorker::onDecoderNameChanged(const QString& name)
340{
341 _updateStatus(&Status::decoderName, name);
342}
343
345{
346 onSessionFailed({.reason = QStringLiteral("decoder failing"),
347 .message = QCoreApplication::translate("GstVideoReceiver", "The video decoder keeps failing."),
348 .permanent = false});
349}
350
351void GstReceiverWorker::onRecordingFileOpened(const QString& file)
352{
353 if (_recording) {
354 (void) _recording->onFileOpened(file);
355 }
356 emit recordingStarted(file);
357}
358
359void GstReceiverWorker::onRecordingFileClosed(const QString& file, const QString& error)
360{
361 if (_recording) {
362 _recording->onFileClosed(file);
363 }
364 emit recordingFinished(file, error);
365}
366
367void GstReceiverWorker::onRecordingFailed(const QString& file, const QString& error, bool fileOpened)
368{
369 if (_recording && (file == _recording->currentFile())) {
370 _endRecording();
371 }
372 // A file that opened already reported the error through recordingFinished().
373 if (!fileOpened) {
374 const QString message =
375 QCoreApplication::translate("GstVideoReceiver", "Video recording failed: %1").arg(error);
376 emit errorOccurred(message);
377 }
378}
379
380void GstReceiverWorker::onRecordingNeedsNewFile(const QString& file)
381{
382 if (!_session || !_recording || (file != _recording->currentFile())) {
383 return;
384 }
385 _recording->nextPart();
386 qCDebug(GstVideoReceiverLog) << "Recording continues in" << _recording->currentFile();
387 _session->setRecording(_recordingRequest());
388}
virtual void onDecoderFailing()=0
void errorOccurred(const QString &message)
GstReceiverRequest Request
void apply(const Request &request)
Steers the stream towards request, acting on what differs from the previous one.
GstReceiverWorker(QObject *parent=nullptr)
void recordingStarted(const QString &file)
void shutdown()
Stops everything and quits the thread.
~GstReceiverWorker() override
void graphicsDeviceLost()
void recordingFinished(const QString &file, const QString &error)
void setReceiverName(const QString &receiverName)
virtual void onSessionStreaming()=0
The first frame reached the tee.
virtual void onSessionGraphicsDeviceLost()=0
The reconnect policy both receivers share: the phase a stream is in, when a failed one connects again...
@ Halted
Turned off while a reconnect was pending: the stream halted.
@ Resumable
Turned on while halted after a failure that wasn't permanent: the halt is lifted.
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.
@ Permanent
It can't: an unsupported stream, a missing plugin.
@ Transient
It may, so reconnecting is worth it.
@ Streaming
The session delivers.
void stateChanged(VideoReceiver::State state)
static qint64 now()
@ Decoder
Displaying, but no frame reached the video sink within twice the timeout.
@ Source
No frame reached the tee within the timeout.
std::optional< std::chrono::milliseconds > connectGracePeriod(const QString &uri)
QString redactedUrlForLogging(const QUrl &url)
VideoReceiver::Config config
quint64 restarts
Counts restart() calls: a new count restarts the stream, with videoSink.
quint64 reconnects
Counts reconnectNow() calls: a new count cuts a reconnect's backoff short.
std::shared_ptr< GstElement > videoSink
std::optional< GstRecordingRequest > recording
VideoReceiver::State state
VideoStreamStats stats
About once a second while streaming, and invalid once the session stops.
QString message
For the user.
bool permanent
Retrying can't help: unsupported URI, missing plugin, refused credentials.
QString reason
For the log.
std::chrono::milliseconds reconnectDelay
Until reconnectDue(), when not halted.
qint64 silentMs
How long the stalled side has gone without a frame.
bool autoReconnect
Reconnect with backoff after a failure. Applies at once; changing any other field restarts the stream...