Files
ShoeGaze/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift
T
josh 7dccf596f4 feat(rigs): persist chain routers + add Garcia two-board split rig
Add ChainRouter persistence so routed multi-board rigs survive save/load —
previously captureState/loadRig only handled plain boards, so any A/B router
rig was silently lost on save (a latent gap this fixes for user rigs too).

- New ChainRouterState (Codable): each router's two linear branches as
  [PedalState] plus splitter branch levels and merger output levels.
- ShoeGazeState gains an additive `routers` field decoded with
  decodeIfPresent (nil for old rigs) — no format-version bump; routerless
  rigs stay byte-identical (nil, not []).
- captureState snapshots routers; rebuildAllBoards reconstructs each via
  makeChainRouter/addTo{A,B}/finalize and restores the blend.

FactoryRig gains a session-scoped builder variant (FactoryRigBuild enum) so
a rig can create its own boards/routers; makeEntries branches on it.

Ships the Garcia OBEL Clean/Effects Split: an effects/lead board (octave,
envelope filter, overdrive, phaser, delay, amp) vs a clean direct board,
selectable via the router — showcasing the multi-board capability.

Tests: full router capture -> JSON -> load round-trip with structure and
branch-level assertions plus a render check, backward-compat (no routers
key when routerless), and the Garcia rig via the factory load+render suite.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-09 13:19:42 -07:00

