Skip to content
Closed
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,16 @@ public final class ScreenCaptureBackend: NSObject, ScreenBackend, SCStreamOutput
/// The capture rate (``setFrameRate(_:)``).
private var frameRate = ScreenQuality.baselineFrameRate
private var onFrame: (@Sendable (CVPixelBuffer, CGRect) -> Void)?
/// The size and pointer position of the last frame sent on (nil: none
/// yet, or the capture restarted).
private var lastDelivered: (size: CGSize, pointer: CGPoint?)?
/// Complete frames with nothing changed that were not sent on.
private var skippedUnchanged = 0
/// The newest of them (nil once a frame goes out): the host's keep-alive
/// sends it, so a cursor the gate missed shows within a second.
private var held: (buffer: CVPixelBuffer, crop: CGRect)?
/// The pointer position read for the frame before (sent or not).
private var lastPointer: CGPoint?
private var onDisplays: (@Sendable ([CGSize], Int) -> Void)?
private let input = EventInjector()
/// Stopped by the viewer: no recovery after that.
Expand Down Expand Up @@ -209,6 +219,11 @@ public final class ScreenCaptureBackend: NSObject, ScreenBackend, SCStreamOutput
let filter = SCContentFilter(display: display, excludingWindows: [])
let stream = SCStream(filter: filter, configuration: configuration, delegate: self)
try stream.addStreamOutput(self, type: .screen, sampleHandlerQueue: queue)
// A new capture's first frame always goes out, whatever its dirty rects say.
lock.withLock {
lastDelivered = nil
held = nil
}
try await stream.startCapture()
// stop() may have run while this capture started: it then ends here, never stored.
let (previous, late, latest, generation) = lock.withLock { () -> (SCStream?, Bool, Int, Int) in
Expand All @@ -224,7 +239,14 @@ public final class ScreenCaptureBackend: NSObject, ScreenBackend, SCStreamOutput
try? await stream.stopCapture()
return
}
if let previous { try? await previous.stopCapture() }
if let previous {
try? await previous.stopCapture()
// The old stream's last frames may have set these while this one started.
lock.withLock {
lastDelivered = nil
held = nil
}
}
input.display = display.frame
log("capturing display \(display.displayID) at \(Int(size.width))x\(Int(size.height)), \(rate) fps")
// The rate changed while this capture started (setFrameRate found no stream to update).
Expand All @@ -236,8 +258,59 @@ public final class ScreenCaptureBackend: NSObject, ScreenBackend, SCStreamOutput
let attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, createIfNecessary: false) as? [[SCStreamFrameInfo: Any]],
let statusRaw = attachments.first?[.status] as? Int, SCFrameStatus(rawValue: statusRaw) == .complete,
let buffer = sampleBuffer.imageBuffer else { return }
let sink = lock.withLock { onFrame }
sink?(buffer, CGRect(x: 0, y: 0, width: CVPixelBufferGetWidth(buffer), height: CVPixelBufferGetHeight(buffer)))
let size = CGSize(width: CVPixelBufferGetWidth(buffer), height: CVPixelBufferGetHeight(buffer))
let dirtyRects = (attachments.first?[.dirtyRects] as? [Any]).map { $0.count }
let pointer = CGEvent(source: nil)?.location
let sink = lock.withLock { () -> (@Sendable (CVPixelBuffer, CGRect) -> Void)? in
defer { lastPointer = pointer }
guard Self.delivers(dirtyRectCount: dirtyRects, size: size, pointer: pointer, last: lastDelivered,
previousPointer: lastPointer) else {
skippedUnchanged += 1
held = (buffer, CGRect(origin: .zero, size: size))
return nil
}
lastDelivered = (size, pointer)
held = nil
return onFrame
}
sink?(buffer, CGRect(origin: .zero, size: size))
}

