QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
PipelineStatsProbe.cc
Go to the documentation of this file.
2
3#include <algorithm>
4#include <utility>
5
6#include <QtCore/QString>
7
8#include "GStreamerHelpers.h"
9#include "GstRtpPacketProbe.h"
10#include "GstScoped.h"
11#include "VideoStreamStats.h"
13
14namespace {
15
16// On a jitter buffer: the packets its "drop-msg" messages told it dropped to stay within its latency. Kept with the
17// element, as its "stats" are, so that both go when rtspsrc replaces its jitter buffers on a reconnect.
18constexpr char kDroppedOnLatencyKey[] = "qgc-dropped-on-latency";
19
20struct JitterBufferTotals
21{
22 bool found = false;
23 quint64 packetsPushed = 0;
25 quint64 packetsLost = 0;
26 quint64 packetsLate = 0;
27 quint64 packetsDuplicate = 0;
28 quint64 rtxRequested = 0;
29 quint64 rtxRecovered = 0;
30 guint64 maxJitterNs = 0;
31};
32
34JitterBufferTotals jitterBufferTotals(GstElement* bin)
35{
36 JitterBufferTotals totals;
37 if (!bin || !GST_IS_BIN(bin)) {
38 return totals;
39 }
40 const auto addStats = [](const GValue* item, gpointer data) {
41 auto* const element = GST_ELEMENT(g_value_get_object(item));
42 if (g_strcmp0(GStreamer::factoryNameOf(GST_OBJECT_CAST(element)), "rtpjitterbuffer") != 0) {
43 return;
44 }
45 GstStructure* rawStats = nullptr;
46 g_object_get(element, "stats", &rawStats, nullptr);
48 const auto field = [&stats](const char* name) -> guint64 { return GstQgc::frameStatsField(stats.get(), name); };
49 auto* const sum = static_cast<JitterBufferTotals*>(data);
50 sum->found = true;
51 sum->packetsPushed += field("num-pushed");
52 sum->packetsLost +=
53 field("num-lost") + GPOINTER_TO_SIZE(g_object_get_data(G_OBJECT(element), kDroppedOnLatencyKey));
54 sum->packetsLate += field("num-late");
55 sum->packetsDuplicate += field("num-duplicates");
56 sum->rtxRequested += field("rtx-count");
57 sum->rtxRecovered += field("rtx-success-count");
58 sum->maxJitterNs = std::max(sum->maxJitterNs, field("avg-jitter"));
59 };
60 GstIterator* const elements = gst_bin_iterate_recurse(GST_BIN(bin));
61 // rtspsrc adds its rtpbin, and rtpbin its jitter buffers, while the stream runs.
62 while (gst_iterator_foreach(elements, addStats, &totals) == GST_ITERATOR_RESYNC) {
63 gst_iterator_resync(elements);
64 totals = {};
65 }
66 gst_iterator_free(elements);
67 return totals;
68}
69
71QString codecName(const GstCaps* caps)
72{
73 if (!caps || gst_caps_is_empty(caps) || gst_caps_is_any(caps)) {
74 return {};
75 }
76 const GstStructure* const structure = gst_caps_get_structure(caps, 0);
77 static constexpr std::pair<const char*, const char*> kCodecs[] = {
78 {"video/x-h264", "H.264"}, {"video/x-h265", "H.265"}, {"video/x-av1", "AV1"},
79 {"video/x-vp8", "VP8"}, {"video/x-vp9", "VP9"}, {"image/jpeg", "MJPEG"},
80 };
81 for (const auto& [mediaType, codec] : kCodecs) {
82 if (gst_structure_has_name(structure, mediaType)) {
83 return QString::fromLatin1(codec);
84 }
85 }
86 gint mpegVersion = 0;
87 if (gst_structure_has_name(structure, "video/mpeg") &&
88 gst_structure_get_int(structure, "mpegversion", &mpegVersion)) {
89 return QStringLiteral("MPEG-%1").arg(mpegVersion);
90 }
91 return QString::fromUtf8(gst_structure_get_name(structure));
92}
93
94} // namespace
95
96void PipelineStatsProbe::noteBuffer(GstBuffer* buffer)
97{
98 (void) _bytesReceived.fetch_add(gst_buffer_get_size(buffer), std::memory_order_relaxed);
99 if (GST_BUFFER_FLAG_IS_SET(buffer, GST_BUFFER_FLAG_DELTA_UNIT)) {
100 return;
101 }
102 const GstClockTime time = GST_BUFFER_PTS_IS_VALID(buffer) ? GST_BUFFER_PTS(buffer) : GST_BUFFER_DTS(buffer);
103 if (GST_CLOCK_TIME_IS_VALID(time)) {
104 _noteKeyframe(time);
105 }
106}
107
109{
110 const GstStructure* const structure = gst_message_get_structure(message);
111 GstObject* const jitterBuffer = GST_MESSAGE_SRC(message);
112 guint dropped = 0;
113 // "num-too-late", the message's other count, is "num-late" of the jitter buffer's stats.
114 if (!structure || !jitterBuffer || !gst_structure_has_name(structure, "drop-msg") ||
115 !gst_structure_get_uint(structure, "num-drop-on-latency", &dropped) || (dropped == 0)) {
116 return;
117 }
118 const gsize total = GPOINTER_TO_SIZE(g_object_get_data(G_OBJECT(jitterBuffer), kDroppedOnLatencyKey)) + dropped;
119 g_object_set_data(G_OBJECT(jitterBuffer), kDroppedOnLatencyKey, GSIZE_TO_POINTER(total));
120}
121
122void PipelineStatsProbe::_noteKeyframe(GstClockTime time)
123{
124 if (_keyframeTimeCount > 0) {
125 const GstClockTime previous = _keyframeTimes[_keyframeTimeCount - 1];
126 // Parameter sets that arrive in a buffer of their own share the keyframe's timestamp.
127 if (time == previous) {
128 return;
129 }
130 // Timestamps that went back start over, as after a new segment.
131 if (time < previous) {
132 _keyframeTimeCount = 0;
133 }
134 }
135 if (_keyframeTimeCount == kKeyframeWindow) {
136 std::shift_left(_keyframeTimes.begin(), _keyframeTimes.end(), 1);
137 --_keyframeTimeCount;
138 }
139 _keyframeTimes[_keyframeTimeCount++] = time;
140 if (_keyframeTimeCount >= 2) {
141 const GstClockTime span = _keyframeTimes[_keyframeTimeCount - 1] - _keyframeTimes[0];
142 _keyframeInterval.store(span / (_keyframeTimeCount - 1), std::memory_order_relaxed);
143 }
144}
145
148{
149 counters.bytesReceived = _bytesReceived.load(std::memory_order_relaxed);
150
151 counters.rtp.reset();
152 stats.jitterMs = -1.0;
153 stats.packetsLate = -1;
154 stats.packetsDuplicate = -1;
155 stats.rtxRequested = -1;
156 stats.rtxRecovered = -1;
157 const JitterBufferTotals jitterBuffers = jitterBufferTotals(source);
158 if (jitterBuffers.found) {
159 counters.rtp = VideoStreamStatsMeter::RtpCounters{.packetsReceived = jitterBuffers.packetsPushed,
160 .packetsLost = jitterBuffers.packetsLost};
161 stats.jitterMs = static_cast<double>(jitterBuffers.maxJitterNs) / GST_MSECOND;
162 stats.packetsLate = static_cast<qint64>(jitterBuffers.packetsLate);
163 stats.packetsDuplicate = static_cast<qint64>(jitterBuffers.packetsDuplicate);
164 stats.rtxRequested = static_cast<qint64>(jitterBuffers.rtxRequested);
165 stats.rtxRecovered = static_cast<qint64>(jitterBuffers.rtxRecovered);
166 } else if (const std::optional<GStreamer::RtpPacketCounts> packets = GStreamer::rtpPacketCounts(source)) {
167 // A packet that arrives late is no longer lost, but the meter takes a counter that shrank for one that started
168 // again from zero: the count it is given only grows, and the next packets lost make up for the late one.
169 _rtpPacketsLost = std::max(_rtpPacketsLost, packets->packetsLost);
170 counters.rtp = VideoStreamStatsMeter::RtpCounters{.packetsReceived = packets->packetsReceived,
171 .packetsLost = _rtpPacketsLost};
172 stats.jitterMs = packets->jitterMs;
173 }
174
175 const GstClockTime keyframeInterval = _keyframeInterval.load(std::memory_order_relaxed);
176 stats.keyframeIntervalMs =
177 GST_CLOCK_TIME_IS_VALID(keyframeInterval) ? static_cast<double>(keyframeInterval) / GST_MSECOND : -1.0;
178
179 GstClockTime minLatency = 0;
180 GstClockTime maxLatency = 0;
181 stats.latencyMs =
182 queryLatency(pipeline, minLatency, maxLatency) ? static_cast<double>(minLatency) / GST_MSECOND : -1.0;
183
184 const GStreamer::GstPadPtr teeSink = GStreamer::adoptPad(tee ? gst_element_get_static_pad(tee, "sink") : nullptr);
185 const GStreamer::GstCapsPtr caps =
186 GStreamer::adoptCaps(teeSink ? gst_pad_get_current_caps(teeSink.get()) : nullptr);
187 stats.codec = codecName(caps.get());
188}
189
190bool PipelineStatsProbe::queryLatency(GstElement* pipeline, GstClockTime& min, GstClockTime& max)
191{
192 if (!pipeline) {
193 return false;
194 }
195 const GStreamer::GstQueryPtr query = GStreamer::adoptQuery(gst_query_new_latency());
196 if (!gst_element_query(pipeline, query.get())) {
197 return false;
198 }
199 gboolean live = FALSE;
200 gst_query_parse_latency(query.get(), &live, &min, &max);
201 return true;
202}
struct _GstElement GstElement
static void noteElementMessage(GstMessage *message)
void sample(GstElement *pipeline, GstElement *source, GstElement *tee, VideoStreamStatsMeter::Counters &counters, VideoStreamStats &stats)
void noteBuffer(GstBuffer *buffer)
Streaming thread (the tee's sink pad, so one at a time): buffer reached the tee.
static bool queryLatency(GstElement *pipeline, GstClockTime &min, GstClockTime &max)
The latency pipeline reports; false when it doesn't answer the latency query.
std::unique_ptr< GstCaps, GstCapsDeleter > GstCapsPtr
Definition GstScoped.h:66
GstStructurePtr adoptStructure(GstStructure *structure) noexcept
Definition GstScoped.h:129
GstQueryPtr adoptQuery(GstQuery *query) noexcept
Definition GstScoped.h:104
std::unique_ptr< GstStructure, GstStructureDeleter > GstStructurePtr
Definition GstScoped.h:70
std::optional< RtpPacketCounts > rtpPacketCounts(GstElement *bin)
What countRtpPackets() counted for bin so far, from any thread; nullopt for a bin without it,...
const char * factoryNameOf(GstObject *object)
The name of the factory that made object ("rtph264depay"); null when it is no element or has no facto...
GstCapsPtr adoptCaps(GstCaps *caps) noexcept
Definition GstScoped.h:109
std::unique_ptr< GstPad, GstObjectDeleter > GstPadPtr
Definition GstScoped.h:61
std::unique_ptr< GstQuery, GstQueryDeleter > GstQueryPtr
Definition GstScoped.h:65
GstPadPtr adoptPad(GstPad *pad) noexcept
Definition GstScoped.h:84
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...
std::optional< quint64 > bytesReceived
Only for a backend that counts the bytes it receives: bitrateKbps is -1 without.
std::optional< RtpCounters > rtp
Only for an RTP stream whose packets the backend counts.
QString codec
"H.264", "H.265", ..., or a USB camera's capture format, such as "MJPEG" or "YUYV".
double keyframeIntervalMs
Between keyframes, from their timestamps, averaged over the last few.
double latencyMs
The pipeline's minimum latency, the playout delay it adds on top of the network's.
double jitterMs
RTP interarrival jitter (RFC 3550), averaged over the last packets.
qint64 packetsLate
Since the stream started: RTP packets that arrived after their playout time, and duplicate RTP packet...
qint64 rtxRequested
Since the stream started: RTP retransmissions requested (RTSP), and how many arrived in time.