From 705b4ed5347fa0a0e55bb24e5202a663ee0c3f88 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Tue, 23 Jun 2026 20:52:11 -0700 Subject: [PATCH] iOS live input via permission-gated engine rebuild Live input on iOS needs an input channel, but constructing the engine with one up-front makes iOS prompt for the microphone at the first Start even in test-loop mode. Instead the engine starts input-less (no prompt) and is rebuilt on demand: - ShoeGazeBuilderView gains an optional onEnableLiveInput hook. When the user picks live input but the engine has no input channel, the picker offers a "Live Input" option that calls the hook; the input binding routes there too. On macOS (engine already has an input channel) the hook is nil and live input is selected directly. - The iOS app model implements the hook: request mic access, then on grant snapshot the rig (rigData), stop + teardown the engine, rebuild it with one input channel, restore the rig (loadRig), and select live input. The new ShoeGaze is published so the @Observable host view re-binds. - Input persistence restores live on relaunch: a saved live choice with the mic already authorised triggers the same rebuild silently (no prompt). Test: a rig captured on a 0-input engine restores onto a freshly built 1-input engine and live input is then selectable. Co-Authored-By: Claude Opus 4.8 --- .../ShoeGazeBuilderiOSApp.swift | 3 +- .../ShoeGazeBuilderiOSAppModel.swift | 150 ++++++++++++++---- .../ShoeGazeBuilderView.swift | 45 +++++- .../ShoeGazeMultiBoardTests.swift | 47 ++++++ 4 files changed, 208 insertions(+), 37 deletions(-) diff --git a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift index 3179b41..2e2ebb4 100644 --- a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift +++ b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift @@ -25,7 +25,8 @@ struct ShoeGazeBuilderiOSApp: App { NavigationStack { ShoeGazeBuilderView( shoeGaze: model.shoeGaze, - hardwareSampleRate: { model.hardwareSampleRate } + hardwareSampleRate: { model.hardwareSampleRate }, + onEnableLiveInput: { model.enableLiveInput() } ) .navigationTitle("ShoeGaze Builder") .navigationBarTitleDisplayMode(.inline) diff --git a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift index 6cb4ecb..129ba3c 100644 --- a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift +++ b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift @@ -32,13 +32,20 @@ final class ShoeGazeBuilderiOSAppModel { private static let numAudioBuses: Int = 256 private static let seedPedalType: String = "Overdrive" + /// UserDefaults key persisting the input selection. Must match the key written by the + /// builder view (`ShoeGazeBuilderView.inputSelectionDefaultsKey`). + private static let inputSelectionDefaultsKey: String = "ShoeGaze.inputSelection" + /// Persisted value meaning "live input, channel 0". + private static let liveInputChannelZeroTag: Int = 0 + // MARK: - Owned objects - /// The active ShoeGaze builder session. + /// The active ShoeGaze builder session. Swapped out when live input is enabled (the engine + /// is rebuilt with an input channel); the `@Observable` change re-binds the hosting view. private(set) var shoeGaze: ShoeGaze - private let engine: SynthesisEngine - private let iosDriver: iOSAudioDriver + private var engine: SynthesisEngine + private var iosDriver: iOSAudioDriver /// The sample rate the audio session actually committed to (for the config mismatch warning). var hardwareSampleRate: Double? { iosDriver.sessionSampleRate } @@ -46,31 +53,12 @@ final class ShoeGazeBuilderiOSAppModel { // MARK: - Init init() { - let session: AVAudioSession = AVAudioSession.sharedInstance() - do { - try session.setCategory(.playAndRecord, - mode: .default, - options: [.defaultToSpeaker, .allowBluetoothHFP]) - try session.setActive(true) - } catch { - // Surface the failure: the engine is built from `session.sampleRate` below, which may - // report a stale/default rate if activation failed. - print("[ShoeGazeBuilderiOS] AVAudioSession setup failed: \(error)") - } - 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: driver - ) - self.iosDriver = driver - self.engine = eng - self.shoeGaze = ShoeGaze(engine: eng) + ShoeGazeBuilderiOSAppModel.configureAudioSession() + let built: (engine: SynthesisEngine, driver: iOSAudioDriver, shoeGaze: ShoeGaze) = + ShoeGazeBuilderiOSAppModel.buildEngine(inputChannels: 0) + self.engine = built.engine + self.iosDriver = built.driver + self.shoeGaze = built.shoeGaze do { let board: PedalBoard = try shoeGaze.addBoard() @@ -81,6 +69,112 @@ final class ShoeGazeBuilderiOSAppModel { } } + // MARK: - Audio session / engine construction + + /// Activates the play-and-record audio session once. Idempotent; safe to call before each + /// engine build. Activating the session does not by itself prompt for microphone access — + /// the prompt only fires when an input-enabled engine first starts. + private static func configureAudioSession() { + let session: AVAudioSession = AVAudioSession.sharedInstance() + do { + try session.setCategory(.playAndRecord, + mode: .default, + options: [.defaultToSpeaker, .allowBluetoothHFP]) + try session.setActive(true) + } catch { + print("[ShoeGazeBuilderiOS] AVAudioSession setup failed: \(error)") + } + } + + /// Builds a fresh engine + driver + empty `ShoeGaze` with the given input-channel count. + private static func buildEngine( + inputChannels: Int + ) -> (engine: SynthesisEngine, driver: iOSAudioDriver, shoeGaze: ShoeGaze) { + let sampleRate: Double = AVAudioSession.sharedInstance().sampleRate + let driver: iOSAudioDriver = iOSAudioDriver() + let engine: SynthesisEngine = SynthesisEngine( + blockSize: ShoeGazeBuilderiOSAppModel.blockSize, + sampleRate: sampleRate, + numOutputChannels: ShoeGazeBuilderiOSAppModel.outputChannels, + numInputChannels: inputChannels, + numAudioBuses: ShoeGazeBuilderiOSAppModel.numAudioBuses, + driver: driver + ) + return (engine, driver, ShoeGaze(engine: engine)) + } + + // MARK: - Live input + + /// Enables live input on iOS: requests microphone access, then (on grant) rebuilds the + /// engine with one input channel — preserving the current rig — and selects live input. + /// + /// The rebuild is required because the input-channel count is fixed at engine construction, + /// and constructing with an input channel up-front would make iOS prompt for the microphone + /// at the first Start even in test-loop mode. Gating the rebuild behind an explicit request + /// keeps the prompt where the user expects it. + func enableLiveInput() { + MicrophonePermission.request { [weak self] granted in + guard let self, granted else { return } + self.rebuildWithLiveInput() + } + } + + /// Snapshots the rig, rebuilds the engine with one input channel, restores the rig, and + /// selects live input on channel 0. No-op if the engine already has an input channel. + private func rebuildWithLiveInput() { + guard engine.numInputChannels == 0 else { + try? shoeGaze.setInputSource(.liveInput(channel: 0)) + return + } + + let wasRunning: Bool = engine.isRunning + let snapshot: Data? = try? shoeGaze.rigData() + + engine.stop() + shoeGaze.teardown() + + ShoeGazeBuilderiOSAppModel.configureAudioSession() + let rebuilt: (engine: SynthesisEngine, driver: iOSAudioDriver, shoeGaze: ShoeGaze) = + ShoeGazeBuilderiOSAppModel.buildEngine(inputChannels: 1) + self.engine = rebuilt.engine + self.iosDriver = rebuilt.driver + self.shoeGaze = rebuilt.shoeGaze + + if let snapshot { + do { + try shoeGaze.loadRig(from: snapshot) + } catch { + print("[ShoeGazeBuilderiOS] rig restore after rebuild failed: \(error)") + seedFallbackBoard() + } + } else { + seedFallbackBoard() + } + + do { + try shoeGaze.setInputSource(.liveInput(channel: 0)) + UserDefaults.standard.set( + ShoeGazeBuilderiOSAppModel.liveInputChannelZeroTag, + forKey: ShoeGazeBuilderiOSAppModel.inputSelectionDefaultsKey + ) + } catch { + print("[ShoeGazeBuilderiOS] selecting live input failed: \(error)") + } + + if wasRunning { try? engine.start() } + } + + /// Seeds a single default board so the rig is never empty after a failed restore. + private func seedFallbackBoard() { + do { + let board: PedalBoard = try shoeGaze.addBoard() + board.label = "Board 1" + try shoeGaze.appendPedal(type: ShoeGazeBuilderiOSAppModel.seedPedalType, to: board) + } catch { + print("[ShoeGazeBuilderiOS] fallback seed board failed: \(error)") + } + } + // MARK: - Transport /// Stops the audio engine. Call from `.onDisappear`. diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index aae545c..17340fb 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -63,6 +63,12 @@ public struct ShoeGazeBuilderView: View { private let shoeGaze: ShoeGaze private let hardwareSampleRate: () -> Double? + /// Host hook to enable live input when the current engine has no input channel (iOS). + /// The host requests microphone access and rebuilds the engine with one input channel, + /// preserving the rig, then swaps in a new `ShoeGaze`. `nil` on platforms (macOS) whose + /// engine already exposes an input channel, where live input is selected directly. + private let onEnableLiveInput: (() -> Void)? + /// Index of the board currently being edited. @State private var selectedBoardIndex: Int = 0 @@ -99,12 +105,19 @@ public struct ShoeGazeBuilderView: View { /// 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`. + /// - onEnableLiveInput: Host hook invoked when the user requests live input but the engine + /// has no input channel (iOS). The host should request microphone access, rebuild the + /// engine with one input channel (preserving the rig), and select live input. Defaults to + /// `nil` — on macOS the engine already has an input channel, so live input is selected + /// directly without a rebuild. public init( shoeGaze: ShoeGaze, - hardwareSampleRate: @escaping () -> Double? = { nil } + hardwareSampleRate: @escaping () -> Double? = { nil }, + onEnableLiveInput: (() -> Void)? = nil ) { self.shoeGaze = shoeGaze self.hardwareSampleRate = hardwareSampleRate + self.onEnableLiveInput = onEnableLiveInput } // MARK: - Body @@ -220,8 +233,14 @@ public struct ShoeGazeBuilderView: View { .foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.labelOpacity)) Picker("Input", selection: inputBinding) { Text("Test Loop").tag(ShoeGazeBuilderView.testLoopTag) - ForEach(Array(0.. 0 { + ForEach(Array(0..= 0, stored < shoeGaze.engine.numInputChannels { switchInput(to: .liveInput(channel: stored)) + } else if stored >= 0, shoeGaze.engine.numInputChannels == 0, + MicrophonePermission.isAuthorized, let onEnableLiveInput { + // iOS: a live choice was saved and the mic is already authorised — rebuild the + // engine with an input channel silently (no prompt, since access is granted). + onEnableLiveInput() } - // A test-loop choice (or an out-of-range channel) leaves the default test loop. + // A test-loop choice (or live with no host hook / no permission) leaves the test loop. } else if MicrophonePermission.isAuthorized, shoeGaze.engine.numInputChannels > 0 { // First launch with no saved choice but mic already granted → default to live input. switchInput(to: .liveInput(channel: 0)) diff --git a/Tests/LyrebirdShoeGazeTests/ShoeGazeMultiBoardTests.swift b/Tests/LyrebirdShoeGazeTests/ShoeGazeMultiBoardTests.swift index 9e92fca..22bd9e6 100644 --- a/Tests/LyrebirdShoeGazeTests/ShoeGazeMultiBoardTests.swift +++ b/Tests/LyrebirdShoeGazeTests/ShoeGazeMultiBoardTests.swift @@ -39,6 +39,53 @@ struct ShoeGazeMultiBoardTests { #expect(shoeGaze.boards.count == 2) } + @Test func rigSnapshotRestoresAcrossEnginesWithInputChannel() throws { + // Backs the iOS "enable live input" rebuild: a rig captured on a 0-input engine must + // restore onto a freshly built 1-input engine, and live input must then be selectable. + let renderDuration: Double = 0.05 + + // Source engine: no input channels (the iOS default before live input is enabled). + let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine( + duration: renderDuration, + numInputChannels: 0, + numAudioBuses: 64 + ) + defer { try? FileManager.default.removeItem(at: urlA) } + + let shoeGazeA: ShoeGaze = ShoeGaze(engine: engineA) + let board1: PedalBoard = try shoeGazeA.addBoard() + board1.label = "Lead" + try shoeGazeA.appendPedal(type: "Overdrive", to: board1) + try shoeGazeA.finalizeBoard(board1) + let board2: PedalBoard = try shoeGazeA.addBoard() + board2.label = "Clean" + try shoeGazeA.appendPedal(type: "Graphic EQ", to: board2) + try shoeGazeA.finalizeBoard(board2) + + let snapshot: Data = try shoeGazeA.rigData() + + // Destination engine: one input channel (the rebuilt engine for live input). + let (engineB, urlB): (SynthesisEngine, URL) = makeNRTEngine( + duration: renderDuration, + numInputChannels: 1, + numAudioBuses: 64 + ) + defer { try? FileManager.default.removeItem(at: urlB) } + + let shoeGazeB: ShoeGaze = ShoeGaze(engine: engineB) + try shoeGazeB.loadRig(from: snapshot) + + // The rig round-trips: same board count and labels. + #expect(shoeGazeB.boards.count == 2) + #expect(shoeGazeB.boards.first?.label == "Lead") + #expect(shoeGazeB.boards.last?.label == "Clean") + + // Live input is now selectable on the rebuilt engine. + #expect(throws: Never.self) { + try shoeGazeB.setInputSource(.liveInput(channel: 0)) + } + } + @Test func soloBlendAndAllControlBoardAudibility() throws { let renderDuration: Double = 0.05 let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(