f8878324fd
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>
323 lines
16 KiB
Swift
323 lines
16 KiB
Swift
// Expander.swift
|
||
// Lyrebird
|
||
//
|
||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
import LyrebirdDSP
|
||
|
||
/// Downward expander and noise gate with optional soft knee.
|
||
///
|
||
/// Reduces gain when the signal level falls below `threshold`. Ratio of `0.0` acts
|
||
/// as a hard gate (output → 0 below threshold), ratio of `1.0` is bypass.
|
||
/// Because attack and release times are non-zero, the output may briefly overshoot
|
||
/// (further reduce) on fast transients.
|
||
///
|
||
/// ## Algorithm
|
||
/// ```
|
||
/// level_dB = 20 × log10(max(|x[n]|, 1e-9))
|
||
///
|
||
/// // Hard-knee gain reduction (diff = level_dB − threshold, negative below threshold)
|
||
/// if level_dB < threshold:
|
||
/// gain_dB = diff × (1/ratio − 1) // diff < 0, (1/ratio − 1) > 0 → gain_dB negative
|
||
/// else:
|
||
/// gain_dB = 0
|
||
///
|
||
/// target = 10^(gain_dB / 20)
|
||
/// coeff = target < _prevGain ? attackCoeff : releaseCoeff
|
||
/// out[n] = x[n] × (_prevGain = coeff × _prevGain + (1 − coeff) × target)
|
||
/// ```
|
||
///
|
||
/// ## Usage
|
||
/// ```swift
|
||
/// let gate = Expander.Audio(in: signal, threshold: -40.0, ratio: 0.0)
|
||
/// let expander = Expander.Audio(in: signal, threshold: -30.0, ratio: 0.5,
|
||
/// attack: 0.005, release: 0.2)
|
||
/// ```
|
||
public enum Expander {
|
||
|
||
// MARK: - Shared base
|
||
|
||
/// Shared base for `Expander.Audio` and `Expander.Control`. Forwards all parameters
|
||
/// to `DynamicsBase`; no extra state.
|
||
///
|
||
/// - Parameters:
|
||
/// - input: Signal to expand.
|
||
/// - threshold: Expansion threshold in dB. Defaults to `−40.0`.
|
||
/// - ratio: Expansion ratio in `[0.0, 1.0]`. `0.0` = gate, `1.0` = bypass.
|
||
/// Defaults to `0.5`.
|
||
/// - attack: Attack time constant in seconds. Defaults to `0.01`.
|
||
/// - release: Release time constant in seconds. Defaults to `0.1`.
|
||
/// - kneeWidth: Soft-knee width in dB (`0` = hard knee). Defaults to `0.0`.
|
||
public class _Base: DynamicsBase {
|
||
/// - Parameters:
|
||
/// - input: Signal to expand.
|
||
/// - threshold: Expansion threshold in dB. Defaults to `−40.0`.
|
||
/// - ratio: Expansion ratio in `[0.0, 1.0]`. Defaults to `0.5`.
|
||
/// - attack: Attack time constant in seconds. Defaults to `0.01`.
|
||
/// - release: Release time constant in seconds. Defaults to `0.1`.
|
||
/// - kneeWidth: Soft-knee width in dB (`0` = hard knee). Defaults to `0.0`.
|
||
public override init(
|
||
in input: any ValidGeneratorInput,
|
||
threshold: any ValidGeneratorInput = -40.0,
|
||
ratio: any ValidGeneratorInput = 0.5,
|
||
attack: any ValidGeneratorInput = 0.01,
|
||
release: any ValidGeneratorInput = 0.1,
|
||
kneeWidth: any ValidGeneratorInput = 0.0
|
||
) {
|
||
super.init(in: input, threshold: threshold, ratio: ratio,
|
||
attack: attack, release: release, kneeWidth: kneeWidth)
|
||
}
|
||
|
||
/// Compute linear gain target below threshold.
|
||
///
|
||
/// Uses the standard expansion slope formula:
|
||
/// gain_dB = diff × (1/ratio − 1)
|
||
/// where diff = level − threshold (negative when below threshold).
|
||
/// ratio=0 → gate (silence); ratio=1 → bypass (no change).
|
||
@inline(__always)
|
||
func _gainTarget(
|
||
levelDB: Double,
|
||
threshDB: Double,
|
||
ratio: Double,
|
||
halfKnee: Double
|
||
) -> Double {
|
||
// Hard-gate floor: −120 dB ≈ 1e-6 linear. Used for ratio=0 (silence below threshold).
|
||
let hardGateSilenceDB: Double = -120.0
|
||
let diff: Double = levelDB - threshDB // negative when below threshold
|
||
let gainDB: Double
|
||
if halfKnee > 0 && abs(diff) < halfKnee {
|
||
// Soft knee: parabolic interpolation from full expansion to bypass at knee top.
|
||
// For ratio=0 (gate), use a fixed slope anchored to halfKnee so the parabola is consistent.
|
||
let slopeBelow: Double = ratio > 0
|
||
? (1.0 / ratio - 1.0)
|
||
: abs(hardGateSilenceDB) / max(1.0, halfKnee)
|
||
gainDB = (diff - halfKnee) * (diff - halfKnee)
|
||
/ (-Self.softKneeParabolaFactor * halfKnee) * slopeBelow
|
||
} else if diff < 0 {
|
||
if ratio <= 0 {
|
||
gainDB = hardGateSilenceDB
|
||
} else {
|
||
gainDB = diff * (1.0 / ratio - 1.0) // expansion: diff neg, (1/ratio-1) pos → gain_dB neg
|
||
}
|
||
} else {
|
||
gainDB = 0.0
|
||
}
|
||
return pow(10.0, gainDB / Self.dbAmplitudeScale)
|
||
}
|
||
}
|
||
|
||
// MARK: - Audio
|
||
|
||
/// Audio-rate expander — per-sample gain smoothing.
|
||
///
|
||
/// - Parameters:
|
||
/// - input: Signal to expand.
|
||
/// - threshold: Expansion threshold in dB. Gain is reduced for signal levels below this threshold. Defaults to `−40.0`.
|
||
/// - ratio: Expansion ratio in [0, 1]. `0.0` = gate (silence below threshold), `1.0` = bypass, `0.5` = 2:1 expansion. Clamped internally to [0, 1]. Defaults to `0.5`.
|
||
/// - attack: Attack time constant in seconds. Practical range 0.001–1.0. Defaults to `0.01`.
|
||
/// - release: Release time constant in seconds. Practical range 0.01–5.0. Defaults to `0.1`.
|
||
/// - kneeWidth: Soft-knee width in dB (0 = hard knee). Must be ≥ 0. Defaults to `0.0`.
|
||
public final class Audio: _Base, AudioGenerator {
|
||
|
||
/// - Parameters:
|
||
/// - input: Signal to expand.
|
||
/// - threshold: Expansion threshold in dB. Gain is reduced for signal levels below this threshold. Defaults to `−40.0`.
|
||
/// - ratio: Expansion ratio in [0, 1]. `0.0` = gate (silence below threshold), `1.0` = bypass, `0.5` = 2:1 expansion. Clamped internally to [0, 1]. Defaults to `0.5`.
|
||
/// - attack: Attack time constant in seconds. Practical range 0.001–1.0. Defaults to `0.01`.
|
||
/// - release: Release time constant in seconds. Practical range 0.01–5.0. Defaults to `0.1`.
|
||
/// - kneeWidth: Soft-knee width in dB (0 = hard knee). Must be ≥ 0. Defaults to `0.0`.
|
||
public override init(
|
||
in input: any ValidGeneratorInput,
|
||
threshold: any ValidGeneratorInput = -40.0,
|
||
ratio: any ValidGeneratorInput = 0.5,
|
||
attack: any ValidGeneratorInput = 0.01,
|
||
release: any ValidGeneratorInput = 0.1,
|
||
kneeWidth: any ValidGeneratorInput = 0.0
|
||
) {
|
||
super.init(in: input, threshold: threshold, ratio: ratio,
|
||
attack: attack, release: release, kneeWidth: kneeWidth)
|
||
}
|
||
public func _computeSamples(
|
||
graph: SynthGraph,
|
||
count: Int
|
||
) -> [[Double]] {
|
||
_checkCount(count)
|
||
guard count > 0 else { return _result }
|
||
|
||
let sr: Double = graph.engine.sampleRate
|
||
|
||
// Read each parameter: when backed by a Generator, take the last sample of
|
||
// the block (captures any ramp); otherwise use floatValue.
|
||
let threshDB: Double = lastGeneratorSampleOrFloat(
|
||
_thresholdInput, isGenerator: _thresholdIsGenerator, graph: graph, count: count)
|
||
let ratioRaw: Double = lastGeneratorSampleOrFloat(
|
||
_ratioInput, isGenerator: _ratioIsGenerator, graph: graph, count: count)
|
||
let attackTRaw: Double = lastGeneratorSampleOrFloat(
|
||
_attackInput, isGenerator: _attackIsGenerator, graph: graph, count: count)
|
||
let releaseTRaw: Double = lastGeneratorSampleOrFloat(
|
||
_releaseInput, isGenerator: _releaseIsGenerator, graph: graph, count: count)
|
||
let kneeDBRaw: Double = lastGeneratorSampleOrFloat(
|
||
_kneeWidthInput, isGenerator: _kneeWidthIsGenerator, graph: graph, count: count)
|
||
|
||
let ratio: Double = max(0.0, min(1.0, ratioRaw))
|
||
let attackT: Double = max(0.0, attackTRaw)
|
||
let releaseT: Double = max(0.0, releaseTRaw)
|
||
let kneeDB: Double = max(0.0, kneeDBRaw)
|
||
|
||
let attackCoeff: Double = attackT > 0 ? exp(-1.0 / (sr * attackT)) : 0.0
|
||
let releaseCoeff: Double = releaseT > 0 ? exp(-1.0 / (sr * releaseT)) : 0.0
|
||
let attackComp: Double = 1.0 - attackCoeff
|
||
let releaseComp: Double = 1.0 - releaseCoeff
|
||
let halfKnee: Double = kneeDB / 2.0
|
||
|
||
let inputSamples: [[Double]] = _input.calculatedSamples(graph: graph, count: count)
|
||
guard let ins: [Double] = inputSamples.first else {
|
||
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
|
||
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||
for i: Int in 0..<count { dstP[i] = 0 }
|
||
}
|
||
return _result
|
||
}
|
||
|
||
// Hoist `_prevGain` to a local across the block — single read/writeback,
|
||
// single denormal flush at end. Mirrors the look-ahead limiter denormal-flush pattern.
|
||
var prevGain: Double = _prevGain
|
||
ins.withUnsafeBufferPointer { (src: UnsafeBufferPointer<Double>) in
|
||
guard let srcP: UnsafePointer<Double> = src.baseAddress else { return }
|
||
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
|
||
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||
for i: Int in 0..<count {
|
||
let x: Double = srcP[i]
|
||
let levelDB: Double = Self.dbAmplitudeScale * log10(max(abs(x), Self.logFloor))
|
||
let target: Double = _gainTarget(
|
||
levelDB: levelDB, threshDB: threshDB,
|
||
ratio: ratio, halfKnee: halfKnee)
|
||
attackReleaseSmoother(
|
||
state: &prevGain, target: target,
|
||
attackCoeff: attackCoeff, attackComp: attackComp,
|
||
releaseCoeff: releaseCoeff, releaseComp: releaseComp,
|
||
direction: .falling
|
||
)
|
||
dstP[i] = x * prevGain
|
||
}
|
||
}
|
||
}
|
||
// Denormal flush once per block — `_prevGain` only enters denormal regime
|
||
// under sustained extreme reduction (gate path).
|
||
prevGain = denormalsToZero(prevGain)
|
||
_prevGain = prevGain
|
||
return _result
|
||
}
|
||
}
|
||
|
||
// MARK: - Control
|
||
|
||
/// Control-rate expander — block-rate peak detection with interpolated gain ramp.
|
||
///
|
||
/// **Time-constant note:** attack/release coefficients use the sample-rate formula
|
||
/// but the smoother steps once per block. Effective time constant ≈ `blockSize / sampleRate`
|
||
/// times longer than the equivalent `Audio` variant.
|
||
///
|
||
/// - Parameters:
|
||
/// - input: Signal to expand.
|
||
/// - threshold: Expansion threshold in dB. Gain is reduced for signal levels below this threshold. Defaults to `−40.0`.
|
||
/// - ratio: Expansion ratio in [0, 1]. `0.0` = gate (silence below threshold), `1.0` = bypass, `0.5` = 2:1 expansion. Clamped internally to [0, 1]. Defaults to `0.5`.
|
||
/// - attack: Attack time constant in seconds. Practical range 0.001–1.0. Defaults to `0.01`.
|
||
/// - release: Release time constant in seconds. Practical range 0.01–5.0. Defaults to `0.1`.
|
||
/// - kneeWidth: Soft-knee width in dB (0 = hard knee). Must be ≥ 0. Defaults to `0.0`.
|
||
public final class Control: _Base, BlockRateControlGenerator {
|
||
public var previousOutputValue: Double = 0.0
|
||
private var _rampTarget: Double = 1.0 // matches _prevGain initial value
|
||
|
||
/// - Parameters:
|
||
/// - input: Signal to expand.
|
||
/// - threshold: Expansion threshold in dB. Gain is reduced for signal levels below this threshold. Defaults to `−40.0`.
|
||
/// - ratio: Expansion ratio in [0, 1]. `0.0` = gate (silence below threshold), `1.0` = bypass, `0.5` = 2:1 expansion. Clamped internally to [0, 1]. Defaults to `0.5`.
|
||
/// - attack: Attack time constant in seconds. Practical range 0.001–1.0. Defaults to `0.01`.
|
||
/// - release: Release time constant in seconds. Practical range 0.01–5.0. Defaults to `0.1`.
|
||
/// - kneeWidth: Soft-knee width in dB (0 = hard knee). Must be ≥ 0. Defaults to `0.0`.
|
||
public override init(
|
||
in input: any ValidGeneratorInput,
|
||
threshold: any ValidGeneratorInput = -40.0,
|
||
ratio: any ValidGeneratorInput = 0.5,
|
||
attack: any ValidGeneratorInput = 0.01,
|
||
release: any ValidGeneratorInput = 0.1,
|
||
kneeWidth: any ValidGeneratorInput = 0.0
|
||
) {
|
||
super.init(in: input, threshold: threshold, ratio: ratio,
|
||
attack: attack, release: release, kneeWidth: kneeWidth)
|
||
}
|
||
|
||
|
||
public func _computeSamples(
|
||
graph: SynthGraph,
|
||
count: Int
|
||
) -> [[Double]] {
|
||
_checkCount(count)
|
||
|
||
let sr: Double = graph.engine.sampleRate
|
||
|
||
// Read each parameter: when backed by a Generator, take the last sample of
|
||
// the block (captures any ramp); otherwise use floatValue.
|
||
let threshDB: Double = lastGeneratorSampleOrFloat(
|
||
_thresholdInput, isGenerator: _thresholdIsGenerator, graph: graph, count: count)
|
||
let ratioRaw: Double = lastGeneratorSampleOrFloat(
|
||
_ratioInput, isGenerator: _ratioIsGenerator, graph: graph, count: count)
|
||
let attackTRaw: Double = lastGeneratorSampleOrFloat(
|
||
_attackInput, isGenerator: _attackIsGenerator, graph: graph, count: count)
|
||
let releaseTRaw: Double = lastGeneratorSampleOrFloat(
|
||
_releaseInput, isGenerator: _releaseIsGenerator, graph: graph, count: count)
|
||
let kneeDBRaw: Double = lastGeneratorSampleOrFloat(
|
||
_kneeWidthInput, isGenerator: _kneeWidthIsGenerator, graph: graph, count: count)
|
||
|
||
let ratio: Double = max(0.0, min(1.0, ratioRaw))
|
||
let attackT: Double = max(0.0, attackTRaw)
|
||
let releaseT: Double = max(0.0, releaseTRaw)
|
||
let kneeDB: Double = max(0.0, kneeDBRaw)
|
||
|
||
let attackCoeff: Double = attackT > 0 ? exp(-1.0 / (sr * attackT)) : 0.0
|
||
let releaseCoeff: Double = releaseT > 0 ? exp(-1.0 / (sr * releaseT)) : 0.0
|
||
let halfKnee: Double = kneeDB / 2.0
|
||
|
||
let inputSamples: [[Double]] = _input.calculatedSamples(graph: graph, count: count)
|
||
guard let ins: [Double] = inputSamples.first else {
|
||
for i: Int in 0..<count { _result[0][i] = 0 }
|
||
_rampTarget = 0
|
||
previousOutputValue = 0
|
||
return _result
|
||
}
|
||
|
||
var blockPeak: Double = 0.0
|
||
for i: Int in 0..<min(count, ins.count) {
|
||
let a: Double = abs(Double(ins[i]))
|
||
if a > blockPeak { blockPeak = a }
|
||
}
|
||
let levelDB: Double = Self.dbAmplitudeScale * log10(max(blockPeak, Self.logFloor))
|
||
let target: Double = _gainTarget(levelDB: levelDB, threshDB: threshDB,
|
||
ratio: ratio, halfKnee: halfKnee)
|
||
let coeff: Double = target < _prevGain ? attackCoeff : releaseCoeff
|
||
_prevGain = coeff * _prevGain + (1.0 - coeff) * target
|
||
_prevGain = denormalsToZero(_prevGain)
|
||
|
||
let rampStart: Double = _rampTarget
|
||
let gainF: Double = Double(_prevGain)
|
||
_rampTarget = gainF
|
||
guard count > 0 else { return _result }
|
||
let step: Double = (gainF - rampStart) / Double(count)
|
||
for i: Int in 0..<count {
|
||
let rampGain: Double = rampStart + step * Double(i + 1)
|
||
let x: Double = i < ins.count ? ins[i] : 0
|
||
_result[0][i] = x * rampGain
|
||
}
|
||
previousOutputValue = count > 0 ? _result[0][count - 1] : 0
|
||
return _result
|
||
}
|
||
}
|
||
}
|
||
|
||
extension Expander: GeneratorEnum {
|
||
public typealias AudioType = Expander.Audio
|
||
public typealias ControlType = Expander.Control
|
||
}
|