diff --git a/.changes/interruption-session-reactivation b/.changes/interruption-session-reactivation new file mode 100644 index 000000000..cf343e6a0 --- /dev/null +++ b/.changes/interruption-session-reactivation @@ -0,0 +1 @@ +patch type="fixed" "Reapply the audio session configuration and reactivate the session when the audio engine restarts after an interruption (iOS, tvOS, visionOS), with automatic audio session configuration enabled. The engine restart only called engineWillStart, so the session observer never reasserted the category, mode or activation. A failed activation is logged and the engine restarts as before" diff --git a/Sources/LiveKit/Audio/AudioSessionEngineObserver+Interruption.swift b/Sources/LiveKit/Audio/AudioSessionEngineObserver+Interruption.swift new file mode 100644 index 000000000..ec92e1d88 --- /dev/null +++ b/Sources/LiveKit/Audio/AudioSessionEngineObserver+Interruption.swift @@ -0,0 +1,73 @@ +/* + * Copyright 2026 LiveKit + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if os(iOS) || os(visionOS) || os(tvOS) + +import AVFAudio + +public extension AudioSessionEngineObserver { + /// Records that the system deactivated the session, so the next engine start reactivates it. + func audioSessionDidBeginInterruption(reason: AVAudioSession.InterruptionReason) { + _state.mutate { + $0.isInterrupted = true + $0.needsActivation = true + } + next?.audioSessionDidBeginInterruption(reason: reason) + } + + /// Records the end of an interruption. The audio device module restarts the engine right after + /// this returns, and ``engineWillStart(_:isPlayoutEnabled:isRecordingEnabled:)`` reapplies the + /// configuration and reactivates the session before it does. + func audioSessionDidEndInterruption(shouldResume: Bool) { + _state.mutate { + $0.isInterrupted = false + $0.shouldResumeAfterInterruption = shouldResume + } + next?.audioSessionDidEndInterruption(shouldResume: shouldResume) + } + + /// Reapplies the session configuration and reactivates the session when the engine restarts after an + /// interruption. The audio device module only calls `engineWillStart` then, not `engineWillEnable`. + /// + /// Only when ``isAutomaticConfigurationEnabled`` is `true`, an interruption began since the session was + /// last activated, it has ended, and the system did not ask to leave resuming to the user. A failure is + /// logged and does not fail the start: the engine restarts as it would without this step. Activation + /// fails in the background or in a CallKit call that CallKit has not reactivated. + func engineWillStart(_ engine: AVAudioEngine, isPlayoutEnabled: Bool, isRecordingEnabled: Bool) -> Int { + if !engine.isInManualRenderingMode { + reactivateSessionAfterInterruptionIfNeeded() + } + return next?.engineWillStart(engine, isPlayoutEnabled: isPlayoutEnabled, isRecordingEnabled: isRecordingEnabled) ?? 0 + } +} + +extension AudioSessionEngineObserver { + func reactivateSessionAfterInterruptionIfNeeded() { + let shouldReactivate = _state.read { + $0.isAutomaticConfigurationEnabled && $0.needsActivation && !$0.isInterrupted && $0.shouldResumeAfterInterruption + } + guard shouldReactivate else { return } + + do { + log("Reactivating the audio session after an interruption") + try reactivateSessionIfNeeded() + } catch { + log("Failed to reactivate the audio session after an interruption, starting the engine anyway: \(error)", .warning) + } + } +} + +#endif diff --git a/Sources/LiveKit/Audio/AudioSessionEngineObserver.swift b/Sources/LiveKit/Audio/AudioSessionEngineObserver.swift index 2d58f2773..cd46c2895 100644 --- a/Sources/LiveKit/Audio/AudioSessionEngineObserver.swift +++ b/Sources/LiveKit/Audio/AudioSessionEngineObserver.swift @@ -84,10 +84,16 @@ public class AudioSessionEngineObserver: AudioEngineObserver, Loggable, @uncheck var hasRecorded: Bool = false // The system deactivated the session or dropped its configuration - // behind the observer's back (a media services reset), so the next - // configuration must apply the category and activate the session even - // though a requirement is already held. + // behind the observer's back (a media services reset or an + // interruption), so the next configuration must apply the category and + // activate the session even though a requirement is already held. var needsActivation: Bool = false + + // Between an interruption's begin and end. The session cannot be + // activated meanwhile. + var isInterrupted: Bool = false + // The system's resume hint from the last interruption end. + var shouldResumeAfterInterruption: Bool = true } let _state = StateSync(State()) diff --git a/Tests/LiveKitCoreTests/AudioSessionEventTests.swift b/Tests/LiveKitCoreTests/AudioSessionEventTests.swift index d753d7228..663ccf0ca 100644 --- a/Tests/LiveKitCoreTests/AudioSessionEventTests.swift +++ b/Tests/LiveKitCoreTests/AudioSessionEventTests.swift @@ -28,16 +28,20 @@ struct AudioSessionEventTests { private typealias Observer = AudioSessionEngineObserver private final class RecordingObserver: AudioSessionEngineObserver, @unchecked Sendable { + struct Failure: Error {} + struct Configuration { let oldState: Observer.State let newState: Observer.State var activates: Bool { Observer.requiresActivation(oldState: oldState, newState: newState) } } + let isFailing = StateSync(false) let configurations = StateSync<[Configuration]>([]) override func configureAudioSession(oldState: Observer.State, newState: Observer.State) throws { configurations.mutate { $0.append(Configuration(oldState: oldState, newState: newState)) } + if isFailing.copy() { throw Failure() } } func takeConfigurations() -> [Configuration] { @@ -129,6 +133,93 @@ struct AudioSessionEventTests { #expect(!Observer.requiresActivation(oldState: active, newState: inactive)) } + // MARK: - Interruptions + + @Test func engineRestartAfterInterruptionReactivatesTheSession() throws { + let (observer, engine) = startedObserver() + + observer.audioSessionDidBeginInterruption(reason: .default) + #expect(observer._state.isInterrupted) + #expect(observer._state.needsActivation) + + // An engine start while still interrupted does not try to activate. + #expect(observer.engineWillStart(engine, isPlayoutEnabled: true, isRecordingEnabled: true) == 0) + #expect(observer.takeConfigurations().isEmpty) + + observer.audioSessionDidEndInterruption(shouldResume: true) + #expect(observer.engineWillStart(engine, isPlayoutEnabled: true, isRecordingEnabled: true) == 0) + + let configuration = try #require(observer.takeConfigurations().first) + #expect(configuration.activates) + #expect(configuration.newState.isRecordingEnabled) + #expect(!observer._state.needsActivation) + + // Done once: later starts do not reconfigure. + _ = observer.engineWillStart(engine, isPlayoutEnabled: true, isRecordingEnabled: true) + #expect(observer.takeConfigurations().isEmpty) + } + + @Test func interruptionEndWithoutResumeHintDefersReactivation() { + let (observer, engine) = startedObserver() + + observer.audioSessionDidBeginInterruption(reason: .default) + observer.audioSessionDidEndInterruption(shouldResume: false) + _ = observer.engineWillStart(engine, isPlayoutEnabled: true, isRecordingEnabled: true) + + #expect(observer.takeConfigurations().isEmpty) + // The next configuration change still activates the session. + #expect(observer._state.needsActivation) + } + + /// `RTCAudioSession` reports an interruption end each time the app becomes active. + @Test func interruptionEndWithoutBeginDoesNothing() { + let (observer, engine) = startedObserver() + + observer.audioSessionDidEndInterruption(shouldResume: true) + _ = observer.engineWillStart(engine, isPlayoutEnabled: true, isRecordingEnabled: true) + + #expect(observer.takeConfigurations().isEmpty) + #expect(!observer._state.needsActivation) + } + + @Test func failedReactivationDoesNotFailTheEngineStart() { + let (observer, engine) = startedObserver() + + observer.audioSessionDidBeginInterruption(reason: .default) + observer.audioSessionDidEndInterruption(shouldResume: true) + observer.isFailing.mutate { $0 = true } + + #expect(observer.engineWillStart(engine, isPlayoutEnabled: true, isRecordingEnabled: true) == 0) + #expect(observer.takeConfigurations().count == 1) + // Kept, so the next configuration activates again. + #expect(observer._state.needsActivation) + } + + @Test func automaticConfigurationDisabledLeavesTheSessionAlone() { + let (observer, engine) = startedObserver() + observer.isAutomaticConfigurationEnabled = false + + observer.audioSessionDidBeginInterruption(reason: .default) + observer.audioSessionDidEndInterruption(shouldResume: true) + _ = observer.engineWillStart(engine, isPlayoutEnabled: true, isRecordingEnabled: true) + + #expect(observer.takeConfigurations().isEmpty) + } + + /// A requirement change after an interruption (the mic is enabled, say) activates the session even + /// though a requirement was already held, and clears the flag. + @Test func requirementChangeAfterInterruptionActivates() throws { + let (observer, engine) = startedObserver() + observer.audioSessionDidBeginInterruption(reason: .default) + observer.audioSessionDidEndInterruption(shouldResume: false) + + _ = observer.engineDidDisable(engine, isPlayoutEnabled: true, isRecordingEnabled: false) + + let configuration = try #require(observer.takeConfigurations().first) + #expect(configuration.activates) + #expect(!observer._state.needsActivation) + } + // MARK: - Media services reset /// With automatic configuration disabled the observer only updates its bookkeeping, so this runs