Coordinate AVAudioSession handoff with iOS PushToTalk for Lock-Screen recording

This commit is contained in:
jack committed 2026-11-28 01:00:18 -10:00
1 parent f7ccde89f9
commit 43900e0689
4 files changed
+184 -5

No files matched your search

@@ -230,6 +230,13 @@ final class AudioSessionCoordinator: @unchecked Sendable {
private var holders: [ObjectIdentifier: WeakHolder] = [:]
private var currentCategory: Category?
private var sessionActive = false
#if os(iOS)
/// True while iOS `PushToTalk` owns `AVAudioSession` activation/deactivation
/// (between `didActivateAudioSession` and `didDeactivateAudioSession`).
/// Calling `setActive(true)` in the background fails with `'!pri'` (561015905),
/// and calling `setActive(false)` conflicts with PushToTalk's session lifecycle.
private var externallyManaged = false
#endif
/// Written once in init, read in deinit — never touched concurrently.
private var observers: [NSObjectProtocol] = []
@@ -360,6 +367,12 @@ final class AudioSessionCoordinator: @unchecked Sendable {
private func releaseOnQueue(id: ObjectIdentifier) {
guard holders.removeValue(forKey: id) != nil else { return }
guard holders.isEmpty else { return }
#if os(iOS)
if externallyManaged {
// iOS PushToTalk owns deactivation and will call didDeactivateAudioSession.
return
}
#endif
currentCategory = nil
guard sessionActive else { return }
sessionActive = false
@@ -397,12 +410,63 @@ final class AudioSessionCoordinator: @unchecked Sendable {
/// No auto-resume — the next acquire re-activates.
func handleInterruptionBegan() async {
let tickets = await onQueue { () -> [Token.CallbackTicket] in
#if os(iOS)
self.externallyManaged = false
#endif
self.sessionActive = false
return self.holders.values.compactMap { $0.token?.record(.interrupted) }
}
await deliver(tickets)
}
#if os(iOS)
/// Pre-configures the audio session category before iOS `PushToTalk`
/// activates the session on our behalf (must NOT call `setActive(true)`).
func prepareForExternalActivation(_ use: Use) {
queue.sync {
guard self.holders.isEmpty else { return }
let target: Category = (use == .capture || self.currentCategory == .playAndRecord) ? .playAndRecord : .playback
guard target != self.currentCategory else { return }
do {
try self.session.setCategory(target)
self.currentCategory = target
} catch {
SecureLogger.warning("AudioSession: failed configuring category for external activation: \(error)", category: .session)
}
}
}
/// Records that iOS `PushToTalk` has activated `AVAudioSession` on our
/// behalf. Subsequent `acquire` calls skip `setActive(true)` and `release`
/// skips `setActive(false)` until `handleExternalDeactivation()` runs.
func handleExternalActivation() {
queue.sync {
self.externallyManaged = true
self.sessionActive = true
if self.holders.isEmpty, self.currentCategory != .playAndRecord {
do {
try self.session.setCategory(.playAndRecord)
self.currentCategory = .playAndRecord
} catch {
SecureLogger.warning("AudioSession: failed setting playAndRecord after external activation: \(error)", category: .session)
}
}
}
}
/// Called when iOS `PushToTalk` deactivates `AVAudioSession`. Releases
/// external ownership and interrupts any remaining holders.
func handleExternalDeactivation() async {
let tickets = await onQueue { () -> [Token.CallbackTicket] in
self.externallyManaged = false
self.sessionActive = false
self.currentCategory = nil
return self.holders.values.compactMap { $0.token?.record(.interrupted) }
}
await deliver(tickets)
}
#endif
/// The active route's input/output device disappeared (e.g. BT headset
/// off): ready holders' engines are wedged against a dead route — stop
/// them; invalidate a holder whose acquire has not returned yet.
@@ -92,6 +92,9 @@ final class SystemPTTChannelManager: ObservableObject {
#if os(iOS) && canImport(PushToTalk)
private var channelManager: PTChannelManager?
private var delegateProxy: SystemPTTDelegateProxy?
private var pendingSystemTransmit = false
private var isAudioSessionExternallyActive = false
private var hasStartedSystemCapture = false
#endif
private init() {}
@@ -155,9 +158,15 @@ final class SystemPTTChannelManager: ObservableObject {
func leaveCurrentChannel() {
#if os(iOS) && canImport(PushToTalk)
let previousUUID = activeChannel?.channelUUID
let wasCapturing = hasStartedSystemCapture
activeChannel = nil
isSystemTransmitting = false
pendingSystemTransmit = false
hasStartedSystemCapture = false
status = .idle
if wasCapturing {
onSystemTransmitEnded?()
}
if let manager = channelManager, let uuid = previousUUID {
manager.leaveChannel(channelUUID: uuid)
}
@@ -222,9 +231,15 @@ final class SystemPTTChannelManager: ObservableObject {
fileprivate func handleDidLeave(channelUUID: UUID) {
if activeChannel?.channelUUID == channelUUID {
let wasCapturing = hasStartedSystemCapture
activeChannel = nil
isSystemTransmitting = false
pendingSystemTransmit = false
hasStartedSystemCapture = false
status = .idle
if wasCapturing {
onSystemTransmitEnded?()
}
}
}
@@ -233,6 +248,8 @@ final class SystemPTTChannelManager: ObservableObject {
if activeChannel?.channelUUID == channelUUID || activeChannel == nil {
activeChannel = nil
isSystemTransmitting = false
pendingSystemTransmit = false
hasStartedSystemCapture = false
status = .unavailable(reason: error.localizedDescription)
}
}
@@ -240,20 +257,55 @@ final class SystemPTTChannelManager: ObservableObject {
fileprivate func handleFailedToTransmit(channelUUID: UUID, error: Error) {
SecureLogger.warning("PTT: failed to transmit on system PushToTalk channel \(channelUUID): \(error.localizedDescription)", category: .session)
if activeChannel?.channelUUID == channelUUID {
let wasCapturing = hasStartedSystemCapture
isSystemTransmitting = false
pendingSystemTransmit = false
hasStartedSystemCapture = false
if wasCapturing {
onSystemTransmitEnded?()
}
}
}
fileprivate func handleTransmitBegan(channelUUID: UUID) {
guard activeChannel?.channelUUID == channelUUID else { return }
isSystemTransmitting = true
onSystemTransmitBegan?(activeChannel?.target)
pendingSystemTransmit = true
beginSystemCaptureIfReady()
}
fileprivate func handleTransmitEnded(channelUUID: UUID) {
guard activeChannel?.channelUUID == channelUUID else { return }
isSystemTransmitting = false
onSystemTransmitEnded?()
pendingSystemTransmit = false
if hasStartedSystemCapture {
hasStartedSystemCapture = false
onSystemTransmitEnded?()
}
}
fileprivate func handleAudioSessionActivated() {
isAudioSessionExternallyActive = true
beginSystemCaptureIfReady()
}
fileprivate func handleAudioSessionDeactivated() async {
isAudioSessionExternallyActive = false
if hasStartedSystemCapture {
hasStartedSystemCapture = false
pendingSystemTransmit = false
isSystemTransmitting = false
onSystemTransmitEnded?()
}
await AudioSessionCoordinator.shared.handleExternalDeactivation()
}
private func beginSystemCaptureIfReady() {
guard pendingSystemTransmit,
isAudioSessionExternallyActive,
!hasStartedSystemCapture else { return }
hasStartedSystemCapture = true
onSystemTransmitBegan?(activeChannel?.target)
}
nonisolated fileprivate static func channelAvatarImage() -> UIImage? {
@@ -319,6 +371,9 @@ private final class SystemPTTDelegateProxy: NSObject, PTChannelManagerDelegate,
}
func channelManager(_ channelManager: PTChannelManager, channelUUID: UUID, didBeginTransmittingFrom source: PTChannelTransmitRequestSource) {
// Configure AVAudioSession category BEFORE iOS PushToTalk activates it
// (must NOT call setActive(true); wait for didActivateAudioSession).
AudioSessionCoordinator.shared.prepareForExternalActivation(.capture)
Task { @MainActor [weak owner] in
owner?.handleTransmitBegan(channelUUID: channelUUID)
}
@@ -335,11 +390,18 @@ private final class SystemPTTDelegateProxy: NSObject, PTChannelManagerDelegate,
}
func channelManager(_ channelManager: PTChannelManager, didActivate audioSession: AVAudioSession) {
SecureLogger.debug("PTT: system PushToTalk audio session activated", category: .session)
SecureLogger.info("PTT: system PushToTalk audio session activated", category: .session)
AudioSessionCoordinator.shared.handleExternalActivation()
Task { @MainActor [weak owner] in
owner?.handleAudioSessionActivated()
}
}
func channelManager(_ channelManager: PTChannelManager, didDeactivate audioSession: AVAudioSession) {
SecureLogger.debug("PTT: system PushToTalk audio session deactivated", category: .session)
SecureLogger.info("PTT: system PushToTalk audio session deactivated", category: .session)
Task { @MainActor [weak owner] in
await owner?.handleAudioSessionDeactivated()
}
}
func incomingPushResult(channelManager: PTChannelManager, channelUUID: UUID, pushPayload: [String: Any]) -> PTPushResult {
+7 -1
View File
@@ -342,7 +342,13 @@ struct ContentView: View {
#if os(iOS)
SystemPTTChannelManager.shared.onSystemTransmitBegan = { [weak voiceRecordingVM, weak uiModel] target in
guard let voiceRecordingVM, let uiModel else { return }
voiceRecordingVM.start(shouldShow: uiModel.canSendVoiceInCurrentContext, target: target)
if case .error = voiceRecordingVM.state {
voiceRecordingVM.showAlert = false
}
voiceRecordingVM.start(
shouldShow: target != nil || uiModel.canSendVoiceInCurrentContext,
target: target
)
}
SystemPTTChannelManager.shared.onSystemTransmitEnded = { [weak voiceRecordingVM, weak uiModel] in
guard let voiceRecordingVM, let uiModel else { return }
@@ -507,4 +507,51 @@ struct AudioSessionCoordinatorTests {
await coordinator.drain()
#expect(session.activationCalls == [true, false])
}
#if os(iOS)
@Test func externalActivationSkipsSetActiveOnAcquireAndRelease() async throws {
let session = MockAudioSession()
let coordinator = AudioSessionCoordinator(session: session)
coordinator.prepareForExternalActivation(.capture)
coordinator.handleExternalActivation()
#expect(session.categoryCalls == [.playAndRecord])
#expect(session.activationCalls.isEmpty)
let token = try await coordinator.acquire(.capture) {}
#expect(session.categoryCalls == [.playAndRecord])
#expect(session.activationCalls.isEmpty)
coordinator.release(token)
await coordinator.drain()
#expect(session.activationCalls.isEmpty)
await coordinator.handleExternalDeactivation()
await coordinator.drain()
#expect(session.activationCalls.isEmpty)
// Normal in-app acquire resumes managing setActive(true/false).
let normal = try await coordinator.acquire(.capture) {}
#expect(session.activationCalls == [true])
coordinator.release(normal)
await coordinator.drain()
#expect(session.activationCalls == [true, false])
}
@Test func externalDeactivationInterruptsLiveHolders() async throws {
let session = MockAudioSession()
let coordinator = AudioSessionCoordinator(session: session)
coordinator.handleExternalActivation()
var interrupted = false
let token = try await coordinator.acquire(.capture) { interrupted = true }
await coordinator.handleExternalDeactivation()
#expect(interrupted)
coordinator.release(token)
await coordinator.drain()
#expect(session.activationCalls.isEmpty)
}
#endif
}