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
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
5
6#ifdef Q_OS_WINDOWS
7# include "qffmpeghwaccel_d3d11_p.h"
8# include <QtCore/private/qsystemlibrary_p.h>
9#endif
10
11#include "qffmpeg_p.h"
16
17#include <QtCore/QElapsedTimer>
18
19#ifdef Q_OS_LINUX
20# include "QtCore/qfile.h"
21# include <QLibrary>
22#endif
23
24#include <rhi/qrhi.h>
25#include <qloggingcategory.h>
26#include <unordered_set>
27
28/* Infrastructure for HW acceleration goes into this file. */
29
30QT_BEGIN_NAMESPACE
31
32using namespace Qt::StringLiterals;
33
34Q_STATIC_LOGGING_CATEGORY(qLHWAccel, "qt.multimedia.ffmpeg.hwaccel");
35
36namespace QFFmpeg {
37
39#if defined(Q_OS_ANDROID)
40 AV_HWDEVICE_TYPE_MEDIACODEC,
41#elif defined(Q_OS_LINUX)
42 AV_HWDEVICE_TYPE_CUDA,
43 AV_HWDEVICE_TYPE_VAAPI,
44
45 // TODO: investigate VDPAU advantages.
46 // nvenc/nvdec codecs use AV_HWDEVICE_TYPE_CUDA by default, but they can also use VDPAU
47 // if it's included into the ffmpeg build and vdpau drivers are installed.
48 // AV_HWDEVICE_TYPE_VDPAU
49#elif defined (Q_OS_WIN)
50 AV_HWDEVICE_TYPE_D3D11VA,
51#elif defined (Q_OS_DARWIN)
52 AV_HWDEVICE_TYPE_VIDEOTOOLBOX,
53#endif
54};
55
56static AVBufferUPtr loadHWContext(AVHWDeviceType type)
57{
58 AVBufferRef *hwContext = nullptr;
59 qCDebug(qLHWAccel) << " Checking HW context:" << type;
60 int ret = av_hwdevice_ctx_create(&hwContext, type, nullptr, nullptr, 0);
61
62 if (ret == 0) {
63 qCDebug(qLHWAccel) << " Using above hw context.";
64 return AVBufferUPtr(hwContext);
65 }
66 qCDebug(qLHWAccel) << " Could not create hw context:" << QFFmpeg::AVError(ret);
67 return nullptr;
68}
69
70// FFmpeg might crash on loading non-existing hw devices.
71// Let's roughly precheck drivers/libraries.
72static bool precheckDriver(AVHWDeviceType type)
73{
74 // precheckings might need some improvements
75#if defined(Q_OS_LINUX)
76 if (type == AV_HWDEVICE_TYPE_CUDA) {
77 if (!QFile::exists(QLatin1String("/proc/driver/nvidia/version")))
78 return false;
79
80 // QTBUG-122199
81 // CUDA backend requires libnvcuvid in libavcodec
82 QLibrary lib(u"libnvcuvid.so"_s);
83 if (!lib.load())
84 return false;
85 lib.unload();
86 return true;
87 }
88#elif defined(Q_OS_WINDOWS)
89 if (type == AV_HWDEVICE_TYPE_D3D11VA)
90 return QSystemLibrary(QLatin1String("d3d11.dll")).load();
91
92#if QT_FFMPEG_HAS_D3D12VA
93 if (type == AV_HWDEVICE_TYPE_D3D12VA)
94 return QSystemLibrary(QLatin1String("d3d12.dll")).load();
95#endif
96
97 if (type == AV_HWDEVICE_TYPE_DXVA2)
98 return QSystemLibrary(QLatin1String("d3d9.dll")).load();
99
100 // TODO: check nvenc/nvdec and revisit the checking
101 if (type == AV_HWDEVICE_TYPE_CUDA)
102 return QSystemLibrary(QLatin1String("nvml.dll")).load();
103#else
104 Q_UNUSED(type);
105#endif
106
107 return true;
108}
109
110static bool checkHwType(AVHWDeviceType type)
111{
112 if (!precheckDriver(type)) {
113 qCDebug(qLHWAccel) << "Drivers for hw device" << type << "is not installed";
114 return false;
115 }
116
117#if QT_FFMPEG_HAS_D3D12VA
118 if (type == AV_HWDEVICE_TYPE_D3D12VA)
119 return false; // QTBUG-146635: opening d3d12va codecs fails
120#endif
121
122 if (type == AV_HWDEVICE_TYPE_MEDIACODEC ||
123 type == AV_HWDEVICE_TYPE_VIDEOTOOLBOX ||
124 type == AV_HWDEVICE_TYPE_D3D11VA ||
125#if QT_FFMPEG_HAS_D3D12VA
126 type == AV_HWDEVICE_TYPE_D3D12VA ||
127#endif
128 type == AV_HWDEVICE_TYPE_DXVA2)
129 return true; // Don't waste time; it's expected to work fine if the precheck is OK
130
131 QScopedValueRollback rollback(FFmpegLogsEnabledInThread);
133
134 return loadHWContext(type) != nullptr;
135}
136
138{
139 static const auto types = []() {
140 qCDebug(qLHWAccel) << "Check device types";
141 QElapsedTimer timer;
142 timer.start();
143
144 // gather hw pix formats
145 std::unordered_set<AVPixelFormat> hwPixFormats;
146 for (const Codec codec : CodecEnumerator()) {
147 forEachAVPixelFormat(codec, [&](AVPixelFormat format) {
148 if (isHwPixelFormat(format))
149 hwPixFormats.insert(format);
150 });
151 }
152
153 // create a device types list
154 std::vector<AVHWDeviceType> result;
155 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
156 while ((type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE)
157 if (hwPixFormats.count(pixelFormatForHwDevice(type)) && checkHwType(type))
158 result.push_back(type);
159 result.shrink_to_fit();
160
161 // reorder the list accordingly preferredHardwareAccelerators
162 auto it = result.begin();
163 for (const auto preffered : preferredHardwareAccelerators) {
164 auto found = std::find(it, result.end(), preffered);
165 if (found != result.end())
166 std::rotate(it++, found, std::next(found));
167 }
168
169 using namespace std::chrono;
170 qCDebug(qLHWAccel) << "Device types checked. Spent time:" << duration_cast<microseconds>(timer.durationElapsed());
171
172 return result;
173 }();
174
175 return types;
176}
177
178static std::vector<AVHWDeviceType> deviceTypes(const char *envVarName)
179{
180 const auto definedDeviceTypes = qgetenv(envVarName);
181
182 if (definedDeviceTypes.isNull())
183 return deviceTypes();
184
185 std::vector<AVHWDeviceType> result;
186 const auto definedDeviceTypesString = QString::fromUtf8(definedDeviceTypes).toLower();
187 for (const auto &deviceType : definedDeviceTypesString.split(u',')) {
188 if (!deviceType.isEmpty()) {
189 const auto foundType = av_hwdevice_find_type_by_name(deviceType.toUtf8().data());
190 if (foundType == AV_HWDEVICE_TYPE_NONE)
191 qWarning() << "Unknown hw device type" << deviceType;
192 else
193 result.emplace_back(foundType);
194 }
195 }
196
197 result.shrink_to_fit();
198 return result;
199}
200
201std::pair<std::optional<Codec>, HWAccelUPtr> HWAccel::findDecoderWithHwAccel(AVCodecID id)
202{
203 for (auto type : decodingDeviceTypes()) {
204 const std::optional<Codec> codec = findAVDecoder(id, pixelFormatForHwDevice(type));
205
206 if (!codec)
207 continue;
208
209 qCDebug(qLHWAccel) << "Found potential codec" << codec->name() << "for hw accel" << type
210 << "; Checking the hw device...";
211
212 HWAccelUPtr hwAccel = create(type);
213
214 if (!hwAccel)
215 continue;
216
217 qCDebug(qLHWAccel) << "HW device is OK";
218
219 return { codec, std::move(hwAccel) };
220 }
221
222 qCDebug(qLHWAccel) << "No hw acceleration found for codec id" << id;
223
224 return { std::nullopt, nullptr };
225}
226
227static bool isNoConversionFormat(AVPixelFormat f)
228{
229 bool needsConversion = true;
230 QFFmpegVideoBuffer::toQtPixelFormat(f, &needsConversion);
231 return !needsConversion;
232};
233
234// Used for the AVCodecContext::get_format callback
235AVPixelFormat getFormat(AVCodecContext *codecContext, const AVPixelFormat *fmt)
236{
237 QSpan<const AVPixelFormat> suggestedFormats = makeSpan(fmt);
238 // First check HW accelerated codecs, the HW device context must be set
239 if (codecContext->hw_device_ctx) {
240 auto *device_ctx = (AVHWDeviceContext *)codecContext->hw_device_ctx->data;
241 std::optional<ValueAndScore<AVPixelFormat>> formatAndScore;
242
243 // to be rewritten via findBestAVFormat
244 const Codec codec{ codecContext->codec };
245 for (const AVCodecHWConfig *config : codec.hwConfigs()) {
246 if (!(config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
247 continue;
248
249 if (device_ctx->type != config->device_type)
250 continue;
251
252 const bool isDeprecated = (config->methods & AV_CODEC_HW_CONFIG_METHOD_AD_HOC) != 0;
253 const bool shouldCheckCodecFormats = config->pix_fmt == AV_PIX_FMT_NONE;
254
255 auto scoresGettor = [&](AVPixelFormat format) {
256 // check in supported codec->pix_fmts (avcodec_get_supported_config with
257 // AV_CODEC_CONFIG_PIX_FORMAT since n7.1); no reason to use findAVPixelFormat as
258 // we're already in the hw_config loop
259 const auto pixelFormats = codec.pixelFormats();
260 if (shouldCheckCodecFormats && !ranges::contains(pixelFormats, format))
261 return NotSuitableAVScore;
262
263 if (!shouldCheckCodecFormats && config->pix_fmt != format)
264 return NotSuitableAVScore;
265
266 auto result = DefaultAVScore;
267
268 if (isDeprecated)
269 result -= 10000;
270 if (isHwPixelFormat(format))
271 result += 10;
272
273 return result;
274 };
275
276 const auto found = findBestAVValueWithScore(suggestedFormats, scoresGettor);
277 if (found) {
278 if (!formatAndScore || found->score > formatAndScore->score)
279 formatAndScore = found;
280 }
281 }
282
283 if (formatAndScore) {
284 AVPixelFormat format = formatAndScore->value;
285 TextureConverter::applyDecoderPreset(format, *codecContext);
286 qCDebug(qLHWAccel) << "Selected format" << format << "for hw" << device_ctx->type;
287 return format;
288 }
289 }
290
291 // prefer video formats we can handle directly
292 const auto noConversionFormat = findIf(suggestedFormats, &isNoConversionFormat);
293 if (noConversionFormat) {
294 qCDebug(qLHWAccel) << "Selected format with no conversion" << *noConversionFormat;
295 return *noConversionFormat;
296 }
297
298 const AVPixelFormat format = !suggestedFormats.empty() ? suggestedFormats[0] : AV_PIX_FMT_NONE;
299 qCDebug(qLHWAccel) << "Selected format with conversion" << format;
300
301 // take the native format, this will involve one additional format conversion on the CPU side
302 return format;
303}
304
305HWAccel::~HWAccel() = default;
306
307HWAccelUPtr HWAccel::create(AVHWDeviceType deviceType)
308{
309 if (auto ctx = loadHWContext(deviceType))
310 return HWAccelUPtr(new HWAccel(std::move(ctx)));
311 else
312 return {};
313}
314
315AVPixelFormat HWAccel::format(AVFrame *frame)
316{
317 if (!frame->hw_frames_ctx)
318 return AVPixelFormat(frame->format);
319
320 auto *hwFramesContext = (AVHWFramesContext *)frame->hw_frames_ctx->data;
321 Q_ASSERT(hwFramesContext);
322 return AVPixelFormat(hwFramesContext->sw_format);
323}
324
325QSpan<const AVHWDeviceType> HWAccel::encodingDeviceTypes()
326{
327 static const auto &result = deviceTypes("QT_FFMPEG_ENCODING_HW_DEVICE_TYPES");
328 return result;
329}
330
331QSpan<const AVHWDeviceType> HWAccel::decodingDeviceTypes()
332{
333 static const auto &result = deviceTypes("QT_FFMPEG_DECODING_HW_DEVICE_TYPES");
334 return result;
335}
336
338{
339 return m_hwDeviceContext ? (AVHWDeviceContext *)m_hwDeviceContext->data : nullptr;
340}
341
343{
344 return pixelFormatForHwDevice(deviceType());
345}
346
348{
349 std::call_once(m_constraintsOnceFlag, [this]() {
350 if (auto context = hwDeviceContextAsBuffer())
351 m_constraints.reset(av_hwdevice_get_hwframe_constraints(context, nullptr));
352 });
353
354 return m_constraints.get();
355}
356
357bool HWAccel::matchesSizeContraints(QSize size) const
358{
359 const auto constraints = this->constraints();
360 if (!constraints)
361 return true;
362
363 return size.width() >= constraints->min_width
364 && size.height() >= constraints->min_height
365 && size.width() <= constraints->max_width
366 && size.height() <= constraints->max_height;
367}
368
370{
371 return m_hwDeviceContext ? hwDeviceContext()->type : AV_HWDEVICE_TYPE_NONE;
372}
373
374void HWAccel::createFramesContext(AVPixelFormat swFormat, const QSize &size)
375{
376 if (m_hwFramesContext) {
377 qWarning() << "Frames context has been already created!";
378 return;
379 }
380
381 if (!m_hwDeviceContext)
382 return;
383
384 m_hwFramesContext.reset(av_hwframe_ctx_alloc(m_hwDeviceContext.get()));
385 auto *c = (AVHWFramesContext *)m_hwFramesContext->data;
386 c->format = hwFormat();
387 c->sw_format = swFormat;
388 c->width = size.width();
389 c->height = size.height();
390 qCDebug(qLHWAccel) << "init frames context";
391 int err = av_hwframe_ctx_init(m_hwFramesContext.get());
392 if (err < 0)
393 qWarning() << "failed to init HW frame context" << err << AVError(err);
394 else
395 qCDebug(qLHWAccel) << "Initialized frames context" << size << c->format << c->sw_format;
396}
397
398void HWAccel::updateFramesContext(AVPixelFormat swFormat, const QSize &size)
399{
400 if (m_hwFramesContext) {
401 auto *c = (AVHWFramesContext *)m_hwFramesContext->data;
402 if (c->sw_format != swFormat || QSize(c->width, c->height) != size)
403 m_hwFramesContext.reset();
404 else
405 return;
406 }
407
408 createFramesContext(swFormat, size);
409}
410
411AVHWFramesContext *HWAccel::hwFramesContext() const
412{
413 return m_hwFramesContext ? (AVHWFramesContext *)m_hwFramesContext->data : nullptr;
414}
415
416static void deleteHwFrameContextData(AVHWFramesContext *context)
417{
418 std::unique_ptr<HwFrameContextData> contextData(
419 static_cast<HwFrameContextData *>(context->user_opaque));
420 Q_ASSERT(contextData);
421
422 if (contextData->avDeleter) {
423 context->user_opaque = contextData->avUserOpaque;
424 context->free = contextData->avDeleter;
425
426 context->free(context);
427 }
428}
429
430HwFrameContextData &HwFrameContextData::ensure(AVFrame &hwFrame)
431{
432 Q_ASSERT(hwFrame.hw_frames_ctx && hwFrame.hw_frames_ctx->data);
433
434 auto context = reinterpret_cast<AVHWFramesContext *>(hwFrame.hw_frames_ctx->data);
435
436 if (context->free != deleteHwFrameContextData) {
437 // In most cases, we expect null context->free and context->user_opaque.
438 // However, FFmpeg decoding implementations for specific graphic card backends
439 // may set a custom deleter. Let's save the deleter and its data (user_opaque)
440 // to invoke it in deleteHwFrameContextData.
441 context->user_opaque = new HwFrameContextData{ context->free, context->user_opaque };
442 context->free = deleteHwFrameContextData;
443 } else {
444 Q_ASSERT(context->user_opaque);
445 }
446
447 return *static_cast<HwFrameContextData *>(context->user_opaque);
448}
449
450AVFrameUPtr copyFromHwPool(AVFrameUPtr frame)
451{
452#ifdef Q_OS_WINDOWS
453 return copyFromHwPoolD3D11(std::move(frame));
454#else
455 return frame;
456#endif
457}
458
459} // namespace QFFmpeg
460
461QT_END_NAMESPACE
AVHWFramesContext * hwFramesContext() const
bool matchesSizeContraints(QSize size) const
void createFramesContext(AVPixelFormat swFormat, const QSize &size)
const AVHWFramesConstraints * constraints() const
void updateFramesContext(AVPixelFormat swFormat, const QSize &size)
AVHWDeviceContext * hwDeviceContext() const
AVPixelFormat hwFormat() const
AVHWDeviceType deviceType() const
static bool isNoConversionFormat(AVPixelFormat f)
AVFrameUPtr copyFromHwPool(AVFrameUPtr frame)
QT_MANGLE_NAMESPACE(QMacScreenCaptureStreamDelegate) QMacScreenCaptureStreamDelegate
static const std::vector< AVHWDeviceType > & deviceTypes()
AVPixelFormat getFormat(AVCodecContext *codecContext, const AVPixelFormat *fmt)
static AVBufferUPtr loadHWContext(AVHWDeviceType type)
static bool checkHwType(AVHWDeviceType type)
static void deleteHwFrameContextData(AVHWFramesContext *context)
static bool precheckDriver(AVHWDeviceType type)
static std::vector< AVHWDeviceType > deviceTypes(const char *envVarName)
static const std::initializer_list< AVHWDeviceType > preferredHardwareAccelerators
bool FFmpegLogsEnabledInThread
#define qCDebug(category,...)
#define Q_STATIC_LOGGING_CATEGORY(name,...)
The HwFrameContextData class contains custom belongings of hw frames context.