QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
GStreamer.cc
Go to the documentation of this file.
1#include "GStreamer.h"
2
3#include <algorithm>
4#include <gst/gst.h>
5#include <mutex>
6#include <utility>
7
8#include <QtCore/QByteArrayList>
9#include <QtCore/QCoreApplication>
10#include <QtCore/QList>
11#include <QtCore/QPointer>
12#include <QtCore/QStringList>
13#include <QtCore/QVarLengthArray>
14#include <QtMultimedia/QVideoSink>
15
18#include "GStreamerHelpers.h"
19#include "GStreamerLogging.h"
21#include "GstScoped.h"
22#include "HwBuffers/HwBuffers.h"
23#include "QGCLoggingCategory.h"
27
28QGC_LOGGING_CATEGORY(GStreamerLog, "Video.GStreamer.GStreamer")
29
30G_BEGIN_DECLS
31#ifdef QGC_GST_STATIC_BUILD
32// Generated from cmake/GStreamer/gst_static_plugins.c.in by qgc_gst_generate_static_init (Mobile.cmake):
33// registers every configured plugin and loads the static GIO modules (gioopenssl + the bundled CA bundle on mobile).
34extern void gst_init_static_plugins(void);
35#endif
36
38G_END_DECLS
39
40namespace GStreamer {
41
42namespace {
43
44void _registerPlugins()
45{
46 // GST_PLUGIN_STATIC_REGISTER / gst_init_static_plugins() are not idempotent: a second pass
47 // re-registers GTypes ("cannot register existing type 'GstBaseQTMux'") and aborts, so run once.
48 static std::once_flag s_pluginsRegistered;
49 std::call_once(s_pluginsRegistered, [] {
50#ifdef QGC_GST_STATIC_BUILD
51 // The generated shim's registrations are registry-guarded: gst_init() may already have run it
52 // (see cmake/GStreamer/gst_static_plugins.c.in).
53 gst_init_static_plugins();
54#endif
55 GST_PLUGIN_STATIC_REGISTER(qgc);
56 });
57}
58
59struct PluginFeature
60{
61 const char* name;
62 bool required;
63 const char* factories; // space-separated; "a|b" is satisfied by either factory
64 const char* hint = nullptr; // the likely cause when the factories are missing, if not a missing plugin
65};
66
67// Checked per element, as Qt's qGstErrorMessageIfElementsNotAvailable does, so a missing optional plugin disables only
68// its feature. Only the display core is required.
69constexpr PluginFeature kPluginFeatures[] = {
70 // The qgc plugin is linked in and registered by completeInit(), so plugin_init succeeded; a missing element means
71 // its GST_ELEMENT_REGISTER side effect was stripped at link time.
72 {"QGC video sink", true, "qgcqvideosink qgcvideosinkbin",
73 "the qgc plugin registered without exposing its elements; link-time symbol stripping (iOS LTO / Android R8) "
74 "likely removed the GST_ELEMENT_REGISTER side effect: add gstqgc.cc to a -force_load / keep rule"},
75 {"Video display", true, "decodebin3 tee queue valve capsfilter videoconvertscale|videoconvert"},
76 {"RTP/UDP video", true, "udpsrc rtpjitterbuffer parsebin rtph264depay h264parse rtph265depay h265parse"},
77 {"RTSP video", false, "rtspsrc"},
78 {"MPEG-TS video", false, "tsdemux"},
79 {"TCP video", false, "tcpclientsrc"},
80 {"MKV recording", false, "matroskamux"},
81 {"MP4/MOV recording", false, "mp4mux qtmux"},
82};
83
84bool _verifyPluginFeatures()
85{
86 GstRegistry* registry = gst_registry_get();
87 if (GStreamerLog().isDebugEnabled()) {
88 qCDebug(GStreamerLog) << "Installed GStreamer plugins:";
89 GStreamer::forEachPlugin(registry, [](GstPlugin* plugin) {
90 qCDebug(GStreamerLog) << " " << gst_plugin_get_name(plugin) << gst_plugin_get_version(plugin);
91 });
92 }
93
94 const QList<MissingPluginFeature> missing = missingPluginFeatures(hasElementFactory);
95 if (missing.isEmpty()) {
96 return true;
97 }
98
99 bool displayAvailable = true;
100 for (const MissingPluginFeature& feature : missing) {
101 const QString message =
102 QStringLiteral("%1 unavailable, GStreamer elements not found: %2%3")
103 .arg(feature.feature, feature.factories.join(QStringLiteral(", ")),
104 feature.hint.isEmpty() ? QString() : QStringLiteral(" (%1)").arg(feature.hint));
105 if (feature.required) {
106 qCCritical(GStreamerLog).noquote() << message;
107 displayAvailable = false;
108 } else {
109 qCWarning(GStreamerLog).noquote() << message;
110 }
111 }
112
113 // Surface blacklisted plugins so a failure from a corrupt/incompatible plugin file
114 // shows up here instead of looking like a missing-plugin problem.
115 GStreamer::forEachPlugin(registry, [](GstPlugin* p) {
116 if (!GST_OBJECT_FLAG_IS_SET(p, GST_PLUGIN_FLAG_BLACKLISTED)) {
117 return;
118 }
119 const gchar* filename = gst_plugin_get_filename(p);
120 qCWarning(GStreamerLog) << "Blacklisted plugin:" << gst_plugin_get_name(p)
121 << "file:" << (filename ? filename : "(null)");
122 });
123
124 if (!displayAvailable) {
125 // Path / scanner env vars belong to the environment layer that set them.
127 }
128
129 return displayAvailable;
130}
131
132} // anonymous namespace
133
134QList<MissingPluginFeature> missingPluginFeatures(const std::function<bool(const char* factoryName)>& hasFactory)
135{
136 QList<MissingPluginFeature> missing;
137 for (const PluginFeature& feature : kPluginFeatures) {
138 QStringList absent;
139 for (const QByteArray& entry : QByteArray(feature.factories).split(' ')) {
140 const QList<QByteArray> alternatives = entry.split('|');
141 if (std::ranges::none_of(alternatives,
142 [&hasFactory](const QByteArray& name) { return hasFactory(name.constData()); })) {
143 absent.append(QString::fromLatin1(entry));
144 }
145 }
146 if (!absent.isEmpty()) {
147 missing.append({.feature = QString::fromLatin1(feature.name),
148 .factories = absent,
149 .required = feature.required,
150 .hint = QString::fromLatin1(feature.hint)});
151 }
152 }
153 return missing;
154}
155
156namespace {
157
158bool _initGstRuntime(const QStringList& args, const VideoBackend::EnvPrepResult& env)
159{
160 if (!env.ok) {
161 qCCritical(GStreamerLog) << "Invalid GStreamer environment configuration:" << env.error;
162 return false;
163 }
164
165 // args is snapshotted on the GUI thread: QCoreApplication::arguments() is not thread-safe
166 // and initialize() runs on a QtConcurrent pool thread.
167 QByteArrayList argStorage;
168 argStorage.reserve(args.size());
169 for (const QString& arg : args) {
170 argStorage.append(arg.toUtf8());
171 }
172
173 QVarLengthArray<char*, 16> argv;
174 for (QByteArray& arg : argStorage) {
175 argv.append(arg.data());
176 }
177
178 int argc = argv.size();
179 char** argvPtr = argv.data();
180 GError* error = nullptr;
181
182 if (!gst_init_check(&argc, &argvPtr, &error)) {
183 qCCritical(GStreamerLog) << "Failed to initialize GStreamer:" << (error ? error->message : "unknown error");
184 g_clear_error(&error);
185 return false;
186 }
187
188 return true;
189}
190
191// A Qt post routine runs in ~QCoreApplication, after QGCApplication::shutdown() has destroyed the receivers.
192void _deinitGStreamer()
193{
194 gst_debug_remove_log_function(GStreamer::qtGstLog);
195 gst_deinit();
196}
197
198} // anonymous namespace
199
200bool completeInit(std::optional<int> debugLevel)
201{
202 if (!gst_is_initialized()) {
203 qCCritical(GStreamerLog) << "completeInit called but gst_init() has not been called";
204 return false;
205 }
206
208
209 guint major, minor, micro, nano;
210 gst_version(&major, &minor, &micro, &nano);
211 qCDebug(GStreamerLog) << "GStreamer initialized:" << major << "." << minor << "." << micro;
212
213 // A newer runtime is ABI-compatible; an older one may lack API the build used.
214 if (std::make_pair(major, minor) < std::make_pair(guint{GST_VERSION_MAJOR}, guint{GST_VERSION_MINOR})) {
215 qCWarning(GStreamerLog) << "GStreamer runtime" << major << "." << minor << "." << micro << "is older than the"
216 << GST_VERSION_MAJOR << "." << GST_VERSION_MINOR << "QGC was built against";
217 }
218
219 _registerPlugins();
220
221 if (!_verifyPluginFeatures()) {
222 return false;
223 }
224
226
228
229 return true;
230}
231
233{
236
237 // Before gst_init_check(), so that what GStreamer logs while it initializes (the plugin scan) reaches QGC's log at
238 // the persisted level. It also removes GStreamer's default stderr handler, unless the user asked for GStreamer's
239 // own output, which gst_init_check() would otherwise keep; its raw ANSI codes corrupt the terminal on macOS.
241
242 if (!_initGstRuntime(params.arguments, params.environment)) {
243 return false;
244 }
245
246 // gst_deinit() can't be undone, so it is opt-in, as Qt's QT_GSTREAMER_DEINIT: it lets the leaks tracer report.
247 if (qEnvironmentVariableIntValue("QGC_GST_DEINIT") > 0) {
248 qAddPostRoutine(_deinitGStreamer);
249 }
250
251 // The threshold in effect: the persisted level, unless a GStreamer option among the arguments (--gst-debug-level)
252 // replaced it during gst_init_check(), which then stays.
253 return completeInit(static_cast<int>(gst_debug_get_default_threshold()));
254}
255
256// Video sink refcount protocol: createVideoSink returns one owned, non-floating ref, which the caller
257// adopts. While decoding, the pipeline bin takes another on gst_bin_add (dropped by gst_bin_remove).
258GstElement* createVideoSink(const QByteArray& conversionElement, bool disablePixelAspectRatio,
259 [[maybe_unused]] bool gpuZeroCopy)
260{
261 const gboolean disablePar = disablePixelAspectRatio ? TRUE : FALSE;
262 const char* const conversion = conversionElement.isEmpty() ? nullptr : conversionElement.constData();
263
264 const GstFactoryPtr factory = adoptFactory(gst_element_factory_find("qgcvideosinkbin"));
265 if (!factory) {
266 // completeInit verified this factory at startup; absence here means the registry changed underfoot.
267 qCCritical(GStreamerLog) << "qgcvideosinkbin factory not found";
268 return nullptr;
269 }
270
271#if defined(QGC_HAS_ANY_GPU_PATH)
272 GstElement* videoSinkBin =
273 gst_element_factory_create_full(factory.get(), "gpu-zerocopy", gpuZeroCopy ? TRUE : FALSE, "conversion-element",
274 conversion, "disable-par", disablePar, NULL);
275#else
276 GstElement* videoSinkBin = gst_element_factory_create_full(factory.get(), "conversion-element", conversion,
277 "disable-par", disablePar, NULL);
278#endif
279 if (!videoSinkBin) {
280 qCCritical(GStreamerLog) << "qgcvideosinkbin element creation failed";
281 return nullptr;
282 }
283 // Sink the floating ref so adding the sink to a bin never consumes the caller's reference.
284 return GST_ELEMENT(gst_object_ref_sink(videoSinkBin));
285}
286
287QGCQVideoSinkController* setupQVideoSinkElement(GstElement* sinkBin, QVideoSink* videoSink, QObject* controllerParent)
288{
289 if (!sinkBin || !videoSink || !controllerParent) {
290 // controllerParent owns the controller's QObject lifetime — else it leaks (caller has no handle).
291 qCWarning(GStreamerLog) << "null sinkBin, videoSink, or controllerParent";
292 return nullptr;
293 }
294
295 // Clear the GL/Vulkan bridges' exhausted-retry latches so a restart after Qt's RHI appears can
296 // prime on the next NEED_CONTEXT.
298
299 // Accessor returns a transfer-full ref; the guard releases it once the controller has taken
300 // its own ref for deferred QObject teardown.
301 const GstObjectPtr element(GST_OBJECT(gst_qgc_video_sink_bin_get_qvideosink(GST_QGC_VIDEO_SINK_BIN(sinkBin))));
302 if (!element) {
303 qCCritical(GStreamerLog) << "bin has no qgcqvideosink child";
304 return nullptr;
305 }
306 GstElement* const elementRaw = GST_ELEMENT(element.get());
307
308 auto* controller = new QGCQVideoSinkController(elementRaw, controllerParent);
309
310 // Route the initial install through the controller so its destroyed-sink QPointer guard
311 // covers setup, not just later swaps.
312 controller->setVideoSink(QPointer<QVideoSink>(videoSink));
313
314 return controller;
315}
316
317void onMainWindowReady(QQuickWindow* window)
318{
319 // Which decoders rank first depends on the device Qt renders with: its API, its adapter and what it opens. The
320 // render thread publishes it; the ranks are the GUI thread's.
322 if (QCoreApplication* const app = QCoreApplication::instance()) {
323 (void) QMetaObject::invokeMethod(
324 app, [] { DecoderRankApplier::instance().reapply(); }, Qt::QueuedConnection);
325 }
326 });
329 qCInfo(GStreamerLog) << "Resolved RHI backend:" << GstQgc::toString(backend)
330 << "→ zero-copy path:" << GstQgc::zeroCopyPathName(backend);
331}
332
333} // namespace GStreamer
G_BEGIN_DECLS GST_PLUGIN_STATIC_DECLARE(qgc)
struct _GstElement GstElement
#define QGC_LOGGING_CATEGORY(name, categoryStr)
void reapply()
apply() for the option applied last, when the platform's RankTraits changed since: Qt's device became...
static DecoderRankApplier & instance()
GstElement * gst_qgc_video_sink_bin_get_qvideosink(GstQgcVideoSinkBin *self)
Returns the internal qgcqvideosink element, transfer-full (caller unrefs); NULL if not yet constructe...
GstElement * createVideoSink(const QByteArray &conversionElement, bool disablePixelAspectRatio, bool gpuZeroCopy)
Definition GStreamer.cc:258
std::unique_ptr< GstObject, GstObjectDeleter > GstObjectPtr
Definition GstScoped.h:59
void onMainWindowReady(QQuickWindow *window)
Definition GStreamer.cc:317
void qtGstLog(GstDebugCategory *category, GstDebugLevel level, const gchar *file, const gchar *function, gint line, GObject *object, GstDebugMessage *message, gpointer data)
std::unique_ptr< GstElementFactory, GstObjectDeleter > GstFactoryPtr
Definition GstScoped.h:63
void forEachPlugin(GstRegistry *registry, const std::function< void(GstPlugin *)> &visitor)
GstFactoryPtr adoptFactory(GstElementFactory *factory) noexcept
Definition GstScoped.h:94
void resetExternalPluginLoaderFailed()
void redirectGLibLogging()
void configureDebugLogging(std::optional< int > level)
QList< MissingPluginFeature > missingPluginFeatures(const std::function< bool(const char *factoryName)> &hasFactory)
Definition GStreamer.cc:134
QGCQVideoSinkController * setupQVideoSinkElement(GstElement *sinkBin, QVideoSink *videoSink, QObject *controllerParent)
Definition GStreamer.cc:287
bool hasElementFactory(const char *name)
Definition GstScoped.h:183
bool completeInit(std::optional< int > debugLevel)
debugLevel: the debug threshold to start with (none when unset), unless GST_DEBUG is set.
Definition GStreamer.cc:200
bool initialize(const VideoBackend::InitParams &params)
Definition GStreamer.cc:232
RenderTarget currentRenderTarget()
const char * toString(RenderBackend backend) noexcept
RenderBackend
Graphics API Qt Quick renders the video with, which decides the GPU memory qgcqvideosink can import.
const char * zeroCopyPathName(RenderBackend backend) noexcept
void setGraphicsDevicePublishedHandler(void(*handler)()) noexcept
Definition HwBuffers.cc:240
void connectMainWindow(QQuickWindow *window)
Definition HwBuffers.cc:173
void onPipelineRestart()
Definition HwBuffers.cc:74
A QGC video feature whose GStreamer elements are not all registered.
Definition GStreamer.h:22
std::optional< int > debugLevel
The persisted debug threshold to start with (persistedDebugLevel()).
QStringList arguments
QCoreApplication::arguments(), snapshotted on the GUI thread.
EnvPrepResult environment
What prepareEnvironment() did.