/// Whether a complete frame goes to the encoder: not when ScreenCaptureKit
/// says nothing in it changed (no dirty rects), at the size and pointer
/// position of the last frame sent and of the frame just before. A frame
/// whose dirty rects are unknown (no attachment) counts as changed, as
/// does the first one, another size or a moved pointer (the cursor is
/// drawn into the picture and may not count as dirty). The pointer is
/// read as the frame arrives, not when it was captured, so the frame
/// after the pointer stops goes out too: it shows where the cursor came
/// to rest; a cursor still missed (it moved while a frame was on its way,
/// or changed shape in place) shows with the keep-alive, which sends the
/// newest frame held back (``takeHeldFrame()``). Petal's dirty-rect skip gate
/// (https://github.com/kiruna-labs/petal, Apache-2.0,
/// `apps/desktop/src-tauri/src/session/share.rs`). The host's keep-alive
/// still sends a frame once a second.
static func delivers(dirtyRectCount: Int?, size: CGSize, pointer: CGPoint?,
last: (size: CGSize, pointer: CGPoint?)?, previousPointer: CGPoint?) -> Bool {
guard let dirtyRectCount, dirtyRectCount == 0, let last else { return true }
return last.size != size || last.pointer != pointer || previousPointer != pointer || pointer == nil
}

/// The newest frame held back since the last one sent, once.
public func takeHeldFrame() -> (CVPixelBuffer, CGRect)? {
lock.withLock {
defer { held = nil }
return held.map { ($0.buffer, $0.crop) }
}
}

/// Complete frames ``delivers(dirtyRectCount:size:pointer:last:previousPointer:)`` held
/// back since the last call (the host's 3 s video log line).
public func takeSkippedUnchangedFrames() -> Int {
lock.withLock {
defer { skippedUnchanged = 0 }
return skippedUnchanged
}
}

public func select(display index: Int) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,12 @@ public protocol ScreenBackend: AnyObject, Sendable {
var maximumFrameRate: Int? { get }
/// Captures at most `fps` frames per second from now on.
func setFrameRate(_ fps: Int)
/// Pictures the source held back since the last call because nothing in
/// them changed (0 for a source that holds none back).
func takeSkippedUnchangedFrames() -> Int
/// The newest of those pictures, once (nil when none was held back since
/// the last one sent): the keep-alive sends it in place of the last one.
func takeHeldFrame() -> (CVPixelBuffer, CGRect)?
}

/// Sources that do not know their display's rate (the Screen Sharing
Expand All @@ -211,6 +217,8 @@ public extension ScreenBackend {
var maximumFrameRate: Int? { nil }
var inputCapabilities: [String] { [] }
func setFrameRate(_ fps: Int) {}
func takeSkippedUnchangedFrames() -> Int { 0 }
func takeHeldFrame() -> (CVPixelBuffer, CGRect)? { nil }
}

/// The Mac side of a screen stream: answers a viewer with the screen as a
Expand Down Expand Up @@ -450,26 +458,42 @@ public final class ScreenStreamHost: @unchecked Sendable {
defer { session.captured = 0 }
return (session.captured, session.frameRate)
}
let skipped = session.backend.takeSkippedUnchangedFrames()
let seconds = max(Double(now - since) / 1e9, 0.001)
since = now
log("video: \(summary) capture \(String(format: "%.1f", Double(captured) / seconds)) fps target \(target.map(String.init) ?? "-") fps")
log("video: \(summary) capture \(String(format: "%.1f", Double(captured) / seconds)) fps unchanged-skipped \(String(format: "%.1f", Double(skipped) / seconds)) fps target \(target.map(String.init) ?? "-") fps")
}
})
// Idle refresh: capture sends nothing while the screen is still, but a
// lost keyframe or a quality step needs a frame to encode.
// Keep-alive: capture sends nothing while the screen is still, but a
// lost keyframe or a quality step needs a frame to encode. Once a
// second (Petal's static refresh floor), not twice: a still screen
// then costs one frame a second.
session.tasks.append(Task { [weak self] in
while !Task.isCancelled {
try? await Task.sleep(for: .milliseconds(500)) // idle refresh period
try? await Task.sleep(for: .milliseconds(ScreenStreamHost.keepAliveMilliseconds)) // keep-alive period
guard let self else { return }
let stale = session.lock.withLock { () -> (CVPixelBuffer, CGRect)? in
guard let last = session.last, DispatchTime.now().uptimeNanoseconds - session.lastPush.uptimeNanoseconds > 450_000_000 else { return nil }
guard let last = session.last,
DispatchTime.now().uptimeNanoseconds - session.lastPush.uptimeNanoseconds > ScreenStreamHost.keepAliveMilliseconds * 900_000 else { return nil }
return (last.buffer, last.crop)
}
if let stale { push(stale.0, crop: stale.1, session: session) }
guard let stale else { continue }
// The newest picture the source held back, else the last one sent.
let frame = ScreenStreamHost.keepAliveFrame(held: session.backend.takeHeldFrame(), last: stale)
push(frame.0, crop: frame.1, session: session)
}
})
}

