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 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
278 if (found.score > formatAndScore.score)
279 formatAndScore = found;
280 }
281
282 const auto format = formatAndScore.value;
283 if (format) {
284 TextureConverter::applyDecoderPreset(*format, *codecContext);
285 qCDebug(qLHWAccel) << "Selected format" << *format << "for hw" << device_ctx->type;
286 return *format;
287 }
288 }
289
290 // prefer video formats we can handle directly
291 const auto noConversionFormat = findIf(suggestedFormats, &isNoConversionFormat);
292 if (noConversionFormat) {
293 qCDebug(qLHWAccel) << "Selected format with no conversion" << *noConversionFormat;
294 return *noConversionFormat;
295 }
296
297 const AVPixelFormat format = !suggestedFormats.empty() ? suggestedFormats[0] : AV_PIX_FMT_NONE;
298 qCDebug(qLHWAccel) << "Selected format with conversion" << format;
299
300 // take the native format, this will involve one additional format conversion on the CPU side
301 return format;
302}
303
304HWAccel::~HWAccel() = default;
305
306HWAccelUPtr HWAccel::create(AVHWDeviceType deviceType)
307{
308 if (auto ctx = loadHWContext(deviceType))
309 return HWAccelUPtr(new HWAccel(std::move(ctx)));
310 else
311 return {};
312}
313
314AVPixelFormat HWAccel::format(AVFrame *frame)
315{
316 if (!frame->hw_frames_ctx)
317 return AVPixelFormat(frame->format);
318
319 auto *hwFramesContext = (AVHWFramesContext *)frame->hw_frames_ctx->data;
320 Q_ASSERT(hwFramesContext);
321 return AVPixelFormat(hwFramesContext->sw_format);
322}
323
324const std::vector<AVHWDeviceType> &HWAccel::encodingDeviceTypes()
325{
326 static const auto &result = deviceTypes("QT_FFMPEG_ENCODING_HW_DEVICE_TYPES");
327 return result;
328}
329
330const std::vector<AVHWDeviceType> &HWAccel::decodingDeviceTypes()
331{
332 static const auto &result = deviceTypes("QT_FFMPEG_DECODING_HW_DEVICE_TYPES");
333 return result;
334}
335
337{
338 return m_hwDeviceContext ? (AVHWDeviceContext *)m_hwDeviceContext->data : nullptr;
339}
340
342{
343 return pixelFormatForHwDevice(deviceType());
344}
345
347{
348 std::call_once(m_constraintsOnceFlag, [this]() {
349 if (auto context = hwDeviceContextAsBuffer())
350 m_constraints.reset(av_hwdevice_get_hwframe_constraints(context, nullptr));
351 });
352
353 return m_constraints.get();
354}
355
356bool HWAccel::matchesSizeContraints(QSize size) const
357{
358 const auto constraints = this->constraints();
359 if (!constraints)
360 return true;
361
362 return size.width() >= constraints->min_width
363 && size.height() >= constraints->min_height
364 && size.width() <= constraints->max_width
365 && size.height() <= constraints->max_height;
366}
367
369{
370 return m_hwDeviceContext ? hwDeviceContext()->type : AV_HWDEVICE_TYPE_NONE;
371}
372
373void HWAccel::createFramesContext(AVPixelFormat swFormat, const QSize &size)
374{
375 if (m_hwFramesContext) {
376 qWarning() << "Frames context has been already created!";
377 return;
378 }
379
380 if (!m_hwDeviceContext)
381 return;
382
383 m_hwFramesContext.reset(av_hwframe_ctx_alloc(m_hwDeviceContext.get()));
384 auto *c = (AVHWFramesContext *)m_hwFramesContext->data;
385 c->format = hwFormat();
386 c->sw_format = swFormat;
387 c->width = size.width();
388 c->height = size.height();
389 qCDebug(qLHWAccel) << "init frames context";
390 int err = av_hwframe_ctx_init(m_hwFramesContext.get());
391 if (err < 0)
392 qWarning() << "failed to init HW frame context" << err << AVError(err);
393 else
394 qCDebug(qLHWAccel) << "Initialized frames context" << size << c->format << c->sw_format;
395}
396
397void HWAccel::updateFramesContext(AVPixelFormat swFormat, const QSize &size)
398{
399 if (m_hwFramesContext) {
400 auto *c = (AVHWFramesContext *)m_hwFramesContext->data;
401 if (c->sw_format != swFormat || QSize(c->width, c->height) != size)
402 m_hwFramesContext.reset();
403 else
404 return;
405 }
406
407 createFramesContext(swFormat, size);
408}
409
410AVHWFramesContext *HWAccel::hwFramesContext() const
411{
412 return m_hwFramesContext ? (AVHWFramesContext *)m_hwFramesContext->data : nullptr;
413}
414
415static void deleteHwFrameContextData(AVHWFramesContext *context)
416{
417 std::unique_ptr<HwFrameContextData> contextData(
418 static_cast<HwFrameContextData *>(context->user_opaque));
419 Q_ASSERT(contextData);
420
421 if (contextData->avDeleter) {
422 context->user_opaque = contextData->avUserOpaque;
423 context->free = contextData->avDeleter;
424
425 context->free(context);
426 }
427}
428
429HwFrameContextData &HwFrameContextData::ensure(AVFrame &hwFrame)
430{
431 Q_ASSERT(hwFrame.hw_frames_ctx && hwFrame.hw_frames_ctx->data);
432
433 auto context = reinterpret_cast<AVHWFramesContext *>(hwFrame.hw_frames_ctx->data);
434
435 if (context->free != deleteHwFrameContextData) {
436 // In most cases, we expect null context->free and context->user_opaque.
437 // However, FFmpeg decoding implementations for specific graphic card backends
438 // may set a custom deleter. Let's save the deleter and its data (user_opaque)
439 // to invoke it in deleteHwFrameContextData.
440 context->user_opaque = new HwFrameContextData{ context->free, context->user_opaque };
441 context->free = deleteHwFrameContextData;
442 } else {
443 Q_ASSERT(context->user_opaque);
444 }
445
446 return *static_cast<HwFrameContextData *>(context->user_opaque);
447}
448
449AVFrameUPtr copyFromHwPool(AVFrameUPtr frame)
450{
451#ifdef Q_OS_WINDOWS
452 return copyFromHwPoolD3D11(std::move(frame));
453#else
454 return frame;
455#endif
456}
457
458} // namespace QFFmpeg
459
460QT_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
QT_BEGIN_NAMESPACE bool FFmpegLogsEnabledInThread
#define qCDebug(category,...)
#define Q_STATIC_LOGGING_CATEGORY(name,...)
The HwFrameContextData class contains custom belongings of hw frames context.