Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
Loading...
Searching...
No Matches
qffmpeghwaccel.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 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
4#include "libavutil/version.h"
5
6#include "qffmpeghwaccel_p.h"
7#if QT_CONFIG(vaapi)
9#endif
10#ifdef Q_OS_DARWIN
12#endif
13#if QT_CONFIG(wmf)
15#include <QtCore/private/qsystemlibrary_p.h>
16
17#endif
18#ifdef Q_OS_ANDROID
20#endif
21#include "qffmpeg_p.h"
24#include "QtCore/qfile.h"
25
26#include <rhi/qrhi.h>
27#include <qloggingcategory.h>
28#include <unordered_set>
29#ifdef Q_OS_LINUX
30#include <QLibrary>
31#endif
32
33/* Infrastructure for HW acceleration goes into this file. */
34
36
37static Q_LOGGING_CATEGORY(qLHWAccel, "qt.multimedia.ffmpeg.hwaccel");
38extern bool thread_local FFmpegLogsEnabledInThread;
39
40namespace QFFmpeg {
41
42static const std::initializer_list<AVHWDeviceType> preferredHardwareAccelerators = {
43#if defined(Q_OS_ANDROID)
44 AV_HWDEVICE_TYPE_MEDIACODEC,
45#elif defined(Q_OS_LINUX)
46 AV_HWDEVICE_TYPE_CUDA,
47 AV_HWDEVICE_TYPE_VAAPI,
48
49 // TODO: investigate VDPAU advantages.
50 // nvenc/nvdec codecs use AV_HWDEVICE_TYPE_CUDA by default, but they can also use VDPAU
51 // if it's included into the ffmpeg build and vdpau drivers are installed.
52 // AV_HWDEVICE_TYPE_VDPAU
53#elif defined (Q_OS_WIN)
54 AV_HWDEVICE_TYPE_D3D11VA,
55#elif defined (Q_OS_DARWIN)
56 AV_HWDEVICE_TYPE_VIDEOTOOLBOX,
57#endif
58};
59
60static AVBufferUPtr loadHWContext(AVHWDeviceType type)
61{
62 AVBufferRef *hwContext = nullptr;
63 qCDebug(qLHWAccel) << " Checking HW context:" << av_hwdevice_get_type_name(type);
64 int ret = av_hwdevice_ctx_create(&hwContext, type, nullptr, nullptr, 0);
65
66 if (ret == 0) {
67 qCDebug(qLHWAccel) << " Using above hw context.";
68 return AVBufferUPtr(hwContext);
69 }
70 qCDebug(qLHWAccel) << " Could not create hw context:" << ret << strerror(-ret);
71 return nullptr;
72}
73
74// FFmpeg might crash on loading non-existing hw devices.
75// Let's roughly precheck drivers/libraries.
76static bool precheckDriver(AVHWDeviceType type)
77{
78 // precheckings might need some improvements
79#if defined(Q_OS_LINUX)
80 if (type == AV_HWDEVICE_TYPE_CUDA) {
81 if (!QFile::exists(QLatin1String("/proc/driver/nvidia/version")))
82 return false;
83
84 // QTBUG-122199
85 // CUDA backend requires libnvcuvid in libavcodec
86 QLibrary lib("libnvcuvid.so");
87 if (!lib.load())
88 return false;
89 lib.unload();
90 return true;
91 }
92#elif defined(Q_OS_WINDOWS)
93 if (type == AV_HWDEVICE_TYPE_D3D11VA)
94 return QSystemLibrary(QLatin1String("d3d11.dll")).load();
95
96#if QT_FFMPEG_HAS_D3D12VA
97 if (type == AV_HWDEVICE_TYPE_D3D12VA)
98 return QSystemLibrary(QLatin1String("d3d12.dll")).load();
99#endif
100
101 if (type == AV_HWDEVICE_TYPE_DXVA2)
102 return QSystemLibrary(QLatin1String("d3d9.dll")).load();
103
104 // TODO: check nvenc/nvdec and revisit the checking
105 if (type == AV_HWDEVICE_TYPE_CUDA)
106 return QSystemLibrary(QLatin1String("nvml.dll")).load();
107#else
108 Q_UNUSED(type);
109#endif
110
111 return true;
112}
113
114static bool checkHwType(AVHWDeviceType type)
115{
116 const auto deviceName = av_hwdevice_get_type_name(type);
117 if (!deviceName) {
118 qWarning() << "Internal FFmpeg error, unknow hw type:" << type;
119 return false;
120 }
121
122 if (!precheckDriver(type)) {
123 qCDebug(qLHWAccel) << "Drivers for hw device" << deviceName << "is not installed";
124 return false;
125 }
126
127 if (type == AV_HWDEVICE_TYPE_MEDIACODEC ||
128 type == AV_HWDEVICE_TYPE_VIDEOTOOLBOX ||
129 type == AV_HWDEVICE_TYPE_D3D11VA ||
131 type == AV_HWDEVICE_TYPE_D3D12VA ||
132#endif
133 type == AV_HWDEVICE_TYPE_DXVA2)
134 return true; // Don't waste time; it's expected to work fine of the precheck is OK
135
136
139
140 return loadHWContext(type) != nullptr;
141}
142
143static const std::vector<AVHWDeviceType> &deviceTypes()
144{
145 static const auto types = []() {
146 qCDebug(qLHWAccel) << "Check device types";
148 timer.start();
149
150 // gather hw pix formats
151 std::unordered_set<AVPixelFormat> hwPixFormats;
152 void *opaque = nullptr;
153 while (auto codec = av_codec_iterate(&opaque)) {
154 if (auto pixFmt = codec->pix_fmts)
155 for (; *pixFmt != AV_PIX_FMT_NONE; ++pixFmt)
156 if (isHwPixelFormat(*pixFmt))
157 hwPixFormats.insert(*pixFmt);
158 }
159
160 // create a device types list
161 std::vector<AVHWDeviceType> result;
162 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
163 while ((type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE)
164 if (hwPixFormats.count(pixelFormatForHwDevice(type)) && checkHwType(type))
165 result.push_back(type);
166 result.shrink_to_fit();
167
168 // reorder the list accordingly preferredHardwareAccelerators
169 auto it = result.begin();
170 for (const auto preffered : preferredHardwareAccelerators) {
171 auto found = std::find(it, result.end(), preffered);
172 if (found != result.end())
173 std::rotate(it++, found, std::next(found));
174 }
175
176 using namespace std::chrono;
177 qCDebug(qLHWAccel) << "Device types checked. Spent time:" << duration_cast<microseconds>(timer.durationElapsed());
178
179 return result;
180 }();
181
182 return types;
183}
184
185static std::vector<AVHWDeviceType> deviceTypes(const char *envVarName)
186{
187 const auto definedDeviceTypes = qgetenv(envVarName);
188
189 if (definedDeviceTypes.isNull())
190 return deviceTypes();
191
192 std::vector<AVHWDeviceType> result;
193 const auto definedDeviceTypesString = QString::fromUtf8(definedDeviceTypes).toLower();
194 for (const auto &deviceType : definedDeviceTypesString.split(',')) {
195 if (!deviceType.isEmpty()) {
196 const auto foundType = av_hwdevice_find_type_by_name(deviceType.toUtf8().data());
197 if (foundType == AV_HWDEVICE_TYPE_NONE)
198 qWarning() << "Unknown hw device type" << deviceType;
199 else
200 result.emplace_back(foundType);
201 }
202 }
203
204 result.shrink_to_fit();
205 return result;
206}
207
208template<typename CodecFinder>
209std::pair<const AVCodec *, std::unique_ptr<HWAccel>>
210findCodecWithHwAccel(AVCodecID id, const std::vector<AVHWDeviceType> &deviceTypes,
211 CodecFinder codecFinder,
212 const std::function<bool(const HWAccel &)> &hwAccelPredicate)
213{
214 for (auto type : deviceTypes) {
215 const auto codec = codecFinder(id, type, {});
216
217 if (!codec)
218 continue;
219
220 qCDebug(qLHWAccel) << "Found potential codec" << codec->name << "for hw accel" << type
221 << "; Checking the hw device...";
222
223 auto hwAccel = QFFmpeg::HWAccel::create(type);
224
225 if (!hwAccel)
226 continue;
227
228 if (hwAccelPredicate && !hwAccelPredicate(*hwAccel)) {
229 qCDebug(qLHWAccel) << "HW device is available but doesn't suit due to restrictions";
230 continue;
231 }
232
233 qCDebug(qLHWAccel) << "HW device is OK";
234
235 return { codec, std::move(hwAccel) };
236 }
237
238 qCDebug(qLHWAccel) << "No hw acceleration found for codec id" << id;
239
240 return { nullptr, nullptr };
241}
242
243static bool isNoConversionFormat(AVPixelFormat f)
244{
245 bool needsConversion = true;
246 QFFmpegVideoBuffer::toQtPixelFormat(f, &needsConversion);
247 return !needsConversion;
248};
249
250namespace {
251
252bool hwTextureConversionEnabled()
253{
254
255 // HW textures conversions are not stable in specific cases, dependent on the hardware and OS.
256 // We need the env var for testing with no textures conversion on the user's side.
257 static const int disableHwConversion =
258 qEnvironmentVariableIntValue("QT_DISABLE_HW_TEXTURES_CONVERSION");
259
260 return !disableHwConversion;
261}
262
263void setupDecoder(const AVPixelFormat format, AVCodecContext *const codecContext)
264{
265 if (!hwTextureConversionEnabled())
266 return;
267
268#if QT_CONFIG(wmf)
269 if (format == AV_PIX_FMT_D3D11)
270 QFFmpeg::D3D11TextureConverter::SetupDecoderTextures(codecContext);
271#elif defined Q_OS_ANDROID
272 if (format == AV_PIX_FMT_MEDIACODEC)
274#else
275 Q_UNUSED(codecContext);
277#endif
278}
279
280} // namespace
281
282// Used for the AVCodecContext::get_format callback
283AVPixelFormat getFormat(AVCodecContext *codecContext, const AVPixelFormat *suggestedFormats)
284{
285 // First check HW accelerated codecs, the HW device context must be set
286 if (codecContext->hw_device_ctx) {
287 auto *device_ctx = (AVHWDeviceContext *)codecContext->hw_device_ctx->data;
288 std::pair formatAndScore(AV_PIX_FMT_NONE, NotSuitableAVScore);
289
290 // to be rewritten via findBestAVFormat
291 for (int i = 0;
292 const AVCodecHWConfig *config = avcodec_get_hw_config(codecContext->codec, i); i++) {
293 if (!(config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
294 continue;
295
296 if (device_ctx->type != config->device_type)
297 continue;
298
299 const bool isDeprecated = (config->methods & AV_CODEC_HW_CONFIG_METHOD_AD_HOC) != 0;
300 const bool shouldCheckCodecFormats = config->pix_fmt == AV_PIX_FMT_NONE;
301
302 auto scoresGettor = [&](AVPixelFormat format) {
303 if (shouldCheckCodecFormats && !isAVFormatSupported(codecContext->codec, format))
304 return NotSuitableAVScore;
305
306 if (!shouldCheckCodecFormats && config->pix_fmt != format)
307 return NotSuitableAVScore;
308
309 auto result = DefaultAVScore;
310
311 if (isDeprecated)
312 result -= 10000;
314 result += 10;
315
316 return result;
317 };
318
319 const auto found = findBestAVFormat(suggestedFormats, scoresGettor);
320
321 if (found.second > formatAndScore.second)
322 formatAndScore = found;
323 }
324
325 const auto &format = formatAndScore.first;
326 if (format != AV_PIX_FMT_NONE) {
327 setupDecoder(format, codecContext);
328 qCDebug(qLHWAccel) << "Selected format" << format << "for hw" << device_ctx->type;
329 return format;
330 }
331 }
332
333 // prefer video formats we can handle directly
334 const auto noConversionFormat = findAVFormat(suggestedFormats, &isNoConversionFormat);
335 if (noConversionFormat != AV_PIX_FMT_NONE) {
336 qCDebug(qLHWAccel) << "Selected format with no conversion" << noConversionFormat;
337 return noConversionFormat;
338 }
339
340 qCDebug(qLHWAccel) << "Selected format with conversion" << *suggestedFormats;
341
342 // take the native format, this will involve one additional format conversion on the CPU side
343 return *suggestedFormats;
344}
345
346HWAccel::~HWAccel() = default;
347
348std::unique_ptr<HWAccel> HWAccel::create(AVHWDeviceType deviceType)
349{
350 if (auto ctx = loadHWContext(deviceType))
351 return std::unique_ptr<HWAccel>(new HWAccel(std::move(ctx)));
352 else
353 return {};
354}
355
356AVPixelFormat HWAccel::format(AVFrame *frame)
357{
358 if (!frame->hw_frames_ctx)
359 return AVPixelFormat(frame->format);
360
361 auto *hwFramesContext = (AVHWFramesContext *)frame->hw_frames_ctx->data;
363 return AVPixelFormat(hwFramesContext->sw_format);
364}
365
366const std::vector<AVHWDeviceType> &HWAccel::encodingDeviceTypes()
367{
368 static const auto &result = deviceTypes("QT_FFMPEG_ENCODING_HW_DEVICE_TYPES");
369 return result;
370}
371
372const std::vector<AVHWDeviceType> &HWAccel::decodingDeviceTypes()
373{
374 static const auto &result = deviceTypes("QT_FFMPEG_DECODING_HW_DEVICE_TYPES");
375 return result;
376}
377
378AVHWDeviceContext *HWAccel::hwDeviceContext() const
379{
380 return m_hwDeviceContext ? (AVHWDeviceContext *)m_hwDeviceContext->data : nullptr;
381}
382
383AVPixelFormat HWAccel::hwFormat() const
384{
386}
387
388const AVHWFramesConstraints *HWAccel::constraints() const
389{
390 std::call_once(m_constraintsOnceFlag, [this]() {
391 if (auto context = hwDeviceContextAsBuffer())
392 m_constraints.reset(av_hwdevice_get_hwframe_constraints(context, nullptr));
393 });
394
395 return m_constraints.get();
396}
397
398std::pair<const AVCodec *, std::unique_ptr<HWAccel>>
399HWAccel::findEncoderWithHwAccel(AVCodecID id, const std::function<bool(const HWAccel &)>& hwAccelPredicate)
400{
401 auto finder = qOverload<AVCodecID, const std::optional<AVHWDeviceType> &,
402 const std::optional<PixelOrSampleFormat> &>(&QFFmpeg::findAVEncoder);
403 return findCodecWithHwAccel(id, encodingDeviceTypes(), finder, hwAccelPredicate);
404}
405
406std::pair<const AVCodec *, std::unique_ptr<HWAccel>>
407HWAccel::findDecoderWithHwAccel(AVCodecID id, const std::function<bool(const HWAccel &)>& hwAccelPredicate)
408{
410 hwAccelPredicate);
411}
412
413AVHWDeviceType HWAccel::deviceType() const
414{
415 return m_hwDeviceContext ? hwDeviceContext()->type : AV_HWDEVICE_TYPE_NONE;
416}
417
418void HWAccel::createFramesContext(AVPixelFormat swFormat, const QSize &size)
419{
420 if (m_hwFramesContext) {
421 qWarning() << "Frames context has been already created!";
422 return;
423 }
424
425 if (!m_hwDeviceContext)
426 return;
427
428 m_hwFramesContext.reset(av_hwframe_ctx_alloc(m_hwDeviceContext.get()));
429 auto *c = (AVHWFramesContext *)m_hwFramesContext->data;
430 c->format = hwFormat();
431 c->sw_format = swFormat;
432 c->width = size.width();
433 c->height = size.height();
434 qCDebug(qLHWAccel) << "init frames context";
435 int err = av_hwframe_ctx_init(m_hwFramesContext.get());
436 if (err < 0)
437 qWarning() << "failed to init HW frame context" << err << err2str(err);
438 else
439 qCDebug(qLHWAccel) << "Initialized frames context" << size << c->format << c->sw_format;
440}
441
442AVHWFramesContext *HWAccel::hwFramesContext() const
443{
444 return m_hwFramesContext ? (AVHWFramesContext *)m_hwFramesContext->data : nullptr;
445}
446
447
449 : d(new Data)
450{
451 d->rhi = rhi;
452}
453
455{
456 if (!frame || isNull())
457 return nullptr;
458
459 Q_ASSERT(frame->format == d->format);
460 return d->backend->getTextures(frame);
461}
462
463void TextureConverter::updateBackend(AVPixelFormat fmt)
464{
465 d->backend = nullptr;
466 if (!d->rhi)
467 return;
468
469 if (!hwTextureConversionEnabled())
470 return;
471
472 switch (fmt) {
473#if QT_CONFIG(vaapi)
474 case AV_PIX_FMT_VAAPI:
475 d->backend = std::make_unique<VAAPITextureConverter>(d->rhi);
476 break;
477#endif
478#ifdef Q_OS_DARWIN
479 case AV_PIX_FMT_VIDEOTOOLBOX:
480 d->backend = std::make_unique<VideoToolBoxTextureConverter>(d->rhi);
481 break;
482#endif
483#if QT_CONFIG(wmf)
484 case AV_PIX_FMT_D3D11:
485 d->backend = std::make_unique<D3D11TextureConverter>(d->rhi);
486 break;
487#endif
488#ifdef Q_OS_ANDROID
489 case AV_PIX_FMT_MEDIACODEC:
490 d->backend = std::make_unique<MediaCodecTextureConverter>(d->rhi);
491 break;
492#endif
493 default:
494 break;
495 }
496 d->format = fmt;
497}
498
499} // namespace QFFmpeg
500
\inmodule QtCore
static QVideoFrameFormat::PixelFormat toQtPixelFormat(AVPixelFormat avPixelFormat, bool *needsConversion=nullptr)
static std::pair< const AVCodec *, std::unique_ptr< HWAccel > > findDecoderWithHwAccel(AVCodecID id, const std::function< bool(const HWAccel &)> &hwAccelPredicate=nullptr)
AVHWFramesContext * hwFramesContext() const
static const std::vector< AVHWDeviceType > & decodingDeviceTypes()
static const std::vector< AVHWDeviceType > & encodingDeviceTypes()
void createFramesContext(AVPixelFormat swFormat, const QSize &size)
static AVPixelFormat format(AVFrame *frame)
static std::pair< const AVCodec *, std::unique_ptr< HWAccel > > findEncoderWithHwAccel(AVCodecID id, const std::function< bool(const HWAccel &)> &hwAccelPredicate=nullptr)
AVBufferRef * hwDeviceContextAsBuffer() const
const AVHWFramesConstraints * constraints() const
AVHWDeviceContext * hwDeviceContext() const
AVPixelFormat hwFormat() const
static std::unique_ptr< HWAccel > create(AVHWDeviceType deviceType)
AVHWDeviceType deviceType() const
static void setupDecoderSurface(AVCodecContext *s)
TextureSet * getTextures(AVFrame *frame)
TextureConverter(QRhi *rhi=nullptr)
bool exists() const
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qfile.cpp:351
\inmodule QtCore \reentrant
Definition qlibrary.h:17
bool load()
Loads the library and returns true if the library was loaded successfully; otherwise returns false.
Definition qlibrary.cpp:813
bool unload()
Unloads the library and returns true if the library could be unloaded; otherwise returns false.
Definition qlibrary.cpp:843
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
Definition qrhi.h:1804
iterator begin()
Definition qset.h:136
iterator end()
Definition qset.h:140
\inmodule QtCore
Definition qsize.h:25
static QString fromUtf8(QByteArrayView utf8)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qstring.cpp:6018
void start(int msec)
Starts or restarts the timer with a timeout interval of msec milliseconds.
Definition qtimer.cpp:241
EGLContext ctx
QSet< QString >::iterator it
const AVCodec * findAVEncoder(AVCodecID codecId, const std::optional< AVHWDeviceType > &deviceType, const std::optional< PixelOrSampleFormat > &format)
Definition qffmpeg.cpp:433
std::pair< Format, AVScore > findBestAVFormat(const Format *fmts, const CalculateScore &calculateScore)
Definition qffmpeg_p.h:210
AVPixelFormat getFormat(AVCodecContext *codecContext, const AVPixelFormat *suggestedFormats)
bool isHwPixelFormat(AVPixelFormat format)
Definition qffmpeg.cpp:456
static const std::initializer_list< AVHWDeviceType > preferredHardwareAccelerators
QString err2str(int errnum)
Definition qffmpeg_p.h:64
static bool isNoConversionFormat(AVPixelFormat f)
bool isAVFormatSupported(const AVCodec *codec, PixelOrSampleFormat format)
Definition qffmpeg.cpp:445
const AVCodec * findAVDecoder(AVCodecID codecId, const std::optional< AVHWDeviceType > &deviceType, const std::optional< PixelOrSampleFormat > &format)
Definition qffmpeg.cpp:427
constexpr AVScore DefaultAVScore
Definition qffmpeg_p.h:160
static const std::vector< AVHWDeviceType > & deviceTypes()
std::unique_ptr< AVBufferRef, AVDeleter< decltype(&av_buffer_unref), &av_buffer_unref > > AVBufferUPtr
Definition qffmpeg_p.h:148
static AVBufferUPtr loadHWContext(AVHWDeviceType type)
static bool checkHwType(AVHWDeviceType type)
Format findAVFormat(const Format *fmts, const Predicate &predicate)
Definition qffmpeg_p.h:184
std::pair< const AVCodec *, std::unique_ptr< HWAccel > > findCodecWithHwAccel(AVCodecID id, const std::vector< AVHWDeviceType > &deviceTypes, CodecFinder codecFinder, const std::function< bool(const HWAccel &)> &hwAccelPredicate)
constexpr AVScore NotSuitableAVScore
Definition qffmpeg_p.h:161
AVPixelFormat pixelFormatForHwDevice(AVHWDeviceType deviceType)
Definition qffmpeg.cpp:476
static bool precheckDriver(AVHWDeviceType type)
Combined button and popup list for selecting options.
static void * context
EGLConfig config
#define QT_FFMPEG_HAS_D3D12VA
bool thread_local FFmpegLogsEnabledInThread
QMediaFormat::AudioCodec codec
#define qWarning
Definition qlogging.h:166
#define Q_LOGGING_CATEGORY(name,...)
#define qCDebug(category,...)
return ret
GLenum GLuint GLintptr GLsizeiptr size
[1]
GLsizei GLenum GLenum * types
GLenum GLuint id
[7]
GLfloat GLfloat f
GLenum type
GLint GLsizei GLsizei GLenum format
const GLubyte * c
GLuint64EXT * result
[6]
#define Q_ASSERT(cond)
Definition qrandom.cpp:47
QLatin1StringView QLatin1String
Definition qstringfwd.h:31
Q_CORE_EXPORT QByteArray qgetenv(const char *varName)
Q_CORE_EXPORT int qEnvironmentVariableIntValue(const char *varName, bool *ok=nullptr) noexcept
#define Q_UNUSED(x)
QVideoFrameFormat::PixelFormat fmt
static QInputDevice::DeviceType deviceType(const UINT cursorType)
QTimer * timer
[3]
QFrame frame
[0]