QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
GstVideoReceiver.cc
Go to the documentation of this file.
1#include "GstVideoReceiver.h"
2
3#include <chrono>
4#include <utility>
5
6#include <QtCore/QCoreApplication>
7#include <QtCore/QDeadlineTimer>
8#include <QtCore/QThread>
9#include <QtCore/QTimer>
10#include <QtMultimedia/QVideoFrame>
11#include <QtMultimedia/QVideoSink>
12
13#include "GStreamer.h"
14#include "GstReceiverWorker.h"
15#include "QGCLoggingCategory.h"
17
18QGC_LOGGING_CATEGORY(GstVideoReceiverLog, "Video.GStreamer.GstVideoReceiver")
19
20namespace {
21
22// The destructor's wait for the worker: a recording's finalization plus time for the pipeline to stop.
23constexpr std::chrono::seconds kWorkerShutdownTimeout = RecordingBranch::kFinalizeTimeout + std::chrono::seconds{2};
24static_assert(GstVideoReceiver::kHeartbeatInterval > kWorkerShutdownTimeout);
25
26// Checks in a row, 60 s, that find the worker has run none of its tasks since the check before, until it counts as
27// stuck: a name lookup for a tcp:// or udp:// host, which runs on the worker, can take half a minute to fail. Each
28// check comes a full interval after the one before, so one that is late (a suspended machine, a stopped process, a
29// stalled GUI thread) can't count twice against a worker that got no time to run a task.
30constexpr int kStuckWorkerChecks = 6;
31
32} // namespace
33
35 : VideoReceiver(parent)
36 , _workerThread(new QThread(this))
37 , _worker(new GstReceiverWorker())
38 , _heartbeatTimer(new QTimer(this))
39{
40 qCDebug(GstVideoReceiverLog) << this;
41
42 _heartbeatTimer->setSingleShot(true);
43 _heartbeatTimer->setInterval(kHeartbeatInterval);
44 (void) connect(_heartbeatTimer, &QTimer::timeout, this, &GstVideoReceiver::_checkWorker);
45
46 // Queued, with this receiver as the context: once it is destroyed, the worker's reports go nowhere.
47 (void) connect(_worker, &GstReceiverWorker::statusChanged, this, &GstVideoReceiver::_onWorkerStatus);
48 (void) connect(_worker, &GstReceiverWorker::taskDone, this, &GstVideoReceiver::_onWorkerTaskDone);
52 // The video sink goes with the pipeline: it too holds the device.
54
55 _workerThread->setObjectName(QStringLiteral("GstVideoReceiver"));
56 _worker->moveToThread(_workerThread);
57 (void) connect(_workerThread, &QThread::finished, _worker, &QObject::deleteLater);
58 _workerThread->start();
59}
60
62{
63 _postToWorker([](GstReceiverWorker& worker) { worker.shutdown(); });
64 if (_workerThread->wait(QDeadlineTimer(kWorkerShutdownTimeout))) {
65 qCDebug(GstVideoReceiverLog) << this;
66 return;
67 }
68
69 // Only a streaming thread that doesn't return (a recorder stuck in the kernel on a hung network mount, a decoder
70 // deadlocked in its library) holds the worker this long. It reaches this receiver only through its signals, so it
71 // can finish on its own and clean up after itself.
72 qCWarning(GstVideoReceiverLog) << "Worker still busy after"
73 << std::chrono::milliseconds(kWorkerShutdownTimeout).count()
74 << "ms; leaving it to finish on its own";
75 _workerThread->setParent(nullptr);
76 (void) connect(_workerThread, &QThread::finished, _workerThread, &QObject::deleteLater);
77 if (_workerThread->isFinished()) {
78 delete _workerThread;
79 }
80}
81
82void GstVideoReceiver::setHeartbeatInterval(std::chrono::milliseconds interval)
83{
84 _heartbeatTimer->setInterval(interval);
85}
86
88{
89 _postRequest();
90}
91
93{
94 _postRequest();
95}
96
98{
99 // Construct-only sink settings apply to a new sink only.
100 _releaseDisplaySink();
101 if (QVideoSink* const sink = videoSink()) {
102 _bindVideoSink(sink);
103 }
104 ++_request.restarts;
105 _postRequest();
106}
107
109{
110 ++_request.reconnects;
111 _postRequest();
112}
113
115{
116 (void) disconnect(_videoSizeConnection);
117
118 QVideoSink* const sink = videoSink();
119 if (sink) {
120 _bindVideoSink(sink);
121 } else {
122 if (videoOutput()) {
123 qCWarning(GstVideoReceiverLog) << "Video output" << videoOutput() << "has no videoSink; not displaying";
124 }
125 if (_sinkController) {
126 _sinkController->setVideoSink(QPointer<QVideoSink>());
127 _sinkController->followWindowVisibility(nullptr);
128 }
129 }
130 _postRequest();
131}
132
133void GstVideoReceiver::onStartRecording(const QString& file, FileFormat format)
134{
135 const quint64 id = (_request.recording ? _request.recording->id : 0) + 1;
136 _request.recording = GstRecordingRequest{.file = file, .format = format, .id = id};
137 _postRequest();
138}
139
141{
142 _request.recording.reset();
143 _postRequest();
144}
145
146void GstVideoReceiver::_postRequest()
147{
148 _request.active = active();
149 _request.name = name();
150 _request.config = config();
151 GstElement* const displaySink = videoSink() ? _displaySink.get() : nullptr;
152 if (displaySink != _request.videoSink.get()) {
153 _request.videoSink = GStreamer::shareObject(displaySink);
154 }
155 _postToWorker([request = _request](GstReceiverWorker& worker) { worker.apply(request); });
156}
157
158void GstVideoReceiver::_checkWorker()
159{
160 const bool frameShown = std::exchange(_frameShown, false);
161 const bool ranTask = _tasksDone != std::exchange(_tasksDoneAtCheck, _tasksDone);
162 if (_tasksDone == _tasksPosted) {
163 _stalledChecks = 0;
164 if (!active()) {
165 // Through with all it was posted, and no stream is wanted of it: it has nothing to get stuck in.
166 return;
167 }
168 // The heartbeat of a worker that is posted nothing else: what it does of its own, as replacing a decoder that
169 // stalled, can hold it too.
170 _postToWorker([](GstReceiverWorker& /*worker*/) {});
171 } else if (ranTask) {
172 // Slow, or behind with a row of requests, but not stuck.
173 _stalledChecks = 0;
174 } else if (_workerStuck) {
175 _applyStuckStatus(frameShown);
176 } else if (++_stalledChecks >= kStuckWorkerChecks) {
177 qCWarning(GstVideoReceiverLog) << "The worker of" << name() << "has run none of its tasks for"
178 << (kStuckWorkerChecks * _heartbeatTimer->intervalAsDuration()).count()
179 << "ms: a streaming thread it waits for doesn't return";
180 _workerStuck = true;
181 _applyStuckStatus(frameShown);
182 emit errorOccurred(
183 tr("The video decoder or recorder stopped responding. Restart %1 to get video working again.")
184 .arg(QCoreApplication::applicationName()));
185 }
186 // A full interval from now, not from when this check was due: one that comes late puts the next ones off.
187 _heartbeatTimer->start();
188}
189
190void GstVideoReceiver::_onWorkerTaskDone()
191{
192 ++_tasksDone;
193 if (_workerStuck) {
194 qCDebug(GstVideoReceiverLog) << "The worker of" << name() << "runs its tasks again";
195 _workerStuck = false;
196 _applyStatus(_workerStatus);
197 }
198}
199
200void GstVideoReceiver::_applyStuckStatus(bool frameShown)
201{
202 // The pipeline runs on without its worker, which a recorder that doesn't return holds as well as a decoder: only
203 // the frames tell which. While they reach the output the stream is as the worker reported it last, though nothing
204 // measures it. Without them it is as one that gave up, so that no frozen picture passes for the live one.
205 GstReceiverStatus status = _workerStatus;
206 status.stats = {};
207 if (!frameShown) {
208 status.state = State::Stopped;
209 status.decoding = false;
210 status.decoderName.clear();
211 }
212 _applyStatus(status);
213}
214
215void GstVideoReceiver::_onWorkerStatus(const GstReceiverStatus& status)
216{
217 _workerStatus = status;
218 if (!_workerStuck) {
219 _applyStatus(status);
220 }
221}
222
223void GstVideoReceiver::_applyStatus(const GstReceiverStatus& status)
224{
225 setState(status.state);
226 const bool wasDecoding = decoding();
227 setDecoding(status.decoding);
228 if (wasDecoding && !status.decoding && _sinkController) {
229 _sinkController->releaseFrame();
230 }
231 _decoderName = status.decoderName;
232 setRecording(status.recording);
233 setStats(status.stats);
234}
235
236void GstVideoReceiver::_postToWorker(std::function<void(GstReceiverWorker&)> task)
237{
238 GstReceiverWorker* const worker = _worker;
239 (void) QMetaObject::invokeMethod(
240 worker,
241 [worker, task = std::move(task)]() {
242 task(*worker);
243 emit worker->taskDone();
244 },
245 Qt::QueuedConnection);
246
247 ++_tasksPosted;
248 if (!_heartbeatTimer->isActive()) {
249 _heartbeatTimer->start();
250 }
251}
252
253void GstVideoReceiver::_releaseDisplaySink()
254{
255 (void) disconnect(_videoSizeConnection);
256 if (_sinkController) {
257 _sinkController->prepareForRelease();
258 _sinkController->deleteLater();
259 _sinkController = nullptr;
260 }
261 _displaySink.reset();
262}
263
264bool GstVideoReceiver::_buildDisplaySink(QVideoSink* videoSink)
265{
266 const DisplayConfig& display = displayConfig();
268 GStreamer::createVideoSink(display.conversionElement, display.disablePixelAspectRatio, display.gpuZeroCopy));
269 QGCQVideoSinkController* const controller =
270 sink ? GStreamer::setupQVideoSinkElement(sink.get(), videoSink, this) : nullptr;
271 if (!controller) {
272 qCWarning(GstVideoReceiverLog) << "Unable to create the video sink for" << name();
273 emit errorOccurred(tr("Unable to display video: the video sink could not be created."));
274 return false;
275 }
276 _displaySink = std::move(sink);
277 _sinkController = controller;
278 return true;
279}
280
281void GstVideoReceiver::_bindVideoSink(QVideoSink* videoSink)
282{
283 (void) disconnect(_videoSizeConnection);
284 if (_displaySink) {
285 _sinkController->setVideoSink(QPointer<QVideoSink>(videoSink));
286 } else if (!_buildDisplaySink(videoSink)) {
287 return;
288 }
289 _sinkController->followWindowVisibility(videoOutput());
290 // Per frame, not on QVideoSink::videoSizeChanged: that follows the frame size, which for a decoder's buffer cropped
291 // by crop meta is larger than the picture, and misses a viewport that changes on its own. Frames reach the sink on
292 // this thread. The picture's size is the display sink's: a viewport that leaves out the padding of a squeezed
293 // texture is smaller.
294 const auto sizeOf = [this](const QVideoFrame& frame) {
295 return presentedSize(frame, _sinkController ? _sinkController->pictureSize() : QSize());
296 };
297 _videoSizeConnection =
298 connect(videoSink, &QVideoSink::videoFrameChanged, this, [this, sizeOf](const QVideoFrame& frame) {
299 _frameShown = _frameShown || frame.isValid();
300 setVideoSize(sizeOf(frame));
301 });
302 if (const QSize size = sizeOf(videoSink->videoFrame()); size.isValid()) {
303 setVideoSize(size);
304 }
305}
struct _GstElement GstElement
#define QGC_LOGGING_CATEGORY(name, categoryStr)
void statusChanged(const GstReceiverStatus &status)
void errorOccurred(const QString &message)
void apply(const Request &request)
Steers the stream towards request, acting on what differs from the previous one.
void recordingStarted(const QString &file)
void shutdown()
Stops everything and quits the thread.
void graphicsDeviceLost()
void recordingFinished(const QString &file, const QString &error)
void onActiveChanged() override
void onReconnectRequested() override
void setHeartbeatInterval(std::chrono::milliseconds interval)
~GstVideoReceiver() override
Finalizes a recording and stops the pipeline, waiting at most a few seconds for the worker.
void onRestartRequested() override
GstVideoReceiver(QObject *parent=nullptr)
void onConfigChanged() override
static constexpr std::chrono::seconds kHeartbeatInterval
void onStartRecording(const QString &file, FileFormat format) override
void onVideoOutputChanged() override
Also called when the current output is set again.
void onStopRecording() override
void followWindowVisibility(QQuickItem *videoOutput)
static constexpr std::chrono::seconds kFinalizeTimeout
void setVideoSize(QSize size)
QQuickItem * videoOutput() const
VideoReceiver(QObject *parent=nullptr)
const DisplayConfig & displayConfig() const
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)
void setRecording(bool recording)
void setState(State state)
const Config & config() const
@ Stopped
Inactive, no URI, or given up after a failure (autoReconnect off).
bool decoding() const
bool active() const
void errorOccurred(const QString &message)
GstElement * createVideoSink(const QByteArray &conversionElement, bool disablePixelAspectRatio, bool gpuZeroCopy)
Definition GStreamer.cc:258
std::shared_ptr< T > shareObject(T *object)
A copyable owner of a new ref on object, for tasks that must be copyable (std::function).
Definition GstScoped.h:164
std::unique_ptr< GstElement, GstObjectDeleter > GstElementPtr
Definition GstScoped.h:60
GstElementPtr adoptElement(GstElement *element) noexcept
Definition GstScoped.h:79
QGCQVideoSinkController * setupQVideoSinkElement(GstElement *sinkBin, QVideoSink *videoSink, QObject *controllerParent)
Definition GStreamer.cc:287
std::optional< Frame > frame(std::string_view text)
VideoReceiver::Config config
std::shared_ptr< GstElement > videoSink
What the worker reports, as it stands after each change.
VideoReceiver::State state
VideoStreamStats stats
About once a second while streaming, and invalid once the session stops.
How the display sink presents frames. Construct-only: a change applies when restart() rebuilds the si...