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