dc42db0c59
Replace the single hand-saved rig file with a managed library of named rigs persisted in app storage and synced across devices and both builder apps via a shared iCloud container (iCloud.net.realizedsound.ShoeGazeData), falling back to local storage when iCloud is unavailable. Core (LyrebirdShoeGaze/Presets): - RigEntry: named, timestamped ShoeGazeState (a whole multi-board rig). - RigArchive: portable multi-rig JSON bundle for backup/transfer; legacy single-rig files import as a one-rig archive. - RigLibraryStore (@MainActor @Observable): one JSON file per rig, with NSFileCoordinator writes and NSMetadataQuery live remote-change watching. - RigLibraryLocation: iCloud-or-local directory resolver (skips the slow ubiquity lookup when no iCloud account is signed in). - ShoeGaze.loadRig(from: ShoeGazeState) + captureEntry; shared filename sanitizer factored out of BoardVersionStore. UI (LyrebirdShoeGazeUI): - RigLibrarySidebarView: persistent left listing with new/save/save-as/ duplicate/rename/delete/erase-all and archive import/export. - RigNamePrompt; RigLibraryBootstrap one-call shell setup. - ShoeGazeBuilderView: sidebar wired in; selecting a rig replaces the session; File menu / sidebar do whole-library archive import/export. Shells/entitlements: both builder targets own+start the store and carry the iCloud Documents entitlement; NSUbiquitousContainers exposes the rigs in the Files app. (macOS pbxproj also carries a pre-existing 1.0->1.1.1 version bump.) Tests: RigEntry/RigArchive round-trip + RigLibraryStore CRUD/import/export (15 new; full suite 206 passing). Provisioning (manual, not done here): enable the iCloud container on both App IDs and select it in Signing & Capabilities for both targets. 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 }
|
|
|
|
/// The library entry to highlight as current on this launch (and after an engine rebuild),
|
|
/// resolved live from the persisted id so a mid-session selection survives a rebuild.
|
|
var initialRigID: UUID? {
|
|
guard let stored: String = UserDefaults.standard.string(
|
|
forKey: ShoeGazeBuilderView.currentRigDefaultsKey),
|
|
let id: UUID = UUID(uuidString: stored),
|
|
library.entries.contains(where: { $0.id == id }) else { return nil }
|
|
return id
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
|
|
// Bootstrap the rig library (iCloud-or-local), seeding it from the working rig on first run.
|
|
self.library = RigLibraryBootstrap.make(for: shoeGaze).store
|
|
}
|
|
|
|
/// Persists the current rig. Call when the app moves to the background.
|
|
func save() {
|
|
RigStore.save(shoeGaze)
|
|
}
|
|
|
|
// 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()
|
|
}
|
|
}
|