QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
GstRtspSource.cc
Go to the documentation of this file.
1#include "GstRtspSource.h"
2
3#include <chrono>
4#include <cstring>
5#include <gst/rtsp/gstrtspmessage.h>
6#include <gst/rtsp/gstrtsptransport.h>
7#include <gst/rtsp/gstrtspurl.h>
8#include <gst/sdp/gstsdpmessage.h>
9
10#include <QtCore/QUrl>
11
12#include "QGCNetworkHelper.h"
13
15
16namespace {
17
18// How long rtspsrc waits to connect and for the answer to each request (20 s by default). It doesn't end a stream
19// whose TCP-interleaved data stops: there rtspsrc only sends a keep-alive when the time is up, and it is the
20// receiver's watchdog that notices the stall.
21constexpr guint64 kRtspTcpTimeoutUs = G_GUINT64_CONSTANT(5000000);
22
23// How long stopping waits for the TEARDOWN to be sent and answered, where rtspsrc's 100 ms cuts it short on a slow
24// link and leaves the camera streaming until the session times out. A camera that is gone holds each stop up for this
25// long, which has to stay well within the 2 s a receiver being destroyed gives its pipeline to stop.
26constexpr guint64 kRtspTeardownTimeoutNs = GST_SECOND;
27
28// Fixed rtx timing instead of the auto(-1) heuristic, which can stack retries and balloon playout
29// latency: bounded recovery latency over a lossy RF link.
30constexpr int kRtxDelayMs = 25;
31// One retry after the first request: at most two requests for a packet.
32constexpr int kRtxMaxRetries = 1;
33
35void configureRtspJitterBuffer([[maybe_unused]] GstElement* manager, GstElement* jitterBuffer,
36 [[maybe_unused]] guint session, [[maybe_unused]] guint ssrc, gpointer data)
37{
38 reportDroppedPackets(jitterBuffer);
39 if (data) {
40 g_object_set(jitterBuffer, "rtx-delay", kRtxDelayMs, "rtx-max-retries", kRtxMaxRetries, nullptr);
41 }
42}
43
45void connectRtspJitterBufferPolicy([[maybe_unused]] GstElement* rtspsrc, GstElement* manager, gpointer data)
46{
47 // rtspsrc picks rtpdec instead of rtpbin for RealMedia; only rtpbin exposes its jitterbuffers.
48 if (g_signal_lookup("new-jitterbuffer", G_OBJECT_TYPE(manager)) == 0) {
49 return;
50 }
51 (void) g_signal_connect(manager, "new-jitterbuffer", G_CALLBACK(configureRtspJitterBuffer), data);
52}
53
54// Runs before SETUP, so skipped SDP streams cost no bandwidth and can't claim the video parser. The caps are
55// still named application/x-unknown here (rtspsrc renames them to the transport's media type only after
56// SETUP), so only the SDP media type decides.
57gboolean selectVideoStream([[maybe_unused]] GstElement* rtspsrc, guint num, GstCaps* caps,
58 [[maybe_unused]] gpointer data)
59{
60 if (caps && (gst_caps_get_size(caps) > 0) && isVideoMedia(gst_caps_get_structure(caps, 0))) {
61 return TRUE;
62 }
63
64 qCDebug(GstSourceFactoryLog) << "Skipping non-video RTSP stream" << num;
65 return FALSE;
66}
67
68// rtpbin sends a keyframe request (an RTCP PLI) only for a stream whose caps say the sender takes one, which they do
69// when its SDP has "a=rtcp-fb: nack pli". Few cameras' SDP has it, also among those that answer a PLI, and the others
70// ignore the packet. Without it the requests of the depayloader, the decoder and the recorder end in rtspsrc.
71void advertiseKeyframeRequests([[maybe_unused]] GstElement* rtspsrc, GstSDPMessage* sdp, [[maybe_unused]] gpointer data)
72{
73 const guint mediaCount = gst_sdp_message_medias_len(sdp);
74 for (guint i = 0; i < mediaCount; ++i) {
75 // The message is rtspsrc's to change here, though its accessor is for reading.
76 auto* const media = const_cast<GstSDPMedia*>(gst_sdp_message_get_media(sdp, i));
77 if (g_strcmp0(gst_sdp_media_get_media(media), "video") != 0) {
78 continue;
79 }
80 bool takesPli = false;
81 for (guint n = 0; !takesPli; ++n) {
82 const gchar* const feedback = gst_sdp_media_get_attribute_val_n(media, "rtcp-fb", n);
83 if (!feedback) {
84 break;
85 }
86 takesPli = std::strstr(feedback, "nack pli") != nullptr;
87 }
88 if (!takesPli) {
89 (void) gst_sdp_media_add_attribute(media, "rtcp-fb", "* nack pli");
90 }
91 }
92}
93
94// A pipeline passes through PAUSED on its way to NULL, where rtspsrc sends a PAUSE before the TEARDOWN that ends the
95// session anyway, and some live cameras answer a PAUSE with an error. The receiver never pauses a stream, so that is
96// the only PAUSE there would be.
97gboolean skipPauseRequest([[maybe_unused]] GstElement* rtspsrc, GstRTSPMessage* request, [[maybe_unused]] gpointer data)
98{
99 const bool pause =
100 (request->type == GST_RTSP_MESSAGE_REQUEST) && (request->type_data.request.method == GST_RTSP_PAUSE);
101 return pause ? FALSE : TRUE;
102}
103
104} // namespace
105
106bool isValidRtspUri(const gchar* uri_str)
107{
108 if (!uri_str) {
109 return false;
110 }
111
112 if (!gst_uri_is_valid(uri_str)) {
113 return false;
114 }
115
116 GstRTSPUrl* url = nullptr;
117 const GstRTSPResult res = gst_rtsp_url_parse(uri_str, &url);
118 if ((res != GST_RTSP_OK) || !url) {
119 if (url) {
120 gst_rtsp_url_free(url);
121 }
122 return false;
123 }
124
125 const bool hasHost = (url->host && url->host[0] != '\0');
126 gst_rtsp_url_free(url);
127 return hasHost;
128}
129
130bool isVideoMedia(const GstStructure* structure)
131{
132 return g_strcmp0(gst_structure_get_string(structure, "media"), "video") == 0;
133}
134
135GstElementPtr buildRtspSource(const QString& uri, const QUrl& sourceUrl, const Config& config, guint latencyMs)
136{
137 if (!isValidRtspUri(uri.toUtf8().constData())) {
138 qCWarning(GstSourceFactoryLog) << "Invalid RTSP URI:" << QGCNetworkHelper::redactedUrlForLogging(sourceUrl);
139 return nullptr;
140 }
141
142 GstElementPtr source = makeElement("rtspsrc", "source");
143 if (!source) {
144 qCWarning(GstSourceFactoryLog) << "gst_element_factory_make('rtspsrc') failed";
145 return nullptr;
146 }
147
148 QUrl cleanUrl(sourceUrl);
149 cleanUrl.setUserInfo(QString());
150 const QByteArray cleanLocation = cleanUrl.toEncoded();
151
152 // Unicast UDP, then TCP-interleaved: rtspsrc retries over TCP when no UDP data arrives within "timeout". The
153 // default would also try UDP multicast, which a GCS link never uses.
154 constexpr GstRTSPLowerTrans kRtspProtocols =
155 static_cast<GstRTSPLowerTrans>(GST_RTSP_LOWER_TRANS_UDP | GST_RTSP_LOWER_TRANS_TCP);
156 constexpr guint64 kRtspUdpTimeoutUs = std::chrono::microseconds(kRtspUdpTimeout).count();
157
158 // rtspsrc always owns an internal jitterbuffer, so None maps to zero playout latency and no retransmission.
159 const guint rtspLatencyMs = (config.jitterBuffer == JitterBuffer::None) ? 0u : latencyMs;
160 const gboolean doRetransmission =
161 ((config.jitterBuffer != JitterBuffer::None) && config.doRetransmission) ? TRUE : FALSE;
162 g_object_set(source.get(), "location", cleanLocation.constData(), "latency", rtspLatencyMs, "do-rtcp", TRUE,
163 "do-retransmission", doRetransmission, "tcp-timeout", kRtspTcpTimeoutUs, "udp-reconnect", TRUE,
164 "drop-on-latency", TRUE, "timeout", kRtspUdpTimeoutUs, "protocols", kRtspProtocols, nullptr);
165 // rtspsrc's own 512 KiB is more than a stock Linux lets a socket ask for, which udpsrc warns about, and less than
166 // the factory's other UDP sockets get where the kernel allows more.
167 g_object_set(source.get(), "udp-buffer-size", udpReceiveBufferSize(), nullptr);
168 // Over TCP rtspsrc stamps only the first packet with its arrival time and derives the others from their RTP
169 // timestamps, so the camera's clock drifts against ours until, with a short latency, every packet is late. With
170 // this (GStreamer 1.24.10) each packet gets its arrival time, as over UDP, and the jitter buffer evens out the
171 // drift.
172 if (g_object_class_find_property(G_OBJECT_GET_CLASS(source.get()), "tcp-timestamp")) {
173 g_object_set(source.get(), "tcp-timestamp", TRUE, nullptr);
174 }
175
176 // rtspsrc forwards latency/drop-on-latency/do-retransmission to its rtpbin, but neither the rtx timing nor the
177 // messages about dropped packets.
178 (void) g_signal_connect(source.get(), "new-manager", G_CALLBACK(connectRtspJitterBufferPolicy),
179 doRetransmission ? GINT_TO_POINTER(TRUE) : nullptr);
180 (void) g_signal_connect(source.get(), "select-stream", G_CALLBACK(selectVideoStream), nullptr);
181 (void) g_signal_connect(source.get(), "on-sdp", G_CALLBACK(advertiseKeyframeRequests), nullptr);
182 (void) g_signal_connect(source.get(), "before-send", G_CALLBACK(skipPauseRequest), nullptr);
183 g_object_set(source.get(), "teardown-timeout", kRtspTeardownTimeoutNs, nullptr);
184
185 const QString rtspUser = sourceUrl.userName(QUrl::FullyDecoded);
186 const QString rtspPassword = sourceUrl.password(QUrl::FullyDecoded);
187 if (!rtspUser.isEmpty()) {
188 g_object_set(source.get(), "user-id", rtspUser.toUtf8().constData(), "user-pw",
189 rtspPassword.toUtf8().constData(), nullptr);
190 }
191 return source;
192}
193
194} // namespace GStreamer::SourceFactory
struct _GstElement GstElement
The RTSP source GStreamer::SourceFactory::create() builds, with QGC's transport, latency and retransm...
void reportDroppedPackets(GstElement *jitterBuffer)
bool isVideoMedia(const GstStructure *structure)
SDP-derived caps carry the stream's media type; audio and metadata streams must never reach the video...
@ None
No playout buffering; omits an explicit buffer or sets rtspsrc latency to zero.
constexpr std::chrono::milliseconds kRtspUdpTimeout
rtspsrc waits this long for UDP data before it retries the session over TCP ("timeout").
GstElementPtr buildRtspSource(const QString &uri, const QUrl &sourceUrl, const Config &config, guint latencyMs)
bool isValidRtspUri(const gchar *uri_str)
True for a syntactically valid rtsp* URI with a host.
GstElementPtr makeElement(const char *factory, const char *name=nullptr)
Definition GstScoped.h:178
std::unique_ptr< GstElement, GstObjectDeleter > GstElementPtr
Definition GstScoped.h:60
QString redactedUrlForLogging(const QUrl &url)
bool doRetransmission
RTSP only: plain UDP/TCP sources have no RTCP back-channel for NACKs.