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
qsckscreencapture.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
5
6#include <QtCore/qthread.h>
7
8#include <QtFFmpegMediaPluginImpl/private/qffmpegmediacapturesession_p.h>
9#include <QtFFmpegMediaPluginImpl/private/qmacscreencapturekit_p.h>
10
11#include <QtMultimedia/private/qmultimedia_ranges_p.h>
12
13#include <QtGui/qscreen.h>
14
15#define AVMediaType XAVMediaType
16extern "C" {
17#include <libavutil/hwcontext_videotoolbox.h>
18}
19#undef AVMediaType
20
21#import <AppKit/NSScreen.h>
22
23#include <algorithm>
24
25namespace ranges = QtMultimediaPrivate::ranges;
26using namespace Qt::Literals::StringLiterals;
27
28QT_BEGIN_NAMESPACE
29
30namespace QFFmpeg {
31
33{
34#if QT_MACOS_PLATFORM_SDK_EQUAL_OR_ABOVE(260000)
35 if (@available(macOS 26.0, *))
36 return screen.CGDirectDisplayID;
37#endif
38
39 NSNumber *screenNumber = screen.deviceDescription[@"NSScreenNumber"];
40 return static_cast<CGDirectDisplayID>(screenNumber.unsignedIntValue);
41}
42
43[[nodiscard]] static q23::expected<AVFScopedPointer<SCDisplay>, QString> findScDisplay(CGDirectDisplayID input)
44{
45 // Do a blocking enumeration of capturable items.
46 q23::expected<QMacScreenCaptureKit::CapturableItems, QString> enumerateResult =
47 QMacScreenCaptureKit::enumerateCapturableItems()
48 .get();
49
50 if (!enumerateResult)
51 return q23::unexpected{ std::move(enumerateResult.error()) };
52
53 const std::vector<AVFScopedPointer<SCDisplay>> &displays = enumerateResult->displays;
54 auto it = ranges::find_if(
55 displays,
56 [&](const AVFScopedPointer<SCDisplay> &item) {
57 return item.data().displayID == input;
58 });
59 if (it == displays.end())
60 return q23::unexpected(u"Display not found"_s);
61
62 // AVFScopedPointer doesn't have shared-ptr semantics, force a reference increment.
63 return AVFScopedPointer<SCDisplay>{ [it->data() retain] };
64}
65
67 QSckScreenCapture &screenCapture,
68 const QMacScreenCaptureKit &macScreenCaptureKit)
69{
70 // Direct connection so application developers can respond to frame directly
71 // from background thread.
72 // Remaining frames are always flushed whenever we go inactive, as a result
73 // of QMacScreenCaptureKit doing so in the destructor. Because we flush,
74 // we trust the application developer to not block the background thread.
75 QObject::connect(
76 &macScreenCaptureKit,
77 &QMacScreenCaptureKit::newVideoFrameGenerated,
78 &screenCapture,
79 [&screenCapture](QMacScreenCaptureKit::StreamId, QVideoFrame videoFrame) {
80 emit screenCapture.newVideoFrame(videoFrame);
81 },
82 Qt::DirectConnection);
83
84 QObject::connect(
85 &macScreenCaptureKit,
86 &QMacScreenCaptureKit::newVideoFrameGenerated,
87 &screenCapture,
88 [&screenCapture](QMacScreenCaptureKit::StreamId streamId, QVideoFrame newFrame) {
89 screenCapture.onNewFrameFormatReceived(streamId, newFrame.surfaceFormat());
90 },
91 Qt::QueuedConnection);
92
93 QObject::connect(
94 &macScreenCaptureKit,
95 &QMacScreenCaptureKit::streamStoppedWithError,
96 &screenCapture,
97 &QSckScreenCapture::onStreamStoppedWithErrorEvent,
98 Qt::QueuedConnection);
99}
100
101
102QSckScreenCapture::QSckScreenCapture() : QPlatformSurfaceCapture(ScreenSource{})
103{
104}
105
106void QSckScreenCapture::setCaptureSession(QPlatformMediaCaptureSession *sessionIn)
107{
108 if (!sessionIn) {
109 m_session = nullptr;
110 return;
111 }
112
113 auto *session = qobject_cast<QFFmpegMediaCaptureSession *>(sessionIn);
114 Q_ASSERT(session);
115 m_session = session;
116}
117
119{
120 struct ErrorPair {
121 QPlatformSurfaceCapture::Error err;
122 QString msg;
123 };
124
125 using TryStartResult = q23::expected<std::unique_ptr<ActiveData>, ErrorPair>;
126
127 auto tryStartStream = [&]() -> TryStartResult {
128 ScreenSource screen = QPlatformSurfaceCapture::source<ScreenSource>();
129 if (!QPlatformSurfaceCapture::checkScreenWithError(screen)) {
130 return q23::unexpected{ ErrorPair {
131 QPlatformSurfaceCapture::Error::NotFound,
132 u"Could not find selected screen"_s } };
133 }
134
135 auto *cocoaScreen = screen->nativeInterface<QNativeInterface::QCocoaScreen>();
136 if (!cocoaScreen) {
137 qCWarning(qLcMacScreenCapture)
138 << "Failed to grab QNativeInterface::QCocoaScreen from QScreen";
139 return q23::unexpected{ ErrorPair{
140 QPlatformSurfaceCapture::Error::CaptureFailed,
141 u"Failed to start stream due to unknown issue"_s } };
142 }
143
144 CGDirectDisplayID cgDisplayId = displayIDForScreen(cocoaScreen->nativeScreen());
145
146 q23::expected<AVFScopedPointer<SCDisplay>, QString> scDisplayResult = findScDisplay(cgDisplayId);
147 if (!scDisplayResult) {
148 qCWarning(qLcMacScreenCapture)
149 << "Could not find associated SCDisplay:"
150 << scDisplayResult.error();
151 return q23::unexpected{ ErrorPair {
152 QPlatformSurfaceCapture::Error::NotFound,
153 u"Backend was unable to find selected QScreen"_s } };
154 }
155
156 QMacScreenCaptureKit::StreamId newStreamId = allocateStreamId();
157
158 AVFScopedPointer<SCDisplay> &scDisplay = *scDisplayResult;
159
160 auto setupConnections = [&](QMacScreenCaptureKit &newObject) {
161 setupQMacScreenCaptureKitConnections(*this, newObject);
162 };
163
164 if (m_session)
165 m_session->onSourceActivating(*this);
166
167 // Start and wait for the stream to start. Blocking operation.
168 using ResultType = q23::expected<std::unique_ptr<QMacScreenCaptureKit>, QString>;
169 std::future<ResultType> streamResultFuture = QMacScreenCaptureKit::createStreamFromDisplay(
170 newStreamId,
171 scDisplay.data(),
172 frameRate(),
173 setupConnections);
174 ResultType streamResult = streamResultFuture.get();
175 if (!streamResult) {
176 if (m_session)
177 m_session->onSourceActivationFailure(*this);
178
179 qCWarning(qLcMacScreenCapture)
180 << "Failed to start screen capture stream: "
181 << streamResult.error();
182 return q23::unexpected{ ErrorPair{
183 QPlatformSurfaceCapture::Error::CaptureFailed,
184 u"Failed to start stream due to unknown issue"_s } };
185 }
186
187 std::unique_ptr<QMacScreenCaptureKit> &macScreenCaptureKit = *streamResult;
188
189 auto newActiveData = std::make_unique<ActiveData>();
190 newActiveData->macScreenCaptureKit = std::move(macScreenCaptureKit);
191 newActiveData->scDisplay = std::move(scDisplay);
192 newActiveData->streamId = newStreamId;
193 return newActiveData;
194 };
195
196 if (active) {
197 Q_ASSERT(!m_activeData);
198
199 TryStartResult result = tryStartStream();
200 if (!result) {
201 const ErrorPair &error = result.error();
202 QPlatformSurfaceCapture::updateError(error.err, error.msg);
203 return false;
204 }
205
206 m_activeData = std::move(*result);
207 } else {
208 m_activeData.reset();
209 }
210
211 return true;
212}
213
215 QMacScreenCaptureKit::StreamId incomingStreamId,
216 QVideoFrameFormat const &format)
217{
218 Q_ASSERT(thread()->isCurrentThread());
219 if (activeStreamId() == incomingStreamId)
220 m_videoFrameFormat = format;
221}
222
224 QMacScreenCaptureKit::StreamId incomingStreamId,
225 const QString &err)
226{
227 Q_ASSERT(thread()->isCurrentThread());
228
229 qCDebug(qLcMacScreenCapture)
230 << "Stream with ID"
231 << static_cast<int64_t>(incomingStreamId)
232 << "stopped with error:"
233 << err;
234
235 if (activeStreamId() != incomingStreamId)
236 return;
237
238 // Possible improvement may be to propagate signal up to QVideoSource
239 // that we are no longer active.
240 m_activeData.reset();
241 m_videoFrameFormat.reset();
242
243 QPlatformSurfaceCapture::updateError(
244 Error::CaptureFailed,
245 u"The capture stream was closed by the system"_s);
246}
247
249{
250 Q_ASSERT(thread()->isCurrentThread());
251
252 if (m_videoFrameFormat)
253 return *m_videoFrameFormat;
254 return {};
255}
256
258{
259 Q_ASSERT(thread()->isCurrentThread());
260 return AV_PIX_FMT_VIDEOTOOLBOX;
261}
262
264{
265 return std::make_unique<QSckScreenCapture>();
266}
267
268} // namespace QFFmpeg
269
270QT_END_NAMESPACE
271
272#include "moc_qsckscreencapture_p.cpp"
std::optional< int > ffmpegHWPixelFormat() const override
void setCaptureSession(QPlatformMediaCaptureSession *) override
bool setActiveInternal(bool active) override
void onNewFrameFormatReceived(QMacScreenCaptureKit::StreamId streamId, const QVideoFrameFormat &)
QVideoFrameFormat frameFormat() const override
void onStreamStoppedWithErrorEvent(QMacScreenCaptureKit::StreamId streamId, const QString &)
static q23::expected< AVFScopedPointer< SCDisplay >, QString > findScDisplay(CGDirectDisplayID input)
static void setupQMacScreenCaptureKitConnections(QSckScreenCapture &screenCapture, const QMacScreenCaptureKit &macScreenCaptureKit)
static CGDirectDisplayID displayIDForScreen(NSScreen *screen)
QT_MANGLE_NAMESPACE(QMacScreenCaptureStreamDelegate) QMacScreenCaptureStreamDelegate
std::unique_ptr< QPlatformSurfaceCapture > makeQSckScreenCapture()