Compare commits
10 Commits
de4d650378
...
16f837ee10
| Author | SHA1 | Date | |
|---|---|---|---|
| 16f837ee10 | |||
| 0d75108fb1 | |||
| 17f74a4ede | |||
| 077a8ad9f0 | |||
| 7ceb93e411 | |||
| a334a76f7c | |||
| 5af4230038 | |||
| 0f69c27772 | |||
| eafc68d283 | |||
| f0b30379c7 |
@@ -0,0 +1,84 @@
|
||||
// BitReduce.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Shared zero-fill fallback block, allocated once at module load, so the RT path never allocates.
|
||||
private let bitReduceZeroBlock: [Double] = makeSampleBuffer()
|
||||
|
||||
/// Bit-depth reducer: quantises the signal to `2^bits` amplitude levels, producing the gritty
|
||||
/// quantisation noise of the "bit" half of a lo-fi / bitcrusher effect.
|
||||
///
|
||||
/// `bits` is read at control rate (once per block) and clamped to `[1, 16]`. Each sample is
|
||||
/// rounded to the nearest of `2^bits` levels over the `[-1, 1]` range (mid-tread). Output is mono.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Audio-rate signal to quantise.
|
||||
/// - bits: Bit depth — quantises to `2^bits` levels. Control rate; clamped to `[1, 16]`.
|
||||
public final class BitReduce: GeneratorBase, AudioGenerator {
|
||||
|
||||
/// Resolved input signal.
|
||||
let _input: any ValidGeneratorInput
|
||||
|
||||
/// `true` when `_input` resolved to a generator; classified once so the RT path runs no
|
||||
/// `is`/`as?` check.
|
||||
let _inputIsGenerator: Bool
|
||||
|
||||
/// Quantisation bit depth, read at block rate. Pass a control-rate node or scalar.
|
||||
let _bits: any ValidGeneratorInput
|
||||
|
||||
/// Quantisation bounds.
|
||||
private let minimumBits: Double = 1.0
|
||||
private let maximumBits: Double = 16.0
|
||||
|
||||
/// Creates a bit-depth reducer.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to quantise.
|
||||
/// - bits: Bit depth (control rate). Clamped to `[1, 16]`.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
bits: any ValidGeneratorInput
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_inputIsGenerator = resolvedInput is any Generator
|
||||
_bits = bits._resolvedInput()
|
||||
super.init()
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
let bits: Double = min(max(_bits.floatValue(graph: graph), minimumBits), maximumBits)
|
||||
// Number of quantisation levels = 2^bits, via an integer shift (avoids importing `pow`).
|
||||
// Clamp the shift amount directly too: `1 << bitsInt` is only safe while bits ∈ [1, 16].
|
||||
let bitsInt: Int = min(max(Int(bits.rounded()), 1), 16)
|
||||
let levels: Double = Double(1 << bitsInt)
|
||||
// Step between adjacent levels over [-1, 1], and its reciprocal for the round.
|
||||
let step: Double = 2.0 / levels
|
||||
let inverseStep: Double = levels / 2.0
|
||||
|
||||
let inputSamples: [Double] = _inputIsGenerator
|
||||
? (_input.calculatedSamples(graph: graph, count: count).first ?? bitReduceZeroBlock)
|
||||
: bitReduceZeroBlock
|
||||
let inputCount: Int = inputSamples.count
|
||||
let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph)
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = _inputIsGenerator
|
||||
? (i < inputCount ? inputSamples[i] : 0.0)
|
||||
: inputScalar
|
||||
_result[0][i] = (x * inverseStep).rounded() * step
|
||||
}
|
||||
|
||||
return _result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
// ReverseDelay.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Shared zero-fill fallback block, allocated once at module load. Returned when an upstream input
|
||||
/// yields no channel for a `_computeSamples` call, so the RT path never allocates.
|
||||
private let reverseDelayZeroBlock: [Double] = makeSampleBuffer()
|
||||
|
||||
/// Segmented reverse delay: records the input in fixed-length segments and plays each segment back
|
||||
/// **reversed**, so phrases come out backwards.
|
||||
///
|
||||
/// Two segment buffers ping-pong: one records the incoming signal while the other is read back from
|
||||
/// its end to its start. At each segment boundary the buffers swap. A short raised-edge (linear)
|
||||
/// fade at both ends of every reversed segment hides the wrap discontinuity, and an optional
|
||||
/// feedback term recirculates the reversed output into the record buffer for layered reverse trails.
|
||||
///
|
||||
/// `delay` and `feedback` are read at **control rate** (once per block via `floatValue`); a changed
|
||||
/// `delay` takes effect at the next segment boundary, so the segment length never changes mid-read.
|
||||
/// Output is mono (channel 0 of the input is processed).
|
||||
///
|
||||
/// - Important: All buffers are pre-allocated at `init` for `maxDelay` seconds — the RT path never
|
||||
/// allocates or resizes. Keep `delay <= maxDelay`; larger values are clamped.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Audio-rate signal to reverse.
|
||||
/// - maxDelay: Maximum segment length in seconds; sizes the pre-allocated buffers.
|
||||
/// - delay: Segment length in seconds. Control rate; clamped to `[1 frame, maxDelay]`; a change
|
||||
/// applies at the next segment boundary.
|
||||
/// - feedback: Reverse-trail feedback factor. Control rate; clamped to `[0, 0.95]`.
|
||||
/// - sampleRate: Sample rate used to size buffers and convert seconds → frames; match the engine.
|
||||
/// - fadeTime: Edge-fade length in seconds hiding the segment wrap. Defaults to `0.004`.
|
||||
public final class ReverseDelay: GeneratorBase, AudioGenerator {
|
||||
|
||||
// MARK: - Inputs (classified once at init)
|
||||
|
||||
/// Resolved input signal.
|
||||
let _input: any ValidGeneratorInput
|
||||
|
||||
/// `true` when `_input` resolved to a generator; `false` for a scalar constant. Classified once
|
||||
/// so the RT path never runs an `is`/`as?` check.
|
||||
let _inputIsGenerator: Bool
|
||||
|
||||
/// Resolved control inputs. Read at block rate via `floatValue` — pass control-rate nodes
|
||||
/// (`@UIParam` projections) or scalars, not audio-rate generators.
|
||||
let _delay: any ValidGeneratorInput
|
||||
let _feedback: any ValidGeneratorInput
|
||||
|
||||
// MARK: - Buffers + state
|
||||
|
||||
/// The two ping-pong segment buffers, each `_maxFrames` long. One records while the other plays.
|
||||
private var _bufferA: [Double]
|
||||
private var _bufferB: [Double]
|
||||
|
||||
/// Maximum segment length in frames (`maxDelay · sampleRate`).
|
||||
private let _maxFrames: Int
|
||||
|
||||
/// `true` when buffer A is the record buffer (B plays); toggled at each segment boundary.
|
||||
var _recordIsA: Bool = true
|
||||
|
||||
/// Read/write position within the current segment, `0 ..< _segLen`.
|
||||
var _phase: Int = 0
|
||||
|
||||
/// Current segment length in frames.
|
||||
var _segLen: Int
|
||||
|
||||
/// `false` until the first render block adopts the live `delay` as the segment length (the node
|
||||
/// value isn't available at `init`).
|
||||
var _segLenInitialized: Bool = false
|
||||
|
||||
/// Edge-fade length in frames, clamped to half the segment per call.
|
||||
private let _fadeFrames: Int
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Largest stable feedback factor.
|
||||
private let maxFeedback: Double = 0.95
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a reverse delay.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to reverse.
|
||||
/// - maxDelay: Maximum segment length in seconds. Sizes the pre-allocated buffers.
|
||||
/// - delay: Segment length in seconds (control rate). Clamped to `[1 frame, maxDelay]`; a
|
||||
/// change applies at the next segment boundary.
|
||||
/// - feedback: Reverse-trail feedback factor (control rate). Clamped to `[0, 0.95]`. Defaults
|
||||
/// to `0`.
|
||||
/// - sampleRate: Sample rate used to size the buffers and convert seconds → frames.
|
||||
/// - fadeTime: Edge-fade length in seconds, hiding the segment wrap. Defaults to `0.004`.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
maxDelay: Double,
|
||||
delay: any ValidGeneratorInput,
|
||||
feedback: any ValidGeneratorInput = 0.0,
|
||||
sampleRate: Double,
|
||||
fadeTime: Double = 0.004
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_inputIsGenerator = resolvedInput is any Generator
|
||||
_delay = delay._resolvedInput()
|
||||
_feedback = feedback._resolvedInput()
|
||||
|
||||
let frames: Int = max(1, Int((maxDelay * sampleRate).rounded()))
|
||||
_maxFrames = frames
|
||||
_bufferA = [Double](repeating: 0.0, count: frames)
|
||||
_bufferB = [Double](repeating: 0.0, count: frames)
|
||||
_segLen = frames
|
||||
_fadeFrames = max(0, Int((fadeTime * sampleRate).rounded()))
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - Render
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
let sampleRate: Double = graph.engine.sampleRate
|
||||
let delaySeconds: Double = _delay.floatValue(graph: graph)
|
||||
let rawFeedback: Double = _feedback.floatValue(graph: graph)
|
||||
let feedback: Double = min(max(rawFeedback, 0.0), maxFeedback)
|
||||
|
||||
// Target segment length, applied at the next boundary so a read never changes length mid-segment.
|
||||
let targetLen: Int = min(max(Int((delaySeconds * sampleRate).rounded()), 1), _maxFrames)
|
||||
|
||||
let inputSamples: [Double] = _inputIsGenerator
|
||||
? (_input.calculatedSamples(graph: graph, count: count).first ?? reverseDelayZeroBlock)
|
||||
: reverseDelayZeroBlock
|
||||
let inputCount: Int = inputSamples.count
|
||||
let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph)
|
||||
|
||||
var phase: Int = _phase
|
||||
var segLen: Int = _segLen
|
||||
var recordIsA: Bool = _recordIsA
|
||||
let fadeFrames: Int = _fadeFrames
|
||||
|
||||
// Adopt the live delay length on the first block — at `init` the node value isn't known, so
|
||||
// the segment must not start at the full buffer length (that would delay the first reversed
|
||||
// segment by `maxDelay`).
|
||||
if !_segLenInitialized {
|
||||
segLen = targetLen
|
||||
phase = 0
|
||||
_segLenInitialized = true
|
||||
}
|
||||
|
||||
_bufferA.withUnsafeMutableBufferPointer { aBuffer in
|
||||
_bufferB.withUnsafeMutableBufferPointer { bBuffer in
|
||||
// `baseAddress` is non-nil for these always-non-empty buffers (sized `_maxFrames >= 1`
|
||||
// at init), so this guard never fires; it satisfies the optional without an RT trap.
|
||||
guard let aPointer: UnsafeMutablePointer<Double> = aBuffer.baseAddress,
|
||||
let bPointer: UnsafeMutablePointer<Double> = bBuffer.baseAddress else { return }
|
||||
_result[0].withUnsafeMutableBufferPointer { outBuffer in
|
||||
guard let outPointer: UnsafeMutablePointer<Double> = outBuffer.baseAddress else { return }
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = _inputIsGenerator
|
||||
? (i < inputCount ? inputSamples[i] : 0.0)
|
||||
: inputScalar
|
||||
|
||||
let recordPointer: UnsafeMutablePointer<Double> = recordIsA ? aPointer : bPointer
|
||||
let playPointer: UnsafeMutablePointer<Double> = recordIsA ? bPointer : aPointer
|
||||
|
||||
// Reversed read: end of the play segment first.
|
||||
let readIndex: Int = segLen - 1 - phase
|
||||
let raw: Double = playPointer[readIndex]
|
||||
let envelope: Double = ReverseDelay.edgeFade(
|
||||
phase: phase, segLen: segLen, fadeFrames: fadeFrames
|
||||
)
|
||||
let out: Double = raw * envelope
|
||||
|
||||
recordPointer[phase] = x + feedback * out
|
||||
outPointer[i] = out
|
||||
|
||||
phase += 1
|
||||
if phase >= segLen {
|
||||
phase = 0
|
||||
recordIsA.toggle()
|
||||
segLen = targetLen
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_phase = phase
|
||||
_segLen = segLen
|
||||
_recordIsA = recordIsA
|
||||
return _result
|
||||
}
|
||||
|
||||
/// Linear raised-edge fade in `[0, 1]`: ramps up over the first `fadeFrames` of a segment and
|
||||
/// down over the last `fadeFrames`, flat `1` in the middle. De-clicks the reverse wrap.
|
||||
private static func edgeFade(
|
||||
phase: Int,
|
||||
segLen: Int,
|
||||
fadeFrames: Int
|
||||
) -> Double {
|
||||
let fade: Int = min(fadeFrames, segLen / 2)
|
||||
guard fade > 0 else { return 1.0 }
|
||||
let fromStart: Int = phase
|
||||
let fromEnd: Int = segLen - 1 - phase
|
||||
let nearestEdge: Int = min(fromStart, fromEnd)
|
||||
guard nearestEdge < fade else { return 1.0 }
|
||||
return Double(nearestEdge) / Double(fade)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
// SampleRateDecimate.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Shared zero-fill fallback block, allocated once at module load, so the RT path never allocates.
|
||||
private let sampleRateDecimateZeroBlock: [Double] = makeSampleBuffer()
|
||||
|
||||
/// Sample-rate reducer (decimator): a sample-and-hold that latches a new input value only once
|
||||
/// every `downsample` samples, holding it in between. The aliased, stair-stepped result is the
|
||||
/// "crushed sample rate" half of a lo-fi / bitcrusher effect.
|
||||
///
|
||||
/// `downsample` is read at control rate (once per block). `1` passes the signal through; `N` holds
|
||||
/// each sample for `N` output samples (effective rate `sampleRate / N`). Output is mono (channel 0).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Audio-rate signal to decimate.
|
||||
/// - downsample: Hold length in samples — effective rate is `sampleRate / downsample`. Control
|
||||
/// rate; clamped to `>= 1` (`1` is transparent).
|
||||
public final class SampleRateDecimate: GeneratorBase, AudioGenerator {
|
||||
|
||||
/// Resolved input signal.
|
||||
let _input: any ValidGeneratorInput
|
||||
|
||||
/// `true` when `_input` resolved to a generator; classified once so the RT path runs no
|
||||
/// `is`/`as?` check.
|
||||
let _inputIsGenerator: Bool
|
||||
|
||||
/// Downsample factor, read at block rate. Pass a control-rate node or scalar.
|
||||
let _downsample: any ValidGeneratorInput
|
||||
|
||||
/// Samples remaining before the next latch. `0` latches a fresh input on the current sample.
|
||||
var _countdown: Int = 0
|
||||
|
||||
/// Currently held output value.
|
||||
var _held: Double = 0.0
|
||||
|
||||
/// Smallest decimation factor (pass-through).
|
||||
private let minimumFactor: Int = 1
|
||||
|
||||
/// Creates a sample-rate decimator.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to decimate.
|
||||
/// - downsample: Hold length in samples (control rate). Clamped to `>= 1`; `1` is transparent.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
downsample: any ValidGeneratorInput
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_inputIsGenerator = resolvedInput is any Generator
|
||||
_downsample = downsample._resolvedInput()
|
||||
super.init()
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
let factor: Int = max(minimumFactor, Int(_downsample.floatValue(graph: graph).rounded()))
|
||||
|
||||
let inputSamples: [Double] = _inputIsGenerator
|
||||
? (_input.calculatedSamples(graph: graph, count: count).first ?? sampleRateDecimateZeroBlock)
|
||||
: sampleRateDecimateZeroBlock
|
||||
let inputCount: Int = inputSamples.count
|
||||
let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph)
|
||||
|
||||
var countdown: Int = _countdown
|
||||
var held: Double = _held
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = _inputIsGenerator
|
||||
? (i < inputCount ? inputSamples[i] : 0.0)
|
||||
: inputScalar
|
||||
if countdown <= 0 {
|
||||
held = x
|
||||
countdown = factor
|
||||
}
|
||||
countdown -= 1
|
||||
_result[0][i] = held
|
||||
}
|
||||
|
||||
_countdown = countdown
|
||||
_held = held
|
||||
return _result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
// ShimmerReverb.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Shared zero-fill fallback block, allocated once at module load, so the RT path never allocates.
|
||||
private let shimmerReverbZeroBlock: [Double] = makeSampleBuffer()
|
||||
|
||||
/// Regenerative shimmer reverb: a damped feedback tank with an octave-up grain reader **inside**
|
||||
/// the feedback path, so the pitched-up tail recirculates and the shimmer builds and sustains
|
||||
/// (rather than the one-shot parallel pitch-into-reverb approximation).
|
||||
///
|
||||
/// Signal path per sample:
|
||||
/// ```
|
||||
/// input → 2 series Schroeder allpasses (diffusion) ─┐
|
||||
/// ▼
|
||||
/// tank delay (size) → damping one-pole → ┬─────────→ output (wet tail)
|
||||
/// │
|
||||
/// octave-up grains read from the tank ───┤ (× shimmer)
|
||||
/// ▼
|
||||
/// feedback = decay·damped + shimmer·pitched → written back into the tank
|
||||
/// ```
|
||||
///
|
||||
/// The octave-up is a two-grain, 50%-overlap, Hann-windowed reader running at 2× over the tank
|
||||
/// buffer (a tape-style pitch raise). A per-sample safety clamp + denormal flush keep the loop
|
||||
/// bounded even at high `decay` / `shimmer`.
|
||||
///
|
||||
/// `size`, `decay`, `shimmer`, and `damp` are read at control rate (once per block). Output is mono.
|
||||
///
|
||||
/// - Important: All buffers are pre-allocated at `init` for `maxDelay` seconds plus the grain
|
||||
/// length — the RT path never allocates or resizes.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Audio-rate signal to reverberate.
|
||||
/// - maxDelay: Maximum tank delay in seconds; sizes the pre-allocated buffer.
|
||||
/// - size: Tank delay in seconds. Control rate; clamped to `[0.005, maxDelay]`.
|
||||
/// - decay: Feedback gain (tail length). Control rate; clamped to `[0, 0.92]`.
|
||||
/// - shimmer: Octave-up feedback amount. Control rate; clamped to `[0, 0.85]`.
|
||||
/// - damp: High-frequency damping in the feedback `[0, 1]` (0 = bright, 1 = dark). Control rate.
|
||||
/// - sampleRate: Sample rate used to size buffers and convert seconds → frames; match the engine.
|
||||
public final class ShimmerReverb: GeneratorBase, AudioGenerator {
|
||||
|
||||
// MARK: - Inputs
|
||||
|
||||
let _input: any ValidGeneratorInput
|
||||
let _inputIsGenerator: Bool
|
||||
let _size: any ValidGeneratorInput
|
||||
let _decay: any ValidGeneratorInput
|
||||
let _shimmer: any ValidGeneratorInput
|
||||
let _damp: any ValidGeneratorInput
|
||||
|
||||
// MARK: - Buffers + state
|
||||
|
||||
/// Tank delay/grain buffer (circular), length `_bufLen`.
|
||||
private var _tank: [Double]
|
||||
/// Two Schroeder input-diffusion allpass buffers.
|
||||
private var _allpassA: [Double]
|
||||
private var _allpassB: [Double]
|
||||
/// Precomputed Hann window over one grain, length `_grainFrames`.
|
||||
private var _hann: [Double]
|
||||
|
||||
private let _bufLen: Int
|
||||
private let _grainFrames: Int
|
||||
private let _maxDelayFrames: Int
|
||||
private let _allpassALen: Int
|
||||
private let _allpassBLen: Int
|
||||
|
||||
private var _writePos: Int = 0
|
||||
private var _allpassAPos: Int = 0
|
||||
private var _allpassBPos: Int = 0
|
||||
private var _grainCounter: Int = 0
|
||||
private var _dampState: Double = 0.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private let minSizeSeconds: Double = 0.005
|
||||
private let maxDecay: Double = 0.92
|
||||
private let maxShimmer: Double = 0.85
|
||||
private let grainSeconds: Double = 0.05
|
||||
/// Schroeder allpass coefficient and (prime-ish) lengths in samples for input diffusion.
|
||||
private let allpassGain: Double = 0.7
|
||||
private let allpassAFrames: Int = 142
|
||||
private let allpassBFrames: Int = 107
|
||||
/// Hard safety bound on the recirculated value — prevents runaway / NaN at extreme settings.
|
||||
private let safetyClamp: Double = 8.0
|
||||
/// Below this magnitude feedback state is flushed to zero (denormal guard).
|
||||
private let denormalFloor: Double = 1.0e-15
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a shimmer reverb.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Audio-rate signal to reverberate.
|
||||
/// - maxDelay: Maximum tank delay in seconds; sizes the pre-allocated buffer.
|
||||
/// - size: Tank delay in seconds. Control rate; clamped to `[0.005, maxDelay]`.
|
||||
/// - decay: Feedback gain (tail length). Control rate; clamped to `[0, 0.92]`.
|
||||
/// - shimmer: Octave-up feedback amount. Control rate; clamped to `[0, 0.85]`.
|
||||
/// - damp: High-frequency damping in the feedback `[0, 1]` (0 = bright, 1 = dark). Control rate.
|
||||
/// - sampleRate: Sample rate used to size buffers and convert seconds → frames; match the engine.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
maxDelay: Double,
|
||||
size: any ValidGeneratorInput,
|
||||
decay: any ValidGeneratorInput,
|
||||
shimmer: any ValidGeneratorInput,
|
||||
damp: any ValidGeneratorInput,
|
||||
sampleRate: Double
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_inputIsGenerator = resolvedInput is any Generator
|
||||
_size = size._resolvedInput()
|
||||
_decay = decay._resolvedInput()
|
||||
_shimmer = shimmer._resolvedInput()
|
||||
_damp = damp._resolvedInput()
|
||||
|
||||
let maxFrames: Int = max(1, Int((maxDelay * sampleRate).rounded()))
|
||||
let grain: Int = max(2, Int((grainSeconds * sampleRate).rounded()))
|
||||
_maxDelayFrames = maxFrames
|
||||
_grainFrames = grain
|
||||
// Buffer holds the deepest tank read plus a full grain look-back, with headroom.
|
||||
_bufLen = maxFrames + grain + 2
|
||||
_allpassALen = allpassAFrames
|
||||
_allpassBLen = allpassBFrames
|
||||
|
||||
_tank = [Double](repeating: 0.0, count: _bufLen)
|
||||
_allpassA = [Double](repeating: 0.0, count: allpassAFrames)
|
||||
_allpassB = [Double](repeating: 0.0, count: allpassBFrames)
|
||||
|
||||
// Precompute the Hann window for the grain (off the RT thread).
|
||||
var hann: [Double] = [Double](repeating: 0.0, count: grain)
|
||||
let twoPi: Double = 2.0 * Double.pi
|
||||
for i: Int in 0..<grain {
|
||||
hann[i] = 0.5 - 0.5 * cos(twoPi * Double(i) / Double(grain))
|
||||
}
|
||||
_hann = hann
|
||||
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - Render
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
let sampleRate: Double = graph.engine.sampleRate
|
||||
let sizeSeconds: Double = _size.floatValue(graph: graph)
|
||||
let decay: Double = min(max(_decay.floatValue(graph: graph), 0.0), maxDecay)
|
||||
let shimmer: Double = min(max(_shimmer.floatValue(graph: graph), 0.0), maxShimmer)
|
||||
let damp: Double = min(max(_damp.floatValue(graph: graph), 0.0), 1.0)
|
||||
|
||||
let minFrames: Int = max(1, Int((minSizeSeconds * sampleRate).rounded()))
|
||||
let sizeFrames: Int = min(max(Int((sizeSeconds * sampleRate).rounded()), minFrames), _maxDelayFrames)
|
||||
let halfGrain: Int = _grainFrames / 2
|
||||
|
||||
let inputSamples: [Double] = _inputIsGenerator
|
||||
? (_input.calculatedSamples(graph: graph, count: count).first ?? shimmerReverbZeroBlock)
|
||||
: shimmerReverbZeroBlock
|
||||
let inputCount: Int = inputSamples.count
|
||||
let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph)
|
||||
|
||||
var writePos: Int = _writePos
|
||||
var grainCounter: Int = _grainCounter
|
||||
var dampState: Double = _dampState
|
||||
var allpassAPos: Int = _allpassAPos
|
||||
var allpassBPos: Int = _allpassBPos
|
||||
|
||||
_tank.withUnsafeMutableBufferPointer { tankBuffer in
|
||||
_allpassA.withUnsafeMutableBufferPointer { apABuffer in
|
||||
_allpassB.withUnsafeMutableBufferPointer { apBBuffer in
|
||||
_hann.withUnsafeBufferPointer { hannBuffer in
|
||||
_result[0].withUnsafeMutableBufferPointer { outBuffer in
|
||||
guard let tank: UnsafeMutablePointer<Double> = tankBuffer.baseAddress,
|
||||
let apA: UnsafeMutablePointer<Double> = apABuffer.baseAddress,
|
||||
let apB: UnsafeMutablePointer<Double> = apBBuffer.baseAddress,
|
||||
let hann: UnsafePointer<Double> = hannBuffer.baseAddress,
|
||||
let out: UnsafeMutablePointer<Double> = outBuffer.baseAddress
|
||||
else { return }
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = _inputIsGenerator
|
||||
? (i < inputCount ? inputSamples[i] : 0.0)
|
||||
: inputScalar
|
||||
|
||||
// Input diffusion: two series Schroeder allpasses.
|
||||
let diffused: Double = ShimmerReverb.allpass(
|
||||
ShimmerReverb.allpass(x, apA, &allpassAPos, _allpassALen, allpassGain),
|
||||
apB, &allpassBPos, _allpassBLen, allpassGain
|
||||
)
|
||||
|
||||
// Delayed tank read → one-pole damping (HF absorption).
|
||||
let readTail: Double = tank[ShimmerReverb.wrap(writePos - sizeFrames, _bufLen)]
|
||||
dampState = dampState + (1.0 - damp) * (readTail - dampState)
|
||||
let damped: Double = dampState
|
||||
|
||||
// Octave-up: two 50%-overlapped Hann grains read at 2× over the tank.
|
||||
let offsetA: Int = _grainFrames - grainCounter
|
||||
let phaseB: Int = (grainCounter + halfGrain) % _grainFrames
|
||||
let offsetB: Int = _grainFrames - phaseB
|
||||
let pitched: Double =
|
||||
hann[grainCounter] * tank[ShimmerReverb.wrap(writePos - offsetA, _bufLen)]
|
||||
+ hann[phaseB] * tank[ShimmerReverb.wrap(writePos - offsetB, _bufLen)]
|
||||
|
||||
// Feedback: decayed damped tail + pitched shimmer, plus diffused input.
|
||||
var writeVal: Double = diffused + decay * damped + shimmer * pitched
|
||||
if writeVal > safetyClamp { writeVal = safetyClamp }
|
||||
else if writeVal < -safetyClamp { writeVal = -safetyClamp }
|
||||
tank[writePos] = writeVal
|
||||
|
||||
out[i] = damped
|
||||
|
||||
writePos += 1
|
||||
if writePos >= _bufLen { writePos = 0 }
|
||||
grainCounter += 1
|
||||
if grainCounter >= _grainFrames { grainCounter = 0 }
|
||||
}
|
||||
if abs(dampState) < denormalFloor { dampState = 0.0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_writePos = writePos
|
||||
_grainCounter = grainCounter
|
||||
_dampState = dampState
|
||||
_allpassAPos = allpassAPos
|
||||
_allpassBPos = allpassBPos
|
||||
return _result
|
||||
}
|
||||
|
||||
/// One Schroeder allpass step over a circular buffer; advances `pos`. `y = -g·x + d;
|
||||
/// buf = x + g·y` where `d` is the delayed sample.
|
||||
private static func allpass(
|
||||
_ x: Double,
|
||||
_ buffer: UnsafeMutablePointer<Double>,
|
||||
_ pos: inout Int,
|
||||
_ length: Int,
|
||||
_ gain: Double
|
||||
) -> Double {
|
||||
let delayed: Double = buffer[pos]
|
||||
let y: Double = -gain * x + delayed
|
||||
buffer[pos] = x + gain * y
|
||||
pos += 1
|
||||
if pos >= length { pos = 0 }
|
||||
return y
|
||||
}
|
||||
|
||||
/// Wraps `index` into `[0, length)` (handles a single negative wrap, as produced by
|
||||
/// `writePos - offset` with `offset <= length`).
|
||||
private static func wrap(_ index: Int, _ length: Int) -> Int {
|
||||
let m: Int = index % length
|
||||
return m < 0 ? m + length : m
|
||||
}
|
||||
}
|
||||
@@ -168,6 +168,15 @@ open class Pedal: SynthesizerBase {
|
||||
[]
|
||||
}
|
||||
|
||||
/// Effect-specific stepped "knob picker" controls for this pedal, rendered as a row of rotary
|
||||
/// knobs that snap to labelled stops, beneath the knob grid.
|
||||
///
|
||||
/// Override in subclasses to publish each discrete `@UIParam` parameter that reads best as a
|
||||
/// knob that snaps through fixed positions (e.g. a harmony interval selector). Defaults to empty.
|
||||
open var effectSelectors: [PedalSelectorKnob] {
|
||||
[]
|
||||
}
|
||||
|
||||
/// 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.
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
// PedalSelectorKnob.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdUI
|
||||
|
||||
/// A UI-agnostic description of a knob that snaps to a fixed set of labelled stops.
|
||||
///
|
||||
/// Where ``PedalKnob`` is a continuous rotary and ``PedalSwitch`` is a segmented strip, a
|
||||
/// `PedalSelectorKnob` reads like a rotary knob but quantises to discrete positions — a knob picker.
|
||||
/// Dragging rotates through the stops; the knob shows the current stop's caption. A `Pedal`
|
||||
/// publishes an array of these via ``Pedal/effectSelectors`` so a generic pedalboard UI can render
|
||||
/// a stepped knob per discrete parameter without knowing the concrete type.
|
||||
///
|
||||
/// Each stop pairs a short caption with the exact `Double` written to the live ``UIParamNode`` when
|
||||
/// that position is selected; the lit position is the stop whose `value` is nearest the node's
|
||||
/// current value.
|
||||
public struct PedalSelectorKnob {
|
||||
|
||||
/// One labelled position of a ``PedalSelectorKnob``.
|
||||
public struct Stop {
|
||||
|
||||
/// Short caption shown under the knob when this position is selected (e.g. "M3", "Oct").
|
||||
public let title: String
|
||||
|
||||
/// Value written to the node when this position is selected.
|
||||
public let value: Double
|
||||
|
||||
/// Creates a selector stop.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - title: Short caption shown when this position is selected.
|
||||
/// - value: Value written to the node when this position is selected.
|
||||
public init(title: String, value: Double) {
|
||||
self.title = title
|
||||
self.value = value
|
||||
}
|
||||
}
|
||||
|
||||
/// Short label shown beneath the knob (e.g. "Voice 1").
|
||||
public let label: String
|
||||
|
||||
/// The live parameter node the knob reads and writes. Pass `pedal.$paramName`.
|
||||
public let node: UIParamNode
|
||||
|
||||
/// Ordered stops the knob snaps through, from fully counter-clockwise to fully clockwise. Must
|
||||
/// contain at least two.
|
||||
public let stops: [Stop]
|
||||
|
||||
/// Creates a selector-knob descriptor.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - label: Short label shown beneath the knob.
|
||||
/// - node: The `UIParamNode` projected value of an `@UIParam` property (`pedal.$voice1`, …).
|
||||
/// - stops: Ordered stops, CCW → CW. At least two.
|
||||
public init(
|
||||
label: String,
|
||||
node: UIParamNode,
|
||||
stops: [Stop]
|
||||
) {
|
||||
precondition(stops.count >= 2, "PedalSelectorKnob requires at least two stops")
|
||||
self.label = label
|
||||
self.node = node
|
||||
self.stops = stops
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,7 @@ public extension PedalType {
|
||||
|
||||
// Drive & dynamics
|
||||
static let overdrive = PedalType("Overdrive")
|
||||
static let distortion = PedalType("Distortion")
|
||||
static let fuzz = PedalType("Fuzz")
|
||||
static let compressor = PedalType("Compressor")
|
||||
static let limiter = PedalType("Limiter")
|
||||
@@ -60,8 +61,12 @@ public extension PedalType {
|
||||
static let tremolo = PedalType("Tremolo")
|
||||
static let modulation = PedalType("Modulation")
|
||||
static let chorus = PedalType("Chorus")
|
||||
static let flanger = PedalType("Flanger")
|
||||
static let vibrato = PedalType("Vibrato")
|
||||
static let rotary = PedalType("Rotary")
|
||||
static let ringModulator = PedalType("Ring Modulator")
|
||||
static let diffuser = PedalType("Diffuser")
|
||||
static let bitcrusher = PedalType("Bitcrusher")
|
||||
|
||||
// Dynamics (additional)
|
||||
static let sustainer = PedalType("Sustainer")
|
||||
@@ -71,9 +76,12 @@ public extension PedalType {
|
||||
static let feedbackDelay = PedalType("Feedback Delay")
|
||||
static let multiTapDelay = PedalType("Multi-Tap Delay")
|
||||
static let pingPong = PedalType("Ping-Pong")
|
||||
static let reverseDelay = PedalType("Reverse Delay")
|
||||
static let reverb = PedalType("Reverb")
|
||||
static let shimmerReverb = PedalType("Shimmer Reverb")
|
||||
|
||||
// Pitch & octave
|
||||
static let octaveSplitter = PedalType("Octave Splitter")
|
||||
static let bassOctaver = PedalType("Bass Octaver")
|
||||
static let harmonizer = PedalType("Harmonizer")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
// BitcrusherPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Lo-fi bitcrusher: sample-rate decimation followed by bit-depth reduction.
|
||||
///
|
||||
/// A sample-and-hold drops the effective sample rate (aliasing, stair-stepping); a quantiser then
|
||||
/// reduces the bit depth (gritty quantisation noise). A post `Tone` low-pass tames the harsh
|
||||
/// aliasing for a more usable lo-fi voice. Wraps the ``SampleRateDecimate`` and ``BitReduce``
|
||||
/// generators, run fully wet so the pedal's `Mix` knob sets the blend.
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `crush`: Sample-rate decimation factor (hold length in samples). Range `[1, 50]`.
|
||||
/// - `bits`: Bit depth. Range `[1, 16]`.
|
||||
/// - `tone`: Post low-pass cutoff in Hz. Range `[800, 8000]`.
|
||||
public final class BitcrusherPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
public override var summary: String {
|
||||
"Lo-fi crusher: drops the sample rate and bit depth for gritty digital grunge."
|
||||
}
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Sample-rate decimation factor (hold length in samples). Range [1, 50].
|
||||
@UIParam public var crush: Double = 8.0
|
||||
|
||||
/// Bit depth. Range [1, 16].
|
||||
@UIParam public var bits: Double = 8.0
|
||||
|
||||
/// Post low-pass cutoff in Hz. Range [800, 8000].
|
||||
@UIParam public var tone: Double = 4000.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Bitcrusher is heard fully wet; the `Mix` knob can dial it back.
|
||||
private static let defaultMix: Double = 1.0
|
||||
|
||||
/// Butterworth Q (no resonant peak) for the tone low-pass.
|
||||
private let filterQ: Double = 0.707
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let crushRange: ClosedRange<Double> = 1.0 ... 50.0
|
||||
private let bitsRange: ClosedRange<Double> = 1.0 ... 16.0
|
||||
private let toneRange: ClosedRange<Double> = 800.0 ... 8000.0
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Crush", node: $crush, range: crushRange),
|
||||
PedalKnob(label: "Bits", node: $bits, range: bitsRange),
|
||||
PedalKnob(label: "Tone", node: $tone, range: toneRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a bitcrusher 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: "Bitcrusher",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: BitcrusherPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
let decimated: SampleRateDecimate = SampleRateDecimate(input: dry, downsample: $crush)
|
||||
let crushed: BitReduce = BitReduce(input: decimated, bits: $bits)
|
||||
return RBJLowPass.Audio(input: crushed, freq: $tone, q: filterQ)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// DistortionPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Mid-gain distortion — more saturated than `OverdrivePedal`, more controlled than `FuzzPedal`.
|
||||
///
|
||||
/// A DC-blocking high-pass feeds a `tanh` soft-clipper driven hard by the `Drive` knob; a
|
||||
/// post-clip low-pass `Tone` control tames the harmonics, and a final hard clip guarantees the
|
||||
/// output stays bounded.
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `drive`: Pre-clip gain into the `tanh` stage. Range `[1, 50]`.
|
||||
/// - `tone`: Post-clip low-pass cutoff in Hz. Range `[500, 6000]`.
|
||||
public final class DistortionPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
public override var summary: String {
|
||||
"Mid-gain saturated distortion sitting between overdrive and fuzz."
|
||||
}
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Pre-clip gain into the `tanh` stage. Range [1, 50].
|
||||
@UIParam public var drive: Double = 12.0
|
||||
|
||||
/// Post-clip low-pass cutoff in Hz. Range [500, 6000].
|
||||
@UIParam public var tone: Double = 3000.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Distortion is heard fully wet; the `Level` knob sets output gain.
|
||||
private static let defaultMix: Double = 1.0
|
||||
|
||||
/// DC-blocking high-pass cutoff in Hz, applied before the clipper.
|
||||
private let dcBlockFreq: Double = 80.0
|
||||
|
||||
/// Butterworth Q (no resonant peak) for the conditioning filters.
|
||||
private let filterQ: Double = 0.707
|
||||
|
||||
/// Output hard-clip bounds — guarantees a bounded signal after tone shaping.
|
||||
private let clipLow: Double = -1.0
|
||||
private let clipHigh: Double = 1.0
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let driveRange: ClosedRange<Double> = 1.0 ... 50.0
|
||||
private let toneRange: ClosedRange<Double> = 500.0 ... 6000.0
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Drive", node: $drive, range: driveRange),
|
||||
PedalKnob(label: "Tone", node: $tone, range: toneRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a distortion 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: "Distortion",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: DistortionPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
let dcBlocked: RBJHighPass.Audio = RBJHighPass.Audio(
|
||||
input: dry,
|
||||
freq: dcBlockFreq,
|
||||
q: filterQ
|
||||
)
|
||||
let driven: Tanh.Audio = Tanh.Audio(dcBlocked, mul: $drive)
|
||||
let toned: RBJLowPass.Audio = RBJLowPass.Audio(
|
||||
input: driven,
|
||||
freq: $tone,
|
||||
q: filterQ
|
||||
)
|
||||
return Clip.Audio(toned, lo: clipLow, hi: clipHigh)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// FlangerPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Classic jet-flanger.
|
||||
///
|
||||
/// A short LFO-swept delay summed with the dry signal produces the sweeping comb-filter notches;
|
||||
/// feedback sharpens them into the metallic "jet" whoosh. Wraps Lyrebird's `Flanger` generator,
|
||||
/// run fully wet so the pedal's own `Mix` knob sets the wet/dry blend.
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `rate`: LFO sweep rate in Hz. Range `[0.05, 8]`.
|
||||
/// - `depth`: Sweep depth as a fraction of the center delay. Range `[0, 1]`.
|
||||
/// - `feedback`: Comb feedback (resonance). Range `[0, 0.95]`.
|
||||
public final class FlangerPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
public override var summary: String {
|
||||
"Sweeping comb-filter jet flanger, with feedback for that metallic whoosh."
|
||||
}
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// LFO sweep rate in Hz. Range [0.05, 8].
|
||||
@UIParam public var rate: Double = 0.4
|
||||
|
||||
/// Sweep depth as a fraction of the center delay. Range [0, 1].
|
||||
@UIParam public var depth: Double = 0.6
|
||||
|
||||
/// Comb feedback (resonance). Range [0, 0.95].
|
||||
@UIParam public var feedback: Double = 0.3
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Default wet/dry blend — flanger sits under the dry signal.
|
||||
private static let defaultMix: Double = 0.5
|
||||
|
||||
/// Center delay the LFO sweeps around, in seconds.
|
||||
private let centerDelayTime: Double = 0.005
|
||||
|
||||
/// Maximum delay the line is allocated for, in seconds. Covers `centerDelayTime · (1 + maxDepth)`.
|
||||
private let maxDelayTime: Double = 0.05
|
||||
|
||||
/// The wrapped generator runs fully wet; the `Pedal` base `Mix` knob does the blend.
|
||||
private let fullyWetMix: Double = 1.0
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let rateRange: ClosedRange<Double> = 0.05 ... 8.0
|
||||
private let depthRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||
private let feedbackRange: ClosedRange<Double> = 0.0 ... 0.95
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Rate", node: $rate, range: rateRange),
|
||||
PedalKnob(label: "Depth", node: $depth, range: depthRange),
|
||||
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a flanger 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: "Flanger",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: FlangerPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
Flanger.Audio(
|
||||
input: dry,
|
||||
delayTime: centerDelayTime,
|
||||
depth: $depth,
|
||||
rate: $rate,
|
||||
feedback: $feedback,
|
||||
mix: fullyWetMix,
|
||||
sampleRate: sampleRate,
|
||||
maxDelayTime: maxDelayTime
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
// HarmonizerPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Two-voice diatonic-interval harmonizer.
|
||||
///
|
||||
/// Adds two pitch-shifted harmony voices at fixed musical intervals above or below the input,
|
||||
/// mixed against the dry signal — an OC-2-style level layout (Voice 1 / Voice 2 / Direct) with a
|
||||
/// knob picker selecting each voice's interval.
|
||||
///
|
||||
/// Each voice is a granular `PitchShift` whose ratio is `2^(semitones/12)`, driven live from the
|
||||
/// voice's interval selector. Intervals include minor and major thirds above and below, plus
|
||||
/// fourths, fifths, and octaves.
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `voice1Level`: Voice 1 level in `[0, 1]`.
|
||||
/// - `voice2Level`: Voice 2 level in `[0, 1]`.
|
||||
/// - `direct`: Dry signal level in `[0, 1]`.
|
||||
///
|
||||
/// ## Selectors (knob pickers)
|
||||
/// - `voice1`: Voice 1 interval in semitones (snaps to musical intervals).
|
||||
/// - `voice2`: Voice 2 interval in semitones.
|
||||
public final class HarmonizerPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
public override var summary: String {
|
||||
"Two pitch-shifted harmony voices at intervals you pick, stacked under your note."
|
||||
}
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Voice 1 interval in semitones. Snaps to musical-interval stops.
|
||||
@UIParam public var voice1: Double = 4.0
|
||||
|
||||
/// Voice 2 interval in semitones. Snaps to musical-interval stops.
|
||||
@UIParam public var voice2: Double = 7.0
|
||||
|
||||
/// Voice 1 level in `[0, 1]`.
|
||||
@UIParam public var voice1Level: Double = 0.6
|
||||
|
||||
/// Voice 2 level in `[0, 1]`.
|
||||
@UIParam public var voice2Level: Double = 0.45
|
||||
|
||||
/// Dry (direct) signal level in `[0, 1]`.
|
||||
@UIParam public var direct: Double = 1.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Pedal blends internally via the level knobs, so the base wet/dry stays fully wet.
|
||||
private static let defaultMix: Double = 1.0
|
||||
|
||||
/// `semitones → ratio` exponent scale: `2^(s/12) = e^(s · ln2/12)`, fed to `Exp.Audio`.
|
||||
private let semitoneToRatioScale: Double = 0.05776226504666215 // ln(2) / 12
|
||||
|
||||
/// Granular pitch-shift window in seconds. Larger = smoother but more latency.
|
||||
private let windowSize: Double = 0.1
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let levelRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "V1 Level", node: $voice1Level, range: levelRange),
|
||||
PedalKnob(label: "V2 Level", node: $voice2Level, range: levelRange),
|
||||
PedalKnob(label: "Direct", node: $direct, range: levelRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Selectors
|
||||
|
||||
/// Musical-interval stops for the voice pickers, low to high. Values are semitones; captions are
|
||||
/// short interval names (`m3`/`M3` = minor/major third, `4`/`5` = perfect fourth/fifth,
|
||||
/// `8ve` = octave, `Uni` = unison). Minus = below the input.
|
||||
private static let intervalStops: [PedalSelectorKnob.Stop] = [
|
||||
PedalSelectorKnob.Stop(title: "-8ve", value: -12.0),
|
||||
PedalSelectorKnob.Stop(title: "-M6", value: -9.0),
|
||||
PedalSelectorKnob.Stop(title: "-m6", value: -8.0),
|
||||
PedalSelectorKnob.Stop(title: "-5", value: -7.0),
|
||||
PedalSelectorKnob.Stop(title: "-4", value: -5.0),
|
||||
PedalSelectorKnob.Stop(title: "-M3", value: -4.0),
|
||||
PedalSelectorKnob.Stop(title: "-m3", value: -3.0),
|
||||
PedalSelectorKnob.Stop(title: "Uni", value: 0.0),
|
||||
PedalSelectorKnob.Stop(title: "m3", value: 3.0),
|
||||
PedalSelectorKnob.Stop(title: "M3", value: 4.0),
|
||||
PedalSelectorKnob.Stop(title: "4", value: 5.0),
|
||||
PedalSelectorKnob.Stop(title: "5", value: 7.0),
|
||||
PedalSelectorKnob.Stop(title: "m6", value: 8.0),
|
||||
PedalSelectorKnob.Stop(title: "M6", value: 9.0),
|
||||
PedalSelectorKnob.Stop(title: "8ve", value: 12.0),
|
||||
]
|
||||
|
||||
public override var effectSelectors: [PedalSelectorKnob] {
|
||||
[
|
||||
PedalSelectorKnob(label: "Voice 1", node: $voice1, stops: HarmonizerPedal.intervalStops),
|
||||
PedalSelectorKnob(label: "Voice 2", node: $voice2, stops: HarmonizerPedal.intervalStops),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a harmonizer pedal.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||
/// - outputBus: Audio bus index to write the output to. Defaults to `0`.
|
||||
public init(
|
||||
inputBus: Int = 0,
|
||||
outputBus: Int = 0
|
||||
) {
|
||||
super.init(
|
||||
name: "Harmonizer",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: HarmonizerPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
let voice1Signal: any ValidGeneratorInput = harmonyVoice(dry, semitones: $voice1)
|
||||
let voice2Signal: any ValidGeneratorInput = harmonyVoice(dry, semitones: $voice2)
|
||||
|
||||
let directVoice: any ValidGeneratorInput = dry * $direct
|
||||
let harmony1: any ValidGeneratorInput = voice1Signal * $voice1Level
|
||||
let harmony2: any ValidGeneratorInput = voice2Signal * $voice2Level
|
||||
return directVoice + harmony1 + harmony2
|
||||
}
|
||||
|
||||
/// One pitch-shifted voice: ratio `2^(semitones/12)` via `Exp`, fed to a granular `PitchShift`.
|
||||
private func harmonyVoice(
|
||||
_ dry: any ValidGeneratorInput,
|
||||
semitones: any ValidGeneratorInput
|
||||
) -> any ValidGeneratorInput {
|
||||
let ratio: Exp.Audio = Exp.Audio(semitones * semitoneToRatioScale)
|
||||
return PitchShift.Audio(input: dry, pitchRatio: ratio, windowSize: windowSize)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// ReverseDelayPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Reverse delay.
|
||||
///
|
||||
/// Records the input in fixed-length segments and plays each one back reversed, so notes and
|
||||
/// phrases swell in backwards — the classic backwards-tape effect. `Feedback` recirculates the
|
||||
/// reversed output for layered backward trails. Wraps the ``ReverseDelay`` generator, run fully wet
|
||||
/// so the pedal's `Mix` knob sets the wet/dry blend.
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `time`: Reverse segment length in seconds. Range `[0.05, 2.0]`.
|
||||
/// - `feedback`: Reverse-trail feedback. Range `[0, 0.95]`.
|
||||
public final class ReverseDelayPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
public override var summary: String {
|
||||
"Plays your phrases back in reverse — the backwards-tape swell, with feedback trails."
|
||||
}
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Reverse segment length in seconds. Range [0.05, 2.0].
|
||||
@UIParam public var time: Double = 0.5
|
||||
|
||||
/// Reverse-trail feedback. Range [0, 0.95].
|
||||
@UIParam public var feedback: Double = 0.3
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Default wet/dry blend — reverse delay sits under the dry signal.
|
||||
private static let defaultMix: Double = 0.5
|
||||
|
||||
/// Maximum segment length the buffers are allocated for, in seconds.
|
||||
private let maxDelayTime: Double = 2.0
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let timeRange: ClosedRange<Double> = 0.05 ... 2.0
|
||||
private let feedbackRange: ClosedRange<Double> = 0.0 ... 0.95
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Time", node: $time, range: timeRange),
|
||||
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a reverse-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: "Reverse Delay",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: ReverseDelayPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
ReverseDelay(
|
||||
input: dry,
|
||||
maxDelay: maxDelayTime,
|
||||
delay: $time,
|
||||
feedback: $feedback,
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
// RotaryPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Rotary-speaker (Leslie) emulation.
|
||||
///
|
||||
/// A spinning speaker produces correlated amplitude modulation (volume throb) and frequency
|
||||
/// modulation (Doppler pitch wobble). This pedal builds both from one rotor LFO per channel, with
|
||||
/// the left and right rotors in anti-phase so the image rotates across the stereo field. A two-speed
|
||||
/// switch (Chorale / Tremolo) selects the rotor speed, and the **Accel** knob sets how quickly the
|
||||
/// rotor ramps between speeds — the authentic spin-up / spin-down glide — via a `Lag` on the rate.
|
||||
///
|
||||
/// Signal path (per channel, inside `wideEffect(_:)`):
|
||||
/// ```
|
||||
/// dry → DelayLine(delay: base ± fm·sin(rate)) → × (1 ± am·sin(rate)) → wet
|
||||
/// ```
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `depth`: Rotor intensity — scales both the AM throb and the FM Doppler. Range `[0, 1]`.
|
||||
/// - `accel`: Spin-up / spin-down ramp time in seconds. Range `[0.05, 3]`.
|
||||
///
|
||||
/// ## Switches
|
||||
/// - `speed` (two-state): `0` = Chorale (slow), `1` = Tremolo (fast).
|
||||
public final class RotaryPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
public override var summary: String {
|
||||
"Spinning Leslie rotor: Doppler pitch wobble plus volume throb, two-speed with ramp."
|
||||
}
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Rotor intensity — scales both AM and FM. Range [0, 1].
|
||||
@UIParam public var depth: Double = 0.7
|
||||
|
||||
/// Spin-up / spin-down ramp time in seconds. Range [0.05, 3].
|
||||
@UIParam public var accel: Double = 0.5
|
||||
|
||||
/// Rotor speed selector. `0` = Chorale (slow), `1` = Tremolo (fast). Driven by a two-state switch.
|
||||
@UIParam public var speed: Double = 0.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Rotary is heard fully wet; the `Mix` knob can dial it back if desired.
|
||||
private static let defaultMix: Double = 1.0
|
||||
|
||||
/// Chorale (slow) rotor rate in Hz.
|
||||
private let slowRateHz: Double = 0.8
|
||||
|
||||
/// Tremolo (fast) rotor rate in Hz.
|
||||
private let fastRateHz: Double = 6.5
|
||||
|
||||
/// Maximum FM (Doppler) sweep half-swing in seconds, at full depth.
|
||||
private let fmDepthScale: Double = 0.0008
|
||||
|
||||
/// Maximum AM (throb) depth, at full depth.
|
||||
private let amDepthScale: Double = 0.4
|
||||
|
||||
/// Center delay the FM sweeps around, in seconds.
|
||||
private let baseDelayTime: Double = 0.004
|
||||
|
||||
/// Maximum delay the lines are allocated for, in seconds.
|
||||
private let maxDelayTime: Double = 0.02
|
||||
|
||||
/// LFO phase (cycles) for the left rotor.
|
||||
private let leftPhase: Double = 0.0
|
||||
|
||||
/// LFO phase (cycles) for the right rotor — a half cycle opposite the left.
|
||||
private let rightPhase: Double = 0.5
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let depthRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||
private let accelRange: ClosedRange<Double> = 0.05 ... 3.0
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Depth", node: $depth, range: depthRange),
|
||||
PedalKnob(label: "Accel", node: $accel, range: accelRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Switches
|
||||
|
||||
private let speedChoraleValue: Double = 0.0
|
||||
private let speedTremoloValue: Double = 1.0
|
||||
|
||||
public override var effectSwitches: [PedalSwitch] {
|
||||
[
|
||||
PedalSwitch(
|
||||
label: "Speed",
|
||||
node: $speed,
|
||||
options: [
|
||||
PedalSwitch.Option(title: "Chorale", value: speedChoraleValue),
|
||||
PedalSwitch.Option(title: "Tremolo", value: speedTremoloValue),
|
||||
]
|
||||
)
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Channel topology
|
||||
|
||||
public override var channelKind: PedalChannelKind { .widener }
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a rotary-speaker 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: "Rotary",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: RotaryPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
public override func wideEffect(
|
||||
_ dry: any ValidGeneratorInput
|
||||
) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) {
|
||||
// Rotor rate glides between the two speeds — the spin-up / spin-down ramp. Shared by both
|
||||
// rotors (fan-out is cached per block).
|
||||
let rateTarget: any ValidGeneratorInput = $speed * (fastRateHz - slowRateHz) + slowRateHz
|
||||
let rate: Lag.Audio = Lag.Audio(input: rateTarget, time: $accel)
|
||||
return (voice(dry, rate: rate, phase: leftPhase),
|
||||
voice(dry, rate: rate, phase: rightPhase))
|
||||
}
|
||||
|
||||
/// One rotor voice: a Doppler-swept delay line whose output is amplitude-modulated by the same
|
||||
/// rotor LFO, both at `rate` and the given `phase`.
|
||||
private func voice(
|
||||
_ dry: any ValidGeneratorInput,
|
||||
rate: any ValidGeneratorInput,
|
||||
phase: Double
|
||||
) -> any ValidGeneratorInput {
|
||||
let fmSweep: OscSin.Audio = OscSin.Audio(
|
||||
freq: rate,
|
||||
phase: phase,
|
||||
mul: $depth * fmDepthScale,
|
||||
add: baseDelayTime
|
||||
)
|
||||
let delayed: DelayLine = DelayLine(
|
||||
input: dry,
|
||||
maxDelay: maxDelayTime,
|
||||
delay: fmSweep,
|
||||
sampleRate: sampleRate,
|
||||
interpolation: .linear
|
||||
)
|
||||
// Throb gain in [1 - 2·depth·amScale, 1].
|
||||
let amGain: OscSin.Audio = OscSin.Audio(
|
||||
freq: rate,
|
||||
phase: phase,
|
||||
mul: $depth * amDepthScale,
|
||||
add: 1.0 - $depth * amDepthScale
|
||||
)
|
||||
return delayed * amGain
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// ShimmerReverbPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Shimmer reverb — an ambient reverb whose tail rises an octave as it sustains.
|
||||
///
|
||||
/// Wraps the ``ShimmerReverb`` generator: a damped feedback tank with an octave-up grain reader
|
||||
/// inside the feedback path, so the pitched tail regenerates into a glassy, ever-ascending wash.
|
||||
/// Run fully wet internally; the pedal's `Mix` knob sets the wet/dry blend.
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `size`: Tank size (delay) in seconds. Range `[0.01, 0.12]`.
|
||||
/// - `decay`: Tail length (feedback). Range `[0, 0.92]`.
|
||||
/// - `shimmer`: Octave-up regeneration amount. Range `[0, 0.85]`.
|
||||
/// - `damp`: High-frequency damping `[0, 1]` (0 = bright, 1 = dark).
|
||||
public final class ShimmerReverbPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
public override var summary: String {
|
||||
"Ambient reverb whose tail climbs an octave as it sustains — glassy, ascending wash."
|
||||
}
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Tank size (delay) in seconds. Range [0.01, 0.12].
|
||||
@UIParam public var size: Double = 0.06
|
||||
|
||||
/// Tail length (feedback). Range [0, 0.92].
|
||||
@UIParam public var decay: Double = 0.8
|
||||
|
||||
/// Octave-up regeneration amount. Range [0, 0.85].
|
||||
@UIParam public var shimmer: Double = 0.5
|
||||
|
||||
/// High-frequency damping. Range [0, 1].
|
||||
@UIParam public var damp: Double = 0.4
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Default wet/dry blend — reverb sits under the dry signal.
|
||||
private static let defaultMix: Double = 0.35
|
||||
|
||||
/// Maximum tank delay the buffers are allocated for, in seconds.
|
||||
private let maxDelayTime: Double = 0.12
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let sizeRange: ClosedRange<Double> = 0.01 ... 0.12
|
||||
private let decayRange: ClosedRange<Double> = 0.0 ... 0.92
|
||||
private let shimmerRange: ClosedRange<Double> = 0.0 ... 0.85
|
||||
private let dampRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Size", node: $size, range: sizeRange),
|
||||
PedalKnob(label: "Decay", node: $decay, range: decayRange),
|
||||
PedalKnob(label: "Shimmer", node: $shimmer, range: shimmerRange),
|
||||
PedalKnob(label: "Damp", node: $damp, range: dampRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a shimmer-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: "Shimmer Reverb",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: ShimmerReverbPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
ShimmerReverb(
|
||||
input: dry,
|
||||
maxDelay: maxDelayTime,
|
||||
size: $size,
|
||||
decay: $decay,
|
||||
shimmer: $shimmer,
|
||||
damp: $damp,
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// VibratoPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Pitch vibrato.
|
||||
///
|
||||
/// A single delay line whose time is swept by a sine LFO produces a periodic pitch wobble. Unlike
|
||||
/// `TremoloPedal` (which modulates *volume*), vibrato modulates *pitch*, and unlike `ChorusPedal`
|
||||
/// it is heard fully wet — there is no dry voice underneath, so the result is pure pitch movement.
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `rate`: LFO rate in Hz. Range `[0.1, 8]`.
|
||||
/// - `depth`: Delay-sweep depth in seconds (half-swing around the base delay). Range
|
||||
/// `[0.0005, 0.006]`.
|
||||
public final class VibratoPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
public override var summary: String {
|
||||
"Periodic pitch wobble — a sine-swept delay heard fully wet."
|
||||
}
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// LFO rate in Hz. Range [0.1, 8].
|
||||
@UIParam public var rate: Double = 5.0
|
||||
|
||||
/// Delay-sweep depth in seconds. Range [0.0005, 0.006].
|
||||
@UIParam public var depth: Double = 0.002
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Vibrato is pure pitch movement — fully wet, no dry voice underneath.
|
||||
private static let defaultMix: Double = 1.0
|
||||
|
||||
/// Base delay around which the LFO sweeps, in seconds.
|
||||
private let baseDelayTime: Double = 0.006
|
||||
|
||||
/// Maximum delay the line is allocated for, in seconds. Covers `baseDelayTime + max depth`.
|
||||
private let maxDelayTime: Double = 0.02
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let rateRange: ClosedRange<Double> = 0.1 ... 8.0
|
||||
private let depthRange: ClosedRange<Double> = 0.0005 ... 0.006
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Rate", node: $rate, range: rateRange),
|
||||
PedalKnob(label: "Depth", node: $depth, range: depthRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a vibrato 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: "Vibrato",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: VibratoPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
let sweep: OscSin.Audio = OscSin.Audio(
|
||||
freq: $rate,
|
||||
phase: 0.0,
|
||||
mul: $depth,
|
||||
add: baseDelayTime
|
||||
)
|
||||
return DelayLine(
|
||||
input: dry,
|
||||
maxDelay: maxDelayTime,
|
||||
delay: sweep,
|
||||
sampleRate: sampleRate,
|
||||
interpolation: .linear
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -19,11 +19,13 @@ extension Pedal {
|
||||
let values: [Double] = knobs.map { $0.node.value }
|
||||
let switchValues: [Double] = effectSwitches.map { $0.node.value }
|
||||
let sliderValues: [Double] = effectSliders.map { $0.node.value }
|
||||
let selectorValues: [Double] = effectSelectors.map { $0.node.value }
|
||||
return PedalState(
|
||||
type: displayName,
|
||||
knobValues: values,
|
||||
switchValues: switchValues,
|
||||
sliderValues: sliderValues,
|
||||
selectorValues: selectorValues,
|
||||
bypass: bypass
|
||||
)
|
||||
}
|
||||
@@ -51,6 +53,9 @@ extension Pedal {
|
||||
for (slider, value) in zip(effectSliders, state.sliderValues) {
|
||||
slider.node.update(value)
|
||||
}
|
||||
for (selector, value) in zip(effectSelectors, state.selectorValues) {
|
||||
selector.node.update(value)
|
||||
}
|
||||
bypass = state.bypass
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ public enum PedalRegistry {
|
||||
/// to a board via `board.add(_:)`.
|
||||
public static let builtIn: [String: @MainActor () -> Pedal] = [
|
||||
"Overdrive": { OverdrivePedal() },
|
||||
"Distortion": { DistortionPedal() },
|
||||
"Delay": { DelayPedal() },
|
||||
"Reverb": { ReverbPedal() },
|
||||
"Modulation": { ModulationPedal() },
|
||||
@@ -45,14 +46,21 @@ public enum PedalRegistry {
|
||||
"Multi-Tap Delay": { MultiTapDelayPedal() },
|
||||
"Octave Splitter": { OctaveUpSplitterPedal() },
|
||||
"Bass Octaver": { BassOctaverPedal() },
|
||||
"Harmonizer": { HarmonizerPedal() },
|
||||
"Ping-Pong": { PingPongDelayPedal() },
|
||||
"Reverse Delay": { ReverseDelayPedal() },
|
||||
"Shimmer Reverb": { ShimmerReverbPedal() },
|
||||
"Limiter": { LimiterPedal() },
|
||||
"Noise Gate": { NoiseGatePedal() },
|
||||
"Graphic EQ": { GraphicEQPedal() },
|
||||
"Chorus": { ChorusPedal() },
|
||||
"Flanger": { FlangerPedal() },
|
||||
"Vibrato": { VibratoPedal() },
|
||||
"Rotary": { RotaryPedal() },
|
||||
"Sustainer": { SustainerPedal() },
|
||||
"Ring Modulator": { RingModulatorPedal() },
|
||||
"Diffuser": { DiffuserPedal() },
|
||||
"Bitcrusher": { BitcrusherPedal() },
|
||||
]
|
||||
|
||||
/// Returns a new `Pedal` instance for the given type string, or `nil` if the type
|
||||
|
||||
@@ -30,6 +30,10 @@ public struct PedalState: Codable, Equatable {
|
||||
/// no sliders. Absent in presets saved before sliders existed — decodes to `[]`.
|
||||
public let sliderValues: [Double]
|
||||
|
||||
/// Selector-knob values in the same order as `Pedal.effectSelectors`. Empty for pedals with
|
||||
/// no selectors. Absent in presets saved before selectors existed — decodes to `[]`.
|
||||
public let selectorValues: [Double]
|
||||
|
||||
/// Bypass parameter value. `0.0` = engaged, `1.0` = bypassed.
|
||||
public let bypass: Double
|
||||
|
||||
@@ -40,18 +44,21 @@ public struct PedalState: Codable, Equatable {
|
||||
/// - knobValues: Current knob values in `Pedal.knobs` order.
|
||||
/// - switchValues: Current switch values in `Pedal.effectSwitches` order. Defaults to empty.
|
||||
/// - sliderValues: Current slider values in `Pedal.effectSliders` order. Defaults to empty.
|
||||
/// - selectorValues: Current selector values in `Pedal.effectSelectors` order. Defaults to empty.
|
||||
/// - bypass: Bypass parameter value (`0.0` = engaged, `1.0` = bypassed).
|
||||
public init(
|
||||
type: String,
|
||||
knobValues: [Double],
|
||||
switchValues: [Double] = [],
|
||||
sliderValues: [Double] = [],
|
||||
selectorValues: [Double] = [],
|
||||
bypass: Double
|
||||
) {
|
||||
self.type = type
|
||||
self.knobValues = knobValues
|
||||
self.switchValues = switchValues
|
||||
self.sliderValues = sliderValues
|
||||
self.selectorValues = selectorValues
|
||||
self.bypass = bypass
|
||||
}
|
||||
|
||||
@@ -60,17 +67,19 @@ public struct PedalState: Codable, Equatable {
|
||||
case knobValues
|
||||
case switchValues
|
||||
case sliderValues
|
||||
case selectorValues
|
||||
case bypass
|
||||
}
|
||||
|
||||
/// Decodes a snapshot, tolerating presets saved before `switchValues` / `sliderValues`
|
||||
/// existed by defaulting the missing keys to an empty array.
|
||||
/// Decodes a snapshot, tolerating presets saved before `switchValues` / `sliderValues` /
|
||||
/// `selectorValues` existed by defaulting the missing keys to an empty array.
|
||||
public init(from decoder: any Decoder) throws {
|
||||
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
|
||||
self.type = try container.decode(String.self, forKey: .type)
|
||||
self.knobValues = try container.decode([Double].self, forKey: .knobValues)
|
||||
self.switchValues = try container.decodeIfPresent([Double].self, forKey: .switchValues) ?? []
|
||||
self.sliderValues = try container.decodeIfPresent([Double].self, forKey: .sliderValues) ?? []
|
||||
self.selectorValues = try container.decodeIfPresent([Double].self, forKey: .selectorValues) ?? []
|
||||
self.bypass = try container.decode(Double.self, forKey: .bypass)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,10 +51,12 @@ public struct PedalPaletteView: View {
|
||||
/// Preferred display order for the built-in pedals. Any registered pedal not listed here is
|
||||
/// appended afterwards (sorted) so the palette never silently drops a newly added pedal.
|
||||
private static let preferredOrder: [String] = [
|
||||
"Overdrive", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz",
|
||||
"Graphic EQ", "Tremolo", "Phaser", "Modulation", "Chorus",
|
||||
"Auto-Wah", "Mutant", "Ring Modulator", "Diffuser", "Bass Octaver", "Octave Splitter",
|
||||
"Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverb",
|
||||
"Overdrive", "Distortion", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz",
|
||||
"Graphic EQ", "Tremolo", "Phaser", "Modulation", "Chorus", "Flanger", "Vibrato", "Rotary",
|
||||
"Auto-Wah", "Mutant", "Ring Modulator", "Diffuser", "Bitcrusher", "Bass Octaver",
|
||||
"Octave Splitter", "Harmonizer",
|
||||
"Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverse Delay", "Reverb",
|
||||
"Shimmer Reverb",
|
||||
]
|
||||
|
||||
/// Routing/branching topologies the user can insert into the board.
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
// PedalSelectorKnobView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// Renders a ``PedalSelectorKnob`` — a rotary knob that snaps to a fixed set of labelled stops.
|
||||
///
|
||||
/// Visually matches `ParameterKnob` (same dial + indicator), but drag quantises to discrete
|
||||
/// positions and the caption shows the current stop's title rather than a numeric value. Drag up to
|
||||
/// advance clockwise through the stops, down to go back.
|
||||
struct PedalSelectorKnobView: View {
|
||||
|
||||
// MARK: - Layout constants
|
||||
|
||||
private static let dialSize: CGFloat = 50
|
||||
private static let indicatorWidth: CGFloat = 2
|
||||
private static let indicatorHeight: CGFloat = 14
|
||||
private static let indicatorInset: CGFloat = 3
|
||||
private static let startAngle: Double = -135.0
|
||||
private static let totalArc: Double = 270.0
|
||||
/// Pixels of vertical drag per stop step.
|
||||
private static let pixelsPerStep: CGFloat = 22
|
||||
private static let labelSpacing: CGFloat = 4
|
||||
|
||||
// MARK: - Input
|
||||
|
||||
private let selector: PedalSelectorKnob
|
||||
|
||||
// MARK: - Drag state
|
||||
|
||||
@State private var dragStartIndex: Int = 0
|
||||
@State private var dragInProgress: Bool = false
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
init(_ selector: PedalSelectorKnob) {
|
||||
self.selector = selector
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: PedalSelectorKnobView.labelSpacing) {
|
||||
dial
|
||||
.frame(width: PedalSelectorKnobView.dialSize, height: PedalSelectorKnobView.dialSize)
|
||||
.gesture(dragGesture)
|
||||
Text(selector.label)
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.white)
|
||||
Text(currentStop.title)
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.white)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Dial
|
||||
|
||||
private var dial: some View {
|
||||
let count: Int = selector.stops.count
|
||||
let normalised: Double = count > 1 ? Double(currentIndex) / Double(count - 1) : 0
|
||||
let rotation: Double = PedalSelectorKnobView.startAngle + normalised * PedalSelectorKnobView.totalArc
|
||||
let offset: CGFloat = -(PedalSelectorKnobView.dialSize / 2
|
||||
- PedalSelectorKnobView.indicatorHeight / 2
|
||||
- PedalSelectorKnobView.indicatorInset)
|
||||
|
||||
return ZStack {
|
||||
Circle()
|
||||
.fill(Color.lyrebirdControlBackground)
|
||||
.overlay(Circle().stroke(Color.lyrebirdSeparator, lineWidth: 1))
|
||||
Rectangle()
|
||||
.fill(Color.accentColor)
|
||||
.frame(
|
||||
width: PedalSelectorKnobView.indicatorWidth,
|
||||
height: PedalSelectorKnobView.indicatorHeight
|
||||
)
|
||||
.offset(y: offset)
|
||||
.rotationEffect(.degrees(rotation))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Drag
|
||||
|
||||
private var dragGesture: some Gesture {
|
||||
DragGesture(minimumDistance: 1)
|
||||
.onChanged { gesture in
|
||||
if !dragInProgress {
|
||||
dragInProgress = true
|
||||
dragStartIndex = currentIndex
|
||||
}
|
||||
let delta: CGFloat = gesture.translation.height // down = positive
|
||||
// Up should advance (increase index), so subtract the downward delta.
|
||||
let steps: Int = Int((-delta / PedalSelectorKnobView.pixelsPerStep).rounded())
|
||||
let target: Int = min(max(dragStartIndex + steps, 0), selector.stops.count - 1)
|
||||
let value: Double = selector.stops[target].value
|
||||
if value != selector.node.value {
|
||||
selector.node.update(value)
|
||||
}
|
||||
}
|
||||
.onEnded { _ in dragInProgress = false }
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Index of the stop whose value is nearest the node's current value.
|
||||
private var currentIndex: Int {
|
||||
let value: Double = selector.node.value
|
||||
var bestIndex: Int = 0
|
||||
var bestDistance: Double = .greatestFiniteMagnitude
|
||||
for (index, stop) in selector.stops.enumerated() {
|
||||
let distance: Double = abs(stop.value - value)
|
||||
if distance < bestDistance {
|
||||
bestDistance = distance
|
||||
bestIndex = index
|
||||
}
|
||||
}
|
||||
return bestIndex
|
||||
}
|
||||
|
||||
private var currentStop: PedalSelectorKnob.Stop {
|
||||
selector.stops[currentIndex]
|
||||
}
|
||||
}
|
||||
@@ -17,8 +17,10 @@ import LyrebirdShoeGaze
|
||||
private func enclosureColor(for displayName: String) -> Color {
|
||||
switch displayName {
|
||||
case "Overdrive": return Color(red: 0.85, green: 0.42, blue: 0.08) // warm orange
|
||||
case "Distortion": return Color(red: 0.80, green: 0.26, blue: 0.12) // hot rust
|
||||
case "Delay": return Color(red: 0.10, green: 0.55, blue: 0.55) // teal
|
||||
case "Reverb": return Color(red: 0.30, green: 0.18, blue: 0.65) // indigo
|
||||
case "Shimmer Reverb": return Color(red: 0.46, green: 0.52, blue: 0.78) // icy periwinkle
|
||||
case "Modulation": return Color(red: 0.12, green: 0.58, blue: 0.22) // green
|
||||
case "Fuzz": return Color(red: 0.55, green: 0.10, blue: 0.10) // deep crimson
|
||||
case "Tremolo": return Color(red: 0.20, green: 0.38, blue: 0.72) // cobalt blue
|
||||
@@ -28,13 +30,19 @@ private func enclosureColor(for displayName: String) -> Color {
|
||||
case "Auto-Wah": return Color(red: 0.80, green: 0.62, blue: 0.10) // gold
|
||||
case "Feedback Delay": return Color(red: 0.48, green: 0.30, blue: 0.14) // tape sepia
|
||||
case "Multi-Tap Delay": return Color(red: 0.08, green: 0.48, blue: 0.68) // cyan
|
||||
case "Reverse Delay": return Color(red: 0.10, green: 0.44, blue: 0.60) // deep cyan-teal
|
||||
case "Limiter": return Color(red: 0.62, green: 0.16, blue: 0.20) // brick red
|
||||
case "Noise Gate": return Color(red: 0.24, green: 0.26, blue: 0.30) // gunmetal
|
||||
case "Graphic EQ": return Color(red: 0.14, green: 0.40, blue: 0.50) // deep teal
|
||||
case "Chorus": return Color(red: 0.16, green: 0.50, blue: 0.64) // aqua
|
||||
case "Flanger": return Color(red: 0.28, green: 0.52, blue: 0.78) // steel blue
|
||||
case "Vibrato": return Color(red: 0.42, green: 0.30, blue: 0.70) // violet-blue
|
||||
case "Rotary": return Color(red: 0.45, green: 0.34, blue: 0.20) // Leslie cabinet walnut
|
||||
case "Sustainer": return Color(red: 0.22, green: 0.46, blue: 0.30) // pine green
|
||||
case "Ring Modulator": return Color(red: 0.64, green: 0.30, blue: 0.10) // burnt amber
|
||||
case "Diffuser": return Color(red: 0.34, green: 0.30, blue: 0.62) // periwinkle
|
||||
case "Harmonizer": return Color(red: 0.52, green: 0.20, blue: 0.40) // wine / mauve
|
||||
case "Bitcrusher": return Color(red: 0.30, green: 0.34, blue: 0.40) // slate / digital gray
|
||||
default: return Color(red: 0.36, green: 0.36, blue: 0.38) // steel gray
|
||||
}
|
||||
}
|
||||
@@ -277,6 +285,7 @@ public struct PedalView: View {
|
||||
VStack(spacing: PedalView.sectionSpacing) {
|
||||
namePlate
|
||||
knobGrid
|
||||
selectorRow
|
||||
switchRow
|
||||
sliderBank(sliders)
|
||||
Spacer(minLength: 0)
|
||||
@@ -371,6 +380,22 @@ public struct PedalView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// Row of stepped selector knobs drawn from `pedal.effectSelectors`, beneath the knob grid.
|
||||
/// Renders nothing when the pedal publishes no selectors.
|
||||
@ViewBuilder
|
||||
private var selectorRow: some View {
|
||||
let selectors: [PedalSelectorKnob] = pedal.effectSelectors
|
||||
if !selectors.isEmpty {
|
||||
HStack(alignment: .top, spacing: PedalView.knobRowItemSpacing) {
|
||||
Spacer(minLength: 0)
|
||||
ForEach(Array(selectors.enumerated()), id: \.offset) { pair in
|
||||
PedalSelectorKnobView(pair.element)
|
||||
}
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Row of segmented switches drawn from `pedal.effectSwitches`, one per row, beneath
|
||||
/// the knob grid. Renders nothing when the pedal publishes no switches.
|
||||
@ViewBuilder
|
||||
|
||||
@@ -180,6 +180,9 @@ public struct ShoeGazeBuilderView: View {
|
||||
blue: ShoeGazeBuilderView.backgroundBlue
|
||||
)
|
||||
)
|
||||
// The builder is always dark-themed; force the dark scheme so system controls (nav title,
|
||||
// steppers, the Record button) use light text instead of black-on-dark in light mode.
|
||||
.preferredColorScheme(.dark)
|
||||
.background(boardSwitchShortcuts)
|
||||
.onAppear {
|
||||
restoreInputSelection()
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
// BitReduceTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@MainActor
|
||||
@Suite("BitReduce")
|
||||
struct BitReduceTests {
|
||||
|
||||
/// Minimal synth: a constant DC value through a `BitReduce`, written to a mono bus.
|
||||
private final class CrushSynth: SynthesizerBase {
|
||||
private let value: Double
|
||||
private let bits: Double
|
||||
private let outBus: Int
|
||||
|
||||
init(value: Double, bits: Double, outBus: Int) {
|
||||
self.value = value
|
||||
self.bits = bits
|
||||
self.outBus = outBus
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
output(bus: outBus, source: BitReduce(input: value, bits: bits))
|
||||
}
|
||||
}
|
||||
|
||||
private func render(value: Double, bits: Double) throws -> [Float] {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer { engine.busAllocator.releaseAudioBus(dstBus) }
|
||||
let synth: CrushSynth = CrushSynth(value: value, bits: bits, outBus: dstBus.index)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
try engine.add(synth)
|
||||
try engine.add(master, position: NodePosition.after(synth))
|
||||
try engine.start()
|
||||
return readStereoCAF(url: url)
|
||||
}
|
||||
|
||||
// Asserts are scale-independent: the test harness applies a fixed output gain/pan, so compare
|
||||
// quantisation *levels* rather than absolute amplitudes.
|
||||
|
||||
@Test func snapsToDiscreteLevels() throws {
|
||||
// 8 bits over [-1, 1]: step = 2/256, inverseStep = 128.
|
||||
// 0.896 → round(114.688) = 115; 0.901 → round(115.328) = 115 (same level);
|
||||
// 0.910 → round(116.48) = 116 (different level).
|
||||
let sameA: [Float] = try render(value: 0.896, bits: 8.0)
|
||||
let sameB: [Float] = try render(value: 0.901, bits: 8.0)
|
||||
let other: [Float] = try render(value: 0.910, bits: 8.0)
|
||||
#expect(sameA[200] == sameB[200], "values in the same 8-bit level should quantise identically")
|
||||
#expect(sameA[200] != other[200], "values in different 8-bit levels should differ")
|
||||
}
|
||||
|
||||
@Test func oneBitFloorsSmallValuesToZero() throws {
|
||||
// 1 bit: levels = 2, step = 1.0; round(0.4) = 0 → exactly zero regardless of output gain.
|
||||
let samples: [Float] = try render(value: 0.4, bits: 1.0)
|
||||
#expect(abs(samples[200]) < 1e-5, "1-bit quantiser should floor 0.4 to 0")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
// BitcrusherPedalTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@MainActor
|
||||
@Suite("BitcrusherPedal")
|
||||
struct BitcrusherPedalTests {
|
||||
|
||||
private func render(
|
||||
configure: (BitcrusherPedal) -> Void
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.2
|
||||
let numAudioBuses: Int = 64
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: renderDuration,
|
||||
numAudioBuses: numAudioBuses
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer {
|
||||
engine.busAllocator.releaseAudioBus(srcBus)
|
||||
engine.busAllocator.releaseAudioBus(dstBus)
|
||||
}
|
||||
|
||||
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
|
||||
let pedal: BitcrusherPedal = BitcrusherPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
configure(pedal)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
|
||||
try engine.add(source)
|
||||
try engine.add(pedal, position: NodePosition.after(source))
|
||||
try engine.add(master, position: NodePosition.after(pedal))
|
||||
try engine.start()
|
||||
|
||||
return readStereoCAF(url: url)
|
||||
}
|
||||
|
||||
private func totalSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
zip(a, b).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||
let samples: [Float] = try render { _ in }
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "bitcrusher output was silent")
|
||||
}
|
||||
|
||||
@Test func crushChangesOutput() throws {
|
||||
let light: [Float] = try render { pedal in pedal.crush = 1.0; pedal.bits = 16.0; pedal.tone = 8000.0; pedal.mix = 1.0 }
|
||||
let heavy: [Float] = try render { pedal in pedal.crush = 32.0; pedal.bits = 16.0; pedal.tone = 8000.0; pedal.mix = 1.0 }
|
||||
#expect(hasNonSilentOutput(heavy), "decimated bitcrusher was silent")
|
||||
#expect(totalSSD(light, heavy) > 0, "changing crush did not change the output")
|
||||
}
|
||||
|
||||
@Test func bitsChangeOutput() throws {
|
||||
let clean: [Float] = try render { pedal in pedal.crush = 1.0; pedal.bits = 16.0; pedal.tone = 8000.0; pedal.mix = 1.0 }
|
||||
let crushed: [Float] = try render { pedal in pedal.crush = 1.0; pedal.bits = 3.0; pedal.tone = 8000.0; pedal.mix = 1.0 }
|
||||
#expect(hasNonSilentOutput(crushed), "bit-reduced output was silent")
|
||||
#expect(totalSSD(clean, crushed) > 0, "changing bit depth did not change the output")
|
||||
}
|
||||
|
||||
@Test func exposesCrushBitsToneKnobs() throws {
|
||||
let pedal: BitcrusherPedal = BitcrusherPedal()
|
||||
let labels: [String] = pedal.effectKnobs.map { $0.label }
|
||||
#expect(labels == ["Crush", "Bits", "Tone"])
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Bitcrusher")
|
||||
#expect(pedal is BitcrusherPedal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// DistortionPedalTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@MainActor
|
||||
@Suite("DistortionPedal")
|
||||
struct DistortionPedalTests {
|
||||
|
||||
private func render(
|
||||
configure: (DistortionPedal) -> Void
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.2
|
||||
let numAudioBuses: Int = 64
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: renderDuration,
|
||||
numAudioBuses: numAudioBuses
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer {
|
||||
engine.busAllocator.releaseAudioBus(srcBus)
|
||||
engine.busAllocator.releaseAudioBus(dstBus)
|
||||
}
|
||||
|
||||
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
|
||||
let pedal: DistortionPedal = DistortionPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
configure(pedal)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
|
||||
try engine.add(source)
|
||||
try engine.add(pedal, position: NodePosition.after(source))
|
||||
try engine.add(master, position: NodePosition.after(pedal))
|
||||
try engine.start()
|
||||
|
||||
return readStereoCAF(url: url)
|
||||
}
|
||||
|
||||
private func windowedSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
let skipSamples: Int = 2048
|
||||
let windowSize: Int = 2048
|
||||
guard a.count >= skipSamples + windowSize,
|
||||
b.count >= skipSamples + windowSize else { return 0.0 }
|
||||
let aWindow: ArraySlice<Float> = a[skipSamples..<(skipSamples + windowSize)]
|
||||
let bWindow: ArraySlice<Float> = b[skipSamples..<(skipSamples + windowSize)]
|
||||
return zip(aWindow, bWindow).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||
let samples: [Float] = try render { _ in }
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "distortion output was silent")
|
||||
}
|
||||
|
||||
@Test func driveChangesOutput() throws {
|
||||
let low: [Float] = try render { pedal in pedal.drive = 2.0 }
|
||||
let high: [Float] = try render { pedal in pedal.drive = 45.0 }
|
||||
#expect(hasNonSilentOutput(high), "high-drive distortion was silent")
|
||||
#expect(windowedSSD(low, high) > 0, "changing drive did not change the output")
|
||||
}
|
||||
|
||||
@Test func toneChangesOutput() throws {
|
||||
let dark: [Float] = try render { pedal in pedal.drive = 30.0; pedal.tone = 700.0 }
|
||||
let bright: [Float] = try render { pedal in pedal.drive = 30.0; pedal.tone = 5500.0 }
|
||||
#expect(hasNonSilentOutput(bright), "bright distortion was silent")
|
||||
#expect(windowedSSD(dark, bright) > 0, "changing tone did not change the output")
|
||||
}
|
||||
|
||||
@Test func exposesDriveToneKnobs() throws {
|
||||
let pedal: DistortionPedal = DistortionPedal()
|
||||
let labels: [String] = pedal.effectKnobs.map { $0.label }
|
||||
#expect(labels == ["Drive", "Tone"])
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Distortion")
|
||||
#expect(pedal is DistortionPedal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// FlangerPedalTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@MainActor
|
||||
@Suite("FlangerPedal")
|
||||
struct FlangerPedalTests {
|
||||
|
||||
private func render(
|
||||
configure: (FlangerPedal) -> Void
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.2
|
||||
let numAudioBuses: Int = 64
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: renderDuration,
|
||||
numAudioBuses: numAudioBuses
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer {
|
||||
engine.busAllocator.releaseAudioBus(srcBus)
|
||||
engine.busAllocator.releaseAudioBus(dstBus)
|
||||
}
|
||||
|
||||
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
|
||||
let pedal: FlangerPedal = FlangerPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
configure(pedal)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
|
||||
try engine.add(source)
|
||||
try engine.add(pedal, position: NodePosition.after(source))
|
||||
try engine.add(master, position: NodePosition.after(pedal))
|
||||
try engine.start()
|
||||
|
||||
return readStereoCAF(url: url)
|
||||
}
|
||||
|
||||
private func windowedSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
let skipSamples: Int = 2048
|
||||
let windowSize: Int = 2048
|
||||
guard a.count >= skipSamples + windowSize,
|
||||
b.count >= skipSamples + windowSize else { return 0.0 }
|
||||
let aWindow: ArraySlice<Float> = a[skipSamples..<(skipSamples + windowSize)]
|
||||
let bWindow: ArraySlice<Float> = b[skipSamples..<(skipSamples + windowSize)]
|
||||
return zip(aWindow, bWindow).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||
let samples: [Float] = try render { _ in }
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "flanger output was silent")
|
||||
}
|
||||
|
||||
@Test func depthChangesOutput() throws {
|
||||
let shallow: [Float] = try render { pedal in pedal.depth = 0.1; pedal.mix = 1.0 }
|
||||
let deep: [Float] = try render { pedal in pedal.depth = 0.95; pedal.mix = 1.0 }
|
||||
#expect(hasNonSilentOutput(deep), "deep flanger was silent")
|
||||
#expect(windowedSSD(shallow, deep) > 0, "changing depth did not change the output")
|
||||
}
|
||||
|
||||
@Test func feedbackChangesOutput() throws {
|
||||
let dry: [Float] = try render { pedal in pedal.feedback = 0.0; pedal.mix = 1.0 }
|
||||
let resonant: [Float] = try render { pedal in pedal.feedback = 0.85; pedal.mix = 1.0 }
|
||||
#expect(hasNonSilentOutput(resonant), "resonant flanger was silent")
|
||||
#expect(windowedSSD(dry, resonant) > 0, "changing feedback did not change the output")
|
||||
}
|
||||
|
||||
@Test func exposesRateDepthFeedbackKnobs() throws {
|
||||
let pedal: FlangerPedal = FlangerPedal()
|
||||
let labels: [String] = pedal.effectKnobs.map { $0.label }
|
||||
#expect(labels == ["Rate", "Depth", "Feedback"])
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Flanger")
|
||||
#expect(pedal is FlangerPedal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
// HarmonizerPedalTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@MainActor
|
||||
@Suite("HarmonizerPedal")
|
||||
struct HarmonizerPedalTests {
|
||||
|
||||
/// Renders the pedal through an NRT engine with the given configuration and returns the output.
|
||||
private func render(
|
||||
configure: (HarmonizerPedal) -> Void
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.3
|
||||
let numAudioBuses: Int = 64
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: renderDuration,
|
||||
numAudioBuses: numAudioBuses
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer {
|
||||
engine.busAllocator.releaseAudioBus(srcBus)
|
||||
engine.busAllocator.releaseAudioBus(dstBus)
|
||||
}
|
||||
|
||||
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
|
||||
let pedal: HarmonizerPedal = HarmonizerPedal(
|
||||
inputBus: srcBus.index,
|
||||
outputBus: dstBus.index
|
||||
)
|
||||
configure(pedal)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
|
||||
try engine.add(source)
|
||||
try engine.add(pedal, position: NodePosition.after(source))
|
||||
try engine.add(master, position: NodePosition.after(pedal))
|
||||
try engine.start()
|
||||
|
||||
return readStereoCAF(url: url)
|
||||
}
|
||||
|
||||
/// Sum of squared differences over a stable window of two renders.
|
||||
private func windowedSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
let skipSamples: Int = 4096
|
||||
let windowSize: Int = 2048
|
||||
guard a.count >= skipSamples + windowSize,
|
||||
b.count >= skipSamples + windowSize else { return 0.0 }
|
||||
let aWindow: ArraySlice<Float> = a[skipSamples..<(skipSamples + windowSize)]
|
||||
let bWindow: ArraySlice<Float> = b[skipSamples..<(skipSamples + windowSize)]
|
||||
return zip(aWindow, bWindow).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||
let samples: [Float] = try render { pedal in
|
||||
pedal.direct = 1.0
|
||||
pedal.voice1Level = 0.6
|
||||
pedal.voice2Level = 0.5
|
||||
}
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "harmonizer output was silent")
|
||||
}
|
||||
|
||||
@Test func changingVoiceIntervalChangesOutput() throws {
|
||||
let third: [Float] = try render { pedal in
|
||||
pedal.direct = 0.0
|
||||
pedal.voice1Level = 1.0
|
||||
pedal.voice2Level = 0.0
|
||||
pedal.voice1 = 3.0 // minor third up
|
||||
}
|
||||
let fifth: [Float] = try render { pedal in
|
||||
pedal.direct = 0.0
|
||||
pedal.voice1Level = 1.0
|
||||
pedal.voice2Level = 0.0
|
||||
pedal.voice1 = 7.0 // perfect fifth up
|
||||
}
|
||||
#expect(hasNonSilentOutput(third), "minor-third voice was silent")
|
||||
#expect(hasNonSilentOutput(fifth), "fifth voice was silent")
|
||||
#expect(windowedSSD(third, fifth) > 0, "changing the interval did not change the output")
|
||||
}
|
||||
|
||||
@Test func harmonyVoicesDifferFromDirectOnly() throws {
|
||||
let directOnly: [Float] = try render { pedal in
|
||||
pedal.direct = 1.0
|
||||
pedal.voice1Level = 0.0
|
||||
pedal.voice2Level = 0.0
|
||||
}
|
||||
let withVoices: [Float] = try render { pedal in
|
||||
pedal.direct = 1.0
|
||||
pedal.voice1Level = 1.0
|
||||
pedal.voice2Level = 1.0
|
||||
}
|
||||
#expect(hasNonSilentOutput(directOnly), "direct-only render was silent")
|
||||
#expect(windowedSSD(directOnly, withVoices) > 0, "adding harmony voices did not change the output")
|
||||
}
|
||||
|
||||
@Test func exposesLevelKnobs() throws {
|
||||
let pedal: HarmonizerPedal = HarmonizerPedal()
|
||||
let labels: [String] = pedal.effectKnobs.map { $0.label }
|
||||
#expect(labels == ["V1 Level", "V2 Level", "Direct"])
|
||||
}
|
||||
|
||||
@Test func exposesTwoIntervalSelectors() throws {
|
||||
let pedal: HarmonizerPedal = HarmonizerPedal()
|
||||
let selectors: [PedalSelectorKnob] = pedal.effectSelectors
|
||||
#expect(selectors.map { $0.label } == ["Voice 1", "Voice 2"])
|
||||
// Both minor- and major-thirds above and below must be available.
|
||||
let titles: [String] = selectors.first?.stops.map { $0.title } ?? []
|
||||
#expect(titles.contains("m3"))
|
||||
#expect(titles.contains("M3"))
|
||||
#expect(titles.contains("-m3"))
|
||||
#expect(titles.contains("-M3"))
|
||||
}
|
||||
|
||||
@Test func presetRoundTripPreservesIntervalsAndLevels() throws {
|
||||
let pedal: HarmonizerPedal = HarmonizerPedal()
|
||||
pedal.voice1 = -3.0
|
||||
pedal.voice2 = 12.0
|
||||
pedal.voice1Level = 0.3
|
||||
|
||||
let state: PedalState = pedal.captureState()
|
||||
#expect(state.selectorValues == [-3.0, 12.0])
|
||||
|
||||
let restored: HarmonizerPedal = HarmonizerPedal()
|
||||
restored.applyState(state)
|
||||
#expect(restored.voice1 == -3.0)
|
||||
#expect(restored.voice2 == 12.0)
|
||||
#expect(restored.voice1Level == 0.3)
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Harmonizer")
|
||||
#expect(pedal is HarmonizerPedal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
// ReverseDelayPedalTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@MainActor
|
||||
@Suite("ReverseDelayPedal")
|
||||
struct ReverseDelayPedalTests {
|
||||
|
||||
private func render(
|
||||
configure: (ReverseDelayPedal) -> Void
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.6
|
||||
let numAudioBuses: Int = 64
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: renderDuration,
|
||||
numAudioBuses: numAudioBuses
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer {
|
||||
engine.busAllocator.releaseAudioBus(srcBus)
|
||||
engine.busAllocator.releaseAudioBus(dstBus)
|
||||
}
|
||||
|
||||
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
|
||||
let pedal: ReverseDelayPedal = ReverseDelayPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
configure(pedal)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
|
||||
try engine.add(source)
|
||||
try engine.add(pedal, position: NodePosition.after(source))
|
||||
try engine.add(master, position: NodePosition.after(pedal))
|
||||
try engine.start()
|
||||
|
||||
return readStereoCAF(url: url)
|
||||
}
|
||||
|
||||
/// Sum of squared differences over the full overlapping length. Feedback only diverges once a
|
||||
/// fed-back segment is replayed (the third segment), so a narrow window can miss it; comparing
|
||||
/// the whole readable buffer (the reader returns the first 4096 frames) is robust.
|
||||
private func totalSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
zip(a, b).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||
// Short segment so reversed playback begins within the reader's 4096-frame window.
|
||||
let samples: [Float] = try render { pedal in pedal.time = 0.03; pedal.mix = 1.0 }
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "reverse delay output was silent")
|
||||
}
|
||||
|
||||
@Test func feedbackChangesOutput() throws {
|
||||
let dry: [Float] = try render { pedal in pedal.time = 0.03; pedal.feedback = 0.0; pedal.mix = 1.0 }
|
||||
let trails: [Float] = try render { pedal in pedal.time = 0.03; pedal.feedback = 0.6; pedal.mix = 1.0 }
|
||||
#expect(hasNonSilentOutput(trails), "feedback reverse delay was silent")
|
||||
#expect(totalSSD(dry, trails) > 0, "changing feedback did not change the output")
|
||||
}
|
||||
|
||||
@Test func exposesTimeFeedbackKnobs() throws {
|
||||
let pedal: ReverseDelayPedal = ReverseDelayPedal()
|
||||
let labels: [String] = pedal.effectKnobs.map { $0.label }
|
||||
#expect(labels == ["Time", "Feedback"])
|
||||
}
|
||||
|
||||
@Test func presetRoundTripPreservesKnobs() throws {
|
||||
let pedal: ReverseDelayPedal = ReverseDelayPedal()
|
||||
pedal.time = 1.2
|
||||
pedal.feedback = 0.7
|
||||
let state: PedalState = pedal.captureState()
|
||||
|
||||
let restored: ReverseDelayPedal = ReverseDelayPedal()
|
||||
restored.applyState(state)
|
||||
#expect(restored.time == 1.2)
|
||||
#expect(restored.feedback == 0.7)
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Reverse Delay")
|
||||
#expect(pedal is ReverseDelayPedal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// ReverseDelayTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@MainActor
|
||||
@Suite("ReverseDelay")
|
||||
struct ReverseDelayTests {
|
||||
|
||||
/// Minimal synth: a DC value through a `ReverseDelay`, written to a mono bus.
|
||||
private final class ReverseSynth: SynthesizerBase {
|
||||
private let value: Double
|
||||
private let delay: Double
|
||||
private let outBus: Int
|
||||
|
||||
init(value: Double, delay: Double, outBus: Int) {
|
||||
self.value = value
|
||||
self.delay = delay
|
||||
self.outBus = outBus
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
output(bus: outBus, source: ReverseDelay(
|
||||
input: value,
|
||||
maxDelay: 0.1,
|
||||
delay: delay,
|
||||
feedback: 0.0,
|
||||
sampleRate: 44100.0
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
private func render(value: Double, delay: Double) throws -> [Float] {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, sampleRate: 44100.0)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer { engine.busAllocator.releaseAudioBus(dstBus) }
|
||||
let synth: ReverseSynth = ReverseSynth(value: value, delay: delay, outBus: dstBus.index)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
try engine.add(synth)
|
||||
try engine.add(master, position: NodePosition.after(synth))
|
||||
try engine.start()
|
||||
return readStereoCAF(url: url, sampleRate: 44100.0)
|
||||
}
|
||||
|
||||
private func left(_ samples: [Float], _ frame: Int) -> Float {
|
||||
samples[frame * 2]
|
||||
}
|
||||
|
||||
@Test func firstSegmentIsSilentThenReplaysRecordedValue() throws {
|
||||
// delay 0.02 s @ 44100 = 882-frame segments. Segment 1 [0, 882) plays the still-empty
|
||||
// buffer (silence); segment 2 [882, 1764) reverses the recorded DC. Asserts are
|
||||
// scale-independent (the harness applies a fixed output gain/pan): check silence vs.
|
||||
// non-silent, and that the replayed DC is flat (reverse of a constant is the same constant).
|
||||
let samples: [Float] = try render(value: 0.5, delay: 0.02)
|
||||
|
||||
// Mid segment 1: still recording, play buffer empty → silent.
|
||||
#expect(abs(left(samples, 441)) < 1e-3, "first segment should be silent (nothing recorded yet)")
|
||||
|
||||
// Segment 2, clear of the edge fades → non-silent and constant (reversed DC).
|
||||
let a: Float = left(samples, 1200)
|
||||
let b: Float = left(samples, 1400)
|
||||
#expect(abs(a) > 1e-2, "second segment should replay the recorded value (non-silent)")
|
||||
#expect(abs(a - b) < 1e-3, "reversed DC should be flat across the segment")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
// RotaryPedalTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@MainActor
|
||||
@Suite("RotaryPedal")
|
||||
struct RotaryPedalTests {
|
||||
|
||||
private func render(
|
||||
configure: (RotaryPedal) -> Void
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.3
|
||||
let numAudioBuses: Int = 64
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: renderDuration,
|
||||
numAudioBuses: numAudioBuses
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 2)
|
||||
defer {
|
||||
engine.busAllocator.releaseAudioBus(srcBus)
|
||||
engine.busAllocator.releaseAudioBus(dstBus)
|
||||
}
|
||||
|
||||
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
|
||||
let pedal: RotaryPedal = RotaryPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
configure(pedal)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
|
||||
try engine.add(source)
|
||||
try engine.add(pedal, position: NodePosition.after(source))
|
||||
try engine.add(master, position: NodePosition.after(pedal))
|
||||
try engine.start()
|
||||
|
||||
return readStereoCAF(url: url)
|
||||
}
|
||||
|
||||
private func windowedSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
let skipSamples: Int = 4096
|
||||
let windowSize: Int = 4096
|
||||
guard a.count >= skipSamples + windowSize,
|
||||
b.count >= skipSamples + windowSize else { return 0.0 }
|
||||
let aWindow: ArraySlice<Float> = a[skipSamples..<(skipSamples + windowSize)]
|
||||
let bWindow: ArraySlice<Float> = b[skipSamples..<(skipSamples + windowSize)]
|
||||
return zip(aWindow, bWindow).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||
let samples: [Float] = try render { _ in }
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "rotary output was silent")
|
||||
}
|
||||
|
||||
@Test func speedChangesOutput() throws {
|
||||
let chorale: [Float] = try render { pedal in pedal.speed = 0.0; pedal.accel = 0.05 }
|
||||
let tremolo: [Float] = try render { pedal in pedal.speed = 1.0; pedal.accel = 0.05 }
|
||||
#expect(hasNonSilentOutput(tremolo), "fast rotary was silent")
|
||||
#expect(windowedSSD(chorale, tremolo) > 0, "changing speed did not change the output")
|
||||
}
|
||||
|
||||
@Test func exposesDepthAccelKnobsAndSpeedSwitch() throws {
|
||||
let pedal: RotaryPedal = RotaryPedal()
|
||||
#expect(pedal.effectKnobs.map { $0.label } == ["Depth", "Accel"])
|
||||
#expect(pedal.effectSwitches.map { $0.label } == ["Speed"])
|
||||
#expect(pedal.effectSwitches.first?.options.map { $0.title } == ["Chorale", "Tremolo"])
|
||||
}
|
||||
|
||||
@Test func presetRoundTripPreservesSpeed() throws {
|
||||
let pedal: RotaryPedal = RotaryPedal()
|
||||
pedal.speed = 1.0
|
||||
pedal.depth = 0.4
|
||||
let state: PedalState = pedal.captureState()
|
||||
|
||||
let restored: RotaryPedal = RotaryPedal()
|
||||
restored.applyState(state)
|
||||
#expect(restored.speed == 1.0)
|
||||
#expect(restored.depth == 0.4)
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Rotary")
|
||||
#expect(pedal is RotaryPedal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
// SampleRateDecimateTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@MainActor
|
||||
@Suite("SampleRateDecimate")
|
||||
struct SampleRateDecimateTests {
|
||||
|
||||
/// Minimal synth: a sine through a `SampleRateDecimate`, written to a mono bus.
|
||||
private final class DecimateSynth: SynthesizerBase {
|
||||
private let freq: Double
|
||||
private let factor: Double
|
||||
private let outBus: Int
|
||||
|
||||
init(freq: Double, factor: Double, outBus: Int) {
|
||||
self.freq = freq
|
||||
self.factor = factor
|
||||
self.outBus = outBus
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
let osc: OscSin.Audio = OscSin.Audio(freq: freq)
|
||||
output(bus: outBus, source: SampleRateDecimate(input: osc, downsample: factor))
|
||||
}
|
||||
}
|
||||
|
||||
private func render(freq: Double, factor: Double) throws -> [Float] {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer { engine.busAllocator.releaseAudioBus(dstBus) }
|
||||
let synth: DecimateSynth = DecimateSynth(freq: freq, factor: factor, outBus: dstBus.index)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
try engine.add(synth)
|
||||
try engine.add(master, position: NodePosition.after(synth))
|
||||
try engine.start()
|
||||
return readStereoCAF(url: url)
|
||||
}
|
||||
|
||||
/// Left-channel frame `i` (interleaved stereo).
|
||||
private func left(_ samples: [Float], _ frame: Int) -> Float {
|
||||
samples[frame * 2]
|
||||
}
|
||||
|
||||
@Test func holdsEachSampleForTheFactor() throws {
|
||||
// Factor 4: frames latch at 0, 4, 8, … and hold for four output samples each.
|
||||
let samples: [Float] = try render(freq: 2000.0, factor: 4.0)
|
||||
// Group [8, 11] holds the value latched at frame 8 (a non-zero point on the sine).
|
||||
#expect(left(samples, 8) == left(samples, 9))
|
||||
#expect(left(samples, 8) == left(samples, 10))
|
||||
#expect(left(samples, 8) == left(samples, 11))
|
||||
// The next group latches a fresh value.
|
||||
#expect(left(samples, 8) != left(samples, 12), "decimator did not re-latch at the group boundary")
|
||||
}
|
||||
|
||||
@Test func factorOneIsTransparent() throws {
|
||||
let samples: [Float] = try render(freq: 2000.0, factor: 1.0)
|
||||
// No two adjacent samples forced equal — a moving sine should differ frame-to-frame.
|
||||
#expect(left(samples, 8) != left(samples, 9), "factor 1 should pass the signal through unheld")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// ShimmerReverbPedalTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@MainActor
|
||||
@Suite("ShimmerReverbPedal")
|
||||
struct ShimmerReverbPedalTests {
|
||||
|
||||
private func render(
|
||||
configure: (ShimmerReverbPedal) -> Void
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.2
|
||||
let numAudioBuses: Int = 64
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: renderDuration,
|
||||
numAudioBuses: numAudioBuses
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer {
|
||||
engine.busAllocator.releaseAudioBus(srcBus)
|
||||
engine.busAllocator.releaseAudioBus(dstBus)
|
||||
}
|
||||
|
||||
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
|
||||
let pedal: ShimmerReverbPedal = ShimmerReverbPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
configure(pedal)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
|
||||
try engine.add(source)
|
||||
try engine.add(pedal, position: NodePosition.after(source))
|
||||
try engine.add(master, position: NodePosition.after(pedal))
|
||||
try engine.start()
|
||||
|
||||
return readStereoCAF(url: url)
|
||||
}
|
||||
|
||||
private func totalSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
zip(a, b).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||
let samples: [Float] = try render { _ in }
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "shimmer reverb output was silent")
|
||||
}
|
||||
|
||||
@Test func shimmerChangesOutput() throws {
|
||||
let none: [Float] = try render { pedal in pedal.shimmer = 0.0; pedal.decay = 0.8; pedal.mix = 1.0 }
|
||||
let glassy: [Float] = try render { pedal in pedal.shimmer = 0.8; pedal.decay = 0.8; pedal.mix = 1.0 }
|
||||
#expect(hasNonSilentOutput(glassy), "shimmered reverb was silent")
|
||||
#expect(totalSSD(none, glassy) > 0, "changing shimmer did not change the output")
|
||||
}
|
||||
|
||||
@Test func exposesSizeDecayShimmerDampKnobs() throws {
|
||||
let pedal: ShimmerReverbPedal = ShimmerReverbPedal()
|
||||
let labels: [String] = pedal.effectKnobs.map { $0.label }
|
||||
#expect(labels == ["Size", "Decay", "Shimmer", "Damp"])
|
||||
}
|
||||
|
||||
@Test func presetRoundTripPreservesKnobs() throws {
|
||||
let pedal: ShimmerReverbPedal = ShimmerReverbPedal()
|
||||
pedal.decay = 0.5
|
||||
pedal.shimmer = 0.7
|
||||
let state: PedalState = pedal.captureState()
|
||||
|
||||
let restored: ShimmerReverbPedal = ShimmerReverbPedal()
|
||||
restored.applyState(state)
|
||||
#expect(restored.decay == 0.5)
|
||||
#expect(restored.shimmer == 0.7)
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Shimmer Reverb")
|
||||
#expect(pedal is ShimmerReverbPedal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
// ShimmerReverbTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@MainActor
|
||||
@Suite("ShimmerReverb")
|
||||
struct ShimmerReverbTests {
|
||||
|
||||
/// Minimal synth: an input source through a `ShimmerReverb`, written to a mono bus.
|
||||
private final class ShimmerSynth: SynthesizerBase {
|
||||
private let oscFreq: Double?
|
||||
private let dc: Double
|
||||
private let size: Double
|
||||
private let decay: Double
|
||||
private let shimmer: Double
|
||||
private let outBus: Int
|
||||
|
||||
init(oscFreq: Double?, dc: Double, size: Double, decay: Double, shimmer: Double, outBus: Int) {
|
||||
self.oscFreq = oscFreq
|
||||
self.dc = dc
|
||||
self.size = size
|
||||
self.decay = decay
|
||||
self.shimmer = shimmer
|
||||
self.outBus = outBus
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
let source: any ValidGeneratorInput = oscFreq.map { OscSin.Audio(freq: $0) } ?? dc
|
||||
output(bus: outBus, source: ShimmerReverb(
|
||||
input: source,
|
||||
maxDelay: 0.12,
|
||||
size: size,
|
||||
decay: decay,
|
||||
shimmer: shimmer,
|
||||
damp: 0.4,
|
||||
sampleRate: 44100.0
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
private func render(
|
||||
oscFreq: Double?,
|
||||
dc: Double,
|
||||
size: Double = 0.05,
|
||||
decay: Double,
|
||||
shimmer: Double
|
||||
) throws -> [Float] {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, sampleRate: 44100.0)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer { engine.busAllocator.releaseAudioBus(dstBus) }
|
||||
let synth: ShimmerSynth = ShimmerSynth(
|
||||
oscFreq: oscFreq, dc: dc, size: size, decay: decay, shimmer: shimmer, outBus: dstBus.index
|
||||
)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
try engine.add(synth)
|
||||
try engine.add(master, position: NodePosition.after(synth))
|
||||
try engine.start()
|
||||
return readStereoCAF(url: url, sampleRate: 44100.0)
|
||||
}
|
||||
|
||||
private func totalSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
zip(a, b).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func silentInputProducesSilence() throws {
|
||||
// No input energy → the feedback loop has nothing to sustain → output stays at zero.
|
||||
let samples: [Float] = try render(oscFreq: nil, dc: 0.0, decay: 0.9, shimmer: 0.8)
|
||||
#expect(!hasNonSilentOutput(samples), "shimmer reverb rang with no input")
|
||||
}
|
||||
|
||||
@Test func passesDCWithUnityGainAndLinearScaling() throws {
|
||||
// With decay = shimmer = damp = 0, the tank is just the input through two Schroeder
|
||||
// allpasses (unity at DC steady state) delayed by `size`. The output is therefore a fixed
|
||||
// gain (the harness output gain/pan) times the DC input — exactly linear. Compare two DC
|
||||
// levels at a settled frame so the harness scale cancels: the ratio must be 2.0.
|
||||
let high: [Float] = try render(oscFreq: nil, dc: 1.0, size: 0.01, decay: 0.0, shimmer: 0.0)
|
||||
let low: [Float] = try render(oscFreq: nil, dc: 0.5, size: 0.01, decay: 0.0, shimmer: 0.0)
|
||||
let frame: Int = 1500 // past the size delay + allpass settling, within the read window
|
||||
let h: Double = Double(high[frame * 2])
|
||||
let l: Double = Double(low[frame * 2])
|
||||
#expect(abs(h) > 1e-3, "settled DC output should be non-zero")
|
||||
#expect(abs(h / l - 2.0) < 0.01, "DC gain should be exactly linear (ratio 2.0)")
|
||||
}
|
||||
|
||||
@Test func decayChangesTheTail() throws {
|
||||
// Small tank so feedback round-trips compound within the reader's window; different decay
|
||||
// must change the tail (direction-agnostic — a tuned comb is not monotonic in level).
|
||||
let low: [Float] = try render(oscFreq: 440.0, dc: 0.0, size: 0.01, decay: 0.1, shimmer: 0.0)
|
||||
let high: [Float] = try render(oscFreq: 440.0, dc: 0.0, size: 0.01, decay: 0.9, shimmer: 0.0)
|
||||
#expect(hasNonSilentOutput(high), "decayed tail was silent")
|
||||
#expect(totalSSD(low, high) > 0, "changing decay did not change the tail")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// VibratoPedalTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@MainActor
|
||||
@Suite("VibratoPedal")
|
||||
struct VibratoPedalTests {
|
||||
|
||||
private func render(
|
||||
configure: (VibratoPedal) -> Void
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.2
|
||||
let numAudioBuses: Int = 64
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: renderDuration,
|
||||
numAudioBuses: numAudioBuses
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer {
|
||||
engine.busAllocator.releaseAudioBus(srcBus)
|
||||
engine.busAllocator.releaseAudioBus(dstBus)
|
||||
}
|
||||
|
||||
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
|
||||
let pedal: VibratoPedal = VibratoPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
configure(pedal)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
|
||||
try engine.add(source)
|
||||
try engine.add(pedal, position: NodePosition.after(source))
|
||||
try engine.add(master, position: NodePosition.after(pedal))
|
||||
try engine.start()
|
||||
|
||||
return readStereoCAF(url: url)
|
||||
}
|
||||
|
||||
private func windowedSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
let skipSamples: Int = 2048
|
||||
let windowSize: Int = 2048
|
||||
guard a.count >= skipSamples + windowSize,
|
||||
b.count >= skipSamples + windowSize else { return 0.0 }
|
||||
let aWindow: ArraySlice<Float> = a[skipSamples..<(skipSamples + windowSize)]
|
||||
let bWindow: ArraySlice<Float> = b[skipSamples..<(skipSamples + windowSize)]
|
||||
return zip(aWindow, bWindow).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||
let samples: [Float] = try render { _ in }
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "vibrato output was silent")
|
||||
}
|
||||
|
||||
@Test func depthChangesOutput() throws {
|
||||
let shallow: [Float] = try render { pedal in pedal.depth = 0.0006 }
|
||||
let deep: [Float] = try render { pedal in pedal.depth = 0.006 }
|
||||
#expect(hasNonSilentOutput(deep), "deep vibrato was silent")
|
||||
#expect(windowedSSD(shallow, deep) > 0, "changing depth did not change the output")
|
||||
}
|
||||
|
||||
@Test func exposesRateDepthKnobs() throws {
|
||||
let pedal: VibratoPedal = VibratoPedal()
|
||||
let labels: [String] = pedal.effectKnobs.map { $0.label }
|
||||
#expect(labels == ["Rate", "Depth"])
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Vibrato")
|
||||
#expect(pedal is VibratoPedal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
# 1.2 New Pedals — Plan
|
||||
|
||||
Eight pedals targeted for 1.2 (Wah deferred — pending MIDI-control hardware). Grounded against the
|
||||
Lyrebird generators actually available. Each entry lists the signal path, the generators used,
|
||||
controls, channel kind, the per-pedal checklist (registry / `PedalType` / enclosure color / palette
|
||||
order / tests), and effort.
|
||||
|
||||
Effort legend: **S** = thin wrapper over existing generators; **M** = composite graph; **L** =
|
||||
needs a new RT-safe generator first.
|
||||
|
||||
Build order recommendation: Flanger → Vibrato → Distortion → Harmonizer → Rotary → Shimmer Reverb →
|
||||
Reverse Delay → Bitcrusher. (Cheap/whole-cloth-available first; new-generator pedals last.)
|
||||
|
||||
---
|
||||
|
||||
## 1. Flanger — **S**
|
||||
|
||||
Lyrebird already ships `Flanger.Audio(input:delayTime:depth:rate:feedback:mix:sampleRate:maxDelayTime:)`.
|
||||
Thin wrapper like `ModulationPedal`.
|
||||
|
||||
- **Path:** `dry → Flanger.Audio → wet` (base `mix`/`level`/bypass handle blend).
|
||||
- **Controls (knobs):** Rate (0.05–8 Hz), Depth (0–1), Feedback (0–0.95), Manual/center delay
|
||||
(0.001–0.01 s, optional). Mix inherited.
|
||||
- **Channel:** `.processor` (mono). A stereo `.widener` variant (two LFOs anti-phase, like
|
||||
`ChorusPedal`) is a nice follow-up but not required.
|
||||
- **Effort:** S.
|
||||
|
||||
## 2. Vibrato — **S**
|
||||
|
||||
Pitch wobble = a single swept delay line, fully wet (no dry blend). Mirrors `ChorusPedal.voice` but
|
||||
`initialMix = 1.0` and one voice.
|
||||
|
||||
- **Path:** `dry → DelayLine(delay: OscSin(rate, mul: depth, add: base)) → wet`, `mix = 1.0`.
|
||||
- **Controls:** Rate (0.1–8 Hz), Depth (0.0005–0.006 s). (Expose Depth as "Depth"; keep mix locked
|
||||
fully wet — vibrato is not a blend effect.)
|
||||
- **Channel:** `.processor`.
|
||||
- **Effort:** S. Distinct from Tremolo (amplitude) — document the difference in `summary`.
|
||||
|
||||
## 3. Distortion — **S**
|
||||
|
||||
Mid-gain clipper between Overdrive (soft) and Fuzz (extreme). Reuse the `Tanh.Audio` drive trick
|
||||
from `BassOctaverPedal`, plus a tone tilt and output clamp.
|
||||
|
||||
- **Path:** `dry → HPF(~80) → Tanh(mul: drive) → tone (RBJLowPass, freq from Tone knob) → Clip(-1,1)
|
||||
→ wet`. (Optionally `Waveshaper` with a fixed asymmetric table for more character.)
|
||||
- **Controls:** Drive (1–50), Tone (500–6000 Hz), Level (inherited). Mix default 1.0.
|
||||
- **Channel:** `.processor`.
|
||||
- **Effort:** S. Pick clipping flavor at impl: `Tanh` (smooth), `Clip` (hard), or `Fold` (octave-y).
|
||||
Recommend `Tanh` → `Clip` cascade.
|
||||
|
||||
## 4. Harmonizer — **M** (user priority)
|
||||
|
||||
Two pitch-shifted harmony voices at **fixed, user-picked interval ratios**, mixed under the dry
|
||||
signal. Uses `PitchShift.Audio` (granular, real-time, mono, `pitchRatio` clamped 0.25–4.0).
|
||||
|
||||
- **Path:**
|
||||
```
|
||||
dry ─┬───────────────────────────────── direct·directLevel
|
||||
├─ PitchShift(pitchRatio: r1) ····· × voice1Level
|
||||
└─ PitchShift(pitchRatio: r2) ····· × voice2Level → sum
|
||||
```
|
||||
- **Interval ratios:** semitone → ratio `2^(n/12)`. Offer a musical set, e.g.
|
||||
`-12, -7, -5, -3, 0, +3, +4, +5, +7, +12` semitones (octave/5th/4th/3rds). Map each option's
|
||||
`value` to the ratio at build time.
|
||||
- **Controls:**
|
||||
- **Voice 1 Interval** + **Voice 2 Interval** — the "knob pickers" for fixed ratios.
|
||||
- **Voice 1 Level**, **Voice 2 Level**, **Direct** (dry) level knobs (OC-2-style, like
|
||||
`BassOctaverPedal`).
|
||||
- **Picker control (decided):** add a new **`PedalSelectorKnob`** — a knob that snaps to labeled
|
||||
stops. Reusable for future discrete-knob pedals. Interval stops must include minor- and major-3rd
|
||||
**above and below**: `-12, -7, -5, -4, -3, 0, +3, +4, +5, +7, +12` semitones (m3 = ±3, M3 = ±4,
|
||||
P4 = ±5, P5 = ±7, octave = ±12, 0 = unison/off). Each stop's value maps to ratio `2^(n/12)`.
|
||||
Default voices: Voice 1 = +4 (M3 up), Voice 2 = +7 (P5 up).
|
||||
- **Channel:** `.processor` (sum to mono). Optional `.widener` (pan the two voices L/R) as a follow-up.
|
||||
- **Effort:** M. Watch granular latency/CPU with two `PitchShift` instances; verify under the
|
||||
512-block engine. Consider `windowSize` tuning per voice for smoothness.
|
||||
|
||||
## 5. Rotary / Leslie — **M**
|
||||
|
||||
Leslie = amplitude modulation (volume throb) + frequency modulation (Doppler pitch wobble) +
|
||||
stereo spread, with a two-speed (Chorale/Tremolo) ramp.
|
||||
|
||||
- **Path (per channel, `.widener`):**
|
||||
`dry → DelayLine(delay: OscSin(rate, mul: depth, add: base)) → ×(0.5 + 0.5·OscSin(rate, phase))`,
|
||||
left/right LFOs offset (≈180°) for rotating stereo image. AM and FM share the rotor `rate`.
|
||||
- **Controls:** Speed switch (Chorale ≈0.8 Hz / Tremolo ≈6.5 Hz) via `PedalSwitch`; **Accel** knob
|
||||
(ramp time between speeds); **Depth**/**Mix**. Acceleration ramp = a `Lag`/`Decay` on the rate
|
||||
target so speed changes glide (authentic spin-up/down).
|
||||
- **Alternative:** `PanAzDistance.Audio` gives real Doppler but outputs 4 channels — would need a
|
||||
4→2 downmix; the LFO-AM+FM approach above stays stereo and is simpler. Recommend the simple path
|
||||
for 1.2.
|
||||
- **Channel:** `.widener`.
|
||||
- **Effort:** M.
|
||||
|
||||
## 6. Shimmer Reverb — **M** (with caveat)
|
||||
|
||||
Octave-up sparkle over a reverb tail. Built on an existing reverb (`PlateReverb` or `GVerb`) plus
|
||||
`PitchShift(pitchRatio: 2.0)`.
|
||||
|
||||
- **Caveat — no true regeneration:** Lyrebird's per-synth graph is an acyclic DAG, so a real
|
||||
*regenerating* shimmer feedback loop (tail → pitch-up → back into tail) isn't expressible inside
|
||||
one pedal. For 1.2 ship the **parallel** approximation:
|
||||
```
|
||||
dry ─┬─ Reverb ───────────────── tail
|
||||
└─ PitchShift(×2) → Reverb → shimmer → blend
|
||||
```
|
||||
This gives the shimmer character without infinite regeneration. True regenerative shimmer needs a
|
||||
bus-feedback structure (cross-block) or a new feedback-capable generator — note as a future item.
|
||||
- **Controls:** Room/Decay, Shimmer amount (pitch-voice level), Damp, Mix.
|
||||
- **Channel:** `.widener` (reverbs output stereo — keep L/R).
|
||||
- **Effort:** M. Confirm which reverb `ReverbPedal` already uses to avoid duplication; pick the other
|
||||
(or add an algorithm switch).
|
||||
|
||||
## 7. Reverse Delay — **L** (needs new generator)
|
||||
|
||||
No reverse-capable delay exists in Lyrebird. Add a new RT-safe generator (in ShoeGaze, or upstream
|
||||
in Lyrebird Delays).
|
||||
|
||||
- **New generator `ReverseDelay`:** pre-allocated segment buffer (max length fixed at init, no RT
|
||||
alloc); record forward into a segment, play it back reversed; segment length = delay time;
|
||||
optional feedback. Crossfade at segment boundaries to avoid clicks. Follow Lyrebird generator
|
||||
rules (`GeneratorBase`, `_checkCount`, pre-allocated buffers, no RT alloc/locks).
|
||||
- **Pedal path:** `dry → ReverseDelay(time, feedback) → wet`.
|
||||
- **Controls:** Time (0.05–2 s), Feedback (0–0.9), Mix.
|
||||
- **Channel:** `.processor`.
|
||||
- **Effort:** L (generator + tests first, then the thin pedal). Run `lyrebird_external_review` on the
|
||||
new generator for RT safety.
|
||||
|
||||
## 8. Bitcrusher / Lo-Fi — **L** (needs new generators)
|
||||
|
||||
No decimation/bit-reduction generators exist. Add two small RT-safe generators.
|
||||
|
||||
- **New generators:**
|
||||
- `SampleRateDecimate` — sample-and-hold at a reduced rate (hold last sample for N input samples;
|
||||
rate or downsample-factor parameter).
|
||||
- `BitReduce` — quantize amplitude to `2^bits` levels.
|
||||
(Both trivial per-sample math, pre-allocated state only.)
|
||||
- **Pedal path:** `dry → SampleRateDecimate(rate) → BitReduce(bits) → (optional RBJLowPass tone) →
|
||||
wet`.
|
||||
- **Controls:** Sample Rate / Downsample (knob), Bits (1–16, stepped), Tone, Mix.
|
||||
- **Channel:** `.processor`.
|
||||
- **Effort:** L (two generators + tests, then pedal). Consider contributing the generators upstream
|
||||
to Lyrebird since they're broadly useful.
|
||||
|
||||
---
|
||||
|
||||
## Cross-cutting checklist (every pedal)
|
||||
|
||||
Per `CLAUDE.md` "Adding a new pedal":
|
||||
1. `Sources/LyrebirdShoeGaze/Pedals/<Name>Pedal.swift` — subclass `Pedal`, override `effect`/
|
||||
`wideEffect`, `effectKnobs`/`effectSwitches`/`effectSliders`.
|
||||
2. **`summary`** (mandatory, one line).
|
||||
3. Register in `PedalRegistry.builtIn["<DisplayName>"]`.
|
||||
4. Add `PedalType.<name>`.
|
||||
5. Enclosure color in `PedalView.enclosureColor(for:)`.
|
||||
6. Add to `PedalPaletteView.preferredOrder` (group with family: gain near Overdrive/Fuzz; modulation
|
||||
near Chorus/Phaser; pitch near the octavers; delay/reverb near their families).
|
||||
7. Tests in `Tests/LyrebirdShoeGazeTests/<Name>PedalTests.swift` — builds + non-silent, each param
|
||||
measurably changes output, knob/switch list assertions, preset round-trip if it has
|
||||
switches/sliders.
|
||||
8. Use `PedalType` static members at call sites.
|
||||
|
||||
## Shimmer scope (true regenerative) — findings
|
||||
|
||||
Investigated the regenerative path. The per-pedal graph is acyclic; the only feedback mechanisms in
|
||||
Lyrebird are (a) generators that close their own loop internally (`DelayLineFeedback`, the reverbs)
|
||||
and (b) cross-block bus read/write. Pedals use inherited `input(bus:)` / `output(bus:)` In/Out
|
||||
nodes, but **no pedal allocates an internal scratch/feedback bus** — there's no precedent or
|
||||
lifecycle hook for that. A bus-feedback shimmer would mean new pedal infrastructure (allocate +
|
||||
release an internal feedback bus, ordered Out→In with a one-block delay) — fragile and off-pattern.
|
||||
|
||||
**Conclusion:** true regenerative shimmer is best built as a **new closed-loop generator**
|
||||
(`ShimmerReverb`) that holds a reverb + an in-loop pitch-shift + damped feedback internally, the same
|
||||
way `DelayLineFeedback` contains its own feedback. That's a substantial RT-safe DSP generator
|
||||
(pre-allocated buffers, denormal guards, feedback clamp for stability, granular/FFT pitch latency in
|
||||
the loop) — larger than Reverse Delay or Bitcrush, and needing its own stability tuning + RT review.
|
||||
|
||||
**Recommendation:** build Reverse Delay and Bitcrusher first (self-contained), then take
|
||||
`ShimmerReverb` as its own focused task. If it proves too large for the 1.2 window, ship the
|
||||
parallel-pitch-into-reverb approximation for 1.2 and schedule the regenerative generator for 1.3.
|
||||
**Decision pending:** regenerative `ShimmerReverb` now, or parallel approximation for 1.2 + defer.
|
||||
|
||||
## Decisions (resolved)
|
||||
|
||||
- **Harmonizer picker:** new `PedalSelectorKnob` (stepped knob) with the ±3rd interval set above.
|
||||
Build the Harmonizer first to evaluate the control.
|
||||
- **New generators (Reverse Delay, Bitcrush):** land in the **ShoeGaze package** (self-contained;
|
||||
no Lyrebird-release dependency for 1.2).
|
||||
- **Shimmer:** built the **true regenerative** version — a new closed-loop `ShimmerReverb`
|
||||
generator (damped feedback tank + in-loop two-grain Hann octave-up reader + Schroeder input
|
||||
diffusion + safety clamp), not the parallel approximation. `ShimmerReverbPedal` wraps it
|
||||
(Size/Decay/Shimmer/Damp). Mono generator; a stereo widener variant is a possible follow-up.
|
||||
Needs an ear/tuning pass on a device (built without audio audition).
|
||||
Reference in New Issue
Block a user