Files
ShoeGaze/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift
T
josh 5987ec7b78 Add input mute + persist engine I/O counts
Input mute: a hard gate on the signal feeding every board (guitar / mic),
distinct from the rig-output mute. Each board input writer (TestLoopTap /
HardwareInputPassThrough) gains a lagged @UIParam mute gain; ShoeGaze holds
inputMuted (default true), drives every input node, and brings newly-added
boards up at the current state. A deliberate user Start re-asserts the mute so
a fresh engine is silent until the player un-mutes — cutting accidental noise.
Toggle sits beside the Start/Stop transport and is MIDI mappable
(MIDIMap.Action.inputMute). First launch now defaults to live In 0 instead of
the test-loop arpeggio.

I/O persistence: the engine's input/output channel counts now persist to
UserDefaults (written by EngineConfigView, restored by the app targets at
engine construction), so a multi-channel setup survives relaunch and a saved
live-input channel stays valid — fixing the input selection reverting to the
test loop after a restart.

Tests: InputMuteTests (default-muted, node driving, per-board adoption, live
path) + a MIDI PC input-mute latch test. StereoRouting render tests un-mute
before rendering. 460 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-11 15:17:51 -07:00

266 lines
12 KiB
Swift

// ShoeGazeBuilderiOSAppModel.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import AVFoundation
import Observation
import LyrebirdSynth
import LyrebirdShoeGaze
import LyrebirdShoeGazeUI
/// Observable model owning the `SynthesisEngine` and `ShoeGaze` session for the iOS builder.
///
/// `AVAudioSession` is activated at init so the hardware sample rate is known before the engine
/// is constructed (iOS devices typically lock to 48 000 Hz). The session is seeded with one board
/// holding a single pedal so the builder opens with an audible starting point; the user adds /
/// removes / reorders pedals from the palette. Input defaults to `.testLoop`, so no microphone
/// permission is required to start.
@Observable
@MainActor
final class ShoeGazeBuilderiOSAppModel {
// MARK: - Engine configuration constants
private static let blockSize: Int = 512
private static let outputChannels: Int = 2
// Default to one input channel so live input is available immediately. The trade-off is
// that the iOS driver runs a `.playAndRecord` session with the RemoteIO input element
// enabled, so iOS prompts for microphone access at the first Start even while the input
// still defaults to `.testLoop`. (The permission-gated `enableLiveInput()` rebuild remains
// available for any future build that starts input-less.)
private static let inputChannels: Int = 1
private static let numAudioBuses: Int = 256
private static let seedPedalType: PedalType = .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"
/// UserDefaults key persisting the last-used output-channel count. Must match the key written by
/// the builder's engine-config UI (`EngineConfigView.outputChannelsDefaultsKey`).
private static let outputChannelsDefaultsKey: String = "ShoeGaze.outputChannels"
/// Persisted value meaning "live input, channel 0".
private static let liveInputChannelZeroTag: Int = 0
// MARK: - Owned objects
/// 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 var engine: SynthesisEngine
private var iosDriver: iOSAudioDriver
/// Foot-controller MIDI input. Owned here so it outlives the live-input engine rebuild; the
/// underlying Core MIDI client is engine-bound, so it is recreated against each new engine.
private(set) var midi: MIDIController
/// The shared rig library (iCloud-or-local). Independent of the engine, so it survives the
/// live-input engine rebuild.
private(set) var library: RigLibraryStore
/// The sample rate the audio session actually committed to (for the config mismatch warning).
var hardwareSampleRate: Double? { iosDriver.sessionSampleRate }
/// Resolves iCloud + loads the library off the main thread, then seeds it from the working rig
/// on first run. Call once from the app's `.task`. Safe to call again (no-op once non-empty).
func startLibrary() async {
await RigLibraryBootstrap.start(library, seedFrom: shoeGaze)
}
// MARK: - Init
init() {
ShoeGazeBuilderiOSAppModel.configureAudioSession()
let built: (engine: SynthesisEngine, driver: iOSAudioDriver, shoeGaze: ShoeGaze) =
ShoeGazeBuilderiOSAppModel.buildEngine(inputChannels: ShoeGazeBuilderiOSAppModel.inputChannels)
let shoeGaze: ShoeGaze = built.shoeGaze
self.engine = built.engine
self.iosDriver = built.driver
self.shoeGaze = shoeGaze
// Restore the autosaved working rig if there is one; otherwise seed a default board. Operate
// on the local `shoeGaze`, not `self.shoeGaze`: self may not be touched until every stored
// property (including `library`) is initialized.
if !RigStore.restore(into: shoeGaze) {
ShoeGazeBuilderiOSAppModel.seedFallbackBoard(into: shoeGaze)
}
// Construct the library instantly; it resolves iCloud + loads asynchronously via
// startLibrary() from the app's .task.
self.library = RigLibraryBootstrap.makeStore()
// Connect MIDI foot-controller input and begin listening for devices.
self.midi = MIDIController(engine: built.engine, shoeGaze: shoeGaze)
self.midi.start()
self.midi.onMapChanged = { [weak self] in self?.save() }
}
/// Persists the current rig. Call when the app moves to the background.
func save() {
RigStore.save(shoeGaze)
// Flush any in-flight background rig-library writes while we still have time in the
// background.
library.flushPendingWrites()
}
// MARK: - Document open
/// Imports a `.shoegaze` file opened from Files, AirDrop, or another app into the rig library.
/// Rig documents add their rigs (they appear in the sidebar, ready to load); board documents are
/// ignored here. Returns the number of rigs added.
@discardableResult
func importDocument(at url: URL) -> Int {
// A document opened from outside the sandbox is security-scoped; start access to read it.
let scoped: Bool = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
do {
let data: Data = try Data(contentsOf: url)
return try library.importArchive(from: data)
} catch {
print("[ShoeGazeBuilderiOS] open document failed: \(error)")
return 0
}
}
// 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()
// Restore the last-used output count so it survives relaunch (input stays on the
// permission-gated rebuild flow). Falls back to the default on first launch.
let defaults: UserDefaults = UserDefaults.standard
let maximumChannels: Int = 8
let restoredOutputs: Int = defaults.object(forKey: outputChannelsDefaultsKey) != nil
? max(1, min(defaults.integer(forKey: outputChannelsDefaultsKey), maximumChannels))
: ShoeGazeBuilderiOSAppModel.outputChannels
let engine: SynthesisEngine = SynthesisEngine(
blockSize: ShoeGazeBuilderiOSAppModel.blockSize,
sampleRate: sampleRate,
numOutputChannels: restoredOutputs,
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 {
// Engine already has an input channel: just select live input, no rebuild.
selectLiveInputAndPersist()
return
}
let wasRunning: Bool = engine.isRunning
// Snapshot the rig BEFORE any teardown. If this fails, abort the rebuild rather than
// tear the engine down and lose the rig — the user stays on the current engine.
let snapshot: Data
do {
snapshot = try shoeGaze.rigData()
} catch {
print("[ShoeGazeBuilderiOS] rig snapshot failed; aborting live-input rebuild: \(error)")
return
}
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
do {
// Teardown already happened, so a restore failure can only recover by seeding.
try shoeGaze.loadRig(from: snapshot)
} catch {
print("[ShoeGazeBuilderiOS] rig restore after rebuild failed: \(error)")
ShoeGazeBuilderiOSAppModel.seedFallbackBoard(into: shoeGaze)
}
// The Core MIDI client is bound to the old engine — recreate it against the new one and
// point it at the rebuilt rig, preserving the "MIDI outlives the rebuild" contract.
midi.stop()
midi = MIDIController(engine: rebuilt.engine, shoeGaze: shoeGaze)
midi.start()
midi.onMapChanged = { [weak self] in self?.save() }
selectLiveInputAndPersist()
if wasRunning { try? engine.start() }
}
/// Selects live input on channel 0 and persists the choice for restore-on-relaunch.
private func selectLiveInputAndPersist() {
do {
try shoeGaze.setInputSource(.liveInput(channel: 0))
UserDefaults.standard.set(
ShoeGazeBuilderiOSAppModel.liveInputChannelZeroTag,
forKey: ShoeGazeBuilderiOSAppModel.inputSelectionDefaultsKey
)
} catch {
print("[ShoeGazeBuilderiOS] selecting live input failed: \(error)")
}
}
/// Seeds a single default board so the rig is never empty after a failed restore.
private static func seedFallbackBoard(into shoeGaze: ShoeGaze) {
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Board 1"
try shoeGaze.appendPedal(ShoeGazeBuilderiOSAppModel.seedPedalType, to: board)
} catch {
print("[ShoeGazeBuilderiOS] fallback seed board failed: \(error)")
}
}
// MARK: - Transport
/// Stops the audio engine. Call from `.onDisappear`.
func stop() {
engine.stop()
}
}