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