oficina / meet Public

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

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2import os
3
4// The screen watchdogs: the sharer's, which notices its own screen
5// stopping on the way out and puts it right, and the receiver's, which
6// notices someone else's screen stopping on the way in and says so.
7//
8// Written for Paul's report of 2026-09-28 (Mac 0.4.1): "When I was
9// screen-sharing, after a while, my screen froze on her end and she was
10// no longer able to see my screen. I had to stop and re-share again." A
11// stop and a share again is a fresh capture, a fresh transceiver, a fresh
12// encoder and a keyframe; the sharer's watchdog does each of those in
13// turn, cheapest first, without anyone noticing or pressing anything.
14
15/// `log show --last 1h --predicate 'subsystem == "net.amadan.oficina.calls" && category == "screen"' --info`.
16/// Every line is also kept in memory (the last 200) for "Copy call
17/// diagnostics".
18enum ScreenLog {
19 static let logger = Logger(subsystem: "net.amadan.oficina.calls", category: "screen")
20
21 static func info(_ message: String) {
22 logger.info("\(message, privacy: .public)")
23 AudioDiagnosticsStore.screen.log("info", message)
24 }
25
26 static func error(_ message: String) {
27 logger.error("\(message, privacy: .public)")
28 AudioDiagnosticsStore.screen.log("error", message)
29 }
30}
31
32extension AudioDiagnosticsStore {
33 /// The screen log's lines, kept apart from the audio log's so neither
34 /// pushes the other out.
35 public static let screen = AudioDiagnosticsStore()
36}
37
38/// One connection's screen on the way out, as the watchdog reads it.
39struct ScreenSendCounts: Equatable, Sendable {
40 var encoded: UInt64 = 0
41 var sent: UInt64 = 0
42 var keyframes: UInt64 = 0
43 /// WebRTC says the link is what is holding the screen back. Frames stop
44 /// being encoded for a while when the estimate collapses, and that is
45 /// the link's to put right, not the encoder's: the watchdog leaves it
46 /// alone (a receiver whose picture stops still reports it).
47 var bandwidthLimited = false
48}
49
50/// What the sharer's watchdog asks for. Each is cheaper than the next.
51enum ScreenRecovery: Equatable, Sendable {
52 /// A fresh capture of the same content into the same source.
53 case restartCapture
54 /// A keyframe on this connection's screen: the encoding switched off
55 /// and on again, which WebRTC answers by starting the stream on one.
56 case keyframe(String)
57 /// A fresh encoder on this connection: the screen's size nudged, which
58 /// makes WebRTC set the hardware encoder up again from nothing.
59 case recreateEncoder(String)
60 /// What stopping and sharing again did: this connection's screen
61 /// transceiver stopped and a new one added, renegotiated.
62 case reAdd(String)
63 /// A receiver's report that keyframes did not answer: this connection's
64 /// screen sending path built again — a new transceiver, so a new encoder
65 /// and, at the far end, a new receiver and decoder — at the same size
66 /// and mode. What stopping and sharing again does, for that one person.
67 case rebuild(String)
68 /// Still reported after that: every connection's screen stopped and
69 /// added again from the same capture (no picker), which is exactly what
70 /// Stop and Share did by hand.
71 case reshare
72}
73
74/// Where the answer to one receiver's report has got to (the sharer's
75/// notice says it in words: see ScreenWords.notice).
76enum ScreenEscalation: Equatable, Sendable {
77 case none
78 /// Keyframes asked for since this time.
79 case keyframes(since: Double)
80 /// That peer's screen rebuilt at this time.
81 case rebuilt(at: Double)
82 /// Everyone's screen shared again at this time.
83 case reshared(at: Double)
84 /// Nothing more to try: the person is told to stop and share again.
85 case failed
86}
87
88/// The sharer's watchdog: pure, fed once a second while sharing.
89///
90/// Three things can freeze a screen on its way out, and each has its own
91/// sign:
92///
93/// - **The capture stops.** ScreenCaptureKit reports even a still screen
94/// (as "idle"), so a capture that reports nothing for three seconds has
95/// stopped — a capture with every surface held by the encoder does
96/// exactly that. Asked for: a fresh capture, with a growing wait
97/// between tries.
98/// - **The encoder stops.** Frames go into the source and none come out
99/// encoded (or none are sent) for five seconds, on one connection, while
100/// the link is not what is holding it back.
101/// Asked for, three seconds apart while it lasts: a keyframe, a fresh
102/// encoder, then the transceiver itself; then a pause of thirty seconds
103/// before starting again.
104/// - **A receiver says so.** Someone's `screenStalled` names this peer
105/// (spec §15.21). A keyframe for that connection, four seconds apart
106/// (the report is a few seconds old when it lands), three times and then
107/// a rest — and the fuller steps only if the screen has stopped leaving
108/// here too.
109/// - **A receiver keeps saying so** (spec §15.22, Paul 2026-09-30: "still
110/// seeing issues with screen sharing after a while", the notice sat at
111/// "recovering"). Keyframes cannot mend a decoder that has wedged at the
112/// far end, or a receiver that has stopped taking this stream at all;
113/// a new transceiver can. Still reported six seconds after the first
114/// keyframe: that connection's screen is rebuilt, at the same size and
115/// mode (a report alone never shrinks a Text and detail share). Still
116/// reported ten seconds after that: everyone's screen is shared again
117/// from the same capture. Ten seconds more and the sharer is told it
118/// could not be restored. A rebuild at most once a minute per person,
119/// a share again at most once every five minutes.
120struct ScreenWatchdog: Equatable {
121 static let captureStallAfter = 3.0
122 static let captureBackoffFirst = 5.0
123 static let captureBackoffMost = 60.0
124 /// Five seconds, not three: a link that has just been capped can hold a
125 /// large keyframe back for that long in Text and detail, and a forced
126 /// keyframe there only makes it longer (the motion gate, 2026-09-28).
127 static let encoderStallAfter = 5.0
128 static let encoderStepEvery = 3.0
129 static let reportStepEvery = 4.0
130 static let holdOff = 30.0
131 /// No encoder verdict in a connection's first ten seconds: a screen
132 /// kept at full size (Text and detail) on a link still ramping up from
133 /// WebRTC's 300 kbit/s start encodes almost nothing for several seconds,
134 /// and that is not a stall (the motion gate, 2026-09-28). A receiver's
135 /// report is still answered then.
136 static let warmUp = 10.0
137 /// §15.22's escalation: how long a report may outlast the first
138 /// keyframe, then the rebuild, then the share again; and how often each
139 /// of the last two may happen.
140 static let rebuildAfter = 6.0
141 static let reshareAfter = 10.0
142 static let giveUpAfter = 10.0
143 static let rebuildEvery = 60.0
144 static let reshareEvery = 300.0
145 /// A loop (2026-10-21): Paul's screen to Farshad in Safari was rebuilt,
146 /// restored within a second, and reported stalled again 25 s later, for
147 /// eight minutes — every rebuild an interruption that mended nothing for
148 /// long. A report that comes back within `loopWithin` of a rebuild or a
149 /// share again having restored the view is that step mending it only
150 /// briefly; `loopLimit` of those in a row and the steps that interrupt
151 /// everyone's picture are not taken for that person for `loopRest`: the
152 /// sharer is told it could not be restored, and keyframes go on.
153 static let loopWithin = 120.0
154 static let loopLimit = 2
155 static let loopRest = 600.0
156 /// "The link is holding the screen back" only while WebRTC's target for
157 /// it is this low. WebRTC goes on naming bandwidth as the limit long
158 /// after the target has recovered, and a screen whose encoder refused
159 /// every frame at a 2.5 Mbit/s target (2026-10-21) was left alone for it.
160 static let linkStarvedBelow: UInt64 = 400_000
161
162 /// Whether WebRTC's own account says the link is what holds the screen
163 /// back: bandwidth named as the limit, at a target this low.
164 static func linkLimited(limitation: String, targetBitrate: UInt64) -> Bool {
165 limitation == "bandwidth" && targetBitrate < linkStarvedBelow
166 }
167
168 struct Peer: Equatable {
169 var last = ScreenSendCounts()
170 var movedAt: Double
171 /// Delivered frames when `movedAt` was last set: a connection is only
172 /// stalled if frames went in meanwhile.
173 var deliveredAt: UInt64
174 var step = 0
175 var stepAt = 0.0
176 var reported = false
177 var restingUntil = 0.0
178 var since = 0.0
179 var escalation = ScreenEscalation.none
180 var lastRebuild: Double?
181 /// Frames sent on this connection since the escalation last moved on:
182 /// a receiver can only be failing to decode frames that were sent. A
183 /// screen the link is holding back, or one with nothing new to send,
184 /// is not taken further.
185 var sentSinceStage: UInt64 = 0
186 /// When a rebuild or a share again last restored this person's view.
187 var restoredByRestartAt: Double?
188 /// Reports in a row that came back soon after such a restore.
189 var loops = 0
190 /// No rebuild or share again for this person before this time.
191 var dampedUntil = 0.0
192 }
193 /// Frames that must leave for a receiver before its report is taken
194 /// further than keyframes.
195 static let escalateAfterSent: UInt64 = 3
196
197 private(set) var peers: [String: Peer] = [:]
198 private var heartbeats: UInt64?
199 private var heartbeatAt = 0.0
200 private var delivered: UInt64 = 0
201 private var captureRetryAt = 0.0
202 private var captureBackoff = ScreenWatchdog.captureBackoffFirst
203 private(set) var captureStalled = false
204
205 // For the readout and the gate.
206 private(set) var captureRestarts = 0
207 private(set) var keyframes = 0
208 private(set) var encoderRecoveries = 0
209 private(set) var reAdds = 0
210 private(set) var stallReports = 0
211 private(set) var rebuilds = 0
212 private(set) var reshares = 0
213 private(set) var failures = 0
214 /// Steps held back because they only ever mended it briefly.
215 private(set) var damped = 0
216 /// Times this side's own screen stopped encoding or sending to someone.
217 private(set) var encoderStalls = 0
218 /// The peers this look found newly stalled on the way out, and the
219 /// peers whose steps it held back: for the quality report (§15.26).
220 private(set) var newlyStarved: [String] = []
221 private(set) var newlyDamped: [String] = []
222 private var lastReshare: Double?
223 /// One line on what the watchdog is doing, for the device panel.
224 private(set) var status = "watching"
225
226 init() {}
227
228 /// Forgets everything: a share starting, or a restart that should be
229 /// given a clean look.
230 mutating func reset() { self = ScreenWatchdog() }
231
232 /// One look. `capture` is the capture's running totals; `sending` each
233 /// connection's screen on the way out, by peer id, for the connections
234 /// that have one negotiated; `stalledBy` the peers whose latest report
235 /// says our screen has stalled for them. Returns what to do now.
236 mutating func observe(
237 at now: Double, capture: ScreenCaptureCounts, sending: [String: ScreenSendCounts],
238 stalledBy: Set<String>
239 ) -> [ScreenRecovery] {
240 var out: [ScreenRecovery] = []
241 newlyStarved = []
242 newlyDamped = []
243 // The capture.
244 let fresh = heartbeats == nil
245 if let beats = capture.heartbeats {
246 if fresh || beats != heartbeats {
247 heartbeats = beats
248 heartbeatAt = now
249 if captureStalled {
250 captureStalled = false
251 captureBackoff = Self.captureBackoffFirst
252 ScreenLog.info("capture reporting again")
253 }
254 } else if now - heartbeatAt >= Self.captureStallAfter {
255 if !captureStalled {
256 captureStalled = true
257 ScreenLog.info("capture stalled: nothing reported for \(Int(now - heartbeatAt)) s")
258 }
259 if now >= captureRetryAt {
260 out.append(.restartCapture)
261 captureRestarts += 1
262 captureRetryAt = now + captureBackoff
263 captureBackoff = min(captureBackoff * 2, Self.captureBackoffMost)
264 }
265 }
266 }
267 delivered = capture.delivered
268 // Each connection.
269 // A connection that has no screen negotiated for the moment — one the
270 // watchdog has just re-added, above all — keeps its record, rest and
271 // all, so the steps do not start again from nothing on the new one.
272 for (id, counts) in sending {
273 var peer = peers[id] ?? Peer(last: counts, movedAt: now, deliveredAt: delivered, since: now)
274 peer.sentSinceStage += counts.sent >= peer.last.sent ? counts.sent - peer.last.sent : counts.sent
275 if counts.encoded < peer.last.encoded || counts.sent < peer.last.sent {
276 // A new transceiver's counters, starting again from nothing.
277 peer.last = counts
278 peer.movedAt = now
279 peer.deliveredAt = delivered
280 }
281 let moved = counts.encoded > peer.last.encoded && counts.sent > peer.last.sent
282 let wasReported = peer.reported
283 let reported = stalledBy.contains(id)
284 if reported && !wasReported { stallReports += 1 }
285 peer.reported = reported
286 peer.last = counts
287 if moved && !reported {
288 if peer.step > 0 {
289 ScreenLog.info("screen to \(Self.short(id)) moving again after step \(peer.step)")
290 peer.step = 0
291 }
292 peer.movedAt = now
293 peer.deliveredAt = delivered
294 } else if moved {
295 peer.movedAt = now
296 peer.deliveredAt = delivered
297 }
298 let starved =
299 !moved && !counts.bandwidthLimited && now - peer.since >= Self.warmUp
300 && now - peer.movedAt >= Self.encoderStallAfter
301 && delivered > peer.deliveredAt
302 if (starved || reported) && now >= peer.restingUntil {
303 let every = reported && !starved ? Self.reportStepEvery : Self.encoderStepEvery
304 if peer.step == 0 || now - peer.stepAt >= every {
305 let why = starved ? "not encoding or sending" : "reported stalled by the receiver"
306 // A receiver's report while this side's screen is leaving
307 // normally is not the encoder's fault — a slow link, a lost
308 // packet — and a keyframe is all it can use: a smaller or a new
309 // encoder would only take the picture down for nothing (Text and
310 // detail after a thin link, the motion gate, 2026-09-28). Only a
311 // screen that has stopped here as well goes further.
312 if starved && peer.step == 0 {
313 encoderStalls += 1
314 newlyStarved.append(id)
315 }
316 switch starved ? peer.step : 0 {
317 case 0:
318 out.append(.keyframe(id))
319 keyframes += 1
320 case 1:
321 out.append(.recreateEncoder(id))
322 encoderRecoveries += 1
323 default:
324 out.append(.reAdd(id))
325 reAdds += 1
326 }
327 peer.step += 1
328 peer.stepAt = now
329 ScreenLog.info("screen to \(Self.short(id)) \(why): step \(peer.step)")
330 if peer.step >= 3 {
331 peer.step = 0
332 peer.restingUntil = now + Self.holdOff
333 }
334 }
335 } else if !starved && !reported && peer.step > 0 && now - peer.stepAt >= Self.encoderStepEvery {
336 peer.step = 0
337 }
338 peers[id] = peer
339 }
340 out += escalate(at: now, stalledBy: stalledBy, negotiated: Set(sending.keys))
341 status = describe()
342 return out
343 }
344
345 /// §15.22: a report that keyframes have not answered, taken further. Run
346 /// over every peer with a record, whether or not its screen is
347 /// negotiated this second — a rebuilt connection has none for a moment,
348 /// and a rebuild that never comes back must still end in words.
349 private mutating func escalate(
350 at now: Double, stalledBy: Set<String>, negotiated: Set<String>
351 ) -> [ScreenRecovery] {
352 var out: [ScreenRecovery] = []
353 var reshare = false
354 for id in peers.keys.sorted() {
355 guard var peer = peers[id] else { continue }
356 let reported = stalledBy.contains(id)
357 // Frames went to this receiver since the last step, or there is no
358 // screen negotiated with it at all (a rebuild that never came back).
359 let owed = peer.sentSinceStage >= Self.escalateAfterSent || !negotiated.contains(id)
360 let before = peer.escalation
361 defer {
362 if peers[id]?.escalation != before { peers[id]?.sentSinceStage = 0 }
363 }
364 if !reported {
365 if peer.escalation != .none {
366 switch peer.escalation {
367 case .keyframes: ScreenLog.info("\(Self.short(id))'s view restored after keyframes")
368 case .rebuilt:
369 ScreenLog.info("\(Self.short(id))'s view restored after the rebuild")
370 peer.restoredByRestartAt = now
371 case .reshared:
372 ScreenLog.info("\(Self.short(id))'s view restored after sharing again")
373 peer.restoredByRestartAt = now
374 case .failed: ScreenLog.info("\(Self.short(id))'s view came back after all")
375 case .none: break
376 }
377 peer.escalation = .none
378 }
379 peers[id] = peer
380 continue
381 }
382 let canRebuild = peer.lastRebuild.map { now - $0 >= Self.rebuildEvery } ?? true
383 let canReshare = reshare || (lastReshare.map { now - $0 >= Self.reshareEvery } ?? true)
384 switch peer.escalation {
385 case .none:
386 peer.escalation = .keyframes(since: now)
387 if let restored = peer.restoredByRestartAt, now - restored < Self.loopWithin {
388 peer.loops += 1
389 ScreenLog.info(
390 "\(Self.short(id)) reports a stall again \(Int(now - restored)) s after a restart restored it (\(peer.loops) in a row)")
391 if peer.loops >= Self.loopLimit {
392 peer.dampedUntil = now + Self.loopRest
393 peer.loops = 0
394 }
395 } else {
396 peer.loops = 0
397 }
398 peer.restoredByRestartAt = nil
399 case .keyframes(let since) where now - since >= Self.rebuildAfter && owed && now < peer.dampedUntil:
400 peer.escalation = .failed
401 failures += 1
402 damped += 1
403 newlyDamped.append(id)
404 ScreenLog.error(
405 "\(Self.short(id)) still reports a stall, and rebuilding has only mended it briefly: not rebuilding or sharing again for \(Int(peer.dampedUntil - now)) s")
406 case .keyframes(let since) where now - since >= Self.rebuildAfter && owed:
407 if canRebuild {
408 out.append(.rebuild(id))
409 rebuilds += 1
410 peer.lastRebuild = now
411 peer.escalation = .rebuilt(at: now)
412 ScreenLog.info(
413 "\(Self.short(id)) still reports a stall \(Int(now - since)) s after keyframes: rebuilding its screen")
414 } else if canReshare {
415 reshare = true
416 peer.escalation = .reshared(at: now)
417 ScreenLog.info("\(Self.short(id)) still reports a stall, rebuilt under a minute ago: sharing again")
418 } else {
419 peer.escalation = .failed
420 failures += 1
421 ScreenLog.error("\(Self.short(id)) still reports a stall and every step is resting: giving up")
422 }
423 case .rebuilt(let at) where now - at >= Self.reshareAfter && owed:
424 if canReshare {
425 reshare = true
426 peer.escalation = .reshared(at: now)
427 ScreenLog.info("\(Self.short(id)) still reports a stall \(Int(now - at)) s after the rebuild: sharing again")
428 } else {
429 peer.escalation = .failed
430 failures += 1
431 ScreenLog.error("\(Self.short(id)) still reports a stall after the rebuild, shared again under five minutes ago: giving up")
432 }
433 case .reshared(let at) where now - at >= Self.giveUpAfter && owed:
434 peer.escalation = .failed
435 failures += 1
436 ScreenLog.error("\(Self.short(id)) still reports a stall \(Int(now - at)) s after sharing again: giving up")
437 default:
438 break
439 }
440 peers[id] = peer
441 }
442 if reshare {
443 out.append(.reshare)
444 reshares += 1
445 lastReshare = now
446 // One share again answers every report in flight.
447 for (id, peer) in peers where stalledBy.contains(id) {
448 switch peer.escalation {
449 case .keyframes, .rebuilt:
450 peers[id]?.escalation = .reshared(at: now)
451 peers[id]?.sentSinceStage = 0
452 default: break
453 }
454 }
455 }
456 return out
457 }
458
459 /// Where the answer to each reporting peer has got to, for the notice.
460 func escalation(of peer: String) -> ScreenEscalation { peers[peer]?.escalation ?? .none }
461
462 /// Whether anyone's view of the screen is being recovered right now.
463 var recovering: Bool { captureStalled || peers.values.contains { $0.step > 0 || $0.reported } }
464
465 private func describe() -> String {
466 if captureStalled { return "capture stalled, restarting (\(captureRestarts))" }
467 let stages = peers.values.map(\.escalation)
468 if stages.contains(.failed) { return "a receiver's view could not be restored" }
469 if stages.contains(where: { if case .reshared = $0 { return true } else { return false } }) {
470 return "shared again for everyone"
471 }
472 if stages.contains(where: { if case .rebuilt = $0 { return true } else { return false } }) {
473 return "rebuilt for a receiver"
474 }
475 if let (_, p) = peers.first(where: { $0.value.step > 0 }) {
476 return ["", "keyframe asked for", "encoder recreated", "re-added"][min(p.step, 3)]
477 }
478 if peers.values.contains(where: \.reported) { return "a receiver reports a stall" }
479 let total = captureRestarts + keyframes + encoderRecoveries + reAdds + rebuilds + reshares
480 return total == 0 ? "watching" : "watching, \(total) recover\(total == 1 ? "y" : "ies") so far"
481 }
482
483 static func short(_ peer: String) -> String { String(peer.prefix(6)) }
484}
485
486/// The receiver's watchdog: whose screens have stopped moving here.
487///
488/// A peer's screen is stalled when nothing new has been decoded from it
489/// for four seconds while it says it is sharing. Every sender repeats a
490/// still screen at least once a second (the iPhone's broadcast too, since
491/// 2026-09-30), so four seconds without a frame is not a still screen. The
492/// list is reported as `screenStalled` (spec §15.21) and the sharer
493/// recovers; it clears as soon as frames move.
494///
495/// Any change in the count is movement, a smaller one included: a screen
496/// the sharer has rebuilt arrives on a new receiver whose count starts
497/// again from nothing (2026-09-30 — before this, a rebuilt screen that was
498/// moving again stayed "stalled" here until its new count passed the old
499/// one, and the sharer's notice with it).
500///
501/// Four seconds into a stall the tile's picture is also dropped and
502/// attached again, once (spec §15.22): a renderer that has stopped, on
503/// this side, is this side's to mend. A report is held for at most three
504/// minutes from the last frame, long enough for the sharer to try
505/// everything and say so, and no longer.
506struct ScreenReceiveWatch: Equatable {
507 static let stallAfter = 4.0
508 static let reattachAfter = 4.0
509 static let giveUpAfter = 180.0
510
511 struct Seen: Equatable {
512 var decoded: UInt64
513 var movedAt: Double
514 var reattached = false
515 }
516 private(set) var seen: [String: Seen] = [:]
517 /// The peers whose picture should be attached again now: set by each
518 /// look, and each stall's only once.
519 private(set) var reattach: [String] = []
520
521 init() {}
522
523 /// `decoded` is frames decoded so far from each peer's screen, for the
524 /// peers that have one arriving. Returns the stalled peers, sorted.
525 mutating func observe(at now: Double, decoded: [String: UInt64]) -> [String] {
526 for id in seen.keys where decoded[id] == nil { seen.removeValue(forKey: id) }
527 var stalled: [String] = []
528 reattach = []
529 for (id, count) in decoded {
530 guard var s = seen[id], count == s.decoded else {
531 seen[id] = Seen(decoded: count, movedAt: now)
532 continue
533 }
534 let quiet = now - s.movedAt
535 if quiet >= Self.stallAfter && quiet < Self.giveUpAfter { stalled.append(id) }
536 if quiet >= Self.stallAfter + Self.reattachAfter && !s.reattached && quiet < Self.giveUpAfter {
537 s.reattached = true
538 reattach.append(id)
539 }
540 seen[id] = s
541 }
542 reattach.sort()
543 return stalled.sorted()
544 }
545
546 /// How long each stalled peer's screen has gone without a frame.
547 func quiet(at now: Double) -> [String: Double] { seen.mapValues { now - $0.movedAt } }
548}
549
550/// The words for the sharer's quiet notice.
551public enum ScreenWords {
552 /// "Vicky’s view of your screen stalled — recovering", or nothing when
553 /// nobody's has.
554 public static func recovering(names: [String]) -> String {
555 switch names.count {
556 case 0: return ""
557 case 1: return "\(names[0])\u{2019}s view of your screen stalled \u{2014} recovering"
558 case 2: return "\(names[0])\u{2019}s and \(names[1])\u{2019}s views of your screen stalled \u{2014} recovering"
559 default: return "\(names.count) people\u{2019}s views of your screen stalled \u{2014} recovering"
560 }
561 }
562
563 /// The notice as the escalation moves on (spec §15.22): "recovering",
564 /// then "Restarting your share for Samuel…", then either nothing or
565 /// "Couldn’t restore Samuel’s view — try Stop and Share again". Worst
566 /// news first when several people are at different steps.
567 public static func notice(recovering: [String], restarting: [String], failed: [String]) -> String {
568 var parts: [String] = []
569 if !failed.isEmpty {
570 let whose: String
571 switch failed.count {
572 case 1: whose = "\(failed[0])\u{2019}s view"
573 case 2: whose = "\(failed[0])\u{2019}s and \(failed[1])\u{2019}s views"
574 default: whose = "\(failed.count) people\u{2019}s views"
575 }
576 parts.append("Couldn\u{2019}t restore \(whose) \u{2014} try Stop and Share again")
577 }
578 if !restarting.isEmpty {
579 let who: String
580 switch restarting.count {
581 case 1: who = restarting[0]
582 case 2: who = "\(restarting[0]) and \(restarting[1])"
583 default: who = "\(restarting.count) people"
584 }
585 parts.append("Restarting your share for \(who)\u{2026}")
586 }
587 let stalled = Self.recovering(names: recovering)
588 if !stalled.isEmpty { parts.append(stalled) }
589 return parts.joined(separator: ". ")
590 }
591}
592
593/// One peer's screen as it arrives here, from the receiver's statistics
594/// (spec §15.22): enough to tell the ways a screen stops apart. Packets
595/// arriving and frames assembled but none decoded is a decoder that has
596/// wedged; nothing arriving at all is the sender, or the path; frames
597/// decoded and a picture that does not move is the renderer.
598struct ScreenReceiveReport: Equatable, Sendable {
599 var packetsReceived: UInt64 = 0
600 var packetsLost: Int64 = 0
601 var bytesReceived: UInt64 = 0
602 var framesReceived: UInt64 = 0
603 var framesDecoded: UInt64 = 0
604 var framesDropped: UInt64 = 0
605 var keyFramesDecoded: UInt64 = 0
606 var pliCount: UInt64 = 0
607 var firCount: UInt64 = 0
608 var nackCount: UInt64 = 0
609 var freezeCount: UInt64 = 0
610 var width = 0
611 var height = 0
612 var decoder = ""
613 /// When the last packet arrived, in the statistics' own milliseconds.
614 var lastPacketAt = 0.0
615 var mid = ""
616
617 init() {}
618
619 /// One inbound-rtp report's values added in (a screen has one).
620 mutating func add(_ v: [String: NSObject]) {
621 func n(_ key: String) -> UInt64 { (v[key] as? NSNumber)?.uint64Value ?? 0 }
622 packetsReceived += n("packetsReceived")
623 packetsLost += (v["packetsLost"] as? NSNumber)?.int64Value ?? 0
624 bytesReceived += n("bytesReceived")
625 framesReceived += n("framesReceived")
626 framesDecoded += n("framesDecoded")
627 framesDropped += n("framesDropped")
628 keyFramesDecoded += n("keyFramesDecoded")
629 pliCount += n("pliCount")
630 firCount += n("firCount")
631 nackCount += n("nackCount")
632 freezeCount += n("freezeCount")
633 width = max(width, Int(n("frameWidth")))
634 height = max(height, Int(n("frameHeight")))
635 if let name = v["decoderImplementation"] as? String, !name.isEmpty { decoder = name }
636 lastPacketAt = max(lastPacketAt, (v["lastPacketReceivedTimestamp"] as? NSNumber)?.doubleValue ?? 0)
637 }
638
639 /// What changed between two looks, in words: "packets +120, frames
640 /// received +30, decoded +0, dropped +0, keyframes +0, PLI +2".
641 func moved(since before: ScreenReceiveReport?) -> String {
642 guard let b = before, b.mid == mid else { return summary }
643 func d(_ a: UInt64, _ z: UInt64) -> String { a >= z ? "+\(a - z)" : "new \(a)" }
644 return "packets \(d(packetsReceived, b.packetsReceived)), frames received \(d(framesReceived, b.framesReceived)), "
645 + "decoded \(d(framesDecoded, b.framesDecoded)), dropped \(d(framesDropped, b.framesDropped)), "
646 + "keyframes \(d(keyFramesDecoded, b.keyFramesDecoded)), PLI \(d(pliCount, b.pliCount)), "
647 + "NACK \(d(nackCount, b.nackCount))"
648 }
649
650 /// The running totals, one line.
651 var summary: String {
652 "mid \(mid.isEmpty ? "-" : mid), \(width)x\(height), decoder \(decoder.isEmpty ? "unknown" : decoder); "
653 + "packets \(packetsReceived) (lost \(packetsLost)), frames received \(framesReceived), "
654 + "decoded \(framesDecoded), dropped \(framesDropped), keyframes \(keyFramesDecoded), "
655 + "PLI \(pliCount), FIR \(firCount), NACK \(nackCount), freezes \(freezeCount)"
656 }
657
658 /// The verdict the numbers point to, for a screen that has stopped.
659 func diagnosis(since before: ScreenReceiveReport?) -> String {
660 guard let b = before, b.mid == mid else { return "no earlier reading" }
661 if packetsReceived == b.packetsReceived { return "no packets arriving (the sender or the path)" }
662 if framesReceived == b.framesReceived { return "packets arriving, no frames assembled (loss, or waiting on a keyframe)" }
663 if framesDecoded == b.framesDecoded { return "frames arriving, none decoded (the decoder)" }
664 return "decoding"
665 }
666}
667