@poolse/native 0.0.0-stage → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/LICENSE +206 -0
  3. package/README.md +116 -2
  4. package/android/build.gradle +58 -0
  5. package/android/consumer-rules.pro +11 -0
  6. package/android/src/main/AndroidManifest.xml +46 -0
  7. package/android/src/main/java/dev/poolse/callcore/CallCoreRuntime.kt +540 -0
  8. package/android/src/main/java/dev/poolse/callcore/CallMachine.kt +492 -0
  9. package/android/src/main/java/dev/poolse/callcore/Ports.kt +132 -0
  10. package/android/src/main/java/dev/poolse/callcore/android/AndroidRingSurface.kt +383 -0
  11. package/android/src/main/java/dev/poolse/callcore/android/CallActionReceiver.kt +45 -0
  12. package/android/src/main/java/dev/poolse/callcore/android/CallCore.kt +578 -0
  13. package/android/src/main/java/dev/poolse/callcore/android/CallForegroundService.kt +294 -0
  14. package/android/src/main/java/dev/poolse/callcore/android/CallHttpClient.kt +207 -0
  15. package/android/src/main/java/dev/poolse/callcore/android/CallMessagingService.kt +161 -0
  16. package/android/src/main/java/dev/poolse/callcore/android/CallVideo.kt +36 -0
  17. package/android/src/main/java/dev/poolse/callcore/android/HandlerTimerPort.kt +42 -0
  18. package/android/src/main/java/dev/poolse/callcore/android/IncomingCallActivity.kt +314 -0
  19. package/android/src/main/java/dev/poolse/callcore/android/MessageNotifications.kt +353 -0
  20. package/android/src/main/java/dev/poolse/callcore/android/MissedCallNotification.kt +103 -0
  21. package/android/src/main/java/dev/poolse/callcore/android/RingBundle.kt +42 -0
  22. package/android/src/main/java/dev/poolse/callcore/android/SnapshotJson.kt +99 -0
  23. package/android/src/main/java/expo/modules/poolsecalls/CallLockscreen.kt +42 -0
  24. package/android/src/main/java/expo/modules/poolsecalls/CallPictureInPicture.kt +92 -0
  25. package/android/src/main/java/expo/modules/poolsecalls/PoolseCallVideoView.kt +64 -0
  26. package/android/src/main/java/expo/modules/poolsecalls/PoolseCallsModule.kt +205 -0
  27. package/android/src/main/livekit/java/dev/poolse/callcore/livekit/LiveKitMediaPort.kt +594 -0
  28. package/android/src/main/livekit/java/dev/poolse/callcore/livekit/LiveKitVideoSurface.kt +107 -0
  29. package/android/src/test/java/dev/poolse/callcore/android/CallHttpClientTest.kt +61 -0
  30. package/app.plugin.js +5 -0
  31. package/dist/index.cjs +197 -0
  32. package/dist/index.cjs.map +1 -0
  33. package/dist/index.d.cts +313 -0
  34. package/dist/index.d.ts +313 -0
  35. package/dist/index.js +161 -0
  36. package/dist/index.js.map +1 -0
  37. package/expo-module.config.json +11 -0
  38. package/ios/Core/CallCoreRuntime.swift +543 -0
  39. package/ios/Core/CallHttpClient.swift +213 -0
  40. package/ios/Core/CallMachine.swift +394 -0
  41. package/ios/Core/PORTS_READY.md +93 -0
  42. package/ios/Core/Ports.swift +238 -0
  43. package/ios/Core/SnapshotEncoding.swift +122 -0
  44. package/ios/Module/PoolseCallVideoView.swift +70 -0
  45. package/ios/Module/PoolseCallsAppDelegateSubscriber.swift +16 -0
  46. package/ios/Module/PoolseCallsModule.swift +150 -0
  47. package/ios/Platform/CallCore.swift +623 -0
  48. package/ios/Platform/CallKitController.swift +326 -0
  49. package/ios/Platform/CallPictureInPicture.swift +145 -0
  50. package/ios/Platform/LiveKitMediaPort.swift +798 -0
  51. package/ios/Platform/LiveKitVideoSurface.swift +68 -0
  52. package/ios/Platform/MessageNotifications.swift +163 -0
  53. package/ios/Platform/Ringback.swift +61 -0
  54. package/ios/Platform/VoipPush.swift +174 -0
  55. package/ios/PoolseCalls.podspec +68 -0
  56. package/package.json +52 -3
  57. package/plugin/index.js +42 -0
  58. package/plugin/package.json +1 -0
  59. package/plugin/withCallDelegate.js +35 -0
  60. package/plugin/withLockscreenCalls.js +84 -0
  61. package/plugin/withNativeCallMedia.js +19 -0
  62. package/plugin/withPictureInPicture.js +28 -0
  63. package/plugin/withRingback.js +86 -0
  64. package/src/expo-modules-core.d.ts +16 -0
  65. package/src/index.ts +564 -0
  66. package/src/react-shims.d.ts +22 -0
