4#include <gst/pbutils/missing-plugins.h>
7#include <QtCore/QDeadlineTimer>
21constexpr quint64 kSourceFlowLogIntervalFrames = 300;
24constexpr int kMinRetransmissionLatencyMs = 40;
26void logBusWarning(GstMessage* message)
31 qCWarning(GstVideoReceiverLog) <<
"GStreamer warning:" << (error ? error->message :
"(no message)")
32 <<
"debug:" << (debug ? debug.get() :
"(none)");
37void logSourceProgress(GstMessage* message)
39 if (GST_MESSAGE_TYPE(message) == GST_MESSAGE_ELEMENT) {
40 if (gst_message_has_name(message,
"GstRTSPSrcTimeout")) {
42 (void) gst_structure_get_int(gst_message_get_structure(message),
"stream-number", &stream);
43 qCDebug(GstVideoReceiverLog) <<
"The sender of RTSP stream" << stream <<
"timed out";
47 GstProgressType type = GST_PROGRESS_TYPE_START;
48 gchar* rawCode =
nullptr;
49 gchar* rawText =
nullptr;
50 gst_message_parse_progress(message, &type, &rawCode, &rawText);
54 const bool connect = (g_strcmp0(code.get(),
"connect") == 0);
55 qCDebug(GstVideoReceiverLog) <<
"Source progress:" << (code ? code.get() :
"(none)")
56 << (connect ?
"Connecting" : (text ? text.get() :
""));
59bool isRecoverableH265PaciError(GstMessage* msg,
const GError* error,
const gchar* debug)
61 if (!msg || !error || (error->domain != GST_STREAM_ERROR) || (error->code != GST_STREAM_ERROR_FORMAT) || !debug ||
62 !g_strrstr(debug,
"NAL unit type 50 not supported yet")) {
68bool postedByRtspSrc(GstMessage* message)
74bool isUnauthorizedError(
const GError* error)
76 return g_error_matches(error, GST_RESOURCE_ERROR, GST_RESOURCE_ERROR_NOT_AUTHORIZED);
80bool isPermanentError(GstMessage* message,
const GError* error)
82 if (g_error_matches(error, GST_STREAM_ERROR, GST_STREAM_ERROR_CODEC_NOT_FOUND)) {
85 return !postedByRtspSrc(message);
87 return g_error_matches(error, GST_CORE_ERROR, GST_CORE_ERROR_MISSING_PLUGIN) || isUnauthorizedError(error);
93QString debugCause(
const gchar* debug)
95 const gchar*
const separator = debug ? g_strstr_len(debug, -1,
":\n") : nullptr;
96 return separator ? QString::fromUtf8(separator + 2).simplified() : QString();
101QString rtspStatus(GstMessage* message)
103 const GstStructure* details =
nullptr;
104 gst_message_parse_error_details(message, &details);
106 if (!details || !gst_structure_get_uint(details,
"rtsp-status-code", &code)) {
109 const gchar*
const reason = gst_structure_get_string(details,
"rtsp-status-reason");
110 return QStringLiteral(
"RTSP %1 %2").arg(QString::number(code), QString::fromUtf8(reason ? reason :
"")).trimmed();
115QString describeError(GstMessage* message,
const QString& text,
const gchar* debug,
116 const QString& missingPlugin = QString())
118 QString cause = missingPlugin;
119 if (cause.isEmpty()) {
120 cause = rtspStatus(message);
122 if (cause.isEmpty()) {
123 cause = debugCause(debug);
126 cause.remove(QLatin1Char(
'<'));
127 return cause.isEmpty() ? text : QStringLiteral(
"%1 (%2)").arg(text, cause);
130bool pipelineEnteredPlaying(GstMessage* message)
133 if (!GST_IS_PIPELINE(GST_MESSAGE_SRC(message))) {
136 GstState oldState = GST_STATE_NULL, newState = GST_STATE_NULL;
137 gst_message_parse_state_changed(message, &oldState, &newState,
nullptr);
138 return (newState == GST_STATE_PLAYING) && (oldState != GST_STATE_PLAYING);
141QString messageSourcePath(GstMessage* message)
144 GST_MESSAGE_SRC(message) ? gst_object_get_path_string(GST_MESSAGE_SRC(message)) :
nullptr);
145 return QString::fromUtf8(path ? path.get() :
"(unknown)");
153 , _settings(settings)
154 , _listener(listener)
155 , _watchdog(watchdog)
156 , _dotDumper(dotDumper)
166 qCDebug(GstVideoReceiverLog) <<
"Starting" << _settings.redactedUri <<
"lowLatency" << _settings.lowLatency;
171 if (!_pipeline || !_bus.attach(
172 _pipeline.get(), [
this](GstMessage* message) { return _onBusSync(message); },
173 [
this](GstMessage* message) {
174 if (_phase != Phase::Down) {
175 _handleMessage(message);
178 return Failure{.reason = QStringLiteral(
"pipeline creation failed"),
179 .message = tr(
"Unable to create the video pipeline."),
183 g_object_set(_pipeline.get(),
"message-forward", TRUE,
nullptr);
188 if (!teeSink || !_teeFrameProbe.add(teeSink.get(), GST_PAD_PROBE_TYPE_BUFFER, _teeProbe,
this)) {
189 return Failure{.reason = QStringLiteral(
"tee creation failed"),
190 .message = tr(
"Unable to create the video pipeline."),
195 .pipeline = _pipeline.get(),
197 .redactedUri = _settings.redactedUri,
198 .dotDumper = &_dotDumper,
199 .watchdog = &_watchdog,
200 .post = [
this](std::function<void()> task) { _post(std::move(task)); },
202 _decoding = std::make_unique<DecodingBranch>(context, _listener, _settings.lowLatency);
203 _recording = std::make_unique<RecordingBranch>(context, _listener);
204 if (!_decoding->build() || !_recording->build()) {
205 return Failure{.reason = QStringLiteral(
"branch creation failed"),
206 .message = tr(
"Unable to create the video pipeline."),
209 _displayValve = _decoding->valve();
210 _recordingValve = _recording->valve();
215 sourceConfig.
latencyMs = _settings.rtpJitterLatencyMs;
216 sourceConfig.
doRetransmission = (_settings.rtpJitterLatencyMs >= kMinRetransmissionLatencyMs) &&
220 if (!_source || !gst_bin_add(GST_BIN(_pipeline.get()), _source)) {
222 return Failure{.reason = QStringLiteral(
"no source for the URI"),
223 .message = tr(
"The video stream %1 is not supported, or a GStreamer plugin it needs is missing.")
224 .arg(_settings.redactedUri),
229 _linkSourcePad(srcPad.get());
231 (void) _sourcePadAdded.connect(_source,
"pad-added", G_CALLBACK(_onSourcePadAdded),
this);
234 _dotDumper.dump(_pipeline.get(),
"pipeline-initial");
235 if (gst_element_set_state(_pipeline.get(), GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
236 const QString error = _takeStartError();
237 qCWarning(GstVideoReceiverLog) <<
"Failed to start" << _settings.redactedUri;
238 return Failure{.reason = QStringLiteral(
"start failure"),
239 .message = tr(
"Unable to start the video stream: %1").arg(error),
243 _dotDumper.dump(_pipeline.get(),
"pipeline-started");
244 qCDebug(GstVideoReceiverLog) <<
"Started" << _settings.redactedUri;
250 if (_decoding && !_tearingDown()) {
251 _decoding->setVideoSink(sink);
257 if (_recording && !_tearingDown()) {
258 _recording->setRequest(request);
264 if (_decoding && !_tearingDown()) {
265 _decoding->restartDecoder(reason);
271 return _decoding && _decoding->displaying();
286 stats.
decoder = _decoding->decoderName();
292 _statsProbe.sample(_pipeline.get(), _source, _tee, counters, stats);
297 _dotDumper.snapshot(_pipeline.get(), tag);
302 if (_phase == Phase::Down) {
305 _phase = Phase::TearingDown;
307 if (_recording && _pipeline && _recording->beginTeardown()) {
311 static_cast<GstMessageType
>(GST_MESSAGE_ERROR | GST_MESSAGE_ELEMENT),
313 _recording->completeTeardown();
316 _phase = Phase::Down;
322 (void) gst_element_set_state(_pipeline.get(), GST_STATE_NULL);
326 _teeFrameProbe.remove();
328 _sourcePadAdded.disconnect();
337 qCDebug(GstVideoReceiverLog).noquote() <<
"GPU path stats" << _settings.redactedUri << hwStats.
line;
341 _dotDumper.dump(_pipeline.get(),
"pipeline-stopped");
342 qCDebug(GstVideoReceiverLog) <<
"Stopped" << _settings.redactedUri;
349void PipelineSession::_post(std::function<
void()> task)
351 (void) QMetaObject::invokeMethod(
353 [
this, task = std::move(task)]() {
354 if (_phase != Phase::Down) {
358 Qt::QueuedConnection);
361void PipelineSession::_fail(
const Failure& failure)
363 if (_phase != Phase::Running) {
366 _phase = Phase::Failed;
367 _post([
this, failure]() { _listener.onSessionFailed(failure); });
370void PipelineSession::_handleMessage(GstMessage* message)
372 if (!_decoding || !_recording) {
375 switch (GST_MESSAGE_TYPE(message)) {
376 case GST_MESSAGE_ERROR:
377 _onBusError(message);
379 case GST_MESSAGE_WARNING:
380 if (!_tearingDown()) {
381 logBusWarning(message);
384 case GST_MESSAGE_ELEMENT:
386 if (!_tearingDown()) {
387 _decoding->onGraphicsDeviceServed();
392 if (_phase == Phase::Running) {
393 qCDebug(GstVideoReceiverLog) <<
"The graphics device is gone" << _settings.redactedUri;
394 _post([
this]() { _listener.onSessionGraphicsDeviceLost(); });
398 _noteMissingPlugin(message);
400 _recording->onBusElement(message);
401 logSourceProgress(message);
403 case GST_MESSAGE_PROGRESS:
404 logSourceProgress(message);
406 case GST_MESSAGE_STATE_CHANGED:
407 if (!_tearingDown() && pipelineEnteredPlaying(message)) {
411 case GST_MESSAGE_LATENCY:
413 if (!_tearingDown()) {
414 (void) gst_bin_recalculate_latency(GST_BIN(_pipeline.get()));
422void PipelineSession::_onBusError(GstMessage* message)
425 const QString text = QString::fromUtf8(error ? error->message :
"(no message)");
427 if (isRecoverableH265PaciError(message, error.get(), debug.get())) {
428 qCWarning(GstVideoReceiverLog) <<
"Ignoring unsupported H.265 RTP PACI packet from rtph265depay:" << text;
434 _recording->onBusError(message, error.get(), text, debug.get());
438 const char*
const debugText = debug ? debug.get() :
"(none)";
439 if (_phase != Phase::Running) {
440 qCDebug(GstVideoReceiverLog) <<
"Ignoring an error after the stream ended:" << text <<
"debug:" << debugText;
443 const bool namesMissingPlugin =
444 g_error_matches(error.get(), GST_CORE_ERROR, GST_CORE_ERROR_MISSING_PLUGIN) && (branch == _missingPluginBranch);
445 const QString description =
446 describeError(message, text, debug.get(), namesMissingPlugin ? _missingPlugin : QString());
449 if (!_decoding->isCurrent(GST_MESSAGE_SRC(message))) {
450 qCDebug(GstVideoReceiverLog) <<
"Ignoring an error from a replaced decoder:" << text
451 <<
"debug:" << debugText;
454 qCWarning(GstVideoReceiverLog) <<
"Decoder error from" << messageSourcePath(message) <<
":" << text
455 <<
"debug:" << debugText;
456 if (isPermanentError(message, error.get())) {
457 _fail({.reason = QStringLiteral(
"decoder error"),
458 .message = tr(
"Unable to decode the video: %1").arg(description),
461 _decoding->restartDecoder(
"decoder error");
466 qCWarning(GstVideoReceiverLog) <<
"GStreamer error from" << messageSourcePath(message) <<
":" << text
467 <<
"debug:" << debugText;
468 _dotDumper.snapshot(_pipeline.get(), QStringLiteral(
"pipeline-error"));
469 const QString userMessage =
470 isUnauthorizedError(error.get())
471 ? tr(
"The video stream refused the connection: its user name or password is missing or wrong.")
472 : tr(
"Video stream error: %1").arg(description);
473 _fail({.reason = QStringLiteral(
"pipeline error"),
474 .message = userMessage,
475 .permanent = isPermanentError(message, error.get())});
478QString PipelineSession::_takeStartError()
484 return tr(
"unknown error");
487 const QString text = QString::fromUtf8(error ? error->message :
"(no message)");
488 qCWarning(GstVideoReceiverLog) <<
"GStreamer error from" << messageSourcePath(message.get()) <<
":" << text
489 <<
"debug:" << (debug ? debug.get() :
"(none)");
490 return describeError(message.get(), text, debug.get());
493void PipelineSession::_noteMissingPlugin(GstMessage* message)
495 if (!gst_is_missing_plugin_message(message)) {
499 _missingPlugin = QString::fromUtf8(description ? description.get() :
"");
501 qCWarning(GstVideoReceiverLog) <<
"Missing GStreamer plugin:" << _missingPlugin <<
"for"
502 << messageSourcePath(message);
505void PipelineSession::_linkSourcePad(GstPad* pad)
508 const GstPadLinkReturn linkResult = teeSink ? gst_pad_link(pad, teeSink.get()) : GST_PAD_LINK_WRONG_HIERARCHY;
509 if (linkResult != GST_PAD_LINK_OK) {
510 qCWarning(GstVideoReceiverLog) <<
"Unable to link source:" << gst_pad_link_get_name(linkResult);
514 (void) _sourceEos.add(pad, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM, _sourceEosProbe,
this);
515 _dotDumper.dump(_pipeline.get(),
"pipeline-with-new-source-pad");
518void PipelineSession::_onFirstFrame()
524 qCDebug(GstVideoReceiverLog) <<
"Streaming started" << _settings.redactedUri;
525 _decoding->onSourceStreaming();
526 _recording->onSourceStreaming();
527 _listener.onSessionStreaming();
530void PipelineSession::_logLatency()
532 GstClockTime min = 0, max = 0;
534 qCDebug(GstVideoReceiverLog).noquote()
535 <<
"Pipeline PLAYING:" << _settings.redactedUri <<
"min-latency:" << GST_TIME_AS_MSECONDS(min) <<
"ms"
536 <<
"max-latency:" << GST_TIME_AS_MSECONDS(max) <<
"ms";
539GstBusSyncReply PipelineSession::_onBusSync(GstMessage* message)
546 if (GST_MESSAGE_TYPE(message) == GST_MESSAGE_ERROR) {
554 g_object_set(valve,
"drop", TRUE,
nullptr);
560void PipelineSession::_onSourcePadAdded(
GstElement* source, GstPad* pad, gpointer data)
566 if (padSource.get() == self->_source) {
567 self->_linkSourcePad(newPad);
572GstPadProbeReturn PipelineSession::_teeProbe(GstPad* , GstPadProbeInfo* info, gpointer data)
575 if (GstBuffer*
const buffer = GST_PAD_PROBE_INFO_BUFFER(info)) {
576 self->_statsProbe.noteBuffer(buffer);
580 self->_post([self]() { self->_onFirstFrame(); });
581 }
else if ((frames % kSourceFlowLogIntervalFrames) == 0) {
582 qCDebug(GstVideoReceiverLog).noquote() <<
"Source flow: teeFrames=" << frames << self->_settings.redactedUri;
584 return GST_PAD_PROBE_OK;
587GstPadProbeReturn PipelineSession::_sourceEosProbe(GstPad* , GstPadProbeInfo* info, gpointer data)
589 const GstEvent*
const event = gst_pad_probe_info_get_event(info);
590 if (event && (GST_EVENT_TYPE(event) == GST_EVENT_EOS)) {
592 self->_post([self]() {
593 self->_fail({.reason = QStringLiteral(
"end of stream"),
594 .message = tr(
"The video stream ended."),
595 .permanent =
false});
598 return GST_PAD_PROBE_OK;
struct _GstElement GstElement
std::optional< Failure > start()
Builds the pipeline and sets it PLAYING. Returns why when it can't; shut the session down then.
void snapshot(const QString &tag) const
Writes PipelineDotDumper::snapshot() of the pipeline under tag.
~PipelineSession() override
GstQgc::PathStats sinkPathStats() const
void restartDecoder(const char *reason)
void setRecording(const std::optional< RecordingBranch::Request > &request)
void setVideoSink(GstElement *sink)
PipelineSession(const Settings &settings, Listener &listener, StreamWatchdog &watchdog, const PipelineDotDumper &dotDumper, QObject *parent=nullptr)
void sampleStats(VideoStreamStatsMeter::Counters &counters, VideoStreamStats &stats)
static void noteElementMessage(GstMessage *message)
static bool queryLatency(GstElement *pipeline, GstClockTime &min, GstClockTime &max)
The latency pipeline reports; false when it doesn't answer the latency query.
static constexpr std::chrono::seconds kFinalizeTimeout
GstElement * create(const QString &uri, const Config &config)
@ None
No playout buffering; omits an explicit buffer or sets rtspsrc latency to zero.
@ DropOnLatency
rtpjitterbuffer with drop-on-latency=TRUE.
GstPadPtr firstSrcPad(GstElement *element)
element's first src pad, or null when it has none (yet).
GCharPtr adoptGChar(gchar *str) noexcept
std::function< void()> holdPadUntilLinked(GstPad *pad, std::function< void(GstPad *pad)> link)
GstElementPtr makeElement(const char *factory, const char *name=nullptr)
const char * factoryNameOf(GstObject *object)
The name of the factory that made object ("rtph264depay"); null when it is no element or has no facto...
PipelineBranch
The tee branch a pipeline element belongs to, so a bus message can be blamed on the part that failed.
GstElement * addToBin(GstElement *bin, GstElementPtr element, const char *what)
std::unique_ptr< T, GstObjectDeleter > adoptFloating(T *object) noexcept
Sinks the floating ref of a new object (pipeline, bin, pad, element) and owns it. Null for null.
PipelineBranch branchOf(GstObject *object)
The branch of object's nearest marked ancestor (itself included). Thread-safe.
std::shared_ptr< T > shareObject(T *object)
A copyable owner of a new ref on object, for tasks that must be copyable (std::function).
MessageError parseMessageError(GstMessage *message)
gst_message_parse_error(), or gst_message_parse_warning() for a WARNING message.
std::unique_ptr< GstPad, GstObjectDeleter > GstPadPtr
std::unique_ptr< GstMessage, GstMessageDeleter > GstMessagePtr
std::unique_ptr< gchar, GFreeDeleter > GCharPtr
GstPadPtr adoptPad(GstPad *pad) noexcept
constexpr char kGraphicsDeviceLostMessage[]
GstBusSyncReply onBusSyncMessage(GstMessage *msg) noexcept
constexpr char kGraphicsDeviceServedMessage[]
What the branch measured for VideoStreamStats.
quint64 framesDisplayed
Since the branch was built: frames the video sink delivered that no newer frame replaced before displ...
quint64 gpuFallbacks
Since the branch was built: frames a GPU path was tried for but the CPU delivered.
quint64 decoderRestarts
Since the branch was built: decoders replaced by restartDecoder().
bool doRetransmission
RTSP only: plain UDP/TCP sources have no RTCP back-channel for NACKs.
JitterBuffer jitterBuffer
Formatted per-path frame counts + the total delivered through GPU paths.
qint64 decoderRestarts
Since the stream started: times the decoder was replaced after an error or a stall.
QString decoder
The decoder's element factory, e.g. "avdec_h264".
qint64 gpuFallbacks
Since the stream started: frames a zero-copy GPU path was tried for but the CPU delivered.