framepress 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,325 @@
1
+ import AppKit
2
+ import AVFoundation
3
+ import CoreGraphics
4
+ import ScreenCaptureKit
5
+
6
+ let permissionMessage = "Screen Recording permission required. In System Settings > Privacy & Security > Screen & System Audio Recording, allow framepress-capture (or the terminal hosting it), then relaunch."
7
+ let readyMessage = "framepress-capture: ready"
8
+
9
+ struct CaptureError: LocalizedError {
10
+ let errorDescription: String?
11
+
12
+ init(_ message: String) {
13
+ errorDescription = message
14
+ }
15
+ }
16
+
17
+ func diagnostic(_ message: String) {
18
+ FileHandle.standardError.write(Data((message + "\n").utf8))
19
+ }
20
+
21
+ func hostTime() -> CMTime {
22
+ CMClockGetTime(CMClockGetHostTimeClock())
23
+ }
24
+
25
+ func jsonData(_ object: Any) throws -> Data {
26
+ var data = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])
27
+ data.append(0x0a)
28
+ return data
29
+ }
30
+
31
+ struct Source {
32
+ let filter: SCContentFilter
33
+ let bounds: CGRect
34
+ let window: SCWindow?
35
+ var scale: Double { Double(filter.pointPixelScale) }
36
+ var width: Int { Int((bounds.width * scale).rounded()) }
37
+ var height: Int { Int((bounds.height * scale).rounded()) }
38
+
39
+ init(content: SCShareableContent, display: UInt32?, window query: String?) throws {
40
+ if let query {
41
+ // Front to back, so a bundle ID picks that app's frontmost window.
42
+ let order = (CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] ?? [])
43
+ .compactMap { $0[kCGWindowNumber as String] as? CGWindowID }
44
+ let rank = Dictionary(order.enumerated().map { ($1, $0) }, uniquingKeysWith: { a, _ in a })
45
+ let candidates = content.windows
46
+ .filter { $0.isOnScreen && $0.windowLayer == 0 && $0.frame.width >= 40 && $0.frame.height >= 40 }
47
+ .sorted { (rank[$0.windowID] ?? .max) < (rank[$1.windowID] ?? .max) }
48
+ let match = candidates.first { $0.title?.caseInsensitiveCompare(query) == .orderedSame }
49
+ ?? candidates.first { $0.owningApplication?.bundleIdentifier.caseInsensitiveCompare(query) == .orderedSame }
50
+ ?? candidates.first { $0.title?.localizedCaseInsensitiveContains(query) == true }
51
+ guard let match else { throw CaptureError("No visible window matches \(query).") }
52
+ // Only this window: no desktop, no other windows, no menu bar.
53
+ filter = SCContentFilter(desktopIndependentWindow: match)
54
+ bounds = match.frame
55
+ window = match
56
+ } else {
57
+ let id = display ?? CGMainDisplayID()
58
+ guard let match = content.displays.first(where: { $0.displayID == id }) else {
59
+ throw CaptureError("Display \(id) is unavailable.")
60
+ }
61
+ filter = SCContentFilter(display: match, excludingWindows: [])
62
+ bounds = CGDisplayBounds(id)
63
+ window = nil
64
+ }
65
+ }
66
+ }
67
+
68
+ // macOS gives no API for a window's corner radius. Window captures keep the corners
69
+ // transparent, so measure the clear run along the top-left diagonal of one BGRA frame:
70
+ // a circular corner of radius r leaves r(1 - 1/sqrt 2) clear along the diagonal.
71
+ let defaultCornerRadius = 10.0
72
+ func measureCornerRadius(_ source: Source) async -> Double? {
73
+ guard source.window != nil else { return nil }
74
+ let config = SCStreamConfiguration()
75
+ config.width = source.width
76
+ config.height = source.height
77
+ config.showsCursor = false
78
+ config.ignoreShadowsSingleWindow = true
79
+ config.pixelFormat = kCVPixelFormatType_32BGRA
80
+ guard let image = try? await SCScreenshotManager.captureImage(contentFilter: source.filter, configuration: config),
81
+ let data = image.dataProvider?.data, let bytes = CFDataGetBytePtr(data),
82
+ image.bitsPerPixel == 32 else { return nil }
83
+ let row = image.bytesPerRow
84
+ // Alpha is the last byte in BGRA and the first in ARGB.
85
+ let alphaOffset = image.alphaInfo == .premultipliedFirst || image.alphaInfo == .first ? (image.bitmapInfo.contains(.byteOrder32Little) ? 3 : 0) : 3
86
+ func alpha(_ x: Int, _ y: Int) -> Double { Double(bytes[y * row + x * 4 + alphaOffset]) / 255 }
87
+ guard alpha(0, 0) < 0.1 else { return nil }
88
+ let limit = min(image.width, image.height) / 3
89
+ var clear = 0.0
90
+ for i in 0..<limit {
91
+ let a = alpha(i, i)
92
+ if a > 0.98 { break }
93
+ clear += 1 - a
94
+ }
95
+ // clear is the inset d along each axis where the arc crosses the diagonal.
96
+ let r = clear / (1 - 1 / 2.0.squareRoot()) / source.scale
97
+ return r > 1 && r < 60 ? (r * 10).rounded() / 10 : nil
98
+ }
99
+
100
+ enum CaptureState {
101
+ case ready(CMTime)
102
+ case stop(CMTime)
103
+ case failed(Error)
104
+ }
105
+
106
+ // Writer and frame state stay on queue. The stream delegate only publishes errors.
107
+ final class Video: NSObject, SCStreamOutput, SCStreamDelegate, @unchecked Sendable {
108
+ let queue = DispatchQueue(label: "framepress.video", qos: .userInteractive)
109
+ private let writer: AVAssetWriter
110
+ private let input: AVAssetWriterInput
111
+ private let adaptor: AVAssetWriterInputPixelBufferAdaptor
112
+ private let fps: Int32
113
+ private let duration: CMTime?
114
+ private let states: AsyncStream<CaptureState>.Continuation
115
+ private var epoch: CMTime?
116
+ private var nextFrame: Int64 = 0
117
+ private var image: CVPixelBuffer?
118
+ private var pending: [(CMTime, CVPixelBuffer)] = []
119
+ private var timer: DispatchSourceTimer?
120
+ private var failure: Error?
121
+ private var ending = false
122
+
123
+ static let pixelFormat = kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange
124
+
125
+ init(url: URL, source: Source, fps: Int32, duration: Double?, states: AsyncStream<CaptureState>.Continuation) throws {
126
+ self.fps = fps
127
+ self.duration = duration.map { CMTime(seconds: $0, preferredTimescale: 600_000) }
128
+ self.states = states
129
+ writer = try AVAssetWriter(outputURL: url, fileType: .mov)
130
+ input = AVAssetWriterInput(mediaType: .video, outputSettings: [
131
+ AVVideoCodecKey: AVVideoCodecType.hevc,
132
+ AVVideoWidthKey: source.width, AVVideoHeightKey: source.height,
133
+ AVVideoCompressionPropertiesKey: [
134
+ AVVideoExpectedSourceFrameRateKey: fps,
135
+ AVVideoAllowFrameReorderingKey: false,
136
+ ],
137
+ ])
138
+ input.expectsMediaDataInRealTime = true
139
+ adaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: input, sourcePixelBufferAttributes: [
140
+ kCVPixelBufferPixelFormatTypeKey as String: Self.pixelFormat,
141
+ kCVPixelBufferWidthKey as String: source.width,
142
+ kCVPixelBufferHeightKey as String: source.height,
143
+ ])
144
+ guard writer.canAdd(input) else { throw CaptureError("The HEVC encoder cannot accept this capture size.") }
145
+ writer.add(input)
146
+ }
147
+
148
+ func stream(_ stream: SCStream, didStopWithError error: Error) {
149
+ states.yield(.failed(error))
150
+ }
151
+
152
+ func stream(_ stream: SCStream, didOutputSampleBuffer sample: CMSampleBuffer, of type: SCStreamOutputType) {
153
+ guard type == .screen, !ending, failure == nil, sample.isValid,
154
+ let buffer = sample.imageBuffer,
155
+ let attachments = CMSampleBufferGetSampleAttachmentsArray(sample, createIfNecessary: false)
156
+ as? [[SCStreamFrameInfo: Any]],
157
+ let rawStatus = attachments.first?[.status] as? Int,
158
+ let status = SCFrameStatus(rawValue: rawStatus),
159
+ status == .complete || status == .started else { return }
160
+
161
+ do {
162
+ let pts = sample.presentationTimeStamp
163
+ guard pts.isNumeric else { return }
164
+ if epoch == nil {
165
+ guard writer.startWriting() else { throw writeError }
166
+ guard abs((pts - hostTime()).seconds) < 5 else {
167
+ throw CaptureError("ScreenCaptureKit frame timestamps do not match the host clock.")
168
+ }
169
+ writer.startSession(atSourceTime: .zero)
170
+ image = try copyImage(buffer)
171
+ epoch = pts
172
+ guard try appendFrame() else { throw writeError }
173
+ startTimer()
174
+ states.yield(.ready(pts))
175
+ } else {
176
+ // Keep the nearest frames while the encoder catches up, plus the latest update.
177
+ if pending.count == 12 { pending.removeLast() }
178
+ pending.append((pts, try copyImage(buffer)))
179
+ }
180
+ } catch {
181
+ fail(error)
182
+ }
183
+ }
184
+
185
+ // Own the buffers that outlive the callback so idle frames cannot pin ScreenCaptureKit's surfaces.
186
+ private func copyImage(_ source: CVPixelBuffer) throws -> CVPixelBuffer {
187
+ var target: CVPixelBuffer?
188
+ guard let pool = adaptor.pixelBufferPool,
189
+ CVPixelBufferPoolCreatePixelBuffer(nil, pool, &target) == kCVReturnSuccess,
190
+ let target else { throw CaptureError("Cannot allocate a recording frame.") }
191
+ guard CVPixelBufferLockBaseAddress(source, .readOnly) == kCVReturnSuccess else {
192
+ throw CaptureError("Cannot read a capture frame.")
193
+ }
194
+ defer { CVPixelBufferUnlockBaseAddress(source, .readOnly) }
195
+ guard CVPixelBufferLockBaseAddress(target, []) == kCVReturnSuccess else {
196
+ throw CaptureError("Cannot write a capture frame.")
197
+ }
198
+ defer { CVPixelBufferUnlockBaseAddress(target, []) }
199
+ guard CVPixelBufferGetWidth(source) == CVPixelBufferGetWidth(target),
200
+ CVPixelBufferGetHeight(source) == CVPixelBufferGetHeight(target),
201
+ CVPixelBufferGetPlaneCount(source) == 2, CVPixelBufferGetPlaneCount(target) == 2 else {
202
+ throw CaptureError("ScreenCaptureKit returned an unexpected frame format.")
203
+ }
204
+ for plane in 0..<2 {
205
+ guard let from = CVPixelBufferGetBaseAddressOfPlane(source, plane),
206
+ let to = CVPixelBufferGetBaseAddressOfPlane(target, plane) else {
207
+ throw CaptureError("Cannot access capture frame pixels.")
208
+ }
209
+ let fromStride = CVPixelBufferGetBytesPerRowOfPlane(source, plane)
210
+ let toStride = CVPixelBufferGetBytesPerRowOfPlane(target, plane)
211
+ let rows = CVPixelBufferGetHeightOfPlane(source, plane)
212
+ if fromStride == toStride {
213
+ memcpy(to, from, rows * toStride)
214
+ } else {
215
+ for row in 0..<rows {
216
+ memcpy(to + row * toStride, from + row * fromStride, min(fromStride, toStride))
217
+ }
218
+ }
219
+ }
220
+ CVBufferPropagateAttachments(source, target)
221
+ return target
222
+ }
223
+
224
+ private var writeError: Error { writer.error ?? CaptureError("Cannot write a video frame.") }
225
+
226
+ private func fail(_ error: Error) {
227
+ failure = error
228
+ timer?.cancel()
229
+ states.yield(.failed(error))
230
+ }
231
+
232
+ private func startTimer() {
233
+ let timer = DispatchSource.makeTimerSource(queue: queue)
234
+ timer.schedule(deadline: .now(), repeating: .nanoseconds(1_000_000_000 / Int(fps)), leeway: .milliseconds(1))
235
+ timer.setEventHandler { [weak self] in
236
+ guard let self else { return }
237
+ do {
238
+ // Allow a few frames for ScreenCaptureKit delivery jitter.
239
+ try self.fill(until: hostTime() - CMTime(value: 3, timescale: self.fps))
240
+ } catch {
241
+ self.fail(error)
242
+ }
243
+ }
244
+ self.timer = timer
245
+ timer.resume()
246
+ }
247
+
248
+ private func fill(until end: CMTime) throws {
249
+ guard let epoch else { return }
250
+ let end = duration.map { min(end, epoch + $0) } ?? end
251
+ while epoch + CMTime(value: nextFrame, timescale: fps) < end {
252
+ let slot = epoch + CMTime(value: nextFrame, timescale: fps)
253
+ // Snap to the nearest output slot so a tiny PTS drift does not add a full frame of lag.
254
+ let cutoff = slot + CMTime(value: 1, timescale: fps * 2)
255
+ while let frame = pending.first, frame.0 <= cutoff {
256
+ image = pending.removeFirst().1
257
+ }
258
+ if try !appendFrame() { break }
259
+ }
260
+ }
261
+
262
+ private func appendFrame() throws -> Bool {
263
+ guard writer.status == .writing else { throw writeError }
264
+ guard input.isReadyForMoreMediaData else { return false }
265
+ guard let image else { throw writeError }
266
+ let pts = CMTime(value: nextFrame, timescale: fps)
267
+ guard adaptor.append(image, withPresentationTime: pts) else { throw writeError }
268
+ nextFrame += 1
269
+ return true
270
+ }
271
+
272
+ func abort() async {
273
+ await withCheckedContinuation { continuation in
274
+ queue.async {
275
+ self.ending = true
276
+ self.timer?.cancel()
277
+ self.writer.cancelWriting()
278
+ continuation.resume()
279
+ }
280
+ }
281
+ }
282
+
283
+ func finish(at end: CMTime) async throws -> Double {
284
+ try await withCheckedThrowingContinuation { continuation in
285
+ queue.async {
286
+ self.ending = true
287
+ self.timer?.cancel()
288
+ guard let epoch = self.epoch else {
289
+ self.writer.cancelWriting()
290
+ continuation.resume(throwing: self.failure ?? CaptureError("No screen frames were recorded."))
291
+ return
292
+ }
293
+ self.finishFrames(at: end, epoch: epoch, retries: 100, continuation: continuation)
294
+ }
295
+ }
296
+ }
297
+
298
+ private func finishFrames(at end: CMTime, epoch: CMTime, retries: Int, continuation: CheckedContinuation<Double, Error>) {
299
+ do {
300
+ if let failure { throw failure }
301
+ try fill(until: end)
302
+ let duration = CMTime(value: nextFrame, timescale: fps)
303
+ let requestedEnd = self.duration.map { min(end, epoch + $0) } ?? end
304
+ if epoch + duration < requestedEnd {
305
+ guard retries > 0 else { throw writeError }
306
+ queue.asyncAfter(deadline: .now() + .milliseconds(10)) {
307
+ self.finishFrames(at: end, epoch: epoch, retries: retries - 1, continuation: continuation)
308
+ }
309
+ return
310
+ }
311
+ writer.endSession(atSourceTime: duration)
312
+ input.markAsFinished()
313
+ writer.finishWriting {
314
+ if self.writer.status == .completed {
315
+ continuation.resume(returning: duration.seconds)
316
+ } else {
317
+ continuation.resume(throwing: self.writeError)
318
+ }
319
+ }
320
+ } catch {
321
+ writer.cancelWriting()
322
+ continuation.resume(throwing: error)
323
+ }
324
+ }
325
+ }
@@ -0,0 +1,219 @@
1
+ import AVFoundation
2
+ import CoreGraphics
3
+ import Foundation
4
+ import ScreenCaptureKit
5
+
6
+ private let usage = """
7
+ Usage: framepress-capture displays
8
+ framepress-capture record --out <dir> [--display <id> | --window <title or bundle id>] [--fps 60] [--duration <s>]
9
+ """
10
+
11
+ private struct Options {
12
+ let out: URL
13
+ let display: UInt32?
14
+ let window: String?
15
+ let fps: Int32
16
+ let duration: Double?
17
+
18
+ init(_ args: ArraySlice<String>) throws {
19
+ var values: [String: String] = [:]
20
+ var args = args.makeIterator()
21
+ while let flag = args.next() {
22
+ guard ["--out", "--display", "--window", "--fps", "--duration"].contains(flag),
23
+ values[flag] == nil, let value = args.next(), !value.isEmpty, !value.hasPrefix("--") else {
24
+ throw CaptureError(usage)
25
+ }
26
+ values[flag] = value
27
+ }
28
+ guard let path = values["--out"], values["--window"] == nil || values["--display"] == nil else {
29
+ throw CaptureError(usage)
30
+ }
31
+ out = URL(fileURLWithPath: path, isDirectory: true)
32
+ display = values["--display"].flatMap(UInt32.init)
33
+ guard values["--display"] == nil || display != nil else { throw CaptureError("--display expects a numeric display ID.") }
34
+ window = values["--window"]
35
+ guard let rate = Int32(values["--fps"] ?? "60"), (1...120).contains(rate) else {
36
+ throw CaptureError("--fps must be an integer from 1 through 120.")
37
+ }
38
+ fps = rate
39
+ duration = values["--duration"].flatMap(Double.init)
40
+ if values["--duration"] != nil {
41
+ guard let duration, duration.isFinite, duration > 0, duration < Double(Int64.max) / 600_000 else {
42
+ throw CaptureError("--duration must be a positive number of seconds.")
43
+ }
44
+ }
45
+ }
46
+ }
47
+
48
+ @main enum Command {
49
+ @MainActor static func main() async {
50
+ do {
51
+ let args = CommandLine.arguments.dropFirst()
52
+ switch Array(args) {
53
+ case ["displays"]:
54
+ try listDisplays()
55
+ case ["--help"], ["-h"], ["record", "--help"]:
56
+ print(usage)
57
+ default:
58
+ guard args.first == "record" else { throw CaptureError(usage) }
59
+ try await record(Options(args.dropFirst()))
60
+ }
61
+ } catch {
62
+ diagnostic(error.localizedDescription)
63
+ exit(1)
64
+ }
65
+ }
66
+
67
+ private static func listDisplays() throws {
68
+ var count: UInt32 = 0
69
+ guard CGGetActiveDisplayList(0, nil, &count) == .success else { throw CaptureError("Cannot enumerate displays.") }
70
+ var ids = [CGDirectDisplayID](repeating: 0, count: Int(count))
71
+ guard CGGetActiveDisplayList(count, &ids, &count) == .success else { throw CaptureError("Cannot enumerate displays.") }
72
+ let displays: [[String: Any]] = ids.prefix(Int(count)).map { id in
73
+ let bounds = CGDisplayBounds(id)
74
+ let mode = CGDisplayCopyDisplayMode(id)
75
+ return [
76
+ "id": id, "main": CGDisplayIsMain(id) != 0,
77
+ "width_px": mode?.pixelWidth ?? CGDisplayPixelsWide(id),
78
+ "height_px": mode?.pixelHeight ?? CGDisplayPixelsHigh(id),
79
+ "display_points": ["w": bounds.width, "h": bounds.height],
80
+ "origin_points": ["x": bounds.minX, "y": bounds.minY],
81
+ ]
82
+ }
83
+ try FileHandle.standardOutput.write(contentsOf: jsonData(displays))
84
+ }
85
+
86
+ @MainActor private static func record(_ options: Options) async throws {
87
+ guard CGPreflightScreenCaptureAccess() else { throw CaptureError(permissionMessage) }
88
+ let content = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: true)
89
+ let source = try Source(content: content, display: options.display, window: options.window)
90
+ guard source.width > 0, source.height > 0 else { throw CaptureError("Capture source has no visible pixels.") }
91
+
92
+ let files = FileManager.default
93
+ try files.createDirectory(at: options.out, withIntermediateDirectories: true)
94
+ let lock = options.out.appendingPathComponent(".framepress-capture.lock")
95
+ let fd = open(lock.path, O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR)
96
+ guard fd >= 0 else { throw CaptureError("Cannot reserve output directory at \(options.out.path). Use a fresh writable directory.") }
97
+ close(fd)
98
+ defer { try? files.removeItem(at: lock) }
99
+
100
+ let movie = options.out.appendingPathComponent("screen.mov")
101
+ let events = options.out.appendingPathComponent("events.jsonl")
102
+ let meta = options.out.appendingPathComponent("meta.json")
103
+ let frames = source.window == nil ? nil : options.out.appendingPathComponent("window.jsonl")
104
+ let paths = [movie, events, meta] + (frames.map { [$0] } ?? [])
105
+ guard paths.allSatisfy({ !files.fileExists(atPath: $0.path) }) else {
106
+ throw CaptureError("Recording output already exists. Choose a fresh directory.")
107
+ }
108
+ var completed = false
109
+ defer {
110
+ if !completed { for path in paths { try? files.removeItem(at: path) } }
111
+ }
112
+
113
+ let (streamStates, states) = AsyncStream<CaptureState>.makeStream()
114
+ let signals = [SIGINT, SIGTERM].map { number in
115
+ signal(number, SIG_IGN)
116
+ let source = DispatchSource.makeSignalSource(signal: number, queue: .main)
117
+ source.setEventHandler { states.yield(.stop(hostTime())) }
118
+ source.resume()
119
+ return source
120
+ }
121
+ defer { for signal in signals { signal.cancel() } }
122
+
123
+ let corner = await measureCornerRadius(source)
124
+ let video = try Video(url: movie, source: source, fps: options.fps, duration: options.duration, states: states)
125
+ let config = SCStreamConfiguration()
126
+ config.width = source.width
127
+ config.height = source.height
128
+ config.captureResolution = .best
129
+ config.pixelFormat = Video.pixelFormat
130
+ config.minimumFrameInterval = CMTime(value: 1, timescale: options.fps)
131
+ config.showsCursor = false
132
+ config.ignoreShadowsSingleWindow = true
133
+ config.queueDepth = 6
134
+ let stream = SCStream(filter: source.filter, configuration: config, delegate: video)
135
+ try stream.addStreamOutput(video, type: .screen, sampleHandlerQueue: video.queue)
136
+ do {
137
+ try await stream.startCapture()
138
+ } catch {
139
+ await video.abort()
140
+ throw error
141
+ }
142
+
143
+ let startup = Task {
144
+ try await Task.sleep(for: .seconds(10))
145
+ states.yield(.failed(CaptureError("ScreenCaptureKit delivered no usable frame within 10 seconds.")))
146
+ }
147
+ var autoStop: Task<Void, Error>?
148
+ var input: Input?
149
+ var startedAt: Date?
150
+ var end = hostTime()
151
+ var error: Error?
152
+ defer {
153
+ startup.cancel()
154
+ autoStop?.cancel()
155
+ states.finish()
156
+ }
157
+ recording: for await state in streamStates {
158
+ switch state {
159
+ case .ready(let epoch):
160
+ startup.cancel()
161
+ startedAt = Date().addingTimeInterval(epoch.seconds - hostTime().seconds)
162
+ do {
163
+ input = try Input(file: events, windowFile: frames, source: source, epoch: epoch, states: states)
164
+ input?.start()
165
+ } catch let inputError {
166
+ error = inputError
167
+ break recording
168
+ }
169
+ if let duration = options.duration {
170
+ let deadline = epoch + CMTime(seconds: duration, preferredTimescale: 600_000)
171
+ autoStop = Task {
172
+ try await Task.sleep(for: .seconds(max(0, (deadline - hostTime()).seconds)))
173
+ states.yield(.stop(deadline))
174
+ }
175
+ }
176
+ diagnostic(readyMessage)
177
+ case .stop(let deadline):
178
+ end = deadline
179
+ break recording
180
+ case .failed(let captureError):
181
+ error = captureError
182
+ break recording
183
+ }
184
+ }
185
+ input?.stop()
186
+ try? await stream.stopCapture()
187
+ if let error {
188
+ await video.abort()
189
+ throw error
190
+ }
191
+ let duration = try await video.finish(at: end)
192
+ try input?.finish(duration: duration)
193
+ guard let startedAt else { throw CaptureError("Stopped before the first screen frame.") }
194
+ let dateFormat = ISO8601DateFormatter()
195
+ dateFormat.formatOptions.insert(.withFractionalSeconds)
196
+ var payload: [String: Any] = [
197
+ "version": 1, "fps": options.fps, "width_px": source.width, "height_px": source.height,
198
+ "scale": source.scale, "display_points": ["w": source.bounds.width, "h": source.bounds.height],
199
+ "origin_points": ["x": source.bounds.minX, "y": source.bounds.minY],
200
+ "started_at": dateFormat.string(from: startedAt),
201
+ "cursor_hidden": true, "duration_s": duration,
202
+ ]
203
+ if let window = source.window {
204
+ // display_points and origin_points describe the window at the first frame.
205
+ payload["source"] = "window"
206
+ payload["window"] = [
207
+ "id": window.windowID, "title": window.title ?? "",
208
+ "bundle_id": window.owningApplication?.bundleIdentifier ?? "",
209
+ "app": window.owningApplication?.applicationName ?? "",
210
+ ]
211
+ payload["corner_radius_points"] = corner ?? defaultCornerRadius
212
+ payload["corner_radius_source"] = corner == nil ? "default" : "measured"
213
+ } else {
214
+ payload["source"] = "display"
215
+ }
216
+ try jsonData(payload).write(to: meta, options: .atomic)
217
+ completed = true
218
+ }
219
+ }