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>
236 lines
10 KiB
Swift
236 lines
10 KiB
Swift
// AmplitudeFollower.swift
|
||
// Lyrebird
|
||
//
|
||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
import LyrebirdDSP
|
||
|
||
/// Envelope follower with asymmetric attack and release smoothing.
|
||
///
|
||
/// Tracks the instantaneous amplitude of an input signal via a one-pole recursive
|
||
/// smoother with independent attack and release time constants.
|
||
///
|
||
/// ```
|
||
/// attackCoeff = exp(−1 / (sampleRate × attackTime))
|
||
/// releaseCoeff = exp(−1 / (sampleRate × releaseTime))
|
||
///
|
||
/// // per sample:
|
||
/// abs_x = |x[n]|
|
||
/// coeff = abs_x > _prevAmp ? attackCoeff : releaseCoeff
|
||
/// out[n] = coeff × _prevAmp + (1 − coeff) × abs_x
|
||
/// ```
|
||
///
|
||
/// ## Usage
|
||
/// ```swift
|
||
/// let follower = AmplitudeFollower.Audio(in: signal)
|
||
/// let follower = AmplitudeFollower.Audio(in: signal, attackTime: 0.005, releaseTime: 0.3)
|
||
/// ```
|
||
public enum AmplitudeFollower {
|
||
|
||
// MARK: - Shared base
|
||
|
||
public class _Base: GeneratorBase {
|
||
let _input: any ValidGeneratorInput
|
||
let _attackInput: any ValidGeneratorInput
|
||
let _releaseInput: any ValidGeneratorInput
|
||
|
||
/// Classify each parameter input at init — avoids `is` checks on the RT thread.
|
||
let _attackIsGenerator: Bool
|
||
let _releaseIsGenerator: Bool
|
||
|
||
var _prevAmp: Double = 0.0
|
||
|
||
public init(
|
||
in input: any ValidGeneratorInput,
|
||
attackTime: any ValidGeneratorInput = 0.01,
|
||
releaseTime: any ValidGeneratorInput = 0.1
|
||
) {
|
||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||
let resolvedAttack: any ValidGeneratorInput = attackTime._resolvedInput()
|
||
let resolvedRelease: any ValidGeneratorInput = releaseTime._resolvedInput()
|
||
_input = resolvedInput
|
||
_attackInput = resolvedAttack
|
||
_releaseInput = resolvedRelease
|
||
_attackIsGenerator = resolvedAttack is any Generator
|
||
_releaseIsGenerator = resolvedRelease is any Generator
|
||
}
|
||
}
|
||
|
||
// MARK: - Audio
|
||
|
||
/// Audio-rate amplitude follower — per-sample envelope tracking.
|
||
///
|
||
/// - Parameters:
|
||
/// - input: Signal to track.
|
||
/// - attackTime: Attack time constant in seconds. Formula: `exp(−1 / (sampleRate × t))`. Practical range 0.001–1.0. Defaults to `0.01`.
|
||
/// - releaseTime: Release time constant in seconds. Practical range 0.01–5.0. Defaults to `0.1`.
|
||
public final class Audio: _Base, AudioGenerator {
|
||
|
||
/// - Parameters:
|
||
/// - input: Signal to track.
|
||
/// - attackTime: Attack time constant in seconds. Formula: `exp(−1 / (sampleRate × t))`. Practical range 0.001–1.0. Defaults to `0.01`.
|
||
/// - releaseTime: Release time constant in seconds. Practical range 0.01–5.0. Defaults to `0.1`.
|
||
public override init(
|
||
in input: any ValidGeneratorInput,
|
||
attackTime: any ValidGeneratorInput = 0.01,
|
||
releaseTime: any ValidGeneratorInput = 0.1
|
||
) {
|
||
super.init(in: input, attackTime: attackTime, releaseTime: releaseTime)
|
||
}
|
||
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 attackTimeRaw: Double = lastGeneratorSampleOrFloat(
|
||
_attackInput, isGenerator: _attackIsGenerator, graph: graph, count: count)
|
||
let releaseTimeRaw: Double = lastGeneratorSampleOrFloat(
|
||
_releaseInput, isGenerator: _releaseIsGenerator, graph: graph, count: count)
|
||
|
||
let attackTime: Double = max(0.0, attackTimeRaw)
|
||
let releaseTime: Double = max(0.0, releaseTimeRaw)
|
||
|
||
// Block-constant smoother coefficients — exp() resolved once per block.
|
||
// Pre-compute one-minus form for the release-branch arithmetic.
|
||
let attackCoeff: Double = attackTime > 0 ? exp(-1.0 / (sr * attackTime)) : 0.0
|
||
let releaseCoeff: Double = releaseTime > 0 ? exp(-1.0 / (sr * releaseTime)) : 0.0
|
||
let attackComp: Double = 1.0 - attackCoeff
|
||
let releaseComp: Double = 1.0 - releaseCoeff
|
||
|
||
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 }
|
||
let hold: Double = _prevAmp
|
||
for i: Int in 0..<count { dstP[i] = hold }
|
||
}
|
||
return _result
|
||
}
|
||
|
||
// Hoist `_prevAmp` to a local — single read/writeback across the block,
|
||
// single denormal flush at end. Mirrors the LookAheadLimiter pattern.
|
||
var prevAmp: Double = _prevAmp
|
||
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 absX: Double = abs(srcP[i])
|
||
attackReleaseSmoother(
|
||
state: &prevAmp, target: absX,
|
||
attackCoeff: attackCoeff, attackComp: attackComp,
|
||
releaseCoeff: releaseCoeff, releaseComp: releaseComp,
|
||
direction: .rising
|
||
)
|
||
dstP[i] = prevAmp
|
||
}
|
||
}
|
||
}
|
||
// Denormal flush once per block — `_prevAmp` only enters denormal regime
|
||
// under sustained near-zero input with tiny release time.
|
||
prevAmp = denormalsToZero(prevAmp)
|
||
_prevAmp = prevAmp
|
||
return _result
|
||
}
|
||
}
|
||
|
||
// MARK: - Control
|
||
|
||
/// Control-rate amplitude follower — block-rate peak detection with smoothed ramp output.
|
||
///
|
||
/// **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 track.
|
||
/// - attackTime: Attack time constant in seconds. Formula: `exp(−1 / (sampleRate × t))`. Practical range 0.001–1.0. Defaults to `0.01`.
|
||
/// - releaseTime: Release time constant in seconds. Practical range 0.01–5.0. Defaults to `0.1`.
|
||
public final class Control: _Base, BlockRateControlGenerator {
|
||
public var previousOutputValue: Double = 0.0
|
||
private var _rampTarget: Double = 0.0
|
||
|
||
/// - Parameters:
|
||
/// - input: Signal to track.
|
||
/// - attackTime: Attack time constant in seconds. Formula: `exp(−1 / (sampleRate × t))`. Practical range 0.001–1.0. Defaults to `0.01`.
|
||
/// - releaseTime: Release time constant in seconds. Practical range 0.01–5.0. Defaults to `0.1`.
|
||
public override init(
|
||
in input: any ValidGeneratorInput,
|
||
attackTime: any ValidGeneratorInput = 0.01,
|
||
releaseTime: any ValidGeneratorInput = 0.1
|
||
) {
|
||
super.init(in: input, attackTime: attackTime, releaseTime: releaseTime)
|
||
}
|
||
|
||
|
||
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 attackTimeRaw: Double = lastGeneratorSampleOrFloat(
|
||
_attackInput, isGenerator: _attackIsGenerator, graph: graph, count: count)
|
||
let releaseTimeRaw: Double = lastGeneratorSampleOrFloat(
|
||
_releaseInput, isGenerator: _releaseIsGenerator, graph: graph, count: count)
|
||
|
||
let attackTime: Double = max(0.0, attackTimeRaw)
|
||
let releaseTime: Double = max(0.0, releaseTimeRaw)
|
||
|
||
let attackCoeff: Double = attackTime > 0 ? exp(-1.0 / (sr * attackTime)) : 0.0
|
||
let releaseCoeff: Double = releaseTime > 0 ? exp(-1.0 / (sr * releaseTime)) : 0.0
|
||
|
||
let inputSamples: [[Double]] = _input.calculatedSamples(graph: graph, count: count)
|
||
guard let ins: [Double] = inputSamples.first else {
|
||
let rampStart: Double = _rampTarget
|
||
_rampTarget = _prevAmp // must update so next call's rampStart is correct
|
||
guard count > 0 else { return _result }
|
||
let step: Double = (_prevAmp - rampStart) / Double(count)
|
||
for i: Int in 0..<count { _result[0][i] = rampStart + step * Double(i + 1) }
|
||
previousOutputValue = _prevAmp
|
||
return _result
|
||
}
|
||
|
||
// Find peak across the block.
|
||
var blockPeak: Double = 0.0
|
||
for i: Int in 0..<min(count, ins.count) {
|
||
let absX: Double = abs(ins[i])
|
||
if absX > blockPeak { blockPeak = absX }
|
||
}
|
||
|
||
// One smoothing step at block rate.
|
||
let coeff: Double = blockPeak > _prevAmp ? attackCoeff : releaseCoeff
|
||
_prevAmp = coeff * _prevAmp + (1.0 - coeff) * blockPeak
|
||
_prevAmp = denormalsToZero(_prevAmp)
|
||
|
||
// Ramp from previous target to new target.
|
||
let rampStart: Double = _rampTarget
|
||
let target: Double = _prevAmp
|
||
_rampTarget = target
|
||
guard count > 0 else { return _result }
|
||
let step: Double = (target - rampStart) / Double(count)
|
||
for i: Int in 0..<count {
|
||
_result[0][i] = rampStart + step * Double(i + 1)
|
||
}
|
||
previousOutputValue = target
|
||
return _result
|
||
}
|
||
}
|
||
}
|
||
|
||
extension AmplitudeFollower: GeneratorEnum {
|
||
public typealias AudioType = AmplitudeFollower.Audio
|
||
public typealias ControlType = AmplitudeFollower.Control
|
||
}
|