Files
Lyrebird/Sources/Lyrebird/Generators/Delays/DelayLine.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

225 lines
10 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.
// DelayLine.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
// MARK: - DelayLine
/// Variable delay line with no feedback.
///
/// Maintains a circular power-of-2 buffer pre-allocated from `maxDelay` and `sampleRate`
/// at init time. The buffer is never resized at runtime — RT-safe.
///
/// **Delay range:** [0, maxDelay] seconds. Requesting more than `maxDelay` is clamped.
///
/// ## RT-allocation model
///
/// Buffer and `_result` allocated in `init` (main thread). No allocation in
/// `calculatedSamples` once the buffer size is stable.
///
/// ## Usage
/// ```swift
/// DelayLine(input: sig, maxDelay: 1.0, delay: 0.25, sampleRate: 44100)
/// DelayLine(input: sig, maxDelay: 1.0, delay: delayGen, sampleRate: 44100, interpolation: .cubic)
/// ```
public final class DelayLine: GeneratorBase, AudioGenerator {
private let inputSource: any ValidGeneratorInput
private let delayInput: 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
private var buffer: [Double]
private let bufferMask: Int // bufferSize − 1, for fast bitwise modulo
private var writePos: Int = 0
private let maxDelaySamples: Int
/// Allpass interpolator state — persists across samples when interpolation == .allpass.
private var allpassPrevOut: Double = 0
// MARK: - Fan-out cache (Generator protocol requirements)
private let _mulAdd: MulAddSpec
/// - Parameters:
/// - input: Signal to delay.
/// - maxDelay: Maximum delay in seconds. Determines buffer size (rounded up to next power of 2).
/// - delay: Current delay time in seconds. Any `ValidGeneratorInput`.
/// - sampleRate: Sample rate used to convert seconds → samples. Must match the engine's rate.
/// - 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,
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()
self.inputSource = resolvedInput
self.delayInput = resolvedDelay
self.interpolation = interpolation
self.delayIsGenerator = resolvedDelay 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 inputBlock: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
let sampleRate: Double = graph.engine.sampleRate
let minDelay: Double = (interpolation == .cubic || interpolation == .allpass) ? 1.0 : 0.0
// Fetch audio-rate delay block when delay is a generator; otherwise read scalar once.
let delaySamplesArr: [Double]? = delayIsGenerator
? delayInput.calculatedSamples(graph: graph, count: count).first
: nil
let scalarDelaySamples: Double
if delaySamplesArr == nil {
let delaySecs: Double = delayInput.floatValue(graph: graph)
let raw: Double = delaySecs * sampleRate
scalarDelaySamples = max(minDelay, min(raw, Double(maxDelaySamples)))
} else {
scalarDelaySamples = 0
}
// Hoist all block-invariant state and pointers outside the per-sample loop.
// `buffer` is a power-of-2 ring; `bufferMask` is its size − 1, so `idx & bufferMask`
// is the canonical fast wrap (no `%`). State (`writePos`, `allpassPrevOut`) is lifted
// to locals across the block — single read at top, single writeback at bottom.
let inputCount: Int = inputBlock.count
let maskLocal: Int = bufferMask
let interp: DelayInterpolation = interpolation
let maxDelayF: Double = Double(maxDelaySamples)
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) * sampleRate
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)
dstP[i] = bufP[(writePosLocal - intD) & maskLocal]
bufP[writePosLocal & maskLocal] = sampleOrZero(srcP, i, inputCount)
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 i0: Int = (writePosLocal - intD) & maskLocal
let i1: Int = (writePosLocal - intD - 1) & maskLocal
dstP[i] = bufP[i0] * (1.0 - frac) + bufP[i1] * frac
bufP[writePosLocal & maskLocal] = sampleOrZero(srcP, i, inputCount)
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 i0: Int = (writePosLocal - intD + 1) & maskLocal
let i1: Int = (writePosLocal - intD) & maskLocal
let i2: Int = (writePosLocal - intD - 1) & maskLocal
let i3: Int = (writePosLocal - intD - 2) & maskLocal
dstP[i] = DelayLine.cubicInterpStatic(
frac: frac,
y0: bufP[i0], y1: bufP[i1], y2: bufP[i2], y3: bufP[i3]
)
bufP[writePosLocal & maskLocal] = sampleOrZero(srcP, i, inputCount)
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]
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
dstP[i] = 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
dstP[i] = yn
}
bufP[writePosLocal & maskLocal] = sampleOrZero(srcP, i, inputCount)
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.