QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
GstSourceFactory.cc
Go to the documentation of this file.
1#include "GstSourceFactory.h"
2
3#include <algorithm>
4#include <chrono>
5#include <cstdio>
6#include <gst/gst.h>
7#include <mutex>
8#include <optional>
9#include <utility>
10
11#include <QtCore/QByteArray>
12#include <QtCore/QFile>
13#include <QtCore/QUrl>
14#include <QtNetwork/QHostAddress>
15
16#include "GStreamerHelpers.h"
17#include "GstRtpPacketProbe.h"
18#include "GstRtspSource.h"
19#include "GstScoped.h"
20#include "QGCLoggingCategory.h"
21#include "QGCNetworkHelper.h"
22#include "VideoStreamUri.h"
23
24QGC_LOGGING_CATEGORY(GstSourceFactoryLog, "Video.GStreamer.GstSourceFactory")
25
26namespace {
27
28using namespace GStreamer;
29
30constexpr int kUdpBufferSizeBytes = 8 * 1024 * 1024;
31// tcpclientsrc connects inside the state change, on the receiver's worker, and without a timeout waits as long as the
32// OS does (minutes for a host that drops the SYN). The same time bounds a read, which is how long the receiver waits
33// for a TCP stream that went silent anyway.
34constexpr guint kTcpTimeoutSeconds = 3;
35// The least latency an MPEG-TS stream is given. tsdemux pushes a video frame only once the next one starts (its PES
36// packet needn't tell its length), so a frame is a frame interval late however steady the network is: this covers
37// streams down to 10 fps.
38constexpr guint kTsDemuxMinLatencyMs = 100;
39// Of the RTP timestamps of video, H.264 (RFC 6184) and H.265 (RFC 7798) included.
40constexpr int kRtpVideoClockRate = 90000;
41
43void configureAutopluggedElement([[maybe_unused]] GstBin* bin, [[maybe_unused]] GstBin* subBin, GstElement* element,
44 gpointer data)
45{
47 SourceFactory::configureH26xRtpDepayloader(element, data != nullptr);
48}
49
50// Older Linux/system GStreamer needs an autoplug-query caps filter to keep parsebin on byte-stream output.
51#if defined(QGC_GST_ENABLE_LEGACY_PARSEBIN_CAPS_FILTER)
52gboolean filterParserCaps([[maybe_unused]] GstElement* bin, [[maybe_unused]] GstPad* pad,
53 [[maybe_unused]] GstElement* element, GstQuery* query, [[maybe_unused]] gpointer data)
54{
55 if (GST_QUERY_TYPE(query) != GST_QUERY_CAPS) {
56 return FALSE;
57 }
58
59 GstCaps* srcCaps;
60 gst_query_parse_caps(query, &srcCaps);
61 if (!srcCaps || gst_caps_is_any(srcCaps)) {
62 return FALSE;
63 }
64
65 GstCapsPtr sinkCaps;
66 GstStructure* structure = gst_caps_get_structure(srcCaps, 0);
67 if (gst_structure_has_name(structure, "video/x-h265")) {
68 const GstCapsPtr filter = adoptCaps(gst_caps_from_string("video/x-h265"));
69 if (gst_caps_can_intersect(srcCaps, filter.get())) {
70 sinkCaps = adoptCaps(gst_caps_from_string("video/x-h265,stream-format=hvc1"));
71 }
72 } else if (gst_structure_has_name(structure, "video/x-h264")) {
73 const GstCapsPtr filter = adoptCaps(gst_caps_from_string("video/x-h264"));
74 if (gst_caps_can_intersect(srcCaps, filter.get())) {
75 sinkCaps = adoptCaps(gst_caps_from_string("video/x-h264,stream-format=avc"));
76 }
77 }
78
79 if (sinkCaps) {
80 gst_query_set_caps_result(query, sinkCaps.get());
81 return TRUE;
82 }
83
84 return FALSE;
85}
86#endif
87
88void wrapWithGhostPad(GstElement* element, GstPad* pad, [[maybe_unused]] gpointer data)
89{
90 const GCharPtr name = adoptGChar(gst_pad_get_name(pad));
91 if (!name) {
92 qCWarning(GstSourceFactoryLog) << "gst_pad_get_name() failed";
93 return;
94 }
95
96 GstPadPtr ghostpad = adoptPad(gst_ghost_pad_new(name.get(), pad));
97 if (!ghostpad) {
98 qCWarning(GstSourceFactoryLog) << "gst_ghost_pad_new() failed";
99 return;
100 }
101
102 (void) gst_pad_set_active(ghostpad.get(), TRUE);
103
104 // gst_object_get_parent takes a ref (GST_ELEMENT_PARENT does not) — guards against a
105 // concurrent bin teardown finalizing the parent before gst_element_add_pad.
106 const GstObjectPtr parent = adoptObject(gst_object_get_parent(GST_OBJECT(element)));
107 if (!parent) {
108 qCWarning(GstSourceFactoryLog) << "Element has no parent; bin already torn down?";
109 return;
110 }
111
112 if (!gst_element_add_pad(GST_ELEMENT(parent.get()), ghostpad.release())) {
113 qCWarning(GstSourceFactoryLog) << "gst_element_add_pad() failed";
114 }
115}
116
117bool addStaticGhostPad(GstElement* element)
118{
119 const GstPadPtr srcPad = adoptPad(gst_element_get_static_pad(element, "src"));
120 if (!srcPad) {
121 qCWarning(GstSourceFactoryLog) << "gst_element_get_static_pad('src') failed";
122 return false;
123 }
124
125 wrapWithGhostPad(element, srcPad.get(), nullptr);
126 return true;
127}
128
129bool isVideoRtp(const GstStructure* structure)
130{
131 return gst_structure_has_name(structure, "application/x-rtp") && SourceFactory::isVideoMedia(structure);
132}
133
134} // namespace
135
136namespace GStreamer::SourceFactory {
137
138namespace {
139
141
143struct RtpCodec
144{
145 const char* encodingName;
146 const char* depayloader;
147 const char* parser;
148 const char* byteStreamCaps;
149};
150
151constexpr RtpCodec kRtpH264{"H264", "rtph264depay", "h264parse",
152 "video/x-h264, stream-format=(string)byte-stream, alignment=(string)au"};
153constexpr RtpCodec kRtpH265{"H265", "rtph265depay", "h265parse",
154 "video/x-h265, stream-format=(string)byte-stream, alignment=(string)au"};
155
156// Retransmission stays off: these sources have no RTCP back-channel, so the jitterbuffer's
157// retransmission requests would only reach the source element, which drops them.
158GstElement* addJitterBuffer(GstElement* bin, guint latencyMs)
159{
160 GstElementPtr buffer = makeElement("rtpjitterbuffer");
161 if (!buffer) {
162 qCWarning(GstSourceFactoryLog) << "gst_element_factory_make('rtpjitterbuffer') failed";
163 return nullptr;
164 }
165
166 // No "do-lost", as in rtspsrc's jitter buffers: nothing downstream acts on the GAP events it brings (the
167 // depayloader tells loss from the DISCONT flag, and the lost packets are counted either way), while one that
168 // reaches a parser ahead of the stream's parameter sets has it announce caps without them.
169 g_object_set(buffer.get(), "latency", latencyMs, "drop-on-latency", TRUE, nullptr);
170 reportDroppedPackets(buffer.get());
171 return addToBin(bin, std::move(buffer), "rtpjitterbuffer");
172}
173
174// Heap-owned context for the dynamic (pad-added) link path; freed with the pad-added handler it is given to.
175struct DynamicLinkContext
176{
178 GstElement* binParser;
179 bool isRtsp;
181 const RtpCodec* rtspCodec;
183 std::mutex linking;
184};
185
186void plugRtspCodec(DynamicLinkContext* ctx, const QByteArray& encoding);
187
188// rtspsrc names the pad of each RTP stream it receives "recv_rtp_src_<stream>_<SSRC>_<payload type>", the stream
189// being the one of the session, in the SDP's order. nullopt for any other pad.
190std::optional<guint> rtspStreamOfPad(GstPad* pad)
191{
192 const GCharPtr name = adoptGChar(gst_pad_get_name(pad));
193 guint stream = 0;
194 guint ssrc = 0;
195 guint payloadType = 0;
196 if (!name || (std::sscanf(name.get(), "recv_rtp_src_%u_%u_%u", &stream, &ssrc, &payloadType) != 3)) {
197 return std::nullopt;
198 }
199 return stream;
200}
201
202// The "encoding-name" of the RTP that @p pad carries, or can carry while it has no caps; empty when they don't tell.
203QByteArray rtpEncodingOfPad(GstPad* pad)
204{
205 GstCapsPtr caps = adoptCaps(gst_pad_get_current_caps(pad));
206 if (!caps) {
207 caps = adoptCaps(gst_pad_query_caps(pad, nullptr));
208 }
209 if (!caps || gst_caps_is_empty(caps.get()) || gst_caps_is_any(caps.get())) {
210 return {};
211 }
212 return QByteArray(gst_structure_get_string(gst_caps_get_structure(caps.get(), 0), "encoding-name"));
213}
214
215// rtspsrc adds a pad for every SSRC and payload type it receives in a stream of the session, and keeps the earlier
216// ones. A camera that starts its encoder over, as for another resolution, goes on under a new SSRC: its pad carries
217// the stream from then on, and @p linkedPad no more. A pad of another encoding is the stream's retransmissions or
218// error correction.
219bool continuesRtspStream(GstPad* pad, GstPad* linkedPad)
220{
221 const std::optional<guint> stream = rtspStreamOfPad(pad);
222 const QByteArray encoding = rtpEncodingOfPad(pad);
223 return stream && (rtspStreamOfPad(linkedPad) == stream) && !encoding.isEmpty() &&
224 (rtpEncodingOfPad(linkedPad) == encoding);
225}
226
227// The source's "pad-added", on the streaming thread that brings the pad's data. A state change of the bin waits for
228// that thread with the bin's state lock held, so what is taken out of the bin here goes through disposeChildAsync().
229void linkPad(GstElement* element, GstPad* pad, gpointer data)
230{
231 auto* const ctx = static_cast<DynamicLinkContext*>(data);
232
233 // tsdemux/rtspsrc fire pad-added for audio/data pads too; only link video src pads so a
234 // non-video pad can't claim the parser ahead of the real video pad.
235 if (GST_PAD_DIRECTION(pad) != GST_PAD_SRC) {
236 return;
237 }
238
239 bool isVideo = false;
240 bool isRtp = false;
241 GstCapsPtr caps = adoptCaps(gst_pad_get_current_caps(pad));
242 if (!caps) {
243 caps = adoptCaps(gst_pad_query_caps(pad, nullptr));
244 }
245 if (caps) {
246 const guint n = gst_caps_get_size(caps.get());
247 for (guint i = 0; i < n; ++i) {
248 const GstStructure* st = gst_caps_get_structure(caps.get(), i);
249 if (isVideoRtp(st)) {
250 // The depayloader/parsebin downstream classifies the video payload.
251 isRtp = true;
252 isVideo = true;
253 } else if (g_str_has_prefix(gst_structure_get_name(st), "video/")) {
254 isVideo = true;
255 }
256 }
257 }
258 if (!isVideo) {
259 return;
260 }
261
262 const std::lock_guard lock(ctx->linking);
263
264 // Link only the first matching video pad. A second pad-added (another video stream of an RTSP session, or a
265 // later tsdemux elementary stream) must not re-link an occupied sink. But a pad that the linked RTSP stream goes
266 // on on takes its place: left unlinked, its data would be dropped without an error, as rtspsrc reports the flow
267 // of the pad that is linked, until the stream watchdog ends the session.
268 const GstPadPtr parserSink = adoptPad(gst_element_get_static_pad(ctx->binParser, "sink"));
269 if (parserSink && gst_pad_is_linked(parserSink.get())) {
270 const GstPadPtr linkedPad = adoptPad(gst_pad_get_peer(parserSink.get()));
271 if (!linkedPad || !continuesRtspStream(pad, linkedPad.get()) ||
272 !gst_pad_unlink(linkedPad.get(), parserSink.get())) {
273 return;
274 }
275 qCDebug(GstSourceFactoryLog) << "The RTSP stream goes on on a new pad:" << GST_PAD_NAME(pad);
276 } else if (isRtp && ctx->isRtsp) {
277 plugRtspCodec(ctx, rtpEncodingOfPad(pad));
278 }
279
280 const GCharPtr name = adoptGChar(gst_pad_get_name(pad));
281 if (!name || !gst_element_link_pads(element, name.get(), ctx->binParser, "sink")) {
282 qCWarning(GstSourceFactoryLog) << "gst_element_link_pads() failed for" << (name ? name.get() : "(unnamed pad)");
283 }
284}
285
286// Each build* helper makes and configures the source element for one scheme family, logs the
287// specific failure, and returns the owning element (or nullptr). create() owns it from here on.
288
289GstElementPtr buildTcpSource(const QUrl& sourceUrl)
290{
291 const int port = sourceUrl.port();
292 if (!VideoStreamUri::isValidPort(port)) {
293 qCWarning(GstSourceFactoryLog) << "Invalid TCP port" << port << "in"
295 return nullptr;
296 }
297 const QString host = sourceUrl.host();
298 if (host.isEmpty()) {
299 qCWarning(GstSourceFactoryLog) << "Missing host in TCP URI"
301 return nullptr;
302 }
303
304 GstElementPtr source = makeElement("tcpclientsrc", "source");
305 if (!source) {
306 qCWarning(GstSourceFactoryLog) << "gst_element_factory_make('tcpclientsrc') failed";
307 return nullptr;
308 }
309
310 g_object_set(source.get(), "host", host.toUtf8().constData(), "port", static_cast<int>(port), "timeout",
311 kTcpTimeoutSeconds, nullptr);
312 return source;
313}
314
315GstElementPtr buildUdpSource(const QUrl& sourceUrl, const char* rtpEncoding)
316{
317 // Port 0 binds a free port, which udpsrc then reports in its "port" property.
318 const int port = sourceUrl.port();
319 if ((port != 0) && !VideoStreamUri::isValidPort(port)) {
320 qCWarning(GstSourceFactoryLog) << "Invalid UDP port" << port << "in"
322 return nullptr;
323 }
324
325 GstElementPtr source = makeElement("udpsrc", "source");
326 if (!source) {
327 qCWarning(GstSourceFactoryLog) << "gst_element_factory_make('udpsrc') failed";
328 return nullptr;
329 }
330
331 // Normalize udp265:///mpegts:// to udp:// for udpsrc, preserving query params.
332 QUrl udpUrl(sourceUrl);
333 udpUrl.setScheme(QStringLiteral("udp"));
334 udpUrl.setUserInfo(QString());
335 // udpsrc doesn't report a URI without a host as the error it takes it for, and listens on its default port, 5004.
336 if (udpUrl.host().isEmpty()) {
337 udpUrl.setHost(QStringLiteral("0.0.0.0"));
338 }
339 const QByteArray udpUri = udpUrl.toEncoded();
340 // udpsrc shares its port by default, and of two listeners on a unicast address only one gets a stream's packets,
341 // the other nothing and no error: a port in use has to fail to bind. The members of a multicast group do share it.
342 const gboolean sharePort = QHostAddress(udpUrl.host()).isMulticast() ? TRUE : FALSE;
343
344 // Nothing reads the sender's address, which udpsrc otherwise allocates a meta for with every packet.
345 g_object_set(source.get(), "uri", udpUri.constData(), "buffer-size", udpReceiveBufferSize(), "reuse", sharePort,
346 "retrieve-sender-address", FALSE, nullptr);
347
348 if (rtpEncoding) {
349 const GstCapsPtr caps = adoptCaps(gst_caps_new_simple("application/x-rtp", "media", G_TYPE_STRING, "video",
350 "clock-rate", G_TYPE_INT, kRtpVideoClockRate,
351 "encoding-name", G_TYPE_STRING, rtpEncoding, nullptr));
352 g_object_set(source.get(), "caps", caps.get(), nullptr);
353 }
354 return source;
355}
356
357struct ParserStage
358{
359 GstElementPtr parser;
360 GstElementPtr depay;
361};
362
363// The parser and the depayloader of @p rtpCodec, or parsebin without one, configured but not yet in a bin.
364ParserStage buildParserStage(const RtpCodec* rtpCodec, bool isRtsp)
365{
366 const char* const parserFactory = rtpCodec ? rtpCodec->parser : "parsebin";
367 ParserStage stage{makeElement(parserFactory, "parser"), {}};
368 if (!stage.parser) {
369 qCWarning(GstSourceFactoryLog) << "gst_element_factory_make(" << parserFactory << ") failed";
370 return {};
371 }
372
373 if (rtpCodec) {
374 // RTP over UDP has no SDP/RTSP control plane. Make depayloading and parser config explicit
375 // so hardware decoders, especially Android MediaCodec, see repeated parameter sets at IDR
376 // boundaries instead of depending on parsebin's defaults after startup or reconnect.
377 stage.depay = makeElement(rtpCodec->depayloader);
378 if (!stage.depay) {
379 qCWarning(GstSourceFactoryLog) << "gst_element_factory_make(" << rtpCodec->depayloader << ") failed";
380 return {};
381 }
382 configureH26xParser(stage.parser.get());
383 configureH26xRtpDepayloader(stage.depay.get(), isRtsp);
384 return stage;
385 }
386
387 // parsebin creates the depayloader and codec parser only after it sees the stream caps. Configure them
388 // as soon as they are autoplugged, before data flows.
389 (void) g_signal_connect(stage.parser.get(), "deep-element-added", G_CALLBACK(configureAutopluggedElement),
390 isRtsp ? GINT_TO_POINTER(TRUE) : nullptr);
391
392 // Older Linux/system GStreamer misnegotiates parser->decoder caps; force avc/hvc1 there only.
393 // Bundled 1.28+ SDKs do not need it, and the forced caps break byte-stream HW decoders.
394#if defined(QGC_GST_ENABLE_LEGACY_PARSEBIN_CAPS_FILTER)
395 (void) g_signal_connect(stage.parser.get(), "autoplug-query", G_CALLBACK(filterParserCaps), nullptr);
396#endif
397 return stage;
398}
399
400// Android can't determine MPEG2-TS via parsebin, so MPEG-TS sources get an explicit tsdemux. Returns the bin-owned
401// demuxer linked after @p upstream, or nullptr (logged).
402GstElement* addTsDemux(GstElement* bin, GstElement* upstream, guint latencyMs)
403{
404 GstElementPtr tsdemux = makeElement("tsdemux");
405 if (!tsdemux) {
406 qCWarning(GstSourceFactoryLog) << "gst_element_factory_make('tsdemux') failed";
407 return nullptr;
408 }
409
410 // tsdemux adds its "latency" to a live stream's: with its default, 700 ms, every frame of MPEG-TS over UDP is
411 // shown that much later.
412 if (g_object_class_find_property(G_OBJECT_GET_CLASS(tsdemux.get()), "latency")) {
413 g_object_set(tsdemux.get(), "latency", static_cast<gint>(std::max(latencyMs, kTsDemuxMinLatencyMs)), nullptr);
414 }
415
416 GstElement* const demux = addToBin(bin, std::move(tsdemux), "tsdemux");
417 if (!demux) {
418 return nullptr;
419 }
420
421 if (!gst_element_link(upstream, demux)) {
422 qCWarning(GstSourceFactoryLog) << "gst_element_link(source, tsdemux) failed";
423 return nullptr;
424 }
425 return demux;
426}
427
428// GStreamer defect, seen in GStreamer 1.28.8: decodebin3 picks the decoder when the stream starts, from the caps on
429// the stream object that came with it, and stores the parsed caps on that object only then, on another thread.
430// tsdemux's object has the caps of the unparsed stream, which no decoder takes, and parsebin leaves an upstream
431// element's object alone: on a busy machine decodebin3 read those caps, and the stream ended for want of a decoder.
432// So they are stored as they leave the parser, which a decodebin3 that waits for the parsed caps would not need.
433GstPadProbeReturn storeParsedCapsOnStream(GstPad* pad, GstPadProbeInfo* info, [[maybe_unused]] gpointer data)
434{
435 GstEvent* const event = GST_PAD_PROBE_INFO_EVENT(info);
436 if (GST_EVENT_TYPE(event) != GST_EVENT_CAPS) {
437 return GST_PAD_PROBE_OK;
438 }
439
440 GstCaps* caps = nullptr;
441 gst_event_parse_caps(event, &caps);
442 const GstEventPtr streamStart = adoptEvent(gst_pad_get_sticky_event(pad, GST_EVENT_STREAM_START, 0));
443 GstStream* rawStream = nullptr;
444 if (streamStart) {
445 gst_event_parse_stream(streamStart.get(), &rawStream);
446 }
447 const GstObjectPtr stream = adoptObject(GST_OBJECT_CAST(rawStream));
448 if (stream && caps && gst_caps_is_fixed(caps)) {
449 gst_stream_set_caps(GST_STREAM_CAST(stream.get()), caps);
450 }
451 return GST_PAD_PROBE_OK;
452}
453
454void storeParsedCapsOnPad([[maybe_unused]] GstElement* parser, GstPad* pad, [[maybe_unused]] gpointer data)
455{
456 (void) gst_pad_add_probe(pad, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM, storeParsedCapsOnStream, nullptr, nullptr);
457}
458
459// Wires upstream → binParser once upstream's video pad appears: rtspsrc and tsdemux have no source pad before they
460// stream. Neither gets a jitter buffer here: rtspsrc runs its own, and tsdemux's pads carry no RTP.
461void linkSourceToParserOnPadAdded(GstElement* upstream, GstElement* binParser, bool isRtsp)
462{
463 // The context lives as long as the handler: binParser may be replaced (plugRtspCodec()).
464 auto* ctx = new DynamicLinkContext{
465 .binParser = binParser,
466 .isRtsp = isRtsp,
467 .rtspCodec = nullptr,
468 .linking = {},
469 };
470 (void) g_signal_connect_data(
471 upstream, "pad-added", G_CALLBACK(linkPad), ctx,
472 [](gpointer context, GClosure*) { delete static_cast<DynamicLinkContext*>(context); }, GConnectFlags(0));
473
474 // pad-added fires on the streaming thread after create() returns the NULL-state bin, so it
475 // can't race construction; wrapWithGhostPad ref-checks the parent against teardown.
476 (void) g_signal_connect(binParser, "pad-added", G_CALLBACK(wrapWithGhostPad), nullptr);
477}
478
479bool linkDepayToParser(GstElement* depay, GstElement* parser, const RtpCodec& codec)
480{
481 // Left to negotiate, the depayloader may pick the length-prefixed format (avc, hvc1), whose caps it only sets once
482 // in-band parameter sets arrive, so its segment can go out first (GStreamer 1.28 warns) and the parameter-set
483 // gate, which handles byte-stream, stands down. Byte-stream caps are set as soon as the RTP caps arrive.
484 const GstCapsPtr byteStream = adoptCaps(gst_caps_from_string(codec.byteStreamCaps));
485 if (!byteStream || !gst_element_link_filtered(depay, parser, byteStream.get())) {
486 qCWarning(GstSourceFactoryLog) << "gst_element_link_filtered(depay, parser, byte-stream) failed";
487 return false;
488 }
489 return true;
490}
491
492bool linkUdpRtpToDepayAndParser(GstElement* bin, GstElement* source, GstElement* depay, GstElement* parser,
493 const RtpCodec& codec, const Config& config, guint latencyMs)
494{
495 GstElement* upstream = source;
496 if (config.jitterBuffer != JitterBuffer::None) {
497 GstElement* const buffer = addJitterBuffer(bin, latencyMs);
498 if (!buffer) {
499 return false;
500 }
501 if (!gst_element_link(source, buffer)) {
502 qCWarning(GstSourceFactoryLog) << "gst_element_link(source, rtpjitterbuffer) failed";
503 return false;
504 }
505 upstream = buffer;
506 } else {
507 // A jitter buffer counts the packets it is given, lost ones included. Without one the bin counts them itself,
508 // where they arrive, so the stream's statistics tell packet loss in this mode too.
509 const GstPadPtr sourcePad = adoptPad(gst_element_get_static_pad(source, "src"));
510 if (!sourcePad || !countRtpPackets(bin, sourcePad.get(), kRtpVideoClockRate)) {
511 qCWarning(GstSourceFactoryLog) << "Unable to count the RTP packets: no packet loss statistics";
512 }
513 }
514
515 if (!gst_element_link(upstream, depay)) {
516 qCWarning(GstSourceFactoryLog) << "gst_element_link(upstream, depay) failed";
517 return false;
518 }
519
520 return linkDepayToParser(depay, parser, codec);
521}
522
523// The SDP names the encoding of an RTSP stream, as the scheme does for RTP over UDP: an H.264 or H.265 stream gets the
524// same depayloader and parser, linked the same way, in place of @p ctx's parsebin, which stays for any other
525// @p encoding. parsebin links a parser only after the depayloader has chosen its output, a buffer for each NAL unit,
526// and the parser then can't tell that a frame is complete until the next one starts: a frame interval of latency.
527void plugRtspCodec(DynamicLinkContext* ctx, const QByteArray& encoding)
528{
529 const RtpCodec* const codec =
530 (encoding == kRtpH264.encodingName) ? &kRtpH264 : ((encoding == kRtpH265.encodingName) ? &kRtpH265 : nullptr);
531 const GstObjectPtr bin = adoptObject(gst_object_get_parent(GST_OBJECT(ctx->binParser)));
532 if (!codec || ctx->rtspCodec || !bin) {
533 return;
534 }
535
536 ParserStage stage = buildParserStage(codec, true);
537 if (!stage.parser) {
538 return;
539 }
540 // The bin has an element of the stage's name while parsebin is in it.
541 (void) gst_object_set_name(GST_OBJECT(stage.parser.get()), nullptr);
542 GstElement* const depay = addToBin(GST_ELEMENT(bin.get()), std::move(stage.depay), codec->depayloader);
543 GstElement* const parser = addToBin(GST_ELEMENT(bin.get()), std::move(stage.parser), codec->parser);
544 if (!depay || !parser || !linkDepayToParser(depay, parser, *codec) || !gst_element_sync_state_with_parent(parser) ||
545 !gst_element_sync_state_with_parent(depay) || !addStaticGhostPad(parser)) {
546 qCWarning(GstSourceFactoryLog) << "Unable to plug" << codec->depayloader << "and" << codec->parser
547 << "for the RTSP stream; leaving it to parsebin";
548 if (depay) {
549 disposeChildAsync(depay);
550 }
551 if (parser) {
552 disposeChildAsync(parser);
553 }
554 return;
555 }
556
557 disposeChildAsync(ctx->binParser);
558 ctx->binParser = depay;
559 ctx->rtspCodec = codec;
560}
561
562} // namespace
563
565{
566 // SO_RCVBUF above net.core.rmem_max needs CAP_NET_ADMIN; without it gstudpsrc fails with EPERM
567 // (scary warning) then clamps. Request the kernel-permitted max instead (Linux/Android only).
568 int udpBufferSize = kUdpBufferSizeBytes;
569#ifdef Q_OS_LINUX
570 // rmem_max is a boot-time sysctl; parse once and cache (0 = unreadable, leave request unclamped).
571 static const int s_rmemMax = [] {
572 QFile rmemMaxFile(QStringLiteral("/proc/sys/net/core/rmem_max"));
573 if (rmemMaxFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
574 bool ok = false;
575 const int sysMax = rmemMaxFile.readAll().trimmed().toInt(&ok);
576 if (ok && (sysMax > 0)) {
577 return sysMax;
578 }
579 }
580 return 0;
581 }();
582 if ((s_rmemMax > 0) && (s_rmemMax < udpBufferSize)) {
583 qCDebug(GstSourceFactoryLog) << "Clamping UDP buffer-size from" << udpBufferSize << "to net.core.rmem_max"
584 << s_rmemMax;
585 udpBufferSize = s_rmemMax;
586 }
587#endif
588 return udpBufferSize;
589}
590
592{
593 // GStreamer 1.18. A message for every packet, rather than the default of one every 200 ms that tells of those
594 // dropped since the last: the rest of a burst would only be told with the next one, which may never come.
595 if (g_object_class_find_property(G_OBJECT_GET_CLASS(jitterBuffer), "post-drop-messages")) {
596 g_object_set(jitterBuffer, "post-drop-messages", TRUE, "drop-messages-interval", 0u, nullptr);
597 }
598}
599
600GstElement* create(const QString& uri, const Config& config)
601{
602 if (uri.isEmpty()) {
603 qCWarning(GstSourceFactoryLog) << "Failed because URI is not specified";
604 return nullptr;
605 }
606
607 const guint latencyMs = (config.latencyMs < 0) ? 0u : static_cast<guint>(config.latencyMs);
608
609 const QUrl sourceUrl(uri);
610 const std::optional<Transport> transport = VideoStreamUri::transportFor(sourceUrl);
611 if (!transport) {
612 qCWarning(GstSourceFactoryLog) << "Unsupported URI scheme:" << sourceUrl.scheme() << "in"
614 return nullptr;
615 }
616
617 const bool isRtsp = (*transport == Transport::Rtsp);
618 // RTP on udpsrc is depayloaded and parsed for the codec its scheme names; the others leave it to parsebin.
619 const RtpCodec* const rtpCodec = (*transport == Transport::RtpUdpH264)
620 ? &kRtpH264
621 : ((*transport == Transport::RtpUdpH265) ? &kRtpH265 : nullptr);
622 // tsdemux ahead of the parser: Android's parsebin can't detect MPEG-TS.
623 const bool demuxMpegTs = (*transport == Transport::MpegTsUdp) || (*transport == Transport::MpegTsTcp);
624
625 GstElementPtr source;
626 switch (*transport) {
627 case Transport::Rtsp:
628 source = buildRtspSource(uri, sourceUrl, config, latencyMs);
629 break;
630 case Transport::MpegTsTcp:
631 source = buildTcpSource(sourceUrl);
632 break;
633 case Transport::RtpUdpH264:
634 case Transport::RtpUdpH265:
635 case Transport::MpegTsUdp:
636 source = buildUdpSource(sourceUrl, rtpCodec ? rtpCodec->encodingName : nullptr);
637 break;
638 }
639 if (!source) {
640 return nullptr;
641 }
642
643 GstElementPtr bin = adoptElement(gst_bin_new("sourcebin"));
644 if (!bin) {
645 qCWarning(GstSourceFactoryLog) << "gst_bin_new('sourcebin') failed";
646 return nullptr;
647 }
648
649 ParserStage parserStage = buildParserStage(rtpCodec, isRtsp);
650 if (!parserStage.parser) {
651 return nullptr;
652 }
653
654 // From here on the bin owns every element; the borrowed pointers stay valid while bin is alive.
655 GstElement* upstream = addToBin(bin.get(), std::move(source), "source");
656 if (!upstream) {
657 return nullptr;
658 }
659
660 GstElement* depay = nullptr;
661 if (parserStage.depay) {
662 depay = addToBin(bin.get(), std::move(parserStage.depay), rtpCodec->depayloader);
663 if (!depay) {
664 return nullptr;
665 }
666 }
667
668 GstElement* const binParser = addToBin(bin.get(), std::move(parserStage.parser), "parser");
669 if (!binParser) {
670 return nullptr;
671 }
672
673 if (demuxMpegTs) {
674 upstream = addTsDemux(bin.get(), upstream, latencyMs);
675 if (!upstream) {
676 return nullptr;
677 }
678 // Ahead of the handler that hands the pad on.
679 (void) g_signal_connect(binParser, "pad-added", G_CALLBACK(storeParsedCapsOnPad), nullptr);
680 }
681
682 if (rtpCodec) {
683 if (!linkUdpRtpToDepayAndParser(bin.get(), upstream, depay, binParser, *rtpCodec, config, latencyMs)) {
684 return nullptr;
685 }
686 if (!addStaticGhostPad(binParser)) {
687 return nullptr;
688 }
689 } else {
690 linkSourceToParserOnPadAdded(upstream, binParser, isRtsp);
691 }
692
693 return bin.release();
694}
695
696std::optional<std::chrono::milliseconds> connectGracePeriod(const QString& uri)
697{
698 const std::optional<Transport> transport = VideoStreamUri::transportFor(QUrl(uri));
699 if (transport && VideoStreamUri::listens(*transport)) {
700 return std::nullopt;
701 }
702 return (transport == Transport::Rtsp) ? kRtspUdpTimeout : std::chrono::milliseconds{0};
703}
704
705} // namespace GStreamer::SourceFactory
struct _GstElement GstElement
#define QGC_LOGGING_CATEGORY(name, categoryStr)
The RTSP source GStreamer::SourceFactory::create() builds, with QGC's transport, latency and retransm...
void reportDroppedPackets(GstElement *jitterBuffer)
GstElement * create(const QString &uri, const Config &config)
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").
void configureH26xParser(GstElement *element)
GstElementPtr buildRtspSource(const QString &uri, const QUrl &sourceUrl, const Config &config, guint latencyMs)
void configureH26xRtpDepayloader(GstElement *element, bool requestKeyframes)
std::optional< std::chrono::milliseconds > connectGracePeriod(const QString &uri)
void disposeChildAsync(GstElement *element)
std::unique_ptr< GstCaps, GstCapsDeleter > GstCapsPtr
Definition GstScoped.h:66
std::unique_ptr< GstObject, GstObjectDeleter > GstObjectPtr
Definition GstScoped.h:59
std::unique_ptr< GstEvent, GstEventDeleter > GstEventPtr
Definition GstScoped.h:68
GCharPtr adoptGChar(gchar *str) noexcept
Definition GstScoped.h:134
GstElementPtr makeElement(const char *factory, const char *name=nullptr)
Definition GstScoped.h:178
GstEventPtr adoptEvent(GstEvent *event) noexcept
Definition GstScoped.h:119
GstElement * addToBin(GstElement *bin, GstElementPtr element, const char *what)
GstCapsPtr adoptCaps(GstCaps *caps) noexcept
Definition GstScoped.h:109
std::unique_ptr< GstElement, GstObjectDeleter > GstElementPtr
Definition GstScoped.h:60
std::unique_ptr< GstPad, GstObjectDeleter > GstPadPtr
Definition GstScoped.h:61
GstObjectPtr adoptObject(GstObject *object) noexcept
Definition GstScoped.h:74
GstElementPtr adoptElement(GstElement *element) noexcept
Definition GstScoped.h:79
bool countRtpPackets(GstElement *bin, GstPad *pad, int clockRate)
std::unique_ptr< gchar, GFreeDeleter > GCharPtr
Definition GstScoped.h:71
GstPadPtr adoptPad(GstPad *pad) noexcept
Definition GstScoped.h:84
QString redactedUrlForLogging(const QUrl &url)
GPSCommandSequence port(QByteArrayView port, unsigned baud)
Clears the SBF output of port, keeps a serial port at the link's baud, and selects SBF and the WGS84 ...
Definition SBFPlan.cc:34
constexpr bool isValidPort(int port)
A TCP or UDP port a source can name: 1 to 65535.
constexpr bool listens(Transport transport)
The receiver listens on a local UDP port for transport, rather than connect to a server.
std::optional< Transport > transportFor(const QUrl &url)
The transport url's scheme selects, case-insensitively; nullopt for any other scheme.