16constexpr guint kDisplayQueueMaxBuffers = 2;
20constexpr qint64 kMaxGateMs = 2000;
25gint decodeVideoOnly([[maybe_unused]]
GstElement* decodebin, [[maybe_unused]] GstStreamCollection* collection,
26 GstStream* stream, [[maybe_unused]] gpointer data)
28 return ((gst_stream_get_stream_type(stream) & GST_STREAM_TYPE_VIDEO) != 0) ? 1 : 0;
34 if (g_object_class_find_property(G_OBJECT_GET_CLASS(sink),
"sync")) {
35 g_object_set(sink,
"sync", sync,
nullptr);
38 if (!GST_IS_BIN(sink)) {
41 GstIterator*
const sinks = gst_bin_iterate_sinks(GST_BIN(sink));
42 (void) gst_iterator_foreach(
44 [](
const GValue* item, gpointer data) {
45 auto*
const child = GST_ELEMENT(g_value_get_object(item));
46 if (g_object_class_find_property(G_OBJECT_GET_CLASS(child),
"sync")) {
47 g_object_set(child,
"sync", GPOINTER_TO_INT(data),
nullptr);
50 GINT_TO_POINTER(sync ? TRUE : FALSE));
51 gst_iterator_free(sinks);
56guint64 lateFramesDroppedBy(
GstElement* element)
58 GParamSpec*
const spec = g_object_class_find_property(G_OBJECT_GET_CLASS(element),
"stats");
59 if (!spec || (G_PARAM_SPEC_VALUE_TYPE(spec) != GST_TYPE_STRUCTURE)) {
62 GstStructure* rawStats =
nullptr;
63 g_object_get(element,
"stats", &rawStats,
nullptr);
75 if (!GST_IS_BIN(sink)) {
76 return lateFramesDroppedBy(sink);
79 GstIterator*
const sinks = gst_bin_iterate_sinks(GST_BIN(sink));
80 (void) gst_iterator_foreach(
82 [](
const GValue* item, gpointer data) {
83 *
static_cast<guint64*
>(data) += lateFramesDroppedBy(GST_ELEMENT(g_value_get_object(item)));
86 gst_iterator_free(sinks);
94 bool hardware =
false;
95 GstIterator*
const elements = gst_bin_iterate_recurse(GST_BIN(decodebin));
96 const auto note = [](
const GValue* item, gpointer data) {
97 GstElementFactory*
const factory = gst_element_get_factory(GST_ELEMENT(g_value_get_object(item)));
98 if (factory && gst_element_factory_list_is_type(factory, GST_ELEMENT_FACTORY_TYPE_DECODER) &&
100 *
static_cast<bool*
>(data) =
true;
103 while (gst_iterator_foreach(elements, note, &hardware) == GST_ITERATOR_RESYNC) {
104 gst_iterator_resync(elements);
106 gst_iterator_free(elements);
115 gboolean live = FALSE;
116 if (sinkPad && gst_pad_peer_query(sinkPad.get(), query.get())) {
117 gst_query_parse_latency(query.get(), &live,
nullptr,
nullptr);
126 GObject*
const object = G_OBJECT(decoder);
128 gst_util_set_object_arg(
object,
"thread-type",
"slice");
130 gst_util_set_object_arg(
object,
"max-display-delay",
"0");
133 gst_util_set_object_arg(
object,
"compliance",
"normal");
136bool isInside(GstObject*
object,
GstElement* element)
138 return element &&
object && gst_object_has_as_ancestor(
object, GST_OBJECT_CAST(element));
141struct SinkFrameCounts
143 quint64 displayed = 0;
144 quint64 superseded = 0;
145 quint64 gpuFallbacks = 0;
150SinkFrameCounts sinkFrameCountsSince(
const GstStructure* stats,
const GstStructure* since)
153 quint64 delivered = 0;
158 return {.displayed = (delivered > superseded) ? (delivered - superseded) : 0,
159 .superseded = superseded,
167 , _listener(listener)
168 , _lowLatency(lowLatency)
188 gst_util_set_object_arg(G_OBJECT(queue),
"leaky",
"downstream");
189 g_object_set(queue,
"max-size-buffers", kDisplayQueueMaxBuffers,
"max-size-bytes", 0,
"max-size-time",
190 G_GUINT64_CONSTANT(0),
nullptr);
193 _head.onOverrun(G_CALLBACK(_onQueueOverrun),
this);
195 if (!queueSrc || !_keyframeGate.add(queueSrc.get(), GST_PAD_PROBE_TYPE_BUFFER, _gateProbe,
this)) {
196 qCCritical(GstVideoReceiverLog) <<
"Failed to add the display keyframe gate";
204 _keyframeGate.remove();
206 _sinkFrameProbe.remove();
208 _sinkStatsAtStart.reset();
215 if (sink == _sink.get()) {
220 _sinkFrameProbe.remove();
223 _sinkStatsAtStart.reset();
232 qCCritical(GstVideoReceiverLog) <<
"The video sink has no sink pad" << _context.redactedUri;
238 _pathFramesAtSample[i] =
243 (void) _sinkFrameProbe.add(sinkPad.get(), GST_PAD_PROBE_TYPE_BUFFER, _sinkProbe,
this);
253 if (_sink && !_decoder) {
265 qCDebug(GstVideoReceiverLog) <<
"Decoder failing after" <<
kMaxDecoderRestarts <<
"restarts, last:" << reason
266 << _context.redactedUri;
267 _context.post([
this]() { _listener.onDecoderFailing(); });
271 qCDebug(GstVideoReceiverLog) <<
"Restarting the decoder after" << reason << _context.redactedUri;
274 if (_restartsWithoutFrame > 1) {
275 _demoteFailedDecoder();
284 if (!_decoder || !hasHardwareDecoder(_decoder.get())) {
287 qCDebug(GstVideoReceiverLog) <<
"Replacing the decoder" << _decoderName
288 <<
"by one on the graphics device Qt renders with" << _context.redactedUri;
296 return _head.contains(source) || isInside(source, _decoder.get()) || (_decoder && isInside(source, _sink.get()));
312 const SinkFrameCounts sinkCounts = sinkFrameCountsSince(stats.get(), _sinkStatsAtStart.get());
314 quint64 busiestPathFrames = 0;
318 const quint64 sinceSample = (frames > _pathFramesAtSample[i]) ? (frames - _pathFramesAtSample[i]) : 0;
319 if (sinceSample > busiestPathFrames) {
320 busiestPathFrames = sinceSample;
323 _pathFramesAtSample[i] = frames;
328 .framesDisplayed = _retiredFramesDisplayed + sinkCounts.displayed,
329 .framesDropped = _framesDropped.load(std::memory_order_relaxed) + _retiredFramesSuperseded +
330 sinkCounts.superseded + _lateFramesDropped,
331 .displayPath = _displayPath,
332 .gpuFallbacks = _retiredGpuFallbacks + sinkCounts.gpuFallbacks,
333 .decoderRestarts = _decoderRestarts,
337void DecodingBranch::_retireSinkCounts()
343 const SinkFrameCounts counts = sinkFrameCountsSince(stats.get(), _sinkStatsAtStart.get());
344 _retiredFramesDisplayed += counts.displayed;
345 _retiredFramesSuperseded += counts.superseded;
346 _retiredGpuFallbacks += counts.gpuFallbacks;
349void DecodingBranch::_countLateFrames()
351 const quint64 dropped = sinkLateFramesDropped(_sink.get());
353 _lateFramesDropped += (dropped >= _sinkLateFramesSeen) ? (dropped - _sinkLateFramesSeen) : dropped;
354 _sinkLateFramesSeen = dropped;
357void DecodingBranch::_insertDecoder()
359 if (_tryInsertDecoder()) {
363 _context.post([
this]() { _listener.onDecoderFailing(); });
366bool DecodingBranch::_tryInsertDecoder()
368 setSinkSync(_sink.get(), !_lowLatency);
369 if (!gst_bin_add(GST_BIN(_context.pipeline), _sink.get())) {
370 qCWarning(GstVideoReceiverLog) <<
"Failed to add the video sink" << _context.redactedUri;
374 (void) gst_element_set_state(_sink.get(), GST_STATE_PAUSED);
378 qCWarning(GstVideoReceiverLog) <<
"gst_element_factory_make('decodebin3') failed";
384 (void) _decoderElementAdded.connect(_decoder.get(),
"deep-element-added", G_CALLBACK(_onDecoderElementAdded),
this);
385 (void) _decoderPadAdded.connect(_decoder.get(),
"pad-added", G_CALLBACK(_onDecoderPadAdded),
this);
386 (void) g_signal_connect(_decoder.get(),
"select-stream", G_CALLBACK(decodeVideoOnly),
nullptr);
388 if (!gst_bin_add(GST_BIN(_context.pipeline), _decoder.get()) ||
389 !gst_element_sync_state_with_parent(_decoder.get()) || !gst_element_link(_head.valve(), _decoder.get())) {
390 qCWarning(GstVideoReceiverLog) <<
"Unable to insert the decoder" << _context.redactedUri;
394 _context.dotDumper->dump(_context.pipeline,
"pipeline-with-decoder");
396 (void) _insertions.fetch_add(1, std::memory_order_relaxed);
398 _gateClosed.store(
false, std::memory_order_relaxed);
402 qCDebug(GstVideoReceiverLog) <<
"Decoder inserted" << _context.redactedUri;
406void DecodingBranch::_removeDecoder()
414 _sinkLateFramesSeen = 0;
417 _decoderPadAdded.disconnect();
418 _decoderElementAdded.disconnect();
421 _pluggedDecoder.reset();
422 _hardwareDecoder =
false;
423 _setDecoderName(QString());
424 _context.dotDumper->dump(_context.pipeline,
"pipeline-decoding-stopped");
428void DecodingBranch::_linkDecoderPad(GstPad* pad)
431 const GstPadLinkReturn linkResult = sinkPad ? gst_pad_link(pad, sinkPad.get()) : GST_PAD_LINK_WRONG_HIERARCHY;
432 if (linkResult != GST_PAD_LINK_OK) {
433 qCWarning(GstVideoReceiverLog) <<
"Unable to link the decoder to the video sink:"
434 << gst_pad_link_get_name(linkResult);
438 (void) gst_element_sync_state_with_parent(_sink.get());
441 (void) gst_bin_recalculate_latency(GST_BIN(_context.pipeline));
442 _context.dotDumper->dump(_context.pipeline,
"pipeline-with-videosink");
445void DecodingBranch::_demoteFailedDecoder()
447 if (!_hardwareDecoder || !_pluggedDecoder) {
458 qCWarning(GstVideoReceiverLog) <<
"The hardware decoder" << _decoderName
459 <<
"brought no frame after a restart: the next decoder takes over"
460 << _context.redactedUri;
464void DecodingBranch::_onFirstFrame(quint64 insertion)
466 if (!_decoder || (insertion != _insertions.load(std::memory_order_relaxed))) {
469 _restartsWithoutFrame = 0;
473void DecodingBranch::_setDecoding(
bool decoding)
475 if (decoding == _decoding) {
478 _decoding = decoding;
479 qCDebug(GstVideoReceiverLog) << (decoding ?
"Decoding started" :
"Decoding stopped") << _context.redactedUri;
480 _listener.onDecodingChanged(decoding);
483void DecodingBranch::_setDecoderName(
const QString& name)
485 if (name == _decoderName) {
489 _listener.onDecoderNameChanged(name);
492void DecodingBranch::_onQueueOverrun(
GstElement* , gpointer data)
497 (void) self->_overruns.fetch_add(1, std::memory_order_relaxed);
500GstPadProbeReturn DecodingBranch::_gateProbe(GstPad* , GstPadProbeInfo* info, gpointer data)
503 const GstBuffer*
const buffer = GST_PAD_PROBE_INFO_BUFFER(info);
507 if (buffer && GST_BUFFER_FLAG_IS_SET(buffer, GST_BUFFER_FLAG_DISCONT)) {
508 const quint64 leaked = self->_overruns.exchange(0, std::memory_order_relaxed);
509 (void) self->_framesDropped.fetch_add(leaked, std::memory_order_relaxed);
510 if ((leaked > 0) && !self->_gateClosed.exchange(
true, std::memory_order_relaxed)) {
512 self->_context.post([self]() { self->_head.requestKeyframe(); });
515 self->_overruns.store(0, std::memory_order_relaxed);
517 if (!self->_gateClosed.load(std::memory_order_relaxed)) {
518 return GST_PAD_PROBE_OK;
520 if (buffer && GST_BUFFER_FLAG_IS_SET(buffer, GST_BUFFER_FLAG_DELTA_UNIT)) {
522 if ((now - self->_gateClosedAtMs.load(std::memory_order_relaxed)) < kMaxGateMs) {
523 (void) self->_framesDropped.fetch_add(1, std::memory_order_relaxed);
526 self->_context.watchdog->noteFrameWithheld(now);
527 return GST_PAD_PROBE_DROP;
530 if (!self->_gateTimeoutWarned.exchange(
true, std::memory_order_relaxed)) {
531 qCWarning(GstVideoReceiverLog) <<
"No keyframe within" << kMaxGateMs
532 <<
"ms of the request that followed a dropped frame: the picture goes on "
533 "without one. The stream's sender may not take keyframe requests."
534 << self->_context.redactedUri;
536 qCDebug(GstVideoReceiverLog) <<
"No keyframe within" << kMaxGateMs <<
"ms of the request"
537 << self->_context.redactedUri;
540 self->_gateClosed.store(
false, std::memory_order_relaxed);
541 return GST_PAD_PROBE_OK;
544GstPadProbeReturn DecodingBranch::_sinkProbe(GstPad* , GstPadProbeInfo* , gpointer data)
548 const quint64 insertion = self->_insertions.load(std::memory_order_relaxed);
549 self->_context.post([self, insertion]() { self->_onFirstFrame(insertion); });
551 return GST_PAD_PROBE_OK;
554void DecodingBranch::_onDecoderPadAdded(
GstElement* decoder, GstPad* pad, gpointer data)
561 if (padDecoder.get() == self->_decoder.get()) {
562 self->_linkDecoderPad(newPad);
567void DecodingBranch::_onDecoderElementAdded(GstBin* decodebin, GstBin* ,
GstElement* element, gpointer data)
572 GstElementFactory* factory = gst_element_get_factory(element);
573 if (!factory || !gst_element_factory_list_is_type(factory, GST_ELEMENT_FACTORY_TYPE_DECODER)) {
581 if (g_object_class_find_property(G_OBJECT_GET_CLASS(element),
"qos")) {
582 g_object_set(element,
"qos", FALSE,
nullptr);
585 const bool live = fedByLiveSource(GST_ELEMENT(decodebin));
587 decodeWithoutDelay(element);
591 qCDebug(GstVideoReceiverLog).noquote()
593 << (live ?
"" :
"- set to decode without delay, as the source isn't live")
594 << (singleThread ?
"- on one thread, as this FFmpeg's HEVC slice threads can deadlock" :
"");
595 const QString name = QString::fromUtf8(gst_plugin_feature_get_name(GST_PLUGIN_FEATURE(factory)));
602 if (decoder.get() != self->_decoder.get()) {
605 self->_hardwareDecoder = hardware;
606 self->_pluggedDecoder = plugged;
607 self->_setDecoderName(name);
HwVideoBufferPath
GPU zero-copy path a frame is imported through; None means the frame takes the CPU path.
struct _GstElement GstElement
void onSourceStreaming()
The first frame reached the tee: inserts the decoder when a video sink is waiting for it.
static constexpr int kMaxDecoderRestarts
bool build()
Adds the branch's leaky queue and closed valve behind the tee.
void onGraphicsDeviceServed()
void reset()
Takes the video sink and decoder out of the pipeline, which must be in NULL, and releases the sink.
GstQgc::PathStats sinkPathStats() const
bool isCurrent(GstObject *source) const
void setVideoSink(GstElement *sink)
Decodes into sink from now on, or stops decoding for nullptr.
StatsSample sampleStats()
Not const: displayPath compares the sink's counts with the previous sample's.
void restartDecoder(const char *reason)
Replaces the decoder and resets the sink, leaving the rest of the pipeline (and a recording) running.
DecodingBranch(const BranchContext &context, Listener &listener, bool lowLatency)
lowLatency: frames are shown as soon as decoded instead of at their presentation time.
static void absorbFlowErrors(GstElement *part)
void disposeChild(GstElement *element)
std::unique_ptr< GstCaps, GstCapsDeleter > GstCapsPtr
GstStructurePtr adoptStructure(GstStructure *structure) noexcept
std::function< void()> holdPadUntilLinked(GstPad *pad, std::function< void(GstPad *pad)> link)
GstQueryPtr adoptQuery(GstQuery *query) noexcept
GstElementPtr makeElement(const char *factory, const char *name=nullptr)
std::unique_ptr< GstStructure, GstStructureDeleter > GstStructurePtr
void markBranch(GstElement *element, PipelineBranch branch)
Marks element and everything inside it as part of branch.
bool demoteFailedDecoder(const char *factoryName, const GstCaps *caps)
DecoderRankApplier::demoteFailedDecoder() on the process's applier. Any thread.
GstCapsPtr adoptCaps(GstCaps *caps) noexcept
std::shared_ptr< T > shareObject(T *object)
A copyable owner of a new ref on object, for tasks that must be copyable (std::function).
std::unique_ptr< GstPad, GstObjectDeleter > GstPadPtr
GstElementPtr adoptElement(GstElement *element) noexcept
bool isHardwareDecoderFactory(GstElementFactory *factory)
std::unique_ptr< GstQuery, GstQueryDeleter > GstQueryPtr
bool avoidHevcWavefrontDeadlock(GstElement *decoder, QLatin1StringView version)
QString describeDecoderFactory(GstElementFactory *factory)
"[HW|SW] <plugin>/<factory> rank=<rank> (<klass>)" for decoder logs.
GstPadPtr adoptPad(GstPad *pad) noexcept
Snapshot snapshot() noexcept
constexpr std::size_t kPathCount
constexpr const char * toString(HwVideoBufferPath path) noexcept
const char * sinkFramesField(HwVideoBufferPath path)
quint64 frameStatsGrowth(const GstStructure *stats, const GstStructure *since, const char *field) noexcept
How far the guint64 field grew from since to stats, two "frame-stats" values of the same sink.
constexpr const char * kSupersededFramesField
PathStats formatSinkStats(const GstStructure *stats, const GstStructure *since)
constexpr const char * kGpuFallbacksField
guint64 "frame-stats" field holding the frames a GPU path was tried for but the CPU delivered.
quint64 frameStatsField(const GstStructure *stats, const char *field) noexcept
The guint64 field of stats, a "frame-stats" or any other structure; 0 without the structure or the fi...
GStreamer::GstStructurePtr frameStats(GstElement *sinkOrBin)
The "frame-stats" of sinkOrBin, a qgcqvideosink or the qgcvideosinkbin around one; null for other ele...
QString extraPathStatsSince(const GstHwPathTelemetry::Snapshot &baseline)
bool graphicsDeviceLost() noexcept
What the branch measured for VideoStreamStats.
Formatted per-path frame counts + the total delivered through GPU paths.