From 1a09cf9cf8cd892abe103237658c77dc09a27750 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Mon, 22 Jun 2026 10:21:18 -0700 Subject: [PATCH] Add Stereo Unzip: process a stereo signal's L/R independently MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A stereo-output pedal (Ping-Pong, Octave Splitter) now shows a "Stereo flow / Split L/R" toggle on its card: - Stereo flow (default): unchanged broadcast behavior — following pedals process both channels as one stereo flow. - Split L/R: inserts a Stereo Unzip region right after the pedal, routing the L channel into one lane and R into the other for independent processing, then recombining to stereo with the same route/solo/bypass control as the stereo split. Engine/core: - StereoUnzipSplitter: 2-in -> 3-out node (L->lane L, R->lane R, and a centered 0.5*L+0.5*R dry tap for the bypass route). - PedalBoard.unzipStereo() mirrors splitStereo() but reads both tails and requires width 2; reuses collectStereo / StereoSplitSection / StereoRouteCollector. New stereoUnzipSections (cleared on teardown). - BoardSegment/.stereoUnzip + StereoUnzipState round-trip via preset capture/rebuild/applyState. - ShoeGaze.insertStereoUnzip(afterSegment:)/isStereoUnzip(afterSegment:) drive the toggle; invalid insert (mono tail) throws cannotUnzipMonoChain and the atomic rebuild keeps the board intact. - StereoSplitSection.splitter relaxed to `any Synthesizer` (stored only) so it can hold either splitter type. UI: per-pedal toggle + STEREO UNZIP region rendering in BoardFlowView. Co-Authored-By: Claude Opus 4.8 --- Sources/LyrebirdShoeGaze/BoardSegment.swift | 4 + Sources/LyrebirdShoeGaze/PedalBoard.swift | 77 +++++++++++++ .../Presets/BoardSegmentState.swift | 3 + .../Presets/PedalBoard+Preset.swift | 7 ++ .../Presets/ShoeGaze+Edit.swift | 42 +++++++ .../Presets/ShoeGaze+Preset.swift | 12 ++ .../Presets/StereoUnzipState.swift | 41 +++++++ .../Routing/StereoSplitSection.swift | 9 +- .../Routing/StereoUnzipSplitter.swift | 94 ++++++++++++++++ Sources/LyrebirdShoeGaze/ShoeGazeError.swift | 6 + .../LyrebirdShoeGazeUI/BoardFlowView.swift | 62 ++++++++++- .../BoardEditAPITests.swift | 105 ++++++++++++++++++ 12 files changed, 455 insertions(+), 7 deletions(-) create mode 100644 Sources/LyrebirdShoeGaze/Presets/StereoUnzipState.swift create mode 100644 Sources/LyrebirdShoeGaze/Routing/StereoUnzipSplitter.swift diff --git a/Sources/LyrebirdShoeGaze/BoardSegment.swift b/Sources/LyrebirdShoeGaze/BoardSegment.swift index b6eb0a4..7e6edb9 100644 --- a/Sources/LyrebirdShoeGaze/BoardSegment.swift +++ b/Sources/LyrebirdShoeGaze/BoardSegment.swift @@ -26,6 +26,10 @@ public enum BoardSegment { /// A stereo split region (`splitStereo()` → two branches → `collectStereo()`). case stereoSplit(StereoSplitSection) + /// A stereo unzip region (`unzipStereo()` → two branches → `collectStereo()`). Reuses the + /// `StereoSplitSection` payload; the distinct case lets capture/rebuild pick the unzip splitter. + case stereoUnzip(StereoSplitSection) + /// A `mergeToMono()` collapse — narrows a stereo tail back to mono. Carries no state; /// recorded so the width transition replays on rebuild. case mergeToMono diff --git a/Sources/LyrebirdShoeGaze/PedalBoard.swift b/Sources/LyrebirdShoeGaze/PedalBoard.swift index dad6cf5..4ab93a9 100644 --- a/Sources/LyrebirdShoeGaze/PedalBoard.swift +++ b/Sources/LyrebirdShoeGaze/PedalBoard.swift @@ -80,6 +80,10 @@ public final class PedalBoard { /// All stereo split sections created via `splitStereo()` (for inspection / UI binding). public private(set) var stereoSplitSections: [StereoSplitSection] = [] + /// All stereo unzip sections created via ``unzipStereo()``. Same `StereoSplitSection` type as + /// ``stereoSplitSections``; tracked separately so a UI can distinguish the two region kinds. + public private(set) var stereoUnzipSections: [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). @@ -367,6 +371,78 @@ public final class PedalBoard { return section } + /// Splits the current **stereo** tail into two independently authored branch chains — left + /// channel into one, right channel into the other — so the channels can be processed + /// separately, then recombined to stereo by ``collectStereo(_:)``. + /// + /// The stereo counterpart of ``splitStereo()``: it requires a width-2 tail and uses a + /// ``StereoUnzipSplitter`` (which reads both channels) instead of a mono-duplicating + /// ``StereoSplitter``. Everything downstream (branch chains, route collector, route control) + /// is identical, so it returns the same ``StereoSplitSection`` type. + /// + /// Route semantics for the reused ``StereoRouteCollector`` differ from a mono split, because + /// each lane here carries one *original* channel rather than a duplicated mono signal: + /// `.stereo` = L lane → left, R lane → right; `.leftOnly` / `.rightOnly` = center the chosen + /// lane (so you hear only that original channel, processed, in both speakers); `.bypass` = + /// the centered mono sum (`0.5·L + 0.5·R`) of the pre-unzip signal in both speakers. + /// + /// - Returns: A ``StereoSplitSection`` with two empty branch chains; call `collectStereo(_:)` + /// after adding branch pedals. + /// - Throws: + /// - `ShoeGazeError.cannotUnzipMonoChain` if the tail is mono (width 1). + /// - `BusAllocatorError.noFreeBus` if no mono audio bus is available. + /// - `EngineAddError` if the engine rejects the splitter add. + public func unzipStereo() throws -> StereoSplitSection { + guard width == 2, let rightTail: AudioBus = outputBusRight else { + throw ShoeGazeError.cannotUnzipMonoChain + } + let preLeft: AudioBus = outputBus + let preRight: AudioBus = rightTail + + // Branch input buses are branch-owned (mirroring `splitStereo`); 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: StereoUnzipSplitter = StereoUnzipSplitter( + inputLeft: preLeft.index, + inputRight: preRight.index, + outputBusLeft: leftInBus.index, + outputBusRight: rightInBus.index, + dryTapBus: dryTapBus.index + ) + + 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 + ) + stereoUnzipSections.append(section) + orderedSegments.append(.stereoUnzip(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 @@ -565,6 +641,7 @@ public final class PedalBoard { lastNode = nil orderedSegments.removeAll() stereoSplitSections.removeAll() + stereoUnzipSections.removeAll() // Step 4: Release board-owned buses (head bus and main-chain inter-node buses). for bus: AudioBus in allocatedBuses { diff --git a/Sources/LyrebirdShoeGaze/Presets/BoardSegmentState.swift b/Sources/LyrebirdShoeGaze/Presets/BoardSegmentState.swift index 84d6977..4bea219 100644 --- a/Sources/LyrebirdShoeGaze/Presets/BoardSegmentState.swift +++ b/Sources/LyrebirdShoeGaze/Presets/BoardSegmentState.swift @@ -27,6 +27,9 @@ public enum BoardSegmentState: Codable, Equatable { /// A stereo split region (`splitStereo()`/`collectStereo()`). Wire discriminator: `"stereoSplit"`. case stereoSplit(StereoSplitState) + /// A stereo unzip region (`unzipStereo()`/`collectStereo()`). Wire discriminator: `"stereoUnzip"`. + case stereoUnzip(StereoUnzipState) + /// A `mergeToMono()` collapse (no payload). Wire discriminator: `"mergeToMono"`. case mergeToMono } diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalBoard+Preset.swift b/Sources/LyrebirdShoeGaze/Presets/PedalBoard+Preset.swift index 48ac683..effe0c0 100644 --- a/Sources/LyrebirdShoeGaze/Presets/PedalBoard+Preset.swift +++ b/Sources/LyrebirdShoeGaze/Presets/PedalBoard+Preset.swift @@ -34,6 +34,13 @@ extension PedalBoard { route: section.route )) + case .stereoUnzip(let section): + return BoardSegmentState.stereoUnzip(StereoUnzipState( + left: section.left.pedals.map { $0.captureState() }, + right: section.right.pedals.map { $0.captureState() }, + route: section.route + )) + case .mergeToMono: return BoardSegmentState.mergeToMono } diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Edit.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Edit.swift index 4c956ef..cb3f759 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Edit.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Edit.swift @@ -133,6 +133,43 @@ extension ShoeGaze { return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) } + /// Inserts an empty stereo-unzip region immediately after the segment at `topLevelIndex`, + /// splitting the stereo signal at that point into two independently editable L/R lanes. + /// + /// Used by the per-pedal "Split L/R" toggle: pass the stereo pedal's segment index. No board- + /// level width guard is needed — `rebuildSegments` replays segments in order, so + /// `unzipStereo()`'s own `width == 2` check validates the *local* width at the insertion point; + /// an invalid insert throws and the atomic `rebuildBoard` leaves the existing board intact. + /// + /// - Parameters: + /// - topLevelIndex: Segment index (in `captureState().segments`) after which to insert. + /// - board: The board to edit. + /// - Returns: The rebuilt board occupying the same slot in `boards`. + /// - Throws: `ShoeGazeError.pedalIndexOutOfRange` for a bad index; + /// `ShoeGazeError.cannotUnzipMonoChain` if the signal at that point is mono; any rebuild error. + @discardableResult + public func insertStereoUnzip(afterSegment topLevelIndex: Int, in board: PedalBoard) throws -> PedalBoard { + var segments: [BoardSegmentState] = board.captureState().segments + guard topLevelIndex >= 0 && topLevelIndex < segments.count else { + throw ShoeGazeError.pedalIndexOutOfRange(index: topLevelIndex, count: segments.count) + } + segments.insert( + .stereoUnzip(StereoUnzipState(left: [], right: [], route: .stereo)), + at: topLevelIndex + 1 + ) + return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) + } + + /// Returns `true` when the segment immediately after `topLevelIndex` is a stereo-unzip region — + /// i.e. the "Split L/R" toggle for the pedal at `topLevelIndex` is on. + public func isStereoUnzip(afterSegment topLevelIndex: Int, in board: PedalBoard) -> Bool { + let segments: [BoardSegmentState] = board.captureState().segments + let next: Int = topLevelIndex + 1 + guard next >= 0 && next < segments.count else { return false } + if case .stereoUnzip = segments[next] { return true } + return false + } + /// Appends an empty parallel section (two A/B branches summed back to one signal) to the board. /// /// - Returns: The rebuilt board occupying the same slot in `boards`. @@ -231,6 +268,11 @@ extension ShoeGaze { var right: [PedalState] = state.right if isLeft { try transform(&left) } else { try transform(&right) } segments[region] = .stereoSplit(StereoSplitState(left: left, right: right, route: state.route)) + case .stereoUnzip(let state): + var left: [PedalState] = state.left + var right: [PedalState] = state.right + if isLeft { try transform(&left) } else { try transform(&right) } + segments[region] = .stereoUnzip(StereoUnzipState(left: left, right: right, route: state.route)) case .parallel(let state): var branchA: [PedalState] = state.branchA var branchB: [PedalState] = state.branchB diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift index cc25a0f..31f735e 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift @@ -150,6 +150,13 @@ extension ShoeGaze { try board.collectStereo(section) section.route = stereoState.route + case .stereoUnzip(let unzipState): + let section: StereoSplitSection = try board.unzipStereo() + try addPedals(unzipState.left, to: section.left) + try addPedals(unzipState.right, to: section.right) + try board.collectStereo(section) + section.route = unzipState.route + case .mergeToMono: try board.mergeToMono() } @@ -289,6 +296,11 @@ extension ShoeGaze { applyBranchParams(stereoState.right, to: section.right.pedals) section.route = stereoState.route + case let (.stereoUnzip(section), .stereoUnzip(unzipState)): + applyBranchParams(unzipState.left, to: section.left.pedals) + applyBranchParams(unzipState.right, to: section.right.pedals) + section.route = unzipState.route + default: // Topology mismatch at this position — skip. continue diff --git a/Sources/LyrebirdShoeGaze/Presets/StereoUnzipState.swift b/Sources/LyrebirdShoeGaze/Presets/StereoUnzipState.swift new file mode 100644 index 0000000..25496d7 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/StereoUnzipState.swift @@ -0,0 +1,41 @@ +// StereoUnzipState.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// Serialisable snapshot of a stereo unzip region (`unzipStereo()` → two branches → +/// `collectStereo()`). +/// +/// Captures the left and right branch pedal chains in signal-flow order plus the active +/// ``StereoRoute``. Reconstructed by `loadRig`/`rebuildBoard` via `board.unzipStereo()`, adding the +/// branch pedals, `board.collectStereo(_:)`, then restoring `route`. Structurally identical to +/// ``StereoSplitState`` — the distinct type keeps the unzip vs split distinction in presets so the +/// correct splitter (stereo-deinterleave vs mono-duplicate) is rebuilt. +public struct StereoUnzipState: Codable, Equatable { + + /// Left-channel branch pedal snapshots in signal-flow order. + public let left: [PedalState] + + /// Right-channel branch pedal snapshots in signal-flow order. + public let right: [PedalState] + + /// The output route mode (`.stereo` / `.leftOnly` / `.rightOnly` / `.bypass`). + public let route: StereoRoute + + /// Creates a stereo unzip snapshot. + /// + /// - Parameters: + /// - left: Left-branch pedal snapshots in order. + /// - right: Right-branch pedal snapshots in order. + /// - route: The output route mode. + public init( + left: [PedalState], + right: [PedalState], + route: StereoRoute + ) { + self.left = left + self.right = right + self.route = route + } +} diff --git a/Sources/LyrebirdShoeGaze/Routing/StereoSplitSection.swift b/Sources/LyrebirdShoeGaze/Routing/StereoSplitSection.swift index ae5a8d6..aaae683 100644 --- a/Sources/LyrebirdShoeGaze/Routing/StereoSplitSection.swift +++ b/Sources/LyrebirdShoeGaze/Routing/StereoSplitSection.swift @@ -32,8 +32,9 @@ 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 head node that feeds the two branches plus the dry tap — a ``StereoSplitter`` for a + /// mono split, or a ``StereoUnzipSplitter`` for a stereo unzip. Stored for reference only. + public let splitter: any Synthesizer /// The left branch sub-chain. Its tail becomes the left output channel. public let left: BranchChain @@ -60,13 +61,13 @@ public final class StereoSplitSection { /// Creates a stereo split section. Called internally by ``PedalBoard/splitStereo()``. /// /// - Parameters: - /// - splitter: The ``StereoSplitter`` feeding the two branches and the dry tap. + /// - splitter: The head node 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, + splitter: any Synthesizer, left: BranchChain, right: BranchChain, sharedTail: SharedTail, diff --git a/Sources/LyrebirdShoeGaze/Routing/StereoUnzipSplitter.swift b/Sources/LyrebirdShoeGaze/Routing/StereoUnzipSplitter.swift new file mode 100644 index 0000000..5e3307f --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Routing/StereoUnzipSplitter.swift @@ -0,0 +1,94 @@ +// StereoUnzipSplitter.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +/// Splits an existing stereo signal's two channels into two independent branch inputs, plus a +/// centered mono dry tap. +/// +/// This is the head of a *stereo unzip* region (the stereo counterpart of ``StereoSplitter``). +/// Where `StereoSplitter` duplicates one mono input into both branches, `StereoUnzipSplitter` +/// reads the current left and right tails and routes each into its own branch so the channels can +/// be processed independently, then recombined by a ``StereoRouteCollector`` (reused from the +/// stereo split). The dry tap carries `0.5·L + 0.5·R` — a centered mono monitor of the pre-unzip +/// signal for the collector's `bypass` route. +/// +/// ## Signal graph +/// +/// ``` +/// inputLeft → In.Audio → outputBusLeft (left branch input) +/// inputRight → In.Audio → outputBusRight (right branch input) +/// (0.5·L + 0.5·R) → dryTapBus (centered mono monitor) +/// ``` +/// +/// - Parameters: +/// - inputLeft: Audio bus index of the incoming left channel. +/// - inputRight: Audio bus index of the incoming right channel. +/// - outputBusLeft: Audio bus index for the left branch input. +/// - outputBusRight: Audio bus index for the right branch input. +/// - dryTapBus: Audio bus index for the centered mono dry tap. +public final class StereoUnzipSplitter: SynthesizerBase { + + // MARK: - Routing + + /// Audio bus index of the incoming left channel. + public internal(set) var inputLeft: Int + + /// Audio bus index of the incoming right channel. + public internal(set) var inputRight: 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 centered mono dry tap. + public internal(set) var dryTapBus: Int + + // MARK: - Constants + + /// Per-channel gain for the centered mono dry sum, so two correlated channels do not double. + private static let dryChannelGain: Double = 0.5 + + // MARK: - Init + + /// Creates a stereo unzip splitter. + /// + /// - Parameters: + /// - inputLeft: Audio bus index of the incoming left channel. + /// - inputRight: Audio bus index of the incoming right channel. + /// - outputBusLeft: Audio bus index for the left branch input. + /// - outputBusRight: Audio bus index for the right branch input. + /// - dryTapBus: Audio bus index for the centered mono dry tap. + public init( + inputLeft: Int, + inputRight: Int, + outputBusLeft: Int, + outputBusRight: Int, + dryTapBus: Int + ) { + self.inputLeft = inputLeft + self.inputRight = inputRight + self.outputBusLeft = outputBusLeft + self.outputBusRight = outputBusRight + self.dryTapBus = dryTapBus + super.init() + } + + // MARK: - Build + + /// Builds the signal graph: each input channel copied to its branch bus, and a centered mono + /// sum written to the dry tap. + public override func build() { + let leftSig: In.Audio = input(bus: inputLeft) + let rightSig: In.Audio = input(bus: inputRight) + output(bus: outputBusLeft, source: leftSig) + output(bus: outputBusRight, source: rightSig) + let gain: Double = StereoUnzipSplitter.dryChannelGain + output(bus: dryTapBus, source: (leftSig * gain) + (rightSig * gain)) + } +} diff --git a/Sources/LyrebirdShoeGaze/ShoeGazeError.swift b/Sources/LyrebirdShoeGaze/ShoeGazeError.swift index 36c5713..4edfbc8 100644 --- a/Sources/LyrebirdShoeGaze/ShoeGazeError.swift +++ b/Sources/LyrebirdShoeGaze/ShoeGazeError.swift @@ -66,6 +66,10 @@ public enum ShoeGazeError: Error, LocalizedError, Equatable, Sendable { /// is no stereo signal to collapse. case cannotMergeMonoChain + /// Thrown by `unzipStereo()` when the tail is mono (width 1) — there is no stereo signal whose + /// L/R channels could be split into independent lanes. + case cannotUnzipMonoChain + /// Thrown by the lane-addressed edit API when the segment at the given top-level index is not a /// branch region (stereo split or parallel section). `index` is the offending segment index. case notABranchRegion(index: Int) @@ -94,6 +98,8 @@ public enum ShoeGazeError: Error, LocalizedError, Equatable, Sendable { return "ShoeGaze: cannot add a stereo split; the chain is already stereo. Merge to mono first." case .cannotMergeMonoChain: return "ShoeGaze: the chain is already mono; there is no stereo signal to merge." + case .cannotUnzipMonoChain: + return "ShoeGaze: the chain is mono; there is no stereo signal to split into L/R lanes." case .notABranchRegion(let index): return "ShoeGaze: segment \(index) is not a branch region (stereo split or parallel section)." } diff --git a/Sources/LyrebirdShoeGazeUI/BoardFlowView.swift b/Sources/LyrebirdShoeGazeUI/BoardFlowView.swift index 0a316b4..97f8346 100644 --- a/Sources/LyrebirdShoeGazeUI/BoardFlowView.swift +++ b/Sources/LyrebirdShoeGazeUI/BoardFlowView.swift @@ -47,6 +47,8 @@ public struct BoardFlowView: View { private static let badgeFontSize: CGFloat = 11 private static let badgeOpacity: Double = 0.6 private static let dropHighlightWidth: CGFloat = 2 + private static let splitToggleSpacing: CGFloat = 6 + private static let splitToggleWidth: CGFloat = 200 private static let emptyLaneOpacity: Double = 0.4 /// Signal-path accent (the pink/magenta connector colour). @@ -121,6 +123,8 @@ public struct BoardFlowView: View { if pedal.channelKind != .mono { stereo = true } case .stereoSplit: stereo = true + case .stereoUnzip: + stereo = true case .parallel: break case .mergeToMono: @@ -145,7 +149,7 @@ public struct BoardFlowView: View { private func stageView(_ stage: StageModel) -> some View { switch stage.segment { case .pedal(let pedal): - mainPedalCard(pedal: pedal, linearIndex: stage.linearIndex ?? 0) + mainPedalCard(pedal: pedal, linearIndex: stage.linearIndex ?? 0, segmentIndex: stage.segmentIndex) case .stereoSplit(let section): regionNode( title: "STEREO SPLIT", @@ -156,6 +160,16 @@ public struct BoardFlowView: View { rightPedals: section.right.pedals, control: AnyView(StereoRouteControlView(section: section)) ) + case .stereoUnzip(let section): + regionNode( + title: "STEREO UNZIP", + segmentIndex: stage.segmentIndex, + leftLabel: "L", + rightLabel: "R", + leftPedals: section.left.pedals, + rightPedals: section.right.pedals, + control: AnyView(StereoRouteControlView(section: section)) + ) case .parallel(let section): regionNode( title: "PARALLEL", @@ -201,9 +215,9 @@ public struct BoardFlowView: View { // MARK: - Main pedal card - private func mainPedalCard(pedal: Pedal, linearIndex: Int) -> some View { + private func mainPedalCard(pedal: Pedal, linearIndex: Int, segmentIndex: Int) -> some View { let payload: String = "movemain:\(linearIndex)" - return PedalView(pedal: pedal) + let card: some View = PedalView(pedal: pedal) .overlay(alignment: .topTrailing) { trashButton { deleteSegment(forLinear: linearIndex) } } .overlay { dropOutline(active: dropTarget == payload) } .draggable(payload) @@ -212,6 +226,48 @@ public struct BoardFlowView: View { } isTargeted: { hovering in dropTarget = hovering ? payload : (dropTarget == payload ? nil : dropTarget) } + return VStack(spacing: BoardFlowView.splitToggleSpacing) { + card + // Stereo-producing pedals (Ping-Pong, Octave Splitter) offer a choice: keep one stereo + // flow downstream, or split the L/R channels into independent lanes (a stereo unzip). + if pedal.channelKind != .mono { + splitToggle(segmentIndex: segmentIndex) + } + } + } + + /// A "Stereo flow / Split L/R" segmented control for a stereo-producing pedal. "Split L/R" + /// inserts a stereo-unzip region right after the pedal; "Stereo flow" removes it. + private func splitToggle(segmentIndex: Int) -> some View { + let binding: Binding = Binding( + get: { + guard let board: PedalBoard = board else { return false } + return shoeGaze.isStereoUnzip(afterSegment: segmentIndex, in: board) + }, + set: { split in + guard let board: PedalBoard = board else { return } + do { + if split { + guard !shoeGaze.isStereoUnzip(afterSegment: segmentIndex, in: board) else { return } + _ = try shoeGaze.insertStereoUnzip(afterSegment: segmentIndex, in: board) + } else { + // Only remove the next segment if it is in fact this pedal's unzip region — + // it may have been removed via the region's own trash button. + guard shoeGaze.isStereoUnzip(afterSegment: segmentIndex, in: board) else { return } + _ = try shoeGaze.removeSegment(at: segmentIndex + 1, from: board) + } + } catch { + print("[BoardFlowView] split toggle failed: \(error)") + } + } + ) + return Picker("", selection: binding) { + Text("Stereo flow").tag(false) + Text("Split L/R").tag(true) + } + .pickerStyle(.segmented) + .labelsHidden() + .frame(maxWidth: BoardFlowView.splitToggleWidth) } // MARK: - Region node (stereo split / parallel) diff --git a/Tests/LyrebirdShoeGazeTests/BoardEditAPITests.swift b/Tests/LyrebirdShoeGazeTests/BoardEditAPITests.swift index dd3ca30..5f2dc1c 100644 --- a/Tests/LyrebirdShoeGazeTests/BoardEditAPITests.swift +++ b/Tests/LyrebirdShoeGazeTests/BoardEditAPITests.swift @@ -299,6 +299,111 @@ struct BoardEditAPITests { } } + // MARK: - Stereo unzip (process L/R of a stereo signal independently) + + private func unzipState(_ board: PedalBoard) -> StereoUnzipState? { + for segment: BoardSegmentState in board.captureState().segments { + if case .stereoUnzip(let state) = segment { return state } + } + return nil + } + + @Test func insertStereoUnzipAfterStereoPedalFillsLanesIndependently() throws { + // Ping-Pong makes the chain stereo; unzip after it → two independent L/R lanes. + let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Ping-Pong"]) + defer { try? FileManager.default.removeItem(at: url) } + #expect(board.width == 2, "Ping-Pong should make the board stereo") + + // Ping-Pong is segment 0; insert the unzip right after it (segment 1). + var live: PedalBoard = try sg.insertStereoUnzip(afterSegment: 0, in: board) + #expect(sg.isStereoUnzip(afterSegment: 0, in: live), "toggle should report unzip present") + + live = try sg.appendPedal(type: "Fuzz", to: live, lane: .left(region: 1)) + live = try sg.appendPedal(type: "Reverb", to: live, lane: .right(region: 1)) + + guard let state: StereoUnzipState = unzipState(live) else { + Issue.record("No stereo unzip segment") + return + } + #expect(state.left.map { $0.type } == ["Fuzz"], "left lane = Fuzz") + #expect(state.right.map { $0.type } == ["Reverb"], "right lane = Reverb") + #expect(live.width == 2, "board stays stereo after unzip + recombine") + + let samples: [Float] = try render(engine, url) + #expect(hasNonSilentOutput(samples), "unzip board should render audio") + } + + @Test func insertStereoUnzipOnMonoTailThrowsAndKeepsBoard() throws { + // Overdrive keeps the chain mono → unzip after it is invalid; rebuild throws, board intact. + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + #expect(throws: ShoeGazeError.cannotUnzipMonoChain) { + try sg.insertStereoUnzip(afterSegment: 0, in: board) + } + #expect(names(sg.boards[0]) == ["Overdrive"], "board unchanged after failed unzip") + #expect(sg.boards[0].width == 1) + } + + @Test func isStereoUnzipFalseWhenNextSegmentIsNotUnzip() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Ping-Pong", "Reverb"]) // two pedals, no unzip + defer { try? FileManager.default.removeItem(at: url) } + // Ping-Pong is segment 0; segment 1 is the Reverb pedal, not an unzip. + #expect(!sg.isStereoUnzip(afterSegment: 0, in: board)) + // Out-of-range (last segment) is also false. + #expect(!sg.isStereoUnzip(afterSegment: 1, in: board)) + } + + @Test func stereoUnzipToggleRoundTrip() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Octave Splitter"]) // widener → stereo + defer { try? FileManager.default.removeItem(at: url) } + #expect(board.width == 2) + + var live: PedalBoard = try sg.insertStereoUnzip(afterSegment: 0, in: board) + #expect(sg.isStereoUnzip(afterSegment: 0, in: live), "unzip present after insert") + live = try sg.removeSegment(at: 1, from: live) + #expect(!sg.isStereoUnzip(afterSegment: 0, in: live), "unzip removed by toggle-off") + } + + @Test func stereoUnzipRoundTripsThroughFile() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Ping-Pong"]) + defer { try? FileManager.default.removeItem(at: url) } + + var live: PedalBoard = try sg.insertStereoUnzip(afterSegment: 0, in: board) + live = try sg.appendPedal(type: "Delay", to: live, lane: .left(region: 1)) + live = try sg.appendPedal(type: "Reverb", to: live, lane: .right(region: 1)) + if let section: StereoSplitSection = live.stereoUnzipSections.first { + section.route = .rightOnly + } + + let preset: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString + ".json") + defer { try? FileManager.default.removeItem(at: preset) } + try sg.saveRig(to: preset) + + let (engine2, url2): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128) + defer { try? FileManager.default.removeItem(at: url2) } + let sg2: ShoeGaze = ShoeGaze(engine: engine2) + try sg2.loadRig(from: preset) + + guard let restored: StereoUnzipState = unzipState(sg2.boards[0]) else { + Issue.record("Unzip region lost on reload") + return + } + #expect(restored.left.map { $0.type } == ["Delay"], "left lane round-trips") + #expect(restored.right.map { $0.type } == ["Reverb"], "right lane round-trips") + #expect(restored.route == .rightOnly, "route round-trips") + #expect(sg2.boards[0].width == 2, "reloaded board stays stereo") + + let samples: [Float] = try render(engine2, url2) + #expect(hasNonSilentOutput(samples), "reloaded unzip rig renders") + } + @Test func parallelSplitBranchEditing() throws { let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = try makeRig(pedals: ["Overdrive"])