Files
ShoeGaze/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift
T
josh 6ad813601f Review fixes: reindex activeBoardIndex; safer live-input rebuild
- moveBoard/removeBoard now keep activeBoardIndex pointing at the soloed board
  (track by identity on move; shift down or clear on remove), so the Solo
  highlight no longer lights the wrong cell after reorder or delete.
- rebuildWithLiveInput snapshots the rig before any teardown and aborts if the
  snapshot fails, instead of tearing down then seeding a fallback (no silent
  rig loss). The engine-already-has-input early return now also persists the
  live-input selection, via a shared selectLiveInputAndPersist helper.
- Test: activeBoardIndex tracks reorder and removal.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 21:22:44 -07:00

198 lines
8.1 KiB
Swift

// ShoeGazeBuilderiOSAppModel.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import AVFoundation
import Observation
import LyrebirdSynth
import LyrebirdShoeGaze
/// 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: 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. 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 sample rate the audio session actually committed to (for the config mismatch warning).
var hardwareSampleRate: Double? { iosDriver.sessionSampleRate }
// MARK: - Init
init() {
ShoeGazeBuilderiOSAppModel.configureAudioSession()
let built: (engine: SynthesisEngine, driver: iOSAudioDriver, shoeGaze: ShoeGaze) =
ShoeGazeBuilderiOSAppModel.buildEngine(inputChannels: ShoeGazeBuilderiOSAppModel.inputChannels)
self.engine = built.engine
self.iosDriver = built.driver
self.shoeGaze = built.shoeGaze
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Board 1"
try shoeGaze.appendPedal(type: ShoeGazeBuilderiOSAppModel.seedPedalType, to: board)
} catch {
print("[ShoeGazeBuilderiOS] seed board failed: \(error)")
}
}
// 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)")
seedFallbackBoard()
}
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 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`.
func stop() {
engine.stop()
}
}