diff --git a/Demo/ShoeGazeBuilderiOS.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Demo/ShoeGazeBuilderiOS.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index e9006c3..8680d91 100644 --- a/Demo/ShoeGazeBuilderiOS.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Demo/ShoeGazeBuilderiOS.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -15,8 +15,8 @@ "kind" : "remoteSourceControl", "location" : "https://realizedsound.mooo.com/josh/Lyrebird", "state" : { - "revision" : "b6fdee8bfc7c44d31a0a8cfe6fbd53f352dfad54", - "version" : "2.0.0" + "revision" : "9f244b19394f6352b0a1dcf532cf142b86e41c30", + "version" : "2.3.0" } }, { diff --git a/Sources/LyrebirdShoeGaze/BoardOutputMaster.swift b/Sources/LyrebirdShoeGaze/BoardOutputMaster.swift index f7c0160..d25b572 100644 --- a/Sources/LyrebirdShoeGaze/BoardOutputMaster.swift +++ b/Sources/LyrebirdShoeGaze/BoardOutputMaster.swift @@ -80,6 +80,12 @@ final class BoardOutputMaster: SynthesizerBase { /// bypass source so a bypassed board passes its untouched input straight through. 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 /// 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, /// 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. - 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.boardOutputBusRightIndex = boardOutputBusRightIndex self.dryInputBusIndex = dryInputBusIndex + self.outputLeftBusIndex = outputLeftBusIndex + self.outputRightBusIndex = outputRightBusIndex super.init() } @@ -131,15 +145,15 @@ final class BoardOutputMaster: SynthesizerBase { let switchedRight: any ValidGeneratorInput = applyBypass(wet: boardOutRight, dry: dry) let gainedRight: any ValidGeneratorInput = ((switchedRight * smoothedSelect) * $masterGain) * rigOutputGain - output(bus: 0, source: gainedLeft) - output(bus: 1, source: gainedRight) + output(bus: outputLeftBusIndex, source: gainedLeft) + output(bus: outputRightBusIndex, source: gainedRight) } else { // 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 // 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. - output(bus: 0, source: gainedLeft) - output(bus: 1, source: gainedLeft) + output(bus: outputLeftBusIndex, source: gainedLeft) + output(bus: outputRightBusIndex, source: gainedLeft) } } diff --git a/Sources/LyrebirdShoeGaze/PostChain.swift b/Sources/LyrebirdShoeGaze/PostChain.swift new file mode 100644 index 0000000..e89167f --- /dev/null +++ b/Sources/LyrebirdShoeGaze/PostChain.swift @@ -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 + } +} diff --git a/Sources/LyrebirdShoeGaze/PostChainOutput.swift b/Sources/LyrebirdShoeGaze/PostChainOutput.swift new file mode 100644 index 0000000..10a7916 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/PostChainOutput.swift @@ -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)) + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Edit.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Edit.swift index 46ee89a..ef4fe3d 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Edit.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Edit.swift @@ -553,4 +553,76 @@ extension ShoeGaze { 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)") } + } + } } diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift index 21c7b5c..2976d2d 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift @@ -41,7 +41,9 @@ extension ShoeGaze { 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 }() + 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 }() ) } @@ -181,9 +183,11 @@ 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`. + // 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 { let board: PedalBoard = try addBoard() board.id = boardState.id @@ -199,6 +203,9 @@ extension ShoeGaze { 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 { // Leave no partial rig behind: tear down whatever was built, then rethrow. teardown() diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift index b1afafd..782c3c4 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift @@ -67,6 +67,11 @@ public struct ShoeGazeState: Codable, Equatable { /// 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. /// /// - Parameters: @@ -89,7 +94,8 @@ public struct ShoeGazeState: Codable, Equatable { numInputChannels: Int? = nil, numOutputChannels: Int? = nil, routers: [ChainRouterState]? = nil, - preChain: [PedalState]? = nil + preChain: [PedalState]? = nil, + postChain: [PedalState]? = nil ) { self.version = version self.boards = boards @@ -101,6 +107,7 @@ public struct ShoeGazeState: Codable, Equatable { self.numOutputChannels = numOutputChannels self.routers = routers self.preChain = preChain + self.postChain = postChain } private enum CodingKeys: String, CodingKey { @@ -114,6 +121,7 @@ public struct ShoeGazeState: Codable, Equatable { case numOutputChannels case routers case preChain + case postChain } /// Decodes a rig snapshot, tolerating an absent, malformed, OR legacy-format `midiMap`. @@ -148,6 +156,7 @@ public struct ShoeGazeState: Codable, Equatable { 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) + self.postChain = try container.decodeIfPresent([PedalState].self, forKey: .postChain) } /// Whether two snapshots describe the same **rig** — its boards, routers, MIDI map, and tempo — @@ -165,6 +174,7 @@ public struct ShoeGazeState: Codable, Equatable { && bpm == other.bpm && 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 @@ -173,7 +183,16 @@ public struct ShoeGazeState: Codable, Equatable { ShoeGazeState( version: version, boards: boards, midiMap: midiMap, bpm: bpm, tempoEnabled: tempoEnabled, inputSource: inputSource, numInputChannels: numInputChannels, - numOutputChannels: numOutputChannels, routers: routers, preChain: preChain + 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 ) } } diff --git a/Sources/LyrebirdShoeGaze/ShoeGaze.swift b/Sources/LyrebirdShoeGaze/ShoeGaze.swift index 4d74c21..95a0cd3 100644 --- a/Sources/LyrebirdShoeGaze/ShoeGaze.swift +++ b/Sources/LyrebirdShoeGaze/ShoeGaze.swift @@ -233,6 +233,76 @@ public final class ShoeGaze { 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()``. /// Routers are torn down (in reverse-creation order) by ``teardown()``. /// @@ -285,6 +355,7 @@ public final class ShoeGaze { private func allPedals() -> [Pedal] { var result: [Pedal] = [] result.append(contentsOf: preBoardPedals) + result.append(contentsOf: postBoardPedals) for board: PedalBoard in boards { result.append(contentsOf: pedals(in: board)) } @@ -525,10 +596,15 @@ public final class ShoeGaze { /// - Parameter board: A `PedalBoard` returned by `addBoard()` with pedals added. /// - Throws: `EngineAddError` if the engine rejects the master node. 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( boardOutputBusIndex: board.outputBus.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). // `board.tailNode` returns the last inserted node (any Synthesizer), which covers @@ -568,6 +644,11 @@ public final class ShoeGaze { // Bring a newly-finalized board up at the current rig volume / mute. master.rigVolumeNode.update(rigVolume) 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 @@ -991,6 +1072,10 @@ public final class ShoeGaze { } 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. // board.teardown() removes pedals from the engine and then releases buses, // so bus release only happens after all writers have been dequeued. diff --git a/Sources/LyrebirdShoeGaze/Undo/UndoCoordinator.swift b/Sources/LyrebirdShoeGaze/Undo/UndoCoordinator.swift index b0deb0b..4967113 100644 --- a/Sources/LyrebirdShoeGaze/Undo/UndoCoordinator.swift +++ b/Sources/LyrebirdShoeGaze/Undo/UndoCoordinator.swift @@ -214,12 +214,17 @@ public final class UndoCoordinator { // `.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 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-board rebuild failed: \(error)") } + 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)") } diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index dc58b61..bb8cede 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -186,6 +186,8 @@ public struct ShoeGazeBuilderView: View { @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 /// Type filter for the compact Add-Pedal sheet, hoisted so it sits in the sheet's fixed header. @@ -587,9 +589,9 @@ public struct ShoeGazeBuilderView: View { /// Hosts the compact Add-pedal palette sheet on its own node. private var paletteSheetAnchor: some View { Color.clear - // 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 }) { + // 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 } } @@ -726,6 +728,7 @@ public struct ShoeGazeBuilderView: View { ControlMappingLegend() preBoardStrip boardArea + postBoardStrip } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) // Make the undo coordinator reachable to every board / palette subview so their structural @@ -943,7 +946,7 @@ public struct ShoeGazeBuilderView: View { .foregroundStyle(Color.white) Spacer() pedalFilterMenu - Button("Done") { addToPreBoard = false; showPaletteSheet = false } + Button("Done") { addToPreBoard = false; addToPostBoard = false; showPaletteSheet = false } .fontWeight(.semibold) } .padding() @@ -956,13 +959,21 @@ public struct ShoeGazeBuilderView: View { filter: $pedalFilter, showsFilterMenu: false, onAdd: { type in - if addToPreBoard { addPrePedal(type: type) } else { addPedal(type: type) } + 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-board chain. + // Routing regions belong to a board, never the linear pre- or post-board chain. addToPreBoard = false + addToPostBoard = false performRouting(action) showPaletteSheet = false } @@ -1490,6 +1501,100 @@ public struct ShoeGazeBuilderView: View { } } + // 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 private var boardArea: some View { diff --git a/Tests/LyrebirdShoeGazeTests/MIDIControllerPCTests.swift b/Tests/LyrebirdShoeGazeTests/MIDIControllerPCTests.swift index 8908bd0..730640b 100644 --- a/Tests/LyrebirdShoeGazeTests/MIDIControllerPCTests.swift +++ b/Tests/LyrebirdShoeGazeTests/MIDIControllerPCTests.swift @@ -355,8 +355,11 @@ struct MIDIControllerPCTests { } @Test func tunedVerbAndFreezVerbExposeAPrimaryTransport() { - #expect((TunedVerbPedal() as? MIDITransportPedal)?.midiTransportName == "Capture") - #expect((FreezVerbPedal() as? MIDITransportPedal)?.midiTransportName == "Freeze") + // 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 { diff --git a/Tests/LyrebirdShoeGazeTests/PostBoardChainTests.swift b/Tests/LyrebirdShoeGazeTests/PostBoardChainTests.swift new file mode 100644 index 0000000..9d7c066 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/PostBoardChainTests.swift @@ -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") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/UndoCoordinatorTests.swift b/Tests/LyrebirdShoeGazeTests/UndoCoordinatorTests.swift index 71e4a37..9ae3ffa 100644 --- a/Tests/LyrebirdShoeGazeTests/UndoCoordinatorTests.swift +++ b/Tests/LyrebirdShoeGazeTests/UndoCoordinatorTests.swift @@ -406,6 +406,26 @@ struct UndoCoordinatorTests { #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 @Test func controlLabelsAreUniqueWithinEachGroupAcrossTheCatalogue() throws {