Open source CapCut alternative.
TypeScript
feat(app): add ScreenCaptureKit screen recorder engine [rebuild]
David Le208963576a11
diff --git a/apps/Donkey/Sources/DonkeyRuntime/SCRecordingScreenRecorder.swift b/apps/Donkey/Sources/DonkeyRuntime/SCRecordingScreenRecorder.swiftnew file mode 100644index 00000000..d22d73d5--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/SCRecordingScreenRecorder.swift@@ -0,0 +1,201 @@+import AVFoundation+import CoreGraphics+import CoreMedia+import CoreVideo+import Foundation+import ScreenCaptureKit++/// The macOS 15+ screen recorder. ScreenCaptureKit's `SCRecordingOutput` owns the encoder and the+/// audio/video mux, so this class only assembles the content filter + stream configuration, starts the+/// stream, and awaits a finalized file on stop. System audio and (optionally) the microphone are mixed+/// into the same `.mov`. A sub-region is captured with `sourceRect` — the GPU crops, so no full-frame+/// re-encode.+@available(macOS 15.0, *)+@MainActor+public final class SCRecordingScreenRecorder: ScreenRecording {+ public private(set) var isRecording = false+ public var onUnexpectedStop: ((Error) -> Void)?++ private var stream: SCStream?+ private var recordingOutput: SCRecordingOutput?+ private var delegate: RecorderDelegate?+ private var outputURL: URL?+ private var pendingFinish: CheckedContinuation<URL, Error>?++ public init() {}++ public func start(_ configuration: ScreenRecordingConfiguration) async throws {+ guard CGPreflightScreenCaptureAccess() else {+ throw ScreenRecordingError.screenRecordingPermissionDenied+ }++ let content = try await SCShareableContent.current+ let filter = try Self.makeFilter(for: configuration, content: content)+ let info = SCShareableContent.info(for: filter)+ let scale = CGFloat(info.pointPixelScale)++ let streamConfig = SCStreamConfiguration()+ // Geometry: crop to the region for a display target, else capture the whole content rect.+ let capturePoints: CGRect+ if case .display(_, let region) = configuration.target, let region {+ streamConfig.sourceRect = region+ capturePoints = region+ } else {+ capturePoints = info.contentRect+ }+ streamConfig.width = Self.evenPixels(capturePoints.width, scale: scale)+ streamConfig.height = Self.evenPixels(capturePoints.height, scale: scale)+ streamConfig.scalesToFit = false++ // System audio (default on) — never record our own UI sounds.+ streamConfig.capturesAudio = configuration.capturesSystemAudio+ streamConfig.sampleRate = 48_000+ streamConfig.channelCount = 2+ streamConfig.excludesCurrentProcessAudio = true+ streamConfig.captureMicrophone = configuration.capturesMicrophone+ if configuration.capturesMicrophone, let deviceID = configuration.microphoneDeviceID {+ streamConfig.microphoneCaptureDeviceID = deviceID+ }++ // Video.+ streamConfig.minimumFrameInterval = CMTime(value: 1, timescale: CMTimeScale(configuration.frameRate))+ streamConfig.showsCursor = configuration.showsCursor+ streamConfig.queueDepth = 6+ streamConfig.pixelFormat = kCVPixelFormatType_32BGRA++ let recordingConfig = SCRecordingOutputConfiguration()+ recordingConfig.outputURL = configuration.outputURL+ recordingConfig.outputFileType = .mov+ recordingConfig.videoCodecType = .h264++ let delegate = RecorderDelegate()+ delegate.owner = self+ let output = SCRecordingOutput(configuration: recordingConfig, delegate: delegate)+ let stream = SCStream(filter: filter, configuration: streamConfig, delegate: delegate)+ do {+ try stream.addRecordingOutput(output)+ try await stream.startCapture()+ } catch {+ throw ScreenRecordingError.startFailed(error.localizedDescription)+ }++ self.stream = stream+ self.recordingOutput = output+ self.delegate = delegate+ self.outputURL = configuration.outputURL+ isRecording = true+ }++ public func stop() async throws -> URL {+ guard let stream, isRecording else { throw ScreenRecordingError.notRecording }+ return try await withCheckedThrowingContinuation { continuation in+ pendingFinish = continuation+ Task { @MainActor in+ do {+ try await stream.stopCapture()+ // Success is delivered by the recording-output delegate once the file is finalized.+ } catch {+ finish(with: .failure(ScreenRecordingError.finalizeFailed(error.localizedDescription)))+ }+ }+ }+ }++ // MARK: - Delegate callbacks (hopped to the main actor)++ fileprivate func handleRecordingFinished(error: Error?) {+ if let error {+ finish(with: .failure(ScreenRecordingError.finalizeFailed(error.localizedDescription)))+ } else {+ finish(with: .success(()))+ }+ }++ fileprivate func handleStreamStopped(error: Error) {+ if pendingFinish != nil {+ // A stop is in flight; an error stop may not deliver a finish callback, so resolve it here.+ finish(with: .failure(ScreenRecordingError.finalizeFailed(error.localizedDescription)))+ } else if isRecording {+ isRecording = false+ teardown()+ onUnexpectedStop?(error)+ }+ }++ private func finish(with result: Result<Void, Error>) {+ guard let continuation = pendingFinish else { return }+ pendingFinish = nil+ isRecording = false+ let url = outputURL+ teardown()+ switch result {+ case .success:+ if let url {+ continuation.resume(returning: url)+ } else {+ continuation.resume(throwing: ScreenRecordingError.finalizeFailed("missing output URL"))+ }+ case .failure(let error):+ continuation.resume(throwing: error)+ }+ }++ private func teardown() {+ stream = nil+ recordingOutput = nil+ delegate = nil+ outputURL = nil+ }++ // MARK: - Helpers++ private static func makeFilter(+ for configuration: ScreenRecordingConfiguration,+ content: SCShareableContent+ ) throws -> SCContentFilter {+ switch configuration.target {+ case .display(let displayID, _):+ guard let display = content.displays.first(where: { $0.displayID == displayID })+ ?? content.displays.first else {+ throw ScreenRecordingError.displayUnavailable+ }+ let excluded = content.windows.filter { configuration.excludedWindowIDs.contains($0.windowID) }+ return SCContentFilter(display: display, excludingWindows: excluded)+ case .window(let windowID):+ guard let window = content.windows.first(where: { $0.windowID == windowID }) else {+ throw ScreenRecordingError.windowUnavailable+ }+ return SCContentFilter(desktopIndependentWindow: window)+ }+ }++ /// Pixel dimension for `points × scale`, rounded down to an even number — H.264 requires even+ /// width/height, and a stray odd pixel otherwise fails the encoder.+ private static func evenPixels(_ points: CGFloat, scale: CGFloat) -> Int {+ let pixels = Int((points * scale).rounded())+ return max(2, pixels - (pixels % 2))+ }+}++/// A nonisolated bridge for ScreenCaptureKit's delegate callbacks, which arrive on a background queue.+/// It forwards each event to the main-actor recorder; keeping it off the recorder means the recorder+/// can stay `@MainActor` without ScreenCaptureKit calling main-actor methods from the wrong thread.+@available(macOS 15.0, *)+private final class RecorderDelegate: NSObject, SCStreamDelegate, SCRecordingOutputDelegate, @unchecked Sendable {+ weak var owner: SCRecordingScreenRecorder?++ func stream(_ stream: SCStream, didStopWithError error: Error) {+ let owner = self.owner+ Task { @MainActor in owner?.handleStreamStopped(error: error) }+ }++ func recordingOutput(_ recordingOutput: SCRecordingOutput, didFailWithError error: Error) {+ let owner = self.owner+ Task { @MainActor in owner?.handleRecordingFinished(error: error) }+ }++ func recordingOutputDidFinishRecording(_ recordingOutput: SCRecordingOutput) {+ let owner = self.owner+ Task { @MainActor in owner?.handleRecordingFinished(error: nil) }+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/ScreenRecorder.swift b/apps/Donkey/Sources/DonkeyRuntime/ScreenRecorder.swiftnew file mode 100644index 00000000..292eb062--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/ScreenRecorder.swift@@ -0,0 +1,68 @@+import CoreGraphics+import Foundation++/// What a screen recording captures: a whole display, a cropped region of a display, or a single+/// window. `region` is in display-local points with a top-left origin (the coordinate space+/// `SCStreamConfiguration.sourceRect` expects); `nil` means the full display.+public enum ScreenCaptureTarget: Equatable, Sendable {+ case display(displayID: CGDirectDisplayID, region: CGRect?)+ case window(windowID: CGWindowID)+}++/// Everything a recorder needs to start: what to capture, which audio sources to mix in, and where+/// the finished file goes. System audio is on by default; the microphone is off by default.+public struct ScreenRecordingConfiguration: Sendable {+ public var target: ScreenCaptureTarget+ public var capturesSystemAudio: Bool+ public var capturesMicrophone: Bool+ /// The microphone device to capture, when `capturesMicrophone` is set. `nil` uses the system default.+ public var microphoneDeviceID: String?+ public var showsCursor: Bool+ public var frameRate: Int+ /// Window IDs to keep out of the capture — our own control bar, so it never appears in the file.+ public var excludedWindowIDs: [CGWindowID]+ public var outputURL: URL++ public init(+ target: ScreenCaptureTarget,+ capturesSystemAudio: Bool = true,+ capturesMicrophone: Bool = false,+ microphoneDeviceID: String? = nil,+ showsCursor: Bool = true,+ frameRate: Int = 60,+ excludedWindowIDs: [CGWindowID] = [],+ outputURL: URL+ ) {+ self.target = target+ self.capturesSystemAudio = capturesSystemAudio+ self.capturesMicrophone = capturesMicrophone+ self.microphoneDeviceID = microphoneDeviceID+ self.showsCursor = showsCursor+ self.frameRate = frameRate+ self.excludedWindowIDs = excludedWindowIDs+ self.outputURL = outputURL+ }+}++public enum ScreenRecordingError: Error, Equatable, Sendable {+ case screenRecordingPermissionDenied+ case unsupportedOSVersion+ case displayUnavailable+ case windowUnavailable+ case notRecording+ case startFailed(String)+ case finalizeFailed(String)+}++/// A live screen recorder. `start` begins capture; `stop` finalizes and resolves only once the file+/// is on disk and playable (its `moov` atom written). Main-actor isolated so it pairs cleanly with the+/// AppKit controllers that drive it. The concrete engine is `SCRecordingScreenRecorder` (macOS 15+);+/// the protocol leaves room for an `AVAssetWriter` fallback on older systems.+@MainActor+public protocol ScreenRecording: AnyObject {+ var isRecording: Bool { get }+ /// Called if the stream stops on its own (display unplugged, permission revoked) rather than via `stop()`.+ var onUnexpectedStop: ((Error) -> Void)? { get set }+ func start(_ configuration: ScreenRecordingConfiguration) async throws+ func stop() async throws -> URL+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/ScreenRecordingDestination.swift b/apps/Donkey/Sources/DonkeyRuntime/ScreenRecordingDestination.swiftnew file mode 100644index 00000000..f85ac8c4--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/ScreenRecordingDestination.swift@@ -0,0 +1,45 @@+import Foundation++/// Where a finished screen recording is written and how it is named — QuickTime's default: a+/// timestamped `.mov` on the Desktop, de-collided so a second recording in the same second doesn't+/// overwrite the first. Pure path logic (no AppKit) so the naming rule is unit-testable; revealing the+/// file in Finder lives with the AppKit controllers.+public enum ScreenRecordingDestination {+ /// `Screen Recording 2026-07-21 at 15.24.05` — QuickTime's filename shape, stable across locales.+ public static func fileName(for date: Date) -> String {+ let formatter = DateFormatter()+ formatter.locale = Locale(identifier: "en_US_POSIX")+ formatter.dateFormat = "yyyy-MM-dd 'at' HH.mm.ss"+ return "Screen Recording \(formatter.string(from: date))"+ }++ /// The first non-colliding URL: `<base>.<ext>`, then `<base> (2).<ext>`, `(3)`, and so on.+ /// `fileExists` is injected so tests can drive collisions without touching the filesystem.+ public static func uniqueURL(+ in directory: URL,+ baseName: String,+ ext: String,+ fileExists: (URL) -> Bool+ ) -> URL {+ var candidate = directory.appendingPathComponent("\(baseName).\(ext)")+ var counter = 2+ while fileExists(candidate) {+ candidate = directory.appendingPathComponent("\(baseName) (\(counter)).\(ext)")+ counter += 1+ }+ return candidate+ }++ /// The concrete output URL for a recording starting now, on the real Desktop.+ public static func makeOutputURL(now: Date = Date()) -> URL {+ let fileManager = FileManager.default+ let desktop = fileManager.urls(for: .desktopDirectory, in: .userDomainMask).first+ ?? fileManager.homeDirectoryForCurrentUser.appendingPathComponent("Desktop")+ return uniqueURL(+ in: desktop,+ baseName: fileName(for: now),+ ext: "mov",+ fileExists: { fileManager.fileExists(atPath: $0.path) }+ )+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ScreenRecordingDestinationTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ScreenRecordingDestinationTests.swiftnew file mode 100644index 00000000..e09690c8--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ScreenRecordingDestinationTests.swift@@ -0,0 +1,50 @@+@testable import DonkeyRuntime+import Foundation+import Testing++@Suite+struct ScreenRecordingDestinationTests {+ private static let referenceDate = Date(timeIntervalSince1970: 1_753_100_645) // 2025-07-21 in UTC++ @Test+ func fileNameFollowsQuickTimeShape() {+ var calendar = Calendar(identifier: .gregorian)+ calendar.timeZone = TimeZone(identifier: "America/Los_Angeles")!+ let date = calendar.date(from: DateComponents(year: 2026, month: 7, day: 21, hour: 15, minute: 24, second: 5))!++ let name = ScreenRecordingDestination.fileName(for: date)++ #expect(name == "Screen Recording 2026-07-21 at 15.24.05")+ }++ @Test+ func firstFileUsesTheBareName() {+ let directory = URL(fileURLWithPath: "/tmp/desktop")+ let url = ScreenRecordingDestination.uniqueURL(+ in: directory,+ baseName: "Screen Recording 2026-07-21 at 15.24.05",+ ext: "mov",+ fileExists: { _ in false }+ )++ #expect(url.lastPathComponent == "Screen Recording 2026-07-21 at 15.24.05.mov")+ }++ @Test+ func collidingNamesGainAnIncrementingSuffix() {+ let directory = URL(fileURLWithPath: "/tmp/desktop")+ let taken: Set<String> = [+ "Screen Recording 2026-07-21 at 15.24.05.mov",+ "Screen Recording 2026-07-21 at 15.24.05 (2).mov"+ ]++ let url = ScreenRecordingDestination.uniqueURL(+ in: directory,+ baseName: "Screen Recording 2026-07-21 at 15.24.05",+ ext: "mov",+ fileExists: { taken.contains($0.lastPathComponent) }+ )++ #expect(url.lastPathComponent == "Screen Recording 2026-07-21 at 15.24.05 (3).mov")+ }+}