Add mono→stereo routing to PedalBoard
Introduce chain width propagation (mono=1 / stereo=2, capped at 2), represented as a pair of mono buses to reuse existing infrastructure. - Pedal: width-parameterized build() with channelKind (mono / widener / stereoNative); effect() runs per channel for auto-stereoize, shared knobs. - PedalBoard: width tracking, add() dispatch, mergeToMono(), splitStereo()/ collectStereo() with four route modes (stereo / leftOnly / rightOnly / bypass), centered solo, click-free lagged gains. - BoardOutputMaster: width-aware (Pan2 mono, direct L/R stereo). - New routing nodes: StereoSplitter, StereoRouteCollector, StereoSplitSection. - Reference pedals: OctaveUpSplitterPedal (widener), PingPongDelayPedal (stereo-native). - 12 stereo-routing tests; full suite 108/108. Design: docs/stereo-routing-design.md Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -40,29 +40,52 @@ final class BoardOutputMaster: SynthesizerBase {
|
||||
|
||||
// MARK: - Routing
|
||||
|
||||
/// Left / mono board output bus index.
|
||||
private let boardOutputBusIndex: Int
|
||||
|
||||
/// Right board output bus index when the board tail is stereo (width 2), else `nil`.
|
||||
/// When set, the left bus drives hardware 0 and the right bus drives hardware 1 directly,
|
||||
/// bypassing the mono `Pan2` spread.
|
||||
private let boardOutputBusRightIndex: Int?
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Pan position for the board in the stereo field. Centre = 0.0.
|
||||
/// Pan position for the board in the stereo field. Centre = 0.0. Used only for a mono board.
|
||||
private let stereoPan: Double = 0.0
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
init(boardOutputBusIndex: Int) {
|
||||
/// Creates a board output master.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - boardOutputBusIndex: Left / mono board output bus index.
|
||||
/// - 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).
|
||||
init(boardOutputBusIndex: Int, boardOutputBusRightIndex: Int? = nil) {
|
||||
self.boardOutputBusIndex = boardOutputBusIndex
|
||||
self.boardOutputBusRightIndex = boardOutputBusRightIndex
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - Build
|
||||
|
||||
override func build() {
|
||||
let boardOut: In.Audio = input(bus: boardOutputBusIndex)
|
||||
// Lag the board-select gain so switching boards crossfades over `crossfadeTime`
|
||||
// seconds rather than clicking. The user master-gain knob is applied directly.
|
||||
let smoothedSelect: Lag.Control = Lag.Control(input: $selectGain, time: $crossfadeTime)
|
||||
let gained: any ValidGeneratorInput = (boardOut * smoothedSelect) * $masterGain
|
||||
// Pan2 spreads the mono pedalboard output to stereo hardware buses 0 + 1.
|
||||
output(bus: 0, source: Pan2(input: gained, pan: stereoPan))
|
||||
|
||||
let boardOutLeft: In.Audio = input(bus: boardOutputBusIndex)
|
||||
let gainedLeft: any ValidGeneratorInput = (boardOutLeft * smoothedSelect) * $masterGain
|
||||
|
||||
if let rightIndex: Int = boardOutputBusRightIndex {
|
||||
// Stereo board: left tail → hardware 0, right tail → hardware 1, no pan spread.
|
||||
let boardOutRight: In.Audio = input(bus: rightIndex)
|
||||
let gainedRight: any ValidGeneratorInput = (boardOutRight * smoothedSelect) * $masterGain
|
||||
output(bus: 0, source: gainedLeft)
|
||||
output(bus: 1, source: gainedRight)
|
||||
} else {
|
||||
// Mono board: Pan2 spreads the mono output to stereo hardware buses 0 + 1.
|
||||
output(bus: 0, source: Pan2(input: gainedLeft, pan: stereoPan))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,12 +64,32 @@ open class Pedal: SynthesizerBase {
|
||||
/// Human-readable name for the pedal (e.g. "Overdrive", "Delay").
|
||||
public let displayName: String
|
||||
|
||||
/// Index of the audio bus from which this pedal reads its dry input.
|
||||
/// Index of the audio bus from which this pedal reads its dry input (channel 0 /
|
||||
/// left / mono).
|
||||
public internal(set) var inputBus: Int
|
||||
|
||||
/// Index of the audio bus to which this pedal writes its output.
|
||||
/// Index of the audio bus to which this pedal writes its output (channel 0 /
|
||||
/// left / mono).
|
||||
public internal(set) var outputBus: Int
|
||||
|
||||
/// Right-channel input bus index, or `nil` for a mono input. When the board places
|
||||
/// this pedal in a stereo (width-2) region it sets this to the right tail bus. A
|
||||
/// `stereoNative` pedal entering a mono region leaves this `nil` and broadcasts the
|
||||
/// mono input to both channels.
|
||||
public internal(set) var inputBusRight: Int?
|
||||
|
||||
/// Right-channel output bus index, or `nil` for a mono output. Non-nil exactly when
|
||||
/// the pedal is part of a stereo region; `build()` emits a second channel only when
|
||||
/// this is set.
|
||||
public internal(set) var outputBusRight: Int?
|
||||
|
||||
/// Declares this pedal's channel topology. Defaults to ``PedalChannelKind/mono``.
|
||||
/// Override in a widener or stereo-native subclass.
|
||||
open var channelKind: PedalChannelKind { .mono }
|
||||
|
||||
/// `true` when the board has placed this pedal in a stereo (width-2) region.
|
||||
public var isStereo: Bool { outputBusRight != nil }
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Lag time constant in seconds (60 dB convergence) for the bypass crossfade.
|
||||
@@ -150,13 +170,53 @@ open class Pedal: SynthesizerBase {
|
||||
dry
|
||||
}
|
||||
|
||||
/// Returns the two distinct wet outputs for a ``PedalChannelKind/widener`` pedal.
|
||||
///
|
||||
/// Called once with the mono dry input; the returned pair becomes the left and right
|
||||
/// wet signals of the now-stereo region. The default applies `effect(_:)` to both,
|
||||
/// which is rarely useful — widener subclasses override this to produce genuinely
|
||||
/// different channels (e.g. dry left, octave-up right).
|
||||
///
|
||||
/// - Parameter dry: The dry mono signal read from `inputBus`.
|
||||
/// - Returns: The left and right wet signals.
|
||||
open func wideEffect(_ dry: any ValidGeneratorInput)
|
||||
-> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) {
|
||||
(effect(dry), effect(dry))
|
||||
}
|
||||
|
||||
/// Returns the coupled stereo wet outputs for a ``PedalChannelKind/stereoNative`` pedal.
|
||||
///
|
||||
/// Called with both dry channels; the returned pair becomes the wet left and right
|
||||
/// signals. The default applies `effect(_:)` per channel independently — stereo-native
|
||||
/// subclasses override this to introduce cross-channel coupling (e.g. ping-pong feedback).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - left: The left dry channel.
|
||||
/// - right: The right dry channel (equals `left` when the pedal entered a mono region).
|
||||
/// - Returns: The left and right wet signals.
|
||||
open func stereoEffect(
|
||||
left: any ValidGeneratorInput,
|
||||
right: any ValidGeneratorInput
|
||||
) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) {
|
||||
(effect(left), effect(right))
|
||||
}
|
||||
|
||||
// MARK: - Build
|
||||
|
||||
/// Builds the signal graph: dry → effect → wet/dry blend → bypass switch → output.
|
||||
public override func build() {
|
||||
let dry: In.Audio = input(bus: inputBus)
|
||||
let wet: any ValidGeneratorInput = effect(dry)
|
||||
|
||||
/// Builds the signal graph for one channel: dry → wet/dry blend → bypass switch → × level.
|
||||
///
|
||||
/// Returns the final post-`level` source for the channel. The `mix`, `bypass`, and `level`
|
||||
/// `@UIParam` nodes are shared across channels; each channel gets its own `Lag.Control`
|
||||
/// for the bypass crossfade so smoothing is per-channel state driven by the same target.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - dry: The dry signal for this channel.
|
||||
/// - wet: The processed signal for this channel.
|
||||
/// - Returns: The channel's output source (post mix/bypass/level).
|
||||
private func applyChain(
|
||||
dry: any ValidGeneratorInput,
|
||||
wet: any ValidGeneratorInput
|
||||
) -> any ValidGeneratorInput {
|
||||
// Map mix [0, 1] → pan [-1, +1] for CrossFade (−1 = full inA/dry, +1 = full inB/wet).
|
||||
let mixPan: any ValidGeneratorInput = ($mix * bipolarSpan) - bipolarOffset
|
||||
|
||||
@@ -183,6 +243,40 @@ open class Pedal: SynthesizerBase {
|
||||
pan: bypassPan
|
||||
)
|
||||
|
||||
output(bus: outputBus, source: switched * $level)
|
||||
return switched * $level
|
||||
}
|
||||
|
||||
/// Builds the pedal's signal graph, dispatching on ``channelKind`` and emitting a second
|
||||
/// channel only when `outputBusRight` is set (a stereo region).
|
||||
public override func build() {
|
||||
switch channelKind {
|
||||
case .mono:
|
||||
// One independent `effect(_:)` graph per output channel; shared knobs.
|
||||
let dryLeft: In.Audio = input(bus: inputBus)
|
||||
output(bus: outputBus, source: applyChain(dry: dryLeft, wet: effect(dryLeft)))
|
||||
if let rightOut: Int = outputBusRight {
|
||||
// Broadcast the mono input to the right channel when no right input exists.
|
||||
let dryRight: In.Audio = input(bus: inputBusRight ?? inputBus)
|
||||
output(bus: rightOut, source: applyChain(dry: dryRight, wet: effect(dryRight)))
|
||||
}
|
||||
|
||||
case .widener:
|
||||
let dry: In.Audio = input(bus: inputBus)
|
||||
let wet: (left: any ValidGeneratorInput, right: any ValidGeneratorInput) = wideEffect(dry)
|
||||
output(bus: outputBus, source: applyChain(dry: dry, wet: wet.left))
|
||||
if let rightOut: Int = outputBusRight {
|
||||
output(bus: rightOut, source: applyChain(dry: dry, wet: wet.right))
|
||||
}
|
||||
|
||||
case .stereoNative:
|
||||
let dryLeft: In.Audio = input(bus: inputBus)
|
||||
let dryRight: In.Audio = input(bus: inputBusRight ?? inputBus)
|
||||
let wet: (left: any ValidGeneratorInput, right: any ValidGeneratorInput) =
|
||||
stereoEffect(left: dryLeft, right: dryRight)
|
||||
output(bus: outputBus, source: applyChain(dry: dryLeft, wet: wet.left))
|
||||
if let rightOut: Int = outputBusRight {
|
||||
output(bus: rightOut, source: applyChain(dry: dryRight, wet: wet.right))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,10 +65,21 @@ public final class PedalBoard {
|
||||
/// All pedals in order of insertion (signal-flow order) in the main chain (not branches).
|
||||
public private(set) var pedals: [Pedal] = []
|
||||
|
||||
/// The bus that the last node in the chain writes to.
|
||||
/// The bus that the last node in the chain writes to (left / mono tail).
|
||||
/// Before any node is added, this is `headBus` (the board is a pass-through).
|
||||
public private(set) var outputBus: AudioBus
|
||||
|
||||
/// The right-channel tail bus when the chain is stereo (``width`` == 2), else `nil`.
|
||||
/// Set by a widener, a stereo-native pedal, an auto-stereoized pedal, or `collectStereo(_:)`;
|
||||
/// cleared by `mergeToMono()`.
|
||||
public private(set) var outputBusRight: AudioBus?
|
||||
|
||||
/// Current channel width of the chain tail: `1` = mono, `2` = stereo. Capped at 2.
|
||||
public private(set) var width: Int = 1
|
||||
|
||||
/// All stereo split sections created via `splitStereo()` (for inspection / UI binding).
|
||||
public private(set) var stereoSplitSections: [StereoSplitSection] = []
|
||||
|
||||
/// The node that writes the head bus (e.g. a `TestLoopSource` or input pass-through).
|
||||
/// Set by `ShoeGaze` after adding the input source. When non-nil, the first `add(_:)`
|
||||
/// call chains the first pedal after this node automatically (no `after:` arg needed).
|
||||
@@ -158,29 +169,223 @@ public final class PedalBoard {
|
||||
/// - `BusAllocatorError.noFreeBus` if no mono audio bus is available for output.
|
||||
/// - `EngineAddError` if the engine rejects the add (e.g. queue full, double-add).
|
||||
public func add(_ pedal: Pedal, after predecessor: (any Synthesizer)? = nil) throws {
|
||||
let pedalInputBus: AudioBus = outputBus
|
||||
let pedalOutputBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
allocatedBuses.append(pedalOutputBus)
|
||||
|
||||
pedal.inputBus = pedalInputBus.index
|
||||
pedal.outputBus = pedalOutputBus.index
|
||||
pedal.sampleRate = engine.sampleRate
|
||||
|
||||
// Maintain evaluation order: each node evaluates immediately after the previous.
|
||||
// `lastNode` tracks the most recently inserted node (pedal, splitter, or merger).
|
||||
// Falls back to the caller-supplied `predecessor` or `headInputNode` for the first
|
||||
// node. If none is available, plain add is used as a last resort.
|
||||
if let previous: any Synthesizer = lastNode {
|
||||
try engine.add(pedal, position: .after(previous))
|
||||
} else if let pred: any Synthesizer = predecessor ?? headInputNode {
|
||||
try engine.add(pedal, position: .after(pred))
|
||||
} else {
|
||||
try engine.add(pedal)
|
||||
// Each arm configures the pedal's buses, inserts it, advances the tail, and only then
|
||||
// records it in `pedals` — so a pedal is never tracked unless it was fully wired and
|
||||
// added to the engine.
|
||||
switch pedal.channelKind {
|
||||
case .mono:
|
||||
if width == 1 {
|
||||
// Mono region: one input, one output. Behaviour is identical to the original
|
||||
// single-bus path.
|
||||
let outLeft: AudioBus = try allocateInterNodeBus()
|
||||
pedal.inputBus = outputBus.index
|
||||
pedal.inputBusRight = nil
|
||||
pedal.outputBus = outLeft.index
|
||||
pedal.outputBusRight = nil
|
||||
try insertNode(pedal, after: predecessor)
|
||||
advanceTail(left: outLeft, right: nil, width: 1)
|
||||
} else {
|
||||
// Stereo region: auto-stereoize. The pedal runs `effect(_:)` per channel into
|
||||
// two new buses — one logical pedal, two independent DSP graphs, shared knobs.
|
||||
let rightTail: AudioBus = try requireRightTail()
|
||||
let outLeft: AudioBus = try allocateInterNodeBus()
|
||||
let outRight: AudioBus = try allocateInterNodeBus()
|
||||
pedal.inputBus = outputBus.index
|
||||
pedal.inputBusRight = rightTail.index
|
||||
pedal.outputBus = outLeft.index
|
||||
pedal.outputBusRight = outRight.index
|
||||
try insertNode(pedal, after: predecessor)
|
||||
advanceTail(left: outLeft, right: outRight, width: 2)
|
||||
}
|
||||
|
||||
case .widener:
|
||||
// 1 → 2. Only valid from a mono tail; width is capped at 2.
|
||||
guard width == 1 else { throw ShoeGazeError.stereoWidthExceeded }
|
||||
let outLeft: AudioBus = try allocateInterNodeBus()
|
||||
let outRight: AudioBus = try allocateInterNodeBus()
|
||||
pedal.inputBus = outputBus.index
|
||||
pedal.inputBusRight = nil
|
||||
pedal.outputBus = outLeft.index
|
||||
pedal.outputBusRight = outRight.index
|
||||
try insertNode(pedal, after: predecessor)
|
||||
advanceTail(left: outLeft, right: outRight, width: 2)
|
||||
|
||||
case .stereoNative:
|
||||
// 2 → 2 with cross-channel coupling. From a mono tail the input broadcasts to both
|
||||
// channels (right input left nil); from a stereo tail it reads both tails.
|
||||
let rightInput: Int? = (width == 2) ? try requireRightTail().index : nil
|
||||
let outLeft: AudioBus = try allocateInterNodeBus()
|
||||
let outRight: AudioBus = try allocateInterNodeBus()
|
||||
pedal.inputBus = outputBus.index
|
||||
pedal.inputBusRight = rightInput
|
||||
pedal.outputBus = outLeft.index
|
||||
pedal.outputBusRight = outRight.index
|
||||
try insertNode(pedal, after: predecessor)
|
||||
advanceTail(left: outLeft, right: outRight, width: 2)
|
||||
}
|
||||
|
||||
pedals.append(pedal)
|
||||
lastNode = pedal
|
||||
outputBus = pedalOutputBus
|
||||
}
|
||||
|
||||
/// Returns the right tail bus, enforcing the `width == 2 ⟺ outputBusRight != nil` invariant.
|
||||
/// Throws rather than crashing if the invariant is ever violated by a coding error.
|
||||
private func requireRightTail() throws -> AudioBus {
|
||||
guard let rightTail: AudioBus = outputBusRight else {
|
||||
throw ShoeGazeError.stereoWidthExceeded
|
||||
}
|
||||
return rightTail
|
||||
}
|
||||
|
||||
// MARK: - Stereo width helpers
|
||||
|
||||
/// Allocates a mono inter-node bus and tracks it for release on teardown.
|
||||
private func allocateInterNodeBus() throws -> AudioBus {
|
||||
let bus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
allocatedBuses.append(bus)
|
||||
return bus
|
||||
}
|
||||
|
||||
/// Inserts a node into the engine maintaining evaluation order, then records it as `lastNode`.
|
||||
///
|
||||
/// Inserts `.after(lastNode)` when a previous node exists, else `.after` the caller-supplied
|
||||
/// predecessor or `headInputNode`, else a plain add as a last resort.
|
||||
private func insertNode(_ node: any Synthesizer, after predecessor: (any Synthesizer)?) throws {
|
||||
if let previous: any Synthesizer = lastNode {
|
||||
try engine.add(node, position: .after(previous))
|
||||
} else if let pred: any Synthesizer = predecessor ?? headInputNode {
|
||||
try engine.add(node, position: .after(pred))
|
||||
} else {
|
||||
try engine.add(node)
|
||||
}
|
||||
lastNode = node
|
||||
}
|
||||
|
||||
/// Advances the chain tail to the given bus pair and width.
|
||||
private func advanceTail(left: AudioBus, right: AudioBus?, width: Int) {
|
||||
self.outputBus = left
|
||||
self.outputBusRight = right
|
||||
self.width = width
|
||||
}
|
||||
|
||||
/// Collapses a stereo (width-2) tail back to mono by summing the two tails (×0.5 each)
|
||||
/// through a ``Merger``. No-op when the chain is already mono.
|
||||
///
|
||||
/// - Throws:
|
||||
/// - `BusAllocatorError.noFreeBus` if no mono audio bus is available.
|
||||
/// - `EngineAddError` if the engine rejects the merger add.
|
||||
public func mergeToMono() throws {
|
||||
guard width == 2, let rightTail: AudioBus = outputBusRight else { return }
|
||||
let monoBus: AudioBus = try allocateInterNodeBus()
|
||||
let merger: Merger = Merger(
|
||||
inputBusA: outputBus.index,
|
||||
inputBusB: rightTail.index,
|
||||
outputBus: monoBus.index
|
||||
)
|
||||
// Sum with equal half-gains so two correlated channels do not double in level.
|
||||
merger.levelA = 0.5
|
||||
merger.levelB = 0.5
|
||||
try insertNode(merger, after: nil)
|
||||
routingNodes.append(merger)
|
||||
advanceTail(left: monoBus, right: nil, width: 1)
|
||||
}
|
||||
|
||||
// MARK: - Stereo split
|
||||
|
||||
/// Fans the current mono tail into two independently authored branch chains that become the
|
||||
/// stereo output pair, plus a clean dry tap for the `bypass` route.
|
||||
///
|
||||
/// Add pedals via `section.left.add(_:)` / `section.right.add(_:)`, then call
|
||||
/// `collectStereo(_:)` to wire the route collector and advance the board to width 2.
|
||||
/// Set `section.route` to choose the output mode (`stereo` / `leftOnly` / `rightOnly` /
|
||||
/// `bypass`) at any time.
|
||||
///
|
||||
/// - Returns: A ``StereoSplitSection`` with two empty branch chains.
|
||||
/// - Throws:
|
||||
/// - `ShoeGazeError.stereoWidthExceeded` if the board is already stereo.
|
||||
/// - `BusAllocatorError.noFreeBus` if no mono audio bus is available.
|
||||
/// - `EngineAddError` if the engine rejects the splitter add.
|
||||
public func splitStereo() throws -> StereoSplitSection {
|
||||
guard width == 1 else { throw ShoeGazeError.stereoWidthExceeded }
|
||||
let preBus: AudioBus = outputBus
|
||||
|
||||
// Branch input buses are owned (and released) by each BranchChain, not by the board,
|
||||
// mirroring `split()`. The dry tap is board-owned.
|
||||
let leftInBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let rightInBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let dryTapBus: AudioBus = try allocateInterNodeBus()
|
||||
|
||||
let splitter: StereoSplitter = StereoSplitter(
|
||||
inputBus: preBus.index,
|
||||
outputBusLeft: leftInBus.index,
|
||||
outputBusRight: rightInBus.index,
|
||||
dryTapBus: dryTapBus.index
|
||||
)
|
||||
|
||||
// Both branches share one tail pointer so their pedals form a flat linear sequence,
|
||||
// guaranteeing all branch pedals evaluate before the collector regardless of add order.
|
||||
// Construct and track the branch chains (which take ownership of `leftInBus`/`rightInBus`)
|
||||
// BEFORE the throwing engine insert below, so those buses are always released on teardown
|
||||
// even if the splitter add fails.
|
||||
let tail: SharedTail = SharedTail(node: splitter)
|
||||
let leftChain: BranchChain = BranchChain(
|
||||
engine: engine,
|
||||
inputBus: leftInBus,
|
||||
sampleRate: engine.sampleRate,
|
||||
sharedTail: tail
|
||||
)
|
||||
let rightChain: BranchChain = BranchChain(
|
||||
engine: engine,
|
||||
inputBus: rightInBus,
|
||||
sampleRate: engine.sampleRate,
|
||||
sharedTail: tail
|
||||
)
|
||||
branchChains.append(leftChain)
|
||||
branchChains.append(rightChain)
|
||||
|
||||
try insertNode(splitter, after: nil)
|
||||
routingNodes.append(splitter)
|
||||
|
||||
let section: StereoSplitSection = StereoSplitSection(
|
||||
splitter: splitter,
|
||||
left: leftChain,
|
||||
right: rightChain,
|
||||
sharedTail: tail,
|
||||
dryTapBus: dryTapBus
|
||||
)
|
||||
stereoSplitSections.append(section)
|
||||
return section
|
||||
}
|
||||
|
||||
/// Inserts the route collector for a stereo split section and advances the board to width 2.
|
||||
///
|
||||
/// The collector reads both branch tails and the dry tap, and writes the board's new left and
|
||||
/// right tail buses. It is inserted after the section's shared tail (the last pedal added
|
||||
/// across either branch), so all branch pedals have written their buses before it reads them.
|
||||
/// Branches with no pedals pass their split signal straight through.
|
||||
///
|
||||
/// - Parameter section: A section returned by `splitStereo()`.
|
||||
/// - Throws:
|
||||
/// - `BusAllocatorError.noFreeBus` if no mono audio bus is available.
|
||||
/// - `EngineAddError` if the engine rejects the collector add.
|
||||
public func collectStereo(_ section: StereoSplitSection) throws {
|
||||
let outLeft: AudioBus = try allocateInterNodeBus()
|
||||
let outRight: AudioBus = try allocateInterNodeBus()
|
||||
|
||||
let collector: StereoRouteCollector = StereoRouteCollector(
|
||||
inputBusLeft: section.left.tailBusIndex,
|
||||
inputBusRight: section.right.tailBusIndex,
|
||||
dryTapBus: section.dryTapBus.index,
|
||||
outputBusLeft: outLeft.index,
|
||||
outputBusRight: outRight.index
|
||||
)
|
||||
// Insert after the shared tail — the most recently added node across both branches.
|
||||
try engine.add(collector, position: .after(section.sharedTail.node))
|
||||
routingNodes.append(collector)
|
||||
lastNode = collector
|
||||
section.bind(collector: collector)
|
||||
advanceTail(left: outLeft, right: outRight, width: 2)
|
||||
}
|
||||
|
||||
// MARK: - Parallel routing
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
// OctaveUpSplitterPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Widener pedal: clean signal on the left, an octave-up fuzz on the right (1 → 2).
|
||||
///
|
||||
/// A ``PedalChannelKind/widener``. It takes a mono input and produces two distinct wet
|
||||
/// channels, widening the board chain from mono to stereo:
|
||||
///
|
||||
/// - **Left**: the dry signal, passed through clean.
|
||||
/// - **Right**: an octave-up voice produced by full-wave rectification (`Abs`, which doubles
|
||||
/// the perceived frequency), DC-removed, driven into a `tanh` saturator, and tone-shaped —
|
||||
/// the classic "Octavia"-style octave fuzz.
|
||||
///
|
||||
/// After this pedal the chain is stereo; subsequent mono pedals auto-stereoize across both
|
||||
/// channels, so you can, for example, add a delay that processes the clean and octave voices
|
||||
/// independently.
|
||||
///
|
||||
/// ## Parameters
|
||||
///
|
||||
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - drive: Pre-gain into the octave-channel saturator. Higher = thicker octave fuzz.
|
||||
/// Range `[1, 40]`. Defaults to `12.0`.
|
||||
/// - tone: Octave-channel low-pass cutoff in Hz. Range `[500, 8000]`. Defaults to `4000.0`.
|
||||
public final class OctaveUpSplitterPedal: Pedal {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Pre-gain into the octave-channel saturator. Range [1, 40]; higher = thicker octave fuzz.
|
||||
@UIParam public var drive: Double = 12.0
|
||||
|
||||
/// Octave-channel tone low-pass cutoff in Hz. Range [500, 8000].
|
||||
@UIParam public var tone: Double = 4000.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Gain applied to the rectified signal before drive, compensating the level drop from
|
||||
/// full-wave rectification.
|
||||
private let rectifyGain: Double = 2.0
|
||||
|
||||
/// DC-removal high-pass cutoff in Hz. Rectification introduces a DC offset that must be
|
||||
/// removed before the octave voice reaches the output.
|
||||
private let dcBlockFreq: Double = 30.0
|
||||
|
||||
/// Q factor for the tone low-pass (Butterworth, no resonant peak).
|
||||
private let toneQ: Double = 0.707
|
||||
|
||||
/// High-pass Q (Butterworth).
|
||||
private let dcBlockQ: Double = 0.707
|
||||
|
||||
/// Output trim after the saturator (`tanh` output is roughly ±1).
|
||||
private let outputTrim: Double = 0.6
|
||||
|
||||
// MARK: - UI knobs
|
||||
|
||||
/// Drive knob range (octave-channel saturator pre-gain).
|
||||
private let driveRange: ClosedRange<Double> = 1.0 ... 40.0
|
||||
|
||||
/// Tone knob range in Hz (octave-channel low-pass cutoff).
|
||||
private let toneRange: ClosedRange<Double> = 500.0 ... 8000.0
|
||||
|
||||
// MARK: - Channel kind
|
||||
|
||||
/// This pedal widens mono → stereo.
|
||||
public override var channelKind: PedalChannelKind { .widener }
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates an octave-up splitter pedal.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||
/// - outputBus: Audio bus index to write the left output to. Defaults to `0`.
|
||||
public init(
|
||||
inputBus: Int = 0,
|
||||
outputBus: Int = 0
|
||||
) {
|
||||
super.init(
|
||||
name: "Octave Splitter",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: 1.0
|
||||
)
|
||||
}
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Drive", node: $drive, range: driveRange),
|
||||
PedalKnob(label: "Tone", node: $tone, range: toneRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
/// Produces the clean left channel and the octave-up right channel.
|
||||
///
|
||||
/// - Parameter dry: Dry mono input signal.
|
||||
/// - Returns: `(left: clean dry, right: octave-up fuzz)`.
|
||||
public override func wideEffect(_ dry: any ValidGeneratorInput)
|
||||
-> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) {
|
||||
// Full-wave rectification doubles the perceived frequency (octave up).
|
||||
let rectified: Abs.Audio = Abs.Audio(dry, mul: rectifyGain)
|
||||
// Remove the DC offset rectification introduces before it reaches the output.
|
||||
let dcBlocked: RBJHighPass.Audio = RBJHighPass.Audio(
|
||||
input: rectified,
|
||||
freq: dcBlockFreq,
|
||||
q: dcBlockQ
|
||||
)
|
||||
// Drive into a saturator for the octave-fuzz texture, then tone-shape.
|
||||
let driven: any ValidGeneratorInput = dcBlocked * $drive
|
||||
let saturated: Tanh.Audio = Tanh.Audio(driven, mul: outputTrim)
|
||||
let shaped: RBJLowPass.Audio = RBJLowPass.Audio(
|
||||
input: saturated,
|
||||
freq: $tone,
|
||||
q: toneQ
|
||||
)
|
||||
return (left: dry, right: shaped)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
// PingPongDelayPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Stereo-native ping-pong delay: echoes bounce left → right across the stereo field.
|
||||
///
|
||||
/// A ``PedalChannelKind/stereoNative`` pedal — a single instance reads both input channels,
|
||||
/// couples them, and writes both outputs (it cannot be expressed as two independent mono
|
||||
/// pedals). When placed in a mono region the mono input broadcasts to both channels and the
|
||||
/// chain widens to stereo; in a stereo region it sums the two inputs as the delay feed.
|
||||
///
|
||||
/// ## Signal chain (inside `stereoEffect(left:right:)`)
|
||||
///
|
||||
/// ```
|
||||
/// feed = (left + right) · 0.5
|
||||
/// leftWet = DelayLineFeedback(feed, delay: time, decayTime: feedback) // echoes at t, 2t, 3t …
|
||||
/// rightWet = DelayLine(leftWet, delay: time) // L delayed one tap → t later
|
||||
/// ```
|
||||
///
|
||||
/// The right channel is the left channel's echo train delayed by one further tap, so each
|
||||
/// repeat lands first on the left, then on the right — the characteristic ping-pong bounce.
|
||||
/// The cross-channel dependency (right derived from the processed left) is what makes this
|
||||
/// stereo-native rather than two independent delays.
|
||||
///
|
||||
/// ## Parameters
|
||||
///
|
||||
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - time: Delay time per tap in seconds. Range `[0.05, 1.0]`. Defaults to `0.3`.
|
||||
/// - feedback: Feedback as decay time in seconds (time for echoes to fall to −60 dB).
|
||||
/// Range `[0.05, 6.0]`. Defaults to `1.2`.
|
||||
public final class PingPongDelayPedal: Pedal {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Delay time per tap in seconds. Range [0.05, 1.0].
|
||||
@UIParam public var time: Double = 0.3
|
||||
|
||||
/// Feedback decay time in seconds (time to reach −60 dB amplitude). Range [0.05, 6.0].
|
||||
@UIParam public var feedback: Double = 1.2
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Maximum supported delay time in seconds. Sizes both delay lines at init.
|
||||
private let maxDelayTime: Double = 1.0
|
||||
|
||||
/// Amplitude target for the `decayTime` calculation (−60 dB).
|
||||
private let targetAmp: Double = 0.001
|
||||
|
||||
/// Gain applied when summing the two input channels into the mono delay feed.
|
||||
private let feedGain: Double = 0.5
|
||||
|
||||
/// Default wet/dry blend — partial so dry and echoes coexist.
|
||||
private static let defaultMix: Double = 0.4
|
||||
|
||||
// MARK: - UI knobs
|
||||
|
||||
/// Delay-time knob range in seconds.
|
||||
private let timeRange: ClosedRange<Double> = 0.05 ... 1.0
|
||||
|
||||
/// Feedback (decay-time) knob range in seconds.
|
||||
private let feedbackRange: ClosedRange<Double> = 0.05 ... 6.0
|
||||
|
||||
// MARK: - Channel kind
|
||||
|
||||
/// This pedal is stereo-native (cross-channel coupling).
|
||||
public override var channelKind: PedalChannelKind { .stereoNative }
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a ping-pong delay pedal.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBus: Audio bus index to read the left/mono input from. Defaults to `0`.
|
||||
/// - outputBus: Audio bus index to write the left output to. Defaults to `0`.
|
||||
public init(
|
||||
inputBus: Int = 0,
|
||||
outputBus: Int = 0
|
||||
) {
|
||||
super.init(
|
||||
name: "Ping-Pong",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: PingPongDelayPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Time", node: $time, range: timeRange),
|
||||
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
/// Builds the cross-coupled ping-pong delay. The right channel is the left echo train
|
||||
/// delayed by one further tap, producing the left → right bounce.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - left: Left dry channel.
|
||||
/// - right: Right dry channel (equals `left` when entering a mono region).
|
||||
/// - Returns: `(left: feedback echoes, right: echoes delayed one tap)`.
|
||||
public override func stereoEffect(
|
||||
left: any ValidGeneratorInput,
|
||||
right: any ValidGeneratorInput
|
||||
) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) {
|
||||
// Sum both inputs to a mono feed; a mono region passes left == right (no change).
|
||||
let feed: any ValidGeneratorInput = (left + right) * feedGain
|
||||
|
||||
let leftWet: DelayLineFeedback = DelayLineFeedback(
|
||||
input: feed,
|
||||
maxDelay: maxDelayTime,
|
||||
delay: $time,
|
||||
decayTime: $feedback,
|
||||
targetAmp: targetAmp,
|
||||
sampleRate: sampleRate,
|
||||
interpolation: .linear
|
||||
)
|
||||
// Right is the left echo train delayed one more tap → the L → R bounce.
|
||||
let rightWet: DelayLine = DelayLine(
|
||||
input: leftWet,
|
||||
maxDelay: maxDelayTime,
|
||||
delay: $time,
|
||||
sampleRate: sampleRate,
|
||||
interpolation: .linear
|
||||
)
|
||||
return (left: leftWet, right: rightWet)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// PedalChannelKind.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Declares how a ``Pedal`` relates its input channels to its output channels.
|
||||
///
|
||||
/// The board uses this to decide how many buses to hand a pedal and how its
|
||||
/// `build()` should be dispatched:
|
||||
///
|
||||
/// - `mono`: one channel in, one channel out. A `mono` pedal is *stereoizable* —
|
||||
/// when the board places it in a stereo (width-2) region it runs the pedal's
|
||||
/// `effect(_:)` once per channel, giving two independent DSP graphs that share
|
||||
/// the pedal's knobs. This is the default and covers every ordinary pedal.
|
||||
/// - `widener`: mono in, two distinct wet outs (1 → 2). Widens the chain from
|
||||
/// mono to stereo. Only valid in a width-1 region; the board rejects a widener
|
||||
/// in an already-stereo region (width is capped at 2).
|
||||
/// - `stereoNative`: two channels in, two channels out, with cross-channel
|
||||
/// coupling that cannot be expressed as two independent monos (e.g. a
|
||||
/// ping-pong delay). One instance reads both input buses and writes both
|
||||
/// output buses.
|
||||
public enum PedalChannelKind {
|
||||
|
||||
/// One in, one out. Stereoized per-channel by the board when in a stereo region.
|
||||
case mono
|
||||
|
||||
/// Mono in, two distinct wet outs (1 → 2). Widens the chain to stereo.
|
||||
case widener
|
||||
|
||||
/// Two in, two out with cross-channel coupling (e.g. ping-pong delay).
|
||||
case stereoNative
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// StereoRoute.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Output routing mode for a stereo split region (see ``StereoSplitSection``).
|
||||
///
|
||||
/// Selects how the left chain, right chain, and the clean pre-split signal map to the
|
||||
/// final stereo output pair. Transitions between modes are click-free — the
|
||||
/// ``StereoRouteCollector`` lags each mode gain over 20 ms.
|
||||
///
|
||||
/// - `stereo`: normal operation — left chain → left output, right chain → right output.
|
||||
/// - `leftOnly`: **centered** solo of the left chain — the left chain is sent to *both*
|
||||
/// output channels, so it plays full and centered rather than only in the left speaker.
|
||||
/// - `rightOnly`: centered solo of the right chain (both output channels).
|
||||
/// - `bypass`: the clean pre-split signal passes to both output channels; both branch
|
||||
/// chains are muted.
|
||||
public enum StereoRoute: String, Codable, CaseIterable {
|
||||
|
||||
/// Left chain → left, right chain → right.
|
||||
case stereo
|
||||
|
||||
/// Centered solo of the left chain (both speakers).
|
||||
case leftOnly
|
||||
|
||||
/// Centered solo of the right chain (both speakers).
|
||||
case rightOnly
|
||||
|
||||
/// Clean pre-split signal through both channels; branches muted.
|
||||
case bypass
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
// StereoRouteCollector.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Produces the final stereo output pair of a stereo split region according to a
|
||||
/// ``StereoRoute``.
|
||||
///
|
||||
/// Reads the left branch tail (`inL`), the right branch tail (`inR`), and the clean
|
||||
/// pre-split tap (`dry`), then mixes them into two output buses. The active route is
|
||||
/// represented by four scalar gains — exactly one is `1.0`, the rest `0.0` — each lagged
|
||||
/// through a ``Lag.Control`` so switching routes crossfades click-free:
|
||||
///
|
||||
/// ```
|
||||
/// outL = inL·(aStereo + aLeftSolo) + inR·aRightSolo + dry·aBypass
|
||||
/// outR = inR·(aStereo + aRightSolo) + inL·aLeftSolo + dry·aBypass
|
||||
/// ```
|
||||
///
|
||||
/// | route | outL | outR | meaning |
|
||||
/// |-------------|------|------|-------------------------------------------|
|
||||
/// | `stereo` | inL | inR | left chain → left, right chain → right |
|
||||
/// | `leftOnly` | inL | inL | centered solo of the left chain |
|
||||
/// | `rightOnly` | inR | inR | centered solo of the right chain |
|
||||
/// | `bypass` | dry | dry | clean pre-split signal; branches muted |
|
||||
///
|
||||
/// Solo routes are *centered* (the soloed chain feeds both output channels) so a soloed
|
||||
/// chain plays full and centered rather than lopsided in one speaker.
|
||||
public final class StereoRouteCollector: SynthesizerBase {
|
||||
|
||||
// MARK: - Route gains
|
||||
|
||||
/// Gain for the `stereo` route (left→left, right→right). `1.0` = active.
|
||||
@UIParam public var gainStereo: Double = 1.0
|
||||
|
||||
/// Gain for the `leftOnly` route (left chain to both channels). `1.0` = active.
|
||||
@UIParam public var gainLeftSolo: Double = 0.0
|
||||
|
||||
/// Gain for the `rightOnly` route (right chain to both channels). `1.0` = active.
|
||||
@UIParam public var gainRightSolo: Double = 0.0
|
||||
|
||||
/// Gain for the `bypass` route (clean pre-split signal to both channels). `1.0` = active.
|
||||
@UIParam public var gainBypass: Double = 0.0
|
||||
|
||||
// MARK: - Routing
|
||||
|
||||
/// Audio bus index of the left branch tail.
|
||||
public internal(set) var inputBusLeft: Int
|
||||
|
||||
/// Audio bus index of the right branch tail.
|
||||
public internal(set) var inputBusRight: Int
|
||||
|
||||
/// Audio bus index of the clean pre-split tap.
|
||||
public internal(set) var dryTapBus: Int
|
||||
|
||||
/// Audio bus index for the left output channel.
|
||||
public internal(set) var outputBusLeft: Int
|
||||
|
||||
/// Audio bus index for the right output channel.
|
||||
public internal(set) var outputBusRight: Int
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Lag time in seconds for route-gain transitions. Smooths route switches to prevent clicks.
|
||||
private let routeLagTime: Double = 0.02
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a stereo route collector.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBusLeft: Audio bus index of the left branch tail.
|
||||
/// - inputBusRight: Audio bus index of the right branch tail.
|
||||
/// - dryTapBus: Audio bus index of the clean pre-split tap.
|
||||
/// - outputBusLeft: Audio bus index for the left output channel.
|
||||
/// - outputBusRight: Audio bus index for the right output channel.
|
||||
public init(
|
||||
inputBusLeft: Int,
|
||||
inputBusRight: Int,
|
||||
dryTapBus: Int,
|
||||
outputBusLeft: Int,
|
||||
outputBusRight: Int
|
||||
) {
|
||||
self.inputBusLeft = inputBusLeft
|
||||
self.inputBusRight = inputBusRight
|
||||
self.dryTapBus = dryTapBus
|
||||
self.outputBusLeft = outputBusLeft
|
||||
self.outputBusRight = outputBusRight
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - Route convenience
|
||||
|
||||
/// The active routing mode, derived from (and applied to) the four route gains.
|
||||
///
|
||||
/// - Getting: returns the route whose gain is highest (defaults to `.stereo` on a tie).
|
||||
/// - Setting: sets the chosen route's gain to `1.0` and the others to `0.0`. The
|
||||
/// collector lags each gain, so the transition is click-free.
|
||||
public var route: StereoRoute {
|
||||
get {
|
||||
var best: StereoRoute = .stereo
|
||||
var bestGain: Double = gainStereo
|
||||
if gainLeftSolo > bestGain { best = .leftOnly; bestGain = gainLeftSolo }
|
||||
if gainRightSolo > bestGain { best = .rightOnly; bestGain = gainRightSolo }
|
||||
if gainBypass > bestGain { best = .bypass; bestGain = gainBypass }
|
||||
return best
|
||||
}
|
||||
set {
|
||||
gainStereo = (newValue == .stereo) ? 1.0 : 0.0
|
||||
gainLeftSolo = (newValue == .leftOnly) ? 1.0 : 0.0
|
||||
gainRightSolo = (newValue == .rightOnly) ? 1.0 : 0.0
|
||||
gainBypass = (newValue == .bypass) ? 1.0 : 0.0
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Build
|
||||
|
||||
/// Builds the signal graph: route-weighted mix of left, right, and dry into two outputs.
|
||||
public override func build() {
|
||||
let inL: In.Audio = input(bus: inputBusLeft)
|
||||
let inR: In.Audio = input(bus: inputBusRight)
|
||||
let dry: In.Audio = input(bus: dryTapBus)
|
||||
|
||||
let aStereo: Lag.Control = Lag.Control(input: $gainStereo, time: routeLagTime)
|
||||
let aLeftSolo: Lag.Control = Lag.Control(input: $gainLeftSolo, time: routeLagTime)
|
||||
let aRightSolo: Lag.Control = Lag.Control(input: $gainRightSolo, time: routeLagTime)
|
||||
let aBypass: Lag.Control = Lag.Control(input: $gainBypass, time: routeLagTime)
|
||||
|
||||
// Left output: left chain in stereo + left solo, right chain in right solo, dry in bypass.
|
||||
let outL: any ValidGeneratorInput =
|
||||
(inL * (aStereo + aLeftSolo)) + (inR * aRightSolo) + (dry * aBypass)
|
||||
// Right output: right chain in stereo + right solo, left chain in left solo, dry in bypass.
|
||||
let outR: any ValidGeneratorInput =
|
||||
(inR * (aStereo + aRightSolo)) + (inL * aLeftSolo) + (dry * aBypass)
|
||||
|
||||
output(bus: outputBusLeft, source: outL)
|
||||
output(bus: outputBusRight, source: outR)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// StereoSplitSection.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// A stereo split region inside a ``PedalBoard``.
|
||||
///
|
||||
/// Created by ``PedalBoard/splitStereo()``. Holds the ``StereoSplitter`` that fans the mono
|
||||
/// tail out, the two independently authored branch sub-chains that *become* the stereo
|
||||
/// channels, and (after ``PedalBoard/collectStereo(_:)``) the ``StereoRouteCollector`` that
|
||||
/// resolves the output ``route``.
|
||||
///
|
||||
/// Unlike a ``ParallelSection`` (whose branches are summed back to mono by a ``Merger``), the
|
||||
/// two branches here map directly to the left and right output channels — the board's width
|
||||
/// becomes 2 after `collectStereo(_:)`.
|
||||
///
|
||||
/// ## Typical usage
|
||||
///
|
||||
/// ```swift
|
||||
/// let s = try board.splitStereo()
|
||||
/// try s.left.add(DelayPedal())
|
||||
/// try s.right.add(DelayPedal())
|
||||
/// try board.collectStereo(s)
|
||||
/// s.route = .leftOnly // centered solo of the left chain
|
||||
/// ```
|
||||
@MainActor
|
||||
public final class StereoSplitSection {
|
||||
|
||||
// MARK: - Nodes and chains
|
||||
|
||||
/// The splitter that fans the pre-split mono signal into both branches plus the dry tap.
|
||||
public let splitter: StereoSplitter
|
||||
|
||||
/// The left branch sub-chain. Its tail becomes the left output channel.
|
||||
public let left: BranchChain
|
||||
|
||||
/// The right branch sub-chain. Its tail becomes the right output channel.
|
||||
public let right: BranchChain
|
||||
|
||||
/// Shared tail pointer updated by both branch chains; used by ``PedalBoard/collectStereo(_:)``
|
||||
/// to place the collector after the last pedal added across either branch.
|
||||
internal let sharedTail: SharedTail
|
||||
|
||||
/// The clean pre-split tap bus carried to the collector for the `bypass` route.
|
||||
internal let dryTapBus: AudioBus
|
||||
|
||||
/// The route collector, set by ``PedalBoard/collectStereo(_:)``. `nil` until then.
|
||||
internal var collector: StereoRouteCollector?
|
||||
|
||||
/// Route requested before the collector exists; applied when `collectStereo(_:)` wires it.
|
||||
private var pendingRoute: StereoRoute = .stereo
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a stereo split section. Called internally by ``PedalBoard/splitStereo()``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - splitter: The ``StereoSplitter`` feeding the two branches and the dry tap.
|
||||
/// - left: The left branch sub-chain.
|
||||
/// - right: The right branch sub-chain.
|
||||
/// - sharedTail: The shared tail tracking pointer used by both branch chains.
|
||||
/// - dryTapBus: The clean pre-split tap bus.
|
||||
init(
|
||||
splitter: StereoSplitter,
|
||||
left: BranchChain,
|
||||
right: BranchChain,
|
||||
sharedTail: SharedTail,
|
||||
dryTapBus: AudioBus
|
||||
) {
|
||||
self.splitter = splitter
|
||||
self.left = left
|
||||
self.right = right
|
||||
self.sharedTail = sharedTail
|
||||
self.dryTapBus = dryTapBus
|
||||
}
|
||||
|
||||
// MARK: - Route
|
||||
|
||||
/// The output routing mode for this region. Settable from code or UI at any time; the
|
||||
/// transition is click-free. Before ``PedalBoard/collectStereo(_:)`` wires the collector
|
||||
/// the value is held and applied on wiring.
|
||||
public var route: StereoRoute {
|
||||
get { collector?.route ?? pendingRoute }
|
||||
set {
|
||||
pendingRoute = newValue
|
||||
collector?.route = newValue
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies the pending route to the freshly wired collector. Called by
|
||||
/// ``PedalBoard/collectStereo(_:)``.
|
||||
internal func bind(collector: StereoRouteCollector) {
|
||||
self.collector = collector
|
||||
collector.route = pendingRoute
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// StereoSplitter.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Fans one mono input bus out to two branch buses plus a dry-tap bus.
|
||||
///
|
||||
/// Unlike ``Splitter`` (which gates each branch and is consumed by a summing ``Merger``),
|
||||
/// `StereoSplitter` is the head of a stereo split region: the two branches are processed
|
||||
/// independently and become the left and right output channels, while the dry tap carries
|
||||
/// the clean pre-split signal forward so the region's ``StereoRouteCollector`` can offer a
|
||||
/// `bypass` route. All three outputs carry the full input signal — gating and routing are
|
||||
/// performed downstream by the collector, not here.
|
||||
///
|
||||
/// ## Signal graph
|
||||
///
|
||||
/// ```
|
||||
/// inputBus → In.Audio ──┬── → outputBusLeft (left branch input)
|
||||
/// ├── → outputBusRight (right branch input)
|
||||
/// └── → dryTapBus (clean pre-split signal)
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBus: Audio bus index to read the mono input from.
|
||||
/// - outputBusLeft: Audio bus index for the left branch input.
|
||||
/// - outputBusRight: Audio bus index for the right branch input.
|
||||
/// - dryTapBus: Audio bus index for the clean pre-split tap.
|
||||
public final class StereoSplitter: SynthesizerBase {
|
||||
|
||||
// MARK: - Routing
|
||||
|
||||
/// Audio bus index from which the mono input is read.
|
||||
public internal(set) var inputBus: Int
|
||||
|
||||
/// Audio bus index for the left branch input.
|
||||
public internal(set) var outputBusLeft: Int
|
||||
|
||||
/// Audio bus index for the right branch input.
|
||||
public internal(set) var outputBusRight: Int
|
||||
|
||||
/// Audio bus index for the clean pre-split tap.
|
||||
public internal(set) var dryTapBus: Int
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a stereo splitter that fans one input to two branches plus a dry tap.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBus: Audio bus index to read the mono input from.
|
||||
/// - outputBusLeft: Audio bus index for the left branch input.
|
||||
/// - outputBusRight: Audio bus index for the right branch input.
|
||||
/// - dryTapBus: Audio bus index for the clean pre-split tap.
|
||||
public init(
|
||||
inputBus: Int,
|
||||
outputBusLeft: Int,
|
||||
outputBusRight: Int,
|
||||
dryTapBus: Int
|
||||
) {
|
||||
self.inputBus = inputBus
|
||||
self.outputBusLeft = outputBusLeft
|
||||
self.outputBusRight = outputBusRight
|
||||
self.dryTapBus = dryTapBus
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - Build
|
||||
|
||||
/// Builds the signal graph: input copied to both branch buses and the dry-tap bus.
|
||||
public override func build() {
|
||||
let inSig: In.Audio = input(bus: inputBus)
|
||||
output(bus: outputBusLeft, source: inSig)
|
||||
output(bus: outputBusRight, source: inSig)
|
||||
output(bus: dryTapBus, source: inSig)
|
||||
}
|
||||
}
|
||||
@@ -181,7 +181,8 @@ public final class ShoeGaze {
|
||||
/// - Throws: `EngineAddError` if the engine rejects the master node.
|
||||
public func finalizeBoard(_ board: PedalBoard) throws {
|
||||
let master: BoardOutputMaster = BoardOutputMaster(
|
||||
boardOutputBusIndex: board.outputBus.index
|
||||
boardOutputBusIndex: board.outputBus.index,
|
||||
boardOutputBusRightIndex: board.outputBusRight?.index
|
||||
)
|
||||
// The master evaluates after the entire chain (pedals, splitters, mergers).
|
||||
// `board.tailNode` returns the last inserted node (any Synthesizer), which covers
|
||||
|
||||
@@ -42,6 +42,12 @@ public enum ShoeGazeError: Error, LocalizedError, Equatable, Sendable {
|
||||
/// session is not started.
|
||||
case recordTapFailedToOpen(URL)
|
||||
|
||||
/// Thrown by `PedalBoard.add(_:)` when a widener pedal (``PedalChannelKind/widener``)
|
||||
/// is added while the board is already stereo (width 2). The chain width is capped at 2.
|
||||
///
|
||||
/// Narrow the chain with `mergeToMono()` before adding another widener.
|
||||
case stereoWidthExceeded
|
||||
|
||||
// MARK: - LocalizedError
|
||||
|
||||
public var errorDescription: String? {
|
||||
@@ -56,6 +62,8 @@ public enum ShoeGazeError: Error, LocalizedError, Equatable, Sendable {
|
||||
return "ShoeGaze: set recordingFolder before calling startRecording()."
|
||||
case .recordTapFailedToOpen(let url):
|
||||
return "ShoeGaze: could not open recording file '\(url.lastPathComponent)'."
|
||||
case .stereoWidthExceeded:
|
||||
return "PedalBoard: chain is already stereo (width 2); cannot add another widener. Use mergeToMono() first."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
// StereoRoutingTests.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("Stereo routing")
|
||||
struct StereoRoutingTests {
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Audio bus pool size for test engines.
|
||||
private let numAudioBuses: Int = 128
|
||||
|
||||
/// Render duration in seconds.
|
||||
private let renderDuration: Double = 0.25
|
||||
|
||||
/// Splits interleaved stereo samples `[L0, R0, L1, R1, …]` into separate channel arrays.
|
||||
private func deinterleave(_ samples: [Float]) -> (left: [Float], right: [Float]) {
|
||||
var left: [Float] = []
|
||||
var right: [Float] = []
|
||||
left.reserveCapacity(samples.count / 2)
|
||||
right.reserveCapacity(samples.count / 2)
|
||||
var index: Int = 0
|
||||
while index + 1 < samples.count {
|
||||
left.append(samples[index])
|
||||
right.append(samples[index + 1])
|
||||
index += 2
|
||||
}
|
||||
return (left, right)
|
||||
}
|
||||
|
||||
/// `true` if the two channels are sample-for-sample equal within `tol`.
|
||||
private func channelsEqual(_ a: [Float], _ b: [Float], tol: Float = 1e-5) -> Bool {
|
||||
guard a.count == b.count else { return false }
|
||||
for index: Int in 0..<a.count where abs(a[index] - b[index]) > tol {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// `true` if the two channels differ by more than `tol` somewhere.
|
||||
private func channelsDiffer(_ a: [Float], _ b: [Float], tol: Float = 1e-4) -> Bool {
|
||||
guard a.count == b.count else { return true }
|
||||
return zip(a, b).contains { abs($0 - $1) > tol }
|
||||
}
|
||||
|
||||
// MARK: - Widener
|
||||
|
||||
@Test func wideningPedalMakesBoardStereo() throws {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: renderDuration, numAudioBuses: numAudioBuses
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
#expect(board.width == 1, "Board should start mono")
|
||||
|
||||
try board.add(OverdrivePedal())
|
||||
try board.add(OctaveUpSplitterPedal())
|
||||
#expect(board.width == 2, "Widener should make the board stereo")
|
||||
#expect(board.outputBusRight != nil, "Stereo board should have a right tail bus")
|
||||
|
||||
try shoeGaze.finalizeBoard(board)
|
||||
try engine.start()
|
||||
|
||||
let samples: [Float] = readStereoCAF(url: url)
|
||||
#expect(hasNonSilentOutput(samples), "Widener chain produced silence")
|
||||
let (left, right): ([Float], [Float]) = deinterleave(samples)
|
||||
#expect(channelsDiffer(left, right), "Clean and octave channels should differ")
|
||||
}
|
||||
|
||||
// MARK: - Auto-stereoize
|
||||
|
||||
@Test func monoPedalAutoStereoizesAfterWidener() throws {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: renderDuration, numAudioBuses: numAudioBuses
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
|
||||
try board.add(OctaveUpSplitterPedal())
|
||||
// A plain mono pedal added in a stereo region must run on both channels.
|
||||
try board.add(DelayPedal())
|
||||
#expect(board.width == 2, "Width should stay stereo after a mono pedal")
|
||||
|
||||
// The delay pedal runs two independent graphs (one per channel).
|
||||
guard let delay: DelayPedal = board.pedals.compactMap({ $0 as? DelayPedal }).first else {
|
||||
Issue.record("DelayPedal not found")
|
||||
return
|
||||
}
|
||||
#expect(delay.isStereo, "Auto-stereoized pedal should report isStereo")
|
||||
#expect(delay.outputBusRight != nil, "Auto-stereoized pedal should have a right output bus")
|
||||
|
||||
try shoeGaze.finalizeBoard(board)
|
||||
try engine.start()
|
||||
|
||||
let samples: [Float] = readStereoCAF(url: url)
|
||||
#expect(hasNonSilentOutput(samples), "Auto-stereoized chain produced silence")
|
||||
}
|
||||
|
||||
// MARK: - Stereo-native
|
||||
|
||||
@Test func stereoNativePedalFromMonoWidensAndDiffersAcrossChannels() throws {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: renderDuration, numAudioBuses: numAudioBuses
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
|
||||
// Short tap so several echoes land inside the render window (the L→R bounce that
|
||||
// makes the channels differ only appears once the first echo arrives).
|
||||
let pingPong: PingPongDelayPedal = PingPongDelayPedal()
|
||||
pingPong.time = 0.04
|
||||
try board.add(pingPong)
|
||||
#expect(board.width == 2, "Stereo-native pedal should widen a mono board")
|
||||
|
||||
try shoeGaze.finalizeBoard(board)
|
||||
try engine.start()
|
||||
|
||||
let samples: [Float] = readStereoCAF(url: url)
|
||||
#expect(hasNonSilentOutput(samples), "Ping-pong produced silence")
|
||||
let (left, right): ([Float], [Float]) = deinterleave(samples)
|
||||
// Right is the left echo train delayed one tap → channels must differ.
|
||||
#expect(channelsDiffer(left, right), "Ping-pong channels should differ (bounce)")
|
||||
}
|
||||
|
||||
// MARK: - mergeToMono
|
||||
|
||||
@Test func mergeToMonoNarrowsBackToMono() throws {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: renderDuration, numAudioBuses: numAudioBuses
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
|
||||
try board.add(OctaveUpSplitterPedal())
|
||||
#expect(board.width == 2)
|
||||
try board.mergeToMono()
|
||||
#expect(board.width == 1, "mergeToMono should narrow the chain")
|
||||
#expect(board.outputBusRight == nil, "Mono tail should have no right bus")
|
||||
|
||||
try board.add(ReverbPedal()) // mono pedal after merge, width-1
|
||||
try shoeGaze.finalizeBoard(board)
|
||||
try engine.start()
|
||||
|
||||
let samples: [Float] = readStereoCAF(url: url)
|
||||
#expect(hasNonSilentOutput(samples), "Merged-to-mono chain produced silence")
|
||||
// Mono board → Pan2 centre → both hardware channels identical.
|
||||
let (left, right): ([Float], [Float]) = deinterleave(samples)
|
||||
#expect(channelsEqual(left, right), "Mono board should produce identical L/R")
|
||||
}
|
||||
|
||||
// MARK: - Width cap
|
||||
|
||||
@Test func wideningTwiceThrows() throws {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: 0.05, numAudioBuses: numAudioBuses
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
|
||||
try board.add(OctaveUpSplitterPedal())
|
||||
#expect(throws: ShoeGazeError.stereoWidthExceeded) {
|
||||
try board.add(OctaveUpSplitterPedal())
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - splitStereo route modes
|
||||
|
||||
/// Builds a stereo split board (left = Fuzz, right = clean Overdrive) and renders it
|
||||
/// at the given route, returning the deinterleaved output channels.
|
||||
private func renderSplit(route: StereoRoute) throws -> (left: [Float], right: [Float]) {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: renderDuration, numAudioBuses: numAudioBuses
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
|
||||
let section: StereoSplitSection = try board.splitStereo()
|
||||
try section.left.add(FuzzPedal())
|
||||
try section.right.add(OverdrivePedal())
|
||||
try board.collectStereo(section)
|
||||
section.route = route
|
||||
#expect(board.width == 2, "collectStereo should make the board stereo")
|
||||
|
||||
try shoeGaze.finalizeBoard(board)
|
||||
try engine.start()
|
||||
|
||||
return deinterleave(readStereoCAF(url: url))
|
||||
}
|
||||
|
||||
@Test func splitStereoRouteStereoDiffersAcrossChannels() throws {
|
||||
let (left, right): ([Float], [Float]) = try renderSplit(route: .stereo)
|
||||
#expect(hasNonSilentOutput(left + right), "stereo route produced silence")
|
||||
#expect(channelsDiffer(left, right), "stereo route: left and right chains should differ")
|
||||
}
|
||||
|
||||
@Test func splitStereoLeftOnlyIsCenteredSolo() throws {
|
||||
let (left, right): ([Float], [Float]) = try renderSplit(route: .leftOnly)
|
||||
#expect(hasNonSilentOutput(left + right), "leftOnly produced silence")
|
||||
// Centered solo: the left chain feeds both output channels identically.
|
||||
#expect(channelsEqual(left, right), "leftOnly should be centered (L == R)")
|
||||
}
|
||||
|
||||
@Test func splitStereoRightOnlyIsCenteredSolo() throws {
|
||||
let (left, right): ([Float], [Float]) = try renderSplit(route: .rightOnly)
|
||||
#expect(hasNonSilentOutput(left + right), "rightOnly produced silence")
|
||||
#expect(channelsEqual(left, right), "rightOnly should be centered (L == R)")
|
||||
}
|
||||
|
||||
@Test func splitStereoBypassPassesCleanThroughBothChannels() throws {
|
||||
let (left, right): ([Float], [Float]) = try renderSplit(route: .bypass)
|
||||
#expect(hasNonSilentOutput(left + right), "bypass produced silence")
|
||||
// Clean pre-split signal to both channels → identical L/R.
|
||||
#expect(channelsEqual(left, right), "bypass should pass clean signal to both channels")
|
||||
}
|
||||
|
||||
@Test func stereoRouteGetterReflectsSetMode() throws {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: 0.05, numAudioBuses: numAudioBuses
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
let section: StereoSplitSection = try board.splitStereo()
|
||||
try section.left.add(FuzzPedal())
|
||||
try section.right.add(OverdrivePedal())
|
||||
try board.collectStereo(section)
|
||||
|
||||
for route: StereoRoute in StereoRoute.allCases {
|
||||
section.route = route
|
||||
#expect(section.route == route, "route getter should reflect \(route)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Teardown
|
||||
|
||||
@Test func teardownRemovesStereoNodes() throws {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: 0.05, numAudioBuses: numAudioBuses
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
|
||||
let section: StereoSplitSection = try board.splitStereo()
|
||||
try section.left.add(DelayPedal())
|
||||
try section.right.add(PingPongDelayPedal())
|
||||
try board.collectStereo(section)
|
||||
try board.add(ReverbPedal()) // auto-stereoized post-collect
|
||||
try shoeGaze.finalizeBoard(board)
|
||||
|
||||
shoeGaze.teardown()
|
||||
#expect(shoeGaze.boards.isEmpty, "boards should be empty after teardown")
|
||||
}
|
||||
|
||||
// MARK: - Mono regression
|
||||
|
||||
@Test func plainMonoBoardStaysMono() throws {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: renderDuration, numAudioBuses: numAudioBuses
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
try board.add(OverdrivePedal())
|
||||
try board.add(DelayPedal())
|
||||
try board.add(ReverbPedal())
|
||||
#expect(board.width == 1, "Plain pedal chain should stay mono")
|
||||
#expect(board.outputBusRight == nil)
|
||||
|
||||
try shoeGaze.finalizeBoard(board)
|
||||
try engine.start()
|
||||
|
||||
let samples: [Float] = readStereoCAF(url: url)
|
||||
#expect(hasNonSilentOutput(samples), "Mono board produced silence")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
# ShoeGaze Stereo Routing Design
|
||||
|
||||
How ShoeGaze handles mono → stereo signal flow inside a `PedalBoard`.
|
||||
|
||||
## Background
|
||||
|
||||
Until now every bus in ShoeGaze was mono (`channelCount: 1`). Pedals were mono-in /
|
||||
mono-out; the handful of stereo DSP blocks (Freeverb, Chorus) folded back to mono with
|
||||
`SumChannels` before leaving `effect(_:)`. Stereo existed only at the very end, where
|
||||
`BoardOutputMaster` used `Pan2` to spread the mono board signal across hardware buses 0/1.
|
||||
|
||||
This design lets stereo *live inside* the chain: a point in the board can widen mono → stereo,
|
||||
downstream pedals process both channels, and the board emits a true stereo pair.
|
||||
|
||||
## Core model: width propagation
|
||||
|
||||
A board chain carries a **width** — the number of parallel mono buses at the current tail:
|
||||
|
||||
- `width == 1` → mono (one tail bus).
|
||||
- `width == 2` → stereo (two tail buses: left, right).
|
||||
|
||||
Stereo is represented as a **pair of mono buses**, not a single 2-channel bus. This reuses all
|
||||
existing mono-bus infrastructure (`Splitter`/`Merger`/`BranchChain` already deal in pairs of
|
||||
mono buses) and makes per-channel duplication trivial. Width is **capped at 2** — a widener
|
||||
placed in a width-2 region is rejected.
|
||||
|
||||
```
|
||||
PedalBoard.width: Int // 1 or 2
|
||||
PedalBoard.outputBus: AudioBus // left / mono tail
|
||||
PedalBoard.outputBusRight: AudioBus? // right tail (non-nil only when width == 2)
|
||||
```
|
||||
|
||||
## Pedal: width-parameterized
|
||||
|
||||
`Pedal` gains an optional right-channel bus pair and a channel-kind declaration. The mono
|
||||
fields (`inputBus`/`outputBus`) keep their meaning (channel 0 / left / mono), so every existing
|
||||
call site and preset is unchanged. When `outputBusRight != nil`, `build()` emits a second
|
||||
channel.
|
||||
|
||||
```swift
|
||||
public internal(set) var inputBus: Int // channel 0 (left / mono)
|
||||
public internal(set) var outputBus: Int // channel 0 (left / mono)
|
||||
public internal(set) var inputBusRight: Int? // channel 1 input (nil = mono / broadcast)
|
||||
public internal(set) var outputBusRight: Int? // channel 1 output (nil = mono region)
|
||||
|
||||
public enum PedalChannelKind { case mono, widener, stereoNative }
|
||||
open var channelKind: PedalChannelKind { .mono }
|
||||
```
|
||||
|
||||
### Subclass hooks
|
||||
|
||||
```swift
|
||||
// mono (default): one channel in, one channel out. Called once per channel.
|
||||
open func effect(_ dry) -> wet
|
||||
|
||||
// widener (1 → 2): mono in, two distinct wet outs.
|
||||
open func wideEffect(_ dry) -> (left, right) // default: (effect(dry), effect(dry))
|
||||
|
||||
// stereoNative (2 → 2): both channels in, coupled, two outs.
|
||||
open func stereoEffect(left, right) -> (left, right) // default: per-channel effect()
|
||||
```
|
||||
|
||||
### build() dispatch
|
||||
|
||||
`build()` factors the existing mix → bypass-lag → level chain into one private
|
||||
`applyChain(dry:wet:)` helper, then dispatches on `channelKind`:
|
||||
|
||||
| kind | left out | right out (only if `outputBusRight != nil`) |
|
||||
|---|---|---|
|
||||
| `mono` | `applyChain(in₀, effect(in₀))` | `applyChain(inR, effect(inR))` — independent graph |
|
||||
| `widener` | `applyChain(in₀, wideEffect.left)` | `applyChain(in₀, wideEffect.right)` |
|
||||
| `stereoNative` | `applyChain(inL, stereoEffect.left)` | `applyChain(inR, stereoEffect.right)` |
|
||||
|
||||
`effect()` rebuilds its generator graph on each call, so calling it once per channel yields
|
||||
**independent L/R DSP with shared knobs** for free — no manual duplication. The `mix`/`bypass`/
|
||||
`level` `@UIParam` nodes are read by both channels; each channel gets its own `Lag.Control` so
|
||||
bypass smoothing is per-channel but driven by the same target. For a width-1 (mono) region the
|
||||
output is bit-identical to the previous implementation.
|
||||
|
||||
## Four ways stereo appears
|
||||
|
||||
1. **Auto-stereoize** (`mono` pedal added while `width == 2`). The board hands it two input and
|
||||
two output buses; `build()` runs `effect()` per channel. One logical pedal, one knob set, two
|
||||
independent DSP graphs. This is "duplicates of a continuation" — the chain just stays stereo.
|
||||
|
||||
2. **Widener** (`widener` pedal, `width == 1` only). Mono in, two distinct outs → `width` becomes
|
||||
2. Reference pedal: `OctaveUpSplitterPedal` (left = dry, right = `Abs`-rectified octave-up,
|
||||
classic Octavia). A widener in a `width == 2` region throws (cap-2 rule).
|
||||
|
||||
3. **Stereo-native** (`stereoNative` pedal). One instance reads both buses, couples them, writes
|
||||
both — for effects that can't be two independent monos. Reference pedal: `PingPongDelayPedal`
|
||||
(offset-tap L/R bounce). Entering at `width == 1` broadcasts the mono input to both channels
|
||||
and sets `width = 2`.
|
||||
|
||||
4. **`splitStereo()`** — manual fan-out into two independently authored mono chains that *become*
|
||||
the stereo pair (see below). Distinct from auto-stereoize: there you mirror one pedal across
|
||||
both channels; here you build each side by hand.
|
||||
|
||||
`mergeToMono()` collapses `width 2 → 1` via a `Merger` (sum, ×0.5) when a mono tail is wanted again.
|
||||
|
||||
## splitStereo() with route modes
|
||||
|
||||
`splitStereo()` fans the current mono tail into two `BranchChain`s (reusing the existing flat
|
||||
shared-tail machinery) plus a **dry tap** carried past the branches. `collectStereo(_:)` inserts a
|
||||
`StereoRouteCollector` that produces the final stereo pair according to a route mode and advances
|
||||
`width` to 2. The branches *are* the stereo channels — there is no sum-merge.
|
||||
|
||||
```swift
|
||||
let s = try board.splitStereo()
|
||||
try s.left.add(DelayPedal()) // left chain
|
||||
try s.right.add(DelayPedal()) // right chain
|
||||
try board.collectStereo(s)
|
||||
s.route = .leftOnly // settable from code or UI any time
|
||||
```
|
||||
|
||||
### StereoRoute
|
||||
|
||||
```swift
|
||||
public enum StereoRoute { case stereo, leftOnly, rightOnly, bypass }
|
||||
```
|
||||
|
||||
`StereoRouteCollector` reads `inL` (left branch tail), `inR` (right branch tail), and `dry`
|
||||
(pre-split tap). The mode is held as four lagged scalar gains — exactly one active — so switching
|
||||
modes crossfades click-free over 20 ms:
|
||||
|
||||
```
|
||||
outL = inL·(aStereo + aLeftSolo) + inR·aRightSolo + dry·aBypass
|
||||
outR = inR·(aStereo + aRightSolo) + inL·aLeftSolo + dry·aBypass
|
||||
```
|
||||
|
||||
| route | outL | outR | meaning |
|
||||
|---|---|---|---|
|
||||
| `stereo` | inL | inR | normal — left chain → left, right chain → right |
|
||||
| `leftOnly` | inL | inL | **centered** solo of the left chain (both speakers) |
|
||||
| `rightOnly` | inR | inR | centered solo of the right chain |
|
||||
| `bypass` | dry | dry | clean pre-split signal through; branches muted |
|
||||
|
||||
Solo is centered (mono to both speakers), not a channel mute, so a soloed chain is full and
|
||||
centered rather than lopsided in one speaker.
|
||||
|
||||
## Output stage
|
||||
|
||||
`BoardOutputMaster` becomes width-aware:
|
||||
|
||||
- `width == 1` → unchanged: `Pan2(mono, center)` → hardware 0/1.
|
||||
- `width == 2` → left tail → hardware 0, right tail → hardware 1, each scaled by
|
||||
`masterGain · select`.
|
||||
|
||||
`finalizeBoard(_:)` passes the board's right tail bus (if any) to the master.
|
||||
|
||||
## What is unchanged
|
||||
|
||||
- Mono boards behave bit-identically. All existing pedals are `mono` and run width-1 by default.
|
||||
- `PedalState` serializes parameter values only (no bus indices), so presets are unaffected.
|
||||
- `Splitter`/`Merger`/`ParallelSection`/`ChainRouter` keep their existing mono semantics; the
|
||||
stereo path adds new nodes rather than reinterpreting the old ones.
|
||||
|
||||
## Files
|
||||
|
||||
New:
|
||||
- `Routing/PedalChannelKind.swift`, `Routing/StereoRoute.swift`
|
||||
- `Routing/StereoSplitter.swift` (1 in → A, B, dry tap)
|
||||
- `Routing/StereoRouteCollector.swift`, `Routing/StereoSplitSection.swift`
|
||||
- `Pedals/OctaveUpSplitterPedal.swift` (widener), `Pedals/PingPongDelayPedal.swift` (stereoNative)
|
||||
|
||||
Modified:
|
||||
- `Pedal.swift` (right buses, channel kind, build dispatch)
|
||||
- `PedalBoard.swift` (width tracking, add dispatch, `mergeToMono`, `splitStereo`/`collectStereo`)
|
||||
- `BoardOutputMaster.swift` (width-aware output)
|
||||
- `ShoeGaze.swift` (`finalizeBoard` passes right tail bus)
|
||||
|
||||
Deferred (follow-up): SwiftUI views for the route segmented control and stereo width indicators;
|
||||
preset round-trip of stereo split topology.
|
||||
Reference in New Issue
Block a user