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
qffmpeg.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 "qffmpeg_p.h"
5
6#include <QtCore/qdebug.h>
7#include <QtCore/qloggingcategory.h>
8#include <QtCore/qscopeguard.h>
9
10extern "C" {
11#include <libavutil/pixdesc.h>
12#include <libavutil/samplefmt.h>
13#include <libavutil/error.h>
14
15#ifdef Q_OS_DARWIN
16#include <libavutil/hwcontext_videotoolbox.h>
17#endif
18}
19
20QT_BEGIN_NAMESPACE
21namespace ranges = QtMultimediaPrivate::ranges;
22
23Q_STATIC_LOGGING_CATEGORY(qLcFFmpegUtils, "qt.multimedia.ffmpeg.utils");
24
25namespace QFFmpeg {
26
27bool isAVFormatSupported(const Codec &codec, PixelOrSampleFormat format)
28{
29 if (codec.type() == AVMEDIA_TYPE_VIDEO) {
30 auto checkFormat = [format](AVPixelFormat f) { return f == format; };
31 return findAVPixelFormat(codec, checkFormat).has_value();
32 }
33
34 if (codec.type() == AVMEDIA_TYPE_AUDIO) {
35 const auto sampleFormats = codec.sampleFormats();
36 return hasValue(sampleFormats, AVSampleFormat(format));
37 }
38
39 return false;
40}
41
42bool isHwPixelFormat(AVPixelFormat format)
43{
44 const auto desc = av_pix_fmt_desc_get(format);
45 return desc && (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) != 0;
46}
47
48void applyExperimentalCodecOptions(const Codec &codec, AVDictionary **opts)
49{
50 if (codec.isExperimental()) {
51 qCWarning(qLcFFmpegUtils) << "Applying the option 'strict -2' for the experimental codec"
52 << codec.name() << ". it's unlikely to work properly";
53 av_dict_set(opts, "strict", "-2", 0);
54 }
55}
56
57AVPixelFormat pixelFormatForHwDevice(AVHWDeviceType deviceType)
58{
59 switch (deviceType) {
60 case AV_HWDEVICE_TYPE_VIDEOTOOLBOX:
61 return AV_PIX_FMT_VIDEOTOOLBOX;
62 case AV_HWDEVICE_TYPE_VAAPI:
63 return AV_PIX_FMT_VAAPI;
64 case AV_HWDEVICE_TYPE_MEDIACODEC:
65 return AV_PIX_FMT_MEDIACODEC;
66 case AV_HWDEVICE_TYPE_CUDA:
67 return AV_PIX_FMT_CUDA;
68 case AV_HWDEVICE_TYPE_VDPAU:
69 return AV_PIX_FMT_VDPAU;
70 case AV_HWDEVICE_TYPE_OPENCL:
71 return AV_PIX_FMT_OPENCL;
72 case AV_HWDEVICE_TYPE_QSV:
73 return AV_PIX_FMT_QSV;
74 case AV_HWDEVICE_TYPE_D3D11VA:
75 return AV_PIX_FMT_D3D11;
76#if QT_FFMPEG_HAS_D3D12VA
77 case AV_HWDEVICE_TYPE_D3D12VA:
78 return AV_PIX_FMT_D3D12;
79#endif
80 case AV_HWDEVICE_TYPE_DXVA2:
81 return AV_PIX_FMT_DXVA2_VLD;
82 case AV_HWDEVICE_TYPE_DRM:
83 return AV_PIX_FMT_DRM_PRIME;
84#if QT_FFMPEG_HAS_VULKAN
85 case AV_HWDEVICE_TYPE_VULKAN:
86 return AV_PIX_FMT_VULKAN;
87#endif
88 default:
89 return AV_PIX_FMT_NONE;
90 }
91}
92
93AVPacketSideData *addStreamSideData(AVStream *stream, AVPacketSideData sideData)
94{
95 QScopeGuard freeData([&sideData]() { av_free(sideData.data); });
96#if QT_FFMPEG_STREAM_SIDE_DATA_DEPRECATED
97 AVPacketSideData *result = av_packet_side_data_add(
98 &stream->codecpar->coded_side_data,
99 &stream->codecpar->nb_coded_side_data,
100 sideData.type,
101 sideData.data,
102 sideData.size,
103 0);
104 if (result) {
105 // If the result is not null, the ownership is taken by AVStream,
106 // otherwise the data must be deleted.
107 freeData.dismiss();
108 return result;
109 }
110#else
111 Q_UNUSED(stream);
112 // TODO: implement for older FFmpeg versions
113 qWarning() << "Adding stream side data is not supported for FFmpeg < 6.1";
114#endif
115
116 return nullptr;
117}
118
119const AVPacketSideData *streamSideData(const AVStream *stream, AVPacketSideDataType type)
120{
121 Q_ASSERT(stream);
122
123#if QT_FFMPEG_STREAM_SIDE_DATA_DEPRECATED
124 return av_packet_side_data_get(stream->codecpar->coded_side_data,
125 stream->codecpar->nb_coded_side_data, type);
126#else
127 auto checkType = [type](const auto &item) { return item.type == type; };
128 const auto end = stream->side_data + stream->nb_side_data;
129 const auto found = ranges::find_if(stream->side_data, end, checkType);
130 return found == end ? nullptr : found;
131#endif
132}
133
134SwrContextUPtr createResampleContext(const AVAudioFormat &inputFormat,
135 const AVAudioFormat &outputFormat)
136{
137 SwrContext *resampler = nullptr;
138#if QT_FFMPEG_HAS_AV_CHANNEL_LAYOUT
139
140#if QT_FFMPEG_SWR_CONST_CH_LAYOUT
141 using AVChannelLayoutPrm = const AVChannelLayout*;
142#else
143 using AVChannelLayoutPrm = AVChannelLayout*;
144#endif
145
146 swr_alloc_set_opts2(&resampler,
147 const_cast<AVChannelLayoutPrm>(&outputFormat.channelLayout),
148 outputFormat.sampleFormat,
149 outputFormat.sampleRate,
150 const_cast<AVChannelLayoutPrm>(&inputFormat.channelLayout),
151 inputFormat.sampleFormat,
152 inputFormat.sampleRate,
153 0,
154 nullptr);
155
156#else
157
158 resampler = swr_alloc_set_opts(nullptr,
159 outputFormat.channelLayoutMask,
160 outputFormat.sampleFormat,
161 outputFormat.sampleRate,
162 inputFormat.channelLayoutMask,
163 inputFormat.sampleFormat,
164 inputFormat.sampleRate,
165 0,
166 nullptr);
167
168#endif
169
170 auto error = QFFmpeg::AVError{
171 swr_init(resampler),
172 };
173 if (error != QFFmpeg::AVError::Success) {
174 qCWarning(qLcFFmpegUtils) << "Failed to initialize audio resampler:" << error;
175 return nullptr;
176 }
177 return SwrContextUPtr(resampler);
178}
179
180QVideoFrameFormat::ColorTransfer fromAvColorTransfer(AVColorTransferCharacteristic colorTrc) {
181 switch (colorTrc) {
182 case AVCOL_TRC_BT709:
183 // The following three cases have transfer characteristics identical to BT709
184 case AVCOL_TRC_BT1361_ECG:
185 case AVCOL_TRC_BT2020_10:
186 case AVCOL_TRC_BT2020_12:
187 case AVCOL_TRC_SMPTE240M: // almost identical to bt709
188 return QVideoFrameFormat::ColorTransfer_BT709;
189 case AVCOL_TRC_GAMMA22:
190 case AVCOL_TRC_SMPTE428: // No idea, let's hope for the best...
191 case AVCOL_TRC_IEC61966_2_1: // sRGB, close enough to 2.2...
192 case AVCOL_TRC_IEC61966_2_4: // not quite, but probably close enough
193 return QVideoFrameFormat::ColorTransfer_Gamma22;
194 case AVCOL_TRC_GAMMA28:
195 return QVideoFrameFormat::ColorTransfer_Gamma28;
196 case AVCOL_TRC_SMPTE170M:
197 return QVideoFrameFormat::ColorTransfer_BT601;
198 case AVCOL_TRC_LINEAR:
199 return QVideoFrameFormat::ColorTransfer_Linear;
200 case AVCOL_TRC_SMPTE2084:
201 return QVideoFrameFormat::ColorTransfer_ST2084;
202 case AVCOL_TRC_ARIB_STD_B67:
203 return QVideoFrameFormat::ColorTransfer_STD_B67;
204 default:
205 break;
206 }
207 return QVideoFrameFormat::ColorTransfer_Unknown;
208}
209
210AVColorTransferCharacteristic toAvColorTransfer(QVideoFrameFormat::ColorTransfer colorTrc)
211{
212 switch (colorTrc) {
213 case QVideoFrameFormat::ColorTransfer_BT709:
214 return AVCOL_TRC_BT709;
215 case QVideoFrameFormat::ColorTransfer_BT601:
216 return AVCOL_TRC_BT709; // which one is the best?
217 case QVideoFrameFormat::ColorTransfer_Linear:
218 return AVCOL_TRC_SMPTE2084;
219 case QVideoFrameFormat::ColorTransfer_Gamma22:
220 return AVCOL_TRC_GAMMA22;
221 case QVideoFrameFormat::ColorTransfer_Gamma28:
222 return AVCOL_TRC_GAMMA28;
223 case QVideoFrameFormat::ColorTransfer_ST2084:
224 return AVCOL_TRC_SMPTE2084;
225 case QVideoFrameFormat::ColorTransfer_STD_B67:
226 return AVCOL_TRC_ARIB_STD_B67;
227 default:
228 return AVCOL_TRC_UNSPECIFIED;
229 }
230}
231
233{
234 switch (colorSpace) {
235 default:
236 case AVCOL_SPC_UNSPECIFIED:
237 case AVCOL_SPC_RESERVED:
238 case AVCOL_SPC_FCC:
239 case AVCOL_SPC_SMPTE240M:
240 case AVCOL_SPC_YCGCO:
241 case AVCOL_SPC_SMPTE2085:
242 case AVCOL_SPC_CHROMA_DERIVED_NCL:
243 case AVCOL_SPC_CHROMA_DERIVED_CL:
244 case AVCOL_SPC_ICTCP: // BT.2100 ICtCp
245 return QVideoFrameFormat::ColorSpace_Undefined;
246 case AVCOL_SPC_RGB:
247 return QVideoFrameFormat::ColorSpace_AdobeRgb;
248 case AVCOL_SPC_BT709:
249 return QVideoFrameFormat::ColorSpace_BT709;
250 case AVCOL_SPC_BT470BG: // BT601
251 case AVCOL_SPC_SMPTE170M: // Also BT601
252 return QVideoFrameFormat::ColorSpace_BT601;
253 case AVCOL_SPC_BT2020_NCL: // Non constant luminence
254 case AVCOL_SPC_BT2020_CL: // Constant luminence
255 return QVideoFrameFormat::ColorSpace_BT2020;
256 }
257}
258
259AVColorSpace toAvColorSpace(QVideoFrameFormat::ColorSpace colorSpace)
260{
261 switch (colorSpace) {
262 case QVideoFrameFormat::ColorSpace_BT601:
263 return AVCOL_SPC_BT470BG;
264 case QVideoFrameFormat::ColorSpace_BT709:
265 return AVCOL_SPC_BT709;
266 case QVideoFrameFormat::ColorSpace_AdobeRgb:
267 return AVCOL_SPC_RGB;
268 case QVideoFrameFormat::ColorSpace_BT2020:
269 return AVCOL_SPC_BT2020_CL;
270 default:
271 return AVCOL_SPC_UNSPECIFIED;
272 }
273}
274
276{
277 switch (colorRange) {
278 case AVCOL_RANGE_MPEG:
279 return QVideoFrameFormat::ColorRange_Video;
280 case AVCOL_RANGE_JPEG:
281 return QVideoFrameFormat::ColorRange_Full;
282 default:
283 return QVideoFrameFormat::ColorRange_Unknown;
284 }
285}
286
287AVColorRange toAvColorRange(QVideoFrameFormat::ColorRange colorRange)
288{
289 switch (colorRange) {
290 case QVideoFrameFormat::ColorRange_Video:
291 return AVCOL_RANGE_MPEG;
292 case QVideoFrameFormat::ColorRange_Full:
293 return AVCOL_RANGE_JPEG;
294 default:
295 return AVCOL_RANGE_UNSPECIFIED;
296 }
297}
298
300 if (!frame)
301 return {};
302 if (!frame->hw_frames_ctx)
303 return {};
304
305 const auto *frameCtx = reinterpret_cast<AVHWFramesContext *>(frame->hw_frames_ctx->data);
306 if (!frameCtx)
307 return {};
308
309 return frameCtx->device_ctx;
310}
311
312SwsContextUPtr createSwsContext(const QSize &srcSize, AVPixelFormat srcPixFmt, const QSize &dstSize,
313 AVPixelFormat dstPixFmt, SwsFlags conversionType)
314{
315
316 SwsContext *result =
317 sws_getContext(srcSize.width(), srcSize.height(), srcPixFmt, dstSize.width(),
318 dstSize.height(), dstPixFmt, conversionType, nullptr, nullptr, nullptr);
319
320 if (!result)
321 qCWarning(qLcFFmpegUtils) << "Cannot create sws context for:\n"
322 << "srcSize:" << srcSize
323 << "srcPixFmt:" << srcPixFmt
324 << "dstSize:" << dstSize
325 << "dstPixFmt:" << dstPixFmt
326 << "conversionType:" << conversionType;
327
328 return SwsContextUPtr(result);
329}
330
331#ifdef Q_OS_DARWIN
333{
335}
336
338{
339 auto formatDescIt = std::make_reverse_iterator(reinterpret_cast<const char *>(&cvFormat));
340 return std::string(formatDescIt - 4, formatDescIt);
341}
342
343#endif
344
345} // namespace QFFmpeg
346
347QDebug operator<<(QDebug dbg, const AVRational &value)
348{
349 dbg << value.num << "/" << value.den;
350 return dbg;
351}
352
353QDebug operator<<(QDebug dbg, const AVDictionary &dict)
354{
355 char *buffer = 0;
356 auto freeBuffer = QScopeGuard([&] {
357 av_free(buffer);
358 });
359
360 int status = av_dict_get_string(&dict, &buffer, '=', ',');
361 if (status < 0 || !buffer)
362 return dbg << "Failed to print AVDictionary";
363
364 dbg << buffer;
365 return dbg;
366}
367
368QDebug operator<<(QDebug dbg, const QFFmpeg::AVDictionaryHolder &dict)
369{
370 const AVDictionary *rawDict = dict.opts;
371 if (rawDict)
372 return dbg << *rawDict;
373 else
374 return dbg << "Empty AVDictionaryHolder";
375}
376
377QDebug operator<<(QDebug dbg, QFFmpeg::AVError error)
378{
379 if (error == QFFmpeg::AVError::Success) {
380 dbg << "Success";
381 return dbg;
382 }
383
384 char errBuf[AV_ERROR_MAX_STRING_SIZE];
385 dbg << av_make_error_string(errBuf, AV_ERROR_MAX_STRING_SIZE, qToUnderlying(error));
386 return dbg;
387}
388
389#if QT_FFMPEG_HAS_AV_CHANNEL_LAYOUT
390QDebug operator<<(QDebug dbg, const AVChannelLayout &layout)
391{
392 dbg << '[';
393 dbg << "nb_channels:" << layout.nb_channels;
394 dbg << ", order:" << layout.order;
395
396 if (layout.order == AV_CHANNEL_ORDER_NATIVE || layout.order == AV_CHANNEL_ORDER_AMBISONIC)
397 dbg << ", mask:" << Qt::bin << layout.u.mask << Qt::dec;
398 else if (layout.order == AV_CHANNEL_ORDER_CUSTOM && layout.u.map)
399 dbg << ", id: " << layout.u.map->id;
400
401 dbg << ']';
402
403 return dbg;
404}
405#endif
406
407#if QT_FFMPEG_HAS_AVCODEC_GET_SUPPORTED_CONFIG
408QDebug operator<<(QDebug dbg, const AVCodecConfig value)
409{
410 switch (value) {
411 case AV_CODEC_CONFIG_CHANNEL_LAYOUT:
412 dbg << "AV_CODEC_CONFIG_CHANNEL_LAYOUT";
413 break;
414 case AV_CODEC_CONFIG_COLOR_RANGE:
415 dbg << "AV_CODEC_CONFIG_COLOR_RANGE";
416 break;
417 case AV_CODEC_CONFIG_COLOR_SPACE:
418 dbg << "AV_CODEC_CONFIG_COLOR_SPACE";
419 break;
420 case AV_CODEC_CONFIG_FRAME_RATE:
421 dbg << "AV_CODEC_CONFIG_FRAME_RATE";
422 break;
423 case AV_CODEC_CONFIG_PIX_FORMAT:
424 dbg << "AV_CODEC_CONFIG_PIX_FORMAT";
425 break;
426 case AV_CODEC_CONFIG_SAMPLE_FORMAT:
427 dbg << "AV_CODEC_CONFIG_SAMPLE_FORMAT";
428 break;
429 case AV_CODEC_CONFIG_SAMPLE_RATE:
430 dbg << "AV_CODEC_CONFIG_SAMPLE_RATE";
431 break;
432 default:
433 dbg << "<UNKNOWN_CODEC_CONFIG>";
434 break;
435 }
436
437 return dbg;
438}
439#endif
440
441QT_END_NAMESPACE
AVColorSpace toAvColorSpace(QVideoFrameFormat::ColorSpace colorSpace)
Definition qffmpeg.cpp:259
SwsContextUPtr createSwsContext(const QSize &srcSize, AVPixelFormat srcPixFmt, const QSize &dstSize, AVPixelFormat dstPixFmt, SwsFlags conversionType)
Definition qffmpeg.cpp:312
void applyExperimentalCodecOptions(const Codec &codec, AVDictionary **opts)
Definition qffmpeg.cpp:48
bool isHwPixelFormat(AVPixelFormat format)
Definition qffmpeg.cpp:42
AVPacketSideData * addStreamSideData(AVStream *stream, AVPacketSideData sideData)
Definition qffmpeg.cpp:93
AVHWDeviceContext * avFrameDeviceContext(const AVFrame *frame)
Definition qffmpeg.cpp:299
AVColorTransferCharacteristic toAvColorTransfer(QVideoFrameFormat::ColorTransfer colorTrc)
Definition qffmpeg.cpp:210
std::conditional_t< QT_FFMPEG_AVIO_WRITE_CONST, const uint8_t *, uint8_t * > AvioWriteBufferType
QVideoFrameFormat::ColorSpace fromAvColorSpace(AVColorSpace colorSpace)
Definition qffmpeg.cpp:232
bool isAVFormatSupported(const Codec &codec, PixelOrSampleFormat format)
Definition qffmpeg.cpp:27
QVideoFrameFormat::ColorTransfer fromAvColorTransfer(AVColorTransferCharacteristic colorTrc)
Definition qffmpeg.cpp:180
QVideoFrameFormat::ColorRange fromAvColorRange(AVColorRange colorRange)
Definition qffmpeg.cpp:275
SwrContextUPtr createResampleContext(const AVAudioFormat &inputFormat, const AVAudioFormat &outputFormat)
Definition qffmpeg.cpp:134
AVPixelFormat pixelFormatForHwDevice(AVHWDeviceType deviceType)
Definition qffmpeg.cpp:57
const AVPacketSideData * streamSideData(const AVStream *stream, AVPacketSideDataType type)
Definition qffmpeg.cpp:119
AVColorRange toAvColorRange(QVideoFrameFormat::ColorRange colorRange)
Definition qffmpeg.cpp:287
QDebug operator<<(QDebug dbg, const QFFmpeg::AVDictionaryHolder &dict)
Definition qffmpeg.cpp:368
QDebug operator<<(QDebug dbg, QFFmpeg::AVError error)
Definition qffmpeg.cpp:377
QDebug operator<<(QDebug dbg, const QFileInfo &fi)
QT_BEGIN_NAMESPACE Q_STATIC_LOGGING_CATEGORY(lcSynthesizedIterableAccess, "qt.iterable.synthesized", QtWarningMsg)