Files
ShoeGaze/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift
T
2026-06-21 12:25:18 -07:00

188 lines
8.4 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 { board in
let pedalStates: [PedalState] = board.pedals.map { $0.captureState() }
return BoardState(label: board.label, pedals: pedalStates)
}
return ShoeGazeState(boards: boardStates)
}
// 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 {
let encoder: JSONEncoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let data: Data = try encoder.encode(captureState())
try data.write(to: url, options: .atomic)
}
/// 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 {
let data: Data = try Data(contentsOf: url)
let decoder: JSONDecoder = JSONDecoder()
let state: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data)
guard state.version <= presetFormatVersion else {
throw PresetError.unsupportedVersion(state.version)
}
teardown()
for boardState: BoardState in state.boards {
let board: PedalBoard = try addBoard()
board.label = boardState.label
for pedalState: PedalState in boardState.pedals {
guard let pedal: Pedal = PedalRegistry.makePedal(type: pedalState.type) else {
// Unknown pedal type — skip without crashing.
continue
}
pedal.applyState(pedalState)
try board.add(pedal)
}
try finalizeBoard(board)
}
}
// 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. For each `PedalState` in `state.pedals`, calls `PedalRegistry.makePedal(type:)`;
/// unknown types are logged and skipped so presets with missing custom pedals degrade
/// gracefully. Known pedals have `applyState(_:)` called before `board.add(_:)`.
/// 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 })
// Build the new board FIRST so that any failure leaves the old board intact.
let newBoard: PedalBoard = try addBoard()
do {
newBoard.label = state.label
for pedalState: PedalState in state.pedals {
guard let pedal: Pedal = PedalRegistry.makePedal(type: pedalState.type) else {
// Unknown pedal type — log for diagnosability, then skip.
print("[ShoeGaze] rebuildBoard: skipping unknown pedal type \(pedalState.type)")
continue
}
pedal.applyState(pedalState)
try newBoard.add(pedal)
}
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 without
/// rebuilding the engine graph.
///
/// This is a lightweight "recall settings" path intended for topologically identical
/// rigs (same board count, same pedal count and types in the same order). Boards
/// and pedals are matched positionally; any count or type mismatch at the board or
/// pedal level is silently ignored for that entry — no error is thrown and remaining
/// entries continue to be processed.
///
/// 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) {
for (pedal, pedalState) in zip(board.pedals, boardState.pedals) {
guard pedal.displayName == pedalState.type else { continue }
pedal.applyState(pedalState)
}
}
}
}