481 lines
23 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// ShoeGaze+Preset.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
extension ShoeGaze {
// MARK: - Capture
/// Captures the current rig topology and parameter values as a `ShoeGazeState`.
///
/// Each board's label and pedal parameters are snapshotted in order. The engine
/// graph is not modified; this is a read-only operation.
///
/// - Returns: A `ShoeGazeState` reflecting the current rig.
public func captureState() -> ShoeGazeState {
let boardStates: [BoardState] = boards.map { $0.captureState() }
let routerStates: [ChainRouterState] = routers.map { router in
ChainRouterState(
boardA: router.boardA.pedals.map { $0.captureState() },
boardB: router.boardB.pedals.map { $0.captureState() },
branchA: router.splitter.branchAEnabled,
branchB: router.splitter.branchBEnabled,
mergerLevelA: router.merger?.levelA ?? 1.0,
mergerLevelB: router.merger?.levelB ?? 1.0
)
}
return ShoeGazeState(
boards: boardStates,
midiMap: midiMap,
bpm: clock.bpm,
tempoEnabled: tempoEnabled,
inputSource: inputSource,
numInputChannels: engine.numInputChannels,
numOutputChannels: engine.numOutputChannels,
// `nil` rather than `[]` when there are no routers, so a routerless rig's JSON is
// unchanged and byte-identical to one saved before router persistence existed.
routers: routerStates.isEmpty ? nil : routerStates
)
}
/// Captures the current rig as a named ``RigEntry`` suitable for the rig library.
///
/// Wraps ``captureState()`` with a name, a fresh `id`, and a `savedAt` timestamp. The engine
/// graph is not modified; this is a read-only operation.
///
/// - Parameters:
/// - name: Human-readable name for the entry (e.g. `"Ambient Wash"`).
/// - id: Stable identifier. Defaults to a newly generated `UUID()`; pass an existing entry's
/// `id` to overwrite that entry in place.
/// - Returns: A ``RigEntry`` reflecting the current rig.
public func captureEntry(
name: String,
id: UUID = UUID()
) -> RigEntry {
RigEntry(id: id, name: name, state: captureState())
}
// MARK: - Save / Load
/// Saves the current rig to a JSON file at `url`.
///
/// The file is pretty-printed for readability and human-editability. Existing
/// files at `url` are overwritten.
///
/// - Parameter url: Destination file URL. The directory must already exist.
/// - Throws: Any error from `JSONEncoder` or `Data.write(to:options:)`.
public func saveRig(to url: URL) throws {
try rigData().write(to: url, options: .atomic)
}
/// Encodes the current rig to pretty-printed JSON `Data`.
///
/// Same payload `saveRig(to:)` writes to disk; exposed for callers that need the bytes
/// directly (e.g. a SwiftUI `fileExporter` `FileDocument` on iOS).
///
/// - Returns: The encoded `ShoeGazeState` JSON.
/// - Throws: Any error from `JSONEncoder`.
public func rigData() throws -> Data {
let encoder: JSONEncoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
return try encoder.encode(captureState())
}
/// Loads a rig from in-memory JSON `Data` and rebuilds the engine graph.
///
/// Identical to ``loadRig(from:)`` but reads from `Data` rather than a file URL — convenient
/// for a SwiftUI `fileImporter` that has already read the document, or for tests.
///
/// - Important: Call with the engine **stopped**, as with ``loadRig(from:)``.
/// - Parameter data: JSON produced by ``rigData()`` / ``saveRig(to:)``.
/// - Throws: `JSONDecoder` errors, `PresetError.unsupportedVersion`, or any board-build error.
public func loadRig(from data: Data) throws {
let decoder: JSONDecoder = JSONDecoder()
let state: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data)
try loadRig(from: state)
}
/// Rebuilds the engine graph from an already-decoded ``ShoeGazeState``.
///
/// Shared core of the `Data` / `URL` loaders, and the entry point the rig library uses to
/// recall a stored ``RigEntry`` (`loadRig(from: entry.state)`) without re-encoding. Rejects a
/// snapshot whose `version` exceeds `presetFormatVersion`, tears down the current rig, then
/// rebuilds every board with the all-or-nothing semantics of ``rebuildAllBoards(from:)``.
///
/// - Important: Call with the engine **stopped**, as with ``loadRig(from:)``.
/// - Parameter state: The rig snapshot to restore.
/// - Throws: `PresetError.unsupportedVersion` for a too-new snapshot, or any board-build error.
public func loadRig(from state: ShoeGazeState) throws {
guard state.version <= presetFormatVersion else {
throw PresetError.unsupportedVersion(state.version)
}
// Note: `state.numInputChannels` / `numOutputChannels` are persisted with the rig (see
// `captureState`) but intentionally NOT auto-applied here. Forcing the engine's channel
// layout on every load would fight the global engine config and clobber the iOS
// enable-live-input flow (rebuild engine to 1 input, then load a rig saved with 0). Apply a
// rig's saved layout deliberately via `applyChannelLayout(from:)` / the config UI instead.
// Restore the saved input source before rebuilding, since board construction reads it. A
// saved live-input channel that no longer exists on this engine falls back to the test loop
// (same guard as reconfigureEngine), so the rebuild's addBoard() can't throw on a stale
// channel. Absent (older rig) → leave the current input source untouched.
if let savedInput: InputSource = state.inputSource {
if case .liveInput(let channel) = savedInput,
channel < 0 || channel >= engine.numInputChannels {
inputSource = .testLoop
} else {
inputSource = savedInput
}
}
teardown()
try rebuildAllBoards(from: state)
// Restore the rig's MIDI bindings after the boards exist, so a MIDIController re-reading the
// map resolves against the freshly rebuilt boards.
midiMap = state.midiMap
// Tempo restore is graph-independent, so it happens after the rebuild. Absent (older rig) →
// leave the current session tempo untouched.
if let savedBpm: Double = state.bpm {
clock.bpm = savedBpm
}
if let savedTempoEnabled: Bool = state.tempoEnabled {
setTempoEnabled(savedTempoEnabled)
}
// Bring restored tempo-synced parameters in line with the loaded tempo. `setTempoEnabled`
// already re-syncs when it runs and is enabled, but an older rig with no saved
// `tempoEnabled` skips that path — recompute unconditionally so synced values are correct.
if tempoEnabled {
applyTempoSyncToAllPedals()
}
}
/// Rebuilds every board from a snapshot with all-or-nothing semantics.
///
/// The caller is responsible for tearing down any existing rig first. On any failure while
/// reconstructing a board, the partially-built rig is torn down and the error rethrown, so
/// callers never observe a half-built rig — a board that fails on iteration N does not leave
/// boards `0..<N` stranded.
///
/// `internal` so `setInputSource(_:)` in `ShoeGaze+Edit.swift` shares the same atomic path.
///
/// - Parameter snapshot: The rig snapshot to reconstruct.
/// - Throws: `BusAllocatorError`, `EngineAddError`, or `ShoeGazeError` from board construction.
func rebuildAllBoards(from snapshot: ShoeGazeState) throws {
do {
for boardState: BoardState in snapshot.boards {
let board: PedalBoard = try addBoard()
board.id = boardState.id
board.label = boardState.label
try rebuildSegments(boardState.segments, into: board)
try finalizeBoard(board)
}
for routerState: ChainRouterState in snapshot.routers ?? [] {
try rebuildRouter(routerState)
}
} catch {
// Leave no partial rig behind: tear down whatever was built, then rethrow.
teardown()
throw error
}
}
/// Reconstructs one ``ChainRouter`` from a saved snapshot: creates the router, replays both linear
/// branches (skipping unknown pedal types), finalizes, then restores the splitter branch levels
/// and merger output levels so the saved A / B / blend selection is preserved.
///
/// - Parameter state: The router snapshot to reconstruct.
/// - Throws: `BusAllocatorError`, `EngineAddError`, or `ShoeGazeError` from router construction.
private func rebuildRouter(_ state: ChainRouterState) throws {
let router: ChainRouter = try makeChainRouter()
for pedalState: PedalState in state.boardA {
if let pedal: Pedal = makeAndApply(pedalState) {
try router.addToA(pedal)
}
}
for pedalState: PedalState in state.boardB {
if let pedal: Pedal = makeAndApply(pedalState) {
try router.addToB(pedal)
}
}
try router.finalize()
// Restore the blend after finalize: the splitter exists from init, the merger only after.
router.splitter.branchAEnabled = state.branchA
router.splitter.branchBEnabled = state.branchB
router.merger?.levelA = state.mergerLevelA
router.merger?.levelB = state.mergerLevelB
}
/// Loads a rig from a JSON preset file and rebuilds the engine graph.
///
/// This method:
/// 1. Calls `teardown()` to remove all current nodes and release all buses.
/// 2. For each `BoardState`, calls `addBoard()`, sets `board.label`, adds each
/// pedal (skipping unknown types without throwing), applies the saved parameter
/// values via `pedal.applyState(_:)`, and calls `finalizeBoard(_:)`.
///
/// - Important: Call this method with the engine **stopped** (before `engine.start()`
/// or after `engine.stop()`). The same async-removal caveat as `teardown()` applies:
/// the engine processes one more block after `remove` is enqueued. Unknown pedal
/// types in the preset are silently skipped — the board is still created and finalized
/// with however many pedals were successfully reconstructed.
///
/// - Parameter url: Source file URL pointing to a JSON preset written by `saveRig(to:)`.
/// - Throws: Any error from `Data(contentsOf:)`, `JSONDecoder`, `PedalBoard.init`,
/// `board.add(_:)`, or `finalizeBoard(_:)`. Also throws
/// `PresetError.unsupportedVersion` when the file's version exceeds
/// `presetFormatVersion`.
public func loadRig(from url: URL) throws {
try loadRig(from: try Data(contentsOf: url))
}
// MARK: - Segment reconstruction
/// Rebuilds a board's ordered segments — linear pedals plus parallel and stereo split
/// regions — replaying each via the corresponding `PedalBoard` API. Unknown pedal types
/// are skipped (logged) so presets with missing custom pedals degrade gracefully.
///
/// - Parameters:
/// - segments: The ordered segment snapshots to reconstruct.
/// - board: The board to populate (freshly created, before `finalizeBoard`).
/// - Throws: `BusAllocatorError.noFreeBus` or `EngineAddError` from any node insertion.
///
/// `internal` (not `private`) so the linear-edit and input-switch helpers in
/// `ShoeGaze+Edit.swift` can replay a captured topology onto a freshly created board.
func rebuildSegments(_ segments: [BoardSegmentState], into board: PedalBoard) throws {
for segment: BoardSegmentState in segments {
switch segment {
case .pedal(let state):
if let pedal: Pedal = makeAndApply(state) {
try board.add(pedal)
}
case .parallel(let parallelState):
let section: ParallelSection = try board.split()
try addPedals(parallelState.branchA, to: section.branchA)
try addPedals(parallelState.branchB, to: section.branchB)
try board.merge(section)
section.splitter.mode = parallelState.mode
case .stereoSplit(let stereoState):
let section: StereoSplitSection = try board.splitStereo()
try addPedals(stereoState.left, to: section.left)
try addPedals(stereoState.right, to: section.right)
try board.collectStereo(section)
section.route = stereoState.route
case .stereoUnzip(let unzipState):
let section: StereoSplitSection = try board.unzipStereo()
try addPedals(unzipState.left, to: section.left)
try addPedals(unzipState.right, to: section.right)
try board.collectStereo(section)
section.route = unzipState.route
case .mergeToMono:
try board.mergeToMono()
}
}
}
/// Adds each pedal snapshot to a branch chain, skipping unknown types.
private func addPedals(_ states: [PedalState], to chain: BranchChain) throws {
for state: PedalState in states {
if let pedal: Pedal = makeAndApply(state) {
try chain.add(pedal)
}
}
}
/// Instantiates a pedal for the snapshot's type and applies its parameters, or returns
/// `nil` (logged) for an unknown type.
private func makeAndApply(_ state: PedalState) -> Pedal? {
guard let pedal: Pedal = PedalRegistry.makePedal(type: state.type) else {
print("[ShoeGaze] preset: skipping unknown pedal type \(state.type)")
return nil
}
pedal.applyState(state)
return pedal
}
// MARK: - Per-board rebuild
/// Tears down a single board and recreates it from a saved `BoardState`, preserving
/// its position in `boards` so UI ordering remains stable.
///
/// ## Behaviour
///
/// 1. Finds `board` in `boards` by identity (`===`). If absent, the board is treated as
/// unmanaged: a fresh board is built, finalised, and returned without reordering.
/// 2. Calls `addBoard()` to allocate a new board and sets `newBoard.label = state.label`.
/// 3. Calls `rebuildSegments(_:into:)` to replay each ordered segment — linear pedals plus
/// parallel and stereo split regions (with their branch pedals and routing mode).
/// Unknown pedal types are logged and skipped so presets with missing custom pedals
/// degrade gracefully.
/// 4. Calls `finalizeBoard(_:)` to connect the output master.
/// 5. Only after the new board is fully wired does `removeBoard(_:)` tear down the old
/// board — so a failure during steps 2–4 leaves the original board intact.
/// 6. Moves the new board to `oldIndex` in `boards` so it occupies the same slot as the
/// removed board.
///
/// - Important: Call with the engine **stopped** (or accept one block of glitch on a
/// running engine). Both boards exist briefly while the new one is being built;
/// this requires two additional buses but is safe because the bus pool has headroom
/// and the documented precondition is engine-stopped. `removeBoard(_:)` enqueues
/// removal; the engine processes one more block before the node is dequeued.
/// Unknown pedal types are silently skipped.
///
/// - Parameters:
/// - board: The board to replace. Must have been returned by `addBoard()` on this instance.
/// - state: The `BoardState` snapshot to restore.
/// - Returns: The newly created `PedalBoard` at the same index as the replaced board.
/// - Throws:
/// - `BusAllocatorError.noFreeBus` if no mono audio bus is available during rebuild.
/// - `EngineAddError` if the engine rejects any node insertion.
@discardableResult
public func rebuildBoard(
_ board: PedalBoard,
from state: BoardState
) throws -> PedalBoard {
// Record the existing position before allocating the new board so the slot
// can be restored. May be nil when `board` is unmanaged (not in `boards`).
let oldIndex: Int? = boards.firstIndex(where: { $0 === board })
// MIDI bindings address pedals/boards by UUID (persisted in PedalState/BoardState and
// carried through capture → rebuild), so a rebuild needs no binding reconciliation — the
// pedal keeps its id, and its binding resolves to it regardless of chain position.
// Build the new board FIRST so that any failure leaves the old board intact.
let newBoard: PedalBoard = try addBoard()
do {
newBoard.id = state.id
newBoard.label = state.label
try rebuildSegments(state.segments, into: newBoard)
try finalizeBoard(newBoard)
} catch {
// New board is partial — clean it up while the old board is still intact.
removeBoard(newBoard)
throw error
}
// New board fully wired — now remove the old one and restore its position.
if let targetIndex: Int = oldIndex {
removeBoard(board)
// `addBoard()` always appends; move the new board back to the original slot.
// `moveBoard(_:to:)` locates by identity so the correct element is repositioned
// even if `removeBoard` shifted indices.
moveBoard(newBoard, to: targetIndex)
}
return newBoard
}
// MARK: - Lightweight recall
/// Applies parameter values from `state` to the current rig topology, rebuilding only the
/// boards where a graph-topology selector changed.
///
/// This is a lightweight "recall settings" path intended for topologically identical
/// rigs (same board count, same segment order, same pedal types). Boards, segments, and
/// pedals — including branch pedals inside parallel and stereo split regions — are matched
/// positionally, and split routing modes (`SplitMode` / `StereoRoute`) are restored too.
/// Any count or type mismatch at any level is silently ignored for that entry — no error
/// is thrown and remaining
/// entries continue to be processed.
///
/// Most parameters apply live with no graph change. The exception is a `rebuildsOnChange`
/// selector (e.g. a cabinet voice, which picks which convolver is instantiated): if such a
/// selector's value differs from the live rig, that board is rebuilt via `rebuildBoard(_:from:)`
/// so the new selection takes effect — which carries the same at-most-one-block glitch as any
/// rebuild on a running engine. Boards without such a selector stay fully live.
///
/// Use `loadRig(from:)` when you need a full topology rebuild.
///
/// - Parameter state: The `ShoeGazeState` whose parameter values should be applied.
public func applyState(_ state: ShoeGazeState) {
for (board, boardState) in zip(boards, state.boards) {
let topologyChanged: Bool = applySegmentParams(boardState.segments, to: board.orderedSegments)
// A `rebuildsOnChange` selector (e.g. a cabinet voice) picks which nodes exist in the
// graph, so a plain node write during recall is invisible until the board is rebuilt.
// Rebuild only the boards where such a selector actually changed value.
if topologyChanged {
do {
_ = try rebuildBoard(board, from: board.captureState())
} catch {
print("[ShoeGaze] board rebuild after recall failed: \(error)")
}
}
}
// A recall restores each pedal's tempo-sync state but not its derived values (no clock is
// consulted in `Pedal.applyState`), so recompute them against the rig's current tempo —
// mirroring the full `loadRig(from:)` path.
if tempoEnabled {
applyTempoSyncToAllPedals()
}
}
/// Positionally applies segment parameter snapshots to live board segments, including
/// branch pedals and split routing modes. Type or topology mismatches at any position are
/// skipped silently (lightweight recall is for topologically identical rigs).
/// - Returns: `true` if any pedal's `rebuildsOnChange` selector value changed, meaning the board
/// must be rebuilt for the new selection to take effect.
@discardableResult
private func applySegmentParams(
_ states: [BoardSegmentState],
to segments: [BoardSegment]
) -> Bool {
var topologyChanged: Bool = false
for (segment, segmentState) in zip(segments, states) {
switch (segment, segmentState) {
case let (.pedal(pedal), .pedal(pedalState)):
if pedal.displayName == pedalState.type {
let before: [Double] = pedal.rebuildTopologyValues
pedal.applyState(pedalState)
if pedal.rebuildTopologyValues != before { topologyChanged = true }
}
case let (.parallel(section), .parallel(parallelState)):
let a: Bool = applyBranchParams(parallelState.branchA, to: section.branchA.pedals)
let b: Bool = applyBranchParams(parallelState.branchB, to: section.branchB.pedals)
if a || b { topologyChanged = true }
section.splitter.mode = parallelState.mode
case let (.stereoSplit(section), .stereoSplit(stereoState)):
let l: Bool = applyBranchParams(stereoState.left, to: section.left.pedals)
let r: Bool = applyBranchParams(stereoState.right, to: section.right.pedals)
if l || r { topologyChanged = true }
section.route = stereoState.route
case let (.stereoUnzip(section), .stereoUnzip(unzipState)):
let l: Bool = applyBranchParams(unzipState.left, to: section.left.pedals)
let r: Bool = applyBranchParams(unzipState.right, to: section.right.pedals)
if l || r { topologyChanged = true }
section.route = unzipState.route
default:
// Topology mismatch at this position — skip.
continue
}
}
return topologyChanged
}
/// Positionally applies branch pedal snapshots to live branch pedals, matching by type.
///
/// - Returns: `true` if any branch pedal's `rebuildsOnChange` selector value changed.
@discardableResult
private func applyBranchParams(_ states: [PedalState], to pedals: [Pedal]) -> Bool {
var topologyChanged: Bool = false
for (pedal, pedalState) in zip(pedals, states) where pedal.displayName == pedalState.type {
let before: [Double] = pedal.rebuildTopologyValues
pedal.applyState(pedalState)
if pedal.rebuildTopologyValues != before { topologyChanged = true }
}
return topologyChanged
}
}