From c6f567535b3370c4630b0b28196a370bf8580cf5 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Mon, 22 Jun 2026 15:40:23 -0700 Subject: [PATCH 1/3] commit current state --- Demo/ShoeGazeBuilder/AppDelegate.swift | 33 ++-- .../ShoeGazeBuilderiOSApp.swift | 5 +- .../ShoeGazeBuilderiOSAppModel.swift | 8 +- Demo/ShoeGazeDemo/AppDelegate.swift | 12 +- Demo/ShoeGazeDemo/DemoRootView.swift | 53 +++--- .../ShoeGazeDemo/ShoeGazeDemoController.swift | 38 +++- .../xcshareddata/swiftpm/Package.resolved | 33 ++++ Demo/ShoeGazeiOSDemo/ShoeGazeiOSDemoApp.swift | 2 +- .../ShoeGazeiOSDemoAppModel.swift | 8 +- .../Presets/ShoeGaze+Engine.swift | 57 ++++++ .../LyrebirdShoeGazeUI/EngineConfigView.swift | 174 ++++++++++++++++++ .../ShoeGazeBuilderView.swift | 34 ++-- Sources/LyrebirdShoeGazeUI/ShoeGazeView.swift | 37 ++-- .../BoardEditAPITests.swift | 38 ++++ 14 files changed, 431 insertions(+), 101 deletions(-) create mode 100644 Demo/ShoeGazeiOSDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved create mode 100644 Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Engine.swift create mode 100644 Sources/LyrebirdShoeGazeUI/EngineConfigView.swift diff --git a/Demo/ShoeGazeBuilder/AppDelegate.swift b/Demo/ShoeGazeBuilder/AppDelegate.swift index 9a4813f..6a16f1c 100644 --- a/Demo/ShoeGazeBuilder/AppDelegate.swift +++ b/Demo/ShoeGazeBuilder/AppDelegate.swift @@ -27,7 +27,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate { private static let blockSize: Int = 512 private static let sampleRate: Double = 48_000.0 private static let outputChannels: Int = 2 - private static let inputChannels: Int = 2 + // Built-in mics are mono; default to one input channel so live input works out of the box. + // CoreAudio can't satisfy a request for more input channels than the device provides, which + // leaves live input silent. Users with multi-input interfaces can raise this in the UI. + private static let inputChannels: Int = 1 private static let numAudioBuses: Int = 256 // MARK: - Window geometry constants @@ -47,14 +50,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // MARK: - Owned objects + private let coreDriver: CoreAudioDriver private let engine: SynthesisEngine private let shoeGaze: ShoeGaze private let window: LyrebirdWindow - /// Transport menu items, retained so `validateMenuItem(_:)` can enable/disable them. - private var startMenuItem: NSMenuItem? - private var stopMenuItem: NSMenuItem? - /// Record toggle item, retained so `validateMenuItem(_:)` can flip its title + enabled state. private var recordMenuItem: NSMenuItem? @@ -64,14 +64,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // MARK: - Init override init() { + let coreDriver: CoreAudioDriver = CoreAudioDriver() let engine: SynthesisEngine = SynthesisEngine( blockSize: AppDelegate.blockSize, sampleRate: AppDelegate.sampleRate, numOutputChannels: AppDelegate.outputChannels, numInputChannels: AppDelegate.inputChannels, numAudioBuses: AppDelegate.numAudioBuses, - driver: CoreAudioDriver() + driver: coreDriver ) + self.coreDriver = coreDriver self.engine = engine self.shoeGaze = ShoeGaze(engine: engine) self.window = LyrebirdWindow( @@ -102,8 +104,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ notification: Notification) { installMainMenu() let session: ShoeGaze = shoeGaze + let driver: CoreAudioDriver = coreDriver window.open { - ShoeGazeBuilderView(shoeGaze: session) + ShoeGazeBuilderView(shoeGaze: session, hardwareSampleRate: { driver.deviceSampleRate }) } anchorWindowLeft() } @@ -176,10 +179,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate { mainMenu.addItem(boardMenuItem) let boardMenu: NSMenu = NSMenu(title: "Board") boardMenuItem.submenu = boardMenu + // Engine start/stop lives in the in-window EngineConfigView (with sample-rate/channel + // config and the mismatch alert), so the Board menu only adds boards. addItem(to: boardMenu, title: "Add Board", action: #selector(addBoardAction(_:)), key: "b") - boardMenu.addItem(NSMenuItem.separator()) - startMenuItem = addItem(to: boardMenu, title: "Start", action: #selector(startAction(_:)), key: "r") - stopMenuItem = addItem(to: boardMenu, title: "Stop", action: #selector(stopAction(_:)), key: ".") // Record menu — choose an output folder, then toggle recording. let recordMenuItem: NSMenuItem = NSMenuItem() @@ -262,15 +264,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } } - @objc private func startAction(_ sender: Any?) { - do { try engine.start() } - catch { print("[ShoeGazeBuilder] engine.start() failed: \(error)") } - } - - @objc private func stopAction(_ sender: Any?) { - engine.stop() - } - @objc private func chooseRecordingFolderAction(_ sender: Any?) { let panel: NSOpenPanel = NSOpenPanel() panel.canChooseDirectories = true @@ -299,8 +292,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { - if menuItem == startMenuItem { return !engine.isRunning } - if menuItem == stopMenuItem { return engine.isRunning } if menuItem == recordMenuItem { menuItem.title = shoeGaze.isRecording ? "Stop Recording" : "Start Recording" // Can always stop; can only start once a folder has been chosen. diff --git a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift index 78f4d3a..3179b41 100644 --- a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift +++ b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift @@ -23,7 +23,10 @@ struct ShoeGazeBuilderiOSApp: App { var body: some Scene { WindowGroup { NavigationStack { - ShoeGazeBuilderView(shoeGaze: model.shoeGaze) + ShoeGazeBuilderView( + shoeGaze: model.shoeGaze, + hardwareSampleRate: { model.hardwareSampleRate } + ) .navigationTitle("ShoeGaze Builder") .navigationBarTitleDisplayMode(.inline) } diff --git a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift index bf5a257..22f044a 100644 --- a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift +++ b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift @@ -33,6 +33,10 @@ final class ShoeGazeBuilderiOSAppModel { private(set) var shoeGaze: ShoeGaze private let engine: SynthesisEngine + private let iosDriver: iOSAudioDriver + + /// The sample rate the audio session actually committed to (for the config mismatch warning). + var hardwareSampleRate: Double? { iosDriver.sessionSampleRate } // MARK: - Init @@ -50,14 +54,16 @@ final class ShoeGazeBuilderiOSAppModel { } let sampleRate: Double = session.sampleRate + let driver: iOSAudioDriver = iOSAudioDriver() let eng: SynthesisEngine = SynthesisEngine( blockSize: ShoeGazeBuilderiOSAppModel.blockSize, sampleRate: sampleRate, numOutputChannels: ShoeGazeBuilderiOSAppModel.outputChannels, numInputChannels: 0, numAudioBuses: ShoeGazeBuilderiOSAppModel.numAudioBuses, - driver: iOSAudioDriver() + driver: driver ) + self.iosDriver = driver self.engine = eng self.shoeGaze = ShoeGaze(engine: eng) diff --git a/Demo/ShoeGazeDemo/AppDelegate.swift b/Demo/ShoeGazeDemo/AppDelegate.swift index a74af91..ab08347 100644 --- a/Demo/ShoeGazeDemo/AppDelegate.swift +++ b/Demo/ShoeGazeDemo/AppDelegate.swift @@ -27,7 +27,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate { private static let blockSize: Int = 512 private static let sampleRate: Double = 48_000.0 private static let outputChannels: Int = 2 - private static let inputChannels: Int = 6 + // Built-in mics are mono; default to one input channel so live input works out of the box + // (CoreAudio can't satisfy more input channels than the device provides). Raise in the UI. + private static let inputChannels: Int = 1 private static let numAudioBuses: Int = 256 // MARK: - Window geometry constants @@ -37,6 +39,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // MARK: - Owned objects + private let coreDriver: CoreAudioDriver private let controller: ShoeGazeDemoController private let window: LyrebirdWindow @@ -46,15 +49,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // MARK: - Init override init() { + let coreDriver: CoreAudioDriver = CoreAudioDriver() let engine: SynthesisEngine = SynthesisEngine( blockSize: AppDelegate.blockSize, sampleRate: AppDelegate.sampleRate, numOutputChannels: AppDelegate.outputChannels, numInputChannels: AppDelegate.inputChannels, numAudioBuses: AppDelegate.numAudioBuses, - driver: CoreAudioDriver() + driver: coreDriver ) + self.coreDriver = coreDriver self.controller = ShoeGazeDemoController(engine: engine) self.window = LyrebirdWindow( title: "ShoeGaze — Lyrebird Guitar Pedalboard", @@ -69,8 +74,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ notification: Notification) { installMainMenu() let demoController: ShoeGazeDemoController = controller + let driver: CoreAudioDriver = coreDriver window.open { - DemoRootView(controller: demoController) + DemoRootView(controller: demoController, hardwareSampleRate: { driver.deviceSampleRate }) } } diff --git a/Demo/ShoeGazeDemo/DemoRootView.swift b/Demo/ShoeGazeDemo/DemoRootView.swift index 856fceb..09cd360 100644 --- a/Demo/ShoeGazeDemo/DemoRootView.swift +++ b/Demo/ShoeGazeDemo/DemoRootView.swift @@ -47,6 +47,7 @@ struct DemoRootView: View { // MARK: - Properties private let controller: ShoeGazeDemoController + private let hardwareSampleRate: () -> Double? /// Bumped on each transport press so the buttons re-read `controller.isRunning` /// (which derives from the non-observable engine). @@ -56,10 +57,17 @@ struct DemoRootView: View { /// Creates the root demo view bound to the given controller. /// - /// - Parameter controller: The `ShoeGazeDemoController` that owns the engine, active - /// `ShoeGaze` session, and current mode. All toolbar actions dispatch through this. - init(controller: ShoeGazeDemoController) { + /// - Parameters: + /// - controller: The `ShoeGazeDemoController` that owns the engine, active `ShoeGaze` + /// session, and current mode. All toolbar actions dispatch through this. + /// - hardwareSampleRate: Returns the actual hardware sample rate (or `nil`), for the engine- + /// config mismatch warning. Defaults to `nil`. + init( + controller: ShoeGazeDemoController, + hardwareSampleRate: @escaping () -> Double? = { nil } + ) { self.controller = controller + self.hardwareSampleRate = hardwareSampleRate } // MARK: - Body @@ -157,7 +165,7 @@ struct DemoRootView: View { .foregroundStyle(Color.white.opacity(0.65)) Picker("Input", selection: inputSourceBinding) { Text("Test Loop").tag(-1) - ForEach(0..= inputChannels { + inputSource = .testLoop + } + buildSession() + + if wasRunning { start() } + } + // MARK: - Rebuild /// Tears down the current session and rebuilds the active mode. @@ -169,14 +195,22 @@ final class ShoeGazeDemoController { private func rebuild() { let wasRunning: Bool = isRunning if wasRunning { stop() } + tearDownSession() + buildSession() + if wasRunning { start() } + } + /// Removes the current session's nodes and clears split/router references. + private func tearDownSession() { shoeGaze.teardown() router = nil parallelSection = nil stereoSection = nil + } + /// Creates a fresh session and builds the active mode's graph. + private func buildSession() { shoeGaze = ShoeGaze(engine: engine, inputSource: inputSource) - switch mode { case .boards: buildBoards() case .editor: buildEditor() @@ -184,8 +218,6 @@ final class ShoeGazeDemoController { case .router: buildRouter() case .stereo: buildStereo() } - - if wasRunning { start() } } // MARK: - Mode builders diff --git a/Demo/ShoeGazeiOSDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Demo/ShoeGazeiOSDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..82a587c --- /dev/null +++ b/Demo/ShoeGazeiOSDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,33 @@ +{ + "originHash" : "cfdd71f4b32d744c862bbe26a8265d75aa9e906275b0fb1b63575b7d68be1b6a", + "pins" : [ + { + "identity" : "linenoise-swift", + "kind" : "remoteSourceControl", + "location" : "https://github.com/andybest/linenoise-swift", + "state" : { + "revision" : "afc897c02b030af7333105c4fedcd843a8339238", + "version" : "0.0.3" + } + }, + { + "identity" : "lyrebird", + "kind" : "remoteSourceControl", + "location" : "https://realizedsound.mooo.com/josh/Lyrebird", + "state" : { + "revision" : "032b7c39d351eba4029e8399e1ab1ee201e8bb5c", + "version" : "1.2.0" + } + }, + { + "identity" : "nimble", + "kind" : "remoteSourceControl", + "location" : "https://github.com/Quick/Nimble.git", + "state" : { + "revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0", + "version" : "7.3.4" + } + } + ], + "version" : 3 +} diff --git a/Demo/ShoeGazeiOSDemo/ShoeGazeiOSDemoApp.swift b/Demo/ShoeGazeiOSDemo/ShoeGazeiOSDemoApp.swift index a254966..4954bab 100644 --- a/Demo/ShoeGazeiOSDemo/ShoeGazeiOSDemoApp.swift +++ b/Demo/ShoeGazeiOSDemo/ShoeGazeiOSDemoApp.swift @@ -22,7 +22,7 @@ struct ShoeGazeiOSDemoApp: App { WindowGroup { NavigationStack { ScrollView { - ShoeGazeView(shoeGaze: model.shoeGaze) + ShoeGazeView(shoeGaze: model.shoeGaze, hardwareSampleRate: { model.hardwareSampleRate }) .padding(.horizontal, 12) } .navigationTitle("ShoeGaze") diff --git a/Demo/ShoeGazeiOSDemo/ShoeGazeiOSDemoAppModel.swift b/Demo/ShoeGazeiOSDemo/ShoeGazeiOSDemoAppModel.swift index d7ceba5..9473c7d 100644 --- a/Demo/ShoeGazeiOSDemo/ShoeGazeiOSDemoAppModel.swift +++ b/Demo/ShoeGazeiOSDemo/ShoeGazeiOSDemoAppModel.swift @@ -41,6 +41,10 @@ final class ShoeGazeiOSDemoAppModel { private(set) var shoeGaze: ShoeGaze private let engine: SynthesisEngine + private let iosDriver: iOSAudioDriver + + /// The sample rate the audio session actually committed to (for the config mismatch warning). + var hardwareSampleRate: Double? { iosDriver.sessionSampleRate } // MARK: - Init @@ -54,14 +58,16 @@ final class ShoeGazeiOSDemoAppModel { try? session.setActive(true) let sampleRate: Double = session.sampleRate + let driver: iOSAudioDriver = iOSAudioDriver() let eng: SynthesisEngine = SynthesisEngine( blockSize: ShoeGazeiOSDemoAppModel.blockSize, sampleRate: sampleRate, numOutputChannels: ShoeGazeiOSDemoAppModel.outputChannels, numInputChannels: 0, numAudioBuses: ShoeGazeiOSDemoAppModel.numAudioBuses, - driver: iOSAudioDriver() + driver: driver ) + self.iosDriver = driver self.engine = eng self.shoeGaze = ShoeGaze(engine: eng) diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Engine.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Engine.swift new file mode 100644 index 0000000..64408c2 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Engine.swift @@ -0,0 +1,57 @@ +// ShoeGaze+Engine.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +extension ShoeGaze { + + /// Reconfigures the engine's sample rate and channel counts while preserving the rig. + /// + /// The engine must be **stopped** (the underlying `SynthesisEngine` setters throw + /// `SynthesisEngineConfigError.engineIsRunning` otherwise). The current rig is captured, + /// the engine is reconfigured, and every board is rebuilt from the snapshot so that + /// sample-rate-dependent nodes — e.g. ``TestLoopSource``'s Karplus-Strong delay line, sized at + /// init from the engine rate — are recreated at the new rate. Reconstruction reuses the atomic + /// ``rebuildAllBoards(from:)`` (teardown-on-failure), so a failure leaves an empty rig rather + /// than a half-built one. + /// + /// If the current `inputSource` is `.liveInput(channel:)` and `channel` is no longer valid + /// under `inputChannels`, the source is reset to `.testLoop` before rebuilding. + /// + /// - Parameters: + /// - sampleRate: New engine sample rate in Hz. + /// - inputChannels: New hardware input-channel count (`>= 0`). + /// - outputChannels: New hardware output-channel count (`>= 1`). + /// - Throws: `SynthesisEngineConfigError.engineIsRunning` if the engine is running; + /// `SynthesisEngineConfigError.invalidValue` for out-of-range values; or any error from + /// board reconstruction. + public func reconfigureEngine( + sampleRate: Double, + inputChannels: Int, + outputChannels: Int + ) throws { + guard !engine.isRunning else { throw SynthesisEngineConfigError.engineIsRunning } + + let snapshot: ShoeGazeState = captureState() + + // Tear the rig down BEFORE reconfiguring: changing the channel counts re-partitions the + // bus allocator's hardware reservation, which would invalidate (double-free) any rig buses + // still allocated under the old layout. + teardown() + + try engine.setSampleRate(sampleRate) + try engine.setNumOutputChannels(outputChannels) + try engine.setNumInputChannels(inputChannels) + + // A live-input source pointing at a channel that no longer exists would make the rebuild's + // addBoard() throw; fall back to the test loop. + if case .liveInput(let channel) = inputSource, channel >= inputChannels { + inputSource = .testLoop + } + + try rebuildAllBoards(from: snapshot) + } +} diff --git a/Sources/LyrebirdShoeGazeUI/EngineConfigView.swift b/Sources/LyrebirdShoeGazeUI/EngineConfigView.swift new file mode 100644 index 0000000..8576a71 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/EngineConfigView.swift @@ -0,0 +1,174 @@ +// EngineConfigView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdSynth +import LyrebirdShoeGaze + +/// Engine configuration + transport: sample rate, input/output channel counts, and a Start/Stop +/// toggle, with a sample-rate-mismatch alert on start. +/// +/// The config controls are editable only while the engine is stopped (the underlying +/// `SynthesisEngine` setters require it). Pressing Start applies the pending values via +/// `ShoeGaze.reconfigureEngine(...)` — which preserves the rig — then starts the engine. On macOS +/// a mismatch surfaces as a thrown `CoreAudioError.sampleRateMismatch` (the engine stays stopped); +/// on iOS the committed session rate is compared against the request after start. Either way an +/// alert reports the requested vs hardware rate; the user picks a matching rate. +/// +/// - Parameters: +/// - shoeGaze: The session whose engine is configured and started/stopped. +/// - hardwareSampleRate: Returns the actual hardware/session rate, or `nil` if unknown. Supplied +/// by the host app (macOS: `CoreAudioDriver.deviceSampleRate`; iOS: `iOSAudioDriver.sessionSampleRate`). +public struct EngineConfigView: View { + + // MARK: - Constants + + /// Standard sample rates offered in the picker. + private static let standardRates: [Double] = [44_100, 48_000, 88_200, 96_000] + /// Channel-count stepper bounds. + private static let maxInputs: Int = 8 + private static let maxOutputs: Int = 8 + /// Sample-rate comparison tolerance in Hz. + private static let rateEpsilon: Double = 0.5 + private static let rowSpacing: CGFloat = 12 + private static let labelOpacity: Double = 0.65 + + // MARK: - Properties + + private let shoeGaze: ShoeGaze + private let hardwareSampleRate: () -> Double? + private let applyConfig: ((Double, Int, Int) throws -> Void)? + private let onConfigApplied: () -> Void + + @State private var pendingSampleRate: Double + @State private var pendingInputs: Int + @State private var pendingOutputs: Int + @State private var transportTick: Bool = false + @State private var showAlert: Bool = false + @State private var alertText: String = "" + + // MARK: - Init + + /// - Parameter applyConfig: Optional override for applying the chosen `(sampleRate, inputs, + /// outputs)` while stopped (e.g. a controller that rebuilds a non-board showcase). When `nil`, + /// `ShoeGaze.reconfigureEngine(...)` is used, which preserves the board rig. + /// - Parameter onConfigApplied: Called after the engine is (re)configured or started/stopped, + /// so a host can refresh views that read non-observable engine state (e.g. an input-channel + /// picker that lists `0.. Double? = { nil }, + applyConfig: ((Double, Int, Int) throws -> Void)? = nil, + onConfigApplied: @escaping () -> Void = { } + ) { + self.shoeGaze = shoeGaze + self.hardwareSampleRate = hardwareSampleRate + self.applyConfig = applyConfig + self.onConfigApplied = onConfigApplied + _pendingSampleRate = State(initialValue: shoeGaze.engine.sampleRate) + _pendingInputs = State(initialValue: shoeGaze.engine.numInputChannels) + _pendingOutputs = State(initialValue: shoeGaze.engine.numOutputChannels) + } + + // MARK: - Body + + public var body: some View { + _ = transportTick + let isRunning: Bool = shoeGaze.engine.isRunning + return HStack(spacing: EngineConfigView.rowSpacing) { + label("Rate") + Picker("Rate", selection: $pendingSampleRate) { + ForEach(EngineConfigView.standardRates, id: \.self) { rate in + Text("\(Int(rate)) Hz").tag(rate) + } + } + .labelsHidden() + .pickerStyle(.menu) + .disabled(isRunning) + + Stepper(value: $pendingInputs, in: 0...EngineConfigView.maxInputs) { + Text("In: \(pendingInputs)").foregroundStyle(Color.white) + } + .disabled(isRunning) + .fixedSize() + + Stepper(value: $pendingOutputs, in: 1...EngineConfigView.maxOutputs) { + Text("Out: \(pendingOutputs)").foregroundStyle(Color.white) + } + .disabled(isRunning) + .fixedSize() + + Button(isRunning ? "Stop" : "Start") { + if isRunning { stopEngine() } else { startEngine() } + } + .buttonStyle(.borderedProminent) + .tint(isRunning ? .red : .green) + } + .alert("Sample Rate Mismatch", isPresented: $showAlert) { + Button("OK", role: .cancel) { } + } message: { + Text(alertText) + } + } + + private func label(_ text: String) -> some View { + Text(text) + .font(.subheadline) + .foregroundStyle(Color.white.opacity(EngineConfigView.labelOpacity)) + } + + // MARK: - Transport + + private func startEngine() { + do { + if let applyConfig: (Double, Int, Int) throws -> Void = applyConfig { + try applyConfig(pendingSampleRate, pendingInputs, pendingOutputs) + } else { + try shoeGaze.reconfigureEngine( + sampleRate: pendingSampleRate, + inputChannels: pendingInputs, + outputChannels: pendingOutputs + ) + } + try shoeGaze.engine.start() + } catch { + handleStartError(error) + transportTick.toggle() + onConfigApplied() // config may have applied even if start failed (e.g. rate mismatch) + return + } + // Started OK. On iOS the session may have committed a different rate than requested. + if let hardware: Double = hardwareSampleRate(), + abs(hardware - shoeGaze.engine.sampleRate) > EngineConfigView.rateEpsilon { + presentMismatch(requested: shoeGaze.engine.sampleRate, hardware: hardware) + } + transportTick.toggle() + onConfigApplied() + } + + private func stopEngine() { + shoeGaze.engine.stop() + transportTick.toggle() + onConfigApplied() + } + + private func handleStartError(_ error: Error) { + #if os(macOS) + if let coreAudio: CoreAudioError = error as? CoreAudioError, + case .sampleRateMismatch(let requested, let deviceRate) = coreAudio { + presentMismatch(requested: requested, hardware: deviceRate) + return + } + #endif + print("[EngineConfigView] engine start failed: \(error)") + } + + private func presentMismatch(requested: Double, hardware: Double) { + alertText = "Requested \(Int(requested)) Hz, but the hardware is running at " + + "\(Int(hardware)) Hz. Set the sample rate to \(Int(hardware)) Hz and start again." + showAlert = true + } +} diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index 1ee4265..dc56cf1 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -55,6 +55,7 @@ public struct ShoeGazeBuilderView: View { // MARK: - Properties private let shoeGaze: ShoeGaze + private let hardwareSampleRate: () -> Double? /// Index of the board currently being edited. @State private var selectedBoardIndex: Int = 0 @@ -75,10 +76,17 @@ public struct ShoeGazeBuilderView: View { /// Creates a builder view. /// - /// - Parameter shoeGaze: The `ShoeGaze` manager whose boards and engine are edited. The - /// caller should create at least one board before presenting this view. - public init(shoeGaze: ShoeGaze) { + /// - Parameters: + /// - shoeGaze: The `ShoeGaze` manager whose boards and engine are edited. The caller should + /// create at least one board before presenting this view. + /// - hardwareSampleRate: Returns the actual hardware/session sample rate (or `nil`), used by + /// the engine-config Start to warn on a mismatch. Defaults to `nil`. + public init( + shoeGaze: ShoeGaze, + hardwareSampleRate: @escaping () -> Double? = { nil } + ) { self.shoeGaze = shoeGaze + self.hardwareSampleRate = hardwareSampleRate } // MARK: - Body @@ -132,7 +140,6 @@ public struct ShoeGazeBuilderView: View { private var transportRow: some View { _ = transportTick - let isRunning: Bool = shoeGaze.engine.isRunning return HStack(spacing: ShoeGazeBuilderView.rowSpacing) { Text("ShoeGaze Builder") .font(.title2).bold() @@ -150,18 +157,11 @@ public struct ShoeGazeBuilderView: View { } } Spacer() - Button("Start") { - do { try shoeGaze.engine.start() } - catch { print("[ShoeGazeBuilderView] engine.start() failed: \(error)") } - transportTick.toggle() - } - .buttonStyle(.borderedProminent).tint(.green).disabled(isRunning) - - Button("Stop") { - shoeGaze.engine.stop() - transportTick.toggle() - } - .buttonStyle(.bordered).tint(.red).disabled(!isRunning) + EngineConfigView( + shoeGaze: shoeGaze, + hardwareSampleRate: hardwareSampleRate, + onConfigApplied: { transportTick.toggle() } + ) } } @@ -174,7 +174,7 @@ public struct ShoeGazeBuilderView: View { .foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.labelOpacity)) Picker("Input", selection: inputBinding) { Text("Test Loop").tag(ShoeGazeBuilderView.testLoopTag) - ForEach(0.. Double? /// Bumped on each transport button press to force a re-read of the engine's /// running state. The button labels/enabled-state read `shoeGaze.engine.isRunning` @@ -87,11 +88,16 @@ public struct ShoeGazeView: View { /// Creates a top-level ShoeGaze view. /// - /// - Parameter shoeGaze: The `ShoeGaze` manager whose boards and engine will - /// be displayed. The caller is responsible for engine lifecycle; this view - /// provides Start and Stop transport buttons as a convenience. - public init(shoeGaze: ShoeGaze) { + /// - Parameters: + /// - shoeGaze: The `ShoeGaze` manager whose boards and engine will be displayed. + /// - hardwareSampleRate: Returns the actual hardware/session sample rate (or `nil`), used by + /// the engine-config Start to warn on a mismatch. Defaults to `nil`. + public init( + shoeGaze: ShoeGaze, + hardwareSampleRate: @escaping () -> Double? = { nil } + ) { self.shoeGaze = shoeGaze + self.hardwareSampleRate = hardwareSampleRate } // MARK: - Body @@ -153,7 +159,6 @@ public struct ShoeGazeView: View { // Referencing `transportTick` makes a press (which toggles it) re-evaluate this // view so `engine.isRunning` is re-read; toggling any @State invalidates the view. _ = transportTick - let isRunning: Bool = shoeGaze.engine.isRunning return HStack(spacing: ShoeGazeView.transportSpacing) { Text("ShoeGaze") .font(.title2) @@ -166,27 +171,7 @@ public struct ShoeGazeView: View { .buttonStyle(.bordered) .tint(.orange) - Button("Start") { - do { - try shoeGaze.engine.start() - } catch { - // Surface start errors to the console; the UI remains in the - // non-running state so the user can retry. - print("[ShoeGazeView] engine.start() failed: \(error)") - } - transportTick.toggle() - } - .buttonStyle(.borderedProminent) - .tint(.green) - .disabled(isRunning) - - Button("Stop") { - shoeGaze.engine.stop() - transportTick.toggle() - } - .buttonStyle(.bordered) - .tint(.red) - .disabled(!isRunning) + EngineConfigView(shoeGaze: shoeGaze, hardwareSampleRate: hardwareSampleRate) } } diff --git a/Tests/LyrebirdShoeGazeTests/BoardEditAPITests.swift b/Tests/LyrebirdShoeGazeTests/BoardEditAPITests.swift index 5f2dc1c..9e348cd 100644 --- a/Tests/LyrebirdShoeGazeTests/BoardEditAPITests.swift +++ b/Tests/LyrebirdShoeGazeTests/BoardEditAPITests.swift @@ -427,6 +427,44 @@ struct BoardEditAPITests { #expect(hasNonSilentOutput(samples), "parallel board should render audio") } + // MARK: - Engine reconfiguration + + @Test func reconfigureEnginePreservesRigAndAppliesConfig() throws { + let (sg, engine, url, _): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay"]) + defer { try? FileManager.default.removeItem(at: url) } + + try sg.reconfigureEngine(sampleRate: 96_000, inputChannels: 0, outputChannels: 2) + + #expect(engine.sampleRate == 96_000) + #expect(engine.numInputChannels == 0) + #expect(engine.numOutputChannels == 2) + #expect(sg.boards.count == 1) + #expect(names(sg.boards[0]) == ["Overdrive", "Delay"], "rig preserved across reconfigure") + + let samples: [Float] = try render(engine, url) + #expect(hasNonSilentOutput(samples), "reconfigured rig should render") + } + + @Test func reconfigureResetsOutOfRangeLiveInput() throws { + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine( + duration: 0.1, + numInputChannels: 2, + numAudioBuses: 128 + ) + defer { try? FileManager.default.removeItem(at: url) } + + let sg: ShoeGaze = ShoeGaze(engine: engine, inputSource: .liveInput(channel: 1)) + let board: PedalBoard = try sg.addBoard() + try board.add(OverdrivePedal()) + try sg.finalizeBoard(board) + + // Drop to a single input channel — channel 1 no longer exists. + try sg.reconfigureEngine(sampleRate: 48_000, inputChannels: 1, outputChannels: 2) + #expect(sg.inputSource == .testLoop, "out-of-range live input should fall back to test loop") + #expect(engine.numInputChannels == 1) + } + // MARK: - Save / load round-trip on an edited board @Test func overdriveDriveEightPersistsAcrossSaveAndReload() throws { From ed27ab166c84f74f44c29ecd528c9a72d3e411d3 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Mon, 22 Jun 2026 21:07:13 -0700 Subject: [PATCH 2/3] add scope for debugging --- Demo/ShoeGazeDemo/AppDelegate.swift | 2 +- Demo/ShoeGazeDemo/DemoRootView.swift | 4 + .../ShoeGazeDemo/ShoeGazeDemoController.swift | 2 + .../Presets/ShoeGaze+Engine.swift | 51 ++++++++++++ Sources/LyrebirdShoeGaze/ShoeGaze.swift | 11 +++ .../ShoeGazeBuilderView.swift | 1 + .../ShoeGazeScopeView.swift | 83 +++++++++++++++++++ Sources/LyrebirdShoeGazeUI/ShoeGazeView.swift | 3 + 8 files changed, 156 insertions(+), 1 deletion(-) create mode 100644 Sources/LyrebirdShoeGazeUI/ShoeGazeScopeView.swift diff --git a/Demo/ShoeGazeDemo/AppDelegate.swift b/Demo/ShoeGazeDemo/AppDelegate.swift index ab08347..aa96e26 100644 --- a/Demo/ShoeGazeDemo/AppDelegate.swift +++ b/Demo/ShoeGazeDemo/AppDelegate.swift @@ -29,7 +29,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { private static let outputChannels: Int = 2 // Built-in mics are mono; default to one input channel so live input works out of the box // (CoreAudio can't satisfy more input channels than the device provides). Raise in the UI. - private static let inputChannels: Int = 1 + private static let inputChannels: Int = 6 private static let numAudioBuses: Int = 256 // MARK: - Window geometry constants diff --git a/Demo/ShoeGazeDemo/DemoRootView.swift b/Demo/ShoeGazeDemo/DemoRootView.swift index 09cd360..765d86f 100644 --- a/Demo/ShoeGazeDemo/DemoRootView.swift +++ b/Demo/ShoeGazeDemo/DemoRootView.swift @@ -79,6 +79,10 @@ struct DemoRootView: View { .overlay(Color.white.opacity(DemoRootView.dividerOpacity)) contentArea .padding(DemoRootView.contentPadding) + Divider() + .overlay(Color.white.opacity(DemoRootView.dividerOpacity)) + ShoeGazeScopeView(shoeGaze: controller.shoeGaze) + .padding(DemoRootView.contentPadding) } .frame( minWidth: DemoRootView.windowMinWidth, diff --git a/Demo/ShoeGazeDemo/ShoeGazeDemoController.swift b/Demo/ShoeGazeDemo/ShoeGazeDemoController.swift index 6d9a86d..01771ed 100644 --- a/Demo/ShoeGazeDemo/ShoeGazeDemoController.swift +++ b/Demo/ShoeGazeDemo/ShoeGazeDemoController.swift @@ -182,6 +182,8 @@ final class ShoeGazeDemoController { inputSource = .testLoop } buildSession() + // Input buses follow the output buses, so the tapped indices change with the layout. + shoeGaze.installScopeTap() if wasRunning { start() } } diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Engine.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Engine.swift index 64408c2..4a8e774 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Engine.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Engine.swift @@ -53,5 +53,56 @@ extension ShoeGaze { } try rebuildAllBoards(from: snapshot) + + // The tapped bus indices depend on the channel layout (input buses follow the output + // buses), so rebuild the scope tap for the new configuration. + installScopeTap() + } + + /// Default samples-per-frame captured by the scope tap. + public static let defaultScopeBufferSize: Int = 2_048 + + /// (Re)builds the ``scopeTap`` over the current hardware input + output buses and assigns it + /// to the engine, so the debug scope view can visualise both the live input signal and the + /// board output. + /// + /// Lane order is **inputs first** (`In 0`, `In 1`, …) then **outputs** (`Out L`, `Out R`, …), + /// so the input waveform sits at the top of the scope. Must be called while the engine is + /// stopped — `SynthesisEngine` caches its scope tap at `start()`. Rebuilt automatically by + /// ``reconfigureEngine(sampleRate:inputChannels:outputChannels:)`` and at init. + /// + /// - Parameter bufferSize: Samples per channel per display frame. Defaults to 2048. + public func installScopeTap(bufferSize: Int = ShoeGaze.defaultScopeBufferSize) { + let numOut: Int = engine.numOutputChannels + let numIn: Int = engine.numInputChannels + + var buses: [Int] = [] + for ch: Int in 0.. String { + let numOut: Int = engine.numOutputChannels + guard bus >= numOut else { + let stereoNames: [String] = ["Out L", "Out R"] + return bus < stereoNames.count ? stereoNames[bus] : "Out \(bus)" + } + return "In \(bus - numOut)" } } diff --git a/Sources/LyrebirdShoeGaze/ShoeGaze.swift b/Sources/LyrebirdShoeGaze/ShoeGaze.swift index d7bb035..a70ff1b 100644 --- a/Sources/LyrebirdShoeGaze/ShoeGaze.swift +++ b/Sources/LyrebirdShoeGaze/ShoeGaze.swift @@ -84,6 +84,16 @@ public final class ShoeGaze { /// (same module, different file) can mutate it. internal var recordTaps: [RecordTap] = [] + // MARK: - Scope state + + /// Scope tap over the hardware input + output buses, feeding the debug scope view. + /// + /// Rebuilt by ``installScopeTap(bufferSize:)`` whenever the engine layout changes (so the + /// tapped bus indices follow the current input/output channel counts). `nil` until first + /// installed. The setter is `internal` so ``installScopeTap(bufferSize:)`` (same module, + /// different file) can assign it; external callers observe it through this `public` getter. + public internal(set) var scopeTap: ScopeCapture? + // MARK: - Private private var testLoopSources: [TestLoopSource] = [] @@ -110,6 +120,7 @@ public final class ShoeGaze { ) { self.engine = engine self.inputSource = inputSource + installScopeTap() } // MARK: - Board management diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index dc56cf1..98b2d46 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -105,6 +105,7 @@ public struct ShoeGazeBuilderView: View { boardArea } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + ShoeGazeScopeView(shoeGaze: shoeGaze) LyrebirdStatusView(engine: shoeGaze.engine) } .padding(ShoeGazeBuilderView.outerPadding) diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeScopeView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeScopeView.swift new file mode 100644 index 0000000..3bbc170 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeScopeView.swift @@ -0,0 +1,83 @@ +// ShoeGazeScopeView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdSynth +import LyrebirdUI +import LyrebirdShoeGaze + +/// Oscilloscope panel showing the live input and board-output waveforms. +/// +/// Wraps Lyrebird's `LyrebirdScopeView` bound to ``ShoeGaze/scopeTap`` and adds a labelled +/// legend so each lane is identifiable (`In 0`, `Out L`, `Out R`, …) — input lanes on top, +/// outputs below. Use it to confirm signal flow: a flat input lane with audible test-tone +/// output means the live input never reaches the board head bus; a live input lane with a flat +/// output lane points downstream. +/// +/// The lane colours match `LyrebirdScopeView` (cyan, orange, green, yellow, cycling). The view +/// keys itself on the tap's object identity so a reconfigure that rebuilds the tap recreates the +/// underlying scope. +public struct ShoeGazeScopeView: View { + + // MARK: - Constants + + /// Colours used by `LyrebirdScopeView`, mirrored here for the legend swatches. + private static let laneColors: [Color] = [.cyan, .orange, .green, .yellow] + private static let scopeHeight: CGFloat = 120 + private static let legendSpacing: CGFloat = 14 + private static let swatchSize: CGFloat = 9 + private static let panelSpacing: CGFloat = 6 + private static let labelOpacity: Double = 0.75 + + // MARK: - Properties + + private let shoeGaze: ShoeGaze + + // MARK: - Init + + /// - Parameter shoeGaze: The session whose ``ShoeGaze/scopeTap`` is visualised. + public init(shoeGaze: ShoeGaze) { + self.shoeGaze = shoeGaze + } + + // MARK: - Body + + public var body: some View { + VStack(alignment: .leading, spacing: ShoeGazeScopeView.panelSpacing) { + if let capture: ScopeCapture = shoeGaze.scopeTap { + legend(for: capture) + LyrebirdScopeView(capture: capture) + .frame(height: ShoeGazeScopeView.scopeHeight) + .id(ObjectIdentifier(capture)) + } else { + Text("Scope unavailable") + .font(.caption) + .foregroundStyle(Color.white.opacity(ShoeGazeScopeView.labelOpacity)) + } + } + } + + // MARK: - Legend + + /// A horizontal legend mapping each lane colour to its bus label. + private func legend(for capture: ScopeCapture) -> some View { + HStack(spacing: ShoeGazeScopeView.legendSpacing) { + ForEach(Array(capture.buses.enumerated()), id: \.offset) { index, bus in + HStack(spacing: 4) { + Circle() + .fill(ShoeGazeScopeView.laneColors[index % ShoeGazeScopeView.laneColors.count]) + .frame( + width: ShoeGazeScopeView.swatchSize, + height: ShoeGazeScopeView.swatchSize + ) + Text(shoeGaze.scopeLaneLabel(forBus: bus)) + .font(.caption2) + .foregroundStyle(Color.white.opacity(ShoeGazeScopeView.labelOpacity)) + } + } + } + } +} diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeView.swift index 5824303..eed07c4 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeView.swift @@ -112,6 +112,9 @@ public struct ShoeGazeView: View { Divider() .overlay(Color.white.opacity(ShoeGazeView.dividerOpacity)) boardList + Divider() + .overlay(Color.white.opacity(ShoeGazeView.dividerOpacity)) + ShoeGazeScopeView(shoeGaze: shoeGaze) Divider() .overlay(Color.white.opacity(ShoeGazeView.dividerOpacity)) LyrebirdStatusView(engine: shoeGaze.engine) From 46e075fb8ce3ad5e3d677f55ae4fe0139e32477f Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Tue, 23 Jun 2026 09:36:35 -0700 Subject: [PATCH 3/3] Add live-input mic permission, audio-input entitlement, and engine-config review fixes Live input was silent on macOS because the apps ran under hardened runtime without the microphone entitlement, so AUHAL input received silent zeros and the OS never prompted. Fixes: - Add com.apple.security.device.audio-input entitlement to the macOS Builder and Demo apps (CODE_SIGN_ENTITLEMENTS wired in both targets). - Add MicrophonePermission helper (AVCaptureDevice.requestAccess) and gate live-input selection through it in the Builder view and Demo controller; deny falls back to the test loop with an explanatory alert. - Fix ShoeGazeDemo inputChannels 6 -> 1 (built-in mics are mono; 6 made CoreAudio deliver silence). Engine-config review fixes: - installScopeTap now requires the engine stopped (precondition) and reconfigureEngine reinstalls the tap on every exit path via defer, so engine.scopeTap never points at a stale channel layout. - EngineConfigView stops the engine on a post-start (iOS) sample-rate mismatch instead of running pitch-shifted, and surfaces non-mismatch start errors through the alert. - Remove redundant installScopeTap call in the demo controller (ShoeGaze.init already installs it). Co-Authored-By: Claude Opus 4.8 --- .../ShoeGazeBuilder.xcodeproj/project.pbxproj | 12 +++-- .../ShoeGazeBuilder.entitlements | 8 +++ Demo/ShoeGazeDemo.xcodeproj/project.pbxproj | 2 + Demo/ShoeGazeDemo/AppDelegate.swift | 2 +- Demo/ShoeGazeDemo/DemoRootView.swift | 12 +++++ Demo/ShoeGazeDemo/ShoeGazeDemo.entitlements | 8 +++ .../ShoeGazeDemo/ShoeGazeDemoController.swift | 24 ++++++++- .../Input/MicrophonePermission.swift | 52 +++++++++++++++++++ .../Presets/ShoeGaze+Engine.swift | 13 +++-- .../LyrebirdShoeGazeUI/EngineConfigView.swift | 16 ++++-- .../ShoeGazeBuilderView.swift | 25 +++++++++ 11 files changed, 160 insertions(+), 14 deletions(-) create mode 100644 Demo/ShoeGazeBuilder/ShoeGazeBuilder.entitlements create mode 100644 Demo/ShoeGazeDemo/ShoeGazeDemo.entitlements create mode 100644 Sources/LyrebirdShoeGaze/Input/MicrophonePermission.swift diff --git a/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj b/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj index 8317f7b..5c5f231 100644 --- a/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj +++ b/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj @@ -7,12 +7,12 @@ objects = { /* Begin PBXBuildFile section */ - C3B1000000000000000000C /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B100000000000000000007 /* main.swift */; }; - C3B1000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B100000000000000000008 /* AppDelegate.swift */; }; C3B100000000000000000020 /* LyrebirdShoeGaze in Frameworks */ = {isa = PBXBuildFile; productRef = C3B10000000000000000001E /* LyrebirdShoeGaze */; }; C3B100000000000000000021 /* LyrebirdShoeGazeUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3B10000000000000000001F /* LyrebirdShoeGazeUI */; }; C3B100000000000000000022 /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = C3B100000000000000000023 /* Lyrebird */; }; C3B100000000000000000024 /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3B100000000000000000025 /* LyrebirdUI */; }; + C3B1000000000000000000C /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B100000000000000000007 /* main.swift */; }; + C3B1000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B100000000000000000008 /* AppDelegate.swift */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ @@ -152,14 +152,16 @@ C3B100000000000000000016 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { - CODE_SIGN_STYLE = Automatic; CODE_SIGNING_REQUIRED = NO; + CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilder/ShoeGazeBuilder.entitlements; + CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = dwarf; DEVELOPMENT_TEAM = ""; ENABLE_HARDENED_RUNTIME = YES; INFOPLIST_FILE = ShoeGazeBuilder/Info.plist; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music"; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/../Frameworks", @@ -175,13 +177,15 @@ C3B100000000000000000017 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { - CODE_SIGN_STYLE = Automatic; CODE_SIGNING_REQUIRED = NO; + CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilder/ShoeGazeBuilder.entitlements; + CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = ""; ENABLE_HARDENED_RUNTIME = YES; INFOPLIST_FILE = ShoeGazeBuilder/Info.plist; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music"; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/../Frameworks", diff --git a/Demo/ShoeGazeBuilder/ShoeGazeBuilder.entitlements b/Demo/ShoeGazeBuilder/ShoeGazeBuilder.entitlements new file mode 100644 index 0000000..b572d9c --- /dev/null +++ b/Demo/ShoeGazeBuilder/ShoeGazeBuilder.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.device.audio-input + + + diff --git a/Demo/ShoeGazeDemo.xcodeproj/project.pbxproj b/Demo/ShoeGazeDemo.xcodeproj/project.pbxproj index 0e6a0f9..b5f254b 100644 --- a/Demo/ShoeGazeDemo.xcodeproj/project.pbxproj +++ b/Demo/ShoeGazeDemo.xcodeproj/project.pbxproj @@ -160,6 +160,7 @@ C3B000000000000000000016 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + CODE_SIGN_ENTITLEMENTS = ShoeGazeDemo/ShoeGazeDemo.entitlements; CODE_SIGN_STYLE = Automatic; CODE_SIGNING_REQUIRED = NO; COMBINE_HIDPI_IMAGES = YES; @@ -183,6 +184,7 @@ C3B000000000000000000017 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + CODE_SIGN_ENTITLEMENTS = ShoeGazeDemo/ShoeGazeDemo.entitlements; CODE_SIGN_STYLE = Automatic; CODE_SIGNING_REQUIRED = NO; COMBINE_HIDPI_IMAGES = YES; diff --git a/Demo/ShoeGazeDemo/AppDelegate.swift b/Demo/ShoeGazeDemo/AppDelegate.swift index aa96e26..ab08347 100644 --- a/Demo/ShoeGazeDemo/AppDelegate.swift +++ b/Demo/ShoeGazeDemo/AppDelegate.swift @@ -29,7 +29,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { private static let outputChannels: Int = 2 // Built-in mics are mono; default to one input channel so live input works out of the box // (CoreAudio can't satisfy more input channels than the device provides). Raise in the UI. - private static let inputChannels: Int = 6 + private static let inputChannels: Int = 1 private static let numAudioBuses: Int = 256 // MARK: - Window geometry constants diff --git a/Demo/ShoeGazeDemo/DemoRootView.swift b/Demo/ShoeGazeDemo/DemoRootView.swift index 765d86f..0a06f6e 100644 --- a/Demo/ShoeGazeDemo/DemoRootView.swift +++ b/Demo/ShoeGazeDemo/DemoRootView.swift @@ -95,6 +95,18 @@ struct DemoRootView: View { blue: DemoRootView.backgroundBlue ) ) + .alert( + "Microphone Access Needed", + isPresented: Binding( + get: { controller.microphoneAccessDenied }, + set: { controller.microphoneAccessDenied = $0 } + ) + ) { + Button("OK", role: .cancel) { } + } message: { + Text("Live input needs microphone access. Enable it in System Settings › Privacy & " + + "Security › Microphone, then select the input again.") + } } // MARK: - Toolbar diff --git a/Demo/ShoeGazeDemo/ShoeGazeDemo.entitlements b/Demo/ShoeGazeDemo/ShoeGazeDemo.entitlements new file mode 100644 index 0000000..b572d9c --- /dev/null +++ b/Demo/ShoeGazeDemo/ShoeGazeDemo.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.device.audio-input + + + diff --git a/Demo/ShoeGazeDemo/ShoeGazeDemoController.swift b/Demo/ShoeGazeDemo/ShoeGazeDemoController.swift index 01771ed..a3b38d0 100644 --- a/Demo/ShoeGazeDemo/ShoeGazeDemoController.swift +++ b/Demo/ShoeGazeDemo/ShoeGazeDemoController.swift @@ -127,9 +127,29 @@ final class ShoeGazeDemoController { /// Changes the input source policy and triggers a full rebuild. /// + /// Live input requires microphone authorisation first — without it macOS feeds the AUHAL input + /// silent zeros. The request is asynchronous, so `.liveInput` is applied only once the grant + /// resolves; a denial falls back to the test loop. + /// /// - Parameter source: `.testLoop` for the built-in test signal or `.liveInput(channel:)` /// for hardware microphone/instrument input on the given channel. func setInputSource(_ source: InputSource) { + guard case .liveInput = source else { + applyInputSource(source) + return + } + MicrophonePermission.request { [weak self] granted in + if !granted { self?.microphoneAccessDenied = true } + self?.applyInputSource(granted ? source : .testLoop) + } + } + + /// Set when live input is requested but microphone access is denied/restricted. The UI observes + /// this and presents an alert, then clears it. + var microphoneAccessDenied: Bool = false + + /// Applies an input-source change and triggers a full rebuild. + private func applyInputSource(_ source: InputSource) { inputSource = source rebuild() } @@ -182,8 +202,8 @@ final class ShoeGazeDemoController { inputSource = .testLoop } buildSession() - // Input buses follow the output buses, so the tapped indices change with the layout. - shoeGaze.installScopeTap() + // `buildSession()` creates a fresh `ShoeGaze`, whose `init` installs the scope tap for the + // new channel layout — no explicit `installScopeTap()` needed here. if wasRunning { start() } } diff --git a/Sources/LyrebirdShoeGaze/Input/MicrophonePermission.swift b/Sources/LyrebirdShoeGaze/Input/MicrophonePermission.swift new file mode 100644 index 0000000..24bfd62 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Input/MicrophonePermission.swift @@ -0,0 +1,52 @@ +// MicrophonePermission.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import AVFoundation + +/// Microphone (audio-input) authorisation helper for live-input mode. +/// +/// On macOS, an AUHAL input unit does **not** reliably trigger the system microphone prompt; +/// without an explicit `AVCaptureDevice.requestAccess(for: .audio)` the OS hands the app a stream +/// of silent zeros (no error). On iOS the record-permission prompt is likewise required before the +/// session delivers input. This helper centralises the cross-platform request so every app routes +/// live input through the same gate. +/// +/// The Info.plist must contain `NSMicrophoneUsageDescription`, or the request crashes at runtime. +public enum MicrophonePermission { + + /// Current authorisation state for audio capture. + public static var status: AVAuthorizationStatus { + AVCaptureDevice.authorizationStatus(for: .audio) + } + + /// `true` only when audio capture is already authorised. + public static var isAuthorized: Bool { + status == .authorized + } + + /// Ensures microphone access, prompting the user once if the state is undetermined. + /// + /// - `authorized` → `completion(true)` immediately (next run loop, on the main actor). + /// - `notDetermined` → shows the system prompt; `completion` fires with the user's choice. + /// - `denied` / `restricted` → `completion(false)` (the app must direct the user to Settings). + /// + /// `completion` is always delivered on the main actor so callers can drive UI / engine state + /// directly without further hops. + /// + /// - Parameter completion: Receives the final grant state. + public static func request(_ completion: @escaping @MainActor (Bool) -> Void) { + switch status { + case .authorized: + Task { @MainActor in completion(true) } + case .notDetermined: + AVCaptureDevice.requestAccess(for: .audio) { granted in + Task { @MainActor in completion(granted) } + } + default: + Task { @MainActor in completion(false) } + } + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Engine.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Engine.swift index 4a8e774..3088a8f 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Engine.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Engine.swift @@ -35,6 +35,11 @@ extension ShoeGaze { ) throws { guard !engine.isRunning else { throw SynthesisEngineConfigError.engineIsRunning } + // The tapped bus indices depend on the channel layout (input buses follow the output + // buses), so the scope tap must be rebuilt for the final configuration — on every exit + // path, including a thrown rebuild, so `engine.scopeTap` never points at a stale layout. + defer { installScopeTap() } + let snapshot: ShoeGazeState = captureState() // Tear the rig down BEFORE reconfiguring: changing the channel counts re-partitions the @@ -53,10 +58,6 @@ extension ShoeGaze { } try rebuildAllBoards(from: snapshot) - - // The tapped bus indices depend on the channel layout (input buses follow the output - // buses), so rebuild the scope tap for the new configuration. - installScopeTap() } /// Default samples-per-frame captured by the scope tap. @@ -73,6 +74,10 @@ extension ShoeGaze { /// /// - Parameter bufferSize: Samples per channel per display frame. Defaults to 2048. public func installScopeTap(bufferSize: Int = ShoeGaze.defaultScopeBufferSize) { + // `SynthesisEngine` caches its scope tap as `_rtScopeTap` at `start()`; assigning a new tap + // while running would silently diverge the RT thread's cached tap from `engine.scopeTap`. + precondition(!engine.isRunning, "installScopeTap must be called while the engine is stopped") + let numOut: Int = engine.numOutputChannels let numIn: Int = engine.numInputChannels diff --git a/Sources/LyrebirdShoeGazeUI/EngineConfigView.swift b/Sources/LyrebirdShoeGazeUI/EngineConfigView.swift index 8576a71..c40414a 100644 --- a/Sources/LyrebirdShoeGazeUI/EngineConfigView.swift +++ b/Sources/LyrebirdShoeGazeUI/EngineConfigView.swift @@ -48,6 +48,7 @@ public struct EngineConfigView: View { @State private var pendingOutputs: Int @State private var transportTick: Bool = false @State private var showAlert: Bool = false + @State private var alertTitle: String = "" @State private var alertText: String = "" // MARK: - Init @@ -107,7 +108,7 @@ public struct EngineConfigView: View { .buttonStyle(.borderedProminent) .tint(isRunning ? .red : .green) } - .alert("Sample Rate Mismatch", isPresented: $showAlert) { + .alert(alertTitle, isPresented: $showAlert) { Button("OK", role: .cancel) { } } message: { Text(alertText) @@ -140,9 +141,12 @@ public struct EngineConfigView: View { onConfigApplied() // config may have applied even if start failed (e.g. rate mismatch) return } - // Started OK. On iOS the session may have committed a different rate than requested. + // Started OK. On iOS the session may have committed a different rate than requested — and + // `setSampleRate` only stores the logical rate, so leaving the engine running would play + // pitch-/time-shifted audio. Stop it (mirroring the macOS thrown-mismatch path) and alert. if let hardware: Double = hardwareSampleRate(), abs(hardware - shoeGaze.engine.sampleRate) > EngineConfigView.rateEpsilon { + shoeGaze.engine.stop() presentMismatch(requested: shoeGaze.engine.sampleRate, hardware: hardware) } transportTick.toggle() @@ -163,10 +167,16 @@ public struct EngineConfigView: View { return } #endif - print("[EngineConfigView] engine start failed: \(error)") + // Any other failure (invalid value, board reconstruction, driver setup) still needs to be + // surfaced — otherwise Start appears to do nothing. + alertTitle = "Couldn’t Start Engine" + alertText = "The engine could not start with the chosen configuration: " + + "\(error.localizedDescription)" + showAlert = true } private func presentMismatch(requested: Double, hardware: Double) { + alertTitle = "Sample Rate Mismatch" alertText = "Requested \(Int(requested)) Hz, but the hardware is running at " + "\(Int(hardware)) Hz. Set the sample rate to \(Int(hardware)) Hz and start again." showAlert = true diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index 98b2d46..8f5100f 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -63,6 +63,9 @@ public struct ShoeGazeBuilderView: View { /// Bumped on transport/edit actions to force a re-read of `engine.isRunning`. @State private var transportTick: Bool = false + /// Shown when live input is selected but microphone access is denied/restricted. + @State private var showMicDeniedAlert: Bool = false + #if !os(macOS) /// iOS file-dialog presentation flags + the document to export. (macOS uses the File menu.) @State private var showImporter: Bool = false @@ -117,6 +120,12 @@ public struct ShoeGazeBuilderView: View { blue: ShoeGazeBuilderView.backgroundBlue ) ) + .alert("Microphone Access Needed", isPresented: $showMicDeniedAlert) { + Button("OK", role: .cancel) { } + } message: { + Text("Live input needs microphone access. Enable it in System Settings › Privacy & " + + "Security › Microphone, then select the input again.") + } #if !os(macOS) .fileImporter(isPresented: $showImporter, allowedContentTypes: [.json]) { result in handleImport(result) @@ -305,7 +314,23 @@ public struct ShoeGazeBuilderView: View { } /// Switches input source, stopping/restarting the engine around the graph rebuild. + /// + /// Live input requires microphone authorisation first — without it macOS feeds the AUHAL + /// input silent zeros. The request is asynchronous, so when the source is `.liveInput` the + /// actual switch is deferred until the grant resolves; a denial falls back to the test loop. private func switchInput(to source: InputSource) { + guard case .liveInput = source else { + applyInputSource(source) + return + } + MicrophonePermission.request { granted in + if !granted { showMicDeniedAlert = true } + applyInputSource(granted ? source : .testLoop) + } + } + + /// Applies an input-source change, stopping/restarting the engine around the graph rebuild. + private func applyInputSource(_ source: InputSource) { let wasRunning: Bool = shoeGaze.engine.isRunning if wasRunning { shoeGaze.engine.stop() } do {