oficina / meet Public

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

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2#if os(iOS)
3 import UIKit
4#endif
5
6// Quality reports (spec §15.26, Paul's ruling of 2026-10-03): every thirty
7// seconds while admitted, and once more at leave, this app tells the
8// server how its connections went over the window — numbers and enums
9// only, in protocol/quality.go's fixed schema. No names, no addresses, no
10// device names, no meeting, nothing typed by a person.
11//
12// Everything here is pure: the statistics come in as a snapshot
13// (`QualityPeerSample`), the notices as a tally (`QualityEventTally`), and
14// the report comes out, so the whole of it is tested from fixtures. Call
15// gathers the snapshot and sends what comes out.
16//
17// Spec §15.29, "ambient quality detail and the automatic report"
18// (2026-10-28): each window also says how its round trip and jitter went
19// over the whole of it (a once-a-second sampler), why the connection took
20// the path it took (its candidates, by type), which reason held each
21// encoder back longest, and which kind of encoder, decoder and codec each
22// stream had. And when a call is struggling — QualityTrouble's rules —
23// the app sends the automatic "Report a problem" with that window, as
24// the web client does, under the same rules and limits.
25
26// MARK: - The wire (protocol/quality.go)
27
28/// The schema's bounds, as protocol/quality.go has them. The server
29/// refuses a report over any of them, so a client clamps to them first.
30public enum QualityBounds {
31 public static let version = 1
32 /// Remote peers in one report: the mesh holds three, and one spare for a
33 /// connection on its way out. Past it the line would not fit the
34 /// platform's 8 KB.
35 public static let peers = 4
36 public static let seconds = 600.0
37 public static let millis = 600_000.0
38 public static let count = 1e9
39 public static let kbps = 1e6
40 public static let pixels = 16384.0
41 public static let fps = 240.0
42 public static let cpuPct = 12800.0
43 public static let memMB = 1_048_576.0
44 public static let load = 10000.0
45 public static let body = 16 << 10
46 public static let note = 1000
47 public static let problemBody = 64 << 10
48}
49
50public struct QualityReport: Encodable, Equatable, Sendable {
51 public var v = QualityBounds.version
52 /// The report sent at leave or end.
53 public var isFinal: Bool?
54 public var seconds: Double
55 public var client: QualityClient
56 public var devices: QualityDevices?
57 public var events: QualityCallEvents?
58 public var peers: [QualityPeer]?
59 /// The reference of the automatic report sent with this window
60 /// (§15.29), when one was.
61 public var autoReport: String?
62 /// How this machine fared in the window (§15.30, 2026-10-29).
63 public var host: QualityHost?
64
65 enum CodingKeys: String, CodingKey {
66 case v, seconds, client, devices, events, peers, autoReport, host
67 case isFinal = "final"
68 }
69
70 /// The body as it is sent: sorted keys, so two equal reports are the
71 /// same bytes.
72 public func encoded() -> String? {
73 let encoder = JSONEncoder()
74 encoder.outputFormatting = [.sortedKeys]
75 guard let data = try? encoder.encode(self), data.count <= QualityBounds.body else { return nil }
76 return String(data: data, encoding: .utf8)
77 }
78}
79
80/// What is reporting: enums, and versions as digits and dots. Never a
81/// device model or a machine name.
82public struct QualityClient: Codable, Equatable, Sendable {
83 public var app: String
84 public var version: String?
85 public var os: String?
86 public var osVersion: String?
87
88 public init(app: String, version: String? = nil, os: String? = nil, osVersion: String? = nil) {
89 self.app = app
90 self.version = version
91 self.os = os
92 self.osVersion = osVersion
93 }
94}
95
96/// The kinds of microphone and speaker in use, by transport: never a
97/// device's name, which can be personal ("Paul's AirPods Pro").
98public struct QualityDevices: Encodable, Equatable, Sendable {
99 public var input: String?
100 public var output: String?
101}
102
103public struct QualityCallEvents: Encodable, Equatable, Sendable {
104 public var reconnecting: Double?
105 public var reconnectingSeconds: Double?
106 /// §15.30: "low" or "audio", the person's own Video quality; absent for
107 /// Auto.
108 public var videoSetting: String?
109}
110
111public struct QualityPeer: Encodable, Equatable, Sendable {
112 public var peer: String
113 public var path: QualityPath?
114 public var rtt: Double?
115 /// The window's round trip (§15.29): its mean, the pair's own total over
116 /// its responses where it has them and the once-a-second readings'
117 /// otherwise, and its highest reading; and the peer's inbound jitter,
118 /// read once a second, its mean and highest. All in ms.
119 public var rttAvg: Double?
120 public var rttMax: Double?
121 public var jitterAvg: Double?
122 public var jitterMax: Double?
123 public var candidates: QualityCandidates?
124 public var out: QualityOutbound?
125 public var `in`: QualityInbound?
126 public var events: QualityPeerEvents?
127}
128
129/// How the connection was found (§15.29): what this side gathered and what
130/// the peer offered, by type, and which kinds of pair worked. Types and
131/// counts only, never an address. A count is left out when it is none;
132/// the three booleans always go, because the server reads the struct's
133/// presence as "measured".
134public struct QualityCandidates: Encodable, Equatable, Sendable {
135 public var host: Double?
136 public var srflx: Double?
137 public var prflx: Double?
138 public var relay: Double?
139 public var remoteHost: Double?
140 public var remoteSrflx: Double?
141 public var remotePrflx: Double?
142 public var remoteRelay: Double?
143 /// A pair with neither end a relay succeeded.
144 public var directOk = false
145 /// A pair whose local end is not a relay succeeded.
146 public var localDirectOk = false
147 /// A pair carried over UDP the whole way to the peer or the relay
148 /// succeeded.
149 public var udpOk = false
150}
151
152public struct QualityPath: Encodable, Equatable, Sendable {
153 public var local: String?
154 public var remote: String?
155 public var `protocol`: String?
156}
157
158public struct QualityOutbound: Encodable, Equatable, Sendable {
159 public var audio: QualityOutStream?
160 public var video: QualityOutStream?
161 public var screen: QualityOutStream?
162}
163
164public struct QualityOutStream: Encodable, Equatable, Sendable {
165 public var kbps: Double?
166 public var packets: Double?
167 public var lost: Double?
168 public var rtt: Double?
169 public var jitter: Double?
170 public var limit: String?
171 public var width: Double?
172 public var height: Double?
173 public var fps: Double?
174 public var keyframes: Double?
175 public var rebuilds: Double?
176 public var reshares: Double?
177 public var failures: Double?
178 /// Steps held back as a loop, and times the screen stopped leaving here
179 /// (2026-10-21).
180 public var damped: Double?
181 public var encoderStalls: Double?
182 /// §15.29: how long bandwidth and the cpu each held the encoder back in
183 /// the window, in seconds; the encoder's kind (CoderKinds), the codec's
184 /// family (Codecs), and the screen's share mode (ShareModes).
185 public var limitedBandwidthSeconds: Double?
186 public var limitedCpuSeconds: Double?
187 public var encoder: String?
188 public var codec: String?
189 public var mode: String?
190}
191
192public struct QualityInbound: Encodable, Equatable, Sendable {
193 public var audio: QualityInAudio?
194 public var video: QualityInVideo?
195 public var screen: QualityInVideo?
196}
197
198public struct QualityInAudio: Encodable, Equatable, Sendable {
199 public var kbps: Double?
200 public var packets: Double?
201 public var lost: Double?
202 public var jitter: Double?
203 public var samples: Double?
204 public var concealed: Double?
205 public var inserted: Double?
206 public var removed: Double?
207 public var jitterBufferMs: Double?
208}
209
210public struct QualityInVideo: Encodable, Equatable, Sendable {
211 public var kbps: Double?
212 public var packets: Double?
213 public var lost: Double?
214 public var jitter: Double?
215 public var freezes: Double?
216 public var freezeSeconds: Double?
217 public var decoded: Double?
218 public var dropped: Double?
219 public var width: Double?
220 public var height: Double?
221 public var fps: Double?
222 public var reattaches: Double?
223 /// Times this side judged the screen stalled, and what its statistics
224 /// said: nothing arriving, or arriving and not decoded (2026-10-21).
225 public var stalls: Double?
226 public var stallsNoPackets: Double?
227 public var stallsUndecoded: Double?
228 /// §15.29: the decoder's kind (CoderKinds) and the codec's family.
229 public var decoder: String?
230 public var codec: String?
231}
232
233public struct QualityPeerEvents: Encodable, Equatable, Sendable {
234 public var reconnecting: Double?
235 public var reconnectingSeconds: Double?
236 public var cantHearSeconds: Double?
237 public var noSound: Bool?
238 public var noSoundFromUs: Bool?
239 public var audioBlocked: Bool?
240 public var screenStalled: Bool?
241 /// §15.28: ICE restarts and rebuilds this app's recovery made.
242 public var autoRestarts: Double?
243 public var autoRebuilds: Double?
244 /// §15.30: seconds this app asked them for each level below normal
245 /// (reduced, minimal, audio), and seconds it sent them less because they
246 /// asked; three numbers, or absent.
247 public var askedSeconds: [Double]?
248 public var sentSeconds: [Double]?
249}
250
251// MARK: - The snapshot
252
253/// One statistics object from WebRTC's report, its values split by kind:
254/// numbers (NSNumber, booleans among them) and strings. A dictionary of
255/// numbers (qualityLimitationDurations) is kept as numbers named
256/// "qualityLimitationDurations.bandwidth" and so on. Nothing else in a
257/// report is read.
258public struct QualityStat: Equatable, Sendable {
259 public var type: String
260 public var numbers: [String: Double]
261 public var strings: [String: String]
262
263 public init(type: String, numbers: [String: Double] = [:], strings: [String: String] = [:]) {
264 self.type = type
265 self.numbers = numbers
266 self.strings = strings
267 }
268
269 /// From WebRTC's own values.
270 init(type: String, values: [String: Any]) {
271 var numbers: [String: Double] = [:]
272 var strings: [String: String] = [:]
273 for (key, value) in values {
274 if let n = value as? NSNumber {
275 numbers[key] = n.doubleValue
276 } else if let s = value as? String {
277 strings[key] = s
278 } else if let d = value as? [String: Any] {
279 for (name, inner) in d {
280 if let n = inner as? NSNumber { numbers[key + "." + name] = n.doubleValue }
281 }
282 }
283 }
284 self.init(type: type, numbers: numbers, strings: strings)
285 }
286}
287
288/// One connection's statistics at one look, with what is needed to read
289/// them: the connection's generation (a new one starts every count from
290/// nothing), and which mids are screens.
291public struct QualityPeerSample: Equatable, Sendable {
292 public var generation: Int64
293 /// The mid this app's own screen goes out on, while sharing.
294 public var ownScreenMid: String?
295 /// The mid their screen arrives on here, while they share.
296 public var screenMid: String
297 public var stats: [String: QualityStat]
298
299 public init(generation: Int64, ownScreenMid: String? = nil, screenMid: String = "", stats: [String: QualityStat]) {
300 self.generation = generation
301 self.ownScreenMid = ownScreenMid
302 self.screenMid = screenMid
303 self.stats = stats
304 }
305}
306
307// MARK: - Running totals, read from a snapshot
308
309/// The cumulative counters and current gauges of one connection, as the
310/// statistics have them. A report is the difference between two of these.
311///
312/// What is read is read by name (§15.29 as §15.26): an encoder's or
313/// decoder's implementation name and a codec's MIME type become the
314/// schema's enums here, as they are read, and the selected pair's id is
315/// kept only to tell the next window it is the same pair. No address,
316/// port, url or implementation name is kept.
317struct QualityCounters: Equatable, Sendable {
318 struct Out: Equatable, Sendable {
319 var bytes: Double?
320 var packets: Double?
321 var lost: Double?
322 var rtt: Double?
323 var jitter: Double?
324 var limit: String?
325 var width: Double?
326 var height: Double?
327 var fps: Double?
328 /// qualityLimitationDurations: seconds the encoder has been held back
329 /// by each reason since the stream began, by reason.
330 var limitSeconds: [String: Double]?
331 /// CoderKinds and Codecs.
332 var encoder: String?
333 var codec: String?
334 }
335 struct InAudio: Equatable, Sendable {
336 var bytes: Double?
337 var packets: Double?
338 var lost: Double?
339 var jitter: Double?
340 var samples: Double?
341 var concealed: Double?
342 var inserted: Double?
343 var removed: Double?
344 var bufferDelay: Double?
345 var emitted: Double?
346 }
347 struct InVideo: Equatable, Sendable {
348 var bytes: Double?
349 var packets: Double?
350 var lost: Double?
351 var jitter: Double?
352 var freezes: Double?
353 var freezeSeconds: Double?
354 var decoded: Double?
355 var dropped: Double?
356 var width: Double?
357 var height: Double?
358 var fps: Double?
359 /// CoderKinds and Codecs.
360 var decoder: String?
361 var codec: String?
362 /// PLIs and FIRs this side sent for it (spec §15.30's watch; not
363 /// reported).
364 var keyframeAsks: Double?
365 }
366 var outAudio: Out?
367 var outVideo: Out?
368 var outScreen: Out?
369 var inAudio: InAudio?
370 var inVideo: InVideo?
371 var inScreen: InVideo?
372 var path: QualityPath?
373 var rtt: Double?
374 /// The selected pair's id (the statistics' own, never sent) and its
375 /// running totals: the round trips it has measured, in seconds, and the
376 /// responses they came from.
377 var pair: String?
378 var totalRtt: Double?
379 var responses: Double?
380 var candidates: QualityCandidates?
381
382 init() {}
383
384 /// Reads a snapshot. A stream absent from the statistics is absent
385 /// here; a value WebRTC does not give is nil, never zero.
386 init(_ sample: QualityPeerSample) {
387 let stats = sample.stats
388 for (id, stat) in stats {
389 let kind = stat.strings["kind"] ?? stat.strings["mediaType"] ?? ""
390 let mid = stat.strings["mid"] ?? ""
391 switch stat.type {
392 case "outbound-rtp":
393 var out = Out()
394 out.bytes = stat.numbers["bytesSent"]
395 out.packets = stat.numbers["packetsSent"]
396 out.limit = stat.strings["qualityLimitationReason"]
397 out.width = stat.numbers["frameWidth"]
398 out.height = stat.numbers["frameHeight"]
399 out.fps = stat.numbers["framesPerSecond"]
400 out.limitSeconds = Self.limitSeconds(stat)
401 out.encoder = QualityWords.coder(
402 impl: stat.strings["encoderImplementation"],
403 powerEfficient: stat.numbers["powerEfficientEncoder"].map { $0 != 0 })
404 out.codec = QualityWords.codec(mimeType: Self.mimeType(of: stat, in: stats))
405 // The receiver's own account of this stream.
406 if let remote = stats.values.first(where: { $0.type == "remote-inbound-rtp" && $0.strings["localId"] == id }) {
407 out.lost = remote.numbers["packetsLost"]
408 out.rtt = remote.numbers["roundTripTime"].map { $0 * 1000 }
409 out.jitter = remote.numbers["jitter"].map { $0 * 1000 }
410 }
411 if kind == "audio" {
412 outAudio = Self.add(outAudio, out)
413 } else if kind == "video" {
414 if let own = sample.ownScreenMid, !own.isEmpty, own == mid {
415 outScreen = Self.add(outScreen, out)
416 } else {
417 outVideo = Self.add(outVideo, out)
418 }
419 }
420 case "inbound-rtp":
421 if kind == "audio" {
422 var a = inAudio ?? InAudio()
423 a.bytes = Self.sum(a.bytes, stat.numbers["bytesReceived"])
424 a.packets = Self.sum(a.packets, stat.numbers["packetsReceived"])
425 a.lost = Self.sum(a.lost, stat.numbers["packetsLost"])
426 a.jitter = Self.most(a.jitter, stat.numbers["jitter"].map { $0 * 1000 })
427 a.samples = Self.sum(a.samples, stat.numbers["totalSamplesReceived"])
428 a.concealed = Self.sum(a.concealed, stat.numbers["concealedSamples"])
429 a.inserted = Self.sum(a.inserted, stat.numbers["insertedSamplesForDeceleration"])
430 a.removed = Self.sum(a.removed, stat.numbers["removedSamplesForAcceleration"])
431 a.bufferDelay = Self.sum(a.bufferDelay, stat.numbers["jitterBufferDelay"])
432 a.emitted = Self.sum(a.emitted, stat.numbers["jitterBufferEmittedCount"])
433 inAudio = a
434 } else if kind == "video" {
435 var v = InVideo()
436 v.bytes = stat.numbers["bytesReceived"]
437 v.packets = stat.numbers["packetsReceived"]
438 v.lost = stat.numbers["packetsLost"]
439 v.jitter = stat.numbers["jitter"].map { $0 * 1000 }
440 v.freezes = stat.numbers["freezeCount"]
441 v.freezeSeconds = stat.numbers["totalFreezesDuration"]
442 v.decoded = stat.numbers["framesDecoded"]
443 v.dropped = stat.numbers["framesDropped"]
444 v.width = stat.numbers["frameWidth"]
445 v.height = stat.numbers["frameHeight"]
446 v.fps = stat.numbers["framesPerSecond"]
447 v.decoder = QualityWords.coder(
448 impl: stat.strings["decoderImplementation"],
449 powerEfficient: stat.numbers["powerEfficientDecoder"].map { $0 != 0 })
450 v.codec = QualityWords.codec(mimeType: Self.mimeType(of: stat, in: stats))
451 if stat.numbers["pliCount"] != nil || stat.numbers["firCount"] != nil {
452 v.keyframeAsks = (stat.numbers["pliCount"] ?? 0) + (stat.numbers["firCount"] ?? 0)
453 }
454 // Told apart by mid, as the statistics elsewhere are: a peer
455 // sharing its screen sends two video streams.
456 if !sample.screenMid.isEmpty, mid == sample.screenMid {
457 inScreen = Self.add(inScreen, v)
458 } else {
459 inVideo = Self.add(inVideo, v)
460 }
461 }
462 default: break
463 }
464 }
465 readPath(stats)
466 readCandidates(stats)
467 }
468
469 /// The reasons qualityLimitationDurations is kept for, as QualityStat
470 /// flattens it.
471 static let limitReasons = ["none", "cpu", "bandwidth", "other"]
472
473 private static func limitSeconds(_ stat: QualityStat) -> [String: Double]? {
474 var out: [String: Double] = [:]
475 for reason in limitReasons {
476 if let v = stat.numbers["qualityLimitationDurations." + reason] { out[reason] = v }
477 }
478 return out.isEmpty ? nil : out
479 }
480
481 /// The stream's codec's MIME type, through its codecId.
482 private static func mimeType(of stat: QualityStat, in stats: [String: QualityStat]) -> String? {
483 guard let id = stat.strings["codecId"], let codec = stats[id], codec.type == "codec" else { return nil }
484 return codec.strings["mimeType"]
485 }
486
487 /// The selected candidate pair: each end's kind of candidate and the
488 /// transport, and its round trip. Addresses and ports are in the same
489 /// objects and are never read.
490 private mutating func readPath(_ stats: [String: QualityStat]) {
491 var pairId = stats.values.first { $0.type == "transport" }?.strings["selectedCandidatePairId"]
492 if pairId == nil {
493 pairId = stats.first {
494 $0.value.type == "candidate-pair" && ($0.value.numbers["nominated"] ?? 0) != 0
495 && $0.value.strings["state"] == "succeeded"
496 }?.key
497 }
498 guard let pairId, let pair = stats[pairId] else { return }
499 let local = pair.strings["localCandidateId"].flatMap { stats[$0] }
500 let remote = pair.strings["remoteCandidateId"].flatMap { stats[$0] }
501 var path = QualityPath()
502 path.local = local.map { QualityWords.candidate($0.strings["candidateType"]) }
503 path.remote = remote.map { QualityWords.candidate($0.strings["candidateType"]) }
504 if let local {
505 path.protocol = QualityWords.transport(
506 local.strings["protocol"], relayProtocol: local.strings["relayProtocol"],
507 relay: local.strings["candidateType"] == "relay")
508 }
509 self.path = path
510 rtt = pair.numbers["currentRoundTripTime"].map { $0 * 1000 }
511 self.pair = pairId
512 totalRtt = pair.numbers["totalRoundTripTime"]
513 responses = pair.numbers["responsesReceived"]
514 }
515
516 /// §15.29: the candidates each side has, counted by type, and which
517 /// kinds of pair succeeded. Nothing when the statistics have no
518 /// candidates at all: a side that cannot read them says nothing, rather
519 /// than "none".
520 private mutating func readCandidates(_ stats: [String: QualityStat]) {
521 let types: Set = ["host", "srflx", "prflx", "relay"]
522 var local: [String: Double] = [:]
523 var remote: [String: Double] = [:]
524 var any = false
525 for stat in stats.values where stat.type == "local-candidate" || stat.type == "remote-candidate" {
526 any = true
527 guard let type = stat.strings["candidateType"], types.contains(type) else { continue }
528 if stat.type == "local-candidate" { local[type, default: 0] += 1 } else { remote[type, default: 0] += 1 }
529 }
530 guard any else { return }
531 let some = { (n: Double?) in n.flatMap { $0 > 0 ? QualityReportBuilder.bound($0, QualityBounds.count) : nil } }
532 var c = QualityCandidates(
533 host: some(local["host"]), srflx: some(local["srflx"]), prflx: some(local["prflx"]),
534 relay: some(local["relay"]), remoteHost: some(remote["host"]), remoteSrflx: some(remote["srflx"]),
535 remotePrflx: some(remote["prflx"]), remoteRelay: some(remote["relay"]))
536 for pair in stats.values where pair.type == "candidate-pair" && pair.strings["state"] == "succeeded" {
537 guard let near = pair.strings["localCandidateId"].flatMap({ stats[$0] }),
538 let nearType = near.strings["candidateType"], types.contains(nearType)
539 else { continue }
540 let farType = pair.strings["remoteCandidateId"].flatMap { stats[$0] }?.strings["candidateType"]
541 let relayed = nearType == "relay"
542 if !relayed { c.localDirectOk = true }
543 if !relayed, let farType, types.contains(farType), farType != "relay" { c.directOk = true }
544 if near.strings["protocol"]?.lowercased() == "udp",
545 !relayed || near.strings["relayProtocol"]?.lowercased() == "udp"
546 {
547 c.udpOk = true
548 }
549 }
550 candidates = c
551 }
552
553 private static func sum(_ a: Double?, _ b: Double?) -> Double? {
554 guard let b else { return a }
555 return (a ?? 0) + b
556 }
557 private static func most(_ a: Double?, _ b: Double?) -> Double? {
558 guard let b else { return a }
559 return max(a ?? b, b)
560 }
561 /// Two streams of the same kind (a stream replaced on a fresh
562 /// transceiver, briefly beside the one it replaces): counts add, gauges
563 /// are the larger.
564 private static func add(_ a: Out?, _ b: Out) -> Out {
565 guard var a else { return b }
566 a.bytes = sum(a.bytes, b.bytes)
567 a.packets = sum(a.packets, b.packets)
568 a.lost = sum(a.lost, b.lost)
569 a.rtt = most(a.rtt, b.rtt)
570 a.jitter = most(a.jitter, b.jitter)
571 a.limit = a.limit ?? b.limit
572 a.width = most(a.width, b.width)
573 a.height = most(a.height, b.height)
574 a.fps = most(a.fps, b.fps)
575 if let more = b.limitSeconds {
576 a.limitSeconds = (a.limitSeconds ?? [:]).merging(more, uniquingKeysWith: +)
577 }
578 a.encoder = a.encoder ?? b.encoder
579 a.codec = a.codec ?? b.codec
580 return a
581 }
582 private static func add(_ a: InVideo?, _ b: InVideo) -> InVideo {
583 guard var a else { return b }
584 a.bytes = sum(a.bytes, b.bytes)
585 a.packets = sum(a.packets, b.packets)
586 a.lost = sum(a.lost, b.lost)
587 a.jitter = most(a.jitter, b.jitter)
588 a.freezes = sum(a.freezes, b.freezes)
589 a.freezeSeconds = sum(a.freezeSeconds, b.freezeSeconds)
590 a.decoded = sum(a.decoded, b.decoded)
591 a.dropped = sum(a.dropped, b.dropped)
592 a.width = most(a.width, b.width)
593 a.height = most(a.height, b.height)
594 a.fps = most(a.fps, b.fps)
595 a.decoder = a.decoder ?? b.decoder
596 a.codec = a.codec ?? b.codec
597 a.keyframeAsks = sum(a.keyframeAsks, b.keyframeAsks)
598 return a
599 }
600}
601
602/// The schema's enums, from WebRTC's words.
603enum QualityWords {
604 static func candidate(_ type: String?) -> String {
605 switch type {
606 case "host", "srflx", "prflx", "relay": return type!
607 default: return "unknown"
608 }
609 }
610
611 /// udp or tcp; tls for a relay reached over TURN/TLS.
612 static func transport(_ proto: String?, relayProtocol: String?, relay: Bool) -> String {
613 // A relay candidate's own protocol is the relay's leg to the peer; how
614 // this side reaches the relay is relayProtocol, as room.js reads it
615 // (2026-10-28: TURN over TCP was "udp" here and "tcp" on the web).
616 if relay, let via = relayProtocol?.lowercased(), ["udp", "tcp", "tls"].contains(via) { return via }
617 switch proto?.lowercased() {
618 case "udp": return "udp"
619 case "tcp": return "tcp"
620 default: return "unknown"
621 }
622 }
623
624 static func limit(_ reason: String?) -> String? {
625 guard let reason, !reason.isEmpty else { return nil }
626 return ["none", "cpu", "bandwidth"].contains(reason) ? reason : "other"
627 }
628
629 /// A video encoder's or decoder's kind (§15.29, CoderKinds), the web
630 /// client's coderKind: the stack's own powerEfficientEncoder/Decoder
631 /// where it says, else the implementation's name ("VideoToolbox",
632 /// "libvpx", "FallbackEncoder (…)"), which never leaves this function;
633 /// "unknown" for a name it cannot place, nil when there is nothing.
634 static func coder(impl: String?, powerEfficient: Bool?) -> String? {
635 if let powerEfficient { return powerEfficient ? "hardware" : "software" }
636 guard let name = impl?.lowercased(), !name.isEmpty else { return nil }
637 let hardware = [
638 "videotoolbox", "external", "mediacodec", "vaapi", "v4l2", "d3d11", "dxva", "nvenc", "nvdec",
639 "mediafoundation", "qsv", "amf",
640 ]
641 if hardware.contains(where: name.contains) { return "hardware" }
642 let software = ["libvpx", "openh264", "libaom", "dav1d", "ffmpeg", "libav", "fallback", "software"]
643 if software.contains(where: name.contains) { return "software" }
644 return "unknown"
645 }
646
647 /// A stream's codec family (§15.29, Codecs) from its MIME type, the web
648 /// client's codecKind: "other" for one not on the list, nil for none.
649 static func codec(mimeType: String?) -> String? {
650 guard let m = mimeType?.lowercased(), !m.isEmpty else { return nil }
651 switch m {
652 case "video/vp8": return "vp8"
653 case "video/vp9": return "vp9"
654 case "video/h264": return "h264"
655 case "video/h265", "video/hevc": return "h265"
656 case "video/av1": return "av1"
657 case "audio/opus": return "opus"
658 default: return "other"
659 }
660 }
661}
662
663// MARK: - The notices, tallied
664
665/// What the call said during a window (§15.20, §15.21, §15.23, §15.24), and
666/// the screen watchdogs' steps (§15.22), fed from the level watch's looks.
667/// A notice still showing when the window ends carries into the next
668/// without being counted again.
669public struct QualityEventTally: Equatable, Sendable {
670 /// A screen recovery step, toward a peer (the sharer's) or for their
671 /// screen here (the receiver's).
672 public enum Step: Sendable {
673 case keyframe, rebuild, reshare, failure, reattach, damped, encoderStall
674 /// The connection's own recovery (§15.28).
675 case autoRestart, autoRebuild
676 /// The receiver judged the screen stalled: `arriving` false when no
677 /// packets came since it last moved, `decoding` false when they came
678 /// and nothing was decoded.
679 case stall(arriving: Bool, decoding: Bool)
680 }
681
682 struct Peer: Equatable, Sendable {
683 var reconnecting = 0
684 var reconnectingSeconds = 0.0
685 var cantHearSeconds = 0.0
686 var noSound = false
687 var noSoundFromUs = false
688 var audioBlocked = false
689 var screenStalled = false
690 var keyframes = 0
691 var rebuilds = 0
692 var reshares = 0
693 var failures = 0
694 var reattaches = 0
695 var damped = 0
696 var encoderStalls = 0
697 var stalls = 0
698 var stallsNoPackets = 0
699 var stallsUndecoded = 0
700 /// The connection's own recovery (§15.28).
701 var autoRestarts = 0
702 var autoRebuilds = 0
703 /// §15.30's seconds at each level, asked and sent.
704 var video = VideoTime()
705 }
706
707 /// The longest a look is taken to cover: the level watch looks five
708 /// times a second, and a gap longer than this is the process asleep, not
709 /// a notice on screen.
710 static let longestLook = 1.0
711
712 private var last: Double?
713 private var callShown = false
714 private var peersShown: Set<String> = []
715 private(set) var callReconnecting = 0
716 private(set) var callSeconds = 0.0
717 private(set) var peers: [String: Peer] = [:]
718 /// §15.30: the person's own Video quality, when it is not Auto.
719 var videoSetting: VideoQualitySetting = .auto
720
721 public init() {}
722
723 /// One look. `reconnecting` and `cantHear` are the people whose tiles
724 /// say so now; the rest are the people each fact is true of now.
725 public mutating func observe(
726 at now: Double, call: Bool, reconnecting: Set<String>, cantHear: Set<String>,
727 noSound: Set<String> = [], noSoundFromUs: Set<String> = [], audioBlocked: Set<String> = [],
728 screenStalled: Set<String> = []
729 ) {
730 let dt = last.map { min(max(now - $0, 0), Self.longestLook) } ?? 0
731 last = now
732 if call {
733 if !callShown { callReconnecting += 1 }
734 callSeconds += dt
735 }
736 callShown = call
737 for id in reconnecting {
738 if !peersShown.contains(id) { peers[id, default: Peer()].reconnecting += 1 }
739 peers[id, default: Peer()].reconnectingSeconds += dt
740 }
741 peersShown = reconnecting
742 for id in cantHear { peers[id, default: Peer()].cantHearSeconds += dt }
743 for id in noSound { peers[id, default: Peer()].noSound = true }
744 for id in noSoundFromUs { peers[id, default: Peer()].noSoundFromUs = true }
745 for id in audioBlocked { peers[id, default: Peer()].audioBlocked = true }
746 for id in screenStalled { peers[id, default: Peer()].screenStalled = true }
747 }
748
749 /// §15.30: time at the levels asked of and sent to one peer.
750 mutating func video(asked: VideoLevel, sent: VideoLevel, seconds: Double, for peer: String) {
751 guard asked > .normal || sent > .normal, seconds > 0 else { return }
752 peers[peer, default: Peer()].video.add(asked: asked, sent: sent, seconds: seconds)
753 }
754
755 public mutating func count(_ step: Step, for peer: String) {
756 switch step {
757 case .keyframe: peers[peer, default: Peer()].keyframes += 1
758 case .rebuild: peers[peer, default: Peer()].rebuilds += 1
759 case .reshare: peers[peer, default: Peer()].reshares += 1
760 case .failure: peers[peer, default: Peer()].failures += 1
761 case .reattach: peers[peer, default: Peer()].reattaches += 1
762 case .damped: peers[peer, default: Peer()].damped += 1
763 case .encoderStall: peers[peer, default: Peer()].encoderStalls += 1
764 case .stall(let arriving, let decoding):
765 peers[peer, default: Peer()].stalls += 1
766 if !arriving { peers[peer, default: Peer()].stallsNoPackets += 1 } else if !decoding {
767 peers[peer, default: Peer()].stallsUndecoded += 1
768 }
769 case .autoRestart: peers[peer, default: Peer()].autoRestarts += 1
770 case .autoRebuild: peers[peer, default: Peer()].autoRebuilds += 1
771 }
772 }
773
774 /// The window's tally, and a fresh one for the next window that
775 /// remembers what is still showing.
776 mutating func take() -> QualityEventTally {
777 let window = self
778 callReconnecting = 0
779 callSeconds = 0
780 peers = [:]
781 return window
782 }
783}
784
785// MARK: - The window's once-a-second readings
786
787/// One peer's round trip and inbound jitter, read once a second through a
788/// window (§15.29): a sum, a count and the highest, in ms. The report says
789/// the mean and the highest, so a window that spiked and settled is not
790/// reported as the moment it ended.
791struct QualityWindowSamples: Equatable, Sendable {
792 var rttSum = 0.0
793 var rttCount = 0
794 var rttMax = 0.0
795 var jitterSum = 0.0
796 var jitterCount = 0
797 var jitterMax = 0.0
798
799 /// One reading; a value that is not a finite, non-negative number is
800 /// not one.
801 mutating func add(rtt: Double?, jitter: Double?) {
802 if let rtt, rtt.isFinite, rtt >= 0 {
803 rttSum += rtt
804 rttCount += 1
805 rttMax = max(rttMax, rtt)
806 }
807 if let jitter, jitter.isFinite, jitter >= 0 {
808 jitterSum += jitter
809 jitterCount += 1
810 jitterMax = max(jitterMax, jitter)
811 }
812 }
813}
814
815// MARK: - The report
816
817/// Turns snapshots into reports: keeps each connection's running totals
818/// from the last report, so a report's counts are what happened during
819/// its window. A new connection generation, or a counter that went
820/// backwards (a stream rebuilt on a fresh transceiver), starts from
821/// nothing. Between reports, `observe` takes the once-a-second readings
822/// the window's round trip and jitter are made from (§15.29).
823public struct QualityReportBuilder: Equatable, Sendable {
824 private var since: Double?
825 private var previous: [String: (generation: Int64, counters: QualityCounters)] = [:]
826 private var window: [String: QualityWindowSamples] = [:]
827
828 public init() {}
829
830 public var started: Bool { since != nil }
831
832 /// Seconds since the window began; zero before it has.
833 public func elapsed(at now: Double) -> Double { since.map { now - $0 } ?? 0 }
834
835 /// The first window begins: at admission.
836 public mutating func start(at now: Double) {
837 since = now
838 previous = [:]
839 window = [:]
840 }
841
842 public static func == (a: Self, b: Self) -> Bool {
843 a.since == b.since && a.previous.keys == b.previous.keys && a.window == b.window
844 }
845
846 /// One look at every connection, once a second (§15.29): the selected
847 /// pair's round trip and the peer's inbound jitter — their audio, or
848 /// their camera when no audio arrives — for the window's mean and
849 /// highest.
850 public mutating func observe(samples: [String: QualityPeerSample]) {
851 for (id, sample) in samples {
852 let now = QualityCounters(sample)
853 window[id, default: QualityWindowSamples()].add(rtt: now.rtt, jitter: now.inAudio?.jitter ?? now.inVideo?.jitter)
854 }
855 }
856
857 /// One report, for the window from the last one (or `start`) to `now`.
858 /// `screenMode` is this app's screen share mode (ScreenShareMode's raw
859 /// value) while it shares, and nil while it does not.
860 public mutating func build(
861 at now: Double, samples: [String: QualityPeerSample], events tally: inout QualityEventTally,
862 client: QualityClient, devices: QualityDevices?, final: Bool, screenMode: String? = nil
863 ) -> QualityReport {
864 let seconds = max(now - (since ?? now), 0.1)
865 since = now
866 let events = tally.take()
867 var report = QualityReport(
868 isFinal: final ? true : nil, seconds: Self.bound(seconds, QualityBounds.seconds) ?? QualityBounds.seconds,
869 client: client, devices: devices)
870 if events.callReconnecting > 0 || events.callSeconds > 0 || events.videoSetting != .auto {
871 report.events = QualityCallEvents(
872 reconnecting: Self.steps(events.callReconnecting),
873 reconnectingSeconds: events.callSeconds > 0 ? Self.bound(events.callSeconds, QualityBounds.seconds) : nil,
874 videoSetting: events.videoSetting == .auto ? nil : events.videoSetting.rawValue)
875 }
876 let ids = Set(samples.keys).union(events.peers.keys).sorted()
877 var peers: [QualityPeer] = []
878 for id in ids.prefix(QualityBounds.peers) {
879 var peer = QualityPeer(peer: id)
880 if let sample = samples[id] {
881 let now = QualityCounters(sample)
882 let before = previous[id].flatMap { $0.generation == sample.generation ? $0.counters : nil }
883 previous[id] = (sample.generation, now)
884 peer.path = now.path
885 peer.rtt = Self.bound(now.rtt, QualityBounds.millis)
886 Self.applyWindow(window[id], now: now, before: before, to: &peer)
887 peer.candidates = now.candidates
888 var out = QualityOutbound()
889 out.audio = now.outAudio.map { Self.out($0, before?.outAudio, seconds, video: false) }
890 out.video = now.outVideo.map { Self.out($0, before?.outVideo, seconds, video: true) }
891 out.screen = now.outScreen.map { Self.out($0, before?.outScreen, seconds, video: true) }
892 if out != QualityOutbound() { peer.out = out }
893 var inbound = QualityInbound()
894 inbound.audio = now.inAudio.map { Self.inAudio($0, before?.inAudio, seconds) }
895 inbound.video = now.inVideo.map { Self.inVideo($0, before?.inVideo, seconds) }
896 inbound.screen = now.inScreen.map { Self.inVideo($0, before?.inScreen, seconds) }
897 if inbound != QualityInbound() { peer.in = inbound }
898 }
899 if let e = events.peers[id] { Self.apply(e, to: &peer) }
900 if let screenMode, peer.out?.screen != nil { peer.out?.screen?.mode = screenMode }
901 peers.append(peer)
902 }
903 // A connection gone is forgotten; if it comes back it starts again.
904 for id in Array(previous.keys) where samples[id] == nil { previous.removeValue(forKey: id) }
905 window = [:]
906 report.peers = peers.isEmpty ? nil : peers
907 return report
908 }
909
910 /// The window's round trip and jitter (§15.29). The mean round trip is
911 /// the pair's own: what its totals moved by, over the responses they
912 /// came from, where the pair is the one the last report read (a new
913 /// pair, or a new connection, counts from nothing, as a new stream
914 /// does); without responses, the once-a-second readings' mean. The
915 /// highest is of those readings and this one.
916 private static func applyWindow(
917 _ w: QualityWindowSamples?, now: QualityCounters, before: QualityCounters?, to peer: inout QualityPeer
918 ) {
919 let same = before?.pair != nil && before?.pair == now.pair
920 if let responses = delta(now.responses, same ? before?.responses : nil), responses > 0,
921 let total = delta(now.totalRtt, same ? before?.totalRtt : nil)
922 {
923 peer.rttAvg = bound(total / responses * 1000, QualityBounds.millis)
924 } else if let w, w.rttCount > 0 {
925 peer.rttAvg = bound(w.rttSum / Double(w.rttCount), QualityBounds.millis)
926 }
927 let highest = [w.flatMap { $0.rttCount > 0 ? $0.rttMax : nil }, now.rtt].compactMap { $0 }.max()
928 peer.rttMax = bound(highest, QualityBounds.millis)
929 if let w, w.jitterCount > 0 {
930 peer.jitterAvg = bound(w.jitterSum / Double(w.jitterCount), QualityBounds.millis)
931 peer.jitterMax = bound(w.jitterMax, QualityBounds.millis)
932 }
933 }
934
935 private static func apply(_ e: QualityEventTally.Peer, to peer: inout QualityPeer) {
936 var events = QualityPeerEvents()
937 events.reconnecting = steps(e.reconnecting)
938 if e.reconnectingSeconds > 0 { events.reconnectingSeconds = bound(e.reconnectingSeconds, QualityBounds.seconds) }
939 if e.cantHearSeconds > 0 { events.cantHearSeconds = bound(e.cantHearSeconds, QualityBounds.seconds) }
940 if e.noSound { events.noSound = true }
941 if e.noSoundFromUs { events.noSoundFromUs = true }
942 if e.audioBlocked { events.audioBlocked = true }
943 if e.screenStalled { events.screenStalled = true }
944 events.autoRestarts = steps(e.autoRestarts)
945 events.autoRebuilds = steps(e.autoRebuilds)
946 events.askedSeconds = VideoTime.seconds(e.video.asked)
947 events.sentSeconds = VideoTime.seconds(e.video.sent)
948 if events != QualityPeerEvents() { peer.events = events }
949 // The sharer's recovery steps toward this peer belong with the screen
950 // going out to them, even in a window where it sent nothing.
951 if e.keyframes + e.rebuilds + e.reshares + e.failures + e.damped + e.encoderStalls > 0 {
952 var out = peer.out ?? QualityOutbound()
953 var screen = out.screen ?? QualityOutStream()
954 screen.keyframes = steps(e.keyframes)
955 screen.rebuilds = steps(e.rebuilds)
956 screen.reshares = steps(e.reshares)
957 screen.failures = steps(e.failures)
958 screen.damped = steps(e.damped)
959 screen.encoderStalls = steps(e.encoderStalls)
960 out.screen = screen
961 peer.out = out
962 }
963 if e.reattaches + e.stalls > 0 {
964 var inbound = peer.in ?? QualityInbound()
965 var screen = inbound.screen ?? QualityInVideo()
966 screen.reattaches = steps(e.reattaches)
967 screen.stalls = steps(e.stalls)
968 screen.stallsNoPackets = steps(e.stallsNoPackets)
969 screen.stallsUndecoded = steps(e.stallsUndecoded)
970 inbound.screen = screen
971 peer.in = inbound
972 }
973 }
974
975 private static func steps(_ n: Int) -> Double? { n > 0 ? bound(Double(n), QualityBounds.count) : nil }
976
977 /// What happened during the window: the difference, or the whole count
978 /// when there is nothing to take it from or it went backwards.
979 static func delta(_ now: Double?, _ before: Double?) -> Double? {
980 // A running total below zero (RTCP's packetsLost can be, with
981 // duplicates) is not a count of anything.
982 guard let now, now.isFinite, now >= 0 else { return nil }
983 guard let before, before.isFinite, now >= before else { return now }
984 return now - before
985 }
986
987 /// Finite, not negative, under the ceiling, to a tenth; nil otherwise.
988 static func bound(_ value: Double?, _ ceiling: Double) -> Double? {
989 guard let value, value.isFinite, value >= 0 else { return nil }
990 return (min(value, ceiling) * 10).rounded() / 10
991 }
992
993 private static func kbps(_ bytes: Double?, _ seconds: Double) -> Double? {
994 guard let bytes, seconds > 0 else { return nil }
995 return bound(bytes * 8 / 1000 / seconds, QualityBounds.kbps)
996 }
997
998 private static func out(
999 _ now: QualityCounters.Out, _ before: QualityCounters.Out?, _ seconds: Double, video: Bool
1000 ) -> QualityOutStream {
1001 var s = QualityOutStream()
1002 s.kbps = kbps(delta(now.bytes, before?.bytes), seconds)
1003 s.packets = bound(delta(now.packets, before?.packets), QualityBounds.count)
1004 s.lost = bound(delta(now.lost, before?.lost), QualityBounds.count)
1005 s.rtt = bound(now.rtt, QualityBounds.millis)
1006 s.jitter = bound(now.jitter, QualityBounds.millis)
1007 s.limit = QualityWords.limit(now.limit)
1008 s.width = bound(now.width, QualityBounds.pixels)
1009 s.height = bound(now.height, QualityBounds.pixels)
1010 s.fps = bound(now.fps, QualityBounds.fps)
1011 guard video else { return s }
1012 // §15.29: the reason that held the encoder back longest in the window,
1013 // where the stack keeps the durations — a tie to bandwidth, then cpu,
1014 // then other, then none, the reasons that say most first, and only a
1015 // reason that held for some of it — else the latest reason.
1016 if let durations = now.limitSeconds {
1017 let held = { (reason: String) in delta(durations[reason], before?.limitSeconds?[reason]) }
1018 var longest = 0.0
1019 for reason in ["bandwidth", "cpu", "other", "none"] {
1020 if let d = held(reason), d > longest {
1021 s.limit = reason
1022 longest = d
1023 }
1024 }
1025 s.limitedBandwidthSeconds = bound(held("bandwidth"), QualityBounds.seconds)
1026 s.limitedCpuSeconds = bound(held("cpu"), QualityBounds.seconds)
1027 }
1028 s.encoder = now.encoder
1029 s.codec = now.codec
1030 return s
1031 }
1032
1033 private static func inAudio(
1034 _ now: QualityCounters.InAudio, _ before: QualityCounters.InAudio?, _ seconds: Double
1035 ) -> QualityInAudio {
1036 var a = QualityInAudio()
1037 a.kbps = kbps(delta(now.bytes, before?.bytes), seconds)
1038 a.packets = bound(delta(now.packets, before?.packets), QualityBounds.count)
1039 a.lost = bound(delta(now.lost, before?.lost), QualityBounds.count)
1040 a.jitter = bound(now.jitter, QualityBounds.millis)
1041 a.samples = bound(delta(now.samples, before?.samples), QualityBounds.count)
1042 a.concealed = bound(delta(now.concealed, before?.concealed), QualityBounds.count)
1043 a.inserted = bound(delta(now.inserted, before?.inserted), QualityBounds.count)
1044 a.removed = bound(delta(now.removed, before?.removed), QualityBounds.count)
1045 // jitterBufferDelay is seconds summed over every sample emitted, so the
1046 // window's mean is one delta over the other.
1047 if let delay = delta(now.bufferDelay, before?.bufferDelay),
1048 let emitted = delta(now.emitted, before?.emitted), emitted > 0
1049 {
1050 a.jitterBufferMs = bound(delay / emitted * 1000, QualityBounds.millis)
1051 }
1052 return a
1053 }
1054
1055 private static func inVideo(
1056 _ now: QualityCounters.InVideo, _ before: QualityCounters.InVideo?, _ seconds: Double
1057 ) -> QualityInVideo {
1058 var v = QualityInVideo()
1059 v.kbps = kbps(delta(now.bytes, before?.bytes), seconds)
1060 v.packets = bound(delta(now.packets, before?.packets), QualityBounds.count)
1061 v.lost = bound(delta(now.lost, before?.lost), QualityBounds.count)
1062 v.jitter = bound(now.jitter, QualityBounds.millis)
1063 v.freezes = bound(delta(now.freezes, before?.freezes), QualityBounds.count)
1064 v.freezeSeconds = bound(delta(now.freezeSeconds, before?.freezeSeconds), QualityBounds.seconds)
1065 v.decoded = bound(delta(now.decoded, before?.decoded), QualityBounds.count)
1066 v.dropped = bound(delta(now.dropped, before?.dropped), QualityBounds.count)
1067 v.width = bound(now.width, QualityBounds.pixels)
1068 v.height = bound(now.height, QualityBounds.pixels)
1069 v.fps = bound(now.fps, QualityBounds.fps)
1070 v.decoder = now.decoder
1071 v.codec = now.codec
1072 return v
1073 }
1074}
1075
1076// MARK: - Who is reporting, and on what
1077
1078/// The app, its version and the system's, as the schema allows them.
1079public enum QualityClientInfo {
1080 /// This process: "mac", or "iphone"/"ipad" by idiom.
1081 @MainActor public static func current() -> QualityClient {
1082 let version = self.version(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String)
1083 let os = osVersion(ProcessInfo.processInfo.operatingSystemVersion)
1084 #if os(macOS)
1085 return QualityClient(app: "mac", version: version, os: "macos", osVersion: os)
1086 #else
1087 let pad = UIDevice.current.userInterfaceIdiom == .pad
1088 return QualityClient(app: pad ? "ipad" : "iphone", version: version, os: pad ? "ipados" : "ios", osVersion: os)
1089 #endif
1090 }
1091
1092 /// Digits and dots, or nothing: a version is never free text.
1093 public static func version(_ raw: String?) -> String? {
1094 guard let raw, !raw.isEmpty, raw.count <= 24,
1095 raw.allSatisfy({ $0.isASCII && ($0.isNumber || $0 == ".") }),
1096 raw.first?.isNumber == true, raw.last?.isNumber == true, !raw.contains("..")
1097 else { return nil }
1098 return raw
1099 }
1100
1101 public static func osVersion(_ v: OperatingSystemVersion) -> String {
1102 "\(v.majorVersion).\(v.minorVersion).\(v.patchVersion)"
1103 }
1104}
1105
1106/// A microphone's or speaker's kind, from how it is connected. Never its
1107/// name.
1108public enum DeviceKind {
1109 /// From CoreAudioDevices.transport's words.
1110 public static func mac(transport: String?) -> String {
1111 switch transport {
1112 case nil, "": return "unknown"
1113 case "built-in": return "built-in"
1114 case "bluetooth": return "bluetooth"
1115 case "usb": return "usb"
1116 case "airplay": return "airplay"
1117 case "virtual", "aggregate": return "virtual"
1118 case "continuity": return "continuity"
1119 default: return "other"
1120 }
1121 }
1122
1123 /// From an AVAudioSession port type's raw value (AVAudioSession.Port).
1124 public static func ios(port: String?) -> String {
1125 switch port {
1126 case nil, "": return "none"
1127 case "MicrophoneBuiltIn", "Speaker", "Receiver": return "built-in"
1128 case "BluetoothHFP", "BluetoothA2DPOutput", "BluetoothLEOutput": return "bluetooth"
1129 case "USBAudio": return "usb"
1130 case "Headphones", "MicrophoneWired": return "wired"
1131 case "AirPlay": return "airplay"
1132 case "Virtual": return "virtual"
1133 case "ContinuityMicrophone": return "continuity"
1134 default: return "other"
1135 }
1136 }
1137}
1138
1139/// The automatic reports' switch, in Settings (spec §15.26). On unless
1140/// turned off; "Report a problem" works either way.
1141public enum QualityReporting {
1142 public static let enabledKey = "sendQualityReports"
1143 public static func enabled(_ defaults: UserDefaults = .standard) -> Bool {
1144 defaults.object(forKey: enabledKey) as? Bool ?? true
1145 }
1146 /// The settings line, both platforms.
1147 public static let disclosure = "Calls sends anonymous connection quality reports to help fix call problems."
1148}
1149
1150// MARK: - The automatic report (§15.29)
1151
1152/// What counts as a call struggling, and how often an app may say so:
1153/// protocol/quality.go's rules, which the server enforces on its own and
1154/// the web client holds as well.
1155public enum AutoReportRules {
1156 /// Inbound freezes, this window and the one before it: at least this
1157 /// many in each.
1158 public static let freezes = 3.0
1159 /// The window's highest round trip, this window and the one before it:
1160 /// above this in each, in ms.
1161 public static let rttMillis = 800.0
1162 /// "Reconnecting…" (the call's or a person's) shown for longer than this
1163 /// in one window, in seconds.
1164 public static let reconnectingSeconds = 5.0
1165 public static let perCall = 3
1166 public static let everyMinutes = 10.0
1167 /// AutoTriggers, in the order they are checked.
1168 public static let triggers = ["freezes", "rtt", "reconnecting", "screen"]
1169}
1170
1171/// The rules, read from a window's report. Pure.
1172public enum QualityTrouble {
1173 /// What one window's report says about the call, for the rules.
1174 public struct Facts: Equatable, Sendable {
1175 /// Freezes of everything arriving: cameras and screens, every peer.
1176 public var freezes: Double
1177 /// The highest round trip anything in the report saw, in ms.
1178 public var maxRtt: Double
1179 /// The longest "Reconnecting…" showed, the call's or anyone's.
1180 public var reconnectingSeconds: Double
1181 /// The screen's ladder went past its keyframes toward anyone: a
1182 /// rebuild, a share again, or giving up.
1183 public var screenEscalated: Bool
1184
1185 public init(freezes: Double = 0, maxRtt: Double = 0, reconnectingSeconds: Double = 0, screenEscalated: Bool = false) {
1186 self.freezes = freezes
1187 self.maxRtt = maxRtt
1188 self.reconnectingSeconds = reconnectingSeconds
1189 self.screenEscalated = screenEscalated
1190 }
1191 }
1192
1193 public static func facts(_ report: QualityReport) -> Facts {
1194 var facts = Facts(reconnectingSeconds: report.events?.reconnectingSeconds ?? 0)
1195 for peer in report.peers ?? [] {
1196 facts.freezes += (peer.in?.video?.freezes ?? 0) + (peer.in?.screen?.freezes ?? 0)
1197 let rtts = [peer.rttMax, peer.rtt, peer.out?.audio?.rtt, peer.out?.video?.rtt, peer.out?.screen?.rtt]
1198 facts.maxRtt = max(facts.maxRtt, rtts.compactMap { $0 }.max() ?? 0)
1199 facts.reconnectingSeconds = max(facts.reconnectingSeconds, peer.events?.reconnectingSeconds ?? 0)
1200 if let screen = peer.out?.screen, (screen.rebuilds ?? 0) + (screen.reshares ?? 0) + (screen.failures ?? 0) > 0 {
1201 facts.screenEscalated = true
1202 }
1203 }
1204 return facts
1205 }
1206
1207 /// The first rule that holds, in AutoTriggers' order, or nil. The
1208 /// freezes and the round trip need two windows in a row; a window with
1209 /// nothing before it (the first, or one after reports were off) cannot
1210 /// meet them.
1211 public static func trigger(previous: Facts?, now: Facts) -> String? {
1212 if let previous, previous.freezes >= AutoReportRules.freezes, now.freezes >= AutoReportRules.freezes {
1213 return "freezes"
1214 }
1215 if let previous, previous.maxRtt > AutoReportRules.rttMillis, now.maxRtt > AutoReportRules.rttMillis {
1216 return "rtt"
1217 }
1218 if now.reconnectingSeconds > AutoReportRules.reconnectingSeconds { return "reconnecting" }
1219 if now.screenEscalated { return "screen" }
1220 return nil
1221 }
1222}
1223
1224/// How many automatic reports this participation has sent, and when the
1225/// last went: at most AutoReportRules.perCall, at least everyMinutes apart.
1226public struct AutoReportGate: Equatable, Sendable {
1227 public private(set) var sent = 0
1228 public private(set) var last: Double?
1229
1230 public init() {}
1231
1232 public func allows(at now: Double) -> Bool {
1233 guard sent < AutoReportRules.perCall else { return false }
1234 guard let last else { return true }
1235 return now - last >= AutoReportRules.everyMinutes * 60
1236 }
1237
1238 /// One sent (or tried: one the server refused still counts, so a server
1239 /// saying no is not asked again every window).
1240 public mutating func record(at now: Double) {
1241 sent += 1
1242 last = now
1243 }
1244}
1245
1246/// Whether this window sends the automatic report, and why. Pure.
1247public enum AutoReportDecision {
1248 /// The trigger to send, or nil. Never for the final report, never with
1249 /// quality reports switched off in Settings (`enabled`) or the server's
1250 /// kill switch thrown (`stopped`), and never past the gate. `forced` is
1251 /// the gate's test hook (CALLS_AUTO_REPORT_TEST): a trigger the rules
1252 /// need not have met, for a window the rest of this allows.
1253 public static func trigger(
1254 previous: QualityTrouble.Facts?, now: QualityTrouble.Facts, gate: AutoReportGate, at time: Double,
1255 enabled: Bool, stopped: Bool, final: Bool, forced: String? = nil
1256 ) -> String? {
1257 guard !final, enabled, !stopped, gate.allows(at: time) else { return nil }
1258 if let forced, AutoReportRules.triggers.contains(forced) { return forced }
1259 return QualityTrouble.trigger(previous: previous, now: now)
1260 }
1261}
1262