Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qffmpegcodecstorage.cpp
Go to the documentation of this file.
1// Copyright (C) 2024 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
5
6#include "qffmpeg_p.h"
8
9#include <QtCore/qapplicationstatic.h>
10#include <QtCore/qoperatingsystemversion.h>
11#include <QtCore/qdebug.h>
12#include <QtCore/qloggingcategory.h>
13
14#include <algorithm>
15#include <array>
16#include <future>
17#include <set>
18#include <string>
19#include <unordered_set>
20#include <vector>
21
22extern "C" {
23#include <libavcodec/avcodec.h>
24#include <libavutil/pixdesc.h>
25#include <libavutil/samplefmt.h>
26}
27
28#ifdef Q_OS_ANDROID
29# include <QtCore/qjniobject.h>
30# include <QtCore/qjniarray.h>
31# include <QtCore/qjnitypes.h>
32
33# include <QtFFmpegMediaPluginImpl/private/qandroidvideojnitypes_p.h>
34#endif
35
37
38Q_STATIC_LOGGING_CATEGORY(qLcCodecStorage, "qt.multimedia.ffmpeg.codecstorage");
39
40namespace QFFmpeg {
41
43using namespace Qt::Literals;
44
45namespace {
46
47using CodecsStorage = std::vector<Codec>;
48
49struct CodecsComparator
50{
51 bool operator()(const Codec &a, const Codec &b) const
52 {
53 return a.id() < b.id() || (a.id() == b.id() && a.isExperimental() < b.isExperimental());
54 }
55
56 bool operator()(const Codec &codec, AVCodecID id) const { return codec.id() < id; }
57 bool operator()(AVCodecID id, const Codec &codec) const { return id < codec.id(); }
58};
59
60void dumpCodecInfo(const Codec &codec)
61{
62 const auto roles =
63 codec.isEncoder() ? codec.isDecoder() ? "encoder/decoder:" : "encoder:" : "decoder:";
64
65 qCDebug(qLcCodecStorage) << codec.type() << roles << codec.name() << "id:" << codec.id()
66 << "capabilities:" << AVCodecCapabilities(codec.capabilities());
67
68 if (codec.type() == AVMEDIA_TYPE_VIDEO) {
69 const auto pixelFormats = codec.pixelFormats();
70 if (!pixelFormats.empty()) {
71 qCDebug(qLcCodecStorage) << " pixelFormats:";
72 for (AVPixelFormat f : pixelFormats) {
73 auto desc = av_pix_fmt_desc_get(f);
74 qCDebug(qLcCodecStorage)
75 << " id:" << f << desc->name << "depth:" << desc->comp[0].depth
76 << "flags:" << AVPixelFormatFlags(desc->flags);
77 }
78 } else {
79 qCDebug(qLcCodecStorage) << " pixelFormats: null";
80 }
81 } else if (codec.type() == AVMEDIA_TYPE_AUDIO) {
82 const auto sampleFormats = codec.sampleFormats();
83 if (!sampleFormats.empty()) {
84 qCDebug(qLcCodecStorage) << " sampleFormats:";
85 for (auto f : sampleFormats) {
86 const auto name = av_get_sample_fmt_name(f);
87 qCDebug(qLcCodecStorage) << " id:" << f << (name ? name : "unknown")
88 << "bytes_per_sample:" << av_get_bytes_per_sample(f)
89 << "is_planar:" << av_sample_fmt_is_planar(f);
90 }
91 } else {
92 qCDebug(qLcCodecStorage) << " sampleFormats: null";
93 }
94 }
95
96 const std::vector<const AVCodecHWConfig*> hwConfigs = codec.hwConfigs();
97 if (!hwConfigs.empty()) {
98 qCDebug(qLcCodecStorage) << " hw config:";
99 for (const AVCodecHWConfig* config : hwConfigs) {
100 const auto pixFmtForDevice = pixelFormatForHwDevice(config->device_type);
101 auto pixFmtDesc = av_pix_fmt_desc_get(config->pix_fmt);
102 auto pixFmtForDeviceDesc = av_pix_fmt_desc_get(pixFmtForDevice);
103 qCDebug(qLcCodecStorage)
104 << " device_type:" << config->device_type << "pix_fmt:" << config->pix_fmt
105 << (pixFmtDesc ? pixFmtDesc->name : "unknown")
106 << "pixelFormatForHwDevice:" << pixelFormatForHwDevice(config->device_type)
107 << (pixFmtForDeviceDesc ? pixFmtForDeviceDesc->name : "unknown")
108 << "hw_config_methods:" << AVHwConfigMethods(config->methods);
109 }
110 }
111}
112
113enum class MFCodecCheckResult {
114 supported_mf_codec,
115 unsupported_mf_codec,
116 not_an_mf_codec,
117};
118
119MFCodecCheckResult isValidMFEncoder([[maybe_unused]] const Codec &codec)
120{
121 if constexpr (QOperatingSystemVersion::currentType() == QOperatingSystemVersion::Windows) {
122 if (!codec.name().endsWith("_mf"_L1))
123 return MFCodecCheckResult::not_an_mf_codec;
124
125 AVCodecContextUPtr ctx{ avcodec_alloc_context3(codec.get()) };
126 if (!ctx)
127 return MFCodecCheckResult::unsupported_mf_codec;
128
129 ctx->width = 1280;
130 ctx->height = 720;
131 ctx->time_base = { 1, 30 };
132 ctx->framerate = { 30, 1 };
133 ctx->pix_fmt = AV_PIX_FMT_NV12;
134
135 const int ret = avcodec_open2(ctx.get(), codec.get(), nullptr);
136 if (ret == AVERROR(ENOSYS)) {
137 qCDebug(qLcCodecStorage) << "MF codec" << codec.name() << "is not available.";
138 return MFCodecCheckResult::unsupported_mf_codec;
139 }
140
141 if (ret < 0) {
142 qCDebug(qLcCodecStorage) << "MF codec" << codec.name()
143 << "is not supported due to avcodec_open2 failure:" << ret
144 << QFFmpeg::AVError(ret);
145 return MFCodecCheckResult::unsupported_mf_codec;
146 }
147
148 return MFCodecCheckResult::supported_mf_codec;
149 } else {
150 return MFCodecCheckResult::not_an_mf_codec;
151 }
152}
153
154bool isCodecValid(const Codec &codec, QSpan<const AVHWDeviceType> availableHwDeviceTypes,
155 const std::optional<std::unordered_set<AVCodecID>> &codecAvailableOnDevice)
156{
157 if (codec.type() != AVMEDIA_TYPE_VIDEO)
158 return true;
159
160 const auto pixelFormats = codec.pixelFormats();
161 if (pixelFormats.empty()) {
162#if defined(Q_OS_LINUX) || defined(Q_OS_ANDROID)
163 // Disable V4L2 M2M codecs for encoding for now,
164 // TODO: Investigate on how to get them working
165 if (codec.name().contains(QLatin1StringView{ "_v4l2m2m" }) && codec.isEncoder())
166 return false;
167
168 // MediaCodec in Android is used for hardware-accelerated media processing. That is why
169 // before marking it as valid, we need to make sure if it is available on current device.
170 if (codec.name().contains(QLatin1StringView{ "_mediacodec" })
171 && (codec.capabilities() & AV_CODEC_CAP_HARDWARE)
172 && codecAvailableOnDevice && codecAvailableOnDevice->count(codec.id()) == 0)
173 return false;
174#endif
175
176 return true; // When the codec reports no pixel formats, format support is unknown.
177 }
178
179 if (codec.isEncoder() && isValidMFEncoder(codec) == MFCodecCheckResult::unsupported_mf_codec)
180 return false; // Unsupported Media Foundation codec
181
182 if (!findAVPixelFormat(codec, &isHwPixelFormat))
183 return true; // Codec does not support any hw pixel formats, so no further checks are needed
184
185 if ((codec.capabilities() & AV_CODEC_CAP_HARDWARE) == 0)
186 return true; // Codec does not support hardware processing, so no further checks are needed
187
188 if (codecAvailableOnDevice && codecAvailableOnDevice->count(codec.id()) == 0)
189 return false; // Codec is not in platform's allow-list
190
191 auto checkDeviceType = [codec](AVHWDeviceType type) {
192 return isAVFormatSupported(codec, pixelFormatForHwDevice(type));
193 };
194
195 return ranges::any_of(availableHwDeviceTypes, checkDeviceType);
196}
197
198std::optional<std::unordered_set<AVCodecID>> availableHWCodecs(const CodecRole type)
199{
200#ifdef Q_OS_ANDROID
201 using namespace Qt::StringLiterals;
202 using namespace QtJniTypes;
203 std::unordered_set<AVCodecID> availabeCodecs;
204
205 auto getCodecId = [](const QString &codecName) {
206 if (codecName == "3gpp"_L1)
207 return AV_CODEC_ID_H263;
208 if (codecName == "avc"_L1)
209 return AV_CODEC_ID_H264;
210 if (codecName == "hevc"_L1)
211 return AV_CODEC_ID_HEVC;
212 if (codecName == "mp4v-es"_L1)
213 return AV_CODEC_ID_MPEG4;
214 if (codecName == "x-vnd.on2.vp8"_L1)
215 return AV_CODEC_ID_VP8;
216 if (codecName == "x-vnd.on2.vp9"_L1)
217 return AV_CODEC_ID_VP9;
218 return AV_CODEC_ID_NONE;
219 };
220
221 const QJniArray jniCodecs = QtVideoDeviceManager::callStaticMethod<String[]>(
222 type == CodecRole::Encoders ? "getHWVideoEncoders" : "getHWVideoDecoders");
223
224 for (const auto &codec : jniCodecs)
225 availabeCodecs.insert(getCodecId(codec.toString()));
226 return availabeCodecs;
227#else
228 Q_UNUSED(type);
229 return {};
230#endif
231}
232
233struct CodecStoreSingleton
234{
235 std::shared_future<std::array<CodecsStorage, 2>> codecStoreFuture;
236
237 static bool isExcludedEncoder(QLatin1String codecName)
238 {
239 static const std::set<std::string, std::less<>> excludeSet = [] {
240 std::set<std::string, std::less<>> s;
241 const QByteArray excludeEnv = qgetenv("QT_FFMPEG_EXCLUDE_ENCODERS");
242 if (excludeEnv.isEmpty())
243 return s;
244 const QStringList parts = QString::fromUtf8(excludeEnv).split(u',', Qt::SkipEmptyParts);
245 for (const QString &p : parts) {
246 const QString t = p.trimmed().toLower();
247 if (!t.isEmpty())
248 s.insert(t.toStdString());
249 }
250 return s;
251 }();
252
253 std::string_view codecNameView{ codecName.data(), size_t(codecName.size()) };
254
255 if (excludeSet.count(codecNameView)) {
256 qCDebug(qLcCodecStorage)
257 << "Skip encoder" << codecName << "due to QT_FFMPEG_EXCLUDE_ENCODERS";
258 return true;
259 }
260 return false;
261 }
262
263 static std::array<CodecsStorage, 2> enumerateCodecs()
264 {
265 std::array<CodecsStorage, 2> result;
266 const auto platformHwEncoders = availableHWCodecs(CodecRole::Encoders);
267 const auto platformHwDecoders = availableHWCodecs(CodecRole::Decoders);
268
269 for (const Codec codec : CodecEnumerator()) {
270 // TODO: to be investigated
271 // FFmpeg functions avcodec_find_decoder/avcodec_find_encoder
272 // find experimental codecs in the last order,
273 // now we don't consider them at all since they are supposed to
274 // be not stable, maybe we shouldn't.
275 // Currently, it's possible to turn them on for testing purposes.
276
277 static const auto experimentalCodecsEnabled =
278 qEnvironmentVariableIntValue("QT_ENABLE_EXPERIMENTAL_CODECS");
279
280 if (!experimentalCodecsEnabled && codec.isExperimental()) {
281 qCDebug(qLcCodecStorage) << "Skip experimental codec" << codec.name();
282 continue;
283 }
284
285 if (codec.isDecoder()) {
286 if (isCodecValid(codec, HWAccel::decodingDeviceTypes(), platformHwDecoders))
287 result[qToUnderlying(CodecRole::Decoders)].emplace_back(codec);
288 else
289 qCDebug(qLcCodecStorage) << "Skip decoder" << codec.name()
290 << "due to disabled matching hw acceleration, or "
291 "dysfunctional codec";
292 }
293
294 if (codec.isEncoder()) {
295 if (isExcludedEncoder(codec.name()))
296 continue;
297
298 if (isCodecValid(codec, HWAccel::encodingDeviceTypes(), platformHwEncoders))
299 result[qToUnderlying(CodecRole::Encoders)].emplace_back(codec);
300 else
301 qCDebug(qLcCodecStorage) << "Skip encoder" << codec.name()
302 << "due to disabled matching hw acceleration, or "
303 "dysfunctional codec";
304 }
305 }
306
307 for (auto &storage : result) {
308 storage.shrink_to_fit();
309
310 // we should ensure the original order
311 ranges::stable_sort(storage, CodecsComparator{});
312 }
313
314 // It print pretty much logs, so let's print it only for special case
315 const bool shouldDumpCodecsInfo = qLcCodecStorage().isEnabled(QtDebugMsg)
316 && qEnvironmentVariableIsSet("QT_FFMPEG_DEBUG");
317
318 if (shouldDumpCodecsInfo) {
319 qCDebug(qLcCodecStorage) << "Advanced FFmpeg codecs info:";
320 for (auto &storage : result) {
321 for (auto &codec : storage)
322 dumpCodecInfo(codec);
323 qCDebug(qLcCodecStorage) << "---------------------------";
324 }
325 }
326 return result;
327 }
328
329 CodecStoreSingleton()
330 {
331 // enumerate codecs asynchronously, so that enumeration is done on a separate thread
332 // without COM initialization, as otherwise avcodec_open2 will fail and ffmpeg will
333 // warn that "COM must not be in STA mode"
334 constexpr auto launchPolicy =
335 QOperatingSystemVersion::currentType() == QOperatingSystemVersion::Windows
336 ? std::launch::async
337 : std::launch::deferred;
338
339 codecStoreFuture = std::async(launchPolicy, [] {
340 return enumerateCodecs();
341 }).share();
342 }
343};
344
345Q_APPLICATION_STATIC(CodecStoreSingleton, codecStoreSingleton)
346
347const CodecsStorage &codecsStorage(CodecRole codecsType)
348{
349 return codecStoreSingleton->codecStoreFuture.get()[qToUnderlying(codecsType)];
350}
351
352template <typename CodecScoreGetter, typename CodecOpener>
353bool findAndOpenCodec(CodecRole codecsType, AVCodecID codecId, const CodecScoreGetter &scoreGetter,
354 const CodecOpener &opener)
355{
356 Q_ASSERT(opener);
357 const auto &storage = codecsStorage(codecsType);
358 auto it = std::lower_bound(storage.begin(), storage.end(), codecId, CodecsComparator{});
359
360 using CodecToScore = std::pair<Codec, AVScore>;
361 std::vector<CodecToScore> codecsToScores;
362
363 for (; it != storage.end() && it->id() == codecId; ++it) {
364 const AVScore score = scoreGetter ? scoreGetter(*it) : DefaultAVScore;
365 if (score != NotSuitableAVScore)
366 codecsToScores.emplace_back(*it, score);
367 }
368
369 if (scoreGetter) {
370 ranges::stable_sort(codecsToScores, [](const CodecToScore &a, const CodecToScore &b) {
371 return a.second > b.second;
372 });
373
374 if (qLcCodecStorage().isEnabled(QtDebugMsg))
375 for (const auto &[codec, score] : codecsToScores)
376 qCDebug(qLcCodecStorage)
377 << "findAndOpenCodec(): candidate:" << codec.name() << "score:" << score;
378 }
379
380 return ranges::any_of(codecsToScores, [&](const CodecToScore &codecToScore) {
381 return opener(codecToScore.first);
382 });
383}
384
385std::optional<Codec> findAVCodec(CodecRole codecsType, AVCodecID codecId,
386 const std::optional<PixelOrSampleFormat> &format)
387{
388 const CodecsStorage& storage = codecsStorage(codecsType);
389
390 // Storage is sorted, so we can quickly narrow down the search to codecs with the specific id.
391 auto begin = std::lower_bound(storage.begin(), storage.end(), codecId, CodecsComparator{});
392 auto end = std::upper_bound(begin, storage.end(), codecId, CodecsComparator{});
393
394 // Within the narrowed down range, look for a codec that supports the format.
395 // If no format is specified, return the first one.
396 auto codecIt = std::find_if(begin, end, [&format](const Codec &codec) {
397 return !format || isAVFormatSupported(codec, *format);
398 });
399
400 if (codecIt != end)
401 return *codecIt;
402
403 return {};
404}
405
406} // namespace
407
408std::optional<Codec> findAVDecoder(AVCodecID codecId,
409 const std::optional<PixelOrSampleFormat> &format)
410{
411 return findAVCodec(CodecRole::Decoders, codecId, format);
412}
413
414std::optional<Codec> findAVEncoder(AVCodecID codecId, const std::optional<PixelOrSampleFormat> &format)
415{
416 return findAVCodec(CodecRole::Encoders, codecId, format);
417}
418
419bool findAndOpenAVDecoder(AVCodecID codecId,
420 const std::function<AVScore(const Codec &)> &scoresGetter,
421 const std::function<bool(const Codec &)> &codecOpener)
422{
423 return findAndOpenCodec(CodecRole::Decoders, codecId, scoresGetter, codecOpener);
424}
425
426bool findAndOpenAVEncoder(AVCodecID codecId,
427 const std::function<AVScore(const Codec &)> &scoresGetter,
428 const std::function<bool(const Codec &)> &codecOpener)
429{
430 return findAndOpenCodec(CodecRole::Encoders, codecId, scoresGetter, codecOpener);
431}
432
433} // namespace QFFmpeg
434
435QT_END_NAMESPACE
AVCodecCapabilities
Definition qffmpeg_p.h:315
QT_MANGLE_NAMESPACE(QMacScreenCaptureStreamDelegate) QMacScreenCaptureStreamDelegate
Definition qcompare.h:111
QT_BEGIN_NAMESPACE Q_STATIC_LOGGING_CATEGORY(lcSynthesizedIterableAccess, "qt.iterable.synthesized", QtWarningMsg)