oficina / meet Public

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

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2import XCTest
3
4@testable import CallsKit
5
6/// Spec §15.30: the receiver's watch (down fast, up slow, a failed probe
7/// doubling the wait), what a sender sends at each level (the camera giving
8/// way before a shared screen, a screen never paused), the media report's
9/// `video`, and the quality report's seconds — on a fake clock. The twin of
10/// test/browser/room-adapt.test.mjs, number for number.
11final class VideoAdaptTests: XCTestCase {
12 typealias Sample = VideoAdapt.Sample
13
14 private func clean(
15 freezes: Double = 0, freezeSeconds: Double = 0, keyframeAsks: Double = 0, packets: Double = 100,
16 lost: Double = 0, rtt: Double? = 80, jitterBufferMs: Double? = 60, decoded: Double = 30, dropped: Double = 0
17 ) -> Sample {
18 Sample(
19 freezes: freezes, freezeSeconds: freezeSeconds, keyframeAsks: keyframeAsks, packets: packets, lost: lost,
20 rtt: rtt, jitterBufferMs: jitterBufferMs, decoded: decoded, dropped: dropped)
21 }
22
23 /// Trouble that is not severe: a freeze every four seconds.
24 private func freezing(_ t: Int) -> Sample { clean(freezes: t % 4 == 0 ? 1 : 0) }
25
26 /// Once a second from `from` to `to`; the seconds the level changed at.
27 @discardableResult
28 private func run(_ watch: inout VideoAdapt, _ from: Int, _ to: Int, _ at: (Int) -> Sample?) -> [[Int]] {
29 var changes: [[Int]] = []
30 for t in from...to {
31 let before = watch.level
32 watch.observe(at: Double(t), at(t))
33 if watch.level != before { changes.append([t, watch.level.rawValue]) }
34 }
35 return changes
36 }
37
38 func testTheNumbersAreTheApprovedOnes() {
39 XCTAssertEqual(VideoAdapt.upAfter, 45)
40 XCTAssertEqual(VideoAdapt.upMax, 300)
41 XCTAssertEqual(VideoAdapt.window, 10)
42 XCTAssertEqual(VideoAdapt.probeWatch, 20)
43 }
44
45 func testTroubleThatLastsStepsDownEveryTenSecondsToAudioOnly() {
46 var w = VideoAdapt()
47 XCTAssertEqual(run(&w, 0, 60, freezing), [[10, 1], [20, 2], [30, 3]])
48 XCTAssertEqual(w.level, .audio)
49 XCTAssertEqual(w.downs, 3)
50 }
51
52 func testSevereTroubleStepsTwoLevelsFiveSecondsIn() {
53 var w = VideoAdapt()
54 XCTAssertEqual(run(&w, 0, 12) { _ in self.clean(freezes: 2) }, [[5, 2], [10, 3]])
55 var lossy = VideoAdapt()
56 XCTAssertEqual(run(&lossy, 0, 6) { _ in self.clean(packets: 80, lost: 20) }, [[5, 2]])
57 }
58
59 func testOccasionalTroubleIsNotTrouble() {
60 var rare = VideoAdapt()
61 XCTAssertEqual(run(&rare, 0, 60) { t in self.clean(freezes: t % 11 == 0 ? 1 : 0) }, [])
62 var lossy = VideoAdapt()
63 XCTAssertEqual(run(&lossy, 0, 60) { _ in self.clean(packets: 97, lost: 3) }, [])
64 var slow = VideoAdapt()
65 XCTAssertEqual(run(&slow, 0, 60) { _ in self.clean(rtt: 900) }, [])
66 }
67
68 func testEachKindOfTroubleStepsDown() {
69 let kinds: [(String, (Int) -> Sample)] = [
70 ("loss", { _ in self.clean(packets: 94, lost: 6) }),
71 ("one freeze on a 700 ms round trip", { t in self.clean(freezes: t == 5 ? 1 : 0, rtt: 700) }),
72 ("the jitter buffer", { _ in self.clean(jitterBufferMs: 650) }),
73 ("frames dropped", { _ in self.clean(decoded: 20, dropped: 10) }),
74 ("one long freeze", { t in self.clean(freezes: t == 5 ? 1 : 0, freezeSeconds: t == 5 ? 2.5 : 0) }),
75 ("a keyframe asked for every three seconds", { t in self.clean(keyframeAsks: t % 3 == 0 ? 1 : 0) }),
76 ]
77 for (what, sample) in kinds {
78 var w = VideoAdapt()
79 XCTAssertEqual(run(&w, 0, 10, sample), [[10, 1]], what)
80 }
81 }
82
83 func testTheRoundTripIsTheMedian() {
84 var w = VideoAdapt()
85 XCTAssertEqual(
86 run(&w, 0, 30) { t in self.clean(freezes: t % 10 == 3 ? 1 : 0, rtt: t % 10 == 3 ? 2000 : 100) }, [])
87 }
88
89 func testNothingMeasuredIsNoNews() {
90 var w = VideoAdapt()
91 run(&w, 0, 9, freezing)
92 XCTAssertEqual(run(&w, 10, 40) { _ in nil }, [])
93 XCTAssertEqual(w.level, .normal)
94 XCTAssertNil(VideoAdapt.sample(QualityCounters(), QualityCounters(), cameraWatched: true))
95 }
96
97 func testFreezesCountOnlyWhileTheCameraIsWatched() {
98 var before = QualityCounters()
99 before.inAudio = .init(packets: 100, lost: 1, bufferDelay: 3000, emitted: 48000)
100 before.inVideo = .init(packets: 200, freezes: 1, freezeSeconds: 0.5, decoded: 100, dropped: 0, keyframeAsks: 1)
101 before.inScreen = .init(packets: 50, lost: 0, decoded: 10)
102 var now = before
103 now.inAudio = .init(packets: 150, lost: 2, bufferDelay: 6360, emitted: 96000)
104 now.inVideo = .init(packets: 290, freezes: 3, freezeSeconds: 2, decoded: 130, dropped: 1, keyframeAsks: 3)
105 now.inScreen = .init(packets: 60, lost: 1, decoded: 11)
106 now.rtt = 50
107 let s = VideoAdapt.sample(now, before, cameraWatched: true)
108 XCTAssertEqual(s?.freezes, 2)
109 XCTAssertEqual(s?.freezeSeconds, 1.5)
110 XCTAssertEqual(s?.keyframeAsks, 2)
111 XCTAssertEqual(s?.packets, 150)
112 XCTAssertEqual(s?.lost, 2)
113 XCTAssertEqual(s?.rtt, 50)
114 XCTAssertEqual(s?.jitterBufferMs ?? 0, 70, accuracy: 0.01)
115 XCTAssertEqual(s?.decoded, 31)
116 XCTAssertEqual(s?.dropped, 1)
117 let off = VideoAdapt.sample(now, before, cameraWatched: false)
118 XCTAssertEqual(off?.freezes, 0)
119 XCTAssertEqual(off?.keyframeAsks, 0)
120 XCTAssertEqual(off?.packets, 150)
121 }
122
123 func testCleanSecondsStepUpAfterFortyFiveAndAgain() {
124 var w = VideoAdapt()
125 run(&w, 0, 20, freezing)
126 XCTAssertEqual(w.level, .minimal)
127 XCTAssertEqual(run(&w, 21, 200) { _ in self.clean() }, [[66, 1], [112, 0]])
128 XCTAssertEqual(w.upWait, VideoAdapt.upAfter)
129 }
130
131 func testAKeyframeAskedForIsNotACleanSecond() {
132 var w = VideoAdapt()
133 run(&w, 0, 10, freezing)
134 XCTAssertEqual(run(&w, 11, 120) { t in self.clean(keyframeAsks: t == 30 ? 1 : 0) }, [[76, 0]])
135 }
136
137 func testOneBadSecondResetsTheCleanRun() {
138 var w = VideoAdapt()
139 run(&w, 0, 10, freezing)
140 XCTAssertEqual(run(&w, 11, 120) { t in self.clean(lost: t == 40 ? 10 : 0) }, [[86, 0]])
141 }
142
143 func testAFailedProbeStepsBackAndDoublesTheWaitToFiveMinutes() {
144 var w = VideoAdapt()
145 run(&w, 0, 10, freezing)
146 XCTAssertEqual(w.level, .reduced)
147 var changes: [[Int]] = []
148 for t in 11...1200 {
149 let before = w.level
150 w.observe(at: Double(t), w.level == .normal ? clean(freezes: 1) : clean())
151 if w.level != before { changes.append([t, w.level.rawValue]) }
152 }
153 XCTAssertEqual(changes.filter { $0[1] == 0 }.map { $0[0] }, [56, 152, 338, 644, 950])
154 XCTAssertEqual(changes.filter { $0[1] == 1 }.map { $0[0] }, [61, 157, 343, 649, 955])
155 XCTAssertEqual(w.upWait, VideoAdapt.upMax)
156 }
157
158 func testTroubleAfterTheProbeWatchIsAnOrdinaryStepDown() {
159 var w = VideoAdapt()
160 run(&w, 0, 10, freezing)
161 run(&w, 11, 56) { _ in self.clean() }
162 XCTAssertEqual(w.level, .normal)
163 XCTAssertEqual(run(&w, 57, 100) { t in t >= 80 ? self.freezing(t) : self.clean() }, [[84, 1], [94, 2]])
164 XCTAssertEqual(w.upWait, VideoAdapt.upAfter)
165 }
166
167 func testTheSettingIsAFloorAndOnlyLevelsBelowNormalAreAsked() {
168 let a = String(repeating: "a", count: 32)
169 let b = String(repeating: "b", count: 32)
170 XCTAssertEqual(VideoAdapt.asks([a: .normal, b: .reduced], setting: .auto), [b: "reduced"])
171 XCTAssertEqual(VideoAdapt.asks([a: .normal, b: .reduced], setting: .low), [a: "minimal", b: "minimal"])
172 XCTAssertEqual(VideoAdapt.asks([a: .audio], setting: .low), [a: "audio"])
173 XCTAssertEqual(VideoAdapt.asks([a: .normal, b: .reduced], setting: .audio), [a: "audio", b: "audio"])
174 XCTAssertEqual(VideoAdapt.asks([a: .normal], setting: .auto), [:])
175 var many: [String: VideoLevel] = [:]
176 for i in 0..<20 { many[String(format: "%032x", i)] = .minimal }
177 XCTAssertEqual(VideoAdapt.asks(many, setting: .auto).count, 15)
178 }
179
180 func testASenderReadsOnlyItsOwnIdAndTheWiresLevels() {
181 let me = String(repeating: "a", count: 32)
182 XCTAssertEqual(VideoAdapt.asked(PeerMedia(muted: false, cameraOff: false, video: [me: "minimal"]), me: me), .minimal)
183 XCTAssertEqual(VideoAdapt.asked(PeerMedia(muted: false, cameraOff: false, video: [me: "minimal"]), me: "b"), .normal)
184 XCTAssertEqual(VideoAdapt.asked(PeerMedia(muted: false, cameraOff: false, video: [me: "tiny"]), me: me), .normal)
185 XCTAssertEqual(VideoAdapt.asked(PeerMedia(muted: false, cameraOff: false), me: me), .normal)
186 XCTAssertEqual(VideoAdapt.asked(nil, me: me), .normal)
187 }
188
189 func testTheCameraAtEachLevel() {
190 XCTAssertEqual(VideoAdapt.camera(.normal, sharing: false), EncodingPlan())
191 let reduced = VideoAdapt.camera(.reduced, sharing: false, width: 640, height: 480)
192 XCTAssertEqual(reduced.maxBitrate, 350_000)
193 XCTAssertEqual(reduced.maxFramerate, 15)
194 XCTAssertEqual(reduced.scaleResolutionDownBy ?? 0, 480.0 / 360, accuracy: 1e-9)
195 XCTAssertTrue(reduced.active)
196 XCTAssertEqual(VideoAdapt.camera(.reduced, sharing: false, width: 720, height: 1280).scaleResolutionDownBy, 2)
197 let minimal = VideoAdapt.camera(.minimal, sharing: false, width: 640, height: 480)
198 XCTAssertEqual(minimal.maxBitrate, 120_000)
199 XCTAssertEqual(minimal.maxFramerate, 8)
200 XCTAssertEqual(minimal.scaleResolutionDownBy ?? 0, 480.0 / 180, accuracy: 1e-9)
201 XCTAssertFalse(VideoAdapt.camera(.audio, sharing: false).active)
202 }
203
204 func testWhileSharingTheCameraGivesWayFirst() {
205 XCTAssertEqual(VideoAdapt.camera(.normal, sharing: true), ScreenSendPolicy.camera(sharing: true))
206 let reduced = VideoAdapt.camera(.reduced, sharing: true)
207 XCTAssertEqual(reduced.maxBitrate, 120_000)
208 XCTAssertTrue(reduced.active)
209 XCTAssertFalse(VideoAdapt.camera(.minimal, sharing: true).active)
210 XCTAssertFalse(VideoAdapt.camera(.audio, sharing: true).active)
211 }
212
213 func testAScreenKeepsItsSizeLosesFrameRateFirstAndIsNeverPaused() {
214 let plan = ScreenSendPolicy.screen(.balanced, width: 1920, height: 1080)
215 XCTAssertEqual(VideoAdapt.screen(plan, .normal, width: 1920, height: 1080), plan)
216 let reduced = VideoAdapt.screen(plan, .reduced, width: 1920, height: 1080)
217 XCTAssertEqual(reduced.maxFramerate, 10)
218 XCTAssertEqual(reduced.maxBitrate, 1_200_000)
219 XCTAssertEqual(reduced.scaleResolutionDownBy, plan.scaleResolutionDownBy, "the size is kept")
220 XCTAssertEqual(reduced.degradation, .maintainResolution)
221 let minimal = VideoAdapt.screen(plan, .minimal, width: 1920, height: 1080)
222 XCTAssertEqual(minimal.maxFramerate, 5)
223 XCTAssertEqual(minimal.maxBitrate, 500_000)
224 XCTAssertEqual(minimal.scaleResolutionDownBy, 1.5)
225 let audio = VideoAdapt.screen(plan, .audio, width: 1920, height: 1080)
226 XCTAssertEqual(audio, minimal)
227 XCTAssertTrue(audio.active)
228 // A level-fit scale larger than minimal's is kept (the H.264 rules).
229 let capped = ScreenSendPolicy.screen(.motion, width: 3840, height: 2160, screencast: false)
230 XCTAssertGreaterThanOrEqual(
231 VideoAdapt.screen(capped, .minimal, width: 3840, height: 2160).scaleResolutionDownBy ?? 0,
232 capped.scaleResolutionDownBy ?? 0)
233 }
234
235 func testBrowsersAndNewAppsHonourAnAsk() {
236 XCTAssertTrue(VideoAdapt.honours(client: nil))
237 XCTAssertTrue(VideoAdapt.honours(client: ""))
238 XCTAssertTrue(VideoAdapt.honours(client: "mac 0.4.15"))
239 XCTAssertFalse(VideoAdapt.honours(client: "mac 0.4.14"))
240 XCTAssertTrue(VideoAdapt.honours(client: "iphone 0.5"))
241 XCTAssertFalse(VideoAdapt.honours(client: "mac 0.4.13"))
242 XCTAssertFalse(VideoAdapt.honours(client: "native"))
243 XCTAssertFalse(VideoAdapt.honours(client: "something else"))
244 }
245
246 func testTheSendersNotice() {
247 XCTAssertEqual(VideoAdapt.noticeWords([]), "")
248 XCTAssertEqual(
249 VideoAdapt.noticeWords([("David", .minimal)]), "Sending reduced video to David (their connection is weak)")
250 XCTAssertEqual(VideoAdapt.noticeWords([("David", .audio)]), "Sending only audio to David (their connection is weak)")
251 XCTAssertEqual(
252 VideoAdapt.noticeWords([("David", .reduced), ("Ana", .audio), ("Cy", .minimal)]),
253 "Sending reduced video to David, Ana and Cy (their connections are weak)")
254 }
255
256 func testTheMediaReportReadsTheAsksLeniently() throws {
257 let me = String(repeating: "a", count: 32)
258 let ok = try JSONDecoder().decode(
259 PeerMedia.self, from: Data(#"{"muted":false,"cameraOff":false,"video":{"\#(me)":"audio"}}"#.utf8))
260 XCTAssertEqual(ok.video, [me: "audio"])
261 let odd = try JSONDecoder().decode(
262 PeerMedia.self, from: Data(#"{"muted":true,"cameraOff":false,"video":["\#(me)"],"hearing":[]}"#.utf8))
263 XCTAssertNil(odd.video, "a video member of another shape is taken as absent")
264 XCTAssertEqual(odd.muted, true)
265 XCTAssertEqual(odd.hearing, [])
266 }
267
268 func testTheQualityReportCarriesTheSecondsAtEachLevel() throws {
269 var tally = QualityEventTally()
270 tally.videoSetting = .low
271 tally.video(asked: .minimal, sent: .normal, seconds: 1, for: "p")
272 tally.video(asked: .minimal, sent: .reduced, seconds: 1.04, for: "p")
273 tally.video(asked: .normal, sent: .normal, seconds: 1, for: "q")
274 var builder = QualityReportBuilder()
275 builder.start(at: 0)
276 let report = builder.build(
277 at: 30, samples: [:], events: &tally, client: QualityClient(app: "mac", version: "0.4.15"), devices: nil,
278 final: false)
279 let body = try XCTUnwrap(report.encoded())
280 XCTAssertTrue(body.contains(#""askedSeconds":[0,2,0]"#), body)
281 XCTAssertTrue(body.contains(#""sentSeconds":[1,0,0]"#), body)
282 XCTAssertTrue(body.contains(#""videoSetting":"low""#), body)
283 XCTAssertFalse(body.contains(#""peer":"q""#), "a peer at normal both ways says nothing")
284 }
285
286 // MARK: - The sender's own watch, and the machine's load (2026-10-29)
287
288 func testThisDeviceStrugglingLowersItsOwnCameraAndCalmBringsItBack() {
289 var w = VideoAdapt()
290 XCTAssertEqual(run(&w, 0, 35) { _ in VideoAdapt.loadSample(struggling: true) }, [[10, 1], [20, 2], [30, 3]])
291 var calm = VideoAdapt()
292 run(&calm, 0, 10) { _ in VideoAdapt.loadSample(struggling: true) }
293 XCTAssertEqual(calm.level, .reduced)
294 XCTAssertEqual(run(&calm, 11, 60) { _ in VideoAdapt.loadSample(struggling: false) }, [[56, 0]])
295 var brief = VideoAdapt()
296 XCTAssertEqual(run(&brief, 0, 60) { t in VideoAdapt.loadSample(struggling: t % 10 < 7) }, [], "seven in ten is not sustained")
297 }
298
299 func testWhatCountsAsStruggling() {
300 XCTAssertTrue(VideoAdapt.struggling(thermal: .serious, cpuPct: 10, mac: false))
301 XCTAssertTrue(VideoAdapt.struggling(thermal: .critical, cpuPct: nil, mac: true))
302 XCTAssertFalse(VideoAdapt.struggling(thermal: .fair, cpuPct: 140, mac: true))
303 XCTAssertTrue(VideoAdapt.struggling(thermal: .nominal, cpuPct: 151, mac: true))
304 XCTAssertFalse(VideoAdapt.struggling(thermal: .nominal, cpuPct: 400, mac: false), "the iPhone goes by its thermal state")
305 }
306
307 func testTheOwnLevelLowersTheCameraNotTheScreen() {
308 // The camera at the larger of what they ask and this device's own.
309 XCTAssertEqual(VideoAdapt.camera(max(.normal, .minimal), sharing: false).maxBitrate, 120_000)
310 let plan = ScreenSendPolicy.screen(.balanced, width: 1920, height: 1080)
311 XCTAssertEqual(VideoAdapt.screen(plan, .normal, width: 1920, height: 1080), plan, "the screen goes by the ask alone")
312 }
313
314 func testTheHostLoadOverAWindow() {
315 typealias R = HostLoadSampler.Reading
316 var h = HostLoadSampler()
317 XCTAssertNil(h.tick(R(at: 0, cpuSeconds: 10, thermal: .nominal, lowPower: false)))
318 XCTAssertEqual(h.tick(R(at: 1, cpuSeconds: 11.6, thermal: .fair, lowPower: false)) ?? 0, 160, accuracy: 1e-9)
319 _ = h.tick(R(at: 2, cpuSeconds: 12, thermal: .serious, lowPower: true))
320 let host = h.take(R(at: 30, cpuSeconds: 25, thermal: .nominal, lowPower: false, memMB: 412.04, load1: 6.21))
321 XCTAssertEqual(host.procCpuPct, 50, "15 s of CPU in 30")
322 XCTAssertEqual(host.procMemMB, 412)
323 XCTAssertEqual(host.sysLoad1, 6.2)
324 XCTAssertEqual(host.thermal, "serious", "the worst in the window")
325 XCTAssertEqual(host.lowPower, true)
326 let next = h.take(R(at: 60, cpuSeconds: 25, thermal: .nominal, lowPower: false))
327 XCTAssertEqual(next.procCpuPct, 0)
328 XCTAssertEqual(next.thermal, "nominal")
329 XCTAssertEqual(next.lowPower, false)
330 XCTAssertNil(next.procMemMB)
331 }
332
333 func testTheHostLoadIsInTheReport() throws {
334 var report = QualityReport(seconds: 30, client: QualityClient(app: "mac", version: "0.4.15"))
335 report.host = QualityHost(procCpuPct: 182.5, procMemMB: 412, sysLoad1: 6.2, thermal: "serious", lowPower: false)
336 let body = try XCTUnwrap(report.encoded())
337 XCTAssertTrue(
338 body.contains(#""host":{"lowPower":false,"procCpuPct":182.5,"procMemMB":412,"sysLoad1":6.2,"thermal":"serious"}"#),
339 body)
340 let reading = HostLoadSampler.Reading.now(at: 1)
341 XCTAssertGreaterThan(reading.cpuSeconds, 0)
342 XCTAssertGreaterThan(reading.memMB ?? 0, 1)
343 }
344}
345