9a8e5461c0
Move the remaining synchronous main-thread I/O off the main actor: - RigLibraryStore now constructs instantly with a local placeholder and exposes an awaitable async start(): it resolves the iCloud-or-local location off-main (the blocking ubiquity lookup), loads entries off-main via the shared ioQueue (so a reload can't drop a just-saved rig), then sets isLoaded. reload() is async; iCloud metadata updates re-read via it. - Seeding moves into RigLibraryBootstrap.start(_:seedFrom:), which seeds a "Default" rig only AFTER the (possibly iCloud) library has loaded and is still empty — preventing a duplicate "Default" on every synced device on first launch. - Sidebar shows a Loading state until isLoaded; the builder restores the persisted current-rig highlight when isLoaded flips true (initialRigID param dropped). - Shells construct the store synchronously and start it asynchronously (macOS via Task in didFinishLaunching; iOS via .task). Codec + file helpers are nonisolated static so background work needs no actor hop. - Tests await store.start(). Full suite: 206 passing. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
221 lines
9.3 KiB
Swift
221 lines
9.3 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"
|
|
/// 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
|
|
|
|
/// 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()
|
|
}
|
|
|
|
/// 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: - 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 {
|
|
// 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)
|
|
}
|
|
|
|
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()
|
|
}
|
|
}
|