oficina / meet Public

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

Plain git — no account needed to clone.

Download

Download this file

1import Combine
2import Foundation
3#if os(iOS)
4 import AVFoundation
5 import UIKit
6#else
7 import AppKit
8#endif
9// Go serializes this API with a mutex; Objective-C bindings carry no Sendable annotation.
10@preconcurrency import CallsBridge
11import LiveKitWebRTC
12
13// The Go callback only enqueues. The main actor owns the interface and media;
14// an epoch prevents callbacks from a closed room reaching a later call.
15private final class Events: NSObject, BridgeListenerProtocol {
16 weak var call: Call?
17 let epoch: UUID
18 init(call: Call, epoch: UUID) {
19 self.call = call
20 self.epoch = epoch
21 }
22 func onEvent(_ event: String?) {
23 guard let event, let data = event.data(using: .utf8) else { return }
24 guard let decoded = try? JSONDecoder().decode(WireEvent.self, from: data) else {
25 DispatchQueue.main.async { [weak self] in self?.call?.invalidEvents += 1 }
26 return
27 }
28 DispatchQueue.main.async { [weak self] in
29 guard let self, let call = self.call, call.epoch == self.epoch else { return }
30 call.receive(decoded)
31 }
32 }
33}
34
35@MainActor public final class Call: ObservableObject {
36 @Published public private(set) var state: RoomState? {
37 didSet { arrangement.roster(state) }
38 }
39 /// This viewer's layout, pin and order of people (0.4.0).
40 public let arrangement = CallArrangement()
41 @Published public private(set) var title = "Calls"
42 /// Whether `title` is one someone chose, shown over the call, rather
43 /// than one Calls wrote, which is not (CallTitle).
44 @Published public private(set) var named = false
45 @Published public private(set) var standing = ""
46 @Published public private(set) var status = "Ready to join"
47 @Published public private(set) var remoteTracks: [String: RTCVideoTrack] = [:]
48 /// §5.4: the peers showing a screen here, oldest first, and the screens
49 /// that have arrived. Two things and not one, because the `share`
50 /// message usually beats the media by a renegotiation, and the tile
51 /// carries its caption before there is anything to show in it.
52 @Published public private(set) var screens: [String] = []
53 @Published public private(set) var remoteScreens: [String: RTCVideoTrack] = [:]
54 /// Whether this app is sending a screen, and what the last attempt to
55 /// had to say — which is usually nothing.
56 @Published public private(set) var sharingScreen = false
57 @Published public private(set) var screenNote = ""
58 private var screenPending = false
59 /// How this app's own screen is going out, while it is sharing: the
60 /// slowest connection's, read once a second. See ScreenSendReport.
61 @Published public private(set) var screenReport: ScreenSendReport?
62 /// "Optimise for": what a shared screen gives up first. Remembered, and
63 /// applied at once to a share in progress (see ScreenSendPolicy).
64 @Published public var screenMode: ScreenShareMode = .remembered {
65 didSet {
66 guard screenMode != oldValue else { return }
67 ScreenShareMode.remembered = screenMode
68 built?.screenMode = screenMode
69 }
70 }
71 private var screenReports: [String: ScreenSendReport] = [:]
72 private var screenWatch: Task<Void, Never>?
73 /// The sharer's watchdog (ScreenWatchdog) and what it is doing, for the
74 /// panel's screen line.
75 private var screenWatchdog = ScreenWatchdog()
76 @Published public private(set) var screenWatchStatus = ""
77 /// The panel's second screen line: encoded and sent rates, keyframes,
78 /// and the watchdog (ScreenSendReport.detail).
79 @Published public private(set) var screenDetail = ""
80 /// The quiet notice while someone's view of this app's screen is being
81 /// put right: "Vicky's view of your screen stalled — recovering".
82 @Published public private(set) var screenRecovery = ""
83 /// The receiver's watchdog, and the list last reported as
84 /// `screenStalled` (spec §15.21).
85 private var screenReceiveWatch = ScreenReceiveWatch()
86 private var reportedStalled: [String] = []
87 /// Each arriving screen's statistics at the last look, for the stall
88 /// log's "what moved" and for "Copy call diagnostics".
89 private var screenReceived: [String: ScreenReceiveReport] = [:]
90 /// Where each arriving screen stood when it last moved, so a stall can
91 /// be described against it.
92 private var screenReceivedMoving: [String: ScreenReceiveReport] = [:]
93 private var screenReattaches = 0
94 /// "Reconnecting…", said only for a problem that lasts (spec §15.23):
95 /// the whole call's, and the people whose tiles say it on their own.
96 private var reconnectWatch = ReconnectWatch()
97 @Published public private(set) var reconnecting = false
98 @Published public private(set) var reconnectingPeers: Set<String> = []
99 /// A connection that stops working is mended without anyone asking (spec
100 /// §15.28): each remote peer's recovery, the restarts waiting on a fresh
101 /// `/ice` answer, and the peers whose connection has been failing for a
102 /// minute, which is when "A participant's media could not connect." is
103 /// said (and their tile may say their app is old).
104 private var recovery: [String: ConnectionRecovery] = [:]
105 private var restartsAwaitingICE: Set<String> = []
106 @Published public private(set) var failingPeers: Set<String> = []
107 private var autoRestartsTotal: UInt64 = 0
108 private var autoRebuildsTotal: UInt64 = 0
109 /// Off only for the gate's stand-in for an app from before §15.28.
110 @_spi(Fixtures) public static var autoRecovery = true
111 /// Whether this app says which it is (§15.28); off only for the same
112 /// stand-in. `clientVersion` stands in for a bundle that has none (the
113 /// interop executable).
114 @_spi(Fixtures) public static var sendsClientInfo = true
115 @_spi(Fixtures) public static var clientVersion: String?
116 static let failureWords = "A participant’s media could not connect."
117 /// "<name> is connecting and can't hear you yet" (spec §15.24): the
118 /// watch, and the people it is said for now — on their tiles, and as a
119 /// dot in the mini window when they are not the one it shows.
120 private var connectingWatch = ConnectingWatch()
121 @Published public private(set) var connectingPeers: Set<String> = []
122 /// This app's own half: whose audio path is established (HearingRule),
123 /// per connection generation; whose receiver reports have shown this
124 /// app's audio reaching them; and the list last reported as `hearing`.
125 private var heardFrom: [String: (epoch: Int64, heard: Bool)] = [:]
126 private var ackedBy: [String: Int64] = [:]
127 private var reportedHearing: [String] = []
128 /// Spec §15.30: each sender's adaptive watch, the counters it last read
129 /// them from (per connection generation), when it last looked, and the
130 /// asks last reported.
131 private var adapt: [String: VideoAdapt] = [:]
132 private var adaptCounters: [String: (generation: Int64, counters: QualityCounters)] = [:]
133 private var adaptLookedAt: Double?
134 private var reportedVideo: [String: String] = [:]
135 /// What this app asks each person for, as the tiles show it: peer id to
136 /// level, only those below normal.
137 @Published public private(set) var videoAsks: [String: String] = [:]
138 /// The sender's notice while it lasts: "Sending reduced video to …".
139 @Published public private(set) var videoNotice = ""
140 /// The person's own Video quality (device panel), remembered.
141 @Published public var videoQuality: VideoQualitySetting = .remembered {
142 didSet {
143 guard videoQuality != oldValue else { return }
144 VideoQualitySetting.remembered = videoQuality
145 CallLog.info("video quality: \(videoQuality.rawValue)")
146 applyVideoQuality()
147 }
148 }
149 /// The sender's own watch of this device (thermal state, Calls' CPU),
150 /// and the readings the quality report's host load is taken from.
151 private var localAdapt = VideoAdapt()
152 private var hostSampler = HostLoadSampler()
153 /// The level this device's own trouble holds its camera at, for the gate.
154 @Published public private(set) var ownCameraLevel = VideoLevel.normal
155 /// The watch's clean time before a probe up; the gate shortens it.
156 @_spi(Fixtures) public var adaptUpAfter = VideoAdapt.upAfter
157 /// Quality reports (spec §15.26): the notices tallied over the window,
158 /// the running totals the last report was taken from, the loop that
159 /// sends one every `qualityInterval`, and whether the server has said to
160 /// stop (its kill switch) or the final one has gone.
161 private var qualityTally = QualityEventTally()
162 private var qualityBuilder = QualityReportBuilder()
163 private var qualityWatch: Task<Void, Never>?
164 private var qualityStopped = false
165 private var qualityFinalSent = false
166 /// Thirty seconds, as the ruling has it; the gate shortens it
167 /// (CALLS_QUALITY_INTERVAL, read by the interop harness).
168 @_spi(Fixtures) public static var qualityInterval: Double = 30
169 /// The automatic report (spec §15.29): the last window's facts, for the
170 /// rules that need two in a row; how many this participation has sent
171 /// and when; and the gate's forced trigger, spent by the first window
172 /// that may send one (CALLS_AUTO_REPORT_TEST, read by the interop
173 /// harness, which copies it here per call).
174 private var qualityFacts: QualityTrouble.Facts?
175 private var autoReportGate = AutoReportGate()
176 private var autoReportForced: String?
177 @_spi(Fixtures) public static var autoReportForTest: String?
178 /// "Report a problem" (spec §15.26): the sheet, while it is open.
179 @Published public var problemReport: ProblemReportModel?
180 /// Until when the last call can still be reported: ten minutes after it
181 /// ended, which is as long as the server keeps its report token. The
182 /// closed bridge client is kept that long — its transport and token
183 /// outlive the room — with the call's diagnostics as they were at the end.
184 @Published public private(set) var reportableUntil: Date?
185 private var reportClient: BridgeClient?
186 private var reportDiagnostics = ""
187 static let reportWindow: TimeInterval = 600
188 /// A fixture call answers a report itself, for the UI test of the sheet.
189 private var fixtureReports = false
190 /// The phase the notices are drawn for: the core's, except that its
191 /// `reconnecting` is only said once ReconnectWatch says so, and is said
192 /// for a second after it is over.
193 public var noticePhase: String? {
194 if reconnecting { return "reconnecting" }
195 if state?.phase == "reconnecting" { return "admitted" }
196 return state?.phase
197 }
198 private var screenWatchFrozenUntil = 0.0
199 @Published public private(set) var localTrack: RTCVideoTrack?
200 @Published public private(set) var muted = false
201 @Published public private(set) var cameraOff = false
202 @Published public private(set) var floor = false
203 @Published public private(set) var chat: [String] = []
204 @Published public private(set) var receivedChatCount = 0
205 @Published public private(set) var invitationURL: URL?
206 @Published public private(set) var invitationError = ""
207 @Published public private(set) var loadingInvitation = false
208 /// A brief message over the stage, such as "Invite link copied".
209 @Published public internal(set) var toast: String?
210 var toastSerial = 0
211 /// What the last device change had to say, and usually nothing.
212 @Published public private(set) var deviceNote = ""
213 /// The audio-health readout, once a call has been up long enough for
214 /// one. Nil means no sample yet, which is not the same as healthy.
215 @Published public private(set) var audioHealth: AudioHealth?
216 /// The camera in use. Published rather than read through the capture on
217 /// demand, because a picker bound to a plain computed property never
218 /// learns that a switch finished.
219 @Published public private(set) var currentCamera: String?
220 /// What the camera is doing (see CameraStatus), and a fallback worth
221 /// saying. Nil status for a capture that does not say, and outside a
222 /// call.
223 @Published public private(set) var cameraStatus: CameraStatus?
224 @Published public private(set) var cameraNote = ""
225 /// The working camera in use when it is not the remembered one, which
226 /// the panel offers to remember.
227 @Published public private(set) var cameraToKeep: CameraDevice?
228 /// A real camera, so the panel shows its row even with nothing in it.
229 @Published public private(set) var offersCameras = false
230 /// Audio routing belongs to this call.
231 public let audio = AudioRoutes()
232 /// "Reduce background noise": the neural suppressor in place of WebRTC's
233 /// own. On by default, and remembered.
234 @Published public var reduceNoise: Bool = UserDefaults.standard.object(forKey: Call.reduceNoiseKey) as? Bool ?? true {
235 didSet {
236 UserDefaults.standard.set(reduceNoise, forKey: Call.reduceNoiseKey)
237 guard let built else { return }
238 built.audio.reduceNoise = reduceNoise
239 audioProcessing = built.audio.report()
240 }
241 }
242 static let reduceNoiseKey = "reduceBackgroundNoise"
243 /// Which processing is running on the microphone, for the readout.
244 @Published public private(set) var audioProcessing: ProcessingReport?
245 /// The meters (spec §15.20): your microphone and everyone's sound, in
246 /// objects of their own so a meter moving does not redraw the call.
247 public let levels = AudioLevels()
248 private var levelWatch: Task<Void, Never>?
249 /// What was last reported as `noSoundFrom`, and the queue that reports
250 /// it: the bridge's send is a request, and not for the main thread.
251 private var reportedNoSound: [String] = []
252 private let noSoundQueue = DispatchQueue(label: "calls.no-sound-from")
253 /// Received bytes per person at the last statistics read, and whether
254 /// they had risen: "arriving" for the no-sound rule.
255 private var audioBytes: [String: UInt64] = [:]
256 private var audioArriving: [String: Bool] = [:]
257 /// Some connection is up, and so carrying the microphone to someone
258 /// (every connection is given the track when it is made). Read from the
259 /// peer sampling, five times a second; the microphone warning waits on
260 /// it (MicSample.sending).
261 private var sendingAudio = false
262 /// Connections up, and connections in ICE `failed`, at the last look.
263 private var iceConnectedPeers = 0
264 private var iceFailedPeers = 0
265 /// The loudest remote sound since the gate last asked (sampleStats).
266 private var remotePeakSinceSample: Float = 0
267 private var micPeakSinceSample: Float = 0
268 private var cameraWork: Task<Void, Never>?
269 private var cameraSwitches = 0
270 private let knocks = KnockWatch()
271 fileprivate var epoch = UUID()
272 private var bridge: BridgeClient?
273 private var events: Events?
274 /// The call's media, made by the first join (MediaEngine.make, off the
275 /// main thread) and kept for the next.
276 private var built: MediaEngine?
277 /// The media, made here and now only if something reaches for it
278 /// before any join has — which nothing in the app does.
279 private var media: MediaEngine {
280 if let built { return built }
281 AudioLog.info("call media made on the main thread, before a join")
282 let made = MediaEngine(call: self)
283 built = made
284 return made
285 }
286 /// The audio test's view of this call's microphone (AudioSelfTestModel):
287 /// the capture hook, nil outside a call, and whether WebRTC has opened it.
288 var captureDenoiser: CaptureDenoiser? { bridge == nil ? nil : built?.audio.denoiser }
289 var captureStarted: Bool { bridge != nil && built?.audio.capturing == true }
290
291 /// For "Copy audio diagnostics" in the panel's ⓘ and in Test audio
292 /// during a call: this call's microphone, devices, engine and hook.
293 func audioDiagnosticSections() -> [(String, [String])] {
294 var lines = [
295 "in a call: \(bridge != nil); muted \(muted); microphone track \(bridge != nil && built?.localAudio != nil)",
296 "people here: \(self.state?.peers.count ?? 0)",
297 "microphone meter: \(levels.mic.silent ? "silent" : "step \(levels.mic.step)"), speaking \(levels.mic.speaking), sending from \(levels.mic.source.isEmpty ? "-" : levels.mic.source)",
298 ]
299 if let health = audioHealth { lines.append("audio health: \(health.summary)") }
300 #if os(macOS)
301 let routeLines = audio.diagnostics()
302 #else
303 let routeLines = audio.inputs.map { "input: \($0.name) [\($0.id)]\($0.id == audio.currentInput ? " (current)" : "")" }
304 + ["output: \(audio.outputName)"]
305 #endif
306 var sections: [(String, [String])] = [("Call", lines), ("Devices", routeLines)]
307 if bridge != nil, let built { sections.append(("Audio engine and processing", built.audio.diagnostics())) }
308 return sections
309 }
310
311 public func audioDiagnosticsText() -> String {
312 diagnosticsText { self.name(of: $0) }
313 }
314
315 /// "Copy call diagnostics" as "Report a problem" sends it (spec §15.26):
316 /// everyone in it named "peer abc123", the first six characters of their
317 /// peer id, rather than by name. The server turns those into its tags.
318 /// Device names stay, as the spec says.
319 public func anonymousDiagnosticsText() -> String {
320 diagnosticsText(label: Self.anonymousLabel)
321 }
322
323 nonisolated static func anonymousLabel(_ peer: String) -> String { "peer " + peer.prefix(6) }
324
325 private func diagnosticsText(label: (String) -> String) -> String {
326 AudioDiagnosticsReport.make(
327 context: "a call's details",
328 sections: audioDiagnosticSections() + peopleDiagnosticSections(label: label)
329 + screenDiagnosticSections(label: label))
330 }
331
332 /// Everyone else in the call, as this app sees them: what they report
333 /// about their own media and hearing, and what this app is saying
334 /// about them.
335 private func peopleDiagnosticSections(label: (String) -> String) -> [(String, [String])] {
336 guard let state else { return [] }
337 var lines: [String] = []
338 for person in state.peers where person.peer != state.peer {
339 var facts = ["connection \(person.gen ?? 0)", "app \(person.client ?? "browser or unknown")"]
340 if let r = recovery[person.peer], r.trying { facts.append("recovering, \(r.attempts) attempts") }
341 if let media = person.media {
342 facts.append(media.muted ? "muted" : "unmuted")
343 facts.append(media.cameraOff ? "camera off" : "camera on")
344 if let hearing = media.hearing { facts.append(hearing.contains(state.peer) ? "hears you" : "does not hear you yet") }
345 if media.noSoundFrom?.contains(state.peer) == true { facts.append("hears no sound from you") }
346 if media.audioBlocked == true { facts.append("their browser blocked sound") }
347 } else {
348 facts.append("no media report")
349 }
350 if levels.noSoundFrom.contains(person.peer) { facts.append("no sound from them here") }
351 if reconnectingPeers.contains(person.peer) { facts.append("reconnecting") }
352 if connectingPeers.contains(person.peer) { facts.append("connecting, can't hear you yet") }
353 lines.append("\(label(person.peer)): " + facts.joined(separator: ", "))
354 }
355 return lines.isEmpty ? [] : [("People", lines)]
356 }
357
358 /// The screen's part of "Copy call diagnostics": how it is leaving, what
359 /// the watchdog has done, and whose screens have stalled here.
360 private func screenDiagnosticSections(label name: (String) -> String) -> [(String, [String])] {
361 var lines: [String] = []
362 if sharingScreen {
363 lines.append("Sharing (\(screenMode.rawValue))")
364 for (peer, report) in screenReports.sorted(by: { $0.key < $1.key }) {
365 lines.append("to \(name(peer)): \(report.summary)")
366 lines.append(" frames captured \(report.framesCaptured), encoded \(report.framesEncoded), sent \(report.framesSent), keyframes \(report.keyFramesEncoded), asked for \(report.keyframeRequests), limitation \(report.limitation.isEmpty ? "none" : report.limitation)")
367 }
368 if let capture = media.screenCaptureCounts {
369 lines.append("capture: \(capture.heartbeats ?? 0) reports, \(capture.delivered) frames delivered")
370 }
371 lines.append("watchdog: \(screenWatchdog.status)")
372 } else {
373 lines.append("Not sharing")
374 }
375 if sharingScreen {
376 for peer in (state?.peers ?? []).map(\.peer) where screenWatchdog.escalation(of: peer) != .none {
377 lines.append("recovering \(name(peer))'s view: \(screenWatchdog.escalation(of: peer))")
378 }
379 lines.append(
380 "recoveries: \(screenWatchdog.keyframes) keyframes, \(screenWatchdog.encoderRecoveries) fresh encoders, \(screenWatchdog.reAdds) re-adds, \(screenWatchdog.rebuilds) rebuilds, \(screenWatchdog.reshares) shares again, \(screenWatchdog.failures) given up")
381 }
382 // The receiver's half: every screen arriving here, as its statistics
383 // have it, whether or not it has stalled.
384 for (peer, report) in screenReceived.sorted(by: { $0.key < $1.key }) {
385 lines.append("from \(name(peer)): \(report.summary)")
386 }
387 if !reportedStalled.isEmpty {
388 lines.append("stalled here: " + reportedStalled.map { name($0) }.joined(separator: ", "))
389 }
390 if screenReattaches > 0 { lines.append("pictures attached again here: \(screenReattaches)") }
391 let log = AudioDiagnosticsStore.screen.lines(last: AudioDiagnosticsStore.lineLimit)
392 let connection = AudioDiagnosticsStore.connection.lines(last: 50)
393 return [
394 ("Screen", lines), ("Screen log (last \(AudioDiagnosticsStore.lineLimit) lines)", log.isEmpty ? ["(nothing logged)"] : log),
395 ("Connection log (last 50 lines)", connection.isEmpty ? ["(nothing logged)"] : connection),
396 ]
397 }
398 private var ice: ICEConfig?
399 private var pendingMedia: [Message] = []
400 fileprivate var invalidEvents: UInt64 = 0
401 let playAudio: Bool
402
403 #if os(iOS)
404 let customAudioDevice: RTCAudioDevice?
405 public init(audioDevice: RTCAudioDevice? = nil, playAudio: Bool = true) {
406 customAudioDevice = audioDevice
407 self.playAudio = playAudio
408 }
409 #else
410 let audioInput: AudioInputSource?
411 /// `audioInput` stands in for the microphone (the interop harness).
412 public init(playAudio: Bool = true, audioInput: AudioInputSource? = nil) {
413 self.playAudio = playAudio
414 self.audioInput = audioInput
415 }
416 #endif
417 public func join(origin: String, room: String, cookies: String, capture: VideoCapture? = nil)
418 async throws
419 {
420 let old = bridge
421 bridge = nil
422 close()
423 let joiningEpoch = epoch
424 if let old { await Task.detached { old.leave() }.value }
425 guard epoch == joiningEpoch else { throw CancellationError() }
426 let listener = Events(call: self, epoch: epoch)
427 // §15.28: which app this is, on every request the core makes.
428 if Self.sendsClientInfo {
429 let info = QualityClientInfo.current()
430 if let version = info.version ?? Self.clientVersion { _ = BridgeSetClientInfo(info.app, version) }
431 }
432 var error: NSError?
433 guard let client = BridgeNewClient(origin, room, cookies, listener, &error) else {
434 throw error ?? NSError(domain: "Calls", code: 1)
435 }
436 events = listener
437 bridge = client
438 arrangement.begin(meeting: origin + "/" + room)
439 muted = false
440 cameraOff = false
441 chat = []
442 receivedChatCount = 0
443 title = "Calls"
444 standing = ""
445 // The factory and its audio device module, built on the audio queue
446 // the first time: the call's window is up while it is made.
447 if built == nil {
448 let made = await MediaEngine.make(call: self)
449 if built == nil { built = made }
450 }
451 guard epoch == joiningEpoch, bridge === client else { throw CancellationError() }
452 try await media.prepare(capture: capture)
453 guard epoch == joiningEpoch, bridge === client else { throw CancellationError() }
454 localTrack = media.localVideo
455 cameraChanged()
456 media.ownAudioOnly = videoQuality == .audio
457 reportMedia()
458 media.audio.reduceNoise = reduceNoise
459 audioProcessing = media.audio.report()
460 watchLevels()
461 startQualityWatch()
462 KnockNotice.requestPermission()
463 // Asking Apple at join, once there is a session to register the
464 // answer against. Apple replies on its own schedule, at the app
465 // delegate, and may never reply at all.
466 RemoteKnocks.register()
467 try client.start()
468 }
469 public func close() {
470 epoch = UUID()
471 let old = bridge
472 bridge = nil
473 events = nil
474 built?.close()
475 // This call's microphone and speaker choices end with it (see AudioRoutes).
476 #if os(macOS)
477 audio.reset()
478 #endif
479 cameras = []
480 remoteTracks = [:]
481 screens = []
482 remoteScreens = [:]
483 sharingScreen = false
484 screenNote = ""
485 endScreenWatch()
486 localTrack = nil
487 ice = nil
488 state = nil
489 pendingMedia = []
490 invitationURL = nil
491 invitationError = ""
492 loadingInvitation = false
493 deviceNote = ""
494 audioHealth = nil
495 audioProcessing = nil
496 endLevelWatch()
497 qualityWatch?.cancel()
498 qualityWatch = nil
499 recovery = [:]
500 restartsAwaitingICE = []
501 failingPeers = []
502 currentCamera = nil
503 cameraStatus = nil
504 cameraNote = ""
505 cameraToKeep = nil
506 knocks.reset()
507 cameraSwitches += 1
508 cameraWork?.cancel()
509 cameraWork = nil
510 if let old { DispatchQueue.global().async { old.close() } }
511 }
512 public func leave() async {
513 // The final quality report reads the connections' statistics, so it is
514 // built before they close, and sent beside the leave rather than after
515 // it: quitting gives the two together three seconds.
516 let final = await finalQualityReport()
517 let old = bridge
518 if let old { keepForReports(old) }
519 bridge = nil
520 close()
521 status = "You left the meeting"
522 if let old {
523 await Task.detached {
524 await withTaskGroup(of: Void.self) { group in
525 if let final { group.addTask { _ = old.sendQuality(final) } }
526 group.addTask { old.leave() }
527 }
528 }.value
529 }
530 }
531 public func mute() {
532 muted.toggle()
533 // On the audio queue: switching a track waits out an engine start,
534 // 1,136 ms measured on the main thread with a Bluetooth switch
535 // simulated — and the first thing someone does as they join is often
536 // to mute.
537 let track = media.localAudio
538 let on = !muted
539 AudioWork.post { track?.isEnabled = on }
540 reportMedia()
541 }
542 public func toggleCamera() {
543 cameraOff.toggle()
544 let track = media.localVideo
545 let on = !cameraOff
546 AudioWork.post { track?.isEnabled = on }
547 reportMedia()
548 }
549
550 // ---------------------------------------------------------------
551 // Media state (§15.19)
552 // ---------------------------------------------------------------
553
554 /// Tells the core what this app is sending. The core reports it once
555 /// admitted, again whenever a roster says the server has not got it —
556 /// a resume, a restart — and at once on a change, so this is called on
557 /// each toggle and once the tracks exist, and nowhere else. No track at
558 /// all is muted, or off, as far as anyone listening can tell.
559 private func reportMedia() {
560 // §15.30: Audio only sends no camera to anyone, so it is off.
561 try? bridge?.setMedia(
562 muted || media.localAudio == nil,
563 cameraOff: cameraOff || media.localVideo == nil || videoQuality == .audio)
564 }
565
566 /// A remote peer's reported state, or nil when it has not reported.
567 public func peerMedia(_ peer: String) -> PeerMedia? { Self.peerMedia(peer, in: state) }
568 /// Whether a remote peer has said it is muted. Unknown is not muted.
569 public func isMuted(_ peer: String) -> Bool { peerMedia(peer)?.muted ?? false }
570 /// Whether a remote peer has said its camera is off. Unknown is not off.
571 public func isCameraOff(_ peer: String) -> Bool { peerMedia(peer)?.cameraOff ?? false }
572 /// Spec §15.30: whether this app is asking a peer for less video — the
573 /// tile's "Low bandwidth" badge.
574 public func isLowBandwidth(_ peer: String) -> Bool { videoAsks[peer] != nil }
575 /// Whether a peer's picture is paused to keep their audio clear: this app
576 /// asks them for audio only, and their camera is not off anyway.
577 public func isVideoPaused(_ peer: String) -> Bool { videoAsks[peer] == VideoLevel.audio.wire && !isCameraOff(peer) }
578 /// What a paused tile says: the words, and for an app too old to send
579 /// less, that it is only hidden here.
580 public func videoPausedWords(_ peer: String) -> String {
581 let client = state?.peers.first { $0.peer == peer }?.client
582 return VideoAdapt.honours(client: client)
583 ? VideoAdapt.pausedWords : VideoAdapt.pausedWords + ". " + VideoAdapt.oldAppWords
584 }
585 nonisolated static func peerMedia(_ peer: String, in state: RoomState?) -> PeerMedia? {
586 state?.peers.first { $0.peer == peer }?.media
587 }
588
589 // ---------------------------------------------------------------
590 // Devices
591 // ---------------------------------------------------------------
592
593 /// The cameras available, and the one in use. Read through the running
594 /// capture rather than from AVFoundation directly, so what the picker
595 /// offers is what the call could actually switch to.
596 @Published public private(set) var cameras: [CameraDevice] = []
597
598 public func refreshDevices() {
599 let available = built?.cameras ?? []
600 if cameras != available { cameras = available }
601 if let currentCamera, !available.contains(where: { $0.id == currentCamera }) {
602 self.currentCamera = nil
603 }
604 audio.refresh()
605 }
606
607 /// The capture said something changed on its own: a camera came or
608 /// went, a fallback, the first frame. Everything camera-shaped is read
609 /// back from it.
610 func cameraChanged() {
611 offersCameras = media.offersCameras
612 refreshDevices()
613 let now = media.currentCamera
614 if currentCamera != now { currentCamera = now }
615 let status = media.cameraStatus
616 if cameraStatus != status { cameraStatus = status }
617 let note = media.cameraNote
618 if cameraNote != note { cameraNote = note }
619 let keep = media.cameraToKeep
620 if cameraToKeep != keep { cameraToKeep = keep }
621 }
622
623 /// What your own tile says in place of your picture, or nil to show it.
624 /// Never an open-ended "Waiting for video": it says what it is waiting
625 /// for, or why there is nothing.
626 public var selfPlaceholder: String? {
627 if state?.phase == "ended" { return "Not in the call" }
628 if localTrack == nil { return "Starting camera…" }
629 return cameraStatus?.tileText
630 }
631
632 /// The panel's "Try again", for a call with no working camera.
633 public func retryCamera() async {
634 await media.retryCamera()
635 cameraChanged()
636 }
637
638 /// Switches camera mid-call. Serialised: two picks are two capture
639 /// restarts on one device, and run at once the survivor is whichever
640 /// session happened to open last, which is not the one the person
641 /// chose. The counter decides who wins; the queue decides that only
642 /// one runs.
643 public func useCamera(_ id: String) async {
644 cameraSwitches += 1
645 let mine = cameraSwitches
646 let previous = cameraWork
647 let work = Task { @MainActor [weak self] in
648 await previous?.value
649 guard let self, mine == self.cameraSwitches, !Task.isCancelled else { return }
650 do {
651 try await self.media.use(camera: id)
652 guard mine == self.cameraSwitches, !Task.isCancelled else { return }
653 self.deviceNote = ""
654 } catch is CancellationError {
655 } catch {
656 guard mine == self.cameraSwitches, !Task.isCancelled else { return }
657 self.deviceNote = error.localizedDescription
658 }
659 // Read back rather than assume: a refused switch left the capture
660 // wherever it actually is, and the picker has to follow the camera
661 // and not the intention.
662 guard mine == self.cameraSwitches, !Task.isCancelled else { return }
663 self.cameraChanged()
664 }
665 cameraWork = work
666 await work.value
667 }
668
669 /// Records something a device change had to say. The panel has no
670 /// place of its own to put an error, and a route that would not change
671 /// belongs beside the control that would not change it.
672 public func noteDevice(_ text: String) { deviceNote = text }
673
674 /// Polls the audio-health counters while a call is up.
675 ///
676 /// This exists because of a call on 2026-09-17 that came back as an
677 /// unintelligible growl, and because nothing in this app recorded
678 /// anything about it — no log, no counters, no artefact. A reproduction
679 /// would have produced nothing either. (Until the move to LiveKit's
680 /// WebRTC build it was also the only instrument on macOS, which had no
681 /// way to switch away from a suspect device.)
682 ///
683 /// Five seconds because this is a readout a person glances at when
684 /// something sounds wrong, not a time series.
685 public func watchAudio() async {
686 while !Task.isCancelled {
687 try? await Task.sleep(nanoseconds: 5_000_000_000)
688 guard !Task.isCancelled, bridge != nil else { return }
689 refreshDevices()
690 audioHealth = AudioHealth(await media.stats())
691 media.audio.refresh()
692 audioProcessing = media.audio.report()
693 }
694 }
695 // ---------------------------------------------------------------
696 // Levels (§15.20)
697 // ---------------------------------------------------------------
698
699 /// What a tile shows about its sound: yours, or a remote person's.
700 public var selfAudio: TileAudio { .you(levels.mic) }
701 public func tileAudio(_ peer: String) -> TileAudio {
702 .peer(levels.peer(peer), name: name(of: peer))
703 }
704
705 /// Reads the meters ten times a second while the call is up: your
706 /// microphone every tick, everyone else's every other (5 Hz), and the
707 /// received byte counts once a second. What is published only changes
708 /// when a meter step or a line does (see AudioLevels).
709 private func watchLevels() {
710 levelWatch?.cancel()
711 levels.reset()
712 resetConnecting()
713 reportedNoSound = []
714 audioBytes = [:]
715 audioArriving = [:]
716 levelWatch = Task { @MainActor [weak self] in
717 var tick = 0
718 while !Task.isCancelled {
719 try? await Task.sleep(nanoseconds: 100_000_000)
720 guard let self, !Task.isCancelled, self.bridge != nil else { return }
721 tick += 1
722 let now = ProcessInfo.processInfo.systemUptime
723 self.sampleMic(now: now)
724 if tick % 2 == 0 { await self.samplePeers(stats: tick % 10 == 0, now: now) }
725 if tick % 10 == 5 { await self.watchRemoteScreens(now: now) }
726 if tick % 10 == 7 { await self.watchAdapt(now: now) }
727 }
728 }
729 }
730
731 private func endLevelWatch() {
732 levelWatch?.cancel()
733 levelWatch = nil
734 adapt = [:]
735 adaptCounters = [:]
736 adaptLookedAt = nil
737 localAdapt = VideoAdapt()
738 ownCameraLevel = .normal
739 built?.localLevel = .normal
740 reportedVideo = [:]
741 videoAsks = [:]
742 videoNotice = ""
743 screenReceiveWatch = ScreenReceiveWatch()
744 reportedStalled = []
745 screenReceived = [:]
746 screenReceivedMoving = [:]
747 levels.reset()
748 resetConnecting()
749 reportedNoSound = []
750 audioBytes = [:]
751 audioArriving = [:]
752 sendingAudio = false
753 }
754
755 private func resetConnecting() {
756 connectingWatch = ConnectingWatch()
757 if !connectingPeers.isEmpty { connectingPeers = [] }
758 heardFrom = [:]
759 ackedBy = [:]
760 // The core starts every report with `hearing: []` (spec §15.24).
761 reportedHearing = []
762 }
763
764 private func sampleMic(now: Double) {
765 let denoiser = media.audio.denoiser
766 let sent = denoiser.level.take()
767 let heard = denoiser.inputLevel.take()
768 micPeakSinceSample = max(micPeakSinceSample, sent.peak)
769 #if os(macOS)
770 let source = audio.inputSource
771 let channels = audio.inputChannels.count > 1
772 let capturing = media.audio.capturing
773 #else
774 let source = audio.inputs.first { $0.id == audio.currentInput }?.name ?? ""
775 let channels = false
776 let capturing = media.audio.hookFlowing
777 #endif
778 levels.updateMic(
779 MicSample(
780 muted: muted || media.localAudio == nil, capturing: capturing,
781 inputPeak: heard.peak, inputBuffers: heard.buffers, sentPeak: sent.peak, sending: sendingAudio),
782 now: now, source: source, channels: channels)
783 AudioDiagnosticsStore.shared.record(
784 .init(
785 at: now, input: heard.peak, inputBuffers: heard.buffers, output: sent.peak, outputBuffers: sent.buffers,
786 source: muted ? "call (muted)" : capturing ? "call" : "call (mic not open)"))
787 }
788
789 private func samplePeers(stats: Bool, now: Double) async {
790 // §15.24: the people whose audio path is not established yet are read
791 // closely, five times a second, until it is; the people in their first
792 // moments who do not say who they hear are asked about this app's audio.
793 let mine = state?.peer ?? ""
794 let joining = connectingWatch.joining
795 var detail = Set<String>()
796 var acks = Set<String>()
797 for person in state?.peers ?? [] where person.peer != mine {
798 let epoch = person.gen ?? 0
799 if heardFrom[person.peer].map({ $0.epoch != epoch || !$0.heard }) ?? true { detail.insert(person.peer) }
800 if joining.contains(person.peer), HearingRule.hearsYou(person.media, me: mine) == nil,
801 ackedBy[person.peer] != epoch
802 {
803 acks.insert(person.peer)
804 }
805 }
806 let readings = await media.peerAudio(stats: stats, detail: detail, acks: acks)
807 guard levelWatch != nil, let state else { return }
808 sendingAudio = readings.values.contains { $0.connected }
809 iceConnectedPeers = readings.values.filter(\.connected).count
810 iceFailedPeers = readings.values.filter(\.failed).count
811 let me = state.peer
812 var present = Set<String>()
813 var people: [String: ReconnectWatch.Peer] = [:]
814 var arrivals: [String: ConnectingWatch.Peer] = [:]
815 for person in state.peers where person.peer != me {
816 guard let reading = readings[person.peer] else { continue }
817 present.insert(person.peer)
818 if stats, let bytes = reading.bytes {
819 audioArriving[person.peer] = bytes > (audioBytes[person.peer] ?? 0)
820 audioBytes[person.peer] = bytes
821 }
822 let epoch = person.gen ?? 0
823 var was = heardFrom[person.peer] ?? (epoch, false)
824 if was.epoch != epoch { was = (epoch, false) }
825 let heard = HearingRule.heard(
826 was: was.heard,
827 .init(
828 connected: reading.connected, bad: reading.gone, hasReceiver: reading.hasReceiver,
829 receiverLive: reading.receiverLive, packets: reading.packets ?? 0, decoded: reading.buffers,
830 senderMuted: person.media?.muted == true))
831 heardFrom[person.peer] = (epoch, heard)
832 if reading.acked == true { ackedBy[person.peer] = epoch }
833 arrivals[person.peer] = ConnectingWatch.Peer(
834 epoch: epoch, hearsMe: HearingRule.hearsYou(person.media, me: me), reported: person.media != nil,
835 connected: reading.connected, acked: ackedBy[person.peer] == epoch)
836 }
837 let trying = watchRecovery(now: now, state: state)
838 for id in Array(heardFrom.keys) where !present.contains(id) { heardFrom.removeValue(forKey: id) }
839 for id in Array(ackedBy.keys) where !present.contains(id) { ackedBy.removeValue(forKey: id) }
840 for id in connectingWatch.observe(at: now, people: arrivals) {
841 CallLog.info("\(id.prefix(6)) can hear us")
842 AudioAnnouncer.say(ConnectingWords.canHear(name(of: id)))
843 }
844 let nowJoining = connectingWatch.joining
845 if connectingPeers != connectingWatch.shown { connectingPeers = connectingWatch.shown }
846 for person in state.peers where person.peer != me {
847 guard let reading = readings[person.peer] else { continue }
848 // Someone in their first moments has not lost anything yet: §15.24
849 // speaks for them until it gives up.
850 people[person.peer] =
851 nowJoining.contains(person.peer)
852 ? ReconnectWatch.Peer()
853 : ReconnectWatch.Peer(
854 connectionBad: reading.connectionBad || trying.contains(person.peer),
855 audioMissing: audioArriving[person.peer] == false && person.media?.muted != true)
856 let said = ConnectingWatch.tile(
857 name: person.name, media: person.media, me: me, muted: muted,
858 joining: nowJoining.contains(person.peer), shown: connectingPeers.contains(person.peer),
859 reconnecting: reconnectingPeers.contains(person.peer))
860 remotePeakSinceSample = max(remotePeakSinceSample, reading.peak)
861 // §15.28: and what their app is, when that is worth saying.
862 var notices = said.notices
863 if let old = ClientVersion.notice(
864 name: person.name, client: person.client, failing: failingPeers.contains(person.peer))
865 {
866 notices.append(old)
867 }
868 levels.updatePeer(
869 person.peer, name: person.name,
870 sample: PeerAudioSample(
871 reported: person.media, connected: reading.connected,
872 arriving: audioArriving[person.peer] ?? false, level: reading.peak),
873 notices: notices, connecting: said.connecting,
874 now: now)
875 }
876 watchReconnect(now: now, people: people)
877 observeQuality(now: now, state: state)
878 levels.settle(present: present)
879 for id in Array(audioBytes.keys) where !present.contains(id) {
880 audioBytes.removeValue(forKey: id)
881 audioArriving.removeValue(forKey: id)
882 }
883 reportNoSound(levels.noSoundFrom)
884 reportHearing(heardFrom.filter { $0.value.heard }.keys.sorted(), present: present)
885 }
886
887 /// §15.24: whose audio this app is receiving and playing. Sent only on a
888 /// change, in order, off the main thread, as `noSoundFrom` is.
889 private func reportHearing(_ peers: [String], present: Set<String>) {
890 guard peers != reportedHearing, let client = bridge else { return }
891 let moved = HearingRule.moved(from: reportedHearing, to: peers, present: present)
892 reportedHearing = peers
893 guard moved else { return }
894 let body = json(peers) ?? "[]"
895 noSoundQueue.async { try? client.setHearing(body) }
896 }
897
898 /// One look by ReconnectWatch (spec §15.23), and the words it says.
899 private func watchReconnect(now: Double, people: [String: ReconnectWatch.Peer]) {
900 reconnectWatch.observe(at: now, streamDown: state?.phase == "reconnecting", people: people)
901 if reconnectingPeers != reconnectWatch.peers {
902 for id in reconnectWatch.peers.subtracting(reconnectingPeers) { CallLog.info("reconnecting to \(id.prefix(6)): shown") }
903 reconnectingPeers = reconnectWatch.peers
904 }
905 guard reconnecting != reconnectWatch.call else { return }
906 reconnecting = reconnectWatch.call
907 CallLog.info(reconnecting ? "reconnecting: shown (a problem that lasted)" : "reconnecting: cleared")
908 switch state?.phase {
909 case "reconnecting", "admitted": status = admittedStatus
910 default: break
911 }
912 }
913
914 /// What the status line says while admitted: "Reconnecting…" for the
915 /// whole call (§15.23), the failure notice once a connection has been
916 /// failing for a minute (§15.28), or that all is well.
917 private var admittedStatus: String {
918 if reconnecting { return ReconnectWords.call }
919 if !failingPeers.isEmpty { return Self.failureWords }
920 return "In the meeting"
921 }
922
923 /// One look by every connection's recovery (spec §15.28), and whatever it
924 /// asks for. Returns the peers it is trying to mend now, whose tiles say
925 /// "Reconnecting to …".
926 private func watchRecovery(now: Double, state: RoomState) -> Set<String> {
927 guard Self.autoRecovery else { return [] }
928 let looks = media.recoveryLooks()
929 for id in Array(recovery.keys) where looks[id] == nil {
930 recovery.removeValue(forKey: id)
931 restartsAwaitingICE.remove(id)
932 }
933 let signalling = state.phase == "admitted"
934 var trying: Set<String> = []
935 var failing: Set<String> = []
936 for (id, var look) in looks where id != state.peer {
937 look.signalling = signalling
938 var r = recovery[id] ?? ConnectionRecovery()
939 let was = r.trying
940 let action = r.observe(at: now, look)
941 if r.trying != was {
942 CallLog.info(r.trying ? "recovery: \(id.prefix(6)) in trouble (ICE \(look.ice))" : "recovery: \(id.prefix(6)) recovered")
943 }
944 recovery[id] = r
945 if r.trying { trying.insert(id) }
946 if r.failing(at: now) { failing.insert(id) }
947 switch action {
948 case .restart?: recoveryRestart(id, attempt: r.attempts)
949 case .rebuild?: recoveryRebuild(id, attempt: r.attempts)
950 case nil: break
951 }
952 }
953 if failingPeers != failing {
954 for id in failing.subtracting(failingPeers) { CallLog.info("recovery: \(id.prefix(6)) still failing after a minute: said") }
955 failingPeers = failing
956 if state.phase == "admitted" || state.phase == "reconnecting" { status = admittedStatus }
957 }
958 return trying
959 }
960
961 /// §15.28's restart, after fresh relay credentials when the ones in hand
962 /// are due for renewal (§5.3): a restart onto a credential the relay is
963 /// about to stop honouring would only fail again.
964 private func recoveryRestart(_ peer: String, attempt: Int) {
965 autoRestartsTotal += 1
966 qualityTally.count(.autoRestart, for: peer)
967 if let ice, !ice.iceServers.isEmpty, ice.renewAt > 0, Int64(Date().timeIntervalSince1970) >= ice.renewAt,
968 let client = bridge
969 {
970 CallLog.info("recovery: attempt \(attempt), ICE restart for \(peer.prefix(6)) after fresh relay credentials")
971 restartsAwaitingICE.insert(peer)
972 DispatchQueue.global().async { client.refreshICE() }
973 return
974 }
975 CallLog.info("recovery: attempt \(attempt), ICE restart for \(peer.prefix(6))")
976 media.restartICE(peer)
977 }
978
979 /// §15.28's rebuild: the hub's pair reset (§4.6), which gives both sides
980 /// a new generation and so a new connection, exactly as a leave and a
981 /// join did — for this one person, and keeping the call.
982 private func recoveryRebuild(_ peer: String, attempt: Int) {
983 autoRebuildsTotal += 1
984 qualityTally.count(.autoRebuild, for: peer)
985 CallLog.info("recovery: attempt \(attempt), rebuilding the connection to \(peer.prefix(6))")
986 guard let client = bridge else { return }
987 DispatchQueue.global().async { try? client.send("reset", to: peer, generation: 0, payload: "") }
988 }
989
990 /// §15.20's receiving half: who is reaching this app as silence. The
991 /// core keeps only roster peers and reports on a change; this sends only
992 /// on a change too, in order, off the main thread.
993 private func reportNoSound(_ peers: [String]) {
994 guard peers != reportedNoSound, let client = bridge else { return }
995 reportedNoSound = peers
996 let body = json(peers) ?? "[]"
997 noSoundQueue.async { try? client.setNoSoundFrom(body) }
998 }
999
1000 public func retryJoin() { send(type: "join", to: "", gen: 0, payload: "") }
1001 public func loadInvitation() async {
1002 guard let client = bridge, !loadingInvitation else { return }
1003 let currentEpoch = epoch
1004 invitationURL = nil
1005 invitationError = ""
1006 loadingInvitation = true
1007 defer { if epoch == currentEpoch { loadingInvitation = false } }
1008 do {
1009 let link = try await Task.detached {
1010 var error: NSError?
1011 let value = client.shareLink(&error)
1012 if let error { throw error }
1013 return value
1014 }.value
1015 guard epoch == currentEpoch else { return }
1016 invitationURL = URL(string: link)
1017 } catch {
1018 guard epoch == currentEpoch else { return }
1019 invitationError = "Could not get the invitation. Try again."
1020 }
1021 }
1022 public func admit(_ peer: String) {
1023 send(type: "admit", to: "", gen: 0, payload: json(["peer": peer]) ?? "")
1024 }
1025 @discardableResult public func sendChat(_ text: String) -> Bool {
1026 guard !text.isEmpty else { return false }
1027 guard let payload = json(["text": text]), payload.utf8.count <= 2059 else {
1028 status = "Keep the message within 2 KB."
1029 return false
1030 }
1031 guard let bridge else { return false }
1032 do {
1033 try bridge.send("chat", to: "", generation: 0, payload: payload)
1034 return true
1035 } catch {
1036 status = "Could not send the message. Try again."
1037 return false
1038 }
1039 }
1040 func send(type: String, to: String, gen: Int64, payload: String) {
1041 do { try bridge?.send(type, to: to, generation: gen, payload: payload) } catch {
1042 status = "Could not send to the meeting. Try again."
1043 }
1044 }
1045 fileprivate func receive(_ event: WireEvent) {
1046 switch event.type {
1047 case "sent", "send-failed":
1048 guard let message = event.signal, message.type == "chat",
1049 let text = message.payload?.text
1050 else { return }
1051 appendChat("\(event.type == "sent" ? "You" : "Not sent"): \(text)")
1052 case "info":
1053 if let info = event.info {
1054 title = info.title
1055 named = info.named ?? false
1056 standing = info.standing
1057 floor = info.floor
1058 }
1059 case "state":
1060 guard let state = event.state else { return }
1061 self.state = state
1062 // Only a member is sent a waiting list at all (spec §4.3), so this
1063 // needs no check of its own for who is allowed to be told.
1064 KnockNotice.announce(
1065 knocks.arrivals(waiting: state.waiting, visible: KnockNotice.appIsFrontmost))
1066 switch state.phase {
1067 case "admitted": status = admittedStatus
1068 case "waiting": status = "Waiting to be let in"
1069 case "full": status = "The meeting is full. Try joining again shortly."
1070 // Said only once it has lasted (ReconnectWatch, spec §15.23): a
1071 // stream renewal is a reconnect of half a second nobody should see.
1072 case "reconnecting": if reconnecting { status = ReconnectWords.call }
1073 case "ended":
1074 status =
1075 [
1076 "left": "You left the meeting", "ended": "This meeting has ended",
1077 "replaced": "This meeting is open elsewhere",
1078 "removed": "You were removed from this meeting",
1079 "standing": "You no longer have access", "expired": "Your invitation has expired",
1080 "signin": "Sign in again to join", "unavailable": "This meeting is unavailable",
1081 ][state.reason ?? ""] ?? "The call has ended"
1082 endedForReports()
1083 media.close()
1084 remoteTracks = [:]
1085 screens = []
1086 remoteScreens = [:]
1087 sharingScreen = false
1088 endScreenWatch()
1089 endLevelWatch()
1090 localTrack = nil
1091 cameraChanged()
1092 default: status = "Connecting…"
1093 }
1094 if state.peer.isEmpty {
1095 media.closePeers()
1096 remoteTracks = [:]
1097 screens = []
1098 remoteScreens = [:]
1099 ice = nil
1100 }
1101 if let ice { media.reconcile(state: state, ice: ice) }
1102 // §15.30: and what each of them asks of us now.
1103 answerVideoAsks(state)
1104 case "ice":
1105 guard let config = event.ice else { return }
1106 let renewing = ice != nil
1107 ice = config
1108 floor = config.iceServers.isEmpty
1109 if let state { media.reconcile(state: state, ice: config) }
1110 if renewing {
1111 // §15.28: recovery restarts that waited for this answer go now, on
1112 // whichever connections the renewal itself did not restart.
1113 let restarted = media.updateICE(config)
1114 for peer in restartsAwaitingICE.subtracting(restarted) { media.restartICE(peer) }
1115 restartsAwaitingICE = []
1116 }
1117 let pending = pendingMedia
1118 pendingMedia = []
1119 for message in pending { media.receive(message) }
1120 case "ice-unavailable":
1121 status = "Could not refresh the call connection. Retrying…"
1122 // The restarts that waited for it go on what is in hand.
1123 for peer in restartsAwaitingICE { media.restartICE(peer) }
1124 restartsAwaitingICE = []
1125 case "message":
1126 guard let message = event.message else { return }
1127 if message.type == "chat", let text = message.payload?.text {
1128 appendChat("\(message.name ?? "Participant"): \(text)")
1129 receivedChatCount += 1
1130 }
1131 if message.type == "share" {
1132 media.receiveShare(message)
1133 return
1134 }
1135 if ice == nil, ["offer", "answer", "candidate"].contains(message.type) {
1136 if pendingMedia.count < 256 { pendingMedia.append(message) }
1137 } else {
1138 media.receive(message)
1139 }
1140 default: break
1141 }
1142 }
1143 private func appendChat(_ line: String) {
1144 chat.append(line)
1145 if chat.count > 200 { chat.removeFirst(chat.count - 200) }
1146 }
1147 func setRemote(_ track: RTCVideoTrack, peer: String) { remoteTracks[peer] = track }
1148 func removeRemote(_ peer: String) {
1149 remoteTracks.removeValue(forKey: peer)
1150 dropScreen(peer)
1151 }
1152
1153 // ---------------------------------------------------------------
1154 // Screens (§5.4)
1155 // ---------------------------------------------------------------
1156
1157 /// The name the roster gives a peer, which is the only place a name
1158 /// comes from: the hub put it there, and nothing a peer sends can.
1159 public func name(of peer: String) -> String {
1160 state?.peers.first { $0.peer == peer }?.name ?? "Participant"
1161 }
1162
1163 /// Shares a screen (§5.4): the capture asks the person what to share,
1164 /// every connection gets it on a transceiver of its own, and then the
1165 /// room is told — the label, not the media, so peers can caption the
1166 /// tile before the renegotiation lands.
1167 ///
1168 /// A refusal at the picker says one sentence, the browser's, and does
1169 /// not diagnose which kind of refusal it was.
1170 public func shareScreen(_ capture: ScreenCapture) async {
1171 // The picker stays open for as long as a person takes to answer it,
1172 // and the button is live the whole time. Without this a second press
1173 // starts a second capture that nothing would ever stop.
1174 guard bridge != nil, !sharingScreen, !screenPending else { return }
1175 screenPending = true
1176 defer { screenPending = false }
1177 let joined = epoch
1178 screenNote = ""
1179 media.screenMode = screenMode
1180 do {
1181 try await media.startScreen(capture) { [weak self] in
1182 // The capture ended on its own: the system's stop control, or
1183 // the shared window closing. The same ending as the button.
1184 guard let self, self.epoch == joined else { return }
1185 self.stopSharingScreen()
1186 }
1187 } catch is CancellationError {
1188 return
1189 } catch {
1190 guard epoch == joined else { return }
1191 screenNote = "Screen sharing was not allowed."
1192 return
1193 }
1194 guard epoch == joined, bridge != nil else {
1195 media.stopScreen()
1196 return
1197 }
1198 sharingScreen = true
1199 screenWatchdog.reset()
1200 ScreenLog.info("sharing started (\(screenMode.rawValue))")
1201 send(type: "share", to: "", gen: 0, payload: json(["on": true]) ?? "")
1202 watchScreen()
1203 }
1204
1205 /// Reads the screen's outbound statistics once a second while sharing,
1206 /// for the device panel's line and the gate.
1207 private func watchScreen() {
1208 screenWatch?.cancel()
1209 screenWatch = Task { @MainActor [weak self] in
1210 while !Task.isCancelled {
1211 try? await Task.sleep(nanoseconds: 1_000_000_000)
1212 guard let self, !Task.isCancelled, self.sharingScreen else { return }
1213 let fresh = await self.media.screenReports()
1214 guard !Task.isCancelled, self.sharingScreen else { return }
1215 var measured: [String: ScreenSendReport] = [:]
1216 for (peer, report) in fresh {
1217 measured[peer] = report.measured(since: self.screenReports[peer])
1218 }
1219 let previous = self.screenReports
1220 self.screenReports = measured
1221 let worst = ScreenSendReport.worst(Array(measured.values))
1222 self.screenReport = worst
1223 // Motion mode scales from the source's own size, which only the
1224 // statistics know (a window can be any shape, and re-picked).
1225 if let worst { self.media.screenSource(width: worst.sourceWidth, height: worst.sourceHeight) }
1226 await self.runScreenWatchdog(measured, previous: previous)
1227 }
1228 }
1229 }
1230
1231 /// Off only for the gate's measurement of what happens without it.
1232 @_spi(Fixtures) public static var screenWatchdogEnabled = true
1233
1234 /// One look by the sharer's watchdog, and whatever it asks for.
1235 private func runScreenWatchdog(
1236 _ reports: [String: ScreenSendReport], previous previousReports: [String: ScreenSendReport]
1237 ) async {
1238 guard sharingScreen, let capture = media.screenCaptureCounts else { return }
1239 let me = state?.peer ?? ""
1240 let stalledBy = Set(
1241 (state?.peers ?? []).filter { $0.peer != me && ($0.media?.screenStalled ?? []).contains(me) }.map(\.peer))
1242 let sending = reports.mapValues {
1243 ScreenSendCounts(
1244 encoded: $0.framesEncoded, sent: $0.framesSent, keyframes: $0.keyFramesEncoded,
1245 bandwidthLimited: ScreenWatchdog.linkLimited(limitation: $0.limitation, targetBitrate: $0.targetBitrate))
1246 }
1247 let failuresBefore = screenWatchdog.failures
1248 var actions = screenWatchdog.observe(
1249 at: ProcessInfo.processInfo.systemUptime, capture: capture, sending: sending, stalledBy: stalledBy)
1250 if !Self.screenWatchdogEnabled { actions = [] }
1251 countScreenSteps(actions, failed: screenWatchdog.failures - failuresBefore, stalledBy: stalledBy)
1252 for action in actions {
1253 switch action {
1254 case .restartCapture:
1255 ScreenLog.info("restarting the capture")
1256 let ok = await media.restartScreenCapture()
1257 if !ok { ScreenLog.error("the capture could not be restarted") }
1258 case .keyframe(let peer):
1259 ScreenLog.info("keyframe for \(ScreenWatchdog.short(peer))")
1260 media.forceScreenKeyframe(peer)
1261 case .recreateEncoder(let peer):
1262 ScreenLog.info("fresh encoder for \(ScreenWatchdog.short(peer))")
1263 media.recreateScreenEncoder(peer)
1264 case .reAdd(let peer):
1265 ScreenLog.info("screen re-added for \(ScreenWatchdog.short(peer))")
1266 media.reAddScreen(peer)
1267 sayShareAgain()
1268 case .rebuild(let peer):
1269 ScreenLog.info("screen rebuilt for \(ScreenWatchdog.short(peer)): new transceiver, same size and mode")
1270 media.reAddScreen(peer)
1271 sayShareAgain()
1272 case .reshare:
1273 ScreenLog.info("sharing again for everyone, from the same capture")
1274 await media.reshareScreen()
1275 sayShareAgain()
1276 }
1277 }
1278 screenWatchStatus = screenWatchdog.status
1279 if let (peer, worst) = reports.min(by: { $0.value.framesPerSecond < $1.value.framesPerSecond }) {
1280 screenDetail = worst.detail(since: previousReports[peer], watchdog: screenWatchdog.status)
1281 }
1282 var recovering: [String] = []
1283 var restarting: [String] = []
1284 var failed: [String] = []
1285 for peer in stalledBy.sorted(by: { name(of: $0) < name(of: $1) }) {
1286 switch screenWatchdog.escalation(of: peer) {
1287 case .rebuilt, .reshared: restarting.append(name(of: peer))
1288 case .failed: failed.append(name(of: peer))
1289 case .none, .keyframes: recovering.append(name(of: peer))
1290 }
1291 }
1292 screenRecovery = ScreenWords.notice(recovering: recovering, restarting: restarting, failed: failed)
1293 }
1294
1295 /// A new transceiver's track arrives unlabelled; say it again.
1296 private func sayShareAgain() {
1297 Task { @MainActor [weak self] in
1298 try? await Task.sleep(nanoseconds: 2_000_000_000)
1299 guard let self, self.sharingScreen else { return }
1300 self.send(type: "share", to: "", gen: 0, payload: json(["on": true]) ?? "")
1301 }
1302 }
1303 private func endScreenWatch() {
1304 screenWatch?.cancel()
1305 screenWatch = nil
1306 screenReports = [:]
1307 screenReport = nil
1308 screenWatchdog.reset()
1309 screenWatchStatus = ""
1310 screenRecovery = ""
1311 screenDetail = ""
1312 }
1313
1314 /// The receiver's watchdog, once a second from the level watch: whose
1315 /// screens have stopped moving here, reported as `screenStalled` when
1316 /// that changes (spec §15.21), each stall logged with what the
1317 /// statistics say is still arriving, and the picture attached again
1318 /// four seconds in (spec §15.22).
1319 private func watchRemoteScreens(now: Double) async {
1320 var stalled: [String] = []
1321 if !screens.isEmpty {
1322 let reports = await media.remoteScreenReports()
1323 var frames = reports.mapValues(\.framesDecoded)
1324 // The gate's frozen picture: the counts held where they were.
1325 if now < screenWatchFrozenUntil { frames = frames.mapValues { _ in 0 } }
1326 let sharing = Set(screens)
1327 let before = screenReceived
1328 screenReceived = reports.filter { sharing.contains($0.key) }
1329 stalled = screenReceiveWatch.observe(at: now, decoded: frames.filter { sharing.contains($0.key) })
1330 for (peer, report) in screenReceived where !stalled.contains(peer) {
1331 if before[peer].map({ $0.framesDecoded != report.framesDecoded || $0.mid != report.mid }) ?? true {
1332 screenReceivedMoving[peer] = report
1333 }
1334 }
1335 for peer in stalled where !reportedStalled.contains(peer) {
1336 let report = screenReceived[peer] ?? ScreenReceiveReport()
1337 let moving = screenReceivedMoving[peer]
1338 ScreenLog.info(
1339 "screen from \(ScreenWatchdog.short(peer)) stalled here: reporting it; since it last moved \(report.moved(since: moving)) — \(report.diagnosis(since: moving))")
1340 ScreenLog.info("screen from \(ScreenWatchdog.short(peer)): \(report.summary)")
1341 let verdict = report.diagnosis(since: moving)
1342 qualityTally.count(
1343 .stall(arriving: !verdict.hasPrefix("no packets"), decoding: !verdict.contains("arriving")), for: peer)
1344 }
1345 for peer in screenReceiveWatch.reattach {
1346 let report = screenReceived[peer] ?? ScreenReceiveReport()
1347 ScreenLog.info(
1348 "screen from \(ScreenWatchdog.short(peer)) still stalled: attaching its picture again; \(report.moved(since: screenReceivedMoving[peer]))")
1349 reattachScreen(peer)
1350 }
1351 } else {
1352 screenReceiveWatch = ScreenReceiveWatch()
1353 screenReceived = [:]
1354 screenReceivedMoving = [:]
1355 }
1356 guard stalled != reportedStalled, let client = bridge else { return }
1357 for peer in reportedStalled where !stalled.contains(peer) {
1358 let report = screenReceived[peer]
1359 ScreenLog.info(
1360 "screen from \(ScreenWatchdog.short(peer)) moving here again\(report.map { ": " + $0.summary } ?? "")")
1361 }
1362 reportedStalled = stalled
1363 let body = json(stalled) ?? "[]"
1364 noSoundQueue.async { try? client.setScreenStalled(body) }
1365 }
1366
1367 /// A stalled screen's picture dropped and attached again: a new renderer
1368 /// on the same track, for a picture stopped on this side.
1369 private func reattachScreen(_ peer: String) {
1370 guard let track = remoteScreens[peer] else { return }
1371 screenReattaches += 1
1372 qualityTally.count(.reattach, for: peer)
1373 remoteScreens.removeValue(forKey: peer)
1374 Task { @MainActor [weak self] in
1375 try? await Task.sleep(nanoseconds: 150_000_000)
1376 guard let self, self.screens.contains(peer), self.remoteScreens[peer] == nil else { return }
1377 self.remoteScreens[peer] = track
1378 }
1379 }
1380
1381 /// Stops sharing, from every way out: the button, the system's own stop
1382 /// control, and the capture ending under us.
1383 public func stopSharingScreen() {
1384 guard sharingScreen else { return }
1385 sharingScreen = false
1386 ScreenLog.info("sharing stopped")
1387 endScreenWatch()
1388 // What was never built has no screen to stop.
1389 built?.stopScreen()
1390 send(type: "share", to: "", gen: 0, payload: json(["on": false]) ?? "")
1391 }
1392
1393 /// A peer has said it is sharing, or its screen has arrived. Either one
1394 /// is enough to draw the tile.
1395 func announceScreen(_ peer: String) {
1396 if !screens.contains(peer) { screens.append(peer) }
1397 }
1398 func setScreen(_ track: RTCVideoTrack, peer: String) {
1399 announceScreen(peer)
1400 remoteScreens[peer] = track
1401 }
1402 /// Both of §5.4's endings meet here — the `share {on:false}` message
1403 /// and the receiver going away with its stopped transceiver — and
1404 /// whichever comes first wins. The second finds nothing to do.
1405 func dropScreen(_ peer: String) {
1406 screens.removeAll { $0 == peer }
1407 remoteScreens.removeValue(forKey: peer)
1408 }
1409 /// Caps the call's uplink estimate at `bps` (nil lifts it): the gate's
1410 /// stand-in for a thin connection, which it has no other way to get.
1411 public func limitUplink(_ bps: Int?) { media.limitUplink(bps) }
1412 /// For the gate: this app's receiver watch sees every screen frozen for
1413 /// `seconds`, so its stall report and the sharer's answer can be driven
1414 /// end to end.
1415 @_spi(Fixtures) public func freezeScreenWatchForTest(seconds: Double) {
1416 screenWatchFrozenUntil = ProcessInfo.processInfo.systemUptime + seconds
1417 }
1418 /// For the gate: every ICE candidate this app sends or receives leads
1419 /// nowhere for `ms` (ICETestBlock), so its connections fail.
1420 @_spi(Fixtures) public func blockICEForTest(ms: Double) {
1421 ICETestBlock.until = ProcessInfo.processInfo.systemUptime + max(0, ms) / 1000
1422 }
1423 /// For the gate's encoder stall (see MediaEngine).
1424 @_spi(Fixtures) public func stallScreenEncoderForTest() { media.stallScreenEncoderForTest() }
1425 /// For the gate: the watchdog's share again (spec §15.22), on demand.
1426 @_spi(Fixtures) public func reshareScreenForTest() async {
1427 guard sharingScreen else { return }
1428 ScreenLog.info("sharing again for everyone, from the same capture (asked for by the gate)")
1429 await media.reshareScreen()
1430 sayShareAgain()
1431 }
1432 public func sampleStats() async -> [String: UInt64] {
1433 var values = await media.stats()
1434 values["hasICE"] = ice == nil ? 0 : 1
1435 values["remoteTracks"] = UInt64(remoteTracks.count)
1436 values["remoteScreens"] = UInt64(remoteScreens.count)
1437 values["screens"] = UInt64(screens.count)
1438 values["invalidEvents"] = invalidEvents
1439 // §15.24: people still in their first moments, people whose tiles say
1440 // they cannot hear you yet, and how many this app reports it hears.
1441 values["connectingJoining"] = UInt64(connectingWatch.joining.count)
1442 values["connectingShown"] = UInt64(connectingPeers.count)
1443 // §15.30: the level this device's own trouble holds its camera at.
1444 values["ownCameraLevel"] = UInt64(ownCameraLevel.rawValue)
1445 values["hearing"] = UInt64(reportedHearing.count)
1446 // This app's own screen, as it leaves: the slowest connection's.
1447 if let screen = screenReport {
1448 values["screenSendWidth"] = UInt64(screen.width)
1449 values["screenSendHeight"] = UInt64(screen.height)
1450 values["screenSendFpsTenths"] = UInt64((screen.framesPerSecond * 10).rounded())
1451 values["screenCapturedFpsTenths"] = UInt64((screen.capturedPerSecond * 10).rounded())
1452 values["screenFramesSent"] = screen.framesSent
1453 values["screenFramesEncoded"] = screen.framesEncoded
1454 values["screenFramesCaptured"] = screen.framesCaptured
1455 values["screenLimitation"] = screen.limitationCode
1456 values["screenLimitedBandwidthMs"] = UInt64(((screen.limitationSeconds["bandwidth"] ?? 0) * 1000).rounded())
1457 values["screenLimitedCpuMs"] = UInt64(((screen.limitationSeconds["cpu"] ?? 0) * 1000).rounded())
1458 values["screenTargetBitrate"] = screen.targetBitrate
1459 values["screenSentBitrate"] = screen.sentBitrate
1460 values["screenEncodeMsTenths"] = UInt64((screen.encodeMsPerFrame * 10).rounded())
1461 values["screenHardwareEncoder"] = screen.hardwareEncoder ? 1 : 0
1462 values["screenCodecH264"] = screen.codec.lowercased().hasSuffix("h264") ? 1 : 0
1463 values["screenPath"] = screen.pathCode
1464 values["screenRttMs"] = UInt64((screen.roundTripTime * 1000).rounded())
1465 values["screenPacketsLost"] = UInt64(max(0, screen.packetsLost))
1466 }
1467 // The screen watchdogs (ScreenWatchdog): what the sharer's has done,
1468 // how many stall reports it has heard, and whose screens this app has
1469 // reported stalled.
1470 values["screenWatchdogCaptureRestarts"] = UInt64(screenWatchdog.captureRestarts)
1471 values["screenWatchdogKeyframes"] = UInt64(screenWatchdog.keyframes)
1472 values["screenWatchdogEncoderRecoveries"] = UInt64(screenWatchdog.encoderRecoveries)
1473 values["screenWatchdogReAdds"] = UInt64(screenWatchdog.reAdds)
1474 values["screenStallReports"] = UInt64(screenWatchdog.stallReports)
1475 values["screenStalledHere"] = UInt64(reportedStalled.count)
1476 values["screenWatchdogRebuilds"] = UInt64(screenWatchdog.rebuilds)
1477 values["screenWatchdogReshares"] = UInt64(screenWatchdog.reshares)
1478 values["screenWatchdogFailures"] = UInt64(screenWatchdog.failures)
1479 values["screenReattaches"] = UInt64(screenReattaches)
1480 values["iceRestarts"] = media.iceRestarts
1481 // Connections up, and connections ICE has given up on, at the last
1482 // look; and the gate's own ICE block (ICETestBlock).
1483 values["iceConnectedPeers"] = UInt64(iceConnectedPeers)
1484 values["iceFailedPeers"] = UInt64(iceFailedPeers)
1485 values["iceBlockMangled"] = ICETestBlock.mangled
1486 // §15.28: the recovery's restarts and rebuilds so far, and the people
1487 // it is trying to mend now, and has been for a minute.
1488 values["autoRestarts"] = autoRestartsTotal
1489 values["autoRebuilds"] = autoRebuildsTotal
1490 values["recoveryTrying"] = UInt64(recovery.values.filter(\.trying).count)
1491 values["recoveryFailing"] = UInt64(failingPeers.count)
1492 values["screenKeyframes"] = screenReport?.keyFramesEncoded ?? 0
1493 if let capture = media.screenCaptureCounts {
1494 values["screenCaptureHeartbeats"] = capture.heartbeats ?? 0
1495 values["screenCaptureDelivered"] = capture.delivered
1496 }
1497 values["rosterPeers"] = UInt64(state?.peers.count ?? 0)
1498 values["noiseFramesProcessed"] = media.audio.denoiser.framesProcessed
1499 values["noiseSuppressor"] = media.audio.denoiser.engineName == "RNNoise" ? 1 : 2
1500 if case .running(_, let cpu) = media.audio.denoiser.state {
1501 values["noiseCpuPermille"] = UInt64((cpu * 1000).rounded())
1502 }
1503 // What WebRTC reports running, not what was asked of it.
1504 let running = media.audio.report()
1505 values["webrtcEchoCancellation"] = running.echoCancellation == "off" ? 0 : 1
1506 values["webrtcNoiseSuppression"] = running.noiseSuppression == "off" ? 0 : 1
1507 values["webrtcGainControl"] = running.gainControl.hasPrefix("Calls") || running.gainControl == "off" ? 0 : 1
1508 // Whether the readout would say the microphone has started.
1509 values["audioReadoutStarted"] = running.started ? 1 : 0
1510 // §15.20's meters, as the tiles see them: the loudest remote sound and
1511 // the loudest sent sound since the last sample, in thousandths of full
1512 // scale; who is in "No sound from"; and whether your own tile says
1513 // the microphone is picking nothing up.
1514 values["remoteAudioPeakPermille"] = UInt64((remotePeakSinceSample * 1000).rounded())
1515 values["micPeakPermille"] = UInt64((micPeakSinceSample * 1000).rounded())
1516 remotePeakSinceSample = 0
1517 micPeakSinceSample = 0
1518 values["noSoundFrom"] = UInt64(levels.noSoundFrom.count)
1519 values["micSilent"] = levels.mic.silent ? 1 : 0
1520 // The speaking glow behind your own name (0.3.7): lit while what is
1521 // sent is speech that has kept up.
1522 values["micGlow"] = levels.mic.glow.glow.lit ? 1 : 0
1523 return values
1524 }
1525}
1526
1527// ---------------------------------------------------------------
1528// Adaptive video (§15.30)
1529// ---------------------------------------------------------------
1530
1531extension Call {
1532 /// One look by every sender's watch, once a second from the level watch:
1533 /// the quality report's own reading of each connection, the second since
1534 /// the last, a step of that sender's watch; then the asks this app makes,
1535 /// reported on a change; and the seconds at each level, asked and sent,
1536 /// for the next quality report.
1537 fileprivate func watchAdapt(now: Double) async {
1538 guard let state, state.phase == "admitted" || state.phase == "reconnecting" else { return }
1539 let samples = await media.qualitySamples()
1540 guard levelWatch != nil, let current = self.state else { return }
1541 let dt = adaptLookedAt.map { min(max(now - $0, 0), 2) } ?? 0
1542 adaptLookedAt = now
1543 #if os(macOS)
1544 let watching = NSApplication.shared.isActive || !NSApplication.shared.isHidden
1545 #else
1546 let watching = UIApplication.shared.applicationState == .active
1547 #endif
1548 let negotiated = media.negotiatedAt
1549 for (id, sample) in samples where id != current.peer {
1550 let counters = QualityCounters(sample)
1551 let before = adaptCounters[id].flatMap { $0.generation == sample.generation ? $0.counters : nil }
1552 adaptCounters[id] = (sample.generation, counters)
1553 guard let before else { continue }
1554 var watch = adapt[id] ?? VideoAdapt(upAfter: adaptUpAfter)
1555 let was = watch.level
1556 let cameraWatched = watching && !isCameraOff(id)
1557 // A renegotiation costs the camera a freeze or two that are not the
1558 // link's: no news while it settles.
1559 let settling = now - (negotiated[id] ?? 0) < VideoAdapt.settle
1560 watch.observe(at: now, settling ? nil : VideoAdapt.sample(counters, before, cameraWatched: cameraWatched))
1561 adapt[id] = watch
1562 if watch.level != was {
1563 CallLog.info("video from \(id.prefix(6)): \(was.wire) -> \(watch.level.wire)\(watch.level < was ? " (probe)" : "")")
1564 }
1565 }
1566 for id in Array(adapt.keys) where samples[id] == nil { adapt.removeValue(forKey: id) }
1567 for id in Array(adaptCounters.keys) where samples[id] == nil { adaptCounters.removeValue(forKey: id) }
1568 reportVideo()
1569 answerVideoAsks(current)
1570 // The sender's own half: this device struggling lowers its camera.
1571 #if os(macOS)
1572 let mac = true
1573 #else
1574 let mac = false
1575 #endif
1576 let reading = HostLoadSampler.Reading.now(at: now)
1577 let cpu = hostSampler.tick(reading)
1578 let wasOwn = localAdapt.level
1579 localAdapt.observe(
1580 at: now, VideoAdapt.loadSample(struggling: VideoAdapt.struggling(thermal: reading.thermal, cpuPct: cpu, mac: mac)))
1581 if localAdapt.level != wasOwn {
1582 CallLog.info(
1583 "own camera: \(wasOwn.wire) -> \(localAdapt.level.wire) (thermal \(HostLoadSampler.word(reading.thermal)), CPU \(Int(cpu ?? 0))%)")
1584 media.localLevel = localAdapt.level
1585 ownCameraLevel = localAdapt.level
1586 }
1587 let sent = media.sentLevels
1588 qualityTally.videoSetting = videoQuality
1589 for id in samples.keys where id != current.peer {
1590 let asked = videoAsks[id].flatMap(VideoLevel.init(wire:)) ?? .normal
1591 qualityTally.video(asked: asked, sent: sent[id] ?? .normal, seconds: dt, for: id)
1592 }
1593 }
1594
1595 /// The asks, from every watch's level and the person's own setting,
1596 /// reported when they change (off the main thread, as the lists are).
1597 fileprivate func reportVideo() {
1598 let levels = adapt.mapValues(\.level).merging(
1599 Dictionary(uniqueKeysWithValues: media.sentLevels.keys.map { ($0, VideoLevel.normal) })
1600 ) { a, _ in a }
1601 let asks = VideoAdapt.asks(levels, setting: videoQuality)
1602 if videoAsks != asks { videoAsks = asks }
1603 guard asks != reportedVideo, let client = bridge else { return }
1604 reportedVideo = asks
1605 let body = json(asks) ?? "{}"
1606 noSoundQueue.async { try? client.setVideo(body) }
1607 }
1608
1609 /// The sender's half: each connection's senders set to what that peer
1610 /// last asked of us, and the notice when someone asks for less.
1611 fileprivate func answerVideoAsks(_ state: RoomState) {
1612 let me = state.peer
1613 let before = media.sentLevels
1614 var lowered = false
1615 for person in state.peers where person.peer != me {
1616 let level = VideoAdapt.asked(person.media, me: me)
1617 let was = before[person.peer] ?? .normal
1618 guard before[person.peer] != nil, level != was else { continue }
1619 CallLog.info("\(person.peer.prefix(6)) asks for \(level.wire) video")
1620 if level > was { lowered = true }
1621 media.setSentLevel(person.peer, level)
1622 }
1623 let sent = media.sentLevels
1624 let people = state.peers.compactMap { p -> (name: String, level: VideoLevel)? in
1625 guard p.peer != me, let level = sent[p.peer], level > .normal else { return nil }
1626 return (p.name, level)
1627 }
1628 let words = VideoAdapt.noticeWords(people)
1629 if words.isEmpty {
1630 videoNotice = ""
1631 } else if lowered, words != videoNotice {
1632 videoNotice = words
1633 say(words, for: 8)
1634 }
1635 }
1636
1637 /// The person's choice taking effect: no camera to anyone at Audio only,
1638 /// reported as off; the asks of everyone; and the tiles.
1639 fileprivate func applyVideoQuality() {
1640 guard bridge != nil else { return }
1641 media.ownAudioOnly = videoQuality == .audio
1642 reportMedia()
1643 reportVideo()
1644 }
1645}
1646
1647// ---------------------------------------------------------------
1648// Quality and problem reports (§15.26)
1649// ---------------------------------------------------------------
1650
1651extension Call {
1652 /// Sends a quality report every `qualityInterval` while admitted: the
1653 /// window starts at admission, and each report covers the time since
1654 /// the last. Read and built on the main actor, as the statistics reads
1655 /// for the meters are; sent off it, because the bridge's send is a
1656 /// request. Between reports it reads the connections once a second for
1657 /// the window's round trip and jitter (§15.29), only while there is a
1658 /// report to read for.
1659 fileprivate func startQualityWatch() {
1660 qualityWatch?.cancel()
1661 qualityTally = QualityEventTally()
1662 qualityBuilder = QualityReportBuilder()
1663 qualityStopped = false
1664 qualityFinalSent = false
1665 qualityFacts = nil
1666 autoReportGate = AutoReportGate()
1667 autoReportForced = Self.autoReportForTest
1668 qualityWatch = Task { @MainActor [weak self] in
1669 while !Task.isCancelled {
1670 try? await Task.sleep(nanoseconds: 1_000_000_000)
1671 guard let self, !Task.isCancelled, let client = self.bridge else { return }
1672 let now = ProcessInfo.processInfo.systemUptime
1673 guard self.qualityBuilder.started else {
1674 if self.admittedForReports {
1675 self.qualityBuilder.start(at: now)
1676 self.qualityTally = QualityEventTally()
1677 }
1678 continue
1679 }
1680 let due = self.qualityBuilder.elapsed(at: now) >= Self.qualityInterval
1681 guard self.admittedForReports, !self.qualityStopped, QualityReporting.enabled() else {
1682 // Off, stopped, or between participations: the window moves on
1683 // with nothing sent, so a report never covers time it did not
1684 // see, and nothing is read until there is a report to read for.
1685 if due {
1686 self.qualityBuilder.start(at: now)
1687 self.qualityTally = QualityEventTally()
1688 self.qualityFacts = nil
1689 }
1690 continue
1691 }
1692 // Once a second (§15.29): the round trip and jitter for the
1693 // window's mean and highest. The window's own report is built from
1694 // the same look.
1695 let samples = await self.built?.qualitySamples() ?? [:]
1696 guard !Task.isCancelled, self.bridge === client else { return }
1697 self.qualityBuilder.observe(samples: samples)
1698 guard due else { continue }
1699 self.sendQualityWindow(samples: samples, client: client)
1700 }
1701 }
1702 }
1703
1704 /// A window's report, and with it the automatic report when the call is
1705 /// struggling (§15.29): that goes first, so the quality report can carry
1706 /// its reference.
1707 private func sendQualityWindow(samples: [String: QualityPeerSample], client: BridgeClient) {
1708 let now = ProcessInfo.processInfo.systemUptime
1709 var report = qualityBuilder.build(
1710 at: now, samples: samples, events: &qualityTally, client: QualityClientInfo.current(),
1711 devices: qualityDevices(), final: false, screenMode: sharingScreen ? screenMode.rawValue : nil)
1712 // §15.30 (2026-10-29): how this machine fared over the window.
1713 report.host = hostSampler.take(HostLoadSampler.Reading.now(at: now))
1714 let facts = QualityTrouble.facts(report)
1715 let trigger = AutoReportDecision.trigger(
1716 previous: qualityFacts, now: facts, gate: autoReportGate, at: now, enabled: QualityReporting.enabled(),
1717 stopped: qualityStopped, final: false, forced: autoReportForced)
1718 qualityFacts = facts
1719 var auto: String?
1720 if let trigger {
1721 autoReportGate.record(at: now)
1722 autoReportForced = nil
1723 auto = AutoReportBody(trigger: trigger, diagnostics: anonymousDiagnosticsText(), client: QualityClientInfo.current())
1724 .encoded()
1725 }
1726 Task.detached { [weak self] in
1727 var report = report
1728 if let trigger, let auto {
1729 let outcome = AutoReportOutcome(bridgeAnswer: client.sendAutoReport(auto))
1730 await MainActor.run { [weak self] in
1731 switch outcome {
1732 case .sent(let ref): CallLog.info("automatic report sent: \(trigger), reference \(ref)")
1733 case .stop:
1734 self?.qualityStopped = true
1735 CallLog.info("quality reports: the server asked for no more this call")
1736 case .notSent(let why): CallLog.info("automatic report not sent: \(trigger), \(why)")
1737 }
1738 }
1739 switch outcome {
1740 case .sent(let ref): report.autoReport = ref
1741 case .stop: return
1742 case .notSent: break
1743 }
1744 }
1745 guard let body = report.encoded() else { return }
1746 if client.sendQuality(body) == "stop" {
1747 await MainActor.run { [weak self] in
1748 self?.qualityStopped = true
1749 CallLog.info("quality reports: the server asked for no more this call")
1750 }
1751 }
1752 }
1753 }
1754
1755 private var admittedForReports: Bool {
1756 guard let phase = state?.phase else { return false }
1757 return phase == "admitted" || phase == "reconnecting"
1758 }
1759
1760 private func qualityReport(at now: Double, samples: [String: QualityPeerSample], final: Bool) -> String? {
1761 var report = qualityBuilder.build(
1762 at: now, samples: samples, events: &qualityTally, client: QualityClientInfo.current(),
1763 devices: qualityDevices(), final: final, screenMode: sharingScreen ? screenMode.rawValue : nil)
1764 // §15.30 (2026-10-29): how this machine fared over the window.
1765 report.host = hostSampler.take(HostLoadSampler.Reading.now(at: now))
1766 return report.encoded()
1767 }
1768
1769 /// The report sent at leave, built while the connections are still up;
1770 /// nil when there is none to send.
1771 fileprivate func finalQualityReport() async -> String? {
1772 guard let client = bridge, qualityBuilder.started, !qualityStopped, !qualityFinalSent,
1773 QualityReporting.enabled()
1774 else { return nil }
1775 let samples = await built?.qualitySamples() ?? [:]
1776 guard bridge === client, !qualityFinalSent else { return nil }
1777 qualityFinalSent = true
1778 return qualityReport(at: ProcessInfo.processInfo.systemUptime, samples: samples, final: true)
1779 }
1780
1781 /// The call ended under this app (ended, removed, open elsewhere): the
1782 /// final report goes now, with the notices but without statistics — the
1783 /// connections are closing as it is built — and the call stays
1784 /// reportable from here.
1785 fileprivate func endedForReports() {
1786 guard let client = bridge else { return }
1787 keepForReports(client)
1788 guard qualityBuilder.started, !qualityStopped, !qualityFinalSent, QualityReporting.enabled() else { return }
1789 qualityFinalSent = true
1790 guard let body = qualityReport(at: ProcessInfo.processInfo.systemUptime, samples: [:], final: true) else { return }
1791 Task.detached { _ = client.sendQuality(body) }
1792 }
1793
1794 /// The kinds of microphone and speaker in use. Never their names.
1795 private func qualityDevices() -> QualityDevices? {
1796 #if os(macOS)
1797 let kinds = audio.deviceKinds()
1798 return QualityDevices(input: kinds.input, output: kinds.output)
1799 #else
1800 let route = AVAudioSession.sharedInstance().currentRoute
1801 return QualityDevices(
1802 input: DeviceKind.ios(port: route.inputs.first?.portType.rawValue),
1803 output: DeviceKind.ios(port: route.outputs.first?.portType.rawValue))
1804 #endif
1805 }
1806
1807 /// One look by the level watch, tallied for the window's events.
1808 fileprivate func observeQuality(now: Double, state: RoomState) {
1809 guard qualityBuilder.started else { return }
1810 let me = state.peer
1811 var fromUs = Set<String>()
1812 var blocked = Set<String>()
1813 for person in state.peers where person.peer != me {
1814 if person.media?.noSoundFrom?.contains(me) == true { fromUs.insert(person.peer) }
1815 if person.media?.audioBlocked == true { blocked.insert(person.peer) }
1816 }
1817 qualityTally.observe(
1818 at: now, call: reconnecting, reconnecting: reconnectingPeers, cantHear: connectingPeers,
1819 noSound: Set(levels.noSoundFrom), noSoundFromUs: fromUs, audioBlocked: blocked,
1820 screenStalled: Set(reportedStalled))
1821 }
1822
1823 /// The sharer's watchdog's steps, toward the peers they were for.
1824 fileprivate func countScreenSteps(_ actions: [ScreenRecovery], failed: Int, stalledBy: Set<String>) {
1825 let me = state?.peer ?? ""
1826 for action in actions {
1827 switch action {
1828 case .keyframe(let peer): qualityTally.count(.keyframe, for: peer)
1829 case .reAdd(let peer), .rebuild(let peer): qualityTally.count(.rebuild, for: peer)
1830 case .reshare:
1831 for person in state?.peers ?? [] where person.peer != me { qualityTally.count(.reshare, for: person.peer) }
1832 case .restartCapture, .recreateEncoder: break
1833 }
1834 }
1835 for peer in screenWatchdog.newlyStarved { qualityTally.count(.encoderStall, for: peer) }
1836 for peer in screenWatchdog.newlyDamped { qualityTally.count(.damped, for: peer) }
1837 guard failed > 0 else { return }
1838 for peer in stalledBy where screenWatchdog.escalation(of: peer) == .failed {
1839 qualityTally.count(.failure, for: peer)
1840 }
1841 }
1842
1843 /// Keeps a call's closed client, and its diagnostics as they are now,
1844 /// for "Report a problem" during the ten minutes after it.
1845 fileprivate func keepForReports(_ client: BridgeClient) {
1846 guard reportClient !== client else { return }
1847 reportClient = client
1848 reportDiagnostics = anonymousDiagnosticsText()
1849 let until = Date().addingTimeInterval(Self.reportWindow)
1850 reportableUntil = until
1851 Task { @MainActor [weak self] in
1852 try? await Task.sleep(nanoseconds: UInt64(Self.reportWindow * 1_000_000_000))
1853 guard let self, self.reportableUntil == until else { return }
1854 self.reportableUntil = nil
1855 self.reportClient = nil
1856 self.reportDiagnostics = ""
1857 }
1858 }
1859
1860 /// Whether "Report a problem" has anything to report: a call in
1861 /// progress, or one that ended less than ten minutes ago.
1862 public var canReportProblem: Bool {
1863 bridge != nil || fixtureReports || (reportableUntil.map { $0 > Date() } ?? false)
1864 }
1865
1866 /// Opens the sheet. In a call it reports this call, its diagnostics read
1867 /// now; after one, the call that ended, as it was when it ended.
1868 public func reportProblem() {
1869 let info = QualityClientInfo.current()
1870 let deliver: @Sendable (String) async -> ProblemOutcome
1871 if let client = bridge ?? (canReportProblem ? reportClient : nil) {
1872 let diagnostics = bridge != nil ? anonymousDiagnosticsText() : reportDiagnostics
1873 deliver = { note in
1874 let body = ProblemReportBody(note: note, diagnostics: diagnostics, client: info).encoded()
1875 return await Task.detached { ProblemOutcome(bridgeAnswer: client.sendProblem(body)) }.value
1876 }
1877 } else if fixtureReports {
1878 // The UI test's call has no server: it is answered here, after a
1879 // moment, with a reference of the server's shape.
1880 deliver = { _ in
1881 try? await Task.sleep(nanoseconds: 300_000_000)
1882 return .sent(ref: "K7Q2M9PD")
1883 }
1884 } else {
1885 return
1886 }
1887 problemReport = ProblemReportModel(deliver: deliver)
1888 }
1889}
1890
1891// ---------------------------------------------------------------
1892// Fixtures
1893// ---------------------------------------------------------------
1894
1895extension Call {
1896 /// Puts the call into a described state without a server, for the
1897 /// offline snapshots of the call views and the iPhone's UI test of its
1898 /// controls. `state` is a roster in the wire's own JSON. Never used by
1899 /// a call that has joined anything.
1900 @_spi(Fixtures) public func showFixture(
1901 title: String, standing: String = "member", status: String = "In the meeting",
1902 state json: String, screens: [String] = [], sharingScreen: Bool = false,
1903 muted: Bool = false, floor: Bool = false, named: Bool = false
1904 ) {
1905 self.title = title
1906 self.named = named
1907 self.standing = standing
1908 self.state = try? JSONDecoder().decode(RoomState.self, from: Data(json.utf8))
1909 self.status = status
1910 // A fixture's reconnecting is one that has lasted (spec §15.23).
1911 self.reconnecting = self.state?.phase == "reconnecting"
1912 self.screens = screens
1913 self.sharingScreen = sharingScreen
1914 self.muted = muted
1915 self.floor = floor
1916 self.fixtureReports = true
1917 }
1918
1919 /// Your own microphone, camera and screen, set over a fixture for the
1920 /// snapshots of the controls in each state.
1921 @_spi(Fixtures) public func showFixtureSelf(muted: Bool, cameraOff: Bool, sharingScreen: Bool) {
1922 self.muted = muted
1923 self.cameraOff = cameraOff
1924 self.sharingScreen = sharingScreen
1925 }
1926
1927 /// Spec §15.24 for the snapshots: these people have just joined and the
1928 /// grace has passed, so each tile says what it would — "connecting", or
1929 /// a report of theirs that replaces it.
1930 @_spi(Fixtures) public func showFixtureConnecting(_ peers: [String]) {
1931 let me = state?.peer ?? ""
1932 var shown: Set<String> = []
1933 for person in state?.peers ?? [] where peers.contains(person.peer) {
1934 let said = ConnectingWatch.tile(
1935 name: person.name, media: person.media, me: me, muted: muted, joining: true, shown: true,
1936 reconnecting: false)
1937 if said.connecting != nil { shown.insert(person.peer) }
1938 levels.peer(person.peer).show(
1939 state: person.media?.muted == true ? .muted : .meter(0), speaking: false, notices: said.notices,
1940 connecting: said.connecting)
1941 }
1942 connectingPeers = shown
1943 }
1944
1945 /// Everyone's glow, and yours, held at one level, for the snapshots.
1946 @_spi(Fixtures) public func showFixtureSpeaking(level: Float) {
1947 levels.mic.glow.showFixture(level: level)
1948 // Nobody muted glows: muted, the speaking gate is shut.
1949 if muted { levels.mic.glow.reset() }
1950 for peer in state?.peers ?? [] where peer.peer != state?.peer && !isMuted(peer.peer) {
1951 levels.peer(peer.peer).glow.showFixture(level: level)
1952 }
1953 levels.othersGlow.showFixture(level: level)
1954 levels.anyoneSpeaking.set(levels.othersGlow.glow.lit)
1955 }
1956}
1957