oficina / meet Public

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

Plain git — no account needed to clone.

Download

Download this file

1import AVFoundation
2import CoreVideo
3import Foundation
4import LiveKitWebRTC
5
6@MainActor final class MediaEngine {
7 weak var call: Call?
8 let factory: RTCPeerConnectionFactory
9 var localVideo: RTCVideoTrack?
10 var localAudio: RTCAudioTrack?
11 /// §5.4: the display track while this app is sharing, and nothing
12 /// otherwise. Every connection carries it on a transceiver of its own.
13 private(set) var localScreen: RTCVideoTrack?
14 private var screenCapture: ScreenCapture?
15 // Bumped by everything that ends a share, so a capture whose picker
16 // was still open when the share or the call ended is stopped when it
17 // finally answers, rather than sent.
18 private var screenAttempt = 0
19 private var capture: VideoCapture?
20 private var peers: [String: MediaPeer] = [:]
21 /// What the screen is optimised for (ScreenSendPolicy), and the size
22 /// its source was last seen at, which motion mode scales down from.
23 var screenMode = ScreenShareMode.balanced {
24 didSet { applySendPolicy() }
25 }
26 private var screenSize = (width: 0, height: 0)
27 /// The screen's source size, for §15.30's minimal fit.
28 var screenSourceSize: (width: Int, height: Int) { screenSize }
29
30 /// The audio device module and processing behind the factory. See CallAudio.
31 let audio: CallAudio
32
33 /// Builds on the calling thread: only for a call touched before it
34 /// joined. A join uses `make`.
35 convenience init(call: Call) {
36 RTCInitializeSSL()
37 #if os(iOS)
38 self.init(call: call, audio: CallAudio(routes: call.audio, audioDevice: call.customAudioDevice))
39 #else
40 self.init(call: call, audio: CallAudio(routes: call.audio, audioDevice: nil, input: call.audioInput))
41 #endif
42 }
43
44 init(call: Call, audio: CallAudio) {
45 self.call = call
46 self.audio = audio
47 factory = audio.factory
48 }
49
50 /// The media for a call, with its factory and audio device module built
51 /// on the audio queue (CallAudio.make): 100–200 ms the main thread no
52 /// longer spends when someone joins.
53 static func make(call: Call) async -> MediaEngine {
54 await AudioWork.run { RTCInitializeSSL() }
55 #if os(iOS)
56 let audio = await CallAudio.make(routes: call.audio, audioDevice: call.customAudioDevice)
57 #else
58 let audio = await CallAudio.make(routes: call.audio, audioDevice: nil, input: call.audioInput)
59 #endif
60 return MediaEngine(call: call, audio: audio)
61 }
62 func prepare(capture supplied: VideoCapture?) async throws {
63 close()
64 let source = factory.videoSource()
65 localVideo = factory.videoTrack(with: source, trackId: "camera")
66 localAudio = audio.makeTrack()
67 let capture = supplied ?? CameraCapture.make()
68 self.capture = capture
69 offersCameras = capture.offersCameras
70 capture.observe { [weak self] in self?.call?.cameraChanged() }
71 try await capture.start(source: source)
72 #if os(iOS)
73 // A supplied audio device owns its session configuration (SDK contract).
74 if call?.customAudioDevice == nil {
75 let audio = RTCAudioSession.sharedInstance()
76 audio.lockForConfiguration()
77 defer { audio.unlockForConfiguration() }
78 // Not .allowBluetoothHFP: see AudioRoutes.options. At join nobody
79 // has chosen a Bluetooth microphone, so the call starts wideband
80 // and only drops to the hands-free profile if someone asks for a
81 // Bluetooth input by name.
82 try audio.setCategory(
83 AVAudioSession.Category.playAndRecord,
84 mode: AVAudioSession.Mode.videoChat,
85 options: AudioRoutes.options(bluetoothInput: false))
86 // WebRTC owns activation and interruption recovery as peers start/stop.
87 }
88 #endif
89 }
90 /// The cameras the running capture can offer, and the one it is on.
91 /// Empty before prepare, and empty for the interop executable's
92 /// synthetic frames, which is how the picker knows not to appear.
93 ///
94 /// With real cameras the list stays live after the capture has gone
95 /// (the call ended under the person), so the panel can still say what
96 /// is connected and a choice there is remembered for next time.
97 var cameras: [CameraDevice] {
98 if let capture { return capture.cameras }
99 return offersCameras ? CameraWatch.shared.cameras : []
100 }
101 var currentCamera: String? { capture?.currentCamera }
102 /// Whether this call's camera is a real one, whose row the panel always
103 /// shows. Kept past the capture, for the same reason as `cameras`.
104 private(set) var offersCameras = false
105 var cameraStatus: CameraStatus? { capture?.cameraStatus }
106 var cameraNote: String { capture?.cameraNote ?? "" }
107 var cameraToKeep: CameraDevice? { capture?.cameraToKeep }
108 func use(camera id: String) async throws {
109 if let capture {
110 try await capture.use(camera: id)
111 } else if offersCameras, let device = CameraWatch.shared.cameras.first(where: { $0.id == id }) {
112 CameraPreference(device).save()
113 }
114 }
115 func retryCamera() async {
116 CameraWatch.shared.refresh()
117 await capture?.retryCamera()
118 }
119
120 func closePeers() {
121 for (_, p) in peers { p.close() }
122 peers.removeAll()
123 }
124
125 /// Starts sending a screen (§5.4). The capture is asked first: a person
126 /// who changes their mind at the system's picker has shared nothing,
127 /// and nothing is added to any connection.
128 ///
129 /// What gives way under pressure — resolution or frame rate — is the
130 /// "Optimise for" mode's, through sender parameters (ScreenSendPolicy).
131 func startScreen(_ capture: ScreenCapture, ended: @escaping @MainActor () -> Void) async throws {
132 guard localScreen == nil else { return }
133 screenAttempt += 1
134 let attempt = screenAttempt
135 screenSize = (0, 0)
136 screenIsScreencast = ScreenSendPolicy.screencast(screenMode)
137 let source = factory.videoSource(forScreenCast: screenIsScreencast)
138 try await capture.start(source: source, ended: ended)
139 guard attempt == screenAttempt, localScreen == nil else {
140 capture.stop()
141 throw CancellationError()
142 }
143 screenCapture = capture
144 screenSourceInUse = source
145 if let size = capture.frameSize, size.width > 0, size.height > 0 { screenSize = size }
146 localScreen = factory.videoTrack(with: source, trackId: "screen")
147 for peer in peers.values { peer.addScreen() }
148 }
149 /// The source the screen's capture is writing into, for a share again
150 /// from the same capture.
151 private var screenSourceInUse: RTCVideoSource?
152 private var reshares = 0
153
154 /// Stop and Share, without the picker (spec §15.22): every connection's
155 /// screen transceiver stopped and renegotiated, a fresh track on the
156 /// same source, the capture started again on the same content, and each
157 /// connection given the new track as soon as it settles. New
158 /// transceivers mean new encoders here and new receivers and decoders at
159 /// every far end, which is what the hand-made stop and share did.
160 func reshareScreen() async {
161 guard let capture = screenCapture, let source = screenSourceInUse, localScreen != nil else { return }
162 reshares += 1
163 for peer in peers.values { peer.removeScreen() }
164 localScreen = factory.videoTrack(with: source, trackId: "screen-\(reshares)")
165 if !(await capture.restart()) { ScreenLog.info("share again: the capture carries on as it was") }
166 guard screenCapture === capture else { return }
167 // Any connection already stable takes it now; the rest as they settle.
168 for peer in peers.values { peer.addScreen() }
169 }
170
171 /// Stops sending the screen: every connection's screen transceiver is
172 /// stopped and renegotiated, so the receivers' tracks *end*, and the
173 /// capture goes last.
174 func stopScreen() {
175 screenAttempt += 1
176 guard let capture = screenCapture else { return }
177 screenCapture = nil
178 screenSourceInUse = nil
179 localScreen = nil
180 for peer in peers.values {
181 peer.removeScreen()
182 peer.screenStopped()
183 }
184 capture.stop()
185 }
186
187 // -------------------------------------------------------------
188 // The screen watchdog's hands (ScreenWatchdog, run by Call)
189 // -------------------------------------------------------------
190
191 /// What the capture has produced so far; nothing while not sharing.
192 var screenCaptureCounts: ScreenCaptureCounts? { screenCapture?.counts }
193
194 /// A fresh capture of the same content, into the same source.
195 func restartScreenCapture() async -> Bool {
196 guard let capture = screenCapture else { return false }
197 return await capture.restart()
198 }
199 func forceScreenKeyframe(_ peer: String) { peers[peer]?.forceScreenKeyframe() }
200 func recreateScreenEncoder(_ peer: String) { peers[peer]?.recreateScreenEncoder() }
201 func reAddScreen(_ peer: String) { peers[peer]?.reAddScreen() }
202
203 /// For the gate: every screen encoding switched off behind the
204 /// watchdog's back, which is what an encoder that has stopped looks
205 /// like from outside it — frames go in, and nothing comes out.
206 func stallScreenEncoderForTest() {
207 for peer in peers.values { peer.setScreenActive(false) }
208 }
209
210 /// Each peer's screen as it arrives here, for the peers whose screen is
211 /// arriving (the receiver's watchdog, and "Copy call diagnostics").
212 func remoteScreenReports() async -> [String: ScreenReceiveReport] {
213 var out: [String: ScreenReceiveReport] = [:]
214 for (id, peer) in peers {
215 guard let pc = peer.pc, peer.receivingScreen else { continue }
216 let report = await PeerCalls.statistics(pc)
217 var reading = ScreenReceiveReport()
218 for stat in report.statistics.values where stat.type == "inbound-rtp" {
219 let mid = stat.values["mid"] as? String ?? ""
220 guard peer.isScreen(mid: mid) else { continue }
221 reading.add(stat.values)
222 }
223 reading.mid = peer.screenMidHere
224 out[id] = reading
225 }
226 return out
227 }
228
229 /// Frames decoded from screens here, never going backwards: a rebuilt
230 /// screen arrives on a new receiver whose own count starts again, and
231 /// the gate's "decoding again" has to see its frames as more.
232 private var screenDecodedSeen: [String: UInt64] = [:]
233 private(set) var screenDecodedTotal: UInt64 = 0
234 private func tallyScreenDecoded(_ peer: String, _ now: UInt64) {
235 let last = screenDecodedSeen[peer] ?? 0
236 screenDecodedTotal += now >= last ? now - last : now
237 screenDecodedSeen[peer] = now
238 }
239
240 /// Puts every connection's screen and camera senders where the policy
241 /// wants them; a no-op for any that already are.
242 func applySendPolicy() {
243 for peer in peers.values { peer.applySendPolicy() }
244 }
245
246 /// Spec §15.30: the level one peer asks of us, applied to that one
247 /// connection's senders. Kept on the peer, so a connection that settles
248 /// later is given it too.
249 func setSentLevel(_ peer: String, _ level: VideoLevel) {
250 guard let p = peers[peer], p.sentLevel != level else { return }
251 p.sentLevel = level
252 p.applySendPolicy()
253 }
254 /// When each connection last renegotiated.
255 var negotiatedAt: [String: Double] { peers.mapValues(\.negotiatedAt) }
256 /// What each connection is sending at, as asked.
257 var sentLevels: [String: VideoLevel] { peers.mapValues(\.sentLevel) }
258 /// The person's own Audio only: no camera to anyone.
259 var ownAudioOnly = false {
260 didSet { if ownAudioOnly != oldValue { applySendPolicy() } }
261 }
262 /// This device's own trouble (§15.30's sender watch): a floor under the
263 /// camera to everyone; the screen and audio are not touched.
264 var localLevel = VideoLevel.normal {
265 didSet { if localLevel != oldValue { applySendPolicy() } }
266 }
267 /// The screen's source size, as its statistics report it.
268 func screenSource(width: Int, height: Int) {
269 guard width > 0, height > 0, (width, height) != screenSize else { return }
270 screenSize = (width, height)
271 applySendPolicy()
272 }
273 var screenPlan: EncodingPlan { screenPlanFor(nil) }
274 /// The plan for one connection, given the H.264 format it negotiated.
275 var screenPlanFor: @Sendable ([String: String]?) -> EncodingPlan {
276 let mode = screenMode
277 let size = screenSize
278 let screencast = screenIsScreencast
279 return { fmtp in
280 ScreenSendPolicy.screen(mode, width: size.width, height: size.height, screencast: screencast, negotiated: fmtp)
281 }
282 }
283 /// Whether this share's source was made as a screencast: fixed when the
284 /// share starts, whatever the mode is changed to afterwards.
285 private var screenIsScreencast = true
286
287 func close() {
288 stopScreen()
289 closePeers()
290 capture?.stop()
291 capture = nil
292 // On the audio queue: a track's switch waits out an engine start.
293 let video = localVideo
294 let audio = localAudio
295 AudioWork.post {
296 video?.isEnabled = false
297 audio?.isEnabled = false
298 }
299 localVideo = nil
300 localAudio = nil
301 }
302 func reconcile(state: RoomState, ice: ICEConfig) {
303 let wanted = Set(state.peers.filter { $0.peer != state.peer }.map(\.peer))
304 for id in Array(peers.keys) where !wanted.contains(id) {
305 peers.removeValue(forKey: id)?.close()
306 call?.removeRemote(id)
307 }
308 for person in state.peers where person.peer != state.peer {
309 let gen = person.gen ?? 1
310 if let old = peers[person.peer], old.generation == gen { continue }
311 peers.removeValue(forKey: person.peer)?.close()
312 call?.removeRemote(person.peer)
313 let peer = MediaPeer(
314 id: person.peer, generation: gen, polite: state.peer < person.peer, engine: self)
315 peers[person.peer] = peer
316 peer.open(ice: ice)
317 }
318 }
319 func receive(_ message: Message) { if let from = message.from { peers[from]?.receive(message) } }
320 /// §5.4's label. A peer this app has no connection to yet is ignored,
321 /// as the browser ignores it: its screen will be told apart from its
322 /// camera by the m-line when the connection comes, and a caption with
323 /// no connection behind it is a tile nothing will ever fill or clear.
324 func receiveShare(_ message: Message) {
325 guard let from = message.from, let peer = peers[from] else { return }
326 peer.share(on: message.payload?.on == true)
327 }
328 /// ICE restarts this app has started for a renewal, for the gate.
329 var iceRestarts: UInt64 = 0
330 /// A fresh `/ice` answer for every connection; the peers whose
331 /// connections it restarted (§5.3's renewal falling due).
332 @discardableResult func updateICE(_ config: ICEConfig) -> Set<String> {
333 let now = Int64(Date().timeIntervalSince1970)
334 var restarted: Set<String> = []
335 for (id, p) in peers where p.updateICE(config, now: now) { restarted.insert(id) }
336 return restarted
337 }
338
339 /// Each connection as ConnectionRecovery reads it (spec §15.28): its ICE
340 /// state as the delegate last reported it, when it was made, which side
341 /// leads, its last remote offer, and whether a step on it threw. No hop
342 /// into WebRTC: all of it is kept on the main actor as it happens.
343 func recoveryLooks() -> [String: ConnectionRecovery.Look] {
344 peers.mapValues {
345 ConnectionRecovery.Look(
346 ice: $0.iceState, builtAt: $0.builtAt, leader: !$0.polite, remoteOfferAt: $0.remoteOfferAt,
347 errored: $0.errored)
348 }
349 }
350
351 /// §15.28's ICE restart, for one connection, on the list it holds now.
352 func restartICE(_ peer: String) { peers[peer]?.recoveryRestart() }
353 /// The five audio-health fields, gathered alongside the byte counts.
354 ///
355 /// Bytes say audio arrived; they say nothing about what it sounded like.
356 /// These five separate the two ways received audio goes wrong, which is
357 /// the distinction a person reporting "it growled" cannot make for us:
358 ///
359 /// - `concealedSamples` against `totalSamplesReceived` is loss. The
360 /// decoder invented that fraction of the audio because nothing
361 /// arrived to decode.
362 /// - `insertedSamplesForDeceleration` and
363 /// `removedSamplesForAcceleration` are clock drift. The jitter
364 /// buffer is stretching or compressing the signal to keep up with a
365 /// sender whose clock runs at a different rate than this device's —
366 /// and stretching a voice is what a growl *is*.
367 ///
368 /// With the device pickers beside it, a suspect device can be ruled out
369 /// by switching away from it while watching these.
370 static let audioHealthFields = [
371 "concealedSamples", "totalSamplesReceived",
372 "insertedSamplesForDeceleration", "removedSamplesForAcceleration",
373 ]
374
375 func stats() async -> [String: UInt64] {
376 var values: [String: UInt64] = [
377 "framesDecoded": 0, "audioBytesReceived": 0, "videoBytesSent": 0, "audioBytesSent": 0,
378 "screenFramesDecoded": 0, "screenBytesSent": 0,
379 "peerConnections": UInt64(peers.count),
380 "concealedSamples": 0, "totalSamplesReceived": 0,
381 "insertedSamplesForDeceleration": 0, "removedSamplesForAcceleration": 0,
382 "jitterBufferDelayMs": 0,
383 ]
384 for (id, peer) in peers {
385 guard let pc = peer.pc else { continue }
386 let ownScreen = await peer.ownScreenMid()
387 let report = await PeerCalls.statistics(pc)
388 var screenDecoded: UInt64 = 0
389 defer { tallyScreenDecoded(id, screenDecoded) }
390 for stat in report.statistics.values {
391 let kind = (stat.values["kind"] as? String) ?? (stat.values["mediaType"] as? String) ?? ""
392 let mid = stat.values["mid"] as? String ?? ""
393 if stat.type == "inbound-rtp" {
394 if kind == "video" {
395 // A peer sharing its screen sends two video streams, and a
396 // count that added them together would let a screen stand in
397 // for a camera that had stopped. Told apart by mid, which is
398 // what the browser's own gate does.
399 let field = peer.isScreen(mid: mid) ? "screenFramesDecoded" : "framesDecoded"
400 let decoded = (stat.values["framesDecoded"] as? NSNumber)?.uint64Value ?? 0
401 values[field, default: 0] += decoded
402 if peer.isScreen(mid: mid) { screenDecoded += decoded }
403 }
404 if kind == "audio" {
405 values["audioBytesReceived", default: 0] +=
406 (stat.values["bytesReceived"] as? NSNumber)?.uint64Value ?? 0
407 for field in MediaEngine.audioHealthFields {
408 values[field, default: 0] += (stat.values[field] as? NSNumber)?.uint64Value ?? 0
409 }
410 // jitterBufferDelay is seconds as a double, and is cumulative
411 // against jitterBufferEmittedCount rather than a gauge. It is
412 // carried in milliseconds because everything else here is an
413 // integer, and a sub-millisecond buffer is not a fact anyone
414 // reading this is going to act on.
415 let delay = (stat.values["jitterBufferDelay"] as? NSNumber)?.doubleValue ?? 0
416 values["jitterBufferDelayMs", default: 0] += UInt64((delay * 1000).rounded())
417 }
418 }
419 if stat.type == "outbound-rtp" {
420 if kind == "video" {
421 let field = !mid.isEmpty && mid == ownScreen ? "screenBytesSent" : "videoBytesSent"
422 values[field, default: 0] +=
423 (stat.values["bytesSent"] as? NSNumber)?.uint64Value ?? 0
424 }
425 if kind == "audio" {
426 values["audioBytesSent", default: 0] +=
427 (stat.values["bytesSent"] as? NSNumber)?.uint64Value ?? 0
428 }
429 }
430 }
431 }
432 values["screenFramesDecodedTotal"] = screenDecodedTotal
433 return values
434 }
435
436 /// Each remote person's sound, for the meters (spec §15.20): the level
437 /// their receive tap has seen since the last look, whether the
438 /// connection is up, and — when `stats` is set, or for the people in
439 /// `detail` — the audio bytes and packets received so far and whether
440 /// the receiver is live, one `statistics(for:)` per audio receiver rather
441 /// than the whole report. For the people in `acks`, whether their
442 /// receiver reports say this app's audio reaches them (spec §15.24's
443 /// fallback for a client that does not say who it hears).
444 func peerAudio(stats: Bool, detail: Set<String> = [], acks: Set<String> = []) async -> [String: PeerAudioReading] {
445 var out: [String: PeerAudioReading] = [:]
446 for (id, peer) in peers {
447 guard let pc = peer.pc else { continue }
448 let (peak, buffers) = peer.tap.take()
449 let deep = stats || detail.contains(id)
450 let ack = acks.contains(id)
451 // Read on the audio queue, as every call into the connection is
452 // (PeerCalls): five times a second, and each one a blocking hop to
453 // WebRTC's signalling thread.
454 let (state, receivers, senders) = await PeerCalls.read(pc) { pc in
455 (
456 pc.iceConnectionState, deep ? pc.receivers.filter { $0.track?.kind == "audio" } : [],
457 ack ? pc.senders.filter { $0.track?.kind == "audio" } : []
458 )
459 }
460 var reading = PeerAudioReading(
461 peak: peak, buffers: buffers, connected: state == .connected || state == .completed,
462 connectionBad: state == .disconnected || state == .failed)
463 reading.gone = state == .failed || state == .closed
464 reading.failed = state == .failed
465 if deep {
466 var bytes: UInt64 = 0
467 var packets: UInt64 = 0
468 var live = false
469 for receiver in receivers {
470 if receiver.track?.readyState == .live { live = true }
471 let report = await PeerCalls.statistics(pc, for: receiver)
472 for stat in report.statistics.values where stat.type == "inbound-rtp" {
473 bytes += (stat.values["bytesReceived"] as? NSNumber)?.uint64Value ?? 0
474 packets += (stat.values["packetsReceived"] as? NSNumber)?.uint64Value ?? 0
475 }
476 }
477 reading.bytes = bytes
478 reading.packets = packets
479 reading.hasReceiver = !receivers.isEmpty
480 reading.receiverLive = live
481 }
482 if ack {
483 var sent: UInt64 = 0
484 var acked = false
485 for sender in senders {
486 let report = await PeerCalls.statistics(pc, for: sender)
487 for stat in report.statistics.values {
488 if stat.type == "outbound-rtp" {
489 sent += (stat.values["packetsSent"] as? NSNumber)?.uint64Value ?? 0
490 } else if stat.type == "remote-inbound-rtp" {
491 // Exists only once a receiver report has come back.
492 let received = (stat.values["packetsReceived"] as? NSNumber)?.uint64Value ?? 0
493 let measured = (stat.values["roundTripTimeMeasurements"] as? NSNumber)?.uint64Value ?? 0
494 if received > 0 || measured > 0 || stat.values["roundTripTime"] != nil { acked = true }
495 }
496 }
497 }
498 reading.acked = sent > 0 && acked
499 }
500 out[id] = reading
501 }
502 return out
503 }
504
505 /// Every connection's statistics at one look, for the quality report
506 /// (spec §15.26): the whole report per connection, with its generation
507 /// and which mids carry screens, read as the other statistics are.
508 func qualitySamples() async -> [String: QualityPeerSample] {
509 var out: [String: QualityPeerSample] = [:]
510 for (id, peer) in peers {
511 guard let pc = peer.pc else { continue }
512 let ownScreen = await peer.ownScreenMid()
513 let report = await PeerCalls.statistics(pc)
514 out[id] = QualityPeerSample(
515 generation: peer.generation, ownScreenMid: ownScreen, screenMid: peer.screenMidHere,
516 stats: report.statistics.mapValues { QualityStat(type: $0.type, values: $0.values) })
517 }
518 return out
519 }
520
521 /// Caps every connection's bandwidth estimate, which is what a thin
522 /// uplink does to it. For the gate, which has no thin uplink to test on;
523 /// nil takes the cap off.
524 func limitUplink(_ bps: Int?) {
525 uplinkLimit = bps
526 for peer in peers.values { peer.limitUplink(bps) }
527 }
528 private(set) var uplinkLimit: Int?
529
530 /// This app's screen on the way out, one report per connection sending
531 /// it (see ScreenSendReport).
532 func screenReports() async -> [String: ScreenSendReport] {
533 var reports: [String: ScreenSendReport] = [:]
534 for (id, peer) in peers {
535 guard let pc = peer.pc, let mid = await peer.ownScreenMid() else { continue }
536 let report = await PeerCalls.statistics(pc)
537 let flat = report.statistics.mapValues { (type: $0.type, values: $0.values as [String: Any]) }
538 if var read = ScreenSendReport.read(flat, mid: mid) {
539 read.timestamp = report.timestamp_us / 1_000_000
540 reports[id] = read
541 }
542 }
543 return reports
544 }
545}
546
547/// A transceiver direction as SDP spells it, which is how the classifier,
548/// and the browser it was ported from, compare them.
549private func sdpDirection(_ direction: RTCRtpTransceiverDirection) -> String {
550 switch direction {
551 case .sendRecv: return "sendrecv"
552 case .sendOnly: return "sendonly"
553 case .recvOnly: return "recvonly"
554 case .inactive: return "inactive"
555 case .stopped: return "stopped"
556 @unknown default: return ""
557 }
558}
559
560/// One look at a remote person's audio (see MediaEngine.peerAudio).
561struct PeerAudioReading: Equatable, Sendable {
562 var peak: Float
563 var buffers: Int
564 var connected: Bool
565 /// ICE `disconnected` or `failed` (spec §15.23's three seconds).
566 var connectionBad = false
567 /// ICE `failed` or `closed`: whatever was heard on it is gone (§15.24).
568 var gone = false
569 /// ICE `failed`.
570 var failed = false
571 var bytes: UInt64?
572 /// Audio packets received, the receiver there at all, and its track
573 /// live (§15.24); read with `bytes`.
574 var packets: UInt64?
575 var hasReceiver = false
576 var receiverLive = false
577 /// Their receiver reports say this app's audio reaches them; nil when
578 /// not asked.
579 var acked: Bool?
580}
581
582@MainActor private final class MediaPeer: NSObject, RTCPeerConnectionDelegate {
583 let id: String
584 /// Measures every audio track that arrives on this connection (their
585 /// microphone; a browser's shared tab audio would add to it).
586 nonisolated let tap = RemoteAudioTap()
587 private var tapped: [RTCAudioTrack] = []
588 let generation: Int64
589 let polite: Bool
590 nonisolated let playAudio: Bool
591 weak var engine: MediaEngine?
592 var pc: RTCPeerConnection?
593 private var work: Task<Void, Never>?
594 private var closed = false
595 private var ignoreOffer = false
596 private var candidates: [Candidate] = []
597 private var lastICE: ICEConfig?
598 /// The list this connection last gathered on — built with, or last
599 /// restarted onto — whose `renewAt` says when it needs a restart.
600 private var gatheredICE: ICEConfig?
601 // §5.4, receiving. What this peer's camera and microphone came in on,
602 // and whether it has said it is sharing; the receiver its screen
603 // arrived on, so that only *that* receiver going away takes the tile
604 // with it; and the mid, so the statistics can count the two video
605 // streams apart.
606 private var clues = ScreenClues()
607 /// Spec §15.30: what this peer asks of us, and so what this connection's
608 /// camera and screen are sent at.
609 var sentLevel = VideoLevel.normal
610 /// When a negotiation on this connection last settled (§15.30's watch
611 /// takes no news for a few seconds after).
612 var negotiatedAt = 0.0
613 private var screenReceiver: String?
614 private var screenMid = ""
615 // Whether this connection carries a camera of ours: the classifier's
616 // direction rule turns on it.
617 private var sentVideo = false
618 // §5.4, sending: the transceiver this connection carries our screen on,
619 // while we are sharing. And an offer this connection owes the far side
620 // but could not make yet, because it was in the middle of another.
621 private var screenTx: RTCRtpTransceiver?
622 private var owesOffer = false
623 // §15.28, what ConnectionRecovery reads: when this connection was made,
624 // its ICE state as the delegate last said, when a remote offer was last
625 // applied, and whether a negotiation step on it threw.
626 let builtAt = ProcessInfo.processInfo.systemUptime
627 private(set) var iceState = ConnectionRecovery.ICE.new
628 private(set) var remoteOfferAt: Double?
629 private var remoteUfrag: String?
630 private(set) var errored = false
631
632 init(id: String, generation: Int64, polite: Bool, engine: MediaEngine) {
633 self.id = id
634 self.generation = generation
635 self.polite = polite
636 self.engine = engine
637 self.playAudio = engine.call?.playAudio ?? true
638 }
639 private func configuration(_ ice: ICEConfig) -> RTCConfiguration {
640 let c = RTCConfiguration()
641 c.sdpSemantics = .unifiedPlan
642 c.iceServers = ice.iceServers.map {
643 RTCIceServer(urlStrings: $0.urls, username: $0.username, credential: $0.credential)
644 }
645 return c
646 }
647 /// Makes the connection on the audio queue, as the first thing this
648 /// peer's work does: everything that arrives for it waits behind it.
649 /// Making one waits on WebRTC's worker thread, which can be busy
650 /// starting the audio engine for someone else (846 ms measured on the
651 /// main thread with a Bluetooth switch simulated).
652 func open(ice: ICEConfig) {
653 guard let engine else { return }
654 lastICE = ice
655 gatheredICE = ice
656 let factory = engine.factory
657 let config = configuration(ice)
658 let audio = engine.localAudio
659 let video = engine.localVideo
660 let delegate: RTCPeerConnectionDelegate = self
661 enqueue { [weak self] in
662 let (made, sent) = await AudioWork.run { () -> (RTCPeerConnection?, Bool) in
663 guard
664 let pc = factory.peerConnection(
665 with: config, constraints: RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil),
666 delegate: delegate)
667 else { return (nil, false) }
668 if let audio { _ = pc.add(audio, streamIds: ["calls"]) }
669 let sent = video.map { pc.add($0, streamIds: ["calls"]) != nil } ?? false
670 return (pc, sent)
671 }
672 guard let self, !self.closed, let made else {
673 if let made { PeerCalls.close(made) }
674 return
675 }
676 self.pc = made
677 self.sentVideo = sent
678 if let limit = self.engine?.uplinkLimit { self.limitUplink(limit) }
679 // A connection built while this app is already sharing gets the
680 // screen with everything else: someone joining mid-share sees it.
681 // Last, as in the browser, so the camera and microphone take the
682 // m-lines the far side built for them and the screen a place of its
683 // own after them.
684 self.addScreen()
685 }
686 }
687
688 /// Gives this connection the screen on a `sendonly` transceiver in a
689 /// stream of its own, which is what keeps it clear of the camera at the
690 /// far end. Adding it asks for negotiation, and perfect negotiation
691 /// carries the offer with no help from here.
692 ///
693 /// Only on a stable connection. A transceiver added mid-negotiation is
694 /// unassociated when the far side's offer arrives, and m-line matching
695 /// will hand it that offer's m-line — so two people sharing at once end
696 /// up each sending a screen in the place the other built for something
697 /// else. The browser's mutualshare gate found that; the deferred ones
698 /// are added when the connection settles.
699 ///
700 /// Added on the audio queue, as every call into the connection is; a
701 /// share that ended while it was being added is taken away again.
702 func addScreen() {
703 guard let pc, !closed, screenTx == nil, !addingScreen, let track = engine?.localScreen, let engine
704 else { return }
705 addingScreen = true
706 let factory = engine.factory
707 Task { @MainActor [weak self] in
708 let added = await PeerCalls.read(pc) { pc -> RTCRtpTransceiver? in
709 guard pc.signalingState == .stable else { return nil }
710 let setup = RTCRtpTransceiverInit()
711 setup.direction = .sendOnly
712 setup.streamIds = ["screen"]
713 guard let tx = pc.addTransceiver(with: track, init: setup) else { return nil }
714 try? tx.setCodecPreferences(
715 ScreenSendPolicy.preferringH264(factory.rtpSenderCapabilities(forKind: "video").codecs), error: ())
716 return tx
717 }
718 guard let self else { return }
719 self.addingScreen = false
720 guard let added else { return }
721 self.screenTx = added
722 self.screenMidCache = nil
723 guard !self.closed, self.pc === pc, self.engine?.localScreen === track else {
724 self.removeScreen()
725 return
726 }
727 self.applySendPolicy()
728 }
729 }
730 private var addingScreen = false
731
732 /// The screen at its mode's parameters and the camera capped beside
733 /// it, or the camera back at its defaults when there is no screen.
734 /// Sender parameters only: nothing here renegotiates.
735 ///
736 /// Applied on the audio queue: a sender's parameters are read and set on
737 /// WebRTC's worker thread, and this runs each time a negotiation settles
738 /// — just when the worker may be starting the audio engine.
739 func applySendPolicy() {
740 guard let pc, !closed, let engine else { return }
741 let screen = screenTx?.sender
742 let plan = engine.screenPlanFor
743 let nudge = self.nudge
744 let cameraTrack = engine.localVideo
745 // §15.30: at the level this peer asks of us, and no camera at all while
746 // the person's own Video quality is Audio only.
747 let level = sentLevel
748 let size = engine.screenSourceSize
749 let camera = VideoAdapt.camera(
750 engine.ownAudioOnly ? .audio : max(level, engine.localLevel), sharing: screenTx != nil)
751 AudioWork.post {
752 if let screen {
753 // The format this connection negotiated, which may hold the
754 // screen to a level (ScreenSendPolicy.levelMacroblocks).
755 let fmtp = screen.parameters.codecs.first.flatMap { codec -> [String: String]? in
756 codec.name.uppercased() == "H264" ? codec.parameters as? [String: String] : nil
757 }
758 var screenPlan = VideoAdapt.screen(plan(fmtp), level, width: size.width, height: size.height)
759 if nudge > 1 { screenPlan.scaleResolutionDownBy = (screenPlan.scaleResolutionDownBy ?? 1) * nudge }
760 screen.apply(screenPlan)
761 }
762 let id = cameraTrack?.trackId
763 if let sender = pc.senders.first(where: { $0.track != nil && $0.track?.trackId == id }) {
764 sender.apply(camera)
765 }
766 }
767 }
768
769 /// Ends this connection's screen m-line. Stopping the transceiver is
770 /// §5.4's own instruction and the only thing that makes the receiver's
771 /// track end rather than freeze on its last frame.
772 ///
773 /// The framework's stop is the immediate one: it stops the transceiver
774 /// and asks for nothing, where the browser's `stop()` also raises
775 /// negotiation-needed. So the offer that tells the far side is asked
776 /// for here, by hand.
777 func removeScreen() {
778 guard let tx = screenTx else { return }
779 screenTx = nil
780 screenMidCache = nil
781 AudioWork.post { tx.stopInternal() }
782 applySendPolicy()
783 renegotiate()
784 }
785
786 /// An offer this side has to make for a reason negotiation-needed will
787 /// not announce. Made now if the connection is quiet, and otherwise
788 /// owed, and made the next time it settles.
789 private func renegotiate() {
790 guard let pc, !closed else { return }
791 Task { @MainActor [weak self] in
792 guard await PeerCalls.read(pc, { $0.signalingState }) == .stable else {
793 self?.owesOffer = true
794 return
795 }
796 guard let self else { return }
797 if self.polite { try? await Task.sleep(nanoseconds: 200_000_000) }
798 self.enqueue { [weak self] in
799 guard let self, let pc = self.pc else { return }
800 if await PeerCalls.read(pc, { $0.signalingState }) != .stable {
801 self.owesOffer = true
802 return
803 }
804 try await self.offer()
805 }
806 }
807 }
808
809 /// The connection is back at stable: the one moment a deferred screen
810 /// can be added, and an owed offer made.
811 private func settled() {
812 negotiatedAt = ProcessInfo.processInfo.systemUptime
813 guard let pc, !closed else { return }
814 Task { @MainActor [weak self] in
815 // Read on the audio queue, as every call into the connection is.
816 let stable = await PeerCalls.read(pc) { $0.signalingState } == .stable
817 guard let self, stable, !self.closed, self.pc === pc else { return }
818 self.addScreen()
819 self.applySendPolicy()
820 if self.owesOffer {
821 self.owesOffer = false
822 self.renegotiate()
823 }
824 }
825 }
826 func isScreen(mid: String) -> Bool { !mid.isEmpty && mid == screenMid }
827 var screenMidHere: String { screenMid }
828 /// The mid our screen went out on, once negotiated: read on the audio
829 /// queue (a transceiver's mid is a hop to WebRTC's signalling thread),
830 /// and kept once known.
831 func ownScreenMid() async -> String? {
832 if let screenMidCache { return screenMidCache }
833 guard let pc, let tx = screenTx else { return nil }
834 let mid = await PeerCalls.read(pc) { _ in tx.mid }
835 guard !mid.isEmpty, screenTx === tx else { return nil }
836 screenMidCache = mid
837 return mid
838 }
839 private var screenMidCache: String?
840 func limitUplink(_ bps: Int?) {
841 guard let pc else { return }
842 AudioWork.post {
843 _ = pc.setBweMinBitrateBps(nil, currentBitrateBps: nil, maxBitrateBps: bps.map { NSNumber(value: $0) })
844 }
845 }
846
847 /// The `share` message: on draws the captioned tile ahead of the media,
848 /// off is one of §5.4's two endings.
849 func share(on: Bool) {
850 if on {
851 clues.sharing = true
852 engine?.call?.announceScreen(id)
853 } else {
854 dropScreen()
855 }
856 }
857 private func dropScreen() {
858 clues.sharing = false
859 screenReceiver = nil
860 screenMid = ""
861 engine?.call?.dropScreen(id)
862 }
863
864 /// One track arriving, put in its place. A camera goes on the peer's
865 /// tile exactly as it always did; a screen gets a tile of its own and
866 /// leaves the camera alone.
867 private func arrived(
868 _ track: RTCMediaStreamTrack, receiver: String, info: ArrivingTrack
869 ) {
870 let role = classifyTrack(clues, info, hasVideo: sentVideo)
871 if role == .screen, let video = track as? RTCVideoTrack {
872 clues.sharing = true
873 screenReceiver = receiver
874 if !info.mid.isEmpty { screenMid = info.mid }
875 engine?.call?.setScreen(video, peer: id)
876 return
877 }
878 if role == .camera {
879 if !info.mid.isEmpty { clues.cameraMid = info.mid }
880 if !info.streamId.isEmpty { clues.cameraStream = info.streamId }
881 }
882 // Recorded from the first track of any kind: it is what places a
883 // video track for a peer that has no camera.
884 if clues.peerStream.isEmpty { clues.peerStream = info.streamId }
885 if role == .camera, let video = track as? RTCVideoTrack {
886 engine?.call?.setRemote(video, peer: id)
887 }
888 if let audio = track as? RTCAudioTrack, !tapped.contains(where: { $0 === audio }) {
889 audio.add(tap)
890 tapped.append(audio)
891 }
892 }
893
894 func close() {
895 closed = true
896 for audio in tapped { audio.remove(tap) }
897 tapped = []
898 screenTx = nil
899 work?.cancel()
900 work = nil
901 // Closing can stop the audio engine (the last connection), which
902 // takes as long as starting it: on the audio queue.
903 if let pc { PeerCalls.close(pc) }
904 pc = nil
905 candidates = []
906 }
907 private func enqueue(_ action: @escaping @MainActor () async throws -> Void) {
908 let previous = work
909 work = Task { [weak self] in
910 await previous?.value
911 guard let self, !self.closed, !Task.isCancelled else { return }
912 do { try await action() } catch {
913 // §15.28: a step that threw leaves this connection to its recovery
914 // (an ICE restart, then a rebuild), which says so if it lasts.
915 guard !self.closed else { return }
916 if !self.errored { CallLog.info("connection to \(self.id.prefix(6)): a negotiation step failed: \(error.localizedDescription)") }
917 self.errored = true
918 }
919 }
920 }
921 private func send(_ type: String, _ payload: [String: Any]) {
922 guard !closed, let body = json(payload) else { return }
923 engine?.call?.send(type: type, to: id, gen: generation, payload: body)
924 }
925 // Descriptions and candidates are applied from the audio queue
926 // (PeerCalls). Applying one waits for WebRTC's worker thread, which
927 // starts the audio engine for the first stream in each direction — a
928 // Bluetooth headset's profile switch included — and up to 0.3.8 the
929 // main thread waited with it.
930 private func setLocal(_ desc: RTCSessionDescription) async throws {
931 guard let pc, !closed else { return }
932 try await PeerCalls.set(pc, local: true, desc)
933 }
934 private func setRemote(_ desc: RTCSessionDescription) async throws {
935 guard let pc, !closed else { return }
936 try await PeerCalls.set(pc, local: false, desc)
937 }
938 private func makeDescription(answer: Bool, restart: Bool = false) async throws
939 -> RTCSessionDescription
940 {
941 guard let pc else { throw CancellationError() }
942 let constraints = RTCMediaConstraints(
943 mandatoryConstraints: restart ? ["IceRestart": "true"] : nil, optionalConstraints: nil)
944 return try await PeerCalls.describe(pc, answer: answer, constraints)
945 }
946 private func offer(restart: Bool = false) async throws {
947 guard let pc, !closed, await PeerCalls.read(pc, { $0.signalingState }) == .stable, !closed else { return }
948 let desc = try await makeDescription(answer: false, restart: restart)
949 guard !closed else { return }
950 try await setLocal(desc)
951 send("offer", ["description": ["type": "offer", "sdp": Self.testBlocked(sdp: desc.sdp)]])
952 }
953 func receive(_ message: Message) {
954 guard message.gen == generation else { return }
955 enqueue { [weak self] in
956 guard let self, let pc = self.pc, !self.closed else { return }
957 if message.type == "candidate", let candidate = message.payload?.candidate {
958 if self.ignoreOffer { return }
959 if await PeerCalls.read(pc, { $0.remoteDescription == nil }) {
960 guard self.candidates.count < 256 else { throw CancellationError() }
961 self.candidates.append(candidate)
962 } else {
963 // A candidate refused is not a connection broken: one from the
964 // generation before an ICE restart is refused as a matter of
965 // course. ICE says whether the connection works (§15.28).
966 do { try await self.add(candidate) } catch {}
967 }
968 return
969 }
970 guard let desc = message.payload?.description else { return }
971 let signaling = await PeerCalls.read(pc) { $0.signalingState }
972 guard !self.closed else { return }
973 if message.type == "offer", desc.type == "offer" {
974 let collision = signaling != .stable
975 self.ignoreOffer = collision && !self.polite
976 if self.ignoreOffer { return }
977 if collision { try await self.setLocal(RTCSessionDescription(type: .rollback, sdp: "")) }
978 try await self.setRemote(RTCSessionDescription(type: .offer, sdp: Self.testBlocked(sdp: desc.sdp)))
979 // An ICE restart is an offer with a new username fragment (§5.3);
980 // only that is the leader acting for ConnectionRecovery.
981 let ufrag = Self.iceUfrag(desc.sdp)
982 if let ufrag, let before = self.remoteUfrag, ufrag != before {
983 self.remoteOfferAt = ProcessInfo.processInfo.systemUptime
984 }
985 if let ufrag { self.remoteUfrag = ufrag }
986 self.ignoreOffer = false
987 try await self.drain()
988 let answer = try await self.makeDescription(answer: true)
989 try await self.setLocal(answer)
990 self.send("answer", ["description": ["type": "answer", "sdp": Self.testBlocked(sdp: answer.sdp)]])
991 } else if message.type == "answer", desc.type == "answer", signaling == .haveLocalOffer {
992 try await self.setRemote(RTCSessionDescription(type: .answer, sdp: Self.testBlocked(sdp: desc.sdp)))
993 self.ignoreOffer = false
994 try await self.drain()
995 }
996 }
997 }
998 /// The first `a=ice-ufrag:` in a description.
999 static func iceUfrag(_ sdp: String) -> String? {
1000 for line in sdp.components(separatedBy: "\r\n") where line.hasPrefix("a=ice-ufrag:") {
1001 return String(line.dropFirst("a=ice-ufrag:".count))
1002 }
1003 return nil
1004 }
1005 /// The gate's ICE block (ICETestBlock), on every candidate either way;
1006 /// what it was otherwise.
1007 private static func testBlocked(sdp: String) -> String {
1008 guard ICETestBlock.active else { return sdp }
1009 ICETestBlock.mangled += 1
1010 return ICETestBlock.mangle(sdp: sdp)
1011 }
1012 private static func testBlocked(candidate: String) -> String {
1013 guard ICETestBlock.active else { return candidate }
1014 ICETestBlock.mangled += 1
1015 return ICETestBlock.mangle(candidate: candidate)
1016 }
1017 private func add(_ candidate: Candidate) async throws {
1018 guard let pc, !closed, !candidate.candidate.isEmpty else { return }
1019 let ice = RTCIceCandidate(
1020 sdp: Self.testBlocked(candidate: candidate.candidate), sdpMLineIndex: candidate.sdpMLineIndex ?? 0,
1021 sdpMid: candidate.sdpMid)
1022 try await PeerCalls.add(pc, ice)
1023 }
1024 private func drain() async throws {
1025 let saved = candidates
1026 candidates = []
1027 for c in saved { do { try await add(c) } catch {} }
1028 }
1029 /// A fresh `/ice` answer (§5.2, §5.3). The core fetches one on every
1030 /// roster, and a roster answers every stream resume — every five
1031 /// minutes at the stream's own TTL — so most answers are not renewals
1032 /// at all. Up to 0.4.1 every one of them restarted ICE on every
1033 /// connection, twelve times an hour, each one a new path for the
1034 /// screen and camera to find their way back onto. Now only a renewal
1035 /// that is due restarts (ICERenewal.restart); anything else is adopted
1036 /// quietly, for whatever this connection gathers next.
1037 @discardableResult func updateICE(_ ice: ICEConfig, now: Int64) -> Bool {
1038 guard ice.renewAt != lastICE?.renewAt || ice.iceServers.count != lastICE?.iceServers.count else { return false }
1039 lastICE = ice
1040 let restart = ICERenewal.restart(gathered: gatheredICE, next: ice, now: now)
1041 if restart { gatheredICE = ice }
1042 enqueue { [weak self] in
1043 guard let self, let pc = self.pc else { return }
1044 let config = self.configuration(ice)
1045 guard await PeerCalls.read(pc, { $0.setConfiguration(config) }) else { return }
1046 if restart {
1047 ScreenLog.info("ICE restart with \(ScreenWatchdog.short(self.id)): renewal due")
1048 self.engine?.iceRestarts += 1
1049 try await self.offer(restart: true)
1050 }
1051 }
1052 return restart
1053 }
1054
1055 /// §15.28: an ICE restart because this connection is not working, on the
1056 /// list it holds now (`updateICE` has handed it every list since it was
1057 /// made). An offer of this side's still waiting for its answer is rolled
1058 /// back first, because an outstanding offer is the one thing that keeps
1059 /// a restart from going out, and an answer that has not come in seconds
1060 /// is not coming; an offer of the far side's being answered right now is
1061 /// left to finish, and that exchange carries on.
1062 func recoveryRestart() {
1063 if let lastICE { gatheredICE = lastICE }
1064 enqueue { [weak self] in
1065 guard let self, let pc = self.pc else { return }
1066 let signaling = await PeerCalls.read(pc) { $0.signalingState }
1067 guard !self.closed, signaling != .haveRemoteOffer else { return }
1068 if signaling == .haveLocalOffer {
1069 try await self.setLocal(RTCSessionDescription(type: .rollback, sdp: ""))
1070 }
1071 try await self.offer(restart: true)
1072 }
1073 }
1074
1075 // -------------------------------------------------------------
1076 // The screen watchdog's hands, for this connection
1077 // -------------------------------------------------------------
1078
1079 /// Whether this peer's screen is arriving here.
1080 var receivingScreen: Bool { screenReceiver != nil && !screenMid.isEmpty }
1081
1082 /// The screen's encoding switched off and on again. WebRTC starts a
1083 /// stream that comes back on with a keyframe, which is the one thing a
1084 /// receiver stuck on a broken picture needs; there is no API on this
1085 /// build of WebRTC to ask for one directly.
1086 func forceScreenKeyframe() {
1087 setScreenActive(false)
1088 Task { @MainActor [weak self] in
1089 try? await Task.sleep(nanoseconds: 150_000_000)
1090 self?.setScreenActive(true)
1091 }
1092 }
1093
1094 func setScreenActive(_ active: Bool) {
1095 guard let sender = screenTx?.sender else { return }
1096 AudioWork.post {
1097 let parameters = sender.parameters
1098 guard let encoding = parameters.encodings.first, encoding.isActive != active else { return }
1099 encoding.isActive = active
1100 sender.parameters = parameters
1101 }
1102 }
1103
1104 /// A fresh encoder: the screen sent smaller for a while. A change of
1105 /// size is what makes WebRTC set its encoder up again from nothing — for
1106 /// H.264 on a Mac, a new VideoToolbox session, which is the part that
1107 /// can go bad under a sleep or a GPU switch and hold the frames it was
1108 /// given. The other way an encoder stops is a frame it cannot take at
1109 /// all (the level's block count, see ScreenSendPolicy), which a smaller
1110 /// size is also the way out of. A third off each side each time, down to
1111 /// a quarter; full size again after thirty seconds, and if that stops it
1112 /// again the watchdog comes back round, after its rest.
1113 func recreateScreenEncoder() {
1114 guard screenTx != nil else { return }
1115 nudge = min(nudge * 1.5, 4)
1116 nudges += 1
1117 let mine = nudges
1118 ScreenLog.info("screen to \(ScreenWatchdog.short(id)) now sent at 1/\(String(format: "%.2f", nudge)) of its size")
1119 applySendPolicy()
1120 setScreenActive(true)
1121 Task { @MainActor [weak self] in
1122 try? await Task.sleep(nanoseconds: 30_000_000_000)
1123 guard let self, self.nudges == mine, self.nudge > 1 else { return }
1124 self.nudge = 1
1125 ScreenLog.info("screen to \(ScreenWatchdog.short(self.id)) back to full size")
1126 self.applySendPolicy()
1127 }
1128 }
1129 private var nudges = 0
1130 private var nudge = 1.0
1131
1132 /// What stopping and sharing again did, on this connection alone: its
1133 /// screen transceiver stopped and renegotiated, and a new one added as
1134 /// soon as that settles (`settled` adds the screen to a connection that
1135 /// has none while the app is sharing).
1136 func reAddScreen() {
1137 guard screenTx != nil else { return }
1138 removeScreen()
1139 }
1140 /// The share has stopped: the next one starts at full size.
1141 func screenStopped() { nudge = 1 }
1142
1143 nonisolated func peerConnectionShouldNegotiate(_ peerConnection: RTCPeerConnection) {
1144 Task { @MainActor [weak self] in
1145 guard let self else { return }
1146 // Give the higher-id peer first chance, matching the browser's
1147 // polite yield. Perfect negotiation still handles actual glare.
1148 if self.polite { try? await Task.sleep(nanoseconds: 200_000_000) }
1149 self.enqueue { [weak self] in try await self?.offer() }
1150 }
1151 }
1152 nonisolated func peerConnection(
1153 _ peerConnection: RTCPeerConnection, didGenerate candidate: RTCIceCandidate
1154 ) {
1155 Task { @MainActor [weak self] in
1156 self?.send(
1157 "candidate",
1158 [
1159 "candidate": [
1160 "candidate": Self.testBlocked(candidate: candidate.sdp), "sdpMid": candidate.sdpMid as Any? ?? NSNull(),
1161 "sdpMLineIndex": candidate.sdpMLineIndex,
1162 ]
1163 ])
1164 }
1165 }
1166 nonisolated func peerConnection(
1167 _ peerConnection: RTCPeerConnection, didAdd rtpReceiver: RTCRtpReceiver,
1168 streams: [RTCMediaStream]
1169 ) {
1170 // Keep decoding and RTP statistics available when a test disables speakers.
1171 if let audio = rtpReceiver.track as? RTCAudioTrack, !playAudio {
1172 audio.source.volume = 0
1173 }
1174 guard let track = rtpReceiver.track else { return }
1175 // Read here, on the signalling thread this callback arrives on, rather
1176 // than on the main actor: by the time the main actor gets to it the
1177 // next description can have moved the transceiver on.
1178 let receiver = rtpReceiver.receiverId
1179 let transceiver = peerConnection.transceivers.first { $0.receiver.receiverId == receiver }
1180 var info = ArrivingTrack(kind: track.kind, streamId: streams.first?.streamId ?? "")
1181 if let transceiver {
1182 info.mid = transceiver.mid
1183 // The negotiated direction when there is one. On the side that
1184 // answers an offer there is not yet, and that is exactly the side a
1185 // screen arrives at; the direction the transceiver was built with is
1186 // recvonly for an m-line the far side added, which is the point.
1187 var current = RTCRtpTransceiverDirection.inactive
1188 info.direction = sdpDirection(
1189 transceiver.currentDirection(&current) ? current : transceiver.direction)
1190 }
1191 Task { @MainActor [weak self] in
1192 guard let self, !self.closed else { return }
1193 self.arrived(track, receiver: receiver, info: info)
1194 }
1195 }
1196 /// §5.4's other ending: the sender stopped its screen's transceiver and
1197 /// the renegotiation took the receiver away. Only the receiver the
1198 /// screen is showing from counts. A screen replaced on its own mid ends
1199 /// its predecessor afterwards, and without the check that took the live
1200 /// replacement's tile with it (the browser's Codex S4-15).
1201 nonisolated func peerConnection(
1202 _ peerConnection: RTCPeerConnection, didRemove rtpReceiver: RTCRtpReceiver
1203 ) {
1204 let receiver = rtpReceiver.receiverId
1205 Task { @MainActor [weak self] in
1206 guard let self, !self.closed, self.screenReceiver == receiver else { return }
1207 self.dropScreen()
1208 }
1209 }
1210 nonisolated func peerConnection(
1211 _ peerConnection: RTCPeerConnection, didChange newState: RTCIceConnectionState
1212 ) {
1213 // §15.28: kept for ConnectionRecovery, which decides what a failure
1214 // means and when it is worth saying.
1215 let state: ConnectionRecovery.ICE
1216 switch newState {
1217 case .new: state = .new
1218 case .checking: state = .checking
1219 case .connected: state = .connected
1220 case .completed: state = .completed
1221 case .disconnected: state = .disconnected
1222 case .failed: state = .failed
1223 case .closed: state = .closed
1224 default: state = .new
1225 }
1226 Task { @MainActor [weak self] in
1227 guard let self, !self.closed, self.pc == nil || self.pc === peerConnection else { return }
1228 if state != self.iceState { CallLog.info("connection to \(self.id.prefix(6)): ICE \(state)") }
1229 self.iceState = state
1230 }
1231 }
1232 nonisolated func peerConnection(
1233 _ peerConnection: RTCPeerConnection, didChange stateChanged: RTCSignalingState
1234 ) {
1235 guard stateChanged == .stable else { return }
1236 Task { @MainActor [weak self] in self?.settled() }
1237 }
1238 nonisolated func peerConnection(
1239 _ peerConnection: RTCPeerConnection, didAdd stream: RTCMediaStream
1240 ) {}
1241 nonisolated func peerConnection(
1242 _ peerConnection: RTCPeerConnection, didRemove stream: RTCMediaStream
1243 ) {}
1244 nonisolated func peerConnection(
1245 _ peerConnection: RTCPeerConnection, didChange newState: RTCIceGatheringState
1246 ) {}
1247 nonisolated func peerConnection(
1248 _ peerConnection: RTCPeerConnection, didRemove candidates: [RTCIceCandidate]
1249 ) {}
1250 nonisolated func peerConnection(
1251 _ peerConnection: RTCPeerConnection, didOpen dataChannel: RTCDataChannel
1252 ) {}
1253}
1254