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>
This commit is contained in:
2026-11-25 19:18:04 -08:00
parent 1f5b70edc7
commit 9dfadb129d
9 changed files with 592 additions and 28 deletions
@@ -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))
}
}
@@ -481,4 +481,76 @@ extension ShoeGaze {
let insertionIndex: Int = destinationIndex > sourceIndex ? destinationIndex - 1 : destinationIndex
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)") }
}
}
}
@@ -38,7 +38,10 @@ extension ShoeGaze {
numOutputChannels: engine.numOutputChannels,
// `nil` rather than `[]` when there are no routers, so a routerless rig's JSON is
// unchanged and byte-identical to one saved before router persistence existed.
routers: routerStates.isEmpty ? nil : routerStates
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 }()
)
}
@@ -178,6 +181,9 @@ extension ShoeGaze {
/// - Throws: `BusAllocatorError`, `EngineAddError`, or `ShoeGazeError` from board construction.
func rebuildAllBoards(from snapshot: ShoeGazeState) throws {
do {
// Set the pre-board chain before building any board: the first board's input tap wires
// through the feed bus, which `ensureFeed()` builds from `preBoardStates`.
preBoardStates = snapshot.preChain ?? []
for boardState: BoardState in snapshot.boards {
let board: PedalBoard = try addBoard()
board.id = boardState.id
@@ -188,6 +194,11 @@ extension ShoeGaze {
for routerState: ChainRouterState in snapshot.routers ?? [] {
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()
}
} catch {
// Leave no partial rig behind: tear down whatever was built, then rethrow.
teardown()
@@ -62,6 +62,11 @@ public struct ShoeGazeState: Codable, Equatable {
/// routers — decode cleanly to `nil` without a format-version bump.
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]?
/// Creates a rig state snapshot.
///
/// - Parameters:
@@ -83,7 +88,8 @@ public struct ShoeGazeState: Codable, Equatable {
inputSource: InputSource? = nil,
numInputChannels: Int? = nil,
numOutputChannels: Int? = nil,
routers: [ChainRouterState]? = nil
routers: [ChainRouterState]? = nil,
preChain: [PedalState]? = nil
) {
self.version = version
self.boards = boards
@@ -94,6 +100,7 @@ public struct ShoeGazeState: Codable, Equatable {
self.numInputChannels = numInputChannels
self.numOutputChannels = numOutputChannels
self.routers = routers
self.preChain = preChain
}
private enum CodingKeys: String, CodingKey {
@@ -106,6 +113,7 @@ public struct ShoeGazeState: Codable, Equatable {
case numInputChannels
case numOutputChannels
case routers
case preChain
}
/// Decodes a rig snapshot, tolerating an absent, malformed, OR legacy-format `midiMap`.
@@ -139,6 +147,7 @@ public struct ShoeGazeState: Codable, Equatable {
self.numInputChannels = try container.decodeIfPresent(Int.self, forKey: .numInputChannels)
self.numOutputChannels = try container.decodeIfPresent(Int.self, forKey: .numOutputChannels)
self.routers = try container.decodeIfPresent([ChainRouterState].self, forKey: .routers)
self.preChain = try container.decodeIfPresent([PedalState].self, forKey: .preChain)
}
/// Whether two snapshots describe the same **rig** — its boards, routers, MIDI map, and tempo —
@@ -155,5 +164,16 @@ public struct ShoeGazeState: Codable, Equatable {
&& midiMap == other.midiMap
&& bpm == other.bpm
&& tempoEnabled == other.tempoEnabled
&& preChain == other.preChain
}
/// 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
)
}
}
+154 -22
View File
@@ -192,11 +192,47 @@ public final class ShoeGaze {
private var globalTestSource: TestLoopSource?
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 inputPassThroughs: [HardwareInputPassThrough] = []
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() }
}
/// All chain routers created via ``makeChainRouter()``.
/// Routers are torn down (in reverse-creation order) by ``teardown()``.
///
@@ -248,6 +284,7 @@ public final class ShoeGaze {
/// Every live `Pedal` across all main boards and chain-router branches.
private func allPedals() -> [Pedal] {
var result: [Pedal] = []
result.append(contentsOf: preBoardPedals)
for board: PedalBoard in boards {
result.append(contentsOf: pedals(in: board))
}
@@ -310,38 +347,36 @@ public final class ShoeGaze {
let board: PedalBoard = try PedalBoard(engine: engine, clock: clock)
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 {
case .testLoop:
// All boards share one global test source so they stay phase-locked. Each board
// gets a tap copying the shared test bus into its head bus, added `.after(_:)` the
// source so it sees the source's output for the current block.
let (source, testBus): (TestLoopSource, AudioBus) = try ensureGlobalTestSource()
// All boards share one feed (and one global test source upstream of it) so they stay
// phase-locked. Each board gets a tap copying the feed bus into its head bus.
let tap: TestLoopTap = TestLoopTap(
inputBusIndex: testBus.index,
inputBusIndex: feedBusIndex,
outputBusIndex: board.headBus.index
)
// 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`).
primeInputMute(tap.inputMuteNode, muted: inputMuted)
try engine.add(tap, position: NodePosition.after(source))
try engine.add(tap, position: NodePosition.after(feedNode))
testLoopTaps.append(tap)
// Record the tap as the head input node so PedalBoard.add(_:) can chain the first
// pedal after it automatically (without needing an explicit `after:`).
board.headInputNode = tap
case .liveInput(let channel):
// Hardware input channel `channel` lives at bus numOutputChannels + channel.
// A HardwareInputPassThrough copies it to the board's head bus so all pedals
// read from a board-owned bus (not the raw hardware input bus).
let hardwareInputBusIndex: Int = try liveInputBusIndex(channel: channel, engine: engine)
case .liveInput:
// Live input flows through the same feed bus (which carries the hardware input, or the
// pre-board chain fed from it). The per-board input mute stays on this tap.
let passThrough: HardwareInputPassThrough = HardwareInputPassThrough(
inputBusIndex: hardwareInputBusIndex,
inputBusIndex: feedBusIndex,
outputBusIndex: board.headBus.index
)
// Prime the mute gain before splicing the node in (see `primeInputMute`).
primeInputMute(passThrough.inputMuteNode, muted: inputMuted)
try engine.add(passThrough)
try engine.add(passThrough, position: NodePosition.after(feedNode))
inputPassThroughs.append(passThrough)
board.headInputNode = passThrough
}
@@ -383,6 +418,100 @@ public final class ShoeGaze {
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.
///
/// Call this after all pedals have been added to the board via `board.add(_:)`.
@@ -837,9 +966,17 @@ public final class ShoeGaze {
engine.remove(tap)
}
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,
// preserving remove-before-release ordering).
// Remove the feed writer + pre-board chain (the taps that read the feed bus are now gone)
// 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 {
engine.remove(source)
}
@@ -849,11 +986,6 @@ public final class ShoeGaze {
}
globalTestBus = nil
for passThrough: HardwareInputPassThrough in inputPassThroughs {
engine.remove(passThrough)
}
inputPassThroughs.removeAll()
for master: BoardOutputMaster in outputMasters {
engine.remove(master)
}
@@ -207,6 +207,26 @@ public final class UndoCoordinator {
/// 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.
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 }
if targetPreIDs != livePreIDs {
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-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.
let liveValues: [UUID: PedalState] = currentPedalStatesByID(shoeGaze)
let targetIDs: Set<UUID> = Set(state.boards.map { $0.id })
@@ -184,6 +184,8 @@ public struct ShoeGazeBuilderView: View {
/// bottom sheets so the board canvas gets the full screen.
@State private var showRigsSheet: 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
@State private var showSettingsSheet: Bool = false
/// Type filter for the compact Add-Pedal sheet, hoisted so it sits in the sheet's fixed header.
@@ -585,7 +587,9 @@ public struct ShoeGazeBuilderView: View {
/// Hosts the compact Add-pedal palette sheet on its own node.
private var paletteSheetAnchor: some View {
Color.clear
.sheet(isPresented: $showPaletteSheet) {
// Reset the pre-board routing flag on any dismissal (incl. swipe-to-dismiss), so a later
// board-level "+" never misroutes its pick into the pre-board chain.
.sheet(isPresented: $showPaletteSheet, onDismiss: { addToPreBoard = false }) {
paletteSheet
}
}
@@ -720,6 +724,7 @@ public struct ShoeGazeBuilderView: View {
}
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
ControlMappingLegend()
preBoardStrip
boardArea
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
@@ -938,7 +943,7 @@ public struct ShoeGazeBuilderView: View {
.foregroundStyle(Color.white)
Spacer()
pedalFilterMenu
Button("Done") { showPaletteSheet = false }
Button("Done") { addToPreBoard = false; showPaletteSheet = false }
.fontWeight(.semibold)
}
.padding()
@@ -950,8 +955,17 @@ public struct ShoeGazeBuilderView: View {
axis: .vertical,
filter: $pedalFilter,
showsFilterMenu: false,
onAdd: { type in addPedal(type: type); showPaletteSheet = false },
onRouting: { action in performRouting(action); showPaletteSheet = false }
onAdd: { type in
if addToPreBoard { addPrePedal(type: type) } else { addPedal(type: type) }
addToPreBoard = false
showPaletteSheet = false
},
onRouting: { action in
// Routing regions belong to a board, never the linear pre-board chain.
addToPreBoard = false
performRouting(action)
showPaletteSheet = false
}
)
.padding()
}
@@ -1382,6 +1396,100 @@ 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: - Board area
private var boardArea: some View {
@@ -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,26 @@ struct UndoCoordinatorTests {
#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: - Parameter resolution relies on unique labels per group
@Test func controlLabelsAreUniqueWithinEachGroupAcrossTheCatalogue() throws {