@@ -0,0 +1,798 @@
1
+ import AVFoundation
2
+ import os
3
+ import Foundation
4
+ #if canImport(LiveKitClient)
5
+ import LiveKitClient // CocoaPods module name
6
+ #else
7
+ import LiveKit // SwiftPM module name
8
+ #endif
9
+ import UIKit
10
+
11
+ /// Media-level signals the SFU adapter reports back to the core
12
+ /// (CallCore.kt's MediaEvents). Delivered on the main thread.
13
+ protocol MediaEvents: AnyObject {
14
+ func onConnected()
15
+ func onFailed()
16
+ /// Unexpected disconnect — the SFU gave up; the core asks the server and rejoins.
17
+ func onLost()
18
+ /// The SFU is resuming the session itself; only reflected in the UI.
19
+ func onReconnecting()
20
+ func onRecovered()
21
+ func onRemoteJoined()
22
+ /// The REMOTE roster (the local participant excluded).
23
+ func onParticipants(_ participants: [SnapshotParticipant])
24
+ /// `earpiece` | `speaker` | `bluetooth` | `headset`.
25
+ func onAudioRoute(_ route: String)
26
+ /// Every output call audio can play through right now, and the one it does.
27
+ func onAudioOutputs(_ outputs: [AudioOutput], selectedId: String?)
28
+ /// The local camera track is (not) published + enabled; facing `front` | `back`.
29
+ func onLocalCamera(on: Bool, facing: String?)
30
+ /// Our own link to the SFU (`good` | `poor` | `lost` | `unknown`), and
31
+ /// whether incoming video is paused to keep the audio going.
32
+ func onNetwork(quality: String, videoPaused: Bool)
33
+ }
34
+
35
+ /// Step-by-step trace of the audio path, in the device log as
36
+ /// "[PoolseCalls] trace …" — the order of activation, engine availability,
37
+ /// connect and publish is what cold-answer audio failures hinge on.
38
+ ///
39
+ /// os_log with a PUBLIC argument: NSLog's text is redacted to "<private>"
40
+ /// on release builds, which made the first device trace unreadable.
41
+ func pcTrace(_ message: @autoclosure () -> String) {
42
+ os_log("[PoolseCalls] trace %{public}@", log: pcLog, type: .default, message())
43
+ }
44
+
45
+ let pcLog = OSLog(subsystem: "dev.poolse.callcore", category: "calls")
46
+
47
+ func pcSessionDescription(_ s: AVAudioSession = .sharedInstance()) -> String {
48
+ let outs = s.currentRoute.outputs.map { $0.portType.rawValue }.joined(separator: ",")
49
+ let ins = s.currentRoute.inputs.map { $0.portType.rawValue }.joined(separator: ",")
50
+ return "category=\(s.category.rawValue) mode=\(s.mode.rawValue) in=[\(ins)] out=[\(outs)] " +
51
+ "otherAudio=\(s.isOtherAudioPlaying) inputAvailable=\(s.isInputAvailable) " +
52
+ "record=\(s.recordPermission.rawValue)"
53
+ }
54
+
55
+ /// The shipped MediaPort over LiveKit's Swift SDK — LiveKitMediaPort.kt
56
+ /// for iOS. Joins with the server-minted token, publishes the mic (and
57
+ /// the camera for video), tracks the roster and reports room transitions.
58
+ ///
59
+ /// Audio is CallKit's: LiveKit's automatic AVAudioSession handling is off
60
+ /// and its engine is only available between CallKit's didActivate and
61
+ /// didDeactivate (LiveKit's documented CallKit integration).
62
+ ///
63
+ /// Threading: every method is called on main; LiveKit's delegate
64
+ /// callbacks hop to main; async work re-checks that the room it captured
65
+ /// is still the current one.
66
+ final class LiveKitMediaPort: NSObject, MediaPort {
67
+ private weak var events: MediaEvents?
68
+
69
+ private(set) var room: Room?
70
+ private var observer: RoomObserver?
71
+ private var media = "audio"
72
+ /// Speaker unless a headset is in: a video call, or a room (a drop-in
73
+ /// room is held like a meeting, not to the ear).
74
+ private var loud = false
75
+ private var connectedRoom: ObjectIdentifier?
76
+
77
+ /// Where the user asked the audio to go, for the CURRENT call.
78
+ enum OutputChoice: Equatable {
79
+ case speaker
80
+ /// The best private route: Bluetooth, then wired, then the earpiece.
81
+ case privateRoute
82
+ /// The phone itself: earpiece (or wired headphones, which replace it).
83
+ case builtIn
84
+ /// One external input/output pair, by AVAudioSessionPortDescription uid.
85
+ case port(String)
86
+ }
87
+
88
+ /// The user's output choice; nil = automatic (see `resolvedChoice`).
89
+ private var outputWanted: OutputChoice?
90
+ /// The user's choices for the CURRENT call; survive a rejoin.
91
+ private var mutedWanted = false
92
+ private var cameraWanted: Bool?
93
+ private var joinedCallId: String?
94
+
95
+ /// Our own link to the SFU, as last reported.
96
+ private var localQuality = "unknown"
97
+ /// Incoming video is switched off to keep the audio going (see
98
+ /// `qualityChanged`). Survives a rejoin of the same call, like mute.
99
+ private var videoPaused = false
100
+ private var pauseWork: DispatchWorkItem?
101
+ private var resumeWork: DispatchWorkItem?
102
+ /// Weak this long before video is paused; good this long before it is back.
103
+ private static let pauseVideoAfter: TimeInterval = 6
104
+ private static let resumeVideoAfter: TimeInterval = 10
105
+
106
+ private let surfaces = NSHashTable<LiveKitVideoSurface>.weakObjects()
107
+ private var audioPrepared = false
108
+ private var audioActive = false
109
+ /// Asks CallKit to (re)try activating the audio session — set by
110
+ /// CallCore. Used when a room is live but activation never arrived.
111
+ var requestAudioActivation: (() -> Void)?
112
+
113
+ init(events: MediaEvents) {
114
+ self.events = events
115
+ super.init()
116
+ NotificationCenter.default.addObserver(self, selector: #selector(routeChanged),
117
+ name: AVAudioSession.routeChangeNotification, object: nil)
118
+ NotificationCenter.default.addObserver(self, selector: #selector(interrupted),
119
+ name: AVAudioSession.interruptionNotification, object: nil)
120
+ NotificationCenter.default.addObserver(self, selector: #selector(mediaServicesReset),
121
+ name: AVAudioSession.mediaServicesWereResetNotification,
122
+ object: nil)
123
+ }
124
+
125
+ // MARK: - audio session (CallKit-driven)
126
+
127
+ /// Before any room exists: LiveKit must not configure the session nor
128
+ /// start its engine outside CallKit's activation window.
129
+ ///
130
+ /// Called at app LAUNCH (CallCore.init, from the app-delegate
131
+ /// subscriber), as LiveKit's CallKit integration requires — before any
132
+ /// audio session can be activated. Doing it inside didActivate meant a
133
+ /// call answered with the app closed created and reconfigured LiveKit's
134
+ /// audio manager mid-activation, and came up with no audio.
135
+ func prepareAudio() {
136
+ guard !audioPrepared else { return }
137
+ audioPrepared = true
138
+ pcTrace("prepareAudio (automatic config off, engine .none)")
139
+ AudioManager.shared.audioSession.isAutomaticConfigurationEnabled = false
140
+ do { try AudioManager.shared.setEngineAvailability(.none) } catch {
141
+ NSLog("[PoolseCalls] setEngineAvailability(.none) failed: %@", "\(error)")
142
+ }
143
+ }
144
+
145
+ /// CallKit activated the session (or, without CallKit, we did).
146
+ func audioActivated(_ session: AVAudioSession, media: String) {
147
+ pcTrace("audioActivated media=\(media) room=\(room != nil) connected=\(connectedRoom != nil) \(pcSessionDescription(session))")
148
+ prepareAudio()
149
+ audioActive = true
150
+ if media != self.media && room == nil { self.media = media }
151
+ reassertAudio(session)
152
+ }
153
+
154
+ /// Connected with a live mic but CallKit never activated the session
155
+ /// (iOS refused the activation): nudge CallKit to retry — a transaction
156
+ /// on the call makes it attempt activation again (in the device log a
157
+ /// mute toggle did exactly that, and audio came up). Three tries, then
158
+ /// activate the session ourselves as a last resort.
159
+ private func ensureAudioActivated(_ r: Room, attempt: Int) {
160
+ guard room === r, !audioActive else { return }
161
+ let delays: [Double] = [1.2, 2.5, 4.0]
162
+ guard attempt <= delays.count else { return }
163
+ if attempt == delays.count {
164
+ pcTrace("audio never activated by CallKit; activating ourselves")
165
+ activateAudioWithoutCallKit(media: media)
166
+ return
167
+ }
168
+ DispatchQueue.main.asyncAfter(deadline: .now() + delays[attempt]) { [weak self] in
169
+ guard let self = self, self.room === r, !self.audioActive else { return }
170
+ pcTrace("audio not active \(attempt + 1)x after connect; nudging CallKit")
171
+ CallKitController.prepareSessionForCall(video: self.media == "video")
172
+ self.requestAudioActivation?()
173
+ self.ensureAudioActivated(r, attempt: attempt + 1)
174
+ }
175
+ }
176
+
177
+ /// Put the call's audio back the way the call needs it: play-and-record
178
+ /// in the voice/video chat mode, LiveKit's engine available, the chosen
179
+ /// route. Idempotent — only touches what differs — so it is safe to run
180
+ /// whenever anything may have changed the session behind the call's
181
+ /// back (another audio library reconfiguring it as JS boots mid-call,
182
+ /// an interruption, a media-services reset). Only while CallKit (or the
183
+ /// no-CallKit fallback) holds the session active.
184
+ func reassertAudio(_ session: AVAudioSession = .sharedInstance()) {
185
+ guard audioActive else { return }
186
+ pcTrace("reassertAudio before: \(pcSessionDescription(session))")
187
+ let mode: AVAudioSession.Mode = media == "video" && resolvedChoice(session) == .speaker ? .videoChat : .voiceChat
188
+ if session.category != .playAndRecord || session.mode != mode {
189
+ do {
190
+ try session.setCategory(.playAndRecord, mode: mode,
191
+ options: [.allowBluetooth, .allowBluetoothA2DP])
192
+ } catch {
193
+ NSLog("[PoolseCalls] audio session category failed: %@", "\(error)")
194
+ }
195
+ }
196
+ do { try AudioManager.shared.setEngineAvailability(.default) } catch {
197
+ NSLog("[PoolseCalls] setEngineAvailability(.default) failed: %@", "\(error)")
198
+ }
199
+ applyRoute()
200
+ }
201
+
202
+ func audioDeactivated() {
203
+ pcTrace("audioDeactivated")
204
+ audioActive = false
205
+ guard audioPrepared else { return }
206
+ do { try AudioManager.shared.setEngineAvailability(.none) } catch {
207
+ NSLog("[PoolseCalls] setEngineAvailability(.none) failed: %@", "\(error)")
208
+ }
209
+ }
210
+
211
+ /// No CallKit call holds the session (CallKit refused the outgoing
212
+ /// transaction): activate it ourselves so the call still has audio.
213
+ func activateAudioWithoutCallKit(media: String) {
214
+ let s = AVAudioSession.sharedInstance()
215
+ do { try s.setActive(true) } catch { NSLog("[PoolseCalls] session activate failed: %@", "\(error)") }
216
+ audioActivated(s, media: media)
217
+ }
218
+
219
+ // MARK: - MediaPort
220
+
221
+ func join(bundle: CallSessionBundle) {
222
+ pcTrace("join call=\(bundle.callId) media=\(bundle.media) audioActive=\(audioActive)")
223
+ prepareAudio()
224
+ if let joined = joinedCallId, joined != bundle.callId { resetWanted() }
225
+ joinedCallId = bundle.callId
226
+ detach()
227
+ media = bundle.media
228
+ let wantsVideo = bundle.media == "video"
229
+ loud = wantsVideo || bundle.kind == "room"
230
+
231
+ // A 1:1/small call: never let the SFU pause a subscribed camera for
232
+ // "not visible" — a view that mounts late would stay black.
233
+ let r = Room(roomOptions: RoomOptions(adaptiveStream: false, dynacast: false))
234
+ let obs = RoomObserver(port: self, room: r)
235
+ r.add(delegate: obs)
236
+ room = r
237
+ observer = obs
238
+ refreshVideo()
239
+
240
+ let url = bundle.livekitUrl
241
+ let token = bundle.livekitToken
242
+ Task { [weak self] in
243
+ do {
244
+ try await r.connect(url: url, token: token, connectOptions: ConnectOptions(autoSubscribe: true))
245
+ } catch {
246
+ NSLog("[PoolseCalls] LiveKit connect failed: %@", "\(error)")
247
+ await MainActor.run {
248
+ guard let self = self, self.room === r else { return }
249
+ self.room = nil
250
+ self.observer = nil
251
+ self.refreshVideo()
252
+ self.events?.onFailed()
253
+ }
254
+ await r.disconnect()
255
+ return
256
+ }
257
+ let proceed: Bool = await MainActor.run {
258
+ guard let self = self, self.room === r else { return false }
259
+ self.markConnected(r)
260
+ return true
261
+ }
262
+ guard proceed, let self = self else {
263
+ if !proceed { await r.disconnect() }
264
+ return
265
+ }
266
+ let muted = await MainActor.run { self.mutedWanted }
267
+ let activeNow = await MainActor.run { self.audioActive }
268
+ pcTrace("connected; publishing mic muted=\(muted) audioActive=\(activeNow)")
269
+ do { try await r.localParticipant.setMicrophone(enabled: !muted) } catch {
270
+ NSLog("[PoolseCalls] microphone publish failed: %@", "\(error)")
271
+ }
272
+ // Connected and publishing: make sure nothing changed the session
273
+ pcTrace("mic published enabled=\(r.localParticipant.isMicrophoneEnabled()) \(pcSessionDescription())")
274
+ // while we connected (a cold answer boots JS in exactly this window),
275
+ // then make sure the engine is actually carrying the mic.
276
+ await MainActor.run {
277
+ self.reassertAudio()
278
+ self.ensureAudioActivated(r, attempt: 0)
279
+ }
280
+ let camera = await MainActor.run { self.cameraWanted ?? wantsVideo }
281
+ if camera { await self.enableCamera(r, true) }
282
+ await MainActor.run {
283
+ self.reportLocalCamera(r)
284
+ self.refreshVideo()
285
+ }
286
+ }
287
+ }
288
+
289
+ /// Connected (once per room): the core moves on; anyone already in is "joined".
290
+ private func markConnected(_ r: Room) {
291
+ guard room === r, connectedRoom != ObjectIdentifier(r) else { return }
292
+ connectedRoom = ObjectIdentifier(r)
293
+ if outputWanted != nil { applyRoute() }
294
+ events?.onConnected()
295
+ if !r.remoteParticipants.isEmpty { events?.onRemoteJoined() }
296
+ emit(r)
297
+ refreshVideo()
298
+ }
299
+
300
+ private func cameraGranted() -> Bool {
301
+ AVCaptureDevice.authorizationStatus(for: .video) == .authorized
302
+ }
303
+
304
+ /// Without the camera grant a video call joins audio-only; a later
305
+ /// setCamera(true) after the user grants it publishes then.
306
+ private func enableCamera(_ r: Room, _ on: Bool) async {
307
+ if on && !cameraGranted() {
308
+ NSLog("[PoolseCalls] camera not authorized: staying audio-only")
309
+ return
310
+ }
311
+ do {
312
+ try await r.localParticipant.setCamera(enabled: on, captureOptions: on ? CameraCaptureOptions(position: .front) : nil)
313
+ } catch {
314
+ NSLog("[PoolseCalls] camera %@ failed: %@", on ? "publish" : "unpublish", "\(error)")
315
+ }
316
+ }
317
+
318
+ func leave() {
319
+ detach()
320
+ resetWanted()
321
+ joinedCallId = nil
322
+ }
323
+
324
+ private func resetWanted() {
325
+ mutedWanted = false
326
+ cameraWanted = nil
327
+ outputWanted = nil
328
+ pauseWork?.cancel()
329
+ resumeWork?.cancel()
330
+ pauseWork = nil
331
+ resumeWork = nil
332
+ videoPaused = false
333
+ localQuality = "unknown"
334
+ reportNetwork()
335
+ }
336
+
337
+ private func detach() {
338
+ guard let r = room else { return }
339
+ if let obs = observer { r.remove(delegate: obs) }
340
+ room = nil
341
+ observer = nil
342
+ connectedRoom = nil
343
+ // Their timers belong to that room; the next one starts its own.
344
+ pauseWork?.cancel()
345
+ resumeWork?.cancel()
346
+ pauseWork = nil
347
+ resumeWork = nil
348
+ refreshVideo()
349
+ Task { await r.disconnect() }
350
+ events?.onLocalCamera(on: false, facing: nil)
351
+ }
352
+
353
+ func setMuted(_ muted: Bool) {
354
+ mutedWanted = muted
355
+ guard let r = room, connectedRoom == ObjectIdentifier(r) else { return }
356
+ Task { _ = try? await r.localParticipant.setMicrophone(enabled: !muted) }
357
+ }
358
+
359
+ func setCamera(_ on: Bool) {
360
+ cameraWanted = on
361
+ guard let r = room, connectedRoom == ObjectIdentifier(r) else { return }
362
+ Task { [weak self] in
363
+ await self?.enableCamera(r, on)
364
+ await MainActor.run {
365
+ guard let self = self, self.room === r else { return }
366
+ self.reportLocalCamera(r)
367
+ self.refreshVideo()
368
+ }
369
+ }
370
+ }
371
+
372
+ func switchCamera() {
373
+ guard let r = room, let track = localCameraTrack(r), let capturer = track.capturer as? CameraCapturer else { return }
374
+ Task { [weak self] in
375
+ do { _ = try await capturer.switchCameraPosition() } catch {
376
+ NSLog("[PoolseCalls] switchCamera failed: %@", "\(error)")
377
+ }
378
+ await MainActor.run {
379
+ guard let self = self, self.room === r else { return }
380
+ self.reportLocalCamera(r)
381
+ self.refreshVideo()
382
+ }
383
+ }
384
+ }
385
+
386
+ func setSpeaker(_ on: Bool) {
387
+ outputWanted = on ? .speaker : .privateRoute
388
+ applyRoute()
389
+ }
390
+
391
+ /// An id from the snapshot's `audioOutputs`: `speaker`, `earpiece`,
392
+ /// `wired`, or `port:<uid>`. An id that is no longer connected is ignored.
393
+ func setAudioOutput(_ id: String) {
394
+ switch id {
395
+ case "speaker": outputWanted = .speaker
396
+ case "earpiece", "wired": outputWanted = .builtIn
397
+ default:
398
+ guard id.hasPrefix("port:") else { return }
399
+ let uid = String(id.dropFirst("port:".count))
400
+ // An output with no matching input (an A2DP-only speaker) cannot be
401
+ // chosen through the session; the system's own route wins there.
402
+ outputWanted = selectablePort(uid) != nil ? .port(uid) : .privateRoute
403
+ }
404
+ applyRoute()
405
+ }
406
+
407
+ // MARK: - audio routing
408
+
409
+ private static let externalInputs: Set<AVAudioSession.Port> =
410
+ [.bluetoothHFP, .bluetoothLE, .carAudio, .usbAudio, .headsetMic]
411
+ private static let externalOutputs: Set<AVAudioSession.Port> =
412
+ [.bluetoothHFP, .bluetoothA2DP, .bluetoothLE, .carAudio, .usbAudio, .headphones, .airPlay, .lineOut, .HDMI]
413
+
414
+ private func selectablePort(_ uid: String, _ s: AVAudioSession = .sharedInstance()) -> AVAudioSessionPortDescription? {
415
+ s.availableInputs?.first { $0.uid == uid && Self.externalInputs.contains($0.portType) }
416
+ }
417
+
418
+ /// A headset, Bluetooth device or car is connected — something the
419
+ /// user put on or plugged in, which should carry the call by default.
420
+ private func externalConnected(_ s: AVAudioSession) -> Bool {
421
+ (s.availableInputs ?? []).contains { Self.externalInputs.contains($0.portType) && $0.portType != .usbAudio }
422
+ || s.currentRoute.outputs.contains { Self.externalOutputs.contains($0.portType) }
423
+ }
424
+
425
+ /// What the call should do now. Automatic: a voice call is held to the
426
+ /// ear and a video call uses the loudspeaker — unless a headset or
427
+ /// Bluetooth device is connected, which wins either way (FaceTime does
428
+ /// the same; forcing the speaker over AirPods was a bug).
429
+ private func resolvedChoice(_ s: AVAudioSession = .sharedInstance()) -> OutputChoice {
430
+ if let wanted = outputWanted { return wanted }
431
+ return loud && !externalConnected(s) ? .speaker : .privateRoute
432
+ }
433
+
434
+ private func applyRoute() {
435
+ guard audioActive else { return }
436
+ let s = AVAudioSession.sharedInstance()
437
+ if case .port(let uid) = outputWanted, selectablePort(uid, s) == nil { outputWanted = nil }
438
+ let choice = resolvedChoice(s)
439
+ do {
440
+ switch choice {
441
+ case .speaker:
442
+ try s.overrideOutputAudioPort(.speaker)
443
+ case .privateRoute:
444
+ try leaveSpeaker(s)
445
+ if s.preferredInput != nil { try s.setPreferredInput(nil) }
446
+ case .builtIn:
447
+ try leaveSpeaker(s)
448
+ let mic = s.availableInputs?.first { $0.portType == .builtInMic }
449
+ if let mic = mic, s.preferredInput?.uid != mic.uid { try s.setPreferredInput(mic) }
450
+ case .port(let uid):
451
+ try leaveSpeaker(s)
452
+ if let port = selectablePort(uid, s), s.preferredInput?.uid != uid { try s.setPreferredInput(port) }
453
+ }
454
+ } catch {
455
+ NSLog("[PoolseCalls] audio route failed: %@", "\(error)")
456
+ }
457
+ reportRoute()
458
+ }
459
+
460
+ /// .videoChat forces the speaker; every private route needs .voiceChat.
461
+ private func leaveSpeaker(_ s: AVAudioSession) throws {
462
+ if s.mode == .videoChat { try s.setMode(.voiceChat) }
463
+ try s.overrideOutputAudioPort(.none)
464
+ }
465
+
466
+ private func kind(of port: AVAudioSession.Port) -> String {
467
+ switch port {
468
+ case .builtInSpeaker: return "speaker"
469
+ case .builtInReceiver: return "earpiece"
470
+ case .bluetoothHFP, .bluetoothA2DP, .bluetoothLE, .carAudio, .airPlay: return "bluetooth"
471
+ default: return "headset"
472
+ }
473
+ }
474
+
475
+ private func currentRoute() -> String {
476
+ guard let port = AVAudioSession.sharedInstance().currentRoute.outputs.first?.portType else {
477
+ return loud ? "speaker" : "earpiece"
478
+ }
479
+ return kind(of: port)
480
+ }
481
+
482
+ /// Every output the user can pick, and the one playing now.
483
+ ///
484
+ /// iOS lists inputs, not outputs: a headset or Bluetooth device is
485
+ /// selectable through its microphone (its input and output share the
486
+ /// uid), while the earpiece and speaker are always there on a phone.
487
+ /// Wired headphones replace the earpiece rather than sitting beside it.
488
+ private func outputs() -> ([AudioOutput], String?) {
489
+ let s = AVAudioSession.sharedInstance()
490
+ let inputs = s.availableInputs ?? []
491
+ let current = s.currentRoute.outputs.first
492
+ var list: [AudioOutput] = []
493
+
494
+ let wiredOut = s.currentRoute.outputs.first { $0.portType == .headphones }
495
+ if inputs.contains(where: { $0.portType == .headsetMic }) || wiredOut != nil {
496
+ list.append(AudioOutput(id: "wired", kind: "headset", name: "Headphones"))
497
+ } else if UIDevice.current.userInterfaceIdiom == .phone {
498
+ list.append(AudioOutput(id: "earpiece", kind: "earpiece", name: UIDevice.current.model))
499
+ }
500
+ list.append(AudioOutput(id: "speaker", kind: "speaker", name: "Speaker"))
501
+ for p in inputs where Self.externalInputs.contains(p.portType) && p.portType != .headsetMic {
502
+ list.append(AudioOutput(id: "port:\(p.uid)", kind: p.portType == .usbAudio ? "headset" : "bluetooth", name: p.portName))
503
+ }
504
+ // Playing through something with no microphone (an A2DP speaker,
505
+ // AirPlay): show it so the selection is truthful, even though only
506
+ // the system picker can choose it.
507
+ if let c = current, Self.externalOutputs.contains(c.portType), c.portType != .headphones,
508
+ !list.contains(where: { $0.id == "port:\(c.uid)" || $0.name == c.portName }) {
509
+ list.append(AudioOutput(id: "port:\(c.uid)", kind: kind(of: c.portType), name: c.portName))
510
+ }
511
+
512
+ let selected: String? = current.map { c in
513
+ switch c.portType {
514
+ case .builtInSpeaker: return "speaker"
515
+ case .builtInReceiver: return "earpiece"
516
+ case .headphones: return "wired"
517
+ default:
518
+ return list.first { $0.id == "port:\(c.uid)" }?.id
519
+ ?? list.first { $0.name == c.portName }?.id
520
+ ?? "port:\(c.uid)"
521
+ }
522
+ }
523
+ return (list, selected)
524
+ }
525
+
526
+ private func reportRoute() {
527
+ guard joinedCallId != nil || audioActive else { return }
528
+ events?.onAudioRoute(currentRoute())
529
+ let (list, selected) = outputs()
530
+ events?.onAudioOutputs(list, selectedId: selected)
531
+ }
532
+
533
+ /// An interruption (another app's audio, Siri) ended: the session may
534
+ /// have been reconfigured; restore the call's.
535
+ @objc private func interrupted(_ note: Notification) {
536
+ pcTrace("interruption \(note.userInfo ?? [:])")
537
+ guard let raw = note.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
538
+ AVAudioSession.InterruptionType(rawValue: raw) == .ended else { return }
539
+ DispatchQueue.main.async { [weak self] in self?.reassertAudio() }
540
+ }
541
+
542
+ @objc private func mediaServicesReset(_ note: Notification) {
543
+ pcTrace("mediaServicesWereReset")
544
+ DispatchQueue.main.async { [weak self] in self?.reassertAudio() }
545
+ }
546
+
547
+ @objc private func routeChanged(_ note: Notification) {
548
+ let reason = (note.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt)
549
+ .flatMap(AVAudioSession.RouteChangeReason.init(rawValue:))
550
+ pcTrace("routeChange reason=\(reason.map { String($0.rawValue) } ?? "?") \(pcSessionDescription())")
551
+ DispatchQueue.main.async { [weak self] in
552
+ guard let self = self, self.audioActive else { return }
553
+ // Something reconfigured the shared session mid-call: put it back.
554
+ if reason == .categoryChange {
555
+ self.reassertAudio()
556
+ return
557
+ }
558
+ switch reason {
559
+ case .newDeviceAvailable:
560
+ // Putting on a headset or AirPods mid-call moves the call to it,
561
+ // whatever was picked before — as the Phone app does.
562
+ self.outputWanted = nil
563
+ self.applyRoute()
564
+ case .oldDeviceUnavailable:
565
+ // A device went away. If it was the chosen one, applyRoute drops
566
+ // the choice and falls back to automatic — speaker for video,
567
+ // earpiece for voice; any other choice stands.
568
+ self.applyRoute()
569
+ default:
570
+ // The override is cleared by any route change: put the speaker
571
+ // back (or take it away) if that is not what the call wants.
572
+ let onSpeaker = self.currentRoute() == "speaker"
573
+ if (self.resolvedChoice() == .speaker) != onSpeaker && reason != .override {
574
+ self.applyRoute()
575
+ } else {
576
+ self.reportRoute()
577
+ }
578
+ }
579
+ }
580
+ }
581
+
582
+ // MARK: - video
583
+
584
+ func createVideoSurface(renderMode: VideoView.RenderMode = .auto) -> LiveKitVideoSurface {
585
+ let s = LiveKitVideoSurface(port: self, renderMode: renderMode)
586
+ surfaces.add(s)
587
+ return s
588
+ }
589
+
590
+ func unregister(_ s: LiveKitVideoSurface) { surfaces.remove(s) }
591
+
592
+ private func refreshVideo() {
593
+ for s in surfaces.allObjects { s.rebind() }
594
+ }
595
+
596
+ private func localCameraTrack(_ r: Room) -> LocalVideoTrack? {
597
+ guard let pub = r.localParticipant.trackPublications.values.first(where: { $0.source == .camera }), !pub.isMuted else { return nil }
598
+ return pub.track as? LocalVideoTrack
599
+ }
600
+
601
+ /// The local camera, or a remote's — only once published, SUBSCRIBED and unmuted.
602
+ func cameraTrack(participantId: String?, local: Bool) -> VideoTrack? {
603
+ guard let r = room else { return nil }
604
+ if local { return localCameraTrack(r) }
605
+ guard let id = participantId,
606
+ let p = r.remoteParticipants.values.first(where: { $0.identity?.stringValue == id }) else { return nil }
607
+ return remoteCamera(p)
608
+ }
609
+
610
+ private func remoteCamera(_ p: RemoteParticipant) -> VideoTrack? {
611
+ // Paused: no picture to draw — the avatar shows, with the reason.
612
+ guard !videoPaused, let pub = p.trackPublications.values.first(where: { $0.source == .camera }) as? RemoteTrackPublication,
613
+ pub.isSubscribed, !pub.isMuted else { return nil }
614
+ return pub.track as? VideoTrack
615
+ }
616
+
617
+ /// `front` | `back` of the published local camera, or nil when none.
618
+ func cameraFacing() -> String? {
619
+ guard let r = room, let track = localCameraTrack(r) else { return nil }
620
+ return (track.capturer as? CameraCapturer)?.position == .back ? "back" : "front"
621
+ }
622
+
623
+ private func reportLocalCamera(_ r: Room) {
624
+ guard room === r else { return }
625
+ let on = localCameraTrack(r) != nil
626
+ events?.onLocalCamera(on: on, facing: on ? cameraFacing() : nil)
627
+ }
628
+
629
+ // MARK: - room events (main thread, via RoomObserver)
630
+
631
+ fileprivate func roomEvent(_ r: Room, _ kind: RoomObserver.Kind) {
632
+ guard room === r else { return }
633
+ switch kind {
634
+ case .connected:
635
+ markConnected(r)
636
+ case .reconnecting:
637
+ events?.onReconnecting()
638
+ case .reconnected:
639
+ events?.onRecovered()
640
+ case .disconnected:
641
+ events?.onLost()
642
+ case .participantJoined:
643
+ events?.onRemoteJoined()
644
+ emit(r)
645
+ refreshVideo()
646
+ case .tracksChanged:
647
+ if videoPaused { applyVideoPause(r) }
648
+ emit(r)
649
+ reportLocalCamera(r)
650
+ refreshVideo()
651
+ case .rosterChanged:
652
+ emit(r)
653
+ case .quality:
654
+ qualityChanged(r)
655
+ emit(r)
656
+ }
657
+ }
658
+
659
+ // MARK: - connection quality
660
+
661
+ static func wire(_ q: ConnectionQuality) -> String {
662
+ switch q {
663
+ case .excellent, .good: return "good"
664
+ case .poor: return "poor"
665
+ case .lost: return "lost"
666
+ default: return "unknown"
667
+ }
668
+ }
669
+
670
+ /// Our link went weak or came back. Weak for a while on a call with
671
+ /// video coming in: switch that video off so the audio keeps going —
672
+ /// the way FaceTime falls back — and bring it back once the link has
673
+ /// been good for a while. Brief dips change nothing.
674
+ private func qualityChanged(_ r: Room) {
675
+ guard room === r else { return }
676
+ let q = Self.wire(r.localParticipant.connectionQuality)
677
+ if q == "poor" || q == "lost" {
678
+ resumeWork?.cancel()
679
+ resumeWork = nil
680
+ if !videoPaused && pauseWork == nil && hasRemoteVideo(r) {
681
+ let w = DispatchWorkItem { [weak self, weak r] in
682
+ guard let self = self, let r = r, self.room === r else { return }
683
+ self.pauseWork = nil
684
+ self.setVideoPaused(r, true)
685
+ }
686
+ pauseWork = w
687
+ DispatchQueue.main.asyncAfter(deadline: .now() + Self.pauseVideoAfter, execute: w)
688
+ }
689
+ } else if q == "good" {
690
+ pauseWork?.cancel()
691
+ pauseWork = nil
692
+ if videoPaused && resumeWork == nil {
693
+ let w = DispatchWorkItem { [weak self, weak r] in
694
+ guard let self = self, let r = r, self.room === r else { return }
695
+ self.resumeWork = nil
696
+ self.setVideoPaused(r, false)
697
+ }
698
+ resumeWork = w
699
+ DispatchQueue.main.asyncAfter(deadline: .now() + Self.resumeVideoAfter, execute: w)
700
+ }
701
+ }
702
+ if q != localQuality {
703
+ localQuality = q
704
+ reportNetwork()
705
+ }
706
+ }
707
+
708
+ private func hasRemoteVideo(_ r: Room) -> Bool {
709
+ r.remoteParticipants.values.contains { p in p.trackPublications.values.contains { $0.source == .camera } }
710
+ }
711
+
712
+ private func setVideoPaused(_ r: Room, _ paused: Bool) {
713
+ pcTrace("incoming video \(paused ? "paused" : "resumed") quality=\(localQuality)")
714
+ videoPaused = paused
715
+ applyVideoPause(r)
716
+ refreshVideo()
717
+ emit(r)
718
+ reportNetwork()
719
+ }
720
+
721
+ /// Every remote camera on or off to match `videoPaused` — including
722
+ /// one published after the pause began.
723
+ private func applyVideoPause(_ r: Room) {
724
+ let enabled = !videoPaused
725
+ for p in r.remoteParticipants.values {
726
+ for case let pub as RemoteTrackPublication in p.trackPublications.values
727
+ where pub.source == .camera && pub.isEnabled != enabled {
728
+ Task { try? await pub.set(enabled: enabled) }
729
+ }
730
+ }
731
+ }
732
+
733
+ private func reportNetwork() {
734
+ events?.onNetwork(quality: localQuality, videoPaused: videoPaused)
735
+ }
736
+
737
+ /// The REMOTE roster — the local participant is never included.
738
+ private func emit(_ r: Room) {
739
+ let roster = r.remoteParticipants.values.map { p -> SnapshotParticipant in
740
+ let identity = p.identity?.stringValue ?? ""
741
+ return SnapshotParticipant(
742
+ userId: identity,
743
+ externalId: externalId(p) ?? identity,
744
+ speaking: p.isSpeaking,
745
+ muted: !p.isMicrophoneEnabled(),
746
+ cameraOn: remoteCamera(p) != nil,
747
+ connectionQuality: Self.wire(p.connectionQuality)
748
+ )
749
+ }
750
+ events?.onParticipants(roster)
751
+ }
752
+
753
+ /// The host's own user id, if the server put it in attributes/metadata.
754
+ private func externalId(_ p: Participant) -> String? {
755
+ if let v = p.attributes["external_id"], !v.isEmpty { return v }
756
+ guard let m = p.metadata, let d = m.data(using: .utf8),
757
+ let obj = (try? JSONSerialization.jsonObject(with: d)) as? [String: Any],
758
+ let v = obj["external_id"] as? String, !v.isEmpty else { return nil }
759
+ return v
760
+ }
761
+ }
762
+
763
+ /// LiveKit's delegate → main-thread room events for the port.
764
+ final class RoomObserver: NSObject, RoomDelegate, @unchecked Sendable {
765
+ enum Kind { case connected, reconnecting, reconnected, disconnected, participantJoined, tracksChanged, rosterChanged, quality }
766
+
767
+ private weak var port: LiveKitMediaPort?
768
+ private weak var room: Room?
769
+
770
+ init(port: LiveKitMediaPort, room: Room) {
771
+ self.port = port
772
+ self.room = room
773
+ }
774
+
775
+ private func send(_ r: Room, _ kind: Kind) {
776
+ DispatchQueue.main.async { [weak self] in self?.port?.roomEvent(r, kind) }
777
+ }
778
+
779
+ func roomDidConnect(_ room: Room) { send(room, .connected) }
780
+ func room(_ room: Room, didStartReconnectWithMode reconnectMode: ReconnectMode) { send(room, .reconnecting) }
781
+ func room(_ room: Room, didCompleteReconnectWithMode reconnectMode: ReconnectMode) { send(room, .reconnected) }
782
+ // Our own leave() removes this delegate before disconnecting, so any
783
+ // disconnect seen here is the SFU giving up (or the server removing us).
784
+ func room(_ room: Room, didDisconnectWithError error: LiveKitError?) { send(room, .disconnected) }
785
+ func room(_ room: Room, participantDidConnect participant: RemoteParticipant) { send(room, .participantJoined) }
786
+ func room(_ room: Room, participantDidDisconnect participant: RemoteParticipant) { send(room, .tracksChanged) }
787
+ func room(_ room: Room, participant: RemoteParticipant, didSubscribeTrack publication: RemoteTrackPublication) { send(room, .tracksChanged) }
788
+ func room(_ room: Room, participant: RemoteParticipant, didUnsubscribeTrack publication: RemoteTrackPublication) { send(room, .tracksChanged) }
789
+ func room(_ room: Room, participant: RemoteParticipant, didPublishTrack publication: RemoteTrackPublication) { send(room, .tracksChanged) }
790
+ func room(_ room: Room, participant: RemoteParticipant, didUnpublishTrack publication: RemoteTrackPublication) { send(room, .tracksChanged) }
791
+ func room(_ room: Room, participant: LocalParticipant, didPublishTrack publication: LocalTrackPublication) { send(room, .tracksChanged) }
792
+ func room(_ room: Room, participant: LocalParticipant, didUnpublishTrack publication: LocalTrackPublication) { send(room, .tracksChanged) }
793
+ func room(_ room: Room, participant: Participant, trackPublication: TrackPublication, didUpdateIsMuted isMuted: Bool) { send(room, .tracksChanged) }
794
+ func room(_ room: Room, didUpdateSpeakingParticipants participants: [Participant]) { send(room, .rosterChanged) }
795
+ func room(_ room: Room, participant: Participant, didUpdateMetadata metadata: String?) { send(room, .rosterChanged) }
796
+ func room(_ room: Room, participant: Participant, didUpdateAttributes attributes: [String: String]) { send(room, .rosterChanged) }
797
+ func room(_ room: Room, participant: Participant, didUpdateConnectionQuality quality: ConnectionQuality) { send(room, .quality) }
798
+ }