3#include <QtCore/QCoreApplication>
4#include <QtCore/QCryptographicHash>
5#include <QtCore/QDateTime>
8#include <QtCore/QFileInfo>
10#include <QtCore/QRegularExpression>
11#include <QtCore/QSaveFile>
12#include <QtCore/QStandardPaths>
13#include <QtCore/QStringList>
14#include <QtCore/QSysInfo>
15#include <QtCore/QThread>
20#include <android/asset_manager.h>
21#include <android/asset_manager_jni.h>
23#include <QtCore/QJniEnvironment>
24#include <QtCore/QJniObject>
43constexpr const char* kManagedGstPathVars[] = {
44 "GST_PLUGIN_PATH",
"GST_PLUGIN_PATH_1_0",
"GST_PLUGIN_SYSTEM_PATH",
"GST_PLUGIN_SYSTEM_PATH_1_0",
45 "GST_PLUGIN_SCANNER",
"GST_PLUGIN_SCANNER_1_0",
48BundledRuntime s_bundledRuntime;
52QHash<QByteArray, QString> s_managedEnvValues;
54QString _cleanJoin(
const QString& base,
const QString& relative)
56 return QDir::cleanPath(QDir(base).filePath(relative));
59QStringList _cleanJoinAll(
const QStringList& bases,
const QString& relative)
62 joined.reserve(bases.size());
63 for (
const QString& base : bases) {
64 joined.append(_cleanJoin(base, relative));
69void _setGstEnv(
const char* name,
const QString& value)
75 (void) g_setenv(name, value.toUtf8().constData(), TRUE);
76 (void) _wputenv_s(QString::fromLatin1(name).toStdWString().c_str(), value.toStdWString().c_str());
78 qputenv(name, value.toUtf8());
80 s_managedEnvValues.insert(name, value);
81 qCDebug(GStreamerEnvLog) <<
" " << name <<
"=" << value;
84bool _setByUser(
const char* name)
86 if (!qEnvironmentVariableIsSet(name)) {
89 const auto managed = s_managedEnvValues.constFind(name);
90 return (managed == s_managedEnvValues.constEnd()) || (qEnvironmentVariable(name) != managed.value());
93QString _firstExistingPath(
const QStringList& paths)
95 for (
const QString& path : paths) {
96 if (QFileInfo::exists(path)) {
106QString _stableInstallPath(
const QString& installPath)
109 QString appImage = qEnvironmentVariable(
"APPIMAGE");
110 const QString mountDir = qEnvironmentVariable(
"APPDIR");
111 if (!appImage.isEmpty() && !mountDir.isEmpty() &&
112 installPath.startsWith(QDir::cleanPath(mountDir) + QLatin1Char(
'/'))) {
116 static const QRegularExpression translocation(QStringLiteral(
"/AppTranslocation/[^/]+/"));
117 return QString(installPath).replace(translocation, QStringLiteral(
"/AppTranslocation/"));
123void _pruneUnusedRegistries(
const QString& registry)
125 static constexpr int kUnusedRegistryDays = 30;
127 const QDateTime now = QDateTime::currentDateTimeUtc();
128 QFile current(registry);
129 if (current.open(QIODevice::ReadWrite | QIODevice::ExistingOnly)) {
130 (void) current.setFileTime(now, QFileDevice::FileModificationTime);
134 const QFileInfo registryInfo(registry);
135 const QDateTime cutoff = now.addDays(-kUnusedRegistryDays);
136 const QFileInfoList registries =
137 registryInfo.absoluteDir().entryInfoList({QStringLiteral(
"gstreamer-*.bin")}, QDir::Files);
138 for (
const QFileInfo& other : registries) {
139 if ((other.fileName() != registryInfo.fileName()) && (other.lastModified() < cutoff) &&
140 QFile::remove(other.absoluteFilePath())) {
141 qCDebug(GStreamerEnvLog) <<
"Removed unused GStreamer registry" << other.absoluteFilePath();
146#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
147void _setTmpDirVars(
const QString& dir)
149 _setGstEnv(
"TMP", dir);
150 _setGstEnv(
"TEMP", dir);
151 _setGstEnv(
"TMPDIR", dir);
156void _setCaBundleIfUnset(
const QString& caBundle)
158 if (qEnvironmentVariableIsEmpty(
"CA_CERTIFICATES") && QFileInfo::exists(caBundle)) {
159 _setGstEnv(
"CA_CERTIFICATES", caBundle);
166bool _extractApkAsset(
const char* assetPath,
const QString& destPath)
168 QJniObject ctx = QNativeInterface::QAndroidApplication::context();
169 if (!ctx.isValid()) {
170 qCWarning(GStreamerEnvLog) <<
"Cannot resolve Android Context for asset extraction";
174 QJniObject jAssetMgr = ctx.callObjectMethod(
"getAssets",
"()Landroid/content/res/AssetManager;");
175 if (!jAssetMgr.isValid()) {
176 qCWarning(GStreamerEnvLog) <<
"Context.getAssets() returned null";
181 AAssetManager* am = AAssetManager_fromJava(env.jniEnv(), jAssetMgr.object());
183 qCWarning(GStreamerEnvLog) <<
"AAssetManager_fromJava failed";
187 AAsset* asset = AAssetManager_open(am, assetPath, AASSET_MODE_BUFFER);
189 qCDebug(GStreamerEnvLog) <<
"APK asset not present:" << assetPath;
192 const off_t assetLen = AAsset_getLength(asset);
193 const void*
const buf = AAsset_getBuffer(asset);
194 const bool ok = buf && (assetLen > 0) &&
196 destPath, QByteArrayView(
static_cast<const char*
>(buf),
static_cast<qsizetype
>(assetLen)));
199 qCWarning(GStreamerEnvLog) <<
"Failed writing asset" << assetPath <<
"to" << destPath;
207#if !defined(Q_OS_ANDROID) && !defined(Q_OS_IOS) && !defined(QGC_GST_SYSTEM_PLUGINS)
209void _unsetEnv(
const char* name)
211 if (qEnvironmentVariableIsSet(name)) {
213 qCDebug(GStreamerEnvLog) <<
" unset" << name;
217bool _isExecutableFile(
const QString& path)
219 const QFileInfo fileInfo(path);
220 return fileInfo.exists() && fileInfo.isFile() && fileInfo.isExecutable();
223QString _joinExistingPaths(
const QStringList& paths)
225 QStringList existing;
226 existing.reserve(
paths.size());
228 for (
const QString& path : paths) {
229 if (QFileInfo::exists(path) && !existing.contains(path)) {
230 existing.append(path);
234 return existing.join(QDir::listSeparator());
237void _clearManagedGstEnvVars()
239 static constexpr const char* gioPtpVars[] = {
240 "GIO_EXTRA_MODULES",
"GIO_MODULE_DIR",
"GIO_USE_VFS",
"GST_PTP_HELPER_1_0",
"GST_PTP_HELPER",
243 for (
const char* name : gioPtpVars) {
246 for (
const char* name : kManagedGstPathVars) {
251void _setGstEnvIfExecutable(
const char* name,
const QString& path)
253 if (_isExecutableFile(path)) {
254 _setGstEnv(name, path);
258void _applyGstEnvVars(
const QString& pluginDir,
const QString& gioModDir,
const QString& scannerPath,
259 const QString& ptpPath)
261 qCDebug(GStreamerEnvLog) <<
"Applying GStreamer environment:";
263 _clearManagedGstEnvVars();
264 if (!gioModDir.isEmpty()) {
265 _setGstEnv(
"GIO_EXTRA_MODULES", gioModDir);
267 _setGstEnvIfExecutable(
"GST_PTP_HELPER_1_0", ptpPath);
268 _setGstEnvIfExecutable(
"GST_PTP_HELPER", ptpPath);
269 _setGstEnvIfExecutable(
"GST_PLUGIN_SCANNER_1_0", scannerPath);
270 _setGstEnvIfExecutable(
"GST_PLUGIN_SCANNER", scannerPath);
273 _setGstEnv(
"GST_PLUGIN_SYSTEM_PATH_1_0", pluginDir);
274 _setGstEnv(
"GST_PLUGIN_SYSTEM_PATH", pluginDir);
277#if defined(Q_OS_LINUX)
278void _applyGioCompatOverride(
const QString& gioModDir)
280 if (gioModDir.isEmpty()) {
286 if (glib_check_version(2, 76, 0) ==
nullptr) {
287 _unsetEnv(
"GIO_EXTRA_MODULES");
288 _setGstEnv(
"GIO_MODULE_DIR", gioModDir);
289 _setGstEnv(
"GIO_USE_VFS", QStringLiteral(
"local"));
294void _warnIfScannerMissing(
const QString& platformLabel,
const QString& scannerPath)
296 if (scannerPath.isEmpty()) {
297 qCWarning(GStreamerEnvLog) <<
"GStreamer:" << platformLabel
298 <<
"bundled gst-plugin-scanner not found; GStreamer will use in-process scanning";
299 }
else if (!_isExecutableFile(scannerPath)) {
300 qCWarning(GStreamerEnvLog) <<
"GStreamer:" << platformLabel
301 <<
"gst-plugin-scanner is not executable:" << scannerPath;
307bool _applyBundleLayout(
const QString& platformLabel,
const BundleLayout& layout)
309 const QString pluginDirs = _joinExistingPaths(layout.pluginDirs);
310 if (pluginDirs.isEmpty()) {
314 const QString scanner = _firstExistingPath(layout.scannerCandidates);
315 _warnIfScannerMissing(platformLabel, scanner);
316 const QString gioModuleDir = _firstExistingPath(layout.gioModuleDirs);
317 _applyGstEnvVars(pluginDirs, gioModuleDir, scanner, _firstExistingPath(layout.ptpCandidates));
320 s_bundledRuntime = {.pluginDirs = pluginDirs.split(QDir::listSeparator()), .gioModuleDir = gioModuleDir};
329 s_bundledRuntime = {};
331 qCDebug(GStreamerEnvLog) <<
"App directory:" << appDir;
333#if defined(Q_OS_MACOS)
334 const QString frameworkDir = _cleanJoin(appDir,
"../Frameworks/GStreamer.framework");
335#if defined(QGC_GST_MACOS_FRAMEWORK)
340 const bool hasBundledFramework = QFileInfo::exists(frameworkDir);
342 if (!_applyBundleLayout(QStringLiteral(
"macOS"), layout) && hasBundledFramework) {
345 QStringLiteral(
"GStreamer: bundled macOS framework found but plugin directory is missing under %1")
347 qCCritical(GStreamerEnvLog) << result.
error;
350#elif defined(Q_OS_WIN)
351 if (_applyBundleLayout(QStringLiteral(
"Windows"),
355 const QString curPath = qEnvironmentVariable(
"PATH");
356 const QString binDir = QDir::toNativeSeparators(appDir);
358 if (!curPath.split(QDir::listSeparator()).contains(binDir, Qt::CaseInsensitive)) {
359 _setGstEnv(
"PATH", binDir + QDir::listSeparator() + curPath);
363#elif defined(Q_OS_IOS)
367 const QString resources = appDir;
368 const QString docs = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
369 const QString cache = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
370 const QString tmp = QStandardPaths::writableLocation(QStandardPaths::TempLocation);
372 if (!tmp.isEmpty()) {
375 if (!cache.isEmpty()) {
376 _setGstEnv(
"XDG_CACHE_HOME", cache);
377 _setGstEnv(
"XDG_CONFIG_HOME", cache);
378 _setGstEnv(
"GST_REGISTRY", _cleanJoin(cache,
"registry.bin"));
381 _setGstEnv(
"GST_REGISTRY_FORK", QStringLiteral(
"no"));
383 if (!resources.isEmpty()) {
384 _setGstEnv(
"XDG_RUNTIME_DIR", resources);
385 _setGstEnv(
"XDG_DATA_DIRS", resources);
386 _setGstEnv(
"XDG_CONFIG_DIRS", resources);
387 _setGstEnv(
"XDG_DATA_HOME", resources);
389 if (!docs.isEmpty()) {
390 _setGstEnv(
"HOME", docs);
393 if (!resources.isEmpty()) {
394 _setCaBundleIfUnset(_cleanJoin(resources,
"ssl/certs/ca-certificates.crt"));
398#elif defined(Q_OS_ANDROID)
402 const QString filesDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
403 const QString cacheDir = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
405 if (!filesDir.isEmpty()) {
406 _setGstEnv(
"HOME", filesDir);
407 _setGstEnv(
"FONTCONFIG_PATH", _cleanJoin(filesDir,
"fontconfig"));
408 const QString caBundle = _cleanJoin(filesDir,
"ssl/certs/ca-certificates.crt");
409 if (_extractApkAsset(
"ssl/certs/ca-certificates.crt", caBundle)) {
410 _setCaBundleIfUnset(caBundle);
412 _setGstEnv(
"XDG_DATA_DIRS", filesDir);
413 _setGstEnv(
"XDG_CONFIG_DIRS", filesDir);
414 _setGstEnv(
"XDG_CONFIG_HOME", filesDir);
415 _setGstEnv(
"XDG_DATA_HOME", filesDir);
418 if (!cacheDir.isEmpty()) {
419 _setTmpDirVars(cacheDir);
420 _setGstEnv(
"XDG_CACHE_HOME", cacheDir);
421 _setGstEnv(
"XDG_RUNTIME_DIR", cacheDir);
422 _setGstEnv(
"GST_REGISTRY", _cleanJoin(cacheDir,
"registry.bin"));
426 _setGstEnv(
"GST_REGISTRY_FORK", QStringLiteral(
"no"));
429#elif defined(Q_OS_LINUX) && !defined(QGC_GST_SYSTEM_PLUGINS)
431 if (!_setByUser(
"GST_PLUGIN_PATH_1_0") && !_setByUser(
"GST_PLUGIN_PATH") &&
432 !_setByUser(
"GST_PLUGIN_SYSTEM_PATH_1_0") && !_setByUser(
"GST_PLUGIN_SYSTEM_PATH")) {
434 if (_applyBundleLayout(QStringLiteral(
"Linux"), layout)) {
435 _applyGioCompatOverride(s_bundledRuntime.gioModuleDir);
449 const QString appLib = _cleanJoin(appDir,
"../lib");
450 QStringList libDirs{appLib};
451 QStringList helperDirs{_cleanJoin(appDir,
"../libexec/gstreamer-1.0")};
456 const QString frameworkDir = _cleanJoin(appDir,
"../Frameworks/GStreamer.framework");
457 QString rootDir = _firstExistingPath({
458 _cleanJoin(frameworkDir,
"Versions/1.0"),
459 _cleanJoin(frameworkDir,
"Versions/Current"),
462 if (rootDir.isEmpty()) {
463 rootDir = _cleanJoin(frameworkDir,
"Versions/1.0");
465 const QString frameworkLib = _cleanJoin(rootDir,
"lib");
467 : QStringList{appLib, frameworkLib};
468 helperDirs.append(_cleanJoin(rootDir,
"libexec/gstreamer-1.0"));
472 exeSuffix = QStringLiteral(
".exe");
475 helperDirs.prepend(_cleanJoin(appLib,
"gstreamer1.0/gstreamer-1.0"));
479 .pluginDirs = _cleanJoinAll(libDirs,
"gstreamer-1.0"),
480 .gioModuleDirs = _cleanJoinAll(libDirs,
"gio/modules"),
481 .scannerCandidates = _cleanJoinAll(helperDirs, QStringLiteral(
"gst-plugin-scanner") + exeSuffix),
482 .ptpCandidates = _cleanJoinAll(helperDirs, QStringLiteral(
"gst-ptp-helper") + exeSuffix),
490 if (QCoreApplication::instance() && (QThread::currentThread() != QCoreApplication::instance()->thread())) {
491 qCWarning(GStreamerEnvLog) <<
"prepareEnvironment() called off the GUI thread; qputenv is not thread-safe";
493 return _setGstEnvVars(appDir.isEmpty() ? QCoreApplication::applicationDirPath() : appDir);
501 if (cacheDir.isEmpty() || _setByUser(
"GST_REGISTRY_1_0") || _setByUser(
"GST_REGISTRY")) {
504 if (!QDir().mkpath(cacheDir)) {
505 qCWarning(GStreamerEnvLog) <<
"Cannot create the GStreamer registry directory" << cacheDir;
513 gst_version(&major, &minor, µ, &nano);
514 const QByteArray installHash =
515 QCryptographicHash::hash(_stableInstallPath(installPath).toUtf8(), QCryptographicHash::Sha256).toHex().left(8);
516 QString registry = _cleanJoin(cacheDir, QStringLiteral(
"gstreamer-%1.%2.%3-%4-%5.bin")
520 .arg(QSysInfo::buildCpuArchitecture(), QLatin1String(installHash)));
521 _setGstEnv(
"GST_REGISTRY", registry);
522 _pruneUnusedRegistries(registry);
529 if (current.open(QIODevice::ReadOnly) && (current.size() == content.size()) && (current.readAll() == content)) {
534 if (!QDir().mkpath(QFileInfo(path).absolutePath())) {
535 qCWarning(GStreamerEnvLog) <<
"Cannot create the directory of" << path;
538 QSaveFile file(path);
539 if (!file.open(QIODevice::WriteOnly) || (file.write(content.data(), content.size()) != content.size()) ||
541 qCWarning(GStreamerEnvLog) <<
"Cannot write" << path <<
":" << file.errorString();
549 return s_bundledRuntime;
554 qCCritical(GStreamerEnvLog) <<
"GStreamer environment diagnostics:";
555 const auto dumpVar = [](
const char* var) {
556 const QByteArray val = qgetenv(var);
557 qCCritical(GStreamerEnvLog) <<
" " << var <<
"=" << (val.isEmpty() ?
"(unset)" : val.constData());
559 for (
const char* var : kManagedGstPathVars) {
562 dumpVar(
"GST_REGISTRY_FORK");
563 dumpVar(
"GST_REGISTRY_REUSE_PLUGIN_SCANNER");
564 dumpVar(
"GST_REGISTRY");
#define QGC_LOGGING_CATEGORY(name, categoryStr)
BundledRuntime bundledRuntime()
The bundled runtime the last prepareEnvironment() applied; empty before it ran.
VideoBackend::EnvPrepResult prepareEnvironment(const QString &appDir)
bool writeIfChanged(const QString &path, QByteArrayView content)
DesktopInstall
The desktop installs prepareEnvironment() knows how to point GStreamer into.
@ MacOSFlat
An app bundle with a flat SDK copied next to the app, whose paths win over the framework's.
@ Windows
bin/ beside lib/gstreamer-1.0 and libexec/gstreamer-1.0.
@ MacOSFramework
An app bundle with GStreamer.framework, whose paths win over the app's own lib.
@ Linux
An AppImage or other prefix: bin/ beside lib/ and libexec/.
QString usePrivateRegistry(const QString &cacheDir, const QString &installPath)
BundleLayout bundleLayout(DesktopInstall install, const QString &appDir)
std::span< const HwPathDescriptor *const > paths() noexcept
Where a desktop install keeps its GStreamer runtime, as candidate paths in priority order.
The desktop GStreamer runtime bundled with the app that prepareEnvironment() pointed GStreamer at.