3 Commits

Author SHA1 Message Date
josh 52c676605f feat(postboard): shared post-board chain after the board mix
Add a dedicated linear stereo post-board chain that processes the summed
board mix once, after the board split, before the hardware output — for
global reverb, a bus limiter, a final EQ, and the like.

Routing: when a post-chain exists, every BoardOutputMaster writes a shared
stereo mix bus (parameterized output bus indices) instead of hardware; the
post-chain (PostChain + PostChainOutput) reads that mix, runs its pedals in
order, and copies the tail to the hardware outputs. Always stereo-headed
(dual-mono for a mono rig) so mono pedals auto-stereoize per channel.

The chain's head node is inserted at .tail(of: mainGroup), so it evaluates
after every board master regardless of board add order — no re-order on
board add, and no board dropped from the mix. buildPostChain tracks the
chain before wiring it so a mid-build throw stays reclaimable by teardown.

State: additive ShoeGazeState.postChain (nil-when-empty, decodeIfPresent,
byte-identical old-rig round-trip). Edit API (append/insert/remove/move)
mirrors the pre-board chain: capture-from-live, stop/teardown/rebuild. Undo
treats a post-topology change as a full rebuild via id-sequence compare.
UI: a hide-when-empty post-board strip below the boards, symmetric to the
pre-board strip, with palette routing and per-pedal remove through undo.

Bumps the iOS demo's Lyrebird pin to 2.3.0 (onEditingEnded).

Tests: PostBoardChainTests (render, closed-volume silences output,
post-chain-after-every-master ordering, board-add ordering, insert/move/
remove, save/load round-trip with knob, old-rig decode) + post-pedal undo.
855 tests pass. Reviewed (RT-safety + line sweep); the ordering bug both
reviewers caught is fixed at the root and covered by a deterministic test.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-26 00:22:39 -08:00
josh 10a6e122bf feat(midi): MIDI-mappable primary transport footswitch (Capture / Freeze)
Expose a pedal's primary transport footswitch — TunedVerb's Capture, FreezVerb's
Freeze — as a MIDI-mappable action, so a footswitch (Program Change) can trigger
it. Previously only per-pedal Bypass and the looper's transport were mappable.

- New `MIDITransportPedal` protocol (@MainActor): `midiTransportName` + a
  `toggleMIDITransport()` that presses the pedal's primary footswitch. TunedVerb
  (Capture) and FreezVerb (Freeze) conform.
- `MIDIMap.PedalActionKind.pedalPrimaryTransport`, dispatched by MIDIController to
  `toggleMIDITransport()`. Learn / persist / resolve-by-id ride the existing
  pedalAction path (same as the looper actions).
- The mapping sheet lists the action for any `MIDITransportPedal`
  ("Board 2 · TunedVerb · Capture"); the per-pedal control-mapping strip shows a
  badge for it. A future press-to-trigger pedal just conforms and appears.

Tests: conformance + a Program-Change round-trip toggling Capture on/off. Full
suite 846 green; both demos build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-25 20:11:07 -08:00
josh 9dfadb129d feat(preboard): shared pre-board chain feeding every board
Add a pre-board stage: one linear pedal chain that processes the input once,
before the board split, and feeds every board — for front-of-chain gates /
drive / EQ, and multi-board "voice spray" rigs (one source → N panned boards →
Blend).

Routing: a stable mono feed bus every board taps. `FeedPassThrough` copies the
input source — or, when a pre-chain exists, that chain's mono output — onto the
feed bus (`ensureFeed`/`buildFeed`/`tearDownFeed`). The pre-chain is modeled as
an unfinalized `PedalBoard` fed from the source; a stereo tail folds to mono
(board heads are mono). Empty pre-chain = passthrough, byte-for-byte
behavior-preserving. addBoard taps the feed bus; teardown releases it
remove-before-release.

State: additive `ShoeGazeState.preChain` (`decodeIfPresent` → nil for old rigs,
no format bump; `hasSameRigContent` includes it). `captureState` reads the LIVE
pre-pedals so knob tweaks are saved; `rebuildAllBoards` sets the pre-chain
before building boards.

Edit API: appendPrePedal / insertPrePedal / removePrePedal / movePrePedal —
each folds in live knob values, then a full ordering-safe rig rebuild
(`setPreBoardChain`, mirrors setInputSource; rolls back on failure). Undo: a
pre-chain topology change (compared by id sequence, so knob-only edits stay on
the surgical path) rebuilds from the snapshot, stopping/starting the engine.
`allPedals()` now includes the pre-chain so pre-pedal knob undo resolves.

UI: an inline pre-board strip above the boards — hidden to a "+ Pre" button when
empty; otherwise the pre-pedals (keyed by stable id) with a per-pedal remove and
a "feeds all boards" divider. Palette adds route to the pre-board via a flag
(reset on any dismissal). Add / remove go through the undo wrapper.

Known scope: a pre-board edit resets transient/looper state (full rebuild, like
input-switch — setup-time); chain-router branches read the input directly and
are not fed by the pre-board. Both documented.