/// How long a still screen goes without a frame before the host sends
/// the last one again (it was 500 ms).
static let keepAliveMilliseconds: UInt64 = 1000

/// What the keep-alive sends: the newest picture the source held back as
/// unchanged (it may show a cursor the skip gate missed), else the last
/// one sent.
static func keepAliveFrame<Frame>(held: Frame?, last: Frame) -> Frame { held ?? last }

private func push(_ buffer: CVPixelBuffer, crop: CGRect, session: Session) {
session.lock.withLock {
session.last = (buffer, crop)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,5 +150,33 @@ struct FrameRateTests {
#expect(ScreenCaptureBackend.queueDepth(for: 60) == 4)
#expect(ScreenCaptureBackend.queueDepth(for: 120) == 6)
}

/// Petal's dirty-rect skip gate: a complete frame ScreenCaptureKit says
/// has nothing changed stays out of the encoder, unless its dirty rects
/// are unknown, it is the first, its size changed or the pointer moved.
@Test func unchangedFramesStayOutOfTheEncoder() {
let size = CGSize(width: 3456, height: 2234)
let pointer = CGPoint(x: 100, y: 200)
let last = (size: size, pointer: Optional(pointer))
#expect(!ScreenCaptureBackend.delivers(dirtyRectCount: 0, size: size, pointer: pointer, last: last, previousPointer: pointer), "nothing changed")
#expect(ScreenCaptureBackend.delivers(dirtyRectCount: 1, size: size, pointer: pointer, last: last, previousPointer: pointer), "something changed")
#expect(ScreenCaptureBackend.delivers(dirtyRectCount: nil, size: size, pointer: pointer, last: last, previousPointer: pointer), "unknown counts as changed")
#expect(ScreenCaptureBackend.delivers(dirtyRectCount: 0, size: size, pointer: pointer, last: nil, previousPointer: pointer), "the first frame")
#expect(ScreenCaptureBackend.delivers(dirtyRectCount: 0, size: CGSize(width: 1920, height: 1080), pointer: pointer, last: last, previousPointer: pointer),
"another size")
#expect(ScreenCaptureBackend.delivers(dirtyRectCount: 0, size: size, pointer: CGPoint(x: 101, y: 200), last: last, previousPointer: pointer),
"the pointer moved")
#expect(ScreenCaptureBackend.delivers(dirtyRectCount: 0, size: size, pointer: nil, last: last, previousPointer: pointer), "pointer unknown")
#expect(ScreenCaptureBackend.delivers(dirtyRectCount: 0, size: size, pointer: pointer, last: last, previousPointer: CGPoint(x: 90, y: 200)),
"the frame after the pointer came to rest")
}

/// A cursor the gate missed (the pointer settled while its frame was on
/// the way) shows with the next keep-alive: it sends the newest frame
/// held back, not the last one sent.
@Test func theKeepAliveSendsTheNewestHeldFrame() {
#expect(ScreenStreamHost.keepAliveFrame(held: "held", last: "sent") == "held")
#expect(ScreenStreamHost.keepAliveFrame(held: String?.none, last: "sent") == "sent")
}
#endif
}