Files
Lyrebird/Sources/Lyrebird/Generators/Reverb/FreeVerb.swift
T

292 lines
12 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// FreeVerb.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// MARK: - FreeVerb constants
/// Standard Freeverb comb delay lengths at 44100 Hz (left channel).
private let freeVerbCombSizesBase: [Int] = [1116, 1188, 1277, 1356, 1422, 1491, 1557, 1617]
/// Standard Freeverb allpass delay lengths at 44100 Hz.
private let freeVerbAllpassSizesBase: [Int] = [556, 441, 341, 225]
/// Reference sample rate for the standard Freeverb tuning constants.
/// `public` (not `private`) because Swift requires default argument values of a `public init`
/// to be at least as accessible as the function itself.
public let freeVerbReferenceSampleRate: Double = 44100.0
/// Pre-gain applied to mono input before the comb filter bank (Jezar's original value).
private let freeVerbFixedGain: Double = 0.015
/// Allpass feedback coefficient (Jezar's original value).
private let freeVerbAllpassFeedback: Double = 0.5
/// Minimum comb filter feedback at roomSize = 0.
private let freeVerbFeedbackMin: Double = 0.7
/// Comb filter feedback range: feedback = roomSize × freeVerbFeedbackRange + freeVerbFeedbackMin.
private let freeVerbFeedbackRange: Double = 0.28
/// Maps damping [0, 1] into the one-pole LP coefficient; `damp1 = damping × scale`.
private let freeVerbDampingScale: Double = 0.4
/// Default wet/dry mix (Jezar's original value).
private let freeVerbDefaultMix: Double = 0.33
/// Default L/R stereo detuning in samples (Jezar's original value). Not scaled with sampleRate.
/// `public` because it is used as a default argument value in the `public init`.
public let freeVerbDefaultSpread: Int = 23
// MARK: - FreeVerb
public enum FreeVerb {
/// Stereo reverb using the Freeverb algorithm (Jezar at Dreampoint, public domain).
///
/// Mono input → two-channel stereo output (channel 0 = left, channel 1 = right).
/// Architecture: 8 parallel filtered-feedback comb filters → 4 series allpass filters,
/// per channel. Left and right are detuned by `spread` samples for stereo width.
///
/// ## Multi-channel output
///
/// `FreeVerb` produces two output channels. Pass it directly to `output(bus:source:)`:
///
/// ```swift
/// override func build() {
/// let src = OscSin.Audio(freq: 220.0)
/// output(bus: 0, source: FreeVerb(source: src, roomSize: 0.8, mix: 0.4))
/// }
/// ```
///
/// Or extract individual channels:
///
/// ```swift
/// let verb = FreeVerb(source: sig, roomSize: 0.7, damping: 0.4, mix: 0.35)
/// output(bus: 0, source: verb.left)
/// output(bus: 1, source: verb.right)
/// ```
///
/// ## Parameters
///
/// All continuous parameters are **silently clamped** to their valid range at block rate.
/// Values outside the range produce the same result as the nearest boundary — passing
/// `roomSize: 2.0` sounds identical to `roomSize: 1.0`, passing `damping: -1.0` sounds
/// identical to `damping: 0.0`, etc. No error or warning is raised.
///
/// - `roomSize`: Room size in [0, 1]. Maps internally to feedback in [0.7, 0.98].
/// Larger values → longer tails. Values outside [0, 1] are clamped.
/// - `damping`: High-frequency absorption in [0, 1]. Higher values → darker, shorter
/// tails (one-pole LP in each comb filter feedback path). Values outside [0, 1] are clamped.
/// - `mix`: Wet/dry mix in [0, 1]. 0 = fully dry, 1 = fully wet. Values outside [0, 1] are clamped.
/// - `spread`: L/R detuning in samples (fixed at init). Defaults to 23 (Jezar's value).
///
/// ## RT-allocation model
///
/// All comb and allpass circular buffers pre-allocated in `init`.
/// No heap allocation in `_computeSamples`.
///
/// ## Sample-rate note
///
/// Buffer sizes are scaled from the reference 44100 Hz tuning by
/// `floor(size × sampleRate / 44100)`. Pass `sampleRate` at init to match your engine's
/// rate; use `SynthesisEngine.sampleRate` if the rate is known at construction time.
public final class Audio: GeneratorBase, AudioGenerator {
// MARK: - Inputs
private let _source: any ValidGeneratorInput
private let _roomSize: any ValidGeneratorInput
private let _damping: any ValidGeneratorInput
private let _mix: any ValidGeneratorInput
// MARK: - Comb filter state (8 per channel)
private var _combBufL: [[Double]]
private var _combBufR: [[Double]]
private var _combPosL: [Int]
private var _combPosR: [Int]
private var _combStateL: [Double] // one-pole LP filter state per comb
private var _combStateR: [Double]
private let _combSizesL: [Int]
private let _combSizesR: [Int]
// MARK: - Allpass filter state (4 per channel)
private var _apBufL: [[Double]]
private var _apBufR: [[Double]]
private var _apPosL: [Int]
private var _apPosR: [Int]
private let _apSizesL: [Int]
private let _apSizesR: [Int]
// MARK: - Output + fan-out cache
private let _mulAdd: MulAddSpec
// MARK: - Init
/// - Parameters:
/// - source: Mono input signal.
/// - roomSize: Room size in [0, 1]. Defaults to `0.5`.
/// - damping: High-frequency damping in [0, 1]. Defaults to `0.5`.
/// - mix: Wet/dry mix in [0, 1]. Defaults to `0.33`.
/// - spread: L/R detuning in samples (fixed at init). Defaults to `23`.
/// - sampleRate: Engine sample rate used to scale delay buffers. Defaults to `44100`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public init(
source: any ValidGeneratorInput,
roomSize: any ValidGeneratorInput = 0.5,
damping: any ValidGeneratorInput = 0.5,
mix: any ValidGeneratorInput = 0.33, // freeVerbDefaultMix
spread: Int = freeVerbDefaultSpread,
sampleRate: Double = freeVerbReferenceSampleRate,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
let resolvedSource: any ValidGeneratorInput = source._resolvedInput()
let resolvedRoomSize: any ValidGeneratorInput = roomSize._resolvedInput()
let resolvedDamping: any ValidGeneratorInput = damping._resolvedInput()
let resolvedMix: any ValidGeneratorInput = mix._resolvedInput()
_source = resolvedSource
_roomSize = resolvedRoomSize
_damping = resolvedDamping
_mix = resolvedMix
_mulAdd = MulAddSpec(mul: mul, add: add)
let scale: Double = sampleRate / freeVerbReferenceSampleRate
let combL: [Int] = freeVerbCombSizesBase.map { max(1, Int(Double($0) * scale)) }
let combR: [Int] = combL.map { max(1, $0 + spread) }
let apL: [Int] = freeVerbAllpassSizesBase.map { max(1, Int(Double($0) * scale)) }
let apR: [Int] = apL.map { max(1, $0 + spread) }
_combSizesL = combL
_combSizesR = combR
_apSizesL = apL
_apSizesR = apR
_combBufL = combL.map { [Double](repeating: 0, count: $0) }
_combBufR = combR.map { [Double](repeating: 0, count: $0) }
_combPosL = [Int](repeating: 0, count: combL.count)
_combPosR = [Int](repeating: 0, count: combR.count)
_combStateL = [Double](repeating: 0, count: combL.count)
_combStateR = [Double](repeating: 0, count: combR.count)
_apBufL = apL.map { [Double](repeating: 0, count: $0) }
_apBufR = apR.map { [Double](repeating: 0, count: $0) }
_apPosL = [Int](repeating: 0, count: apL.count)
_apPosR = [Int](repeating: 0, count: apR.count)
super.init(channels: 2)
}
public override var outputChannelCount: Int { 2 }
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
let srcSamples: [[Double]] = _source.calculatedSamples(graph: graph, count: count)
let src: [Double] = srcSamples.first ?? []
// Read parameters once per block (control-rate update).
let roomSizeRaw: Double = max(0.0, min(1.0, _roomSize.floatValue(graph: graph)))
let dampRaw: Double = max(0.0, min(1.0, _damping.floatValue(graph: graph)))
let mix: Double = max(0.0, min(1.0, _mix.floatValue(graph: graph)))
// Freeverb feedback: roomSize [0,1] → feedback [freeVerbFeedbackMin, 0.98].
let roomSizeFeedback: Double = roomSizeRaw * freeVerbFeedbackRange + freeVerbFeedbackMin
// One-pole LP coefficients for comb damping (Jezar's assignment):
// damp1 = damping × scale (weight on stored state — more = darker)
// damp2 = 1 − damp1 (weight on new comb output — feeds forward)
// At damping=0: damp1=0, damp2=1 → state = output (no smoothing, full HF).
// At damping=1: damp1=0.4, damp2=0.6 → gentle LP, darker tail.
let damp1: Double = dampRaw * freeVerbDampingScale
let damp2: Double = 1.0 - damp1
let combCount: Int = _combSizesL.count
let allpassCount: Int = _apSizesL.count
let dryComp: Double = 1.0 - mix
for i: Int in 0..<count {
let dry: Double = i < src.count ? src[i] : 0.0
let input: Double = dry * freeVerbFixedGain
// --- 8 parallel comb filters, left ---
var sumL: Double = 0.0
for c: Int in 0..<combCount {
let pos: Int = _combPosL[c]
let out: Double = _combBufL[c][pos]
// Jezar's LP: new_state = out × damp2 + prev_state × damp1
let newState: Double = denormalsToZero(out * damp2 + _combStateL[c] * damp1)
_combStateL[c] = newState
_combBufL[c][pos] = denormalsToZero(input + newState * roomSizeFeedback)
_combPosL[c] = pos + 1 < _combSizesL[c] ? pos + 1 : 0
sumL += out
}
// --- 8 parallel comb filters, right ---
var sumR: Double = 0.0
for c: Int in 0..<combCount {
let pos: Int = _combPosR[c]
let out: Double = _combBufR[c][pos]
let newState: Double = denormalsToZero(out * damp2 + _combStateR[c] * damp1)
_combStateR[c] = newState
_combBufR[c][pos] = denormalsToZero(input + newState * roomSizeFeedback)
_combPosR[c] = pos + 1 < _combSizesR[c] ? pos + 1 : 0
sumR += out
}
// --- 4 series allpass filters, left ---
var apL: Double = sumL
for a: Int in 0..<allpassCount {
let pos: Int = _apPosL[a]
let bufSample: Double = _apBufL[a][pos]
let apOut: Double = -apL + bufSample
_apBufL[a][pos] = denormalsToZero(apL + bufSample * freeVerbAllpassFeedback)
_apPosL[a] = pos + 1 < _apSizesL[a] ? pos + 1 : 0
apL = apOut
}
// --- 4 series allpass filters, right ---
var apR: Double = sumR
for a: Int in 0..<allpassCount {
let pos: Int = _apPosR[a]
let bufSample: Double = _apBufR[a][pos]
let apOut: Double = -apR + bufSample
_apBufR[a][pos] = denormalsToZero(apR + bufSample * freeVerbAllpassFeedback)
_apPosR[a] = pos + 1 < _apSizesR[a] ? pos + 1 : 0
apR = apOut
}
_result[0][i] = mix * apL + dryComp * dry
_result[1][i] = mix * apR + dryComp * dry
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
}
} // enum FreeVerb
// MARK: - Named channel aliases
extension FreeVerb.Audio {
/// Left output channel (channel 0). Equivalent to `self[0]`.
public var left: ChannelSelect.Audio { self[0] }
/// Right output channel (channel 1). Equivalent to `self[1]`.
public var right: ChannelSelect.Audio { self[1] }
}
// MARK: - GeneratorEnum
// `GeneratorEnum` conformance is intentionally omitted — this is an Audio-only
// generator with no paired `Control` variant.