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
qavfsamplebufferdelegate.mm
Go to the documentation of this file.
1// Copyright (C) 2022 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 <QtFFmpegMediaPluginImpl/private/qavfsamplebufferdelegate_p.h>
5
6#define AVMediaType XAVMediaType
7extern "C" {
8#include <libavutil/hwcontext_videotoolbox.h>
9} // extern "C"
10#undef AVMediaType
11
12#include <QtCore/qloggingcategory.h>
13#include <QtCore/qsize.h>
14
15#include <QtMultimedia/private/qavfhelpers_p.h>
16#include <QtMultimedia/private/qvideoframe_p.h>
17
18#include <QtFFmpegMediaPluginImpl/private/qcvimagevideobuffer_p.h>
19#include <QtFFmpegMediaPluginImpl/private/qffmpegdarwinhwframehelpers_p.h>
20#define AVMediaType XAVMediaType
21#include <QtFFmpegMediaPluginImpl/private/qffmpegvideobuffer_p.h>
22#include <QtFFmpegMediaPluginImpl/private/qffmpeghwaccel_p.h>
23#undef AVMediaType
24
25#include <chrono>
26#include <optional>
27
28Q_STATIC_LOGGING_CATEGORY(qLcAvfSampleBufferDelegate, "qt.multimedia.avf.samplebufferdelegate");
29
30using namespace Qt::StringLiterals;
31
32QT_USE_NAMESPACE
33
34@implementation QT_MANGLE_NAMESPACE(QAVFSampleBufferDelegate) {
35@private
36 std::function<void(const QVideoFrame &)> frameHandler;
37 QFFmpeg::QAVFSampleBufferDelegateTransformProvider transformationProvider;
38 std::unique_ptr<QFFmpeg::HWAccel> m_accel;
39 std::optional<std::chrono::microseconds> baseTime;
40 std::optional<qreal> frameRate;
41}
42
43- (instancetype)initWithFrameHandler:(std::function<void(const QVideoFrame &)>)handler
44{
45 if (!(self = [super init]))
46 return nil;
47
48 Q_ASSERT(handler);
49
50 frameHandler = std::move(handler);
51 return self;
52}
53
54- (void)discardFutureSamples
55{
56 frameHandler = nullptr;
57}
58
59- (void)setTransformationProvider:
60 (const QFFmpeg::QAVFSampleBufferDelegateTransformProvider &)provider
61{
62 transformationProvider = std::move(provider);
63}
64
65- (void)captureOutput:(AVCaptureOutput *)captureOutput
66 didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
67 fromConnection:(AVCaptureConnection *)connection
68{
69 Q_UNUSED(captureOutput);
70
71 if (!frameHandler)
72 return;
73
74 CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
75 if (!imageBuffer || CFGetTypeID(imageBuffer) != CVPixelBufferGetTypeID()) {
76 qWarning() << "Cannot get image buffer from sample buffer";
77 return;
78 }
79
80 auto pixelBuffer = QAVFHelpers::QSharedCVPixelBuffer(
81 imageBuffer,
82 QAVFHelpers::QSharedCVPixelBuffer::RefMode::NeedsRef);
83
84 // The incoming buffer is recycled from a pool owned by AVFoundation, so we
85 // copy it into a free-standing CVPixelBuffer that we fully own before
86 // keeping it around in a QVideoFrame.
87 q23::expected<QAVFHelpers::QSharedCVPixelBuffer, QString> copyResult =
88 QFFmpeg::deepCopyCvPixelBuffer(pixelBuffer.get());
89 if (!copyResult) {
90 qCWarning(qLcAvfSampleBufferDelegate)
91 << "Failed to copy incoming pixel buffer:" << copyResult.error();
92 return;
93 }
94 pixelBuffer = std::move(*copyResult);
95
96 QSize incomingFrameSize = QAVFHelpers::CVPixelBufferSize(pixelBuffer.get());
97 Q_ASSERT(!incomingFrameSize.isEmpty());
98 CvPixelFormat incomingCvPixelFormat = CVPixelBufferGetPixelFormatType(pixelBuffer.get());
99
100 Q_ASSERT(m_accel);
101 m_accel->updateFramesContext(
102 av_map_videotoolbox_format_to_pixfmt(incomingCvPixelFormat),
103 incomingFrameSize);
104
105 std::chrono::microseconds frameTime =
106 QAVFHelpers::CMTimeToMicroseconds(CMSampleBufferGetPresentationTimeStamp(sampleBuffer));
107 if (!baseTime)
108 baseTime = frameTime;
109 const std::chrono::microseconds presentationTime = frameTime - *baseTime;
110
111 QVideoFrameFormat format = QAVFHelpers::videoFormatForImageBuffer(pixelBuffer.get());
112 if (!format.isValid()) {
113 qWarning() << "Cannot get get video format for image buffer"
114 << QAVFHelpers::CVPixelBufferSize(pixelBuffer.get());
115 return;
116 }
117
118 std::optional<QFFmpeg::QAVFSampleBufferDelegateTransform> transform;
119 if (transformationProvider) {
120 transform = transformationProvider(connection);
121 const VideoTransformation &surfaceTransform = transform.value().surfaceTransform;
122 format.setRotation(surfaceTransform.rotation);
123 format.setMirrored(surfaceTransform.mirroredHorizontallyAfterRotation);
124 }
125
126 if (frameRate)
127 format.setStreamFrameRate(*frameRate);
128
129 QVideoFrame frame;
130 q23::expected<QVideoFrame, QString> frameResult = QFFmpeg::qVideoFrameFromCvPixelBuffer(
131 *m_accel,
132 presentationTime,
133 pixelBuffer,
134 format);
135 if (!frameResult)
136 qCWarning(qLcAvfSampleBufferDelegate) << frameResult.error();
137 else
138 frame = *frameResult;
139
140 if (!frame.isValid())
141 frame = QVideoFramePrivate::createFrame(
142 std::make_unique<QFFmpeg::CVImageVideoBuffer>(std::move(pixelBuffer)),
143 std::move(format));
144
145 if (transform.has_value()) {
146 const VideoTransformation &presentationTransform = transform.value().presentationTransform;
147 frame.setRotation(presentationTransform.rotation);
148 frame.setMirrored(presentationTransform.mirroredHorizontallyAfterRotation);
149 }
150
151 frame.setStartTime(presentationTime.count());
152 if (frameRate) {
153 using namespace std::chrono;
154 const auto frameDuration = round<microseconds>(duration<double>(1.0 / *frameRate));
155 frame.setEndTime((presentationTime + frameDuration).count());
156 } else {
157 frame.setEndTime(-1);
158 }
159
160 frameHandler(frame);
161}
162
163// Sets the initial HWAccel. Should only be called once during
164// initialization.
165- (void)setHWAccel:(std::unique_ptr<QFFmpeg::HWAccel> &&)accel
166{
167 m_accel = std::move(accel);
168}
169
170- (void)setVideoFormatFrameRate:(qreal)rate
171{
172 if (rate > 0)
173 frameRate = rate;
174 else
175 frameRate.reset();
176}
177
178@end
QT_BEGIN_NAMESPACE Q_STATIC_LOGGING_CATEGORY(lcSynthesizedIterableAccess, "qt.iterable.synthesized", QtWarningMsg)