Skip to content

Commit 3ccde61

Browse files
committed
refactoring
1 parent bb15c07 commit 3ccde61

10 files changed

Lines changed: 105 additions & 151 deletions

File tree

native/app/Source/AppDelegate.swift

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,14 @@ class AppDelegate: NSObject, NSApplicationDelegate, SUUpdaterDelegate {
3535
Utilities.delay(2000) {
3636
self.updateProcessed.emit()
3737
}
38+
39+
NSWorkspace.shared.notificationCenter.addObserver(
40+
self, selector: #selector(didWakeUp(event:)),
41+
name: NSWorkspace.didWakeNotification, object: nil)
42+
43+
NSWorkspace.shared.notificationCenter.addObserver(
44+
self, selector: #selector(willSleep(event:)),
45+
name: NSWorkspace.willSleepNotification, object: nil)
3846
}
3947

4048
func applicationWillTerminate(_ aNotification: Notification) {
@@ -89,6 +97,14 @@ class AppDelegate: NSObject, NSApplicationDelegate, SUUpdaterDelegate {
8997
func updater(_ updater: SUUpdater, failedToDownloadUpdate item: SUAppcastItem, error: Error) {
9098
updateProcessed.emit()
9199
}
100+
101+
@objc func willSleep(event: NSNotification) {
102+
Application.stopSave()
103+
}
104+
105+
@objc func didWakeUp(event: NSNotification) {
106+
Application.restart()
107+
}
92108
}
93109

94110

native/app/Source/Application.swift

Lines changed: 56 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,12 @@ class Application {
4646
static var dataBus: DataBus!
4747
static var updater = SUUpdater(for: Bundle.main)!
4848

49-
static let store: Store = Store(reducer: ApplicationStateReducer, state: Storage[.state] ?? ApplicationState(), middleware: [])
50-
51-
49+
static let store: Store = Store(
50+
reducer: ApplicationStateReducer,
51+
state: Storage[.state] ?? ApplicationState(),
52+
middleware: []
53+
)
54+
5255
static public func start () {
5356
if (!Constants.DEBUG) {
5457
setupCrashReporting()
@@ -94,7 +97,6 @@ class Application {
9497
message: message,
9598
buttons: ["Restart Mac", "Re-install eqMac", "Quit"]
9699
) { buttonPressed in
97-
Console.log(buttonPressed)
98100
switch NSApplication.ModalResponse(buttonPressed) {
99101
case .alertFirstButtonReturn:
100102
self.restartMac()
@@ -112,7 +114,7 @@ class Application {
112114

113115
private static func setupAudio () {
114116
Console.log("Setting up Audio Engine")
115-
showPassthroughDevice() {
117+
showDriver {
116118
// Make sure the Driver is not currently selected
117119
if (AudioDevice.currentOutputDevice.id == Driver.device!.id) {
118120
AudioDevice.builtInOutputDevice.setAsDefaultOutputDevice()
@@ -122,36 +124,36 @@ class Application {
122124
}
123125
}
124126

125-
private static var showPasshtroughDeviceChecks: Int = 0
126-
private static var showPassthroughDeviceCheckQueue: DispatchQueue?
127-
private static func showPassthroughDevice (_ completion: @escaping() -> Void) {
127+
private static var showDriverChecks: Int = 0
128+
private static var showDriverCheckQueue: DispatchQueue?
129+
private static func showDriver (_ completion: @escaping() -> Void) {
128130
if (Driver.hidden) {
129131
Driver.shown = true
130-
showPasshtroughDeviceChecks = 0
131-
showPassthroughDeviceCheckQueue = DispatchQueue(label: "check-driver-shown", qos: .userInteractive)
132-
showPassthroughDeviceCheckQueue!.asyncAfter(deadline: .now() + .milliseconds(500)) {
133-
return waitAndCheckForPasshtroughDeviceShown(completion)
132+
showDriverChecks = 0
133+
showDriverCheckQueue = DispatchQueue(label: "check-driver-shown", qos: .userInteractive)
134+
showDriverCheckQueue!.asyncAfter(deadline: .now() + .milliseconds(500)) {
135+
return waitAndCheckForDriverShown(completion)
134136
}
135137
} else {
136138
completion()
137139
}
138140
}
139-
private static func waitAndCheckForPasshtroughDeviceShown (_ completion: @escaping() -> Void) {
140-
showPasshtroughDeviceChecks += 1
141+
private static func waitAndCheckForDriverShown (_ completion: @escaping() -> Void) {
142+
showDriverChecks += 1
141143
if (Driver.device == nil) {
142-
if (showPasshtroughDeviceChecks > 5) {
143-
return passthroughDeviceFailedToActivatePrompt()
144+
if (showDriverChecks > 5) {
145+
return driverFailedToActivatePrompt()
144146
}
145-
showPassthroughDeviceCheckQueue!.asyncAfter(deadline: .now() + .milliseconds(500)) {
146-
return waitAndCheckForPasshtroughDeviceShown(completion)
147+
showDriverCheckQueue!.asyncAfter(deadline: .now() + .milliseconds(500)) {
148+
return waitAndCheckForDriverShown(completion)
147149
}
148150
return
149151
}
150-
showPassthroughDeviceCheckQueue = nil
152+
showDriverCheckQueue = nil
151153
completion()
152154
}
153155

154-
private static func passthroughDeviceFailedToActivatePrompt () {
156+
private static func driverFailedToActivatePrompt () {
155157
Alert.confirm(
156158
title: "Driver failed to activate", message: "Unfortunately the audio driver has failed to active. You can restart eqMac and try again or quit.", okText: "Try again", cancelText: "Quit") { restart in
157159
if restart {
@@ -164,11 +166,14 @@ class Application {
164166

165167
static var ignoreNextVolumeEvent = false
166168

167-
private static func setupDeviceEvents () {
169+
static func setupDeviceEvents () {
168170
AudioDeviceEvents.on(.outputChanged) { device in
169-
if device.isHardware {
171+
if device.id == Driver.device!.id { return }
172+
if Output.isDeviceAllowed(device) {
170173
Console.log("outputChanged: ", device, " starting PlayThrough")
171174
startPassthrough()
175+
} else {
176+
// TODO: Tell the user eqMac doesn't support this device
172177
}
173178
}
174179

@@ -177,35 +182,30 @@ class Application {
177182

178183
if list.added.count > 0 {
179184
for added in list.added {
180-
if Output.autoSelect(added) {
185+
if Output.shouldAutoSelect(added) {
181186
selectOutput(device: added)
182187
break
183188
}
184189
}
185190
} else if (list.removed.count > 0) {
186191

187-
var currentDeviceRemoved = false
188-
for removed in list.removed {
189-
if removed.id == selectedDevice.id {
190-
currentDeviceRemoved = true
191-
break
192-
}
193-
}
192+
let currentDeviceRemoved = list.removed.contains(where: { $0.id == selectedDevice.id })
194193

195-
stopEngines()
196-
if (!currentDeviceRemoved) {
194+
if (currentDeviceRemoved) {
195+
stopEngines()
197196
try! AudioDeviceEvents.recreateEventEmitters([.isAliveChanged, .volumeChanged, .nominalSampleRateChanged])
198197
self.setupDriverDeviceEvents()
199198
Utilities.delay(500) {
200-
createAudioPipeline()
199+
selectOutput(device: AudioDevice.builtInOutputDevice) // TODO: Replace with a known device from a stack
201200
}
202201
}
203202
}
204203

205204
}
206205
AudioDeviceEvents.on(.isJackConnectedChanged) { device in
207-
Console.log("isJackConnectedChanged", device, device.isJackConnected(direction: .playback))
208-
if (device.id != selectedDevice.id) {
206+
let connected = device.isJackConnected(direction: .playback)
207+
Console.log("isJackConnectedChanged", device, connected)
208+
if (connected == true && device.id != selectedDevice.id) {
209209
selectOutput(device: device)
210210
}
211211
}
@@ -214,7 +214,7 @@ class Application {
214214
}
215215

216216
static var ignoreNextDriverMuteEvent = false
217-
private static func setupDriverDeviceEvents () {
217+
static func setupDriverDeviceEvents () {
218218
AudioDeviceEvents.on(.volumeChanged, onDevice: Driver.device!) {
219219
if ignoreNextVolumeEvent {
220220
ignoreNextVolumeEvent = false
@@ -249,9 +249,13 @@ class Application {
249249
}
250250
}
251251

252-
private static func startPassthrough () {
252+
static func startPassthrough () {
253253
selectedDevice = AudioDevice.currentOutputDevice
254-
254+
255+
if (selectedDevice.id == Driver.device!.id) {
256+
selectOutput(device: AudioDevice.builtInOutputDevice) // TODO: Replace with a known device from a stack
257+
return
258+
}
255259
var volume: Double = Application.store.state.effects.volume.gain
256260
if (AudioDevice.currentOutputDevice.outputVolumeSupported) {
257261
volume = Double(AudioDevice.currentOutputDevice.virtualMasterVolume(direction: .playback)!)
@@ -263,7 +267,7 @@ class Application {
263267
Driver.device!.setVirtualMasterVolume(volume > 1 ? 1 : Float32(volume), direction: .playback)
264268
Driver.latency = selectedDevice.latency(direction: .playback) ?? 0 // Set driver latency to mimic device
265269
Driver.safetyOffset = selectedDevice.safetyOffset(direction: .playback) ?? 0 // Set driver latency to mimic device
266-
self.matchDriverSampleRateTo48000()
270+
self.matchDriverSampleRateToOutput()
267271

268272
Console.log("Driver new Latency: \(Driver.latency)")
269273
Console.log("Driver new Safety Offset: \(Driver.safetyOffset)")
@@ -308,7 +312,7 @@ class Application {
308312
// If device that we are sending audio to goes offline we need to stop and switch to a different device
309313
if (selectedDevice.isAlive() == false) {
310314
Console.log("Current device dies so switching to built it")
311-
selectOutput(device: AudioDevice.builtInOutputDevice)
315+
selectOutput(device: AudioDevice.builtInOutputDevice) // TODO: Replace with a known device from stack
312316
}
313317
}
314318

@@ -322,6 +326,7 @@ class Application {
322326
// need a delay, because emitter should finish it's work at first
323327
try! AudioDeviceEvents.recreateEventEmitters([.isAliveChanged, .volumeChanged, .nominalSampleRateChanged])
324328
self.setupDriverDeviceEvents()
329+
self.matchDriverSampleRateToOutput()
325330
stopEngines()
326331
createAudioPipeline()
327332
}
@@ -349,12 +354,12 @@ class Application {
349354
}
350355
}
351356

352-
private static func stopEngines () {
357+
static func stopEngines () {
353358
if (output != nil) {
354-
output.stop()
359+
output = nil
355360
}
356361
if (engine != nil) {
357-
engine.stop()
362+
engine = nil
358363
}
359364
}
360365

@@ -432,13 +437,17 @@ class Application {
432437
AudioDevice.currentOutputDevice = selectedDevice
433438
}
434439
}
435-
436-
static func quit () {
440+
441+
static func stopSave () {
437442
stopListeners()
438443
stopEngines()
439444
switchBackToLastKnownDevice()
440-
Driver.hidden = true
441445
Storage.synchronize()
446+
}
447+
448+
static func quit () {
449+
stopSave()
450+
Driver.hidden = true
442451
NSApp.terminate(nil)
443452
}
444453

@@ -462,9 +471,7 @@ class Application {
462471

463472
static func uninstall (_ completion: @escaping (Bool) -> Void) {
464473
Driver.uninstall(started: {
465-
self.stopListeners()
466-
self.stopEngines()
467-
self.switchBackToLastKnownDevice()
474+
self.stopSave()
468475
UI.close()
469476
Utilities.delay(100) { UI.showLoadingWindow("Uninstalling eqMac\nIf this process takes too long,\nplease restart your Mac") }
470477
}) { success in

native/app/Source/Audio/Engine.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ class Engine {
7979

8080
private func setupBuffer () {
8181
let framesPerSample = Driver.device!.bufferFrameSize(direction: .playback)
82-
ringBuffer = CARingBuffer<Float>(numberOfChannels: 2, capacityFrames: UInt32(framesPerSample * 2048))
82+
ringBuffer = CARingBuffer<Float>(numberOfChannels: 2, capacityFrames: UInt32(framesPerSample * 8))
8383
}
8484

8585
private func attach () {

native/app/Source/Audio/Outputs/Output.swift

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,23 +20,17 @@ class Output {
2020
&& Constants.SUPPORTED_TRANSPORT_TYPES.contains(device.transportType!)
2121
&& !device.isInputOnlyDevice()
2222
&& !device.name.contains("CADefaultDeviceAggregate")
23+
&& device.uid != Constants.DRIVER_DEVICE_UID
24+
&& !Constants.LEGACY_DRIVER_UIDS.contains(device.uid ?? "")
2325
}
2426

25-
static func autoSelect (_ device: AudioDevice) -> Bool {
27+
static func shouldAutoSelect (_ device: AudioDevice) -> Bool {
2628
let types: [TransportType] = [.bluetooth, .bluetoothLE, .builtIn]
2729
return Output.isDeviceAllowed(device) && types.contains(device.transportType!)
2830
}
2931

3032
static var allowedDevices: [AudioDevice] {
31-
return AudioDevice.allOutputDevices()
32-
.filter({ device in
33-
if let uid = device.uid {
34-
if (uid == Constants.PASSTHROUGH_DEVICE_UID || Constants.LEGACY_DRIVER_UIDS.contains(uid)) {
35-
return false
36-
}
37-
}
38-
return isDeviceAllowed(device)
39-
})
33+
return AudioDevice.allOutputDevices().filter({ isDeviceAllowed($0) })
4034
}
4135

4236
let outputRenderCallback: AURenderCallback = {

0 commit comments

Comments
 (0)