// 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 // 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() // The engine is built with the default layout; the autosaved rig's saved I/O (if any) is // applied by `RigStore.restore`, so an output change survives relaunch. 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 { // 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 autosaves so the rig (the source of truth for the input /// selection) records it for restore-on-relaunch. private func selectLiveInputAndPersist() { do { try shoeGaze.setInputSource(.liveInput(channel: 0)) save() } 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) { // Fresh launch (no autosaved rig): default to live In 0 rather than the test-loop arpeggio. // A restored rig keeps its own saved input selection. if shoeGaze.engine.numInputChannels > 0 { shoeGaze.inputSource = .liveInput(channel: 0) } 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() } }