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 <qdebug.h>
10#include <qloggingcategory.h>
11
12#include <algorithm>
13#include <vector>
14#include <array>
15
16#include <unordered_set>
17
18extern "C" {
19#include <libavutil/pixdesc.h>
20#include <libavutil/samplefmt.h>
21}
22
23#ifdef Q_OS_ANDROID
24# include <QtCore/qjniobject.h>
25# include <QtCore/qjniarray.h>
26# include <QtCore/qjnitypes.h>
27#endif
28
29QT_BEGIN_NAMESPACE
30
31#ifdef Q_OS_ANDROID
32Q_DECLARE_JNI_CLASS(QtVideoDeviceManager,
33 "org/qtproject/qt/android/multimedia/QtVideoDeviceManager")
34#endif // Q_OS_ANDROID
35
36Q_STATIC_LOGGING_CATEGORY(qLcCodecStorage, "qt.multimedia.ffmpeg.codecstorage");
37
38namespace QFFmpeg {
39
40namespace {
41
42enum CodecStorageType {
43 Encoders,
44 Decoders,
45
46 // TODO: maybe split sw/hw codecs
47
48 CodecStorageTypeCount
49};
50
51using CodecsStorage = std::vector<Codec>;
52
53struct CodecsComparator
54{
55 bool operator()(const Codec &a, const Codec &b) const
56 {
57 return a.id() < b.id() || (a.id() == b.id() && a.isExperimental() < b.isExperimental());
58 }
59
60 bool operator()(const Codec &codec, AVCodecID id) const { return codec.id() < id; }
61 bool operator()(AVCodecID id, const Codec &codec) const { return id < codec.id(); }
62};
63
64template <typename FlagNames>
65QString flagsToString(int flags, const FlagNames &flagNames)
66{
67 QString result;
68 int leftover = flags;
69 for (const auto &flagAndName : flagNames)
70 if ((flags & flagAndName.first) != 0) {
71 leftover &= ~flagAndName.first;
72 if (!result.isEmpty())
73 result += u", ";
74 result += QLatin1StringView(flagAndName.second);
75 }
76
77 if (leftover) {
78 if (!result.isEmpty())
79 result += u", ";
80 result += QString::number(leftover, 16);
81 }
82 return result;
83}
84
85void dumpCodecInfo(const Codec &codec)
86{
87 using FlagNames = std::initializer_list<std::pair<int, const char *>>;
88 const auto mediaType = codec.type() == AVMEDIA_TYPE_VIDEO ? "video"
89 : codec.type() == AVMEDIA_TYPE_AUDIO ? "audio"
90 : codec.type() == AVMEDIA_TYPE_SUBTITLE ? "subtitle"
91 : "other_type";
92
93 const auto type = codec.isEncoder()
94 ? codec.isDecoder() ? "encoder/decoder:" : "encoder:"
95 : "decoder:";
96
97 static const FlagNames capabilitiesNames = {
98 { AV_CODEC_CAP_DRAW_HORIZ_BAND, "DRAW_HORIZ_BAND" },
99 { AV_CODEC_CAP_DR1, "DRAW_HORIZ_DR1" },
100 { AV_CODEC_CAP_DELAY, "DELAY" },
101 { AV_CODEC_CAP_SMALL_LAST_FRAME, "SMALL_LAST_FRAME" },
102#ifdef AV_CODEC_CAP_SUBFRAMES
103 { AV_CODEC_CAP_SUBFRAMES, "SUBFRAMES" },
104#endif
105 { AV_CODEC_CAP_EXPERIMENTAL, "EXPERIMENTAL" },
106 { AV_CODEC_CAP_CHANNEL_CONF, "CHANNEL_CONF" },
107 { AV_CODEC_CAP_FRAME_THREADS, "FRAME_THREADS" },
108 { AV_CODEC_CAP_SLICE_THREADS, "SLICE_THREADS" },
109 { AV_CODEC_CAP_PARAM_CHANGE, "PARAM_CHANGE" },
110#ifdef AV_CODEC_CAP_OTHER_THREADS
111 { AV_CODEC_CAP_OTHER_THREADS, "OTHER_THREADS" },
112#endif
113 { AV_CODEC_CAP_VARIABLE_FRAME_SIZE, "VARIABLE_FRAME_SIZE" },
114 { AV_CODEC_CAP_AVOID_PROBING, "AVOID_PROBING" },
115 { AV_CODEC_CAP_HARDWARE, "HARDWARE" },
116 { AV_CODEC_CAP_HYBRID, "HYBRID" },
117 { AV_CODEC_CAP_ENCODER_REORDERED_OPAQUE, "ENCODER_REORDERED_OPAQUE" },
118#ifdef AV_CODEC_CAP_ENCODER_FLUSH
119 { AV_CODEC_CAP_ENCODER_FLUSH, "ENCODER_FLUSH" },
120#endif
121 };
122
123 qCDebug(qLcCodecStorage) << mediaType << type << codec.name() << "id:" << codec.id()
124 << "capabilities:"
125 << flagsToString(codec.capabilities(), capabilitiesNames);
126
127 if (codec.type() == AVMEDIA_TYPE_VIDEO) {
128 const auto pixelFormats = codec.pixelFormats();
129 if (!pixelFormats.empty()) {
130 static const FlagNames flagNames = {
131 { AV_PIX_FMT_FLAG_BE, "BE" },
132 { AV_PIX_FMT_FLAG_PAL, "PAL" },
133 { AV_PIX_FMT_FLAG_BITSTREAM, "BITSTREAM" },
134 { AV_PIX_FMT_FLAG_HWACCEL, "HWACCEL" },
135 { AV_PIX_FMT_FLAG_PLANAR, "PLANAR" },
136 { AV_PIX_FMT_FLAG_RGB, "RGB" },
137 { AV_PIX_FMT_FLAG_ALPHA, "ALPHA" },
138 { AV_PIX_FMT_FLAG_BAYER, "BAYER" },
139 { AV_PIX_FMT_FLAG_FLOAT, "FLOAT" },
140 };
141
142 qCDebug(qLcCodecStorage) << " pixelFormats:";
143 for (AVPixelFormat f : pixelFormats) {
144 auto desc = av_pix_fmt_desc_get(f);
145 qCDebug(qLcCodecStorage)
146 << " id:" << f << desc->name << "depth:" << desc->comp[0].depth
147 << "flags:" << flagsToString(desc->flags, flagNames);
148 }
149 } else {
150 qCDebug(qLcCodecStorage) << " pixelFormats: null";
151 }
152 } else if (codec.type() == AVMEDIA_TYPE_AUDIO) {
153 const auto sampleFormats = codec.sampleFormats();
154 if (!sampleFormats.empty()) {
155 qCDebug(qLcCodecStorage) << " sampleFormats:";
156 for (auto f : sampleFormats) {
157 const auto name = av_get_sample_fmt_name(f);
158 qCDebug(qLcCodecStorage) << " id:" << f << (name ? name : "unknown")
159 << "bytes_per_sample:" << av_get_bytes_per_sample(f)
160 << "is_planar:" << av_sample_fmt_is_planar(f);
161 }
162 } else {
163 qCDebug(qLcCodecStorage) << " sampleFormats: null";
164 }
165 }
166
167 const std::vector<const AVCodecHWConfig*> hwConfigs = codec.hwConfigs();
168 if (!hwConfigs.empty()) {
169 static const FlagNames hwConfigMethodNames = {
170 { AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX, "HW_DEVICE_CTX" },
171 { AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX, "HW_FRAMES_CTX" },
172 { AV_CODEC_HW_CONFIG_METHOD_INTERNAL, "INTERNAL" },
173 { AV_CODEC_HW_CONFIG_METHOD_AD_HOC, "AD_HOC" }
174 };
175
176 qCDebug(qLcCodecStorage) << " hw config:";
177 for (const AVCodecHWConfig* config : hwConfigs) {
178 const auto pixFmtForDevice = pixelFormatForHwDevice(config->device_type);
179 auto pixFmtDesc = av_pix_fmt_desc_get(config->pix_fmt);
180 auto pixFmtForDeviceDesc = av_pix_fmt_desc_get(pixFmtForDevice);
181 qCDebug(qLcCodecStorage)
182 << " device_type:" << config->device_type << "pix_fmt:" << config->pix_fmt
183 << (pixFmtDesc ? pixFmtDesc->name : "unknown")
184 << "pixelFormatForHwDevice:" << pixelFormatForHwDevice(config->device_type)
185 << (pixFmtForDeviceDesc ? pixFmtForDeviceDesc->name : "unknown")
186 << "hw_config_methods:" << flagsToString(config->methods, hwConfigMethodNames);
187 }
188 }
189}
190
191bool isCodecValid(const Codec &codec, const std::vector<AVHWDeviceType> &availableHwDeviceTypes,
192 const std::optional<std::unordered_set<AVCodecID>> &codecAvailableOnDevice)
193{
194 if (codec.type() != AVMEDIA_TYPE_VIDEO)
195 return true;
196
197 const auto pixelFormats = codec.pixelFormats();
198 if (pixelFormats.empty()) {
199#if defined(Q_OS_LINUX) || defined(Q_OS_ANDROID)
200 // Disable V4L2 M2M codecs for encoding for now,
201 // TODO: Investigate on how to get them working
202 if (codec.name().contains(QLatin1StringView{ "_v4l2m2m" }) && codec.isEncoder())
203 return false;
204
205 // MediaCodec in Android is used for hardware-accelerated media processing. That is why
206 // before marking it as valid, we need to make sure if it is available on current device.
207 if (codec.name().contains(QLatin1StringView{ "_mediacodec" })
208 && (codec.capabilities() & AV_CODEC_CAP_HARDWARE)
209 && codecAvailableOnDevice && codecAvailableOnDevice->count(codec.id()) == 0)
210 return false;
211#endif
212
213 return true; // When the codec reports no pixel formats, format support is unknown.
214 }
215
216 if (!findAVPixelFormat(codec, &isHwPixelFormat))
217 return true; // Codec does not support any hw pixel formats, so no further checks are needed
218
219 if ((codec.capabilities() & AV_CODEC_CAP_HARDWARE) == 0)
220 return true; // Codec does not support hardware processing, so no further checks are needed
221
222 if (codecAvailableOnDevice && codecAvailableOnDevice->count(codec.id()) == 0)
223 return false; // Codec is not in platform's allow-list
224
225 auto checkDeviceType = [codec](AVHWDeviceType type) {
226 return isAVFormatSupported(codec, pixelFormatForHwDevice(type));
227 };
228
229 return std::any_of(availableHwDeviceTypes.begin(), availableHwDeviceTypes.end(),
230 checkDeviceType);
231}
232
233std::optional<std::unordered_set<AVCodecID>> availableHWCodecs(const CodecStorageType type)
234{
235#ifdef Q_OS_ANDROID
236 using namespace Qt::StringLiterals;
237 using namespace QtJniTypes;
238 std::unordered_set<AVCodecID> availabeCodecs;
239
240 auto getCodecId = [](const QString &codecName) {
241 if (codecName == "3gpp"_L1)
242 return AV_CODEC_ID_H263;
243 if (codecName == "avc"_L1)
244 return AV_CODEC_ID_H264;
245 if (codecName == "hevc"_L1)
246 return AV_CODEC_ID_HEVC;
247 if (codecName == "mp4v-es"_L1)
248 return AV_CODEC_ID_MPEG4;
249 if (codecName == "x-vnd.on2.vp8"_L1)
250 return AV_CODEC_ID_VP8;
251 if (codecName == "x-vnd.on2.vp9"_L1)
252 return AV_CODEC_ID_VP9;
253 return AV_CODEC_ID_NONE;
254 };
255
256 const QJniArray jniCodecs = QtVideoDeviceManager::callStaticMethod<String[]>(
257 type == Encoders ? "getHWVideoEncoders" : "getHWVideoDecoders");
258
259 for (const auto &codec : jniCodecs)
260 availabeCodecs.insert(getCodecId(codec.toString()));
261 return availabeCodecs;
262#else
263 Q_UNUSED(type);
264 return {};
265#endif
266}
267
268const CodecsStorage &codecsStorage(CodecStorageType codecsType)
269{
270 static const auto &storages = []() {
271 std::array<CodecsStorage, CodecStorageTypeCount> result;
272 const auto platformHwEncoders = availableHWCodecs(Encoders);
273 const auto platformHwDecoders = availableHWCodecs(Decoders);
274
275 for (const Codec codec : CodecEnumerator()) {
276 // TODO: to be investigated
277 // FFmpeg functions avcodec_find_decoder/avcodec_find_encoder
278 // find experimental codecs in the last order,
279 // now we don't consider them at all since they are supposed to
280 // be not stable, maybe we shouldn't.
281 // Currently, it's possible to turn them on for testing purposes.
282
283 static const auto experimentalCodecsEnabled =
284 qEnvironmentVariableIntValue("QT_ENABLE_EXPERIMENTAL_CODECS");
285
286 if (!experimentalCodecsEnabled && codec.isExperimental()) {
287 qCDebug(qLcCodecStorage) << "Skip experimental codec" << codec.name();
288 continue;
289 }
290
291 if (codec.isDecoder()) {
292 if (isCodecValid(codec, HWAccel::decodingDeviceTypes(), platformHwDecoders))
293 result[Decoders].emplace_back(codec);
294 else
295 qCDebug(qLcCodecStorage)
296 << "Skip decoder" << codec.name()
297 << "due to disabled matching hw acceleration, or dysfunctional codec";
298 }
299
300 if (codec.isEncoder()) {
301 if (isCodecValid(codec, HWAccel::encodingDeviceTypes(), platformHwEncoders))
302 result[Encoders].emplace_back(codec);
303 else
304 qCDebug(qLcCodecStorage)
305 << "Skip encoder" << codec.name()
306 << "due to disabled matching hw acceleration, or dysfunctional codec";
307 }
308 }
309
310 for (auto &storage : result) {
311 storage.shrink_to_fit();
312
313 // we should ensure the original order
314 std::stable_sort(storage.begin(), storage.end(), CodecsComparator{});
315 }
316
317 // It print pretty much logs, so let's print it only for special case
318 const bool shouldDumpCodecsInfo = qLcCodecStorage().isEnabled(QtDebugMsg)
319 && qEnvironmentVariableIsSet("QT_FFMPEG_DEBUG");
320
321 if (shouldDumpCodecsInfo) {
322 qCDebug(qLcCodecStorage) << "Advanced FFmpeg codecs info:";
323 for (auto &storage : result) {
324 std::for_each(storage.begin(), storage.end(), &dumpCodecInfo);
325 qCDebug(qLcCodecStorage) << "---------------------------";
326 }
327 }
328
329 return result;
330 }();
331
332 return storages[codecsType];
333}
334
335template <typename CodecScoreGetter, typename CodecOpener>
336bool findAndOpenCodec(CodecStorageType codecsType, AVCodecID codecId,
337 const CodecScoreGetter &scoreGetter, const CodecOpener &opener)
338{
339 Q_ASSERT(opener);
340 const auto &storage = codecsStorage(codecsType);
341 auto it = std::lower_bound(storage.begin(), storage.end(), codecId, CodecsComparator{});
342
343 using CodecToScore = std::pair<Codec, AVScore>;
344 std::vector<CodecToScore> codecsToScores;
345
346 for (; it != storage.end() && it->id() == codecId; ++it) {
347 const AVScore score = scoreGetter ? scoreGetter(*it) : DefaultAVScore;
348 if (score != NotSuitableAVScore)
349 codecsToScores.emplace_back(*it, score);
350 }
351
352 if (scoreGetter) {
353 std::stable_sort(
354 codecsToScores.begin(), codecsToScores.end(),
355 [](const CodecToScore &a, const CodecToScore &b) { return a.second > b.second; });
356 }
357
358 auto open = [&opener](const CodecToScore &codecToScore) { return opener(codecToScore.first); };
359
360 return std::any_of(codecsToScores.begin(), codecsToScores.end(), open);
361}
362
363std::optional<Codec> findAVCodec(CodecStorageType codecsType, AVCodecID codecId,
364 const std::optional<PixelOrSampleFormat> &format)
365{
366 const CodecsStorage& storage = codecsStorage(codecsType);
367
368 // Storage is sorted, so we can quickly narrow down the search to codecs with the specific id.
369 auto begin = std::lower_bound(storage.begin(), storage.end(), codecId, CodecsComparator{});
370 auto end = std::upper_bound(begin, storage.end(), codecId, CodecsComparator{});
371
372 // Within the narrowed down range, look for a codec that supports the format.
373 // If no format is specified, return the first one.
374 auto codecIt = std::find_if(begin, end, [&format](const Codec &codec) {
375 return !format || isAVFormatSupported(codec, *format);
376 });
377
378 if (codecIt != end)
379 return *codecIt;
380
381 return {};
382}
383
384} // namespace
385
386std::optional<Codec> findAVDecoder(AVCodecID codecId,
387 const std::optional<PixelOrSampleFormat> &format)
388{
389 return findAVCodec(Decoders, codecId, format);
390}
391
392std::optional<Codec> findAVEncoder(AVCodecID codecId, const std::optional<PixelOrSampleFormat> &format)
393{
394 return findAVCodec(Encoders, codecId, format);
395}
396
397bool findAndOpenAVDecoder(AVCodecID codecId,
398 const std::function<AVScore(const Codec &)> &scoresGetter,
399 const std::function<bool(const Codec &)> &codecOpener)
400{
401 return findAndOpenCodec(Decoders, codecId, scoresGetter, codecOpener);
402}
403
404bool findAndOpenAVEncoder(AVCodecID codecId,
405 const std::function<AVScore(const Codec &)> &scoresGetter,
406 const std::function<bool(const Codec &)> &codecOpener)
407{
408 return findAndOpenCodec(Encoders, codecId, scoresGetter, codecOpener);
409}
410
411} // namespace QFFmpeg
412
413QT_END_NAMESPACE
bool findAndOpenAVDecoder(AVCodecID codecId, const std::function< AVScore(const Codec &)> &scoresGetter, const std::function< bool(const Codec &)> &codecOpener)
std::conditional_t< QT_FFMPEG_AVIO_WRITE_CONST, const uint8_t *, uint8_t * > AvioWriteBufferType
std::optional< Codec > findAVEncoder(AVCodecID codecId, const std::optional< PixelOrSampleFormat > &format={})
bool findAndOpenAVEncoder(AVCodecID codecId, const std::function< AVScore(const Codec &)> &scoresGetter, const std::function< bool(const Codec &)> &codecOpener)
std::optional< Codec > findAVDecoder(AVCodecID codecId, const std::optional< PixelOrSampleFormat > &format={})
#define qCDebug(category,...)
#define Q_STATIC_LOGGING_CATEGORY(name,...)