QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
GStreamerDecoderRanks.cc
Go to the documentation of this file.
2
3#include <algorithm>
4
5#include <QtCore/QByteArray>
6#include <QtCore/QHash>
7#include <QtCore/QList>
8#include <QtCore/QString>
9
10#include "GstScoped.h"
11#include "HwBuffers/HwBuffers.h"
12#include "QGCLoggingCategory.h"
13#ifdef Q_OS_WIN
15#endif
16
17QGC_LOGGING_CATEGORY(GStreamerDecoderRanksLog, "Video.GStreamer.DecoderRanks")
18
19namespace GStreamer {
20
21void forEachVideoDecoderFactory(GstRank minRank, const std::function<void(GstElementFactory*)>& visitor)
22{
23 GList* factories = gst_element_factory_list_get_elements(
24 static_cast<GstElementFactoryListType>(GST_ELEMENT_FACTORY_TYPE_DECODER | GST_ELEMENT_FACTORY_TYPE_MEDIA_VIDEO),
25 minRank);
26 for (GList* node = factories; node != nullptr; node = node->next) {
27 visitor(GST_ELEMENT_FACTORY(node->data));
28 }
29 gst_plugin_feature_list_free(factories);
30}
31
32namespace {
33
34struct DecoderFamilyPrefix
35{
36 const char* prefix;
37 VideoDecoderOption family; // VideoDecoderOption::Default: not a user-selectable family
38 bool isHardware;
39};
40
41// Single name-based decoder classification for the hardware/software split, the forceVideoDecoder
42// rank overrides and availableDecoderFamilies(). Prefix (not substring) matching, so e.g. avdec_wnv1
43// isn't taken for an NVIDIA decoder. The first match wins: specific prefixes precede general ones.
44constexpr DecoderFamilyPrefix kDecoderFamilyPrefixes[] = {
45 // Android MediaCodec: Google/Codec2 software wrappers; every other amcviddec is a hardware codec.
46 {"amcviddec-omxgoogle", VideoDecoderOption::Default, false},
47 {"amcviddec-c2android", VideoDecoderOption::Default, false},
48 {"amcviddec-", VideoDecoderOption::Default, true},
49 // Legacy gstreamer-vaapi is demoted on Linux and never bumped by VideoDecoderOption::VAAPI (modern va* only).
50 {"vaapi", VideoDecoderOption::Default, true},
51 {"va", VideoDecoderOption::VAAPI, true},
52 {"nv", VideoDecoderOption::NVIDIA, true},
53 {"d3d11", VideoDecoderOption::DirectX3D, true},
54 {"d3d12", VideoDecoderOption::DirectX3D, true},
55 {"dxva", VideoDecoderOption::DirectX3D, true},
56 // vtdec and vtdec_hw, and from GStreamer 1.30 one decoder per codec (vth264dec, vth264dec_hw, ...).
58 {"qsv", VideoDecoderOption::Intel, true},
59 {"msdk", VideoDecoderOption::Intel, true},
60 {"vulkan", VideoDecoderOption::Vulkan, true},
61};
62
63const DecoderFamilyPrefix* findDecoderFamilyPrefix(const char* factoryName)
64{
65 const GCharPtr lowerName = adoptGChar(g_ascii_strdown(factoryName, -1));
66 for (const DecoderFamilyPrefix& entry : kDecoderFamilyPrefixes) {
67 if (g_str_has_prefix(lowerName.get(), entry.prefix)) {
68 return &entry;
69 }
70 }
71 return nullptr;
72}
73
74} // namespace
75
77{
78 if (!factoryName) {
80 }
81
82 const DecoderFamilyPrefix* entry = findDecoderFamilyPrefix(factoryName);
83 return entry ? entry->family : VideoDecoderOption::Default;
84}
85
86bool isHardwareDecoderFactory(GstElementFactory* factory)
87{
88 if (!factory) {
89 return false;
90 }
91
92 const gchar* factoryName = gst_plugin_feature_get_name(GST_PLUGIN_FEATURE(factory));
93 if (!factoryName) {
94 return false;
95 }
96
97 if (const DecoderFamilyPrefix* entry = findDecoderFamilyPrefix(factoryName)) {
98 return entry->isHardware;
99 }
100
101 const auto containsHardware = [](const gchar* value) {
102 if (!value) {
103 return false;
104 }
105 const GCharPtr lower = adoptGChar(g_ascii_strdown(value, -1));
106 return g_strrstr(lower.get(), "hardware") != nullptr;
107 };
108
109 return containsHardware(gst_element_factory_get_metadata(factory, GST_ELEMENT_METADATA_KLASS)) ||
110 containsHardware(gst_element_factory_get_metadata(factory, GST_ELEMENT_METADATA_DESCRIPTION));
111}
112
113QString describeDecoderFactory(GstElementFactory* factory)
114{
115 GstPluginFeature* const feature = GST_PLUGIN_FEATURE(factory);
116 const GstObjectPtr plugin = adoptObject(GST_OBJECT(gst_plugin_feature_get_plugin(feature)));
117 return QStringLiteral("[%1] %2/%3 rank=%4 (%5)")
118 .arg(isHardwareDecoderFactory(factory) ? QStringLiteral("HW") : QStringLiteral("SW"),
119 plugin ? QString::fromUtf8(gst_plugin_get_name(GST_PLUGIN(plugin.get()))) : QStringLiteral("?"),
120 QString::fromUtf8(gst_plugin_feature_get_name(feature)))
121 .arg(gst_plugin_feature_get_rank(feature))
122 .arg(QString::fromUtf8(gst_element_factory_get_klass(factory)));
123}
124
125namespace {
126
127// gst_init() applies GST_PLUGIN_FEATURE_RANK ("name:rank,..."), and nothing re-applies it after QGC's overrides.
128bool rankedByUser(const gchar* featureName)
129{
130 const QList<QByteArray> userRanks = qgetenv("GST_PLUGIN_FEATURE_RANK").split(',');
131 return std::ranges::any_of(userRanks, [featureName](const QByteArray& entry) {
132 return entry.left(entry.indexOf(':')).trimmed() == featureName;
133 });
134}
135
136#ifdef Q_OS_WIN
140qint64 decoderAdapterLuid(GstElementFactory* factory)
141{
142 static QHash<QByteArray, qint64> s_luids;
143 const QByteArray name(gst_plugin_feature_get_name(GST_PLUGIN_FEATURE(factory)));
144 if (const auto known = s_luids.constFind(name); known != s_luids.constEnd()) {
145 return known.value();
146 }
147 gint64 luid = 0;
148 if (const GstElementPtr decoder = makeElement(name.constData());
149 decoder && g_object_class_find_property(G_OBJECT_GET_CLASS(decoder.get()), "adapter-luid")) {
150 g_object_get(decoder.get(), "adapter-luid", &luid, nullptr);
151 }
152 s_luids.insert(name, luid);
153 return luid;
154}
155#endif
156
158QList<DecoderInfo> installedDecoders()
159{
160 QList<DecoderInfo> decoders;
161 forEachVideoDecoderFactory(GST_RANK_NONE, [&decoders](GstElementFactory* factory) {
162 GstPluginFeature* const feature = GST_PLUGIN_FEATURE(factory);
163 const gchar* const name = gst_plugin_feature_get_name(feature);
164 DecoderInfo decoder{.name = QByteArray(name),
165 .rank = gst_plugin_feature_get_rank(feature),
166 .hardware = isHardwareDecoderFactory(factory),
167 .family = decoderFamilyForFactory(name)};
168#ifdef Q_OS_WIN
169 if (decoder.family == VideoDecoderOption::DirectX3D) {
170 decoder.adapterLuid = decoderAdapterLuid(factory);
171 }
172#endif
173 decoders.append(decoder);
174 });
175 return decoders;
176}
177
179RankTraits currentRankTraits()
180{
181 RankTraits traits;
182#if defined(Q_OS_LINUX)
183 traits.preferZeroCopyDecoders = true;
184#elif defined(Q_OS_WIN)
185 // Ranks usually apply before the scene graph resolves its backend, while the render target is still Unknown: fall
186 // back to QSG_RHI_BACKEND (Qt's D3D11 default) then.
187 bool d3d12 = false;
188 switch (GstQgc::currentRenderTarget().backend) {
190 d3d12 = true;
191 break;
193 d3d12 = qEnvironmentVariable("QSG_RHI_BACKEND").compare(QLatin1String("d3d12"), Qt::CaseInsensitive) == 0;
194 break;
196 // No D3D API is sampled zero-copy under these: the D3D11 decoders stay the ones preferred.
201 break;
202 }
203 traits.rhiD3DApi = d3d12 ? D3DApi::D3D12 : D3DApi::D3D11;
204 // Both known once the scene graph has published Qt's device, which has the ranks applied again (reapply()).
205 traits.d3d11OpensD3D12 = !d3d12 && HwBuffers::d3d11OpensD3D12();
206 traits.rhiAdapterLuid = HwBuffers::graphicsAdapterLuid();
207#endif
208 traits.softwareRendering = HwBuffers::softwareRenderingRequested();
209 return traits;
210}
211
212} // namespace
213
215{
216 static DecoderRankApplier applier;
217 return applier;
218}
219
221{
222 GstRegistry* const registry = _registry();
223 if (!registry) {
224 return;
225 }
226 const QMutexLocker locker(&_mutex);
227 _restore(registry);
228
229 const RankTraits traits = currentRankTraits();
230 const RankPlan plan = planRanks(option, installedDecoders(), traits);
231 qCDebug(GStreamerDecoderRanksLog) << "Applying decoder option" << static_cast<int>(option) << "with"
232 << plan.changes.size() << "rank changes";
233 for (const QString& warning : plan.warnings) {
234 qCWarning(GStreamerDecoderRanksLog).noquote() << warning;
235 }
236 for (const RankChange& change : plan.changes) {
237 (void) _setRank(registry, change.feature.constData(), change.rank);
238 }
239 _applied = option;
240 _appliedTraits = traits;
241}
242
244{
245 if (_applied && (currentRankTraits() != _appliedTraits)) {
246 apply(*_applied);
247 }
248}
249
251{
252 if (GstRegistry* const registry = _registry()) {
253 const QMutexLocker locker(&_mutex);
254 _restore(registry);
255 }
256}
257
258bool DecoderRankApplier::setRank(GstRegistry* registry, const char* featureName, uint16_t rank)
259{
260 const QMutexLocker locker(&_mutex);
261 return _setRank(registry, featureName, rank);
262}
263
264bool DecoderRankApplier::demoteFailedDecoder(const char* featureName, const GstCaps* caps)
265{
266 GstRegistry* const registry = _registry();
267 if (!registry || !featureName || !caps || rankedByUser(featureName)) {
268 return false;
269 }
270 // decodebin3's candidates for the stream: the autoplugged decoders whose sink template covers its caps.
271 GList* const decoders = gst_element_factory_list_get_elements(GST_ELEMENT_FACTORY_TYPE_DECODER, GST_RANK_MARGINAL);
272 GList* const candidates = gst_element_factory_list_filter(decoders, caps, GST_PAD_SINK, TRUE);
273 gst_plugin_feature_list_free(decoders);
274 bool otherDecoder = false;
275 for (GList* node = candidates; node != nullptr; node = node->next) {
276 otherDecoder =
277 otherDecoder || (g_strcmp0(gst_plugin_feature_get_name(GST_PLUGIN_FEATURE(node->data)), featureName) != 0);
278 }
279 gst_plugin_feature_list_free(candidates);
280 if (!otherDecoder) {
281 return false;
282 }
283 const QMutexLocker locker(&_mutex);
284 return _setRank(registry, featureName, GST_RANK_NONE);
285}
286
287bool DecoderRankApplier::_setRank(GstRegistry* registry, const char* featureName, uint16_t rank)
288{
289 if (!registry || !featureName) {
290 return false;
291 }
292 const GstFeaturePtr feature = adoptFeature(gst_registry_lookup_feature(registry, featureName));
293 if (!feature) {
294 return false;
295 }
296
297 if (rankedByUser(featureName)) {
298 qCDebug(GStreamerDecoderRanksLog) << " Keeping the GST_PLUGIN_FEATURE_RANK rank of" << featureName;
299 return true;
300 }
301 const QByteArray key(featureName);
302 if (!_originalRanks.contains(key)) {
303 _originalRanks.insert(key, gst_plugin_feature_get_rank(feature.get()));
304 }
305 qCDebug(GStreamerDecoderRanksLog) << " Changing feature (" << featureName << ") to use rank:" << rank;
306 gst_plugin_feature_set_rank(feature.get(), rank);
307 return true;
308}
309
310GstRegistry* DecoderRankApplier::_registry()
311{
312 if (!gst_is_initialized()) {
313 return nullptr;
314 }
315 GstRegistry* const registry = gst_registry_get();
316 if (!registry) {
317 qCCritical(GStreamerDecoderRanksLog) << "Failed to get gstreamer registry.";
318 }
319 return registry;
320}
321
322void DecoderRankApplier::_restore(GstRegistry* registry)
323{
324 for (auto it = _originalRanks.cbegin(); it != _originalRanks.cend(); ++it) {
325 const GstFeaturePtr feature = adoptFeature(gst_registry_lookup_feature(registry, it.key().constData()));
326 if (feature) {
327 gst_plugin_feature_set_rank(feature.get(), it.value());
328 }
329 }
330 _applied.reset();
331}
332
334 : _previous(DecoderRankApplier::instance().applied())
335{
337}
338
340{
341 if (_previous) {
343 } else {
345 }
346}
347
348bool changeFeatureRank(GstRegistry* registry, const char* featureName, uint16_t rank)
349{
350 return DecoderRankApplier::instance().setRank(registry, featureName, rank);
351}
352
357
358bool demoteFailedDecoder(const char* factoryName, const GstCaps* caps)
359{
360 return DecoderRankApplier::instance().demoteFailedDecoder(factoryName, caps);
361}
362
363QList<VideoDecoderOption> availableDecoderFamilies()
364{
365 QList<VideoDecoderOption> families;
366 forEachVideoDecoderFactory(GST_RANK_NONE, [&families](GstElementFactory* factory) {
367 const VideoDecoderOption family =
368 decoderFamilyForFactory(gst_plugin_feature_get_name(GST_PLUGIN_FEATURE(factory)));
369#ifndef QGC_HAS_GST_VULKAN_GPU_PATH
370 // Only a build with the opt-in Vulkan GPU path has a use for them: no sink takes their VulkanImage memory.
371 if (family == VideoDecoderOption::Vulkan) {
372 return;
373 }
374#endif
375 if ((family != VideoDecoderOption::Default) && !families.contains(family)) {
376 families.append(family);
377 }
378 });
379 return families;
380}
381
383{
384 if (!GStreamerDecoderRanksLog().isDebugEnabled()) {
385 return;
386 }
387
388 struct Decoder
389 {
390 guint rank;
391 QByteArray name;
392 QString description;
393 };
394
395 QList<Decoder> decoders;
396 forEachVideoDecoderFactory(GST_RANK_NONE, [&decoders](GstElementFactory* factory) {
397 GstPluginFeature* const feature = GST_PLUGIN_FEATURE(factory);
398 decoders.append({gst_plugin_feature_get_rank(feature), QByteArray(gst_plugin_feature_get_name(feature)),
399 describeDecoderFactory(factory)});
400 });
401
402 if (decoders.isEmpty()) {
403 qCDebug(GStreamerDecoderRanksLog) << "No video decoder factories found";
404 return;
405 }
406
407 std::ranges::sort(decoders, [](const Decoder& lhs, const Decoder& rhs) {
408 return (lhs.rank != rhs.rank) ? (lhs.rank > rhs.rank) : (lhs.name < rhs.name);
409 });
410
411 qCDebug(GStreamerDecoderRanksLog) << "Video decoder ranks:";
412 for (const Decoder& decoder : std::as_const(decoders)) {
413 qCDebug(GStreamerDecoderRanksLog).noquote() << " " + decoder.description;
414 }
415}
416
417} // namespace GStreamer
#define QGC_LOGGING_CATEGORY(name, categoryStr)
VideoDecoderOption
The decoders VideoSettings' forceVideoDecoder can force. The values are persisted.
void apply(VideoDecoderOption option)
Restores the original ranks, then applies option's plan for the installed decoders on this platform.
bool setRank(GstRegistry *registry, const char *featureName, uint16_t rank)
Sets featureName's rank in registry. False when the registry or name is null or the feature is absent...
DecoderRankApplier(const DecoderRankApplier &)=delete
bool demoteFailedDecoder(const char *featureName, const GstCaps *caps)
void restore()
Restores the original ranks.
void reapply()
apply() for the option applied last, when the platform's RankTraits changed since: Qt's device became...
static DecoderRankApplier & instance()
ScopedDecoderOption(VideoDecoderOption option)
QList< VideoDecoderOption > availableDecoderFamilies()
std::unique_ptr< GstObject, GstObjectDeleter > GstObjectPtr
Definition GstScoped.h:59
GCharPtr adoptGChar(gchar *str) noexcept
Definition GstScoped.h:134
bool changeFeatureRank(GstRegistry *registry, const char *featureName, uint16_t rank)
DecoderRankApplier::setRank() on the process's applier, so setCodecPriorities() restores the rank too...
std::unique_ptr< GstPluginFeature, GstObjectDeleter > GstFeaturePtr
Definition GstScoped.h:64
GstElementPtr makeElement(const char *factory, const char *name=nullptr)
Definition GstScoped.h:178
void setCodecPriorities(VideoDecoderOption option)
DecoderRankApplier::apply() on the process's applier. GUI thread.
bool demoteFailedDecoder(const char *factoryName, const GstCaps *caps)
DecoderRankApplier::demoteFailedDecoder() on the process's applier. Any thread.
GstObjectPtr adoptObject(GstObject *object) noexcept
Definition GstScoped.h:74
bool isHardwareDecoderFactory(GstElementFactory *factory)
RankPlan planRanks(VideoDecoderOption option, const QList< DecoderInfo > &decoders, const RankTraits &traits)
The rank changes option makes to decoders, from their original ranks, on a platform with traits.
VideoDecoderOption decoderFamilyForFactory(const char *factoryName)
GstFeaturePtr adoptFeature(GstPluginFeature *feature) noexcept
Definition GstScoped.h:99
QString describeDecoderFactory(GstElementFactory *factory)
"[HW|SW] <plugin>/<factory> rank=<rank> (<klass>)" for decoder logs.
void forEachVideoDecoderFactory(GstRank minRank, const std::function< void(GstElementFactory *)> &visitor)
std::unique_ptr< gchar, GFreeDeleter > GCharPtr
Definition GstScoped.h:71
RenderTarget currentRenderTarget()
@ Unknown
No scene graph yet, and the GUI thread hasn't recorded the requested API either.
@ Null
QRhi's Null backend or the software renderer: no GPU import.
qint64 graphicsAdapterLuid() noexcept
Definition HwBuffers.cc:231
bool d3d11OpensD3D12() noexcept
Definition HwBuffers.cc:247
bool softwareRenderingRequested() noexcept
What configureQtGraphics() was told: the user asked for software rendering (–swrast)....
Definition HwBuffers.cc:168
QList< RankChange > changes
At most one per decoder, in the order of planRanks()'s input.
QStringList warnings
Why the option may not do what it says, for the log.
The platform rules planRanks() adds to an option.