11#include <QtCore/QByteArray>
12#include <QtCore/QFile>
14#include <QtNetwork/QHostAddress>
30constexpr int kUdpBufferSizeBytes = 8 * 1024 * 1024;
34constexpr guint kTcpTimeoutSeconds = 3;
38constexpr guint kTsDemuxMinLatencyMs = 100;
40constexpr int kRtpVideoClockRate = 90000;
43void configureAutopluggedElement([[maybe_unused]] GstBin* bin, [[maybe_unused]] GstBin* subBin,
GstElement* element,
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)
55 if (GST_QUERY_TYPE(query) != GST_QUERY_CAPS) {
60 gst_query_parse_caps(query, &srcCaps);
61 if (!srcCaps || gst_caps_is_any(srcCaps)) {
66 GstStructure* structure = gst_caps_get_structure(srcCaps, 0);
67 if (gst_structure_has_name(structure,
"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"));
72 }
else if (gst_structure_has_name(structure,
"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"));
80 gst_query_set_caps_result(query, sinkCaps.get());
88void wrapWithGhostPad(
GstElement* element, GstPad* pad, [[maybe_unused]] gpointer data)
92 qCWarning(GstSourceFactoryLog) <<
"gst_pad_get_name() failed";
98 qCWarning(GstSourceFactoryLog) <<
"gst_ghost_pad_new() failed";
102 (void) gst_pad_set_active(ghostpad.get(), TRUE);
108 qCWarning(GstSourceFactoryLog) <<
"Element has no parent; bin already torn down?";
112 if (!gst_element_add_pad(GST_ELEMENT(parent.get()), ghostpad.release())) {
113 qCWarning(GstSourceFactoryLog) <<
"gst_element_add_pad() failed";
121 qCWarning(GstSourceFactoryLog) <<
"gst_element_get_static_pad('src') failed";
125 wrapWithGhostPad(element, srcPad.get(),
nullptr);
129bool isVideoRtp(
const GstStructure* structure)
145 const char* encodingName;
146 const char* depayloader;
148 const char* byteStreamCaps;
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"};
162 qCWarning(GstSourceFactoryLog) <<
"gst_element_factory_make('rtpjitterbuffer') failed";
169 g_object_set(buffer.get(),
"latency", latencyMs,
"drop-on-latency", TRUE,
nullptr);
171 return addToBin(bin, std::move(buffer),
"rtpjitterbuffer");
175struct DynamicLinkContext
181 const RtpCodec* rtspCodec;
186void plugRtspCodec(DynamicLinkContext* ctx,
const QByteArray& encoding);
190std::optional<guint> rtspStreamOfPad(GstPad* pad)
195 guint payloadType = 0;
196 if (!name || (std::sscanf(name.get(),
"recv_rtp_src_%u_%u_%u", &stream, &ssrc, &payloadType) != 3)) {
203QByteArray rtpEncodingOfPad(GstPad* pad)
207 caps =
adoptCaps(gst_pad_query_caps(pad,
nullptr));
209 if (!caps || gst_caps_is_empty(caps.get()) || gst_caps_is_any(caps.get())) {
212 return QByteArray(gst_structure_get_string(gst_caps_get_structure(caps.get(), 0),
"encoding-name"));
219bool continuesRtspStream(GstPad* pad, GstPad* linkedPad)
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);
229void linkPad(
GstElement* element, GstPad* pad, gpointer data)
231 auto*
const ctx =
static_cast<DynamicLinkContext*
>(data);
235 if (GST_PAD_DIRECTION(pad) != GST_PAD_SRC) {
239 bool isVideo =
false;
243 caps =
adoptCaps(gst_pad_query_caps(pad,
nullptr));
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)) {
253 }
else if (g_str_has_prefix(gst_structure_get_name(st),
"video/")) {
262 const std::lock_guard lock(ctx->linking);
268 const GstPadPtr parserSink =
adoptPad(gst_element_get_static_pad(ctx->binParser,
"sink"));
269 if (parserSink && gst_pad_is_linked(parserSink.get())) {
271 if (!linkedPad || !continuesRtspStream(pad, linkedPad.get()) ||
272 !gst_pad_unlink(linkedPad.get(), parserSink.get())) {
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));
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)");
291 const int port = sourceUrl.port();
293 qCWarning(GstSourceFactoryLog) <<
"Invalid TCP port" <<
port <<
"in"
297 const QString host = sourceUrl.host();
298 if (host.isEmpty()) {
299 qCWarning(GstSourceFactoryLog) <<
"Missing host in TCP URI"
306 qCWarning(GstSourceFactoryLog) <<
"gst_element_factory_make('tcpclientsrc') failed";
310 g_object_set(source.get(),
"host", host.toUtf8().constData(),
"port",
static_cast<int>(port),
"timeout",
311 kTcpTimeoutSeconds,
nullptr);
315GstElementPtr buildUdpSource(
const QUrl& sourceUrl,
const char* rtpEncoding)
318 const int port = sourceUrl.port();
320 qCWarning(GstSourceFactoryLog) <<
"Invalid UDP port" <<
port <<
"in"
327 qCWarning(GstSourceFactoryLog) <<
"gst_element_factory_make('udpsrc') failed";
332 QUrl udpUrl(sourceUrl);
333 udpUrl.setScheme(QStringLiteral(
"udp"));
334 udpUrl.setUserInfo(QString());
336 if (udpUrl.host().isEmpty()) {
337 udpUrl.setHost(QStringLiteral(
"0.0.0.0"));
339 const QByteArray udpUri = udpUrl.toEncoded();
342 const gboolean sharePort = QHostAddress(udpUrl.host()).isMulticast() ? TRUE : FALSE;
345 g_object_set(source.get(),
"uri", udpUri.constData(),
"buffer-size",
udpReceiveBufferSize(),
"reuse", sharePort,
346 "retrieve-sender-address", FALSE,
nullptr);
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);
364ParserStage buildParserStage(
const RtpCodec* rtpCodec,
bool isRtsp)
366 const char*
const parserFactory = rtpCodec ? rtpCodec->parser :
"parsebin";
367 ParserStage stage{
makeElement(parserFactory,
"parser"), {}};
369 qCWarning(GstSourceFactoryLog) <<
"gst_element_factory_make(" << parserFactory <<
") failed";
379 qCWarning(GstSourceFactoryLog) <<
"gst_element_factory_make(" << rtpCodec->depayloader <<
") failed";
389 (void) g_signal_connect(stage.parser.get(),
"deep-element-added", G_CALLBACK(configureAutopluggedElement),
390 isRtsp ? GINT_TO_POINTER(TRUE) :
nullptr);
394#if defined(QGC_GST_ENABLE_LEGACY_PARSEBIN_CAPS_FILTER)
395 (void) g_signal_connect(stage.parser.get(),
"autoplug-query", G_CALLBACK(filterParserCaps),
nullptr);
406 qCWarning(GstSourceFactoryLog) <<
"gst_element_factory_make('tsdemux') failed";
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);
421 if (!gst_element_link(upstream, demux)) {
422 qCWarning(GstSourceFactoryLog) <<
"gst_element_link(source, tsdemux) failed";
433GstPadProbeReturn storeParsedCapsOnStream(GstPad* pad, GstPadProbeInfo* info, [[maybe_unused]] gpointer data)
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;
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;
445 gst_event_parse_stream(streamStart.get(), &rawStream);
448 if (stream && caps && gst_caps_is_fixed(caps)) {
449 gst_stream_set_caps(GST_STREAM_CAST(stream.get()), caps);
451 return GST_PAD_PROBE_OK;
454void storeParsedCapsOnPad([[maybe_unused]]
GstElement* parser, GstPad* pad, [[maybe_unused]] gpointer data)
456 (void) gst_pad_add_probe(pad, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM, storeParsedCapsOnStream,
nullptr,
nullptr);
464 auto* ctx =
new DynamicLinkContext{
465 .binParser = binParser,
467 .rtspCodec =
nullptr,
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));
476 (void) g_signal_connect(binParser,
"pad-added", G_CALLBACK(wrapWithGhostPad),
nullptr);
485 if (!byteStream || !gst_element_link_filtered(depay, parser, byteStream.get())) {
486 qCWarning(GstSourceFactoryLog) <<
"gst_element_link_filtered(depay, parser, byte-stream) failed";
493 const RtpCodec& codec,
const Config& config, guint latencyMs)
497 GstElement*
const buffer = addJitterBuffer(bin, latencyMs);
501 if (!gst_element_link(source, buffer)) {
502 qCWarning(GstSourceFactoryLog) <<
"gst_element_link(source, rtpjitterbuffer) failed";
510 if (!sourcePad || !
countRtpPackets(bin, sourcePad.get(), kRtpVideoClockRate)) {
511 qCWarning(GstSourceFactoryLog) <<
"Unable to count the RTP packets: no packet loss statistics";
515 if (!gst_element_link(upstream, depay)) {
516 qCWarning(GstSourceFactoryLog) <<
"gst_element_link(upstream, depay) failed";
520 return linkDepayToParser(depay, parser, codec);
527void plugRtspCodec(DynamicLinkContext* ctx,
const QByteArray& encoding)
529 const RtpCodec*
const codec =
530 (encoding == kRtpH264.encodingName) ? &kRtpH264 : ((encoding == kRtpH265.encodingName) ? &kRtpH265 : nullptr);
532 if (!codec || ctx->rtspCodec || !bin) {
536 ParserStage stage = buildParserStage(codec,
true);
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";
558 ctx->binParser = depay;
559 ctx->rtspCodec = codec;
568 int udpBufferSize = kUdpBufferSizeBytes;
571 static const int s_rmemMax = [] {
572 QFile rmemMaxFile(QStringLiteral(
"/proc/sys/net/core/rmem_max"));
573 if (rmemMaxFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
575 const int sysMax = rmemMaxFile.readAll().trimmed().toInt(&ok);
576 if (ok && (sysMax > 0)) {
582 if ((s_rmemMax > 0) && (s_rmemMax < udpBufferSize)) {
583 qCDebug(GstSourceFactoryLog) <<
"Clamping UDP buffer-size from" << udpBufferSize <<
"to net.core.rmem_max"
585 udpBufferSize = s_rmemMax;
588 return udpBufferSize;
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);
603 qCWarning(GstSourceFactoryLog) <<
"Failed because URI is not specified";
607 const guint latencyMs = (config.
latencyMs < 0) ? 0u :
static_cast<guint
>(config.
latencyMs);
609 const QUrl sourceUrl(uri);
612 qCWarning(GstSourceFactoryLog) <<
"Unsupported URI scheme:" << sourceUrl.scheme() <<
"in"
617 const bool isRtsp = (*transport == Transport::Rtsp);
619 const RtpCodec*
const rtpCodec = (*transport == Transport::RtpUdpH264)
621 : ((*transport == Transport::RtpUdpH265) ? &kRtpH265 :
nullptr);
623 const bool demuxMpegTs = (*transport == Transport::MpegTsUdp) || (*transport == Transport::MpegTsTcp);
626 switch (*transport) {
627 case Transport::Rtsp:
630 case Transport::MpegTsTcp:
631 source = buildTcpSource(sourceUrl);
633 case Transport::RtpUdpH264:
634 case Transport::RtpUdpH265:
635 case Transport::MpegTsUdp:
636 source = buildUdpSource(sourceUrl, rtpCodec ? rtpCodec->encodingName :
nullptr);
645 qCWarning(GstSourceFactoryLog) <<
"gst_bin_new('sourcebin') failed";
649 ParserStage parserStage = buildParserStage(rtpCodec, isRtsp);
650 if (!parserStage.parser) {
661 if (parserStage.depay) {
662 depay =
addToBin(bin.get(), std::move(parserStage.depay), rtpCodec->depayloader);
668 GstElement*
const binParser =
addToBin(bin.get(), std::move(parserStage.parser),
"parser");
674 upstream = addTsDemux(bin.get(), upstream, latencyMs);
679 (void) g_signal_connect(binParser,
"pad-added", G_CALLBACK(storeParsedCapsOnPad),
nullptr);
683 if (!linkUdpRtpToDepayAndParser(bin.get(), upstream, depay, binParser, *rtpCodec, config, latencyMs)) {
686 if (!addStaticGhostPad(binParser)) {
690 linkSourceToParserOnPadAdded(upstream, binParser, isRtsp);
693 return bin.release();
702 return (transport == Transport::Rtsp) ?
kRtspUdpTimeout : std::chrono::milliseconds{0};
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...
int udpReceiveBufferSize()
@ 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
std::unique_ptr< GstObject, GstObjectDeleter > GstObjectPtr
std::unique_ptr< GstEvent, GstEventDeleter > GstEventPtr
GCharPtr adoptGChar(gchar *str) noexcept
GstElementPtr makeElement(const char *factory, const char *name=nullptr)
GstEventPtr adoptEvent(GstEvent *event) noexcept
GstElement * addToBin(GstElement *bin, GstElementPtr element, const char *what)
GstCapsPtr adoptCaps(GstCaps *caps) noexcept
std::unique_ptr< GstElement, GstObjectDeleter > GstElementPtr
std::unique_ptr< GstPad, GstObjectDeleter > GstPadPtr
GstObjectPtr adoptObject(GstObject *object) noexcept
GstElementPtr adoptElement(GstElement *element) noexcept
bool countRtpPackets(GstElement *bin, GstPad *pad, int clockRate)
std::unique_ptr< gchar, GFreeDeleter > GCharPtr
GstPadPtr adoptPad(GstPad *pad) noexcept
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 ...
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.