QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
DecodingBranch.cc
Go to the documentation of this file.
1#include "DecodingBranch.h"
2
3#include <gst/gst.h>
4
6#include "GStreamerHelpers.h"
8#include "GstVideoReceiver.h"
10#include "PipelineDotDumper.h"
11#include "StreamWatchdog.h"
13
14namespace {
15
16constexpr guint kDisplayQueueMaxBuffers = 2;
17// How long the keyframe gate waits for a keyframe: time for one that was asked for to arrive, and most streams' own
18// keyframe interval. A stream without keyframes (intra refresh), or one whose sender takes no requests, would
19// otherwise freeze for good, or for a whole GOP, after a dropped frame.
20constexpr qint64 kMaxGateMs = 2000;
21
25gint decodeVideoOnly([[maybe_unused]] GstElement* decodebin, [[maybe_unused]] GstStreamCollection* collection,
26 GstStream* stream, [[maybe_unused]] gpointer data)
27{
28 return ((gst_stream_get_stream_type(stream) & GST_STREAM_TYPE_VIDEO) != 0) ? 1 : 0;
29}
30
32void setSinkSync(GstElement* sink, bool sync)
33{
34 if (g_object_class_find_property(G_OBJECT_GET_CLASS(sink), "sync")) {
35 g_object_set(sink, "sync", sync, nullptr);
36 return;
37 }
38 if (!GST_IS_BIN(sink)) {
39 return;
40 }
41 GstIterator* const sinks = gst_bin_iterate_sinks(GST_BIN(sink));
42 (void) gst_iterator_foreach(
43 sinks,
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);
48 }
49 },
50 GINT_TO_POINTER(sync ? TRUE : FALSE));
51 gst_iterator_free(sinks);
52}
53
56guint64 lateFramesDroppedBy(GstElement* element)
57{
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)) {
60 return 0;
61 }
62 GstStructure* rawStats = nullptr;
63 g_object_get(element, "stats", &rawStats, nullptr);
65 return GstQgc::frameStatsField(stats.get(), "dropped");
66}
67
70quint64 sinkLateFramesDropped(GstElement* sink)
71{
72 if (!sink) {
73 return 0;
74 }
75 if (!GST_IS_BIN(sink)) {
76 return lateFramesDroppedBy(sink);
77 }
78 guint64 dropped = 0;
79 GstIterator* const sinks = gst_bin_iterate_sinks(GST_BIN(sink));
80 (void) gst_iterator_foreach(
81 sinks,
82 [](const GValue* item, gpointer data) {
83 *static_cast<guint64*>(data) += lateFramesDroppedBy(GST_ELEMENT(g_value_get_object(item)));
84 },
85 &dropped);
86 gst_iterator_free(sinks);
87 return dropped;
88}
89
92bool hasHardwareDecoder(GstElement* decodebin)
93{
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;
101 }
102 };
103 while (gst_iterator_foreach(elements, note, &hardware) == GST_ITERATOR_RESYNC) {
104 gst_iterator_resync(elements);
105 }
106 gst_iterator_free(elements);
107 return hardware;
108}
109
111bool fedByLiveSource(GstElement* decodebin)
112{
113 const GStreamer::GstPadPtr sinkPad = GStreamer::adoptPad(gst_element_get_static_pad(decodebin, "sink"));
114 const GStreamer::GstQueryPtr query = GStreamer::adoptQuery(gst_query_new_latency());
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);
118 }
119 return live;
120}
121
124void decodeWithoutDelay(GstElement* decoder)
125{
126 GObject* const object = G_OBJECT(decoder);
127 // libav: every frame thread holds a frame back.
128 gst_util_set_object_arg(object, "thread-type", "slice");
129 // nvcodec: frames held back to pipeline decoding with display.
130 gst_util_set_object_arg(object, "max-display-delay", "0");
131 // The stateless H.264 decoders (va, d3d11, d3d12, v4l2sl, nv; GStreamer 1.20): a frame leaves the picture buffer
132 // once its place in the output order is known, not when the buffer is full.
133 gst_util_set_object_arg(object, "compliance", "normal");
134}
135
136bool isInside(GstObject* object, GstElement* element)
137{
138 return element && object && gst_object_has_as_ancestor(object, GST_OBJECT_CAST(element));
139}
140
141struct SinkFrameCounts
142{
143 quint64 displayed = 0;
144 quint64 superseded = 0;
145 quint64 gpuFallbacks = 0;
146};
147
150SinkFrameCounts sinkFrameCountsSince(const GstStructure* stats, const GstStructure* since)
151{
152 const auto growth = [stats, since](const char* field) { return GstQgc::frameStatsGrowth(stats, since, field); };
153 quint64 delivered = 0;
154 for (std::size_t i = 0; i < GstHw::kPathCount; ++i) {
155 delivered += growth(GstQgc::sinkFramesField(HwVideoBufferPath(i)));
156 }
157 const quint64 superseded = growth(GstQgc::kSupersededFramesField);
158 return {.displayed = (delivered > superseded) ? (delivered - superseded) : 0,
159 .superseded = superseded,
160 .gpuFallbacks = growth(GstQgc::kGpuFallbacksField)};
161}
162
163} // namespace
164
165DecodingBranch::DecodingBranch(const BranchContext& context, Listener& listener, bool lowLatency)
166 : _context(context)
167 , _listener(listener)
168 , _lowLatency(lowLatency)
169{}
170
175
177{
178 if (!_head.build(_context.pipeline, _context.tee, GStreamer::PipelineBranch::Decoding, "display")) {
179 return false;
180 }
181 GstElement* const queue = _head.queue();
182
183 // Tiny and leaky: the live display must drop its oldest frame on backpressure, never stall the tee. The
184 // backpressure comes late, though: ahead of its decoder, decodebin3's multiqueue first buffers the stream, by
185 // time and with no limit on buffers. It holds its min-interleave-time: 250 ms by default, the decoder's latency
186 // plus 100 ms once the decoder reports one, and no less than the pipeline's latency (GStreamer 1.24, and the
187 // later 1.22 releases). Only a decoder that falls further behind than that makes this queue leak.
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);
191
192 // "overrun" announces a leak; the gate's probe sees whether one followed.
193 _head.onOverrun(G_CALLBACK(_onQueueOverrun), this);
194 const GStreamer::GstPadPtr queueSrc = GStreamer::adoptPad(gst_element_get_static_pad(queue, "src"));
195 if (!queueSrc || !_keyframeGate.add(queueSrc.get(), GST_PAD_PROBE_TYPE_BUFFER, _gateProbe, this)) {
196 qCCritical(GstVideoReceiverLog) << "Failed to add the display keyframe gate";
197 return false;
198 }
199 return true;
200}
201
203{
204 _keyframeGate.remove();
205 _removeDecoder();
206 _sinkFrameProbe.remove();
207 _sink.reset();
208 _sinkStatsAtStart.reset();
209 _setDecoding(false);
210 _head.reset();
211}
212
214{
215 if (sink == _sink.get()) {
216 return;
217 }
218
219 _removeDecoder();
220 _sinkFrameProbe.remove();
221 _retireSinkCounts();
222 _sink.reset();
223 _sinkStatsAtStart.reset();
224 _setDecoding(false);
225
226 if (!sink) {
227 return;
228 }
229
230 const GStreamer::GstPadPtr sinkPad = GStreamer::adoptPad(gst_element_get_static_pad(sink, "sink"));
231 if (!sinkPad) {
232 qCCritical(GstVideoReceiverLog) << "The video sink has no sink pad" << _context.redactedUri;
233 return;
234 }
235 _sink = GStreamer::adoptElement(GST_ELEMENT(gst_object_ref(sink)));
236 _sinkStatsAtStart = GstQgc::frameStats(_sink.get());
237 for (std::size_t i = 0; i < GstHw::kPathCount; ++i) {
238 _pathFramesAtSample[i] =
240 }
241 _gpuCountersAtStart = GstHwPathTelemetry::snapshot();
243 (void) _sinkFrameProbe.add(sinkPad.get(), GST_PAD_PROBE_TYPE_BUFFER, _sinkProbe, this);
244
245 if (_streaming) {
246 _insertDecoder();
247 }
248}
249
251{
252 _streaming = true;
253 if (_sink && !_decoder) {
254 _insertDecoder();
255 }
256}
257
258void DecodingBranch::restartDecoder(const char* reason)
259{
260 if (!_decoder) {
261 return;
262 }
263
264 if (++_restartsWithoutFrame > kMaxDecoderRestarts) {
265 qCDebug(GstVideoReceiverLog) << "Decoder failing after" << kMaxDecoderRestarts << "restarts, last:" << reason
266 << _context.redactedUri;
267 _context.post([this]() { _listener.onDecoderFailing(); });
268 return;
269 }
270
271 qCDebug(GstVideoReceiverLog) << "Restarting the decoder after" << reason << _context.redactedUri;
272 ++_decoderRestarts;
273 // The restart before this one brought no frame: with the same ranks decodebin3 would plug the same decoder again.
274 if (_restartsWithoutFrame > 1) {
275 _demoteFailedDecoder();
276 }
277 _removeDecoder();
278 _setDecoding(false);
279 _insertDecoder();
280}
281
283{
284 if (!_decoder || !hasHardwareDecoder(_decoder.get())) {
285 return;
286 }
287 qCDebug(GstVideoReceiverLog) << "Replacing the decoder" << _decoderName
288 << "by one on the graphics device Qt renders with" << _context.redactedUri;
289 _removeDecoder();
290 _setDecoding(false);
291 _insertDecoder();
292}
293
294bool DecodingBranch::isCurrent(GstObject* source) const
295{
296 return _head.contains(source) || isInside(source, _decoder.get()) || (_decoder && isInside(source, _sink.get()));
297}
298
300{
301 const GStreamer::GstStructurePtr stats = GstQgc::frameStats(_sink.get());
302 GstQgc::PathStats out = GstQgc::formatSinkStats(stats.get(), _sinkStatsAtStart.get());
303 if (stats) {
304 out.line += HwBuffers::extraPathStatsSince(_gpuCountersAtStart);
305 }
306 return out;
307}
308
310{
311 const GStreamer::GstStructurePtr stats = GstQgc::frameStats(_sink.get());
312 const SinkFrameCounts sinkCounts = sinkFrameCountsSince(stats.get(), _sinkStatsAtStart.get());
313
314 quint64 busiestPathFrames = 0;
315 for (std::size_t i = 0; i < GstHw::kPathCount; ++i) {
316 const auto path = HwVideoBufferPath(i);
317 const quint64 frames = GstQgc::frameStatsField(stats.get(), GstQgc::sinkFramesField(path));
318 const quint64 sinceSample = (frames > _pathFramesAtSample[i]) ? (frames - _pathFramesAtSample[i]) : 0;
319 if (sinceSample > busiestPathFrames) {
320 busiestPathFrames = sinceSample;
321 _displayPath = QString::fromLatin1(GstHw::toString(path));
322 }
323 _pathFramesAtSample[i] = frames;
324 }
325 _countLateFrames();
326
327 return {
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,
334 };
335}
336
337void DecodingBranch::_retireSinkCounts()
338{
339 if (!_sink) {
340 return;
341 }
342 const GStreamer::GstStructurePtr stats = GstQgc::frameStats(_sink.get());
343 const SinkFrameCounts counts = sinkFrameCountsSince(stats.get(), _sinkStatsAtStart.get());
344 _retiredFramesDisplayed += counts.displayed;
345 _retiredFramesSuperseded += counts.superseded;
346 _retiredGpuFallbacks += counts.gpuFallbacks;
347}
348
349void DecodingBranch::_countLateFrames()
350{
351 const quint64 dropped = sinkLateFramesDropped(_sink.get());
352 // A count below the last one started over.
353 _lateFramesDropped += (dropped >= _sinkLateFramesSeen) ? (dropped - _sinkLateFramesSeen) : dropped;
354 _sinkLateFramesSeen = dropped;
355}
356
357void DecodingBranch::_insertDecoder()
358{
359 if (_tryInsertDecoder()) {
360 return;
361 }
362 // Without a decoder no frame is due at the sink, so neither the watchdog nor a bus error would ever report this.
363 _context.post([this]() { _listener.onDecoderFailing(); });
364}
365
366bool DecodingBranch::_tryInsertDecoder()
367{
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;
371 return false;
372 }
373 // PAUSED (not READY) negotiates downstream caps before the decoder pushes; PLAYING once linked.
374 (void) gst_element_set_state(_sink.get(), GST_STATE_PAUSED);
375
376 _decoder = GStreamer::makeElement("decodebin3");
377 if (!_decoder) {
378 qCWarning(GstVideoReceiverLog) << "gst_element_factory_make('decodebin3') failed";
379 GStreamer::disposeChild(_sink.get());
380 return false;
381 }
383 TeeBranchHead::absorbFlowErrors(_decoder.get());
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);
387
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;
391 _removeDecoder();
392 return false;
393 }
394 _context.dotDumper->dump(_context.pipeline, "pipeline-with-decoder");
395
396 (void) _insertions.fetch_add(1, std::memory_order_relaxed);
397 _context.watchdog->startSinkClock(StreamWatchdog::now());
398 _gateClosed.store(false, std::memory_order_relaxed);
399 // Without a keyframe the new decoder has nothing to start from until the stream's next one.
400 _head.open();
401
402 qCDebug(GstVideoReceiverLog) << "Decoder inserted" << _context.redactedUri;
403 return true;
404}
405
406void DecodingBranch::_removeDecoder()
407{
408 _head.close();
409 // The sink first: going NULL releases a decoder thread waiting inside it, so the decoder can stop.
410 if (_sink) {
411 // Leaving PLAYING starts the sink's count of late frames over.
412 _countLateFrames();
413 GStreamer::disposeChild(_sink.get());
414 _sinkLateFramesSeen = 0;
415 }
416 if (_decoder) {
417 _decoderPadAdded.disconnect();
418 _decoderElementAdded.disconnect();
419 GStreamer::disposeChild(_decoder.get());
420 _decoder.reset();
421 _pluggedDecoder.reset();
422 _hardwareDecoder = false;
423 _setDecoderName(QString());
424 _context.dotDumper->dump(_context.pipeline, "pipeline-decoding-stopped");
425 }
426}
427
428void DecodingBranch::_linkDecoderPad(GstPad* pad)
429{
430 const GStreamer::GstPadPtr sinkPad = GStreamer::adoptPad(gst_element_get_static_pad(_sink.get(), "sink"));
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);
435 restartDecoder("link failure");
436 return;
437 }
438 (void) gst_element_sync_state_with_parent(_sink.get());
439 // The sink posted LATENCY when it was added, with nothing linked to it yet, so that recalculation failed. Without
440 // this one it would take its first frames for late ones, until another element posted LATENCY.
441 (void) gst_bin_recalculate_latency(GST_BIN(_context.pipeline));
442 _context.dotDumper->dump(_context.pipeline, "pipeline-with-videosink");
443}
444
445void DecodingBranch::_demoteFailedDecoder()
446{
447 if (!_hardwareDecoder || !_pluggedDecoder) {
448 return;
449 }
450 // Every decoder fails on a device that was removed, and none is at fault.
452 return;
453 }
454 const GStreamer::GstPadPtr sinkPad = GStreamer::adoptPad(gst_element_get_static_pad(_pluggedDecoder.get(), "sink"));
455 const GStreamer::GstCapsPtr caps =
456 GStreamer::adoptCaps(sinkPad ? gst_pad_get_current_caps(sinkPad.get()) : nullptr);
457 if (caps && GStreamer::demoteFailedDecoder(_decoderName.toUtf8().constData(), caps.get())) {
458 qCWarning(GstVideoReceiverLog) << "The hardware decoder" << _decoderName
459 << "brought no frame after a restart: the next decoder takes over"
460 << _context.redactedUri;
461 }
462}
463
464void DecodingBranch::_onFirstFrame(quint64 insertion)
465{
466 if (!_decoder || (insertion != _insertions.load(std::memory_order_relaxed))) {
467 return;
468 }
469 _restartsWithoutFrame = 0;
470 _setDecoding(true);
471}
472
473void DecodingBranch::_setDecoding(bool decoding)
474{
475 if (decoding == _decoding) {
476 return;
477 }
478 _decoding = decoding;
479 qCDebug(GstVideoReceiverLog) << (decoding ? "Decoding started" : "Decoding stopped") << _context.redactedUri;
480 _listener.onDecodingChanged(decoding);
481}
482
483void DecodingBranch::_setDecoderName(const QString& name)
484{
485 if (name == _decoderName) {
486 return;
487 }
488 _decoderName = name;
489 _listener.onDecoderNameChanged(name);
490}
491
492void DecodingBranch::_onQueueOverrun(GstElement* /*queue*/, gpointer data)
493{
494 auto* const self = static_cast<DecodingBranch*>(data);
495 // No frame is lost yet: the queue looks again once this returns, and leaks its oldest buffer only if it is still
496 // full. The decoder may have taken one meanwhile.
497 (void) self->_overruns.fetch_add(1, std::memory_order_relaxed);
498}
499
500GstPadProbeReturn DecodingBranch::_gateProbe(GstPad* /*pad*/, GstPadProbeInfo* info, gpointer data)
501{
502 auto* const self = static_cast<DecodingBranch*>(data);
503 const GstBuffer* const buffer = GST_PAD_PROBE_INFO_BUFFER(info);
504 // The queue marks the buffer that follows a leak. Each overrun before it leaked one buffer, as the queue fills by
505 // buffer count only. An overrun before a buffer without the mark leaked nothing, and is forgotten: it would be
506 // taken for the leak behind a mark that upstream sets later, for a loss ahead of the tee.
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)) {
511 self->_gateClosedAtMs.store(StreamWatchdog::now(), std::memory_order_relaxed);
512 self->_context.post([self]() { self->_head.requestKeyframe(); });
513 }
514 } else {
515 self->_overruns.store(0, std::memory_order_relaxed);
516 }
517 if (!self->_gateClosed.load(std::memory_order_relaxed)) {
518 return GST_PAD_PROBE_OK;
519 }
520 if (buffer && GST_BUFFER_FLAG_IS_SET(buffer, GST_BUFFER_FLAG_DELTA_UNIT)) {
521 const qint64 now = StreamWatchdog::now();
522 if ((now - self->_gateClosedAtMs.load(std::memory_order_relaxed)) < kMaxGateMs) {
523 (void) self->_framesDropped.fetch_add(1, std::memory_order_relaxed);
524 // The gate's time is not the decoder's: with the shortest stream timeout the decoder counts as stalled
525 // after as long as the gate may stay closed.
526 self->_context.watchdog->noteFrameWithheld(now);
527 return GST_PAD_PROBE_DROP;
528 }
529 // Told once at a level that shows: the same holds for every later request to this stream's sender.
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;
535 } else {
536 qCDebug(GstVideoReceiverLog) << "No keyframe within" << kMaxGateMs << "ms of the request"
537 << self->_context.redactedUri;
538 }
539 }
540 self->_gateClosed.store(false, std::memory_order_relaxed);
541 return GST_PAD_PROBE_OK;
542}
543
544GstPadProbeReturn DecodingBranch::_sinkProbe(GstPad* /*pad*/, GstPadProbeInfo* /*info*/, gpointer data)
545{
546 auto* const self = static_cast<DecodingBranch*>(data);
547 if (self->_context.watchdog->noteSinkFrame(StreamWatchdog::now())) {
548 const quint64 insertion = self->_insertions.load(std::memory_order_relaxed);
549 self->_context.post([self, insertion]() { self->_onFirstFrame(insertion); });
550 }
551 return GST_PAD_PROBE_OK;
552}
553
554void DecodingBranch::_onDecoderPadAdded(GstElement* decoder, GstPad* pad, gpointer data)
555{
556 auto* const self = static_cast<DecodingBranch*>(data);
557
558 // Runs on a streaming thread; the pipeline is only changed on the worker.
559 self->_context.post(
560 GStreamer::holdPadUntilLinked(pad, [self, padDecoder = GStreamer::shareObject(decoder)](GstPad* newPad) {
561 if (padDecoder.get() == self->_decoder.get()) {
562 self->_linkDecoderPad(newPad);
563 }
564 }));
565}
566
567void DecodingBranch::_onDecoderElementAdded(GstBin* decodebin, GstBin* /*subBin*/, GstElement* element, gpointer data)
568{
569 // A message can outlive the decoder that held its source, which leaves nothing to blame it on but its own mark.
571
572 GstElementFactory* factory = gst_element_get_factory(element);
573 if (!factory || !gst_element_factory_list_is_type(factory, GST_ELEMENT_FACTORY_TYPE_DECODER)) {
574 return;
575 }
576
577 // Live streams: once a frame is late, a QoS event has the videodecoder base class drop the frames due before the
578 // time it names. Turned off here, before the decoder sees data, for each decoder decodebin3 plugs, later swaps
579 // included. That stops the base class only: avdec and amcvideodec act on the event's deadline themselves, and it
580 // is the sink bin, which keeps its sink's QoS off, that sends them none.
581 if (g_object_class_find_property(G_OBJECT_GET_CLASS(element), "qos")) {
582 g_object_set(element, "qos", FALSE, nullptr);
583 }
584 // A decoder takes a source that isn't live (tcp://) for a file, and trades delay for throughput.
585 const bool live = fedByLiveSource(GST_ELEMENT(decodebin));
586 if (!live) {
587 decodeWithoutDelay(element);
588 }
589 const bool singleThread = GStreamer::avoidHevcWavefrontDeadlock(element);
590
591 qCDebug(GstVideoReceiverLog).noquote()
592 << "Decodebin3 selected" << GStreamer::describeDecoderFactory(factory) << "- QoS disabled"
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)));
596 const bool hardware = GStreamer::isHardwareDecoderFactory(factory);
597
598 auto* const self = static_cast<DecodingBranch*>(data);
599 self->_context.post([self, name, hardware, decoder = GStreamer::shareObject(GST_ELEMENT(decodebin)),
600 plugged = GStreamer::shareObject(element)]() {
601 // A decodebin3 taken out meanwhile has no decoder left to name.
602 if (decoder.get() != self->_decoder.get()) {
603 return;
604 }
605 self->_hardwareDecoder = hardware;
606 self->_pluggedDecoder = plugged;
607 self->_setDecoderName(name);
608 });
609}
HwVideoBufferPath
GPU zero-copy path a frame is imported through; None means the frame takes the CPU path.
Definition GstHwTypes.h:7
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 qint64 now()
static void absorbFlowErrors(GstElement *part)
void disposeChild(GstElement *element)
std::unique_ptr< GstCaps, GstCapsDeleter > GstCapsPtr
Definition GstScoped.h:66
GstStructurePtr adoptStructure(GstStructure *structure) noexcept
Definition GstScoped.h:129
std::function< void()> holdPadUntilLinked(GstPad *pad, std::function< void(GstPad *pad)> link)
GstQueryPtr adoptQuery(GstQuery *query) noexcept
Definition GstScoped.h:104
GstElementPtr makeElement(const char *factory, const char *name=nullptr)
Definition GstScoped.h:178
std::unique_ptr< GstStructure, GstStructureDeleter > GstStructurePtr
Definition GstScoped.h:70
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
Definition GstScoped.h:109
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< GstPad, GstObjectDeleter > GstPadPtr
Definition GstScoped.h:61
GstElementPtr adoptElement(GstElement *element) noexcept
Definition GstScoped.h:79
bool isHardwareDecoderFactory(GstElementFactory *factory)
std::unique_ptr< GstQuery, GstQueryDeleter > GstQueryPtr
Definition GstScoped.h:65
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
Definition GstScoped.h:84
Snapshot snapshot() noexcept
constexpr std::size_t kPathCount
Definition GstHwTypes.h:33
constexpr const char * toString(HwVideoBufferPath path) noexcept
Definition GstHwTypes.h:37
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)
Definition HwBuffers.cc:294
bool graphicsDeviceLost() noexcept
Definition HwBuffers.cc:129
What the branch measured for VideoStreamStats.
Formatted per-path frame counts + the total delivered through GPU paths.