d6875da2cb
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
776 lines
39 KiB
Swift
776 lines
39 KiB
Swift
// DynamicsTests.swift
|
||
// Lyrebird
|
||
//
|
||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
import Darwin
|
||
import Testing
|
||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||
|
||
// MARK: - Helpers
|
||
|
||
private func rmsD(_ samples: [Double]) -> Double {
|
||
guard !samples.isEmpty else { return 0 }
|
||
return sqrt(samples.map { Double($0) * Double($0) }.reduce(0, +) / Double(samples.count))
|
||
}
|
||
|
||
/// Drive a 2-channel generator for `blocks` blocks; returns (ch0, ch1) flat arrays.
|
||
private func collect2ch(
|
||
_ gen: any Generator,
|
||
engine: SynthesisEngine,
|
||
blocks: Int
|
||
) -> ([Double], [Double]) {
|
||
let bs: Int = engine.blockSize
|
||
var ch0: [Double] = []
|
||
var ch1: [Double] = []
|
||
ch0.reserveCapacity(blocks * bs)
|
||
ch1.reserveCapacity(blocks * bs)
|
||
for _ in 0..<blocks {
|
||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||
let result: [[Double]] = gen.calculatedSamples(graph: g, count: bs)
|
||
ch0 += (result.count > 0 ? result[0] : [Double](repeating: 0, count: bs)).prefix(bs)
|
||
ch1 += (result.count > 1 ? result[1] : [Double](repeating: 0, count: bs)).prefix(bs)
|
||
advanceBlock(engine)
|
||
}
|
||
return (ch0, ch1)
|
||
}
|
||
|
||
// MARK: - AmplitudeFollower Tests
|
||
|
||
@MainActor
|
||
@Suite("AmplitudeFollower")
|
||
struct AmplitudeFollowerTests {
|
||
|
||
let engine: SynthesisEngine
|
||
|
||
init() throws {
|
||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||
try engine.start()
|
||
}
|
||
|
||
@Test func silenceOutputsZero() {
|
||
let follower: AmplitudeFollower.Audio = AmplitudeFollower.Audio(in: ConstantGeneratorInput(0.0))
|
||
let samples: [Double] = collectBlocks(follower, engine: engine, blocks: 10)
|
||
#expect(samples.allSatisfy { $0 == 0.0 })
|
||
}
|
||
|
||
@Test func steadySineConvergesToAmplitude() {
|
||
// A 440 Hz sine at amplitude 0.5. Follower should converge near 0.5.
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.5)
|
||
let follower: AmplitudeFollower.Audio = AmplitudeFollower.Audio(in: sine, attackTime: 0.01, releaseTime: 0.01)
|
||
let all: [Double] = collectBlocks(follower, engine: engine, blocks: 200)
|
||
// Check steady-state tail.
|
||
let tail: [Double] = Array(all.suffix(engine.blockSize * 50))
|
||
let avg: Double = tail.reduce(0.0, +) / Double(tail.count)
|
||
// Sine amplitude 0.5 → follower should stabilise around ~0.3–0.5 (peak tracks ~0.5).
|
||
#expect(avg > 0.2 && avg < 0.55)
|
||
}
|
||
|
||
@Test func impulseThenDecay() {
|
||
// Single block at 1.0 then silence. Follower should rise then decay.
|
||
let const: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||
let follower: AmplitudeFollower.Audio = AmplitudeFollower.Audio(in: const,
|
||
attackTime: 0.001, releaseTime: 0.5)
|
||
// Hot block (amplitude 1.0).
|
||
let g1: SynthGraph = makeSynthGraph(engine: engine)
|
||
let hot: [Double] = follower.calculatedSamples(graph: g1, count: engine.blockSize)[0]
|
||
advanceBlock(engine)
|
||
// Check last valid sample (index blockSize-1), not hot.last which is element [511].
|
||
let lastValidSample: Double = hot[engine.blockSize - 1]
|
||
#expect(lastValidSample > 0.5)
|
||
|
||
// Now silence input.
|
||
let silence: ConstantGeneratorInput = ConstantGeneratorInput(0.0)
|
||
let follower2: AmplitudeFollower.Audio = AmplitudeFollower.Audio(in: silence,
|
||
attackTime: 0.001, releaseTime: 0.5)
|
||
// Pre-heat follower2 to a high value by running one block with amplitude 1.
|
||
let constIn: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||
let follower3: AmplitudeFollower.Audio = AmplitudeFollower.Audio(in: constIn,
|
||
attackTime: 0.0, releaseTime: 0.5)
|
||
let g2: SynthGraph = makeSynthGraph(engine: engine)
|
||
let _ = follower3.calculatedSamples(graph: g2, count: engine.blockSize)
|
||
advanceBlock(engine)
|
||
// Now feed silence — amplitude should decrease.
|
||
let silenceGen: ConstantGeneratorInput = ConstantGeneratorInput(0.0)
|
||
let follower4: AmplitudeFollower.Audio = AmplitudeFollower.Audio(in: silenceGen,
|
||
attackTime: 0.0, releaseTime: 0.5)
|
||
let g3: SynthGraph = makeSynthGraph(engine: engine)
|
||
let decaying: [Double] = follower4.calculatedSamples(graph: g3, count: engine.blockSize)[0]
|
||
// Fresh follower starts at 0 and stays 0 with silence.
|
||
#expect(decaying.allSatisfy { $0 == 0.0 })
|
||
}
|
||
|
||
@Test func attackFasterThanRelease() {
|
||
// With zero attack and long release, the follower immediately follows peaks up.
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 0.8)
|
||
let fastAtk: AmplitudeFollower.Audio = AmplitudeFollower.Audio(in: sine, attackTime: 0.0, releaseTime: 2.0)
|
||
let all: [Double] = collectBlocks(fastAtk, engine: engine, blocks: 10)
|
||
// With instant attack, peak should reach near 0.8 very quickly.
|
||
let peak: Double = all.max() ?? 0
|
||
#expect(peak > 0.7)
|
||
}
|
||
|
||
@Test func controlVariantBlockRatePeak() throws {
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.5)
|
||
let ctrl: AmplitudeFollower.Control = AmplitudeFollower.Control(in: sine, attackTime: 0.001, releaseTime: 0.001)
|
||
let all: [Double] = collectBlocks(ctrl, engine: engine, blocks: 100)
|
||
let tail: [Double] = Array(all.suffix(engine.blockSize * 20))
|
||
let avg: Double = tail.reduce(0.0, +) / Double(tail.count)
|
||
#expect(avg > 0.2 && avg < 0.6)
|
||
}
|
||
|
||
@Test func generatorEnumConformance() {
|
||
// Verify GeneratorEnum typealiases compile and construct.
|
||
let _: AmplitudeFollower.Audio = AmplitudeFollower.AudioType(in: 0.0)
|
||
let _: AmplitudeFollower.Control = AmplitudeFollower.ControlType(in: 0.0)
|
||
}
|
||
|
||
@Test func zeroAttackInstantaneousRise() {
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 1.0)
|
||
let follower: AmplitudeFollower.Audio = AmplitudeFollower.Audio(in: sine, attackTime: 0.0, releaseTime: 0.1)
|
||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||
let block: [Double] = follower.calculatedSamples(graph: g, count: engine.blockSize)[0]
|
||
// First non-zero sine sample should already be tracked (instant attack).
|
||
let nonZero: [Double] = block.filter { $0 > 0.001 }
|
||
#expect(!nonZero.isEmpty)
|
||
}
|
||
|
||
/// Denormal flush moved to once-per-block. Pre-heat the smoother
|
||
/// to ~1.0 with a loud DC input, then switch to a tiny-but-nonzero input
|
||
/// (1e-20) with very fast release — `_prevAmp` drops several orders of
|
||
/// magnitude per block, sweeping through the denormal regime that the
|
||
/// once-per-block flush is responsible for catching. Output must stay
|
||
/// finite + bounded over the full render.
|
||
///
|
||
/// We construct two followers (preheat + measurement) because input is
|
||
/// captured at init; the pre-heat is solely to prove the smoother had
|
||
/// genuine non-zero state before we observed it converge. The measurement
|
||
/// follower's `_prevAmp` starts at 0; with a tiny input + fast release it
|
||
/// rises slowly toward 1e-20, then would normally drift through the
|
||
/// denormal band but for the once-per-block `denormalsToZero` flush.
|
||
@Test func denormalCadenceAmplitudeFollower() {
|
||
// Pre-heat sanity check — distinct follower; validates the smoother
|
||
// tracks a non-zero level (no assertion needed beyond non-finite check).
|
||
let driven: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||
let preheat: AmplitudeFollower.Audio = AmplitudeFollower.Audio(
|
||
in: driven, attackTime: 0.001, releaseTime: 0.001)
|
||
for _: Int in 0..<32 {
|
||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||
let block: [Double] = preheat.calculatedSamples(graph: g, count: engine.blockSize)[0]
|
||
for v: Double in block { #expect(v.isFinite) }
|
||
advanceBlock(engine)
|
||
}
|
||
|
||
// Measurement follower — tiny non-zero input + tiny release time. Output
|
||
// converges toward 1e-20 (a denormal-adjacent value) over the render.
|
||
let tiny: ConstantGeneratorInput = ConstantGeneratorInput(1e-20)
|
||
let follower: AmplitudeFollower.Audio = AmplitudeFollower.Audio(
|
||
in: tiny, attackTime: 1e-5, releaseTime: 1e-5)
|
||
let blocks: Int = (Int(44100.0 * 2.0) / engine.blockSize) + 1
|
||
var sawNonFinite: Bool = false
|
||
var maxObserved: Double = 0.0
|
||
for _: Int in 0..<blocks {
|
||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||
let block: [Double] = follower.calculatedSamples(graph: g, count: engine.blockSize)[0]
|
||
for v: Double in block {
|
||
if !v.isFinite { sawNonFinite = true }
|
||
if v > maxObserved { maxObserved = v }
|
||
}
|
||
advanceBlock(engine)
|
||
}
|
||
#expect(!sawNonFinite, "AmplitudeFollower output must remain finite")
|
||
#expect(maxObserved < 1.0, "envelope of tiny input must remain bounded")
|
||
}
|
||
}
|
||
|
||
// MARK: - FreqTracker Tests
|
||
|
||
@MainActor
|
||
@Suite("FreqTracker")
|
||
struct FreqTrackerTests {
|
||
|
||
let engine: SynthesisEngine
|
||
let sr: Double = 44100.0
|
||
|
||
init() throws {
|
||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||
try engine.start()
|
||
}
|
||
|
||
@Test func silenceOutputsZeroConfidence() {
|
||
let tracker: FreqTracker = FreqTracker(in: ConstantGeneratorInput(0.0),
|
||
fftSize: 512, hopSize: 256)
|
||
let (_, conf) = collect2ch(tracker, engine: engine, blocks: 20)
|
||
let tailConf: [Double] = Array(conf.suffix(engine.blockSize * 5))
|
||
let avgConf: Double = tailConf.reduce(Double(0), +) / Double(tailConf.count)
|
||
// Silence → near-zero confidence.
|
||
#expect(avgConf < 0.2)
|
||
}
|
||
|
||
@Test func pureA440FreqTracked() {
|
||
// Use smaller fftSize for faster convergence in tests.
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.8)
|
||
let tracker: FreqTracker = FreqTracker(in: sine, fftSize: 512, hopSize: 128,
|
||
minFreq: 60.0, maxFreq: 3000.0)
|
||
// Render enough blocks to warm up (need hopSize × 4 samples at minimum).
|
||
let warmUpBlocks: Int = (512 / engine.blockSize) + 10
|
||
let (freqs, _) = collect2ch(tracker, engine: engine, blocks: warmUpBlocks)
|
||
// Check the tail.
|
||
let tail: [Double] = Array(freqs.suffix(engine.blockSize * 5))
|
||
let nonZero: [Double] = tail.filter { $0 > 0 }
|
||
if !nonZero.isEmpty {
|
||
let avgFreq: Double = nonZero.reduce(0.0, +) / Double(nonZero.count)
|
||
#expect(avgFreq > 420.0 && avgFreq < 460.0)
|
||
}
|
||
}
|
||
|
||
@Test func twoChannelOutput() {
|
||
let tracker: FreqTracker = FreqTracker(in: ConstantGeneratorInput(0.0), fftSize: 256, hopSize: 128)
|
||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||
let result: [[Double]] = tracker.calculatedSamples(graph: g, count: engine.blockSize)
|
||
#expect(result.count == 2)
|
||
// Buffers are pre-allocated to 512; at least blockSize valid samples in each.
|
||
#expect(result[0].count >= engine.blockSize)
|
||
#expect(result[1].count >= engine.blockSize)
|
||
}
|
||
|
||
@Test func confidenceHighForPureSine() {
|
||
let freq: Double = 440.0
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: freq, mul: 0.9)
|
||
let tracker: FreqTracker = FreqTracker(in: sine, fftSize: 512, hopSize: 128,
|
||
minFreq: 60.0, maxFreq: 3000.0)
|
||
// Warm up and check confidence.
|
||
let blocks: Int = (1024 / engine.blockSize) + 20
|
||
let (_, conf) = collect2ch(tracker, engine: engine, blocks: blocks)
|
||
let tail: [Double] = Array(conf.suffix(engine.blockSize * 10))
|
||
let nonZero: [Double] = tail.filter { $0 > 0 }
|
||
if !nonZero.isEmpty {
|
||
let maxConf: Double = nonZero.max() ?? 0
|
||
#expect(maxConf > 0.5)
|
||
}
|
||
}
|
||
|
||
@Test func fftSizePreconditionPowerOfTwo() {
|
||
// Valid: power of 2 ≥ 64.
|
||
let t: FreqTracker = FreqTracker(in: ConstantGeneratorInput(0.0), fftSize: 64)
|
||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||
let result: [[Double]] = t.calculatedSamples(graph: g, count: engine.blockSize)
|
||
#expect(result.count == 2)
|
||
}
|
||
|
||
@Test func outOfRangeFreqReturnsZero() {
|
||
// A 440 Hz sine with maxFreq = 200 Hz — should report 0 Hz (out of range).
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||
let tracker: FreqTracker = FreqTracker(in: sine, fftSize: 512, hopSize: 128,
|
||
minFreq: 60.0, maxFreq: 200.0)
|
||
let blocks: Int = (1024 / engine.blockSize) + 20
|
||
let (freqs, _) = collect2ch(tracker, engine: engine, blocks: blocks)
|
||
let tail: [Double] = Array(freqs.suffix(engine.blockSize * 10))
|
||
// 440 Hz is above maxFreq → should output 0.
|
||
let above: [Double] = tail.filter { $0 > 250.0 }
|
||
#expect(above.isEmpty)
|
||
}
|
||
|
||
@Test func differentPitch880Hz() {
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: 880.0, mul: 0.8)
|
||
let tracker: FreqTracker = FreqTracker(in: sine, fftSize: 512, hopSize: 256,
|
||
minFreq: 60.0, maxFreq: 3000.0)
|
||
let blocks: Int = (1024 / engine.blockSize) + 30
|
||
let (freqs, _) = collect2ch(tracker, engine: engine, blocks: blocks)
|
||
let nonZero: [Double] = freqs.filter { $0 > 400.0 } // filter out subharmonic at 440 Hz
|
||
if !nonZero.isEmpty {
|
||
let avgFreq: Double = nonZero.suffix(engine.blockSize * 5).reduce(Double(0), +)
|
||
/ Double(min(engine.blockSize * 5, nonZero.count))
|
||
#expect(avgFreq > 800.0 && avgFreq < 960.0)
|
||
}
|
||
}
|
||
|
||
@Test func decimationEnablesLowFrequencyTracking() {
|
||
// Low-E guitar string (E2 ≈ 82.4 Hz). At 44100 Hz with fftSize 512 (halfSize 256),
|
||
// the undecimated tracker floors out around 173 Hz and cannot see this pitch. With
|
||
// 4× decimation the effective rate is ~11025 Hz, dropping the floor to ~43 Hz, so
|
||
// the fundamental is now trackable with the same (cheap) 256-lag YIN window.
|
||
let e2: Double = 82.41
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: e2, mul: 0.8)
|
||
let tracker: FreqTracker = FreqTracker(
|
||
in: sine,
|
||
fftSize: 512,
|
||
hopSize: 256,
|
||
minFreq: 40.0,
|
||
maxFreq: 660.0,
|
||
decimation: 4
|
||
)
|
||
// Decimation means each hop needs 4× more input samples, so render longer.
|
||
let blocks: Int = (512 * 4 / engine.blockSize) + 60
|
||
let (freqs, _) = collect2ch(tracker, engine: engine, blocks: blocks)
|
||
let tail: [Double] = Array(freqs.suffix(engine.blockSize * 5))
|
||
let nonZero: [Double] = tail.filter { $0 > 0 }
|
||
#expect(!nonZero.isEmpty, "4× decimation should let FreqTracker detect an 82 Hz tone")
|
||
if !nonZero.isEmpty {
|
||
let avgFreq: Double = nonZero.reduce(0.0, +) / Double(nonZero.count)
|
||
#expect(avgFreq > 78.0 && avgFreq < 87.0, "Expected ~82 Hz, got \(avgFreq)")
|
||
}
|
||
}
|
||
|
||
@Test func decimationDefaultsToUnchangedBehaviour() {
|
||
// decimation: 1 (default) must reproduce the plain-A440 tracking result.
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.8)
|
||
let tracker: FreqTracker = FreqTracker(
|
||
in: sine,
|
||
fftSize: 512,
|
||
hopSize: 128,
|
||
minFreq: 60.0,
|
||
maxFreq: 3000.0,
|
||
decimation: 1
|
||
)
|
||
let warmUpBlocks: Int = (512 / engine.blockSize) + 10
|
||
let (freqs, _) = collect2ch(tracker, engine: engine, blocks: warmUpBlocks)
|
||
let tail: [Double] = Array(freqs.suffix(engine.blockSize * 5))
|
||
let nonZero: [Double] = tail.filter { $0 > 0 }
|
||
#expect(!nonZero.isEmpty, "decimation: 1 must still track A440 (regression guard)")
|
||
if !nonZero.isEmpty {
|
||
let avgFreq: Double = nonZero.reduce(0.0, +) / Double(nonZero.count)
|
||
#expect(avgFreq > 420.0 && avgFreq < 460.0)
|
||
}
|
||
}
|
||
}
|
||
|
||
// MARK: - LookAheadLimiter Tests
|
||
|
||
@MainActor
|
||
@Suite("LookAheadLimiter")
|
||
struct LookAheadLimiterTests {
|
||
|
||
let engine: SynthesisEngine
|
||
let sr: Double = 44100.0
|
||
|
||
init() throws {
|
||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||
try engine.start()
|
||
}
|
||
|
||
@Test func lowAmplitudePassesThrough() {
|
||
// Signal well below maxAmplitude should pass through with gain ≈ 1.
|
||
// Compare RMS (not sample-by-sample — look-ahead delay shifts phase).
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 0.3)
|
||
let limiter: LookAheadLimiter = LookAheadLimiter(in: sine, maxAmplitude: 1.0,
|
||
lookAheadTime: 0.005, sampleRate: sr)
|
||
let limited: [Double] = collectBlocks(limiter, engine: engine, blocks: 100)
|
||
let tail: [Double] = Array(limited.suffix(engine.blockSize * 50))
|
||
let rmsLimited: Double = rmsD(tail)
|
||
// 100 Hz sine at amplitude 0.3 → RMS ≈ 0.212. No limiting expected.
|
||
#expect(rmsLimited > 0.18 && rmsLimited < 0.25)
|
||
}
|
||
|
||
@Test func peakNeverExceedsMaxAmplitude() {
|
||
// Loud signal — limiter must clamp absolute peak to ≤ maxAmplitude.
|
||
let maxAmp: Double = 0.5
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: 220.0, mul: 2.0)
|
||
let limiter: LookAheadLimiter = LookAheadLimiter(in: sine, maxAmplitude: maxAmp,
|
||
lookAheadTime: 0.01, sampleRate: sr)
|
||
let samples: [Double] = collectBlocks(limiter, engine: engine, blocks: 100)
|
||
// Allow small margin for release tail.
|
||
let violators: [Double] = samples.filter { abs(Double($0)) > maxAmp + 0.001 }
|
||
#expect(violators.isEmpty)
|
||
}
|
||
|
||
@Test func delayedBylookAheadSamples() {
|
||
// An impulse at sample 0 should appear delayed by lookAheadSamples.
|
||
let lookAheadTime: Double = 0.002
|
||
let lookAheadSamples: Int = Int(lookAheadTime * sr)
|
||
let impulse: Impulse.Audio = Impulse.Audio(freq: 0.0) // fires once at t=0 (never repeats if freq=0)
|
||
let limiter: LookAheadLimiter = LookAheadLimiter(in: impulse, maxAmplitude: 2.0,
|
||
lookAheadTime: lookAheadTime, sampleRate: sr)
|
||
let blocks: Int = (lookAheadSamples / engine.blockSize) + 5
|
||
let samples: [Double] = collectBlocks(limiter, engine: engine, blocks: blocks)
|
||
// First `lookAheadSamples` outputs should be zero (before the impulse arrives).
|
||
let prefix: [Double] = Array(samples.prefix(lookAheadSamples))
|
||
#expect(prefix.allSatisfy { abs($0) < 0.001 })
|
||
}
|
||
|
||
@Test func zeroLookAheadStillLimits() {
|
||
let maxAmp: Double = 0.4
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 1.5)
|
||
let limiter: LookAheadLimiter = LookAheadLimiter(in: sine, maxAmplitude: maxAmp,
|
||
lookAheadTime: 0.0, sampleRate: sr)
|
||
let samples: [Double] = collectBlocks(limiter, engine: engine, blocks: 100)
|
||
// May briefly overshoot on first cycle without look-ahead — allow small margin.
|
||
let steadyTail: [Double] = Array(samples.suffix(engine.blockSize * 50))
|
||
let violators: [Double] = steadyTail.filter { abs(Double($0)) > maxAmp + 0.01 }
|
||
#expect(violators.isEmpty)
|
||
}
|
||
|
||
@Test func dcSignalLimitedToMaxAmplitude() {
|
||
// DC at 2.0 should be limited to 1.0.
|
||
let maxAmp: Double = 1.0
|
||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(2.0)
|
||
let limiter: LookAheadLimiter = LookAheadLimiter(in: dc, maxAmplitude: maxAmp,
|
||
lookAheadTime: 0.005, sampleRate: sr)
|
||
// After warm-up (look-ahead fills), output should be ≈ 1.0.
|
||
let warmUpSamples: Int = Int(0.005 * sr) + engine.blockSize
|
||
let warmUpBlocks: Int = warmUpSamples / engine.blockSize + 2
|
||
let all: [Double] = collectBlocks(limiter, engine: engine, blocks: warmUpBlocks + 20)
|
||
let tail: [Double] = Array(all.suffix(engine.blockSize * 10))
|
||
let avg: Double = tail.reduce(0.0, +) / Double(tail.count)
|
||
#expect(abs(Double(avg) - maxAmp) < 0.05)
|
||
}
|
||
|
||
@Test func customMaxAmplitude() {
|
||
let maxAmp: Double = 0.25
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 1.0)
|
||
let limiter: LookAheadLimiter = LookAheadLimiter(in: sine, maxAmplitude: maxAmp,
|
||
lookAheadTime: 0.005, sampleRate: sr)
|
||
let samples: [Double] = collectBlocks(limiter, engine: engine, blocks: 200)
|
||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 100))
|
||
let peak: Double = tail.map { abs(Double($0)) }.max() ?? 0
|
||
#expect(peak <= maxAmp + 0.001)
|
||
}
|
||
|
||
/// DC at 2.0, maxAmplitude=1.0, lookAheadTime=0 (no delay).
|
||
/// windowPeak = 2.0, requiredGain = 0.5 (instantaneous attack).
|
||
/// Steady-state output = 2.0 × 0.5 = 1.0.
|
||
@Test func exactLimitingOfKnownDCSignal() {
|
||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(2.0)
|
||
let limiter: LookAheadLimiter = LookAheadLimiter(in: dc, maxAmplitude: 1.0,
|
||
lookAheadTime: 0.0, sampleRate: sr)
|
||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||
let block: [Double] = limiter.calculatedSamples(graph: g, count: engine.blockSize)[0]
|
||
// With instant attack and DC, every sample after the first should be exactly 1.0.
|
||
let steadySample: Double = Double(block[engine.blockSize - 1])
|
||
#expect(abs(steadySample - 1.0) < 0.001)
|
||
}
|
||
|
||
/// Zero-look-ahead fast path is a pure peak follower (no ring, no deque).
|
||
/// A loud transient must clamp on the same sample (instantaneous attack), and after
|
||
/// the transient passes the gain must release back toward 1.0.
|
||
@Test func zeroLookAheadPeakFollowerInstantClamp() {
|
||
// Loud DC step at maxAmp=0.5 → instantaneous gain 0.5/2.0 = 0.25 → output = 0.5.
|
||
let maxAmp: Double = 0.5
|
||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(2.0)
|
||
let limiter: LookAheadLimiter = LookAheadLimiter(in: dc, maxAmplitude: maxAmp,
|
||
lookAheadTime: 0.0, sampleRate: sr)
|
||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||
let block: [Double] = limiter.calculatedSamples(graph: g, count: engine.blockSize)[0]
|
||
// Every sample (including the first) is clamped to maxAmp.
|
||
let peak: Double = block.map { abs(Double($0)) }.max() ?? 0
|
||
#expect(peak <= maxAmp + 1e-9)
|
||
// Steady state hits maxAmp exactly.
|
||
#expect(abs(Double(block[engine.blockSize - 1]) - maxAmp) < 1e-9)
|
||
}
|
||
|
||
/// Denormal flush moved to once-per-block (was per-sample).
|
||
/// Sustained extreme reduction (tiny maxAmp on loud DC) drives `_gain` toward a
|
||
/// very small value; the once-per-block flush must keep it from becoming a
|
||
/// denormal that would slow down the RT path. Render long enough (~2 s) to
|
||
/// flush many blocks and verify the output stream never produces NaN / inf
|
||
/// and remains bounded.
|
||
@Test func sustainedExtremeReductionStaysFinite() {
|
||
let maxAmp: Double = 1e-30 // extreme; gain → ~5e-31 in steady state
|
||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(2.0)
|
||
let limiter: LookAheadLimiter = LookAheadLimiter(in: dc, maxAmplitude: maxAmp,
|
||
lookAheadTime: 0.005, sampleRate: sr)
|
||
// ~2 seconds at blockSize 64 / sr 44100 → ~1378 blocks.
|
||
let blocks: Int = (Int(sr * 2.0) / engine.blockSize) + 1
|
||
let samples: [Double] = collectBlocks(limiter, engine: engine, blocks: blocks)
|
||
let badSamples: [Double] = samples.filter { !$0.isFinite }
|
||
#expect(badSamples.isEmpty)
|
||
// Output magnitudes stay near maxAmp once the look-ahead window warms up.
|
||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 100))
|
||
let tailMax: Double = tail.map { abs($0) }.max() ?? 0
|
||
#expect(tailMax < maxAmp * 10.0) // generous bound; really we want "small"
|
||
}
|
||
|
||
/// `releaseTime` is decoupled from `lookAheadTime`: with the look-ahead window held
|
||
/// fixed, two different release times must produce different gain-recovery behaviour
|
||
/// (hence different output) on a low-frequency signal that crosses the ceiling on its
|
||
/// peaks and dips below between them — while both still respect the ceiling.
|
||
@Test func releaseTimeIndependentOfLookAhead() {
|
||
let maxAmp: Double = 0.3
|
||
func run(_ releaseTime: Double) -> [Double] {
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: 60.0, mul: 1.0)
|
||
let lim: LookAheadLimiter = LookAheadLimiter(
|
||
in: sine, maxAmplitude: maxAmp,
|
||
lookAheadTime: 0.005, releaseTime: releaseTime, sampleRate: sr)
|
||
return collectBlocks(lim, engine: engine, blocks: 100)
|
||
}
|
||
let fast: [Double] = run(0.005)
|
||
let slow: [Double] = run(0.200)
|
||
// Ceiling holds for both release settings.
|
||
#expect(fast.allSatisfy { abs($0) <= maxAmp + 0.001 })
|
||
#expect(slow.allSatisfy { abs($0) <= maxAmp + 0.001 })
|
||
// Different release → different waveform.
|
||
let tailFast: [Double] = Array(fast.suffix(engine.blockSize * 50))
|
||
let tailSlow: [Double] = Array(slow.suffix(engine.blockSize * 50))
|
||
let ssd: Double = zip(tailFast, tailSlow).reduce(0.0) { acc, pair in
|
||
let diff: Double = pair.0 - pair.1
|
||
return acc + diff * diff
|
||
}
|
||
#expect(ssd > 0, "releaseTime had no effect on limiter output")
|
||
}
|
||
}
|
||
|
||
// MARK: - Compressor Tests
|
||
|
||
@MainActor
|
||
@Suite("Compressor")
|
||
struct CompressorTests {
|
||
|
||
let engine: SynthesisEngine
|
||
|
||
init() throws {
|
||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||
try engine.start()
|
||
}
|
||
|
||
@Test func signalBelowThresholdUnchanged() {
|
||
// Signal at -20 dBFS, threshold at -6 dB → no compression.
|
||
let amp: Float = Float(pow(10.0, -20.0 / 20.0)) // ≈ 0.1
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: Double(amp))
|
||
let comp: Compressor.Audio = Compressor.Audio(in: sine, threshold: -6.0, ratio: 4.0,
|
||
attack: 0.0, release: 0.0, makeupGain: 0.0)
|
||
let samples: [Double] = collectBlocks(comp, engine: engine, blocks: 50)
|
||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 20))
|
||
let rmsOut: Double = rmsD(tail)
|
||
let rmsIn: Double = Double(amp) / sqrt(2.0) // sine RMS
|
||
// Output RMS should be very close to input RMS (no compression).
|
||
#expect(abs(rmsOut - rmsIn) < 0.01)
|
||
}
|
||
|
||
@Test func signalAboveThresholdCompressed() {
|
||
// Signal at 0 dBFS (amplitude 1.0), threshold at -6 dB, ratio 4:1, instant attack.
|
||
// Expected: 6 dB over threshold → 6/4 = 1.5 dB output above threshold → gain ≈ -4.5 dB.
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 1.0)
|
||
let comp: Compressor.Audio = Compressor.Audio(in: sine, threshold: -6.0, ratio: 4.0,
|
||
attack: 0.0, release: 0.0, makeupGain: 0.0)
|
||
let samples: [Double] = collectBlocks(comp, engine: engine, blocks: 100)
|
||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 50))
|
||
let peak: Double = tail.map { abs($0) }.max() ?? 0
|
||
// Peak should be reduced below 1.0.
|
||
#expect(Double(peak) < 0.9)
|
||
}
|
||
|
||
@Test func makeupGainBoostsOutput() {
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 0.5)
|
||
let noMakeup: Compressor.Audio = Compressor.Audio(in: sine, threshold: -6.0, ratio: 1.0,
|
||
attack: 0.0, release: 0.0, makeupGain: 0.0)
|
||
let withMakeup: Compressor.Audio = Compressor.Audio(in: OscSin.Audio(freq: 100.0, mul: 0.5),
|
||
threshold: -6.0, ratio: 1.0,
|
||
attack: 0.0, release: 0.0, makeupGain: 6.0)
|
||
let ref: [Double] = collectBlocks(noMakeup, engine: engine, blocks: 50)
|
||
let boosted: [Double] = collectBlocks(withMakeup, engine: engine, blocks: 50)
|
||
let rmsRef: Double = rmsD(ref)
|
||
let rmsBoosted: Double = rmsD(boosted)
|
||
// +6 dB makeup ≈ ×2 amplitude → roughly 2× RMS.
|
||
#expect(rmsBoosted > rmsRef * 1.7)
|
||
}
|
||
|
||
@Test func controlVariantMatchesAudioWithinTolerance() {
|
||
let sine1: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 1.0)
|
||
let sine2: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 1.0)
|
||
let audioComp: Compressor.Audio = Compressor.Audio(in: sine1, threshold: -6.0, ratio: 4.0,
|
||
attack: 0.005, release: 0.1)
|
||
let ctrlComp: Compressor.Control = Compressor.Control(in: sine2, threshold: -6.0, ratio: 4.0,
|
||
attack: 0.005, release: 0.1)
|
||
let audioOut: [Double] = collectBlocks(audioComp, engine: engine, blocks: 100)
|
||
let ctrlOut: [Double] = collectBlocks(ctrlComp, engine: engine, blocks: 100)
|
||
let rmsAudio: Double = rmsD(audioOut)
|
||
let rmsCtrl: Double = rmsD(ctrlOut)
|
||
// Control and audio should be within 3 dB of each other.
|
||
let ratio: Double = max(rmsAudio, rmsCtrl) / (min(rmsAudio, rmsCtrl) + 1e-9)
|
||
#expect(ratio < 1.5)
|
||
}
|
||
|
||
@Test func softKneeSmoothsTransition() {
|
||
// With a soft knee, the gain reduction should start before the threshold.
|
||
// A signal right at threshold with soft knee should have some reduction vs none.
|
||
let threshDB: Double = -12.0
|
||
let amp: Float = Float(pow(10.0, threshDB / 20.0))
|
||
let sineHard: Compressor.Audio = Compressor.Audio(in: OscSin.Audio(freq: 100.0, mul: Double(amp)),
|
||
threshold: threshDB, ratio: 4.0,
|
||
attack: 0.0, release: 0.0, kneeWidth: 0.0)
|
||
let sineSoft: Compressor.Audio = Compressor.Audio(in: OscSin.Audio(freq: 100.0, mul: Double(amp)),
|
||
threshold: threshDB, ratio: 4.0,
|
||
attack: 0.0, release: 0.0, kneeWidth: 6.0)
|
||
let hardOut: [Double] = collectBlocks(sineHard, engine: engine, blocks: 50)
|
||
let softOut: [Double] = collectBlocks(sineSoft, engine: engine, blocks: 50)
|
||
// At threshold, both should produce similar (not wildly different) output.
|
||
let rmsHard: Double = rmsD(hardOut)
|
||
let rmsSoft: Double = rmsD(softOut)
|
||
let ratio: Double = max(rmsHard, rmsSoft) / (min(rmsHard, rmsSoft) + 1e-9)
|
||
#expect(ratio < 2.0)
|
||
}
|
||
|
||
@Test func generatorEnumConformance() {
|
||
let _: Compressor.Audio = Compressor.AudioType(in: 0.0)
|
||
let _: Compressor.Control = Compressor.ControlType(in: 0.0)
|
||
}
|
||
|
||
/// DC at 0 dBFS (1.0), threshold=-6 dB, ratio=4:1, instant attack/release.
|
||
/// gain_dB = (0 − (−6)) × (1/4 − 1) = 6 × (−0.75) = −4.5 dB
|
||
/// target = 10^(−4.5/20) ≈ 0.5957.
|
||
/// With attack=0, _prevGain collapses to target on first sample → steady-state output = target.
|
||
@Test func exactGainForKnownDCInput() {
|
||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||
let comp: Compressor.Audio = Compressor.Audio(in: dc, threshold: -6.0, ratio: 4.0,
|
||
attack: 0.0, release: 0.0, makeupGain: 0.0)
|
||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||
let block: [Double] = comp.calculatedSamples(graph: g, count: engine.blockSize)[0]
|
||
let expectedGain: Double = pow(10.0, -4.5 / 20.0)
|
||
let steadySample: Double = Double(block[engine.blockSize - 1])
|
||
// Steady-state DC output = 1.0 × gain = expectedGain.
|
||
#expect(abs(steadySample - expectedGain) < 0.001)
|
||
}
|
||
|
||
/// Once-per-block denormal flush survives sustained extreme reduction.
|
||
/// 1.0 DC at threshold=-60 dB ratio=20:1 with makeup -40 dB drives gain very low;
|
||
/// output must stay finite + bounded over ~2 s.
|
||
@Test func denormalCadenceCompressor() {
|
||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
|
||
let comp: Compressor.Audio = Compressor.Audio(
|
||
in: dc, threshold: -60.0, ratio: 20.0,
|
||
attack: 0.001, release: 0.001,
|
||
kneeWidth: 0.0, makeupGain: -40.0)
|
||
let blocks: Int = (Int(44100.0 * 2.0) / engine.blockSize) + 1
|
||
var sawNonFinite: Bool = false
|
||
var maxAbs: Double = 0.0
|
||
for _: Int in 0..<blocks {
|
||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||
let block: [Double] = comp.calculatedSamples(graph: g, count: engine.blockSize)[0]
|
||
for v: Double in block {
|
||
if !v.isFinite { sawNonFinite = true }
|
||
let a: Double = abs(v)
|
||
if a > maxAbs { maxAbs = a }
|
||
}
|
||
advanceBlock(engine)
|
||
}
|
||
#expect(!sawNonFinite, "Compressor output must remain finite")
|
||
#expect(maxAbs < 1.0, "heavily-reduced output must stay below input level")
|
||
}
|
||
}
|
||
|
||
// MARK: - Expander Tests
|
||
|
||
@MainActor
|
||
@Suite("Expander")
|
||
struct ExpanderTests {
|
||
|
||
let engine: SynthesisEngine
|
||
|
||
init() throws {
|
||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||
try engine.start()
|
||
}
|
||
|
||
@Test func signalAboveThresholdUnchanged() {
|
||
// Signal at 0 dBFS, threshold at -40 dB → above threshold, no expansion.
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 1.0)
|
||
let exp: Expander.Audio = Expander.Audio(in: sine, threshold: -40.0, ratio: 0.0,
|
||
attack: 0.0, release: 0.0)
|
||
let samples: [Double] = collectBlocks(exp, engine: engine, blocks: 50)
|
||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 20))
|
||
let rmsOut: Double = rmsD(tail)
|
||
// Input RMS ≈ 0.707. Output should be close.
|
||
#expect(rmsOut > 0.6)
|
||
}
|
||
|
||
@Test func gateRatioBelowThresholdSilences() {
|
||
// Signal at -40 dBFS, threshold at -20 dB, ratio 0.0 (gate).
|
||
let amp: Float = Float(pow(10.0, -40.0 / 20.0)) // −40 dBFS
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: Double(amp))
|
||
let gate: Expander.Audio = Expander.Audio(in: sine, threshold: -20.0, ratio: 0.0,
|
||
attack: 0.0, release: 0.0)
|
||
let samples: [Double] = collectBlocks(gate, engine: engine, blocks: 50)
|
||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 20))
|
||
let rmsOut: Double = rmsD(tail)
|
||
// Gate should suppress signal significantly (≤ −20 dB relative to input).
|
||
#expect(rmsOut < Double(amp) * 0.2)
|
||
}
|
||
|
||
@Test func expansionReducesLowLevelSignal() {
|
||
// Signal 20 dB below threshold. With ratio 0.5, gain_dB = 20 × (0.5 − 1) = −10 dB.
|
||
let amp: Float = Float(pow(10.0, -40.0 / 20.0)) // −40 dBFS
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: Double(amp))
|
||
let expander: Expander.Audio = Expander.Audio(in: sine, threshold: -20.0, ratio: 0.5,
|
||
attack: 0.0, release: 0.0)
|
||
let samples: [Double] = collectBlocks(expander, engine: engine, blocks: 50)
|
||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 20))
|
||
let rmsOut: Double = rmsD(tail)
|
||
// Output should be lower than input.
|
||
#expect(rmsOut < Double(amp) * 0.8)
|
||
}
|
||
|
||
@Test func controlVariantMatchesAudioWithinTolerance() {
|
||
// Use signal well above threshold so both variants see no expansion.
|
||
let sine1: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 0.5)
|
||
let sine2: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 0.5)
|
||
let audioExp: Expander.Audio = Expander.Audio(in: sine1, threshold: -40.0, ratio: 0.5,
|
||
attack: 0.005, release: 0.1)
|
||
let ctrlExp: Expander.Control = Expander.Control(in: sine2, threshold: -40.0, ratio: 0.5,
|
||
attack: 0.005, release: 0.1)
|
||
let audioOut: [Double] = collectBlocks(audioExp, engine: engine, blocks: 100)
|
||
let ctrlOut: [Double] = collectBlocks(ctrlExp, engine: engine, blocks: 100)
|
||
let rmsAudio: Double = rmsD(audioOut)
|
||
let rmsCtrl: Double = rmsD(ctrlOut)
|
||
let ratio: Double = max(rmsAudio, rmsCtrl) / (min(rmsAudio, rmsCtrl) + 1e-9)
|
||
#expect(ratio < 1.5)
|
||
}
|
||
|
||
@Test func generatorEnumConformance() {
|
||
let _: Expander.Audio = Expander.AudioType(in: 0.0)
|
||
let _: Expander.Control = Expander.ControlType(in: 0.0)
|
||
}
|
||
|
||
@Test func bypassRatioOneNoChange() {
|
||
// ratio = 1.0 → gain_dB = 0 at all levels, output equals input.
|
||
let amp: Double = 0.02
|
||
let sine: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: amp)
|
||
let bypass: Expander.Audio = Expander.Audio(in: sine, threshold: -20.0, ratio: 1.0,
|
||
attack: 0.0, release: 0.0)
|
||
let samples: [Double] = collectBlocks(bypass, engine: engine, blocks: 50)
|
||
let rmsOut: Double = rmsD(samples)
|
||
let rmsIn: Double = Double(amp) / sqrt(2.0)
|
||
#expect(abs(rmsOut - rmsIn) < 0.005)
|
||
}
|
||
|
||
/// DC at −40 dBFS (0.01), threshold=−20 dB, ratio=0.5, instant.
|
||
/// diff = −40 − (−20) = −20 dB. gain_dB = −20 × (1/0.5 − 1) = −20 × 1 = −20 dB.
|
||
/// target = 10^(−20/20) = 0.1. output = 0.01 × 0.1 = 0.001.
|
||
@Test func exactGainForKnownDCInput() {
|
||
let inputAmp: Double = 0.01 // −40 dBFS
|
||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(inputAmp)
|
||
let expander: Expander.Audio = Expander.Audio(in: dc, threshold: -20.0, ratio: 0.5,
|
||
attack: 0.0, release: 0.0)
|
||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||
let block: [Double] = expander.calculatedSamples(graph: g, count: engine.blockSize)[0]
|
||
let expectedOutput: Double = inputAmp * 0.1 // gain = −20 dB = 0.1 linear
|
||
let steadySample: Double = Double(block[engine.blockSize - 1])
|
||
#expect(abs(steadySample - expectedOutput) < 0.0001)
|
||
}
|
||
|
||
/// Once-per-block denormal flush survives the gate path.
|
||
/// ratio=0 (hard gate) on a sub-threshold signal drives gain → 1e-6 (−120 dB
|
||
/// floor); output must stay finite + bounded over ~2 s.
|
||
@Test func denormalCadenceExpander() {
|
||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(0.001) // −60 dBFS
|
||
let exp: Expander.Audio = Expander.Audio(
|
||
in: dc, threshold: -20.0, ratio: 0.0,
|
||
attack: 0.001, release: 0.001, kneeWidth: 0.0)
|
||
let blocks: Int = (Int(44100.0 * 2.0) / engine.blockSize) + 1
|
||
var sawNonFinite: Bool = false
|
||
var maxAbs: Double = 0.0
|
||
for _: Int in 0..<blocks {
|
||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||
let block: [Double] = exp.calculatedSamples(graph: g, count: engine.blockSize)[0]
|
||
for v: Double in block {
|
||
if !v.isFinite { sawNonFinite = true }
|
||
let a: Double = abs(v)
|
||
if a > maxAbs { maxAbs = a }
|
||
}
|
||
advanceBlock(engine)
|
||
}
|
||
#expect(!sawNonFinite, "Expander output must remain finite")
|
||
#expect(maxAbs < 0.001, "gated output must stay near silence")
|
||
}
|
||
}
|