| 1 | import Foundation |
| 2 | |
| 3 | /// Spec §15.30 (2026-10-28): adaptive video, room.js's `adapt*` twins |
| 4 | /// number for number (test/browser/room-adapt.test.mjs and VideoAdaptTests |
| 5 | /// hold both). |
| 6 | /// |
| 7 | /// Paul, after a Dublin–London call whose guest was on café Wi-Fi, relayed, |
| 8 | /// at 840–1300 ms round trips and up to seven freezes every thirty seconds: |
| 9 | /// "Low-bandwidth with auto-switching up and down." It is a mesh, so every |
| 10 | /// pair has its own sender, and the one who can see the trouble is the |
| 11 | /// receiver. Each receiver watches what arrives from each sender and asks |
| 12 | /// that sender, in its own media report, for one of these levels; the |
| 13 | /// sender sets that one connection's sender parameters. Audio is never |
| 14 | /// touched; a shared screen keeps its size, loses frame rate first, and is |
| 15 | /// never paused, and while one is going the camera gives way first. |
| 16 | public enum VideoLevel: Int, CaseIterable, Comparable, Sendable { |
| 17 | case normal, reduced, minimal, audio |
| 18 | |
| 19 | /// The wire's word; normal is never sent (it is the absence of an entry). |
| 20 | public var wire: String { |
| 21 | switch self { |
| 22 | case .normal: return "normal" |
| 23 | case .reduced: return "reduced" |
| 24 | case .minimal: return "minimal" |
| 25 | case .audio: return "audio" |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | init?(wire: String) { |
| 30 | guard let level = Self.allCases.first(where: { $0.wire == wire }), level != .normal else { return nil } |
| 31 | self = level |
| 32 | } |
| 33 | |
| 34 | public static func < (a: Self, b: Self) -> Bool { a.rawValue < b.rawValue } |
| 35 | } |
| 36 | |
| 37 | /// The person's own "Video quality", in the device panel and remembered: |
| 38 | /// Auto leaves it to the watch, Low bandwidth asks everyone for minimal, |
| 39 | /// Audio only asks everyone for no video and sends no camera to anyone. |
| 40 | public enum VideoQualitySetting: String, CaseIterable, Identifiable, Sendable { |
| 41 | case auto, low, audio |
| 42 | |
| 43 | public var id: String { rawValue } |
| 44 | |
| 45 | public var title: String { |
| 46 | switch self { |
| 47 | case .auto: return "Auto" |
| 48 | case .low: return "Low bandwidth" |
| 49 | case .audio: return "Audio only" |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | public static let explanation = |
| 54 | "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." |
| 55 | |
| 56 | /// The lowest level asked of anyone while this is chosen. |
| 57 | var floor: VideoLevel { |
| 58 | switch self { |
| 59 | case .auto: return .normal |
| 60 | case .low: return .minimal |
| 61 | case .audio: return .audio |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | static let key = "videoQuality" |
| 66 | |
| 67 | /// The remembered choice, Auto until someone picks another. |
| 68 | public static var remembered: VideoQualitySetting { |
| 69 | get { UserDefaults.standard.string(forKey: key).flatMap(Self.init(rawValue:)) ?? .auto } |
| 70 | set { UserDefaults.standard.set(newValue.rawValue, forKey: key) } |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | /// One sender's watch, on the receiving side: down quickly, up slowly, and |
| 75 | /// a probe up that fails doubling the wait before the next. |
| 76 | struct VideoAdapt: Equatable, Sendable { |
| 77 | // The thresholds, as room.js has them (ADAPT_*). |
| 78 | static let window = 10.0 // s: the trouble window, and the time at a level before a step down |
| 79 | static let severeAfter = 5.0 // s: severe trouble steps two levels after this long |
| 80 | static let downFreezes = 2.0 // camera freezes in the window |
| 81 | static let downFreezeSeconds = 2.0 // seconds frozen in the window |
| 82 | static let downKeyframeAsks = 3.0 // PLIs and FIRs this side sent for the camera |
| 83 | static let downLoss = 0.05 // of all inbound packets |
| 84 | static let downRTT = 600.0 // ms, with at least one freeze |
| 85 | static let downJitterBuffer = 500.0 // ms, the audio jitter buffer's mean delay |
| 86 | static let downDropped = 0.25 // frames dropped, of decoded and dropped, |
| 87 | static let downDroppedMin = 10.0 // at least this many |
| 88 | static let severeFreezes = 5.0 |
| 89 | static let severeFreezeSeconds = 4.0 |
| 90 | static let severeLoss = 0.15 |
| 91 | static let cleanLoss = 0.02 // a clean second: no freeze, loss at most this, |
| 92 | static let cleanRTT = 400.0 // a round trip under this, |
| 93 | static let cleanJitterBuffer = 300.0 // and the jitter buffer under this |
| 94 | static let upAfter = 45.0 // s clean at a level, then probe one up |
| 95 | static let probeWatch = 20.0 // trouble this soon after a probe steps back |
| 96 | static let probeJudge = 5.0 // judged on at least this much of it |
| 97 | static let upMax = 300.0 // the probe's wait doubles to at most this |
| 98 | static let settle = 5.0 // after a renegotiation (a screen added or taken away), no news this long |
| 99 | // The sender's own half (2026-10-29): this device struggling for this |
| 100 | // many of the window's seconds is trouble for its own camera, judged by |
| 101 | // the same watch at the same levels; the screen and audio are not |
| 102 | // touched. Struggling is a thermal state of serious or worse, or (Mac) |
| 103 | // Calls' own process over loadCPUPct of one core. |
| 104 | static let downLoadSeconds = 8 |
| 105 | static let loadCPUPct = 150.0 |
| 106 | |
| 107 | /// One second of what arrived from the sender. |
| 108 | struct Sample: Equatable, Sendable { |
| 109 | var freezes = 0.0 |
| 110 | var freezeSeconds = 0.0 |
| 111 | var keyframeAsks = 0.0 |
| 112 | var packets = 0.0 |
| 113 | var lost = 0.0 |
| 114 | var rtt: Double? |
| 115 | var jitterBufferMs: Double? |
| 116 | var decoded = 0.0 |
| 117 | var dropped = 0.0 |
| 118 | /// This device struggled in this second (the sender's own watch). |
| 119 | var load = false |
| 120 | } |
| 121 | |
| 122 | /// One second of this device's own load, for the sender's watch of |
| 123 | /// itself: nothing about a link, only whether it struggled. |
| 124 | static func loadSample(struggling: Bool) -> Sample { |
| 125 | Sample(rtt: nil, jitterBufferMs: nil, load: struggling) |
| 126 | } |
| 127 | |
| 128 | /// Whether this device is struggling now (see `downLoadSeconds`). |
| 129 | static func struggling(thermal: ProcessInfo.ThermalState, cpuPct: Double?, mac: Bool) -> Bool { |
| 130 | if thermal == .serious || thermal == .critical { return true } |
| 131 | return mac && (cpuPct ?? 0) > loadCPUPct |
| 132 | } |
| 133 | |
| 134 | private(set) var level = VideoLevel.normal |
| 135 | private var since: Double? |
| 136 | private var samples: [(at: Double, sample: Sample)] = [] |
| 137 | private var cleanSince: Double? |
| 138 | let upBase: Double |
| 139 | private(set) var upWait: Double |
| 140 | private var probeAt: Double? |
| 141 | private var probeFrom = VideoLevel.normal |
| 142 | private(set) var downs = 0 |
| 143 | private(set) var ups = 0 |
| 144 | |
| 145 | init(upAfter: Double = Self.upAfter) { |
| 146 | upBase = upAfter |
| 147 | upWait = upAfter |
| 148 | } |
| 149 | |
| 150 | static func == (a: Self, b: Self) -> Bool { |
| 151 | a.level == b.level && a.since == b.since && a.upWait == b.upWait && a.downs == b.downs && a.ups == b.ups |
| 152 | } |
| 153 | |
| 154 | /// A window's sums: counts added, the round trip as their median (one |
| 155 | /// spike is not a slow link), the jitter buffer as their mean. |
| 156 | struct Window: Equatable { |
| 157 | var freezes = 0.0, freezeSeconds = 0.0, keyframeAsks = 0.0, packets = 0.0, lost = 0.0 |
| 158 | var loadSeconds = 0 |
| 159 | var decoded = 0.0, dropped = 0.0 |
| 160 | var rtt: Double? |
| 161 | var jitterBuffer: Double? |
| 162 | var loss: Double { packets + lost > 0 ? lost / (packets + lost) : 0 } |
| 163 | } |
| 164 | |
| 165 | static func window(_ samples: [Sample]) -> Window { |
| 166 | var w = Window() |
| 167 | var rtts: [Double] = [] |
| 168 | var jbs: [Double] = [] |
| 169 | for x in samples { |
| 170 | w.freezes += x.freezes |
| 171 | w.freezeSeconds += x.freezeSeconds |
| 172 | w.keyframeAsks += x.keyframeAsks |
| 173 | if x.load { w.loadSeconds += 1 } |
| 174 | w.packets += x.packets |
| 175 | w.lost += x.lost |
| 176 | w.decoded += x.decoded |
| 177 | w.dropped += x.dropped |
| 178 | if let r = x.rtt { rtts.append(r) } |
| 179 | if let j = x.jitterBufferMs { jbs.append(j) } |
| 180 | } |
| 181 | if !rtts.isEmpty { w.rtt = rtts.sorted()[rtts.count / 2] } |
| 182 | if !jbs.isEmpty { w.jitterBuffer = jbs.reduce(0, +) / Double(jbs.count) } |
| 183 | return w |
| 184 | } |
| 185 | |
| 186 | enum Verdict: Equatable { case none, trouble, severe } |
| 187 | |
| 188 | static func verdict(_ w: Window) -> Verdict { |
| 189 | if w.freezes >= severeFreezes || w.freezeSeconds >= severeFreezeSeconds || w.loss > severeLoss { |
| 190 | return .severe |
| 191 | } |
| 192 | if w.freezes >= downFreezes || w.freezeSeconds >= downFreezeSeconds || w.loss > downLoss |
| 193 | || w.keyframeAsks >= downKeyframeAsks || w.loadSeconds >= downLoadSeconds |
| 194 | || (w.rtt.map { $0 >= downRTT } ?? false && w.freezes >= 1) |
| 195 | || (w.jitterBuffer.map { $0 >= downJitterBuffer } ?? false) |
| 196 | || (w.dropped >= downDroppedMin && w.dropped >= downDropped * (w.decoded + w.dropped)) |
| 197 | { |
| 198 | return .trouble |
| 199 | } |
| 200 | return .none |
| 201 | } |
| 202 | |
| 203 | static func clean(_ x: Sample) -> Bool { |
| 204 | let n = x.packets + x.lost |
| 205 | return x.freezes == 0 && x.freezeSeconds == 0 && x.keyframeAsks == 0 && !x.load && (n == 0 || x.lost / n <= cleanLoss) |
| 206 | && (x.rtt.map { $0 < cleanRTT } ?? true) && (x.jitterBufferMs.map { $0 < cleanJitterBuffer } ?? true) |
| 207 | } |
| 208 | |
| 209 | private mutating func move(to next: VideoLevel, at now: Double, up: Bool) { |
| 210 | if up { ups += 1 } else { downs += 1 } |
| 211 | level = next |
| 212 | since = now |
| 213 | samples = [] |
| 214 | cleanSince = nil |
| 215 | if !up { probeAt = nil } |
| 216 | } |
| 217 | |
| 218 | /// One look, about once a second (`now` in seconds), with that second's |
| 219 | /// sample or nil for none: a connection that is down is §15.28's to |
| 220 | /// mend and says nothing about the link. Returns the level. |
| 221 | @discardableResult mutating func observe(at now: Double, _ sample: Sample?) -> VideoLevel { |
| 222 | if since == nil { since = now } |
| 223 | guard let sample else { return level } |
| 224 | samples.append((now, sample)) |
| 225 | samples.removeAll { $0.at <= now - Self.window } |
| 226 | let observed = now - (since ?? now) |
| 227 | let verdict = Self.verdict(Self.window(samples.map(\.sample))) |
| 228 | if Self.clean(sample) { |
| 229 | if cleanSince == nil { cleanSince = now } |
| 230 | } else { |
| 231 | cleanSince = nil |
| 232 | } |
| 233 | if let probeAt { |
| 234 | if now - probeAt < Self.probeWatch { |
| 235 | if verdict != .none, observed >= Self.probeJudge { |
| 236 | upWait = min(upWait * 2, Self.upMax) |
| 237 | move(to: probeFrom, at: now, up: false) |
| 238 | return level |
| 239 | } |
| 240 | } else { |
| 241 | self.probeAt = nil |
| 242 | upWait = upBase |
| 243 | } |
| 244 | } |
| 245 | if verdict == .severe, observed >= Self.severeAfter, level < .audio { |
| 246 | move(to: VideoLevel(rawValue: min(VideoLevel.audio.rawValue, level.rawValue + 2)) ?? .audio, at: now, up: false) |
| 247 | return level |
| 248 | } |
| 249 | if verdict != .none, observed >= Self.window, level < .audio, let next = VideoLevel(rawValue: level.rawValue + 1) { |
| 250 | move(to: next, at: now, up: false) |
| 251 | return level |
| 252 | } |
| 253 | if level > .normal, let cleanSince, now - cleanSince >= upWait, let next = VideoLevel(rawValue: level.rawValue - 1) { |
| 254 | let from = level |
| 255 | move(to: next, at: now, up: true) |
| 256 | probeAt = now |
| 257 | probeFrom = from |
| 258 | } |
| 259 | return level |
| 260 | } |
| 261 | |
| 262 | // MARK: - What arrives, one second of it |
| 263 | |
| 264 | /// One second from two readings of the quality report's counters: camera |
| 265 | /// freezes and keyframe asks only while the camera is watched (on, and |
| 266 | /// the app in front — a still screen's gaps and an unseen tile's frames |
| 267 | /// are not freezes), packets and loss across audio, camera and screen, |
| 268 | /// the round trip, the audio jitter buffer, and frames decoded and |
| 269 | /// dropped. Nil when nothing at all arrived and nothing was measured. |
| 270 | static func sample(_ now: QualityCounters, _ before: QualityCounters?, cameraWatched: Bool) -> Sample? { |
| 271 | func d(_ a: Double?, _ b: Double?) -> Double { QualityReportBuilder.delta(a, b) ?? 0 } |
| 272 | var s = Sample() |
| 273 | s.packets = |
| 274 | d(now.inAudio?.packets, before?.inAudio?.packets) + d(now.inVideo?.packets, before?.inVideo?.packets) |
| 275 | + d(now.inScreen?.packets, before?.inScreen?.packets) |
| 276 | s.lost = |
| 277 | d(now.inAudio?.lost, before?.inAudio?.lost) + d(now.inVideo?.lost, before?.inVideo?.lost) |
| 278 | + d(now.inScreen?.lost, before?.inScreen?.lost) |
| 279 | s.rtt = now.rtt |
| 280 | if s.packets + s.lost == 0, s.rtt == nil { return nil } |
| 281 | if cameraWatched { |
| 282 | s.freezes = d(now.inVideo?.freezes, before?.inVideo?.freezes) |
| 283 | s.freezeSeconds = d(now.inVideo?.freezeSeconds, before?.inVideo?.freezeSeconds) |
| 284 | s.keyframeAsks = d(now.inVideo?.keyframeAsks, before?.inVideo?.keyframeAsks) |
| 285 | } |
| 286 | if let delay = QualityReportBuilder.delta(now.inAudio?.bufferDelay, before?.inAudio?.bufferDelay), |
| 287 | let emitted = QualityReportBuilder.delta(now.inAudio?.emitted, before?.inAudio?.emitted), emitted > 0 |
| 288 | { |
| 289 | s.jitterBufferMs = delay / emitted * 1000 |
| 290 | } |
| 291 | s.decoded = d(now.inVideo?.decoded, before?.inVideo?.decoded) + d(now.inScreen?.decoded, before?.inScreen?.decoded) |
| 292 | s.dropped = d(now.inVideo?.dropped, before?.inVideo?.dropped) + d(now.inScreen?.dropped, before?.inScreen?.dropped) |
| 293 | return s |
| 294 | } |
| 295 | |
| 296 | // MARK: - What is asked, and what is sent |
| 297 | |
| 298 | /// The `video` report: every peer whose level — the watch's or the |
| 299 | /// setting's, whichever is lower — is below normal, at most fifteen. |
| 300 | static func asks(_ levels: [String: VideoLevel], setting: VideoQualitySetting) -> [String: String] { |
| 301 | var out: [String: String] = [:] |
| 302 | for (id, level) in levels.sorted(by: { $0.key < $1.key }) { |
| 303 | let at = max(level, setting.floor) |
| 304 | if at > .normal, out.count < 15 { out[id] = at.wire } |
| 305 | } |
| 306 | return out |
| 307 | } |
| 308 | |
| 309 | /// What one peer's report asks of us. |
| 310 | static func asked(_ media: PeerMedia?, me: String) -> VideoLevel { |
| 311 | guard !me.isEmpty, let word = media?.video?[me] else { return .normal } |
| 312 | return VideoLevel(wire: word) ?? .normal |
| 313 | } |
| 314 | |
| 315 | // The sender's half, as room.js has it (ADAPT_CAMERA, ADAPT_SCREEN). |
| 316 | static let reducedCamera = (bitrate: 350_000, fps: 15, long: 640.0, short: 360.0) |
| 317 | static let minimalCamera = (bitrate: 120_000, fps: 8, long: 320.0, short: 180.0) |
| 318 | static let reducedScreen = (bitrate: 1_200_000, fps: 10) |
| 319 | static let minimalScreen = (bitrate: 500_000, fps: 5, long: 1280.0) |
| 320 | |
| 321 | /// The camera's encoding for one receiver at a level. While a screen |
| 322 | /// goes out the camera gives way first: normal is the cap beside the |
| 323 | /// screen (ScreenSendPolicy.camera), and every level below is one lower |
| 324 | /// for the camera, so a receiver at minimal gets the screen and no |
| 325 | /// camera. Fitted by the camera's long and short sides, so a portrait |
| 326 | /// camera is boxed the right way round. |
| 327 | static func camera(_ level: VideoLevel, sharing: Bool, width: Int = 640, height: Int = 480) -> EncodingPlan { |
| 328 | let at = sharing && level > .normal ? VideoLevel(rawValue: min(3, level.rawValue + 1)) ?? .audio : level |
| 329 | if at == .normal { return ScreenSendPolicy.camera(sharing: sharing, height: height) } |
| 330 | let c = at == .reduced ? reducedCamera : minimalCamera |
| 331 | let long = Double(max(width, height)) |
| 332 | let short = Double(min(width, height)) |
| 333 | let scale = max(1, long / c.long, short / c.short) |
| 334 | var plan = EncodingPlan(maxBitrate: c.bitrate, maxFramerate: c.fps, scaleResolutionDownBy: scale > 1 ? scale : nil) |
| 335 | plan.active = at != .audio |
| 336 | return plan |
| 337 | } |
| 338 | |
| 339 | /// The screen's plan for one receiver at a level: frame rate and bitrate |
| 340 | /// lowered, the size kept, and only at minimal and below the long side |
| 341 | /// brought to 1280; resolution held under pressure from then on. Never |
| 342 | /// paused. The level-fit scale the plan carries (ScreenSendPolicy's H.264 |
| 343 | /// rules) is kept whenever it is larger. |
| 344 | static func screen(_ plan: EncodingPlan, _ level: VideoLevel, width: Int, height: Int) -> EncodingPlan { |
| 345 | guard level > .normal else { return plan } |
| 346 | var out = plan |
| 347 | out.degradation = .maintainResolution |
| 348 | out.active = true |
| 349 | if level == .reduced { |
| 350 | out.maxFramerate = reducedScreen.fps |
| 351 | out.maxBitrate = min(plan.maxBitrate ?? reducedScreen.bitrate, reducedScreen.bitrate) |
| 352 | } else { |
| 353 | out.maxFramerate = minimalScreen.fps |
| 354 | out.maxBitrate = min(plan.maxBitrate ?? minimalScreen.bitrate, minimalScreen.bitrate) |
| 355 | let longest = Double(max(width, height)) |
| 356 | let fit = longest > minimalScreen.long ? longest / minimalScreen.long : 1 |
| 357 | let scale = max(plan.scaleResolutionDownBy ?? 1, fit) |
| 358 | out.scaleResolutionDownBy = scale > 1 ? scale : nil |
| 359 | } |
| 360 | return out |
| 361 | } |
| 362 | |
| 363 | /// An app older than this ignores a request: its video can only be hidden |
| 364 | /// here, which saves this device's work and not the connection. |
| 365 | static let minNativeVersion = "0.4.15" |
| 366 | |
| 367 | /// Whether a peer's client acts on a request: every browser (its page is |
| 368 | /// the server's own), and an app from `minNativeVersion` on. |
| 369 | static func honours(client: String?) -> Bool { |
| 370 | guard let client, !client.isEmpty else { return true } |
| 371 | let parts = client.split(separator: " ") |
| 372 | guard parts.count == 2, ["mac", "iphone", "ipad"].contains(String(parts[0])) else { return false } |
| 373 | return ClientVersion.compare(String(parts[1]), minNativeVersion) >= 0 |
| 374 | } |
| 375 | |
| 376 | /// The sender's quiet notice, for the people it is sending less to. |
| 377 | static func noticeWords(_ people: [(name: String, level: VideoLevel)]) -> String { |
| 378 | guard !people.isEmpty else { return "" } |
| 379 | let names = people.map(\.name) |
| 380 | let list = names.count == 1 ? names[0] : names.dropLast().joined(separator: ", ") + " and " + names[names.count - 1] |
| 381 | let weak = names.count == 1 ? "(their connection is weak)" : "(their connections are weak)" |
| 382 | if people.allSatisfy({ $0.level >= .audio }) { return "Sending only audio to \(list) \(weak)" } |
| 383 | return "Sending reduced video to \(list) \(weak)" |
| 384 | } |
| 385 | |
| 386 | /// The tile's words at audio only. |
| 387 | static let pausedWords = "Video paused to keep audio clear" |
| 388 | static let oldAppWords = "Their app can’t send less video, so it’s only hidden here" |
| 389 | static let badgeWord = "Low bandwidth" |
| 390 | } |
| 391 | |
| 392 | /// §15.30's seconds at each level below normal, asked of and sent to each |
| 393 | /// peer, for the quality report. |
| 394 | struct VideoTime: Equatable, Sendable { |
| 395 | var asked: [Double] = [0, 0, 0] |
| 396 | var sent: [Double] = [0, 0, 0] |
| 397 | |
| 398 | mutating func add(asked a: VideoLevel, sent s: VideoLevel, seconds: Double) { |
| 399 | if a > .normal { asked[a.rawValue - 1] += seconds } |
| 400 | if s > .normal { sent[s.rawValue - 1] += seconds } |
| 401 | } |
| 402 | |
| 403 | /// The report's arrays: three numbers, or nil when all are zero. |
| 404 | static func seconds(_ v: [Double]) -> [Double]? { |
| 405 | guard v.contains(where: { $0 > 0 }) else { return nil } |
| 406 | return v.map { QualityReportBuilder.bound($0, QualityBounds.seconds) ?? 0 } |
| 407 | } |
| 408 | } |
| 409 | |