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