6#include <QtCore/qmutex.h>
8#include <QtFFmpegMediaPluginImpl/private/qcvimagevideobuffer_p.h>
9#include <QtFFmpegMediaPluginImpl/private/qffmpegdarwinhwframehelpers_p.h>
10#define AVMediaType XAVMediaType
11#include <QtFFmpegMediaPluginImpl/private/qffmpeghwaccel_p.h>
12#include <QtFFmpegMediaPluginImpl/private/qffmpegvideobuffer_p.h>
14#include <libavutil/hwcontext_videotoolbox.h>
18#include <QtMultimedia/private/qavfcamerautility_p.h>
19#include <QtMultimedia/private/qavfhelpers_p.h>
20#include <QtMultimedia/private/qvideoframe_p.h>
22#include <CoreMedia/CMSync.h>
23#include <CoreMedia/CMTime.h>
24#include <ScreenCaptureKit/ScreenCaptureKit.h>
28using namespace Qt::Literals::StringLiterals;
29using QMacScreenCaptureKit = QT_PREPEND_NAMESPACE(QFFmpeg::QMacScreenCaptureKit);
33 "qt.multimedia.screencapture.macscreencapturekit");
37struct QMacScreenCaptureStreamDelegateHelper :
public QObject {
40 void didStopWithError(QMacScreenCaptureKit::StreamId streamId, QString);
46@implementation QT_MANGLE_NAMESPACE(QMacScreenCaptureStreamDelegate) {
48 QMacScreenCaptureKit::StreamId m_streamId;
49 QMacScreenCaptureStreamDelegateHelper m_helper;
52- (
void)stream:(SCStream *)stream didStopWithError:(NSError *)error
54 Q_EMIT m_helper.didStopWithError(
56 QString::fromNSString(error.localizedDescription));
66 QMacScreenCaptureStreamOutput &scStreamOutput,
67 CMSampleBufferRef sampleBufferRef);
73@implementation QT_MANGLE_NAMESPACE(QMacScreenCaptureStreamOutput) {
77 QT_PREPEND_NAMESPACE(QFFmpeg::QMacScreenCaptureKit) *m_qScreenCaptureKit;
80 QSize m_previousFrameContentRect;
84 std::optional<std::chrono::microseconds> m_baseTime;
86 std::chrono::microseconds m_lastPresentationTime;
87 std::unique_ptr<QT_PREPEND_NAMESPACE(QFFmpeg::HWAccel)> m_hwAccel;
90- (
void) stream:(SCStream *) stream
91didOutputSampleBuffer:(CMSampleBufferRef) sampleBufferRef
92 ofType:(SCStreamOutputType) type
95 using namespace QFFmpeg;
100 Q_ASSERT(type == SCStreamOutputTypeScreen);
102 handleFrameOutput(*self, sampleBufferRef);
127 CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer,
false);
128 if (!attachments || CFArrayGetCount(attachments) == 0)
129 return q23::unexpected{ u"CMSampleBuffer has no attachments array"_s };
131 CFDictionaryRef attachment = (CFDictionaryRef)CFArrayGetValueAtIndex(attachments, 0);
132 NSDictionary *dict = (__bridge NSDictionary *)attachment;
134 NSNumber *statusNumber = dict[(id)SCStreamFrameInfoStatus];
136 return q23::unexpected{ u"CMSampleBuffer has no frame status"_s };
139 info.status =
static_cast<SCFrameStatus>(statusNumber.intValue);
141 CGRect contentRect = CGRectZero;
142 NSDictionary *frameInfo = dict[(id)SCStreamFrameInfoContentRect];
144 contentRect = CGRectMakeWithDictionaryRepresentation(
145 (__bridge CFDictionaryRef)frameInfo, &contentRect)
150 NSNumber *scaleNumber = dict[(id)SCStreamFrameInfoScaleFactor];
151 CGFloat scaleFactor = scaleNumber ? scaleNumber.doubleValue : 1.0;
153 NSNumber *contentScaleNumber = dict[(id)SCStreamFrameInfoContentScale];
154 CGFloat contentScale = contentScaleNumber ? contentScaleNumber.doubleValue : 1.0;
155 if (contentScale <= 0.0)
158 info.contentRect = QSize{
159 static_cast<
int>(std::lround(contentRect.size.width * scaleFactor / contentScale)),
160 static_cast<
int>(std::lround(contentRect.size.height * scaleFactor / contentScale)), };
168 QMacScreenCaptureStreamOutput &scStreamOutput,
169 CMSampleBufferRef sampleBufferRef)
171 CVImageBufferRef imageBufferRef = CMSampleBufferGetImageBuffer(sampleBufferRef);
173 return q23::unexpected(u"Cannot get CVImageBufferRef from CMSampleBufferRef"_s);
174 if (CFGetTypeID(imageBufferRef) != CVPixelBufferGetTypeID())
175 return q23::unexpected(u"Grabbed CVImageBufferRef that is not of type CVPixelBuffer"_s);
177 auto pixelBuffer = QAVFHelpers::QSharedCVPixelBuffer(
179 QAVFHelpers::QSharedCVPixelBuffer::RefMode::NeedsRef);
184 q23::expected<QAVFHelpers::QSharedCVPixelBuffer, QString> copyResult = deepCopyCvPixelBuffer(
187 return q23::unexpected(u"Failed to copy incoming pixel buffer: "_s + copyResult.error());
188 pixelBuffer =
std::move(*copyResult);
191 QSize incomingFrameSize = QAVFHelpers::CVPixelBufferSize(pixelBuffer.get());
192 Q_ASSERT(!incomingFrameSize.isEmpty());
193 CvPixelFormat incomingCvPixelFormat = CVPixelBufferGetPixelFormatType(pixelBuffer.get());
194 Q_ASSERT(scStreamOutput.m_hwAccel);
195 scStreamOutput.m_hwAccel->updateFramesContext(
196 av_map_videotoolbox_format_to_pixfmt(incomingCvPixelFormat),
201 const std::chrono::microseconds frameTime =
202 QAVFHelpers::CMTimeToMicroseconds(CMSampleBufferGetPresentationTimeStamp(sampleBufferRef));
203 if (!scStreamOutput.m_baseTime)
204 scStreamOutput.m_baseTime = frameTime;
205 const std::chrono::microseconds presentationTime = frameTime - *scStreamOutput.m_baseTime;
206 scStreamOutput.m_lastPresentationTime = presentationTime;
208 QVideoFrameFormat format = QAVFHelpers::videoFormatForImageBuffer(pixelBuffer.get());
209 if (!format.isValid())
210 return q23::unexpected(u"Cannot get get video format for image buffer"_s);
212 format.setColorSpace(QMacScreenCaptureKit::colorSpace);
213 format.setColorRange(QMacScreenCaptureKit::colorRange);
214 format.setColorTransfer(QMacScreenCaptureKit::colorTransfer);
216 Q_ASSERT(scStreamOutput.m_hwAccel);
218 q23::expected<QVideoFrame, QString> frameResult = QFFmpeg::qVideoFrameFromCvPixelBuffer(
219 *scStreamOutput.m_hwAccel,
224 qCWarning(qLcMacScreenCapture) << frameResult.error();
226 frame = *frameResult;
228 if (!frame.isValid()) {
229 frame = QVideoFramePrivate::createFrame(
230 std::make_unique<QFFmpeg::CVImageVideoBuffer>(std::move(pixelBuffer)),
234 frame.setStartTime(presentationTime.count());
236 frame.setEndTime(-1);
242 std::chrono::microseconds baseTime,
243 std::chrono::microseconds lastPresentationTime)
245 using namespace std::chrono_literals;
251 const std::chrono::microseconds hostTime =
252 QAVFHelpers::CMTimeToMicroseconds(CMClockGetTime(CMClockGetHostTimeClock()));
253 std::chrono::microseconds endTime = hostTime - baseTime;
254 if (endTime <= lastPresentationTime)
255 endTime = lastPresentationTime + 1us;
256 return QVideoFramePrivate::createEndOfStreamFrame(endTime);
262 QFFmpeg::QMacScreenCaptureStreamOutput &streamOutput,
263 CMSampleBufferRef sampleBufferRef)
265 Q_ASSERT(streamOutput.m_qScreenCaptureKit);
267 q23::expected<FrameInfo, QString> frameInfoResult = readFrameInfo(sampleBufferRef);
268 if (!frameInfoResult) {
269 qCDebug(qLcMacScreenCapture)
270 <<
"Error while reading frame info of CMSampleBufferRef:"
271 << frameInfoResult.error();
275 const FrameInfo &frameInfo = *frameInfoResult;
279 if (frameInfo.status != SCFrameStatusComplete)
289 if (!frameInfo.contentRect.isEmpty()) {
290 if (streamOutput.m_previousFrameContentRect != frameInfo.contentRect)
291 streamOutput.m_qScreenCaptureKit->updateStream(frameInfo.contentRect);
293 streamOutput.m_previousFrameContentRect = frameInfo.contentRect;
296 q23::expected<QVideoFrame, QString> videoFrameResult = createQVideoFrame(
299 if (!videoFrameResult) {
300 qCWarning(qLcMacScreenCapture)
301 <<
"Failed to create qVideoFrame from CMSampleBufferRef:"
302 << videoFrameResult.error();
306 Q_EMIT streamOutput.m_qScreenCaptureKit->newVideoFrameGenerated(
307 streamOutput.m_qScreenCaptureKit->streamId(),
308 std::move(*videoFrameResult));
316 Q_ASSERT(!resolutionPx.isEmpty());
320 auto scStreamConfig = AVFScopedPointer{ [[SCStreamConfiguration alloc] init] };
321 scStreamConfig.data().width = resolutionPx.width();
322 scStreamConfig.data().height = resolutionPx.height();
325 scStreamConfig.data().scalesToFit =
false;
327 scStreamConfig.data().pixelFormat = QMacScreenCaptureKit::cvPixelFormat;
328 scStreamConfig.data().colorSpaceName = QMacScreenCaptureKit::cgColorSpace();
329 scStreamConfig.data().ignoreShadowsSingleWindow =
true;
330 scStreamConfig.data().captureResolution = SCCaptureResolutionBest;
331 if (@available(macOS 15.0, *))
332 scStreamConfig.data().captureDynamicRange = SCCaptureDynamicRangeSDR;
334 if (settings.frameRate) {
335 Q_ASSERT(settings.frameRate > 0);
336 scStreamConfig.data().minimumFrameInterval =
337 CMTimeMake(1,
static_cast<int32_t>(std::round(*settings.frameRate)));
339 scStreamConfig.data().minimumFrameInterval = kCMTimeZero;
344 scStreamConfig.data().showsCursor =
false;
346 return scStreamConfig;
350 QMacScreenCaptureStreamDelegate &streamDelegate,
351 QMacScreenCaptureKit::StreamId streamId,
354 streamDelegate.m_streamId = streamId;
356 &streamDelegate.m_helper,
357 &QMacScreenCaptureStreamDelegateHelper::didStopWithError,
358 &macScreenCaptureKit,
359 &QMacScreenCaptureKit::streamStoppedWithError);
365 uint32_t cvPixelFormat,
368 auto streamOutput = AVFScopedPointer{ [[QMacScreenCaptureStreamOutput alloc] init] };
370 streamOutput.data()->m_qScreenCaptureKit = &macScreenCaptureKit;
372 streamOutput.data()->m_previousFrameContentRect = resolution;
374 streamOutput.data()->m_hwAccel = HWAccel::create(AV_HWDEVICE_TYPE_VIDEOTOOLBOX);
375 if (!streamOutput.data()->m_hwAccel)
376 return q23::unexpected(
377 u"Unable to create FFmpeg HW context when starting ScreenCaptureKit stream"_s);
379 streamOutput.data()->m_hwAccel->createFramesContext(
380 av_map_videotoolbox_format_to_pixfmt(cvPixelFormat),
383 if (!streamOutput.data()->m_hwAccel->hwFramesContextAsBuffer())
384 return q23::unexpected(
385 u"Unable to create FFmpeg HW context when starting ScreenCaptureKit stream"_s);
393 return AVFScopedPointer<SCContentFilter>{ [[SCContentFilter alloc]
394 initWithDisplay: scDisplay
395 excludingWindows: @[] ] };
401 return AVFScopedPointer<SCContentFilter>{ [[SCContentFilter alloc]
402 initWithDesktopIndependentWindow: scWindow] };
408 SCContentFilter *scContentFilter)
412 const CGRect contentRect = scContentFilter.contentRect;
413 const QSize resolutionPx =
414 (QSizeF::fromCGSize(contentRect.size) * scContentFilter.pointPixelScale).toSize();
417 if (resolutionPx.isEmpty())
418 return q23::unexpected{ u"SCContentFilter contentRect reported as zero size"_s };
431 dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
432 [m_stream.data() stopCaptureWithCompletionHandler:[semaphore](NSError *error) {
434 qCWarning(qLcMacScreenCapture)
435 <<
"Error while stopping ScreenCaptureKit stream during teardown:"
436 << QString::fromNSString(error.localizedDescription);
438 dispatch_semaphore_signal(semaphore);
440 dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
441 dispatch_release(semaphore);
447 if (m_dispatchQueue) {
448 Q_ASSERT(m_streamOutput);
451 dispatch_async(m_dispatchQueue.data(), [
this] {
452 QMacScreenCaptureStreamOutput *streamOutput = m_streamOutput.data();
453 std::optional<
std::chrono::microseconds> baseTime = streamOutput->m_baseTime;
460 QVideoFrame endFrame = createEndOfStreamFrame(
462 streamOutput->m_lastPresentationTime);
463 emit newVideoFrameGenerated(m_streamId, endFrame);
467 dispatch_sync(m_dispatchQueue.data(), []{});
653 u"Error when reconfiguring stream for new content: "_s
671 u"Error when switching stream content: "_s
713 AVFScopedPointer<SCStreamConfiguration> scStreamConfig = createStreamConfig(
718 updateConfiguration:scStreamConfig.data()
719 completionHandler:[](NSError *err) {
723 qCWarning(qLcMacScreenCapture)
724 <<
"Error when reconfiguring ScreenCaptureKit stream:"
725 << QString::fromNSString(err.description);
737 Q_ASSERT(m_dispatchQueue);
738 dispatch_assert_queue(m_dispatchQueue.data());
740 startStreamReconfigure(m_stream.data(), resolutionPx, m_streamSettings);
747#include "moc_qmacscreencapturekit_p.cpp"
748#include "qmacscreencapturekit.moc"
static constexpr int queueDepth
void updateStream(QSize resolutionPx)
static AVFScopedPointer< SCStreamConfiguration > createStreamConfig(QSize resolutionPx, QMacScreenCaptureKit::StreamSettings const &settings)
static AVFScopedPointer< SCContentFilter > createDisplayFilter(SCDisplay *scDisplay)
Q_DECLARE_LOGGING_CATEGORY(qLcMacScreenCapture)
static void handleFrameOutput(QMacScreenCaptureStreamOutput &scStreamOutput, CMSampleBufferRef sampleBufferRef)
static q23::expected< QVideoFrame, QString > createQVideoFrame(QMacScreenCaptureStreamOutput &scStreamOutput, CMSampleBufferRef sampleBufferRef)
static QVideoFrame createEndOfStreamFrame(std::chrono::microseconds baseTime, std::chrono::microseconds lastPresentationTime)
static q23::expected< AVFScopedPointer< QMacScreenCaptureStreamOutput >, QString > createStreamOutput(QMacScreenCaptureKit &macScreenCaptureKit, uint32_t cvPixelFormat, QSize resolution)
static AVFScopedPointer< SCContentFilter > createWindowFilter(SCWindow *scWindow)
static void configureStreamDelegate(QMacScreenCaptureStreamDelegate &streamDelegate, QMacScreenCaptureKit::StreamId streamId, const QMacScreenCaptureKit &macScreenCaptureKit)
static q23::expected< FrameInfo, QString > readFrameInfo(CMSampleBufferRef sampleBuffer)
static q23::expected< QSize, QString > resolutionForFilter(SCContentFilter *scContentFilter)
Q_LOGGING_CATEGORY_IMPL(QT_PREPEND_NAMESPACE(QFFmpeg::qLcMacScreenCapture), "qt.multimedia.screencapture.macscreencapturekit")
bool overrideIgnoreCursor