Serialize split-region topology in presets

Replace the flat per-board pedal list with an ordered [BoardSegmentState]
(pedal | parallel | stereoSplit | mergeToMono) so parallel and stereo
split regions — branch pedal chains plus SplitMode/StereoRoute — round-trip
through saveRig/loadRig and rebuildBoard.

- PedalBoard.orderedSegments tracks chain structure (add/split/splitStereo/
  mergeToMono); captureState() walks it; rebuildSegments() replays it.
- BoardState backward-compatible: decodes legacy flat `pedals` arrays;
  computed `pedals` exposes the linear subset; throws on a file missing both
  keys. BoardSegmentState wire discriminators documented.
- applyState (lightweight recall) extended to branch pedals + routing modes.
- Unknown pedal types skipped on load, including inside branches.
- Tests: parallel / stereo / mergeToMono file round-trips, legacy decode,
  unknown-pedal-in-branch, branch-param recall. Suite 116/116; demo builds.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-21 17:12:46 -07:00
parent 211b9da438
commit 712f049f96
10 changed files with 571 additions and 56 deletions
@@ -0,0 +1,27 @@
// BoardSegment.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// One ordered element of a ``PedalBoard``'s signal chain, used to capture full topology
/// (including parallel and stereo split regions) in signal-flow order.
///
/// `PedalBoard` records these as pedals and split regions are added, so a board can be
/// serialized and rebuilt faithfully rather than as a flat pedal list. Branch pedals live
/// inside their section objects, not as separate segments.
enum BoardSegment {
/// A single linear pedal in the main chain.
case pedal(Pedal)
/// A parallel section (`split()` → two branches → `merge()`).
case parallel(ParallelSection)
/// A stereo split region (`splitStereo()` → two branches → `collectStereo()`).
case stereoSplit(StereoSplitSection)
/// A `mergeToMono()` collapse — narrows a stereo tail back to mono. Carries no state;
/// recorded so the width transition replays on rebuild.
case mergeToMono
}
+17 -1
View File
@@ -121,6 +121,10 @@ public final class PedalBoard {
/// All branch chains owned by the board (for teardown).
private var branchChains: [BranchChain] = []
/// Ordered signal-chain segments (pedals + split regions) in signal-flow order. Used to
/// capture full board topology for serialization. Maintained by `add`/`split`/`splitStereo`.
private(set) var orderedSegments: [BoardSegment] = []
// MARK: - Init
/// Creates a pedalboard that allocates its head bus and prepares for pedal insertion.
@@ -227,6 +231,7 @@ public final class PedalBoard {
}
pedals.append(pedal)
orderedSegments.append(.pedal(pedal))
}
/// Returns the right tail bus, enforcing the `width == 2 ⟺ outputBusRight != nil` invariant.
@@ -289,6 +294,7 @@ public final class PedalBoard {
try insertNode(merger, after: nil)
routingNodes.append(merger)
advanceTail(left: monoBus, right: nil, width: 1)
orderedSegments.append(.mergeToMono)
}
// MARK: - Stereo split
@@ -355,6 +361,7 @@ public final class PedalBoard {
dryTapBus: dryTapBus
)
stereoSplitSections.append(section)
orderedSegments.append(.stereoSplit(section))
return section
}
@@ -458,7 +465,14 @@ public final class PedalBoard {
branchChains.append(chainA)
branchChains.append(chainB)
return ParallelSection(splitter: splitter, branchA: chainA, branchB: chainB, sharedTail: tail)
let section: ParallelSection = ParallelSection(
splitter: splitter,
branchA: chainA,
branchB: chainB,
sharedTail: tail
)
orderedSegments.append(.parallel(section))
return section
}
/// Combines the two branches of a ``ParallelSection`` back into the main board chain.
@@ -547,6 +561,8 @@ public final class PedalBoard {
branchChains.removeAll()
lastNode = nil
orderedSegments.removeAll()
stereoSplitSections.removeAll()
// Step 4: Release board-owned buses (head bus and main-chain inter-node buses).
for bus: AudioBus in allocatedBuses {
@@ -0,0 +1,32 @@
// BoardSegmentState.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Serialisable snapshot of one ordered element of a board's signal chain.
///
/// A board's full topology is a `[BoardSegmentState]` in signal-flow order: a sequence of
/// linear pedals interleaved with parallel and stereo split regions. This is the unit that
/// makes split-region topology round-trip through presets, where the older flat
/// `[PedalState]` list could not.
///
/// `Codable` conformance is auto-synthesized for this associated-value enum.
///
/// > Important: The synthesized encoding uses the case names — `"pedal"`, `"parallel"`,
/// > `"stereoSplit"` — as the on-disk discriminators. Renaming a case is a wire-format break
/// > that would prevent older presets from decoding; rename only with a migration.
public enum BoardSegmentState: Codable, Equatable {
/// A single linear pedal. Wire discriminator: `"pedal"`.
case pedal(PedalState)
/// A parallel section (`split()`/`merge()`). Wire discriminator: `"parallel"`.
case parallel(ParallelSectionState)
/// A stereo split region (`splitStereo()`/`collectStereo()`). Wire discriminator: `"stereoSplit"`.
case stereoSplit(StereoSplitState)
/// A `mergeToMono()` collapse (no payload). Wire discriminator: `"mergeToMono"`.
case mergeToMono
}
@@ -4,20 +4,52 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Serialisable snapshot of one `PedalBoard`'s label and pedal chain.
/// Serialisable snapshot of one `PedalBoard`'s label and full signal-chain topology.
///
/// `label` is the board's display name. `pedals` contains one `PedalState` per
/// pedal in signal-flow order. Unknown pedal types in the array are skipped
/// silently during `ShoeGaze.loadRig(from:)`.
/// `label` is the board's display name. `segments` captures the chain in signal-flow order:
/// linear pedals interleaved with parallel and stereo split regions (each region carries its
/// branch pedal chains and routing mode). Unknown pedal types are skipped silently on load.
///
/// ## Backward compatibility
///
/// Presets written before topology capture stored a flat `pedals` array instead of `segments`.
/// Such files still decode: the legacy `pedals` array is wrapped as `.pedal` segments. New
/// files encode `segments` only. The computed ``pedals`` property exposes the linear pedal
/// subset (the whole chain for boards with no split regions) for callers that only need it.
public struct BoardState: Codable, Equatable {
/// The board's display label (e.g. `"Board 1"`).
public let label: String
/// Ordered list of pedal snapshots in signal-flow order.
public let pedals: [PedalState]
/// Ordered signal-chain segments (pedals + split regions) in signal-flow order.
public let segments: [BoardSegmentState]
/// Creates a board state snapshot.
/// The linear pedal subset of the chain — the `.pedal` segments only, in order. For a
/// board with no split regions this is the entire chain.
public var pedals: [PedalState] {
segments.compactMap { segment in
if case .pedal(let state) = segment { return state }
return nil
}
}
/// Creates a board state snapshot from an ordered segment list.
///
/// - Parameters:
/// - label: The board's display label.
/// - segments: Ordered signal-chain segments.
public init(
label: String,
segments: [BoardSegmentState]
) {
self.label = label
self.segments = segments
}
/// Creates a board state snapshot from a flat pedal list (no split regions).
///
/// Each pedal becomes a `.pedal` segment. Convenience for linear boards and the legacy
/// call shape.
///
/// - Parameters:
/// - label: The board's display label.
@@ -27,6 +59,42 @@ public struct BoardState: Codable, Equatable {
pedals: [PedalState]
) {
self.label = label
self.pedals = pedals
self.segments = pedals.map { BoardSegmentState.pedal($0) }
}
private enum CodingKeys: String, CodingKey {
case label
case segments
case pedals
}
/// Decodes a snapshot, tolerating legacy presets that stored a flat `pedals` array by
/// wrapping each entry as a `.pedal` segment.
public init(from decoder: any Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
self.label = try container.decode(String.self, forKey: .label)
if let decodedSegments: [BoardSegmentState] =
try container.decodeIfPresent([BoardSegmentState].self, forKey: .segments) {
self.segments = decodedSegments
} else if let legacyPedals: [PedalState] =
try container.decodeIfPresent([PedalState].self, forKey: .pedals) {
// Legacy file: a flat pedal list with no split regions.
self.segments = legacyPedals.map { BoardSegmentState.pedal($0) }
} else {
// Neither key present — a malformed file. Fail loudly rather than silently
// producing an empty board.
throw DecodingError.dataCorruptedError(
forKey: CodingKeys.segments,
in: container,
debugDescription: "BoardState requires either 'segments' or legacy 'pedals'."
)
}
}
/// Encodes the snapshot using the current `segments` representation.
public func encode(to encoder: any Encoder) throws {
var container: KeyedEncodingContainer<CodingKeys> = encoder.container(keyedBy: CodingKeys.self)
try container.encode(label, forKey: .label)
try container.encode(segments, forKey: .segments)
}
}
@@ -0,0 +1,38 @@
// ParallelSectionState.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Serialisable snapshot of a parallel section (`split()` → two branches → `merge()`).
///
/// Captures each branch's pedal chain in signal-flow order plus the splitter's current
/// routing `mode`. Reconstructed by `loadRig`/`rebuildBoard` via `board.split()`, adding the
/// branch pedals, `board.merge(_:)`, then restoring `mode`.
public struct ParallelSectionState: Codable, Equatable {
/// Branch A pedal snapshots in signal-flow order.
public let branchA: [PedalState]
/// Branch B pedal snapshots in signal-flow order.
public let branchB: [PedalState]
/// The splitter routing mode (`.a` / `.b` / `.both`).
public let mode: SplitMode
/// Creates a parallel section snapshot.
///
/// - Parameters:
/// - branchA: Branch A pedal snapshots in order.
/// - branchB: Branch B pedal snapshots in order.
/// - mode: The splitter routing mode.
public init(
branchA: [PedalState],
branchB: [PedalState],
mode: SplitMode
) {
self.branchA = branchA
self.branchB = branchB
self.mode = mode
}
}
@@ -6,14 +6,38 @@
extension PedalBoard {
/// Captures the current state of this board's label and pedal chain as a `BoardState`.
/// Captures the current state of this board's label and full signal-chain topology as a
/// `BoardState`.
///
/// Each pedal's `displayName`, knob values, and bypass flag are snapshotted in
/// signal-flow order. The engine graph is not modified; this is a read-only operation.
/// Walks the board's ordered segments, snapshotting each linear pedal and each split
/// region (parallel and stereo) in signal-flow order — including branch pedal chains and
/// the section's routing mode. The engine graph is not modified; this is read-only.
///
/// - Returns: A `BoardState` reflecting the board's current label and pedal parameters.
/// - Returns: A `BoardState` reflecting the board's current topology and parameters.
public func captureState() -> BoardState {
let pedalStates: [PedalState] = pedals.map { $0.captureState() }
return BoardState(label: label, pedals: pedalStates)
let segmentStates: [BoardSegmentState] = orderedSegments.map { segment in
switch segment {
case .pedal(let pedal):
return BoardSegmentState.pedal(pedal.captureState())
case .parallel(let section):
return BoardSegmentState.parallel(ParallelSectionState(
branchA: section.branchA.pedals.map { $0.captureState() },
branchB: section.branchB.pedals.map { $0.captureState() },
mode: section.splitter.mode
))
case .stereoSplit(let section):
return BoardSegmentState.stereoSplit(StereoSplitState(
left: section.left.pedals.map { $0.captureState() },
right: section.right.pedals.map { $0.captureState() },
route: section.route
))
case .mergeToMono:
return BoardSegmentState.mergeToMono
}
}
return BoardState(label: label, segments: segmentStates)
}
}
@@ -17,10 +17,7 @@ extension ShoeGaze {
///
/// - 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)
}
let boardStates: [BoardState] = boards.map { $0.captureState() }
return ShoeGazeState(boards: boardStates)
}
@@ -72,20 +69,69 @@ extension ShoeGaze {
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 rebuildSegments(boardState.segments, into: board)
try finalizeBoard(board)
}
}
// 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.
private 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 .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
@@ -96,9 +142,10 @@ extension ShoeGaze {
/// 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(_:)`.
/// 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.
@@ -132,17 +179,7 @@ extension ShoeGaze {
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 rebuildSegments(state.segments, into: newBoard)
try finalizeBoard(newBoard)
} catch {
// New board is partial — clean it up while the old board is still intact.
@@ -168,9 +205,11 @@ extension ShoeGaze {
/// 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
/// 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.
///
/// Use `loadRig(from:)` when you need a full topology rebuild.
@@ -178,10 +217,45 @@ extension ShoeGaze {
/// - 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)
applySegmentParams(boardState.segments, to: board.orderedSegments)
}
}
/// 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).
private func applySegmentParams(
_ states: [BoardSegmentState],
to segments: [BoardSegment]
) {
for (segment, segmentState) in zip(segments, states) {
switch (segment, segmentState) {
case let (.pedal(pedal), .pedal(pedalState)):
if pedal.displayName == pedalState.type {
pedal.applyState(pedalState)
}
case let (.parallel(section), .parallel(parallelState)):
applyBranchParams(parallelState.branchA, to: section.branchA.pedals)
applyBranchParams(parallelState.branchB, to: section.branchB.pedals)
section.splitter.mode = parallelState.mode
case let (.stereoSplit(section), .stereoSplit(stereoState)):
applyBranchParams(stereoState.left, to: section.left.pedals)
applyBranchParams(stereoState.right, to: section.right.pedals)
section.route = stereoState.route
default:
// Topology mismatch at this position — skip.
continue
}
}
}
/// Positionally applies branch pedal snapshots to live branch pedals, matching by type.
private func applyBranchParams(_ states: [PedalState], to pedals: [Pedal]) {
for (pedal, pedalState) in zip(pedals, states) where pedal.displayName == pedalState.type {
pedal.applyState(pedalState)
}
}
}
@@ -0,0 +1,39 @@
// StereoSplitState.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Serialisable snapshot of a stereo split region (`splitStereo()` → two branches →
/// `collectStereo()`).
///
/// Captures the left and right branch pedal chains in signal-flow order plus the active
/// ``StereoRoute``. Reconstructed by `loadRig`/`rebuildBoard` via `board.splitStereo()`,
/// adding the branch pedals, `board.collectStereo(_:)`, then restoring `route`.
public struct StereoSplitState: Codable, Equatable {
/// Left-branch pedal snapshots in signal-flow order (becomes the left channel).
public let left: [PedalState]
/// Right-branch pedal snapshots in signal-flow order (becomes the right channel).
public let right: [PedalState]
/// The output route mode (`.stereo` / `.leftOnly` / `.rightOnly` / `.bypass`).
public let route: StereoRoute
/// Creates a stereo split snapshot.
///
/// - Parameters:
/// - left: Left-branch pedal snapshots in order.
/// - right: Right-branch pedal snapshots in order.
/// - route: The output route mode.
public init(
left: [PedalState],
right: [PedalState],
route: StereoRoute
) {
self.left = left
self.right = right
self.route = route
}
}
@@ -87,6 +87,194 @@ struct PresetTests {
#expect(pedal is PingPongDelayPedal, "Ping-Pong should be registered")
}
// MARK: - Split-region topology round-trip
@Test func parallelTopologyRoundTripsThroughFile() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128)
defer { try? FileManager.default.removeItem(at: url) }
let preset: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: preset) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
try board.add(OverdrivePedal())
let section: ParallelSection = try board.split()
try section.branchA.add(DelayPedal())
try section.branchB.add(FuzzPedal())
try board.merge(section)
try board.add(ReverbPedal())
try sg.finalizeBoard(board)
// Non-default routing + branch param so the round-trip proves real capture.
section.splitter.mode = .a
if let delay: DelayPedal = section.branchA.pedals.first as? DelayPedal {
delay.time = 0.6
}
let before: ShoeGazeState = sg.captureState()
try sg.saveRig(to: preset)
try sg.loadRig(from: preset)
let after: ShoeGazeState = sg.captureState()
#expect(before == after, "Parallel topology should round-trip through a file")
let hasParallel: Bool = after.boards[0].segments.contains {
if case .parallel = $0 { return true } else { return false }
}
#expect(hasParallel, "Reconstructed board should contain a parallel segment")
}
@Test func stereoSplitTopologyRoundTripsThroughFile() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128)
defer { try? FileManager.default.removeItem(at: url) }
let preset: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: preset) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
try board.add(OverdrivePedal())
let section: StereoSplitSection = try board.splitStereo()
try section.left.add(DelayPedal())
try section.right.add(PingPongDelayPedal())
try board.collectStereo(section)
try sg.finalizeBoard(board)
section.route = .rightOnly
if let delay: DelayPedal = section.left.pedals.first as? DelayPedal {
delay.time = 0.45
}
let before: ShoeGazeState = sg.captureState()
try sg.saveRig(to: preset)
try sg.loadRig(from: preset)
let after: ShoeGazeState = sg.captureState()
#expect(before == after, "Stereo split topology should round-trip through a file")
#expect(sg.boards[0].width == 2, "Reconstructed board should be stereo")
let hasStereo: Bool = after.boards[0].segments.contains {
if case .stereoSplit = $0 { return true } else { return false }
}
#expect(hasStereo, "Reconstructed board should contain a stereo split segment")
// Route survived.
guard case .stereoSplit(let stereoState)? =
after.boards[0].segments.first(where: {
if case .stereoSplit = $0 { return true } else { return false }
}) else {
Issue.record("No stereo split segment after reload")
return
}
#expect(stereoState.route == .rightOnly, "Route should be restored")
}
@Test func mergeToMonoTopologyRoundTripsThroughFile() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128)
defer { try? FileManager.default.removeItem(at: url) }
let preset: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: preset) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
try board.add(OctaveUpSplitterPedal()) // widen → stereo
try board.mergeToMono() // collapse → mono
try board.add(ReverbPedal()) // mono pedal after merge
try sg.finalizeBoard(board)
#expect(board.width == 1, "Board should be mono after merge")
let before: ShoeGazeState = sg.captureState()
try sg.saveRig(to: preset)
try sg.loadRig(from: preset)
let after: ShoeGazeState = sg.captureState()
#expect(before == after, "Widen→merge→mono topology should round-trip")
#expect(sg.boards[0].width == 1, "Rebuilt board should be mono (merge replayed)")
let hasMerge: Bool = after.boards[0].segments.contains {
if case .mergeToMono = $0 { return true } else { return false }
}
#expect(hasMerge, "Reconstructed board should contain a mergeToMono segment")
}
@Test func legacyFlatPedalsPresetStillDecodes() throws {
// A board snapshot written before topology capture stored a flat `pedals` array and
// no `segments` key. It must still decode, wrapping each pedal as a `.pedal` segment.
let legacyJSON: String = """
{"label":"Legacy","pedals":[\
{"type":"Overdrive","knobValues":[0.5,1.0,1.0],"switchValues":[],"bypass":0.0},\
{"type":"Delay","knobValues":[0.25,1.0,0.35,1.0],"switchValues":[],"bypass":0.0}]}
"""
let decoded: BoardState = try JSONDecoder().decode(
BoardState.self,
from: Data(legacyJSON.utf8)
)
#expect(decoded.label == "Legacy")
#expect(decoded.segments.count == 2, "Legacy pedals should become two segments")
#expect(decoded.pedals.count == 2, "Linear pedal view should expose both")
#expect(decoded.pedals[0].type == "Overdrive")
#expect(decoded.pedals[1].type == "Delay")
}
@Test func unknownPedalInBranchIsSkippedOnLoad() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128)
defer { try? FileManager.default.removeItem(at: url) }
let preset: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: preset) }
// Parallel segment with an unknown pedal in branch A and a known one in branch B.
let parallel: ParallelSectionState = ParallelSectionState(
branchA: [PedalState(type: "GhostPedal", knobValues: [], bypass: 0.0)],
branchB: [PedalState(type: "Fuzz", knobValues: [20.0, 1.0, 1.0], bypass: 0.0)],
mode: .both
)
let boardState: BoardState = BoardState(label: "B", segments: [.parallel(parallel)])
let state: ShoeGazeState = ShoeGazeState(boards: [boardState])
try JSONEncoder().encode(state).write(to: preset)
let sg: ShoeGaze = ShoeGaze(engine: engine)
try sg.loadRig(from: preset)
let after: ShoeGazeState = sg.captureState()
guard case .parallel(let rebuilt)? = after.boards.first?.segments.first(where: {
if case .parallel = $0 { return true } else { return false }
}) else {
Issue.record("No parallel segment after load")
return
}
#expect(rebuilt.branchA.isEmpty, "Unknown branch-A pedal should be skipped")
#expect(rebuilt.branchB.count == 1, "Known branch-B pedal should rebuild")
#expect(rebuilt.branchB.first?.type == "Fuzz")
}
@Test func applyStateRecallsBranchParamsAndRoute() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
let section: StereoSplitSection = try board.splitStereo()
try section.left.add(DelayPedal())
try section.right.add(FuzzPedal())
try board.collectStereo(section)
try sg.finalizeBoard(board)
let defaultTime: Double = 0.25 // DelayPedal default
let baseline: ShoeGazeState = sg.captureState()
// Mutate a branch pedal param and the route, then recall the baseline.
guard let delay: DelayPedal = section.left.pedals.first as? DelayPedal else {
Issue.record("No DelayPedal in left branch")
return
}
delay.time = 0.9
section.route = .bypass
sg.applyState(baseline)
#expect(abs(delay.$time.value - defaultTime) < 1e-9, "Branch pedal param should be recalled")
#expect(section.route == .stereo, "Route should be recalled")
}
// MARK: - In-memory round-trip
@Test func captureStateRoundTripEquality() throws {
+16 -7
View File
@@ -183,15 +183,24 @@ exposed on `StereoSplitSection` so the route control can observe its `@Observabl
## Presets
A saved rig captures each board's *linear* `pedals` chain only (unchanged). Wideners and
stereo-native pedals added via `board.add(_:)` are in that chain, so they round-trip — the
mono → stereo width transition replays on load. `OctaveUpSplitterPedal` ("Octave Splitter") and
`PingPongDelayPedal` ("Ping-Pong") are registered in `PedalRegistry`. Split-region *topology*
(`splitStereo()` branches) is not serialized — the same limitation as parallel `split()`.
A saved rig captures each board's full topology as an ordered `[BoardSegmentState]` —
`PedalBoard.orderedSegments`, maintained by `add`/`split`/`splitStereo`/`mergeToMono`. A segment
is a linear pedal, a parallel section (branch chains + `SplitMode`), a stereo split region
(branch chains + `StereoRoute`), or a `mergeToMono` collapse. `captureState()` walks it;
`loadRig`/`rebuildBoard` replay each segment via the matching `PedalBoard` API, so split regions
and width transitions round-trip faithfully. `applyState` (lightweight recall) also walks
segments, restoring branch-pedal params and routing modes positionally.
`BoardState` decodes legacy presets (flat `pedals` array, no `segments`) by wrapping each pedal
as a `.pedal` segment; new files encode `segments` only. `BoardSegmentState` wire discriminators
are the case names — renames are a format break. Wideners and stereo-native pedals
(`OctaveUpSplitterPedal` "Octave Splitter", `PingPongDelayPedal` "Ping-Pong") are registered in
`PedalRegistry`. Unknown pedal types are skipped on load, including inside branches.
The macOS Demo app has a `.stereo` mode (`ShoeGazeDemoController.buildStereo()` +
`DemoRootView.stereoContent`): Overdrive → `splitStereo(Delay | Ping-Pong)` → `collectStereo`,
with the four route modes selectable live.
Deferred (follow-up): serializing split-region topology (would also need to cover parallel
sections for consistency); an iOS demo showcase (the iOS demo app has no mode switcher).
Deferred (follow-up): an iOS demo showcase (the iOS demo app has no mode switcher); rendering
the board's `orderedSegments` directly in a generic board view (today the UI composes pedal
rows and section views separately).