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): recover malformed direct capture

altic-dev5f34b1a92f0b
diff --git a/Sources/CoreAudioCaptureSupport/CoreAudioCaptureSupport.c b/Sources/CoreAudioCaptureSupport/CoreAudioCaptureSupport.c
index 07f631fd..5cebb086 100644
--- a/Sources/CoreAudioCaptureSupport/CoreAudioCaptureSupport.c
+++ b/Sources/CoreAudioCaptureSupport/CoreAudioCaptureSupport.c
@@ -171,6 +171,27 @@ static inline float fv_read_sample(
}
}
+uint32_t fv_core_audio_buffer_bytes_per_frame(
+ uint32_t bytesPerSample,
+ uint32_t channelCount
+) {
+ if (bytesPerSample == 0 || channelCount == 0 ||
+ bytesPerSample > UINT32_MAX / channelCount) {
+ return 0;
+ }
+ return bytesPerSample * channelCount;
+}
+
+uint32_t fv_core_audio_buffer_frame_count(
+ uint32_t dataByteSize,
+ uint32_t bytesPerSample,
+ uint32_t channelCount
+) {
+ const uint32_t bytesPerFrame =
+ fv_core_audio_buffer_bytes_per_frame(bytesPerSample, channelCount);
+ return bytesPerFrame == 0 ? 0 : dataByteSize / bytesPerFrame;
+}
+
static uint32_t fv_frame_count(
const FVCapture *capture,
const AudioBufferList *inputData
@@ -182,7 +203,19 @@ static uint32_t fv_frame_count(
if (buffer->mData == NULL || buffer->mDataByteSize == 0) {
continue;
}
- const uint32_t frames = buffer->mDataByteSize / capture->format.mBytesPerFrame;
+ // Derive the stride from the actual AudioBuffer layout. Core Audio can
+ // expose one buffer per channel even when the device's virtual ASBD
+ // temporarily reports the stream-wide interleaved byte stride during
+ // a route change. Using ASBD.mBytesPerFrame in that state turns a
+ // 512-frame, 3-buffer callback into 170 frames and speeds audio up 3x.
+ const uint32_t frames = fv_core_audio_buffer_frame_count(
+ buffer->mDataByteSize,
+ capture->bytesPerSample,
+ buffer->mNumberChannels
+ );
+ if (frames == 0) {
+ continue;
+ }
if (frames < frameCount) {
frameCount = frames;
}
@@ -242,8 +275,10 @@ static OSStatus fv_io_proc(
const uint8_t *data = (const uint8_t *) buffer->mData;
const uint32_t channelCount = buffer->mNumberChannels;
+ const uint32_t bufferBytesPerFrame =
+ fv_core_audio_buffer_bytes_per_frame(capture->bytesPerSample, channelCount);
for (uint32_t frame = 0; frame < frameCount; ++frame) {
- const uint8_t *frameData = data + frame * capture->format.mBytesPerFrame;
+ const uint8_t *frameData = data + frame * bufferBytesPerFrame;
float sum = 0.0f;
for (uint32_t channel = 0; channel < channelCount; ++channel) {
sum += fv_read_sample(
diff --git a/Sources/CoreAudioCaptureSupport/include/CoreAudioCaptureSupport.h b/Sources/CoreAudioCaptureSupport/include/CoreAudioCaptureSupport.h
index f733297a..a8c3dd72 100644
--- a/Sources/CoreAudioCaptureSupport/include/CoreAudioCaptureSupport.h
+++ b/Sources/CoreAudioCaptureSupport/include/CoreAudioCaptureSupport.h
@@ -20,6 +20,17 @@ typedef struct {
uint64_t sequence;
} FVCoreAudioPacket;
+/// Layout helpers shared by capture and deterministic tests.
+uint32_t fv_core_audio_buffer_bytes_per_frame(
+ uint32_t bytesPerSample,
+ uint32_t channelCount
+);
+uint32_t fv_core_audio_buffer_frame_count(
+ uint32_t dataByteSize,
+ uint32_t bytesPerSample,
+ uint32_t channelCount
+);
+
/// Creates a prepared, input-only capture for one physical Core Audio device.
/// The device is not started and the microphone is not active until start.
int32_t fv_core_audio_capture_create(
diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swift
index bc100315..074486b2 100644
--- a/Sources/Fluid/Persistence/SettingsStore.swift
+++ b/Sources/Fluid/Persistence/SettingsStore.swift
@@ -1727,6 +1727,11 @@ final class SettingsStore: ObservableObject {
}
}
+ var directAudioCaptureConsecutiveFailures: Int {
+ get { self.defaults.integer(forKey: Keys.directAudioCaptureConsecutiveFailures) }
+ set { self.defaults.set(max(0, newValue), forKey: Keys.directAudioCaptureConsecutiveFailures) }
+ }
+
var copyTranscriptionToClipboard: Bool {
get { self.defaults.bool(forKey: Keys.copyTranscriptionToClipboard) }
set { self.defaults.set(newValue, forKey: Keys.copyTranscriptionToClipboard) }
@@ -4784,6 +4789,7 @@ private extension SettingsStore {
static let enableStreamingPreview = "EnableStreamingPreview"
static let enableAIStreaming = "EnableAIStreaming"
static let experimentalDirectAudioCaptureEnabled = "ExperimentalDirectAudioCaptureEnabled"
+ static let directAudioCaptureConsecutiveFailures = "DirectAudioCaptureConsecutiveFailures"
static let copyTranscriptionToClipboard = "CopyTranscriptionToClipboard"
static let textInsertionMode = "TextInsertionMode"
static let autoUpdateCheckEnabled = "AutoUpdateCheckEnabled"
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index 60a777b6..74f834a8 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -39,7 +39,7 @@ private actor TranscriptionExecutor {
}
}
-// swiftlint:disable type_body_length
+// swiftlint:disable file_length type_body_length
/// A comprehensive speech recognition service that handles real-time audio transcription.
///
/// This service manages the entire ASR (Automatic Speech Recognition) pipeline including:
@@ -72,6 +72,19 @@ private actor TranscriptionExecutor {
/// Models are cached locally to avoid repeated downloads.
@MainActor
final class ASRService: ObservableObject {
+ nonisolated static func directCaptureDurationIsMismatched(
+ capturedMilliseconds: Int,
+ elapsedMilliseconds: Int
+ ) -> Bool {
+ guard elapsedMilliseconds >= 500 else { return false }
+ return capturedMilliseconds * 10 < elapsedMilliseconds * 7 ||
+ capturedMilliseconds * 10 > elapsedMilliseconds * 13
+ }
+
+ nonisolated static func directCaptureShouldDisable(afterFailureCount failureCount: Int) -> Bool {
+ failureCount >= 3
+ }
+
@Published var isRunning: Bool = false
@Published var finalText: String = ""
@Published var partialTranscription: String = ""
@@ -598,6 +611,8 @@ final class ASRService: ObservableObject {
private var directAudioInput: DirectCoreAudioInput?
private var activeAudioCaptureBackend: AudioCaptureBackend = .none
+ private var directCaptureIncompatibleDeviceIDs: Set<AudioObjectID> = []
+ private var isFallingBackFromDirectCapture = false
private var hasPreparedAudioCapture: Bool {
self.directAudioInput != nil || self.hasWarmAudioEngine
@@ -726,6 +741,13 @@ final class ASRService: ObservableObject {
DebugLogger.shared.warning("No input device is available for direct capture", source: "ASRService")
return false
}
+ guard self.directCaptureIncompatibleDeviceIDs.contains(device.id) == false else {
+ DebugLogger.shared.warning(
+ "Skipping direct Core Audio input for '\(device.name)' after a runtime capture mismatch",
+ source: "ASRService"
+ )
+ return false
+ }
if let directAudioInput = self.directAudioInput,
directAudioInput.deviceID == device.id
@@ -838,6 +860,85 @@ final class ASRService: ObservableObject {
self.activeAudioCaptureBackend = .none
}
+ private func handleDirectCaptureDurationMismatch(
+ sessionID: Int,
+ capturedMilliseconds: Int,
+ elapsedMilliseconds: Int
+ ) async {
+ guard sessionID == self.benchmarkSessionID,
+ self.isRunning,
+ self.activeAudioCaptureBackend == .directCoreAudio,
+ self.isFallingBackFromDirectCapture == false
+ else { return }
+
+ self.isFallingBackFromDirectCapture = true
+ defer { self.isFallingBackFromDirectCapture = false }
+
+ if let deviceID = self.directAudioInput?.deviceID {
+ self.directCaptureIncompatibleDeviceIDs.insert(deviceID)
+ }
+ let failureCount = SettingsStore.shared.directAudioCaptureConsecutiveFailures + 1
+ SettingsStore.shared.directAudioCaptureConsecutiveFailures = failureCount
+ let shouldDisable = Self.directCaptureShouldDisable(afterFailureCount: failureCount)
+ if shouldDisable {
+ SettingsStore.shared.experimentalDirectAudioCaptureEnabled = false
+ }
+ NotificationService.showAudioCaptureFallback(
+ failureCount: failureCount,
+ experimentalSettingDisabled: shouldDisable
+ )
+ DebugLogger.shared.error(
+ "DIRECT_CAPTURE_RATE_MISMATCH session=\(sessionID) " +
+ "capturedMs=\(capturedMilliseconds) elapsedMs=\(elapsedMilliseconds); " +
+ "switching to AVAudioEngine",
+ source: "ASRService"
+ )
+ self.benchmarkLog(
+ "direct_capture_fallback reason=duration_mismatch " +
+ "capturedMs=\(capturedMilliseconds) elapsedMs=\(elapsedMilliseconds)"
+ )
+
+ self.audioCapturePipeline.setRecordingEnabled(false)
+ self.stopActiveAudioCapture()
+ self.directAudioInput?.invalidate()
+ self.directAudioInput = nil
+ await self.stopStreamingTimerAndAwait()
+ self.audioBuffer.clear(keepingCapacity: true)
+ self.lastProcessedSampleCount = 0
+ self.benchmarkLastChunkSampleCount = 0
+ (self.transcriptionProvider as? FluidAudioProvider)?.resetStreamingPreviewCache()
+
+ do {
+ self.audioCapturePipeline.setRecordingEnabled(
+ true,
+ sessionID: sessionID,
+ startHostTime: mach_absolute_time()
+ )
+ try self.startPreferredAudioCapture()
+ let model = SettingsStore.shared.selectedSpeechModel
+ if model.supportsStreaming, self.isDictionaryTrainingCaptureActive == false {
+ self.startStreamingTranscription()
+ }
+ DebugLogger.shared.info(
+ "Direct capture runtime fallback to AVAudioEngine succeeded",
+ source: "ASRService"
+ )
+ } catch {
+ self.audioCapturePipeline.setRecordingEnabled(false)
+ self.stopActiveAudioCapture()
+ DebugLogger.shared.error(
+ "Direct capture runtime fallback failed: \(error.localizedDescription)",
+ source: "ASRService"
+ )
+ await self.stopWithoutTranscription()
+ NotificationCenter.default.post(
+ name: NSNotification.Name("ASRServiceStartFailed"),
+ object: nil,
+ userInfo: ["errorMessage": "The microphone changed unexpectedly. Please try recording again."]
+ )
+ }
+ }
+
/// Applies the experimental capture preference immediately when idle.
/// If a recording transition is already underway, start() reads the latest
/// persisted value and the following session will use it.
@@ -938,6 +1039,15 @@ final class ASRService: ObservableObject {
)
}
},
+ onDurationMismatch: { [weak self] sessionID, capturedMilliseconds, elapsedMilliseconds in
+ Task { @MainActor [weak self] in
+ await self?.handleDirectCaptureDurationMismatch(
+ sessionID: sessionID,
+ capturedMilliseconds: capturedMilliseconds,
+ elapsedMilliseconds: elapsedMilliseconds
+ )
+ }
+ },
onLevel: { [weak self] level in
// Keep Combine sends on the main queue.
DispatchQueue.main.async { [weak self] in
@@ -1390,6 +1500,22 @@ final class ASRService: ObservableObject {
self.stopMonitoringDevice()
DebugLogger.shared.debug("✅ Device monitoring stopped", source: "ASRService")
+ if self.activeAudioCaptureBackend == .directCoreAudio,
+ let recordingStartedAt = self.benchmarkRecordingStartedAt
+ {
+ let elapsedMilliseconds = Int(
+ (Date().timeIntervalSince1970 - recordingStartedAt) * 1000
+ )
+ let capturedMilliseconds = self.audioBuffer.count * 1000 / 16_000
+ if elapsedMilliseconds >= 500,
+ Self.directCaptureDurationIsMismatched(
+ capturedMilliseconds: capturedMilliseconds,
+ elapsedMilliseconds: elapsedMilliseconds
+ ) == false
+ {
+ SettingsStore.shared.directAudioCaptureConsecutiveFailures = 0
+ }
+ }
self.stopActiveAudioCapture()
self.audioCapturePipeline.finishRecording()
@@ -3612,6 +3738,7 @@ private extension ASRService {
private final nonisolated class AudioCapturePipeline: @unchecked Sendable {
private let audioBuffer: ThreadSafeAudioBuffer
private let onFirstAudio: (Int, Int, Int, Double, Int, Int) -> Void
+ private let onDurationMismatch: (Int, Int, Int) -> Void
private let onLevel: (CGFloat) -> Void
private let lock = NSLock()
@@ -3620,6 +3747,8 @@ private final nonisolated class AudioCapturePipeline: @unchecked Sendable {
private var recordingSessionID: Int = 0
private var recordingStartHostTime: UInt64 = 0
private var recordingStopHostTime: UInt64?
+ private var capturedOutputFrameCount: Int = 0
+ private var durationMismatchReported: Bool = false
private var resampleSourceRate: Double = 0
private var resampleSourceFrameCursor: Int64 = 0
private var resampleNextSourcePosition: Double = 0
@@ -3642,10 +3771,12 @@ private final nonisolated class AudioCapturePipeline: @unchecked Sendable {
init(
audioBuffer: ThreadSafeAudioBuffer,
onFirstAudio: @escaping (Int, Int, Int, Double, Int, Int) -> Void,
+ onDurationMismatch: @escaping (Int, Int, Int) -> Void,
onLevel: @escaping (CGFloat) -> Void
) {
self.audioBuffer = audioBuffer
self.onFirstAudio = onFirstAudio
+ self.onDurationMismatch = onDurationMismatch
self.onLevel = onLevel
}
@@ -3660,6 +3791,8 @@ private final nonisolated class AudioCapturePipeline: @unchecked Sendable {
self.recordingSessionID = sessionID
self.recordingStartHostTime = startHostTime == 0 ? mach_absolute_time() : startHostTime
self.recordingStopHostTime = nil
+ self.capturedOutputFrameCount = 0
+ self.durationMismatchReported = false
self.resetResamplerLocked()
self.lastInputSampleEnd = nil
self.recordingEnabled = true
@@ -3669,6 +3802,8 @@ private final nonisolated class AudioCapturePipeline: @unchecked Sendable {
self.recordingSessionID = 0
self.recordingStartHostTime = 0
self.recordingStopHostTime = nil
+ self.capturedOutputFrameCount = 0
+ self.durationMismatchReported = false
self.resetResamplerLocked()
self.lastInputSampleEnd = nil
self.levelHistory.removeAll(keepingCapacity: true)
@@ -3796,6 +3931,20 @@ private final nonisolated class AudioCapturePipeline: @unchecked Sendable {
if shouldReportFirstAudio {
self.firstAudioReported = true
}
+ self.capturedOutputFrameCount += mono16k.count
+ let capturedMilliseconds = self.capturedOutputFrameCount * 1000 / 16_000
+ let elapsedMilliseconds = Self.elapsedMilliseconds(
+ from: startHostTime,
+ to: mach_absolute_time()
+ )
+ let shouldReportDurationMismatch = self.durationMismatchReported == false &&
+ ASRService.directCaptureDurationIsMismatched(
+ capturedMilliseconds: capturedMilliseconds,
+ elapsedMilliseconds: elapsedMilliseconds
+ )
+ if shouldReportDurationMismatch {
+ self.durationMismatchReported = true
+ }
self.lock.unlock()
self.audioBuffer.append(mono16k)
@@ -3822,6 +3971,13 @@ private final nonisolated class AudioCapturePipeline: @unchecked Sendable {
deliveryMs
)
}
+ if shouldReportDurationMismatch {
+ self.onDurationMismatch(
+ recordingSessionID,
+ capturedMilliseconds,
+ elapsedMilliseconds
+ )
+ }
let level = self.calculateAudioLevel(mono16k)
self.onLevel(level)
}
diff --git a/Sources/Fluid/Services/NotificationService.swift b/Sources/Fluid/Services/NotificationService.swift
index a5bbdbb5..312e0170 100644
--- a/Sources/Fluid/Services/NotificationService.swift
+++ b/Sources/Fluid/Services/NotificationService.swift
@@ -8,9 +8,49 @@ enum NotificationService {
enum Kind {
static let aiProcessingFallback = "aiProcessingFallback"
+ static let audioCaptureFallback = "audioCaptureFallback"
static let commandModeFailure = "commandModeFailure"
}
+ static func showAudioCaptureFallback(
+ failureCount: Int,
+ experimentalSettingDisabled: Bool
+ ) {
+ let center = UNUserNotificationCenter.current()
+ center.getNotificationSettings { settings in
+ switch settings.authorizationStatus {
+ case .authorized, .provisional, .ephemeral:
+ self.deliverAudioCaptureFallback(
+ failureCount: failureCount,
+ experimentalSettingDisabled: experimentalSettingDisabled,
+ using: center
+ )
+ case .notDetermined:
+ center.requestAuthorization(options: [.alert]) { granted, requestError in
+ if let requestError {
+ DebugLogger.shared.warning(
+ "Notification permission request failed: \(requestError.localizedDescription)",
+ source: "NotificationService"
+ )
+ }
+ guard granted else { return }
+ self.deliverAudioCaptureFallback(
+ failureCount: failureCount,
+ experimentalSettingDisabled: experimentalSettingDisabled,
+ using: center
+ )
+ }
+ case .denied:
+ DebugLogger.shared.debug(
+ "Skipping audio capture fallback notification because notification permission is denied",
+ source: "NotificationService"
+ )
+ @unknown default:
+ break
+ }
+ }
+ }
+
static func showAIProcessingFallback(error: String) {
guard SettingsStore.shared.notifyAIProcessingFailures else { return }
@@ -95,6 +135,38 @@ enum NotificationService {
}
}
+ private static func deliverAudioCaptureFallback(
+ failureCount: Int,
+ experimentalSettingDisabled: Bool,
+ using center: UNUserNotificationCenter
+ ) {
+ let content = UNMutableNotificationContent()
+ if experimentalSettingDisabled {
+ content.title = "Faster Recording Start turned off"
+ content.body = "FluidVoice detected malformed microphone audio three times and switched to the compatibility audio path. You can turn it back on in Settings."
+ } else {
+ content.title = "Microphone audio recovered"
+ content.body = "FluidVoice detected malformed audio and switched this session to the compatibility audio path. Faster Recording Start will retry after restart. (\(failureCount)/3)"
+ }
+ content.sound = nil
+ content.userInfo = [UserInfoKey.kind: Kind.audioCaptureFallback]
+
+ let request = UNNotificationRequest(
+ identifier: "audio-capture-fallback-\(UUID().uuidString)",
+ content: content,
+ trigger: nil
+ )
+
+ center.add(request) { addError in
+ if let addError {
+ DebugLogger.shared.warning(
+ "Failed to show audio capture fallback notification: \(addError.localizedDescription)",
+ source: "NotificationService"
+ )
+ }
+ }
+ }
+
private static func deliverCommandModeFailure(error: String, using center: UNUserNotificationCenter) {
let content = UNMutableNotificationContent()
content.title = "Command Mode needs setup"
diff --git a/Sources/Fluid/UI/SettingsView.swift b/Sources/Fluid/UI/SettingsView.swift
index 46d3342d..730e2a76 100644
--- a/Sources/Fluid/UI/SettingsView.swift
+++ b/Sources/Fluid/UI/SettingsView.swift
@@ -2520,6 +2520,9 @@ private extension SettingsView {
get: { self.settings.experimentalDirectAudioCaptureEnabled },
set: { enabled in
self.settings.experimentalDirectAudioCaptureEnabled = enabled
+ if enabled {
+ self.settings.directAudioCaptureConsecutiveFailures = 0
+ }
self.asr.refreshAudioCaptureBackendPreference()
}
)
diff --git a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
index b7e0f8ee..2f45e12f 100644
--- a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
+++ b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
@@ -9,6 +9,49 @@ final class HotkeyShortcutTests: XCTestCase {
private let pasteLastTranscriptionShortcutKey = "PasteLastTranscriptionHotkeyShortcut"
private let pasteLastTranscriptionEnabledKey = "PasteLastTranscriptionShortcutEnabled"
+ func testCoreAudioFrameCountUsesActualBufferChannelLayout() {
+ XCTAssertEqual(fv_core_audio_buffer_frame_count(512 * 4, 4, 1), 512)
+ XCTAssertEqual(fv_core_audio_buffer_frame_count(512 * 8, 4, 2), 512)
+ XCTAssertEqual(fv_core_audio_buffer_frame_count(512 * 12, 4, 3), 512)
+
+ // Three non-interleaved buffers each contain one channel and must each
+ // report 512 frames, never the 170-frame failure observed in the field.
+ for _ in 0..<3 {
+ XCTAssertEqual(fv_core_audio_buffer_frame_count(512 * 4, 4, 1), 512)
+ }
+ }
+
+ func testDirectCaptureDurationMismatchFilter() {
+ XCTAssertFalse(ASRService.directCaptureDurationIsMismatched(
+ capturedMilliseconds: 100,
+ elapsedMilliseconds: 499
+ ))
+ XCTAssertFalse(ASRService.directCaptureDurationIsMismatched(
+ capturedMilliseconds: 460,
+ elapsedMilliseconds: 500
+ ))
+ XCTAssertFalse(ASRService.directCaptureDurationIsMismatched(
+ capturedMilliseconds: 700,
+ elapsedMilliseconds: 1000
+ ))
+ XCTAssertFalse(ASRService.directCaptureDurationIsMismatched(
+ capturedMilliseconds: 1300,
+ elapsedMilliseconds: 1000
+ ))
+ XCTAssertTrue(ASRService.directCaptureDurationIsMismatched(
+ capturedMilliseconds: 333,
+ elapsedMilliseconds: 1000
+ ))
+ XCTAssertTrue(ASRService.directCaptureDurationIsMismatched(
+ capturedMilliseconds: 1500,
+ elapsedMilliseconds: 1000
+ ))
+ XCTAssertFalse(ASRService.directCaptureShouldDisable(afterFailureCount: 1))
+ XCTAssertFalse(ASRService.directCaptureShouldDisable(afterFailureCount: 2))
+ XCTAssertTrue(ASRService.directCaptureShouldDisable(afterFailureCount: 3))
+ XCTAssertTrue(ASRService.directCaptureShouldDisable(afterFailureCount: 4))
+ }
+
func testLegacyKeyboardShortcutPayloadDefaultsToKeyboardKind() throws {
let json = #"{"keyCode":61,"modifierFlagsRawValue":0}"#
let data = try XCTUnwrap(json.data(using: .utf8))