forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAudioCaptureService.swift
More file actions
1253 lines (1093 loc) · 47.4 KB
/
Copy pathAudioCaptureService.swift
File metadata and controls
1253 lines (1093 loc) · 47.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
@preconcurrency import AVFoundation
@preconcurrency import CoreAudio
import Foundation
/// Service for capturing microphone audio as 16-bit PCM at 16kHz
/// Uses CoreAudio IOProc directly on the default input device to avoid
/// AVAudioEngine's implicit aggregate device creation, which degrades
/// system audio output quality (especially Bluetooth A2DP → SCO switch).
class AudioCaptureService: @unchecked Sendable {
// MARK: - Types
/// A currently available CoreAudio input device. `uid` stays stable when
/// CoreAudio assigns a different numeric device ID after reconnecting it.
struct InputDevice: Hashable {
let id: AudioDeviceID
let uid: String
let name: String
}
/// Callback for receiving audio chunks
typealias AudioChunkHandler = @Sendable (Data) -> Void
/// Callback for receiving audio levels (0.0 - 1.0)
typealias AudioLevelHandler = @Sendable (Float) -> Void
enum SilentMicRecoveryAction {
case fallbackToBuiltIn
case rebuildCoreAudioStack
}
struct SilentMicDetection {
let deviceID: AudioDeviceID
let deviceDescription: String
let consecutiveSilentWindows: Int
let isBluetoothTransport: Bool
var suggestedAction: SilentMicRecoveryAction {
isBluetoothTransport ? .fallbackToBuiltIn : .rebuildCoreAudioStack
}
var reason: String {
"silent input on \(deviceDescription) after \(consecutiveSilentWindows) windows"
}
}
enum AudioCaptureError: LocalizedError {
case noInputAvailable
case engineStartFailed(Error)
case permissionDenied
case converterCreationFailed
var errorDescription: String? {
switch self {
case .noInputAvailable:
return "No audio input device available"
case .engineStartFailed(let error):
return "Failed to start audio engine: \(error.localizedDescription)"
case .permissionDenied:
return "Microphone permission denied"
case .converterCreationFailed:
return "Failed to create audio converter"
}
}
}
// MARK: - Properties
private var deviceID: AudioDeviceID = kAudioObjectUnknown
private var ioProcID: AudioDeviceIOProcID?
private var defaultDeviceListenerBlock: AudioObjectPropertyListenerBlock?
private var deviceFormatListenerBlock: AudioObjectPropertyListenerBlock?
private var isCapturing = false
private var isTrackingOverrideDevice = false
/// Optional explicit device to open instead of the system default input.
/// Used by the silent-mic fallback path to bind directly to the built-in mic.
private let overrideDeviceID: AudioDeviceID?
/// True when this service was built to pin capture to an explicit device.
var hasOverrideDevice: Bool { overrideDeviceID != nil }
/// CoreAudio device currently opened by this service (for preferred-mic reconnect).
var activeDeviceID: AudioDeviceID { deviceID }
/// Default initializer — opens the system default input device.
init() {
self.overrideDeviceID = nil
}
/// Initializer that binds to an explicit CoreAudio device (e.g. built-in mic after
/// a silent-mic fallback). Pass `kAudioObjectUnknown` to disable the override.
init(overrideDeviceID: AudioDeviceID) {
self.overrideDeviceID = (overrideDeviceID == kAudioObjectUnknown) ? nil : overrideDeviceID
}
private var onAudioChunk: AudioChunkHandler?
private var onAudioLevel: AudioLevelHandler?
/// Called when the mic has been alive-but-silent for `silentMicWindowThreshold`
/// windows. By default this is limited to Bluetooth inputs, where macOS can feed
/// zeros during A2DP/HFP profile conflicts. PTT enables all-transport detection so
/// it can recover a stale HAL route that reports the built-in mic but still returns
/// silence. The watchdog re-arms after each fire (see `evaluateSilentMicWindow`), so a
/// single capture session can recover from more than one silent episode.
var onSilentMicDetected: (@Sendable (SilentMicDetection) -> Void)?
var detectSilentMicOnAnyTransport = false
/// Fires (once per change) when the HAL reports a device/format/route change
/// during an active capture — a known precursor of silent capture (headset
/// plug/unplug, Bluetooth profile flip, default-input switch). Carries no
/// device identity; owners record only a boolean "route changed" flag.
var onInputRouteChanged: (@Sendable () -> Void)?
/// Human-readable description of the capture device currently in use — for
/// diagnostics (which mic a turn was recorded from).
var currentDeviceDescription: String {
let isBuiltIn = (deviceID == AudioCaptureService.findBuiltInMicDeviceID())
return isBuiltIn ? "built-in id=\(deviceID)" : "id=\(deviceID)"
}
/// Whether the active capture device is on a Bluetooth transport (A2DP/HFP),
/// the known profile-conflict case that feeds zeros. Exposed so the PTT
/// lifecycle route classification can label Bluetooth without logging the
/// device name. Derives from CoreAudio transport type, not the redacted
/// `currentDeviceDescription` string.
var isCurrentDeviceBluetoothTransport: Bool {
Self.isBluetoothTransport(deviceID: deviceID)
}
// Silent-mic watchdog. Re-arms after each fire so one session can recover from more
// than one silent episode; two guards keep it from spinning the recovery loop:
// - `silentMicRecoveryCooldown`: suppress re-detection right after a fire so a freshly
// rebuilt/switched capture has time to deliver real audio before we judge it again.
// - `maxSilentMicFiresPerSession`: hard cap so an unrecoverable mic can't loop forever.
// `silentMicDetectedFired` now means "recently fired, awaiting re-arm" (not a permanent latch).
private var consecutiveSilentWindows: Int = 0
private var silentMicDetectedFired: Bool = false
private var silentMicFireCount: Int = 0
private var lastSilentMicFireTime: CFAbsoluteTime = 0
private let silentMicWindowThreshold: Int = 2 // windows of ~1s each
private let silentMicRecoveryCooldown: CFAbsoluteTime = 3.0 // seconds to let recovery take effect
private let maxSilentMicFiresPerSession: Int = 3
/// Target sample rate for DeepGram
private let targetSampleRate: Double = 16000
// Resampling
private var audioConverter: AVAudioConverter?
private var inputFormat: AVAudioFormat?
private var targetFormat: AVAudioFormat?
private var detectedSampleRate: Double = 0.0
// Flipped exactly once per convert() call by the synchronous AVAudioConverter input
// block (a @Sendable closure) on the non-reentrant CoreAudio IO thread. nonisolated(unsafe)
// because the IOProc is serial; it is reset at the top of every handleAudioInput() call.
private nonisolated(unsafe) var hasConsumedInput = false
// Audio level smoothing (for natural decay like system audio)
private var smoothedLevel: Float = 0.0
private let noiseFloor: Float = 0.005 // Very low threshold for preamp noise
private let decayRate: Float = 0.85 // Decay multiplier per frame (lower = faster decay)
// Device change handling
private var isReconfiguring = false
private let listenerQueue = DispatchQueue(label: "com.omi.audiocapture.listener")
// Silent-mic watchdog state — tracks peak amplitude within a ~1 second window
// so we can detect a Bluetooth mic that's alive-but-silent (A2DP profile conflict).
private var watchdogWindowPeak: Int16 = 0
private var watchdogWindowStart: CFAbsoluteTime = 0
private let silentMicWatchdogLock = NSLock()
/// Dedicated queue for CoreAudio device operations (start/stop/reconfigure)
/// to avoid blocking the main thread on AudioDeviceStart/Stop calls.
private let audioQueue = DispatchQueue(label: "com.omi.audiocapture.device")
// MARK: - Public Methods
func resetSilentMicWatchdog() {
silentMicWatchdogLock.lock()
defer { silentMicWatchdogLock.unlock() }
consecutiveSilentWindows = 0
silentMicDetectedFired = false
silentMicFireCount = 0
lastSilentMicFireTime = 0
watchdogWindowPeak = 0
watchdogWindowStart = 0
}
/// Classify one closed ~1-second watchdog window and update re-arm bookkeeping.
///
/// Returns a `SilentMicDetection` when the mic has been silent for
/// `silentMicWindowThreshold` consecutive windows and the watchdog is armed — the
/// caller then invokes `onSilentMicDetected`. Returns `nil` otherwise. After a fire the
/// watchdog suppresses re-detection until `silentMicRecoveryCooldown` has elapsed, then
/// re-arms, so a mic that recovered and later re-wedged (or a recovery that did not take)
/// is detected again — bounded by `maxSilentMicFiresPerSession` so an unrecoverable mic
/// cannot loop the recovery path forever.
///
/// `internal` (not `private`) so the recover-more-than-once-per-session contract can be
/// unit-tested without driving real CoreAudio buffers.
func evaluateSilentMicWindow(peak: Int16, isBluetooth: Bool, now: CFAbsoluteTime) -> SilentMicDetection? {
silentMicWatchdogLock.lock()
defer { silentMicWatchdogLock.unlock() }
return evaluateSilentMicWindowLocked(peak: peak, isBluetooth: isBluetooth, now: now)
}
private func evaluateSilentMicWindowLocked(
peak: Int16,
isBluetooth: Bool,
now: CFAbsoluteTime
) -> SilentMicDetection? {
// peak ≤ 5 (≈ -76 dBFS) is effectively silent compared to real speech.
if peak <= 5 {
consecutiveSilentWindows += 1
} else {
consecutiveSilentWindows = 0
}
// Re-arm once the post-fire cooldown has elapsed.
if silentMicDetectedFired, now - lastSilentMicFireTime >= silentMicRecoveryCooldown {
silentMicDetectedFired = false
}
guard !silentMicDetectedFired,
silentMicFireCount < maxSilentMicFiresPerSession,
consecutiveSilentWindows >= silentMicWindowThreshold,
isBluetooth || detectSilentMicOnAnyTransport
else {
return nil
}
let firedWindows = consecutiveSilentWindows
silentMicDetectedFired = true
silentMicFireCount += 1
lastSilentMicFireTime = now
// Require a fresh run of silent windows before the next fire so we never re-trigger
// on the very next window.
consecutiveSilentWindows = 0
return SilentMicDetection(
deviceID: deviceID,
deviceDescription: currentDeviceDescription,
consecutiveSilentWindows: firedWindows,
isBluetoothTransport: isBluetooth
)
}
/// Check if microphone permission is granted
static func checkPermission() -> Bool {
switch AVCaptureDevice.authorizationStatus(for: .audio) {
case .authorized:
return true
case .notDetermined, .denied, .restricted:
return false
@unknown default:
return false
}
}
/// Check if microphone permission was explicitly denied by the user
static func isPermissionDenied() -> Bool {
return AVCaptureDevice.authorizationStatus(for: .audio) == .denied
}
/// Get the current authorization status
static func authorizationStatus() -> AVAuthorizationStatus {
return AVCaptureDevice.authorizationStatus(for: .audio)
}
/// Request microphone permission
static func requestPermission() async -> Bool {
return await withCheckedContinuation { continuation in
AVCaptureDevice.requestAccess(for: .audio) { granted in
continuation.resume(returning: granted)
}
}
}
/// Start capturing audio from microphone
/// - Parameters:
/// - onAudioChunk: Callback receiving 16-bit PCM audio data chunks at 16kHz
/// - onAudioLevel: Optional callback receiving normalized audio level (0.0 - 1.0)
func startCapture(onAudioChunk: @escaping AudioChunkHandler, onAudioLevel: AudioLevelHandler? = nil) async throws {
guard !isCapturing else {
log("AudioCapture: Already capturing")
return
}
resetSilentMicWatchdog()
// All CoreAudio HAL calls (AudioObjectGetPropertyData, AudioDeviceStart, etc.) are
// synchronous IPC to coreaudiod via mach_msg. After wake from sleep the daemon can
// take seconds to respond, blocking the caller. Dispatch the entire setup to audioQueue,
// mirroring the pattern already used in stopCapture() and handleConfigurationChange().
// The callback assignments live on audioQueue too: the serial queue is the single
// owner of all state the HAL IO thread reads (callbacks, converter, formats), so a
// stop's deferred clear and a restart's fresh assignment can never interleave.
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
audioQueue.async { [weak self] in
guard let self else {
continuation.resume()
return
}
self.onAudioChunk = onAudioChunk
self.onAudioLevel = onAudioLevel
do {
try self.startCaptureOnQueue()
continuation.resume()
} catch {
continuation.resume(throwing: error)
}
}
}
}
/// Performs all blocking CoreAudio HAL setup. Must be called on audioQueue, not the main thread.
private func startCaptureOnQueue() throws {
resetSilentMicWatchdog()
// 1. Resolve input device: explicit override wins while available, otherwise
// fall back to the system default instead of pinning capture to a stale device.
let inputDeviceID = try resolveInputDeviceID()
self.deviceID = inputDeviceID
registerActiveCapture(deviceID: inputDeviceID)
// 2. Get device stream format
guard let streamFormat = getStreamFormat(for: deviceID) else {
unregisterActiveCapture()
throw AudioCaptureError.noInputAvailable
}
detectedSampleRate = streamFormat.mSampleRate
log("AudioCapture: Hardware format - \(streamFormat.mSampleRate)Hz, \(streamFormat.mChannelsPerFrame) channels")
// 3. Create mono input format (we mix to mono before conversion)
guard
let inputFmt = AVAudioFormat(
commonFormat: .pcmFormatFloat32,
sampleRate: streamFormat.mSampleRate,
channels: 1,
interleaved: false
)
else {
unregisterActiveCapture()
throw AudioCaptureError.converterCreationFailed
}
self.inputFormat = inputFmt
// 4. Create target format: Float32 at 16kHz mono
guard let targetFmt = AVAudioFormat(standardFormatWithSampleRate: targetSampleRate, channels: 1) else {
unregisterActiveCapture()
throw AudioCaptureError.converterCreationFailed
}
self.targetFormat = targetFmt
log("AudioCapture: Target format - \(targetFmt.sampleRate)Hz, \(targetFmt.channelCount) channels, Float32")
// 5. Create audio converter for resampling
guard let converter = AVAudioConverter(from: inputFmt, to: targetFmt) else {
unregisterActiveCapture()
throw AudioCaptureError.converterCreationFailed
}
self.audioConverter = converter
// 6. Create IOProc on the input device directly (no aggregate device)
var procID: AudioDeviceIOProcID?
let ioProcStatus = AudioDeviceCreateIOProcIDWithBlock(&procID, deviceID, nil) {
[weak self] inNow, inInputData, inInputTime, outOutputData, inOutputTime in
self?.handleAudioInput(inInputData, timestamp: inInputTime)
}
guard ioProcStatus == noErr, let validProcID = procID else {
unregisterActiveCapture()
throw AudioCaptureError.engineStartFailed(
NSError(
domain: "AudioCapture", code: Int(ioProcStatus),
userInfo: [NSLocalizedDescriptionKey: "Failed to create IOProc: \(ioProcStatus)"])
)
}
self.ioProcID = validProcID
// 7. Start the device
let startStatus = AudioDeviceStart(deviceID, validProcID)
guard startStatus == noErr else {
AudioDeviceDestroyIOProcID(deviceID, validProcID)
self.ioProcID = nil
unregisterActiveCapture()
throw AudioCaptureError.engineStartFailed(
NSError(
domain: "AudioCapture", code: Int(startStatus),
userInfo: [NSLocalizedDescriptionKey: "Failed to start device: \(startStatus)"])
)
}
isCapturing = true
log("AudioCapture: Started capturing")
// 8. Install property listeners for device changes
installPropertyListeners()
}
/// Stop capturing audio
func stopCapture() {
resetSilentMicWatchdog()
guard isCapturing else { return }
removePropertyListeners()
// Capture values before clearing state so we can dispatch the heavy
// CoreAudio calls off the main thread.
let procID = self.ioProcID
let devID = self.deviceID
ioProcID = nil
deviceID = kAudioObjectUnknown
isCapturing = false
isReconfiguring = false
isTrackingOverrideDevice = false
// Do NOT release the state handleAudioInput reads (callbacks, converter,
// formats, detectedSampleRate) here: the CoreAudio HAL IO thread can still be
// inside handleAudioInput until AudioDeviceStop below returns, and nil-ing
// ARC references from the main thread races its reads (torn retain/release →
// intermittent crash on stop; detectedSampleRate=0 would divide-by-zero the
// resample math). The serial audioQueue quiesces the IOProc first and then
// clears; startCapture assigns this state on the same queue, so a stop's
// clear and a restart's fresh assignment can never interleave.
// AudioDeviceStop can block waiting for the IO thread — run off main thread.
let teardownToken = activeCaptureToken
audioQueue.async { [weak self] in
if let procID = procID, devID != kAudioObjectUnknown {
AudioDeviceStop(devID, procID)
AudioDeviceDestroyIOProcID(devID, procID)
}
// Token unregister: releases physical ownership only after the HAL
// teardown above completes, still runs if the service was deallocated
// while this block waited, and can never collide with a replacement
// service's registration (no reliance on weak self or address identity).
AudioCaptureService.unregisterActiveCapture(token: teardownToken)
guard let self else { return }
self.onAudioChunk = nil
self.onAudioLevel = nil
self.audioConverter = nil
self.inputFormat = nil
self.targetFormat = nil
self.detectedSampleRate = 0.0
self.smoothedLevel = 0.0
}
log("AudioCapture: Stopped capturing")
}
/// Wait until every CoreAudio stop/destroy operation already enqueued by
/// `stopCapture()` has completed. Effective-owner replacement uses this as
/// a hard physical boundary before the new owner becomes visible.
func waitForPhysicalStop() async {
await withCheckedContinuation { continuation in
audioQueue.async {
continuation.resume()
}
}
}
/// Check if currently capturing
var capturing: Bool {
return isCapturing
}
/// The input devices currently available to use for microphone capture.
static func availableInputDevices() -> [InputDevice] {
audioDeviceIDs().compactMap { deviceID in
guard
isAvailableInputDevice(deviceID),
let uid = deviceStringProperty(deviceID, selector: kAudioDevicePropertyDeviceUID)
else { return nil }
return InputDevice(
id: deviceID,
uid: uid,
name: deviceStringProperty(deviceID, selector: kAudioObjectPropertyName) ?? "Microphone"
)
}
.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
}
/// Resolve a persisted CoreAudio device UID to its current numeric ID.
static func inputDeviceID(forUID uid: String) -> AudioDeviceID? {
availableInputDevices().first(where: { $0.uid == uid })?.id
}
/// Ray-Ban Meta / Oakley Meta glasses expose no vendor API on macOS; the
/// input-device name is the only identity signal, so match Meta's product
/// names precisely rather than anything containing "glass".
static func isMetaGlassesName(_ name: String) -> Bool {
let lower = name.lowercased()
// Real glasses often present their EssilorLuxottica codename rather than a
// product name — observed as "EL AI 000F" on hardware. Prefix-anchored so
// it cannot swallow unrelated names like "El Camino AI".
return lower.contains("ray-ban") || lower.contains("rayban")
|| lower.contains("oakley meta") || lower.contains("meta glasses")
|| lower.hasPrefix("el ai ")
}
/// Human-readable name for a CoreAudio device.
static func deviceName(for deviceID: AudioDeviceID) -> String? {
deviceStringProperty(deviceID, selector: kAudioObjectPropertyName)
}
/// UserDefaults key for the user's explicit microphone choice ("" = system default).
static let preferredInputUIDDefaultsKey = DefaultsKey.preferredMicrophoneDeviceUID.rawValue
/// Serializes every preferred-microphone HAL resolution onto one queue: the
/// enumeration has no deadline against a wedged driver, so concurrent callers
/// (session metadata, capture open, retries) must strand at most one worker —
/// later requests wait behind it instead of spawning more blocked tasks.
private static let preferredMicResolveQueue = DispatchQueue(
label: "com.omi.preferred-mic-resolve", qos: .userInitiated)
/// Resolve the persisted preferred-microphone UID to its current device ID
/// and display name, off the calling actor. Returns nil when no selection is
/// set or the device is unavailable.
static func resolvePreferredMicrophone() async -> (id: AudioDeviceID, name: String?)? {
let uid = UserDefaults.standard.string(forKey: preferredInputUIDDefaultsKey) ?? ""
guard !uid.isEmpty else { return nil }
return await withCheckedContinuation { continuation in
preferredMicResolveQueue.async {
guard let id = inputDeviceID(forUID: uid) else {
continuation.resume(returning: nil)
return
}
continuation.resume(returning: (id: id, name: deviceName(for: id)))
}
}
}
// MARK: - Active-capture registry
//
// Tracks which devices are held by a live capture so other audio consumers
// (push-to-talk) can avoid opening a second IOProc against the same device
// — or joining a Bluetooth mic's A2DP↔HFP profile flap — which races the
// two instances' stream-format reconfiguration paths.
private static let activeCapturesLock = NSLock()
// nonisolated(unsafe): every access is guarded by activeCapturesLock (same
// pattern as ScreenCaptureService's lock-guarded statics).
nonisolated(unsafe) private static var activeCaptures: [UUID: AudioDeviceID] = [:]
/// Per-instance registration token. Deliberately NOT ObjectIdentifier: the
/// queued HAL-teardown unregister can run after this service deallocates,
/// and a replacement service allocated at the same address would collide on
/// an identity key — the stale removal would then delete the replacement's
/// live entry. A UUID can never be reused by a new instance.
private let activeCaptureToken = UUID()
private func registerActiveCapture(deviceID: AudioDeviceID) {
Self.activeCapturesLock.lock()
Self.activeCaptures[activeCaptureToken] = deviceID
Self.activeCapturesLock.unlock()
}
private func unregisterActiveCapture() {
Self.unregisterActiveCapture(token: activeCaptureToken)
}
/// Token form so a queued HAL-teardown block can release the registry entry
/// after AudioDeviceStop completes even when the service itself was
/// deallocated while the block waited.
private static func unregisterActiveCapture(token: UUID) {
activeCapturesLock.lock()
activeCaptures.removeValue(forKey: token)
activeCapturesLock.unlock()
}
/// True when a live capture already holds this device.
static func isDeviceActivelyCaptured(
_ deviceID: AudioDeviceID,
excluding excludedCapture: AudioCaptureService? = nil
) -> Bool {
activeCapturesLock.lock()
defer { activeCapturesLock.unlock() }
let excludedToken = excludedCapture?.activeCaptureToken
return activeCaptures.contains { token, activeDeviceID in
activeDeviceID == deviceID && token != excludedToken
}
}
/// True when any capture is currently running in this process.
static func hasActiveCapture(excluding excludedCapture: AudioCaptureService? = nil) -> Bool {
activeCapturesLock.lock()
defer { activeCapturesLock.unlock() }
guard let excludedCapture else { return !activeCaptures.isEmpty }
return activeCaptures.keys.contains { $0 != excludedCapture.activeCaptureToken }
}
/// Get the name of the current default input device (microphone)
static func getCurrentMicrophoneName() -> String? {
guard let deviceID = currentDefaultInputDeviceID() else { return nil }
return deviceStringProperty(deviceID, selector: kAudioObjectPropertyName)
}
// MARK: - Private Methods
private func resolveInputDeviceID() throws -> AudioDeviceID {
if let override = overrideDeviceID {
if Self.isAvailableInputDevice(override) {
log("AudioCapture: Using override device ID \(override)")
isTrackingOverrideDevice = true
return override
}
log("AudioCapture: Override device ID \(override) is unavailable; falling back to default input")
}
guard let defaultDeviceID = Self.currentDefaultInputDeviceID() else {
throw AudioCaptureError.noInputAvailable
}
isTrackingOverrideDevice = false
return defaultDeviceID
}
static func currentDefaultInputDeviceID() -> AudioDeviceID? {
var deviceID: AudioDeviceID = kAudioObjectUnknown
var size = UInt32(MemoryLayout<AudioDeviceID>.size)
var address = AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyDefaultInputDevice,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
let status = AudioObjectGetPropertyData(
AudioObjectID(kAudioObjectSystemObject),
&address,
0,
nil,
&size,
&deviceID
)
guard status == noErr, isAvailableInputDevice(deviceID) else { return nil }
return deviceID
}
private static func isAvailableInputDevice(_ deviceID: AudioDeviceID) -> Bool {
deviceID != kAudioObjectUnknown && deviceID != kAudioDeviceUnknown && deviceHasInputChannels(deviceID)
}
private static func audioDeviceIDs() -> [AudioDeviceID] {
var address = AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyDevices,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
var size: UInt32 = 0
guard
AudioObjectGetPropertyDataSize(
AudioObjectID(kAudioObjectSystemObject),
&address,
0,
nil,
&size
) == noErr
else { return [] }
let count = Int(size) / MemoryLayout<AudioDeviceID>.size
guard count > 0 else { return [] }
var deviceIDs = [AudioDeviceID](repeating: kAudioObjectUnknown, count: count)
guard
AudioObjectGetPropertyData(
AudioObjectID(kAudioObjectSystemObject),
&address,
0,
nil,
&size,
&deviceIDs
) == noErr
else { return [] }
return deviceIDs
}
private static func deviceStringProperty(_ deviceID: AudioDeviceID, selector: AudioObjectPropertySelector) -> String?
{
var value: Unmanaged<CFString>?
var size = UInt32(MemoryLayout<Unmanaged<CFString>?>.size)
var address = AudioObjectPropertyAddress(
mSelector: selector,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
guard
AudioObjectGetPropertyData(deviceID, &address, 0, nil, &size, &value) == noErr,
let string = value?.takeRetainedValue()
else { return nil }
return string as String
}
/// Get stream format for a device on input scope
private func getStreamFormat(for deviceID: AudioObjectID) -> AudioStreamBasicDescription? {
var address = AudioObjectPropertyAddress(
mSelector: kAudioDevicePropertyStreamFormat,
mScope: kAudioDevicePropertyScopeInput,
mElement: kAudioObjectPropertyElementMain
)
var format = AudioStreamBasicDescription()
var size = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
let status = AudioObjectGetPropertyData(
deviceID,
&address,
0,
nil,
&size,
&format
)
return status == noErr ? format : nil
}
/// Frames a `sourceSampleRate`→`targetSampleRate` conversion of `frameCount` input
/// frames produces. Returns 0 when the source rate is unknown (0): dividing by a
/// zero rate yields `.infinity`, and `AVAudioFrameCount(.infinity)` traps the
/// real-time IOProc thread — reachable when a device reports no rate at start or
/// `stopCapture` zeroes `detectedSampleRate` mid-callback. Pure math, unit-testable.
static func resampledFrameCapacity(
frameCount: AVAudioFrameCount, sourceSampleRate: Double, targetSampleRate: Double
) -> AVAudioFrameCount {
guard frameCount > 0, sourceSampleRate > 0, targetSampleRate > 0 else { return 0 }
return AVAudioFrameCount(ceil(Double(frameCount) * targetSampleRate / sourceSampleRate))
}
/// Handle incoming audio data from the IOProc callback
private func handleAudioInput(_ inputData: UnsafePointer<AudioBufferList>?, timestamp: UnsafePointer<AudioTimeStamp>?)
{
guard isCapturing,
let bufferList = inputData?.pointee,
let converter = audioConverter,
let targetFmt = targetFormat,
let inputFmt = inputFormat
else { return }
let buffer = bufferList.mBuffers
guard let data = buffer.mData, buffer.mDataByteSize > 0 else { return }
let bytesPerFrame = UInt32(MemoryLayout<Float32>.size) * buffer.mNumberChannels
guard bytesPerFrame > 0 else { return }
let frameCount = buffer.mDataByteSize / bytesPerFrame
guard frameCount > 0 else { return }
// Create mono input buffer for converter
guard let inputBuffer = AVAudioPCMBuffer(pcmFormat: inputFmt, frameCapacity: frameCount) else { return }
inputBuffer.frameLength = frameCount
let srcPtr = data.assumingMemoryBound(to: Float32.self)
let channelCount = Int(buffer.mNumberChannels)
guard let floatData = inputBuffer.floatChannelData else { return }
let monoPtr = floatData[0]
if channelCount >= 2 {
// Mix stereo to mono by averaging channels
for i in 0..<Int(frameCount) {
let left = srcPtr[i * channelCount]
let right = srcPtr[i * channelCount + 1]
monoPtr[i] = (left + right) / 2.0
}
} else {
// Already mono, just copy
memcpy(monoPtr, srcPtr, Int(buffer.mDataByteSize))
}
// Convert to target format (16kHz mono)
let outputFrameCapacity = Self.resampledFrameCapacity(
frameCount: frameCount, sourceSampleRate: detectedSampleRate, targetSampleRate: targetSampleRate)
guard outputFrameCapacity > 0,
let outputBuffer = AVAudioPCMBuffer(pcmFormat: targetFmt, frameCapacity: outputFrameCapacity)
else { return }
var error: NSError?
hasConsumedInput = false
let inputBlock: AVAudioConverterInputBlock = { inNumPackets, outStatus in
if self.hasConsumedInput {
outStatus.pointee = .noDataNow
return nil
}
self.hasConsumedInput = true
outStatus.pointee = .haveData
return inputBuffer
}
converter.convert(to: outputBuffer, error: &error, withInputFrom: inputBlock)
if let error = error {
logError("AudioCapture: Conversion error", error: error)
return
}
// Convert Float32 samples to Int16 (linear16 PCM for DeepGram)
guard let channelData = outputBuffer.floatChannelData?[0] else { return }
let processedFrameLength = Int(outputBuffer.frameLength)
var pcmData = [Int16]()
pcmData.reserveCapacity(processedFrameLength)
var windowPeak: Int16 = 0
for i in 0..<processedFrameLength {
let sample = channelData[i]
// Clamp and convert to Int16 range (-32768 to 32767)
let pcmSample = Int16(max(-32768, min(32767, sample * 32767)))
pcmData.append(pcmSample)
// Accumulate the silent-mic peak while converting samples to avoid an
// extra pass on the audio callback hot path.
let absoluteSample = pcmSample == Int16.min ? Int16.max : Int16(pcmSample.magnitude)
if absoluteSample > windowPeak { windowPeak = absoluteSample }
}
// Convert to Data (little-endian, which is native on Apple platforms)
let byteData = pcmData.withUnsafeBufferPointer { buffer in
return Data(buffer: buffer)
}
// Silent-mic watchdog: macOS can accept the IOProc but deliver only zero samples.
// Bluetooth inputs recover by switching to the built-in mic; PTT can opt into
// all-transport detection so a stale built-in/default route triggers a full rebuild.
// Classify once every ~1s window. Windows keep rolling after a fire (unlike a
// one-shot latch) so the watchdog observes recovery and can re-arm for a second
// episode — see `evaluateSilentMicWindow`.
let nowAbs = CFAbsoluteTimeGetCurrent()
let isBluetooth = Self.isBluetoothTransport(deviceID: deviceID)
silentMicWatchdogLock.lock()
if windowPeak > watchdogWindowPeak { watchdogWindowPeak = windowPeak }
if watchdogWindowStart == 0 { watchdogWindowStart = nowAbs }
let detection: SilentMicDetection?
if nowAbs - watchdogWindowStart >= 1.0 {
detection = evaluateSilentMicWindowLocked(peak: watchdogWindowPeak, isBluetooth: isBluetooth, now: nowAbs)
watchdogWindowPeak = 0
watchdogWindowStart = nowAbs
} else {
detection = nil
}
silentMicWatchdogLock.unlock()
if let detection {
if isBluetooth {
log(
"AudioCapture: Bluetooth mic returning silence for \(detection.consecutiveSilentWindows)s — falling back to built-in mic"
)
} else {
log(
"AudioCapture: Input device returning silence for \(detection.consecutiveSilentWindows)s — rebuilding CoreAudio capture"
)
}
let handler = onSilentMicDetected
DispatchQueue.main.async { handler?(detection) }
}
// Calculate and report audio level (RMS normalized to 0.0 - 1.0)
// Uses smoothing and decay to match system audio behavior
if let levelHandler = onAudioLevel, !pcmData.isEmpty {
let sumOfSquares: Float = pcmData.reduce(0.0) { acc, sample in
let normalized = Float(sample) / 32767.0
return acc + normalized * normalized
}
let rms = sqrt(sumOfSquares / Float(pcmData.count))
// Apply soft noise floor - subtract noise but don't hard cutoff
let cleanedRms = max(0.0, rms - noiseFloor)
// Smoothing: if current level is higher, jump to it; if lower, decay gradually
// This matches how system audio naturally behaves and feels more responsive
if cleanedRms > smoothedLevel {
// Rising: follow immediately for responsiveness
smoothedLevel = cleanedRms
} else {
// Falling: decay gradually for smooth animation
smoothedLevel = smoothedLevel * decayRate
// If decayed level is very small, snap to zero to avoid endless tiny values
if smoothedLevel < 0.001 {
smoothedLevel = 0.0
}
}
let level = min(Float(1.0), smoothedLevel)
DispatchQueue.main.async {
levelHandler(level)
}
}
// Send to callback
onAudioChunk?(byteData)
}
// MARK: - Property Listeners
private func installPropertyListeners() {
registerActiveCapture(deviceID: deviceID)
updateDefaultDeviceListener()
installDeviceFormatListener()
}
private func updateDefaultDeviceListener() {
if isTrackingOverrideDevice {
removeDefaultDeviceListener()
return
}
guard defaultDeviceListenerBlock == nil else { return }
// Listen for default input device changes when the resolved capture device
// is the system default. If an explicit override was requested but is
// unavailable, capture falls back to the default and must still observe
// default-device changes.
var defaultDeviceAddress = AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyDefaultInputDevice,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
let deviceBlock: AudioObjectPropertyListenerBlock = { [weak self] numberAddresses, addresses in
guard let self else { return }
self.audioQueue.async {
self.handleConfigurationChange()
}
}
self.defaultDeviceListenerBlock = deviceBlock
AudioObjectAddPropertyListenerBlock(
AudioObjectID(kAudioObjectSystemObject),
&defaultDeviceAddress,
listenerQueue,
deviceBlock
)
}
private func installDeviceFormatListener() {
guard deviceFormatListenerBlock == nil else { return }
// Listen for format changes on current device
var formatAddress = AudioObjectPropertyAddress(
mSelector: kAudioDevicePropertyStreamFormat,
mScope: kAudioDevicePropertyScopeInput,
mElement: kAudioObjectPropertyElementMain
)
let formatBlock: AudioObjectPropertyListenerBlock = { [weak self] numberAddresses, addresses in
guard let self else { return }
self.audioQueue.async {
self.handleConfigurationChange()
}
}
self.deviceFormatListenerBlock = formatBlock
AudioObjectAddPropertyListenerBlock(
deviceID,
&formatAddress,
listenerQueue,
formatBlock
)
}
private func removePropertyListeners() {
removeDefaultDeviceListener()
removeDeviceFormatListener()
}
private func removeDefaultDeviceListener() {
if let block = defaultDeviceListenerBlock {
var address = AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyDefaultInputDevice,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
AudioObjectRemovePropertyListenerBlock(
AudioObjectID(kAudioObjectSystemObject),
&address,
listenerQueue,
block
)
defaultDeviceListenerBlock = nil
}
}
private func removeDeviceFormatListener() {
if let block = deviceFormatListenerBlock, deviceID != kAudioObjectUnknown {
var address = AudioObjectPropertyAddress(
mSelector: kAudioDevicePropertyStreamFormat,
mScope: kAudioDevicePropertyScopeInput,
mElement: kAudioObjectPropertyElementMain
)
AudioObjectRemovePropertyListenerBlock(
deviceID,
&address,
listenerQueue,
block
)
deviceFormatListenerBlock = nil
}
}
// MARK: - Device Change Handling
/// Handle audio configuration change (e.g., user switched microphone)
/// Runs on audioQueue to avoid blocking the main thread.
private func handleConfigurationChange() {