QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
GStreamerSelfTest.cc
Go to the documentation of this file.
1#include "GStreamerSelfTest.h"
2
3#include <algorithm>
4#include <chrono>
5#include <gst/gst.h>
6#include <memory>
7#include <utility>
8
9// gdbusintrospection.h's `signals` member collides with Qt's `signals` keyword macro.
10#pragma push_macro("signals")
11#undef signals
12#include <gio/gio.h>
13#pragma pop_macro("signals")
14
15#include <QtCore/QDeadlineTimer>
16#include <QtCore/QDir>
17#include <QtCore/QDirIterator>
18#include <QtCore/QElapsedTimer>
19#include <QtCore/QFile>
20#include <QtCore/QFileInfo>
21#if defined(Q_OS_WIN)
22#include <QtCore/QProcess>
23#endif
24#include <QtCore/QScopeGuard>
25#include <QtCore/QSet>
26#include <QtCore/QTemporaryDir>
27
28#include "GStreamer.h"
30#include "GStreamerHelpers.h"
31#include "GStreamerLogging.h"
33#include "GstScoped.h"
34#include "QGCLoggingCategory.h"
35
36QGC_LOGGING_CATEGORY(GStreamerSelfTestLog, "Video.GStreamer.SelfTest")
37
38namespace GStreamer::SelfTest {
39
40namespace {
41
42using namespace std::chrono_literals;
43
44constexpr std::chrono::milliseconds kBudget = 15s;
45constexpr std::chrono::milliseconds kPipelineTimeout = 4s;
46#if defined(Q_OS_WIN)
48constexpr std::chrono::milliseconds kScannerStartTimeout = 5s;
49#endif
50constexpr const char* kProxyLookupUri = "rtsp://127.0.0.1";
51
52#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
53// The plugins and the OpenSSL GIO module are linked into the app (Mobile.cmake).
54constexpr bool kStaticRuntime = true;
55#else
56constexpr bool kStaticRuntime = false;
57#endif
58
59#ifdef Q_OS_WIN
60constexpr Qt::CaseSensitivity kPathCase = Qt::CaseInsensitive;
61#else
62constexpr Qt::CaseSensitivity kPathCase = Qt::CaseSensitive;
63#endif
64
65QString normalizedPath(const QString& path)
66{
67 return QDir::cleanPath(QDir::fromNativeSeparators(path));
68}
69
70QString pathKey(const QString& path)
71{
72 const QString normalized = normalizedPath(path);
73 return (kPathCase == Qt::CaseInsensitive) ? normalized.toCaseFolded() : normalized;
74}
75
76// The files GStreamer's registry scan loads (gstregistry.c): the platform's module suffix, also .dylib on macOS.
77bool isPluginFile(const QString& fileName)
78{
79#if defined(Q_OS_WIN)
80 return fileName.endsWith(QLatin1String(".dll"), Qt::CaseInsensitive);
81#elif defined(Q_OS_MACOS)
82 return fileName.endsWith(QLatin1String(".dylib")) || fileName.endsWith(QLatin1String(".so"));
83#else
84 return fileName.endsWith(QLatin1String(".so"));
85#endif
86}
87
88QStringList pluginFilesIn(const QStringList& dirs)
89{
90 QStringList files;
91 for (const QString& dir : dirs) {
92 QDirIterator it(dir, QDir::Files, QDirIterator::Subdirectories);
93 while (it.hasNext()) {
94 const QString file = it.next();
95 if (isPluginFile(file)) {
96 files.append(file);
97 }
98 }
99 }
100 return files;
101}
102
103bool hasGioModule(const QString& dir, const QString& module)
104{
105 return !dir.isEmpty() && !QDir(dir).entryList({QStringLiteral("*%1.*").arg(module)}, QDir::Files).isEmpty();
106}
107
108struct ProxyLookup
109{
110 bool done = false;
111 QString proxy;
112 QString failure;
113};
114
115void onProxyLookedUp(GObject* resolver, GAsyncResult* result, gpointer data)
116{
117 auto* const lookup = static_cast<ProxyLookup*>(data);
118 GError* error = nullptr;
119 gchar** const proxies = g_proxy_resolver_lookup_finish(G_PROXY_RESOLVER(resolver), result, &error);
120 if (proxies && proxies[0]) {
121 lookup->proxy = QString::fromUtf8(proxies[0]);
122 } else {
123 lookup->failure = error ? QString::fromUtf8(error->message) : QStringLiteral("no proxy returned");
124 }
125 g_strfreev(proxies);
126 g_clear_error(&error);
127 lookup->done = true;
128}
129
130gboolean markTimedOut(gpointer flag)
131{
132 *static_cast<bool*>(flag) = true;
133 return G_SOURCE_REMOVE;
134}
135
137std::pair<QString, QString> lookUpProxy(GProxyResolver* resolver, const char* uri, std::chrono::milliseconds timeout)
138{
139 // A private context bounds the wait; Qt's event loop doesn't run during the self-test anyway.
140 GMainContext* const context = g_main_context_new();
141 g_main_context_push_thread_default(context);
142
143 bool timedOut = false;
144 GSource* const timer = g_timeout_source_new(static_cast<guint>(std::max(timeout, 0ms).count()));
145 g_source_set_callback(timer, markTimedOut, &timedOut, nullptr);
146 (void) g_source_attach(timer, context);
147
148 auto lookup = std::make_unique<ProxyLookup>();
149 g_proxy_resolver_lookup_async(resolver, uri, nullptr, onProxyLookedUp, lookup.get());
150 while (!lookup->done && !timedOut) {
151 (void) g_main_context_iteration(context, TRUE);
152 }
153
154 g_source_destroy(timer);
155 g_source_unref(timer);
156 g_main_context_pop_thread_default(context);
157 g_main_context_unref(context);
158
159 if (!lookup->done) {
160 // Nothing iterates the context again, so the callback never runs: leave the lookup to it.
161 (void) lookup.release();
162 return {QStringLiteral("no answer within %1 ms").arg(timeout.count()), QString()};
163 }
164 return {lookup->failure, lookup->proxy};
165}
166
167class Checker
168{
169public:
170 explicit Checker(const Environment::BundledRuntime& runtime)
171 : _runtime(runtime)
172 {}
173
174 bool run();
175
176private:
177 std::chrono::milliseconds _timeout() const;
178 void _fail(const QString& message);
179 QByteArray _readSample(const Sample& sample);
180 void _checkBundledPlugins();
181 void _checkPluginScanner();
182 void _checkFeatures();
183 void _checkTls();
184 void _checkProxy();
185 void _checkDecoding(const Sample& sample, const QByteArray& data);
186 void _checkRecordings(const QByteArray& h264);
187
188 const Environment::BundledRuntime _runtime;
189 const QDeadlineTimer _budget{kBudget};
190 int _failures = 0;
191 QStringList _notes;
192};
193
194bool Checker::run()
195{
196 QElapsedTimer elapsed;
197 elapsed.start();
198
199 const bool bundled = !_runtime.pluginDirs.isEmpty();
200 if (bundled) {
201 _checkBundledPlugins();
202 _checkPluginScanner();
203 }
204 _checkFeatures();
205 if (bundled || kStaticRuntime) {
206 _checkTls();
207 }
208 // libproxy loads its backend with dlopen(), so only a lookup shows it was bundled with what it needs.
209 if (hasGioModule(_runtime.gioModuleDir, QStringLiteral("giolibproxy"))) {
210 _checkProxy();
211 }
212
213 const QByteArray h264 = _readSample(kH264Sample);
214 if (!h264.isEmpty()) {
215 _checkDecoding(kH264Sample, h264);
216 _checkRecordings(h264);
217 }
218 // Decoder availability differs per platform; H.264 is the codec QGC must always play.
220 const QByteArray h265 = _readSample(kH265Sample);
221 if (!h265.isEmpty()) {
222 _checkDecoding(kH265Sample, h265);
223 }
224 } else {
225 _notes.append(QStringLiteral("no H.265 decoder to test"));
226 }
227
228 if (_failures == 0) {
229 qCInfo(GStreamerSelfTestLog).noquote() << QStringLiteral("GStreamer self-test passed in %1 ms: %2")
230 .arg(elapsed.elapsed())
231 .arg(_notes.join(QStringLiteral(", ")));
232 return true;
233 }
234 qCCritical(GStreamerSelfTestLog).noquote()
235 << QStringLiteral("GStreamer self-test failed %1 check(s) in %2 ms").arg(_failures).arg(elapsed.elapsed());
236 return false;
237}
238
239std::chrono::milliseconds Checker::_timeout() const
240{
241 return std::min(kPipelineTimeout,
242 std::chrono::duration_cast<std::chrono::milliseconds>(_budget.remainingTimeAsDuration()));
243}
244
245void Checker::_fail(const QString& message)
246{
247 qCCritical(GStreamerSelfTestLog).noquote() << message;
248 ++_failures;
249}
250
251QByteArray Checker::_readSample(const Sample& sample)
252{
253 QFile file(QString::fromLatin1(sample.resource));
254 if (!file.open(QIODevice::ReadOnly) || (file.size() == 0)) {
255 _fail(QStringLiteral("The %1 sample %2 is missing from the app's resources")
256 .arg(QLatin1String(sample.codec), QLatin1String(sample.resource)));
257 return {};
258 }
259 return file.readAll();
260}
261
262void Checker::_checkBundledPlugins()
263{
264 QList<RegisteredPlugin> registered;
265 forEachPlugin(gst_registry_get(), [&registered](GstPlugin* plugin) {
266 const gchar* const filename = gst_plugin_get_filename(plugin);
267 registered.append({.name = QString::fromUtf8(gst_plugin_get_name(plugin)),
268 .filename = filename ? QString::fromUtf8(filename) : QString(),
269 .blacklisted = GST_OBJECT_FLAG_IS_SET(plugin, GST_PLUGIN_FLAG_BLACKLISTED) != 0});
270 });
271
272 const QStringList files = pluginFilesIn(_runtime.pluginDirs);
273 const QStringList issues = bundledPluginIssues(registered, _runtime.pluginDirs, files);
274 for (const QString& issue : issues) {
275 _fail(issue);
276 }
277 if (!issues.isEmpty()) {
279 }
280 _notes.append(QStringLiteral("%1 bundled plugins").arg(files.size()));
281}
282
283void Checker::_checkPluginScanner()
284{
285 const QString scanner = qEnvironmentVariable("GST_PLUGIN_SCANNER_1_0");
286 QString failure = externalPluginLoaderFailed() ? QStringLiteral("failed to run") : QString();
287#if defined(Q_OS_WIN)
288 // GStreamer for Windows tries the scanner before it scans. One that doesn't start is only named in GStreamer's
289 // debug log, and no scan may have been due in this launch, so the scanner is tried here as well.
290 if (failure.isEmpty()) {
291 failure = scanner.isEmpty() ? QStringLiteral("is not in the bundle") : pluginScannerStartFailure(scanner);
292 }
293#endif
294 if (failure.isEmpty()) {
295 return;
296 }
297 _fail(QStringLiteral("GStreamer's plugin scanner %1 %2, so GStreamer loads the plugins into QGC's process: check "
298 "that the bundled gst-plugin-scanner is executable and signed and finds the GStreamer "
299 "libraries")
300 .arg(scanner.isEmpty() ? QStringLiteral("(GST_PLUGIN_SCANNER unset)") : scanner, failure));
301}
302
303void Checker::_checkFeatures()
304{
305 // completeInit() only needs the display core, but every package ships every feature's plugins (the common
306 // gstreamer.plugins of build-config.json, GSTREAMER_BUNDLE_REQUIRED_PLUGINS), so all are required on every
307 // platform.
308 const QList<MissingPluginFeature> missing = missingPluginFeatures(hasElementFactory);
309 for (const MissingPluginFeature& feature : missing) {
310 _fail(QStringLiteral("%1 unavailable: GStreamer elements %2 not found; %3")
311 .arg(feature.feature, feature.factories.join(QStringLiteral(", ")),
312 feature.hint.isEmpty() ? QStringLiteral("their plugin is missing or failed to load")
313 : feature.hint));
314 }
315}
316
317void Checker::_checkTls()
318{
319 GTlsBackend* const backend = g_tls_backend_get_default();
320 if (!backend || !g_tls_backend_supports_tls(backend)) {
321 const QString where =
322 _runtime.gioModuleDir.isEmpty() ? QString() : QStringLiteral(" from ") + _runtime.gioModuleDir;
323 _fail(QStringLiteral("GIO has no TLS support: no TLS GIO module (gioopenssl, giognutls) loaded%1, so RTSP over "
324 "TLS and HTTPS sources fail")
325 .arg(where));
326 return;
327 }
328
329 GTlsDatabase* const database = g_tls_backend_get_default_database(backend);
330 if (!database) {
331 _fail(QStringLiteral("GIO's TLS backend %1 has no certificate database, so no server certificate verifies")
332 .arg(QLatin1String(G_OBJECT_TYPE_NAME(backend))));
333 return;
334 }
335 g_object_unref(database);
336 _notes.append(QStringLiteral("TLS by %1").arg(QLatin1String(G_OBJECT_TYPE_NAME(backend))));
337}
338
339void Checker::_checkProxy()
340{
341 // Loads the GIO modules, so the extension point lists the libproxy resolver if its module loaded.
342 (void) g_proxy_resolver_get_default();
343 GIOExtensionPoint* const point = g_io_extension_point_lookup(G_PROXY_RESOLVER_EXTENSION_POINT_NAME);
344 GIOExtension* const extension = point ? g_io_extension_point_get_extension_by_name(point, "libproxy") : nullptr;
345 if (!extension) {
346 _fail(
347 QStringLiteral("The libproxy GIO module in %1 did not load: libproxy or a library it links is missing, so "
348 "proxy settings are ignored")
349 .arg(_runtime.gioModuleDir));
350 return;
351 }
352
353 auto* const resolver = static_cast<GProxyResolver*>(g_object_new(g_io_extension_get_type(extension), nullptr));
354 const auto unref = qScopeGuard([resolver] { g_object_unref(resolver); });
355 if (!g_proxy_resolver_is_supported(resolver)) {
356 _fail(QStringLiteral("The libproxy GIO module in %1 loaded, but libproxy failed to start")
357 .arg(_runtime.gioModuleDir));
358 return;
359 }
360
361 const auto [failure, proxy] = lookUpProxy(resolver, kProxyLookupUri, std::min(_timeout(), 3000ms));
362 if (!failure.isEmpty()) {
363 _fail(QStringLiteral("libproxy failed to look up the proxy for %1: %2; its backend (pxbackend), which it loads "
364 "by name, may be missing from the bundle")
365 .arg(QLatin1String(kProxyLookupUri), failure));
366 return;
367 }
368 _notes.append(QStringLiteral("libproxy: %1").arg(proxy));
369}
370
371void Checker::_checkDecoding(const Sample& sample, const QByteArray& data)
372{
373 DecodeResult result = decodeSample(sample, data, _timeout());
374 if (!result.failure.isEmpty() && result.hardware) {
375 // decodebin3 doesn't fall back when the decoder it plugged fails, as a hardware decoder may in a VM: retry once
376 // the way the Software decoder setting does.
378 const DecodeResult software = decodeSample(sample, data, _timeout());
379 if (software.failure.isEmpty()) {
380 qCWarning(GStreamerSelfTestLog).noquote()
381 << QStringLiteral("%1 hardware decoding with %2 failed (%3); software decoding with %4 works")
382 .arg(QLatin1String(sample.codec), result.decoders.join(QLatin1Char('+')), result.failure,
383 software.decoders.join(QLatin1Char('+')));
384 result = software;
385 } else {
386 result.failure += QStringLiteral("; with software decoders forced: %1").arg(software.failure);
387 result.decoders += software.decoders;
388 }
389 }
390
391 if (result.failure.isEmpty()) {
392 // decodebin3 replaces a decoder that fails to start, so the last one decoded.
393 const QString decoder = result.decoders.isEmpty() ? QStringLiteral("?") : result.decoders.takeLast();
394 QString note = QStringLiteral("%1 decoded by %2").arg(QLatin1String(sample.codec), decoder);
395 if (!result.decoders.isEmpty()) {
396 note += QStringLiteral(" (%1 failed to start)").arg(result.decoders.join(QLatin1Char('+')));
397 }
398 _notes.append(note);
399 return;
400 }
401 _fail(QStringLiteral("%1 decoding failed with decoders [%2]: %3")
402 .arg(QLatin1String(sample.codec), result.decoders.join(QStringLiteral(", ")), result.failure));
403}
404
405void Checker::_checkRecordings(const QByteArray& h264)
406{
407 const QTemporaryDir dir;
408 if (!dir.isValid()) {
409 _fail(QStringLiteral("Cannot create a directory to record into: %1").arg(dir.errorString()));
410 return;
411 }
412
413 QStringList recorded;
414 for (const RecordingFormat& format : kRecordingFormats) {
415 const QString file = dir.filePath(QStringLiteral("selftest.%1").arg(QLatin1String(format.extension)));
416 QString failure = recordSample(file, format.format, h264, _timeout());
417 if (failure.isEmpty() && (QFileInfo(file).size() <= 0)) {
418 failure = QStringLiteral("the file is empty");
419 }
420 if (failure.isEmpty()) {
421 failure = readBack(file, format.demuxer, _timeout());
422 }
423 if (failure.isEmpty()) {
424 recorded.append(QLatin1String(format.name));
425 } else {
426 _fail(QStringLiteral("%1 recording to %2 failed: %3").arg(QLatin1String(format.name), file, failure));
427 }
428 }
429 if (!recorded.isEmpty()) {
430 _notes.append(QStringLiteral("recorded %1").arg(recorded.join(QLatin1Char('/'))));
431 }
432}
433
434} // namespace
435
436QStringList bundledPluginIssues(const QList<RegisteredPlugin>& registered, const QStringList& pluginDirs,
437 const QStringList& pluginFiles)
438{
439 QStringList dirs;
440 for (const QString& dir : pluginDirs) {
441 dirs.append(normalizedPath(dir) + QLatin1Char('/'));
442 }
443 const auto inBundle = [&dirs](const QString& file) {
444 return std::ranges::any_of(dirs, [&file](const QString& dir) { return file.startsWith(dir, kPathCase); });
445 };
446
447 QSet<QString> shipped;
448 for (const QString& file : pluginFiles) {
449 shipped.insert(pathKey(file));
450 }
451
452 QStringList issues;
453 QSet<QString> registeredFiles;
454 for (const RegisteredPlugin& plugin : registered) {
455 if (plugin.filename.isEmpty()) {
456 continue;
457 }
458 const QString file = normalizedPath(plugin.filename);
459 registeredFiles.insert(pathKey(file));
460 if (!inBundle(file)) {
461 issues.append(QStringLiteral("Plugin %1 was loaded from %2, outside the bundled plugin directory %3: a "
462 "GStreamer installed outside the app leaks into it")
463 .arg(plugin.name, file, pluginDirs.join(QStringLiteral(", "))));
464 } else if (!shipped.contains(pathKey(file))) {
465 issues.append(QStringLiteral("Plugin %1 is registered from %2, which the bundle does not ship: the plugin "
466 "registry is stale")
467 .arg(plugin.name, file));
468 } else if (plugin.blacklisted) {
469 issues.append(
470 QStringLiteral("Plugin %1 (%2) is blacklisted: it failed to load, typically because a library "
471 "it links is missing from the bundle")
472 .arg(plugin.name, file));
473 }
474 }
475
476 for (const QString& file : pluginFiles) {
477 if (!registeredFiles.contains(pathKey(file))) {
478 issues.append(QStringLiteral("Plugin file %1 is not in GStreamer's registry: GStreamer failed to load it")
479 .arg(normalizedPath(file)));
480 }
481 }
482 return issues;
483}
484
485#if defined(Q_OS_WIN)
486QString pluginScannerStartFailure(const QString& scanner)
487{
488 const int timeoutMs = static_cast<int>(kScannerStartTimeout.count());
489 QProcess process;
490 process.setProgram(scanner);
491 process.start();
492 if (!process.waitForStarted(timeoutMs)) {
493 return QStringLiteral("could not be started (%1)").arg(process.errorString());
494 }
495 if (!process.waitForFinished(timeoutMs)) {
496 process.kill();
497 (void) process.waitForFinished(timeoutMs);
498 return QStringLiteral("did not exit within %1 ms").arg(timeoutMs);
499 }
500 if ((process.exitStatus() != QProcess::NormalExit) || (process.exitCode() != 1)) {
501 return QStringLiteral("exited with code 0x%1 where a working scanner exits with 1")
502 .arg(static_cast<quint32>(process.exitCode()), 0, 16);
503 }
504 return {};
505}
506#endif
507
509{
510 return Checker(runtime).run();
511}
512
513} // namespace GStreamer::SelfTest
#define QGC_LOGGING_CATEGORY(name, categoryStr)
The self-test's media pipelines: decoding the embedded samples and recording and reading back a file.
bool hasDecoderFor(const Sample &sample)
Whether decodebin3 has a decoder for sample's codec to plug: one ranked at least MARGINAL.
QString recordSample(const QString &file, VideoReceiver::FileFormat format, const QByteArray &h264, std::chrono::milliseconds timeout)
appsrc ! RecordingBranch's file sink (h264parse ! muxer ! filesink), as a recording is muxed.
QStringList bundledPluginIssues(const QList< RegisteredPlugin > &registered, const QStringList &pluginDirs, const QStringList &pluginFiles)
constexpr RecordingFormat kRecordingFormats[]
DecodeResult decodeSample(const Sample &sample, const QByteArray &data, std::chrono::milliseconds timeout)
appsrc ! <parser> ! decodebin3 ! appsink, the sink taking raw video in system memory,...
QString readBack(const QString &file, const char *demuxer, std::chrono::milliseconds timeout)
filesrc ! <demuxer> ! fakesink: the recorded file opens and holds video.
bool run(const Environment::BundledRuntime &runtime)
void forEachPlugin(GstRegistry *registry, const std::function< void(GstPlugin *)> &visitor)
bool externalPluginLoaderFailed()
QList< MissingPluginFeature > missingPluginFeatures(const std::function< bool(const char *factoryName)> &hasFactory)
Definition GStreamer.cc:134
bool hasElementFactory(const char *name)
Definition GstScoped.h:183
The desktop GStreamer runtime bundled with the app that prepareEnvironment() pointed GStreamer at.
QStringList pluginDirs
Empty when GStreamer uses the system's plugins, or Android's and iOS's static ones.
A QGC video feature whose GStreamer elements are not all registered.
Definition GStreamer.h:22
A plugin as GStreamer's registry has it.
An encoded sample in the app's resources (Media/generate.sh makes them).