import Foundation import XCTest @testable import CallsKit /// Spec §15.30: the receiver's watch (down fast, up slow, a failed probe /// doubling the wait), what a sender sends at each level (the camera giving /// way before a shared screen, a screen never paused), the media report's /// `video`, and the quality report's seconds — on a fake clock. The twin of /// test/browser/room-adapt.test.mjs, number for number. final class VideoAdaptTests: XCTestCase { typealias Sample = VideoAdapt.Sample private func clean( freezes: Double = 0, freezeSeconds: Double = 0, keyframeAsks: Double = 0, packets: Double = 100, lost: Double = 0, rtt: Double? = 80, jitterBufferMs: Double? = 60, decoded: Double = 30, dropped: Double = 0 ) -> Sample { Sample( freezes: freezes, freezeSeconds: freezeSeconds, keyframeAsks: keyframeAsks, packets: packets, lost: lost, rtt: rtt, jitterBufferMs: jitterBufferMs, decoded: decoded, dropped: dropped) } /// Trouble that is not severe: a freeze every four seconds. private func freezing(_ t: Int) -> Sample { clean(freezes: t % 4 == 0 ? 1 : 0) } /// Once a second from `from` to `to`; the seconds the level changed at. @discardableResult private func run(_ watch: inout VideoAdapt, _ from: Int, _ to: Int, _ at: (Int) -> Sample?) -> [[Int]] { var changes: [[Int]] = [] for t in from...to { let before = watch.level watch.observe(at: Double(t), at(t)) if watch.level != before { changes.append([t, watch.level.rawValue]) } } return changes } func testTheNumbersAreTheApprovedOnes() { XCTAssertEqual(VideoAdapt.upAfter, 45) XCTAssertEqual(VideoAdapt.upMax, 300) XCTAssertEqual(VideoAdapt.window, 10) XCTAssertEqual(VideoAdapt.probeWatch, 20) } func testTroubleThatLastsStepsDownEveryTenSecondsToAudioOnly() { var w = VideoAdapt() XCTAssertEqual(run(&w, 0, 60, freezing), [[10, 1], [20, 2], [30, 3]]) XCTAssertEqual(w.level, .audio) XCTAssertEqual(w.downs, 3) } func testSevereTroubleStepsTwoLevelsFiveSecondsIn() { var w = VideoAdapt() XCTAssertEqual(run(&w, 0, 12) { _ in self.clean(freezes: 2) }, [[5, 2], [10, 3]]) var lossy = VideoAdapt() XCTAssertEqual(run(&lossy, 0, 6) { _ in self.clean(packets: 80, lost: 20) }, [[5, 2]]) } func testOccasionalTroubleIsNotTrouble() { var rare = VideoAdapt() XCTAssertEqual(run(&rare, 0, 60) { t in self.clean(freezes: t % 11 == 0 ? 1 : 0) }, []) var lossy = VideoAdapt() XCTAssertEqual(run(&lossy, 0, 60) { _ in self.clean(packets: 97, lost: 3) }, []) var slow = VideoAdapt() XCTAssertEqual(run(&slow, 0, 60) { _ in self.clean(rtt: 900) }, []) } func testEachKindOfTroubleStepsDown() { let kinds: [(String, (Int) -> Sample)] = [ ("loss", { _ in self.clean(packets: 94, lost: 6) }), ("one freeze on a 700 ms round trip", { t in self.clean(freezes: t == 5 ? 1 : 0, rtt: 700) }), ("the jitter buffer", { _ in self.clean(jitterBufferMs: 650) }), ("frames dropped", { _ in self.clean(decoded: 20, dropped: 10) }), ("one long freeze", { t in self.clean(freezes: t == 5 ? 1 : 0, freezeSeconds: t == 5 ? 2.5 : 0) }), ("a keyframe asked for every three seconds", { t in self.clean(keyframeAsks: t % 3 == 0 ? 1 : 0) }), ] for (what, sample) in kinds { var w = VideoAdapt() XCTAssertEqual(run(&w, 0, 10, sample), [[10, 1]], what) } } func testTheRoundTripIsTheMedian() { var w = VideoAdapt() XCTAssertEqual( run(&w, 0, 30) { t in self.clean(freezes: t % 10 == 3 ? 1 : 0, rtt: t % 10 == 3 ? 2000 : 100) }, []) } func testNothingMeasuredIsNoNews() { var w = VideoAdapt() run(&w, 0, 9, freezing) XCTAssertEqual(run(&w, 10, 40) { _ in nil }, []) XCTAssertEqual(w.level, .normal) XCTAssertNil(VideoAdapt.sample(QualityCounters(), QualityCounters(), cameraWatched: true)) } func testFreezesCountOnlyWhileTheCameraIsWatched() { var before = QualityCounters() before.inAudio = .init(packets: 100, lost: 1, bufferDelay: 3000, emitted: 48000) before.inVideo = .init(packets: 200, freezes: 1, freezeSeconds: 0.5, decoded: 100, dropped: 0, keyframeAsks: 1) before.inScreen = .init(packets: 50, lost: 0, decoded: 10) var now = before now.inAudio = .init(packets: 150, lost: 2, bufferDelay: 6360, emitted: 96000) now.inVideo = .init(packets: 290, freezes: 3, freezeSeconds: 2, decoded: 130, dropped: 1, keyframeAsks: 3) now.inScreen = .init(packets: 60, lost: 1, decoded: 11) now.rtt = 50 let s = VideoAdapt.sample(now, before, cameraWatched: true) XCTAssertEqual(s?.freezes, 2) XCTAssertEqual(s?.freezeSeconds, 1.5) XCTAssertEqual(s?.keyframeAsks, 2) XCTAssertEqual(s?.packets, 150) XCTAssertEqual(s?.lost, 2) XCTAssertEqual(s?.rtt, 50) XCTAssertEqual(s?.jitterBufferMs ?? 0, 70, accuracy: 0.01) XCTAssertEqual(s?.decoded, 31) XCTAssertEqual(s?.dropped, 1) let off = VideoAdapt.sample(now, before, cameraWatched: false) XCTAssertEqual(off?.freezes, 0) XCTAssertEqual(off?.keyframeAsks, 0) XCTAssertEqual(off?.packets, 150) } func testCleanSecondsStepUpAfterFortyFiveAndAgain() { var w = VideoAdapt() run(&w, 0, 20, freezing) XCTAssertEqual(w.level, .minimal) XCTAssertEqual(run(&w, 21, 200) { _ in self.clean() }, [[66, 1], [112, 0]]) XCTAssertEqual(w.upWait, VideoAdapt.upAfter) } func testAKeyframeAskedForIsNotACleanSecond() { var w = VideoAdapt() run(&w, 0, 10, freezing) XCTAssertEqual(run(&w, 11, 120) { t in self.clean(keyframeAsks: t == 30 ? 1 : 0) }, [[76, 0]]) } func testOneBadSecondResetsTheCleanRun() { var w = VideoAdapt() run(&w, 0, 10, freezing) XCTAssertEqual(run(&w, 11, 120) { t in self.clean(lost: t == 40 ? 10 : 0) }, [[86, 0]]) } func testAFailedProbeStepsBackAndDoublesTheWaitToFiveMinutes() { var w = VideoAdapt() run(&w, 0, 10, freezing) XCTAssertEqual(w.level, .reduced) var changes: [[Int]] = [] for t in 11...1200 { let before = w.level w.observe(at: Double(t), w.level == .normal ? clean(freezes: 1) : clean()) if w.level != before { changes.append([t, w.level.rawValue]) } } XCTAssertEqual(changes.filter { $0[1] == 0 }.map { $0[0] }, [56, 152, 338, 644, 950]) XCTAssertEqual(changes.filter { $0[1] == 1 }.map { $0[0] }, [61, 157, 343, 649, 955]) XCTAssertEqual(w.upWait, VideoAdapt.upMax) } func testTroubleAfterTheProbeWatchIsAnOrdinaryStepDown() { var w = VideoAdapt() run(&w, 0, 10, freezing) run(&w, 11, 56) { _ in self.clean() } XCTAssertEqual(w.level, .normal) XCTAssertEqual(run(&w, 57, 100) { t in t >= 80 ? self.freezing(t) : self.clean() }, [[84, 1], [94, 2]]) XCTAssertEqual(w.upWait, VideoAdapt.upAfter) } func testTheSettingIsAFloorAndOnlyLevelsBelowNormalAreAsked() { let a = String(repeating: "a", count: 32) let b = String(repeating: "b", count: 32) XCTAssertEqual(VideoAdapt.asks([a: .normal, b: .reduced], setting: .auto), [b: "reduced"]) XCTAssertEqual(VideoAdapt.asks([a: .normal, b: .reduced], setting: .low), [a: "minimal", b: "minimal"]) XCTAssertEqual(VideoAdapt.asks([a: .audio], setting: .low), [a: "audio"]) XCTAssertEqual(VideoAdapt.asks([a: .normal, b: .reduced], setting: .audio), [a: "audio", b: "audio"]) XCTAssertEqual(VideoAdapt.asks([a: .normal], setting: .auto), [:]) var many: [String: VideoLevel] = [:] for i in 0..<20 { many[String(format: "%032x", i)] = .minimal } XCTAssertEqual(VideoAdapt.asks(many, setting: .auto).count, 15) } func testASenderReadsOnlyItsOwnIdAndTheWiresLevels() { let me = String(repeating: "a", count: 32) XCTAssertEqual(VideoAdapt.asked(PeerMedia(muted: false, cameraOff: false, video: [me: "minimal"]), me: me), .minimal) XCTAssertEqual(VideoAdapt.asked(PeerMedia(muted: false, cameraOff: false, video: [me: "minimal"]), me: "b"), .normal) XCTAssertEqual(VideoAdapt.asked(PeerMedia(muted: false, cameraOff: false, video: [me: "tiny"]), me: me), .normal) XCTAssertEqual(VideoAdapt.asked(PeerMedia(muted: false, cameraOff: false), me: me), .normal) XCTAssertEqual(VideoAdapt.asked(nil, me: me), .normal) } func testTheCameraAtEachLevel() { XCTAssertEqual(VideoAdapt.camera(.normal, sharing: false), EncodingPlan()) let reduced = VideoAdapt.camera(.reduced, sharing: false, width: 640, height: 480) XCTAssertEqual(reduced.maxBitrate, 350_000) XCTAssertEqual(reduced.maxFramerate, 15) XCTAssertEqual(reduced.scaleResolutionDownBy ?? 0, 480.0 / 360, accuracy: 1e-9) XCTAssertTrue(reduced.active) XCTAssertEqual(VideoAdapt.camera(.reduced, sharing: false, width: 720, height: 1280).scaleResolutionDownBy, 2) let minimal = VideoAdapt.camera(.minimal, sharing: false, width: 640, height: 480) XCTAssertEqual(minimal.maxBitrate, 120_000) XCTAssertEqual(minimal.maxFramerate, 8) XCTAssertEqual(minimal.scaleResolutionDownBy ?? 0, 480.0 / 180, accuracy: 1e-9) XCTAssertFalse(VideoAdapt.camera(.audio, sharing: false).active) } func testWhileSharingTheCameraGivesWayFirst() { XCTAssertEqual(VideoAdapt.camera(.normal, sharing: true), ScreenSendPolicy.camera(sharing: true)) let reduced = VideoAdapt.camera(.reduced, sharing: true) XCTAssertEqual(reduced.maxBitrate, 120_000) XCTAssertTrue(reduced.active) XCTAssertFalse(VideoAdapt.camera(.minimal, sharing: true).active) XCTAssertFalse(VideoAdapt.camera(.audio, sharing: true).active) } func testAScreenKeepsItsSizeLosesFrameRateFirstAndIsNeverPaused() { let plan = ScreenSendPolicy.screen(.balanced, width: 1920, height: 1080) XCTAssertEqual(VideoAdapt.screen(plan, .normal, width: 1920, height: 1080), plan) let reduced = VideoAdapt.screen(plan, .reduced, width: 1920, height: 1080) XCTAssertEqual(reduced.maxFramerate, 10) XCTAssertEqual(reduced.maxBitrate, 1_200_000) XCTAssertEqual(reduced.scaleResolutionDownBy, plan.scaleResolutionDownBy, "the size is kept") XCTAssertEqual(reduced.degradation, .maintainResolution) let minimal = VideoAdapt.screen(plan, .minimal, width: 1920, height: 1080) XCTAssertEqual(minimal.maxFramerate, 5) XCTAssertEqual(minimal.maxBitrate, 500_000) XCTAssertEqual(minimal.scaleResolutionDownBy, 1.5) let audio = VideoAdapt.screen(plan, .audio, width: 1920, height: 1080) XCTAssertEqual(audio, minimal) XCTAssertTrue(audio.active) // A level-fit scale larger than minimal's is kept (the H.264 rules). let capped = ScreenSendPolicy.screen(.motion, width: 3840, height: 2160, screencast: false) XCTAssertGreaterThanOrEqual( VideoAdapt.screen(capped, .minimal, width: 3840, height: 2160).scaleResolutionDownBy ?? 0, capped.scaleResolutionDownBy ?? 0) } func testBrowsersAndNewAppsHonourAnAsk() { XCTAssertTrue(VideoAdapt.honours(client: nil)) XCTAssertTrue(VideoAdapt.honours(client: "")) XCTAssertTrue(VideoAdapt.honours(client: "mac 0.4.15")) XCTAssertFalse(VideoAdapt.honours(client: "mac 0.4.14")) XCTAssertTrue(VideoAdapt.honours(client: "iphone 0.5")) XCTAssertFalse(VideoAdapt.honours(client: "mac 0.4.13")) XCTAssertFalse(VideoAdapt.honours(client: "native")) XCTAssertFalse(VideoAdapt.honours(client: "something else")) } func testTheSendersNotice() { XCTAssertEqual(VideoAdapt.noticeWords([]), "") XCTAssertEqual( VideoAdapt.noticeWords([("David", .minimal)]), "Sending reduced video to David (their connection is weak)") XCTAssertEqual(VideoAdapt.noticeWords([("David", .audio)]), "Sending only audio to David (their connection is weak)") XCTAssertEqual( VideoAdapt.noticeWords([("David", .reduced), ("Ana", .audio), ("Cy", .minimal)]), "Sending reduced video to David, Ana and Cy (their connections are weak)") } func testTheMediaReportReadsTheAsksLeniently() throws { let me = String(repeating: "a", count: 32) let ok = try JSONDecoder().decode( PeerMedia.self, from: Data(#"{"muted":false,"cameraOff":false,"video":{"\#(me)":"audio"}}"#.utf8)) XCTAssertEqual(ok.video, [me: "audio"]) let odd = try JSONDecoder().decode( PeerMedia.self, from: Data(#"{"muted":true,"cameraOff":false,"video":["\#(me)"],"hearing":[]}"#.utf8)) XCTAssertNil(odd.video, "a video member of another shape is taken as absent") XCTAssertEqual(odd.muted, true) XCTAssertEqual(odd.hearing, []) } func testTheQualityReportCarriesTheSecondsAtEachLevel() throws { var tally = QualityEventTally() tally.videoSetting = .low tally.video(asked: .minimal, sent: .normal, seconds: 1, for: "p") tally.video(asked: .minimal, sent: .reduced, seconds: 1.04, for: "p") tally.video(asked: .normal, sent: .normal, seconds: 1, for: "q") var builder = QualityReportBuilder() builder.start(at: 0) let report = builder.build( at: 30, samples: [:], events: &tally, client: QualityClient(app: "mac", version: "0.4.15"), devices: nil, final: false) let body = try XCTUnwrap(report.encoded()) XCTAssertTrue(body.contains(#""askedSeconds":[0,2,0]"#), body) XCTAssertTrue(body.contains(#""sentSeconds":[1,0,0]"#), body) XCTAssertTrue(body.contains(#""videoSetting":"low""#), body) XCTAssertFalse(body.contains(#""peer":"q""#), "a peer at normal both ways says nothing") } // MARK: - The sender's own watch, and the machine's load (2026-10-29) func testThisDeviceStrugglingLowersItsOwnCameraAndCalmBringsItBack() { var w = VideoAdapt() XCTAssertEqual(run(&w, 0, 35) { _ in VideoAdapt.loadSample(struggling: true) }, [[10, 1], [20, 2], [30, 3]]) var calm = VideoAdapt() run(&calm, 0, 10) { _ in VideoAdapt.loadSample(struggling: true) } XCTAssertEqual(calm.level, .reduced) XCTAssertEqual(run(&calm, 11, 60) { _ in VideoAdapt.loadSample(struggling: false) }, [[56, 0]]) var brief = VideoAdapt() XCTAssertEqual(run(&brief, 0, 60) { t in VideoAdapt.loadSample(struggling: t % 10 < 7) }, [], "seven in ten is not sustained") } func testWhatCountsAsStruggling() { XCTAssertTrue(VideoAdapt.struggling(thermal: .serious, cpuPct: 10, mac: false)) XCTAssertTrue(VideoAdapt.struggling(thermal: .critical, cpuPct: nil, mac: true)) XCTAssertFalse(VideoAdapt.struggling(thermal: .fair, cpuPct: 140, mac: true)) XCTAssertTrue(VideoAdapt.struggling(thermal: .nominal, cpuPct: 151, mac: true)) XCTAssertFalse(VideoAdapt.struggling(thermal: .nominal, cpuPct: 400, mac: false), "the iPhone goes by its thermal state") } func testTheOwnLevelLowersTheCameraNotTheScreen() { // The camera at the larger of what they ask and this device's own. XCTAssertEqual(VideoAdapt.camera(max(.normal, .minimal), sharing: false).maxBitrate, 120_000) let plan = ScreenSendPolicy.screen(.balanced, width: 1920, height: 1080) XCTAssertEqual(VideoAdapt.screen(plan, .normal, width: 1920, height: 1080), plan, "the screen goes by the ask alone") } func testTheHostLoadOverAWindow() { typealias R = HostLoadSampler.Reading var h = HostLoadSampler() XCTAssertNil(h.tick(R(at: 0, cpuSeconds: 10, thermal: .nominal, lowPower: false))) XCTAssertEqual(h.tick(R(at: 1, cpuSeconds: 11.6, thermal: .fair, lowPower: false)) ?? 0, 160, accuracy: 1e-9) _ = h.tick(R(at: 2, cpuSeconds: 12, thermal: .serious, lowPower: true)) let host = h.take(R(at: 30, cpuSeconds: 25, thermal: .nominal, lowPower: false, memMB: 412.04, load1: 6.21)) XCTAssertEqual(host.procCpuPct, 50, "15 s of CPU in 30") XCTAssertEqual(host.procMemMB, 412) XCTAssertEqual(host.sysLoad1, 6.2) XCTAssertEqual(host.thermal, "serious", "the worst in the window") XCTAssertEqual(host.lowPower, true) let next = h.take(R(at: 60, cpuSeconds: 25, thermal: .nominal, lowPower: false)) XCTAssertEqual(next.procCpuPct, 0) XCTAssertEqual(next.thermal, "nominal") XCTAssertEqual(next.lowPower, false) XCTAssertNil(next.procMemMB) } func testTheHostLoadIsInTheReport() throws { var report = QualityReport(seconds: 30, client: QualityClient(app: "mac", version: "0.4.15")) report.host = QualityHost(procCpuPct: 182.5, procMemMB: 412, sysLoad1: 6.2, thermal: "serious", lowPower: false) let body = try XCTUnwrap(report.encoded()) XCTAssertTrue( body.contains(#""host":{"lowPower":false,"procCpuPct":182.5,"procMemMB":412,"sysLoad1":6.2,"thermal":"serious"}"#), body) let reading = HostLoadSampler.Reading.now(at: 1) XCTAssertGreaterThan(reading.cpuSeconds, 0) XCTAssertGreaterThan(reading.memMB ?? 0, 1) } }