Files
Lyrebird/Sources/Lyrebird/Generators/Delays/DelayLineFeedback.swift
T
josh f8878324fd v2.1.1 release: delay-click fix + internal consolidation
Mirror of Lyrebird dev HEAD (9f791c7c) minus maintainer-only paths. Patch release:
fixes the allpass fractional-delay click (DelayLine/CombFilter/AllpassFilter/
DelayLineFeedback under a modulated delay) and lands the internal code-quality
consolidation pass (~160 deduped sites + shared base classes/helpers, bit-identical
output). No public API removed or changed. See RELEASES.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-07 21:20:49 -07:00

324 lines
16 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.
// DelayLineFeedback.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Delay line with feedback, decay time, and selectable interpolation.
///
/// The feedback coefficient is computed from `decayTime` and `targetAmp` using:
/// ```
/// feedback = exp(log(targetAmp) × delay / decayTime)
/// ```
/// This gives the amplitude attenuation per delay-time period that causes the signal
/// to reach `targetAmp` after `decayTime` seconds of decay.
///
/// Each sample, the buffer is written with `input + feedback × delayed`, and the output
/// is the delayed signal before feedback is applied (delays output, not fed-back output).
///
/// **Stability:** Feedback magnitude is clamped to < 1.0 internally to prevent runaway.
///
/// **Sample-rate note:** `maxDelay` is sized using the `sampleRate` passed at init.
/// `calculatedSamples` reads the live rate from `graph.engine.sampleRate` each block so
/// delay times remain correct even when the constructor default is left at 44100.
/// The `sampleRate` init parameter only affects buffer allocation — set it to match the
/// engine's rate so the buffer is never undersized.
///
/// ## RT-allocation model
///
/// Buffer and `_result` allocated in `init`. No allocation in `calculatedSamples`.
///
/// ## Interpolation modes
///
/// | Mode | Quality | CPU |
/// |---|---|---|
/// | `.none` | Lowest — integer steps, aliasing on modulation | Lowest |
/// | `.linear` | Good for most uses | Low |
/// | `.cubic` | Smooth pitch-shifting / chorus | Moderate |
/// | `.allpass` | Phase-preserving fractional delay | Moderate |
///
/// ## Usage
/// ```swift
/// DelayLineFeedback(input: sig, maxDelay: 1.0, delay: 0.25,
/// decayTime: 2.0, targetAmp: 0.001, sampleRate: 44100)
/// DelayLineFeedback(input: sig, maxDelay: 1.0, delay: modLFO,
/// decayTime: 2.0, interpolation: .cubic, sampleRate: 44100)
/// ```
///
/// - Parameters:
/// - input: Input signal.
/// - maxDelay: Maximum delay in seconds. Used to size the circular buffer at init.
/// - delay: Delay time in seconds. Any `ValidGeneratorInput`.
/// - decayTime: Time for the signal to reach `targetAmp` level.
/// - targetAmp: Target amplitude at end of `decayTime`. Defaults to 0.001 (−60 dB).
/// - sampleRate: Sample rate used to size the buffer. Must be ≥ the engine's rate to
/// avoid buffer undersize. Defaults to 44100.
/// - interpolation: Buffer read interpolation mode. Defaults to `.linear`.
/// - mul: Output multiplier applied after synthesis. Defaults to `1.0`.
/// - add: Offset added after multiplier. Defaults to `0.0`.
public final class DelayLineFeedback: GeneratorBase, AudioGenerator {
private let inputSource: any ValidGeneratorInput
private let delayInput: any ValidGeneratorInput
private let decayTimeInput: any ValidGeneratorInput
private let targetAmpInput: any ValidGeneratorInput
private let interpolation: DelayInterpolation
/// True when `delay` was supplied as a `Generator` at init — set once, never mutated.
/// When true, `_computeSamples` reads delay time per sample from `calculatedSamples`.
private let delayIsGenerator: Bool
/// True when `decayTime` or `targetAmp` was supplied as a `Generator` at init.
/// When true, `_computeSamples` reads the last sample of their block (captures ramps).
private let decayTimeIsGenerator: Bool
private let targetAmpIsGenerator: Bool
private var buffer: [Double]
private let bufferMask: Int
private var writePos: Int = 0
private let maxDelaySamples: Int
/// Allpass interpolator state — persists across samples when interpolation == .allpass.
private var allpassPrevOut: Double = 0
// Cached feedback coefficient — recomputed only when inputs change.
private var _cachedFeedback: Double = 0.0
private var _prevDelaySecs: Double = -1.0
private var _prevDecayTime: Double = -1.0
private var _prevTargetAmp: Double = -1.0
// MARK: - Fan-out cache (Generator protocol requirements)
private let _mulAdd: MulAddSpec
/// - Parameters:
/// - input: Input signal.
/// - maxDelay: Maximum delay in seconds. Used to size the circular buffer at init.
/// - delay: Delay time in seconds. Any `ValidGeneratorInput`.
/// - decayTime: Time for the signal to reach `targetAmp` level.
/// - targetAmp: Target amplitude at end of `decayTime`. Defaults to 0.001 (−60 dB).
/// - sampleRate: Sample rate used to size the buffer. Must be ≥ the engine's rate to
/// avoid buffer undersize. Defaults to 44100.
/// - interpolation: Buffer read interpolation mode. Defaults to `.linear`.
/// - mul: Output multiplier applied after synthesis. Defaults to `1.0`.
/// - add: Offset added after multiplier. Defaults to `0.0`.
public init(
input: any ValidGeneratorInput,
maxDelay: Double,
delay: any ValidGeneratorInput,
decayTime: any ValidGeneratorInput,
targetAmp: any ValidGeneratorInput = 0.001 as Double,
sampleRate: Double = 44100,
interpolation: DelayInterpolation = .linear,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
let resolvedDelay: any ValidGeneratorInput = delay._resolvedInput()
let resolvedDecayTime: any ValidGeneratorInput = decayTime._resolvedInput()
let resolvedTargetAmp: any ValidGeneratorInput = targetAmp._resolvedInput()
self.inputSource = resolvedInput
self.delayInput = resolvedDelay
self.decayTimeInput = resolvedDecayTime
self.targetAmpInput = resolvedTargetAmp
self.interpolation = interpolation
self.delayIsGenerator = resolvedDelay is any Generator
self.decayTimeIsGenerator = resolvedDecayTime is any Generator
self.targetAmpIsGenerator = resolvedTargetAmp is any Generator
let maxSamples: Int = Int(ceil(maxDelay * sampleRate)) + 1
let bufSize: Int = lyrebirdNextPowerOfTwo(max(maxSamples, 2))
self.buffer = [Double](repeating: 0, count: bufSize)
self.bufferMask = bufSize - 1
self.maxDelaySamples = maxSamples - 1
self._mulAdd = MulAddSpec(mul: mul, add: add)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
guard count > 0 else { return _result }
let inputSamples: [[Double]] = inputSource.calculatedSamples(graph: graph, count: count)
let inputBlock: [Double] = inputSamples.first ?? []
// Read live sample rate from the engine — correct even when the constructor
// default (44100) differs from the engine's actual rate.
let engineSampleRate: Double = graph.engine.sampleRate
// Feedback topology requires at least 1 sample of delay — a zero-sample delay would
// read the slot about to be overwritten (undefined). Cubic/allpass need ≥1 for
// look-behind too, so 1.0 is the universal floor for DelayLineFeedback.
let minDelay: Double = 1.0
// Fetch per-sample delay block when delay is a generator; otherwise read scalar once.
let delaySamplesArr: [Double]? = delayIsGenerator
? delayInput.calculatedSamples(graph: graph, count: count).first
: nil
// floatValue gives the nominal delay in seconds — used for feedback coefficient
// even when delay is modulated (generator input), matching the common chorus/flanger
// convention of deriving feedback from the center delay time.
let nominalDelaySecs: Double = delayInput.floatValue(graph: graph)
let scalarDelaySamples: Double
if delaySamplesArr == nil {
let raw: Double = nominalDelaySecs * engineSampleRate
scalarDelaySamples = max(minDelay, min(raw, Double(maxDelaySamples)))
} else {
scalarDelaySamples = 0
}
// Read decayTime and targetAmp: when backed by a Generator, take the last sample of
// the block (captures any ramp); otherwise use floatValue.
let decayTime: Double = lastGeneratorSampleOrFloat(
decayTimeInput, isGenerator: decayTimeIsGenerator, graph: graph, count: count)
let targetAmp: Double = lastGeneratorSampleOrFloat(
targetAmpInput, isGenerator: targetAmpIsGenerator, graph: graph, count: count)
// feedback = exp(log(targetAmp) × delay / decayTime)
// Recompute only when inputs change — avoids exp()/log() on every block.
if nominalDelaySecs != _prevDelaySecs || decayTime != _prevDecayTime || targetAmp != _prevTargetAmp {
let maxStableFeedback: Double = 0.9999
if decayTime > 0 && targetAmp > 0 && nominalDelaySecs > 0 {
let raw: Double = exp(log(targetAmp) * nominalDelaySecs / decayTime)
_cachedFeedback = min(abs(raw), maxStableFeedback)
} else {
_cachedFeedback = 0.0
}
_prevDelaySecs = nominalDelaySecs
_prevDecayTime = decayTime
_prevTargetAmp = targetAmp
}
let feedback: Double = _cachedFeedback
// Hoist block-invariant state and pointers; specialize per
// interpolation mode outside the per-sample loop. `bufferMask = bufSize - 1`
// so `idx & bufferMask` is the canonical fast wrap on the PoT ring.
let inputCount: Int = inputBlock.count
let maskLocal: Int = bufferMask
let maxDelayF: Double = Double(maxDelaySamples)
let interp: DelayInterpolation = interpolation
var writePosLocal: Int = writePos
var apPrev: Double = allpassPrevOut
buffer.withUnsafeMutableBufferPointer { (buf: inout UnsafeMutableBufferPointer<Double>) in
guard let bufP: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
inputBlock.withUnsafeBufferPointer { (src: UnsafeBufferPointer<Double>) in
guard let srcP: UnsafePointer<Double> = src.baseAddress else { return }
@inline(__always)
func resolveDelay(_ i: Int) -> Double {
if let arr: [Double] = delaySamplesArr {
let raw: Double = (i < arr.count ? arr[i] : 0) * engineSampleRate
return max(minDelay, min(raw, maxDelayF))
}
return scalarDelaySamples
}
switch interp {
case .none:
for i: Int in 0..<count {
let d: Double = resolveDelay(i)
let intD: Int = Int(d)
let delayed: Double = bufP[(writePosLocal - intD) & maskLocal]
let x: Double = sampleOrZero(srcP, i, inputCount)
bufP[writePosLocal & maskLocal] = denormalsToZero(x + feedback * delayed)
dstP[i] = delayed
writePosLocal = (writePosLocal + 1) & maskLocal
}
case .linear:
for i: Int in 0..<count {
let d: Double = resolveDelay(i)
let intD: Int = Int(d)
let frac: Double = d - Double(intD)
let y0: Double = bufP[(writePosLocal - intD) & maskLocal]
let y1: Double = bufP[(writePosLocal - intD - 1) & maskLocal]
let delayed: Double = y0 * (1.0 - frac) + y1 * frac
let x: Double = sampleOrZero(srcP, i, inputCount)
bufP[writePosLocal & maskLocal] = denormalsToZero(x + feedback * delayed)
dstP[i] = delayed
writePosLocal = (writePosLocal + 1) & maskLocal
}
case .cubic:
for i: Int in 0..<count {
let d: Double = resolveDelay(i)
let intD: Int = Int(d)
let frac: Double = d - Double(intD)
let y0: Double = bufP[(writePosLocal - intD + 1) & maskLocal]
let y1: Double = bufP[(writePosLocal - intD) & maskLocal]
let y2: Double = bufP[(writePosLocal - intD - 1) & maskLocal]
let y3: Double = bufP[(writePosLocal - intD - 2) & maskLocal]
let delayed: Double = DelayLineFeedback.cubicInterpStatic(
frac: frac, y0: y0, y1: y1, y2: y2, y3: y3
)
let x: Double = sampleOrZero(srcP, i, inputCount)
bufP[writePosLocal & maskLocal] = denormalsToZero(x + feedback * delayed)
dstP[i] = delayed
writePosLocal = (writePosLocal + 1) & maskLocal
}
case .allpass:
for i: Int in 0..<count {
let d: Double = resolveDelay(i)
let intD: Int = Int(d)
let frac: Double = d - Double(intD)
let yn: Double = bufP[(writePosLocal - intD) & maskLocal]
let delayed: Double
if frac > 0 {
let eta: Double = (1.0 - frac) / (1.0 + frac)
let ynm1: Double = bufP[(writePosLocal - intD - 1) & maskLocal]
let out: Double = eta * (yn - apPrev) + ynm1
apPrev = out
delayed = out
} else {
// frac == 0: the output is exactly the integer-delayed sample,
// so the allpass interpolator's output here IS yn. Record that
// as its previous output. Zeroing apPrev clicks when a modulated
// delay crosses an integer boundary; freezing the old value
// clicks when the delay dwells on an integer and then moves off.
// apPrev = yn tracks the true state and stays click-free in both.
apPrev = yn
delayed = yn
}
let x: Double = sampleOrZero(srcP, i, inputCount)
bufP[writePosLocal & maskLocal] = denormalsToZero(x + feedback * delayed)
dstP[i] = delayed
writePosLocal = (writePosLocal + 1) & maskLocal
}
}
}
}
}
writePos = writePosLocal
allpassPrevOut = apPrev
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
// MARK: - Private
/// Catmull-Rom cubic interpolation (delegates to the shared `catmullRomCubic`)
/// — static so the per-sample inner loop can call it without a method-dispatch
/// frame on `self`.
@inline(__always)
fileprivate static func cubicInterpStatic(
frac: Double,
y0: Double, y1: Double,
y2: Double, y3: Double
) -> Double {
catmullRomCubic(y0, y1, y2, y3, t: frac)
}
}
// MARK: - GeneratorEnum
// `GeneratorEnum` conformance is intentionally omitted — this is an Audio-only
// generator with no paired `Control` variant.