Skip to content

Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more

fix(audio): close bluetooth recovery races

altic-dev9d2795666d6e
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index 7e5142ac..8f3539f4 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -711,7 +711,7 @@ final class ASRService: ObservableObject {
private var audioStartAttemptInputUID: String?
private var audioStartAttemptInputName: String?
private var audioStartAttemptIsBluetooth = false
- private var audioStartAttemptIsBuiltIn = false
+ private var audioStartAttemptIsInternalMicrophone = false
private var deferredBluetoothStartupRouteRecovery =
AudioCaptureIdlePolicy.DeferredBluetoothRouteRecovery()
private var silentPCMRecoveryWatchdog = AudioCaptureIdlePolicy.SilentPCMRecoveryWatchdog()
@@ -930,7 +930,7 @@ final class ASRService: ObservableObject {
self.audioStartAttemptInputUID = nil
self.audioStartAttemptInputName = nil
self.audioStartAttemptIsBluetooth = false
- self.audioStartAttemptIsBuiltIn = false
+ self.audioStartAttemptIsInternalMicrophone = false
if SettingsStore.shared.experimentalDirectAudioCaptureEnabled {
// A non-route path may have scheduled a fire-and-forget retirement.
// Do not let direct capture startup overlap a queued AVAudioEngine
@@ -956,7 +956,7 @@ final class ASRService: ObservableObject {
self.audioStartAttemptInputUID = device.uid
self.audioStartAttemptInputName = device.name
self.audioStartAttemptIsBluetooth = device.isBluetooth
- self.audioStartAttemptIsBuiltIn = device.isBuiltIn
+ self.audioStartAttemptIsInternalMicrophone = device.isUnavailableWhenClamshellClosed
AppServices.shared.microphonePreferenceCoordinator.reportResolvedSelection(
uid: device.uid,
name: device.name
@@ -1153,7 +1153,7 @@ final class ASRService: ObservableObject {
"inputUID=\(self.audioStartAttemptInputUID ?? "unknown")"
)
if self.silentPCMRecoveryWatchdog.shouldRecover(
- isBuiltInInput: self.audioStartAttemptIsBuiltIn,
+ isInternalMicrophone: self.audioStartAttemptIsInternalMicrophone,
isDirectCapture: self.activeAudioCaptureBackend == .directCoreAudio,
rms: rms,
peak: peak
@@ -2123,12 +2123,13 @@ final class ASRService: ObservableObject {
reason: String
) {
let elapsedMilliseconds = Int((elapsed * 1000).rounded())
- let maximumMilliseconds = Int(
- (AudioCaptureIdlePolicy.BluetoothInputStabilization.maximumDuration * 1000).rounded()
+ let admissionWindowMilliseconds = Int(
+ (AudioCaptureIdlePolicy.BluetoothInputStabilization.retryAdmissionWindow * 1000).rounded()
)
self.benchmarkLog(
"bluetooth_start_retry uid=\(uid) attempt=\(attempt) " +
- "elapsedMs=\(elapsedMilliseconds) budgetMs=\(maximumMilliseconds) reason=\(reason)"
+ "elapsedMs=\(elapsedMilliseconds) " +
+ "admissionWindowMs=\(admissionWindowMilliseconds) reason=\(reason)"
)
}
@@ -3177,7 +3178,8 @@ final class ASRService: ObservableObject {
private func scheduleAudioRouteRecovery(
reason: String,
requiresIdlePrewarm: Bool = false,
- reconcilesInputSelection: Bool = false
+ reconcilesInputSelection: Bool = false,
+ invalidatesCurrentStart: Bool = false
) {
guard self.isTerminating == false else {
self.benchmarkLog("route_recovery_ignored reason=app_terminating event=\(reason)")
@@ -3193,15 +3195,32 @@ final class ASRService: ObservableObject {
// than once while entering microphone mode. The active start owns
// its bounded retry loop; a second recovery owner would exclude the
// same healthy device before the Bluetooth route settles.
- self.deferredBluetoothStartupRouteRecovery.preserve(
- reason: reason,
+ let disposition = AudioCaptureIdlePolicy.bluetoothStartupRouteChangeDisposition(
+ invalidatesCurrentStart: invalidatesCurrentStart,
requiresIdlePrewarm: requiresIdlePrewarm,
reconcilesInputSelection: reconcilesInputSelection
)
- let preserved = requiresIdlePrewarm || reconcilesInputSelection
+ if disposition == .retryCurrentStart {
+ // Make routeStayedStable false even if first PCM won the
+ // readiness-gate race. The startup loop then retries the same
+ // Bluetooth input without handing it to active-route recovery.
+ self.audioRouteRecoveryGeneration &+= 1
+ self.benchmarkLog(
+ "bluetooth_start_route_invalidation_retry event=\(reason) " +
+ "routeGeneration=\(self.audioRouteRecoveryGeneration)"
+ )
+ return
+ }
+ if disposition == .preserveDeferredWork {
+ self.deferredBluetoothStartupRouteRecovery.preserve(
+ reason: reason,
+ requiresIdlePrewarm: requiresIdlePrewarm,
+ reconcilesInputSelection: reconcilesInputSelection
+ )
+ }
self.benchmarkLog(
"bluetooth_start_route_change_deferred event=\(reason) " +
- "reconciliationPreserved=\(preserved)"
+ "disposition=\(disposition)"
)
return
}
@@ -3604,7 +3623,8 @@ final class ASRService: ObservableObject {
)
self.scheduleAudioRouteRecovery(
reason: "direct format changed: \(invalidation.reason)",
- requiresIdlePrewarm: true
+ requiresIdlePrewarm: true,
+ invalidatesCurrentStart: true
)
}
diff --git a/Sources/Fluid/Services/AudioCaptureIdlePolicy.swift b/Sources/Fluid/Services/AudioCaptureIdlePolicy.swift
index f6b251cf..9350d6fc 100644
--- a/Sources/Fluid/Services/AudioCaptureIdlePolicy.swift
+++ b/Sources/Fluid/Services/AudioCaptureIdlePolicy.swift
@@ -1,6 +1,12 @@
import CoreAudio
enum AudioCaptureIdlePolicy {
+ enum BluetoothStartupRouteChangeDisposition: Equatable {
+ case retryCurrentStart
+ case preserveDeferredWork
+ case ignore
+ }
+
struct DeferredBluetoothRouteRecovery {
struct Request {
let reason: String
@@ -39,12 +45,12 @@ enum AudioCaptureIdlePolicy {
private var hasRequestedRecovery = false
mutating func shouldRecover(
- isBuiltInInput: Bool,
+ isInternalMicrophone: Bool,
isDirectCapture: Bool,
rms: Float,
peak: Float
) -> Bool {
- guard isBuiltInInput, isDirectCapture, self.hasRequestedRecovery == false else { return false }
+ guard isInternalMicrophone, isDirectCapture, self.hasRequestedRecovery == false else { return false }
let isEffectivelySilent = rms <= Self.maximumSilentRMS && peak <= Self.maximumSilentPeak
if isEffectivelySilent == false {
self.hasSeenSignal = true
@@ -60,7 +66,10 @@ enum AudioCaptureIdlePolicy {
}
struct BluetoothInputStabilization {
- static let maximumDuration: TimeInterval = 5
+ /// New same-device retries may begin within this window. An admitted
+ /// attempt still gets its normal readiness timeout so a nearly settled
+ /// Bluetooth route is not cancelled at the deadline.
+ static let retryAdmissionWindow: TimeInterval = 5
private(set) var inputUID: String?
private(set) var startedAt: TimeInterval?
@@ -75,7 +84,7 @@ enum AudioCaptureIdlePolicy {
self.inputUID = inputUID
self.startedAt = now
}
- return self.elapsed(at: now) < Self.maximumDuration
+ return self.elapsed(at: now) < Self.retryAdmissionWindow
}
func elapsed(at now: TimeInterval) -> TimeInterval {
@@ -146,6 +155,20 @@ enum AudioCaptureIdlePolicy {
directCaptureEnabled && isStarting && isRunning == false && attemptedInputIsBluetooth
}
+ static func bluetoothStartupRouteChangeDisposition(
+ invalidatesCurrentStart: Bool,
+ requiresIdlePrewarm: Bool,
+ reconcilesInputSelection: Bool
+ ) -> BluetoothStartupRouteChangeDisposition {
+ if invalidatesCurrentStart {
+ return .retryCurrentStart
+ }
+ if requiresIdlePrewarm || reconcilesInputSelection {
+ return .preserveDeferredWork
+ }
+ return .ignore
+ }
+
static func shouldRecoverAfterDeferredBluetoothReconciliation(
isRunning: Bool,
confirmedInputUID: String?,
diff --git a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
index 59265781..c2614f1e 100644
--- a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
+++ b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
@@ -652,10 +652,20 @@ final class HotkeyShortcutTests: XCTestCase {
)
XCTAssertTrue(builtInDevice.isBuiltIn)
+ XCTAssertTrue(builtInDevice.isUnavailableWhenClamshellClosed)
XCTAssertFalse(builtInDevice.isBluetooth)
+
+ let analogHeadset = Self.device(
+ uid: "analog-headset",
+ name: "External Microphone",
+ transportType: kAudioDeviceTransportTypeBuiltIn,
+ inputDataSourceID: AudioDevice.Device.externalMicrophoneDataSourceID
+ )
+ XCTAssertTrue(analogHeadset.isBuiltIn)
+ XCTAssertFalse(analogHeadset.isUnavailableWhenClamshellClosed)
}
- func testBluetoothStartupRetriesSameInputWithinBoundedWindow() {
+ func testBluetoothStartupAdmitsSameInputRetriesWithinFiveSecondWindow() {
var stabilization = AudioCaptureIdlePolicy.BluetoothInputStabilization()
XCTAssertTrue(stabilization.shouldRetry(
@@ -701,6 +711,31 @@ final class HotkeyShortcutTests: XCTestCase {
isRunning: false,
attemptedInputIsBluetooth: false
))
+
+ XCTAssertEqual(
+ AudioCaptureIdlePolicy.bluetoothStartupRouteChangeDisposition(
+ invalidatesCurrentStart: true,
+ requiresIdlePrewarm: true,
+ reconcilesInputSelection: false
+ ),
+ .retryCurrentStart
+ )
+ XCTAssertEqual(
+ AudioCaptureIdlePolicy.bluetoothStartupRouteChangeDisposition(
+ invalidatesCurrentStart: false,
+ requiresIdlePrewarm: true,
+ reconcilesInputSelection: true
+ ),
+ .preserveDeferredWork
+ )
+ XCTAssertEqual(
+ AudioCaptureIdlePolicy.bluetoothStartupRouteChangeDisposition(
+ invalidatesCurrentStart: false,
+ requiresIdlePrewarm: false,
+ reconcilesInputSelection: false
+ ),
+ .ignore
+ )
}
func testBluetoothStartupPreservesOnlyExplicitReconciliationWork() {
@@ -784,56 +819,56 @@ final class HotkeyShortcutTests: XCTestCase {
))
}
- func testSilentPCMWatchdogRecoversBuiltInDirectCaptureOnceAfterRealSignal() {
+ func testSilentPCMWatchdogRecoversInternalDirectCaptureOnceAfterRealSignal() {
var watchdog = AudioCaptureIdlePolicy.SilentPCMRecoveryWatchdog()
XCTAssertFalse(watchdog.shouldRecover(
- isBuiltInInput: true, isDirectCapture: true, rms: 0, peak: 0
+ isInternalMicrophone: true, isDirectCapture: true, rms: 0, peak: 0
))
XCTAssertFalse(watchdog.shouldRecover(
- isBuiltInInput: true, isDirectCapture: true, rms: 0.02, peak: 0.08
+ isInternalMicrophone: true, isDirectCapture: true, rms: 0.02, peak: 0.08
))
for _ in 0..<(AudioCaptureIdlePolicy.SilentPCMRecoveryWatchdog.requiredSilentWindows - 1) {
XCTAssertFalse(watchdog.shouldRecover(
- isBuiltInInput: true, isDirectCapture: true, rms: 0, peak: 0
+ isInternalMicrophone: true, isDirectCapture: true, rms: 0, peak: 0
))
}
XCTAssertTrue(watchdog.shouldRecover(
- isBuiltInInput: true, isDirectCapture: true, rms: 0, peak: 0
+ isInternalMicrophone: true, isDirectCapture: true, rms: 0, peak: 0
))
XCTAssertFalse(watchdog.shouldRecover(
- isBuiltInInput: true, isDirectCapture: true, rms: 0, peak: 0
+ isInternalMicrophone: true, isDirectCapture: true, rms: 0, peak: 0
))
}
func testSilentPCMWatchdogIgnoresExternalAndLowAmbientInputs() {
var externalWatchdog = AudioCaptureIdlePolicy.SilentPCMRecoveryWatchdog()
XCTAssertFalse(externalWatchdog.shouldRecover(
- isBuiltInInput: false, isDirectCapture: true, rms: 0.02, peak: 0.08
+ isInternalMicrophone: false, isDirectCapture: true, rms: 0.02, peak: 0.08
))
for _ in 0...AudioCaptureIdlePolicy.SilentPCMRecoveryWatchdog.requiredSilentWindows {
XCTAssertFalse(externalWatchdog.shouldRecover(
- isBuiltInInput: false, isDirectCapture: true, rms: 0, peak: 0
+ isInternalMicrophone: false, isDirectCapture: true, rms: 0, peak: 0
))
}
var legacyCaptureWatchdog = AudioCaptureIdlePolicy.SilentPCMRecoveryWatchdog()
XCTAssertFalse(legacyCaptureWatchdog.shouldRecover(
- isBuiltInInput: true, isDirectCapture: false, rms: 0.02, peak: 0.08
+ isInternalMicrophone: true, isDirectCapture: false, rms: 0.02, peak: 0.08
))
for _ in 0...AudioCaptureIdlePolicy.SilentPCMRecoveryWatchdog.requiredSilentWindows {
XCTAssertFalse(legacyCaptureWatchdog.shouldRecover(
- isBuiltInInput: true, isDirectCapture: false, rms: 0, peak: 0
+ isInternalMicrophone: true, isDirectCapture: false, rms: 0, peak: 0
))
}
var ambientWatchdog = AudioCaptureIdlePolicy.SilentPCMRecoveryWatchdog()
XCTAssertFalse(ambientWatchdog.shouldRecover(
- isBuiltInInput: true, isDirectCapture: true, rms: 0.02, peak: 0.08
+ isInternalMicrophone: true, isDirectCapture: true, rms: 0.02, peak: 0.08
))
for _ in 0...AudioCaptureIdlePolicy.SilentPCMRecoveryWatchdog.requiredSilentWindows {
XCTAssertFalse(ambientWatchdog.shouldRecover(
- isBuiltInInput: true, isDirectCapture: true, rms: 0.000_1, peak: 0.001
+ isInternalMicrophone: true, isDirectCapture: true, rms: 0.000_1, peak: 0.001
))
}
}