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
qffmpegcodeccontext.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 "playbackengine/qffmpegcodeccontext_p.h"
6
7#include <QtMultimedia/qplaybackoptions.h>
8#include <QtCore/qloggingcategory.h>
9
11
12using namespace Qt::StringLiterals;
13
14Q_STATIC_LOGGING_CATEGORY(qLcPlaybackEngineCodec, "qt.multimedia.playbackengine.codec");
15
16namespace QFFmpeg {
17
19
20void PlaybackCodecContextDeleter::operator()(AVCodecContext *context) const
21{
22 if (!context)
23 return;
24
25 Q_ASSERT(m_state && m_state->context == context && context->opaque == m_state.get());
26 const Finalizer finalizer = m_state->finalizer;
27 m_state->finalizer = nullptr;
28 if (finalizer)
29 finalizer(context);
30
31 context->opaque = nullptr;
32 avcodec_free_context(&context);
33}
34
35void PlaybackCodecContextDeleter::attach(AVCodecContext *context) const
36{
37 if (!context)
38 return;
39
40 Q_ASSERT(context->opaque == nullptr);
41 m_state->context = context;
42 // AVCodecContext::opaque is reserved for this playback finalizer state.
43 context->opaque = m_state.get();
44}
45
46void PlaybackCodecContextDeleter::setFinalizer(AVCodecContext *context, Finalizer finalizer)
47{
48 Q_ASSERT(context && context->opaque);
49 auto *state = static_cast<State *>(context->opaque);
50 Q_ASSERT(state->context == context && !state->finalizer && finalizer);
51 state->finalizer = finalizer;
52}
53
55{
56 PlaybackCodecContextUPtr context{ avcodec_alloc_context3(codec),
58 context.get_deleter().attach(context.get());
59 return context;
60}
61
62CodecContext::Data::Data(PlaybackCodecContextUPtr context, AVStream *avStream,
63 AVFormatContext *avFormatContext, std::unique_ptr<HWAccel> hwAccel)
64 : context(std::move(context)),
65 stream(avStream),
66 formatContext(avFormatContext),
67 hwAccel(std::move(hwAccel))
68{
69 if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
70 pixelAspectRatio = av_guess_sample_aspect_ratio(formatContext, stream, nullptr);
71}
72
73q23::expected<CodecContext, QString> CodecContext::create(AVStream *stream,
74 AVFormatContext *formatContext,
75 const QPlaybackOptions &options)
76{
77 if (!stream)
78 return q23::unexpected{ u"Invalid stream"_s };
79
80 if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
81 auto hwCodec = create(stream, formatContext, options, Hw);
82 if (hwCodec)
83 return hwCodec;
84
85 qCInfo(qLcPlaybackEngineCodec) << hwCodec.error();
86 }
87
88 auto context = create(stream, formatContext, options, Sw);
89 if (!context)
90 qCWarning(qLcPlaybackEngineCodec) << context.error();
91
92 return context;
93}
94
96{
97 // does the same as av_guess_sample_aspect_ratio, but more efficient
98 return d->pixelAspectRatio.num && d->pixelAspectRatio.den ? d->pixelAspectRatio
99 : frame->sample_aspect_ratio;
100}
101
102q23::expected<CodecContext, QString> CodecContext::create(AVStream *stream,
103 AVFormatContext *formatContext,
104 const QPlaybackOptions &options,
105 VideoCodecCreationPolicy videoCodecPolicy)
106{
107 Q_ASSERT(stream);
108
109 if (videoCodecPolicy == Hw && stream->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
110 Q_ASSERT(!"Codec::create has been called with Hw policy on a non-video stream");
111
112 std::optional<Codec> decoder;
113 std::unique_ptr<QFFmpeg::HWAccel> hwAccel;
114
115 if (videoCodecPolicy == Hw)
116 std::tie(decoder, hwAccel) = HWAccel::findDecoderWithHwAccel(stream->codecpar->codec_id);
117 else
118 decoder = QFFmpeg::findAVDecoder(stream->codecpar->codec_id);
119
120 if (!decoder)
121 return q23::unexpected{ u"No %1 decoder found"_s.arg(videoCodecPolicy == Hw ? "HW"
122 : "SW") };
123
124 qCDebug(qLcPlaybackEngineCodec)
125 << "found decoder" << decoder->name() << "for id" << decoder->id();
126
127 PlaybackCodecContextUPtr context = createPlaybackCodecContext(decoder->get());
128 if (!context)
129 return q23::unexpected{ u"Failed to allocate a FFmpeg codec context"_s };
130
131 // Use HW decoding even if the codec level doesn't match the reported capabilities
132 // of the hardware. FFmpeg documentation recommendeds setting this flag by default.
133 context->hwaccel_flags |= AV_HWACCEL_FLAG_IGNORE_LEVEL;
134
135 static const bool allowProfileMismatch = static_cast<bool>(
136 qEnvironmentVariableIntValue("QT_FFMPEG_HW_ALLOW_PROFILE_MISMATCH"));
137 if (allowProfileMismatch) {
138 // Use HW decoding even if the codec profile doesn't match the reported capabilities
139 // of the hardware.
140 context->hwaccel_flags |= AV_HWACCEL_FLAG_ALLOW_PROFILE_MISMATCH;
141 }
142
143 if (hwAccel)
144 context->hw_device_ctx = av_buffer_ref(hwAccel->hwDeviceContextAsBuffer());
145
146 if (context->codec_type != AVMEDIA_TYPE_AUDIO && context->codec_type != AVMEDIA_TYPE_VIDEO
147 && context->codec_type != AVMEDIA_TYPE_SUBTITLE) {
148 return q23::unexpected{ u"Unknown codec type"_s };
149 }
150
151 int ret = avcodec_parameters_to_context(context.get(), stream->codecpar);
152 if (ret < 0)
153 return q23::unexpected{
154 QStringLiteral("Failed to set FFmpeg codec parameters: %1").arg(err2str(ret))
155 };
156
157 // Required so that decoders can rescale packet-side timestamps (e.g. when
158 // trimming AAC/Opus priming/padding samples signalled via skip_samples).
159 context->pkt_timebase = stream->time_base;
160
161 // ### This still gives errors about wrong HW formats (as we accept all of them)
162 // But it would be good to get so we can filter out pixel format we don't support natively
163 context->get_format = QFFmpeg::getFormat;
164
165 /* Init the decoder, with reference counting and threading */
166 AVDictionaryHolder opts;
167 if (options.playbackIntent() == QPlaybackOptions::PlaybackIntent::LowLatencyStreaming)
168 av_dict_set(opts, "flags", "low_delay", 0);
169
170 av_dict_set(opts, "refcounted_frames", "1", 0);
171 av_dict_set(opts, "threads", "auto", 0);
172 applyExperimentalCodecOptions(*decoder, opts);
173
174 ret = avcodec_open2(context.get(), decoder->get(), opts);
175
176 if (ret < 0)
177 return q23::unexpected{
178 QStringLiteral("Failed to open FFmpeg codec context: %1").arg(err2str(ret))
179 };
180
181 return CodecContext(new Data(std::move(context), stream, formatContext, std::move(hwAccel)));
182}
183
185
186} // namespace QFFmpeg
AVRational pixelAspectRatio(AVFrame *frame) const
The QPlaybackOptions class enables low-level control of media playback options.
PlaybackCodecContextUPtr createPlaybackCodecContext(const AVCodec *codec)
Combined button and popup list for selecting options.
QT_BEGIN_NAMESPACE Q_STATIC_LOGGING_CATEGORY(lcSynthesizedIterableAccess, "qt.iterable.synthesized", QtWarningMsg)
void attach(AVCodecContext *context) const
void operator()(AVCodecContext *context) const