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