-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAudioEngine.swift
More file actions
2267 lines (1947 loc) · 100 KB
/
Copy pathAudioEngine.swift
File metadata and controls
2267 lines (1947 loc) · 100 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
// FineTune/Audio/Engine/AudioEngine.swift
import AudioToolbox
import Foundation
import os
import UserNotifications
@Observable
@MainActor
final class AudioEngine {
let processMonitor: any AudioProcessMonitoring
let deviceMonitor: any AudioDeviceProviding
let bluetoothDeviceMonitor: BluetoothDeviceMonitor
let deviceVolumeMonitor: any DeviceVolumeProviding
let volumeState: VolumeState
let settingsManager: SettingsManager
let autoEQProfileManager: AutoEQProfileManager
let permission: AudioRecordingPermission
let appListCoordinator: AppListCoordinator
#if !APP_STORE
let ddcController: DDCController
#endif
private var taps: [pid_t: any ProcessTapControlling] = [:]
/// Factory for creating tap controllers. Overridable for testing.
private let tapFactory: @MainActor (AudioApp, [String], String?) throws -> any ProcessTapControlling
/// Closure to check if a device is alive. Overridable for testing.
private let isAliveCheck: (AudioDeviceID) -> Bool
/// One-shot HAL listeners for devices that were present but not alive during priority resolution.
/// Keyed by AudioDeviceID. Each entry holds the device UID, listener block, and a timeout task.
private var aliveWatchers: [AudioDeviceID: (uid: String, block: AudioObjectPropertyListenerBlock, timeout: Task<Void, Never>)] = [:]
/// Number of pending alive watchers (exposed for testing).
var pendingAliveWatcherCount: Int { aliveWatchers.count }
private var appliedPIDs: Set<pid_t> = []
private var appDeviceRouting: [pid_t: String] = [:] // pid → deviceUID (always explicit)
private var followsDefault: Set<pid_t> = [] // Apps that follow system default
/// The last output default confirmed by FineTune (user change or programmatic switch).
/// Used to restore after macOS auto-switches to a lower-priority device.
private var lastConfirmedDefaultUID: String?
/// Timestamp of the last auto-switch override. Used to distinguish rapid BT auto-switches
/// (< 1s apart) from deliberate user changes (> 1s after last override).
private var lastAutoSwitchOverrideTime: Date?
private var pendingCleanup: [pid_t: Task<Void, Never>] = [:] // Grace period for stale tap cleanup
private var staleCleanupTask: Task<Void, Never>? // Debounced cleanup scheduling
private var healthMonitorTask: Task<Void, Never>? // Periodic tap health monitor
private var tapRecoveryCooldownUntil: [pid_t: Date] = [:] // Prevents tap recreation thrashing
private let logger = Logger(subsystem: Bundle.main.bundleIdentifier ?? "FineTune", category: "AudioEngine")
// MARK: - Priority State Machine
/// Tracks whether we're waiting for macOS to potentially auto-switch after a device connect.
private enum PriorityState {
case stable
case pendingAutoSwitch(connectedDeviceUID: String, timeoutTask: Task<Void, Never>)
}
private var outputPriorityState: PriorityState = .stable
private var inputPriorityState: PriorityState = .stable
/// Grace period for auto-switch detection (wired devices)
private let autoSwitchGracePeriod: TimeInterval = 2.0
/// Extended grace period for Bluetooth devices (firmware handshake takes longer)
private let btAutoSwitchGracePeriod: TimeInterval = 5.0
// MARK: - Echo Suppression
private let outputEchoTracker = EchoTracker(label: "Output")
private let inputEchoTracker = EchoTracker(label: "Input")
var outputDevices: [AudioDevice] {
deviceMonitor.outputDevices
}
func outputVolumeBackend(for deviceID: AudioDeviceID) -> VolumeControlTier {
deviceVolumeMonitor.outputVolumeBackend(for: deviceID)
}
var inputDevices: [AudioDevice] {
deviceMonitor.inputDevices
}
/// Output devices sorted by user-defined priority order.
/// Devices in the priority list appear in that order; new/unknown devices are appended alphabetically.
var prioritySortedOutputDevices: [AudioDevice] {
let devices = outputDevices
let priorityOrder = settingsManager.devicePriorityOrder
let devicesByUID = Dictionary(devices.map { ($0.uid, $0) }, uniquingKeysWith: { _, latest in latest })
// Collect devices in priority order (skip stale UIDs)
var sorted: [AudioDevice] = []
var seen = Set<String>()
for uid in priorityOrder {
if let device = devicesByUID[uid] {
sorted.append(device)
seen.insert(uid)
}
}
// Append new devices alphabetically
let remaining = devices
.filter { !seen.contains($0.uid) }
.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
sorted.append(contentsOf: remaining)
return sorted
}
/// Input devices sorted by user-defined priority order.
var prioritySortedInputDevices: [AudioDevice] {
let devices = inputDevices
let priorityOrder = settingsManager.inputDevicePriorityOrder
let devicesByUID = Dictionary(devices.map { ($0.uid, $0) }, uniquingKeysWith: { _, latest in latest })
var sorted: [AudioDevice] = []
var seen = Set<String>()
for uid in priorityOrder {
if let device = devicesByUID[uid] {
sorted.append(device)
seen.insert(uid)
}
}
let remaining = devices
.filter { !seen.contains($0.uid) }
.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
sorted.append(contentsOf: remaining)
return sorted
}
/// Registers any output devices not yet in the priority list.
/// Call this when devices change (not from computed properties).
func registerNewDevicesInPriority() {
for device in outputDevices {
settingsManager.ensureDeviceInPriority(device.uid)
}
for device in inputDevices {
settingsManager.ensureInputDeviceInPriority(device.uid)
}
}
/// Returns the highest-priority device that is both connected and alive.
/// `isDeviceAlive()` is checked internally — callers never need to check separately.
static func resolveHighestPriority(
priorityOrder: [String],
connectedDevices: [AudioDevice],
excluding: String? = nil,
isAlive: ((AudioDeviceID) -> Bool)? = nil
) -> AudioDevice? {
let aliveCheck = isAlive ?? { $0.isDeviceAlive() }
let connected = Dictionary(
connectedDevices.map { ($0.uid, $0) },
uniquingKeysWith: { _, latest in latest }
)
for uid in priorityOrder {
guard uid != excluding,
let device = connected[uid],
aliveCheck(device.id) else { continue }
return device
}
// Fallback: any alive connected device not excluded
return connectedDevices.first {
$0.uid != excluding && aliveCheck($0.id)
}
}
init(
permission: AudioRecordingPermission,
settingsManager: SettingsManager,
autoEQProfileManager: AutoEQProfileManager,
deviceProvider: (any AudioDeviceProviding)? = nil,
processMonitor: (any AudioProcessMonitoring)? = nil,
deviceVolumeMonitor: (any DeviceVolumeProviding)? = nil,
tapFactory: (@MainActor (AudioApp, [String], String?) throws -> any ProcessTapControlling)? = nil,
isAlive: ((AudioDeviceID) -> Bool)? = nil,
startMonitorsAutomatically: Bool = true
) {
self.permission = permission
let manager = settingsManager
self.settingsManager = manager
self.appListCoordinator = AppListCoordinator(settingsManager: manager)
self.autoEQProfileManager = autoEQProfileManager
self.volumeState = VolumeState(settingsManager: manager)
self.isAliveCheck = isAlive ?? { $0.isDeviceAlive() }
// If a custom deviceProvider is given, use it directly.
// Otherwise create a real AudioDeviceMonitor (needed by DeviceVolumeMonitor and default tap factory).
let realDeviceMonitor: AudioDeviceMonitor?
if let provider = deviceProvider {
realDeviceMonitor = provider as? AudioDeviceMonitor
self.deviceMonitor = provider
} else {
let monitor = AudioDeviceMonitor()
realDeviceMonitor = monitor
self.deviceMonitor = monitor
}
self.processMonitor = processMonitor ?? AudioProcessMonitor()
self.bluetoothDeviceMonitor = BluetoothDeviceMonitor()
#if !APP_STORE
let ddc = DDCController(settingsManager: manager)
self.ddcController = ddc
if let dvMonitor = deviceVolumeMonitor {
self.deviceVolumeMonitor = dvMonitor
} else {
guard let realDeviceMonitor else {
preconditionFailure("AudioEngine: must provide deviceVolumeMonitor when deviceProvider is not AudioDeviceMonitor")
}
self.deviceVolumeMonitor = DeviceVolumeMonitor(deviceMonitor: realDeviceMonitor, settingsManager: manager, ddcController: ddc)
}
#else
if let dvMonitor = deviceVolumeMonitor {
self.deviceVolumeMonitor = dvMonitor
} else {
guard let realDeviceMonitor else {
preconditionFailure("AudioEngine: must provide deviceVolumeMonitor when deviceProvider is not AudioDeviceMonitor")
}
self.deviceVolumeMonitor = DeviceVolumeMonitor(deviceMonitor: realDeviceMonitor, settingsManager: manager)
}
#endif
// Tap factory: use provided factory or default to ProcessTapController
if let factory = tapFactory {
self.tapFactory = factory
} else {
self.tapFactory = { app, deviceUIDs, preferredSource in
if deviceUIDs.count == 1 {
return ProcessTapController(
app: app,
targetDeviceUID: deviceUIDs[0],
deviceMonitor: realDeviceMonitor,
preferredTapSourceDeviceUID: preferredSource
)
} else {
return ProcessTapController(
app: app,
targetDeviceUIDs: deviceUIDs,
deviceMonitor: realDeviceMonitor,
preferredTapSourceDeviceUID: preferredSource
)
}
}
}
outputEchoTracker.onTimeout = { [weak self] _ in
self?.restoreConfirmedDefault()
}
inputEchoTracker.onTimeout = { [weak self] _ in
guard let self, self.settingsManager.appSettings.lockInputDevice else { return }
self.restoreLockedInputDevice()
}
// Wire callbacks — needed for both test and production mode
wireCallbacks()
if startMonitorsAutomatically {
Task { @MainActor in
if self.permission.status == .authorized {
self.processMonitor.start()
}
self.deviceMonitor.start()
self.bluetoothDeviceMonitor.start()
#if !APP_STORE
ddc.onProbeCompleted = { [weak self] in
self?.deviceVolumeMonitor.refreshAfterDDCProbe()
self?.refreshAllTapOutputStates()
}
ddc.start()
#endif
// Start device volume monitor AFTER deviceMonitor.start() populates devices
self.deviceVolumeMonitor.start()
self.applyPersistedSettings()
self.registerNewDevicesInPriority()
// Seed the confirmed default from whatever macOS has at startup
self.lastConfirmedDefaultUID = self.deviceVolumeMonitor.defaultDeviceUID
if manager.appSettings.lockInputDevice {
self.restoreLockedInputDevice()
}
}
}
// Start process monitor when permission is granted
if startMonitorsAutomatically && permission.status != .authorized {
observePermissionGranted()
}
}
private func observePermissionGranted() {
withObservationTracking {
_ = self.permission.status
} onChange: { [weak self] in
Task { @MainActor [weak self] in
guard let self else { return }
if self.permission.status == .authorized {
self.processMonitor.start()
self.applyPersistedSettings()
self.startHealthMonitor()
self.logger.info("Audio capture authorized — process monitor started")
} else {
self.observePermissionGranted()
}
}
}
}
/// Wire all event callbacks from monitors to AudioEngine handlers.
private func wireCallbacks() {
// Sync device volume changes to taps for VU meter accuracy
deviceVolumeMonitor.onVolumeChanged = { [weak self] deviceID, newVolume in
guard let self else { return }
guard let deviceUID = self.deviceMonitor.outputDevices.first(where: { $0.id == deviceID })?.uid else { return }
let loudnessEnabled = self.settingsManager.appSettings.loudnessCompensationEnabled
for (_, tap) in self.taps {
if tap.currentDeviceUID == deviceUID {
tap.currentDeviceVolume = newVolume
if tap.currentDeviceUIDs.count == 1,
self.outputVolumeBackend(for: deviceID) == .software {
tap.volume = self.effectiveVolume(for: tap.app.id, deviceUIDs: tap.currentDeviceUIDs)
}
tap.updateLoudnessCompensation(
volume: self.effectiveLoudnessVolume(for: tap),
enabled: loudnessEnabled,
intensity: self.settingsManager.appSettings.loudnessCompensationIntensity
)
}
}
}
deviceVolumeMonitor.onMuteChanged = { [weak self] deviceID, isMuted in
guard let self else { return }
guard let deviceUID = self.deviceMonitor.outputDevices.first(where: { $0.id == deviceID })?.uid else { return }
for (_, tap) in self.taps {
if tap.currentDeviceUID == deviceUID {
tap.isDeviceMuted = isMuted
if tap.currentDeviceUIDs.count == 1,
self.outputVolumeBackend(for: deviceID) == .software {
tap.volume = self.effectiveVolume(for: tap.app.id, deviceUIDs: tap.currentDeviceUIDs)
}
}
}
}
processMonitor.onAppsChanged = { [weak self] apps in
self?.applyPersistedSettings()
self?.scheduleStaleCleanup()
}
// Priority order closures — only for concrete AudioDeviceMonitor
if let realMonitor = deviceMonitor as? AudioDeviceMonitor {
realMonitor.outputPriorityOrder = { [weak self] in
self?.settingsManager.devicePriorityOrder ?? []
}
realMonitor.inputPriorityOrder = { [weak self] in
self?.settingsManager.inputDevicePriorityOrder ?? []
}
realMonitor.onBTDeviceSampleRateChanged = { [weak self] uid, newRate in
Task { @MainActor [weak self] in
await self?.handleBTDeviceSampleRateChanged(uid: uid, newRate: newRate)
}
}
}
deviceMonitor.onDeviceDisconnected = { [weak self] deviceUID, deviceName in
self?.handleDeviceDisconnected(deviceUID, name: deviceName)
self?.bluetoothDeviceMonitor.refresh()
}
deviceMonitor.onDeviceConnected = { [weak self] deviceUID, deviceName in
self?.handleDeviceConnected(deviceUID, name: deviceName)
self?.bluetoothDeviceMonitor.notifyDeviceAppearedInCoreAudio()
}
deviceMonitor.onInputDeviceDisconnected = { [weak self] deviceUID, deviceName in
self?.logger.info("Input device disconnected: \(deviceName) (\(deviceUID))")
self?.handleInputDeviceDisconnected(deviceUID)
}
deviceMonitor.onInputDeviceConnected = { [weak self] deviceUID, deviceName in
self?.logger.info("Input device connected: \(deviceName) (\(deviceUID))")
self?.settingsManager.ensureInputDeviceInPriority(deviceUID)
self?.handleInputDeviceConnected(deviceUID, name: deviceName)
}
deviceVolumeMonitor.onDefaultDeviceChanged = { [weak self] newDefaultUID in
self?.handleDefaultDeviceChanged(newDefaultUID)
}
deviceVolumeMonitor.onDefaultInputDeviceChanged = { [weak self] newDefaultInputUID in
Task { @MainActor [weak self] in
self?.handleDefaultInputDeviceChanged(newDefaultInputUID)
}
}
}
var apps: [AudioApp] {
processMonitor.activeApps
}
// MARK: - Displayable Apps (Active + Pinned Inactive)
/// Combined list of active apps and pinned inactive apps for UI display.
/// Pinned apps appear first (sorted alphabetically), then unpinned active apps (sorted alphabetically).
var displayableApps: [DisplayableApp] {
let activeApps = apps
.filter { !appListCoordinator.isIgnored(identifier: $0.persistenceIdentifier) }
let activeIdentifiers = Set(activeApps.map { $0.persistenceIdentifier })
// Get pinned apps that are not currently active
let pinnedInactiveInfos = appListCoordinator.pinnedAppInfo()
.filter { !activeIdentifiers.contains($0.persistenceIdentifier) }
// Pinned active apps (sorted alphabetically)
let pinnedActive = activeApps
.filter { appListCoordinator.isPinned(identifier: $0.persistenceIdentifier) }
.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
.map { DisplayableApp.active($0) }
// Pinned inactive apps (sorted alphabetically)
let pinnedInactive = pinnedInactiveInfos
.sorted { $0.displayName.localizedCaseInsensitiveCompare($1.displayName) == .orderedAscending }
.map { DisplayableApp.pinnedInactive($0) }
// Unpinned active apps (sorted alphabetically)
let unpinnedActive = activeApps
.filter { !appListCoordinator.isPinned(identifier: $0.persistenceIdentifier) }
.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
.map { DisplayableApp.active($0) }
return pinnedActive + pinnedInactive + unpinnedActive
}
// MARK: - Pinning
/// Pin an active app so it remains visible when inactive.
func pinApp(_ app: AudioApp) {
appListCoordinator.pinApp(app)
}
/// Unpin an app by its persistence identifier.
func unpinApp(_ identifier: String) {
appListCoordinator.unpinApp(identifier)
}
/// Check if an app is pinned.
func isPinned(_ app: AudioApp) -> Bool {
appListCoordinator.isPinned(app)
}
/// Check if an identifier is pinned (for inactive apps).
func isPinned(identifier: String) -> Bool {
appListCoordinator.isPinned(identifier: identifier)
}
// MARK: - Ignored Apps
/// Hide an active app so FineTune ignores it entirely. Persists the ignore,
/// then tears down the live tap so audio returns to natural volume.
func ignoreApp(_ app: AudioApp) {
appListCoordinator.recordIgnore(app)
if let tap = taps.removeValue(forKey: app.id) {
tap.invalidate()
}
appDeviceRouting.removeValue(forKey: app.id)
followsDefault.remove(app.id)
appliedPIDs.remove(app.id)
}
/// Unhide an app by its persistence identifier.
/// Immediately creates a tap if the app is currently running.
func unignoreApp(_ identifier: String) {
appListCoordinator.clearIgnore(identifier)
applyPersistedSettings()
}
/// Check if an identifier is hidden.
func isIgnored(identifier: String) -> Bool {
appListCoordinator.isIgnored(identifier: identifier)
}
// MARK: - Inactive App Settings (by persistence identifier)
func getVolumeForInactive(identifier: String) -> Float {
appListCoordinator.getVolumeForInactive(identifier: identifier)
}
func setVolumeForInactive(identifier: String, to volume: Float) {
appListCoordinator.setVolumeForInactive(identifier: identifier, to: volume)
}
func getBoostForInactive(identifier: String) -> BoostLevel {
appListCoordinator.getBoostForInactive(identifier: identifier)
}
func setBoostForInactive(identifier: String, to boost: BoostLevel) {
appListCoordinator.setBoostForInactive(identifier: identifier, to: boost)
}
func getMuteForInactive(identifier: String) -> Bool {
appListCoordinator.getMuteForInactive(identifier: identifier)
}
func setMuteForInactive(identifier: String, to muted: Bool) {
appListCoordinator.setMuteForInactive(identifier: identifier, to: muted)
}
func getEQSettingsForInactive(identifier: String) -> EQSettings {
appListCoordinator.getEQSettingsForInactive(identifier: identifier)
}
func setEQSettingsForInactive(_ settings: EQSettings, identifier: String) {
appListCoordinator.setEQSettingsForInactive(settings, identifier: identifier)
}
func getDeviceRoutingForInactive(identifier: String) -> String? {
appListCoordinator.getDeviceRoutingForInactive(identifier: identifier)
}
func setDeviceRoutingForInactive(identifier: String, deviceUID: String?) {
appListCoordinator.setDeviceRoutingForInactive(identifier: identifier, deviceUID: deviceUID)
}
func isFollowingDefaultForInactive(identifier: String) -> Bool {
appListCoordinator.isFollowingDefaultForInactive(identifier: identifier)
}
func getDeviceSelectionModeForInactive(identifier: String) -> DeviceSelectionMode {
appListCoordinator.getDeviceSelectionModeForInactive(identifier: identifier)
}
func setDeviceSelectionModeForInactive(identifier: String, to mode: DeviceSelectionMode) {
appListCoordinator.setDeviceSelectionModeForInactive(identifier: identifier, to: mode)
}
func getSelectedDeviceUIDsForInactive(identifier: String) -> Set<String> {
appListCoordinator.getSelectedDeviceUIDsForInactive(identifier: identifier)
}
func setSelectedDeviceUIDsForInactive(identifier: String, to uids: Set<String>) {
appListCoordinator.setSelectedDeviceUIDsForInactive(identifier: identifier, to: uids)
}
/// Audio levels for all active apps (for VU meter visualization)
/// Returns a dictionary mapping PID to peak audio level (0-1)
var audioLevels: [pid_t: Float] {
var levels: [pid_t: Float] = [:]
for (pid, tap) in taps {
levels[pid] = tap.audioLevel
}
return levels
}
/// Get audio level for a specific app
func getAudioLevel(for app: AudioApp) -> Float {
taps[app.id]?.audioLevel ?? 0.0
}
func start() {
// Monitors have internal guards against double-starting
if permission.status == .authorized {
processMonitor.start()
}
deviceMonitor.start()
applyPersistedSettings()
if permission.status == .authorized {
startHealthMonitor()
}
// Restore locked input device if feature is enabled
if settingsManager.appSettings.lockInputDevice {
restoreLockedInputDevice()
}
logger.info("AudioEngine started")
}
func stop() {
stopHealthMonitor()
processMonitor.stop()
deviceMonitor.stop()
for tap in taps.values {
tap.invalidate()
}
taps.removeAll()
logger.info("AudioEngine stopped")
}
/// Explicit shutdown for app termination. Ensures all listeners are cleaned up.
/// Call from applicationWillTerminate or equivalent lifecycle hook.
/// Note: For menu bar apps, process exit cleans up resources anyway, so this is optional.
func shutdown() {
stop()
deviceVolumeMonitor.stop()
logger.info("AudioEngine shutdown complete")
}
// MARK: - Settings Reset
/// Resets all persisted settings and synchronizes in-memory engine state.
/// Active taps are kept alive but reverted to defaults (unity volume, unmuted, flat EQ).
func handleSettingsReset() {
// 1. Clear persisted state
settingsManager.resetAllSettings()
// 2. Clear in-memory routing and tracking state
appliedPIDs.removeAll()
appDeviceRouting.removeAll()
followsDefault.removeAll()
// 3. Clear cached per-app audio state
volumeState.resetAll()
// 4. Refresh output state caches so software-backed devices reset to defaults.
deviceVolumeMonitor.refreshOutputDeviceStates()
// 5. Push defaults to all active taps
for tap in taps.values {
applyTapOutputState(to: tap, for: tap.app.id, deviceUIDs: tap.currentDeviceUIDs)
tap.updateEQSettings(.flat)
tap.updateAutoEQProfile(nil)
tap.updateLoudnessCompensation(
volume: effectiveLoudnessVolume(for: tap),
enabled: false,
intensity: settingsManager.appSettings.loudnessCompensationIntensity
)
}
// 6. Re-apply from clean settings (re-establishes routing to system default)
applyPersistedSettings()
logger.info("Settings reset: engine state synchronized")
}
func setVolume(for app: AudioApp, to volume: Float) {
volumeState.setVolume(for: app.id, to: volume, identifier: app.persistenceIdentifier)
if let deviceUID = appDeviceRouting[app.id] {
ensureTapExists(for: app, deviceUID: deviceUID)
}
if let tap = taps[app.id] {
tap.volume = effectiveVolume(for: app.id, deviceUIDs: tap.currentDeviceUIDs)
if settingsManager.appSettings.loudnessCompensationEnabled {
tap.updateLoudnessCompensation(
volume: effectiveLoudnessVolume(for: tap),
enabled: true,
intensity: settingsManager.appSettings.loudnessCompensationIntensity
)
}
}
}
func getVolume(for app: AudioApp) -> Float {
volumeState.getVolume(for: app.id)
}
// MARK: - Boost
func setBoost(for app: AudioApp, to boost: BoostLevel) {
volumeState.setBoost(for: app.id, to: boost, identifier: app.persistenceIdentifier)
if let tap = taps[app.id] {
tap.volume = effectiveVolume(for: app.id, deviceUIDs: tap.currentDeviceUIDs)
}
}
func getBoost(for app: AudioApp) -> BoostLevel {
volumeState.getBoost(for: app.id)
}
/// Effective gain for ProcessTapController: app volume × boost, plus optional
/// single-device software output gain for software-backed devices.
/// Single-device-routed apps on `.software`-backed devices always receive the
/// device's software gain; multi-destination routing keeps `appGain` alone
/// because per-device software gain has no unambiguous meaning across fan-out.
private func effectiveVolume(for pid: pid_t, deviceUIDs: [String]? = nil) -> Float {
let appGain = volumeState.getVolume(for: pid) * volumeState.getBoost(for: pid).rawValue
guard let resolvedUIDs = deviceUIDs, resolvedUIDs.count == 1,
let primaryUID = resolvedUIDs.first,
let device = deviceMonitor.device(for: primaryUID),
outputVolumeBackend(for: device.id) == .software else {
return appGain
}
return appGain * deviceVolumeMonitor.outputProcessingGain(for: device.id)
}
/// Estimated listening level for loudness compensation: device volume × per-app slider.
/// Does not include boost (intentional amplification beyond reference).
/// The compensator's phon estimation clamps to [0,1] so values > 1 are treated as reference.
private func effectiveLoudnessVolume(for tap: any ProcessTapControlling) -> Float {
tap.currentDeviceVolume * volumeState.getVolume(for: tap.app.id)
}
private func applyTapOutputState(to tap: any ProcessTapControlling, for pid: pid_t, deviceUIDs: [String]? = nil) {
let resolvedUIDs = deviceUIDs ?? tap.currentDeviceUIDs
tap.volume = effectiveVolume(for: pid, deviceUIDs: resolvedUIDs)
tap.isMuted = volumeState.getMute(for: pid)
if let primaryUID = resolvedUIDs.first,
let device = deviceMonitor.device(for: primaryUID) {
tap.currentDeviceVolume = deviceVolumeMonitor.volumes[device.id] ?? 1.0
tap.isDeviceMuted = deviceVolumeMonitor.muteStates[device.id] ?? false
} else {
tap.currentDeviceVolume = 1.0
tap.isDeviceMuted = false
}
}
private func refreshAllTapOutputStates() {
for tap in taps.values {
applyTapOutputState(to: tap, for: tap.app.id, deviceUIDs: tap.currentDeviceUIDs)
}
}
func toggleMute(for app: AudioApp) {
let current = volumeState.getMute(for: app.id)
setMute(for: app, to: !current)
}
func currentVolume(for app: AudioApp) -> Float {
volumeState.getVolume(for: app.id)
}
func isMuted(for app: AudioApp) -> Bool {
volumeState.getMute(for: app.id)
}
func isAudibleNow(bundleID: String) -> Bool {
guard let app = apps.first(where: { $0.bundleID == bundleID }) else {
return false
}
return app.processObjectIDs.contains { $0.readProcessIsRunning() }
}
func setMute(for app: AudioApp, to muted: Bool) {
volumeState.setMute(for: app.id, to: muted, identifier: app.persistenceIdentifier)
taps[app.id]?.isMuted = muted
}
func getMute(for app: AudioApp) -> Bool {
volumeState.getMute(for: app.id)
}
/// Update EQ settings for an app
func setEQSettings(_ settings: EQSettings, for app: AudioApp) {
guard let tap = taps[app.id] else { return }
tap.updateEQSettings(settings)
settingsManager.setEQSettings(settings, for: app.persistenceIdentifier)
}
/// Get EQ settings for an app
func getEQSettings(for app: AudioApp) -> EQSettings {
return settingsManager.getEQSettings(for: app.persistenceIdentifier)
}
// MARK: - Per-Device AutoEQ
func getAutoEQProfile(for deviceUID: String) -> AutoEQProfile? {
guard let selection = settingsManager.getAutoEQSelection(for: deviceUID) else { return nil }
return autoEQProfileManager.profile(for: selection.profileID)
}
func setAutoEQProfile(for deviceUID: String, profileID: String?) {
if let profileID {
settingsManager.setAutoEQSelection(for: deviceUID, to: AutoEQSelection(profileID: profileID, isEnabled: true))
} else {
settingsManager.setAutoEQSelection(for: deviceUID, to: nil)
}
applyAutoEQToTaps(for: deviceUID)
}
func setAutoEQEnabled(for deviceUID: String, enabled: Bool) {
guard var selection = settingsManager.getAutoEQSelection(for: deviceUID) else { return }
selection.isEnabled = enabled
settingsManager.setAutoEQSelection(for: deviceUID, to: selection)
applyAutoEQToTaps(for: deviceUID)
}
func getAutoEQSelection(for deviceUID: String) -> AutoEQSelection? {
settingsManager.getAutoEQSelection(for: deviceUID)
}
var autoEQPreampEnabled: Bool {
settingsManager.autoEQPreampEnabled
}
func setAutoEQPreampEnabled(_ enabled: Bool) {
settingsManager.autoEQPreampEnabled = enabled
for tap in taps.values {
tap.setAutoEQPreampEnabled(enabled)
}
}
func setLoudnessCompensationEnabled(_ enabled: Bool) {
let intensity = settingsManager.loudnessCompensationIntensity
for tap in taps.values {
tap.updateLoudnessCompensation(
volume: effectiveLoudnessVolume(for: tap),
enabled: enabled,
intensity: intensity
)
}
}
func setLoudnessCompensationIntensity(_ intensity: Float) {
for tap in taps.values {
tap.updateLoudnessCompensation(
volume: effectiveLoudnessVolume(for: tap),
enabled: settingsManager.appSettings.loudnessCompensationEnabled,
intensity: intensity
)
}
}
func setLoudnessEqualizationEnabled(_ enabled: Bool) {
var settings = LoudnessEqualizerSettings()
settings.enabled = enabled
for tap in taps.values {
tap.updateLoudnessEqualization(settings)
}
}
func setLoudnessEqualizationIntensity(_ intensity: Float) {
for tap in taps.values {
tap.setLoudnessEqualizationIntensity(intensity)
}
}
/// Apply AutoEQ profile to all taps currently routed to the given device.
private func applyAutoEQToTaps(for deviceUID: String) {
for tap in taps.values {
guard tap.currentDeviceUID == deviceUID else { continue }
applyAutoEQToTap(tap)
}
}
/// Synchronous in-memory AutoEQ profile lookup. nil = not yet cached.
private func autoEQProfileForActivation(deviceUID: String) -> AutoEQProfile? {
guard let device = deviceMonitor.device(for: deviceUID), device.supportsAutoEQ else { return nil }
guard let selection = settingsManager.getAutoEQSelection(for: deviceUID), selection.isEnabled else { return nil }
return autoEQProfileManager.profile(for: selection.profileID)
}
private func tapInitialState(forApp app: AudioApp, primaryDeviceUID: String, deviceVolume: Float) -> TapInitialState {
var loudnessEqSettings = LoudnessEqualizerSettings()
loudnessEqSettings.enabled = settingsManager.appSettings.loudnessEqualizationEnabled
return TapInitialState(
eqSettings: settingsManager.getEQSettings(for: app.persistenceIdentifier),
autoEQProfile: autoEQProfileForActivation(deviceUID: primaryDeviceUID),
autoEQPreampEnabled: settingsManager.autoEQPreampEnabled,
loudnessVolume: deviceVolume * volumeState.getVolume(for: app.id),
loudnessCompensationEnabled: settingsManager.appSettings.loudnessCompensationEnabled,
loudnessCompensationIntensity: settingsManager.appSettings.loudnessCompensationIntensity,
loudnessEqualizerSettings: loudnessEqSettings
)
}
/// Skips AutoEQ entirely for devices that don't support it (speakers, HDMI, etc.).
/// If the profile isn't loaded yet, triggers an async fetch and applies when ready.
private func applyAutoEQToTap(_ tap: any ProcessTapControlling) {
guard let deviceUID = tap.currentDeviceUID else { return }
// Skip AutoEQ for non-headphone devices (or if device not found in monitor)
guard let device = deviceMonitor.device(for: deviceUID) else {
logger.debug("AutoEQ skip for \(tap.app.name): device \(deviceUID) not found in monitor")
return
}
guard device.supportsAutoEQ else {
tap.updateAutoEQProfile(nil)
logger.debug("AutoEQ skip for \(tap.app.name): \(device.name) doesn't support AutoEQ")
return
}
guard let selection = settingsManager.getAutoEQSelection(for: deviceUID),
selection.isEnabled else {
tap.updateAutoEQProfile(nil)
logger.debug("AutoEQ skip for \(tap.app.name): no selection or disabled for \(device.name)")
return
}
// Try in-memory first (instant)
if let profile = autoEQProfileManager.profile(for: selection.profileID) {
tap.updateAutoEQProfile(profile)
return
}
// Profile not loaded yet — fetch asynchronously
tap.updateAutoEQProfile(nil)
Task { @MainActor in
guard let profile = await autoEQProfileManager.resolveProfile(for: selection.profileID) else { return }
// Verify tap still exists and is still routed to the same device
guard tap.currentDeviceUID == deviceUID else { return }
guard let latestSelection = settingsManager.getAutoEQSelection(for: deviceUID),
latestSelection.profileID == selection.profileID,
latestSelection.isEnabled else { return }
tap.updateAutoEQProfile(profile)
}
}
/// Sets the system default output device, routes followsDefault apps, and registers
/// an echo so the resulting CoreAudio callback is consumed rather than treated as
/// an external change.
/// UI code should call this instead of `deviceVolumeMonitor.setDefaultDevice` directly.
@discardableResult
func setDefaultOutputDevice(_ deviceID: AudioDeviceID) -> Bool {
guard deviceVolumeMonitor.setDefaultDevice(deviceID) else { return false }
if let uid = deviceMonitor.outputDevices.first(where: { $0.id == deviceID })?.uid {
outputEchoTracker.increment(uid)
lastConfirmedDefaultUID = uid
routeFollowsDefaultApps(to: uid)
}
return true
}
/// Sets the output device for an app.
/// - Parameters:
/// - app: The app to route
/// - deviceUID: The device UID to route to, or nil to follow system default
func setDevice(for app: AudioApp, deviceUID: String?) {
if let deviceUID = deviceUID {
// Explicit device selection - stop following default
followsDefault.remove(app.id)
// Defensive: re-persist routing even if in-memory state matches,
// to guard against settings file corruption or incomplete prior writes
settingsManager.setDeviceRouting(for: app.persistenceIdentifier, deviceUID: deviceUID)
// If transitioning from follows-default to explicit and tap has a stream-specific
// source, refresh to mixdown so it won't go stale when the default changes later.
if let tap = taps[app.id], tap.tapSourceDeviceUID != nil {
Task {
do {
try await tap.refreshTapSource(nil)
self.applyTapOutputState(to: tap, for: app.id)
} catch {
self.logger.error("Failed to refresh tap source for \(app.name): \(error)")
}
}
}
guard appDeviceRouting[app.id] != deviceUID else { return }
appDeviceRouting[app.id] = deviceUID
} else {
// "System Audio" selected - follow default
followsDefault.insert(app.id)
settingsManager.setFollowDefault(for: app.persistenceIdentifier)
// Route to current default (if available)
guard let defaultUID = deviceVolumeMonitor.defaultDeviceUID else {
// No default available yet - routing will happen when default becomes available
// via handleDefaultDeviceChanged callback
logger.warning("No default device available for \(app.name), will route when available")
return
}
guard appDeviceRouting[app.id] != defaultUID else { return }
appDeviceRouting[app.id] = defaultUID
}
// Switch tap if needed
guard let targetUID = appDeviceRouting[app.id] else { return }
let preferredTapSourceUID = preferredTapSourceDeviceUID(forOutputUIDs: [targetUID], isFollowsDefault: followsDefault.contains(app.id))
if let tap = taps[app.id] {
Task {
do {
try await tap.switchDevice(to: targetUID, preferredTapSourceDeviceUID: preferredTapSourceUID)
self.applyTapOutputState(to: tap, for: app.id, deviceUIDs: [targetUID])
self.applyAutoEQToTap(tap)
self.logger.debug("Switched \(app.name) to device: \(targetUID)")
} catch {
self.logger.error("Failed to switch device for \(app.name): \(error.localizedDescription)")
self.logger.info("Falling back to recreateTap for \(app.name)")
await self.recreateTap(for: app.id)
}
}
} else {
ensureTapExists(for: app, deviceUID: targetUID)
}
}
func getDeviceUID(for app: AudioApp) -> String? {
appDeviceRouting[app.id]
}
/// Returns true if the app follows system default device
func isFollowingDefault(for app: AudioApp) -> Bool {
followsDefault.contains(app.id)
}
// MARK: - Multi-Device Selection
/// Gets the device selection mode for an app
func getDeviceSelectionMode(for app: AudioApp) -> DeviceSelectionMode {