Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(ios): call improvements (#4123)

Peter Chinman8dbd360f4ba2
diff --git a/js/app/packages/channel/Call/CallContext.tsx b/js/app/packages/channel/Call/CallContext.tsx
index daa62839df..467cdbf656 100644
--- a/js/app/packages/channel/Call/CallContext.tsx
+++ b/js/app/packages/channel/Call/CallContext.tsx
@@ -884,6 +884,7 @@ function createCallState() {
const currentActiveChannelId = () =>
currentNativeCallSnapshot()?.channelId ??
+ nativeCall?.bootstrapChannelId() ??
store.activeChannelId ??
store.optimisticJoinChannelId;
@@ -898,10 +899,14 @@ function createCallState() {
const currentIsInCall = () =>
isActiveCallConnectionState(currentConnectionState()) ||
+ (currentNativeCallSnapshot() === null &&
+ (nativeCall?.bootstrapChannelId() ?? null) !== null) ||
(currentNativeCallSnapshot() === null &&
store.optimisticJoinChannelId !== null);
const currentIsConnecting = () =>
+ (currentNativeCallSnapshot() === null &&
+ (nativeCall?.bootstrapChannelId() ?? null) !== null) ||
(currentNativeCallSnapshot() === null &&
store.optimisticJoinChannelId !== null) ||
currentConnectionState() === ConnectionState.Connecting ||
@@ -993,6 +998,10 @@ function createCallState() {
nativeCall,
jsConnect: livekitJs.connect,
jsDisconnect: livekitJs.disconnect,
+ clearOptimisticJoin: () => {
+ setStore('optimisticJoinChannelId', null);
+ setStore('joinError', null);
+ },
});
async function toggleAudio() {
diff --git a/js/app/packages/channel/Call/CallSessionController.ts b/js/app/packages/channel/Call/CallSessionController.ts
index 4cc5aa95fe..84bb1f3ffb 100644
--- a/js/app/packages/channel/Call/CallSessionController.ts
+++ b/js/app/packages/channel/Call/CallSessionController.ts
@@ -10,6 +10,7 @@ type CallSessionControllerOptions = {
nativeCall: NativeCallState | undefined;
jsConnect: (tokenResponse: CallTokenResponse) => Promise<void>;
jsDisconnect: () => Promise<void>;
+ clearOptimisticJoin: () => void;
};
export type CallSessionConnectMetadata = {
@@ -41,6 +42,7 @@ export function createCallSessionController(
return createNativeCallKitSessionController({
nativeCall: options.nativeCall,
jsDisconnect: options.jsDisconnect,
+ clearOptimisticJoin: options.clearOptimisticJoin,
});
}
@@ -64,6 +66,7 @@ function createJsLivekitSessionController(options: {
function createNativeCallKitSessionController(options: {
nativeCall: NativeCallState;
jsDisconnect: () => Promise<void>;
+ clearOptimisticJoin: () => void;
}): CallSessionController {
return {
shouldRequestToken: (channelId) => {
@@ -87,9 +90,9 @@ function createNativeCallKitSessionController(options: {
return !shouldSkip;
},
- connectWithToken: (tokenResponse, metadata) => {
+ connectWithToken: async (tokenResponse, metadata) => {
const channelTitle = metadata?.channelTitle ?? null;
- return startNativeCallKitOutgoingCall(
+ await startNativeCallKitOutgoingCall(
{
channelId: tokenResponse.channelId,
callId: tokenResponse.callId,
@@ -100,6 +103,7 @@ function createNativeCallKitSessionController(options: {
},
options.nativeCall
);
+ options.clearOptimisticJoin();
},
disconnect: async (disconnectOptions) => {
if (disconnectOptions?.endNativeCall !== false) {
@@ -110,6 +114,7 @@ function createNativeCallKitSessionController(options: {
}
}
await options.jsDisconnect();
+ options.clearOptimisticJoin();
},
};
}
diff --git a/js/app/packages/channel/Call/use-callkit.ts b/js/app/packages/channel/Call/use-callkit.ts
index 3a666aed23..50e37c7500 100644
--- a/js/app/packages/channel/Call/use-callkit.ts
+++ b/js/app/packages/channel/Call/use-callkit.ts
@@ -76,6 +76,12 @@ type NativeParticipantDisplayNames =
errors: unknown[];
};
+function refreshActiveCallQueriesAfterLeave() {
+ void invalidateActiveCallQueries().catch((err) =>
+ console.error('[callkit] failed to refresh active call state', err)
+ );
+}
+
function applyConnectionState(
nativeCall: NativeCallState,
payload: ConnectionStatePayload
@@ -89,6 +95,9 @@ function applyConnectionState(
nativeCall.setBootstrapChannelId(null);
nativeCall.setParticipantIdentities([]);
nativeCall.setSnapshot(null);
+ if (payload.state === 'disconnected') {
+ refreshActiveCallQueriesAfterLeave();
+ }
return;
}
const snapshot: NativeCallSnapshot = {
@@ -336,16 +345,14 @@ export function useCallKitSetup() {
(payload) => {
console.info('[callkit] call ended event', payload);
lastHandledAnsweredCall = undefined;
+ refreshActiveCallQueriesAfterLeave();
nativeCall.setBootstrapChannelId(null);
nativeCall.setParticipantIdentities([]);
const handler = getActiveCallEndedHandler();
if (!handler) {
- // No channel call UI is mounted to run the full leave flow; refetch
- // active-call state so the channel still reflects the ongoing call.
console.warn(
'[callkit] no call-ended handler registered; invalidating active call queries'
);
- void invalidateActiveCallQueries();
return;
}
Promise.resolve(handler(payload)).catch((err) =>
diff --git a/js/app/tauri/callkit_plugin/ios/Sources/CallAudioRouteController.swift b/js/app/tauri/callkit_plugin/ios/Sources/CallAudioRouteController.swift
index ea2f082952..4c82f82d83 100644
--- a/js/app/tauri/callkit_plugin/ios/Sources/CallAudioRouteController.swift
+++ b/js/app/tauri/callkit_plugin/ios/Sources/CallAudioRouteController.swift
@@ -6,6 +6,7 @@ enum CallAudioOutputRoute: String {
case speaker
case bluetooth
case headphones
+ case external
case unknown
}
@@ -16,7 +17,7 @@ enum CallAudioInputRoute: String {
case unknown
}
-struct CallAudioRouteSnapshot {
+struct CallAudioRouteSnapshot: Equatable {
let input: CallAudioInputRoute
let output: CallAudioOutputRoute
let isSpeakerForced: Bool
@@ -86,7 +87,7 @@ final class CallAudioRouteController: NSObject, @unchecked Sendable {
func setSpeakerEnabled(_ enabled: Bool) {
onMain { [weak self] in
- self?.setSpeakerEnabledOnMain(enabled, isUserSelection: true)
+ _ = self?.setSpeakerEnabledOnMain(enabled, isUserSelection: true)
}
}
@@ -98,25 +99,34 @@ final class CallAudioRouteController: NSObject, @unchecked Sendable {
}
}
- func defaultToSpeakerIfBuiltInRoute(reason: String) {
- onMain { [weak self] in
- self?.defaultToSpeakerIfBuiltInRouteOnMain(reason: reason)
+ func defaultToSpeakerIfBuiltInRoute(reason: String) -> Bool {
+ onMainSync {
+ defaultToSpeakerIfBuiltInRouteOnMain(reason: reason)
}
}
- private func defaultToSpeakerIfBuiltInRouteOnMain(reason: String) {
- guard preferredBuiltInSpeakerEnabled != false else { return }
- guard !isExternalRouteAvailable() else {
- print("[CallKit] Skipping built-in speaker default because external route is available reason=\(reason) available=\(describeAvailableRoutes()) current=\(describeCurrentRoute())")
- return
+ func canDefaultToSpeakerIfBuiltInRoute() -> Bool {
+ onMainSync {
+ shouldDefaultToSpeakerAfterRouteChange(reason: "sessionDefaultCheck")
+ }
+ }
+
+ private func defaultToSpeakerIfBuiltInRouteOnMain(reason: String) -> Bool {
+ guard preferredBuiltInSpeakerEnabled != false else { return false }
+ guard !isCurrentExternalOutputRoute() else {
+ print("[CallKit] Skipping built-in speaker default because external route is active reason=\(reason) available=\(describeAvailableRoutes()) current=\(describeCurrentRoute())")
+ return false
}
let snapshot = currentSnapshotOnMain()
- guard snapshot.supportsSpeakerToggle, snapshot.output != .speaker else { return }
+ guard snapshot.supportsSpeakerToggle else { return false }
+ if snapshot.output == .speaker, isSpeakerForced {
+ return true
+ }
print("[CallKit] Defaulting built-in audio route to speaker reason=\(reason) output=\(snapshot.output.rawValue)")
- setSpeakerEnabledOnMain(true, isUserSelection: false)
+ return setSpeakerEnabledOnMain(true, isUserSelection: false)
}
- private func setSpeakerEnabledOnMain(_ enabled: Bool, isUserSelection: Bool) {
+ private func setSpeakerEnabledOnMain(_ enabled: Bool, isUserSelection: Bool) -> Bool {
let session = AVAudioSession.sharedInstance()
let snapshot = currentSnapshotOnMain()
if snapshot.output == .unknown {
@@ -126,7 +136,7 @@ final class CallAudioRouteController: NSObject, @unchecked Sendable {
isSpeakerForced = enabled
print("[CallKit] Queued audio route speaker preference enabled=\(enabled) userSelection=\(isUserSelection); current route is not ready \(describeCurrentRoute())")
emitCurrentRouteOnMain()
- return
+ return false
}
do {
@@ -138,8 +148,10 @@ final class CallAudioRouteController: NSObject, @unchecked Sendable {
print("[CallKit] Audio route speaker override enabled=\(enabled) userSelection=\(isUserSelection) \(describeCurrentRoute())")
print("[CallKit] Audio route available after speaker override \(describeAvailableRoutes())")
emitCurrentRouteOnMain()
+ return true
} catch {
print("[CallKit] Failed to set audio route speaker override enabled=\(enabled): \(error) \(describeCurrentRoute())")
+ return false
}
}
@@ -152,7 +164,7 @@ final class CallAudioRouteController: NSObject, @unchecked Sendable {
private func resetSpeakerOverrideOnMain() {
preferredBuiltInSpeakerEnabled = nil
guard isSpeakerForced else { return }
- setSpeakerEnabledOnMain(false, isUserSelection: false)
+ _ = setSpeakerEnabledOnMain(false, isUserSelection: false)
}
func emitCurrentRoute() {
@@ -178,10 +190,15 @@ final class CallAudioRouteController: NSObject, @unchecked Sendable {
private func currentSnapshotOnMain() -> CallAudioRouteSnapshot {
let route = AVAudioSession.sharedInstance().currentRoute
let output = classifyOutput(route.outputs.first)
- let supportsSpeakerToggle = output == .receiver || output == .speaker || (output == .unknown && !isExternalRouteAvailable())
+ let supportsSpeakerToggle = switch output {
+ case .receiver, .speaker, .unknown:
+ true
+ case .bluetooth, .headphones, .external:
+ false
+ }
let snapshotSpeakerForced = isSpeakerForced
&& supportsSpeakerToggle
- && (output == .speaker || output == .unknown)
+ && (output == .speaker || output == .receiver || output == .unknown)
return CallAudioRouteSnapshot(
input: classifyInput(route.inputs.first),
@@ -205,20 +222,31 @@ final class CallAudioRouteController: NSObject, @unchecked Sendable {
if shouldReleaseSpeakerOverrideForExternalRoute(reason: reason) {
print("[CallKit] Releasing speaker override for external audio route reason=\(reason)")
- setSpeakerEnabledOnMain(false, isUserSelection: false)
+ _ = setSpeakerEnabledOnMain(false, isUserSelection: false)
return
}
- if shouldDefaultToSpeakerAfterRouteChange(reason: reason) {
- defaultToSpeakerIfBuiltInRouteOnMain(reason: "routeChange:\(reason)")
+ if shouldApplyQueuedSpeakerOverride(reason: reason) {
+ print("[CallKit] Applying queued speaker override after route became available reason=\(reason)")
+ _ = setSpeakerEnabledOnMain(true, isUserSelection: false)
return
}
+
+ if shouldDefaultToSpeakerAfterRouteChange(reason: reason) {
+ print("[CallKit] Built-in speaker default is eligible after route change reason=\(reason)")
+ }
emitCurrentRouteOnMain()
}
+ private func shouldApplyQueuedSpeakerOverride(reason: String) -> Bool {
+ guard isSpeakerForced, reason != "override" else { return false }
+ guard !isCurrentExternalOutputRoute() else { return false }
+ return currentSnapshotOnMain().output == .receiver
+ }
+
private func shouldDefaultToSpeakerAfterRouteChange(reason: String) -> Bool {
guard preferredBuiltInSpeakerEnabled != false else { return false }
- guard !isExternalRouteAvailable() else { return false }
+ guard !isCurrentExternalOutputRoute() else { return false }
let snapshot = currentSnapshotOnMain()
guard snapshot.supportsSpeakerToggle, snapshot.output != .unknown else { return false }
return reason != "override"
@@ -226,14 +254,19 @@ final class CallAudioRouteController: NSObject, @unchecked Sendable {
private func shouldReleaseSpeakerOverrideForExternalRoute(reason: String) -> Bool {
guard isSpeakerForced, reason != "override" else { return false }
- if preferredBuiltInSpeakerEnabled == true, !isExternalRouteAvailable() {
+ if preferredBuiltInSpeakerEnabled == true, !isCurrentExternalOutputRoute() {
return false
}
- let output = currentSnapshotOnMain().output
- if output != .speaker && output != .unknown {
+ return isCurrentExternalOutputRoute()
+ }
+
+ private func isCurrentExternalOutputRoute() -> Bool {
+ switch currentSnapshotOnMain().output {
+ case .bluetooth, .headphones, .external:
return true
+ case .receiver, .speaker, .unknown:
+ return false
}
- return isExternalRouteAvailable()
}
private func isExternalRouteAvailable() -> Bool {
@@ -307,7 +340,7 @@ final class CallAudioRouteController: NSObject, @unchecked Sendable {
case .headphones:
return .headphones
default:
- return .unknown
+ return .external
}
}
diff --git a/js/app/tauri/callkit_plugin/ios/Sources/CallVideoOverlayController.swift b/js/app/tauri/callkit_plugin/ios/Sources/CallVideoOverlayController.swift
index fbb780344c..62d8e5676d 100644
--- a/js/app/tauri/callkit_plugin/ios/Sources/CallVideoOverlayController.swift
+++ b/js/app/tauri/callkit_plugin/ios/Sources/CallVideoOverlayController.swift
@@ -619,6 +619,8 @@ final class CallVideoOverlayController: NSObject, UIGestureRecognizerDelegate, U
return UIImage(systemName: "bluetooth") ?? bluetoothTemplateImage()
case .headphones:
return UIImage(systemName: "headphones")
+ case .external:
+ return UIImage(systemName: "airplayaudio") ?? UIImage(systemName: "speaker.wave.2.fill")
}
}
diff --git a/js/app/tauri/callkit_plugin/ios/Sources/IncomingCallCoordinator.swift b/js/app/tauri/callkit_plugin/ios/Sources/IncomingCallCoordinator.swift
index 8683d438bc..444edcd53b 100644
--- a/js/app/tauri/callkit_plugin/ios/Sources/IncomingCallCoordinator.swift
+++ b/js/app/tauri/callkit_plugin/ios/Sources/IncomingCallCoordinator.swift
@@ -27,6 +27,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
private var reportedConnectedOutgoingCallUUIDs: Set<UUID> = []
private var cachedVoipToken: String?
private var pendingAnsweredCall: (channelId: String, nativeMedia: Bool)?
+ private var pendingEndCallCompletions: [UUID: [() -> Void]] = [:]
init(
mediaSession: @escaping () -> NativeLiveKitCallSession,
@@ -85,17 +86,48 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
let title = channelName?.trimmingCharacters(in: .whitespacesAndNewlines)
let displayTitle = title?.isEmpty == false ? title : nil
+ let isAnsweringPendingIncomingCall = activeCallUUID == uuid
+ && pendingCalls[uuid] != nil
+ && !outgoingCallUUIDs.contains(uuid)
pendingCalls[uuid] = PendingCallInfo(
channelId: channelId,
channelName: displayTitle,
callerName: callerName
)
pendingCallTokens[uuid] = PendingCallToken(serverUrl: serverUrl, token: token)
+
+ if isAnsweringPendingIncomingCall {
+ activeNativeMediaUUID = uuid
+ let mediaSession = mediaSessionProvider()
+ mediaSession.setChannelTitle(displayTitle)
+ mediaSession.prepareForCallKitAudio()
+ activateNativeMediaAudioIfNeeded(reason: "JS answer prepared")
+ let action = CXAnswerCallAction(call: uuid)
+ let transaction = CXTransaction(action: action)
+ print("[CallKit] Requesting CXAnswerCallAction from JS uuid=\(uuid.uuidString) channelId=\(channelId) channelName=\(displayTitle ?? "nil")")
+ callController.request(transaction) { error in
+ DispatchQueue.main.async {
+ if let error {
+ print("[CallKit] JS CXAnswerCallAction request failed uuid=\(uuid.uuidString) error=\(error)")
+ if self.activeNativeMediaUUID == uuid {
+ self.activeNativeMediaUUID = nil
+ }
+ } else {
+ print("[CallKit] JS CXAnswerCallAction request accepted uuid=\(uuid.uuidString)")
+ }
+ completion(error)
+ }
+ }
+ return
+ }
+
activeCallUUID = uuid
activeNativeMediaUUID = uuid
outgoingCallUUIDs.insert(uuid)
reportedConnectedOutgoingCallUUIDs.remove(uuid)
- mediaSessionProvider().setChannelTitle(displayTitle)
+ let mediaSession = mediaSessionProvider()
+ mediaSession.setChannelTitle(displayTitle)
+ mediaSession.prepareForCallKitAudio()
activateNativeMediaAudioIfNeeded(reason: "outgoing call prepared")
let handle = CXHandle(type: .generic, value: displayTitle ?? channelId)
@@ -132,6 +164,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
}
print("[CallKit] endActiveCall requesting CXEndCallAction uuid=\(uuid.uuidString)")
+ appendPendingEndCallCompletion(uuid: uuid, completion)
requestEndCall(uuid: uuid) { [weak self] error in
guard let self else {
completion()
@@ -148,8 +181,23 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
await mediaSession.disconnect()
}
}
+ return
+ }
+
+ DispatchQueue.main.asyncAfter(deadline: .now() + 5) { [weak self] in
+ guard let self else { return }
+ guard self.pendingEndCallCompletions[uuid]?.isEmpty == false else { return }
+ print("[CallKit] Timed out waiting for CXEndCallAction provider callback; completing JS endActiveCall uuid=\(uuid.uuidString)")
+ let shouldDisconnectNativeMedia = self.activeNativeMediaUUID == uuid
+ self.completePendingEndCall(uuid: uuid)
+ self.clearCallState(uuid: uuid)
+ if shouldDisconnectNativeMedia {
+ let mediaSession = self.mediaSessionProvider()
+ Task {
+ await mediaSession.disconnect()
+ }
+ }
}
- completion()
}
}
}
@@ -303,6 +351,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
pendingAnsweredCall = nil
outgoingCallUUIDs.removeAll()
reportedConnectedOutgoingCallUUIDs.removeAll()
+ completeAllPendingEndCalls()
if activeNativeMediaUUID != nil {
activeNativeMediaUUID = nil
let mediaSession = mediaSessionProvider()
@@ -326,6 +375,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
activeCallUUID = uuid
activeNativeMediaUUID = uuid
provider.reportOutgoingCall(with: uuid, startedConnectingAt: Date())
+ mediaSessionProvider().prepareForCallKitAudio()
action.fulfill()
print("[CallKit] Fulfilled CXStartCallAction uuid=\(uuid.uuidString)")
@@ -473,6 +523,28 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
outgoingCallUUIDs.remove(uuid)
reportedConnectedOutgoingCallUUIDs.remove(uuid)
pendingAnsweredCall = nil
+ completePendingEndCall(uuid: uuid)
+ }
+
+ private func appendPendingEndCallCompletion(uuid: UUID, _ completion: @escaping () -> Void) {
+ var completions = pendingEndCallCompletions[uuid] ?? []
+ completions.append(completion)
+ pendingEndCallCompletions[uuid] = completions
+ }
+
+ private func completePendingEndCall(uuid: UUID) {
+ guard let completions = pendingEndCallCompletions.removeValue(forKey: uuid) else { return }
+ for completion in completions {
+ completion()
+ }
+ }
+
+ private func completeAllPendingEndCalls() {
+ let completions = pendingEndCallCompletions.values.flatMap { $0 }
+ pendingEndCallCompletions.removeAll()
+ for completion in completions {
+ completion()
+ }
}
private func startRingStatePolling(uuid: UUID, ringStatusUrl: String, bearerToken: String) {
diff --git a/js/app/tauri/callkit_plugin/ios/Sources/NativeLiveKitCallSession.swift b/js/app/tauri/callkit_plugin/ios/Sources/NativeLiveKitCallSession.swift
index 46d13ff491..58a84ed73c 100644
--- a/js/app/tauri/callkit_plugin/ios/Sources/NativeLiveKitCallSession.swift
+++ b/js/app/tauri/callkit_plugin/ios/Sources/NativeLiveKitCallSession.swift
@@ -40,7 +40,11 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl
private var didPrepareAudio = false
private var isCallKitAudioActive = false
private var isActivatingAudioEngine = false
- private var desiredAudioMuted = false
+ private var microphoneCoordinator = MicrophoneStateCoordinator()
+ private var didApplyDefaultSpeakerRoute = false
+ private var lastAudioRouteSnapshot: CallAudioRouteSnapshot?
+ private var lastAudioEngineInputAvailable: Bool?
+ private var lastAudioEngineOutputAvailable: Bool?
private let audioEngineLogger = CallKitAudioEngineLogger()
private let audioRouteController = CallAudioRouteController()
@@ -58,7 +62,7 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl
self.videoOverlay = videoOverlay
super.init()
audioEngineLogger.desiredMutedProvider = { [weak self] in
- self?.desiredAudioMuted
+ self?.microphoneCoordinator.desiredMuted
}
configureLiveKitAudioForCallKit()
videoOverlay.onToggleMicrophone = { [weak self] in
@@ -91,12 +95,31 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl
}
audioRouteController.onRouteChanged = { [weak self] route in
guard let self else { return }
+ let previousRoute = self.lastAudioRouteSnapshot
+ let previousInputAvailable = self.lastAudioEngineInputAvailable
+ let previousOutputAvailable = self.lastAudioEngineOutputAvailable
+ let inputAvailable = AudioManager.shared.engineAvailability.isInputAvailable
+ let outputAvailable = AudioManager.shared.engineAvailability.isOutputAvailable
+ self.lastAudioRouteSnapshot = route
+ self.lastAudioEngineInputAvailable = inputAvailable
+ self.lastAudioEngineOutputAvailable = outputAvailable
self.videoOverlay.setAudioRoute(route)
guard self.activeCallUUID != nil else { return }
- if self.isCallKitAudioActive, !AudioManager.shared.engineAvailability.isOutputAvailable {
+
+ let routeChanged = previousRoute != route
+ let audioAvailabilityChanged = previousInputAvailable != inputAvailable
+ || previousOutputAvailable != outputAvailable
+ guard routeChanged || audioAvailabilityChanged else {
+ print("[CallKit] Audio route emit did not change route or engine availability; skipping microphone restore")
+ return
+ }
+
+ self.defaultBuiltInSpeakerRouteOnceIfNeeded(reason: "audio route changed")
+
+ if self.isCallKitAudioActive, !outputAvailable {
self.activateAudioEngine(reason: "audio route changed")
} else if self.canEnableMicrophoneAudio() {
- self.enableMicrophoneAfterAudioActivationIfNeeded(reason: "audio route changed")
+ self.restoreMicrophoneIfNeeded(reason: "audio route changed")
}
}
audioRouteController.startObserving()
@@ -139,11 +162,7 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl
try session.setPreferredIOBufferDuration(0.02)
print("[CallKit] Configured AVAudioSession category for voice call reason=\(reason) \(describeAudioSession())")
audioRouteController.emitCurrentRoute()
- if hasUsableAudioOutputRoute() {
- audioRouteController.defaultToSpeakerIfBuiltInRoute(reason: "audioSessionCategoryConfigured")
- } else {
- print("[CallKit] Skipping built-in speaker default because AVAudioSession route is not ready reason=\(reason) \(describeAudioSession())")
- }
+ defaultBuiltInSpeakerRouteOnceIfNeeded(reason: "audioSessionCategoryConfigured:\(reason)")
} catch {
print("[CallKit] Failed to set audio session category reason=\(reason): \(error) \(describeAudioSession())")
}
@@ -171,7 +190,7 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl
try AudioManager.shared.setEngineAvailability(availability)
isCallKitAudioActive = true
print("[CallKit] CallKit activated AVAudioSession; LiveKit audio engine available reason=\(reason) input=\(AudioManager.shared.engineAvailability.isInputAvailable) output=\(AudioManager.shared.engineAvailability.isOutputAvailable) running=\(AudioManager.shared.isEngineRunning) \(describeAudioSession())")
- enableMicrophoneAfterAudioActivationIfNeeded(reason: reason)
+ restoreMicrophoneIfNeeded(reason: reason)
} catch {
print("[CallKit] Failed to enable LiveKit audio engine after CallKit activation reason=\(reason): \(error) \(describeAudioSession())")
}
@@ -203,6 +222,12 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl
func connect(uuid: UUID, channelId: String, serverUrl: String, token: String) {
print("[CallKit] Native LiveKit connect requested uuid=\(uuid.uuidString) channelId=\(channelId)")
+ let desiredAudioMuted = microphoneCoordinator.desiredMuted
+ microphoneCoordinator.reset(desiredMuted: desiredAudioMuted)
+ didApplyDefaultSpeakerRoute = false
+ lastAudioRouteSnapshot = nil
+ lastAudioEngineInputAvailable = nil
+ lastAudioEngineOutputAvailable = nil
prepareForCallKitAudio()
audioRouteController.prepareForCall()
@@ -218,16 +243,16 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl
channelId: channelId,
callId: uuid.uuidString,
connectionState: "connecting",
- isAudioMuted: false,
+ isAudioMuted: desiredAudioMuted,
isVideoMuted: true,
videoOverlayMode: "hidden"
)
- desiredAudioMuted = false
pinnedRemoteVideoParticipantId = nil
speakingRemoteParticipantIds = []
- videoOverlay.setAudioMuted(false)
+ videoOverlay.setAudioMuted(desiredAudioMuted)
videoOverlay.setLocalVideoEnabled(false)
emitSnapshot()
+ defaultBuiltInSpeakerRouteOnceIfNeeded(reason: "connect")
connectTask?.cancel()
let oldRoom = room
@@ -273,34 +298,7 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl
return
}
- do {
- guard await self.ensureMicrophonePermission(uuid: uuid) else {
- self.updateAudioMuted(true, room: newRoom, uuid: uuid)
- return
- }
-
- print("[CallKit] Enabling LiveKit microphone uuid=\(uuid.uuidString) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) callKitAudioActive=\(self.isCallKitAudioActive) \(self.describeAudioSession())")
- guard self.canEnableMicrophoneAudio() else {
- print("[CallKit] Deferring LiveKit microphone enable until CallKit audio engine is ready uuid=\(uuid.uuidString) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) callKitAudioActive=\(self.isCallKitAudioActive) \(self.describeAudioSession())")
- return
- }
- let microphoneWarning = Task {
- try? await Task.sleep(nanoseconds: 5_000_000_000)
- if !Task.isCancelled {
- print("[CallKit] Still waiting for LiveKit microphone enable uuid=\(uuid.uuidString) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) \(self.describeAudioSession())")
- }
- }
- defer { microphoneWarning.cancel() }
- try await newRoom.localParticipant.setMicrophone(enabled: true)
- self.updateAudioMuted(false, room: newRoom, uuid: uuid)
- print("[CallKit] LiveKit microphone enabled uuid=\(uuid.uuidString) engineRunning=\(AudioManager.shared.isEngineRunning) \(self.describeAudioSession())")
- } catch is CancellationError {
- print("[CallKit] LiveKit microphone enable cancelled uuid=\(uuid.uuidString)")
- return
- } catch {
- print("[CallKit] Failed to enable LiveKit microphone; keeping room connected uuid=\(uuid.uuidString) error=\(error) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) callKitAudioActive=\(self.isCallKitAudioActive) \(self.describeAudioSession())")
- self.updateAudioMuted(true, room: newRoom, uuid: uuid)
- }
+ self.applyInitialMicrophoneState(room: newRoom, uuid: uuid, reason: "connect")
}
}
@@ -347,44 +345,13 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl
}
func setAudioMuted(_ muted: Bool) {
- guard let room, let uuid = activeCallUUID else {
- print("[CallKit] setAudioMuted ignored; no active native room muted=\(muted)")
+ guard activeCallUUID != nil, room != nil else {
+ let generation = microphoneCoordinator.setDesiredMuted(muted)
+ print("[CallKit] setAudioMuted queued; no active native room muted=\(muted) generation=\(generation)")
return
}
- desiredAudioMuted = muted
- print("[CallKit] Native LiveKit desired microphone muted=\(muted) uuid=\(uuid.uuidString) currentSnapshotMuted=\(activeCall?.isAudioMuted.description ?? "nil")")
-
- Task { [weak self, weak room] in
- guard let self, let room else { return }
-
- do {
- if muted {
- print("[CallKit] Applying native LiveKit microphone muted=true uuid=\(uuid.uuidString) desiredMuted=\(self.desiredAudioMuted)")
- try await room.localParticipant.setMicrophone(enabled: false)
- self.updateAudioMuted(true, room: room, uuid: uuid)
- print("[CallKit] Native LiveKit microphone muted uuid=\(uuid.uuidString) desiredMuted=\(self.desiredAudioMuted)")
- return
- }
-
- guard await self.ensureMicrophonePermission(uuid: uuid) else {
- self.updateAudioMuted(true, room: room, uuid: uuid)
- return
- }
-
- print("[CallKit] Applying native LiveKit microphone muted=false uuid=\(uuid.uuidString) desiredMuted=\(self.desiredAudioMuted) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) \(describeAudioSession())")
- guard self.canEnableMicrophoneAudio() else {
- print("[CallKit] Deferring native LiveKit microphone unmute until CallKit audio engine is ready uuid=\(uuid.uuidString) desiredMuted=\(self.desiredAudioMuted) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) \(self.describeAudioSession())")
- return
- }
- try await room.localParticipant.setMicrophone(enabled: true)
- self.updateAudioMuted(false, room: room, uuid: uuid)
- print("[CallKit] Native LiveKit microphone unmuted uuid=\(uuid.uuidString) desiredMuted=\(self.desiredAudioMuted)")
- } catch {
- print("[CallKit] Failed to set native LiveKit microphone muted=\(muted) uuid=\(uuid.uuidString) desiredMuted=\(self.desiredAudioMuted): \(error)")
- self.updateAudioMuted(true, room: room, uuid: uuid)
- }
- }
+ setDesiredAudioMuted(muted, reason: "setAudioMuted")
}
func setParticipantDisplayName(identity: String, displayName: String?) {
@@ -470,6 +437,7 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl
let currentOutput = audioRouteController.currentRouteSnapshot().output
let enableSpeaker = currentOutput != .speaker
print("[CallKit] Native video overlay requested speaker enabled=\(enableSpeaker) currentOutput=\(currentOutput.rawValue)")
+ didApplyDefaultSpeakerRoute = true
audioRouteController.setSpeakerEnabled(enableSpeaker)
}
@@ -949,29 +917,139 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl
&& AudioManager.shared.engineAvailability.isInputAvailable
}
- private func enableMicrophoneAfterAudioActivationIfNeeded(reason: String) {
- guard !desiredAudioMuted else { return }
+ private func defaultBuiltInSpeakerRouteOnceIfNeeded(reason: String) {
+ guard activeCallUUID != nil else { return }
+ guard !didApplyDefaultSpeakerRoute else { return }
+ guard hasUsableAudioOutputRoute() else {
+ print("[CallKit] Skipping built-in speaker default because AVAudioSession route is not ready reason=\(reason) \(describeAudioSession())")
+ return
+ }
+
+ let route = audioRouteController.currentRouteSnapshot()
+ guard route.supportsSpeakerToggle else { return }
+
+ guard route.output != .speaker || !route.isSpeakerForced else {
+ didApplyDefaultSpeakerRoute = true
+ print("[CallKit] Built-in speaker default already satisfied reason=\(reason)")
+ return
+ }
+ if route.output != .unknown {
+ guard audioRouteController.canDefaultToSpeakerIfBuiltInRoute() else { return }
+ }
+
+ let didDefault = audioRouteController.defaultToSpeakerIfBuiltInRoute(reason: reason)
+ didApplyDefaultSpeakerRoute = didDefault
+ if !didDefault {
+ print("[CallKit] Built-in speaker default did not apply; will retry on later route change reason=\(reason)")
+ }
+ }
+
+ private func setDesiredAudioMuted(_ muted: Bool, reason: String) {
+ guard let room, let uuid = activeCallUUID else { return }
+ let generation = microphoneCoordinator.setDesiredMuted(muted)
+ print("[CallKit] Native LiveKit desired microphone muted=\(muted) reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation) currentSnapshotMuted=\(activeCall?.isAudioMuted.description ?? "nil")")
+ applyMicrophoneState(muted, room: room, uuid: uuid, generation: generation, reason: reason)
+ }
+
+ private func applyInitialMicrophoneState(room: Room, uuid: UUID, reason: String) {
+ let muted = microphoneCoordinator.desiredMuted
+ let generation = microphoneCoordinator.generation
+ print("[CallKit] Applying initial LiveKit microphone state muted=\(muted) reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation)")
+ applyMicrophoneState(muted, room: room, uuid: uuid, generation: generation, reason: reason)
+ }
+
+ private func restoreMicrophoneIfNeeded(reason: String) {
guard let room, let uuid = activeCallUUID else { return }
guard activeCall?.connectionState == "connected" else { return }
guard canEnableMicrophoneAudio() else {
- print("[CallKit] Waiting to restore LiveKit microphone after audio activation reason=\(reason) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) \(describeAudioSession())")
+ print("[CallKit] Waiting to restore LiveKit microphone reason=\(reason) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) \(describeAudioSession())")
return
}
+ guard let generation = microphoneCoordinator.beginRestoreIfNeeded() else {
+ print("[CallKit] Skipping LiveKit microphone restore reason=\(reason) desiredMuted=\(microphoneCoordinator.desiredMuted) lastKnownMuted=\(microphoneCoordinator.describeLastKnownMuted()) restoreInFlight=\(microphoneCoordinator.isRestoreInFlight) lastApplyFailed=\(microphoneCoordinator.lastApplyFailed)")
+ return
+ }
+
+ applyMicrophoneState(false, room: room, uuid: uuid, generation: generation, reason: reason)
+ }
+ private func applyMicrophoneState(
+ _ muted: Bool,
+ room: Room,
+ uuid: UUID,
+ generation: UInt64,
+ reason: String
+ ) {
Task { [weak self, weak room] in
guard let self, let room else { return }
- guard self.activeCallUUID == uuid, self.room === room, !self.desiredAudioMuted else { return }
+ let enabled = !muted
+
do {
- print("[CallKit] Restoring LiveKit microphone after audio activation reason=\(reason) uuid=\(uuid.uuidString) engineRunning=\(AudioManager.shared.isEngineRunning) \(self.describeAudioSession())")
- try await room.localParticipant.setMicrophone(enabled: true)
- self.updateAudioMuted(false, room: room, uuid: uuid)
- print("[CallKit] Restored LiveKit microphone after audio activation reason=\(reason) uuid=\(uuid.uuidString)")
+ if enabled {
+ guard await self.ensureMicrophonePermission(uuid: uuid) else {
+ guard self.isCurrentMicrophoneOperation(generation, room: room, uuid: uuid, desiredMuted: muted) else { return }
+ self.updateAudioMuted(true, room: room, uuid: uuid, expectedGeneration: generation, applyFailed: false)
+ return
+ }
+
+ guard self.isCurrentMicrophoneOperation(generation, room: room, uuid: uuid, desiredMuted: muted) else {
+ print("[CallKit] Skipping LiveKit microphone unmute for stale desired state reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation) desiredMuted=\(self.microphoneCoordinator.desiredMuted)")
+ return
+ }
+ guard self.canEnableMicrophoneAudio() else {
+ print("[CallKit] Deferring LiveKit microphone unmute until CallKit audio engine is ready reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation) desiredMuted=\(self.microphoneCoordinator.desiredMuted) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) \(self.describeAudioSession())")
+ await self.markMicrophoneApplyDeferred(room: room, uuid: uuid, generation: generation)
+ return
+ }
+ }
+
+ guard self.isCurrentMicrophoneOperation(generation, room: room, uuid: uuid, desiredMuted: muted) else { return }
+
+ let microphoneWarning = enabled ? Task {
+ try? await Task.sleep(nanoseconds: 5_000_000_000)
+ if !Task.isCancelled {
+ print("[CallKit] Still waiting for LiveKit microphone enable reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) \(self.describeAudioSession())")
+ }
+ } : nil
+ defer { microphoneWarning?.cancel() }
+
+ print("[CallKit] Applying native LiveKit microphone muted=\(muted) reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation) desiredMuted=\(self.microphoneCoordinator.desiredMuted) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) \(self.describeAudioSession())")
+ try await room.localParticipant.setMicrophone(enabled: enabled)
+ guard self.isCurrentMicrophoneOperation(generation, room: room, uuid: uuid, desiredMuted: muted) else {
+ print("[CallKit] Native LiveKit microphone apply completed after desired state changed reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation) desiredMuted=\(self.microphoneCoordinator.desiredMuted)")
+ return
+ }
+ self.updateAudioMuted(muted, room: room, uuid: uuid, expectedGeneration: generation, applyFailed: false)
+ print("[CallKit] Native LiveKit microphone applied muted=\(muted) reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation)")
+ } catch is CancellationError {
+ print("[CallKit] LiveKit microphone apply cancelled reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation)")
} catch {
- print("[CallKit] Failed to restore LiveKit microphone after audio activation reason=\(reason) uuid=\(uuid.uuidString): \(error) \(self.describeAudioSession())")
+ print("[CallKit] Failed to apply native LiveKit microphone muted=\(muted) reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation) desiredMuted=\(self.microphoneCoordinator.desiredMuted): \(error)")
+ guard self.isCurrentMicrophoneOperation(generation, room: room, uuid: uuid, desiredMuted: muted) else { return }
+ self.updateAudioMuted(muted, room: room, uuid: uuid, expectedGeneration: generation, applyFailed: true)
}
}
}
+ private func markMicrophoneApplyDeferred(room: Room, uuid: UUID, generation: UInt64) async {
+ await MainActor.run {
+ guard activeCallUUID == uuid, self.room === room else { return }
+ _ = microphoneCoordinator.markApplyDeferred(generation: generation)
+ }
+ }
+
+ private func isCurrentMicrophoneOperation(
+ _ generation: UInt64,
+ room: Room,
+ uuid: UUID,
+ desiredMuted: Bool
+ ) -> Bool {
+ activeCallUUID == uuid
+ && self.room === room
+ && microphoneCoordinator.desiredMuted == desiredMuted
+ && microphoneCoordinator.generation == generation
+ }
+
private func setOutputOnlyAvailabilityIfNeeded(uuid: UUID) {
guard isCallKitAudioActive else { return }
do {
@@ -1017,14 +1095,31 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl
}
}
- private func updateAudioMuted(_ isMuted: Bool, room: Room, uuid: UUID) {
+ private func updateAudioMuted(
+ _ isMuted: Bool,
+ room: Room,
+ uuid: UUID,
+ expectedGeneration: UInt64,
+ applyFailed: Bool
+ ) {
DispatchQueue.main.async { [weak self, weak room] in
guard let self, let room, self.activeCallUUID == uuid, self.room === room, var snapshot = self.activeCall else { return }
+ guard self.microphoneCoordinator.finishApply(
+ generation: expectedGeneration,
+ actualMuted: isMuted,
+ applyFailed: applyFailed
+ ) else {
+ print("[CallKit] Ignoring stale native microphone state update uuid=\(uuid.uuidString) generation=\(expectedGeneration) currentGeneration=\(self.microphoneCoordinator.generation) actualMuted=\(isMuted)")
+ return
+ }
let previousMuted = snapshot.isAudioMuted
+ guard previousMuted != isMuted else {
+ print("[CallKit] Native LiveKit microphone state unchanged uuid=\(uuid.uuidString) actualMuted=\(isMuted) desiredMuted=\(self.microphoneCoordinator.desiredMuted) generation=\(expectedGeneration)")
+ return
+ }
snapshot.isAudioMuted = isMuted
- self.desiredAudioMuted = isMuted
self.activeCall = snapshot
- print("[CallKit] Native LiveKit microphone state updated uuid=\(uuid.uuidString) previousMuted=\(previousMuted) actualMuted=\(isMuted) desiredMuted=\(self.desiredAudioMuted)")
+ print("[CallKit] Native LiveKit microphone state updated uuid=\(uuid.uuidString) previousMuted=\(previousMuted) actualMuted=\(isMuted) desiredMuted=\(self.microphoneCoordinator.desiredMuted) generation=\(expectedGeneration)")
self.videoOverlay.setAudioMuted(isMuted)
self.emitSnapshot()
}
@@ -1046,18 +1141,36 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl
if deactivateAudio, isCallKitAudioActive {
deactivateAudioEngine()
}
+ let disconnectedSnapshot = activeCall.map { snapshot in
+ ActiveCallSnapshot(
+ channelId: snapshot.channelId,
+ callId: snapshot.callId,
+ connectionState: "disconnected",
+ isAudioMuted: snapshot.isAudioMuted,
+ isVideoMuted: snapshot.isVideoMuted,
+ videoOverlayMode: snapshot.videoOverlayMode
+ )
+ }
let r = room
room = nil
activeCallUUID = nil
activeCall = nil
- desiredAudioMuted = false
+ microphoneCoordinator.reset(desiredMuted: false)
+ didApplyDefaultSpeakerRoute = false
+ lastAudioRouteSnapshot = nil
+ lastAudioEngineInputAvailable = nil
+ lastAudioEngineOutputAvailable = nil
pinnedRemoteVideoParticipantId = nil
speakingRemoteParticipantIds = []
participantDisplayNamesByIdentity = [:]
onParticipantIdentitiesChanged([])
pictureInPicture.stopAndReset()
audioRouteController.resetSpeakerOverride()
- emitSnapshot()
+ if let disconnectedSnapshot {
+ emitDisconnectedSnapshot(disconnectedSnapshot)
+ } else {
+ emitSnapshot()
+ }
videoOverlay.reset()
return r
}
@@ -1070,6 +1183,63 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl
}
onSnapshotChanged(activeCall)
}
+
+ private func emitDisconnectedSnapshot(_ snapshot: ActiveCallSnapshot) {
+ print("[CallKit] Emitting native snapshot state=disconnected channelId=\(snapshot.channelId) callId=\(snapshot.callId)")
+ onSnapshotChanged(snapshot)
+ }
+}
+
+private struct MicrophoneStateCoordinator {
+ private(set) var desiredMuted = false
+ private(set) var generation: UInt64 = 0
+ private(set) var lastKnownMuted: Bool?
+ private(set) var isRestoreInFlight = false
+ private(set) var lastApplyFailed = false
+
+ mutating func reset(desiredMuted: Bool) {
+ self.desiredMuted = desiredMuted
+ generation &+= 1
+ lastKnownMuted = nil
+ isRestoreInFlight = false
+ lastApplyFailed = false
+ }
+
+ mutating func setDesiredMuted(_ muted: Bool) -> UInt64 {
+ desiredMuted = muted
+ generation &+= 1
+ isRestoreInFlight = false
+ if muted {
+ lastApplyFailed = false
+ }
+ return generation
+ }
+
+ mutating func beginRestoreIfNeeded() -> UInt64? {
+ guard !desiredMuted else { return nil }
+ guard !isRestoreInFlight else { return nil }
+ guard lastApplyFailed || lastKnownMuted != false else { return nil }
+ isRestoreInFlight = true
+ return generation
+ }
+
+ mutating func finishApply(generation expectedGeneration: UInt64, actualMuted: Bool, applyFailed: Bool) -> Bool {
+ guard generation == expectedGeneration else { return false }
+ lastKnownMuted = actualMuted
+ lastApplyFailed = applyFailed
+ isRestoreInFlight = false
+ return true
+ }
+
+ mutating func markApplyDeferred(generation expectedGeneration: UInt64) -> Bool {
+ guard generation == expectedGeneration else { return false }
+ isRestoreInFlight = false
+ return true
+ }
+
+ func describeLastKnownMuted() -> String {
+ lastKnownMuted.map(String.init) ?? "nil"
+ }
}
private final class CallKitAudioEngineLogger: AudioEngineObserver, @unchecked Sendable {