oficina / meet Public

Clone
git clone https://amadan.net/oficina/meet

Plain git — no account needed to clone.

Download

Download this file

1import CoreVideo
2import Foundation
3import CallsKit
4import LiveKitWebRTC
5
6/// Two synthetic cameras behind the app's own camera management
7/// (`ManagedCamera`), so the gate drives the same choice, switching and
8/// recovery code the apps run — only the frames are made up.
9///
10/// The cameras differ only in frame size, so that a switch is something
11/// the far side can *see* rather than something this side merely claims.
12/// There is no camera in CI; what the gate can still hold is the plumbing
13/// — that a switch is serialised, that the track and its m-line survive
14/// it, that frames keep arriving across it, and (`stall`) that a camera
15/// which stops sending is noticed and restarted.
16@MainActor final class SyntheticCameras: CameraBackend {
17 private var delegate: RTCVideoCapturerDelegate?
18 private var syntheticCapturer: RTCVideoCapturer?
19 private var task: Task<Void, Never>?
20 private var chosen = SyntheticCameras.first
21 /// Set by the gate: frames stop until the camera is next opened, as an
22 /// ATEM's do when its input changes format.
23 var stalled = false
24 nonisolated static let first = "synthetic-320"
25 nonisolated static let second = "synthetic-480"
26 private var width: Int { chosen == SyntheticCameras.second ? 480 : 320 }
27 private var height: Int { chosen == SyntheticCameras.second ? 360 : 240 }
28 var devicesChanged: (@MainActor () -> Void)?
29 var trouble: (@MainActor () -> Void)?
30
31 func requestAccess() async throws {}
32
33 var devices: [CameraDevice] {
34 [
35 CameraDevice(id: SyntheticCameras.first, name: "Synthetic 320x240"),
36 CameraDevice(id: SyntheticCameras.second, name: "Synthetic 480x360"),
37 ]
38 }
39 func formatCount(_ id: String) -> Int { 1 }
40
41 func open(_ id: String, format: Int, delegate: RTCVideoCapturerDelegate) async throws {
42 guard devices.contains(where: { $0.id == id }) else {
43 throw NSError(
44 domain: "Calls", code: 4,
45 userInfo: [NSLocalizedDescriptionKey: "That camera is no longer available."])
46 }
47 chosen = id
48 stalled = false
49 self.delegate = delegate
50 syntheticCapturer = RTCVideoCapturer(delegate: delegate)
51 task?.cancel()
52 task = Task { @MainActor [weak self] in
53 while !Task.isCancelled {
54 self?.frame()
55 try? await Task.sleep(nanoseconds: 66_666_667)
56 }
57 }
58 }
59 func close() async {
60 task?.cancel()
61 task = nil
62 }
63 private func frame() {
64 guard !stalled, let delegate, let syntheticCapturer else { return }
65 var pixel: CVPixelBuffer?
66 CVPixelBufferCreate(
67 kCFAllocatorDefault, width, height, kCVPixelFormatType_32BGRA,
68 [kCVPixelBufferIOSurfacePropertiesKey: [:]] as CFDictionary, &pixel)
69 guard let pixel else { return }
70 CVPixelBufferLockBaseAddress(pixel, [])
71 if let base = CVPixelBufferGetBaseAddress(pixel) {
72 memset(
73 base, Int32(Int(Date().timeIntervalSince1970 * 30) % 200 + 30),
74 CVPixelBufferGetDataSize(pixel))
75 }
76 CVPixelBufferUnlockBaseAddress(pixel, [])
77 delegate.capturer(
78 syntheticCapturer,
79 didCapture: RTCVideoFrame(
80 buffer: RTCCVPixelBuffer(pixelBuffer: pixel), rotation: ._0,
81 timeStampNs: Int64(ProcessInfo.processInfo.systemUptime * 1_000_000_000)))
82 }
83}
84
85/// A screen with nothing on it but frames, for the gates: there is no
86/// display to share in CI and no person to answer a picker. What it can
87/// still hold is everything after the picker — the source, the sendonly
88/// transceiver, the `share` message, and both of §5.4's endings, the
89/// button's and the capture's own (`end`, which is the system's stop
90/// control as far as the call can tell).
91@MainActor final class SyntheticScreen: ScreenCapture {
92 private var source: RTCVideoSource?
93 private var capturer: RTCVideoCapturer?
94 private var task: Task<Void, Never>?
95 private var ended: (@MainActor () -> Void)?
96 /// A 1920×1080 page of text scrolling at 30 frames a second, for the
97 /// motion gate: what someone scrolling a document looks like to the
98 /// encoder, which is where a screencast source falls behind.
99 private let page: ScrollingPage?
100
101 init(motion: Bool = false) { page = motion ? ScrollingPage() : nil }
102 /// A still page, as the Mac's real capture sends one (2026-10-21, a
103 /// Safari receiver reporting stalls every 40 s): the page once, then the
104 /// same pixels again once a second while nothing changes, as
105 /// MacScreenCapture's repeat does; and, every `changeEvery` seconds
106 /// (never when zero), a new view of the page, as a slide advancing or a
107 /// scroll would.
108 init(stillChangingEvery changeEvery: Double) { page = ScrollingPage(stillChangingEvery: changeEvery) }
109
110 func start(source: RTCVideoSource, ended: @escaping @MainActor () -> Void) async throws {
111 self.source = source
112 self.ended = ended
113 let capturer = RTCVideoCapturer(delegate: source)
114 self.capturer = capturer
115 if let page {
116 // Off the main actor and on a timer of its own, as a real capture
117 // is: the gate measures WebRTC, not this process's main thread.
118 page.start(source: source, capturer: capturer)
119 return
120 }
121 task = Task { @MainActor [weak self] in
122 while !Task.isCancelled {
123 self?.frame()
124 try? await Task.sleep(nanoseconds: 100_000_000)
125 }
126 }
127 }
128 /// Frames the moving page has produced, for the gate.
129 var produced: Int { page?.produced ?? 0 }
130 /// A capture that has stalled: no frames, and nothing else either, until
131 /// the watchdog restarts it (`screen-stall`).
132 var stalled = false
133 private var made: UInt64 = 0
134 private(set) var restarts = 0
135 var counts: ScreenCaptureCounts {
136 let n = page.map { UInt64($0.produced) } ?? made
137 return ScreenCaptureCounts(heartbeats: n, delivered: n)
138 }
139 var frameSize: (width: Int, height: Int)? { page != nil ? (ScrollingPage.width, ScrollingPage.height) : (640, 360) }
140 func restart() async -> Bool {
141 guard source != nil else { return false }
142 restarts += 1
143 stalled = false
144 page?.stalled = false
145 return true
146 }
147 func stall() {
148 stalled = true
149 page?.stalled = true
150 }
151 func stop() {
152 page?.stop()
153 task?.cancel()
154 task = nil
155 source = nil
156 capturer = nil
157 ended = nil
158 }
159 /// The capture ending on its own, as a shared window closing would.
160 func end() {
161 let ended = self.ended
162 stop()
163 ended?()
164 }
165 private func frame() {
166 guard let source, let capturer, !stalled else { return }
167 made += 1
168 // A 16:9 screen, wider than either synthetic camera, so the far side
169 // can tell by size alone which one it is decoding.
170 var pixel: CVPixelBuffer?
171 CVPixelBufferCreate(
172 kCFAllocatorDefault, 640, 360, kCVPixelFormatType_32BGRA,
173 [kCVPixelBufferIOSurfacePropertiesKey: [:]] as CFDictionary, &pixel)
174 guard let pixel else { return }
175 CVPixelBufferLockBaseAddress(pixel, [])
176 if let base = CVPixelBufferGetBaseAddress(pixel) {
177 memset(
178 base, Int32(Int(Date().timeIntervalSince1970 * 10) % 100 + 120),
179 CVPixelBufferGetDataSize(pixel))
180 }
181 CVPixelBufferUnlockBaseAddress(pixel, [])
182 source.capturer(
183 capturer,
184 didCapture: RTCVideoFrame(
185 buffer: RTCCVPixelBuffer(pixelBuffer: pixel), rotation: ._0,
186 timeStampNs: Int64(ProcessInfo.processInfo.systemUptime * 1_000_000_000)))
187 }
188}
189
190/// Lines of dark "glyphs" on white, twice a screen tall, shown through a
191/// 1920×1080 window that moves down 12 rows a frame and wraps: a fast
192/// scroll through a dense document, at 30 frames a second, with a window
193/// dragged across it. Built once;
194/// each frame is row copies into a pooled buffer, on a queue of its own.
195final class ScrollingPage: @unchecked Sendable {
196 static let width = 1920
197 /// 1080 unless `CALLS_SYNTHETIC_SCREEN_HEIGHT` says otherwise: 1246 is a
198 /// 16:10 Retina display as the Mac's capture fits it to 1920 wide, the
199 /// size that meets H.264 level 3.1's block limit (spec §15.21, §15.22).
200 static let height = Int(ProcessInfo.processInfo.environment["CALLS_SYNTHETIC_SCREEN_HEIGHT"] ?? "") ?? 1080
201 private let rows = ScrollingPage.height * 2
202 private let texture: [UInt8]
203 private var offset = 0
204 private var frame = 0
205 private let queue = DispatchQueue(label: "calls.synthetic-screen", qos: .userInteractive)
206 private var timer: DispatchSourceTimer?
207 private var pool: CVPixelBufferPool?
208 private let lock = NSLock()
209 private var count = 0
210 var produced: Int { lock.withLock { count } }
211 private var stalledFlag = false
212 /// Set by the gate's `screen-stall`: no frames until cleared.
213 var stalled: Bool {
214 get { lock.withLock { stalledFlag } }
215 set { lock.withLock { stalledFlag = newValue } }
216 }
217
218 /// Nil for the 30 fps scroll; otherwise a still page, changed this
219 /// often (never when zero) and repeated once a second between changes.
220 private let changeEvery: Double?
221 private var last: CVPixelBuffer?
222 private var lastSent = 0.0
223 private var lastChange = 0.0
224
225 init(stillChangingEvery changeEvery: Double? = nil) {
226 self.changeEvery = changeEvery
227 let stride = Self.width * 4
228 var texture = [UInt8](repeating: 0xF4, count: stride * rows)
229 var seed: UInt64 = 0x9E37_79B9_7F4A_7C15
230 func random(_ n: Int) -> Int {
231 seed = seed &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407
232 return Int((seed >> 33) % UInt64(n))
233 }
234 let rows = self.rows
235 texture.withUnsafeMutableBytes { raw in
236 guard let base = raw.baseAddress else { return }
237 var line = 8
238 while line + 16 < rows {
239 var x = 40 + random(40)
240 let end = Self.width - 40 - random(600)
241 while x < end {
242 let glyph = 5 + random(9)
243 let tall = 9 + random(6)
244 let shade = Int32(20 + random(60))
245 for y in (line + 14 - tall)..<(line + 14) {
246 memset(base + y * stride + x * 4, shade, min(glyph, end - x) * 4)
247 }
248 x += glyph + 2 + (random(6) == 0 ? 8 : 0)
249 }
250 line += 22
251 }
252 }
253 self.texture = texture
254 CVPixelBufferPoolCreate(
255 kCFAllocatorDefault, nil,
256 [
257 kCVPixelBufferWidthKey: Self.width, kCVPixelBufferHeightKey: Self.height,
258 kCVPixelBufferPixelFormatTypeKey: kCVPixelFormatType_32BGRA,
259 kCVPixelBufferIOSurfacePropertiesKey: [:],
260 ] as CFDictionary, &pool)
261 }
262
263 func start(source: RTCVideoSource, capturer: RTCVideoCapturer) {
264 if let changeEvery {
265 startStill(source: source, capturer: capturer, changeEvery: changeEvery)
266 return
267 }
268 // Strict: a lenient timer on a background process is coalesced to a
269 // third of this rate, which measured the timer and not WebRTC.
270 let timer = DispatchSource.makeTimerSource(flags: .strict, queue: queue)
271 timer.schedule(deadline: .now(), repeating: .nanoseconds(33_333_333), leeway: .milliseconds(2))
272 timer.setEventHandler { [weak self] in
273 guard let self, !self.stalled, let pixel = self.next() else { return }
274 source.capturer(
275 capturer,
276 didCapture: RTCVideoFrame(
277 buffer: RTCCVPixelBuffer(pixelBuffer: pixel), rotation: ._0,
278 timeStampNs: Int64(DispatchTime.now().uptimeNanoseconds)))
279 self.lock.withLock { self.count += 1 }
280 }
281 self.timer = timer
282 timer.resume()
283 }
284
285 /// MacScreenCapture.ScreenFrames' shape: a timer every half second that
286 /// sends the last frame again when a second has passed since anything
287 /// was sent, with a fresh capture time, the same pixel buffer.
288 private func startStill(source: RTCVideoSource, capturer: RTCVideoCapturer, changeEvery: Double) {
289 let timer = DispatchSource.makeTimerSource(flags: .strict, queue: queue)
290 timer.schedule(deadline: .now(), repeating: .milliseconds(500), leeway: .milliseconds(50))
291 timer.setEventHandler { [weak self] in
292 guard let self, !self.stalled else { return }
293 let now = Double(DispatchTime.now().uptimeNanoseconds) / 1e9
294 if self.last == nil || (changeEvery > 0 && now - self.lastChange >= changeEvery) {
295 self.offset = (self.offset + 22 * 9) % self.rows
296 self.last = self.next(still: true)
297 self.lastChange = now
298 } else if now - self.lastSent < 1 {
299 return
300 }
301 guard let pixel = self.last else { return }
302 self.lastSent = now
303 source.capturer(
304 capturer,
305 didCapture: RTCVideoFrame(
306 buffer: RTCCVPixelBuffer(pixelBuffer: pixel), rotation: ._0,
307 timeStampNs: Int64(DispatchTime.now().uptimeNanoseconds)))
308 self.lock.withLock { self.count += 1 }
309 }
310 self.timer = timer
311 timer.resume()
312 }
313
314 func stop() {
315 timer?.cancel()
316 timer = nil
317 }
318
319 private func bounce(_ travelled: Int, _ span: Int) -> Int {
320 let lap = travelled % (2 * span)
321 return lap < span ? lap : 2 * span - lap
322 }
323
324 private func next(still: Bool = false) -> CVPixelBuffer? {
325 guard let pool else { return nil }
326 var pixel: CVPixelBuffer?
327 CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, pool, &pixel)
328 guard let pixel else { return nil }
329 CVPixelBufferLockBaseAddress(pixel, [])
330 defer { CVPixelBufferUnlockBaseAddress(pixel, []) }
331 guard let base = CVPixelBufferGetBaseAddress(pixel) else { return nil }
332 let destination = CVPixelBufferGetBytesPerRow(pixel)
333 let stride = Self.width * 4
334 let first = offset
335 let rows = self.rows
336 frame += 1
337 // A window being dragged across the page — 800×450, moving 10 rows
338 // and 14 columns a frame and bouncing off the edges — whose content
339 // changes every half second, as a page loading or a slide advancing
340 // would. Together with the scroll beneath it, what someone moving
341 // things around a busy screen sends the encoder.
342 let span = (x: Self.width - 800, y: Self.height - 450)
343 let wx = bounce(frame * 14, span.x)
344 let wy = bounce(frame * 10, span.y)
345 let scene = frame / 15
346 let jump = (scene &* 7919) % (rows - 450)
347 let shift = ((scene &* 104_729) % 900) * 4
348 texture.withUnsafeBytes { raw in
349 guard let source = raw.baseAddress else { return }
350 for y in 0..<Self.height {
351 memcpy(base + y * destination, source + ((first + y) % rows) * stride, stride)
352 if !still, y >= wy, y < wy + 450 {
353 memcpy(base + y * destination + wx * 4, source + (jump + y - wy) * stride + shift, 800 * 4)
354 }
355 }
356 }
357 if !still { offset = (offset + 12) % rows }
358 return pixel
359 }
360}
361