1.0 release
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
// BoardOutputMaster.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Internal synthesizer that reads a pedalboard's output bus, applies a master
|
||||
/// gain, pans it to stereo, and writes to hardware output buses 0 (left) and 1 (right).
|
||||
///
|
||||
/// Ordered `.after` the last pedal in the board's chain so it evaluates after the
|
||||
/// full signal chain is complete.
|
||||
final class BoardOutputMaster: SynthesizerBase {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Master output gain in [0, 1]. The user-facing volume knob; applied directly.
|
||||
@UIParam var masterGain: Double = 0.8
|
||||
|
||||
/// Board-select gain in [0, 1]. `1` = this board is audible, `0` = silenced.
|
||||
/// Driven by `ShoeGaze.selectBoard(_:crossfadeSeconds:)`; lagged by `crossfadeTime`
|
||||
/// so switching boards crossfades instead of clicking. Defaults to `1` (audible).
|
||||
@UIParam var selectGain: Double = 1.0
|
||||
|
||||
/// Lag time in seconds for `selectGain` transitions — the board crossfade duration.
|
||||
/// Defaults to a short 20 ms so normal use is click-free; raise it for a slow crossfade.
|
||||
@UIParam var crossfadeTime: Double = 0.02
|
||||
|
||||
/// The live `UIParamNode` backing `masterGain`, exposed so the board (and its UI)
|
||||
/// can bind a master-volume knob to this stage.
|
||||
var gainNode: UIParamNode { $masterGain }
|
||||
|
||||
/// The live `UIParamNode` backing `selectGain` (board-select crossfade gain).
|
||||
var selectGainNode: UIParamNode { $selectGain }
|
||||
|
||||
/// The live `UIParamNode` backing `crossfadeTime` (board crossfade seconds).
|
||||
var crossfadeTimeNode: UIParamNode { $crossfadeTime }
|
||||
|
||||
// MARK: - Routing
|
||||
|
||||
private let boardOutputBusIndex: Int
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Pan position for the board in the stereo field. Centre = 0.0.
|
||||
private let stereoPan: Double = 0.0
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
init(boardOutputBusIndex: Int) {
|
||||
self.boardOutputBusIndex = boardOutputBusIndex
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// HardwareInputPassThrough.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Internal synthesizer that copies one hardware input bus to a board head bus.
|
||||
///
|
||||
/// When `ShoeGaze` is configured with `.liveInput`, a `HardwareInputPassThrough` is
|
||||
/// added to the engine before the first pedal. It reads the hardware input bus at
|
||||
/// `inputBusIndex` and writes its samples to the board's head bus at `outputBusIndex`.
|
||||
/// This ensures the first pedal reads from a user-space bus that the board controls,
|
||||
/// rather than from the raw hardware input bus directly.
|
||||
///
|
||||
/// - Note: The synthesizer must be removed from the engine before the board's
|
||||
/// `teardown()` releases the head bus back to the allocator.
|
||||
final class HardwareInputPassThrough: SynthesizerBase {
|
||||
|
||||
// MARK: - Routing
|
||||
|
||||
/// Index of the hardware input bus to read from (typically `engine.numOutputChannels`).
|
||||
private let inputBusIndex: Int
|
||||
|
||||
/// Index of the board head bus to write to.
|
||||
private let outputBusIndex: Int
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a pass-through that copies `inputBusIndex` to `outputBusIndex`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBusIndex: Hardware input bus index to read from.
|
||||
/// Typically `engine.numOutputChannels` for the first input channel.
|
||||
/// - outputBusIndex: Board head bus index to write to.
|
||||
init(inputBusIndex: Int, outputBusIndex: Int) {
|
||||
self.inputBusIndex = inputBusIndex
|
||||
self.outputBusIndex = outputBusIndex
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - Build
|
||||
|
||||
override func build() {
|
||||
output(bus: outputBusIndex, source: input(bus: inputBusIndex))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// InputSource.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Selects how the pedalboard's head bus is fed with audio.
|
||||
///
|
||||
/// - `.testLoop`: A synthesized test tone (`TestLoopSource`) writes to the head bus.
|
||||
/// Suitable for testing the pedalboard with no hardware connected.
|
||||
/// - `.liveInput(channel:)`: A hardware input channel feeds the head bus. `channel` is
|
||||
/// the zero-based hardware input channel index (`0` = first input). It maps to engine
|
||||
/// audio-bus index `numOutputChannels + channel` (hardware input buses follow the
|
||||
/// output buses). Requires the engine to be created with `numInputChannels > channel`.
|
||||
public enum InputSource {
|
||||
/// Synthesized test signal — no hardware required.
|
||||
case testLoop
|
||||
/// Live hardware input from the given zero-based input channel. The engine must be
|
||||
/// created with `numInputChannels > channel`.
|
||||
case liveInput(channel: Int)
|
||||
}
|
||||
|
||||
/// Validates a `.liveInput` channel against the engine and returns the engine audio-bus
|
||||
/// index of that hardware input channel.
|
||||
///
|
||||
/// Hardware input buses occupy indices `numOutputChannels ..< (numOutputChannels +
|
||||
/// numInputChannels)`, so input channel `channel` lives at `numOutputChannels + channel`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - channel: Zero-based hardware input channel index.
|
||||
/// - engine: The engine whose bus layout is queried.
|
||||
/// - Returns: The audio-bus index to read the requested input channel from.
|
||||
/// - Throws:
|
||||
/// - `ShoeGazeError.liveInputRequiresInputChannels` if the engine has no input channels.
|
||||
/// - `ShoeGazeError.inputChannelOutOfRange` if `channel` is negative or `>= numInputChannels`.
|
||||
internal func liveInputBusIndex(
|
||||
channel: Int,
|
||||
engine: SynthesisEngine
|
||||
) throws -> Int {
|
||||
guard engine.numInputChannels > 0 else {
|
||||
throw ShoeGazeError.liveInputRequiresInputChannels
|
||||
}
|
||||
guard channel >= 0, channel < engine.numInputChannels else {
|
||||
throw ShoeGazeError.inputChannelOutOfRange(
|
||||
requested: channel,
|
||||
available: engine.numInputChannels
|
||||
)
|
||||
}
|
||||
return engine.numOutputChannels + channel
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// TestLoopSource.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// A synthesized test signal source that writes to a target audio bus.
|
||||
///
|
||||
/// Produces two detuned sine oscillators at 110 Hz and 165 Hz — an approximation
|
||||
/// of a guitar's A2 and E3 strings — with a slow amplitude envelope driven by a
|
||||
/// low-frequency sine LFO. This makes the board audible immediately without any
|
||||
/// hardware connection.
|
||||
///
|
||||
/// The output is written to `targetBus` so downstream pedals read it from that bus.
|
||||
/// `TestLoopSource` should be added to the engine **before** the first pedal in the
|
||||
/// chain to ensure signal-order correctness (source evaluates first).
|
||||
///
|
||||
/// ## Parameters
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - targetBus: Audio bus index to write the test signal to. Typically the
|
||||
/// pedalboard's head bus index.
|
||||
/// - amplitude: Output amplitude in [0, 1]. Defaults to `0.25`.
|
||||
public final class TestLoopSource: SynthesizerBase {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Output amplitude in [0, 1].
|
||||
@UIParam public var amplitude: Double = 0.25
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Frequency of the first oscillator in Hz (approximates guitar A2 string).
|
||||
private let freqA: Double = 110.0
|
||||
|
||||
/// Frequency of the second oscillator in Hz (approximates guitar E3 string, slightly detuned).
|
||||
private let freqB: Double = 165.75
|
||||
|
||||
/// LFO frequency in Hz for amplitude modulation (slow tremolo).
|
||||
private let lfoFreq: Double = 0.5
|
||||
|
||||
/// LFO depth as a fraction of base amplitude [0, 1].
|
||||
private let lfoDepth: Double = 0.3
|
||||
|
||||
/// Gain for each individual oscillator before summing. Two oscillators × 0.5 = unity.
|
||||
private let oscGain: Double = 0.5
|
||||
|
||||
// MARK: - Routing
|
||||
|
||||
/// The bus this source writes its output to.
|
||||
private let targetBus: Int
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a test loop source that writes to `targetBus`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - targetBus: Audio bus index to write the synthesized test signal to.
|
||||
public init(targetBus: Int) {
|
||||
self.targetBus = targetBus
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - Build
|
||||
|
||||
public override func build() {
|
||||
let oscA: OscSin.Audio = OscSin.Audio(freq: freqA, mul: oscGain)
|
||||
let oscB: OscSin.Audio = OscSin.Audio(freq: freqB, phase: 0.25, mul: oscGain)
|
||||
let lfo: OscSin.Audio = OscSin.Audio(freq: lfoFreq, mul: lfoDepth, add: 1.0 - lfoDepth)
|
||||
let signal: any ValidGeneratorInput = (oscA + oscB) * lfo * $amplitude
|
||||
output(bus: targetBus, source: signal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
// Pedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Abstract base class for a single-signal-chain guitar pedal effect.
|
||||
///
|
||||
/// Each pedal reads from `inputBus`, applies `effect(_:)` (implemented by subclasses),
|
||||
/// then crossfades wet/dry and bypass before writing to `outputBus`.
|
||||
///
|
||||
/// ## Signal chain
|
||||
///
|
||||
/// ```
|
||||
/// inputBus → dry → effect(_:) → wet
|
||||
/// ↕ mix (equal-power crossfade)
|
||||
/// blended
|
||||
/// ↕ bypass (lagged equal-power crossfade with dry)
|
||||
/// switched → × level → outputBus
|
||||
/// ```
|
||||
///
|
||||
/// ## Subclassing
|
||||
///
|
||||
/// Override `effect(_:)` to return a mono processed signal. The base `build()` handles
|
||||
/// wet/dry mixing, smooth bypass switching, and output gain automatically.
|
||||
///
|
||||
/// ## Parameters
|
||||
///
|
||||
/// - `mix`: Wet/dry blend in `[0, 1]`. `0` = fully dry, `1` = fully wet.
|
||||
/// - `bypass`: Bypass state. `0` = engaged (effect active), `1` = bypassed (pure dry).
|
||||
/// Transitions are smoothed with a 20 ms lag to avoid clicks.
|
||||
/// - `level`: Output gain as a linear multiplier. `1.0` = unity gain.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - mix: Wet/dry ratio in [0, 1]. `0` = dry only, `1` = wet only. Defaults to `1.0`.
|
||||
/// - bypass: Bypass flag. `0` = engaged, `1` = bypassed. Defaults to `0.0`.
|
||||
/// - level: Output gain multiplier in [0, ∞). Defaults to `1.0`.
|
||||
open class Pedal: SynthesizerBase {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Wet/dry blend ratio in [0, 1]. `0` = dry only, `1` = wet only.
|
||||
@UIParam public var mix: Double = 1.0
|
||||
|
||||
/// Bypass state. `0` = engaged (effect active), `1` = bypassed (dry signal only).
|
||||
/// Transitions are smoothed by `bypassLagTime` seconds to prevent clicks.
|
||||
@UIParam public var bypass: Double = 0.0
|
||||
|
||||
/// Output gain as a linear multiplier. `1.0` = unity gain.
|
||||
@UIParam public var level: Double = 1.0
|
||||
|
||||
// MARK: - Sample rate
|
||||
|
||||
/// Engine sample rate, injected by `PedalBoard.add(_:)` before the pedal is added
|
||||
/// to the engine; effect stages that need the sample rate read this. Defaults to a
|
||||
/// safe 48 kHz fallback.
|
||||
public var sampleRate: Double = 48000.0
|
||||
|
||||
// MARK: - Identity / routing
|
||||
|
||||
/// 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.
|
||||
public internal(set) var inputBus: Int
|
||||
|
||||
/// Index of the audio bus to which this pedal writes its output.
|
||||
public internal(set) var outputBus: Int
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Lag time constant in seconds (60 dB convergence) for the bypass crossfade.
|
||||
/// Smooths engaged ↔ bypassed transitions to prevent audible clicks.
|
||||
private let bypassLagTime: Double = 0.02
|
||||
|
||||
// Bipolar-span constant used to remap a [0, 1] value to [-1, +1]
|
||||
// for CrossFade's equal-power pan parameter.
|
||||
private let bipolarSpan: Double = 2.0
|
||||
private let bipolarOffset: Double = 1.0
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a pedal with a display name and initial bus assignments.
|
||||
///
|
||||
/// Bus assignments are updated by `PedalBoard.add(_:)` before `engine.add`; the
|
||||
/// defaults here are only placeholders. Always configure via the board.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - name: Human-readable pedal name shown in UI and debug output.
|
||||
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
|
||||
/// - initialMix: Initial wet/dry blend in `[0, 1]`. Time-based pedals (delay,
|
||||
/// reverb, modulation) pass a partial blend so the dry signal stays present;
|
||||
/// gain-shaping pedals (overdrive) leave the default fully-wet `1.0`.
|
||||
public init(
|
||||
name: String,
|
||||
inputBus: Int = 0,
|
||||
outputBus: Int = 0,
|
||||
initialMix: Double = 1.0
|
||||
) {
|
||||
self.displayName = name
|
||||
self.inputBus = inputBus
|
||||
self.outputBus = outputBus
|
||||
super.init()
|
||||
self.mix = initialMix
|
||||
}
|
||||
|
||||
// MARK: - UI knob descriptors
|
||||
|
||||
/// Effect-specific knobs for this pedal, listed before the common knobs in the UI.
|
||||
///
|
||||
/// Override in subclasses to publish each `@UIParam` effect parameter with its
|
||||
/// display label and value range. Defaults to an empty list.
|
||||
open var effectKnobs: [PedalKnob] {
|
||||
[]
|
||||
}
|
||||
|
||||
/// All knobs a generic UI should render for this pedal: effect-specific knobs
|
||||
/// first, then the common `mix` and `level` knobs. The `bypass` parameter is
|
||||
/// surfaced separately as a header toggle, not as a knob.
|
||||
public var knobs: [PedalKnob] {
|
||||
effectKnobs + [
|
||||
PedalKnob(label: "Mix", node: $mix, range: 0.0 ... 1.0),
|
||||
PedalKnob(label: "Level", node: $level, range: 0.0 ... 1.0),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Subclass hook
|
||||
|
||||
/// Returns the processed (wet) mono signal for this pedal.
|
||||
///
|
||||
/// The default implementation is a pass-through — override in subclasses to apply
|
||||
/// the desired effect. The return value must be mono.
|
||||
///
|
||||
/// - Parameter dry: The dry signal read from `inputBus`.
|
||||
/// - Returns: The wet processed signal (mono).
|
||||
open func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
dry
|
||||
}
|
||||
|
||||
// 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)
|
||||
|
||||
// Map mix [0, 1] → pan [-1, +1] for CrossFade (−1 = full inA/dry, +1 = full inB/wet).
|
||||
let mixPan: any ValidGeneratorInput = ($mix * bipolarSpan) - bipolarOffset
|
||||
|
||||
// Equal-power crossfade between dry and wet signal.
|
||||
let blended: CrossFade.Audio = CrossFade.Audio(
|
||||
inA: dry,
|
||||
inB: wet,
|
||||
pan: mixPan
|
||||
)
|
||||
|
||||
// Smooth bypass transitions with a 20 ms lag to prevent clicks.
|
||||
let bypassLagged: Lag.Control = Lag.Control(
|
||||
input: $bypass,
|
||||
time: bypassLagTime
|
||||
)
|
||||
|
||||
// Map bypass [0, 1] → pan [-1, +1]: −1 = blended (engaged), +1 = dry (bypassed).
|
||||
let bypassPan: any ValidGeneratorInput = (bypassLagged * bipolarSpan) - bipolarOffset
|
||||
|
||||
// Equal-power crossfade: engaged → blended; bypassed → dry.
|
||||
let switched: CrossFade.Audio = CrossFade.Audio(
|
||||
inA: blended,
|
||||
inB: dry,
|
||||
pan: bypassPan
|
||||
)
|
||||
|
||||
output(bus: outputBus, source: switched * $level)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
// PedalBoard.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// A linear signal chain of `Pedal` instances sharing a dedicated mono bus path, with
|
||||
/// optional parallel sections created via `split()` and `merge()`.
|
||||
///
|
||||
/// `PedalBoard` manages bus allocation and the engine node-tree insertion order
|
||||
/// so that signal flows:
|
||||
///
|
||||
/// ```
|
||||
/// headBus → pedal[0] → pedal[1] → … → pedal[N-1] → outputBus (tail)
|
||||
/// ```
|
||||
///
|
||||
/// Parallel branches can be inserted at any point in the chain:
|
||||
///
|
||||
/// ```
|
||||
/// headBus → pre-pedals → Splitter → branchA pedals ─┐
|
||||
/// → branchB pedals ─┤
|
||||
/// Merger → post-pedals → outputBus
|
||||
/// ```
|
||||
///
|
||||
/// ## Evaluation order
|
||||
///
|
||||
/// Lyrebird evaluates the node tree top-to-bottom. Every node is inserted `.after` its
|
||||
/// predecessor so signal flows correctly:
|
||||
///
|
||||
/// ```
|
||||
/// headInputNode → pedal[0] → … → Splitter → branchA[0] → … → branchB[0] → … → Merger → …
|
||||
/// ```
|
||||
///
|
||||
/// Both branch chains share a single tail tracking pointer so all branch pedals appear in
|
||||
/// a flat linear sequence in the tree, regardless of which branch the caller adds pedals
|
||||
/// to first. The merger is always inserted after the shared tail — i.e. after the last pedal
|
||||
/// added across either branch — ensuring all branch pedals have evaluated before the merge.
|
||||
///
|
||||
/// ## Bus allocation
|
||||
///
|
||||
/// - One mono bus is allocated for the board head (`headBus`).
|
||||
/// - Each `add(_:)` call allocates a new mono bus for the pedal's output.
|
||||
/// - `split()` allocates two branch-input buses (one per branch) and one bus per pedal
|
||||
/// added to each branch.
|
||||
/// - `merge()` allocates one post-merge output bus.
|
||||
/// - Hardware output buses (indices 0..<numOutputChannels) are managed by the engine
|
||||
/// and are never requested from the bus allocator here.
|
||||
///
|
||||
/// ## Thread safety
|
||||
///
|
||||
/// `PedalBoard` is `@MainActor`. All methods must be called from the main thread.
|
||||
@MainActor
|
||||
public final class PedalBoard {
|
||||
|
||||
// MARK: - State
|
||||
|
||||
private let engine: SynthesisEngine
|
||||
|
||||
/// The bus that feeds the first pedal in the chain.
|
||||
public let headBus: AudioBus
|
||||
|
||||
/// 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.
|
||||
/// Before any node is added, this is `headBus` (the board is a pass-through).
|
||||
public private(set) var outputBus: AudioBus
|
||||
|
||||
/// 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).
|
||||
public internal(set) var headInputNode: (any Synthesizer)?
|
||||
|
||||
/// Display label for the board, shown in the UI. Defaults to `"Board"`; `ShoeGaze`
|
||||
/// assigns a numbered label (`"Board 1"`, `"Board 2"`, …) when it creates the board.
|
||||
public var label: String = "Board"
|
||||
|
||||
/// The live master-gain `UIParamNode` for this board's output stage. `nil` until
|
||||
/// `ShoeGaze.finalizeBoard(_:)` connects the output master. Bind a master-volume knob here.
|
||||
public internal(set) var masterGainNode: UIParamNode?
|
||||
|
||||
/// The live board-select gain `UIParamNode` (`1` = audible, `0` = silenced), driven by
|
||||
/// `ShoeGaze.selectBoard(_:crossfadeSeconds:)`. `nil` until `finalizeBoard(_:)`.
|
||||
public internal(set) var selectGainNode: UIParamNode?
|
||||
|
||||
/// The live crossfade-time `UIParamNode` (seconds) for board-select transitions.
|
||||
/// `nil` until `finalizeBoard(_:)`.
|
||||
public internal(set) var crossfadeTimeNode: UIParamNode?
|
||||
|
||||
/// The output master synth for this board. Set by `ShoeGaze.finalizeBoard(_:)`;
|
||||
/// used by `ShoeGaze.removeBoard(_:)` to tear down just this board's master.
|
||||
internal var outputMaster: BoardOutputMaster?
|
||||
|
||||
// MARK: - Private tracking
|
||||
|
||||
/// Tracks all allocated inter-node buses so they can be released on teardown.
|
||||
private var allocatedBuses: [AudioBus] = []
|
||||
|
||||
/// The last node (pedal, splitter, or merger) inserted into the board. Used as the
|
||||
/// `.after(_:)` predecessor for the next inserted node. Falls back to `headInputNode`
|
||||
/// when no node has been added yet.
|
||||
private var lastNode: (any Synthesizer)?
|
||||
|
||||
/// All splitter and merger nodes owned by the board (for removal on teardown).
|
||||
private var routingNodes: [any Synthesizer] = []
|
||||
|
||||
/// All branch chains owned by the board (for teardown).
|
||||
private var branchChains: [BranchChain] = []
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a pedalboard that allocates its head bus and prepares for pedal insertion.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - engine: The `SynthesisEngine` that will own the pedal nodes.
|
||||
/// - Throws: `BusAllocatorError.noFreeBus` if no mono audio bus is available.
|
||||
public init(engine: SynthesisEngine) throws {
|
||||
self.engine = engine
|
||||
let head: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
self.headBus = head
|
||||
self.outputBus = head
|
||||
self.allocatedBuses.append(head)
|
||||
}
|
||||
|
||||
// MARK: - Tail node
|
||||
|
||||
/// The last node inserted into the board (pedal, splitter, or merger), or `nil` if no
|
||||
/// node has been added yet. Used by `ShoeGaze.finalizeBoard(_:)` to position the master
|
||||
/// synth after the entire chain.
|
||||
///
|
||||
/// Falls back to `headInputNode` when no node has been inserted; `finalizeBoard` handles
|
||||
/// the case where both are `nil` by using a plain `engine.add`.
|
||||
public var tailNode: (any Synthesizer)? { lastNode ?? headInputNode }
|
||||
|
||||
// MARK: - Adding pedals
|
||||
|
||||
/// Appends a pedal to the end of the signal chain and adds it to the engine.
|
||||
///
|
||||
/// The pedal's `inputBus` is set to the current tail bus index; a new mono bus is
|
||||
/// allocated for its `outputBus`. After this call, `outputBus` advances to the
|
||||
/// newly allocated output bus.
|
||||
///
|
||||
/// Signal order is maintained by inserting each node `.after(_:)` the previous one
|
||||
/// in the engine's node tree. For the first pedal in the chain, pass `after:` the
|
||||
/// node that writes the head bus (e.g. the input source) so evaluation order is
|
||||
/// preserved: source evaluates first, then the pedal, then subsequent pedals.
|
||||
/// Subsequent calls do not need `after:` — the board tracks `lastNode` internally.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pedal: The `Pedal` instance to append.
|
||||
/// - after: The `Synthesizer` that the first pedal should evaluate after. Only used
|
||||
/// when this is the first node added to the board. Ignored for subsequent nodes
|
||||
/// (the board chains them after the previous node automatically).
|
||||
/// - Throws:
|
||||
/// - `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)
|
||||
}
|
||||
|
||||
pedals.append(pedal)
|
||||
lastNode = pedal
|
||||
outputBus = pedalOutputBus
|
||||
}
|
||||
|
||||
// MARK: - Parallel routing
|
||||
|
||||
/// Inserts a parallel section into the board at the current tail position.
|
||||
///
|
||||
/// Creates a ``Splitter`` that routes the current tail bus into two independent
|
||||
/// branch buses. Returns a ``ParallelSection`` with empty ``BranchChain``s;
|
||||
/// add pedals to each branch via `section.branchA.add(_:)` and
|
||||
/// `section.branchB.add(_:)`, then call ``merge(_:)`` to combine the branches.
|
||||
///
|
||||
/// ## Evaluation order
|
||||
///
|
||||
/// The splitter is inserted after the current tail node (`lastNode` or `headInputNode`).
|
||||
/// Both branch chains share a ``SharedTail`` that starts at the splitter. Every subsequent
|
||||
/// `BranchChain.add(_:)` advances the shared tail so pedals from either branch always
|
||||
/// append after the previous insertion, forming a flat linear chain:
|
||||
///
|
||||
/// ```
|
||||
/// Splitter → [branchA/B pedals in insertion order] → (Merger, added by merge(_:))
|
||||
/// ```
|
||||
///
|
||||
/// - Returns: A ``ParallelSection`` with the splitter and two empty branch chains.
|
||||
/// - Throws:
|
||||
/// - `BusAllocatorError.noFreeBus` if no mono audio bus is available.
|
||||
/// - `EngineAddError` if the engine rejects the splitter add.
|
||||
public func split() throws -> ParallelSection {
|
||||
let preBus: AudioBus = outputBus
|
||||
|
||||
let branchAInBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let branchBInBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
// Branch input buses are tracked (and released) by each BranchChain, not here.
|
||||
// Do not append to allocatedBuses to avoid a double-release on teardown.
|
||||
|
||||
let splitter: Splitter = Splitter(
|
||||
inputBus: preBus.index,
|
||||
outputBusA: branchAInBus.index,
|
||||
outputBusB: branchBInBus.index
|
||||
)
|
||||
|
||||
if let previous: any Synthesizer = lastNode {
|
||||
try engine.add(splitter, position: .after(previous))
|
||||
} else if let head: any Synthesizer = headInputNode {
|
||||
try engine.add(splitter, position: .after(head))
|
||||
} else {
|
||||
try engine.add(splitter)
|
||||
}
|
||||
|
||||
routingNodes.append(splitter)
|
||||
lastNode = splitter
|
||||
|
||||
// Both branch chains share a single tail pointer so their pedals form a flat linear
|
||||
// sequence in the node tree rather than two sibling sub-trees both rooted at the
|
||||
// splitter. This guarantees all branch pedals evaluate before the merger regardless
|
||||
// of whether the caller adds pedals to branchA first, branchB first, or interleaved.
|
||||
let tail: SharedTail = SharedTail(node: splitter)
|
||||
|
||||
let chainA: BranchChain = BranchChain(
|
||||
engine: engine,
|
||||
inputBus: branchAInBus,
|
||||
sampleRate: engine.sampleRate,
|
||||
sharedTail: tail
|
||||
)
|
||||
let chainB: BranchChain = BranchChain(
|
||||
engine: engine,
|
||||
inputBus: branchBInBus,
|
||||
sampleRate: engine.sampleRate,
|
||||
sharedTail: tail
|
||||
)
|
||||
branchChains.append(chainA)
|
||||
branchChains.append(chainB)
|
||||
|
||||
return ParallelSection(splitter: splitter, branchA: chainA, branchB: chainB, sharedTail: tail)
|
||||
}
|
||||
|
||||
/// Combines the two branches of a ``ParallelSection`` back into the main board chain.
|
||||
///
|
||||
/// Creates a ``Merger`` that sums the tail buses of both branches into a new output bus.
|
||||
/// The merger is inserted after the section's shared tail node — the last node inserted
|
||||
/// across either branch. Because both branch chains share a single ``SharedTail`` pointer,
|
||||
/// this is always the most recently added pedal from either branch, guaranteeing all branch
|
||||
/// pedals have evaluated before the merger reads their output buses.
|
||||
///
|
||||
/// After `merge(_:)` returns, subsequent `board.add(_:)` calls chain after the merger.
|
||||
///
|
||||
/// - Parameter section: A ``ParallelSection`` returned by ``split()`` with pedals added to
|
||||
/// each branch. Passing the same section twice or a section from a different board is
|
||||
/// undefined behaviour.
|
||||
/// - Throws:
|
||||
/// - `BusAllocatorError.noFreeBus` if no mono audio bus is available for the post-merge bus.
|
||||
/// - `EngineAddError` if the engine rejects the merger add.
|
||||
public func merge(_ section: ParallelSection) throws {
|
||||
let branchAOut: Int = section.branchA.tailBusIndex
|
||||
let branchBOut: Int = section.branchB.tailBusIndex
|
||||
|
||||
let postBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
allocatedBuses.append(postBus)
|
||||
|
||||
let merger: Merger = Merger(
|
||||
inputBusA: branchAOut,
|
||||
inputBusB: branchBOut,
|
||||
outputBus: postBus.index
|
||||
)
|
||||
|
||||
// Insert merger after the shared tail — the last node inserted across either branch.
|
||||
// Because both branch chains share a single `SharedTail` pointer, `sharedTail.node`
|
||||
// is always the node that was most recently added to the tree (from either branch).
|
||||
// This guarantees all branch pedals have written their output buses before the merger
|
||||
// reads them, regardless of which branch the caller added pedals to last.
|
||||
let mergerPredecessor: any Synthesizer = section.sharedTail.node
|
||||
try engine.add(merger, position: .after(mergerPredecessor))
|
||||
|
||||
routingNodes.append(merger)
|
||||
lastNode = merger
|
||||
outputBus = postBus
|
||||
}
|
||||
|
||||
// MARK: - Teardown
|
||||
|
||||
/// Removes all pedals, routing nodes, and branch chains from the engine and releases
|
||||
/// all allocated buses.
|
||||
///
|
||||
/// Removal order follows the remove-before-release invariant:
|
||||
///
|
||||
/// 1. Remove main-chain pedals from the engine.
|
||||
/// 2. Remove all routing nodes (splitters, mergers) — these write branch buses that
|
||||
/// the next step releases, so they must be dequeued first.
|
||||
/// 3. `BranchChain.teardown()` for each branch — removes branch pedals and releases
|
||||
/// branch buses (safe because the splitter/merger writers are already dequeued).
|
||||
/// 4. Release board-owned buses.
|
||||
///
|
||||
/// - Important: Call only after the engine has been stopped, or accept one block
|
||||
/// of glitch on a still-running engine. `engine.remove(_:)` only enqueues removal;
|
||||
/// the actual dequeue happens on the next render block. Releasing buses immediately
|
||||
/// after enqueue means a still-running engine could write to a reallocated bus for
|
||||
/// one block. The buses are pooled (not freed), so worst case is a transient glitch,
|
||||
/// not a crash. Stop the engine first to avoid this.
|
||||
///
|
||||
/// After calling this method the `PedalBoard` should not be reused.
|
||||
public func teardown() {
|
||||
// Step 1: Remove main-chain pedals.
|
||||
for pedal: Pedal in pedals {
|
||||
engine.remove(pedal)
|
||||
}
|
||||
pedals.removeAll()
|
||||
|
||||
// Step 2: Remove routing nodes (splitters and mergers) BEFORE releasing the branch
|
||||
// buses they write/read. BranchChain.teardown() releases those buses in step 3,
|
||||
// so the writers must be dequeued first.
|
||||
for node: any Synthesizer in routingNodes {
|
||||
engine.remove(node)
|
||||
}
|
||||
routingNodes.removeAll()
|
||||
|
||||
// Step 3: Remove branch pedals and release branch buses.
|
||||
for chain: BranchChain in branchChains {
|
||||
chain.teardown()
|
||||
}
|
||||
branchChains.removeAll()
|
||||
|
||||
lastNode = nil
|
||||
|
||||
// Step 4: Release board-owned buses (head bus and main-chain inter-node buses).
|
||||
for bus: AudioBus in allocatedBuses {
|
||||
engine.busAllocator.releaseAudioBus(bus)
|
||||
}
|
||||
allocatedBuses.removeAll()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// PedalKnob.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdUI
|
||||
|
||||
/// A UI-agnostic description of one controllable pedal knob.
|
||||
///
|
||||
/// A `Pedal` publishes an array of these (via ``Pedal/knobs``) so a generic
|
||||
/// pedalboard UI can render a rotary control per parameter without knowing the
|
||||
/// concrete pedal type. Each descriptor pairs a display label with the live
|
||||
/// ``UIParamNode`` (the projected value of an `@UIParam` property) and the
|
||||
/// value range the control should span.
|
||||
public struct PedalKnob {
|
||||
|
||||
/// Short label shown beneath the knob (e.g. "Drive", "Mix").
|
||||
public let label: String
|
||||
|
||||
/// The live parameter node the knob reads and writes. Pass `pedal.$paramName`.
|
||||
public let node: UIParamNode
|
||||
|
||||
/// Inclusive value range the knob spans, in the parameter's own units.
|
||||
public let range: ClosedRange<Double>
|
||||
|
||||
/// Creates a knob descriptor.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - label: Short label shown beneath the knob.
|
||||
/// - node: The `UIParamNode` projected value of an `@UIParam` property
|
||||
/// (`pedal.$drive`, `pedal.$mix`, …).
|
||||
/// - range: Inclusive value range the knob spans, in the parameter's units.
|
||||
public init(
|
||||
label: String,
|
||||
node: UIParamNode,
|
||||
range: ClosedRange<Double>
|
||||
) {
|
||||
self.label = label
|
||||
self.node = node
|
||||
self.range = range
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
// CompressorPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Compressor pedal: feed-forward dynamic range compressor.
|
||||
///
|
||||
/// Signal chain (inside `effect(_:)`):
|
||||
/// ```
|
||||
/// dry → Compressor.Audio(threshold:, ratio:, attack:, release:, makeupGain:) → mono out
|
||||
/// ```
|
||||
///
|
||||
/// Attack, release, knee, and makeup gain are fixed at musically sensible defaults.
|
||||
/// Knobs expose the two most-musical parameters: threshold and ratio.
|
||||
///
|
||||
/// The wet/dry mix and bypass switching are handled by the `Pedal` base class.
|
||||
///
|
||||
/// ## Parameters
|
||||
///
|
||||
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - threshold: Gain-reduction threshold in dB. Signals above this level are
|
||||
/// compressed. Range `[-40, 0]` dB. Defaults to `-12.0`.
|
||||
/// - ratio: Compression ratio `≥ 1.0`. `1.0` = bypass, `4.0` = 4:1 compression.
|
||||
/// Range `[1, 20]`. Defaults to `4.0`.
|
||||
public final class CompressorPedal: Pedal {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Compression threshold in dB. Range [-40, 0].
|
||||
@UIParam public var threshold: Double = -12.0
|
||||
|
||||
/// Compression ratio. Range [1, 20].
|
||||
@UIParam public var ratio: Double = 4.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Default wet/dry blend — fully wet; the compressor is inserted in-line.
|
||||
private static let defaultMix: Double = 1.0
|
||||
|
||||
/// Attack time constant in seconds — time to reach full gain reduction on a transient.
|
||||
private let attackTime: Double = 0.01
|
||||
|
||||
/// Release time constant in seconds — time for gain to recover after level drops below threshold.
|
||||
private let releaseTime: Double = 0.1
|
||||
|
||||
/// Soft-knee width in dB. Zero = hard knee for maximum punch.
|
||||
private let kneeWidth: Double = 0.0
|
||||
|
||||
/// Makeup gain in dB applied after compression to restore perceived loudness.
|
||||
private let makeupGainDB: Double = 4.0
|
||||
|
||||
// MARK: - UI knobs
|
||||
|
||||
/// Threshold knob range in dB.
|
||||
private let thresholdRange: ClosedRange<Double> = -40.0 ... 0.0
|
||||
|
||||
/// Ratio knob range.
|
||||
private let ratioRange: ClosedRange<Double> = 1.0 ... 20.0
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Threshold", node: $threshold, range: thresholdRange),
|
||||
PedalKnob(label: "Ratio", node: $ratio, range: ratioRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a compressor pedal.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
|
||||
public init(
|
||||
inputBus: Int = 0,
|
||||
outputBus: Int = 0
|
||||
) {
|
||||
super.init(
|
||||
name: "Compressor",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: CompressorPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
/// Applies feed-forward dynamic range compression.
|
||||
///
|
||||
/// Output is mono.
|
||||
///
|
||||
/// - Parameter dry: Dry mono input signal.
|
||||
/// - Returns: Compressed mono output.
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
Compressor.Audio(
|
||||
in: dry,
|
||||
threshold: $threshold,
|
||||
ratio: $ratio,
|
||||
attack: attackTime,
|
||||
release: releaseTime,
|
||||
kneeWidth: kneeWidth,
|
||||
makeupGain: makeupGainDB
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// DelayPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Delay pedal: feedback delay line.
|
||||
///
|
||||
/// Signal chain (inside `effect(_:)`):
|
||||
/// ```
|
||||
/// dry → DelayLineFeedback(delay: time, decayTime: feedback) → mono wet out
|
||||
/// ```
|
||||
///
|
||||
/// `effect` returns the pure wet delay signal. The base `Pedal` class handles
|
||||
/// wet/dry blending via `mix`, so do not pre-blend inside `effect`.
|
||||
///
|
||||
/// ## Parameters
|
||||
///
|
||||
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - time: Delay time in seconds. Range `[0.01, 1.5]`. Defaults to `0.25`.
|
||||
/// - feedback: Feedback amount expressed as decay time in seconds — the time
|
||||
/// for echoes to fall to `targetAmp` (−60 dB). Longer values produce more
|
||||
/// repeats. Range `[0.05, 6.0]` seconds. Defaults to `1.0`.
|
||||
public final class DelayPedal: Pedal {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Delay time in seconds. Range [0.01, 1.5].
|
||||
@UIParam public var time: Double = 0.25
|
||||
|
||||
/// Feedback decay time in seconds (time to reach −60 dB amplitude).
|
||||
@UIParam public var feedback: Double = 1.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Maximum supported delay time in seconds. Sizes the delay line buffer at init.
|
||||
private let maxDelayTime: Double = 1.5
|
||||
|
||||
/// Amplitude target for the `decayTime` calculation (−60 dB).
|
||||
private let targetAmp: Double = 0.001
|
||||
|
||||
/// Default wet/dry blend — a partial mix so dry signal and echoes coexist.
|
||||
private static let defaultMix: Double = 0.35
|
||||
|
||||
// MARK: - UI knobs
|
||||
|
||||
/// Delay-time knob range in seconds.
|
||||
private let timeRange: ClosedRange<Double> = 0.01 ... 1.5
|
||||
|
||||
/// Feedback (decay-time) knob range in seconds.
|
||||
private let feedbackRange: ClosedRange<Double> = 0.05 ... 6.0
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a delay pedal.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
|
||||
public init(
|
||||
inputBus: Int = 0,
|
||||
outputBus: Int = 0
|
||||
) {
|
||||
super.init(
|
||||
name: "Delay",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: DelayPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Time", node: $time, range: timeRange),
|
||||
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
/// Applies a feedback delay line. Returns the pure wet (delayed) signal.
|
||||
///
|
||||
/// The base class `Pedal` mixes this with the dry signal via the `mix` parameter.
|
||||
///
|
||||
/// - Parameter dry: Dry mono input signal.
|
||||
/// - Returns: Pure wet mono delayed output.
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
DelayLineFeedback(
|
||||
input: dry,
|
||||
maxDelay: maxDelayTime,
|
||||
delay: $time,
|
||||
decayTime: $feedback,
|
||||
targetAmp: targetAmp,
|
||||
sampleRate: sampleRate,
|
||||
interpolation: .linear
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
// FuzzPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Fuzz pedal: high-gain `tanh` saturation followed by a tonal low-pass filter.
|
||||
///
|
||||
/// Signal chain (inside `effect(_:)`):
|
||||
/// ```
|
||||
/// dry → (× fuzz drive) → Tanh → RBJLowPass(freq: tone, q: 0.707) → mono out
|
||||
/// ```
|
||||
///
|
||||
/// The `fuzz` knob is a pre-gain (drive): it multiplies the input hard before the
|
||||
/// `tanh` saturator, which squares the waveform off into the thick, sustaining fuzz
|
||||
/// texture. Because `tanh` saturates toward ±1, the output level stays roughly constant
|
||||
/// as `fuzz` rises — more drive means more grit and sustain, never less signal. A tone
|
||||
/// filter then rolls off high-frequency harshness.
|
||||
///
|
||||
/// > Note: This deliberately differs from the earlier crossover-distortion model, where
|
||||
/// > the knob set a silent dead-zone width and large values muted quiet signals.
|
||||
///
|
||||
/// The wet/dry mix and bypass switching are handled by the `Pedal` base class.
|
||||
///
|
||||
/// ## Parameters
|
||||
///
|
||||
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - fuzz: Pre-gain drive into the `tanh` saturator. Higher = more saturation and
|
||||
/// sustain. Range `[1, 60]`. Defaults to `20.0`.
|
||||
/// - tone: Low-pass tone cutoff in Hz. Roll off high-frequency fuzz harshness.
|
||||
/// Range `[200, 8000]` Hz. Defaults to `3500.0`.
|
||||
public final class FuzzPedal: Pedal {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Pre-gain drive into the saturator. Range [1, 60]; higher = more fuzz.
|
||||
@UIParam public var fuzz: Double = 20.0
|
||||
|
||||
/// Tone filter cutoff frequency in Hz. Range [200, 8000].
|
||||
@UIParam public var tone: Double = 3500.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Default wet/dry blend — fully wet so fuzz completely replaces dry signal.
|
||||
private static let defaultMix: Double = 1.0
|
||||
|
||||
/// Q factor for the tone low-pass filter. Butterworth response (no resonant peak).
|
||||
private let toneQ: Double = 0.707
|
||||
|
||||
/// Output trim applied after the `tanh` saturator so the fuzz sits at a sane level
|
||||
/// relative to the other pedals (`tanh` output is roughly ±1).
|
||||
private let outputTrim: Double = 0.6
|
||||
|
||||
// MARK: - UI knobs
|
||||
|
||||
/// Fuzz knob range (saturator pre-gain / drive).
|
||||
private let fuzzRange: ClosedRange<Double> = 1.0 ... 60.0
|
||||
|
||||
/// Tone knob range in Hz (low-pass cutoff).
|
||||
private let toneRange: ClosedRange<Double> = 200.0 ... 8000.0
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Fuzz", node: $fuzz, range: fuzzRange),
|
||||
PedalKnob(label: "Tone", node: $tone, range: toneRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a fuzz pedal.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
|
||||
public init(
|
||||
inputBus: Int = 0,
|
||||
outputBus: Int = 0
|
||||
) {
|
||||
super.init(
|
||||
name: "Fuzz",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: FuzzPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
/// Drives the input hard into a `tanh` saturator, then applies a tonal low-pass.
|
||||
///
|
||||
/// Output is mono.
|
||||
///
|
||||
/// - Parameter dry: Dry mono input signal.
|
||||
/// - Returns: Fuzzed and tone-shaped mono output.
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
// Pre-gain the signal hard, then saturate. `tanh` squares the waveform off as the
|
||||
// drive rises while keeping the level bounded — the hallmark of a fuzz.
|
||||
let driven: any ValidGeneratorInput = dry * $fuzz
|
||||
let saturated: Tanh.Audio = Tanh.Audio(driven, mul: outputTrim)
|
||||
return RBJLowPass.Audio(
|
||||
input: saturated,
|
||||
freq: $tone,
|
||||
q: toneQ
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// ModulationPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Modulation pedal: stereo chorus folded to mono.
|
||||
///
|
||||
/// Signal chain (inside `effect(_:)`):
|
||||
/// ```
|
||||
/// dry → Chorus.Audio(mix: 1.0, rate:, depth:) → stereo (2 ch)
|
||||
/// → SumChannels.Audio(mul: 0.5) → mono
|
||||
/// ```
|
||||
///
|
||||
/// `Chorus.Audio` has a built-in `mix` parameter that blends dry+wet internally.
|
||||
/// Here it is set to `1.0` (fully wet) so the base `Pedal` class handles dry/wet
|
||||
/// blending uniformly via its own `mix` parameter.
|
||||
///
|
||||
/// The stereo output from `Chorus` is summed to mono with a ×0.5 gain to compensate
|
||||
/// for channel doubling.
|
||||
///
|
||||
/// ## Parameters
|
||||
///
|
||||
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - rate: Chorus LFO frequency in Hz. Range `[0.1, 10]`. Defaults to `1.5`.
|
||||
/// - depth: Chorus modulation depth as a fraction of the delay time in [0, 1].
|
||||
/// Smaller values (0.001–0.01) produce classic chorus width. Defaults to `0.002`.
|
||||
public final class ModulationPedal: Pedal {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Chorus LFO rate in Hz. Range [0.1, 10].
|
||||
@UIParam public var rate: Double = 1.5
|
||||
|
||||
/// Chorus modulation depth as a fraction of delay time in [0, 1].
|
||||
@UIParam public var depth: Double = 0.002
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Chorus `mix` value. Set to 1.0 (fully wet) so the base `Pedal` handles
|
||||
/// the dry/wet blend via its own `mix` parameter.
|
||||
private let chorusWetMix: Double = 1.0
|
||||
|
||||
/// Base delay time for the chorus in seconds.
|
||||
private let chorusDelayTime: Double = 0.025
|
||||
|
||||
/// Maximum delay time that the chorus delay line is allocated for.
|
||||
private let chorusMaxDelayTime: Double = 0.1
|
||||
|
||||
/// Gain applied to the summed stereo→mono output to compensate for channel doubling.
|
||||
private let stereoSumGain: Double = 0.5
|
||||
|
||||
/// Default wet/dry blend — an even mix for classic chorus width.
|
||||
private static let defaultMix: Double = 0.5
|
||||
|
||||
// MARK: - UI knobs
|
||||
|
||||
/// Rate knob range in Hz (chorus LFO frequency).
|
||||
private let rateRange: ClosedRange<Double> = 0.1 ... 8.0
|
||||
|
||||
/// Depth knob range (fraction of delay time).
|
||||
private let depthRange: ClosedRange<Double> = 0.0005 ... 0.01
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a modulation (chorus) pedal.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
|
||||
public init(
|
||||
inputBus: Int = 0,
|
||||
outputBus: Int = 0
|
||||
) {
|
||||
super.init(
|
||||
name: "Modulation",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: ModulationPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Rate", node: $rate, range: rateRange),
|
||||
PedalKnob(label: "Depth", node: $depth, range: depthRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
/// Applies stereo chorus and folds the result to mono.
|
||||
///
|
||||
/// Returns a mono wet signal. The base `Pedal` class mixes this with the
|
||||
/// dry signal according to the `mix` parameter.
|
||||
///
|
||||
/// - Parameter dry: Dry mono input signal.
|
||||
/// - Returns: Wet mono chorus output.
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
// Chorus.Audio produces a 2-channel stereo output.
|
||||
let stereoChorus: Chorus.Audio = Chorus.Audio(
|
||||
input: dry,
|
||||
delayTime: chorusDelayTime,
|
||||
depth: $depth,
|
||||
rate: $rate,
|
||||
mix: chorusWetMix,
|
||||
sampleRate: sampleRate,
|
||||
maxDelayTime: chorusMaxDelayTime
|
||||
)
|
||||
// Sum stereo → mono with ×0.5 to avoid level doubling.
|
||||
return SumChannels.Audio(
|
||||
input: stereoChorus,
|
||||
mul: stereoSumGain
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
// OverdrivePedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Overdrive pedal: soft-clipping saturation followed by a tonal low-pass filter.
|
||||
///
|
||||
/// Signal chain (inside `effect(_:)`):
|
||||
/// ```
|
||||
/// dry → SoftClip(drive:) → RBJLowPass(freq: tone, q: 0.707) → mono out
|
||||
/// ```
|
||||
///
|
||||
/// The wet/dry mix and bypass switching are handled by the `Pedal` base class.
|
||||
///
|
||||
/// ## Parameters
|
||||
///
|
||||
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - drive: Saturation amount. Higher values push more of the signal into soft-clip
|
||||
/// territory. Range `[1, 20]`. Defaults to `4.0`.
|
||||
/// - tone: Low-pass tone cutoff in Hz. Roll off high-frequency harshness.
|
||||
/// Range `(0, 20000]`. Defaults to `4000.0`.
|
||||
public final class OverdrivePedal: Pedal {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Saturation drive amount. Range [1, 20]; higher = more clipping.
|
||||
@UIParam public var drive: Double = 4.0
|
||||
|
||||
/// Tone filter cutoff frequency in Hz. Range (0, 20000].
|
||||
@UIParam public var tone: Double = 4000.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Q factor for the tone low-pass filter. Butterworth response (no resonant peak).
|
||||
private let toneQ: Double = 0.707
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates an overdrive pedal.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
|
||||
public init(
|
||||
inputBus: Int = 0,
|
||||
outputBus: Int = 0
|
||||
) {
|
||||
super.init(name: "Overdrive", inputBus: inputBus, outputBus: outputBus)
|
||||
}
|
||||
|
||||
// MARK: - UI knobs
|
||||
|
||||
/// Drive knob range (waveshaper input gain).
|
||||
private let driveRange: ClosedRange<Double> = 1.0 ... 20.0
|
||||
|
||||
/// Tone knob range in Hz (low-pass cutoff).
|
||||
private let toneRange: ClosedRange<Double> = 200.0 ... 8000.0
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Drive", node: $drive, range: driveRange),
|
||||
PedalKnob(label: "Tone", node: $tone, range: toneRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
/// Applies soft-clip saturation followed by a tonal low-pass filter.
|
||||
///
|
||||
/// Output is mono.
|
||||
///
|
||||
/// - Parameter dry: Dry mono input signal.
|
||||
/// - Returns: Saturated and tone-shaped mono output.
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
let saturated: SoftClip.Audio = SoftClip.Audio(dry, drive: $drive)
|
||||
return RBJLowPass.Audio(
|
||||
input: saturated,
|
||||
freq: $tone,
|
||||
q: toneQ
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// PhaserPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Phaser pedal: cascaded all-pass filter swept by a sine LFO.
|
||||
///
|
||||
/// Signal chain (inside `effect(_:)`):
|
||||
/// ```
|
||||
/// dry → Phaser.Audio(rate:, feedback:, mix: 1.0) → mono out
|
||||
/// ```
|
||||
///
|
||||
/// `Phaser.Audio` is mono-in / mono-out. Its internal `mix` is set to `1.0` (fully
|
||||
/// wet) so the base `Pedal` class handles the dry/wet blend uniformly via its own
|
||||
/// `mix` parameter.
|
||||
///
|
||||
/// The wet/dry mix and bypass switching are handled by the `Pedal` base class.
|
||||
///
|
||||
/// ## Parameters
|
||||
///
|
||||
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - rate: LFO sweep rate in Hz. Range `[0.05, 5.0]`. Defaults to `0.5`.
|
||||
/// - feedback: Feedback gain in `[0, 0.9]`. Higher values deepen the notches.
|
||||
/// Range `[0.0, 0.9]`. Defaults to `0.5`.
|
||||
public final class PhaserPedal: Pedal {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// LFO sweep rate in Hz. Range [0.05, 5.0].
|
||||
@UIParam public var rate: Double = 0.5
|
||||
|
||||
/// Feedback gain in [0, 0.9]. Deepens the all-pass notches.
|
||||
@UIParam public var feedback: Double = 0.5
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Default wet/dry blend — even mix for classic phaser comb-filter sweep.
|
||||
private static let defaultMix: Double = 0.5
|
||||
|
||||
/// Internal `Phaser.Audio` mix — set to 1.0 so the base `Pedal` handles dry/wet.
|
||||
private let phaserInternalMix: Double = 1.0
|
||||
|
||||
/// LFO depth fraction — sweeps the all-pass coefficient across its full range.
|
||||
private let phaserDepth: Double = 0.9
|
||||
|
||||
/// Center frequency in Hz for the all-pass coefficient sweep.
|
||||
private let phaserCenterFreq: Double = 800.0
|
||||
|
||||
/// Number of cascaded all-pass stages. Must be 4, 6, or 8.
|
||||
private let phaserStages: Int = 6
|
||||
|
||||
// MARK: - UI knobs
|
||||
|
||||
/// Rate knob range in Hz (LFO sweep frequency).
|
||||
private let rateRange: ClosedRange<Double> = 0.05 ... 5.0
|
||||
|
||||
/// Feedback knob range (all-pass feedback gain).
|
||||
private let feedbackRange: ClosedRange<Double> = 0.0 ... 0.9
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Rate", node: $rate, range: rateRange),
|
||||
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a phaser pedal.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
|
||||
public init(
|
||||
inputBus: Int = 0,
|
||||
outputBus: Int = 0
|
||||
) {
|
||||
super.init(
|
||||
name: "Phaser",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: PhaserPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
/// Applies cascaded all-pass phasing and returns the fully-wet signal.
|
||||
///
|
||||
/// `Phaser.Audio` is mono-in / mono-out. The base `Pedal` class mixes this with
|
||||
/// the dry signal according to the `mix` parameter.
|
||||
///
|
||||
/// - Parameter dry: Dry mono input signal.
|
||||
/// - Returns: Wet mono phaser output.
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
Phaser.Audio(
|
||||
input: dry,
|
||||
rate: $rate,
|
||||
depth: phaserDepth,
|
||||
centerFreq: phaserCenterFreq,
|
||||
feedback: $feedback,
|
||||
stages: phaserStages,
|
||||
mix: phaserInternalMix,
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// ReverbPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Reverb pedal: Freeverb stereo reverb folded to mono.
|
||||
///
|
||||
/// Signal chain (inside `effect(_:)`):
|
||||
/// ```
|
||||
/// dry → FreeVerb.Audio(mix: 1.0, roomSize:, damping:) → stereo (2 ch)
|
||||
/// → SumChannels.Audio(mul: 0.5) → mono (fold + compensate)
|
||||
/// ```
|
||||
///
|
||||
/// `FreeVerb` is driven at `mix: 1.0` so it produces a pure wet signal; the base
|
||||
/// `Pedal` class handles the wet/dry blend via its `mix` parameter. The stereo
|
||||
/// output from `FreeVerb` is summed to mono with a ×0.5 gain to compensate for
|
||||
/// the channel doubling.
|
||||
///
|
||||
/// ## Parameters
|
||||
///
|
||||
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - roomSize: Room size in [0, 1]. Larger values produce longer, denser tails.
|
||||
/// Defaults to `0.6`.
|
||||
/// - damping: High-frequency damping in [0, 1]. Higher values produce darker,
|
||||
/// shorter tails. Defaults to `0.5`.
|
||||
public final class ReverbPedal: Pedal {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Room size in [0, 1]. Larger = longer reverb tail.
|
||||
@UIParam public var roomSize: Double = 0.6
|
||||
|
||||
/// High-frequency damping in [0, 1]. Higher = darker tail.
|
||||
@UIParam public var damping: Double = 0.5
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// FreeVerb mix value. Set to 1.0 so FreeVerb produces pure wet output;
|
||||
/// the base Pedal handles dry/wet blending via its own `mix` parameter.
|
||||
private let freeVerbWetMix: Double = 1.0
|
||||
|
||||
/// Gain applied to the summed stereo→mono fold to compensate for the doubling
|
||||
/// of energy when two channels are added together.
|
||||
private let stereoSumGain: Double = 0.5
|
||||
|
||||
/// Default wet/dry blend — a partial mix so the dry signal stays up front.
|
||||
private static let defaultMix: Double = 0.3
|
||||
|
||||
// MARK: - UI knobs
|
||||
|
||||
/// Room-size and damping knob range (both normalised [0, 1]).
|
||||
private let normalizedRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a reverb pedal.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
|
||||
public init(
|
||||
inputBus: Int = 0,
|
||||
outputBus: Int = 0
|
||||
) {
|
||||
super.init(
|
||||
name: "Reverb",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: ReverbPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Room", node: $roomSize, range: normalizedRange),
|
||||
PedalKnob(label: "Damp", node: $damping, range: normalizedRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
/// Applies Freeverb stereo reverb and folds the result to mono.
|
||||
///
|
||||
/// Returns a mono wet signal. The base `Pedal` class mixes this with the
|
||||
/// dry signal according to the `mix` parameter.
|
||||
///
|
||||
/// - Parameter dry: Dry mono input signal.
|
||||
/// - Returns: Wet mono reverberated output.
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
// FreeVerb produces a 2-channel stereo output.
|
||||
let stereoVerb: FreeVerb.Audio = FreeVerb.Audio(
|
||||
source: dry,
|
||||
roomSize: $roomSize,
|
||||
damping: $damping,
|
||||
mix: freeVerbWetMix,
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
// Sum stereo → mono with ×0.5 to avoid level doubling.
|
||||
return SumChannels.Audio(
|
||||
input: stereoVerb,
|
||||
mul: stereoSumGain
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// TremoloPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Tremolo pedal: amplitude modulation via a unipolar sine LFO.
|
||||
///
|
||||
/// Signal chain (inside `effect(_:)`):
|
||||
/// ```
|
||||
/// dry × OscSin(freq: rate, mul: depth×0.5, add: 1−depth×0.5) → mono out
|
||||
/// ```
|
||||
///
|
||||
/// The LFO oscillates between `[1 − depth, 1]` so full depth produces silence-to-unity
|
||||
/// swells while zero depth leaves the signal unmodified. The result is a gain effect —
|
||||
/// `defaultMix` is `1.0` (fully wet) so the base `Pedal` passes the tremolo signal through
|
||||
/// unchanged; the `mix` knob can soften the wobble effect.
|
||||
///
|
||||
/// The wet/dry mix and bypass switching are handled by the `Pedal` base class.
|
||||
///
|
||||
/// ## Parameters
|
||||
///
|
||||
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - rate: LFO modulation rate in Hz. Range `[0.5, 12]`. Defaults to `4.0`.
|
||||
/// - depth: Modulation depth in `[0, 1]`. `0` = no modulation, `1` = full tremolo.
|
||||
/// Defaults to `0.7`.
|
||||
public final class TremoloPedal: Pedal {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// LFO rate in Hz. Range [0.5, 12].
|
||||
@UIParam public var rate: Double = 4.0
|
||||
|
||||
/// Modulation depth in [0, 1].
|
||||
@UIParam public var depth: Double = 0.7
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Default wet/dry blend — fully wet; tremolo is a gain effect so dry/wet
|
||||
/// blending does not apply in the same way as a parallel effect.
|
||||
private static let defaultMix: Double = 1.0
|
||||
|
||||
/// Scale factor applied to `depth` to compute the LFO half-amplitude swing.
|
||||
/// At full depth the LFO oscillates over half the normalised range, so the
|
||||
/// peak gain is 1.0 and the trough is `1 − depth`.
|
||||
private let lfoDepthScale: Double = 0.5
|
||||
|
||||
// MARK: - UI knobs
|
||||
|
||||
/// Rate knob range in Hz (LFO frequency).
|
||||
private let rateRange: ClosedRange<Double> = 0.5 ... 12.0
|
||||
|
||||
/// Depth knob range (modulation fraction).
|
||||
private let depthRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Rate", node: $rate, range: rateRange),
|
||||
PedalKnob(label: "Depth", node: $depth, range: depthRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a tremolo pedal.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
|
||||
public init(
|
||||
inputBus: Int = 0,
|
||||
outputBus: Int = 0
|
||||
) {
|
||||
super.init(
|
||||
name: "Tremolo",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: TremoloPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
/// Multiplies the dry signal by a unipolar sine LFO.
|
||||
///
|
||||
/// The LFO range is `[1 − depth, 1]`. At `depth = 0` the multiplier is constant 1.0;
|
||||
/// at `depth = 1` it swings between `0.0` and `1.0`.
|
||||
///
|
||||
/// Output is mono.
|
||||
///
|
||||
/// - Parameter dry: Dry mono input signal.
|
||||
/// - Returns: Amplitude-modulated mono output.
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
// lfoScale = depth × lfoDepthScale → LFO swing half-amplitude
|
||||
// lfoOffset = 1 − depth × lfoDepthScale → LFO centre, so peak = 1.0, trough = 1 − depth
|
||||
let lfoScale: any ValidGeneratorInput = $depth * lfoDepthScale
|
||||
let lfoOffset: any ValidGeneratorInput = 1.0 - ($depth * lfoDepthScale)
|
||||
let lfo: OscSin.Audio = OscSin.Audio(
|
||||
freq: $rate,
|
||||
mul: lfoScale,
|
||||
add: lfoOffset
|
||||
)
|
||||
return dry * lfo
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// BoardState.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Serialisable snapshot of one `PedalBoard`'s label and pedal chain.
|
||||
///
|
||||
/// `label` is the board's display name. `pedals` contains one `PedalState` per
|
||||
/// pedal in signal-flow order. Unknown pedal types in the array are skipped
|
||||
/// silently during `ShoeGaze.loadRig(from:)`.
|
||||
public struct BoardState: Codable, Equatable {
|
||||
|
||||
/// The board's display label (e.g. `"Board 1"`).
|
||||
public let label: String
|
||||
|
||||
/// Ordered list of pedal snapshots in signal-flow order.
|
||||
public let pedals: [PedalState]
|
||||
|
||||
/// Creates a board state snapshot.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - label: The board's display label.
|
||||
/// - pedals: Ordered list of pedal state snapshots.
|
||||
public init(
|
||||
label: String,
|
||||
pedals: [PedalState]
|
||||
) {
|
||||
self.label = label
|
||||
self.pedals = pedals
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// BoardVersion.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// A named, timestamped snapshot of a single `PedalBoard`'s label and pedal chain.
|
||||
///
|
||||
/// `BoardVersion` is the unit stored and retrieved by `BoardVersionStore`. Each version
|
||||
/// captures a complete `BoardState` (pedal types, knob values, bypass flags) alongside
|
||||
/// a human-readable `name` (e.g. `"Lead Crunch"`) and a `savedAt` timestamp.
|
||||
///
|
||||
/// `BoardVersion` is `Codable` so it can be written to and read from JSON files by
|
||||
/// `BoardVersionStore`. It is `Identifiable` (via `UUID`) so SwiftUI `List` and
|
||||
/// `ForEach` views can use it directly, and `Equatable` for round-trip testing.
|
||||
///
|
||||
/// ## Typical usage
|
||||
///
|
||||
/// ```swift
|
||||
/// let store = BoardVersionStore()
|
||||
/// store.capture(myBoard, name: "Lead Crunch")
|
||||
/// try store.writeAllToDisk(in: BoardVersionStore.defaultDirectory())
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - id: Stable unique identifier for this version.
|
||||
/// - name: Human-readable label (e.g. `"Lead Crunch"`).
|
||||
/// - savedAt: The `Date` when this version was captured.
|
||||
/// - state: The full `BoardState` snapshot.
|
||||
public struct BoardVersion: Codable, Identifiable, Equatable {
|
||||
|
||||
/// Stable unique identifier for this version entry.
|
||||
public let id: UUID
|
||||
|
||||
/// Human-readable name for this version (e.g. `"Lead Crunch"`, `"Clean Wash"`).
|
||||
public let name: String
|
||||
|
||||
/// Date and time at which this version was captured, at **whole-second precision**.
|
||||
///
|
||||
/// The timestamp is rounded to the nearest second at init so it survives a JSON
|
||||
/// round-trip exactly (a `Date` serialised as a fractional `secondsSince1970` Double
|
||||
/// otherwise loses precision through the decimal text form, which would break
|
||||
/// `Equatable` after `writeToDisk` / `loadAllFromDisk`).
|
||||
public let savedAt: Date
|
||||
|
||||
/// The full `BoardState` snapshot — label, pedal types, knob values, and bypass flags.
|
||||
public let state: BoardState
|
||||
|
||||
/// Creates a board version snapshot.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - id: Stable unique identifier. Defaults to a newly generated `UUID()`.
|
||||
/// - name: Human-readable name for this version.
|
||||
/// - savedAt: Capture timestamp. Defaults to `Date()` (now). Rounded to the
|
||||
/// nearest whole second so persistence round-trips are lossless.
|
||||
/// - state: The `BoardState` to store.
|
||||
public init(
|
||||
id: UUID = UUID(),
|
||||
name: String,
|
||||
savedAt: Date = Date(),
|
||||
state: BoardState
|
||||
) {
|
||||
self.id = id
|
||||
self.name = name
|
||||
// Round to whole seconds: a fractional Date loses precision through the JSON
|
||||
// `secondsSince1970` Double text form, which would break `Equatable` after a
|
||||
// disk round-trip.
|
||||
self.savedAt = Date(timeIntervalSince1970: savedAt.timeIntervalSince1970.rounded())
|
||||
self.state = state
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
// BoardVersionStore.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import Observation
|
||||
|
||||
/// In-memory list of `BoardVersion` snapshots with optional disk persistence.
|
||||
///
|
||||
/// `BoardVersionStore` is `@Observable` so SwiftUI views automatically update when the
|
||||
/// `versions` list changes. All mutations run on the main actor.
|
||||
///
|
||||
/// ## Typical usage
|
||||
///
|
||||
/// ```swift
|
||||
/// let store = BoardVersionStore()
|
||||
/// store.capture(myBoard, name: "Lead Crunch") // add a version
|
||||
/// try store.writeAllToDisk(in: BoardVersionStore.defaultDirectory())
|
||||
///
|
||||
/// // Restore on next launch:
|
||||
/// let freshStore = BoardVersionStore()
|
||||
/// try freshStore.loadAllFromDisk(in: BoardVersionStore.defaultDirectory())
|
||||
/// if let v = freshStore.versions.first {
|
||||
/// try shoeGaze.rebuildBoard(myBoard, from: v.state)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ## Disk format
|
||||
///
|
||||
/// Each `BoardVersion` is written as a separate pretty-printed JSON file named
|
||||
/// `<sanitized-name>-<id>.json` inside the chosen directory. File names are
|
||||
/// sanitised by replacing `/`, `\`, `:`, NUL, leading `.`, and whitespace with
|
||||
/// underscores; the sanitised prefix is capped at 200 UTF-8 bytes; all-whitespace
|
||||
/// or all-separator names fall back to `"unnamed"`. `Date` values are encoded as
|
||||
/// seconds since the Unix epoch (`TimeInterval`) for lossless round-trip equality.
|
||||
@MainActor
|
||||
@Observable
|
||||
public final class BoardVersionStore {
|
||||
|
||||
// MARK: - State
|
||||
|
||||
/// All in-memory `BoardVersion` entries, sorted by `savedAt` after any disk load.
|
||||
public private(set) var versions: [BoardVersion] = []
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates an empty store. Call `loadAllFromDisk(in:)` to populate from disk.
|
||||
public init() {}
|
||||
|
||||
// MARK: - Capture
|
||||
|
||||
/// Captures the current state of `board` and appends a new `BoardVersion` to `versions`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - board: The `PedalBoard` to snapshot.
|
||||
/// - name: Human-readable label for this version (e.g. `"Lead Crunch"`).
|
||||
public func capture(
|
||||
_ board: PedalBoard,
|
||||
name: String
|
||||
) {
|
||||
let version: BoardVersion = BoardVersion(
|
||||
id: UUID(),
|
||||
name: name,
|
||||
savedAt: Date(),
|
||||
state: board.captureState()
|
||||
)
|
||||
versions.append(version)
|
||||
}
|
||||
|
||||
// MARK: - Remove
|
||||
|
||||
/// Removes a version from the in-memory list. Matching is by `id`.
|
||||
///
|
||||
/// This is **memory-only**. Any JSON file previously written by `writeToDisk(_:in:)` is
|
||||
/// not touched; call `deleteFromDisk(_:in:)` first if you also need to remove the file
|
||||
/// so that the deletion survives `loadAllFromDisk`.
|
||||
///
|
||||
/// - Parameter version: The `BoardVersion` to remove.
|
||||
public func remove(_ version: BoardVersion) {
|
||||
versions.removeAll { $0.id == version.id }
|
||||
}
|
||||
|
||||
// MARK: - Disk delete
|
||||
|
||||
/// Deletes the JSON file for `version` from `directory`.
|
||||
///
|
||||
/// The filename is derived using the same `<sanitized-name>-<id>.json` scheme as
|
||||
/// `writeToDisk(_:in:)`. No-op if the file does not exist. Use this alongside
|
||||
/// `remove(_:)` to make a deletion persist across `loadAllFromDisk`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - version: The `BoardVersion` whose file should be removed.
|
||||
/// - directory: The directory that was passed to `writeToDisk(_:in:)`.
|
||||
/// - Throws: `FileManager` errors other than "file not found".
|
||||
public func deleteFromDisk(
|
||||
_ version: BoardVersion,
|
||||
in directory: URL
|
||||
) throws {
|
||||
let sanitized: String = sanitizeFilename(version.name)
|
||||
let filename: String = "\(sanitized)-\(version.id.uuidString).json"
|
||||
let fileURL: URL = directory.appendingPathComponent(filename)
|
||||
do {
|
||||
try FileManager.default.removeItem(at: fileURL)
|
||||
} catch let error as NSError
|
||||
where error.domain == NSCocoaErrorDomain && error.code == NSFileNoSuchFileError {
|
||||
// File does not exist — treat as a no-op.
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Disk write
|
||||
|
||||
/// Writes a single `BoardVersion` to `directory` as pretty-printed JSON.
|
||||
///
|
||||
/// The filename is `<sanitized-name>-<id>.json`. The sanitised name replaces `/`,
|
||||
/// `:`, newlines, and other whitespace with underscores so the filename is safe on
|
||||
/// HFS+ and APFS. The directory is created if it does not already exist.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - version: The `BoardVersion` to write.
|
||||
/// - directory: Destination directory URL. Created recursively if absent.
|
||||
/// - Throws:
|
||||
/// - `FileManager` errors if directory creation fails.
|
||||
/// - `JSONEncoder` errors on encode failure.
|
||||
/// - `Data.write(to:options:)` errors on write failure.
|
||||
public func writeToDisk(
|
||||
_ version: BoardVersion,
|
||||
in directory: URL
|
||||
) throws {
|
||||
try FileManager.default.createDirectory(
|
||||
at: directory,
|
||||
withIntermediateDirectories: true,
|
||||
attributes: nil
|
||||
)
|
||||
|
||||
let sanitized: String = sanitizeFilename(version.name)
|
||||
let filename: String = "\(sanitized)-\(version.id.uuidString).json"
|
||||
let fileURL: URL = directory.appendingPathComponent(filename)
|
||||
|
||||
let encoder: JSONEncoder = JSONEncoder()
|
||||
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
|
||||
encoder.dateEncodingStrategy = .secondsSince1970
|
||||
let data: Data = try encoder.encode(version)
|
||||
try data.write(to: fileURL, options: .atomic)
|
||||
}
|
||||
|
||||
/// Writes every in-memory `BoardVersion` to `directory`.
|
||||
///
|
||||
/// Each version is written as a separate file (see `writeToDisk(_:in:)`).
|
||||
/// The directory is created if it does not already exist. A failure on one file
|
||||
/// propagates immediately and stops the remaining writes.
|
||||
///
|
||||
/// - Parameter directory: Destination directory URL. Created recursively if absent.
|
||||
/// - Throws: The first error encountered during write.
|
||||
public func writeAllToDisk(in directory: URL) throws {
|
||||
for version: BoardVersion in versions {
|
||||
try writeToDisk(version, in: directory)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Disk load
|
||||
|
||||
/// Loads all `*.json` files in `directory` as `BoardVersion` entries, replacing the
|
||||
/// current in-memory `versions` list.
|
||||
///
|
||||
/// Files that cannot be **read** (e.g. permission errors) and files that cannot be
|
||||
/// **decoded** (corrupt or unrecognised JSON) are both silently skipped — a single
|
||||
/// bad file does not prevent the rest from loading. After loading, the list is sorted
|
||||
/// ascending by `savedAt`.
|
||||
///
|
||||
/// - Parameter directory: The directory to scan. If the directory does not exist or
|
||||
/// is empty, `versions` is set to `[]` without throwing.
|
||||
/// - Throws: `FileManager` errors for directory enumeration failures (not for
|
||||
/// individual file read/decode failures — those are silently skipped).
|
||||
public func loadAllFromDisk(in directory: URL) throws {
|
||||
var loaded: [BoardVersion] = []
|
||||
|
||||
// Early exit if the directory doesn't exist yet.
|
||||
var isDirectory: ObjCBool = false
|
||||
guard FileManager.default.fileExists(atPath: directory.path, isDirectory: &isDirectory),
|
||||
isDirectory.boolValue else {
|
||||
versions = []
|
||||
return
|
||||
}
|
||||
|
||||
let contents: [URL] = try FileManager.default.contentsOfDirectory(
|
||||
at: directory,
|
||||
includingPropertiesForKeys: nil,
|
||||
options: .skipsHiddenFiles
|
||||
)
|
||||
|
||||
let decoder: JSONDecoder = JSONDecoder()
|
||||
decoder.dateDecodingStrategy = .secondsSince1970
|
||||
|
||||
for fileURL: URL in contents {
|
||||
guard fileURL.pathExtension == "json" else { continue }
|
||||
guard let data: Data = try? Data(contentsOf: fileURL) else { continue }
|
||||
guard let version: BoardVersion = try? decoder.decode(BoardVersion.self, from: data) else {
|
||||
continue
|
||||
}
|
||||
loaded.append(version)
|
||||
}
|
||||
|
||||
loaded.sort { $0.savedAt < $1.savedAt }
|
||||
versions = loaded
|
||||
}
|
||||
|
||||
// MARK: - Default directory
|
||||
|
||||
/// Returns the recommended directory for storing board version files.
|
||||
///
|
||||
/// Resolves to `<Application Support>/LyrebirdShoeGaze/ShoeGazeVersions/` for the
|
||||
/// current user. Falls back to a `ShoeGazeVersions/` subdirectory inside the
|
||||
/// system temporary directory if Application Support is unavailable.
|
||||
///
|
||||
/// The directory is **not** created by this method — call `writeToDisk(_:in:)` or
|
||||
/// `writeAllToDisk(in:)` (which create the directory automatically) before writing.
|
||||
///
|
||||
/// - Returns: A `URL` for the ShoeGaze versions directory.
|
||||
public static func defaultDirectory() -> URL {
|
||||
let appSupportDir: URL? = try? FileManager.default.url(
|
||||
for: .applicationSupportDirectory,
|
||||
in: .userDomainMask,
|
||||
appropriateFor: nil,
|
||||
create: false
|
||||
)
|
||||
let base: URL = appSupportDir ?? FileManager.default.temporaryDirectory
|
||||
return base
|
||||
.appendingPathComponent("LyrebirdShoeGaze", isDirectory: true)
|
||||
.appendingPathComponent("ShoeGazeVersions", isDirectory: true)
|
||||
}
|
||||
|
||||
// MARK: - Private helpers
|
||||
|
||||
/// Maximum UTF-8 byte length for the sanitised name prefix before the `-<uuid>.json`
|
||||
/// suffix is appended, so the full filename stays well under the 255-byte component limit.
|
||||
private let maxNameLength: Int = 200
|
||||
|
||||
/// Sanitises a string so it is safe as a file-system component on HFS+ and APFS.
|
||||
///
|
||||
/// - Replaces `/`, `\`, `:`, NUL (`\0`), and all whitespace characters with underscores.
|
||||
/// - Replaces a leading `.` (which would produce hidden-file or `.`/`..` names) with an
|
||||
/// underscore.
|
||||
/// - Trims leading and trailing underscores that resulted from whitespace or separator
|
||||
/// substitution (cosmetic only — the result is always safe even before trimming).
|
||||
/// - Caps the UTF-8 byte length of the result at `maxNameLength` so the full filename
|
||||
/// (`<name>-<uuid>.json`, 54 extra bytes) cannot exceed the 255-byte component limit.
|
||||
/// - Returns `"unnamed"` when the input is empty, all-whitespace, or reduces entirely
|
||||
/// to separator characters after substitution.
|
||||
private func sanitizeFilename(_ name: String) -> String {
|
||||
let replacementCharacter: Character = "_"
|
||||
let forbiddenCharacters: Set<Character> = ["/", "\\", ":", "\0"]
|
||||
|
||||
var sanitized: String = name.map { character -> Character in
|
||||
if character.isWhitespace || forbiddenCharacters.contains(character) {
|
||||
return replacementCharacter
|
||||
}
|
||||
return character
|
||||
}.reduce(into: "") { $0.append($1) }
|
||||
|
||||
// Replace a leading dot so the filename is never `.`, `..`, or a hidden file.
|
||||
if sanitized.first == "." {
|
||||
sanitized.replaceSubrange(sanitized.startIndex...sanitized.startIndex, with: "_")
|
||||
}
|
||||
|
||||
// Trim whitespace-replacement underscores at both ends (cosmetic).
|
||||
sanitized = sanitized.trimmingCharacters(in: CharacterSet(charactersIn: "_"))
|
||||
|
||||
// Treat all-empty or all-separator results as unnamed.
|
||||
guard !sanitized.isEmpty else { return "unnamed" }
|
||||
|
||||
// Cap to maxNameLength UTF-8 bytes so the full filename stays within 255 bytes.
|
||||
if sanitized.utf8.count > maxNameLength {
|
||||
var truncated: String = ""
|
||||
var byteCount: Int = 0
|
||||
for scalar: Unicode.Scalar in sanitized.unicodeScalars {
|
||||
let encodedLength: Int = UTF8.width(scalar)
|
||||
guard byteCount + encodedLength <= maxNameLength else { break }
|
||||
truncated.unicodeScalars.append(scalar)
|
||||
byteCount += encodedLength
|
||||
}
|
||||
sanitized = truncated
|
||||
}
|
||||
|
||||
return sanitized.isEmpty ? "unnamed" : sanitized
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// Pedal+Preset.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
extension Pedal {
|
||||
|
||||
/// Captures the current parameter values of this pedal as a `PedalState`.
|
||||
///
|
||||
/// The returned snapshot includes:
|
||||
/// - `type`: the pedal's `displayName` (used as a factory key on load).
|
||||
/// - `knobValues`: one `Double` per entry in `knobs`, in order
|
||||
/// (effect-specific knobs first, then Mix, then Level).
|
||||
/// - `bypass`: the current bypass parameter value.
|
||||
///
|
||||
/// - Returns: A `PedalState` reflecting the pedal's current parameter values.
|
||||
public func captureState() -> PedalState {
|
||||
let values: [Double] = knobs.map { $0.node.value }
|
||||
return PedalState(
|
||||
type: displayName,
|
||||
knobValues: values,
|
||||
bypass: bypass
|
||||
)
|
||||
}
|
||||
|
||||
/// Applies a previously captured `PedalState` to this pedal's parameters.
|
||||
///
|
||||
/// For each (knob, value) pair in `zip(knobs, state.knobValues)`, the knob's
|
||||
/// `UIParamNode` is updated via `node.update(_:)`. If `state.knobValues` has
|
||||
/// fewer entries than `knobs`, the trailing knobs retain their current values.
|
||||
/// Extra values beyond `knobs.count` are ignored. The `bypass` parameter is
|
||||
/// always applied regardless of knob-count mismatches.
|
||||
///
|
||||
/// - Parameter state: The state to restore. The `state.type` is not validated
|
||||
/// against `displayName` — the caller is responsible for matching types before
|
||||
/// calling this method.
|
||||
public func applyState(_ state: PedalState) {
|
||||
for (knob, value) in zip(knobs, state.knobValues) {
|
||||
knob.node.update(value)
|
||||
}
|
||||
bypass = state.bypass
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// PedalBoard+Preset.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
extension PedalBoard {
|
||||
|
||||
/// Captures the current state of this board's label and pedal chain as a `BoardState`.
|
||||
///
|
||||
/// Each pedal's `displayName`, knob values, and bypass flag are snapshotted in
|
||||
/// signal-flow order. The engine graph is not modified; this is a read-only operation.
|
||||
///
|
||||
/// - Returns: A `BoardState` reflecting the board's current label and pedal parameters.
|
||||
public func captureState() -> BoardState {
|
||||
let pedalStates: [PedalState] = pedals.map { $0.captureState() }
|
||||
return BoardState(label: label, pedals: pedalStates)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// PedalRegistry.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// A factory registry mapping built-in pedal display names to their constructors.
|
||||
///
|
||||
/// `PedalRegistry` is the authoritative lookup used by `ShoeGaze.loadRig(from:)` to
|
||||
/// instantiate the correct `Pedal` subclass for each `PedalState.type` string found
|
||||
/// in a saved preset. Unknown type strings return `nil` from `makePedal(type:)` and
|
||||
/// 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 eight
|
||||
/// factory pedals: Overdrive, Delay, Reverb, Modulation, Fuzz, Tremolo, Phaser, and
|
||||
/// Compressor.
|
||||
public enum PedalRegistry {
|
||||
|
||||
/// Maps each built-in pedal display name to a `@MainActor` no-argument constructor.
|
||||
///
|
||||
/// Keys are the `displayName` values returned by the corresponding `Pedal` subclass.
|
||||
/// Values are closures that allocate a fresh instance with default bus indices —
|
||||
/// `ShoeGaze.loadRig(from:)` updates `inputBus`/`outputBus` when adding the pedal
|
||||
/// to a board via `board.add(_:)`.
|
||||
public static let builtIn: [String: @MainActor () -> Pedal] = [
|
||||
"Overdrive": { OverdrivePedal() },
|
||||
"Delay": { DelayPedal() },
|
||||
"Reverb": { ReverbPedal() },
|
||||
"Modulation": { ModulationPedal() },
|
||||
"Fuzz": { FuzzPedal() },
|
||||
"Tremolo": { TremoloPedal() },
|
||||
"Phaser": { PhaserPedal() },
|
||||
"Compressor": { CompressorPedal() },
|
||||
]
|
||||
|
||||
/// Returns a new `Pedal` instance for the given type string, or `nil` if the type
|
||||
/// is not in the built-in registry.
|
||||
///
|
||||
/// The returned pedal has default bus indices (`inputBus: 0`, `outputBus: 0`);
|
||||
/// the caller is responsible for routing it via `board.add(_:)` before the engine
|
||||
/// processes any audio.
|
||||
///
|
||||
/// - Parameter type: The `displayName` of the pedal (e.g. `"Overdrive"`, `"Delay"`).
|
||||
/// - Returns: A freshly allocated `Pedal` subclass instance, or `nil` for unknown types.
|
||||
@MainActor
|
||||
public static func makePedal(type: String) -> Pedal? {
|
||||
guard let constructor: @MainActor () -> Pedal = builtIn[type] else { return nil }
|
||||
return constructor()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// PedalState.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Serialisable snapshot of one pedal's parameter values.
|
||||
///
|
||||
/// `type` stores the pedal's `displayName` and is used by `PedalRegistry` to
|
||||
/// reconstruct the correct subclass on load. `knobValues` mirrors `Pedal.knobs`
|
||||
/// in order — effect-specific knobs first, then `mix`, then `level`. `bypass`
|
||||
/// stores the bypass parameter value (`0.0` = engaged, `1.0` = bypassed).
|
||||
///
|
||||
/// - Note: Extra knob values beyond the pedal's current knob count are silently
|
||||
/// ignored on apply; missing values (fewer entries than knobs) leave trailing
|
||||
/// knobs at their current value.
|
||||
public struct PedalState: Codable, Equatable {
|
||||
|
||||
/// The pedal's `displayName` — used as a factory key by `PedalRegistry`.
|
||||
public let type: String
|
||||
|
||||
/// Knob values in the same order as `Pedal.knobs` (effect knobs then Mix, Level).
|
||||
public let knobValues: [Double]
|
||||
|
||||
/// Bypass parameter value. `0.0` = engaged, `1.0` = bypassed.
|
||||
public let bypass: Double
|
||||
|
||||
/// Creates a pedal state snapshot.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - type: The pedal's `displayName`, used to identify the pedal type on load.
|
||||
/// - knobValues: Current knob values in `Pedal.knobs` order.
|
||||
/// - bypass: Bypass parameter value (`0.0` = engaged, `1.0` = bypassed).
|
||||
public init(
|
||||
type: String,
|
||||
knobValues: [Double],
|
||||
bypass: Double
|
||||
) {
|
||||
self.type = type
|
||||
self.knobValues = knobValues
|
||||
self.bypass = bypass
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// PresetError.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Errors thrown by preset load and version-check operations.
|
||||
///
|
||||
/// - `unsupportedVersion`: The serialised preset's `version` field exceeds
|
||||
/// `presetFormatVersion`. The associated value carries the version number that
|
||||
/// was found in the file so callers can surface a meaningful error message.
|
||||
public enum PresetError: Error, Equatable {
|
||||
|
||||
/// The preset file was written by a newer version of the format than this
|
||||
/// build understands. The associated `Int` is the version found in the file.
|
||||
case unsupportedVersion(Int)
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
// ShoeGaze+Preset.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
extension ShoeGaze {
|
||||
|
||||
// MARK: - Capture
|
||||
|
||||
/// Captures the current rig topology and parameter values as a `ShoeGazeState`.
|
||||
///
|
||||
/// Each board's label and pedal parameters are snapshotted in order. The engine
|
||||
/// graph is not modified; this is a read-only operation.
|
||||
///
|
||||
/// - Returns: A `ShoeGazeState` reflecting the current rig.
|
||||
public func captureState() -> ShoeGazeState {
|
||||
let boardStates: [BoardState] = boards.map { board in
|
||||
let pedalStates: [PedalState] = board.pedals.map { $0.captureState() }
|
||||
return BoardState(label: board.label, pedals: pedalStates)
|
||||
}
|
||||
return ShoeGazeState(boards: boardStates)
|
||||
}
|
||||
|
||||
// MARK: - Save / Load
|
||||
|
||||
/// Saves the current rig to a JSON file at `url`.
|
||||
///
|
||||
/// The file is pretty-printed for readability and human-editability. Existing
|
||||
/// files at `url` are overwritten.
|
||||
///
|
||||
/// - Parameter url: Destination file URL. The directory must already exist.
|
||||
/// - Throws: Any error from `JSONEncoder` or `Data.write(to:options:)`.
|
||||
public func saveRig(to url: URL) throws {
|
||||
let encoder: JSONEncoder = JSONEncoder()
|
||||
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
|
||||
let data: Data = try encoder.encode(captureState())
|
||||
try data.write(to: url, options: .atomic)
|
||||
}
|
||||
|
||||
/// Loads a rig from a JSON preset file and rebuilds the engine graph.
|
||||
///
|
||||
/// This method:
|
||||
/// 1. Calls `teardown()` to remove all current nodes and release all buses.
|
||||
/// 2. For each `BoardState`, calls `addBoard()`, sets `board.label`, adds each
|
||||
/// pedal (skipping unknown types without throwing), applies the saved parameter
|
||||
/// values via `pedal.applyState(_:)`, and calls `finalizeBoard(_:)`.
|
||||
///
|
||||
/// - Important: Call this method with the engine **stopped** (before `engine.start()`
|
||||
/// or after `engine.stop()`). The same async-removal caveat as `teardown()` applies:
|
||||
/// the engine processes one more block after `remove` is enqueued. Unknown pedal
|
||||
/// types in the preset are silently skipped — the board is still created and finalized
|
||||
/// with however many pedals were successfully reconstructed.
|
||||
///
|
||||
/// - Parameter url: Source file URL pointing to a JSON preset written by `saveRig(to:)`.
|
||||
/// - Throws: Any error from `Data(contentsOf:)`, `JSONDecoder`, `PedalBoard.init`,
|
||||
/// `board.add(_:)`, or `finalizeBoard(_:)`. Also throws
|
||||
/// `PresetError.unsupportedVersion` when the file's version exceeds
|
||||
/// `presetFormatVersion`.
|
||||
public func loadRig(from url: URL) throws {
|
||||
let data: Data = try Data(contentsOf: url)
|
||||
let decoder: JSONDecoder = JSONDecoder()
|
||||
let state: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data)
|
||||
guard state.version <= presetFormatVersion else {
|
||||
throw PresetError.unsupportedVersion(state.version)
|
||||
}
|
||||
|
||||
teardown()
|
||||
|
||||
for boardState: BoardState in state.boards {
|
||||
let board: PedalBoard = try addBoard()
|
||||
board.label = boardState.label
|
||||
|
||||
for pedalState: PedalState in boardState.pedals {
|
||||
guard let pedal: Pedal = PedalRegistry.makePedal(type: pedalState.type) else {
|
||||
// Unknown pedal type — skip without crashing.
|
||||
continue
|
||||
}
|
||||
pedal.applyState(pedalState)
|
||||
try board.add(pedal)
|
||||
}
|
||||
|
||||
try finalizeBoard(board)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Per-board rebuild
|
||||
|
||||
/// Tears down a single board and recreates it from a saved `BoardState`, preserving
|
||||
/// its position in `boards` so UI ordering remains stable.
|
||||
///
|
||||
/// ## Behaviour
|
||||
///
|
||||
/// 1. Finds `board` in `boards` by identity (`===`). If absent, the board is treated as
|
||||
/// unmanaged: a fresh board is built, finalised, and returned without reordering.
|
||||
/// 2. Calls `addBoard()` to allocate a new board and sets `newBoard.label = state.label`.
|
||||
/// 3. For each `PedalState` in `state.pedals`, calls `PedalRegistry.makePedal(type:)`;
|
||||
/// unknown types are logged and skipped so presets with missing custom pedals degrade
|
||||
/// gracefully. Known pedals have `applyState(_:)` called before `board.add(_:)`.
|
||||
/// 4. Calls `finalizeBoard(_:)` to connect the output master.
|
||||
/// 5. Only after the new board is fully wired does `removeBoard(_:)` tear down the old
|
||||
/// board — so a failure during steps 2–4 leaves the original board intact.
|
||||
/// 6. Moves the new board to `oldIndex` in `boards` so it occupies the same slot as the
|
||||
/// removed board.
|
||||
///
|
||||
/// - Important: Call with the engine **stopped** (or accept one block of glitch on a
|
||||
/// running engine). Both boards exist briefly while the new one is being built;
|
||||
/// this requires two additional buses but is safe because the bus pool has headroom
|
||||
/// and the documented precondition is engine-stopped. `removeBoard(_:)` enqueues
|
||||
/// removal; the engine processes one more block before the node is dequeued.
|
||||
/// Unknown pedal types are silently skipped.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - board: The board to replace. Must have been returned by `addBoard()` on this instance.
|
||||
/// - state: The `BoardState` snapshot to restore.
|
||||
/// - Returns: The newly created `PedalBoard` at the same index as the replaced board.
|
||||
/// - Throws:
|
||||
/// - `BusAllocatorError.noFreeBus` if no mono audio bus is available during rebuild.
|
||||
/// - `EngineAddError` if the engine rejects any node insertion.
|
||||
@discardableResult
|
||||
public func rebuildBoard(
|
||||
_ board: PedalBoard,
|
||||
from state: BoardState
|
||||
) throws -> PedalBoard {
|
||||
// Record the existing position before allocating the new board so the slot
|
||||
// can be restored. May be nil when `board` is unmanaged (not in `boards`).
|
||||
let oldIndex: Int? = boards.firstIndex(where: { $0 === board })
|
||||
|
||||
// Build the new board FIRST so that any failure leaves the old board intact.
|
||||
let newBoard: PedalBoard = try addBoard()
|
||||
do {
|
||||
newBoard.label = state.label
|
||||
|
||||
for pedalState: PedalState in state.pedals {
|
||||
guard let pedal: Pedal = PedalRegistry.makePedal(type: pedalState.type) else {
|
||||
// Unknown pedal type — log for diagnosability, then skip.
|
||||
print("[ShoeGaze] rebuildBoard: skipping unknown pedal type \(pedalState.type)")
|
||||
continue
|
||||
}
|
||||
pedal.applyState(pedalState)
|
||||
try newBoard.add(pedal)
|
||||
}
|
||||
|
||||
try finalizeBoard(newBoard)
|
||||
} catch {
|
||||
// New board is partial — clean it up while the old board is still intact.
|
||||
removeBoard(newBoard)
|
||||
throw error
|
||||
}
|
||||
|
||||
// New board fully wired — now remove the old one and restore its position.
|
||||
if let targetIndex: Int = oldIndex {
|
||||
removeBoard(board)
|
||||
// `addBoard()` always appends; move the new board back to the original slot.
|
||||
// `moveBoard(_:to:)` locates by identity so the correct element is repositioned
|
||||
// even if `removeBoard` shifted indices.
|
||||
moveBoard(newBoard, to: targetIndex)
|
||||
}
|
||||
|
||||
return newBoard
|
||||
}
|
||||
|
||||
// MARK: - Lightweight recall
|
||||
|
||||
/// Applies parameter values from `state` to the current rig topology without
|
||||
/// rebuilding the engine graph.
|
||||
///
|
||||
/// This is a lightweight "recall settings" path intended for topologically identical
|
||||
/// rigs (same board count, same pedal count and types in the same order). Boards
|
||||
/// and pedals are matched positionally; any count or type mismatch at the board or
|
||||
/// pedal level is silently ignored for that entry — no error is thrown and remaining
|
||||
/// entries continue to be processed.
|
||||
///
|
||||
/// Use `loadRig(from:)` when you need a full topology rebuild.
|
||||
///
|
||||
/// - Parameter state: The `ShoeGazeState` whose parameter values should be applied.
|
||||
public func applyState(_ state: ShoeGazeState) {
|
||||
for (board, boardState) in zip(boards, state.boards) {
|
||||
for (pedal, pedalState) in zip(board.pedals, boardState.pedals) {
|
||||
guard pedal.displayName == pedalState.type else { continue }
|
||||
pedal.applyState(pedalState)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// ShoeGazeState.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Format version written into every saved preset file.
|
||||
///
|
||||
/// Increment this constant when the `ShoeGazeState` schema changes in a way that
|
||||
/// requires migration logic on load.
|
||||
public let presetFormatVersion: Int = 1
|
||||
|
||||
/// Serialisable snapshot of an entire `ShoeGaze` rig — all boards and their pedals.
|
||||
///
|
||||
/// Use `ShoeGaze.saveRig(to:)` to write and `ShoeGaze.loadRig(from:)` to restore.
|
||||
/// The `version` field allows future migrations: loaders that read a file with a
|
||||
/// higher `version` than `presetFormatVersion` should reject or warn, while loaders
|
||||
/// reading older versions may apply forward-compatibility mappings.
|
||||
///
|
||||
/// Unknown pedal types encountered during load are silently skipped so presets made
|
||||
/// with custom third-party pedals degrade gracefully on systems without those pedals.
|
||||
public struct ShoeGazeState: Codable, Equatable {
|
||||
|
||||
/// Preset format version. Written as `presetFormatVersion` at save time.
|
||||
public let version: Int
|
||||
|
||||
/// All board snapshots in the order they were created.
|
||||
public let boards: [BoardState]
|
||||
|
||||
/// Creates a rig state snapshot.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - version: Preset format version. Defaults to `presetFormatVersion`.
|
||||
/// - boards: Ordered list of board state snapshots.
|
||||
public init(
|
||||
version: Int = presetFormatVersion,
|
||||
boards: [BoardState]
|
||||
) {
|
||||
self.version = version
|
||||
self.boards = boards
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// RecordTap.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
/// An internal synthesizer that taps one or more audio buses and records them to a
|
||||
/// WAV file via `DiskOut.Audio`.
|
||||
///
|
||||
/// `RecordTap` reads `channelCount` consecutive audio buses starting at `firstBusIndex`
|
||||
/// and passes them to a `DiskOut.Audio` instance that writes to `fileURL`. It is added
|
||||
/// `.after(engine.mainGroup)` so it evaluates after every board and master synth has
|
||||
/// written their final bus values for the block.
|
||||
///
|
||||
/// Call `diskOut?.close()` after removing the tap from the engine to flush any
|
||||
/// buffered frames and close the file handle.
|
||||
final class RecordTap: SynthesizerBase {
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// Index of the first audio bus to record.
|
||||
private let firstBusIndex: Int
|
||||
|
||||
/// Number of consecutive buses to record (and interleave into the output file).
|
||||
private let channelCount: Int
|
||||
|
||||
/// Destination file URL. Created or overwritten when the `DiskOut.Audio` is initialised.
|
||||
private let fileURL: URL
|
||||
|
||||
/// Sample rate written into the WAV file header.
|
||||
private let recordSampleRate: Double
|
||||
|
||||
// MARK: - DiskOut handle
|
||||
|
||||
/// The `DiskOut.Audio` generator created during `build()`. `nil` if `build()` has not
|
||||
/// run yet, or if `DiskOut.Audio.init` threw (error is printed to stdout).
|
||||
private(set) var diskOut: DiskOut.Audio?
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a record tap that reads `channelCount` buses from `firstBusIndex`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - firstBusIndex: Index of the first audio bus to record.
|
||||
/// - channelCount: Number of consecutive audio buses to record.
|
||||
/// - fileURL: Output WAV file URL. Created or overwritten at build time.
|
||||
/// - sampleRate: Sample rate to embed in the WAV file header.
|
||||
init(
|
||||
firstBusIndex: Int,
|
||||
channelCount: Int,
|
||||
fileURL: URL,
|
||||
sampleRate: Double
|
||||
) {
|
||||
self.firstBusIndex = firstBusIndex
|
||||
self.channelCount = channelCount
|
||||
self.fileURL = fileURL
|
||||
self.recordSampleRate = sampleRate
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - Build
|
||||
|
||||
override func build() {
|
||||
let source: any ValidGeneratorInput = channelCount > 1
|
||||
? input(bus: firstBusIndex, channels: channelCount)
|
||||
: input(bus: firstBusIndex)
|
||||
do {
|
||||
diskOut = try DiskOut.Audio(
|
||||
source: source,
|
||||
channelCount: channelCount,
|
||||
url: fileURL,
|
||||
sampleRate: recordSampleRate,
|
||||
format: .wav
|
||||
)
|
||||
// DiskOut.Audio conforms to RootRegistering and auto-registers as a synth root
|
||||
// when constructed inside build(). No explicit addOutputGenerator call is needed.
|
||||
} catch {
|
||||
print("[ShoeGaze] RecordTap could not open \(fileURL.lastPathComponent): \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
// ShoeGaze+Recording.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// MARK: - Recording constants
|
||||
|
||||
/// Preferred number of interleaved output channels captured by the output record tap.
|
||||
/// Clamped to `engine.numOutputChannels` at recording time so a mono engine never reads
|
||||
/// an input bus as if it were a second output channel.
|
||||
private let recordingOutputChannelCount: Int = 2
|
||||
|
||||
/// Number of channels captured by the input record tap (always mono — hardware input is mono).
|
||||
private let recordingInputChannelCount: Int = 1
|
||||
|
||||
/// `DateFormatter` format string used to build timestamped file names.
|
||||
private let recordingTimestampFormat: String = "yyyyMMdd-HHmmss"
|
||||
|
||||
/// POSIX locale used for the timestamp `DateFormatter` so the filename always uses the
|
||||
/// Gregorian calendar regardless of the user's system locale.
|
||||
private let posixLocaleIdentifier: String = "en_US_POSIX"
|
||||
|
||||
// MARK: - ShoeGaze + Recording
|
||||
|
||||
extension ShoeGaze {
|
||||
|
||||
// MARK: - Start
|
||||
|
||||
/// Starts recording the overall output and (when possible) the raw input to timestamped
|
||||
/// WAV files in ``recordingFolder``.
|
||||
///
|
||||
/// Two files are written:
|
||||
/// - `output-<timestamp>.wav` — the final mix read from hardware output buses starting at 0.
|
||||
/// The channel count is `min(2, engine.numOutputChannels)` so a mono-output engine records
|
||||
/// only one channel (bus 0) instead of accidentally reading bus 1 (which is the first input
|
||||
/// bus on a mono-output configuration).
|
||||
/// - `input-<timestamp>.wav` — the raw mono input signal. For `.liveInput(channel:)` this is
|
||||
/// the hardware input bus; for `.testLoop` this is the head bus of the first board. If no
|
||||
/// board exists when using `.testLoop`, only the output file is created and a note is printed.
|
||||
/// If `.liveInput(channel:)` specifies an out-of-range channel, only the output file is
|
||||
/// created and a note is printed.
|
||||
///
|
||||
/// Both taps are inserted `.after(engine.mainGroup)` so they evaluate after every board and
|
||||
/// master synth, guaranteeing they read final bus values for each block.
|
||||
///
|
||||
/// If a tap's output file cannot be opened (e.g. disk full or permissions error), any taps
|
||||
/// that were already added to the engine are removed, and
|
||||
/// `ShoeGazeError.recordTapFailedToOpen` is thrown. `isRecording` remains `false`.
|
||||
///
|
||||
/// - Throws:
|
||||
/// - `ShoeGazeError.recordingFolderNotSet` if ``recordingFolder`` is `nil`.
|
||||
/// - Any error thrown by `FileManager.createDirectory` if the folder cannot be created.
|
||||
/// - `EngineAddError` if the engine rejects a tap insertion.
|
||||
/// - `ShoeGazeError.recordTapFailedToOpen` if a `DiskOut.Audio` could not open its file.
|
||||
public func startRecording() throws {
|
||||
guard let folder: URL = recordingFolder else {
|
||||
throw ShoeGazeError.recordingFolderNotSet
|
||||
}
|
||||
guard !isRecording else { return }
|
||||
|
||||
// Ensure the destination folder exists.
|
||||
try FileManager.default.createDirectory(
|
||||
at: folder,
|
||||
withIntermediateDirectories: true,
|
||||
attributes: nil
|
||||
)
|
||||
|
||||
// Build a timestamp string using POSIX locale so the Gregorian calendar is always
|
||||
// used, regardless of the user's system locale or calendar setting.
|
||||
let formatter: DateFormatter = DateFormatter()
|
||||
formatter.dateFormat = recordingTimestampFormat
|
||||
formatter.locale = Locale(identifier: posixLocaleIdentifier)
|
||||
let timestamp: String = formatter.string(from: Date())
|
||||
|
||||
// Clamp the output channel count to the engine's actual output channel count so we
|
||||
// never read bus index 1 on a mono-output engine (bus 1 would be the first input bus).
|
||||
let outChannels: Int = min(recordingOutputChannelCount, engine.numOutputChannels)
|
||||
guard outChannels >= 1 else {
|
||||
// Engine has no output channels — nothing to record.
|
||||
print("[ShoeGaze] startRecording: engine has no output channels — skipping output tap.")
|
||||
return
|
||||
}
|
||||
|
||||
// --- Output tap ---
|
||||
let outputFileURL: URL = folder
|
||||
.appendingPathComponent("output-\(timestamp).wav")
|
||||
let outputTap: RecordTap = RecordTap(
|
||||
firstBusIndex: 0,
|
||||
channelCount: outChannels,
|
||||
fileURL: outputFileURL,
|
||||
sampleRate: engine.sampleRate
|
||||
)
|
||||
try engine.add(outputTap, position: .after(engine.mainGroup))
|
||||
// Guard that DiskOut actually opened — build() prints the error; we surface it here.
|
||||
guard outputTap.diskOut != nil else {
|
||||
engine.remove(outputTap)
|
||||
throw ShoeGazeError.recordTapFailedToOpen(outputFileURL)
|
||||
}
|
||||
recordTaps.append(outputTap)
|
||||
|
||||
// --- Input tap (mono) ---
|
||||
let inputBusIndex: Int? = resolvedInputBusIndex()
|
||||
if let busIndex: Int = inputBusIndex {
|
||||
let inputFileURL: URL = folder
|
||||
.appendingPathComponent("input-\(timestamp).wav")
|
||||
let inputTap: RecordTap = RecordTap(
|
||||
firstBusIndex: busIndex,
|
||||
channelCount: recordingInputChannelCount,
|
||||
fileURL: inputFileURL,
|
||||
sampleRate: engine.sampleRate
|
||||
)
|
||||
do {
|
||||
try engine.add(inputTap, position: .after(engine.mainGroup))
|
||||
} catch {
|
||||
// The output tap was already added — remove it before propagating.
|
||||
engine.remove(outputTap)
|
||||
outputTap.diskOut?.close()
|
||||
recordTaps.removeAll()
|
||||
throw error
|
||||
}
|
||||
guard inputTap.diskOut != nil else {
|
||||
// Input file could not be opened — roll back both taps cleanly.
|
||||
engine.remove(inputTap)
|
||||
engine.remove(outputTap)
|
||||
outputTap.diskOut?.close()
|
||||
recordTaps.removeAll()
|
||||
throw ShoeGazeError.recordTapFailedToOpen(inputFileURL)
|
||||
}
|
||||
recordTaps.append(inputTap)
|
||||
}
|
||||
|
||||
isRecording = true
|
||||
}
|
||||
|
||||
// MARK: - Stop
|
||||
|
||||
/// Stops an active recording, flushes all buffered frames to disk, and closes the output files.
|
||||
///
|
||||
/// Each tap is removed from the engine then `DiskOut.close()` is called synchronously to
|
||||
/// flush any remaining buffered frames and dispose the file handle.
|
||||
///
|
||||
/// > Important: `engine.remove(_:)` is asynchronous — it enqueues the removal for the next
|
||||
/// > render block. When the engine is still running, the RT thread may render one or two
|
||||
/// > additional blocks after `stopRecording()` returns; those frames are written to the
|
||||
/// > `DiskOut` ring buffer but the ring buffer drainer may not flush them before `close()`
|
||||
/// > is called, resulting in a bounded tail truncation of those final blocks. This is not
|
||||
/// > file corruption — the WAV header length is written on `close()`. For a sample-accurate
|
||||
/// > tail with no truncation, stop the engine (`engine.stop()`) before calling
|
||||
/// > `stopRecording()`, then close.
|
||||
///
|
||||
/// No-op if `isRecording` is `false`.
|
||||
public func stopRecording() {
|
||||
guard isRecording else { return }
|
||||
for tap: RecordTap in recordTaps {
|
||||
engine.remove(tap)
|
||||
tap.diskOut?.close()
|
||||
}
|
||||
recordTaps.removeAll()
|
||||
isRecording = false
|
||||
}
|
||||
|
||||
// MARK: - Private helpers
|
||||
|
||||
/// Resolves the audio bus index of the raw input signal based on the current `inputSource`.
|
||||
///
|
||||
/// - `.liveInput(channel:)` → validated via `liveInputBusIndex(channel:engine:)`. Returns
|
||||
/// `nil` (with a printed note) if the channel is out of range rather than recording an
|
||||
/// incorrect bus; the output track is still written.
|
||||
/// - `.testLoop` → `boards.first?.headBus.index` (the first board's head bus). Returns `nil`
|
||||
/// if there are no boards; the input track is skipped and a note is printed.
|
||||
private func resolvedInputBusIndex() -> Int? {
|
||||
switch inputSource {
|
||||
case .liveInput(let channel):
|
||||
do {
|
||||
return try liveInputBusIndex(channel: channel, engine: engine)
|
||||
} catch {
|
||||
print("[ShoeGaze] startRecording: invalid .liveInput channel — skipping input tap. (\(error))")
|
||||
return nil
|
||||
}
|
||||
|
||||
case .testLoop:
|
||||
guard let firstBoard: PedalBoard = boards.first else {
|
||||
print("[ShoeGaze] startRecording: no boards available for .testLoop input tap — recording output only.")
|
||||
return nil
|
||||
}
|
||||
return firstBoard.headBus.index
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
// BranchChain.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// A linear sub-chain of pedals within one branch of a parallel section.
|
||||
///
|
||||
/// `BranchChain` mirrors ``PedalBoard/add(_:)`` logic but writes into branch-local buses
|
||||
/// rather than the board's main bus path. Each call to ``add(_:)`` allocates a new output
|
||||
/// bus, configures the pedal's sample rate and bus indices, and inserts the pedal into the
|
||||
/// engine immediately after the current shared tail node.
|
||||
///
|
||||
/// ## Evaluation order
|
||||
///
|
||||
/// Both branches in a ``ParallelSection`` share a single `sharedTail` pointer so that all
|
||||
/// branch pedals appear in a flat linear sequence in the engine's node tree. The tree layout is:
|
||||
///
|
||||
/// ```
|
||||
/// Splitter → [branchA pedals in order] → [branchB pedals in order] → Merger
|
||||
/// ```
|
||||
///
|
||||
/// Despite being "parallel" in signal-flow terms (each branch reads from an independent
|
||||
/// splitter output bus), correctness requires that all pedals that write their respective
|
||||
/// output buses evaluate before the ``Merger`` reads those buses. The flat linear layout
|
||||
/// guarantees this regardless of which branch pedals are added first.
|
||||
///
|
||||
/// A `BranchChain` is created by ``PedalBoard/split()`` and is accessed via
|
||||
/// ``ParallelSection/branchA`` and ``ParallelSection/branchB``. Call ``PedalBoard/merge(_:)``
|
||||
/// to combine the two branches back into the main chain after adding pedals.
|
||||
@MainActor
|
||||
public final class BranchChain {
|
||||
|
||||
// MARK: - State
|
||||
|
||||
private let engine: SynthesisEngine
|
||||
|
||||
/// All pedals in this branch in insertion (signal-flow) order.
|
||||
public private(set) var pedals: [Pedal] = []
|
||||
|
||||
/// Index of the bus that the last pedal in this branch writes to. Before any pedal is
|
||||
/// added this is the branch's input bus (the output of the splitter for this branch).
|
||||
public private(set) var tailBusIndex: Int
|
||||
|
||||
/// Shared tail node pointer. Both branches in a ``ParallelSection`` share the same
|
||||
/// `SharedTail` wrapper so all pedals are inserted in a flat linear order.
|
||||
private let sharedTail: SharedTail
|
||||
|
||||
/// All buses allocated by this branch (for release on teardown).
|
||||
private var allocatedBuses: [AudioBus] = []
|
||||
|
||||
/// Sample rate injected from the board, used to configure each added pedal.
|
||||
private let sampleRate: Double
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a branch chain seeded to a particular starting bus and shared tail reference.
|
||||
///
|
||||
/// This initialiser is called internally by ``PedalBoard/split()``. Callers never
|
||||
/// construct a `BranchChain` directly.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - engine: The `SynthesisEngine` that will own the branch's pedal nodes.
|
||||
/// - inputBus: The bus index from which the first pedal in the branch reads its input.
|
||||
/// - sampleRate: The engine sample rate; injected into each added pedal.
|
||||
/// - sharedTail: Shared mutable reference to the current tree tail node. Both branches
|
||||
/// of the same `ParallelSection` share this wrapper so insertions from either branch
|
||||
/// form a flat linear chain rather than sibling trees both rooted at the splitter.
|
||||
init(
|
||||
engine: SynthesisEngine,
|
||||
inputBus: AudioBus,
|
||||
sampleRate: Double,
|
||||
sharedTail: SharedTail
|
||||
) {
|
||||
self.engine = engine
|
||||
self.tailBusIndex = inputBus.index
|
||||
self.sampleRate = sampleRate
|
||||
self.sharedTail = sharedTail
|
||||
self.allocatedBuses.append(inputBus)
|
||||
}
|
||||
|
||||
// MARK: - Adding pedals
|
||||
|
||||
/// Appends a pedal to the end of this branch and adds it to the engine.
|
||||
///
|
||||
/// The pedal's `inputBus` is set to the current branch tail bus; a new mono bus is
|
||||
/// allocated for its `outputBus`. After this call, ``tailBusIndex`` advances to the
|
||||
/// new output bus.
|
||||
///
|
||||
/// The pedal is inserted after the shared tail node (which may be the splitter, or a
|
||||
/// pedal from either branch), so all branch pedals appear in the tree in the order they
|
||||
/// were added across both branches combined.
|
||||
///
|
||||
/// - Parameter pedal: The pedal to append to this branch.
|
||||
/// - Throws:
|
||||
/// - `BusAllocatorError.noFreeBus` if no mono audio bus is available.
|
||||
/// - `EngineAddError` if the engine rejects the add (e.g. queue full, double-add).
|
||||
public func add(_ pedal: Pedal) throws {
|
||||
let pedalOutputBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
allocatedBuses.append(pedalOutputBus)
|
||||
|
||||
pedal.inputBus = tailBusIndex
|
||||
pedal.outputBus = pedalOutputBus.index
|
||||
pedal.sampleRate = sampleRate
|
||||
|
||||
try engine.add(pedal, position: .after(sharedTail.node))
|
||||
|
||||
pedals.append(pedal)
|
||||
sharedTail.node = pedal
|
||||
tailBusIndex = pedalOutputBus.index
|
||||
}
|
||||
|
||||
// MARK: - Teardown
|
||||
|
||||
/// Removes all pedals from the engine and releases all allocated buses.
|
||||
///
|
||||
/// Called internally by ``PedalBoard/teardown()`` when the board is torn down.
|
||||
/// After calling this method the `BranchChain` should not be reused.
|
||||
func teardown() {
|
||||
for pedal: Pedal in pedals {
|
||||
engine.remove(pedal)
|
||||
}
|
||||
pedals.removeAll()
|
||||
for bus: AudioBus in allocatedBuses {
|
||||
engine.busAllocator.releaseAudioBus(bus)
|
||||
}
|
||||
allocatedBuses.removeAll()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SharedTail
|
||||
|
||||
/// A mutable reference wrapper for the current tree-tail node shared between branch chains.
|
||||
///
|
||||
/// Both ``BranchChain`` instances in a ``ParallelSection`` hold the same `SharedTail` so
|
||||
/// that insertions from either branch always go after the most recently inserted node — forming
|
||||
/// a flat linear chain in the node tree. Isolation is provided by `@MainActor`.
|
||||
@MainActor
|
||||
final class SharedTail {
|
||||
|
||||
/// The current tree-tail node. Updated by each `BranchChain.add(_:)` call.
|
||||
var node: any Synthesizer
|
||||
|
||||
/// Creates a `SharedTail` seeded to the given node (typically the ``Splitter``).
|
||||
///
|
||||
/// - Parameter node: The initial tail — the node after which the first branch pedal will
|
||||
/// be inserted.
|
||||
init(node: any Synthesizer) {
|
||||
self.node = node
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
// ChainRouter.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Routes one shared input to two independent `PedalBoard` chains, then merges their
|
||||
/// outputs through a single `BoardOutputMaster` to stereo hardware output.
|
||||
///
|
||||
/// ## Topology
|
||||
///
|
||||
/// ```
|
||||
/// inputSource → routerInputBus → Splitter → boardA.headBus → boardA chain ─┐
|
||||
/// → boardB.headBus → boardB chain ─┤
|
||||
/// Merger → routerMixBus → BoardOutputMaster → hw 0/1
|
||||
/// ```
|
||||
///
|
||||
/// The ``mode`` property (delegating to ``splitter``) selects which chain is audible:
|
||||
/// - `.a` — only board A passes through; board B is muted.
|
||||
/// - `.b` — only board B passes through; board A is muted.
|
||||
/// - `.both` — both boards are summed at the merger (full parallel operation).
|
||||
///
|
||||
/// ## Typical usage
|
||||
///
|
||||
/// ```swift
|
||||
/// let router: ChainRouter = try shoeGaze.makeChainRouter()
|
||||
/// try router.addToA(OverdrivePedal())
|
||||
/// try router.addToB(DelayPedal())
|
||||
/// try router.finalize()
|
||||
/// router.mode = .both
|
||||
/// try engine.start()
|
||||
/// ```
|
||||
///
|
||||
/// Add pedals via ``addToA(_:)`` and ``addToB(_:)`` rather than calling `boardA.add` or
|
||||
/// `boardB.add` directly. These methods update an internal `lastInsertedNode` pointer so
|
||||
/// ``finalize()`` can always place the merger after the true last node in the evaluation
|
||||
/// tree, regardless of the order in which boards are populated.
|
||||
///
|
||||
/// Do **not** add the router's boards to `ShoeGaze.boards` via `addBoard()` —
|
||||
/// this router owns their lifecycle. Call ``teardown()`` (or `ShoeGaze.teardown()`)
|
||||
/// to clean up.
|
||||
///
|
||||
/// ## Evaluation order
|
||||
///
|
||||
/// 1. `source` evaluates first and writes `routerInputBus`.
|
||||
/// 2. `splitter` evaluates immediately after `source`, reads `routerInputBus`,
|
||||
/// and writes `boardA.headBus` and `boardB.headBus`.
|
||||
/// 3. Each board's pedals evaluate in the order they were added via ``addToA(_:)`` /
|
||||
/// ``addToB(_:)``. Because `lastInsertedNode` is updated after every add,
|
||||
/// pedals from either board are always chained after the previously inserted node.
|
||||
/// 4. After ``finalize()``, the `merger` is inserted after `lastInsertedNode`
|
||||
/// (the overall last node across both boards, or the splitter when both are empty).
|
||||
/// 5. The `BoardOutputMaster` is inserted immediately after the merger.
|
||||
@MainActor
|
||||
public final class ChainRouter {
|
||||
|
||||
// MARK: - Public boards
|
||||
|
||||
/// The first pedalboard chain.
|
||||
///
|
||||
/// Add pedals via ``addToA(_:)`` (preferred) to keep ``finalize()`` ordering correct.
|
||||
/// This property is public for read-only inspection and UI binding only.
|
||||
public let boardA: PedalBoard
|
||||
|
||||
/// The second pedalboard chain.
|
||||
///
|
||||
/// Add pedals via ``addToB(_:)`` (preferred) to keep ``finalize()`` ordering correct.
|
||||
/// This property is public for read-only inspection and UI binding only.
|
||||
public let boardB: PedalBoard
|
||||
|
||||
// MARK: - Routing nodes
|
||||
|
||||
/// The splitter that distributes the shared input to both board head buses.
|
||||
public let splitter: Splitter
|
||||
|
||||
/// The merger that combines both board output buses.
|
||||
/// `nil` until ``finalize()`` is called.
|
||||
public private(set) var merger: Merger?
|
||||
|
||||
// MARK: - Mode convenience
|
||||
|
||||
/// Routing mode. Delegates to ``splitter``.
|
||||
///
|
||||
/// - `.a` → board A audible, board B muted.
|
||||
/// - `.b` → board B audible, board A muted.
|
||||
/// - `.both` → both boards summed at the merger.
|
||||
///
|
||||
/// Transitions are click-free (the splitter lags branch enables over 20 ms).
|
||||
public var mode: SplitMode {
|
||||
get { splitter.mode }
|
||||
set { splitter.mode = newValue }
|
||||
}
|
||||
|
||||
// MARK: - Master stage
|
||||
|
||||
/// The live master-gain `UIParamNode` for the router's output stage. `nil` until
|
||||
/// ``finalize()`` is called. Bind a master-volume knob here.
|
||||
public internal(set) var masterGainNode: UIParamNode?
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
private let engine: SynthesisEngine
|
||||
|
||||
/// The shared input source (either a `TestLoopSource` or `HardwareInputPassThrough`).
|
||||
private let source: any Synthesizer
|
||||
|
||||
/// The bus that the input source writes to, shared by both board head buses via the splitter.
|
||||
private let routerInputBus: AudioBus
|
||||
|
||||
/// The bus that the merger writes to, read by the `BoardOutputMaster`.
|
||||
/// Allocated during ``finalize()``.
|
||||
private var routerMixBus: AudioBus?
|
||||
|
||||
/// The output master synth. `nil` until ``finalize()`` is called.
|
||||
private var outputMaster: BoardOutputMaster?
|
||||
|
||||
/// The board whose first pedal was added earliest (i.e. the board that received its first
|
||||
/// `addToA` / `addToB` call first). Because each board's first pedal inserts
|
||||
/// `.after(splitter)` and subsequent boards push the earlier board further down the
|
||||
/// evaluation list, the first-populated board's tail node is always the last node
|
||||
/// evaluated across both boards — regardless of populate order. ``finalize()`` uses
|
||||
/// `firstPopulatedBoard.tailNode` to place the merger after the full tree.
|
||||
///
|
||||
/// `nil` until the first `addToA` or `addToB` call.
|
||||
private var firstPopulatedBoard: PedalBoard?
|
||||
|
||||
/// Guard that prevents pedals being added after the merger has been inserted.
|
||||
private var finalized: Bool = false
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a chain router backed by `engine` with the given input source policy.
|
||||
///
|
||||
/// Allocates `routerInputBus`, adds the input source to the engine, creates `boardA`
|
||||
/// and `boardB` (each with their own `headBus`), creates the `Splitter` and adds it
|
||||
/// after the source, then sets both boards' `headInputNode` to the splitter so the
|
||||
/// first pedal on each board chains after the splitter automatically.
|
||||
///
|
||||
/// Call ``finalize()`` after all pedals have been added to both boards via
|
||||
/// ``addToA(_:)`` and ``addToB(_:)``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - engine: The `SynthesisEngine` that will own all nodes.
|
||||
/// - inputSource: How the shared input bus is fed. Defaults to `.testLoop`.
|
||||
/// - Throws:
|
||||
/// - `ShoeGazeError.liveInputRequiresInputChannels` when `.liveInput` is used
|
||||
/// but `engine.numInputChannels == 0`.
|
||||
/// - `BusAllocatorError.noFreeBus` if no mono audio bus is available.
|
||||
/// - `EngineAddError` if the engine rejects any node insertion.
|
||||
public init(
|
||||
engine: SynthesisEngine,
|
||||
inputSource: InputSource = .testLoop
|
||||
) throws {
|
||||
self.engine = engine
|
||||
|
||||
// Step 1 — allocate the shared input bus.
|
||||
let inputBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
self.routerInputBus = inputBus
|
||||
|
||||
// Step 2 — add the input source that writes the shared input bus.
|
||||
let addedSource: any Synthesizer
|
||||
switch inputSource {
|
||||
case .testLoop:
|
||||
let loop: TestLoopSource = TestLoopSource(targetBus: inputBus.index)
|
||||
try engine.add(loop)
|
||||
addedSource = loop
|
||||
|
||||
case .liveInput(let channel):
|
||||
let hardwareInputBusIndex: Int
|
||||
do {
|
||||
hardwareInputBusIndex = try liveInputBusIndex(channel: channel, engine: engine)
|
||||
} catch {
|
||||
engine.busAllocator.releaseAudioBus(inputBus)
|
||||
throw error
|
||||
}
|
||||
let passThrough: HardwareInputPassThrough = HardwareInputPassThrough(
|
||||
inputBusIndex: hardwareInputBusIndex,
|
||||
outputBusIndex: inputBus.index
|
||||
)
|
||||
try engine.add(passThrough)
|
||||
addedSource = passThrough
|
||||
}
|
||||
self.source = addedSource
|
||||
|
||||
// Step 3 — create both boards (each allocates its own head bus).
|
||||
let createdBoardA: PedalBoard = try PedalBoard(engine: engine)
|
||||
let createdBoardB: PedalBoard = try PedalBoard(engine: engine)
|
||||
self.boardA = createdBoardA
|
||||
self.boardB = createdBoardB
|
||||
|
||||
// Step 4 — create the splitter and insert it after the source.
|
||||
let builtSplitter: Splitter = Splitter(
|
||||
inputBus: inputBus.index,
|
||||
outputBusA: createdBoardA.headBus.index,
|
||||
outputBusB: createdBoardB.headBus.index
|
||||
)
|
||||
try engine.add(builtSplitter, position: .after(addedSource))
|
||||
self.splitter = builtSplitter
|
||||
|
||||
// Step 5 — point each board's headInputNode at the splitter so the first
|
||||
// pedal on each board is inserted `.after(splitter)` automatically.
|
||||
createdBoardA.headInputNode = builtSplitter
|
||||
createdBoardB.headInputNode = builtSplitter
|
||||
}
|
||||
|
||||
// MARK: - Pedal add helpers
|
||||
|
||||
/// Appends a pedal to board A and, on the first call across either board, records
|
||||
/// board A as the first-populated board so ``finalize()`` can correctly place the
|
||||
/// merger after the full evaluation tree.
|
||||
///
|
||||
/// - Parameter pedal: The pedal to append to board A's signal chain.
|
||||
/// - Throws:
|
||||
/// - `ShoeGazeError.routerAlreadyFinalized` if ``finalize()`` has already been called.
|
||||
/// - `BusAllocatorError.noFreeBus` if no mono audio bus is available.
|
||||
/// - `EngineAddError` if the engine rejects the add.
|
||||
public func addToA(_ pedal: Pedal) throws {
|
||||
guard !finalized else { throw ShoeGazeError.routerAlreadyFinalized }
|
||||
try boardA.add(pedal)
|
||||
// Record the first board to receive a pedal. The first-populated board's first
|
||||
// pedal inserts `.after(splitter)`; subsequent boards push it further down the
|
||||
// tree, making the first-populated board's tail always the last evaluated node.
|
||||
if firstPopulatedBoard == nil { firstPopulatedBoard = boardA }
|
||||
}
|
||||
|
||||
/// Appends a pedal to board B and, on the first call across either board, records
|
||||
/// board B as the first-populated board so ``finalize()`` can correctly place the
|
||||
/// merger after the full evaluation tree.
|
||||
///
|
||||
/// - Parameter pedal: The pedal to append to board B's signal chain.
|
||||
/// - Throws:
|
||||
/// - `ShoeGazeError.routerAlreadyFinalized` if ``finalize()`` has already been called.
|
||||
/// - `BusAllocatorError.noFreeBus` if no mono audio bus is available.
|
||||
/// - `EngineAddError` if the engine rejects the add.
|
||||
public func addToB(_ pedal: Pedal) throws {
|
||||
guard !finalized else { throw ShoeGazeError.routerAlreadyFinalized }
|
||||
try boardB.add(pedal)
|
||||
// See addToA — only the first call across either board sets firstPopulatedBoard.
|
||||
if firstPopulatedBoard == nil { firstPopulatedBoard = boardB }
|
||||
}
|
||||
|
||||
// MARK: - Finalize
|
||||
|
||||
/// Completes the router by inserting the merger and output master into the engine.
|
||||
///
|
||||
/// The merger is inserted after ``lastInsertedNode`` — the most recently added pedal
|
||||
/// across either board (via ``addToA(_:)`` / ``addToB(_:)``), or the splitter when
|
||||
/// neither board has any pedals. This placement is correct regardless of whether
|
||||
/// board A or board B was populated first. The `BoardOutputMaster` is inserted
|
||||
/// immediately after the merger and writes stereo hardware output buses 0 and 1.
|
||||
///
|
||||
/// After `finalize()` returns, calls to ``addToA(_:)`` / ``addToB(_:)`` throw
|
||||
/// `ShoeGazeError.routerAlreadyFinalized`.
|
||||
///
|
||||
/// - Throws:
|
||||
/// - `BusAllocatorError.noFreeBus` if no mono audio bus is available for the mix bus.
|
||||
/// - `EngineAddError` if the engine rejects the merger or master node.
|
||||
public func finalize() throws {
|
||||
// Finalize step 1 — allocate the mix bus and create the merger.
|
||||
let mixBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
self.routerMixBus = mixBus
|
||||
|
||||
let builtMerger: Merger = Merger(
|
||||
inputBusA: boardA.outputBus.index,
|
||||
inputBusB: boardB.outputBus.index,
|
||||
outputBus: mixBus.index
|
||||
)
|
||||
|
||||
// Insert the merger after the true last node in the evaluation tree.
|
||||
//
|
||||
// Both boards set headInputNode = splitter, so each board's first pedal inserts
|
||||
// `.after(splitter)`. The second board to add its first pedal pushes the first
|
||||
// board's chain further down the list. Therefore the board whose first pedal was
|
||||
// added FIRST always has its tail node last in the tree — `firstPopulatedBoard`
|
||||
// captures this. Fall back to the splitter when neither board has any pedals.
|
||||
let mergerPredecessor: any Synthesizer = firstPopulatedBoard?.tailNode ?? splitter
|
||||
try engine.add(builtMerger, position: .after(mergerPredecessor))
|
||||
self.merger = builtMerger
|
||||
|
||||
// Finalize step 2 — create the output master and insert it after the merger.
|
||||
let master: BoardOutputMaster = BoardOutputMaster(boardOutputBusIndex: mixBus.index)
|
||||
try engine.add(master, position: .after(builtMerger))
|
||||
self.outputMaster = master
|
||||
self.masterGainNode = master.gainNode
|
||||
|
||||
finalized = true
|
||||
}
|
||||
|
||||
// MARK: - Teardown
|
||||
|
||||
/// Removes all router-owned nodes from the engine and releases the router buses.
|
||||
///
|
||||
/// Calls `boardA.teardown()` and `boardB.teardown()` to remove pedals and release
|
||||
/// board buses. The router's own nodes (master, merger, splitter, source) are
|
||||
/// removed first so no node writes to a bus after it has been released.
|
||||
///
|
||||
/// - Important: Call only after the engine has been stopped, or accept one block
|
||||
/// of glitch on a still-running engine. `engine.remove(_:)` only enqueues removal;
|
||||
/// the actual dequeue happens on the next render block. Releasing buses immediately
|
||||
/// after enqueue means a still-running engine could write to a reallocated bus for
|
||||
/// one block. The buses are pooled (not freed), so worst case is a transient glitch,
|
||||
/// not a crash. Stop the engine first to avoid this.
|
||||
public func teardown() {
|
||||
// Remove master and merger (writers of routerMixBus) before releasing it.
|
||||
if let master: BoardOutputMaster = outputMaster {
|
||||
engine.remove(master)
|
||||
}
|
||||
if let builtMerger: Merger = merger {
|
||||
engine.remove(builtMerger)
|
||||
}
|
||||
// Remove splitter and source before boards release their head buses.
|
||||
engine.remove(splitter)
|
||||
engine.remove(source)
|
||||
|
||||
// Remove all pedals from both boards and release board buses.
|
||||
boardA.teardown()
|
||||
boardB.teardown()
|
||||
|
||||
// Release the router-owned buses.
|
||||
if let mixBus: AudioBus = routerMixBus {
|
||||
engine.busAllocator.releaseAudioBus(mixBus)
|
||||
}
|
||||
engine.busAllocator.releaseAudioBus(routerInputBus)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// Merger.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Sums two branch buses to a single output bus with independent per-branch levels.
|
||||
///
|
||||
/// Intended as the downstream companion to ``Splitter`` when combining two parallel
|
||||
/// signal paths back into a single chain. Each branch contributes its signal scaled
|
||||
/// by its level parameter; the two scaled signals are summed into `outputBus`.
|
||||
///
|
||||
/// ## Signal graph
|
||||
///
|
||||
/// ```
|
||||
/// inputBusA → In.Audio × levelA ──┐
|
||||
/// + → outputBus
|
||||
/// inputBusB → In.Audio × levelB ──┘
|
||||
/// ```
|
||||
///
|
||||
/// ## Parameters
|
||||
///
|
||||
/// - `levelA`: Gain applied to branch A before summing. `1.0` = unity gain, `0.0` = muted.
|
||||
/// - `levelB`: Gain applied to branch B before summing. `1.0` = unity gain, `0.0` = muted.
|
||||
///
|
||||
/// > Note: With both defaults at `1.0`, two branches carrying the same signal sum to
|
||||
/// > approximately 2× amplitude. In normal use the ``Splitter`` routes independent bus
|
||||
/// > paths to each branch, so they carry different signals and this doubling does not
|
||||
/// > occur. For an empty (pass-through) branch with `levelA = levelB = 1.0`, lower
|
||||
/// > one of the levels or attenuate in the signal chain to avoid the additive boost.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBusA: Audio bus index from which branch A's signal is read.
|
||||
/// - inputBusB: Audio bus index from which branch B's signal is read.
|
||||
/// - outputBus: Audio bus index to which the summed output is written.
|
||||
public final class Merger: SynthesizerBase {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Level for branch A. `1.0` = unity gain, `0.0` = muted.
|
||||
@UIParam public var levelA: Double = 1.0
|
||||
|
||||
/// Level for branch B. `1.0` = unity gain, `0.0` = muted.
|
||||
@UIParam public var levelB: Double = 1.0
|
||||
|
||||
// MARK: - Routing
|
||||
|
||||
/// Audio bus index from which branch A's signal is read.
|
||||
public internal(set) var inputBusA: Int
|
||||
|
||||
/// Audio bus index from which branch B's signal is read.
|
||||
public internal(set) var inputBusB: Int
|
||||
|
||||
/// Audio bus index to which the summed output is written.
|
||||
public internal(set) var outputBus: Int
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a merger that sums two branch buses into one output bus.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBusA: Audio bus index from which branch A's signal is read.
|
||||
/// - inputBusB: Audio bus index from which branch B's signal is read.
|
||||
/// - outputBus: Audio bus index to which the summed output is written.
|
||||
public init(
|
||||
inputBusA: Int,
|
||||
inputBusB: Int,
|
||||
outputBus: Int
|
||||
) {
|
||||
self.inputBusA = inputBusA
|
||||
self.inputBusB = inputBusB
|
||||
self.outputBus = outputBus
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - Build
|
||||
|
||||
/// Builds the signal graph: (inputBusA × levelA) + (inputBusB × levelB) → outputBus.
|
||||
public override func build() {
|
||||
let sigA: In.Audio = input(bus: inputBusA)
|
||||
let sigB: In.Audio = input(bus: inputBusB)
|
||||
output(bus: outputBus, source: (sigA * $levelA) + (sigB * $levelB))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// ParallelSection.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// A parallel signal-routing section inside a ``PedalBoard``.
|
||||
///
|
||||
/// A `ParallelSection` is created by ``PedalBoard/split()`` and holds the two independent
|
||||
/// branch sub-chains plus the ``Splitter`` node that feeds them. After adding pedals to each
|
||||
/// branch, pass the section to ``PedalBoard/merge(_:)`` to combine the branches back into
|
||||
/// the main board chain.
|
||||
///
|
||||
/// ## Typical usage
|
||||
///
|
||||
/// ```swift
|
||||
/// let section = try board.split()
|
||||
/// try section.branchA.add(DelayPedal())
|
||||
/// try section.branchB.add(FuzzPedal())
|
||||
/// try board.merge(section)
|
||||
/// // Further board.add(_:) calls chain after the merger.
|
||||
/// ```
|
||||
///
|
||||
/// ## Evaluation order
|
||||
///
|
||||
/// Both branches share a single `SharedTail` tracking pointer so all pedals from both
|
||||
/// branches are inserted in a flat linear sequence in the node tree. Signal-flow parallelism
|
||||
/// is expressed via independent buses, not via tree structure:
|
||||
///
|
||||
/// ```
|
||||
/// … → Splitter → [branchA pedals] → [branchB pedals] → Merger → …
|
||||
/// ```
|
||||
///
|
||||
/// The merger is inserted after the `SharedTail` — i.e. after the last pedal added across
|
||||
/// either branch — so all branch pedals have written their output buses before the merger reads
|
||||
/// them. This guarantees correctness regardless of the order in which the caller adds pedals to
|
||||
/// the two branches.
|
||||
@MainActor
|
||||
public final class ParallelSection {
|
||||
|
||||
// MARK: - Nodes and chains
|
||||
|
||||
/// The splitter that routes the pre-section signal into the two branches.
|
||||
public let splitter: Splitter
|
||||
|
||||
/// Sub-chain A of this parallel section.
|
||||
public let branchA: BranchChain
|
||||
|
||||
/// Sub-chain B of this parallel section.
|
||||
public let branchB: BranchChain
|
||||
|
||||
/// Shared tail pointer updated by both branch chains. Used by ``PedalBoard/merge(_:)``
|
||||
/// to determine the node after which the merger should be inserted.
|
||||
internal let sharedTail: SharedTail
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a parallel section. Called internally by ``PedalBoard/split()``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - splitter: The ``Splitter`` node that fans out into the two branches.
|
||||
/// - branchA: The first branch sub-chain, fed by the splitter's A output bus.
|
||||
/// - branchB: The second branch sub-chain, fed by the splitter's B output bus.
|
||||
/// - sharedTail: The shared tail tracking pointer used by both branch chains.
|
||||
init(
|
||||
splitter: Splitter,
|
||||
branchA: BranchChain,
|
||||
branchB: BranchChain,
|
||||
sharedTail: SharedTail
|
||||
) {
|
||||
self.splitter = splitter
|
||||
self.branchA = branchA
|
||||
self.branchB = branchB
|
||||
self.sharedTail = sharedTail
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// SplitMode.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Routing mode for a ``Splitter``.
|
||||
///
|
||||
/// Controls which of the two output branches carries signal:
|
||||
///
|
||||
/// - `.a`: Only branch A passes; branch B is muted.
|
||||
/// - `.b`: Only branch B passes; branch A is muted.
|
||||
/// - `.both`: Both branches carry the full input signal (parallel operation).
|
||||
///
|
||||
/// Transitions between modes are click-free because the ``Splitter`` applies
|
||||
/// a lag to each branch enable value.
|
||||
public enum SplitMode: String, Codable, CaseIterable {
|
||||
|
||||
/// Branch A active, branch B muted.
|
||||
case a
|
||||
|
||||
/// Branch B active, branch A muted.
|
||||
case b
|
||||
|
||||
/// Both branches active (parallel routing).
|
||||
case both
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
// Splitter.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Routes one input bus to two independent output buses with click-free per-branch enables.
|
||||
///
|
||||
/// Both branches read the same input signal. Each branch level is lagged through a
|
||||
/// ``Lag.Control`` so enable/disable transitions are artefact-free (no abrupt cuts).
|
||||
///
|
||||
/// Use ``mode`` as a convenience setter to configure common routing patterns:
|
||||
/// - `.a` → branch A on, branch B muted
|
||||
/// - `.b` → branch B on, branch A muted
|
||||
/// - `.both` → both branches active (full parallel routing)
|
||||
///
|
||||
/// ## Signal graph
|
||||
///
|
||||
/// ```
|
||||
/// inputBus → In.Audio
|
||||
/// ├── × Lag(branchAEnabled) → outputBusA
|
||||
/// └── × Lag(branchBEnabled) → outputBusB
|
||||
/// ```
|
||||
///
|
||||
/// ## Parameters
|
||||
///
|
||||
/// - `branchAEnabled`: Branch A level. `1.0` = passing, `0.0` = muted.
|
||||
/// - `branchBEnabled`: Branch B level. `1.0` = passing, `0.0` = muted.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBus: Audio bus index to read the input signal from.
|
||||
/// - outputBusA: Audio bus index to write branch A's output to.
|
||||
/// - outputBusB: Audio bus index to write branch B's output to.
|
||||
public final class Splitter: SynthesizerBase {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Branch A level. `1.0` = passing, `0.0` = muted. Transitions are click-free.
|
||||
@UIParam public var branchAEnabled: Double = 1.0
|
||||
|
||||
/// Branch B level. `1.0` = passing, `0.0` = muted. Transitions are click-free.
|
||||
@UIParam public var branchBEnabled: Double = 1.0
|
||||
|
||||
// MARK: - Routing
|
||||
|
||||
/// Audio bus index from which the input signal is read.
|
||||
public internal(set) var inputBus: Int
|
||||
|
||||
/// Audio bus index to which branch A's output is written.
|
||||
public internal(set) var outputBusA: Int
|
||||
|
||||
/// Audio bus index to which branch B's output is written.
|
||||
public internal(set) var outputBusB: Int
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Lag time in seconds for branch enable transitions.
|
||||
/// Prevents audible clicks when toggling a branch on or off.
|
||||
private let switchLagTime: Double = 0.02
|
||||
|
||||
/// Threshold above which an enable value is treated as "on" for ``mode`` getter.
|
||||
private let enableThreshold: Double = 0.5
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a splitter that routes one input bus to two branch buses.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBus: Audio bus index to read the input signal from.
|
||||
/// - outputBusA: Audio bus index to write branch A's output to.
|
||||
/// - outputBusB: Audio bus index to write branch B's output to.
|
||||
public init(
|
||||
inputBus: Int,
|
||||
outputBusA: Int,
|
||||
outputBusB: Int
|
||||
) {
|
||||
self.inputBus = inputBus
|
||||
self.outputBusA = outputBusA
|
||||
self.outputBusB = outputBusB
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - Mode convenience
|
||||
|
||||
/// Routing mode derived from the current branch enable values.
|
||||
///
|
||||
/// - Getting: Returns `.both` if both enables are ≥ 0.5; `.a` if only branch A
|
||||
/// is ≥ 0.5; `.b` if only branch B is ≥ 0.5. Returns `.a` if both are below 0.5
|
||||
/// (neither branch active — `.a` is the least-surprising fallback).
|
||||
/// - Setting: Updates `branchAEnabled` and `branchBEnabled` to match the chosen mode.
|
||||
/// `.a` → (1, 0); `.b` → (0, 1); `.both` → (1, 1). Transitions are click-free.
|
||||
public var mode: SplitMode {
|
||||
get {
|
||||
let aOn: Bool = branchAEnabled >= enableThreshold
|
||||
let bOn: Bool = branchBEnabled >= enableThreshold
|
||||
if aOn && bOn { return .both }
|
||||
if aOn { return .a }
|
||||
if bOn { return .b }
|
||||
return .a
|
||||
}
|
||||
set {
|
||||
switch newValue {
|
||||
case .a:
|
||||
branchAEnabled = 1.0
|
||||
branchBEnabled = 0.0
|
||||
case .b:
|
||||
branchAEnabled = 0.0
|
||||
branchBEnabled = 1.0
|
||||
case .both:
|
||||
branchAEnabled = 1.0
|
||||
branchBEnabled = 1.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Build
|
||||
|
||||
/// Builds the signal graph: input → lagged per-branch gain → two output buses.
|
||||
public override func build() {
|
||||
let inSig: In.Audio = input(bus: inputBus)
|
||||
let gainA: Lag.Control = Lag.Control(input: $branchAEnabled, time: switchLagTime)
|
||||
let gainB: Lag.Control = Lag.Control(input: $branchBEnabled, time: switchLagTime)
|
||||
output(bus: outputBusA, source: inSig * gainA)
|
||||
output(bus: outputBusB, source: inSig * gainB)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
// ShoeGaze.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import Observation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
// MARK: - ShoeGaze
|
||||
|
||||
/// Top-level manager for a collection of `PedalBoard`s connected to a `SynthesisEngine`.
|
||||
///
|
||||
/// `ShoeGaze` allocates and connects input sources, board chains, and a master output
|
||||
/// stage. The caller owns the `SynthesisEngine` lifecycle (`engine.start()` /
|
||||
/// `engine.stop()`).
|
||||
///
|
||||
/// ## Typical usage
|
||||
///
|
||||
/// ```swift
|
||||
/// let driver = CoreAudioDriver()
|
||||
/// let engine = SynthesisEngine(
|
||||
/// blockSize: 512, sampleRate: 44100,
|
||||
/// numOutputChannels: 2, numInputChannels: 0, driver: driver
|
||||
/// )
|
||||
/// let sg = try ShoeGaze(engine: engine)
|
||||
/// let board = try sg.addBoard()
|
||||
/// try board.add(OverdrivePedal())
|
||||
/// try board.add(ReverbPedal())
|
||||
/// try engine.start()
|
||||
/// ```
|
||||
///
|
||||
/// ## Input routing
|
||||
///
|
||||
/// When `inputSource == .testLoop`, a `TestLoopSource` is added to the engine
|
||||
/// **before** the first pedal on each board (plain `engine.add` places it at the
|
||||
/// head of `mainGroup`, so it evaluates first).
|
||||
///
|
||||
/// When `inputSource == .liveInput(channel:)`, a `HardwareInputPassThrough` synthesizer
|
||||
/// copies hardware input `channel` (engine bus `numOutputChannels + channel`) to the
|
||||
/// board's head bus. This ensures the first pedal reads from a board-owned bus, not the
|
||||
/// raw hardware input bus. The engine must be created with `numInputChannels > channel`;
|
||||
/// otherwise `addBoard()` throws `ShoeGazeError.liveInputRequiresInputChannels` (no input
|
||||
/// channels) or `.inputChannelOutOfRange` (channel too high).
|
||||
///
|
||||
/// ## Master stage
|
||||
///
|
||||
/// Each board's output bus is read by a `BoardOutputMaster` synth added **after**
|
||||
/// the board's last pedal via `.after(_:)`. The master pans the mono board signal
|
||||
/// to stereo and writes to hardware buses 0 (left) and 1 (right).
|
||||
@MainActor
|
||||
@Observable
|
||||
public final class ShoeGaze {
|
||||
|
||||
// MARK: - Public state
|
||||
|
||||
/// The engine that owns all nodes.
|
||||
public let engine: SynthesisEngine
|
||||
|
||||
/// All boards managed by this instance.
|
||||
public private(set) var boards: [PedalBoard] = []
|
||||
|
||||
/// Input source policy. Affects how `addBoard()` routes signal to the head bus.
|
||||
public var inputSource: InputSource
|
||||
|
||||
// MARK: - Recording state
|
||||
|
||||
/// The folder into which `startRecording()` writes timestamped WAV files.
|
||||
///
|
||||
/// Set this before calling `startRecording()`. If `nil`, `startRecording()` throws
|
||||
/// `ShoeGazeError.recordingFolderNotSet`. The folder is created if it does not exist.
|
||||
public var recordingFolder: URL?
|
||||
|
||||
/// `true` while recording is in progress (between `startRecording()` and `stopRecording()`).
|
||||
///
|
||||
/// The setter is `internal` so that `ShoeGaze+Recording.swift` (same module, different file)
|
||||
/// can toggle this flag; external callers only observe the value through this `public` getter.
|
||||
public internal(set) var isRecording: Bool = false
|
||||
|
||||
/// Active `RecordTap` instances (output + optional input). Populated by `startRecording()`,
|
||||
/// cleared by `stopRecording()`. `internal` so the extension in `ShoeGaze+Recording.swift`
|
||||
/// (same module, different file) can mutate it.
|
||||
internal var recordTaps: [RecordTap] = []
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
private var testLoopSources: [TestLoopSource] = []
|
||||
private var inputPassThroughs: [HardwareInputPassThrough] = []
|
||||
private var outputMasters: [BoardOutputMaster] = []
|
||||
|
||||
/// All chain routers created via ``makeChainRouter()``.
|
||||
/// Routers are torn down (in reverse-creation order) by ``teardown()``.
|
||||
private var routers: [ChainRouter] = []
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a `ShoeGaze` manager backed by the given engine.
|
||||
///
|
||||
/// The caller retains ownership of `engine` and is responsible for calling
|
||||
/// `engine.start()` and `engine.stop()`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - engine: The `SynthesisEngine` to add synthesizers and boards to.
|
||||
/// - inputSource: How the board head bus is fed. Defaults to `.testLoop`.
|
||||
public init(
|
||||
engine: SynthesisEngine,
|
||||
inputSource: InputSource = .testLoop
|
||||
) {
|
||||
self.engine = engine
|
||||
self.inputSource = inputSource
|
||||
}
|
||||
|
||||
// MARK: - Board management
|
||||
|
||||
/// Allocates a new `PedalBoard` connected to the engine, wires the input source,
|
||||
/// and returns the board ready for pedals to be added via `board.add(_:)`.
|
||||
///
|
||||
/// Call this before adding pedals. After all pedals have been added to the returned
|
||||
/// board, call `finalizeBoard(_:)` to connect the output master.
|
||||
///
|
||||
/// When `inputSource == .liveInput(channel:)`, a `HardwareInputPassThrough` is added
|
||||
/// that copies hardware input bus `numOutputChannels + channel` to the board head bus.
|
||||
/// The engine must have been created with `numInputChannels > channel`.
|
||||
///
|
||||
/// - Returns: A configured `PedalBoard` with its head bus allocated and input source wired.
|
||||
/// - Throws:
|
||||
/// - `ShoeGazeError.liveInputRequiresInputChannels` if `.liveInput` is selected but
|
||||
/// the engine has `numInputChannels == 0`.
|
||||
/// - `BusAllocatorError.noFreeBus` if no mono bus is available.
|
||||
/// - `EngineAddError` if the engine rejects a node insertion.
|
||||
@discardableResult
|
||||
public func addBoard() throws -> PedalBoard {
|
||||
let board: PedalBoard = try PedalBoard(engine: engine)
|
||||
board.label = "Board \(boards.count + 1)"
|
||||
|
||||
// Route the input source to the board head bus.
|
||||
switch inputSource {
|
||||
case .testLoop:
|
||||
let source: TestLoopSource = TestLoopSource(targetBus: board.headBus.index)
|
||||
// Plain add → head of mainGroup (evaluates before any pedal).
|
||||
try engine.add(source)
|
||||
testLoopSources.append(source)
|
||||
// Record the source as the head input node so PedalBoard.add(_:) can chain
|
||||
// the first pedal after it automatically (without needing an explicit `after:`).
|
||||
board.headInputNode = source
|
||||
|
||||
case .liveInput(let channel):
|
||||
// Hardware input channel `channel` lives at bus numOutputChannels + channel.
|
||||
// A HardwareInputPassThrough copies it to the board's head bus so all pedals
|
||||
// read from a board-owned bus (not the raw hardware input bus).
|
||||
let hardwareInputBusIndex: Int = try liveInputBusIndex(channel: channel, engine: engine)
|
||||
let passThrough: HardwareInputPassThrough = HardwareInputPassThrough(
|
||||
inputBusIndex: hardwareInputBusIndex,
|
||||
outputBusIndex: board.headBus.index
|
||||
)
|
||||
try engine.add(passThrough)
|
||||
inputPassThroughs.append(passThrough)
|
||||
board.headInputNode = passThrough
|
||||
}
|
||||
|
||||
// Only record the board after all wiring has succeeded. This prevents
|
||||
// orphaning a board (with an allocated head bus) in `boards` if the
|
||||
// input-source add or the guard above throws.
|
||||
boards.append(board)
|
||||
return board
|
||||
}
|
||||
|
||||
/// Connects the output master for a previously prepared board and adds it to the engine.
|
||||
///
|
||||
/// Call this after all pedals have been added to the board via `board.add(_:)`.
|
||||
/// The master reads the board's current `outputBus` and routes it to hardware
|
||||
/// outputs 0 and 1 in stereo.
|
||||
///
|
||||
/// If the board has no pedals, the master is added `.after(headInputNode)` so it
|
||||
/// evaluates after the input source has written the head bus. If no head input node
|
||||
/// is present either, a plain add is used as a last resort.
|
||||
///
|
||||
/// - Parameter board: A `PedalBoard` returned by `addBoard()` with pedals added.
|
||||
/// - Throws: `EngineAddError` if the engine rejects the master node.
|
||||
public func finalizeBoard(_ board: PedalBoard) throws {
|
||||
let master: BoardOutputMaster = BoardOutputMaster(
|
||||
boardOutputBusIndex: board.outputBus.index
|
||||
)
|
||||
// The master evaluates after the entire chain (pedals, splitters, mergers).
|
||||
// `board.tailNode` returns the last inserted node (any Synthesizer), which covers
|
||||
// plain-pedal chains and parallel sections containing routing nodes alike.
|
||||
if let tail: any Synthesizer = board.tailNode {
|
||||
// Normal case: chain after the last node in the board.
|
||||
try engine.add(master, position: .after(tail))
|
||||
} else {
|
||||
// No nodes and no head input node (unusual): plain add.
|
||||
try engine.add(master)
|
||||
}
|
||||
outputMasters.append(master)
|
||||
// Expose the master to the board so the UI can bind a master-volume knob
|
||||
// and `removeBoard(_:)` can tear down just this board's master.
|
||||
board.outputMaster = master
|
||||
board.masterGainNode = master.gainNode
|
||||
board.selectGainNode = master.selectGainNode
|
||||
board.crossfadeTimeNode = master.crossfadeTimeNode
|
||||
|
||||
// If a board is currently soloed, a newly-finalized board must come up silent
|
||||
// (select-gain 0) so it doesn't leak audio past the active solo.
|
||||
if let soloIndex: Int = activeBoardIndex,
|
||||
let newIndex: Int = boards.firstIndex(where: { $0 === board }),
|
||||
newIndex != soloIndex {
|
||||
master.selectGainNode.update(0.0)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Board selection / crossfade
|
||||
|
||||
/// The index of the currently soloed board in ``boards``, or `nil` when all boards
|
||||
/// are audible (the default — every board's output sums to the hardware output).
|
||||
public private(set) var activeBoardIndex: Int?
|
||||
|
||||
/// Crossfades so only `board` is audible, fading the others out.
|
||||
///
|
||||
/// Sets every board's crossfade time to `crossfadeSeconds`, then ramps the selected
|
||||
/// board's select-gain to `1` and all others to `0`. Each board's `BoardOutputMaster`
|
||||
/// lags the select-gain, so the transition is a click-free crossfade of that duration.
|
||||
/// The per-board master-volume knob is unaffected.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - board: The board to make audible. No-op if not managed by this instance.
|
||||
/// - crossfadeSeconds: Crossfade duration in seconds (`0` = instant).
|
||||
public func selectBoard(_ board: PedalBoard, crossfadeSeconds: Double) {
|
||||
guard let index: Int = boards.firstIndex(where: { $0 === board }) else { return }
|
||||
for (offset, managed): (Int, PedalBoard) in boards.enumerated() {
|
||||
managed.crossfadeTimeNode?.update(crossfadeSeconds)
|
||||
managed.selectGainNode?.update(offset == index ? 1.0 : 0.0)
|
||||
}
|
||||
activeBoardIndex = index
|
||||
}
|
||||
|
||||
/// Crossfades all boards back to audible (the default summed state).
|
||||
///
|
||||
/// - Parameter crossfadeSeconds: Crossfade duration in seconds (`0` = instant).
|
||||
public func selectAllBoards(crossfadeSeconds: Double) {
|
||||
for managed: PedalBoard in boards {
|
||||
managed.crossfadeTimeNode?.update(crossfadeSeconds)
|
||||
managed.selectGainNode?.update(1.0)
|
||||
}
|
||||
activeBoardIndex = nil
|
||||
}
|
||||
|
||||
/// Removes a single board and its associated input source and output master from
|
||||
/// the engine, then releases the board's buses. The other boards are unaffected.
|
||||
///
|
||||
/// - Important: Same async-removal caveat as ``teardown()`` — call with the engine
|
||||
/// stopped, or accept up to one block of glitch on a still-running engine.
|
||||
///
|
||||
/// - Parameter board: A board previously returned by ``addBoard()``. No-op if the
|
||||
/// board is not managed by this instance.
|
||||
public func removeBoard(_ board: PedalBoard) {
|
||||
guard let index: Int = boards.firstIndex(where: { $0 === board }) else { return }
|
||||
|
||||
// Stop any active recording before removing the board. The record taps in .testLoop
|
||||
// mode read the first board's headBus; in .liveInput mode they read a hardware input
|
||||
// bus that is valid until the board's input pass-through is removed. Either way,
|
||||
// removing a board while recording could leave the input tap reading a released or
|
||||
// reused bus. Stopping first ensures all taps are removed before any bus is freed.
|
||||
if isRecording {
|
||||
stopRecording()
|
||||
}
|
||||
|
||||
// Remove the board's output master (writer of the hardware output bus).
|
||||
if let master: BoardOutputMaster = board.outputMaster {
|
||||
engine.remove(master)
|
||||
outputMasters.removeAll { $0 === master }
|
||||
}
|
||||
|
||||
// Remove the board's input source (writer of the head bus).
|
||||
if let testLoop: TestLoopSource = board.headInputNode as? TestLoopSource {
|
||||
engine.remove(testLoop)
|
||||
testLoopSources.removeAll { $0 === testLoop }
|
||||
} else if let passThrough: HardwareInputPassThrough = board.headInputNode as? HardwareInputPassThrough {
|
||||
engine.remove(passThrough)
|
||||
inputPassThroughs.removeAll { $0 === passThrough }
|
||||
}
|
||||
|
||||
// Remove the pedals and release the board's buses.
|
||||
board.teardown()
|
||||
boards.remove(at: index)
|
||||
}
|
||||
|
||||
// MARK: - Chain router
|
||||
|
||||
/// Creates a ``ChainRouter`` that routes one shared input to two independent
|
||||
/// ``PedalBoard`` chains and merges their outputs through a single master stage.
|
||||
///
|
||||
/// The router is tracked internally and torn down automatically by ``teardown()``.
|
||||
/// Do **not** also add the router's boards via ``addBoard()`` — the router owns
|
||||
/// their lifecycle.
|
||||
///
|
||||
/// Typical usage:
|
||||
///
|
||||
/// ```swift
|
||||
/// let router = try shoeGaze.makeChainRouter()
|
||||
/// try router.boardA.add(OverdrivePedal())
|
||||
/// try router.boardB.add(DelayPedal())
|
||||
/// try router.finalize()
|
||||
/// router.mode = .both
|
||||
/// try engine.start()
|
||||
/// ```
|
||||
///
|
||||
/// - Returns: A ``ChainRouter`` with both boards ready to receive pedals.
|
||||
/// - Throws:
|
||||
/// - `ShoeGazeError.liveInputRequiresInputChannels` when `inputSource == .liveInput`
|
||||
/// but `engine.numInputChannels == 0`.
|
||||
/// - `BusAllocatorError.noFreeBus` if no mono bus is available.
|
||||
/// - `EngineAddError` if the engine rejects any node insertion.
|
||||
@discardableResult
|
||||
public func makeChainRouter() throws -> ChainRouter {
|
||||
let router: ChainRouter = try ChainRouter(engine: engine, inputSource: inputSource)
|
||||
routers.append(router)
|
||||
return router
|
||||
}
|
||||
|
||||
// MARK: - Internal board reordering
|
||||
|
||||
/// Moves `board` to `targetIndex` within `boards`, locating it by identity.
|
||||
///
|
||||
/// This is an internal helper that mutates `boards` directly — valid only because
|
||||
/// `ShoeGaze` is `@MainActor` (no concurrent access). The method is `internal` rather than
|
||||
/// `public` so callers outside the ShoeGaze module cannot disrupt board ordering.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - board: The `PedalBoard` to reposition. No-op if not found in `boards`.
|
||||
/// - index: The desired destination index. Clamped to `boards.count` after removal
|
||||
/// so it is always a valid insertion point.
|
||||
internal func moveBoard(_ board: PedalBoard, to index: Int) {
|
||||
guard let sourceIndex: Int = boards.firstIndex(where: { $0 === board }) else { return }
|
||||
let removed: PedalBoard = boards.remove(at: sourceIndex)
|
||||
let destination: Int = min(index, boards.count)
|
||||
boards.insert(removed, at: destination)
|
||||
}
|
||||
|
||||
// MARK: - Teardown
|
||||
|
||||
/// Removes all nodes (test sources, input pass-throughs, pedals, masters) from
|
||||
/// the engine and releases all allocated buses.
|
||||
///
|
||||
/// - Important: Call only after the engine has been stopped, or accept one block
|
||||
/// of glitch on a still-running engine. `engine.remove(_:)` only enqueues removal;
|
||||
/// the actual dequeue happens on the next render block. Releasing buses immediately
|
||||
/// after enqueue means a still-running engine could write to a reallocated bus for
|
||||
/// one block. The buses are pooled (not freed), so worst case is a transient glitch,
|
||||
/// not a crash. Stop the engine first to avoid this.
|
||||
///
|
||||
/// All engine nodes that write board buses are removed **before** any
|
||||
/// `board.teardown()` releases buses back to the allocator, preserving the
|
||||
/// remove-before-release ordering.
|
||||
public func teardown() {
|
||||
// Step 0: Stop any active recording before removing board nodes. This ensures
|
||||
// the record taps are removed and their DiskOut handles are closed before the
|
||||
// board buses they reference are released.
|
||||
stopRecording()
|
||||
|
||||
// Step 1: Remove all engine nodes that write to board buses.
|
||||
// Order within this step does not matter; all must finish before bus release.
|
||||
for source: TestLoopSource in testLoopSources {
|
||||
engine.remove(source)
|
||||
}
|
||||
testLoopSources.removeAll()
|
||||
|
||||
for passThrough: HardwareInputPassThrough in inputPassThroughs {
|
||||
engine.remove(passThrough)
|
||||
}
|
||||
inputPassThroughs.removeAll()
|
||||
|
||||
for master: BoardOutputMaster in outputMasters {
|
||||
engine.remove(master)
|
||||
}
|
||||
outputMasters.removeAll()
|
||||
|
||||
// Step 2: Remove pedals from the engine and release all board-owned buses.
|
||||
// board.teardown() removes pedals from the engine and then releases buses,
|
||||
// so bus release only happens after all writers have been dequeued.
|
||||
for board: PedalBoard in boards {
|
||||
board.teardown()
|
||||
}
|
||||
boards.removeAll()
|
||||
|
||||
// Step 3: Tear down all chain routers. Each router removes its own nodes and
|
||||
// releases its buses (master → merger → splitter → source → board buses →
|
||||
// router buses), maintaining the remove-before-release ordering.
|
||||
for router: ChainRouter in routers {
|
||||
router.teardown()
|
||||
}
|
||||
routers.removeAll()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// ShoeGazeError.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Errors thrown by `ShoeGaze` during board and session management.
|
||||
public enum ShoeGazeError: Error, LocalizedError, Equatable, Sendable {
|
||||
|
||||
/// Thrown by `ShoeGaze.addBoard()` when `inputSource == .liveInput` but the engine
|
||||
/// was created with `numInputChannels == 0`.
|
||||
///
|
||||
/// Re-create the `SynthesisEngine` with `numInputChannels > 0` before using `.liveInput`.
|
||||
case liveInputRequiresInputChannels
|
||||
|
||||
/// Thrown when `.liveInput(channel:)` requests a hardware input channel that is
|
||||
/// negative or `>= numInputChannels`. `requested` is the channel asked for;
|
||||
/// `available` is the engine's `numInputChannels`.
|
||||
case inputChannelOutOfRange(requested: Int, available: Int)
|
||||
|
||||
/// Thrown by `ChainRouter.addToA(_:)` or `addToB(_:)` when called after
|
||||
/// ``ChainRouter/finalize()`` has already been invoked.
|
||||
///
|
||||
/// Pedals must be added to the router's boards before `finalize()` so the merger
|
||||
/// is placed after the full evaluation tree. Adding pedals after finalization would
|
||||
/// leave them ordered before the merger in the node tree, causing stale-bus reads.
|
||||
case routerAlreadyFinalized
|
||||
|
||||
/// Thrown by `ShoeGaze.startRecording()` when `recordingFolder` is `nil`.
|
||||
///
|
||||
/// Set `ShoeGaze.recordingFolder` to a `URL` pointing to the desired output
|
||||
/// directory before calling `startRecording()`.
|
||||
case recordingFolderNotSet
|
||||
|
||||
/// Thrown by `ShoeGaze.startRecording()` when a `RecordTap`'s `DiskOut.Audio`
|
||||
/// could not open the destination file (e.g. permissions, disk full).
|
||||
///
|
||||
/// The `URL` identifies the file that could not be created. Any taps that
|
||||
/// were successfully added before the failure are removed and the recording
|
||||
/// session is not started.
|
||||
case recordTapFailedToOpen(URL)
|
||||
|
||||
// MARK: - LocalizedError
|
||||
|
||||
public var errorDescription: String? {
|
||||
switch self {
|
||||
case .liveInputRequiresInputChannels:
|
||||
return "ShoeGaze: .liveInput requires the engine to be created with numInputChannels > 0."
|
||||
case .inputChannelOutOfRange(let requested, let available):
|
||||
return "ShoeGaze: .liveInput channel \(requested) is out of range; engine has \(available) input channel(s)."
|
||||
case .routerAlreadyFinalized:
|
||||
return "ChainRouter: cannot add pedals after finalize() has been called."
|
||||
case .recordingFolderNotSet:
|
||||
return "ShoeGaze: set recordingFolder before calling startRecording()."
|
||||
case .recordTapFailedToOpen(let url):
|
||||
return "ShoeGaze: could not open recording file '\(url.lastPathComponent)'."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
// BoardEditorView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdUI
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// An interactive editor for a single `PedalBoard`.
|
||||
///
|
||||
/// `BoardEditorView` binds to `ShoeGaze` (an `@Observable` class) and reads the live
|
||||
/// board via `shoeGaze.boards[boardIndex]`. Because `ShoeGaze.boards` is an `@Observable`
|
||||
/// tracked property, loading a version — which calls `shoeGaze.rebuildBoard(_:from:)` and
|
||||
/// mutates `boards` in-place at the same index — triggers an automatic SwiftUI re-render
|
||||
/// with the new board and its new pedal list without any manual refresh.
|
||||
///
|
||||
/// ## Board-load re-binding
|
||||
///
|
||||
/// `rebuildBoard(_:from:)` tears down the old board, calls `addBoard()`, and moves the
|
||||
/// result back to `oldIndex`. The `boards` array is mutated on the main actor, so
|
||||
/// `shoeGaze.boards[boardIndex]` — read fresh in `body` — always resolves to the current
|
||||
/// board after a load. `BoardEditorView` never caches the `PedalBoard` reference itself;
|
||||
/// the index is the stable anchor.
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// ```swift
|
||||
/// BoardEditorView(
|
||||
/// shoeGaze: shoeGaze,
|
||||
/// boardIndex: 0,
|
||||
/// versionStore: versionStore
|
||||
/// )
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - shoeGaze: The `ShoeGaze` manager that owns the board.
|
||||
/// - boardIndex: Index into `shoeGaze.boards`. If out of range, a small placeholder
|
||||
/// is shown instead.
|
||||
/// - versionStore: The `BoardVersionStore` that manages named snapshots.
|
||||
public struct BoardEditorView: View {
|
||||
|
||||
// MARK: - Layout constants
|
||||
|
||||
private static let outerPadding: CGFloat = 16
|
||||
private static let headerSpacing: CGFloat = 10
|
||||
private static let sectionSpacing: CGFloat = 14
|
||||
private static let boardBackgroundRed: Double = 0.12
|
||||
private static let boardBackgroundGreen: Double = 0.10
|
||||
private static let boardBackgroundBlue: Double = 0.08
|
||||
private static let boardCornerRadius: CGFloat = 10
|
||||
private static let boardBorderBrightness: Double = 0.30
|
||||
private static let boardBorderOpacity: Double = 0.50
|
||||
private static let boardBorderLineWidth: CGFloat = 1
|
||||
private static let boardPedalAreaPadding: CGFloat = 16
|
||||
private static let labelFontSize: CGFloat = 17
|
||||
private static let placeholderOpacity: Double = 0.55
|
||||
private static let versionMenuMaxWidth: CGFloat = 280
|
||||
private static let versionRowSpacing: CGFloat = 6
|
||||
private static let versionDateOpacity: Double = 0.55
|
||||
private static let versionDateFontSize: CGFloat = 11
|
||||
private static let toolbarButtonSpacing: CGFloat = 8
|
||||
private static let textFieldMinWidth: CGFloat = 160
|
||||
private static let dividerOpacity: Double = 0.20
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let shoeGaze: ShoeGaze
|
||||
private let boardIndex: Int
|
||||
private let versionStore: BoardVersionStore
|
||||
|
||||
/// The text typed into the version-name field before saving.
|
||||
@State private var newVersionName: String = ""
|
||||
|
||||
// MARK: - Date formatting
|
||||
|
||||
/// Short date + time formatter used on version menu rows.
|
||||
private static let savedAtStyle: Date.FormatStyle = Date.FormatStyle()
|
||||
.month(.abbreviated)
|
||||
.day(.defaultDigits)
|
||||
.year(.defaultDigits)
|
||||
.hour(.defaultDigits(amPM: .abbreviated))
|
||||
.minute(.twoDigits)
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a board editor view.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - shoeGaze: The `ShoeGaze` manager that owns the board at `boardIndex`.
|
||||
/// - boardIndex: Index into `shoeGaze.boards`. Renders a placeholder when out of range.
|
||||
/// - versionStore: The `BoardVersionStore` that manages named snapshots for this board.
|
||||
public init(
|
||||
shoeGaze: ShoeGaze,
|
||||
boardIndex: Int,
|
||||
versionStore: BoardVersionStore
|
||||
) {
|
||||
self.shoeGaze = shoeGaze
|
||||
self.boardIndex = boardIndex
|
||||
self.versionStore = versionStore
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
if boardIndex < 0 || boardIndex >= shoeGaze.boards.count {
|
||||
outOfRangePlaceholder
|
||||
} else {
|
||||
let board: PedalBoard = shoeGaze.boards[boardIndex]
|
||||
editorContent(board: board)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Main editor layout
|
||||
|
||||
/// The primary editor layout when `boardIndex` is in range.
|
||||
private func editorContent(board: PedalBoard) -> some View {
|
||||
VStack(alignment: .leading, spacing: BoardEditorView.sectionSpacing) {
|
||||
header(board: board)
|
||||
Divider()
|
||||
.overlay(Color.white.opacity(BoardEditorView.dividerOpacity))
|
||||
pedalArea(board: board)
|
||||
}
|
||||
.padding(BoardEditorView.outerPadding)
|
||||
}
|
||||
|
||||
// MARK: - Header
|
||||
|
||||
/// Toolbar row: board label on the left, version controls on the right.
|
||||
private func header(board: PedalBoard) -> some View {
|
||||
VStack(alignment: .leading, spacing: BoardEditorView.headerSpacing) {
|
||||
HStack(spacing: BoardEditorView.headerSpacing) {
|
||||
Text(board.label)
|
||||
.font(.system(size: BoardEditorView.labelFontSize, weight: .semibold))
|
||||
.foregroundStyle(Color.white)
|
||||
Spacer()
|
||||
diskButtons
|
||||
}
|
||||
HStack(spacing: BoardEditorView.toolbarButtonSpacing) {
|
||||
versionNameField(board: board)
|
||||
versionsMenu
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// "Save to Disk" and "Load from Disk" buttons. Cross-platform; no file picker used.
|
||||
private var diskButtons: some View {
|
||||
HStack(spacing: BoardEditorView.toolbarButtonSpacing) {
|
||||
Button("Save to Disk") {
|
||||
try? versionStore.writeAllToDisk(
|
||||
in: BoardVersionStore.defaultDirectory()
|
||||
)
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
|
||||
Button("Load from Disk") {
|
||||
try? versionStore.loadAllFromDisk(
|
||||
in: BoardVersionStore.defaultDirectory()
|
||||
)
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
}
|
||||
}
|
||||
|
||||
/// Version-name `TextField` + "Save Version" button.
|
||||
private func versionNameField(board: PedalBoard) -> some View {
|
||||
HStack(spacing: BoardEditorView.toolbarButtonSpacing) {
|
||||
TextField("Version name…", text: $newVersionName)
|
||||
.textFieldStyle(.roundedBorder)
|
||||
.frame(minWidth: BoardEditorView.textFieldMinWidth)
|
||||
|
||||
Button("Save Version") {
|
||||
let effectiveName: String = newVersionName.isEmpty
|
||||
? "Version \(versionStore.versions.count + 1)"
|
||||
: newVersionName
|
||||
versionStore.capture(board, name: effectiveName)
|
||||
newVersionName = ""
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
.tint(.orange)
|
||||
}
|
||||
}
|
||||
|
||||
/// A `Menu` listing all saved versions.
|
||||
///
|
||||
/// Each version is represented by a nested `Menu` whose title is the version name.
|
||||
/// Opening a version's sub-menu exposes two reliably-reachable actions:
|
||||
/// - **Load** — calls `shoeGaze.rebuildBoard(_:from:)`, which tears down the old board,
|
||||
/// builds a fresh one from the saved `BoardState`, and moves it back to `boardIndex`.
|
||||
/// Because `ShoeGaze.boards` is `@Observable`, every view reading `shoeGaze.boards`
|
||||
/// re-renders automatically with the replacement board.
|
||||
/// - **Delete** — removes the version from memory AND from disk so that the deletion
|
||||
/// survives the next `loadAllFromDisk` call.
|
||||
private var versionsMenu: some View {
|
||||
Menu {
|
||||
if versionStore.versions.isEmpty {
|
||||
Text("No saved versions")
|
||||
} else {
|
||||
ForEach(versionStore.versions) { version in
|
||||
versionSubmenu(version: version)
|
||||
}
|
||||
}
|
||||
} label: {
|
||||
Label("Versions", systemImage: "clock.arrow.circlepath")
|
||||
}
|
||||
.menuStyle(.automatic)
|
||||
.frame(maxWidth: BoardEditorView.versionMenuMaxWidth, alignment: .leading)
|
||||
}
|
||||
|
||||
/// A nested `Menu` for a single version with Load and Delete actions.
|
||||
///
|
||||
/// Using a sub-menu rather than an `HStack` inside a single menu row ensures that
|
||||
/// both buttons are independently hittable on every platform.
|
||||
private func versionSubmenu(version: BoardVersion) -> some View {
|
||||
let dateString: String = version.savedAt.formatted(BoardEditorView.savedAtStyle)
|
||||
return Menu {
|
||||
Button("Load") {
|
||||
loadVersion(version)
|
||||
}
|
||||
Button("Delete", role: .destructive) {
|
||||
versionStore.remove(version)
|
||||
try? versionStore.deleteFromDisk(version, in: BoardVersionStore.defaultDirectory())
|
||||
}
|
||||
} label: {
|
||||
VStack(alignment: .leading, spacing: BoardEditorView.versionRowSpacing) {
|
||||
Text(version.name)
|
||||
Text(dateString)
|
||||
.font(.system(size: BoardEditorView.versionDateFontSize))
|
||||
.foregroundStyle(Color.secondary.opacity(BoardEditorView.versionDateOpacity))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Pedal area
|
||||
|
||||
/// Scrollable wrap-to-fit pedal area backed by `FlowLayout`.
|
||||
private func pedalArea(board: PedalBoard) -> some View {
|
||||
ScrollView(.vertical, showsIndicators: true) {
|
||||
FlowLayout(
|
||||
horizontalSpacing: FlowLayout.defaultHorizontalSpacing,
|
||||
verticalSpacing: FlowLayout.defaultVerticalSpacing
|
||||
) {
|
||||
ForEach(Array(board.pedals.enumerated()), id: \.offset) { pair in
|
||||
let pedal: Pedal = pair.element
|
||||
PedalView(pedal: pedal)
|
||||
}
|
||||
}
|
||||
.padding(BoardEditorView.boardPedalAreaPadding)
|
||||
}
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: BoardEditorView.boardCornerRadius)
|
||||
.fill(
|
||||
Color(
|
||||
red: BoardEditorView.boardBackgroundRed,
|
||||
green: BoardEditorView.boardBackgroundGreen,
|
||||
blue: BoardEditorView.boardBackgroundBlue
|
||||
)
|
||||
)
|
||||
.overlay(
|
||||
RoundedRectangle(cornerRadius: BoardEditorView.boardCornerRadius)
|
||||
.stroke(
|
||||
Color(white: BoardEditorView.boardBorderBrightness)
|
||||
.opacity(BoardEditorView.boardBorderOpacity),
|
||||
lineWidth: BoardEditorView.boardBorderLineWidth
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Out-of-range placeholder
|
||||
|
||||
/// Shown when `boardIndex` is outside `shoeGaze.boards`.
|
||||
private var outOfRangePlaceholder: some View {
|
||||
Text("No board at index \(boardIndex).")
|
||||
.foregroundStyle(Color.secondary.opacity(BoardEditorView.placeholderOpacity))
|
||||
.padding(BoardEditorView.outerPadding)
|
||||
}
|
||||
|
||||
// MARK: - Version loading
|
||||
|
||||
/// Loads `version` back into the board at `boardIndex`.
|
||||
///
|
||||
/// `rebuildBoard(_:from:)` tears down the old board, allocates a new one populated
|
||||
/// from `version.state`, finalises it, and moves it back to `boardIndex`. Because
|
||||
/// `ShoeGaze` is `@Observable` and `boards` is a tracked property, the mutation
|
||||
/// causes this view to re-render immediately with the replacement board — no manual
|
||||
/// state refresh needed.
|
||||
private func loadVersion(_ version: BoardVersion) {
|
||||
guard boardIndex >= 0, boardIndex < shoeGaze.boards.count else { return }
|
||||
let board: PedalBoard = shoeGaze.boards[boardIndex]
|
||||
do {
|
||||
_ = try shoeGaze.rebuildBoard(board, from: version.state)
|
||||
} catch {
|
||||
print("[BoardEditorView] rebuildBoard failed: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
// ChainRouterView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdUI
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// Renders a ``ChainRouter`` as a vertical stack with transport controls, two labelled
|
||||
/// board rows, and a merger + optional master-gain output stage.
|
||||
///
|
||||
/// Layout (top → bottom):
|
||||
/// 1. **Header row** — ``SplitterView`` on the left; if `router.masterGainNode` is
|
||||
/// non-nil, a "Master" ``ParameterKnob`` on the right.
|
||||
/// 2. **Board A row** — label "A" followed by ``PedalBoardView`` for `router.boardA`.
|
||||
/// 3. **Board B row** — label "B" followed by ``PedalBoardView`` for `router.boardB`.
|
||||
/// 4. **Footer row** — ``MergerView`` for `router.merger` (shown only once finalize
|
||||
/// has been called and `router.merger` is non-nil).
|
||||
///
|
||||
/// `merger` is optional on `ChainRouter` (nil before `finalize()`) — the footer is
|
||||
/// conditionally shown so the view is usable at any lifecycle stage.
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// ```swift
|
||||
/// ChainRouterView(router: chainRouter)
|
||||
/// ```
|
||||
public struct ChainRouterView: View {
|
||||
|
||||
// MARK: - Layout constants
|
||||
|
||||
private static let outerSpacing: CGFloat = 16
|
||||
private static let headerSpacing: CGFloat = 14
|
||||
private static let boardRowSpacing: CGFloat = 8
|
||||
private static let boardLabelFontSize: CGFloat = 11
|
||||
private static let boardLabelOpacity: Double = 0.55
|
||||
private static let masterLabelFontSize: CGFloat = 11
|
||||
private static let masterLabelOpacity: Double = 0.45
|
||||
private static let masterKnobSpacing: CGFloat = 6
|
||||
private static let footerSpacing: CGFloat = 14
|
||||
private static let outerPaddingH: CGFloat = 12
|
||||
private static let outerPaddingV: CGFloat = 12
|
||||
private static let sectionDividerOpacity: Double = 0.12
|
||||
private static let sectionDividerHeight: CGFloat = 1
|
||||
/// Master gain range: 0 = silence, 1 = unity output.
|
||||
private static let masterGainRange: ClosedRange<Double> = 0.0...1.0
|
||||
/// Background colour for the router enclosure (darker than stage floor).
|
||||
private static let backgroundRed: Double = 0.11
|
||||
private static let backgroundGreen: Double = 0.10
|
||||
private static let backgroundBlue: Double = 0.13
|
||||
private static let backgroundCornerRadius: CGFloat = 10
|
||||
private static let backgroundBorderOpacity: Double = 0.30
|
||||
private static let backgroundBorderLineWidth: CGFloat = 1.0
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let router: ChainRouter
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a chain router view for the given ``ChainRouter``.
|
||||
///
|
||||
/// - Parameter router: The `ChainRouter` to display. Board A/B pedal views, the
|
||||
/// splitter mode picker, the merger mix knobs, and the optional master gain knob
|
||||
/// are all derived from this instance. The view correctly handles the pre-`finalize()`
|
||||
/// state where `router.merger` and `router.masterGainNode` are `nil`.
|
||||
public init(router: ChainRouter) {
|
||||
self.router = router
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
VStack(alignment: .leading, spacing: ChainRouterView.outerSpacing) {
|
||||
headerRow
|
||||
sectionDivider
|
||||
boardRow(label: "A", board: router.boardA)
|
||||
sectionDivider
|
||||
boardRow(label: "B", board: router.boardB)
|
||||
if let builtMerger: Merger = router.merger {
|
||||
sectionDivider
|
||||
footerRow(merger: builtMerger)
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, ChainRouterView.outerPaddingH)
|
||||
.padding(.vertical, ChainRouterView.outerPaddingV)
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: ChainRouterView.backgroundCornerRadius)
|
||||
.fill(Color(
|
||||
red: ChainRouterView.backgroundRed,
|
||||
green: ChainRouterView.backgroundGreen,
|
||||
blue: ChainRouterView.backgroundBlue
|
||||
))
|
||||
.overlay(
|
||||
RoundedRectangle(cornerRadius: ChainRouterView.backgroundCornerRadius)
|
||||
.stroke(
|
||||
Color.white.opacity(ChainRouterView.backgroundBorderOpacity),
|
||||
lineWidth: ChainRouterView.backgroundBorderLineWidth
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Subviews
|
||||
|
||||
/// Top row: splitter mode selector + optional master gain knob.
|
||||
private var headerRow: some View {
|
||||
HStack(alignment: .top, spacing: ChainRouterView.headerSpacing) {
|
||||
SplitterView(splitter: router.splitter)
|
||||
Spacer()
|
||||
if let masterNode: UIParamNode = router.masterGainNode {
|
||||
masterKnob(node: masterNode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Master gain knob with a small label above.
|
||||
private func masterKnob(node: UIParamNode) -> some View {
|
||||
VStack(spacing: ChainRouterView.masterKnobSpacing) {
|
||||
Text("MASTER")
|
||||
.font(.system(
|
||||
size: ChainRouterView.masterLabelFontSize,
|
||||
weight: .medium,
|
||||
design: .monospaced
|
||||
))
|
||||
.foregroundStyle(Color.white.opacity(ChainRouterView.masterLabelOpacity))
|
||||
ParameterKnob("Gain", node: node, range: ChainRouterView.masterGainRange)
|
||||
.foregroundStyle(Color.white)
|
||||
}
|
||||
}
|
||||
|
||||
/// A labelled board row.
|
||||
private func boardRow(label: String, board: PedalBoard) -> some View {
|
||||
HStack(alignment: .top, spacing: ChainRouterView.boardRowSpacing) {
|
||||
Text(label)
|
||||
.font(.system(
|
||||
size: ChainRouterView.boardLabelFontSize,
|
||||
weight: .semibold,
|
||||
design: .monospaced
|
||||
))
|
||||
.foregroundStyle(Color.white.opacity(ChainRouterView.boardLabelOpacity))
|
||||
.frame(width: 14, alignment: .leading)
|
||||
.padding(.top, 4) // optically align with board content
|
||||
PedalBoardView(board: board)
|
||||
}
|
||||
}
|
||||
|
||||
/// Footer row with merger mix knobs.
|
||||
private func footerRow(merger: Merger) -> some View {
|
||||
HStack(spacing: ChainRouterView.footerSpacing) {
|
||||
MergerView(merger: merger)
|
||||
Spacer()
|
||||
}
|
||||
}
|
||||
|
||||
/// A thin horizontal rule between sections.
|
||||
private var sectionDivider: some View {
|
||||
Rectangle()
|
||||
.fill(Color.white.opacity(ChainRouterView.sectionDividerOpacity))
|
||||
.frame(height: ChainRouterView.sectionDividerHeight)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
// FlowLayout.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
|
||||
/// A SwiftUI `Layout` that arranges subviews left-to-right and wraps to the next
|
||||
/// row whenever the remaining horizontal space in the current row is exhausted.
|
||||
///
|
||||
/// Each row is filled greedily: subviews are placed in insertion order until
|
||||
/// the next subview would exceed the proposed width, at which point a new row
|
||||
/// begins. The final layout height is the sum of all row heights plus the
|
||||
/// inter-row spacing.
|
||||
///
|
||||
/// ## Infinite / nil proposed width
|
||||
///
|
||||
/// When the container proposes an infinite or `nil` width (e.g. inside a
|
||||
/// horizontal `ScrollView`), `FlowLayout` falls back to `FlowLayout.fallbackMaxWidth`
|
||||
/// and lays out subviews on a single logical strip up to that cap. This avoids
|
||||
/// an unbounded single-row layout that would make `sizeThatFits` report infinite
|
||||
/// height.
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// ```swift
|
||||
/// FlowLayout(horizontalSpacing: 12, verticalSpacing: 16) {
|
||||
/// ForEach(pedals, id: \.id) { pedal in
|
||||
/// PedalView(pedal: pedal)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - horizontalSpacing: Gap between adjacent subviews in the same row.
|
||||
/// Defaults to `FlowLayout.defaultHorizontalSpacing`.
|
||||
/// - verticalSpacing: Gap between rows.
|
||||
/// Defaults to `FlowLayout.defaultVerticalSpacing`.
|
||||
public struct FlowLayout: Layout {
|
||||
|
||||
// MARK: - Named constants
|
||||
|
||||
/// Default gap between subviews within the same row (points).
|
||||
public static let defaultHorizontalSpacing: CGFloat = 16
|
||||
|
||||
/// Default gap between rows (points).
|
||||
public static let defaultVerticalSpacing: CGFloat = 16
|
||||
|
||||
/// Maximum width used when the container proposes infinite or zero width,
|
||||
/// preventing an unbounded single-row layout.
|
||||
public static let fallbackMaxWidth: CGFloat = 1200
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
/// Gap between adjacent subviews in the same row.
|
||||
public let horizontalSpacing: CGFloat
|
||||
|
||||
/// Gap between rows.
|
||||
public let verticalSpacing: CGFloat
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a flow layout with the given spacings.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - horizontalSpacing: Gap between subviews within a row (points).
|
||||
/// Defaults to `FlowLayout.defaultHorizontalSpacing`.
|
||||
/// - verticalSpacing: Gap between rows (points).
|
||||
/// Defaults to `FlowLayout.defaultVerticalSpacing`.
|
||||
public init(
|
||||
horizontalSpacing: CGFloat = FlowLayout.defaultHorizontalSpacing,
|
||||
verticalSpacing: CGFloat = FlowLayout.defaultVerticalSpacing
|
||||
) {
|
||||
self.horizontalSpacing = horizontalSpacing
|
||||
self.verticalSpacing = verticalSpacing
|
||||
}
|
||||
|
||||
// MARK: - Layout protocol
|
||||
|
||||
public func sizeThatFits(
|
||||
proposal: ProposedViewSize,
|
||||
subviews: Subviews,
|
||||
cache: inout ()
|
||||
) -> CGSize {
|
||||
let rows: [[RowItem]] = computeRows(
|
||||
subviews: subviews,
|
||||
availableWidth: resolvedWidth(from: proposal)
|
||||
)
|
||||
return totalSize(rows: rows)
|
||||
}
|
||||
|
||||
public func placeSubviews(
|
||||
in bounds: CGRect,
|
||||
proposal: ProposedViewSize,
|
||||
subviews: Subviews,
|
||||
cache: inout ()
|
||||
) {
|
||||
let rows: [[RowItem]] = computeRows(
|
||||
subviews: subviews,
|
||||
availableWidth: resolvedWidth(from: proposal)
|
||||
)
|
||||
|
||||
var y: CGFloat = bounds.minY
|
||||
for (rowIndex, row): (Int, [RowItem]) in rows.enumerated() {
|
||||
var x: CGFloat = bounds.minX
|
||||
let rowHeight: CGFloat = row.max(by: { $0.size.height < $1.size.height })?.size.height ?? 0
|
||||
|
||||
for item: RowItem in row {
|
||||
subviews[item.index].place(
|
||||
at: CGPoint(x: x, y: y),
|
||||
anchor: .topLeading,
|
||||
proposal: ProposedViewSize(item.size)
|
||||
)
|
||||
x += item.size.width + horizontalSpacing
|
||||
}
|
||||
y += rowHeight
|
||||
if rowIndex < rows.count - 1 {
|
||||
y += verticalSpacing
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Private helpers
|
||||
|
||||
/// A single subview's natural (ideal) size and its index into `subviews`.
|
||||
private struct RowItem {
|
||||
let index: Int
|
||||
let size: CGSize
|
||||
}
|
||||
|
||||
/// Resolves the available width from the container proposal.
|
||||
///
|
||||
/// Falls back to `FlowLayout.fallbackMaxWidth` when the proposed width is
|
||||
/// `nil`, zero, or infinite so the layout algorithm always has a finite bound
|
||||
/// to wrap against.
|
||||
private func resolvedWidth(from proposal: ProposedViewSize) -> CGFloat {
|
||||
guard let width: CGFloat = proposal.width,
|
||||
width > 0,
|
||||
width.isFinite else {
|
||||
return FlowLayout.fallbackMaxWidth
|
||||
}
|
||||
return width
|
||||
}
|
||||
|
||||
/// Partitions all subviews into rows given the available width.
|
||||
///
|
||||
/// Each subview is measured at its ideal size (`unspecified` proposal).
|
||||
/// Subviews are appended to the current row while they fit; when adding the
|
||||
/// next subview would overflow `availableWidth`, a new row is started.
|
||||
///
|
||||
/// A subview wider than `availableWidth` is placed alone on its own row so
|
||||
/// it is always visible rather than silently clipped.
|
||||
private func computeRows(subviews: Subviews, availableWidth: CGFloat) -> [[RowItem]] {
|
||||
var rows: [[RowItem]] = []
|
||||
var currentRow: [RowItem] = []
|
||||
var currentRowWidth: CGFloat = 0
|
||||
|
||||
for index: Int in subviews.indices {
|
||||
let size: CGSize = subviews[index].sizeThatFits(.unspecified)
|
||||
let neededWidth: CGFloat = currentRow.isEmpty
|
||||
? size.width
|
||||
: currentRowWidth + horizontalSpacing + size.width
|
||||
|
||||
if !currentRow.isEmpty, neededWidth > availableWidth {
|
||||
// The subview doesn't fit — commit the current row and start fresh.
|
||||
rows.append(currentRow)
|
||||
currentRow = [RowItem(index: index, size: size)]
|
||||
currentRowWidth = size.width
|
||||
} else {
|
||||
// Fits in the current row (or is the first item on a new row).
|
||||
currentRow.append(RowItem(index: index, size: size))
|
||||
currentRowWidth = neededWidth
|
||||
}
|
||||
}
|
||||
|
||||
if !currentRow.isEmpty {
|
||||
rows.append(currentRow)
|
||||
}
|
||||
|
||||
return rows
|
||||
}
|
||||
|
||||
/// Computes the bounding size of the finished row layout.
|
||||
///
|
||||
/// Width is the widest row; height is the sum of all row heights plus
|
||||
/// inter-row spacing. Returns `.zero` for an empty subview list.
|
||||
private func totalSize(rows: [[RowItem]]) -> CGSize {
|
||||
guard !rows.isEmpty else { return .zero }
|
||||
|
||||
var totalHeight: CGFloat = 0
|
||||
var maxWidth: CGFloat = 0
|
||||
|
||||
for (rowIndex, row): (Int, [RowItem]) in rows.enumerated() {
|
||||
let rowHeight: CGFloat = row.max(by: { $0.size.height < $1.size.height })?.size.height ?? 0
|
||||
let rowWidth: CGFloat = row.reduce(0) { acc, item in
|
||||
acc + item.size.width
|
||||
} + CGFloat(max(row.count - 1, 0)) * horizontalSpacing
|
||||
|
||||
totalHeight += rowHeight
|
||||
if rowIndex < rows.count - 1 {
|
||||
totalHeight += verticalSpacing
|
||||
}
|
||||
maxWidth = max(maxWidth, rowWidth)
|
||||
}
|
||||
|
||||
return CGSize(width: maxWidth, height: totalHeight)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
// MergerView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdUI
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// A compact routing-box view for a ``Merger`` showing two `ParameterKnob` controls
|
||||
/// that adjust the per-branch mix levels.
|
||||
///
|
||||
/// Branch A and B knobs are each bound to their respective `UIParamNode` (obtained via
|
||||
/// `merger.$levelA` / `merger.$levelB`) and accept values in ``MergerView/levelRange``.
|
||||
///
|
||||
/// The enclosure uses a slate/steel tint to visually distinguish routing boxes from
|
||||
/// effect pedals.
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// ```swift
|
||||
/// MergerView(merger: router.merger)
|
||||
/// ```
|
||||
public struct MergerView: 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 knobRowSpacing: CGFloat = 12
|
||||
private static let titleFontSize: CGFloat = 11
|
||||
private static let titleOpacity: Double = 0.55
|
||||
/// Background colour components for the routing-box enclosure (steel).
|
||||
private static let backgroundRed: Double = 0.22
|
||||
private static let backgroundGreen: Double = 0.22
|
||||
private static let backgroundBlue: Double = 0.26
|
||||
/// Level knob range: 0 = muted, 1 = unity gain, 2 = double gain.
|
||||
private static let levelRange: ClosedRange<Double> = 0.0...2.0
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let merger: Merger
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a merger view for the given ``Merger``.
|
||||
///
|
||||
/// - Parameter merger: The `Merger` whose branch level parameters will be bound to
|
||||
/// the two knobs.
|
||||
public init(merger: Merger) {
|
||||
self.merger = merger
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
VStack(spacing: MergerView.sectionSpacing) {
|
||||
Text("MIX")
|
||||
.font(.system(size: MergerView.titleFontSize, weight: .semibold, design: .monospaced))
|
||||
.foregroundStyle(Color.white.opacity(MergerView.titleOpacity))
|
||||
|
||||
HStack(spacing: MergerView.knobRowSpacing) {
|
||||
ParameterKnob("A", node: merger.$levelA, range: MergerView.levelRange)
|
||||
.foregroundStyle(Color.white)
|
||||
ParameterKnob("B", node: merger.$levelB, range: MergerView.levelRange)
|
||||
.foregroundStyle(Color.white)
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, MergerView.containerPaddingH)
|
||||
.padding(.vertical, MergerView.containerPaddingV)
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: MergerView.containerCornerRadius)
|
||||
.fill(Color(
|
||||
red: MergerView.backgroundRed,
|
||||
green: MergerView.backgroundGreen,
|
||||
blue: MergerView.backgroundBlue
|
||||
))
|
||||
.overlay(
|
||||
RoundedRectangle(cornerRadius: MergerView.containerCornerRadius)
|
||||
.stroke(
|
||||
Color.white.opacity(MergerView.containerBorderOpacity),
|
||||
lineWidth: MergerView.containerBorderLineWidth
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
// ParallelSectionView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdUI
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// Renders a ``ParallelSection`` as a horizontal parallel rack.
|
||||
///
|
||||
/// Layout (left → right):
|
||||
/// 1. ``SplitterView`` — mode selector and branch LED indicators.
|
||||
/// 2. A central `VStack` with two labelled branch rows:
|
||||
/// - **A** row: one ``PedalView`` per pedal in `section.branchA`.
|
||||
/// - **B** row: one ``PedalView`` per pedal in `section.branchB`.
|
||||
/// Empty branches show a placeholder label.
|
||||
///
|
||||
/// `ParallelSection` does not expose a `Merger`; the merger is owned by `PedalBoard`
|
||||
/// and is not part of the section object. Only the splitter and branch pedal rows are
|
||||
/// rendered here. The view wraps its central panel in a horizontal `ScrollView` so
|
||||
/// wide branch chains do not overflow the window.
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// ```swift
|
||||
/// ParallelSectionView(section: parallelSection)
|
||||
/// ```
|
||||
public struct ParallelSectionView: 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
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let section: ParallelSection
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a parallel section view for the given ``ParallelSection``.
|
||||
///
|
||||
/// - Parameter section: The `ParallelSection` to render. Both branch pedal arrays
|
||||
/// and the splitter's enable nodes are read from this instance.
|
||||
public init(section: ParallelSection) {
|
||||
self.section = section
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
HStack(alignment: .top, spacing: ParallelSectionView.outerSpacing) {
|
||||
SplitterView(splitter: section.splitter)
|
||||
|
||||
ScrollView(.horizontal, showsIndicators: false) {
|
||||
VStack(alignment: .leading, spacing: ParallelSectionView.branchStackSpacing) {
|
||||
branchRow(label: "A", pedals: section.branchA.pedals)
|
||||
|
||||
Rectangle()
|
||||
.fill(Color.white.opacity(ParallelSectionView.branchSeparatorOpacity))
|
||||
.frame(height: ParallelSectionView.branchSeparatorHeight)
|
||||
|
||||
branchRow(label: "B", pedals: section.branchB.pedals)
|
||||
}
|
||||
.padding(.horizontal, ParallelSectionView.scrollPaddingH)
|
||||
.padding(.vertical, ParallelSectionView.scrollPaddingV)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Subviews
|
||||
|
||||
/// A labelled row of pedal cards for one branch.
|
||||
private func branchRow(label: String, pedals: [Pedal]) -> some View {
|
||||
HStack(alignment: .bottom, spacing: ParallelSectionView.pedalSpacing) {
|
||||
Text(label)
|
||||
.font(.system(
|
||||
size: ParallelSectionView.branchLabelFontSize,
|
||||
weight: .semibold,
|
||||
design: .monospaced
|
||||
))
|
||||
.foregroundStyle(Color.white.opacity(ParallelSectionView.branchLabelOpacity))
|
||||
.frame(width: 14, alignment: .leading)
|
||||
|
||||
if pedals.isEmpty {
|
||||
Text("(empty)")
|
||||
.font(.system(size: ParallelSectionView.emptyBranchFontSize))
|
||||
.foregroundStyle(Color.white.opacity(ParallelSectionView.emptyBranchOpacity))
|
||||
} else {
|
||||
ForEach(Array(pedals.enumerated()), id: \.offset) { pair in
|
||||
let pedal: Pedal = pair.element
|
||||
PedalView(pedal: pedal)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
// PedalBoardView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdUI
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// A horizontal scrolling strip of ``PedalView`` cards, one per pedal in a `PedalBoard`.
|
||||
///
|
||||
/// Pedals appear left-to-right in signal-flow order (the same order as
|
||||
/// `PedalBoard.pedals`). The board's `label` property is shown above the strip on a
|
||||
/// dark "pedalboard" backdrop that evokes a wooden/metal board surface.
|
||||
///
|
||||
/// When `board.masterGainNode` is non-nil (i.e. after `ShoeGaze.finalizeBoard(_:)` has
|
||||
/// been called), a small "Master" section appears at the right end of the scrollable
|
||||
/// strip, containing a single output-level `ParameterKnob` bound to the board's gain node.
|
||||
///
|
||||
/// An optional `onRemove` callback, if provided, is invoked by a small remove button
|
||||
/// rendered in the header row so `PedalBoardView` remains decoupled from `ShoeGaze`.
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// ```swift
|
||||
/// PedalBoardView(board: pedalBoard, onRemove: { shoeGaze.removeBoard(pedalBoard) })
|
||||
/// ```
|
||||
public struct PedalBoardView: View {
|
||||
|
||||
// MARK: - Layout constants
|
||||
|
||||
private static let pedalSpacing: CGFloat = 20
|
||||
private static let horizontalPadding: CGFloat = 16
|
||||
private static let verticalPadding: CGFloat = 20
|
||||
private static let sectionSpacing: CGFloat = 10
|
||||
private static let boardCornerRadius: CGFloat = 8
|
||||
private static let boardBorderOpacity: Double = 0.50
|
||||
private static let boardBorderBrightness: Double = 0.30
|
||||
private static let labelOpacity: Double = 0.60
|
||||
private static let outerHorizontalPadding: CGFloat = 4
|
||||
private static let boardBorderLineWidth: CGFloat = 1
|
||||
/// Dark walnut board surface colour components.
|
||||
private static let boardBackgroundRed: Double = 0.12
|
||||
private static let boardBackgroundGreen: Double = 0.10
|
||||
private static let boardBackgroundBlue: Double = 0.08
|
||||
/// Separator between the pedal strip and the master section.
|
||||
private static let masterSeparatorOpacity: Double = 0.25
|
||||
private static let masterSeparatorWidth: CGFloat = 1
|
||||
private static let masterSectionPaddingH: CGFloat = 12
|
||||
private static let masterSectionPaddingV: CGFloat = 8
|
||||
private static let masterLabelOpacity: Double = 0.45
|
||||
private static let masterGainRange: ClosedRange<Double> = 0.0...1.0
|
||||
/// Size of the header-area remove button.
|
||||
private static let removeButtonFontSize: CGFloat = 11
|
||||
private static let removeButtonOpacity: Double = 0.55
|
||||
private static let headerSpacing: CGFloat = 6
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let board: PedalBoard
|
||||
|
||||
/// Called when the user taps the remove button in the board header.
|
||||
/// If `nil`, no remove button is rendered.
|
||||
private let onRemove: (() -> Void)?
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a horizontal board view for the given `PedalBoard`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - board: The `PedalBoard` whose pedals will be rendered as stompbox cards.
|
||||
/// The board's `label` property is used as the header text.
|
||||
/// - onRemove: Optional closure invoked when the user taps the remove button.
|
||||
/// Pass `nil` to suppress the button entirely. Defaults to `nil`.
|
||||
public init(
|
||||
board: PedalBoard,
|
||||
onRemove: (() -> Void)? = nil
|
||||
) {
|
||||
self.board = board
|
||||
self.onRemove = onRemove
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
VStack(alignment: .leading, spacing: PedalBoardView.sectionSpacing) {
|
||||
boardHeader
|
||||
ScrollView(.horizontal, showsIndicators: false) {
|
||||
HStack(alignment: .bottom, spacing: PedalBoardView.pedalSpacing) {
|
||||
ForEach(Array(board.pedals.enumerated()), id: \.offset) { pair in
|
||||
let pedal: Pedal = pair.element
|
||||
PedalView(pedal: pedal)
|
||||
}
|
||||
if let masterNode: UIParamNode = board.masterGainNode {
|
||||
masterSection(node: masterNode)
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, PedalBoardView.horizontalPadding)
|
||||
.padding(.vertical, PedalBoardView.verticalPadding)
|
||||
}
|
||||
}
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: PedalBoardView.boardCornerRadius)
|
||||
.fill(Color(
|
||||
red: PedalBoardView.boardBackgroundRed,
|
||||
green: PedalBoardView.boardBackgroundGreen,
|
||||
blue: PedalBoardView.boardBackgroundBlue
|
||||
)) // dark walnut board surface
|
||||
.overlay(
|
||||
RoundedRectangle(cornerRadius: PedalBoardView.boardCornerRadius)
|
||||
.stroke(
|
||||
Color(white: PedalBoardView.boardBorderBrightness)
|
||||
.opacity(PedalBoardView.boardBorderOpacity),
|
||||
lineWidth: PedalBoardView.boardBorderLineWidth
|
||||
)
|
||||
)
|
||||
)
|
||||
.padding(.horizontal, PedalBoardView.outerHorizontalPadding)
|
||||
}
|
||||
|
||||
// MARK: - Subviews
|
||||
|
||||
/// Label row with optional remove button, shown above the pedal strip.
|
||||
private var boardHeader: some View {
|
||||
HStack(spacing: PedalBoardView.headerSpacing) {
|
||||
Text(board.label)
|
||||
.font(.subheadline)
|
||||
.foregroundStyle(Color.white.opacity(PedalBoardView.labelOpacity))
|
||||
Spacer()
|
||||
if let remove: () -> Void = onRemove {
|
||||
Button(action: remove) {
|
||||
Text("Remove")
|
||||
.font(.system(size: PedalBoardView.removeButtonFontSize))
|
||||
.foregroundStyle(Color.white.opacity(PedalBoardView.removeButtonOpacity))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
}
|
||||
// Indent to align with the board interior, matching horizontalPadding.
|
||||
.padding(.horizontal, PedalBoardView.horizontalPadding)
|
||||
.padding(.top, PedalBoardView.masterSectionPaddingV)
|
||||
}
|
||||
|
||||
/// Master-gain section rendered at the right end of the pedal strip.
|
||||
///
|
||||
/// A thin vertical separator visually divides the pedal chain from the
|
||||
/// master output stage, matching the pattern used by hardware pedalboards.
|
||||
private func masterSection(node: UIParamNode) -> some View {
|
||||
HStack(alignment: .bottom, spacing: PedalBoardView.pedalSpacing) {
|
||||
Rectangle()
|
||||
.fill(Color.white.opacity(PedalBoardView.masterSeparatorOpacity))
|
||||
.frame(width: PedalBoardView.masterSeparatorWidth)
|
||||
.padding(.vertical, PedalBoardView.masterSectionPaddingV)
|
||||
|
||||
VStack(spacing: PedalBoardView.masterSectionPaddingV) {
|
||||
Text("MASTER")
|
||||
.font(.system(size: PedalBoardView.removeButtonFontSize, weight: .medium, design: .monospaced))
|
||||
.foregroundStyle(Color.white.opacity(PedalBoardView.masterLabelOpacity))
|
||||
ParameterKnob("Gain", node: node, range: PedalBoardView.masterGainRange)
|
||||
.foregroundStyle(Color.white)
|
||||
}
|
||||
.padding(.horizontal, PedalBoardView.masterSectionPaddingH)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
// PedalView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdUI
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
// MARK: - Accent-color mapping (UI-only, never in the core target)
|
||||
|
||||
/// Returns a stompbox enclosure tint colour keyed on the pedal's display name.
|
||||
///
|
||||
/// The core `Pedal` type cannot carry a SwiftUI `Color`, so the mapping lives
|
||||
/// here in the UI target. Unrecognised names fall through to `.gray`.
|
||||
private func enclosureColor(for displayName: String) -> Color {
|
||||
switch displayName {
|
||||
case "Overdrive": return Color(red: 0.85, green: 0.42, blue: 0.08) // warm orange
|
||||
case "Delay": return Color(red: 0.10, green: 0.55, blue: 0.55) // teal
|
||||
case "Reverb": return Color(red: 0.30, green: 0.18, blue: 0.65) // indigo
|
||||
case "Modulation": return Color(red: 0.12, green: 0.58, blue: 0.22) // green
|
||||
case "Fuzz": return Color(red: 0.55, green: 0.10, blue: 0.10) // deep crimson
|
||||
case "Tremolo": return Color(red: 0.20, green: 0.38, blue: 0.72) // cobalt blue
|
||||
case "Phaser": return Color(red: 0.60, green: 0.22, blue: 0.62) // violet
|
||||
case "Compressor": return Color(red: 0.18, green: 0.42, blue: 0.32) // forest green
|
||||
default: return Color(red: 0.36, green: 0.36, blue: 0.38) // steel gray
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Screw decoration
|
||||
|
||||
/// A small circular "screw head" decoration placed in each corner of the enclosure.
|
||||
private struct ScrewDot: View {
|
||||
|
||||
private static let size: CGFloat = 8
|
||||
private static let strokeWidth: CGFloat = 1
|
||||
private static let slotWidth: CGFloat = 1
|
||||
private static let slotHeight: CGFloat = 4
|
||||
private static let fillOpacity: Double = 0.25
|
||||
private static let rimOpacity: Double = 0.18
|
||||
private static let slotOpacity: Double = 0.50
|
||||
|
||||
var body: some View {
|
||||
ZStack {
|
||||
Circle()
|
||||
.fill(Color.black.opacity(ScrewDot.fillOpacity))
|
||||
.frame(width: ScrewDot.size, height: ScrewDot.size)
|
||||
Circle()
|
||||
.stroke(Color.white.opacity(ScrewDot.rimOpacity), lineWidth: ScrewDot.strokeWidth)
|
||||
.frame(width: ScrewDot.size, height: ScrewDot.size)
|
||||
// Slot line — Phillips-style cross
|
||||
Rectangle()
|
||||
.fill(Color.black.opacity(ScrewDot.slotOpacity))
|
||||
.frame(width: ScrewDot.slotWidth, height: ScrewDot.slotHeight)
|
||||
Rectangle()
|
||||
.fill(Color.black.opacity(ScrewDot.slotOpacity))
|
||||
.frame(width: ScrewDot.slotHeight, height: ScrewDot.slotWidth)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - LED
|
||||
|
||||
/// A small circular LED that glows green when the effect is engaged.
|
||||
///
|
||||
/// Bypass polarity: `0` = engaged (effect ON), `1` = bypassed.
|
||||
/// The LED is lit when `bypassValue < 0.5`.
|
||||
private struct LEDIndicator: View {
|
||||
|
||||
private static let diameter: CGFloat = 10
|
||||
private static let glowRadius: CGFloat = 6
|
||||
private static let glowOpacity: Double = 0.75
|
||||
private static let rimLineWidth: CGFloat = 0.5
|
||||
private static let dimBrightness: Double = 0.15
|
||||
private static let rimStrokeOpacity: Double = 0.30
|
||||
|
||||
let bypassValue: Double
|
||||
|
||||
private var isEngaged: Bool { bypassValue < 0.5 }
|
||||
|
||||
var body: some View {
|
||||
ZStack {
|
||||
if isEngaged {
|
||||
Circle()
|
||||
.fill(Color.green.opacity(LEDIndicator.glowOpacity))
|
||||
.frame(
|
||||
width: LEDIndicator.diameter + LEDIndicator.glowRadius,
|
||||
height: LEDIndicator.diameter + LEDIndicator.glowRadius
|
||||
)
|
||||
.blur(radius: LEDIndicator.glowRadius / 2)
|
||||
}
|
||||
Circle()
|
||||
.fill(isEngaged ? Color.green : Color(white: LEDIndicator.dimBrightness))
|
||||
.frame(width: LEDIndicator.diameter, height: LEDIndicator.diameter)
|
||||
.overlay(
|
||||
Circle()
|
||||
.stroke(Color.white.opacity(LEDIndicator.rimStrokeOpacity), lineWidth: LEDIndicator.rimLineWidth)
|
||||
.frame(width: LEDIndicator.diameter, height: LEDIndicator.diameter)
|
||||
)
|
||||
}
|
||||
.frame(width: LEDIndicator.diameter + LEDIndicator.glowRadius,
|
||||
height: LEDIndicator.diameter + LEDIndicator.glowRadius)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Footswitch
|
||||
|
||||
/// A round footswitch-style button that toggles bypass on/off.
|
||||
private struct FootswitchButton: View {
|
||||
|
||||
private static let diameter: CGFloat = 44
|
||||
private static let strokeWidth: CGFloat = 2.5
|
||||
private static let innerDiameter: CGFloat = 36
|
||||
private static let outerFillBrightness: Double = 0.18
|
||||
private static let ringBrightness: Double = 0.50
|
||||
private static let innerFillBrightness: Double = 0.25
|
||||
|
||||
let node: UIParamNode
|
||||
|
||||
var body: some View {
|
||||
Button(action: {
|
||||
let engaged: Bool = node.value < 0.5
|
||||
// Toggle: engaged (0) → bypassed (1) and vice-versa.
|
||||
node.update(engaged ? 1.0 : 0.0)
|
||||
}) {
|
||||
ZStack {
|
||||
Circle()
|
||||
.fill(Color(white: FootswitchButton.outerFillBrightness))
|
||||
.frame(width: FootswitchButton.diameter, height: FootswitchButton.diameter)
|
||||
Circle()
|
||||
.stroke(Color(white: FootswitchButton.ringBrightness),
|
||||
lineWidth: FootswitchButton.strokeWidth)
|
||||
.frame(width: FootswitchButton.diameter, height: FootswitchButton.diameter)
|
||||
Circle()
|
||||
.fill(Color(white: FootswitchButton.innerFillBrightness))
|
||||
.frame(width: FootswitchButton.innerDiameter, height: FootswitchButton.innerDiameter)
|
||||
}
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.frame(width: FootswitchButton.diameter, height: FootswitchButton.diameter)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - PedalView
|
||||
|
||||
/// A stompbox-style enclosure view that renders all controls for a single `Pedal`.
|
||||
///
|
||||
/// The enclosure shows:
|
||||
/// - Corner screw decorations.
|
||||
/// - A contrasting name-plate capsule near the top with `displayName`.
|
||||
/// - A grid of ``ParameterKnob`` controls (up to ``knobColumnCount`` per row) drawn from
|
||||
/// the effect + `Mix` knobs of ``Pedal/knobs``.
|
||||
/// - A centred bottom row pairing the `Level` knob with the bypass switch (LED + footswitch).
|
||||
///
|
||||
/// ## Bypass LED polarity
|
||||
///
|
||||
/// `Pedal.bypass` is `0` = engaged (effect active), `1` = bypassed.
|
||||
/// The LED is **green/lit** when `bypass < 0.5` (effect is on) and dark when bypassed.
|
||||
///
|
||||
/// ## Accent color
|
||||
///
|
||||
/// The enclosure tint is assigned by `enclosureColor(for:)` — a private helper in
|
||||
/// this file keyed on `displayName`. Core `Pedal` never imports SwiftUI.
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// ```swift
|
||||
/// PedalView(pedal: overdrivePedal)
|
||||
/// ```
|
||||
public struct PedalView: View {
|
||||
|
||||
// MARK: - Layout constants
|
||||
|
||||
/// Wide enough for three ~55 pt knobs (dial + label + value) plus padding in a
|
||||
/// single row, so the effect controls never overlap.
|
||||
private static let enclosureWidth: CGFloat = 220
|
||||
private static let enclosureCornerRadius: CGFloat = 12
|
||||
private static let enclosurePadding: CGFloat = 14
|
||||
private static let screwInset: CGFloat = 6
|
||||
private static let knobColumnCount: Int = 3
|
||||
private static let knobSpacing: CGFloat = 10
|
||||
/// Horizontal gap between the Level knob and the bypass control in the bottom row.
|
||||
private static let bottomControlsSpacing: CGFloat = 18
|
||||
private static let sectionSpacing: CGFloat = 14
|
||||
private static let namePlateCornerRadius: CGFloat = 8
|
||||
private static let namePlatePaddingH: CGFloat = 10
|
||||
private static let namePlatePaddingV: CGFloat = 4
|
||||
private static let outerBorderOpacity: Double = 0.60
|
||||
private static let innerHighlightOpacity: Double = 0.22
|
||||
private static let shadowRadius: CGFloat = 8
|
||||
private static let shadowYOffset: CGFloat = 4
|
||||
private static let shadowOpacity: Double = 0.60
|
||||
private static let enclosureGradientDarkFraction: Double = 0.30
|
||||
private static let bypassSectionSpacing: CGFloat = 6
|
||||
/// Half the screw-dot size — used to centre screws on the corner position.
|
||||
private static let screwHalfSize: CGFloat = 4
|
||||
private static let namePlateBackgroundOpacity: Double = 0.35
|
||||
private static let fontSizeNamePlate: CGFloat = 13
|
||||
private static let outerBorderLineWidth: CGFloat = 1.5
|
||||
private static let innerHighlightLineWidth: CGFloat = 1
|
||||
private static let innerHighlightPadding: CGFloat = 1
|
||||
private static let shadowXOffset: CGFloat = 0
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let pedal: Pedal
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a stompbox pedal view for the given pedal.
|
||||
///
|
||||
/// - Parameter pedal: The `Pedal` whose parameters will be displayed.
|
||||
public init(pedal: Pedal) {
|
||||
self.pedal = pedal
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
let accent: Color = enclosureColor(for: pedal.displayName)
|
||||
let darkAccent: Color = accent.opacity(PedalView.enclosureGradientDarkFraction)
|
||||
|
||||
ZStack(alignment: .topLeading) {
|
||||
// Enclosure fill with top-to-bottom gradient
|
||||
RoundedRectangle(cornerRadius: PedalView.enclosureCornerRadius)
|
||||
.fill(
|
||||
LinearGradient(
|
||||
gradient: Gradient(colors: [accent, darkAccent]),
|
||||
startPoint: .top,
|
||||
endPoint: .bottom
|
||||
)
|
||||
)
|
||||
|
||||
// Outer border
|
||||
RoundedRectangle(cornerRadius: PedalView.enclosureCornerRadius)
|
||||
.stroke(Color.black.opacity(PedalView.outerBorderOpacity),
|
||||
lineWidth: PedalView.outerBorderLineWidth)
|
||||
|
||||
// Inner highlight rim (subtle bevel)
|
||||
RoundedRectangle(cornerRadius: PedalView.enclosureCornerRadius - PedalView.innerHighlightPadding)
|
||||
.stroke(Color.white.opacity(PedalView.innerHighlightOpacity),
|
||||
lineWidth: PedalView.innerHighlightLineWidth)
|
||||
.padding(PedalView.innerHighlightPadding)
|
||||
|
||||
// Content stack
|
||||
VStack(spacing: PedalView.sectionSpacing) {
|
||||
namePlate
|
||||
knobGrid
|
||||
Spacer(minLength: 0)
|
||||
bottomControls
|
||||
}
|
||||
.padding(PedalView.enclosurePadding)
|
||||
|
||||
// Corner screws — overlaid at the four corners
|
||||
screwCorners
|
||||
}
|
||||
.frame(width: PedalView.enclosureWidth)
|
||||
.shadow(
|
||||
color: Color.black.opacity(PedalView.shadowOpacity),
|
||||
radius: PedalView.shadowRadius,
|
||||
x: PedalView.shadowXOffset,
|
||||
y: PedalView.shadowYOffset
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Subviews
|
||||
|
||||
/// Capsule name plate near the top of the enclosure.
|
||||
private var namePlate: some View {
|
||||
Text(pedal.displayName)
|
||||
.font(.system(size: PedalView.fontSizeNamePlate, weight: .bold, design: .rounded))
|
||||
.foregroundStyle(Color.white)
|
||||
.padding(.horizontal, PedalView.namePlatePaddingH)
|
||||
.padding(.vertical, PedalView.namePlatePaddingV)
|
||||
.background(Color.black.opacity(PedalView.namePlateBackgroundOpacity))
|
||||
.clipShape(RoundedRectangle(cornerRadius: PedalView.namePlateCornerRadius))
|
||||
}
|
||||
|
||||
/// Grid of the effect + `Mix` knobs, in rows of up to `knobColumnCount`.
|
||||
///
|
||||
/// The `Level` knob (the last entry of `pedal.knobs`) is dropped here and rendered in
|
||||
/// the bottom control row next to the bypass switch, leaving more room for the effect
|
||||
/// controls at the top.
|
||||
private var knobGrid: some View {
|
||||
let knobs: [PedalKnob] = Array(pedal.knobs.dropLast())
|
||||
let rows: [[PedalKnob]] = stride(
|
||||
from: 0,
|
||||
to: knobs.count,
|
||||
by: PedalView.knobColumnCount
|
||||
).map { startIndex in
|
||||
Array(knobs[startIndex ..< min(startIndex + PedalView.knobColumnCount, knobs.count)])
|
||||
}
|
||||
|
||||
return VStack(spacing: PedalView.knobSpacing) {
|
||||
ForEach(Array(rows.enumerated()), id: \.offset) { rowPair in
|
||||
let row: [PedalKnob] = rowPair.element
|
||||
HStack(spacing: PedalView.knobSpacing) {
|
||||
ForEach(Array(row.enumerated()), id: \.offset) { knobPair in
|
||||
let knob: PedalKnob = knobPair.element
|
||||
ParameterKnob(knob.label, node: knob.node, range: knob.range)
|
||||
.foregroundStyle(Color.white)
|
||||
}
|
||||
// Pad short rows so knobs stay aligned in their columns.
|
||||
if row.count < PedalView.knobColumnCount {
|
||||
ForEach(0 ..< (PedalView.knobColumnCount - row.count), id: \.self) { _ in
|
||||
Spacer()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bottom control row: the `Level` knob and the bypass switch side-by-side, centred
|
||||
/// with equal padding below.
|
||||
private var bottomControls: some View {
|
||||
HStack(alignment: .center, spacing: PedalView.bottomControlsSpacing) {
|
||||
levelControl
|
||||
bypassControl
|
||||
}
|
||||
.frame(maxWidth: .infinity)
|
||||
}
|
||||
|
||||
/// The `Level` knob — the last entry of `pedal.knobs`.
|
||||
@ViewBuilder
|
||||
private var levelControl: some View {
|
||||
if let level: PedalKnob = pedal.knobs.last {
|
||||
ParameterKnob(level.label, node: level.node, range: level.range)
|
||||
.foregroundStyle(Color.white)
|
||||
}
|
||||
}
|
||||
|
||||
/// LED + footswitch bypass control, paired beside the Level knob.
|
||||
private var bypassControl: some View {
|
||||
// Reading `pedal.$bypass.value` here registers this view for automatic
|
||||
// re-renders whenever the bypass parameter changes on the main thread
|
||||
// (UIParamNode is @Observable).
|
||||
let bypassValue: Double = pedal.$bypass.value
|
||||
|
||||
return VStack(spacing: PedalView.bypassSectionSpacing) {
|
||||
LEDIndicator(bypassValue: bypassValue)
|
||||
FootswitchButton(node: pedal.$bypass)
|
||||
}
|
||||
}
|
||||
|
||||
/// Four screw dots overlaid at the enclosure corners.
|
||||
private var screwCorners: some View {
|
||||
GeometryReader { geometry in
|
||||
let w: CGFloat = geometry.size.width
|
||||
let h: CGFloat = geometry.size.height
|
||||
let inset: CGFloat = PedalView.screwInset
|
||||
|
||||
let half: CGFloat = PedalView.screwHalfSize
|
||||
|
||||
ZStack(alignment: .topLeading) {
|
||||
// Top-left
|
||||
ScrewDot()
|
||||
.position(x: inset + half, y: inset + half)
|
||||
// Top-right
|
||||
ScrewDot()
|
||||
.position(x: w - inset - half, y: inset + half)
|
||||
// Bottom-left
|
||||
ScrewDot()
|
||||
.position(x: inset + half, y: h - inset - half)
|
||||
// Bottom-right
|
||||
ScrewDot()
|
||||
.position(x: w - inset - half, y: h - inset - half)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// ShoeGazeUI.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdShoeGazeUI views are implemented in:
|
||||
// PedalView.swift — single pedal card
|
||||
// PedalBoardView.swift — horizontal board strip
|
||||
// ShoeGazeView.swift — top-level session view with transport
|
||||
// FlowLayout.swift — wrap-to-fit Layout (left-to-right, row-wrapping)
|
||||
// BoardEditorView.swift — per-board editor with FlowLayout pedal area + version store
|
||||
@@ -0,0 +1,381 @@
|
||||
// ShoeGazeView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AppKit)
|
||||
import AppKit
|
||||
#endif
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// The top-level view for a `ShoeGaze` session.
|
||||
///
|
||||
/// Displays a transport header (Start / Stop engine buttons and an Add Board button),
|
||||
/// a vertically scrollable list of ``PedalBoardView`` strips (one per board), and a
|
||||
/// ``LyrebirdStatusView`` CPU meter at the bottom, all on a dark backdrop that matches
|
||||
/// the stompbox enclosure aesthetic.
|
||||
///
|
||||
/// ## Board identity keying
|
||||
///
|
||||
/// The boards `ForEach` uses `id: \.offset` on an enumerated copy of `shoeGaze.boards`.
|
||||
/// `PedalBoard` is a `@MainActor` class and is neither `Identifiable` nor `Hashable`
|
||||
/// (adding conformance to the core type would violate the module-layering constraint).
|
||||
/// Index keying is stable for the simple append/remove-by-position pattern this demo
|
||||
/// uses and avoids any protocol requirements on the core `PedalBoard` type.
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// ```swift
|
||||
/// ShoeGazeView(shoeGaze: shoeGaze)
|
||||
/// ```
|
||||
public struct ShoeGazeView: View {
|
||||
|
||||
// MARK: - Layout constants
|
||||
|
||||
private static let outerPadding: CGFloat = 20
|
||||
private static let sectionSpacing: CGFloat = 16
|
||||
private static let transportSpacing: CGFloat = 12
|
||||
private static let boardSpacing: CGFloat = 20
|
||||
private static let minWidth: CGFloat = 400
|
||||
private static let dividerOpacity: Double = 0.12
|
||||
/// Stage-floor dark background colour components (very dark warm black).
|
||||
private static let backgroundRed: Double = 0.08
|
||||
private static let backgroundGreen: Double = 0.07
|
||||
private static let backgroundBlue: Double = 0.06
|
||||
/// Default crossfade duration in seconds for board-select transitions.
|
||||
private static let defaultCrossfadeSeconds: Double = 0.3
|
||||
/// Maximum crossfade duration accepted by the crossfade seconds stepper.
|
||||
private static let maxCrossfadeSeconds: Double = 10.0
|
||||
/// Stepper increment for the crossfade seconds control.
|
||||
private static let crossfadeStepIncrement: Double = 0.1
|
||||
/// Width of the crossfade-seconds text field.
|
||||
private static let crossfadeFieldWidth: CGFloat = 60
|
||||
/// Spacing inside the board-select row.
|
||||
private static let boardSelectSpacing: CGFloat = 8
|
||||
/// Opacity for the board-select row labels.
|
||||
private static let labelOpacity: Double = 0.65
|
||||
/// Diameter of the recording-in-progress indicator dot.
|
||||
private static let recordDotSize: CGFloat = 10
|
||||
/// Opacity of the secondary folder-name label shown next to the folder picker button.
|
||||
private static let folderLabelOpacity: Double = 0.55
|
||||
/// Spacing inside the recording controls sub-row.
|
||||
private static let recordingRowSpacing: CGFloat = 10
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let shoeGaze: ShoeGaze
|
||||
|
||||
/// Bumped on each transport button press to force a re-read of the engine's
|
||||
/// running state. The button labels/enabled-state read `shoeGaze.engine.isRunning`
|
||||
/// directly (the single source of truth) rather than a private mirror that could
|
||||
/// drift out of sync if the engine is started/stopped elsewhere.
|
||||
@State private var transportTick: Bool = false
|
||||
|
||||
/// Crossfade duration used for the next board-select transition.
|
||||
@State private var crossfadeSeconds: Double = ShoeGazeView.defaultCrossfadeSeconds
|
||||
|
||||
/// Controls presentation of the iOS `.fileImporter` directory picker.
|
||||
/// On macOS the picker is opened imperatively via `NSOpenPanel`; this flag is
|
||||
/// only meaningful on iOS / non-macOS targets.
|
||||
@State private var showFolderImporter: Bool = false
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a top-level ShoeGaze view.
|
||||
///
|
||||
/// - Parameter shoeGaze: The `ShoeGaze` manager whose boards and engine will
|
||||
/// be displayed. The caller is responsible for engine lifecycle; this view
|
||||
/// provides Start and Stop transport buttons as a convenience.
|
||||
public init(shoeGaze: ShoeGaze) {
|
||||
self.shoeGaze = shoeGaze
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
VStack(alignment: .leading, spacing: ShoeGazeView.sectionSpacing) {
|
||||
transportHeader
|
||||
recordingRow
|
||||
Divider()
|
||||
.overlay(Color.white.opacity(ShoeGazeView.dividerOpacity))
|
||||
boardSelectRow
|
||||
Divider()
|
||||
.overlay(Color.white.opacity(ShoeGazeView.dividerOpacity))
|
||||
boardList
|
||||
Divider()
|
||||
.overlay(Color.white.opacity(ShoeGazeView.dividerOpacity))
|
||||
LyrebirdStatusView(engine: shoeGaze.engine)
|
||||
}
|
||||
.padding(ShoeGazeView.outerPadding)
|
||||
.frame(minWidth: ShoeGazeView.minWidth)
|
||||
.background(
|
||||
Color(
|
||||
red: ShoeGazeView.backgroundRed,
|
||||
green: ShoeGazeView.backgroundGreen,
|
||||
blue: ShoeGazeView.backgroundBlue
|
||||
)
|
||||
)
|
||||
#if !os(macOS)
|
||||
.fileImporter(
|
||||
isPresented: $showFolderImporter,
|
||||
allowedContentTypes: [.folder]
|
||||
) { result in
|
||||
switch result {
|
||||
case .success(let url):
|
||||
// A `.fileImporter` directory URL is security-scoped on iOS; access must
|
||||
// be started before `FileManager` can write into it. Kept open for the
|
||||
// session (released when the app exits).
|
||||
if url.startAccessingSecurityScopedResource() {
|
||||
shoeGaze.recordingFolder = url
|
||||
} else {
|
||||
print("[ShoeGazeView] could not access selected folder")
|
||||
}
|
||||
case .failure(let error):
|
||||
print("[ShoeGazeView] folder picker failed: \(error)")
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Subviews
|
||||
|
||||
/// Transport bar: title, Start/Stop engine buttons, and Add Board button.
|
||||
///
|
||||
/// The button state reads `shoeGaze.engine.isRunning` (the single source of truth)
|
||||
/// so it stays correct even when the engine is started/stopped by another control.
|
||||
/// Audio only flows once the user presses Start — adding boards does not auto-start
|
||||
/// the engine.
|
||||
private var transportHeader: some View {
|
||||
// Referencing `transportTick` makes a press (which toggles it) re-evaluate this
|
||||
// view so `engine.isRunning` is re-read; toggling any @State invalidates the view.
|
||||
_ = transportTick
|
||||
let isRunning: Bool = shoeGaze.engine.isRunning
|
||||
return HStack(spacing: ShoeGazeView.transportSpacing) {
|
||||
Text("ShoeGaze")
|
||||
.font(.title2)
|
||||
.bold()
|
||||
.foregroundStyle(Color.white)
|
||||
Spacer()
|
||||
Button("Add Board") {
|
||||
addBoard()
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.tint(.orange)
|
||||
|
||||
Button("Start") {
|
||||
do {
|
||||
try shoeGaze.engine.start()
|
||||
} catch {
|
||||
// Surface start errors to the console; the UI remains in the
|
||||
// non-running state so the user can retry.
|
||||
print("[ShoeGazeView] engine.start() failed: \(error)")
|
||||
}
|
||||
transportTick.toggle()
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
.tint(.green)
|
||||
.disabled(isRunning)
|
||||
|
||||
Button("Stop") {
|
||||
shoeGaze.engine.stop()
|
||||
transportTick.toggle()
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.tint(.red)
|
||||
.disabled(!isRunning)
|
||||
}
|
||||
}
|
||||
|
||||
/// Recording controls: folder picker, chosen-folder label, and record/stop button.
|
||||
///
|
||||
/// The folder picker opens an `NSOpenPanel` on macOS or a `.fileImporter` sheet on iOS.
|
||||
/// The Record button is disabled until a folder has been chosen; it turns into a Stop
|
||||
/// button (red) while recording is in progress.
|
||||
private var recordingRow: some View {
|
||||
HStack(spacing: ShoeGazeView.recordingRowSpacing) {
|
||||
// --- Folder picker button ---
|
||||
Button("Choose Folder…") {
|
||||
chooseFolderAction()
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.tint(.blue)
|
||||
|
||||
// --- Chosen folder label ---
|
||||
let folderName: String = shoeGaze.recordingFolder?.lastPathComponent ?? "No folder"
|
||||
Text(folderName)
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.white.opacity(ShoeGazeView.folderLabelOpacity))
|
||||
.lineLimit(1)
|
||||
.truncationMode(.middle)
|
||||
|
||||
Spacer()
|
||||
|
||||
// --- Recording-in-progress indicator dot ---
|
||||
if shoeGaze.isRecording {
|
||||
Circle()
|
||||
.fill(Color.red)
|
||||
.frame(
|
||||
width: ShoeGazeView.recordDotSize,
|
||||
height: ShoeGazeView.recordDotSize
|
||||
)
|
||||
}
|
||||
|
||||
// --- Record / Stop button ---
|
||||
Button(shoeGaze.isRecording ? "Stop" : "Record") {
|
||||
if shoeGaze.isRecording {
|
||||
shoeGaze.stopRecording()
|
||||
} else {
|
||||
do {
|
||||
try shoeGaze.startRecording()
|
||||
} catch {
|
||||
print("[ShoeGazeView] startRecording() failed: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
.tint(shoeGaze.isRecording ? .red : .accentColor)
|
||||
.disabled(shoeGaze.recordingFolder == nil)
|
||||
}
|
||||
}
|
||||
|
||||
/// A `Binding<Int>` that maps between the Picker's integer tag and `ShoeGaze` select API.
|
||||
///
|
||||
/// Tag `-1` represents "All boards audible" (`activeBoardIndex == nil`).
|
||||
/// Tags `0 ..< boards.count` represent the soloed board at that index.
|
||||
/// Setting the binding calls `selectBoard(_:crossfadeSeconds:)` or
|
||||
/// `selectAllBoards(crossfadeSeconds:)` with the current `crossfadeSeconds` value.
|
||||
private var boardSelectBinding: Binding<Int> {
|
||||
Binding(
|
||||
get: { shoeGaze.activeBoardIndex ?? -1 },
|
||||
set: { newValue in
|
||||
// Clamp here so a value typed into the crossfade text field (which has no
|
||||
// built-in bounds) can never pass a negative or oversized lag time.
|
||||
let seconds: Double = min(max(crossfadeSeconds, 0.0), ShoeGazeView.maxCrossfadeSeconds)
|
||||
if newValue == -1 {
|
||||
shoeGaze.selectAllBoards(crossfadeSeconds: seconds)
|
||||
} else if newValue >= 0, newValue < shoeGaze.boards.count {
|
||||
shoeGaze.selectBoard(shoeGaze.boards[newValue], crossfadeSeconds: seconds)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/// Board-select row: an "Active" Picker to solo a board (or hear all), a crossfade-
|
||||
/// seconds text field, and a companion Stepper for convenient adjustment.
|
||||
///
|
||||
/// The row is always visible. When `boards.count <= 1` the Picker has only one or two
|
||||
/// options, which is still useful for the "All" / single-board toggle.
|
||||
private var boardSelectRow: some View {
|
||||
HStack(spacing: ShoeGazeView.boardSelectSpacing) {
|
||||
Text("Active:")
|
||||
.font(.subheadline)
|
||||
.foregroundStyle(Color.white.opacity(ShoeGazeView.labelOpacity))
|
||||
|
||||
Picker("Active", selection: boardSelectBinding) {
|
||||
Text("All").tag(-1)
|
||||
ForEach(Array(shoeGaze.boards.enumerated()), id: \.offset) { pair in
|
||||
let label: String = pair.element.label.isEmpty
|
||||
? "Board \(pair.offset + 1)"
|
||||
: pair.element.label
|
||||
Text(label).tag(pair.offset)
|
||||
}
|
||||
}
|
||||
.pickerStyle(.menu)
|
||||
.foregroundStyle(Color.white)
|
||||
|
||||
Spacer()
|
||||
|
||||
Text("Crossfade (s):")
|
||||
.font(.subheadline)
|
||||
.foregroundStyle(Color.white.opacity(ShoeGazeView.labelOpacity))
|
||||
|
||||
TextField(
|
||||
"s",
|
||||
value: $crossfadeSeconds,
|
||||
format: .number.precision(.fractionLength(1))
|
||||
)
|
||||
.frame(width: ShoeGazeView.crossfadeFieldWidth)
|
||||
#if os(macOS)
|
||||
.textFieldStyle(.squareBorder)
|
||||
#endif
|
||||
|
||||
Stepper(
|
||||
"",
|
||||
value: $crossfadeSeconds,
|
||||
in: 0...ShoeGazeView.maxCrossfadeSeconds,
|
||||
step: ShoeGazeView.crossfadeStepIncrement
|
||||
)
|
||||
.labelsHidden()
|
||||
}
|
||||
}
|
||||
|
||||
/// Vertically scrollable list of board strips.
|
||||
///
|
||||
/// Keyed by `\.offset` on an enumerated snapshot; see the doc-comment on
|
||||
/// `ShoeGazeView` for the rationale.
|
||||
private var boardList: some View {
|
||||
ScrollView(.vertical, showsIndicators: true) {
|
||||
VStack(alignment: .leading, spacing: ShoeGazeView.boardSpacing) {
|
||||
ForEach(Array(shoeGaze.boards.enumerated()), id: \.offset) { pair in
|
||||
let board: PedalBoard = pair.element
|
||||
PedalBoardView(board: board) {
|
||||
shoeGaze.removeBoard(board)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Recording
|
||||
|
||||
/// Opens a directory picker so the user can choose the recording destination folder.
|
||||
///
|
||||
/// On macOS an `NSOpenPanel` is presented imperatively (directories only, no file
|
||||
/// selection, no multiple selection). On iOS/non-macOS the `.fileImporter` modifier
|
||||
/// attached to the view hierarchy is toggled via `showFolderImporter`.
|
||||
private func chooseFolderAction() {
|
||||
#if os(macOS)
|
||||
let panel: NSOpenPanel = NSOpenPanel()
|
||||
panel.canChooseDirectories = true
|
||||
panel.canChooseFiles = false
|
||||
panel.allowsMultipleSelection = false
|
||||
panel.canCreateDirectories = true // show the "New Folder" button
|
||||
panel.prompt = "Choose"
|
||||
panel.message = "Select a folder for recording output"
|
||||
// `begin` is non-blocking (unlike `runModal`, which would freeze the SwiftUI
|
||||
// main-thread update loop while the panel is open).
|
||||
panel.begin { response in
|
||||
if response == .OK, let url: URL = panel.url {
|
||||
shoeGaze.recordingFolder = url
|
||||
}
|
||||
}
|
||||
#else
|
||||
showFolderImporter = true
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Board management
|
||||
|
||||
/// Adds a new board with one `OverdrivePedal` as a default pedal so the board
|
||||
/// produces audible output immediately after being finalized. If any step after
|
||||
/// `shoeGaze.addBoard()` throws, the partially-built board is removed via
|
||||
/// `shoeGaze.removeBoard(_:)` before logging, leaving the rig in a consistent state.
|
||||
private func addBoard() {
|
||||
var createdBoard: PedalBoard?
|
||||
do {
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
createdBoard = board
|
||||
try board.add(OverdrivePedal())
|
||||
try shoeGaze.finalizeBoard(board)
|
||||
} catch {
|
||||
if let board: PedalBoard = createdBoard {
|
||||
shoeGaze.removeBoard(board)
|
||||
}
|
||||
print("[ShoeGazeView] addBoard() failed: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
// SplitterView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdUI
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// A compact routing-box view for a ``Splitter`` that exposes a 3-way mode selector
|
||||
/// and two live LED indicators reflecting each branch's current enable value.
|
||||
///
|
||||
/// The segmented `Picker` is driven by a computed `Binding<SplitMode>` whose `get` reads
|
||||
/// `splitter.mode` directly and whose `set` writes back to `splitter.mode`, so the picker
|
||||
/// stays in sync whether the mode is changed via the UI or programmatically.
|
||||
///
|
||||
/// Because `body` already reads `splitter.$branchAEnabled.value` and
|
||||
/// `splitter.$branchBEnabled.value` (both `@Observable`), SwiftUI re-renders the view on
|
||||
/// any external mode change and the binding getter returns the correct value.
|
||||
///
|
||||
/// LED polarity: a branch LED is **lit** (blue/teal) when its `UIParamNode` value is
|
||||
/// ≥ 0.5, and dark when the branch is muted.
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// ```swift
|
||||
/// SplitterView(splitter: section.splitter)
|
||||
/// ```
|
||||
public struct SplitterView: 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 ledRowSpacing: CGFloat = 16
|
||||
private static let titleFontSize: CGFloat = 11
|
||||
private static let titleOpacity: Double = 0.55
|
||||
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
|
||||
/// Threshold above which a UIParamNode enable value is considered "on".
|
||||
private static let enableOnThreshold: Double = 0.5
|
||||
/// 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
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let splitter: Splitter
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a splitter view for the given ``Splitter``.
|
||||
///
|
||||
/// - Parameter splitter: The `Splitter` whose mode and branch enable values will be
|
||||
/// displayed and edited. The picker reads and writes `splitter.mode` directly via
|
||||
/// a computed binding, so external mode changes are always reflected correctly.
|
||||
public init(splitter: Splitter) {
|
||||
self.splitter = splitter
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
// Read branch enable values — because UIParamNode is @Observable, SwiftUI
|
||||
// automatically re-renders this view whenever either value changes on the main thread.
|
||||
// The mode binding getter also reads splitter.mode directly, so the picker stays in
|
||||
// sync with any programmatic mode change.
|
||||
let aValue: Double = splitter.$branchAEnabled.value
|
||||
let bValue: Double = splitter.$branchBEnabled.value
|
||||
let modeBinding: Binding<SplitMode> = Binding(
|
||||
get: { splitter.mode },
|
||||
set: { splitter.mode = $0 }
|
||||
)
|
||||
|
||||
VStack(spacing: SplitterView.sectionSpacing) {
|
||||
Text("SPLIT")
|
||||
.font(.system(size: SplitterView.titleFontSize, weight: .semibold, design: .monospaced))
|
||||
.foregroundStyle(Color.white.opacity(SplitterView.titleOpacity))
|
||||
|
||||
Picker("Mode", selection: modeBinding) {
|
||||
ForEach(SplitMode.allCases, id: \.self) { splitMode in
|
||||
Text(splitMode.rawValue.uppercased())
|
||||
.tag(splitMode)
|
||||
}
|
||||
}
|
||||
.pickerStyle(.segmented)
|
||||
|
||||
branchLEDs(aValue: aValue, bValue: bValue)
|
||||
}
|
||||
.padding(.horizontal, SplitterView.containerPaddingH)
|
||||
.padding(.vertical, SplitterView.containerPaddingV)
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: SplitterView.containerCornerRadius)
|
||||
.fill(Color(
|
||||
red: SplitterView.backgroundRed,
|
||||
green: SplitterView.backgroundGreen,
|
||||
blue: SplitterView.backgroundBlue
|
||||
))
|
||||
.overlay(
|
||||
RoundedRectangle(cornerRadius: SplitterView.containerCornerRadius)
|
||||
.stroke(
|
||||
Color.white.opacity(SplitterView.containerBorderOpacity),
|
||||
lineWidth: SplitterView.containerBorderLineWidth
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Subviews
|
||||
|
||||
/// Pair of LED indicators showing live branch enable state.
|
||||
private func branchLEDs(aValue: Double, bValue: Double) -> some View {
|
||||
HStack(spacing: SplitterView.ledRowSpacing) {
|
||||
branchLED(label: "A", value: aValue)
|
||||
branchLED(label: "B", value: bValue)
|
||||
}
|
||||
}
|
||||
|
||||
/// A single labelled LED dot for one branch.
|
||||
private func branchLED(label: String, value: Double) -> some View {
|
||||
let isOn: Bool = value >= SplitterView.enableOnThreshold
|
||||
|
||||
return VStack(spacing: SplitterView.ledPairSpacing) {
|
||||
Text(label)
|
||||
.font(.system(size: SplitterView.ledLabelFontSize, weight: .medium, design: .monospaced))
|
||||
.foregroundStyle(Color.white.opacity(SplitterView.ledLabelOpacity))
|
||||
ZStack {
|
||||
if isOn {
|
||||
Circle()
|
||||
.fill(Color.cyan.opacity(SplitterView.ledGlowOpacity))
|
||||
.frame(
|
||||
width: SplitterView.ledDiameter + SplitterView.ledGlowRadius,
|
||||
height: SplitterView.ledDiameter + SplitterView.ledGlowRadius
|
||||
)
|
||||
.blur(radius: SplitterView.ledGlowRadius / 2)
|
||||
}
|
||||
Circle()
|
||||
.fill(isOn ? Color.cyan : Color(white: SplitterView.ledDimBrightness))
|
||||
.frame(width: SplitterView.ledDiameter, height: SplitterView.ledDiameter)
|
||||
.overlay(
|
||||
Circle()
|
||||
.stroke(
|
||||
Color.white.opacity(SplitterView.ledRimOpacity),
|
||||
lineWidth: SplitterView.ledRimLineWidth
|
||||
)
|
||||
.frame(width: SplitterView.ledDiameter, height: SplitterView.ledDiameter)
|
||||
)
|
||||
}
|
||||
.frame(
|
||||
width: SplitterView.ledDiameter + SplitterView.ledGlowRadius,
|
||||
height: SplitterView.ledDiameter + SplitterView.ledGlowRadius
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user