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)'."
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user