Tests: PreBoardChainTests (feeds boards, closed pre-Volume silences every board,
remove restores direct feed, save/load incl. a knob tweak, prior pre-pedal's
knob survives adding another, old-rig decode) + a pre-board undo test. Full
suite 844 green; both demos build. External review + caveman sweep: one blocking
(live knob sync) fixed + regression-tested, all non-blocking addressed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-25 19:18:04 -08:00
22 changed files with 1381 additions and 36 deletions
@@ -15,8 +15,8 @@
"kind" : "remoteSourceControl", "kind" : "remoteSourceControl",
"location" : "https://realizedsound.mooo.com/josh/Lyrebird", "location" : "https://realizedsound.mooo.com/josh/Lyrebird",
"state" : { "state" : {
"revision" : "b6fdee8bfc7c44d31a0a8cfe6fbd53f352dfad54", "revision" : "9f244b19394f6352b0a1dcf532cf142b86e41c30",
"version" : "2.0.0" "version" : "2.3.0"
} }
}, },
{ {
@@ -80,6 +80,12 @@ final class BoardOutputMaster: SynthesizerBase {
/// bypass source so a bypassed board passes its untouched input straight through. /// bypass source so a bypassed board passes its untouched input straight through.
private let dryInputBusIndex: Int private let dryInputBusIndex: Int
/// Destination buses for the master's stereo output — hardware 0 / 1 by default. When a
/// post-board chain exists, the masters are pointed at a shared **mix bus** instead, and the
/// post-chain reads that mix and writes hardware. All boards share the same destination.
private let outputLeftBusIndex: Int
private let outputRightBusIndex: Int
// MARK: - Constants // MARK: - Constants
/// Lag time constant in seconds for the bypass crossfades — smooths engaged ↔ bypassed /// Lag time constant in seconds for the bypass crossfades — smooths engaged ↔ bypassed
@@ -99,10 +105,18 @@ final class BoardOutputMaster: SynthesizerBase {
/// - boardOutputBusRightIndex: Right board output bus index for a stereo (width-2) board, /// - boardOutputBusRightIndex: Right board output bus index for a stereo (width-2) board,
/// or `nil` for a mono board (the signal is panned to centre instead). /// or `nil` for a mono board (the signal is panned to centre instead).
/// - dryInputBusIndex: The board's head-bus index, read as the dry bypass source. /// - dryInputBusIndex: The board's head-bus index, read as the dry bypass source.
init(boardOutputBusIndex: Int, boardOutputBusRightIndex: Int? = nil, dryInputBusIndex: Int) { init(
boardOutputBusIndex: Int,
boardOutputBusRightIndex: Int? = nil,
dryInputBusIndex: Int,
outputLeftBusIndex: Int = 0,
outputRightBusIndex: Int = 1
) {
self.boardOutputBusIndex = boardOutputBusIndex self.boardOutputBusIndex = boardOutputBusIndex
self.boardOutputBusRightIndex = boardOutputBusRightIndex self.boardOutputBusRightIndex = boardOutputBusRightIndex
self.dryInputBusIndex = dryInputBusIndex self.dryInputBusIndex = dryInputBusIndex
self.outputLeftBusIndex = outputLeftBusIndex
self.outputRightBusIndex = outputRightBusIndex
super.init() super.init()
} }
@@ -131,15 +145,15 @@ final class BoardOutputMaster: SynthesizerBase {
let switchedRight: any ValidGeneratorInput = applyBypass(wet: boardOutRight, dry: dry) let switchedRight: any ValidGeneratorInput = applyBypass(wet: boardOutRight, dry: dry)
let gainedRight: any ValidGeneratorInput = let gainedRight: any ValidGeneratorInput =
((switchedRight * smoothedSelect) * $masterGain) * rigOutputGain ((switchedRight * smoothedSelect) * $masterGain) * rigOutputGain
output(bus: 0, source: gainedLeft) output(bus: outputLeftBusIndex, source: gainedLeft)
output(bus: 1, source: gainedRight) output(bus: outputRightBusIndex, source: gainedRight)
} else { } else {
// Mono board: write the mono signal to both hardware buses at unity (0 dB). Using an // Mono board: write the mono signal to both hardware buses at unity (0 dB). Using an
// equal-power `Pan2` to centre would drop each channel by 3 dB (×0.707) — power-correct // equal-power `Pan2` to centre would drop each channel by 3 dB (×0.707) — power-correct
// for a true pan, but a mono guitar rig should come out at the same level it went in, so // for a true pan, but a mono guitar rig should come out at the same level it went in, so
// the signal is copied to left and right directly instead. // the signal is copied to left and right directly instead.
output(bus: 0, source: gainedLeft) output(bus: outputLeftBusIndex, source: gainedLeft)
output(bus: 1, source: gainedLeft) output(bus: outputRightBusIndex, source: gainedLeft)
} }
} }
@@ -0,0 +1,44 @@
// FeedPassThrough.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// Internal synthesizer that copies one mono bus straight to another — the writer of the shared
/// **feed bus** that every board taps.
///
/// The feed bus sits between the input source and the boards: a `FeedPassThrough` copies either the
/// raw input source (when there is no pre-board chain) or the pre-board chain's mono output onto a
/// single stable feed bus, and every board's input tap reads that feed bus. Keeping the feed bus
/// stable means a pre-board edit only rebuilds the pre-chain + this one node, never the boards.
///
/// Unlike ``TestLoopTap`` / ``HardwareInputPassThrough`` it carries no input-mute gain: the input
/// mute lives on the per-board taps (downstream of the feed), so a tail-producing pedal in the
/// pre-board chain is unaffected by it.
///
/// - Note: Must be removed from the engine before the feed bus it writes is released.
final class FeedPassThrough: SynthesizerBase {
/// Index of the bus to read from — the input source bus, or the pre-board chain's mono output.
private let inputBusIndex: Int
/// Index of the shared feed bus to write to.
private let outputBusIndex: Int
/// Creates a pass-through that copies `inputBusIndex` to `outputBusIndex`.
///
/// - Parameters:
/// - inputBusIndex: Bus to read from (input source, or pre-board chain output).
/// - outputBusIndex: The shared feed bus to write to.
init(inputBusIndex: Int, outputBusIndex: Int) {
self.inputBusIndex = inputBusIndex
self.outputBusIndex = outputBusIndex
super.init()
}
override func build() {
output(bus: outputBusIndex, source: input(bus: inputBusIndex))
}
}
@@ -417,6 +417,8 @@ public final class MIDIController {
(pedal as? LooperPedal)?.cycleSyncMode() (pedal as? LooperPedal)?.cycleSyncMode()
case .looperTrack(let index): case .looperTrack(let index):
(pedal as? LooperPedal)?.tapTrack(index) (pedal as? LooperPedal)?.tapTrack(index)
case .pedalPrimaryTransport:
(pedal as? MIDITransportPedal)?.toggleMIDITransport()
} }
} }
@@ -114,6 +114,10 @@ public struct MIDIMap: Codable, Equatable, Sendable {
/// Looper: taps track `index` (0 = A) — selects it, or mutes it if already selected and /// Looper: taps track `index` (0 = A) — selects it, or mutes it if already selected and
/// recorded (`LooperPedal.tapTrack(_:)`), matching the A/B/C/D dots. /// recorded (`LooperPedal.tapTrack(_:)`), matching the A/B/C/D dots.
case looperTrack(index: Int) case looperTrack(index: Int)
/// Toggles a pedal's primary transport footswitch — any ``MIDITransportPedal`` (e.g.
/// TunedVerb's Capture, FreezVerb's Freeze). Dispatched to `toggleMIDITransport()`.
case pedalPrimaryTransport
} }
// MARK: - Switch binding // MARK: - Switch binding
@@ -0,0 +1,25 @@
// MIDITransportPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// A pedal with a primary **transport footswitch** — a momentary, latching action beyond generic
/// bypass (e.g. TunedVerb's *Capture*, FreezVerb's *Freeze*) — that can be driven by a MIDI
/// footswitch.
///
/// Conforming makes the action appear in the MIDI mapping sheet automatically and lets a mapped
/// Program Change fire it: the sheet lists `midiTransportName`, and `MIDIController` calls
/// ``toggleMIDITransport()`` for a `PedalActionKind/pedalPrimaryTransport` binding. A pedal with a
/// richer transport surface (the looper) is handled by its own dedicated action kinds instead.
@MainActor
public protocol MIDITransportPedal: AnyObject {
/// Short display name of the primary transport footswitch (e.g. `"Capture"`, `"Freeze"`), shown
/// in the MIDI mapping sheet after the pedal name.
var midiTransportName: String { get }
/// Toggles the primary transport footswitch — called when a mapped MIDI footswitch fires. Same
/// effect as pressing the pedal's on-screen footswitch.
func toggleMIDITransport()
}
@@ -243,3 +243,12 @@ public final class FreezVerbPedal: Pedal {
frozen = 0.0 frozen = 0.0
} }
} }
// MARK: - MIDI transport
extension FreezVerbPedal: MIDITransportPedal {
/// The Freeze footswitch is the mappable transport action.
public var midiTransportName: String { "Freeze" }
public func toggleMIDITransport() { toggleFreeze() }
}
@@ -242,3 +242,12 @@ public final class TunedVerbPedal: Pedal {
captured = 0.0 captured = 0.0
} }
} }
// MARK: - MIDI transport
extension TunedVerbPedal: MIDITransportPedal {
/// The Capture footswitch is the mappable transport action.
public var midiTransportName: String { "Capture" }
public func toggleMIDITransport() { toggleCapture() }
}
+143
View File
@@ -0,0 +1,143 @@
// PostChain.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// The shared **post-board chain**: a linear chain of pedals that processes the summed board mix
/// once, after the board split, before the hardware output — for global reverb, a bus limiter, a
/// final EQ, and the like.
///
/// Signal flow: every board master writes a shared stereo **mix bus**; this chain reads that mix,
/// runs its pedals in order, and copies the processed tail to the hardware outputs (via
/// ``PostChainOutput``). The chain is **always stereo-headed** — the mix carries two channels even
/// for a mono rig (dual-mono) — so a mono pedal auto-stereoizes per channel while a stereo-native
/// pedal cross-couples, exactly as in a ``PedalBoard``'s stereo region. It is a *linear* stage:
/// no split / parallel / stereo regions, which a post-master bus doesn't need.
///
/// `PostChain` is deliberately a dedicated type (not a `PedalBoard`): it owns only its inter-node
/// buses — the mix buses and the hardware outputs are owned elsewhere — and has post-specific
/// routing (mix in, hardware out). Its pedal buses are wired like `PedalBoard.add`'s width-2 arms.
///
/// - Note: Rig-wide volume / mute live on the board masters, *upstream* of this chain, so a panic
/// mute can let a post-chain reverb tail ring out briefly. Acceptable for a setup-time stage.
@MainActor
final class PostChain {
private let engine: SynthesisEngine
private let clock: LyrebirdClock?
/// The shared mix bus this chain reads (externally owned — never released here).
private let mixLeftBus: Int
private let mixRightBus: Int
/// Hardware output buses the processed tail is copied to.
private let outputLeftBus: Int
private let outputRightBus: Int
/// Inter-node buses this chain allocates and owns (released on ``teardown()``).
private var allocatedBuses: [AudioBus] = []
/// The chain's pedals, in signal-flow order.
private(set) var pedals: [Pedal] = []
/// The current stereo tail — starts at the mix, advances with each pedal.
private var tailLeft: Int
private var tailRight: Int
/// The last node inserted (for `.after` ordering of the next node).
private var lastNode: (any Synthesizer)?
/// The final node copying the tail to the hardware outputs.
private var outputNode: PostChainOutput?
/// Creates a post-board chain reading `mixLeftBus` / `mixRightBus` and writing the hardware
/// outputs. The mix and hardware buses are owned by the caller.
init(
engine: SynthesisEngine,
clock: LyrebirdClock?,
mixLeftBus: Int,
mixRightBus: Int,
outputLeftBus: Int = 0,
outputRightBus: Int = 1
) {
self.engine = engine
self.clock = clock
self.mixLeftBus = mixLeftBus
self.mixRightBus = mixRightBus
self.outputLeftBus = outputLeftBus
self.outputRightBus = outputRightBus
self.tailLeft = mixLeftBus
self.tailRight = mixRightBus
}
/// Appends a pedal to the chain. The first pedal is inserted at the **tail of the main group** so
/// it evaluates after every board master regardless of board add order; later calls chain after
/// the previous node automatically.
///
/// The pedal is wired at stereo width: both input channels read the current tail, both output
/// channels write fresh buses. The pedal's `channelKind` decides how its `build()` uses them (a
/// mono pedal runs `effect(_:)` per channel; a stereo-native pedal cross-couples).
func add(_ pedal: Pedal) throws {
pedal.sampleRate = engine.sampleRate
pedal.hostEngine = engine
pedal.clock = clock
let outLeft: AudioBus = try allocateInterNodeBus()
let outRight: AudioBus = try allocateInterNodeBus()
pedal.inputBus = tailLeft
pedal.inputBusRight = tailRight
pedal.outputBus = outLeft.index
pedal.outputBusRight = outRight.index
try insertNode(pedal)
tailLeft = outLeft.index
tailRight = outRight.index
pedals.append(pedal)
}
/// Adds the output node that copies the chain tail to the hardware outputs. Call once, after all
/// pedals have been added.
func finalize() throws {
let output: PostChainOutput = PostChainOutput(
leftInputBus: tailLeft,
rightInputBus: tailRight,
leftOutputBus: outputLeftBus,
rightOutputBus: outputRightBus
)
try insertNode(output)
outputNode = output
}
/// Removes every node this chain added and releases its inter-node buses. Call before the mix /
/// hardware buses it references are released.
func teardown() {
if let output: PostChainOutput = outputNode { engine.remove(output) }
outputNode = nil
for pedal: Pedal in pedals { engine.remove(pedal) }
pedals.removeAll()
for bus: AudioBus in allocatedBuses { engine.busAllocator.releaseAudioBus(bus) }
allocatedBuses.removeAll()
}
// MARK: - Private
private func allocateInterNodeBus() throws -> AudioBus {
let bus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
allocatedBuses.append(bus)
return bus
}
private func insertNode(_ node: any Synthesizer) throws {
if let previous: any Synthesizer = lastNode {
try engine.add(node, position: .after(previous))
} else {
// Head node: tail of the main group → after every board master already there, and
// order-independent, so a board added later (spliced near the group head) still
// evaluates before this chain. No re-order needed on board add.
try engine.add(node, position: .tail(of: engine.mainGroup))
}
lastNode = node
}
}
@@ -0,0 +1,43 @@
// PostChainOutput.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// Internal synthesizer that copies the post-board chain's stereo tail onto the hardware output
/// buses — the final node of the ``PostChain``.
///
/// The board masters write the shared mix bus, the post-chain's pedals process it, and this node
/// copies the processed tail (left / right) to the hardware outputs. It carries no gain: the
/// rig-wide volume / mute live on the board masters, upstream of the post-chain.
///
/// - Note: Must be removed from the engine before the tail / hardware buses it reads are released.
final class PostChainOutput: SynthesizerBase {
private let leftInputBus: Int
private let rightInputBus: Int
private let leftOutputBus: Int
private let rightOutputBus: Int
/// Creates a stereo copy from the chain tail to the hardware outputs.
///
/// - Parameters:
/// - leftInputBus: Chain-tail left bus to read.
/// - rightInputBus: Chain-tail right bus to read.
/// - leftOutputBus: Hardware output for the left channel (default `0`).
/// - rightOutputBus: Hardware output for the right channel (default `1`).
init(leftInputBus: Int, rightInputBus: Int, leftOutputBus: Int = 0, rightOutputBus: Int = 1) {
self.leftInputBus = leftInputBus
self.rightInputBus = rightInputBus
self.leftOutputBus = leftOutputBus
self.rightOutputBus = rightOutputBus
super.init()
}
override func build() {
output(bus: leftOutputBus, source: input(bus: leftInputBus))
output(bus: rightOutputBus, source: input(bus: rightInputBus))
}
}
@@ -481,4 +481,148 @@ extension ShoeGaze {
let insertionIndex: Int = destinationIndex > sourceIndex ? destinationIndex - 1 : destinationIndex let insertionIndex: Int = destinationIndex > sourceIndex ? destinationIndex - 1 : destinationIndex
array.insert(element, at: insertionIndex) array.insert(element, at: insertionIndex)
} }
// MARK: - Pre-board chain editing
/// Appends a pedal to the end of the pre-board chain — the shared stage that processes the input
/// once, before the board split, and feeds every board.
///
/// - Important: A pre-board edit reshapes the shared feed every board taps, so the whole rig is
/// torn down and rebuilt (ordering-safe). Like ``setInputSource(_:)``, this resets transient
/// live state (solo / bypass) and stateful pedals (looper buffers) — it is a setup-time edit.
/// - Note: The pre-board chain feeds the **main boards** only. Chain-router branches read the
/// input source directly and are not fed by the pre-board chain.
public func appendPrePedal(_ kind: PedalType) throws {
let type: String = kind.rawValue
guard PedalRegistry.builtIn[type] != nil else { throw ShoeGazeError.unknownPedalType(type) }
var updated: [PedalState] = capturePreBoardStates() // fold in live knob tweaks first
updated.append(PedalState(type: type, knobValues: [], switchValues: [], bypass: 0.0))
try setPreBoardChain(updated)
}
/// Inserts a pedal at `index` in the pre-board chain (insert-before; `index == count` appends).
public func insertPrePedal(_ kind: PedalType, at index: Int) throws {
let type: String = kind.rawValue
guard PedalRegistry.builtIn[type] != nil else { throw ShoeGazeError.unknownPedalType(type) }
var updated: [PedalState] = capturePreBoardStates()
guard index >= 0 && index <= updated.count else {
throw ShoeGazeError.pedalIndexOutOfRange(index: index, count: updated.count)
}
updated.insert(PedalState(type: type, knobValues: [], switchValues: [], bypass: 0.0), at: index)
try setPreBoardChain(updated)
}
/// Removes the pre-board pedal at `index`.
public func removePrePedal(at index: Int) throws {
var updated: [PedalState] = capturePreBoardStates()
guard index >= 0 && index < updated.count else {
throw ShoeGazeError.pedalIndexOutOfRange(index: index, count: updated.count)
}
updated.remove(at: index)
try setPreBoardChain(updated)
}
/// Moves the pre-board pedal at `sourceIndex` to `destinationIndex` (SwiftUI `onMove` semantics).
public func movePrePedal(from sourceIndex: Int, to destinationIndex: Int) throws {
var updated: [PedalState] = capturePreBoardStates()
try Self.moveWithinArray(&updated, from: sourceIndex, to: destinationIndex)
try setPreBoardChain(updated)
}
/// Replaces the pre-board chain with `newStates` and rebuilds the rig. The pre-chain reshapes the
/// shared feed that every board taps, so the whole rig is torn down and rebuilt (ordering-safe);
/// mirrors ``setInputSource(_:)``, resetting transient / looper state like it does. On failure the
/// previous pre-board states are restored so a later capture never persists a half-applied edit.
private func setPreBoardChain(_ newStates: [PedalState]) throws {
let previous: [PedalState] = preBoardStates
preBoardStates = newStates
let wasRunning: Bool = engine.isRunning
if wasRunning { engine.stop() }
let snapshot: ShoeGazeState = captureState().withPreChain(newStates.isEmpty ? nil : newStates)
teardown()
do {
try rebuildAllBoards(from: snapshot)
} catch {
preBoardStates = previous
if wasRunning {
do { try engine.start() } catch { print("[ShoeGaze] engine restart after failed pre-board edit failed: \(error)") }
}
throw error
}
if wasRunning {
do { try engine.start() } catch { print("[ShoeGaze] engine restart after pre-board edit failed: \(error)") }
}
}
// MARK: - Post-board chain editing
/// Appends a pedal to the end of the post-board chain — the shared stage that processes the
/// summed board mix, after the split, before the hardware output (global reverb, bus limiter).
///
/// - Important: Reshapes the shared mix path, so the whole rig is torn down and rebuilt
/// (ordering-safe); resets transient / looper state like ``setInputSource(_:)``.
public func appendPostPedal(_ kind: PedalType) throws {
let type: String = kind.rawValue
guard PedalRegistry.builtIn[type] != nil else { throw ShoeGazeError.unknownPedalType(type) }
var updated: [PedalState] = capturePostBoardStates()
updated.append(PedalState(type: type, knobValues: [], switchValues: [], bypass: 0.0))
try setPostBoardChain(updated)
}
/// Inserts a pedal at `index` in the post-board chain (insert-before; `index == count` appends).
public func insertPostPedal(_ kind: PedalType, at index: Int) throws {
let type: String = kind.rawValue
guard PedalRegistry.builtIn[type] != nil else { throw ShoeGazeError.unknownPedalType(type) }
var updated: [PedalState] = capturePostBoardStates()
guard index >= 0 && index <= updated.count else {
throw ShoeGazeError.pedalIndexOutOfRange(index: index, count: updated.count)
}
updated.insert(PedalState(type: type, knobValues: [], switchValues: [], bypass: 0.0), at: index)
try setPostBoardChain(updated)
}
/// Removes the post-board pedal at `index`.
public func removePostPedal(at index: Int) throws {
var updated: [PedalState] = capturePostBoardStates()
guard index >= 0 && index < updated.count else {
throw ShoeGazeError.pedalIndexOutOfRange(index: index, count: updated.count)
}
updated.remove(at: index)
try setPostBoardChain(updated)
}
/// Moves the post-board pedal at `sourceIndex` to `destinationIndex` (SwiftUI `onMove` semantics).
public func movePostPedal(from sourceIndex: Int, to destinationIndex: Int) throws {
var updated: [PedalState] = capturePostBoardStates()
try Self.moveWithinArray(&updated, from: sourceIndex, to: destinationIndex)
try setPostBoardChain(updated)
}
/// Replaces the post-board chain with `newStates` and rebuilds the rig (ordering-safe). The
/// masters' output target (mix bus vs hardware) depends on whether a post-chain exists, so the
/// whole rig is rebuilt; mirrors ``setInputSource(_:)``.
///
/// - Note: On a rebuild failure the `postBoardStates` are restored and the engine is restarted,
/// but the graph was already torn down and is left empty — the rig runs silent until the next
/// successful edit. A setup-time edit, so this is acceptable (same contract as the pre-board edit).
private func setPostBoardChain(_ newStates: [PedalState]) throws {
let previous: [PedalState] = postBoardStates
postBoardStates = newStates
let wasRunning: Bool = engine.isRunning
if wasRunning { engine.stop() }
let snapshot: ShoeGazeState = captureState().withPostChain(newStates.isEmpty ? nil : newStates)
teardown()
do {
try rebuildAllBoards(from: snapshot)
} catch {
postBoardStates = previous
if wasRunning {
do { try engine.start() } catch { print("[ShoeGaze] engine restart after failed post-board edit failed: \(error)") }
}
throw error
}
if wasRunning {
do { try engine.start() } catch { print("[ShoeGaze] engine restart after post-board edit failed: \(error)") }
}
}
} }
@@ -38,7 +38,12 @@ extension ShoeGaze {
numOutputChannels: engine.numOutputChannels, numOutputChannels: engine.numOutputChannels,
// `nil` rather than `[]` when there are no routers, so a routerless rig's JSON is // `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. // unchanged and byte-identical to one saved before router persistence existed.
routers: routerStates.isEmpty ? nil : routerStates routers: routerStates.isEmpty ? nil : routerStates,
// Captured from the LIVE pre-pedals (so knob tweaks are saved); `nil` rather than `[]`
// when empty, so a rig without a pre-board chain stays byte-identical to the old format.
preChain: { let s: [PedalState] = capturePreBoardStates(); return s.isEmpty ? nil : s }(),
// Likewise for the post-board chain, captured from the live post-pedals.
postChain: { let s: [PedalState] = capturePostBoardStates(); return s.isEmpty ? nil : s }()
) )
} }
@@ -178,6 +183,11 @@ extension ShoeGaze {
/// - Throws: `BusAllocatorError`, `EngineAddError`, or `ShoeGazeError` from board construction. /// - Throws: `BusAllocatorError`, `EngineAddError`, or `ShoeGazeError` from board construction.
func rebuildAllBoards(from snapshot: ShoeGazeState) throws { func rebuildAllBoards(from snapshot: ShoeGazeState) throws {
do { do {
// Set the pre- and post-board chains before building any board: a board's input tap wires
// through the feed bus (`ensureFeed()` from `preBoardStates`), and its master targets the
// mix bus (`ensurePostMix()` from `postBoardStates`), both decided per board.
preBoardStates = snapshot.preChain ?? []
postBoardStates = snapshot.postChain ?? []
for boardState: BoardState in snapshot.boards { for boardState: BoardState in snapshot.boards {
let board: PedalBoard = try addBoard() let board: PedalBoard = try addBoard()
board.id = boardState.id board.id = boardState.id
@@ -188,6 +198,14 @@ extension ShoeGaze {
for routerState: ChainRouterState in snapshot.routers ?? [] { for routerState: ChainRouterState in snapshot.routers ?? [] {
try rebuildRouter(routerState) try rebuildRouter(routerState)
} }
// With no boards to pull the feed into being, build the pre-chain anyway so it isn't an
// invisible accumulation of states (`preBoardPedals` reflects it; a later board taps it).
if boards.isEmpty && !preBoardStates.isEmpty {
_ = try ensureFeed()
}
// Build the post-board chain after every board master exists (it reads the mix those
// masters write and must evaluate after them).
try buildPostChain()
} catch { } catch {
// Leave no partial rig behind: tear down whatever was built, then rethrow. // Leave no partial rig behind: tear down whatever was built, then rethrow.
teardown() teardown()
@@ -62,6 +62,16 @@ public struct ShoeGazeState: Codable, Equatable {
/// routers — decode cleanly to `nil` without a format-version bump. /// routers — decode cleanly to `nil` without a format-version bump.
public let routers: [ChainRouterState]? public let routers: [ChainRouterState]?
/// The rig's pre-board chain — pedals that process the input once, before the board split, and
/// feed every board — or `nil` for a rig saved before the pre-board stage existed. Additive:
/// decoded with `decodeIfPresent`, so older rigs decode cleanly to `nil` without a format bump.
public let preChain: [PedalState]?
/// The rig's post-board chain — pedals that process the summed board mix, after the split, before
/// the hardware output (global reverb, bus limiter, …) — or `nil` for a rig saved before the
/// post-board stage existed. Additive: decoded with `decodeIfPresent`.
public let postChain: [PedalState]?
/// Creates a rig state snapshot. /// Creates a rig state snapshot.
/// ///
/// - Parameters: /// - Parameters:
@@ -83,7 +93,9 @@ public struct ShoeGazeState: Codable, Equatable {
inputSource: InputSource? = nil, inputSource: InputSource? = nil,
numInputChannels: Int? = nil, numInputChannels: Int? = nil,
numOutputChannels: Int? = nil, numOutputChannels: Int? = nil,
routers: [ChainRouterState]? = nil routers: [ChainRouterState]? = nil,
preChain: [PedalState]? = nil,
postChain: [PedalState]? = nil
) { ) {
self.version = version self.version = version
self.boards = boards self.boards = boards
@@ -94,6 +106,8 @@ public struct ShoeGazeState: Codable, Equatable {
self.numInputChannels = numInputChannels self.numInputChannels = numInputChannels
self.numOutputChannels = numOutputChannels self.numOutputChannels = numOutputChannels
self.routers = routers self.routers = routers
self.preChain = preChain
self.postChain = postChain
} }
private enum CodingKeys: String, CodingKey { private enum CodingKeys: String, CodingKey {
@@ -106,6 +120,8 @@ public struct ShoeGazeState: Codable, Equatable {
case numInputChannels case numInputChannels
case numOutputChannels case numOutputChannels
case routers case routers
case preChain
case postChain
} }
/// Decodes a rig snapshot, tolerating an absent, malformed, OR legacy-format `midiMap`. /// Decodes a rig snapshot, tolerating an absent, malformed, OR legacy-format `midiMap`.
@@ -139,6 +155,8 @@ public struct ShoeGazeState: Codable, Equatable {
self.numInputChannels = try container.decodeIfPresent(Int.self, forKey: .numInputChannels) self.numInputChannels = try container.decodeIfPresent(Int.self, forKey: .numInputChannels)
self.numOutputChannels = try container.decodeIfPresent(Int.self, forKey: .numOutputChannels) self.numOutputChannels = try container.decodeIfPresent(Int.self, forKey: .numOutputChannels)
self.routers = try container.decodeIfPresent([ChainRouterState].self, forKey: .routers) self.routers = try container.decodeIfPresent([ChainRouterState].self, forKey: .routers)
self.preChain = try container.decodeIfPresent([PedalState].self, forKey: .preChain)
self.postChain = try container.decodeIfPresent([PedalState].self, forKey: .postChain)
} }
/// Whether two snapshots describe the same **rig** — its boards, routers, MIDI map, and tempo — /// Whether two snapshots describe the same **rig** — its boards, routers, MIDI map, and tempo —
@@ -155,5 +173,26 @@ public struct ShoeGazeState: Codable, Equatable {
&& midiMap == other.midiMap && midiMap == other.midiMap
&& bpm == other.bpm && bpm == other.bpm
&& tempoEnabled == other.tempoEnabled && tempoEnabled == other.tempoEnabled
&& preChain == other.preChain
&& postChain == other.postChain
}
/// Returns a copy of this snapshot with its `preChain` replaced. Used by the pre-board edit path
/// to force the just-mutated intended chain (rather than a re-read of the still-live pre-pedals).
public func withPreChain(_ preChain: [PedalState]?) -> ShoeGazeState {
ShoeGazeState(
version: version, boards: boards, midiMap: midiMap, bpm: bpm, tempoEnabled: tempoEnabled,
inputSource: inputSource, numInputChannels: numInputChannels,
numOutputChannels: numOutputChannels, routers: routers, preChain: preChain, postChain: postChain
)
}
/// Returns a copy with its `postChain` replaced. Post-board edit counterpart of ``withPreChain(_:)``.
public func withPostChain(_ postChain: [PedalState]?) -> ShoeGazeState {
ShoeGazeState(
version: version, boards: boards, midiMap: midiMap, bpm: bpm, tempoEnabled: tempoEnabled,
inputSource: inputSource, numInputChannels: numInputChannels,
numOutputChannels: numOutputChannels, routers: routers, preChain: preChain, postChain: postChain
)
} }
} }
+240 -23
View File
@@ -192,11 +192,117 @@ public final class ShoeGaze {
private var globalTestSource: TestLoopSource? private var globalTestSource: TestLoopSource?
private var globalTestBus: AudioBus? private var globalTestBus: AudioBus?
/// Per-board taps copying the global test bus into each board's head bus. /// Per-board taps copying the shared feed bus into each board's head bus.
private var testLoopTaps: [TestLoopTap] = [] private var testLoopTaps: [TestLoopTap] = []
private var inputPassThroughs: [HardwareInputPassThrough] = [] private var inputPassThroughs: [HardwareInputPassThrough] = []
private var outputMasters: [BoardOutputMaster] = [] private var outputMasters: [BoardOutputMaster] = []
// MARK: - Pre-board chain
/// The shared **feed bus** every board taps. It carries the input source directly, or — when a
/// pre-board chain exists — that chain's mono output. Allocated lazily by ``ensureFeed()`` when
/// the first board is wired, and rebuilt with the rig on a pre-board edit (which reshapes it).
private var feedBus: AudioBus?
/// The node that writes ``feedBus``: copies the input source, or the pre-board chain's mono
/// output, onto the feed bus. Board taps read the feed bus and so must evaluate after this node.
private var feedWriter: FeedPassThrough?
/// The live pre-board processing chain (a ``PedalBoard`` whose mono output feeds every board),
/// or `nil` when there is no pre-board processing. Rebuilt from ``preBoardStates``.
private var preChainBoard: PedalBoard?
/// The tap that feeds the pre-board chain's head bus from the input source. `nil` when there is
/// no pre-board chain.
private var preChainFeedTap: FeedPassThrough?
/// Persisted pre-board pedal states — the serialization source of truth. The live
/// ``preChainBoard`` is rebuilt from these. Empty when there is no pre-board processing.
/// Set via the pre-board edit API and on rig load; read by ``ensureFeed()`` when wiring the feed.
public internal(set) var preBoardStates: [PedalState] = []
/// The live pedals currently in the pre-board chain, in signal-flow order; empty when there is no
/// pre-board processing. For UI rendering + inspection (the persisted truth is ``preBoardStates``).
public var preBoardPedals: [Pedal] { preChainBoard?.pedals ?? [] }
/// The pre-board states captured from the **live** pre-pedals (so knob / switch tweaks are
/// included), or the stored ``preBoardStates`` when there is no live chain. Use this — never the
/// raw ``preBoardStates`` — wherever the pre-chain is saved or rebuilt, so live edits aren't lost.
func capturePreBoardStates() -> [PedalState] {
guard let pre: PedalBoard = preChainBoard else { return preBoardStates }
return pre.pedals.map { $0.captureState() }
}
// MARK: - Post-board chain
/// Shared stereo mix bus the board masters write **into** when a post-board chain exists; `nil`
/// otherwise (the masters write the hardware outputs directly). Owned here, released with the
/// post-chain. The post-chain reads this mix and writes the hardware outputs.
private var postMixLeft: AudioBus?
private var postMixRight: AudioBus?
/// The live post-board chain (reads the mix, writes hardware), or `nil` when there is none.
private var postChain: PostChain?
/// Persisted post-board pedal states — the serialization source of truth; the live ``postChain``
/// is rebuilt from these. Empty when there is no post-board processing.
public internal(set) var postBoardStates: [PedalState] = []
/// The live pedals in the post-board chain, in signal-flow order; empty when there is none.
public var postBoardPedals: [Pedal] { postChain?.pedals ?? [] }
/// Post-board states captured from the **live** post-pedals (so knob tweaks are included), or the
/// stored ``postBoardStates`` when there is no live chain. Use this wherever the post-chain is
/// saved or rebuilt, so live edits aren't lost.
func capturePostBoardStates() -> [PedalState] {
guard let post: PostChain = postChain else { return postBoardStates }
return post.pedals.map { $0.captureState() }
}
/// Ensures the stereo mix bus exists when a post-board chain is present, returning its bus
/// indices — or `nil` when there is none (the masters then write hardware directly).
private func ensurePostMix() throws -> (left: Int, right: Int)? {
guard !postBoardStates.isEmpty else { return nil }
if let left: AudioBus = postMixLeft, let right: AudioBus = postMixRight {
return (left.index, right.index)
}
let left: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let right: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
postMixLeft = left
postMixRight = right
return (left.index, right.index)
}
/// Builds the post-board chain from ``postBoardStates`` — reading the mix, writing hardware,
/// inserted at the tail of the main group so it evaluates after **every** board master (order-
/// independent). No-op when empty. Call after all boards are finalized.
func buildPostChain() throws {
guard !postBoardStates.isEmpty, let mix: (left: Int, right: Int) = try ensurePostMix() else { return }
let post: PostChain = PostChain(
engine: engine, clock: clock, mixLeftBus: mix.left, mixRightBus: mix.right
)
// Track the chain before wiring it, so a mid-build throw leaves its partial nodes/buses
// reachable for teardown (`tearDownPost` / the rebuild catch) instead of orphaned.
postChain = post
for state: PedalState in postBoardStates {
guard let pedal: Pedal = PedalRegistry.makePedal(type: state.type) else { continue }
pedal.applyState(state)
try post.add(pedal)
}
try post.finalize()
}
/// Removes the post-board chain nodes and releases the mix bus. Call from ``teardown()`` after the
/// masters that write the mix are removed.
private func tearDownPost() {
postChain?.teardown()
postChain = nil
if let left: AudioBus = postMixLeft { engine.busAllocator.releaseAudioBus(left) }
postMixLeft = nil
if let right: AudioBus = postMixRight { engine.busAllocator.releaseAudioBus(right) }
postMixRight = nil
}
/// All chain routers created via ``makeChainRouter()``. /// All chain routers created via ``makeChainRouter()``.
/// Routers are torn down (in reverse-creation order) by ``teardown()``. /// Routers are torn down (in reverse-creation order) by ``teardown()``.
/// ///
@@ -248,6 +354,8 @@ public final class ShoeGaze {
/// Every live `Pedal` across all main boards and chain-router branches. /// Every live `Pedal` across all main boards and chain-router branches.
private func allPedals() -> [Pedal] { private func allPedals() -> [Pedal] {
var result: [Pedal] = [] var result: [Pedal] = []
result.append(contentsOf: preBoardPedals)
result.append(contentsOf: postBoardPedals)
for board: PedalBoard in boards { for board: PedalBoard in boards {
result.append(contentsOf: pedals(in: board)) result.append(contentsOf: pedals(in: board))
} }
@@ -310,38 +418,36 @@ public final class ShoeGaze {
let board: PedalBoard = try PedalBoard(engine: engine, clock: clock) let board: PedalBoard = try PedalBoard(engine: engine, clock: clock)
board.label = "Board \(boards.count + 1)" board.label = "Board \(boards.count + 1)"
// Route the input source to the board head bus. // Every board taps the shared feed bus — the input source, or (when present) the pre-board
// chain's mono output. The tap evaluates after the feed writer so it reads a written bus.
let (feedBusIndex, feedNode): (Int, any Synthesizer) = try ensureFeed()
switch inputSource { switch inputSource {
case .testLoop: case .testLoop:
// All boards share one global test source so they stay phase-locked. Each board // All boards share one feed (and one global test source upstream of it) so they stay
// gets a tap copying the shared test bus into its head bus, added `.after(_:)` the // phase-locked. Each board gets a tap copying the feed bus into its head bus.
// source so it sees the source's output for the current block.
let (source, testBus): (TestLoopSource, AudioBus) = try ensureGlobalTestSource()
let tap: TestLoopTap = TestLoopTap( let tap: TestLoopTap = TestLoopTap(
inputBusIndex: testBus.index, inputBusIndex: feedBusIndex,
outputBusIndex: board.headBus.index outputBusIndex: board.headBus.index
) )
// Prime the mute gain before splicing the node in, so its very first render block // Prime the mute gain before splicing the node in, so its very first render block
// reflects the current mute state with no ramp (see `primeInputMute`). // reflects the current mute state with no ramp (see `primeInputMute`).
primeInputMute(tap.inputMuteNode, muted: inputMuted) primeInputMute(tap.inputMuteNode, muted: inputMuted)
try engine.add(tap, position: NodePosition.after(source)) try engine.add(tap, position: NodePosition.after(feedNode))
testLoopTaps.append(tap) testLoopTaps.append(tap)
// Record the tap as the head input node so PedalBoard.add(_:) can chain the first // Record the tap as the head input node so PedalBoard.add(_:) can chain the first
// pedal after it automatically (without needing an explicit `after:`). // pedal after it automatically (without needing an explicit `after:`).
board.headInputNode = tap board.headInputNode = tap
case .liveInput(let channel): case .liveInput:
// Hardware input channel `channel` lives at bus numOutputChannels + channel. // Live input flows through the same feed bus (which carries the hardware input, or the
// A HardwareInputPassThrough copies it to the board's head bus so all pedals // pre-board chain fed from it). The per-board input mute stays on this tap.
// read from a board-owned bus (not the raw hardware input bus).
let hardwareInputBusIndex: Int = try liveInputBusIndex(channel: channel, engine: engine)
let passThrough: HardwareInputPassThrough = HardwareInputPassThrough( let passThrough: HardwareInputPassThrough = HardwareInputPassThrough(
inputBusIndex: hardwareInputBusIndex, inputBusIndex: feedBusIndex,
outputBusIndex: board.headBus.index outputBusIndex: board.headBus.index
) )
// Prime the mute gain before splicing the node in (see `primeInputMute`). // Prime the mute gain before splicing the node in (see `primeInputMute`).
primeInputMute(passThrough.inputMuteNode, muted: inputMuted) primeInputMute(passThrough.inputMuteNode, muted: inputMuted)
try engine.add(passThrough) try engine.add(passThrough, position: NodePosition.after(feedNode))
inputPassThroughs.append(passThrough) inputPassThroughs.append(passThrough)
board.headInputNode = passThrough board.headInputNode = passThrough
} }
@@ -383,6 +489,100 @@ public final class ShoeGaze {
return (source, testBus) return (source, testBus)
} }
// MARK: - Pre-board feed wiring
/// Ensures the input source for the current ``inputSource`` exists and returns the bus it writes
/// plus the node that writes it (`nil` for live input — the hardware input bus is already
/// populated at block start, so nothing need evaluate before a reader).
private func ensureInputSourceBus() throws -> (bus: Int, node: (any Synthesizer)?) {
switch inputSource {
case .testLoop:
let (source, testBus): (TestLoopSource, AudioBus) = try ensureGlobalTestSource()
return (testBus.index, source)
case .liveInput(let channel):
let index: Int = try liveInputBusIndex(channel: channel, engine: engine)
return (index, nil)
}
}
/// Ensures the shared feed bus and its writer exist for the current input source and pre-board
/// state, returning the feed bus index and the node a board must order its input tap after.
@discardableResult
func ensureFeed() throws -> (bus: Int, node: any Synthesizer) {
if let feedBus: AudioBus = feedBus, let feedWriter: FeedPassThrough = feedWriter {
return (feedBus.index, feedWriter)
}
return try buildFeed()
}
/// Allocates the feed bus (if needed), builds the pre-board chain when ``preBoardStates`` is
/// non-empty (source → pedals → mono output), and creates the feed writer that copies the source
/// or the pre-chain output onto the feed bus. Returns the feed bus index + the feed writer node.
@discardableResult
private func buildFeed() throws -> (bus: Int, node: any Synthesizer) {
let (sourceBus, sourceNode): (Int, (any Synthesizer)?) = try ensureInputSourceBus()
let feed: AudioBus = try feedBus ?? engine.busAllocator.allocateAudioBus(channelCount: 1)
feedBus = feed
// What the feed writer reads: the source directly, or the pre-board chain's mono output.
var writerInputBus: Int = sourceBus
var writerAfter: (any Synthesizer)? = sourceNode
if !preBoardStates.isEmpty {
let pre: PedalBoard = try PedalBoard(engine: engine, clock: clock)
// Feed the pre-chain head from the input source.
let feedTap: FeedPassThrough = FeedPassThrough(
inputBusIndex: sourceBus,
outputBusIndex: pre.headBus.index
)
if let sourceNode: any Synthesizer = sourceNode {
try engine.add(feedTap, position: NodePosition.after(sourceNode))
} else {
try engine.add(feedTap)
}
pre.headInputNode = feedTap
preChainFeedTap = feedTap
for state: PedalState in preBoardStates {
guard let pedal: Pedal = PedalRegistry.makePedal(type: state.type) else { continue }
pedal.applyState(state)
try pre.add(pedal)
}
// The feed is mono (board heads are mono); fold any multi-channel pre-chain tail to mono.
if pre.width > 1 {
try pre.mergeToMono()
}
preChainBoard = pre
writerInputBus = pre.outputBus.index
writerAfter = pre.tailNode ?? feedTap
}
let writer: FeedPassThrough = FeedPassThrough(inputBusIndex: writerInputBus, outputBusIndex: feed.index)
if let after: any Synthesizer = writerAfter {
try engine.add(writer, position: NodePosition.after(after))
} else {
try engine.add(writer)
}
feedWriter = writer
return (feed.index, writer)
}
/// Removes the feed writer + pre-board chain nodes and releases the feed bus. Called from
/// ``teardown()`` (the whole feed is rebuilt from scratch on the next ``ensureFeed()``).
private func tearDownFeed() {
if let writer: FeedPassThrough = feedWriter { engine.remove(writer) }
feedWriter = nil
if let feedTap: FeedPassThrough = preChainFeedTap { engine.remove(feedTap) }
preChainFeedTap = nil
preChainBoard?.teardown()
preChainBoard = nil
if let feed: AudioBus = feedBus {
engine.busAllocator.releaseAudioBus(feed)
feedBus = nil
}
}
/// Connects the output master for a previously prepared board and adds it to the engine. /// Connects the output master for a previously prepared board and adds it to the engine.
/// ///
/// Call this after all pedals have been added to the board via `board.add(_:)`. /// Call this after all pedals have been added to the board via `board.add(_:)`.
@@ -396,10 +596,15 @@ public final class ShoeGaze {
/// - Parameter board: A `PedalBoard` returned by `addBoard()` with pedals added. /// - Parameter board: A `PedalBoard` returned by `addBoard()` with pedals added.
/// - Throws: `EngineAddError` if the engine rejects the master node. /// - Throws: `EngineAddError` if the engine rejects the master node.
public func finalizeBoard(_ board: PedalBoard) throws { public func finalizeBoard(_ board: PedalBoard) throws {
// When a post-board chain exists, every master writes the shared mix bus (the post-chain
// then reads the mix and writes hardware); otherwise the master writes hardware directly.
let mix: (left: Int, right: Int)? = try ensurePostMix()
let master: BoardOutputMaster = BoardOutputMaster( let master: BoardOutputMaster = BoardOutputMaster(
boardOutputBusIndex: board.outputBus.index, boardOutputBusIndex: board.outputBus.index,
boardOutputBusRightIndex: board.outputBusRight?.index, boardOutputBusRightIndex: board.outputBusRight?.index,
dryInputBusIndex: board.headBus.index dryInputBusIndex: board.headBus.index,
outputLeftBusIndex: mix?.left ?? 0,
outputRightBusIndex: mix?.right ?? 1
) )
// The master evaluates after the entire chain (pedals, splitters, mergers). // The master evaluates after the entire chain (pedals, splitters, mergers).
// `board.tailNode` returns the last inserted node (any Synthesizer), which covers // `board.tailNode` returns the last inserted node (any Synthesizer), which covers
@@ -439,6 +644,11 @@ public final class ShoeGaze {
// Bring a newly-finalized board up at the current rig volume / mute. // Bring a newly-finalized board up at the current rig volume / mute.
master.rigVolumeNode.update(rigVolume) master.rigVolumeNode.update(rigVolume)
master.rigMuteNode.update(rigMuted ? 1.0 : 0.0) master.rigMuteNode.update(rigMuted ? 1.0 : 0.0)
// A board finalized while a post-board chain already exists needs no post-chain rebuild: the
// post-chain sits at the tail of the main group, so the new master (spliced nearer the group
// head) evaluates before it automatically, and the new master already writes the shared mix
// (via the `ensurePostMix()` redirect above). The post-chain keeps its live pedal state.
} }
// MARK: - Board selection / crossfade // MARK: - Board selection / crossfade
@@ -837,9 +1047,17 @@ public final class ShoeGaze {
engine.remove(tap) engine.remove(tap)
} }
testLoopTaps.removeAll() testLoopTaps.removeAll()
for passThrough: HardwareInputPassThrough in inputPassThroughs {
engine.remove(passThrough)
}
inputPassThroughs.removeAll()
// Remove the shared global test source and release its bus (after its taps are removed, // Remove the feed writer + pre-board chain (the taps that read the feed bus are now gone)
// preserving remove-before-release ordering). // and release the feed bus, before the source it reads is removed.
tearDownFeed()
// Remove the shared global test source and release its bus (after the taps + feed that read
// it are removed, preserving remove-before-release ordering).
if let source: TestLoopSource = globalTestSource { if let source: TestLoopSource = globalTestSource {
engine.remove(source) engine.remove(source)
} }
@@ -849,16 +1067,15 @@ public final class ShoeGaze {
} }
globalTestBus = nil globalTestBus = nil
for passThrough: HardwareInputPassThrough in inputPassThroughs {
engine.remove(passThrough)
}
inputPassThroughs.removeAll()
for master: BoardOutputMaster in outputMasters { for master: BoardOutputMaster in outputMasters {
engine.remove(master) engine.remove(master)
} }
outputMasters.removeAll() outputMasters.removeAll()
// Remove the post-board chain (reader of the mix, writer of hardware) and release the mix
// bus, now that the masters that write it are gone.
tearDownPost()
// Step 2: Remove pedals from the engine and release all board-owned buses. // Step 2: Remove pedals from the engine and release all board-owned buses.
// board.teardown() removes pedals from the engine and then releases buses, // board.teardown() removes pedals from the engine and then releases buses,
// so bus release only happens after all writers have been dequeued. // so bus release only happens after all writers have been dequeued.
@@ -207,6 +207,31 @@ public final class UndoCoordinator {
/// bindings are restored from the snapshot (so undoing a Clear brings them back); tempo and /// bindings are restored from the snapshot (so undoing a Clear brings them back); tempo and
/// bypass/solo state are left as they are, being orthogonal to a topology edit. /// bypass/solo state are left as they are, being orthogonal to a topology edit.
private func restore(_ state: ShoeGazeState, on shoeGaze: ShoeGaze) { private func restore(_ state: ShoeGazeState, on shoeGaze: ShoeGaze) {
// Pre-board TOPOLOGY changed (a pre-pedal added / removed / reordered — compared by id
// sequence, so a knob-only change doesn't count) → the shared feed every board taps is
// different, which a surgical per-board reconcile can't express; rebuild the whole rig from
// the snapshot (ordering-safe), matching the forward edit. (Pre-pedal knob changes are
// `.parameter` undo entries, resolved by applyParameter, and never reach here.)
let targetPreIDs: [UUID] = (state.preChain ?? []).map { $0.id }
let livePreIDs: [UUID] = shoeGaze.capturePreBoardStates().map { $0.id }
let targetPostIDs: [UUID] = (state.postChain ?? []).map { $0.id }
let livePostIDs: [UUID] = shoeGaze.capturePostBoardStates().map { $0.id }
if targetPreIDs != livePreIDs || targetPostIDs != livePostIDs {
// A pre- or post-board topology change reshapes the shared feed / mix every board touches,
// which a surgical per-board reconcile can't express → rebuild the whole rig (as the
// forward edit does). Knob-only pre/post changes are `.parameter` entries, not here.
let wasRunning: Bool = shoeGaze.engine.isRunning
if wasRunning { shoeGaze.engine.stop() }
shoeGaze.teardown()
do { try shoeGaze.rebuildAllBoards(from: state) }
catch { print("[ShoeGaze] undo/redo pre/post-board rebuild failed: \(error)") }
shoeGaze.midiMap = state.midiMap
if wasRunning {
do { try shoeGaze.engine.start() } catch { print("[ShoeGaze] undo/redo engine restart failed: \(error)") }
}
return
}
// Current per-pedal values, keyed by pedal id, to merge onto the restored topology. // Current per-pedal values, keyed by pedal id, to merge onto the restored topology.
let liveValues: [UUID: PedalState] = currentPedalStatesByID(shoeGaze) let liveValues: [UUID: PedalState] = currentPedalStatesByID(shoeGaze)
let targetIDs: Set<UUID> = Set(state.boards.map { $0.id }) let targetIDs: Set<UUID> = Set(state.boards.map { $0.id })
@@ -191,6 +191,15 @@ struct PedalMappingStrip: View {
rows.append(PedalMappingRow(id: "bypass", label: "Bypass", badges: bypassBadges)) rows.append(PedalMappingRow(id: "bypass", label: "Bypass", badges: bypassBadges))
} }
// Primary transport footswitch (TunedVerb Capture, FreezVerb Freeze).
if let transport: MIDITransportPedal = pedal as? MIDITransportPedal {
let action: MIDIMap.Action = .pedalAction(pedalID: pedalID, kind: .pedalPrimaryTransport)
let transportBadges: [PedalMappingBadge] = badges(for: action, in: map)
if transportBadges.isEmpty == false {
rows.append(PedalMappingRow(id: "transport", label: transport.midiTransportName, badges: transportBadges))
}
}
// Looper transport actions. // Looper transport actions.
if pedal is LooperPedal { if pedal is LooperPedal {
for kind: MIDIMap.PedalActionKind in loopedActionOrder { for kind: MIDIMap.PedalActionKind in loopedActionOrder {
@@ -248,6 +257,8 @@ struct PedalMappingStrip: View {
case .looperSyncToggle: return "Sync" case .looperSyncToggle: return "Sync"
case .looperReset: return "Reset" case .looperReset: return "Reset"
case .looperTrack(let index): return "Track \(LooperPedal.trackLabel(index))" case .looperTrack(let index): return "Track \(LooperPedal.trackLabel(index))"
// Not a looper action; only looper kinds reach this helper, so a plain fallback suffices.
case .pedalPrimaryTransport: return "Transport"
} }
} }
} }
@@ -120,6 +120,14 @@ public struct MIDIMappingSheet: View {
id: "sw-pb-\(pedal.id)", id: "sw-pb-\(pedal.id)",
action: .pedalBypass(pedalID: pedal.id), action: .pedalBypass(pedalID: pedal.id),
label: "\(board.label) · \(pedal.displayName) · Bypass")) label: "\(board.label) · \(pedal.displayName) · Bypass"))
// A pedal with a primary transport footswitch (TunedVerb Capture, FreezVerb Freeze)
// exposes it as a mappable action.
if let transport: MIDITransportPedal = pedal as? MIDITransportPedal {
rows.append(SwitchRowModel(
id: "sw-pt-\(pedal.id)",
action: .pedalAction(pedalID: pedal.id, kind: .pedalPrimaryTransport),
label: "\(board.label) · \(pedal.displayName) · \(transport.midiTransportName)"))
}
// Loopers expose their transport footswitches as mappable switch actions. // Loopers expose their transport footswitches as mappable switch actions.
if pedal is LooperPedal { if pedal is LooperPedal {
var looperActions: [(String, String, MIDIMap.PedalActionKind)] = [ var looperActions: [(String, String, MIDIMap.PedalActionKind)] = [
@@ -184,6 +184,10 @@ public struct ShoeGazeBuilderView: View {
/// bottom sheets so the board canvas gets the full screen. /// bottom sheets so the board canvas gets the full screen.
@State private var showRigsSheet: Bool = false @State private var showRigsSheet: Bool = false
@State private var showPaletteSheet: Bool = false @State private var showPaletteSheet: Bool = false
/// When `true`, the next palette pick is added to the pre-board chain rather than a board.
@State private var addToPreBoard: Bool = false
/// When `true`, the next palette pick is added to the post-board chain rather than a board.
@State private var addToPostBoard: Bool = false
@State private var showSettingsSheet: Bool = false @State private var showSettingsSheet: Bool = false
/// Type filter for the compact Add-Pedal sheet, hoisted so it sits in the sheet's fixed header. /// Type filter for the compact Add-Pedal sheet, hoisted so it sits in the sheet's fixed header.
@@ -585,7 +589,9 @@ public struct ShoeGazeBuilderView: View {
/// Hosts the compact Add-pedal palette sheet on its own node. /// Hosts the compact Add-pedal palette sheet on its own node.
private var paletteSheetAnchor: some View { private var paletteSheetAnchor: some View {
Color.clear Color.clear
.sheet(isPresented: $showPaletteSheet) { // Reset the pre/post-board routing flags on any dismissal (incl. swipe-to-dismiss), so a
// later board-level "+" never misroutes its pick into a pre- or post-board chain.
.sheet(isPresented: $showPaletteSheet, onDismiss: { addToPreBoard = false; addToPostBoard = false }) {
paletteSheet paletteSheet
} }
} }
@@ -720,7 +726,9 @@ public struct ShoeGazeBuilderView: View {
} }
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)) Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
ControlMappingLegend() ControlMappingLegend()
preBoardStrip
boardArea boardArea
postBoardStrip
} }
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
// Make the undo coordinator reachable to every board / palette subview so their structural // Make the undo coordinator reachable to every board / palette subview so their structural
@@ -938,7 +946,7 @@ public struct ShoeGazeBuilderView: View {
.foregroundStyle(Color.white) .foregroundStyle(Color.white)
Spacer() Spacer()
pedalFilterMenu pedalFilterMenu
Button("Done") { showPaletteSheet = false } Button("Done") { addToPreBoard = false; addToPostBoard = false; showPaletteSheet = false }
.fontWeight(.semibold) .fontWeight(.semibold)
} }
.padding() .padding()
@@ -950,8 +958,25 @@ public struct ShoeGazeBuilderView: View {
axis: .vertical, axis: .vertical,
filter: $pedalFilter, filter: $pedalFilter,
showsFilterMenu: false, showsFilterMenu: false,
onAdd: { type in addPedal(type: type); showPaletteSheet = false }, onAdd: { type in
onRouting: { action in performRouting(action); showPaletteSheet = false } if addToPreBoard {
addPrePedal(type: type)
} else if addToPostBoard {
addPostPedal(type: type)
} else {
addPedal(type: type)
}
addToPreBoard = false
addToPostBoard = false
showPaletteSheet = false
},
onRouting: { action in
// Routing regions belong to a board, never the linear pre- or post-board chain.
addToPreBoard = false
addToPostBoard = false
performRouting(action)
showPaletteSheet = false
}
) )
.padding() .padding()
} }
@@ -1382,6 +1407,194 @@ public struct ShoeGazeBuilderView: View {
} }
} }
// MARK: - Pre-board strip
/// The shared pre-board processing chain, shown above the boards. Hidden to a thin "+ Pre" button
/// when empty; otherwise a horizontal row of pre-pedals over a divider marking that it feeds all
/// boards. Pre-pedals carry their own undo (knob edits) via the injected coordinator.
@ViewBuilder
private var preBoardStrip: some View {
let prePedals: [Pedal] = shoeGaze.preBoardPedals
if prePedals.isEmpty {
HStack {
Button {
addToPreBoard = true
showPaletteSheet = true
} label: {
Label("Pre-board", systemImage: "plus").font(.caption)
}
.buttonStyle(.bordered)
.tint(.gray)
.help("Add a pre-board pedal — processes the input once, feeding every board")
Spacer()
}
.padding(.horizontal, ShoeGazeBuilderView.outerPadding)
} else {
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.rowSpacing) {
HStack {
Text("Pre-board").font(.caption).bold().foregroundStyle(Color.white)
Spacer()
Button {
addToPreBoard = true
showPaletteSheet = true
} label: {
Image(systemName: "plus")
}
.buttonStyle(.bordered)
.tint(.gray)
.help("Add a pre-board pedal")
}
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .top, spacing: ShoeGazeBuilderView.rowSpacing) {
// Key by the pedal's stable id — a pre-board edit rebuilds the chain into new
// instances, so an offset key would bind a card to a torn-down pedal.
ForEach(Array(prePedals.enumerated()), id: \.element.id) { pair in
PedalView(pedal: pair.element)
.overlay(alignment: .topTrailing) {
Button(role: .destructive) {
removePreBoardPedal(at: pair.offset)
} label: {
Image(systemName: "xmark.circle.fill")
.font(.title3)
.foregroundStyle(Color.white, Color.black.opacity(0.55))
}
.buttonStyle(.plain)
.padding(4)
.help("Remove this pre-board pedal")
}
}
}
.padding(.horizontal, ShoeGazeBuilderView.outerPadding)
}
HStack(spacing: 6) {
Rectangle().fill(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)).frame(height: 1)
Text("feeds all boards")
.font(.caption2)
.foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.labelOpacity))
.fixedSize()
Rectangle().fill(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)).frame(height: 1)
}
.padding(.horizontal, ShoeGazeBuilderView.outerPadding)
}
.environment(undo)
.environment(\.shoeGazeTempoEnabled, shoeGaze.tempoEnabled)
}
}
private func addPrePedal(type: String) {
do {
try editing("Add \(type) (pre-board)") { try shoeGaze.appendPrePedal(PedalType(type)) }
autosave()
} catch {
print("[ShoeGazeBuilderView] appendPrePedal failed: \(error)")
reportError("Couldn’t add \(type)", error)
}
}
private func removePreBoardPedal(at index: Int) {
do {
try editing("Remove pre-board pedal") { try shoeGaze.removePrePedal(at: index) }
autosave()
} catch {
print("[ShoeGazeBuilderView] removePrePedal failed: \(error)")
reportError("Couldn’t remove pre-board pedal", error)
}
}
// MARK: - Post-board chain
/// The post-board chain strip, shown below the boards. Mirrors ``preBoardStrip``: hidden (just a
/// "+Post" button) when empty, a horizontal pedal strip otherwise. The post-chain processes the
/// summed board mix once before the hardware output — global reverb, a bus limiter, a final EQ.
@ViewBuilder
private var postBoardStrip: some View {
let postPedals: [Pedal] = shoeGaze.postBoardPedals
if postPedals.isEmpty {
HStack {
Button {
addToPostBoard = true
showPaletteSheet = true
} label: {
Label("Post-board", systemImage: "plus").font(.caption)
}
.buttonStyle(.bordered)
.tint(.gray)
.help("Add a post-board pedal — processes the summed board mix before the output")
Spacer()
}
.padding(.horizontal, ShoeGazeBuilderView.outerPadding)
} else {
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.rowSpacing) {
HStack(spacing: 6) {
Rectangle().fill(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)).frame(height: 1)
Text("from board mix")
.font(.caption2)
.foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.labelOpacity))
.fixedSize()
Rectangle().fill(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)).frame(height: 1)
}
.padding(.horizontal, ShoeGazeBuilderView.outerPadding)
HStack {
Text("Post-board").font(.caption).bold().foregroundStyle(Color.white)
Spacer()
Button {
addToPostBoard = true
showPaletteSheet = true
} label: {
Image(systemName: "plus")
}
.buttonStyle(.bordered)
.tint(.gray)
.help("Add a post-board pedal")
}
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .top, spacing: ShoeGazeBuilderView.rowSpacing) {
// Key by the pedal's stable id — a post-board edit rebuilds the chain into new
// instances, so an offset key would bind a card to a torn-down pedal.
ForEach(Array(postPedals.enumerated()), id: \.element.id) { pair in
PedalView(pedal: pair.element)
.overlay(alignment: .topTrailing) {
Button(role: .destructive) {
removePostBoardPedal(at: pair.offset)
} label: {
Image(systemName: "xmark.circle.fill")
.font(.title3)
.foregroundStyle(Color.white, Color.black.opacity(0.55))
}
.buttonStyle(.plain)
.padding(4)
.help("Remove this post-board pedal")
}
}
}
.padding(.horizontal, ShoeGazeBuilderView.outerPadding)
}
}
.environment(undo)
.environment(\.shoeGazeTempoEnabled, shoeGaze.tempoEnabled)
}
}
private func addPostPedal(type: String) {
do {
try editing("Add \(type) (post-board)") { try shoeGaze.appendPostPedal(PedalType(type)) }
autosave()
} catch {
print("[ShoeGazeBuilderView] appendPostPedal failed: \(error)")
reportError("Couldn’t add \(type)", error)
}
}
private func removePostBoardPedal(at index: Int) {
do {
try editing("Remove post-board pedal") { try shoeGaze.removePostPedal(at: index) }
autosave()
} catch {
print("[ShoeGazeBuilderView] removePostPedal failed: \(error)")
reportError("Couldn’t remove post-board pedal", error)
}
}
// MARK: - Board area // MARK: - Board area
private var boardArea: some View { private var boardArea: some View {
@@ -353,4 +353,34 @@ struct MIDIControllerPCTests {
#expect(looper.isTrackMuted(0), "mapped Program Change should tap (mute) the selected recorded track") #expect(looper.isTrackMuted(0), "mapped Program Change should tap (mute) the selected recorded track")
} }
} }
@Test func tunedVerbAndFreezVerbExposeAPrimaryTransport() {
// Unconditional conformance — the `as` is a compile-time proof the pedals are transport-mappable.
let tunedVerb: any MIDITransportPedal = TunedVerbPedal()
let freezVerb: any MIDITransportPedal = FreezVerbPedal()
#expect(tunedVerb.midiTransportName == "Capture")
#expect(freezVerb.midiTransportName == "Freeze")
}
@Test func mappedProgramChangeTogglesTunedVerbCapture() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
let tuned: TunedVerbPedal = TunedVerbPedal()
try board.add(tuned)
try sg.finalizeBoard(board)
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
withExtendedLifetime(sg) {
controller.armSwitchLearn(.pedalAction(pedalID: tuned.id, kind: .pedalPrimaryTransport))
controller.ingestForTesting(.programChange(channel: 0, program: 3)) // learn only
#expect(tuned.captured < 0.5, "learn must not toggle Capture")
controller.ingestForTesting(.programChange(channel: 0, program: 3)) // fire
#expect(tuned.captured > 0.5, "a mapped Program Change toggles Capture on")
controller.ingestForTesting(.programChange(channel: 0, program: 3)) // fire again
#expect(tuned.captured < 0.5, "a second press toggles Capture off")
}
}
} }
@@ -0,0 +1,170 @@
// PostBoardChainTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("Post-board chain")
struct PostBoardChainTests {
private func makeRig(
boardCount: Int,
duration: Double = 0.1
) throws -> (ShoeGaze, SynthesisEngine, URL) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: duration, numAudioBuses: 256)
let sg: ShoeGaze = ShoeGaze(engine: engine)
for _ in 0 ..< boardCount {
let board: PedalBoard = try sg.addBoard()
try board.add(OverdrivePedal())
try sg.finalizeBoard(board)
}
return (sg, engine, url)
}
private func render(_ engine: SynthesisEngine, _ url: URL) throws -> [Float] {
try engine.start()
return readStereoCAF(url: url)
}
@Test func postBoardChainProcessesTheMixAndRenders() throws {
let (sg, engine, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 2)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPostPedal(.reverb)
#expect(sg.postBoardStates.count == 1)
#expect(sg.postBoardPedals.count == 1, "the live post-chain holds the added pedal")
#expect(sg.boards.count == 2, "the boards are left in place")
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples), "a post-board pedal keeps the summed mix flowing to output")
}
@Test func aClosedPostBoardVolumeSilencesTheOutput() throws {
let (sg, engine, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 2)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPostPedal(.volume)
// Close the post-board volume (position 0 = silent) before start → the final output is silent,
// proving the post-chain sits in the output path after the board mix.
let volume: Pedal = try #require(sg.postBoardPedals.first)
let state: PedalState = volume.captureState()
try #require(!state.knobValues.isEmpty)
volume.applyState(
PedalState(id: state.id, type: state.type, knobValues: [0.0],
switchValues: state.switchValues, bypass: state.bypass)
)
let samples: [Float] = try render(engine, url)
#expect(!hasNonSilentOutput(samples), "a closed post-board volume silences the whole rig output")
}
@Test func removingTheLastPostPedalRestoresDirectOutput() throws {
let (sg, engine, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 1)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPostPedal(.reverb)
#expect(sg.postBoardPedals.count == 1)
try sg.removePostPedal(at: 0)
#expect(sg.postBoardStates.isEmpty)
#expect(sg.postBoardPedals.isEmpty, "the post-chain is gone")
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples), "the rig renders straight to hardware again")
}
@Test func addingABoardWhileAPostChainExistsKeepsOutputFlowing() throws {
let (sg, engine, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 1)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPostPedal(.reverb)
// Add a second board AFTER the post-chain exists. The post-chain sits at the tail of the main
// group, so the new master (spliced nearer the head) evaluates before it with no rebuild.
let second: PedalBoard = try sg.addBoard()
try second.add(DelayPedal())
try sg.finalizeBoard(second)
#expect(sg.boards.count == 2)
#expect(sg.postBoardPedals.count == 1, "the post-chain survives the board add")
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples), "both boards reach output through the re-ordered post-chain")
}
@Test func postChainEvaluatesAfterEveryBoardMasterNotJustTheLast() throws {
// The naive anchor was `outputMasters.last` — the *last-finalized* board. But board taps are
// spliced `.after(feedNode)`, so a later board evaluates EARLIER; `outputMasters.last` is the
// first-evaluated master, and a post-chain placed after it reads the mix before the other
// boards write it. Here we silence the last-finalized board and keep the first one audible:
// if the post-chain ran before board 0's master, the mix would be empty and the output silent.
let (sg, engine, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 2)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPostPedal(.reverb)
// Close the LAST-finalized board's master; only the first board feeds the mix now.
let lastBoardGain: UIParamNode = try #require(sg.boards[1].masterGainNode)
lastBoardGain.update(0.0)
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples),
"the first board must still reach the output through a tail-ordered post-chain")
}
@Test func insertMoveAndRemoveOrderThePostChain() throws {
let (sg, _, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 1)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPostPedal(.reverb)
try sg.insertPostPedal(.volume, at: 0)
#expect(sg.postBoardStates.map { $0.type } == ["Volume", "Reverb"], "insert lands at the index")
// SwiftUI `toOffset` semantics — move the Reverb (index 1) to the front.
try sg.movePostPedal(from: 1, to: 0)
#expect(sg.postBoardStates.map { $0.type } == ["Reverb", "Volume"], "move reorders the chain")
try sg.removePostPedal(at: 0)
#expect(sg.postBoardStates.map { $0.type } == ["Volume"], "remove drops the indexed pedal")
#expect(sg.postBoardPedals.map { $0.id } == sg.postBoardStates.map { $0.id },
"live pedals track the states in order")
}
@Test func postBoardChainRoundTripsThroughSaveLoad() throws {
let (sg, _, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 1)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPostPedal(.reverb)
let knob: PedalKnob = try #require(sg.postBoardPedals.first?.knobs.first)
let sentinel: Double = knob.range.lowerBound + (knob.range.upperBound - knob.range.lowerBound) * 0.44
knob.node.update(sentinel)
let preset: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: preset) }
try sg.saveRig(to: preset)
let (engine2, url2): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 256)
defer { try? FileManager.default.removeItem(at: url2) }
let sg2: ShoeGaze = ShoeGaze(engine: engine2)
try sg2.loadRig(from: preset)
#expect(sg2.postBoardStates.map { $0.type } == ["Reverb"], "post-chain round-trips")
#expect(sg2.postBoardPedals.count == 1, "the reloaded post-chain is live")
let reloadedKnob: Double = try #require(sg2.postBoardPedals.first?.captureState().knobValues.first)
#expect(abs(reloadedKnob - sentinel) < 1e-9, "a post-pedal knob tweak survives save/load")
try engine2.start()
#expect(hasNonSilentOutput(readStereoCAF(url: url2)), "reloaded post-board rig renders")
}
@Test func oldRigWithoutPostChainDecodesToEmpty() throws {
let state: ShoeGazeState = ShoeGazeState(boards: [])
#expect(state.postChain == nil)
let data: Data = try JSONEncoder().encode(state)
let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
#expect(decoded.postChain == nil, "absent/nil postChain stays nil")
}
}
@@ -0,0 +1,137 @@
// PreBoardChainTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("Pre-board chain")
struct PreBoardChainTests {
/// Builds an NRT-backed `ShoeGaze` with `boardCount` single-Overdrive boards.
private func makeRig(
boardCount: Int,
duration: Double = 0.1
) throws -> (ShoeGaze, SynthesisEngine, URL) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: duration, numAudioBuses: 256)
let sg: ShoeGaze = ShoeGaze(engine: engine)
for _ in 0 ..< boardCount {
let board: PedalBoard = try sg.addBoard()
try board.add(OverdrivePedal())
try sg.finalizeBoard(board)
}
return (sg, engine, url)
}
private func render(_ engine: SynthesisEngine, _ url: URL) throws -> [Float] {
try engine.start()
return readStereoCAF(url: url)
}
@Test func preBoardChainRendersAndFeedsBoards() throws {
let (sg, engine, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 2)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPrePedal(.overdrive)
#expect(sg.preBoardStates.count == 1)
#expect(sg.preBoardPedals.count == 1, "the live pre-chain holds the added pedal")
#expect(sg.boards.count == 2, "pre-board edit leaves the boards in place")
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples), "a pre-board pedal keeps the signal flowing to the boards")
}
@Test func aClosedPreBoardVolumeSilencesEveryBoard() throws {
let (sg, engine, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 2)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPrePedal(.volume)
// Close the pre-board volume (position 0 = silent) before start, so it is delivered flat.
let volume: Pedal = try #require(sg.preBoardPedals.first)
let state: PedalState = volume.captureState()
try #require(!state.knobValues.isEmpty)
volume.applyState(
PedalState(id: state.id, type: state.type, knobValues: [0.0],
switchValues: state.switchValues, bypass: state.bypass)
)
let samples: [Float] = try render(engine, url)
#expect(!hasNonSilentOutput(samples), "a closed pre-board volume silences the feed to every board")
}
@Test func removingTheLastPrePedalRestoresTheDirectFeed() throws {
let (sg, engine, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 1)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPrePedal(.overdrive)
#expect(sg.preBoardPedals.count == 1)
try sg.removePrePedal(at: 0)
#expect(sg.preBoardStates.isEmpty)
#expect(sg.preBoardPedals.isEmpty, "the pre-chain is gone")
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples), "the board renders from the direct feed again")
}
@Test func preBoardChainRoundTripsThroughSaveLoad() throws {
let (sg, _, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 1)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPrePedal(.overdrive)
try sg.appendPrePedal(.delay)
#expect(sg.preBoardStates.map { $0.type } == ["Overdrive", "Delay"])
// Tweak the LIVE first pre-pedal's knob — the save must capture it, not the stale default.
let knob: PedalKnob = try #require(sg.preBoardPedals.first?.knobs.first)
let sentinel: Double = knob.range.lowerBound + (knob.range.upperBound - knob.range.lowerBound) * 0.41
knob.node.update(sentinel)
let preset: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: preset) }
try sg.saveRig(to: preset)
let (engine2, url2): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 256)
defer { try? FileManager.default.removeItem(at: url2) }
let sg2: ShoeGaze = ShoeGaze(engine: engine2)
try sg2.loadRig(from: preset)
#expect(sg2.preBoardStates.map { $0.type } == ["Overdrive", "Delay"], "pre-chain round-trips")
#expect(sg2.preBoardPedals.count == 2, "the reloaded pre-chain is live")
let reloadedKnob: Double = try #require(sg2.preBoardPedals.first?.captureState().knobValues.first)
#expect(abs(reloadedKnob - sentinel) < 1e-9, "a pre-pedal knob tweak survives save/load")
try engine2.start()
#expect(hasNonSilentOutput(readStereoCAF(url: url2)), "reloaded pre-board rig renders")
}
@Test func addingASecondPrePedalKeepsTheFirstsLiveKnob() throws {
let (sg, _, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 1)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPrePedal(.overdrive)
let knob: PedalKnob = try #require(sg.preBoardPedals.first?.knobs.first)
let sentinel: Double = knob.range.lowerBound + (knob.range.upperBound - knob.range.lowerBound) * 0.37
knob.node.update(sentinel)
// Adding a second pre-pedal rebuilds the whole pre-chain; the first pedal's live knob must be
// folded into the rebuild, not reset to its default.
try sg.appendPrePedal(.delay)
let firstKnob: Double = try #require(sg.preBoardPedals.first?.captureState().knobValues.first)
#expect(abs(firstKnob - sentinel) < 1e-9, "a prior pre-pedal's live knob survives adding another")
}
@Test func oldRigWithoutPreChainDecodesToEmpty() throws {
// A ShoeGazeState encoded without the preChain key (older rig) decodes to no pre-board chain.
let state: ShoeGazeState = ShoeGazeState(boards: [])
#expect(state.preChain == nil)
let data: Data = try JSONEncoder().encode(state)
let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
#expect(decoded.preChain == nil, "absent/nil preChain stays nil")
}
}
@@ -386,6 +386,46 @@ struct UndoCoordinatorTests {
#expect(abs(selector.node.value - newValue) < 1e-9) #expect(abs(selector.node.value - newValue) < 1e-9)
} }
// MARK: - Undo of a pre-board edit
@Test func undoOfAddPrePedalRemovesItAndRedoBringsItBack() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
_ = board
try undo.perform("Add pre-pedal") { try sg.appendPrePedal(.reverb) }
#expect(sg.preBoardStates.map { $0.type } == ["Reverb"])
#expect(names(sg) == ["Overdrive"], "the board is untouched by a pre-board edit")
undo.undo()
#expect(sg.preBoardStates.isEmpty, "undo removes the pre-board pedal")
#expect(names(sg) == ["Overdrive"], "the board survives the pre-board undo")
undo.redo()
#expect(sg.preBoardStates.map { $0.type } == ["Reverb"], "redo re-adds the pre-board pedal")
}
// MARK: - Undo of a post-board edit
@Test func undoOfAddPostPedalRemovesItAndRedoBringsItBack() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
_ = board
try undo.perform("Add post-pedal") { try sg.appendPostPedal(.reverb) }
#expect(sg.postBoardStates.map { $0.type } == ["Reverb"])
#expect(names(sg) == ["Overdrive"], "the board is untouched by a post-board edit")
undo.undo()
#expect(sg.postBoardStates.isEmpty, "undo removes the post-board pedal")
#expect(names(sg) == ["Overdrive"], "the board survives the post-board undo")
undo.redo()
#expect(sg.postBoardStates.map { $0.type } == ["Reverb"], "redo re-adds the post-board pedal")
}
// MARK: - Parameter resolution relies on unique labels per group // MARK: - Parameter resolution relies on unique labels per group
@Test func controlLabelsAreUniqueWithinEachGroupAcrossTheCatalogue() throws { @Test func controlLabelsAreUniqueWithinEachGroupAcrossTheCatalogue() throws {