Compare commits
8 Commits
1f5b70edc7
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 42ad32a4d0 | |||
| 3ef09a771a | |||
| 3f05cfa416 | |||
| 4cae1e6fd0 | |||
| 24ac361c48 | |||
| 52c676605f | |||
| 10a6e122bf | |||
| 9dfadb129d |
@@ -163,7 +163,7 @@
|
||||
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 23;
|
||||
CURRENT_PROJECT_VERSION = 34;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
@@ -175,7 +175,7 @@
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
MARKETING_VERSION = 3.3;
|
||||
MARKETING_VERSION = 3.4;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
@@ -193,7 +193,7 @@
|
||||
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 23;
|
||||
CURRENT_PROJECT_VERSION = 34;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
INFOPLIST_FILE = ShoeGazeBuilder/Info.plist;
|
||||
@@ -204,7 +204,7 @@
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
MARKETING_VERSION = 3.3;
|
||||
MARKETING_VERSION = 3.4;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
@@ -366,7 +366,7 @@
|
||||
/* Begin XCRemoteSwiftPackageReference section */
|
||||
C3B10000000000000000001C /* XCRemoteSwiftPackageReference "Lyrebird" */ = {
|
||||
isa = XCRemoteSwiftPackageReference;
|
||||
repositoryURL = "https://realizedsound.mooo.com/josh/Lyrebird";
|
||||
repositoryURL = "https://git.lyrebirdsynth.net/josh/Lyrebird";
|
||||
requirement = {
|
||||
kind = versionRange;
|
||||
maximumVersion = 3.0.0;
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@
|
||||
{
|
||||
"identity" : "lyrebird",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
|
||||
"location" : "https://git.lyrebirdsynth.net/josh/Lyrebird",
|
||||
"state" : {
|
||||
"revision" : "9f244b19394f6352b0a1dcf532cf142b86e41c30",
|
||||
"version" : "2.3.0"
|
||||
|
||||
@@ -372,7 +372,7 @@
|
||||
/* Begin XCRemoteSwiftPackageReference section */
|
||||
C3C100000000000000000019 /* XCRemoteSwiftPackageReference "Lyrebird" */ = {
|
||||
isa = XCRemoteSwiftPackageReference;
|
||||
repositoryURL = "https://realizedsound.mooo.com/josh/Lyrebird";
|
||||
repositoryURL = "https://git.lyrebirdsynth.net/josh/Lyrebird";
|
||||
requirement = {
|
||||
kind = versionRange;
|
||||
maximumVersion = 3.0.0;
|
||||
|
||||
+3
-3
@@ -13,10 +13,10 @@
|
||||
{
|
||||
"identity" : "lyrebird",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
|
||||
"location" : "https://git.lyrebirdsynth.net/josh/Lyrebird",
|
||||
"state" : {
|
||||
"revision" : "b6fdee8bfc7c44d31a0a8cfe6fbd53f352dfad54",
|
||||
"version" : "2.0.0"
|
||||
"revision" : "9f244b19394f6352b0a1dcf532cf142b86e41c30",
|
||||
"version" : "2.3.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@
|
||||
{
|
||||
"identity" : "lyrebird",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
|
||||
"location" : "https://git.lyrebirdsynth.net/josh/Lyrebird",
|
||||
"state" : {
|
||||
"revision" : "9f244b19394f6352b0a1dcf532cf142b86e41c30",
|
||||
"version" : "2.3.0"
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@ let package = Package(
|
||||
.library(name: "LyrebirdShoeGazeUI", targets: ["LyrebirdShoeGazeUI"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "2.3.0"),
|
||||
.package(url: "https://git.lyrebirdsynth.net/josh/Lyrebird", from: "2.3.0"),
|
||||
],
|
||||
targets: [
|
||||
// Both targets depend on the core `Lyrebird` product AND `LyrebirdUI`.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# ShoeGaze
|
||||
|
||||
**A virtual guitar-pedalboard framework for macOS and iPadOS, built on [Lyrebird](https://realizedsound.mooo.com/josh/Lyrebird).**
|
||||
**A virtual guitar-pedalboard framework for macOS and iPadOS, built on [Lyrebird](https://git.lyrebirdsynth.net/josh/Lyrebird).**
|
||||
|
||||
ShoeGaze turns Lyrebird's real-time synthesis engine into a stompbox rig: chain modeled
|
||||
guitar pedals into one or more signal-flow boards, tweak them live with knobs and switches,
|
||||
@@ -60,7 +60,7 @@ Every pedal exposes its parameters as knobs/switches and round-trips through the
|
||||
|
||||
- macOS 15+ / iPadOS 18+ (iPad, landscape)
|
||||
- Swift 6.0 toolchain / Xcode 16+
|
||||
- [Lyrebird](https://realizedsound.mooo.com/josh/Lyrebird) 1.7.0+
|
||||
- [Lyrebird](https://git.lyrebirdsynth.net/josh/Lyrebird) 1.7.0+
|
||||
|
||||
## Packages
|
||||
|
||||
@@ -72,7 +72,7 @@ Two library products:
|
||||
Add the dependency in your `Package.swift`:
|
||||
|
||||
```swift
|
||||
.package(url: "https://realizedsound.mooo.com/josh/ShoeGaze", from: "1.0.0"),
|
||||
.package(url: "https://git.lyrebirdsynth.net/josh/ShoeGaze", from: "1.0.0"),
|
||||
```
|
||||
|
||||
## Getting started
|
||||
@@ -127,7 +127,7 @@ Open `ShoeGaze.xcworkspace` in Xcode and run a scheme from `Demo/`:
|
||||
|
||||
## Built on Lyrebird
|
||||
|
||||
ShoeGaze is a sample project for [Lyrebird](https://realizedsound.mooo.com/josh/Lyrebird), a
|
||||
ShoeGaze is a sample project for [Lyrebird](https://git.lyrebirdsynth.net/josh/Lyrebird), a
|
||||
native Swift audio-synthesis framework. Pedals are Lyrebird `Synthesizer` graphs of `Generator`
|
||||
nodes; the board/engine plumbing handles real-time-safe signal routing and scheduling.
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
{
|
||||
"identity" : "lyrebird",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
|
||||
"location" : "https://git.lyrebirdsynth.net/josh/Lyrebird",
|
||||
"state" : {
|
||||
"revision" : "9f244b19394f6352b0a1dcf532cf142b86e41c30",
|
||||
"version" : "2.3.0"
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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()
|
||||
case .looperTrack(let 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
|
||||
/// recorded (`LooperPedal.tapTrack(_:)`), matching the A/B/C/D dots.
|
||||
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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - MIDI transport
|
||||
|
||||
extension FreezVerbPedal: MIDITransportPedal {
|
||||
/// The Freeze footswitch is the mappable transport action.
|
||||
public var midiTransportName: String { "Freeze" }
|
||||
|
||||
public func toggleMIDITransport() { toggleFreeze() }
|
||||
}
|
||||
|
||||
@@ -196,9 +196,18 @@ public final class TunedVerbPedal: Pedal {
|
||||
stages: [.dual(map, sideChain: sideChain)]
|
||||
)
|
||||
|
||||
// Gate the wash by the Capture latch. Until a moment is captured there is no filter template,
|
||||
// so the reverb must be fed silence rather than the live pass-through — otherwise an
|
||||
// uncaptured TunedVerb pours the dry signal straight into the tail. `captured` is `0` until the
|
||||
// footswitch fires and is reset to `0` on every rebuild and on engine stop (`resetForRebuild`
|
||||
// / `releaseHold`), so a fresh app launch or an engine restart comes up silent with no stale
|
||||
// capture. The analysis side-chain inside `masked` keeps tracking while gated, so pressing
|
||||
// Capture still freezes the current-moment spectrum.
|
||||
let gatedIntoVerb: any ValidGeneratorInput = masked * $captured
|
||||
|
||||
// A large room for a cavernous tail; `time` sets the T60, `damp` the brightness.
|
||||
let reverb: GVerb.Audio = GVerb.Audio(
|
||||
source: masked,
|
||||
source: gatedIntoVerb,
|
||||
roomSize: roomSize,
|
||||
reverbTime: $time,
|
||||
damping: $damp,
|
||||
@@ -242,3 +251,12 @@ public final class TunedVerbPedal: Pedal {
|
||||
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() }
|
||||
}
|
||||
|
||||
@@ -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
|
||||
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,
|
||||
// `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 }(),
|
||||
// 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.
|
||||
func rebuildAllBoards(from snapshot: ShoeGazeState) throws {
|
||||
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 {
|
||||
let board: PedalBoard = try addBoard()
|
||||
board.id = boardState.id
|
||||
@@ -188,6 +198,14 @@ 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()
|
||||
}
|
||||
// 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()
|
||||
|
||||
@@ -62,6 +62,16 @@ 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]?
|
||||
|
||||
/// 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:
|
||||
@@ -83,7 +93,9 @@ public struct ShoeGazeState: Codable, Equatable {
|
||||
inputSource: InputSource? = nil,
|
||||
numInputChannels: Int? = nil,
|
||||
numOutputChannels: Int? = nil,
|
||||
routers: [ChainRouterState]? = nil
|
||||
routers: [ChainRouterState]? = nil,
|
||||
preChain: [PedalState]? = nil,
|
||||
postChain: [PedalState]? = nil
|
||||
) {
|
||||
self.version = version
|
||||
self.boards = boards
|
||||
@@ -94,6 +106,8 @@ public struct ShoeGazeState: Codable, Equatable {
|
||||
self.numInputChannels = numInputChannels
|
||||
self.numOutputChannels = numOutputChannels
|
||||
self.routers = routers
|
||||
self.preChain = preChain
|
||||
self.postChain = postChain
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
@@ -106,6 +120,8 @@ public struct ShoeGazeState: Codable, Equatable {
|
||||
case numInputChannels
|
||||
case numOutputChannels
|
||||
case routers
|
||||
case preChain
|
||||
case postChain
|
||||
}
|
||||
|
||||
/// 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.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 —
|
||||
@@ -155,5 +173,26 @@ public struct ShoeGazeState: Codable, Equatable {
|
||||
&& midiMap == other.midiMap
|
||||
&& 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
|
||||
/// 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
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -192,11 +192,117 @@ 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() }
|
||||
}
|
||||
|
||||
// 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()``.
|
||||
///
|
||||
@@ -248,6 +354,8 @@ 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)
|
||||
result.append(contentsOf: postBoardPedals)
|
||||
for board: PedalBoard in boards {
|
||||
result.append(contentsOf: pedals(in: board))
|
||||
}
|
||||
@@ -310,38 +418,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 +489,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(_:)`.
|
||||
@@ -396,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
|
||||
@@ -439,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
|
||||
@@ -837,9 +1047,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,16 +1067,15 @@ public final class ShoeGaze {
|
||||
}
|
||||
globalTestBus = nil
|
||||
|
||||
for passThrough: HardwareInputPassThrough in inputPassThroughs {
|
||||
engine.remove(passThrough)
|
||||
}
|
||||
inputPassThroughs.removeAll()
|
||||
|
||||
for master: BoardOutputMaster in outputMasters {
|
||||
engine.remove(master)
|
||||
}
|
||||
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.
|
||||
|
||||
@@ -207,6 +207,31 @@ 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 }
|
||||
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.
|
||||
let liveValues: [UUID: PedalState] = currentPedalStatesByID(shoeGaze)
|
||||
let targetIDs: Set<UUID> = Set(state.boards.map { $0.id })
|
||||
|
||||
@@ -63,6 +63,12 @@ public struct BoardFlowView: View {
|
||||
private let shoeGaze: ShoeGaze
|
||||
private let boardIndex: Int
|
||||
|
||||
/// When `true`, the view sizes to its content height and scrolls only horizontally, so it can sit
|
||||
/// inside an outer vertical scroller (the pre-board → board → post-board page) without a nested
|
||||
/// vertical scroll. When `false` (the default), it fills the available height and centres the
|
||||
/// chain, adding a vertical scroll only for tall parallel splits.
|
||||
private let sizesToContent: Bool
|
||||
|
||||
/// Undo coordinator injected by ``ShoeGazeBuilderView``; `nil` in lightweight hosts (previews),
|
||||
/// where edits run directly without recording history.
|
||||
@Environment(UndoCoordinator.self) private var undo: UndoCoordinator?
|
||||
@@ -74,9 +80,10 @@ public struct BoardFlowView: View {
|
||||
/// lanes exceed the viewport height (tall parallel splits). Otherwise scrolling stays horizontal.
|
||||
@State private var contentHeight: CGFloat = 0
|
||||
|
||||
public init(shoeGaze: ShoeGaze, boardIndex: Int) {
|
||||
public init(shoeGaze: ShoeGaze, boardIndex: Int, sizesToContent: Bool = false) {
|
||||
self.shoeGaze = shoeGaze
|
||||
self.boardIndex = boardIndex
|
||||
self.sizesToContent = sizesToContent
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
@@ -91,31 +98,45 @@ public struct BoardFlowView: View {
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func flow(board: PedalBoard) -> some View {
|
||||
let stages: [StageModel] = stageModels(board: board)
|
||||
return GeometryReader { proxy in
|
||||
let viewportHeight: CGFloat = proxy.size.height
|
||||
// Lock to horizontal, adding the vertical axis only when the chain is taller than the
|
||||
// viewport (deep parallel splits) so it can be reached instead of clipped.
|
||||
let axes: Axis.Set = contentHeight > viewportHeight + BoardFlowView.verticalScrollSlack
|
||||
? [.horizontal, .vertical]
|
||||
: .horizontal
|
||||
ScrollView(axes, showsIndicators: true) {
|
||||
// The spacers centre the chain vertically when it is shorter than the viewport; when
|
||||
// it overflows, the min-height floor is already exceeded so they collapse to zero and
|
||||
// the chain scrolls. Pedals keep their intrinsic height either way — the window no
|
||||
// longer stretches them.
|
||||
VStack(spacing: 0) {
|
||||
Spacer(minLength: 0)
|
||||
chainRow(board: board, stages: stages)
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
.frame(minHeight: viewportHeight)
|
||||
if sizesToContent {
|
||||
// One-scroller mode: the board is only as tall as its chain and scrolls horizontally,
|
||||
// so the outer vertical scroller flows pre-board → board → post-board as one page with
|
||||
// no nested vertical scroll. A tall parallel split simply makes the page taller.
|
||||
ScrollView(.horizontal, showsIndicators: true) {
|
||||
chainRow(board: board, stages: stages)
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.frame(height: contentHeight > 0 ? contentHeight : nil)
|
||||
.onPreferenceChange(BoardFlowContentHeightKey.self) { height in
|
||||
contentHeight = height
|
||||
}
|
||||
} else {
|
||||
GeometryReader { proxy in
|
||||
let viewportHeight: CGFloat = proxy.size.height
|
||||
// Lock to horizontal, adding the vertical axis only when the chain is taller than the
|
||||
// viewport (deep parallel splits) so it can be reached instead of clipped.
|
||||
let axes: Axis.Set = contentHeight > viewportHeight + BoardFlowView.verticalScrollSlack
|
||||
? [.horizontal, .vertical]
|
||||
: .horizontal
|
||||
ScrollView(axes, showsIndicators: true) {
|
||||
// The spacers centre the chain vertically when it is shorter than the viewport; when
|
||||
// it overflows, the min-height floor is already exceeded so they collapse to zero and
|
||||
// the chain scrolls. Pedals keep their intrinsic height either way — the window no
|
||||
// longer stretches them.
|
||||
VStack(spacing: 0) {
|
||||
Spacer(minLength: 0)
|
||||
chainRow(board: board, stages: stages)
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
.frame(minHeight: viewportHeight)
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.onPreferenceChange(BoardFlowContentHeightKey.self) { height in
|
||||
contentHeight = height
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -191,6 +191,15 @@ struct PedalMappingStrip: View {
|
||||
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.
|
||||
if pedal is LooperPedal {
|
||||
for kind: MIDIMap.PedalActionKind in loopedActionOrder {
|
||||
@@ -248,6 +257,8 @@ struct PedalMappingStrip: View {
|
||||
case .looperSyncToggle: return "Sync"
|
||||
case .looperReset: return "Reset"
|
||||
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"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,6 +90,14 @@ public struct HelpView: View {
|
||||
+ "insert before it; tap a palette pedal to append.",
|
||||
"Add boards with +. Solo / Blend / All choose which boards you hear; XFade sets the "
|
||||
+ "crossfade time; each board has S (solo) and B (bypass).",
|
||||
"Pre-board is one chain that processes your input once, before the board split, and "
|
||||
+ "feeds every board — good for a shared tuner, compressor, or noise gate. Tap "
|
||||
+ "+ Pre-board to start it; it hides when empty.",
|
||||
"Post-board is one chain after all boards are mixed down — good for a global reverb, "
|
||||
+ "a limiter, or a final EQ across the whole rig. Tap + Post-board to start it; it "
|
||||
+ "hides when empty.",
|
||||
"Pre-board, the boards, and post-board scroll together top-to-bottom as one signal "
|
||||
+ "path; each board's chain scrolls sideways.",
|
||||
"The Rigs sidebar lists saved rigs, with New, Save, Save As, Duplicate, Rename, "
|
||||
+ "Delete, and Erase All.",
|
||||
"Reorder rigs into a set list by dragging a row, or via each rig's Move Up / "
|
||||
|
||||
@@ -120,6 +120,14 @@ public struct MIDIMappingSheet: View {
|
||||
id: "sw-pb-\(pedal.id)",
|
||||
action: .pedalBypass(pedalID: pedal.id),
|
||||
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.
|
||||
if pedal is LooperPedal {
|
||||
var looperActions: [(String, String, MIDIMap.PedalActionKind)] = [
|
||||
|
||||
@@ -184,6 +184,10 @@ 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
|
||||
/// 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.
|
||||
@@ -585,7 +589,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/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
|
||||
}
|
||||
}
|
||||
@@ -720,7 +726,18 @@ public struct ShoeGazeBuilderView: View {
|
||||
}
|
||||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||||
ControlMappingLegend()
|
||||
boardArea
|
||||
// Pre-board, the board canvas and post-board share a single vertical scroller, so the whole
|
||||
// signal path reads top-to-bottom as one page (on macOS and iOS alike) instead of pinning
|
||||
// the board and clipping the pre/post strips.
|
||||
ScrollView(.vertical, showsIndicators: true) {
|
||||
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) {
|
||||
preBoardStrip
|
||||
boardArea
|
||||
postBoardStrip
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .topLeading)
|
||||
}
|
||||
.frame(maxHeight: .infinity)
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||||
// Make the undo coordinator reachable to every board / palette subview so their structural
|
||||
@@ -938,7 +955,7 @@ public struct ShoeGazeBuilderView: View {
|
||||
.foregroundStyle(Color.white)
|
||||
Spacer()
|
||||
pedalFilterMenu
|
||||
Button("Done") { showPaletteSheet = false }
|
||||
Button("Done") { addToPreBoard = false; addToPostBoard = false; showPaletteSheet = false }
|
||||
.fontWeight(.semibold)
|
||||
}
|
||||
.padding()
|
||||
@@ -950,8 +967,25 @@ 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 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()
|
||||
}
|
||||
@@ -1382,16 +1416,202 @@ 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
|
||||
|
||||
private var boardArea: some View {
|
||||
// Vertically center the signal-flow board in the available space.
|
||||
VStack(spacing: 0) {
|
||||
Spacer(minLength: 0)
|
||||
BoardFlowView(shoeGaze: shoeGaze, boardIndex: clampedBoardIndex)
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
// Content-sized so it flows inside the shared pre/board/post vertical scroller (scrolls
|
||||
// horizontally for a long chain; a tall parallel split grows the page). No vertical centering —
|
||||
// the board sits in signal-flow order between the pre-board and post-board strips.
|
||||
BoardFlowView(shoeGaze: shoeGaze, boardIndex: clampedBoardIndex, sizesToContent: true)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
|
||||
/// Performs a routing action from the palette against the selected board.
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import SwiftUI
|
||||
import LyrebirdUI
|
||||
import LyrebirdSynth
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// A vertical fader bound to a single ``UIParamNode``.
|
||||
///
|
||||
|
||||
@@ -353,4 +353,34 @@ struct MIDIControllerPCTests {
|
||||
#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")
|
||||
}
|
||||
}
|
||||
@@ -188,47 +188,87 @@ struct TunedVerbPedalTests {
|
||||
}
|
||||
|
||||
@Test func panShiftsTheLeftLeg() throws {
|
||||
// Fully wet, the output follows the panned wash. Hard left fills the left leg; hard right
|
||||
// nearly empties it. (Tests exercise the left output leg; the right is board-wired live.)
|
||||
let hardLeft: [Float] = try render(duration: 0.6) { pedal in pedal.mix = 1.0; pedal.pan = -1.0 }
|
||||
let hardRight: [Float] = try render(duration: 0.6) { pedal in pedal.mix = 1.0; pedal.pan = 1.0 }
|
||||
let leftRMS: Double = rms(hardLeft, loFrame: 0, hiFrame: hardLeft.count)
|
||||
let rightRMS: Double = rms(hardRight, loFrame: 0, hiFrame: hardRight.count)
|
||||
// Fully wet, the output follows the panned wash — but the wash only exists after a capture, so
|
||||
// capture early, then measure. Hard left fills the left leg; hard right nearly empties it.
|
||||
// (`stepRender` returns the left output bus; the right is board-wired live.)
|
||||
let blockSize: Int = 512
|
||||
let totalFrames: Int = Int(0.8 * sampleRate)
|
||||
let captureFrame: Int = Int(0.1 * sampleRate)
|
||||
let windowLo: Int = Int(0.4 * sampleRate)
|
||||
|
||||
func leftLeg(pan: Double) throws -> [Float] {
|
||||
var captured: Bool = false
|
||||
return try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in
|
||||
pedal.mix = 1.0; pedal.pan = pan; pedal.time = 2.0
|
||||
} onFrame: { frame, _, pedal in
|
||||
if frame >= captureFrame, !captured { pedal.toggleCapture(); captured = true }
|
||||
}
|
||||
}
|
||||
|
||||
let hardLeft: [Float] = try leftLeg(pan: -1.0)
|
||||
let hardRight: [Float] = try leftLeg(pan: 1.0)
|
||||
let leftRMS: Double = rms(hardLeft, loFrame: windowLo, hiFrame: hardLeft.count)
|
||||
let rightRMS: Double = rms(hardRight, loFrame: windowLo, hiFrame: hardRight.count)
|
||||
#expect(leftRMS > rightRMS * 3.0,
|
||||
"panning hard left should fill the left leg far more than hard right: L \(leftRMS) vs R \(rightRMS)")
|
||||
}
|
||||
|
||||
@Test func captureLocksTheFilterSoAChangedInputIsShapedDifferently() throws {
|
||||
// Capture the filter on tone A, then morph the input to tone B. A locked filter (shaped by A)
|
||||
// masks B differently than a filter that keeps tracking the live input — so the two renders
|
||||
// diverge once the input has changed.
|
||||
@Test func wetIsSilentUntilCaptureThenAudible() throws {
|
||||
// Core contract: with no captured moment there is no filter template, so a fully-wet TunedVerb
|
||||
// must output silence — not the live pass-through poured into the reverb. After the Capture
|
||||
// footswitch fires, the wash appears. Fully wet (mix 1.0) so the only output is the gated wash.
|
||||
let blockSize: Int = 512
|
||||
let totalFrames: Int = Int(1.4 * sampleRate)
|
||||
let captureFrame: Int = Int(0.5 * sampleRate)
|
||||
|
||||
var captured: Bool = false
|
||||
let out: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in
|
||||
pedal.mix = 1.0; pedal.time = 1.0
|
||||
} onFrame: { frame, _, pedal in
|
||||
if frame >= captureFrame, !captured { pedal.toggleCapture(); captured = true }
|
||||
}
|
||||
|
||||
// Before capture: fully-wet output must be silent (reverb fed zero).
|
||||
let preRMS: Double = rms(out, loFrame: 0, hiFrame: captureFrame - blockSize)
|
||||
// Well after capture (give the reverb time to build): audible.
|
||||
let postRMS: Double = rms(out, loFrame: captureFrame + Int(0.4 * sampleRate), hiFrame: out.count)
|
||||
#expect(preRMS < 1.0e-6, "an uncaptured fully-wet TunedVerb must be silent, got \(preRMS)")
|
||||
#expect(postRMS > 1.0e-4, "after Capture the wash must be audible, got \(postRMS)")
|
||||
}
|
||||
|
||||
@Test func captureLocksTheFilterSoAChangedInputIsShapedDifferently() throws {
|
||||
// Which moment you capture determines the filter. Capture on tone A then morph to B (the wash
|
||||
// on B is shaped by A's spectrum) versus morph to B first then capture on B (shaped by B's own
|
||||
// spectrum). Both are audible — the wash exists only after a capture — but the two locked
|
||||
// templates mask the ongoing tone-B input differently, so the renders diverge.
|
||||
let blockSize: Int = 512
|
||||
let totalFrames: Int = Int(1.4 * sampleRate)
|
||||
let captureFrame: Int = Int(0.4 * sampleRate)
|
||||
let morphFrame: Int = Int(0.6 * sampleRate)
|
||||
let windowLo: Int = Int(0.95 * sampleRate)
|
||||
let windowHi: Int = Int(1.35 * sampleRate)
|
||||
|
||||
var captured: Bool = false
|
||||
let locked: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in
|
||||
// Locked on tone A, then morphed to B.
|
||||
var capturedA: Bool = false
|
||||
let lockedOnA: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in
|
||||
pedal.mix = 1.0; pedal.time = 3.0
|
||||
} onFrame: { frame, source, pedal in
|
||||
if frame >= captureFrame, !captured { pedal.toggleCapture(); captured = true }
|
||||
if frame >= morphFrame { source.morph = 1.0 } // switch to tone B
|
||||
if frame >= Int(0.4 * sampleRate), !capturedA { pedal.toggleCapture(); capturedA = true }
|
||||
if frame >= Int(0.6 * sampleRate) { source.morph = 1.0 } // switch to tone B after capture
|
||||
}
|
||||
|
||||
let tracking: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in
|
||||
// Morphed to B first, then locked on B.
|
||||
var capturedB: Bool = false
|
||||
let lockedOnB: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in
|
||||
pedal.mix = 1.0; pedal.time = 3.0
|
||||
} onFrame: { frame, source, _ in
|
||||
// Never capture; morph at the same frame.
|
||||
if frame >= morphFrame { source.morph = 1.0 }
|
||||
} onFrame: { frame, source, pedal in
|
||||
if frame >= Int(0.2 * sampleRate) { source.morph = 1.0 } // switch to tone B first
|
||||
if frame >= Int(0.4 * sampleRate), !capturedB { pedal.toggleCapture(); capturedB = true }
|
||||
}
|
||||
|
||||
let signal: Double = rms(tracking, loFrame: windowLo, hiFrame: windowHi)
|
||||
let diff: Double = rmsDiff(locked, tracking, loFrame: windowLo, hiFrame: windowHi)
|
||||
#expect(signal > 1.0e-4, "control render should be audible on tone B, got \(signal)")
|
||||
let signal: Double = rms(lockedOnB, loFrame: windowLo, hiFrame: windowHi)
|
||||
let diff: Double = rmsDiff(lockedOnA, lockedOnB, loFrame: windowLo, hiFrame: windowHi)
|
||||
#expect(signal > 1.0e-4, "a captured render should be audible on tone B, got \(signal)")
|
||||
#expect(diff > signal * 0.25,
|
||||
"a captured filter should shape the changed input differently: diff \(diff) vs signal \(signal)")
|
||||
"locking a different moment should shape the input differently: diff \(diff) vs signal \(signal)")
|
||||
}
|
||||
|
||||
// MARK: - Bypass
|
||||
|
||||
@@ -386,6 +386,46 @@ 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: - 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 {
|
||||
|
||||
Reference in New Issue
Block a user