diff --git a/Demo/ShoeGazeDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Demo/ShoeGazeDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..82a587c --- /dev/null +++ b/Demo/ShoeGazeDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,33 @@ +{ + "originHash" : "cfdd71f4b32d744c862bbe26a8265d75aa9e906275b0fb1b63575b7d68be1b6a", + "pins" : [ + { + "identity" : "linenoise-swift", + "kind" : "remoteSourceControl", + "location" : "https://github.com/andybest/linenoise-swift", + "state" : { + "revision" : "afc897c02b030af7333105c4fedcd843a8339238", + "version" : "0.0.3" + } + }, + { + "identity" : "lyrebird", + "kind" : "remoteSourceControl", + "location" : "https://realizedsound.mooo.com/josh/Lyrebird", + "state" : { + "revision" : "032b7c39d351eba4029e8399e1ab1ee201e8bb5c", + "version" : "1.2.0" + } + }, + { + "identity" : "nimble", + "kind" : "remoteSourceControl", + "location" : "https://github.com/Quick/Nimble.git", + "state" : { + "revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0", + "version" : "7.3.4" + } + } + ], + "version" : 3 +} diff --git a/Demo/ShoeGazeDemo/DemoRootView.swift b/Demo/ShoeGazeDemo/DemoRootView.swift index 4a40d78..856fceb 100644 --- a/Demo/ShoeGazeDemo/DemoRootView.swift +++ b/Demo/ShoeGazeDemo/DemoRootView.swift @@ -28,6 +28,7 @@ import LyrebirdShoeGazeUI /// - `.editor` → `BoardEditorView` — board + FlowLayout pedal area + version snapshots. /// - `.parallel` → `ParallelSectionView` — splitter, two branch rows, merger (via board). /// - `.router` → `ChainRouterView` — dual-board chain router with splitter + master. +/// - `.stereo` → `StereoSplitSectionView` — stereo split with the four route modes. struct DemoRootView: View { // MARK: - Layout constants @@ -207,6 +208,9 @@ struct DemoRootView: View { case .router: routerContent + + case .stereo: + stereoContent } } @@ -247,6 +251,27 @@ struct DemoRootView: View { } } + /// `.stereo` content: the full board view (shows the pre-split pedal) stacked above a + /// width badge and `StereoSplitSectionView` (route picker + L/R branch rows). + @ViewBuilder + private var stereoContent: some View { + if let section: StereoSplitSection = controller.stereoSection, + let board: PedalBoard = controller.shoeGaze.boards.first { + ScrollView(.vertical, showsIndicators: true) { + VStack(alignment: .leading, spacing: 20) { + HStack(spacing: 10) { + PedalBoardView(board: board) + StereoWidthBadge(width: board.width) + } + StereoSplitSectionView(section: section) + } + } + } else { + Text("Stereo split unavailable.") + .foregroundStyle(Color.white.opacity(0.55)) + } + } + /// `.router` content: `ChainRouterView` bound to the live `ChainRouter`. @ViewBuilder private var routerContent: some View { diff --git a/Demo/ShoeGazeDemo/ShoeGazeDemoController.swift b/Demo/ShoeGazeDemo/ShoeGazeDemoController.swift index 071378c..7c6a34d 100644 --- a/Demo/ShoeGazeDemo/ShoeGazeDemoController.swift +++ b/Demo/ShoeGazeDemo/ShoeGazeDemoController.swift @@ -32,6 +32,10 @@ enum DemoMode: String, CaseIterable, Identifiable { /// B: Fuzz + Reverb) and recombines them through a shared master stage. case router = "Router" + /// A board with a ``StereoSplitSection`` (Overdrive → splitStereo(Delay | PingPong) → + /// collectStereo) showcasing the four ``StereoRoute`` modes and stereo output. + case stereo = "Stereo" + var id: String { rawValue } /// Short human-readable title used in the mode picker. @@ -41,6 +45,7 @@ enum DemoMode: String, CaseIterable, Identifiable { case .editor: return "Editor" case .parallel: return "Parallel" case .router: return "Router" + case .stereo: return "Stereo" } } } @@ -79,6 +84,9 @@ final class ShoeGazeDemoController { /// Non-nil only in `.parallel` mode, after ``buildParallel()`` succeeds. private(set) var parallelSection: ParallelSection? + /// Non-nil only in `.stereo` mode, after ``buildStereo()`` succeeds. + private(set) var stereoSection: StereoSplitSection? + /// Stores named board snapshots for the `.editor` showcase. let versionStore: BoardVersionStore = BoardVersionStore() @@ -165,6 +173,7 @@ final class ShoeGazeDemoController { shoeGaze.teardown() router = nil parallelSection = nil + stereoSection = nil shoeGaze = ShoeGaze(engine: engine, inputSource: inputSource) @@ -173,6 +182,7 @@ final class ShoeGazeDemoController { case .editor: buildEditor() case .parallel: buildParallel() case .router: buildRouter() + case .stereo: buildStereo() } if wasRunning { start() } @@ -279,5 +289,29 @@ final class ShoeGazeDemoController { print("[ShoeGazeDemoController] buildRouter failed: \(error)") } } + + /// `.stereo` — Overdrive → splitStereo(left: Delay | right: Ping-Pong) → collectStereo. + /// + /// Demonstrates the stereo split mechanism: a mono signal fanned into two independently + /// authored chains that become the left and right output channels, with the four + /// ``StereoRoute`` modes (stereo / left / right / bypass) selectable live. Stores the + /// `StereoSplitSection` so `DemoRootView` can display `StereoSplitSectionView`. + private func buildStereo() { + do { + let board: PedalBoard = try shoeGaze.addBoard() + board.label = "Stereo Board" + try board.add(OverdrivePedal()) + + let section: StereoSplitSection = try board.splitStereo() + try section.left.add(DelayPedal()) + try section.right.add(PingPongDelayPedal()) + try board.collectStereo(section) + + try shoeGaze.finalizeBoard(board) + stereoSection = section + } catch { + print("[ShoeGazeDemoController] buildStereo failed: \(error)") + } + } } #endif diff --git a/Sources/LyrebirdShoeGaze/BoardOutputMaster.swift b/Sources/LyrebirdShoeGaze/BoardOutputMaster.swift index c3ebccc..b3021e5 100644 --- a/Sources/LyrebirdShoeGaze/BoardOutputMaster.swift +++ b/Sources/LyrebirdShoeGaze/BoardOutputMaster.swift @@ -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)) + } } } diff --git a/Sources/LyrebirdShoeGaze/Pedal.swift b/Sources/LyrebirdShoeGaze/Pedal.swift index 43b1034..bcc001c 100644 --- a/Sources/LyrebirdShoeGaze/Pedal.swift +++ b/Sources/LyrebirdShoeGaze/Pedal.swift @@ -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)) + } + } } } diff --git a/Sources/LyrebirdShoeGaze/PedalBoard.swift b/Sources/LyrebirdShoeGaze/PedalBoard.swift index 964f5cc..2b6f255 100644 --- a/Sources/LyrebirdShoeGaze/PedalBoard.swift +++ b/Sources/LyrebirdShoeGaze/PedalBoard.swift @@ -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 diff --git a/Sources/LyrebirdShoeGaze/Pedals/OctaveUpSplitterPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/OctaveUpSplitterPedal.swift new file mode 100644 index 0000000..69def72 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/OctaveUpSplitterPedal.swift @@ -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 = 1.0 ... 40.0 + + /// Tone knob range in Hz (octave-channel low-pass cutoff). + private let toneRange: ClosedRange = 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) + } +} diff --git a/Sources/LyrebirdShoeGaze/Pedals/PingPongDelayPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/PingPongDelayPedal.swift new file mode 100644 index 0000000..346d946 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/PingPongDelayPedal.swift @@ -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 = 0.05 ... 1.0 + + /// Feedback (decay-time) knob range in seconds. + private let feedbackRange: ClosedRange = 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) + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift index 138c88f..619bdc1 100644 --- a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift +++ b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift @@ -12,9 +12,16 @@ /// are silently skipped by the loader. /// /// To register custom pedal types, extend `builtIn` by building your own dictionary -/// and merging it before calling `loadRig`. The built-in registry covers the twelve -/// factory pedals: Overdrive, Delay, Reverb, Modulation, Fuzz, Tremolo, Phaser, -/// Compressor, Mu-Tron, Auto-Wah, Feedback Delay, and Multi-Tap Delay. +/// and merging it before calling `loadRig`. The built-in registry covers the factory +/// pedals: Overdrive, Delay, Reverb, Modulation, Fuzz, Tremolo, Phaser, Compressor, +/// Mu-Tron, Auto-Wah, Feedback Delay, Multi-Tap Delay, Octave Splitter, and Ping-Pong. +/// +/// > Note: A saved rig captures each board's *linear* pedal chain only (see `BoardState`). +/// > When a registered widener (e.g. Octave Splitter) or stereo-native pedal (e.g. +/// > Ping-Pong) appears in that chain it round-trips fully — `board.add(_:)` replays the +/// > mono → stereo width transition on load. Parallel sections (`split()`/`merge()`) and +/// > stereo split regions (`splitStereo()`) are *not* part of the captured linear chain +/// > and are therefore not serialized. public enum PedalRegistry { /// Maps each built-in pedal display name to a `@MainActor` no-argument constructor. @@ -36,6 +43,8 @@ public enum PedalRegistry { "Auto-Wah": { AutoWahPedal() }, "Feedback Delay": { FeedbackDelayPedal() }, "Multi-Tap Delay": { MultiTapDelayPedal() }, + "Octave Splitter": { OctaveUpSplitterPedal() }, + "Ping-Pong": { PingPongDelayPedal() }, ] /// Returns a new `Pedal` instance for the given type string, or `nil` if the type diff --git a/Sources/LyrebirdShoeGaze/Routing/PedalChannelKind.swift b/Sources/LyrebirdShoeGaze/Routing/PedalChannelKind.swift new file mode 100644 index 0000000..8a0d19a --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Routing/PedalChannelKind.swift @@ -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 +} diff --git a/Sources/LyrebirdShoeGaze/Routing/StereoRoute.swift b/Sources/LyrebirdShoeGaze/Routing/StereoRoute.swift new file mode 100644 index 0000000..ac84b37 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Routing/StereoRoute.swift @@ -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 +} diff --git a/Sources/LyrebirdShoeGaze/Routing/StereoRouteCollector.swift b/Sources/LyrebirdShoeGaze/Routing/StereoRouteCollector.swift new file mode 100644 index 0000000..22e04ec --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Routing/StereoRouteCollector.swift @@ -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) + } +} diff --git a/Sources/LyrebirdShoeGaze/Routing/StereoSplitSection.swift b/Sources/LyrebirdShoeGaze/Routing/StereoSplitSection.swift new file mode 100644 index 0000000..ae5a8d6 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Routing/StereoSplitSection.swift @@ -0,0 +1,101 @@ +// 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. + /// Exposed for UI binding (its route gains are `@Observable`). + public internal(set) 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 + } +} diff --git a/Sources/LyrebirdShoeGaze/Routing/StereoSplitter.swift b/Sources/LyrebirdShoeGaze/Routing/StereoSplitter.swift new file mode 100644 index 0000000..e4ae491 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Routing/StereoSplitter.swift @@ -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) + } +} diff --git a/Sources/LyrebirdShoeGaze/ShoeGaze.swift b/Sources/LyrebirdShoeGaze/ShoeGaze.swift index 4a14f0a..56cc1c6 100644 --- a/Sources/LyrebirdShoeGaze/ShoeGaze.swift +++ b/Sources/LyrebirdShoeGaze/ShoeGaze.swift @@ -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 diff --git a/Sources/LyrebirdShoeGaze/ShoeGazeError.swift b/Sources/LyrebirdShoeGaze/ShoeGazeError.swift index 3a82605..d03338d 100644 --- a/Sources/LyrebirdShoeGaze/ShoeGazeError.swift +++ b/Sources/LyrebirdShoeGaze/ShoeGazeError.swift @@ -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." } } } diff --git a/Sources/LyrebirdShoeGazeUI/StereoRouteControlView.swift b/Sources/LyrebirdShoeGazeUI/StereoRouteControlView.swift new file mode 100644 index 0000000..499b782 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/StereoRouteControlView.swift @@ -0,0 +1,185 @@ +// StereoRouteControlView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdUI +import LyrebirdShoeGaze + +/// A compact routing box for a ``StereoSplitSection`` exposing a 4-way ``StereoRoute`` +/// selector and live indicators for the active route and which output channels carry signal. +/// +/// The segmented `Picker` is driven by a computed `Binding` whose `get`/`set` +/// read and write `section.route`, so it stays in sync with programmatic changes. When the +/// section has been collected (its `collector` exists), the view also reads the collector's +/// `@Observable` route gains so the channel LEDs re-render as the route crossfades. +/// +/// Source LEDs show what is feeding the output for the active route: +/// - `stereo` → L and R branch LEDs lit (both chains feed their channel). +/// - `leftOnly` → L lit (left chain, centered to both channels). +/// - `rightOnly` → R lit (right chain, centered to both channels). +/// - `bypass` → DRY lit (clean pre-split signal; both branches muted). +/// +/// ## Usage +/// +/// ```swift +/// StereoRouteControlView(section: stereoSplitSection) +/// ``` +public struct StereoRouteControlView: View { + + // MARK: - Layout constants + + private static let containerCornerRadius: CGFloat = 10 + private static let containerPaddingH: CGFloat = 14 + private static let containerPaddingV: CGFloat = 10 + private static let containerBorderOpacity: Double = 0.55 + private static let containerBorderLineWidth: CGFloat = 1.0 + private static let sectionSpacing: CGFloat = 8 + private static let titleFontSize: CGFloat = 11 + private static let titleOpacity: Double = 0.55 + private static let ledRowSpacing: CGFloat = 16 + private static let ledLabelFontSize: CGFloat = 10 + private static let ledLabelOpacity: Double = 0.60 + private static let ledDiameter: CGFloat = 8 + private static let ledGlowRadius: CGFloat = 5 + private static let ledGlowOpacity: Double = 0.80 + private static let ledDimBrightness: Double = 0.12 + private static let ledRimOpacity: Double = 0.30 + private static let ledRimLineWidth: CGFloat = 0.5 + private static let ledPairSpacing: CGFloat = 6 + /// Background colour components for the routing-box enclosure (slate). + private static let backgroundRed: Double = 0.20 + private static let backgroundGreen: Double = 0.23 + private static let backgroundBlue: Double = 0.28 + /// Width allotted to each segmented label so the four route names fit. + private static let pickerMinWidth: CGFloat = 220 + + /// Short uppercase label shown in the segmented control for each route. + private static func segmentLabel(_ route: StereoRoute) -> String { + switch route { + case .stereo: return "STEREO" + case .leftOnly: return "L" + case .rightOnly: return "R" + case .bypass: return "BYP" + } + } + + // MARK: - Properties + + private let section: StereoSplitSection + + // MARK: - Init + + /// Creates a route control view for the given ``StereoSplitSection``. + /// + /// - Parameter section: The stereo split section whose ``StereoSplitSection/route`` is + /// displayed and edited. + public init(section: StereoSplitSection) { + self.section = section + } + + // MARK: - Body + + /// The active route, after touching the collector's `@Observable` route gains so SwiftUI + /// re-renders the LEDs as the route crossfades or changes programmatically. + private var liveRoute: StereoRoute { + _ = section.collector?.$gainStereo.value + _ = section.collector?.$gainLeftSolo.value + _ = section.collector?.$gainRightSolo.value + _ = section.collector?.$gainBypass.value + return section.route + } + + public var body: some View { + let routeBinding: Binding = Binding( + get: { section.route }, + set: { section.route = $0 } + ) + let active: StereoRoute = liveRoute + + VStack(spacing: StereoRouteControlView.sectionSpacing) { + Text("STEREO ROUTE") + .font(.system(size: StereoRouteControlView.titleFontSize, weight: .semibold, design: .monospaced)) + .foregroundStyle(Color.white.opacity(StereoRouteControlView.titleOpacity)) + + Picker("Route", selection: routeBinding) { + ForEach(StereoRoute.allCases, id: \.self) { route in + Text(StereoRouteControlView.segmentLabel(route)) + .tag(route) + } + } + .pickerStyle(.segmented) + .frame(minWidth: StereoRouteControlView.pickerMinWidth) + + sourceLEDs(active: active) + } + .padding(.horizontal, StereoRouteControlView.containerPaddingH) + .padding(.vertical, StereoRouteControlView.containerPaddingV) + .background( + RoundedRectangle(cornerRadius: StereoRouteControlView.containerCornerRadius) + .fill(Color( + red: StereoRouteControlView.backgroundRed, + green: StereoRouteControlView.backgroundGreen, + blue: StereoRouteControlView.backgroundBlue + )) + .overlay( + RoundedRectangle(cornerRadius: StereoRouteControlView.containerCornerRadius) + .stroke( + Color.white.opacity(StereoRouteControlView.containerBorderOpacity), + lineWidth: StereoRouteControlView.containerBorderLineWidth + ) + ) + ) + } + + // MARK: - Subviews + + /// L / R / DRY source LEDs reflecting what feeds the output for the active route. + private func sourceLEDs(active: StereoRoute) -> some View { + let leftLit: Bool = (active == .stereo || active == .leftOnly) + let rightLit: Bool = (active == .stereo || active == .rightOnly) + let dryLit: Bool = (active == .bypass) + return HStack(spacing: StereoRouteControlView.ledRowSpacing) { + sourceLED(label: "L", lit: leftLit) + sourceLED(label: "R", lit: rightLit) + sourceLED(label: "DRY", lit: dryLit) + } + } + + /// A single labelled LED dot for one signal source. + private func sourceLED(label: String, lit: Bool) -> some View { + VStack(spacing: StereoRouteControlView.ledPairSpacing) { + Text(label) + .font(.system(size: StereoRouteControlView.ledLabelFontSize, weight: .medium, design: .monospaced)) + .foregroundStyle(Color.white.opacity(StereoRouteControlView.ledLabelOpacity)) + ZStack { + if lit { + Circle() + .fill(Color.cyan.opacity(StereoRouteControlView.ledGlowOpacity)) + .frame( + width: StereoRouteControlView.ledDiameter + StereoRouteControlView.ledGlowRadius, + height: StereoRouteControlView.ledDiameter + StereoRouteControlView.ledGlowRadius + ) + .blur(radius: StereoRouteControlView.ledGlowRadius / 2) + } + Circle() + .fill(lit ? Color.cyan : Color(white: StereoRouteControlView.ledDimBrightness)) + .frame(width: StereoRouteControlView.ledDiameter, height: StereoRouteControlView.ledDiameter) + .overlay( + Circle() + .stroke( + Color.white.opacity(StereoRouteControlView.ledRimOpacity), + lineWidth: StereoRouteControlView.ledRimLineWidth + ) + .frame(width: StereoRouteControlView.ledDiameter, height: StereoRouteControlView.ledDiameter) + ) + } + .frame( + width: StereoRouteControlView.ledDiameter + StereoRouteControlView.ledGlowRadius, + height: StereoRouteControlView.ledDiameter + StereoRouteControlView.ledGlowRadius + ) + } + } +} diff --git a/Sources/LyrebirdShoeGazeUI/StereoSplitSectionView.swift b/Sources/LyrebirdShoeGazeUI/StereoSplitSectionView.swift new file mode 100644 index 0000000..97994f5 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/StereoSplitSectionView.swift @@ -0,0 +1,108 @@ +// StereoSplitSectionView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdUI +import LyrebirdShoeGaze + +/// Renders a ``StereoSplitSection`` as a horizontal stereo rack. +/// +/// Layout (left → right): +/// 1. ``StereoRouteControlView`` — the 4-way ``StereoRoute`` selector and source LEDs. +/// 2. A central panel with two labelled branch rows that become the stereo channels: +/// - **L** row: one ``PedalView`` per pedal in `section.left`. +/// - **R** row: one ``PedalView`` per pedal in `section.right`. +/// Empty branches show a placeholder (the split signal passes straight through). +/// +/// The route collector and dry tap are owned by `PedalBoard`, not the section, so only +/// the route control and the two branch rows are rendered here. The central panel is +/// wrapped in a horizontal `ScrollView` so wide branch chains do not overflow. +/// +/// ## Usage +/// +/// ```swift +/// StereoSplitSectionView(section: stereoSplitSection) +/// ``` +public struct StereoSplitSectionView: View { + + // MARK: - Layout constants + + private static let outerSpacing: CGFloat = 16 + private static let branchStackSpacing: CGFloat = 12 + private static let pedalSpacing: CGFloat = 16 + private static let branchLabelFontSize: CGFloat = 11 + private static let branchLabelOpacity: Double = 0.55 + private static let emptyBranchOpacity: Double = 0.30 + private static let emptyBranchFontSize: CGFloat = 11 + private static let scrollPaddingH: CGFloat = 12 + private static let scrollPaddingV: CGFloat = 8 + private static let branchSeparatorOpacity: Double = 0.15 + private static let branchSeparatorHeight: CGFloat = 1 + private static let branchLabelWidth: CGFloat = 18 + + // MARK: - Properties + + private let section: StereoSplitSection + + // MARK: - Init + + /// Creates a stereo split section view. + /// + /// - Parameter section: The `StereoSplitSection` to render. Both branch pedal arrays + /// and the route are read from this instance. + public init(section: StereoSplitSection) { + self.section = section + } + + // MARK: - Body + + public var body: some View { + HStack(alignment: .top, spacing: StereoSplitSectionView.outerSpacing) { + StereoRouteControlView(section: section) + + ScrollView(.horizontal, showsIndicators: false) { + VStack(alignment: .leading, spacing: StereoSplitSectionView.branchStackSpacing) { + branchRow(label: "L", pedals: section.left.pedals) + + Rectangle() + .fill(Color.white.opacity(StereoSplitSectionView.branchSeparatorOpacity)) + .frame(height: StereoSplitSectionView.branchSeparatorHeight) + + branchRow(label: "R", pedals: section.right.pedals) + } + .padding(.horizontal, StereoSplitSectionView.scrollPaddingH) + .padding(.vertical, StereoSplitSectionView.scrollPaddingV) + } + } + } + + // MARK: - Subviews + + /// A labelled row of pedal cards for one stereo channel. + private func branchRow(label: String, pedals: [Pedal]) -> some View { + HStack(alignment: .bottom, spacing: StereoSplitSectionView.pedalSpacing) { + Text(label) + .font(.system( + size: StereoSplitSectionView.branchLabelFontSize, + weight: .semibold, + design: .monospaced + )) + .foregroundStyle(Color.white.opacity(StereoSplitSectionView.branchLabelOpacity)) + .frame(width: StereoSplitSectionView.branchLabelWidth, alignment: .leading) + + if pedals.isEmpty { + Text("(empty)") + .font(.system(size: StereoSplitSectionView.emptyBranchFontSize)) + .foregroundStyle(Color.white.opacity(StereoSplitSectionView.emptyBranchOpacity)) + } else { + ForEach(Array(pedals.enumerated()), id: \.offset) { pair in + let pedal: Pedal = pair.element + PedalView(pedal: pedal) + } + } + } + } +} diff --git a/Sources/LyrebirdShoeGazeUI/StereoWidthBadge.swift b/Sources/LyrebirdShoeGazeUI/StereoWidthBadge.swift new file mode 100644 index 0000000..adb7337 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/StereoWidthBadge.swift @@ -0,0 +1,75 @@ +// StereoWidthBadge.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI + +/// A small pill badge indicating whether a chain point is mono (width 1) or stereo (width 2). +/// +/// Pass `PedalBoard.width` (or any channel count). Width `2` shows a cyan "STEREO" pill; +/// anything else shows a dim "MONO" pill. Width is structural (it changes only when pedals +/// are added or removed), so the badge does not need to observe live parameter state — the +/// surrounding board view rebuilds when the chain changes. +/// +/// ## Usage +/// +/// ```swift +/// StereoWidthBadge(width: board.width) +/// ``` +public struct StereoWidthBadge: View { + + // MARK: - Layout constants + + private static let fontSize: CGFloat = 9 + private static let paddingH: CGFloat = 7 + private static let paddingV: CGFloat = 3 + private static let cornerRadius: CGFloat = 4 + private static let stereoWidth: Int = 2 + private static let monoFillOpacity: Double = 0.14 + private static let stereoFillOpacity: Double = 0.85 + private static let monoTextOpacity: Double = 0.45 + private static let borderOpacity: Double = 0.30 + private static let borderLineWidth: CGFloat = 0.5 + + // MARK: - Properties + + private let width: Int + + // MARK: - Init + + /// Creates a width badge. + /// + /// - Parameter width: Channel count at this chain point (`PedalBoard.width`). `2` renders + /// the stereo badge; any other value renders the mono badge. + public init(width: Int) { + self.width = width + } + + // MARK: - Body + + public var body: some View { + let isStereo: Bool = (width == StereoWidthBadge.stereoWidth) + Text(isStereo ? "STEREO" : "MONO") + .font(.system(size: StereoWidthBadge.fontSize, weight: .bold, design: .monospaced)) + .foregroundStyle(isStereo ? Color.black : Color.white.opacity(StereoWidthBadge.monoTextOpacity)) + .padding(.horizontal, StereoWidthBadge.paddingH) + .padding(.vertical, StereoWidthBadge.paddingV) + .background( + RoundedRectangle(cornerRadius: StereoWidthBadge.cornerRadius) + .fill( + isStereo + ? Color.cyan.opacity(StereoWidthBadge.stereoFillOpacity) + : Color.white.opacity(StereoWidthBadge.monoFillOpacity) + ) + .overlay( + RoundedRectangle(cornerRadius: StereoWidthBadge.cornerRadius) + .stroke( + Color.white.opacity(StereoWidthBadge.borderOpacity), + lineWidth: StereoWidthBadge.borderLineWidth + ) + ) + ) + } +} diff --git a/Tests/LyrebirdShoeGazeTests/PresetTests.swift b/Tests/LyrebirdShoeGazeTests/PresetTests.swift index ed37c09..7ee2ceb 100644 --- a/Tests/LyrebirdShoeGazeTests/PresetTests.swift +++ b/Tests/LyrebirdShoeGazeTests/PresetTests.swift @@ -43,6 +43,50 @@ struct PresetTests { return (sg, engine, url) } + // MARK: - Stereo pedal round-trip + + @Test func wideningPedalRigRoundTripsThroughFile() throws { + // A linear rig containing a widener + a downstream mono pedal must round-trip: + // the registered widener replays the mono → stereo transition on load, and the + // downstream pedal auto-stereoizes. + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128) + defer { try? FileManager.default.removeItem(at: url) } + let presetURL: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString + ".json") + defer { try? FileManager.default.removeItem(at: presetURL) } + + let sg: ShoeGaze = ShoeGaze(engine: engine) + let board: PedalBoard = try sg.addBoard() + let octave: OctaveUpSplitterPedal = OctaveUpSplitterPedal() + octave.drive = 22.0 + try board.add(octave) + try board.add(DelayPedal()) + try sg.finalizeBoard(board) + #expect(board.width == 2, "Rig should be stereo before saving") + + try sg.saveRig(to: presetURL) + try sg.loadRig(from: presetURL) + + // After reload: same topology + restored parameter. + guard let loadedBoard: PedalBoard = sg.boards.first else { + Issue.record("No board after loadRig") + return + } + #expect(loadedBoard.width == 2, "Widener should re-widen the board on load") + #expect(loadedBoard.pedals.count == 2, "Both pedals should be reconstructed") + guard let loadedOctave: OctaveUpSplitterPedal = + loadedBoard.pedals.first as? OctaveUpSplitterPedal else { + Issue.record("Octave Splitter not reconstructed (registry miss?)") + return + } + #expect(loadedOctave.$drive.value == 22.0, "Widener drive should be restored") + } + + @Test func pingPongPedalIsRegistered() throws { + let pedal: Pedal? = PedalRegistry.makePedal(type: "Ping-Pong") + #expect(pedal is PingPongDelayPedal, "Ping-Pong should be registered") + } + // MARK: - In-memory round-trip @Test func captureStateRoundTripEquality() throws { diff --git a/Tests/LyrebirdShoeGazeTests/StereoRoutingTests.swift b/Tests/LyrebirdShoeGazeTests/StereoRoutingTests.swift new file mode 100644 index 0000000..3b0eb8c --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/StereoRoutingTests.swift @@ -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.. 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") + } +} diff --git a/docs/stereo-routing-design.md b/docs/stereo-routing-design.md new file mode 100644 index 0000000..216d3dd --- /dev/null +++ b/docs/stereo-routing-design.md @@ -0,0 +1,197 @@ +# 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) + +## UI + +`Sources/LyrebirdShoeGazeUI/`: +- `StereoRouteControlView` — 4-way `StereoRoute` segmented selector + L/R/DRY source LEDs, + bound to a `StereoSplitSection.route` (mirrors `SplitterView`). +- `StereoSplitSectionView` — route control + the two branch (L/R) pedal rows (mirrors + `ParallelSectionView`). +- `StereoWidthBadge` — MONO/STEREO pill driven by `PedalBoard.width`. + +These are standalone public views, like `SplitterView`/`ParallelSectionView`. `collector` is +exposed on `StereoSplitSection` so the route control can observe its `@Observable` route gains. + +## Presets + +A saved rig captures each board's *linear* `pedals` chain only (unchanged). Wideners and +stereo-native pedals added via `board.add(_:)` are in that chain, so they round-trip — the +mono → stereo width transition replays on load. `OctaveUpSplitterPedal` ("Octave Splitter") and +`PingPongDelayPedal` ("Ping-Pong") are registered in `PedalRegistry`. Split-region *topology* +(`splitStereo()` branches) is not serialized — the same limitation as parallel `split()`. + +The macOS Demo app has a `.stereo` mode (`ShoeGazeDemoController.buildStereo()` + +`DemoRootView.stereoContent`): Overdrive → `splitStereo(Delay | Ping-Pong)` → `collectStereo`, +with the four route modes selectable live. + +Deferred (follow-up): serializing split-region topology (would also need to cover parallel +sections for consistency); an iOS demo showcase (the iOS demo app has no mode switcher).