prep for 1.2.0 release updates
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
// AmplitudeFollowerParameterRampingTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@MainActor
|
||||
@Suite("AmplitudeFollower parameter ramping")
|
||||
struct AmplitudeFollowerParameterRampingTests {
|
||||
|
||||
@Test func attackTimeGeneratorInputIsRead() throws {
|
||||
// Verify that wiring a ParameterNode to attackTime does not crash and produces output.
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let attackNode: ParameterNode = ParameterNode(0.01)
|
||||
let releaseNode: ParameterNode = ParameterNode(0.1)
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let follower: AmplitudeFollower.Audio = AmplitudeFollower.Audio(in: signal, attackTime: attackNode,
|
||||
releaseTime: releaseNode)
|
||||
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = follower.calculatedSamples(graph: g, count: 64)
|
||||
#expect(out.count == 1, "AmplitudeFollower should produce 1 channel")
|
||||
let hasEnergy: Bool = (out.first ?? []).prefix(64).contains { $0 > 0 }
|
||||
#expect(hasEnergy, "AmplitudeFollower with sine input should produce non-zero output")
|
||||
}
|
||||
|
||||
@Test func controlAttackTimeGeneratorInputIsRead() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let attackNode: ParameterNode = ParameterNode(0.01)
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let follower: AmplitudeFollower.Control = AmplitudeFollower.Control(in: signal, attackTime: attackNode)
|
||||
|
||||
// Warm up one block to prime the follower.
|
||||
let g1: SynthGraph = makeSynthGraph(engine: engine)
|
||||
_ = follower.calculatedSamples(graph: g1, count: 64)
|
||||
advanceBlock(engine)
|
||||
|
||||
// Change attack time via the ParameterNode and verify no crash/invalid output.
|
||||
attackNode.value = 0.5
|
||||
let g2: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out2: [[Double]] = follower.calculatedSamples(graph: g2, count: 64)
|
||||
let samples: [Double] = Array((out2.first ?? []).prefix(64))
|
||||
#expect(samples.allSatisfy { $0.isFinite },
|
||||
"AmplitudeFollower.Control output must remain finite after attackTime change")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
// BalanceTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@MainActor
|
||||
@Suite("Balance")
|
||||
struct BalanceTests {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
|
||||
init() throws {
|
||||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
@Test func quietInMatchedUpToTestRMS() {
|
||||
// in: quiet sine (amp 0.2); test: louder sine (amp 0.5). Output amplitude
|
||||
// should rise to ~0.5 → RMS ≈ 0.5/√2 ≈ 0.354.
|
||||
let quiet: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.2)
|
||||
let loud: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.5)
|
||||
let bal: Balance = Balance(in: quiet, test: loud)
|
||||
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 300)
|
||||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 100))
|
||||
let expected: Double = 0.5 / 2.0.squareRoot()
|
||||
#expect(abs(rmsValue(tail) - expected) < 0.02)
|
||||
}
|
||||
|
||||
@Test func loudInMatchedDownToTestRMS() {
|
||||
let loud: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 1.0)
|
||||
let quiet: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.3)
|
||||
let bal: Balance = Balance(in: loud, test: quiet)
|
||||
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 300)
|
||||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 100))
|
||||
let expected: Double = 0.3 / 2.0.squareRoot()
|
||||
#expect(abs(rmsValue(tail) - expected) < 0.02)
|
||||
}
|
||||
|
||||
@Test func dcSteadyStateMatchesTestLevel() {
|
||||
// in DC 0.25, test DC 0.5. ms_in → 0.0625, ms_test → 0.25,
|
||||
// gain → sqrt(0.25/0.0625) = 2, out → 0.25·2 = 0.5 = test level.
|
||||
let inDC: ConstantGeneratorInput = ConstantGeneratorInput(0.25)
|
||||
let testDC: ConstantGeneratorInput = ConstantGeneratorInput(0.5)
|
||||
let bal: Balance = Balance(in: inDC, test: testDC)
|
||||
let all: [Double] = collectBlocks(bal, engine: engine, blocks: 400)
|
||||
let tail: [Double] = Array(all.suffix(engine.blockSize * 50))
|
||||
let avg: Double = tail.reduce(0.0, +) / Double(tail.count)
|
||||
#expect(abs(avg - 0.5) < 0.01)
|
||||
}
|
||||
|
||||
@Test func silenceStaysSilentAndFinite() {
|
||||
let inSil: ConstantGeneratorInput = ConstantGeneratorInput(0.0)
|
||||
let testSil: ConstantGeneratorInput = ConstantGeneratorInput(0.0)
|
||||
let bal: Balance = Balance(in: inSil, test: testSil)
|
||||
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 50)
|
||||
#expect(samples.allSatisfy { $0.isFinite })
|
||||
#expect(rmsValue(samples) < 1e-9)
|
||||
}
|
||||
|
||||
@Test func silentTestDrivesInputDown() {
|
||||
// test is silent → in should be scaled toward zero (can't match RMS of silence).
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.5)
|
||||
let testSil: ConstantGeneratorInput = ConstantGeneratorInput(0.0)
|
||||
let bal: Balance = Balance(in: sine, test: testSil)
|
||||
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 200)
|
||||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 50))
|
||||
#expect(rmsValue(tail) < 0.01)
|
||||
#expect(samples.allSatisfy { $0.isFinite })
|
||||
}
|
||||
|
||||
@Test func silentInputStaysSilent() {
|
||||
// in is silent → output stays zero regardless of loud test (0 has no RMS to scale).
|
||||
let inSil: ConstantGeneratorInput = ConstantGeneratorInput(0.0)
|
||||
let loud: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.8)
|
||||
let bal: Balance = Balance(in: inSil, test: loud)
|
||||
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 100)
|
||||
#expect(samples.allSatisfy { $0.isFinite })
|
||||
#expect(rmsValue(samples) < 1e-9)
|
||||
}
|
||||
|
||||
@Test func hpControlsTrackingWindow() {
|
||||
// Both hp settings converge to the same steady-state DC level; just verify
|
||||
// both are finite and matched (window length affects speed, not target).
|
||||
let inDC: ConstantGeneratorInput = ConstantGeneratorInput(0.25)
|
||||
let testDC: ConstantGeneratorInput = ConstantGeneratorInput(0.5)
|
||||
let slow: Balance = Balance(in: inDC, test: testDC, hp: 2.0)
|
||||
let fast: Balance = Balance(in: ConstantGeneratorInput(0.25),
|
||||
test: ConstantGeneratorInput(0.5), hp: 50.0)
|
||||
let slowTail: [Double] = Array(collectBlocks(slow, engine: engine, blocks: 600).suffix(engine.blockSize * 50))
|
||||
let fastTail: [Double] = Array(collectBlocks(fast, engine: engine, blocks: 600).suffix(engine.blockSize * 50))
|
||||
let slowAvg: Double = slowTail.reduce(0.0, +) / Double(slowTail.count)
|
||||
let fastAvg: Double = fastTail.reduce(0.0, +) / Double(fastTail.count)
|
||||
#expect(abs(slowAvg - 0.5) < 0.02)
|
||||
#expect(abs(fastAvg - 0.5) < 0.02)
|
||||
}
|
||||
|
||||
@Test func mulScalesOutput() {
|
||||
let inDC: ConstantGeneratorInput = ConstantGeneratorInput(0.25)
|
||||
let testDC: ConstantGeneratorInput = ConstantGeneratorInput(0.5)
|
||||
let plain: Balance = Balance(in: ConstantGeneratorInput(0.25),
|
||||
test: ConstantGeneratorInput(0.5))
|
||||
let scaled: Balance = Balance(in: inDC, test: testDC, mul: 0.5)
|
||||
let p: [Double] = Array(collectBlocks(plain, engine: engine, blocks: 400).suffix(engine.blockSize * 50))
|
||||
let s: [Double] = Array(collectBlocks(scaled, engine: engine, blocks: 400).suffix(engine.blockSize * 50))
|
||||
let pAvg: Double = p.reduce(0.0, +) / Double(p.count)
|
||||
let sAvg: Double = s.reduce(0.0, +) / Double(s.count)
|
||||
#expect(abs(sAvg - 0.5 * pAvg) < 0.01)
|
||||
}
|
||||
|
||||
@Test func finiteWithNoise() {
|
||||
let bal: Balance = Balance(in: WhiteNoise.Audio(mul: 0.1),
|
||||
test: WhiteNoise.Audio(mul: 0.5))
|
||||
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 200)
|
||||
#expect(samples.allSatisfy { $0.isFinite })
|
||||
}
|
||||
|
||||
// MARK: - smooth (decoupled gain lag)
|
||||
|
||||
@Test func smoothDefaultIsBackwardCompatible() {
|
||||
// smooth == 0.0 (default) must reproduce the un-smoothed steady-state exactly.
|
||||
let bal: Balance = Balance(in: ConstantGeneratorInput(0.25),
|
||||
test: ConstantGeneratorInput(0.5), smooth: 0.0)
|
||||
let all: [Double] = collectBlocks(bal, engine: engine, blocks: 400)
|
||||
let tail: [Double] = Array(all.suffix(engine.blockSize * 50))
|
||||
let avg: Double = tail.reduce(0.0, +) / Double(tail.count)
|
||||
#expect(abs(avg - 0.5) < 0.01)
|
||||
}
|
||||
|
||||
@Test func smoothPreservesSteadyLevel() {
|
||||
// A gain lag must not change the converged level, only the path to it.
|
||||
let bal: Balance = Balance(in: ConstantGeneratorInput(0.25),
|
||||
test: ConstantGeneratorInput(0.5), smooth: 0.05)
|
||||
let all: [Double] = collectBlocks(bal, engine: engine, blocks: 600)
|
||||
let tail: [Double] = Array(all.suffix(engine.blockSize * 50))
|
||||
let avg: Double = tail.reduce(0.0, +) / Double(tail.count)
|
||||
#expect(abs(avg - 0.5) < 0.01)
|
||||
}
|
||||
|
||||
@Test func largerSmoothSlowsInitialResponse() {
|
||||
// From the unity-gain start, a quiet-in/loud-test pair needs gain > 1. With a gain
|
||||
// lag the early output rises more slowly, so its early-window RMS is lower; both
|
||||
// converge to the same tail level.
|
||||
let unsmoothed: Balance = Balance(in: OscSin.Audio(freq: 200.0, mul: 0.2),
|
||||
test: OscSin.Audio(freq: 200.0, mul: 0.5), smooth: 0.0)
|
||||
let smoothed: Balance = Balance(in: OscSin.Audio(freq: 200.0, mul: 0.2),
|
||||
test: OscSin.Audio(freq: 200.0, mul: 0.5), smooth: 0.1)
|
||||
let u: [Double] = collectBlocks(unsmoothed, engine: engine, blocks: 300)
|
||||
let s: [Double] = collectBlocks(smoothed, engine: engine, blocks: 300)
|
||||
|
||||
let earlyWin: Int = engine.blockSize * 15
|
||||
#expect(rmsValue(Array(u.prefix(earlyWin))) > rmsValue(Array(s.prefix(earlyWin))))
|
||||
|
||||
let target: Double = 0.5 / 2.0.squareRoot()
|
||||
#expect(abs(rmsValue(Array(u.suffix(engine.blockSize * 100))) - target) < 0.02)
|
||||
#expect(abs(rmsValue(Array(s.suffix(engine.blockSize * 100))) - target) < 0.02)
|
||||
}
|
||||
|
||||
// MARK: - logDomain (decibel-domain gain glide)
|
||||
|
||||
@Test func logDomainDCSteadyStateMatchesTestLevel() {
|
||||
let bal: Balance = Balance(in: ConstantGeneratorInput(0.25),
|
||||
test: ConstantGeneratorInput(0.5), smooth: 0.02, logDomain: true)
|
||||
let all: [Double] = collectBlocks(bal, engine: engine, blocks: 500)
|
||||
let tail: [Double] = Array(all.suffix(engine.blockSize * 50))
|
||||
let avg: Double = tail.reduce(0.0, +) / Double(tail.count)
|
||||
#expect(abs(avg - 0.5) < 0.01)
|
||||
}
|
||||
|
||||
@Test func logDomainQuietSineMatchedUpToTestRMS() {
|
||||
let quiet: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.2)
|
||||
let loud: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.5)
|
||||
let bal: Balance = Balance(in: quiet, test: loud, smooth: 0.02, logDomain: true)
|
||||
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 500)
|
||||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 100))
|
||||
let expected: Double = 0.5 / 2.0.squareRoot()
|
||||
#expect(abs(rmsValue(tail) - expected) < 0.02)
|
||||
}
|
||||
|
||||
@Test func logDomainSilenceStaysSilentAndFinite() {
|
||||
let bal: Balance = Balance(in: ConstantGeneratorInput(0.0),
|
||||
test: ConstantGeneratorInput(0.0), logDomain: true)
|
||||
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 50)
|
||||
#expect(samples.allSatisfy { $0.isFinite })
|
||||
#expect(rmsValue(samples) < 1e-9)
|
||||
}
|
||||
|
||||
@Test func logDomainSilentInputStaysSilent() {
|
||||
let bal: Balance = Balance(in: ConstantGeneratorInput(0.0),
|
||||
test: OscSin.Audio(freq: 200.0, mul: 0.8), logDomain: true)
|
||||
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 100)
|
||||
#expect(samples.allSatisfy { $0.isFinite })
|
||||
#expect(rmsValue(samples) < 1e-9)
|
||||
}
|
||||
|
||||
@Test func logDomainSilentTestDrivesInputDown() {
|
||||
let bal: Balance = Balance(in: OscSin.Audio(freq: 200.0, mul: 0.5),
|
||||
test: ConstantGeneratorInput(0.0), smooth: 0.02, logDomain: true)
|
||||
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 300)
|
||||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 50))
|
||||
#expect(rmsValue(tail) < 0.01)
|
||||
#expect(samples.allSatisfy { $0.isFinite })
|
||||
}
|
||||
|
||||
@Test func logDomainMulScalesOutput() {
|
||||
let plain: Balance = Balance(in: ConstantGeneratorInput(0.25),
|
||||
test: ConstantGeneratorInput(0.5), smooth: 0.02, logDomain: true)
|
||||
let scaled: Balance = Balance(in: ConstantGeneratorInput(0.25),
|
||||
test: ConstantGeneratorInput(0.5), smooth: 0.02, logDomain: true, mul: 0.5)
|
||||
let p: [Double] = Array(collectBlocks(plain, engine: engine, blocks: 500).suffix(engine.blockSize * 50))
|
||||
let s: [Double] = Array(collectBlocks(scaled, engine: engine, blocks: 500).suffix(engine.blockSize * 50))
|
||||
let pAvg: Double = p.reduce(0.0, +) / Double(p.count)
|
||||
let sAvg: Double = s.reduce(0.0, +) / Double(s.count)
|
||||
#expect(abs(sAvg - 0.5 * pAvg) < 0.01)
|
||||
}
|
||||
|
||||
@Test func logDomainFiniteWithNoise() {
|
||||
let bal: Balance = Balance(in: WhiteNoise.Audio(mul: 0.1),
|
||||
test: WhiteNoise.Audio(mul: 0.5), logDomain: true)
|
||||
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 200)
|
||||
#expect(samples.allSatisfy { $0.isFinite })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// CompressorParameterRampingTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@MainActor
|
||||
@Suite("Compressor parameter ramping")
|
||||
struct CompressorParameterRampingTests {
|
||||
|
||||
@Test func thresholdGeneratorInputIsRead() throws {
|
||||
// Verify wiring a ParameterNode to threshold produces valid output.
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let threshNode: ParameterNode = ParameterNode(-6.0)
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.5)
|
||||
let comp: Compressor.Audio = Compressor.Audio(in: signal, threshold: threshNode)
|
||||
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = comp.calculatedSamples(graph: g, count: 64)
|
||||
let samples: [Double] = Array((out.first ?? []).prefix(64))
|
||||
#expect(samples.allSatisfy { $0.isFinite },
|
||||
"Compressor.Audio output must be finite with ParameterNode threshold")
|
||||
}
|
||||
|
||||
@Test func thresholdParameterNodeOutputDiffersByBlock() throws {
|
||||
// Verify that the ParameterNode-wired threshold is read (not ignored).
|
||||
// Two separate Compressor instances with instant attack (attack=0):
|
||||
// - comp1: threshold = -20 dB → signal at -6 dBFS is well above threshold → heavy compression
|
||||
// - comp2: threshold = 0 dB → signal is below threshold → bypass (no compression)
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let signal1: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.5)
|
||||
let signal2: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.5)
|
||||
|
||||
// threshNode1: -20 dB → signal at ~-6 dBFS is 14 dB above threshold → compression
|
||||
let threshNode1: ParameterNode = ParameterNode(-20.0)
|
||||
let comp1: Compressor.Audio = Compressor.Audio(in: signal1, threshold: threshNode1,
|
||||
ratio: 100.0, attack: 0.0, release: 0.0)
|
||||
|
||||
// threshNode2: 0 dB → signal is below threshold → no compression
|
||||
let threshNode2: ParameterNode = ParameterNode(0.0)
|
||||
let comp2: Compressor.Audio = Compressor.Audio(in: signal2, threshold: threshNode2,
|
||||
ratio: 100.0, attack: 0.0, release: 0.0)
|
||||
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out1: [[Double]] = comp1.calculatedSamples(graph: g, count: 64)
|
||||
let out2: [[Double]] = comp2.calculatedSamples(graph: g, count: 64)
|
||||
|
||||
let rms1: Double = rmsValue(Array((out1.first ?? []).prefix(64)))
|
||||
let rms2: Double = rmsValue(Array((out2.first ?? []).prefix(64)))
|
||||
|
||||
// comp1 compresses aggressively (14 dB above threshold, ratio 100:1, instant attack).
|
||||
// comp2 passes through unchanged. rms1 should be significantly less than rms2.
|
||||
#expect(rms1 < rms2 * 0.5,
|
||||
"ParameterNode threshold at -20dB with ratio=100 should heavily compress vs threshold=0dB: rms1=\(rms1) rms2=\(rms2)")
|
||||
}
|
||||
|
||||
@Test func controlThresholdGeneratorInputIsRead() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let threshNode: ParameterNode = ParameterNode(-6.0)
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.5)
|
||||
let comp: Compressor.Control = Compressor.Control(in: signal, threshold: threshNode)
|
||||
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = comp.calculatedSamples(graph: g, count: 64)
|
||||
let samples: [Double] = Array((out.first ?? []).prefix(64))
|
||||
#expect(samples.allSatisfy { $0.isFinite },
|
||||
"Compressor.Control output must be finite with ParameterNode threshold")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,698 @@
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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"
|
||||
}
|
||||
}
|
||||
|
||||
// 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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// ExpanderParameterRampingTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@MainActor
|
||||
@Suite("Expander parameter ramping")
|
||||
struct ExpanderParameterRampingTests {
|
||||
|
||||
@Test func thresholdGeneratorInputIsRead() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let threshNode: ParameterNode = ParameterNode(-40.0)
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.1)
|
||||
let expander: Expander.Audio = Expander.Audio(in: signal, threshold: threshNode)
|
||||
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = expander.calculatedSamples(graph: g, count: 64)
|
||||
let samples: [Double] = Array((out.first ?? []).prefix(64))
|
||||
#expect(samples.allSatisfy { $0.isFinite },
|
||||
"Expander.Audio output must be finite with ParameterNode threshold")
|
||||
}
|
||||
|
||||
@Test func thresholdParameterRampChangesGain() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
// Start with threshold well above signal (-10 dB, signal ~0.1 ≈ -20 dB) → expansion active.
|
||||
let threshNode: ParameterNode = ParameterNode(-10.0)
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.1)
|
||||
let expander: Expander.Audio = Expander.Audio(in: signal, threshold: threshNode, ratio: 0.0) // gate
|
||||
|
||||
let g1: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out1: [[Double]] = expander.calculatedSamples(graph: g1, count: 64)
|
||||
advanceBlock(engine)
|
||||
|
||||
// Now set threshold very low (gate opens) → signal passes through.
|
||||
threshNode.value = -80.0
|
||||
let g2: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out2: [[Double]] = expander.calculatedSamples(graph: g2, count: 64)
|
||||
|
||||
let rms1: Double = rmsValue(Array((out1.first ?? []).prefix(64)))
|
||||
let rms2: Double = rmsValue(Array((out2.first ?? []).prefix(64)))
|
||||
// With gate open (threshold=-80dB), signal should pass more freely.
|
||||
#expect(rms2 > rms1,
|
||||
"After gate threshold ramp to -80dB, signal should pass more freely: \(rms2) vs \(rms1)")
|
||||
}
|
||||
|
||||
@Test func controlThresholdGeneratorInputIsRead() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let threshNode: ParameterNode = ParameterNode(-40.0)
|
||||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.1)
|
||||
let expander: Expander.Control = Expander.Control(in: signal, threshold: threshNode)
|
||||
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let out: [[Double]] = expander.calculatedSamples(graph: g, count: 64)
|
||||
let samples: [Double] = Array((out.first ?? []).prefix(64))
|
||||
#expect(samples.allSatisfy { $0.isFinite },
|
||||
"Expander.Control output must be finite with ParameterNode threshold")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
// NormalizerTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
private func peak(_ samples: [Double]) -> Double {
|
||||
samples.map { abs($0) }.max() ?? 0
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Suite("Normalizer")
|
||||
struct NormalizerTests {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
let sr: Double = 44100.0
|
||||
|
||||
init() throws {
|
||||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
}
|
||||
|
||||
@Test func quietSineNormalizedUpToLevel() {
|
||||
// A sine well below `level` is scaled UP so its steady-state peak ≈ level.
|
||||
let level: Double = 0.8
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.2)
|
||||
let norm: Normalizer = Normalizer(in: sine, level: level, dur: 0.01, sampleRate: sr)
|
||||
let samples: [Double] = collectBlocks(norm, engine: engine, blocks: 300)
|
||||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 100))
|
||||
let p: Double = peak(tail)
|
||||
#expect(p > level - 0.05)
|
||||
#expect(p < level + 0.02)
|
||||
}
|
||||
|
||||
@Test func loudSineNormalizedDownToLevel() {
|
||||
// A sine above `level` is scaled DOWN; steady-state peak ≈ level, no overshoot.
|
||||
let level: Double = 0.5
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 220.0, mul: 2.0)
|
||||
let norm: Normalizer = Normalizer(in: sine, level: level, dur: 0.01, sampleRate: sr)
|
||||
let samples: [Double] = collectBlocks(norm, engine: engine, blocks: 200)
|
||||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 100))
|
||||
let p: Double = peak(tail)
|
||||
#expect(p > level - 0.05)
|
||||
#expect(p < level + 0.001)
|
||||
}
|
||||
|
||||
@Test func peakNeverExceedsLevelOnTransient() {
|
||||
// Look-ahead must pre-emptively reduce gain so a sudden loud burst never
|
||||
// overshoots `level`.
|
||||
let level: Double = 0.5
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 110.0, mul: 3.0)
|
||||
let norm: Normalizer = Normalizer(in: sine, level: level, dur: 0.01, sampleRate: sr)
|
||||
let samples: [Double] = collectBlocks(norm, engine: engine, blocks: 200)
|
||||
let violators: [Double] = samples.filter { abs($0) > level + 0.001 }
|
||||
#expect(violators.isEmpty)
|
||||
}
|
||||
|
||||
@Test func delayedByDurSamples() {
|
||||
// An impulse at sample 0 appears delayed by Int(dur·sr); the first dur·sr
|
||||
// output samples are zero.
|
||||
let dur: Double = 0.003
|
||||
let delaySamples: Int = Int(dur * sr)
|
||||
let impulse: Impulse.Audio = Impulse.Audio(freq: 0.0)
|
||||
let norm: Normalizer = Normalizer(in: impulse, level: 1.0, dur: dur, sampleRate: sr)
|
||||
let blocks: Int = (delaySamples / engine.blockSize) + 5
|
||||
let samples: [Double] = collectBlocks(norm, engine: engine, blocks: blocks)
|
||||
let prefix: [Double] = Array(samples.prefix(delaySamples))
|
||||
#expect(prefix.allSatisfy { abs($0) < 0.001 })
|
||||
}
|
||||
|
||||
@Test func levelParamScales() {
|
||||
// Doubling `level` doubles the normalized steady-state peak.
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.3)
|
||||
let low: Normalizer = Normalizer(in: sine, level: 0.3, dur: 0.01, sampleRate: sr)
|
||||
let lowSamples: [Double] = collectBlocks(low, engine: engine, blocks: 300)
|
||||
|
||||
let sine2: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.3)
|
||||
let high: Normalizer = Normalizer(in: sine2, level: 0.6, dur: 0.01, sampleRate: sr)
|
||||
let highSamples: [Double] = collectBlocks(high, engine: engine, blocks: 300)
|
||||
|
||||
let pLow: Double = peak(Array(lowSamples.suffix(engine.blockSize * 100)))
|
||||
let pHigh: Double = peak(Array(highSamples.suffix(engine.blockSize * 100)))
|
||||
#expect(abs(pHigh - 2.0 * pLow) < 0.05)
|
||||
}
|
||||
|
||||
@Test func silenceStaysSilentAndFinite() {
|
||||
// Zero input must not blow up (no level/0 division producing NaN/Inf).
|
||||
let silence: ConstantGeneratorInput = ConstantGeneratorInput(0.0)
|
||||
let norm: Normalizer = Normalizer(in: silence, level: 1.0, dur: 0.01, sampleRate: sr)
|
||||
let samples: [Double] = collectBlocks(norm, engine: engine, blocks: 50)
|
||||
#expect(samples.allSatisfy { $0.isFinite })
|
||||
#expect(peak(samples) < 1e-9)
|
||||
}
|
||||
|
||||
@Test func dcConvergesToLevel() {
|
||||
// Constant DC v with level L → gain converges to L/v, output → L.
|
||||
let level: Double = 0.5
|
||||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(0.25)
|
||||
let norm: Normalizer = Normalizer(in: dc, level: level, dur: 0.01, sampleRate: sr)
|
||||
let all: [Double] = collectBlocks(norm, engine: engine, blocks: 300)
|
||||
let tail: [Double] = Array(all.suffix(engine.blockSize * 50))
|
||||
let avg: Double = tail.reduce(0.0, +) / Double(tail.count)
|
||||
#expect(abs(avg - level) < 0.01)
|
||||
}
|
||||
|
||||
@Test func zeroDelayNormalizesDownExactly() {
|
||||
// dur == 0 fast path: releaseCoeff == 0, attackComp == 1 → gain reaches
|
||||
// level/|x| within one sample. DC 2.0 at level 1.0 → every output == 1.0.
|
||||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(2.0)
|
||||
let norm: Normalizer = Normalizer(in: dc, level: 1.0, dur: 0.0, sampleRate: sr)
|
||||
let samples: [Double] = collectBlocks(norm, engine: engine, blocks: 2)
|
||||
#expect(samples.allSatisfy { abs($0 - 1.0) < 1e-12 })
|
||||
}
|
||||
|
||||
@Test func zeroDelayScalesUpExactly() {
|
||||
// dur == 0 fast path scaling up: DC 0.25 at level 1.0 → gain 4, output 1.0.
|
||||
let dc: ConstantGeneratorInput = ConstantGeneratorInput(0.25)
|
||||
let norm: Normalizer = Normalizer(in: dc, level: 1.0, dur: 0.0, sampleRate: sr)
|
||||
let samples: [Double] = collectBlocks(norm, engine: engine, blocks: 2)
|
||||
#expect(samples.allSatisfy { abs($0 - 1.0) < 1e-12 })
|
||||
}
|
||||
|
||||
@Test func finiteWithNoise() {
|
||||
let norm: Normalizer = Normalizer(in: WhiteNoise.Audio(mul: 0.4),
|
||||
level: 0.9, dur: 0.005, sampleRate: sr)
|
||||
let samples: [Double] = collectBlocks(norm, engine: engine, blocks: 200)
|
||||
#expect(samples.allSatisfy { $0.isFinite })
|
||||
// Peak should be bounded near level once settled.
|
||||
let tail: [Double] = Array(samples.suffix(engine.blockSize * 100))
|
||||
#expect(peak(tail) < 0.9 + 0.01)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user