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/qdebug.h>
11#include <QtCore/qloggingcategory.h>
12
13#include <algorithm>
14#include <array>
15#include <future>
16#include <set>
17#include <string>
18#include <unordered_set>
19#include <vector>
20
21extern "C" {
22#include <libavcodec/avcodec.h>
23#include <libavutil/pixdesc.h>
24#include <libavutil/samplefmt.h>
25}
26
27#ifdef Q_OS_ANDROID
28# include <QtCore/qjniobject.h>
29# include <QtCore/qjniarray.h>
30# include <QtCore/qjnitypes.h>
31
32# include <QtFFmpegMediaPluginImpl/private/qandroidvideojnitypes_p.h>
33#endif
34
36
37Q_STATIC_LOGGING_CATEGORY(qLcCodecStorage, "qt.multimedia.ffmpeg.codecstorage");
38
39namespace QFFmpeg {
40
42using namespace Qt::Literals;
43
44namespace {
45
46enum CodecStorageType {
47 Encoders,
48 Decoders,
49
50 // TODO: maybe split sw/hw codecs
51
52 CodecStorageTypeCount
53};
54
55using CodecsStorage = std::vector<Codec>;
56
57struct CodecsComparator
58{
59 bool operator()(const Codec &a, const Codec &b) const
60 {
61 return a.id() < b.id() || (a.id() == b.id() && a.isExperimental() < b.isExperimental());
62 }
63
64 bool operator()(const Codec &codec, AVCodecID id) const { return codec.id() < id; }
65 bool operator()(AVCodecID id, const Codec &codec) const { return id < codec.id(); }
66};
67
68template <typename FlagNames>
69QString flagsToString(int flags, const FlagNames &flagNames)
70{
71 QString result;
72 int leftover = flags;
73 for (const auto &flagAndName : flagNames)
74 if ((flags & flagAndName.first) != 0) {
75 leftover &= ~flagAndName.first;
76 if (!result.isEmpty())
77 result += u", ";
78 result += QLatin1StringView(flagAndName.second);
79 }
80
81 if (leftover) {
82 if (!result.isEmpty())
83 result += u", ";
84 result += QString::number(leftover, 16);
85 }
86 return result;
87}
88
89void dumpCodecInfo(const Codec &codec)
90{
91 using FlagNames = std::initializer_list<std::pair<int, const char *>>;
92 const auto mediaType = codec.type() == AVMEDIA_TYPE_VIDEO ? "video"
93 : codec.type() == AVMEDIA_TYPE_AUDIO ? "audio"
94 : codec.type() == AVMEDIA_TYPE_SUBTITLE ? "subtitle"
95 : "other_type";
96
97 const auto type = codec.isEncoder()
98 ? codec.isDecoder() ? "encoder/decoder:" : "encoder:"
99 : "decoder:";
100
101 static const FlagNames capabilitiesNames = {
102 { AV_CODEC_CAP_DRAW_HORIZ_BAND, "DRAW_HORIZ_BAND" },
103 { AV_CODEC_CAP_DR1, "DRAW_HORIZ_DR1" },
104 { AV_CODEC_CAP_DELAY, "DELAY" },
105 { AV_CODEC_CAP_SMALL_LAST_FRAME, "SMALL_LAST_FRAME" },
106#ifdef AV_CODEC_CAP_SUBFRAMES
107 { AV_CODEC_CAP_SUBFRAMES, "SUBFRAMES" },
108#endif
109 { AV_CODEC_CAP_EXPERIMENTAL, "EXPERIMENTAL" },
110 { AV_CODEC_CAP_CHANNEL_CONF, "CHANNEL_CONF" },
111 { AV_CODEC_CAP_FRAME_THREADS, "FRAME_THREADS" },
112 { AV_CODEC_CAP_SLICE_THREADS, "SLICE_THREADS" },
113 { AV_CODEC_CAP_PARAM_CHANGE, "PARAM_CHANGE" },
114#ifdef AV_CODEC_CAP_OTHER_THREADS
115 { AV_CODEC_CAP_OTHER_THREADS, "OTHER_THREADS" },
116#endif
117 { AV_CODEC_CAP_VARIABLE_FRAME_SIZE, "VARIABLE_FRAME_SIZE" },
118 { AV_CODEC_CAP_AVOID_PROBING, "AVOID_PROBING" },
119 { AV_CODEC_CAP_HARDWARE, "HARDWARE" },
120 { AV_CODEC_CAP_HYBRID, "HYBRID" },
121 { AV_CODEC_CAP_ENCODER_REORDERED_OPAQUE, "ENCODER_REORDERED_OPAQUE" },
122#ifdef AV_CODEC_CAP_ENCODER_FLUSH
123 { AV_CODEC_CAP_ENCODER_FLUSH, "ENCODER_FLUSH" },
124#endif
125 };
126
127 qCDebug(qLcCodecStorage) << mediaType << type << codec.name() << "id:" << codec.id()
128 << "capabilities:"
129 << flagsToString(codec.capabilities(), capabilitiesNames);
130
131 if (codec.type() == AVMEDIA_TYPE_VIDEO) {
132 const auto pixelFormats = codec.pixelFormats();
133 if (!pixelFormats.empty()) {
134 static const FlagNames flagNames = {
135 { AV_PIX_FMT_FLAG_BE, "BE" },
136 { AV_PIX_FMT_FLAG_PAL, "PAL" },
137 { AV_PIX_FMT_FLAG_BITSTREAM, "BITSTREAM" },
138 { AV_PIX_FMT_FLAG_HWACCEL, "HWACCEL" },
139 { AV_PIX_FMT_FLAG_PLANAR, "PLANAR" },
140 { AV_PIX_FMT_FLAG_RGB, "RGB" },
141 { AV_PIX_FMT_FLAG_ALPHA, "ALPHA" },
142 { AV_PIX_FMT_FLAG_BAYER, "BAYER" },
143 { AV_PIX_FMT_FLAG_FLOAT, "FLOAT" },
144 };
145
146 qCDebug(qLcCodecStorage) << " pixelFormats:";
147 for (AVPixelFormat f : pixelFormats) {
148 auto desc = av_pix_fmt_desc_get(f);
149 qCDebug(qLcCodecStorage)
150 << " id:" << f << desc->name << "depth:" << desc->comp[0].depth
151 << "flags:" << flagsToString(desc->flags, flagNames);
152 }
153 } else {
154 qCDebug(qLcCodecStorage) << " pixelFormats: null";
155 }
156 } else if (codec.type() == AVMEDIA_TYPE_AUDIO) {
157 const auto sampleFormats = codec.sampleFormats();
158 if (!sampleFormats.empty()) {
159 qCDebug(qLcCodecStorage) << " sampleFormats:";
160 for (auto f : sampleFormats) {
161 const auto name = av_get_sample_fmt_name(f);
162 qCDebug(qLcCodecStorage) << " id:" << f << (name ? name : "unknown")
163 << "bytes_per_sample:" << av_get_bytes_per_sample(f)
164 << "is_planar:" << av_sample_fmt_is_planar(f);
165 }
166 } else {
167 qCDebug(qLcCodecStorage) << " sampleFormats: null";
168 }
169 }
170
171 const std::vector<const AVCodecHWConfig*> hwConfigs = codec.hwConfigs();
172 if (!hwConfigs.empty()) {
173 static const FlagNames hwConfigMethodNames = {
174 { AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX, "HW_DEVICE_CTX" },
175 { AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX, "HW_FRAMES_CTX" },
176 { AV_CODEC_HW_CONFIG_METHOD_INTERNAL, "INTERNAL" },
177 { AV_CODEC_HW_CONFIG_METHOD_AD_HOC, "AD_HOC" }
178 };
179
180 qCDebug(qLcCodecStorage) << " hw config:";
181 for (const AVCodecHWConfig* config : hwConfigs) {
182 const auto pixFmtForDevice = pixelFormatForHwDevice(config->device_type);
183 auto pixFmtDesc = av_pix_fmt_desc_get(config->pix_fmt);
184 auto pixFmtForDeviceDesc = av_pix_fmt_desc_get(pixFmtForDevice);
185 qCDebug(qLcCodecStorage)
186 << " device_type:" << config->device_type << "pix_fmt:" << config->pix_fmt
187 << (pixFmtDesc ? pixFmtDesc->name : "unknown")
188 << "pixelFormatForHwDevice:" << pixelFormatForHwDevice(config->device_type)
189 << (pixFmtForDeviceDesc ? pixFmtForDeviceDesc->name : "unknown")
190 << "hw_config_methods:" << flagsToString(config->methods, hwConfigMethodNames);
191 }
192 }
193}
194
195enum class MFCodecCheckResult {
196 supported_mf_codec,
197 unsupported_mf_codec,
198 not_an_mf_codec,
199};
200
201MFCodecCheckResult isValidMFEncoder([[maybe_unused]] const Codec &codec)
202{
203#ifdef Q_OS_WIN
204 if (!codec.name().endsWith("_mf"_L1))
205 return MFCodecCheckResult::not_an_mf_codec;
206
207 AVCodecContextUPtr ctx{ avcodec_alloc_context3(codec.get()) };
208 if (!ctx)
209 return MFCodecCheckResult::unsupported_mf_codec;
210
211 ctx->width = 1280;
212 ctx->height = 720;
213 ctx->time_base = { 1, 30 };
214 ctx->framerate = { 30, 1 };
215 ctx->pix_fmt = AV_PIX_FMT_NV12;
216
217 const int ret = avcodec_open2(ctx.get(), codec.get(), nullptr);
218 if (ret == AVERROR(ENOSYS)) {
219 qCDebug(qLcCodecStorage) << "MF codec" << codec.name() << "is not available.";
220 return MFCodecCheckResult::unsupported_mf_codec;
221 }
222
223 if (ret < 0) {
224 qCDebug(qLcCodecStorage) << "MF codec" << codec.name()
225 << "is not supported due to avcodec_open2 failure:" << ret
226 << QFFmpeg::AVError(ret);
227 return MFCodecCheckResult::unsupported_mf_codec;
228 }
229
230 return MFCodecCheckResult::supported_mf_codec;
231#else
232 return MFCodecCheckResult::not_an_mf_codec;
233#endif
234}
235
236bool isCodecValid(const Codec &codec, const std::vector<AVHWDeviceType> &availableHwDeviceTypes,
237 const std::optional<std::unordered_set<AVCodecID>> &codecAvailableOnDevice)
238{
239 if (codec.type() != AVMEDIA_TYPE_VIDEO)
240 return true;
241
242 const auto pixelFormats = codec.pixelFormats();
243 if (pixelFormats.empty()) {
244#if defined(Q_OS_LINUX) || defined(Q_OS_ANDROID)
245 // Disable V4L2 M2M codecs for encoding for now,
246 // TODO: Investigate on how to get them working
247 if (codec.name().contains(QLatin1StringView{ "_v4l2m2m" }) && codec.isEncoder())
248 return false;
249
250 // MediaCodec in Android is used for hardware-accelerated media processing. That is why
251 // before marking it as valid, we need to make sure if it is available on current device.
252 if (codec.name().contains(QLatin1StringView{ "_mediacodec" })
253 && (codec.capabilities() & AV_CODEC_CAP_HARDWARE)
254 && codecAvailableOnDevice && codecAvailableOnDevice->count(codec.id()) == 0)
255 return false;
256#endif
257
258 return true; // When the codec reports no pixel formats, format support is unknown.
259 }
260
261 if (codec.isEncoder() && isValidMFEncoder(codec) == MFCodecCheckResult::unsupported_mf_codec)
262 return false; // Unsupported Media Foundation codec
263
264 if (!findAVPixelFormat(codec, &isHwPixelFormat))
265 return true; // Codec does not support any hw pixel formats, so no further checks are needed
266
267 if ((codec.capabilities() & AV_CODEC_CAP_HARDWARE) == 0)
268 return true; // Codec does not support hardware processing, so no further checks are needed
269
270 if (codecAvailableOnDevice && codecAvailableOnDevice->count(codec.id()) == 0)
271 return false; // Codec is not in platform's allow-list
272
273 auto checkDeviceType = [codec](AVHWDeviceType type) {
274 return isAVFormatSupported(codec, pixelFormatForHwDevice(type));
275 };
276
277 return ranges::any_of(availableHwDeviceTypes, checkDeviceType);
278}
279
280std::optional<std::unordered_set<AVCodecID>> availableHWCodecs(const CodecStorageType type)
281{
282#ifdef Q_OS_ANDROID
283 using namespace Qt::StringLiterals;
284 using namespace QtJniTypes;
285 std::unordered_set<AVCodecID> availabeCodecs;
286
287 auto getCodecId = [](const QString &codecName) {
288 if (codecName == "3gpp"_L1)
289 return AV_CODEC_ID_H263;
290 if (codecName == "avc"_L1)
291 return AV_CODEC_ID_H264;
292 if (codecName == "hevc"_L1)
293 return AV_CODEC_ID_HEVC;
294 if (codecName == "mp4v-es"_L1)
295 return AV_CODEC_ID_MPEG4;
296 if (codecName == "x-vnd.on2.vp8"_L1)
297 return AV_CODEC_ID_VP8;
298 if (codecName == "x-vnd.on2.vp9"_L1)
299 return AV_CODEC_ID_VP9;
300 return AV_CODEC_ID_NONE;
301 };
302
303 const QJniArray jniCodecs = QtVideoDeviceManager::callStaticMethod<String[]>(
304 type == Encoders ? "getHWVideoEncoders" : "getHWVideoDecoders");
305
306 for (const auto &codec : jniCodecs)
307 availabeCodecs.insert(getCodecId(codec.toString()));
308 return availabeCodecs;
309#else
310 Q_UNUSED(type);
311 return {};
312#endif
313}
314
315struct CodecStoreSingleton
316{
317 std::shared_future<std::array<CodecsStorage, 2>> codecStoreFuture;
318
319 static bool isExcludedEncoder(QLatin1String codecName)
320 {
321 static const std::set<std::string, std::less<>> excludeSet = [] {
322 std::set<std::string, std::less<>> s;
323 const QByteArray excludeEnv = qgetenv("QT_FFMPEG_EXCLUDE_ENCODERS");
324 if (excludeEnv.isEmpty())
325 return s;
326 const QStringList parts = QString::fromUtf8(excludeEnv).split(u',', Qt::SkipEmptyParts);
327 for (const QString &p : parts) {
328 const QString t = p.trimmed().toLower();
329 if (!t.isEmpty())
330 s.insert(t.toStdString());
331 }
332 return s;
333 }();
334
335 std::string_view codecNameView{ codecName.data(), size_t(codecName.size()) };
336
337 if (excludeSet.count(codecNameView)) {
338 qCDebug(qLcCodecStorage)
339 << "Skip encoder" << codecName << "due to QT_FFMPEG_EXCLUDE_ENCODERS";
340 return true;
341 }
342 return false;
343 }
344
345 static std::array<CodecsStorage, 2> enumerateCodecs()
346 {
347 std::array<CodecsStorage, 2> result;
348 const auto platformHwEncoders = availableHWCodecs(Encoders);
349 const auto platformHwDecoders = availableHWCodecs(Decoders);
350
351 for (const Codec codec : CodecEnumerator()) {
352 // TODO: to be investigated
353 // FFmpeg functions avcodec_find_decoder/avcodec_find_encoder
354 // find experimental codecs in the last order,
355 // now we don't consider them at all since they are supposed to
356 // be not stable, maybe we shouldn't.
357 // Currently, it's possible to turn them on for testing purposes.
358
359 static const auto experimentalCodecsEnabled =
360 qEnvironmentVariableIntValue("QT_ENABLE_EXPERIMENTAL_CODECS");
361
362 if (!experimentalCodecsEnabled && codec.isExperimental()) {
363 qCDebug(qLcCodecStorage) << "Skip experimental codec" << codec.name();
364 continue;
365 }
366
367 if (codec.isDecoder()) {
368 if (isCodecValid(codec, HWAccel::decodingDeviceTypes(), platformHwDecoders))
369 result[Decoders].emplace_back(codec);
370 else
371 qCDebug(qLcCodecStorage) << "Skip decoder" << codec.name()
372 << "due to disabled matching hw acceleration, or "
373 "dysfunctional codec";
374 }
375
376 if (codec.isEncoder()) {
377 if (isExcludedEncoder(codec.name()))
378 continue;
379
380 if (isCodecValid(codec, HWAccel::encodingDeviceTypes(), platformHwEncoders))
381 result[Encoders].emplace_back(codec);
382 else
383 qCDebug(qLcCodecStorage) << "Skip encoder" << codec.name()
384 << "due to disabled matching hw acceleration, or "
385 "dysfunctional codec";
386 }
387 }
388
389 for (auto &storage : result) {
390 storage.shrink_to_fit();
391
392 // we should ensure the original order
393 ranges::stable_sort(storage, CodecsComparator{});
394 }
395
396 // It print pretty much logs, so let's print it only for special case
397 const bool shouldDumpCodecsInfo = qLcCodecStorage().isEnabled(QtDebugMsg)
398 && qEnvironmentVariableIsSet("QT_FFMPEG_DEBUG");
399
400 if (shouldDumpCodecsInfo) {
401 qCDebug(qLcCodecStorage) << "Advanced FFmpeg codecs info:";
402 for (auto &storage : result) {
403 for (auto &codec : storage)
404 dumpCodecInfo(codec);
405 qCDebug(qLcCodecStorage) << "---------------------------";
406 }
407 }
408 return result;
409 }
410
411 CodecStoreSingleton()
412 {
413#ifdef Q_OS_WINDOWS
414 // enumerate codecs asynchronously, so that enumeration is done on a separate thread
415 // without COM initialization, as otherwise avcodec_open2 will fail and ffmpeg will
416 // warn that "COM must not be in STA mode"
417 auto launchPolicy = std::launch::async;
418#else
419 auto launchPolicy = std::launch::deferred;
420#endif
421
422 codecStoreFuture = std::async(launchPolicy, [] {
423 return enumerateCodecs();
424 }).share();
425 }
426};
427
428Q_APPLICATION_STATIC(CodecStoreSingleton, codecStoreSingleton)
429
430const CodecsStorage &codecsStorage(CodecStorageType codecsType)
431{
432 return codecStoreSingleton->codecStoreFuture.get()[codecsType];
433}
434
435template <typename CodecScoreGetter, typename CodecOpener>
436bool findAndOpenCodec(CodecStorageType codecsType, AVCodecID codecId,
437 const CodecScoreGetter &scoreGetter, const CodecOpener &opener)
438{
439 Q_ASSERT(opener);
440 const auto &storage = codecsStorage(codecsType);
441 auto it = std::lower_bound(storage.begin(), storage.end(), codecId, CodecsComparator{});
442
443 using CodecToScore = std::pair<Codec, AVScore>;
444 std::vector<CodecToScore> codecsToScores;
445
446 for (; it != storage.end() && it->id() == codecId; ++it) {
447 const AVScore score = scoreGetter ? scoreGetter(*it) : DefaultAVScore;
448 if (score != NotSuitableAVScore)
449 codecsToScores.emplace_back(*it, score);
450 }
451
452 if (scoreGetter) {
453 ranges::stable_sort(codecsToScores, [](const CodecToScore &a, const CodecToScore &b) {
454 return a.second > b.second;
455 });
456
457 if (qLcCodecStorage().isEnabled(QtDebugMsg))
458 for (const auto &[codec, score] : codecsToScores)
459 qCDebug(qLcCodecStorage)
460 << "findAndOpenCodec(): candidate:" << codec.name() << "score:" << score;
461 }
462
463 return ranges::any_of(codecsToScores, [&](const CodecToScore &codecToScore) {
464 return opener(codecToScore.first);
465 });
466}
467
468std::optional<Codec> findAVCodec(CodecStorageType codecsType, AVCodecID codecId,
469 const std::optional<PixelOrSampleFormat> &format)
470{
471 const CodecsStorage& storage = codecsStorage(codecsType);
472
473 // Storage is sorted, so we can quickly narrow down the search to codecs with the specific id.
474 auto begin = std::lower_bound(storage.begin(), storage.end(), codecId, CodecsComparator{});
475 auto end = std::upper_bound(begin, storage.end(), codecId, CodecsComparator{});
476
477 // Within the narrowed down range, look for a codec that supports the format.
478 // If no format is specified, return the first one.
479 auto codecIt = std::find_if(begin, end, [&format](const Codec &codec) {
480 return !format || isAVFormatSupported(codec, *format);
481 });
482
483 if (codecIt != end)
484 return *codecIt;
485
486 return {};
487}
488
489} // namespace
490
491std::optional<Codec> findAVDecoder(AVCodecID codecId,
492 const std::optional<PixelOrSampleFormat> &format)
493{
494 return findAVCodec(Decoders, codecId, format);
495}
496
497std::optional<Codec> findAVEncoder(AVCodecID codecId, const std::optional<PixelOrSampleFormat> &format)
498{
499 return findAVCodec(Encoders, codecId, format);
500}
501
502bool findAndOpenAVDecoder(AVCodecID codecId,
503 const std::function<AVScore(const Codec &)> &scoresGetter,
504 const std::function<bool(const Codec &)> &codecOpener)
505{
506 return findAndOpenCodec(Decoders, codecId, scoresGetter, codecOpener);
507}
508
509bool findAndOpenAVEncoder(AVCodecID codecId,
510 const std::function<AVScore(const Codec &)> &scoresGetter,
511 const std::function<bool(const Codec &)> &codecOpener)
512{
513 return findAndOpenCodec(Encoders, codecId, scoresGetter, codecOpener);
514}
515
516} // namespace QFFmpeg
517
518QT_END_NAMESPACE
QT_MANGLE_NAMESPACE(QMacScreenCaptureStreamDelegate) QMacScreenCaptureStreamDelegate
Definition qcompare.h:111
QT_BEGIN_NAMESPACE Q_STATIC_LOGGING_CATEGORY(lcSynthesizedIterableAccess, "qt.iterable.synthesized", QtWarningMsg)