import Foundation /// Spec §15.30 (2026-10-28): adaptive video, room.js's `adapt*` twins /// number for number (test/browser/room-adapt.test.mjs and VideoAdaptTests /// hold both). /// /// Paul, after a Dublin–London call whose guest was on café Wi-Fi, relayed, /// at 840–1300 ms round trips and up to seven freezes every thirty seconds: /// "Low-bandwidth with auto-switching up and down." It is a mesh, so every /// pair has its own sender, and the one who can see the trouble is the /// receiver. Each receiver watches what arrives from each sender and asks /// that sender, in its own media report, for one of these levels; the /// sender sets that one connection's sender parameters. Audio is never /// touched; a shared screen keeps its size, loses frame rate first, and is /// never paused, and while one is going the camera gives way first. public enum VideoLevel: Int, CaseIterable, Comparable, Sendable { case normal, reduced, minimal, audio /// The wire's word; normal is never sent (it is the absence of an entry). public var wire: String { switch self { case .normal: return "normal" case .reduced: return "reduced" case .minimal: return "minimal" case .audio: return "audio" } } init?(wire: String) { guard let level = Self.allCases.first(where: { $0.wire == wire }), level != .normal else { return nil } self = level } public static func < (a: Self, b: Self) -> Bool { a.rawValue < b.rawValue } } /// The person's own "Video quality", in the device panel and remembered: /// Auto leaves it to the watch, Low bandwidth asks everyone for minimal, /// Audio only asks everyone for no video and sends no camera to anyone. public enum VideoQualitySetting: String, CaseIterable, Identifiable, Sendable { case auto, low, audio public var id: String { rawValue } public var title: String { switch self { case .auto: return "Auto" case .low: return "Low bandwidth" case .audio: return "Audio only" } } public static let explanation = "Auto lowers video when a connection is weak and raises it again when it recovers. Low bandwidth asks everyone for small video. Audio only pauses video both ways, to keep sound clear." /// The lowest level asked of anyone while this is chosen. var floor: VideoLevel { switch self { case .auto: return .normal case .low: return .minimal case .audio: return .audio } } static let key = "videoQuality" /// The remembered choice, Auto until someone picks another. public static var remembered: VideoQualitySetting { get { UserDefaults.standard.string(forKey: key).flatMap(Self.init(rawValue:)) ?? .auto } set { UserDefaults.standard.set(newValue.rawValue, forKey: key) } } } /// One sender's watch, on the receiving side: down quickly, up slowly, and /// a probe up that fails doubling the wait before the next. struct VideoAdapt: Equatable, Sendable { // The thresholds, as room.js has them (ADAPT_*). static let window = 10.0 // s: the trouble window, and the time at a level before a step down static let severeAfter = 5.0 // s: severe trouble steps two levels after this long static let downFreezes = 2.0 // camera freezes in the window static let downFreezeSeconds = 2.0 // seconds frozen in the window static let downKeyframeAsks = 3.0 // PLIs and FIRs this side sent for the camera static let downLoss = 0.05 // of all inbound packets static let downRTT = 600.0 // ms, with at least one freeze static let downJitterBuffer = 500.0 // ms, the audio jitter buffer's mean delay static let downDropped = 0.25 // frames dropped, of decoded and dropped, static let downDroppedMin = 10.0 // at least this many static let severeFreezes = 5.0 static let severeFreezeSeconds = 4.0 static let severeLoss = 0.15 static let cleanLoss = 0.02 // a clean second: no freeze, loss at most this, static let cleanRTT = 400.0 // a round trip under this, static let cleanJitterBuffer = 300.0 // and the jitter buffer under this static let upAfter = 45.0 // s clean at a level, then probe one up static let probeWatch = 20.0 // trouble this soon after a probe steps back static let probeJudge = 5.0 // judged on at least this much of it static let upMax = 300.0 // the probe's wait doubles to at most this static let settle = 5.0 // after a renegotiation (a screen added or taken away), no news this long // The sender's own half (2026-10-29): this device struggling for this // many of the window's seconds is trouble for its own camera, judged by // the same watch at the same levels; the screen and audio are not // touched. Struggling is a thermal state of serious or worse, or (Mac) // Calls' own process over loadCPUPct of one core. static let downLoadSeconds = 8 static let loadCPUPct = 150.0 /// One second of what arrived from the sender. struct Sample: Equatable, Sendable { var freezes = 0.0 var freezeSeconds = 0.0 var keyframeAsks = 0.0 var packets = 0.0 var lost = 0.0 var rtt: Double? var jitterBufferMs: Double? var decoded = 0.0 var dropped = 0.0 /// This device struggled in this second (the sender's own watch). var load = false } /// One second of this device's own load, for the sender's watch of /// itself: nothing about a link, only whether it struggled. static func loadSample(struggling: Bool) -> Sample { Sample(rtt: nil, jitterBufferMs: nil, load: struggling) } /// Whether this device is struggling now (see `downLoadSeconds`). static func struggling(thermal: ProcessInfo.ThermalState, cpuPct: Double?, mac: Bool) -> Bool { if thermal == .serious || thermal == .critical { return true } return mac && (cpuPct ?? 0) > loadCPUPct } private(set) var level = VideoLevel.normal private var since: Double? private var samples: [(at: Double, sample: Sample)] = [] private var cleanSince: Double? let upBase: Double private(set) var upWait: Double private var probeAt: Double? private var probeFrom = VideoLevel.normal private(set) var downs = 0 private(set) var ups = 0 init(upAfter: Double = Self.upAfter) { upBase = upAfter upWait = upAfter } static func == (a: Self, b: Self) -> Bool { a.level == b.level && a.since == b.since && a.upWait == b.upWait && a.downs == b.downs && a.ups == b.ups } /// A window's sums: counts added, the round trip as their median (one /// spike is not a slow link), the jitter buffer as their mean. struct Window: Equatable { var freezes = 0.0, freezeSeconds = 0.0, keyframeAsks = 0.0, packets = 0.0, lost = 0.0 var loadSeconds = 0 var decoded = 0.0, dropped = 0.0 var rtt: Double? var jitterBuffer: Double? var loss: Double { packets + lost > 0 ? lost / (packets + lost) : 0 } } static func window(_ samples: [Sample]) -> Window { var w = Window() var rtts: [Double] = [] var jbs: [Double] = [] for x in samples { w.freezes += x.freezes w.freezeSeconds += x.freezeSeconds w.keyframeAsks += x.keyframeAsks if x.load { w.loadSeconds += 1 } w.packets += x.packets w.lost += x.lost w.decoded += x.decoded w.dropped += x.dropped if let r = x.rtt { rtts.append(r) } if let j = x.jitterBufferMs { jbs.append(j) } } if !rtts.isEmpty { w.rtt = rtts.sorted()[rtts.count / 2] } if !jbs.isEmpty { w.jitterBuffer = jbs.reduce(0, +) / Double(jbs.count) } return w } enum Verdict: Equatable { case none, trouble, severe } static func verdict(_ w: Window) -> Verdict { if w.freezes >= severeFreezes || w.freezeSeconds >= severeFreezeSeconds || w.loss > severeLoss { return .severe } if w.freezes >= downFreezes || w.freezeSeconds >= downFreezeSeconds || w.loss > downLoss || w.keyframeAsks >= downKeyframeAsks || w.loadSeconds >= downLoadSeconds || (w.rtt.map { $0 >= downRTT } ?? false && w.freezes >= 1) || (w.jitterBuffer.map { $0 >= downJitterBuffer } ?? false) || (w.dropped >= downDroppedMin && w.dropped >= downDropped * (w.decoded + w.dropped)) { return .trouble } return .none } static func clean(_ x: Sample) -> Bool { let n = x.packets + x.lost return x.freezes == 0 && x.freezeSeconds == 0 && x.keyframeAsks == 0 && !x.load && (n == 0 || x.lost / n <= cleanLoss) && (x.rtt.map { $0 < cleanRTT } ?? true) && (x.jitterBufferMs.map { $0 < cleanJitterBuffer } ?? true) } private mutating func move(to next: VideoLevel, at now: Double, up: Bool) { if up { ups += 1 } else { downs += 1 } level = next since = now samples = [] cleanSince = nil if !up { probeAt = nil } } /// One look, about once a second (`now` in seconds), with that second's /// sample or nil for none: a connection that is down is §15.28's to /// mend and says nothing about the link. Returns the level. @discardableResult mutating func observe(at now: Double, _ sample: Sample?) -> VideoLevel { if since == nil { since = now } guard let sample else { return level } samples.append((now, sample)) samples.removeAll { $0.at <= now - Self.window } let observed = now - (since ?? now) let verdict = Self.verdict(Self.window(samples.map(\.sample))) if Self.clean(sample) { if cleanSince == nil { cleanSince = now } } else { cleanSince = nil } if let probeAt { if now - probeAt < Self.probeWatch { if verdict != .none, observed >= Self.probeJudge { upWait = min(upWait * 2, Self.upMax) move(to: probeFrom, at: now, up: false) return level } } else { self.probeAt = nil upWait = upBase } } if verdict == .severe, observed >= Self.severeAfter, level < .audio { move(to: VideoLevel(rawValue: min(VideoLevel.audio.rawValue, level.rawValue + 2)) ?? .audio, at: now, up: false) return level } if verdict != .none, observed >= Self.window, level < .audio, let next = VideoLevel(rawValue: level.rawValue + 1) { move(to: next, at: now, up: false) return level } if level > .normal, let cleanSince, now - cleanSince >= upWait, let next = VideoLevel(rawValue: level.rawValue - 1) { let from = level move(to: next, at: now, up: true) probeAt = now probeFrom = from } return level } // MARK: - What arrives, one second of it /// One second from two readings of the quality report's counters: camera /// freezes and keyframe asks only while the camera is watched (on, and /// the app in front — a still screen's gaps and an unseen tile's frames /// are not freezes), packets and loss across audio, camera and screen, /// the round trip, the audio jitter buffer, and frames decoded and /// dropped. Nil when nothing at all arrived and nothing was measured. static func sample(_ now: QualityCounters, _ before: QualityCounters?, cameraWatched: Bool) -> Sample? { func d(_ a: Double?, _ b: Double?) -> Double { QualityReportBuilder.delta(a, b) ?? 0 } var s = Sample() s.packets = d(now.inAudio?.packets, before?.inAudio?.packets) + d(now.inVideo?.packets, before?.inVideo?.packets) + d(now.inScreen?.packets, before?.inScreen?.packets) s.lost = d(now.inAudio?.lost, before?.inAudio?.lost) + d(now.inVideo?.lost, before?.inVideo?.lost) + d(now.inScreen?.lost, before?.inScreen?.lost) s.rtt = now.rtt if s.packets + s.lost == 0, s.rtt == nil { return nil } if cameraWatched { s.freezes = d(now.inVideo?.freezes, before?.inVideo?.freezes) s.freezeSeconds = d(now.inVideo?.freezeSeconds, before?.inVideo?.freezeSeconds) s.keyframeAsks = d(now.inVideo?.keyframeAsks, before?.inVideo?.keyframeAsks) } if let delay = QualityReportBuilder.delta(now.inAudio?.bufferDelay, before?.inAudio?.bufferDelay), let emitted = QualityReportBuilder.delta(now.inAudio?.emitted, before?.inAudio?.emitted), emitted > 0 { s.jitterBufferMs = delay / emitted * 1000 } s.decoded = d(now.inVideo?.decoded, before?.inVideo?.decoded) + d(now.inScreen?.decoded, before?.inScreen?.decoded) s.dropped = d(now.inVideo?.dropped, before?.inVideo?.dropped) + d(now.inScreen?.dropped, before?.inScreen?.dropped) return s } // MARK: - What is asked, and what is sent /// The `video` report: every peer whose level — the watch's or the /// setting's, whichever is lower — is below normal, at most fifteen. static func asks(_ levels: [String: VideoLevel], setting: VideoQualitySetting) -> [String: String] { var out: [String: String] = [:] for (id, level) in levels.sorted(by: { $0.key < $1.key }) { let at = max(level, setting.floor) if at > .normal, out.count < 15 { out[id] = at.wire } } return out } /// What one peer's report asks of us. static func asked(_ media: PeerMedia?, me: String) -> VideoLevel { guard !me.isEmpty, let word = media?.video?[me] else { return .normal } return VideoLevel(wire: word) ?? .normal } // The sender's half, as room.js has it (ADAPT_CAMERA, ADAPT_SCREEN). static let reducedCamera = (bitrate: 350_000, fps: 15, long: 640.0, short: 360.0) static let minimalCamera = (bitrate: 120_000, fps: 8, long: 320.0, short: 180.0) static let reducedScreen = (bitrate: 1_200_000, fps: 10) static let minimalScreen = (bitrate: 500_000, fps: 5, long: 1280.0) /// The camera's encoding for one receiver at a level. While a screen /// goes out the camera gives way first: normal is the cap beside the /// screen (ScreenSendPolicy.camera), and every level below is one lower /// for the camera, so a receiver at minimal gets the screen and no /// camera. Fitted by the camera's long and short sides, so a portrait /// camera is boxed the right way round. static func camera(_ level: VideoLevel, sharing: Bool, width: Int = 640, height: Int = 480) -> EncodingPlan { let at = sharing && level > .normal ? VideoLevel(rawValue: min(3, level.rawValue + 1)) ?? .audio : level if at == .normal { return ScreenSendPolicy.camera(sharing: sharing, height: height) } let c = at == .reduced ? reducedCamera : minimalCamera let long = Double(max(width, height)) let short = Double(min(width, height)) let scale = max(1, long / c.long, short / c.short) var plan = EncodingPlan(maxBitrate: c.bitrate, maxFramerate: c.fps, scaleResolutionDownBy: scale > 1 ? scale : nil) plan.active = at != .audio return plan } /// The screen's plan for one receiver at a level: frame rate and bitrate /// lowered, the size kept, and only at minimal and below the long side /// brought to 1280; resolution held under pressure from then on. Never /// paused. The level-fit scale the plan carries (ScreenSendPolicy's H.264 /// rules) is kept whenever it is larger. static func screen(_ plan: EncodingPlan, _ level: VideoLevel, width: Int, height: Int) -> EncodingPlan { guard level > .normal else { return plan } var out = plan out.degradation = .maintainResolution out.active = true if level == .reduced { out.maxFramerate = reducedScreen.fps out.maxBitrate = min(plan.maxBitrate ?? reducedScreen.bitrate, reducedScreen.bitrate) } else { out.maxFramerate = minimalScreen.fps out.maxBitrate = min(plan.maxBitrate ?? minimalScreen.bitrate, minimalScreen.bitrate) let longest = Double(max(width, height)) let fit = longest > minimalScreen.long ? longest / minimalScreen.long : 1 let scale = max(plan.scaleResolutionDownBy ?? 1, fit) out.scaleResolutionDownBy = scale > 1 ? scale : nil } return out } /// An app older than this ignores a request: its video can only be hidden /// here, which saves this device's work and not the connection. static let minNativeVersion = "0.4.15" /// Whether a peer's client acts on a request: every browser (its page is /// the server's own), and an app from `minNativeVersion` on. static func honours(client: String?) -> Bool { guard let client, !client.isEmpty else { return true } let parts = client.split(separator: " ") guard parts.count == 2, ["mac", "iphone", "ipad"].contains(String(parts[0])) else { return false } return ClientVersion.compare(String(parts[1]), minNativeVersion) >= 0 } /// The sender's quiet notice, for the people it is sending less to. static func noticeWords(_ people: [(name: String, level: VideoLevel)]) -> String { guard !people.isEmpty else { return "" } let names = people.map(\.name) let list = names.count == 1 ? names[0] : names.dropLast().joined(separator: ", ") + " and " + names[names.count - 1] let weak = names.count == 1 ? "(their connection is weak)" : "(their connections are weak)" if people.allSatisfy({ $0.level >= .audio }) { return "Sending only audio to \(list) \(weak)" } return "Sending reduced video to \(list) \(weak)" } /// The tile's words at audio only. static let pausedWords = "Video paused to keep audio clear" static let oldAppWords = "Their app can’t send less video, so it’s only hidden here" static let badgeWord = "Low bandwidth" } /// §15.30's seconds at each level below normal, asked of and sent to each /// peer, for the quality report. struct VideoTime: Equatable, Sendable { var asked: [Double] = [0, 0, 0] var sent: [Double] = [0, 0, 0] mutating func add(asked a: VideoLevel, sent s: VideoLevel, seconds: Double) { if a > .normal { asked[a.rawValue - 1] += seconds } if s > .normal { sent[s.rawValue - 1] += seconds } } /// The report's arrays: three numbers, or nil when all are zero. static func seconds(_ v: [Double]) -> [Double]? { guard v.contains(where: { $0 > 0 }) else { return nil } return v.map { QualityReportBuilder.bound($0, QualityBounds.seconds) ?? 0 } } }