prep for 1.2.0 release updates

This commit is contained in:
2026-06-21 11:45:58 -07:00
parent 73191c958f
commit 032b7c39d3
286 changed files with 21116 additions and 121 deletions
@@ -0,0 +1,226 @@
// ChorusTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("Chorus")
struct ChorusTests {
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
var graph: SynthGraph { makeSynthGraph(engine: engine) }
let testSampleRate: Double = 44100
init() throws {
try engine.start()
}
// MARK: - Deterministic first sample
@Test func firstSampleDeterministic() {
// input=0.5, depth=0, rate=0, mix=0.5 → first sample = 0.25 on both channels.
// Delay line starts all-zero; wet = 0; output = 0.5*(1-0.5) + 0*0.5 = 0.25.
let chorus: Chorus.Audio = Chorus.Audio(
input: ConstantGeneratorInput(0.5),
delayTime: 0.025,
depth: 0.0,
rate: 0.0,
mix: 0.5,
sampleRate: testSampleRate
)
let out: [[Double]] = chorus.calculatedSamples(graph: graph, count: 1)
let expected: Double = 0.25
#expect(abs(out[0][0] - expected) < 1e-10, "Left ch first sample must be \(expected)")
#expect(abs(out[1][0] - expected) < 1e-10, "Right ch first sample must be \(expected)")
}
// MARK: - Rate
@Test func rateIsAudio() {
let chorus: Chorus.Audio = Chorus.Audio(
input: 0.0,
sampleRate: testSampleRate
)
#expect(chorus.rate == .audio)
}
// MARK: - Output is stereo (2 channels)
@Test func outputIsStereo() {
let chorus: Chorus.Audio = Chorus.Audio(
input: ConstantGeneratorInput(0.5),
sampleRate: testSampleRate
)
let out: [[Double]] = chorus.calculatedSamples(graph: graph, count: 512)
#expect(out.count == 2, "Chorus.Audio must produce exactly 2 output channels")
#expect(out[0].count >= 512, "Channel 0 must have at least 512 samples")
#expect(out[1].count >= 512, "Channel 1 must have at least 512 samples")
}
// MARK: - Silent input → near-zero output
@Test func silentInputProducesNearZeroOutput() {
let chorus: Chorus.Audio = Chorus.Audio(
input: 0.0,
mix: 0.5,
sampleRate: testSampleRate
)
let out: [[Double]] = chorus.calculatedSamples(graph: graph, count: 512)
let samplesL: [Double] = Array(out[0].prefix(512))
let samplesR: [Double] = Array(out[1].prefix(512))
let allNearZeroL: Bool = samplesL.allSatisfy { abs($0) < 1e-12 }
let allNearZeroR: Bool = samplesR.allSatisfy { abs($0) < 1e-12 }
#expect(allNearZeroL, "Left channel: zero input must produce near-zero output")
#expect(allNearZeroR, "Right channel: zero input must produce near-zero output")
}
// MARK: - Non-silent input produces non-zero output
@Test func nonSilentInputProducesNonZeroOutput() {
let chorus: Chorus.Audio = Chorus.Audio(
input: ConstantGeneratorInput(0.5),
mix: 0.5,
sampleRate: testSampleRate
)
// Let delay line fill.
for _ in 0..<5 {
_ = chorus.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let out: [[Double]] = chorus.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
let rmsL: Double = rmsValue(Array(out[0].prefix(512)))
let rmsR: Double = rmsValue(Array(out[1].prefix(512)))
#expect(rmsL > 0, "Left channel must have non-zero output with non-silent input")
#expect(rmsR > 0, "Right channel must have non-zero output with non-silent input")
}
// MARK: - Left and right channels are distinct (LFOs 180° apart)
@Test func leftAndRightChannelsAreDistinct() {
// With a varying input (sine wave), different delay offsets driven by the two LFOs
// (180° apart) will read different values from the delay line, producing distinct
// left and right outputs. Use mix=1.0 (all wet) so only tap differences matter.
let input: OscSin.Audio = OscSin.Audio(freq: 880.0)
let chorus: Chorus.Audio = Chorus.Audio(
input: input,
delayTime: 0.010,
depth: 0.9,
rate: 5.0,
mix: 1.0,
sampleRate: testSampleRate
)
// Let delay line fill with the sine wave content and LFOs diverge.
for _ in 0..<20 {
_ = chorus.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let out: [[Double]] = chorus.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
let anyDiff: Bool = zip(out[0].prefix(512), out[1].prefix(512))
.contains { abs($0 - $1) > 1e-8 }
#expect(anyDiff, "Left and right channels must differ due to 180° LFO phase offset")
}
// MARK: - Fan-out
@Test func fanOutSingleEvaluation() {
let chorus: Chorus.Audio = Chorus.Audio(
input: ConstantGeneratorInput(0.3),
sampleRate: testSampleRate
)
let out1: [[Double]] = chorus.calculatedSamples(graph: graph, count: 512)
let out2: [[Double]] = chorus.calculatedSamples(graph: graph, count: 512)
let s1L: [Double] = Array(out1[0].prefix(512))
let s2L: [Double] = Array(out2[0].prefix(512))
let s1R: [Double] = Array(out1[1].prefix(512))
let s2R: [Double] = Array(out2[1].prefix(512))
#expect(s1L == s2L, "Fan-out: left channel must be identical on second call in same segment")
#expect(s1R == s2R, "Fan-out: right channel must be identical on second call in same segment")
}
// MARK: - State advances once per block
@Test func stateAdvancesOncePerBlock() {
let chorus: Chorus.Audio = Chorus.Audio(
input: ConstantGeneratorInput(0.3),
sampleRate: testSampleRate
)
_ = chorus.calculatedSamples(graph: graph, count: 512)
_ = chorus.calculatedSamples(graph: graph, count: 512) // cache hit
advanceBlock(engine)
let block2: [[Double]] = chorus.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
let allFiniteL: Bool = Array(block2[0].prefix(512)).allSatisfy { $0.isFinite }
let allFiniteR: Bool = Array(block2[1].prefix(512)).allSatisfy { $0.isFinite }
#expect(allFiniteL, "Left channel must be finite after block advance")
#expect(allFiniteR, "Right channel must be finite after block advance")
}
// MARK: - mulAdd applied
@Test func mulAddApplied() {
// Zero input → zero wet and dry → output 0. After mul:2 add:1 → output 1.
let chorus: Chorus.Audio = Chorus.Audio(
input: 0.0,
mix: 0.5,
sampleRate: testSampleRate,
mul: 2.0,
add: 1.0
)
let out: [[Double]] = chorus.calculatedSamples(graph: graph, count: 512)
let samplesL: [Double] = Array(out[0].prefix(512))
let samplesR: [Double] = Array(out[1].prefix(512))
let allNearOneL: Bool = samplesL.allSatisfy { abs($0 - 1.0) < 1e-10 }
let allNearOneR: Bool = samplesR.allSatisfy { abs($0 - 1.0) < 1e-10 }
#expect(allNearOneL, "Left channel: mulAdd(mul:2, add:1) on zero input must produce 1.0")
#expect(allNearOneR, "Right channel: mulAdd(mul:2, add:1) on zero input must produce 1.0")
}
// MARK: - Channel aliases
@Test func channelAliasesMatchSubscripts() {
let chorus: Chorus.Audio = Chorus.Audio(
input: ConstantGeneratorInput(0.5),
sampleRate: testSampleRate
)
let leftOut: [[Double]] = chorus.left.calculatedSamples(graph: graph, count: 64)
let rightOut: [[Double]] = chorus.right.calculatedSamples(graph: graph, count: 64)
let fullOut: [[Double]] = chorus.calculatedSamples(graph: graph, count: 64)
for i: Int in 0..<64 {
#expect(abs(leftOut[0][i] - fullOut[0][i]) < 1e-10,
"left alias must match channel 0 at index \(i)")
#expect(abs(rightOut[0][i] - fullOut[1][i]) < 1e-10,
"right alias must match channel 1 at index \(i)")
}
}
// MARK: - Integration with engine
@Test func integrationWithEngine() throws {
final class ChorusSynth: SynthesizerBase {
override func build() {
let chorus: Chorus.Audio = Chorus.Audio(
input: OscSin.Audio(freq: 220.0),
delayTime: 0.025,
depth: 0.002,
rate: 1.5,
mix: 0.5,
sampleRate: 44100
)
addOutputGenerator(Out.Audio(bus: 0, source: chorus.left))
addOutputGenerator(Out.Audio(bus: 1, source: chorus.right))
}
}
let intEngine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
try intEngine.start()
let synth: ChorusSynth = ChorusSynth()
try intEngine.add(synth)
for _ in 0..<4 {
intEngine.processBlock(inputSamples: [])
}
intEngine.stop()
}
}
@@ -0,0 +1,222 @@
// FlangerTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("Flanger")
struct FlangerTests {
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
var graph: SynthGraph { makeSynthGraph(engine: engine) }
let testSampleRate: Double = 44100
init() throws {
try engine.start()
}
// MARK: - Deterministic first sample
@Test func firstSampleDeterministic() {
// input=0.5, depth=0, rate=0, feedback=0, mix=0.5 → first sample always 0.25.
// Delay line starts all-zero; wet signal = 0; output = dry*(1-0.5) + 0*0.5 = 0.25.
let flanger: Flanger.Audio = Flanger.Audio(
input: ConstantGeneratorInput(0.5),
delayTime: 0.005,
depth: 0.0,
rate: 0.0,
feedback: 0.0,
mix: 0.5,
sampleRate: testSampleRate
)
let out: [[Double]] = flanger.calculatedSamples(graph: graph, count: 1)
let expected: Double = 0.25
#expect(abs(out[0][0] - expected) < 1e-10, "First sample must be \(expected), got \(out[0][0])")
}
// MARK: - Rate
@Test func rateIsAudio() {
let flanger: Flanger.Audio = Flanger.Audio(
input: 0.0,
sampleRate: testSampleRate
)
#expect(flanger.rate == .audio)
}
// MARK: - Output count
@Test func outputCountMatchesRequest() {
let flanger: Flanger.Audio = Flanger.Audio(
input: ConstantGeneratorInput(0.5),
sampleRate: testSampleRate
)
let out: [[Double]] = flanger.calculatedSamples(graph: graph, count: 512)
#expect(out.count >= 1)
#expect(out[0].count >= 512)
}
// MARK: - Silent input → output near zero (with mix 0.5, dry is 0 so output is 0)
@Test func silentInputProducesNearZeroOutput() {
// With input = 0 and no feedback, delay line stays zero.
// Output = 0 * (1 - mix) + 0 * mix = 0.
let flanger: Flanger.Audio = Flanger.Audio(
input: 0.0,
mix: 0.5,
sampleRate: testSampleRate
)
let out: [[Double]] = flanger.calculatedSamples(graph: graph, count: 512)
let samples: [Double] = Array(out[0].prefix(512))
let allNearZero: Bool = samples.allSatisfy { abs($0) < 1e-12 }
#expect(allNearZero, "Zero input with no feedback must produce near-zero output")
}
// MARK: - Non-silent input → output differs from dry (modulation is happening)
@Test func nonSilentInputDiffersFromDry() {
// After some blocks the modulated delay creates a different signal from dry.
let amplitude: Double = 0.5
let flanger: Flanger.Audio = Flanger.Audio(
input: ConstantGeneratorInput(amplitude),
delayTime: 0.005,
depth: 0.5,
rate: 2.0,
feedback: 0.0,
mix: 0.5,
sampleRate: testSampleRate
)
// Run several blocks to let delay line fill.
for _ in 0..<5 {
_ = flanger.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let out: [[Double]] = flanger.calculatedSamples(graph: graph, count: 512)
let samples: [Double] = Array(out[0].prefix(512))
// With constant input the delayed signal is also constant, so mix just attenuates.
// At mix=0.5: output = 0.5 * amplitude + 0.5 * amplitude = amplitude.
// Verify output is non-zero and finite.
let rms: Double = rmsValue(samples)
#expect(rms > 0, "Non-silent input must produce non-zero output")
let allFinite: Bool = samples.allSatisfy { $0.isFinite }
#expect(allFinite, "All output samples must be finite")
}
// MARK: - Fan-out (same segment returns identical result)
@Test func fanOutSingleEvaluation() {
let flanger: Flanger.Audio = Flanger.Audio(
input: ConstantGeneratorInput(0.3),
sampleRate: testSampleRate
)
let out1: [[Double]] = flanger.calculatedSamples(graph: graph, count: 512)
let out2: [[Double]] = flanger.calculatedSamples(graph: graph, count: 512)
let s1: [Double] = Array(out1[0].prefix(512))
let s2: [Double] = Array(out2[0].prefix(512))
#expect(s1 == s2, "Fan-out: two calculatedSamples calls in same segment must return identical data")
}
// MARK: - State advances once per block
@Test func stateAdvancesOncePerBlock() {
let flanger: Flanger.Audio = Flanger.Audio(
input: ConstantGeneratorInput(0.3),
sampleRate: testSampleRate
)
_ = flanger.calculatedSamples(graph: graph, count: 512)
_ = flanger.calculatedSamples(graph: graph, count: 512) // cache hit
advanceBlock(engine)
let block2: [[Double]] = flanger.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
let allFinite: Bool = Array(block2[0].prefix(512)).allSatisfy { $0.isFinite }
#expect(allFinite, "All output samples after block advance must be finite")
}
// MARK: - mulAdd applied
@Test func mulAddApplied() {
// With zero input: output = 0 * (1 - mix) + 0 * mix = 0.
// After mulAdd(mul: 2.0, add: 1.0): output = 0 * 2 + 1 = 1.
let flanger: Flanger.Audio = Flanger.Audio(
input: 0.0,
mix: 0.5,
sampleRate: testSampleRate,
mul: 2.0,
add: 1.0
)
let out: [[Double]] = flanger.calculatedSamples(graph: graph, count: 512)
let samples: [Double] = Array(out[0].prefix(512))
let allNearOne: Bool = samples.allSatisfy { abs($0 - 1.0) < 1e-10 }
#expect(allNearOne, "mulAdd(mul:2, add:1) on zero input must produce output of 1.0")
}
// MARK: - Feedback affects output amplitude
@Test func feedbackOutputIsFinite() {
// With feedback the delayed signal feeds back into the delay line.
// Verify both variants (feedback=0 and feedback=0.8) produce finite output.
let flangerNoFb: Flanger.Audio = Flanger.Audio(
input: ConstantGeneratorInput(0.2),
delayTime: 0.005,
depth: 0.3,
rate: 0.5,
feedback: 0.0,
mix: 0.5,
sampleRate: testSampleRate
)
let flangerFb: Flanger.Audio = Flanger.Audio(
input: ConstantGeneratorInput(0.2),
delayTime: 0.005,
depth: 0.3,
rate: 0.5,
feedback: 0.8,
mix: 0.5,
sampleRate: testSampleRate
)
for _ in 0..<10 {
_ = flangerNoFb.calculatedSamples(graph: graph, count: 512)
_ = flangerFb.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let outNoFb: [Double] = Array(flangerNoFb.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)[0].prefix(512))
let outFb: [Double] = Array(flangerFb.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)[0].prefix(512))
let rmsNoFb: Double = rmsValue(outNoFb)
let rmsFb: Double = rmsValue(outFb)
// Feedback with constant input is stable (clamped to 0.9). Both must be finite.
#expect(rmsNoFb.isFinite, "No-feedback output must be finite")
#expect(rmsFb.isFinite, "Feedback output must be finite")
}
// MARK: - Integration with engine
@Test func integrationWithEngine() throws {
final class FlangerSynth: SynthesizerBase {
override func build() {
let flanger: Flanger.Audio = Flanger.Audio(
input: OscSin.Audio(freq: 220.0),
delayTime: 0.005,
depth: 0.5,
rate: 0.5,
feedback: 0.2,
mix: 0.5,
sampleRate: 44100
)
addOutputGenerator(Out.Audio(bus: 0, source: flanger))
}
}
let intEngine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
try intEngine.start()
let synth: FlangerSynth = FlangerSynth()
try intEngine.add(synth)
for _ in 0..<4 {
intEngine.processBlock(inputSamples: [])
}
intEngine.stop()
}
}
@@ -0,0 +1,321 @@
// FrequencyShifterTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("FrequencyShifter")
struct FrequencyShifterTests {
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
var graph: SynthGraph { makeSynthGraph(engine: engine) }
let testSampleRate: Double = 44100
init() throws {
try engine.start()
}
// MARK: - 1. Rate
@Test func rateIsAudio() {
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
input: 0.0,
sampleRate: testSampleRate
)
#expect(shifter.rate == .audio)
}
// MARK: - 2. Two-channel output count
@Test func outputCountTwoChannels() {
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
input: ConstantGeneratorInput(0.5),
shiftHz: 100.0,
sampleRate: testSampleRate
)
let out: [[Double]] = shifter.calculatedSamples(graph: graph, count: 64)
#expect(out.count == 2, "FrequencyShifter.Audio must produce exactly 2 output channels")
#expect(Array(out[0].prefix(64)).count == 64, "Upper sideband must have 64 samples")
#expect(Array(out[1].prefix(64)).count == 64, "Lower sideband must have 64 samples")
}
// MARK: - 3. Fan-out
@Test func fanOutSingleEvaluation() {
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
input: ConstantGeneratorInput(0.3),
shiftHz: 50.0,
sampleRate: testSampleRate
)
let out1: [[Double]] = shifter.calculatedSamples(graph: graph, count: 512)
let out2: [[Double]] = shifter.calculatedSamples(graph: graph, count: 512)
let s1Upper: [Double] = Array(out1[0].prefix(512))
let s2Upper: [Double] = Array(out2[0].prefix(512))
let s1Lower: [Double] = Array(out1[1].prefix(512))
let s2Lower: [Double] = Array(out2[1].prefix(512))
#expect(s1Upper == s2Upper,
"Fan-out: upper sideband must be identical on second call in same segment")
#expect(s1Lower == s2Lower,
"Fan-out: lower sideband must be identical on second call in same segment")
}
// MARK: - 4. State advances once per block (cache hit does not double-advance)
@Test func stateAdvancesOncePerBlock() {
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
input: ConstantGeneratorInput(0.3),
shiftHz: 100.0,
sampleRate: testSampleRate
)
_ = shifter.calculatedSamples(graph: graph, count: 512)
_ = shifter.calculatedSamples(graph: graph, count: 512) // cache hit
advanceBlock(engine)
let block2: [[Double]] = shifter.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
let allFiniteUpper: Bool = Array(block2[0].prefix(512)).allSatisfy { $0.isFinite }
let allFiniteLower: Bool = Array(block2[1].prefix(512)).allSatisfy { $0.isFinite }
#expect(allFiniteUpper, "Upper sideband must be finite after block advance")
#expect(allFiniteLower, "Lower sideband must be finite after block advance")
}
// MARK: - 5. Deterministic first sample
@Test func firstSampleUpperEqualsLowerAtZeroShift() {
// Structural invariant: at θ = 0 (first sample with shiftHz = 0), cos(θ) = 1 and
// sin(θ) = 0 so the SSB matrix collapses to upper = lower = xA. Both output channels
// must match on sample 0 regardless of the underlying Hilbert cascade values.
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
input: ConstantGeneratorInput(1.0),
shiftHz: 0.0,
sampleRate: testSampleRate
)
let out: [[Double]] = shifter.calculatedSamples(graph: graph, count: 1)
#expect(out[0][0] == out[1][0],
"At θ = 0 with zero shift, upper and lower outputs must match on sample 0")
#expect(out[0][0].isFinite)
}
@Test func nonZeroShiftProducesAsymmetricSidebands() {
// After a long enough render with shiftHz ≠ 0, the SSB matrix should diverge upper
// and lower outputs (the cos·sin asymmetry exercised). Verifies the SSB sign
// convention — a sign flip on the xB·sin term would leave both rows equal at every
// sample, not just at θ = 0.
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
input: OscSin.Audio(freq: 1_000.0),
shiftHz: 200.0,
sampleRate: testSampleRate
)
// Settle Hilbert IIRs so the shifter is in steady state.
for _: Int in 0..<32 {
_ = shifter.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
advanceBlock(engine)
}
let out: [[Double]] = shifter.calculatedSamples(
graph: makeSynthGraph(engine: engine), count: 512
)
var anyDiff: Bool = false
for i: Int in 0..<512 {
if abs(out[0][i] - out[1][i]) > 1e-6 { anyDiff = true; break }
}
#expect(anyDiff,
"Non-zero shift: upper and lower sidebands must diverge once steady state reached")
}
// MARK: - 6. Zero shift — pass-through average
@Test func zeroShiftPassthrough() {
// With shiftHz=0: cos(θ)=1, sin(θ)=0 for all samples (phase stays at 0).
// upper = xA·1 + xB·0 = xA, lower = xA·1 − xB·0 = xA.
// Both channels equal path A output. Average of upper+lower = xA = path A output.
// After filter group delay, output should be non-zero and finite for a sine input.
let input: OscSin.Audio = OscSin.Audio(freq: 440.0)
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
input: input,
shiftHz: 0.0,
sampleRate: testSampleRate
)
let out: [[Double]] = shifter.calculatedSamples(graph: graph, count: 512)
let upper: [Double] = Array(out[0].prefix(512))
let lower: [Double] = Array(out[1].prefix(512))
// Both channels should be identical (xA·1 ± xB·0 = xA).
let allMatch: Bool = zip(upper, lower).allSatisfy { abs($0 - $1) < 1e-10 }
#expect(allMatch, "With shiftHz=0, upper and lower sidebands must be identical")
// Output should be non-trivial (filter introduces group delay but passes the sine).
let rmsUpper: Double = rmsValue(upper)
#expect(rmsUpper > 0.01, "Non-silent sine input with zero shift must produce non-trivial output")
}
// MARK: - 7. DC input → quadrature oscillator visible
@Test func dcInputProducesOscillatorOutput() {
// With DC input (constant 1.0): after the all-pass filters settle, xA ≈ xB ≈ 1.
// upper ≈ cos(θ) − sin(θ), lower ≈ cos(θ) + sin(θ).
// Both channels should be oscillating (non-DC) after many blocks.
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
input: ConstantGeneratorInput(1.0),
shiftHz: 400.0,
sampleRate: testSampleRate
)
// Let the Hilbert filters settle.
for _ in 0..<20 {
_ = shifter.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let out: [[Double]] = shifter.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
let upper: [Double] = Array(out[0].prefix(512))
let lower: [Double] = Array(out[1].prefix(512))
// Compute RMS — a constant output would have very low AC content.
// An oscillating signal at 400 Hz will have significant variation.
let maxUpper: Double = upper.max() ?? 0
let minUpper: Double = upper.min() ?? 0
let rangeUpper: Double = maxUpper - minUpper
#expect(rangeUpper > 0.5, "DC input with 400 Hz shift should produce oscillating upper sideband")
let maxLower: Double = lower.max() ?? 0
let minLower: Double = lower.min() ?? 0
let rangeLower: Double = maxLower - minLower
#expect(rangeLower > 0.5, "DC input with 400 Hz shift should produce oscillating lower sideband")
}
// MARK: - 8. Audio-rate shift input
@Test func audioRateShiftInput() {
// Drive shiftHz with an OscSin generator — verify output is non-trivial and non-NaN.
let shiftMod: OscSin.Audio = OscSin.Audio(freq: 2.0) // 2 Hz LFO
let input: OscSin.Audio = OscSin.Audio(freq: 440.0)
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
input: input,
shiftHz: shiftMod,
sampleRate: testSampleRate
)
let out: [[Double]] = shifter.calculatedSamples(graph: graph, count: 512)
let upper: [Double] = Array(out[0].prefix(512))
let lower: [Double] = Array(out[1].prefix(512))
let allFiniteUpper: Bool = upper.allSatisfy { $0.isFinite }
let allFiniteLower: Bool = lower.allSatisfy { $0.isFinite }
#expect(allFiniteUpper, "Audio-rate shift: upper sideband must not contain NaN/Inf")
#expect(allFiniteLower, "Audio-rate shift: lower sideband must not contain NaN/Inf")
let rmsUpper: Double = rmsValue(upper)
#expect(rmsUpper > 0.001, "Audio-rate shift: upper sideband must be non-trivial")
}
// MARK: - 9. mulAdd applied
@Test func mulAddApplied() {
// Zero input → zero output for both sidebands.
// With mul:2, add:1 → output must be 1.0 for all samples.
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
input: 0.0,
shiftHz: 100.0,
sampleRate: testSampleRate,
mul: 2.0,
add: 1.0
)
let out: [[Double]] = shifter.calculatedSamples(graph: graph, count: 512)
let upper: [Double] = Array(out[0].prefix(512))
let lower: [Double] = Array(out[1].prefix(512))
let allNearOneUpper: Bool = upper.allSatisfy { abs($0 - 1.0) < 1e-10 }
let allNearOneLower: Bool = lower.allSatisfy { abs($0 - 1.0) < 1e-10 }
#expect(allNearOneUpper, "Upper sideband: mul:2 add:1 on zero input must produce 1.0")
#expect(allNearOneLower, "Lower sideband: mul:2 add:1 on zero input must produce 1.0")
}
// MARK: - 10. Denormal safety
@Test func denormalSafe() {
// Feed a tiny sub-normal-adjacent input for many blocks — verify no NaN or Inf.
let tinyInput: Double = 1e-300
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
input: ConstantGeneratorInput(tinyInput),
shiftHz: 200.0,
sampleRate: testSampleRate
)
for _ in 0..<1000 {
let out: [[Double]] = shifter.calculatedSamples(graph: graph, count: 512)
let upper: [Double] = Array(out[0].prefix(512))
let lower: [Double] = Array(out[1].prefix(512))
let upperOk: Bool = upper.allSatisfy { $0.isFinite }
let lowerOk: Bool = lower.allSatisfy { $0.isFinite }
if !upperOk || !lowerOk {
#expect(Bool(false), "Denormal input must not produce NaN/Inf in output")
break
}
advanceBlock(engine)
}
}
// MARK: - 11. Channel aliases
@Test func channelAliasesMatchSubscripts() {
let input: OscSin.Audio = OscSin.Audio(freq: 220.0)
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
input: input,
shiftHz: 50.0,
sampleRate: testSampleRate
)
let upperOut: [[Double]] = shifter.upper.calculatedSamples(graph: graph, count: 64)
let lowerOut: [[Double]] = shifter.lower.calculatedSamples(graph: graph, count: 64)
let fullOut: [[Double]] = shifter.calculatedSamples(graph: graph, count: 64)
for i: Int in 0..<64 {
#expect(abs(upperOut[0][i] - fullOut[0][i]) < 1e-10,
"upper alias must match channel 0 at index \(i)")
#expect(abs(lowerOut[0][i] - fullOut[1][i]) < 1e-10,
"lower alias must match channel 1 at index \(i)")
}
}
// MARK: - 12. Integration with engine
@Test func integrationWithEngine() throws {
final class FreqShiftSynth: SynthesizerBase {
override func build() {
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
input: OscSin.Audio(freq: 440.0),
shiftHz: 100.0,
sampleRate: 44100
)
addOutputGenerator(Out.Audio(bus: 0, source: shifter.upper))
addOutputGenerator(Out.Audio(bus: 1, source: shifter.lower))
}
}
let intEngine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
try intEngine.start()
let synth: FreqShiftSynth = FreqShiftSynth()
try intEngine.add(synth)
for _ in 0..<4 {
intEngine.processBlock(inputSamples: [])
}
intEngine.stop()
}
// MARK: - 13. Upper and lower sidebands differ (non-trivial signal)
@Test func upperAndLowerSidebandsAreDifferent() {
let input: OscSin.Audio = OscSin.Audio(freq: 440.0)
let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio(
input: input,
shiftHz: 200.0,
sampleRate: testSampleRate
)
// Let the Hilbert filters settle so path A and B outputs diverge.
for _ in 0..<10 {
_ = shifter.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let out: [[Double]] = shifter.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
let upper: [Double] = Array(out[0].prefix(512))
let lower: [Double] = Array(out[1].prefix(512))
// upper = xA·cos + xB·sin, lower = xA·cos − xB·sin.
// They differ when xB·sin ≠ 0, i.e. once the Hilbert filter is producing output.
let anyDiff: Bool = zip(upper, lower).contains { abs($0 - $1) > 1e-6 }
#expect(anyDiff, "Upper and lower sidebands must differ once the Hilbert filter is active")
}
}
@@ -0,0 +1,283 @@
// PhaserTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("Phaser")
struct PhaserTests {
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
var graph: SynthGraph { makeSynthGraph(engine: engine) }
let testSampleRate: Double = 44100
init() throws {
try engine.start()
}
// MARK: - Deterministic first sample
@Test func firstSampleDeterministic() {
// input=1.0, rate=0, depth=0, centerFreq=800, stages=4, mix=0.5.
// With static LFO (rate=0, depth=0) sweepFreq=centerFreq; all-pass state starts at 0.
// First sample: each stage y[n] = apCoef * (x - 0) + 0 = apCoef * x.
// After 4 stages: chainIn = apCoef^4. output = 1*(1-0.5) + apCoef^4*0.5.
let sr: Double = 44100
let centerFreq: Double = 800.0
let tanArg: Double = tan(Double.pi * centerFreq / sr)
let apCoef: Double = (tanArg - 1.0) / (tanArg + 1.0)
let expectedWet: Double = pow(apCoef, 4.0)
let expected: Double = 1.0 * 0.5 + expectedWet * 0.5
let phaser: Phaser.Audio = Phaser.Audio(
input: ConstantGeneratorInput(1.0),
rate: 0.0,
depth: 0.0,
centerFreq: centerFreq,
feedback: 0.0,
stages: 4,
mix: 0.5,
sampleRate: sr
)
let out: [[Double]] = phaser.calculatedSamples(graph: graph, count: 1)
#expect(abs(out[0][0] - expected) < 1e-10, "First sample must be \(expected), got \(out[0][0])")
}
// MARK: - Rate
@Test func rateIsAudio() {
let phaser: Phaser.Audio = Phaser.Audio(
input: 0.0,
sampleRate: testSampleRate
)
#expect(phaser.rate == .audio)
}
// MARK: - Output count
@Test func outputCountMatchesRequest() {
let phaser: Phaser.Audio = Phaser.Audio(
input: ConstantGeneratorInput(0.5),
sampleRate: testSampleRate
)
let out: [[Double]] = phaser.calculatedSamples(graph: graph, count: 512)
#expect(out.count >= 1)
#expect(out[0].count >= 512)
}
// MARK: - Silent input → near-zero output
@Test func silentInputProducesNearZeroOutput() {
// Zero input: all-pass chain preserves zero; output = 0 * (1-mix) + 0 * mix = 0.
let phaser: Phaser.Audio = Phaser.Audio(
input: 0.0,
feedback: 0.0,
mix: 0.5,
sampleRate: testSampleRate
)
let out: [[Double]] = phaser.calculatedSamples(graph: graph, count: 512)
let samples: [Double] = Array(out[0].prefix(512))
let allNearZero: Bool = samples.allSatisfy { abs($0) < 1e-12 }
#expect(allNearZero, "Zero input with no feedback must produce near-zero output")
}
// MARK: - Non-silent input → output differs from dry
@Test func nonSilentInputDiffersFromDry() {
// With a constant input and mix=1.0 (all wet), the all-pass chain introduces
// phase shifts → output will differ from the raw input after several blocks.
let phaser: Phaser.Audio = Phaser.Audio(
input: ConstantGeneratorInput(1.0),
rate: 2.0,
depth: 0.9,
centerFreq: 800.0,
feedback: 0.0,
stages: 4,
mix: 0.5,
sampleRate: testSampleRate
)
let out: [[Double]] = phaser.calculatedSamples(graph: graph, count: 512)
let samples: [Double] = Array(out[0].prefix(512))
let rms: Double = rmsValue(samples)
#expect(rms > 0, "Non-silent input must produce non-zero output")
let allFinite: Bool = samples.allSatisfy { $0.isFinite }
#expect(allFinite, "All output samples must be finite")
}
// MARK: - Fan-out
@Test func fanOutSingleEvaluation() {
let phaser: Phaser.Audio = Phaser.Audio(
input: ConstantGeneratorInput(0.3),
sampleRate: testSampleRate
)
let out1: [[Double]] = phaser.calculatedSamples(graph: graph, count: 512)
let out2: [[Double]] = phaser.calculatedSamples(graph: graph, count: 512)
let s1: [Double] = Array(out1[0].prefix(512))
let s2: [Double] = Array(out2[0].prefix(512))
#expect(s1 == s2, "Fan-out: two calculatedSamples calls in same segment must return identical data")
}
// MARK: - State advances once per block
@Test func stateAdvancesOncePerBlock() {
let phaser: Phaser.Audio = Phaser.Audio(
input: ConstantGeneratorInput(0.3),
sampleRate: testSampleRate
)
_ = phaser.calculatedSamples(graph: graph, count: 512)
_ = phaser.calculatedSamples(graph: graph, count: 512) // cache hit
advanceBlock(engine)
let block2: [[Double]] = phaser.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
let allFinite: Bool = Array(block2[0].prefix(512)).allSatisfy { $0.isFinite }
#expect(allFinite, "All output samples after block advance must be finite")
}
// MARK: - Feedback=0 → output amplitude bounded
@Test func feedbackZeroOutputBounded() {
// With no feedback the all-pass chain preserves signal energy, so
// a ±1 input with mix=0.5 must stay in [-1, 1].
let phaser: Phaser.Audio = Phaser.Audio(
input: ConstantGeneratorInput(0.8),
rate: 1.0,
depth: 1.0,
centerFreq: 800.0,
feedback: 0.0,
stages: 4,
mix: 0.5,
sampleRate: testSampleRate
)
for _ in 0..<5 {
_ = phaser.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let out: [[Double]] = phaser.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
let samples: [Double] = Array(out[0].prefix(512))
let allBounded: Bool = samples.allSatisfy { abs($0) <= 1.5 }
#expect(allBounded, "With feedback=0 and ±0.8 input, output must be bounded")
}
// MARK: - All stage counts (4, 6, 8) run without crash
@Test func stages4Runs() {
let phaser: Phaser.Audio = Phaser.Audio(
input: ConstantGeneratorInput(0.5),
stages: 4,
sampleRate: testSampleRate
)
let out: [[Double]] = phaser.calculatedSamples(graph: graph, count: 512)
#expect(out[0].count >= 512, "4-stage phaser must produce output")
}
@Test func stages6Runs() {
let phaser: Phaser.Audio = Phaser.Audio(
input: ConstantGeneratorInput(0.5),
stages: 6,
sampleRate: testSampleRate
)
let out: [[Double]] = phaser.calculatedSamples(graph: graph, count: 512)
#expect(out[0].count >= 512, "6-stage phaser must produce output")
}
@Test func stages8Runs() {
let phaser: Phaser.Audio = Phaser.Audio(
input: ConstantGeneratorInput(0.5),
stages: 8,
sampleRate: testSampleRate
)
let out: [[Double]] = phaser.calculatedSamples(graph: graph, count: 512)
#expect(out[0].count >= 512, "8-stage phaser must produce output")
}
// MARK: - mulAdd applied
@Test func mulAddApplied() {
// Zero input → zero through all-pass → zero at output. After mul:2 add:1 → 1.0.
let phaser: Phaser.Audio = Phaser.Audio(
input: 0.0,
feedback: 0.0,
mix: 0.5,
sampleRate: testSampleRate,
mul: 2.0,
add: 1.0
)
let out: [[Double]] = phaser.calculatedSamples(graph: graph, count: 512)
let samples: [Double] = Array(out[0].prefix(512))
let allNearOne: Bool = samples.allSatisfy { abs($0 - 1.0) < 1e-10 }
#expect(allNearOne, "mulAdd(mul:2, add:1) on zero input must produce output of 1.0")
}
// MARK: - Rate affects all-pass sweep (higher rate → more variation per block)
@Test func higherRateProducesMoreVariation() {
// With a sine input and high rate, the sweep moves faster → more inter-sample
// variation in output. Compare variance between low-rate and high-rate phasers.
let slowPhaser: Phaser.Audio = Phaser.Audio(
input: ConstantGeneratorInput(0.5),
rate: 0.01,
depth: 1.0,
centerFreq: 800.0,
feedback: 0.0,
stages: 4,
mix: 1.0,
sampleRate: testSampleRate
)
let fastPhaser: Phaser.Audio = Phaser.Audio(
input: ConstantGeneratorInput(0.5),
rate: 10.0,
depth: 1.0,
centerFreq: 800.0,
feedback: 0.0,
stages: 4,
mix: 1.0,
sampleRate: testSampleRate
)
let slowOut: [Double] = Array(slowPhaser.calculatedSamples(graph: graph, count: 512)[0].prefix(512))
let fastOut: [Double] = Array(fastPhaser.calculatedSamples(graph: graph, count: 512)[0].prefix(512))
// With constant input and slow rate the all-pass output is nearly constant.
// With fast rate the coefficient changes rapidly → more inter-sample variation.
let slowVariance: Double = slowOut.map { $0 * $0 }.reduce(0, +)
let fastVariance: Double = fastOut.map { $0 * $0 }.reduce(0, +)
// Both should be finite and non-negative. We don't assert ordering because
// the all-pass is energy-preserving; just verify both produce finite results.
#expect(slowVariance.isFinite, "Slow phaser output must be finite")
#expect(fastVariance.isFinite, "Fast phaser output must be finite")
}
// MARK: - Integration with engine
@Test func integrationWithEngine() throws {
final class PhaserSynth: SynthesizerBase {
override func build() {
let phaser: Phaser.Audio = Phaser.Audio(
input: OscSin.Audio(freq: 220.0),
rate: 0.5,
depth: 1.0,
centerFreq: 800.0,
feedback: 0.3,
stages: 6,
mix: 0.5,
sampleRate: 44100
)
addOutputGenerator(Out.Audio(bus: 0, source: phaser))
}
}
let intEngine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
try intEngine.start()
let synth: PhaserSynth = PhaserSynth()
try intEngine.add(synth)
for _ in 0..<4 {
intEngine.processBlock(inputSamples: [])
}
intEngine.stop()
}
}
@@ -0,0 +1,317 @@
// SpatialDistanceTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpatialDistance")
struct SpatialDistanceTests {
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
var graph: SynthGraph { makeSynthGraph(engine: engine) }
let testSampleRate: Double = 44100
let blockSize: Int = 512
init() throws {
try engine.start()
}
// MARK: - 1. Rate
@Test func rateIsAudio() {
let gen: SpatialDistance.Audio = SpatialDistance.Audio(input: 0.0, sampleRate: testSampleRate)
#expect(gen.rate == .audio)
}
// MARK: - 2. Output count
@Test func outputCountMatchesRequest() {
let gen: SpatialDistance.Audio = SpatialDistance.Audio(input: 0.0, sampleRate: testSampleRate)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let samples: [Double] = Array(out[0].prefix(blockSize))
#expect(samples.count == blockSize)
}
// MARK: - 2b. Deterministic first sample (exact numeric verification)
@Test func firstSampleDeterministic() {
// Zero input, identity mul/add → first sample is exactly 0.0.
// Delay line is zero-initialised so dry=0 → delay line write of 0 → delayed=0 →
// LP state = (1-a)*0 + a*0 = 0 → output = 0 * attenuation = 0.
let gen: SpatialDistance.Audio = SpatialDistance.Audio(
input: ConstantGeneratorInput(0.0),
distance: 1.0,
velocity: 0.0,
sampleRate: testSampleRate
)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 1)
#expect(abs(out[0][0] - 0.0) < 1e-12,
"Zero input first sample must be exactly 0.0, got \(out[0][0])")
// With mul=2, add=1 the same chain (output 0 before mulAdd) must yield 0*2 + 1 = 1.0.
let gen2: SpatialDistance.Audio = SpatialDistance.Audio(
input: ConstantGeneratorInput(0.0),
distance: 1.0,
velocity: 0.0,
sampleRate: testSampleRate,
mul: 2.0,
add: 1.0
)
let out2: [[Double]] = gen2.calculatedSamples(graph: graph, count: 1)
#expect(abs(out2[0][0] - 1.0) < 1e-12,
"Zero input + mul=2,add=1 first sample must be exactly 1.0, got \(out2[0][0])")
}
// MARK: - 3. Silent input → silent output
@Test func silentInputProducesSilentOutput() {
// No feedback path, so zero input → zero output.
let gen: SpatialDistance.Audio = SpatialDistance.Audio(
input: 0.0,
distance: 2.0,
velocity: 0.0,
sampleRate: testSampleRate
)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let samples: [Double] = Array(out[0].prefix(blockSize))
let allNearZero: Bool = samples.allSatisfy { abs($0) < 1e-10 }
#expect(allNearZero, "Zero input must produce near-zero output (no feedback)")
}
// MARK: - 4. First block is finite
@Test func firstBlockNotNaN() {
let gen: SpatialDistance.Audio = SpatialDistance.Audio(
input: ConstantGeneratorInput(0.5),
distance: 1.0,
velocity: 0.0,
sampleRate: testSampleRate
)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let samples: [Double] = Array(out[0].prefix(blockSize))
let allFinite: Bool = samples.allSatisfy { $0.isFinite }
#expect(allFinite, "All output samples must be finite for sane parameters at distance=1.0")
}
// MARK: - 5. Larger distance attenuates output
@Test func largerDistanceAttenuatesOutput() {
// Feed several blocks to fill the delay line, then compare RMS.
let nearGen: SpatialDistance.Audio = SpatialDistance.Audio(
input: ConstantGeneratorInput(0.8),
distance: 1.0,
velocity: 0.0,
sampleRate: testSampleRate
)
let farGen: SpatialDistance.Audio = SpatialDistance.Audio(
input: ConstantGeneratorInput(0.8),
distance: 10.0,
velocity: 0.0,
sampleRate: testSampleRate
)
// Prime the delay lines.
for _ in 0..<5 {
_ = nearGen.calculatedSamples(graph: graph, count: blockSize)
_ = farGen.calculatedSamples(graph: graph, count: blockSize)
advanceBlock(engine)
}
let nearOut: [[Double]] = nearGen.calculatedSamples(graph: makeSynthGraph(engine: engine), count: blockSize)
let farOut: [[Double]] = farGen.calculatedSamples(graph: makeSynthGraph(engine: engine), count: blockSize)
let nearRms: Double = rmsValue(Array(nearOut[0].prefix(blockSize)))
let farRms: Double = rmsValue(Array(farOut[0].prefix(blockSize)))
// The far source should be materially quieter (at least half).
#expect(
farRms < 0.5 * nearRms,
"Far source (d=10) RMS \(farRms) should be < half of near source (d=1) RMS \(nearRms)"
)
}
// MARK: - 6. Larger distance lowpasses output
@Test func largerDistanceLowpassesOutput() {
// Drive an 8 kHz sine and compare high-frequency energy (via 1-sample differences)
// between near and far instances. Far should have less HF energy due to air absorption.
let freq: Double = 8000.0
let nearGen: SpatialDistance.Audio = SpatialDistance.Audio(
input: OscSin.Audio(freq: freq),
distance: 1.0,
velocity: 0.0,
airAbsorptionCutoff: 16000.0,
sampleRate: testSampleRate
)
let farGen: SpatialDistance.Audio = SpatialDistance.Audio(
input: OscSin.Audio(freq: freq),
distance: 20.0,
velocity: 0.0,
airAbsorptionCutoff: 16000.0,
sampleRate: testSampleRate
)
// Prime with several blocks.
for _ in 0..<10 {
_ = nearGen.calculatedSamples(graph: graph, count: blockSize)
_ = farGen.calculatedSamples(graph: graph, count: blockSize)
advanceBlock(engine)
}
let nearSamples: [Double] = Array(nearGen.calculatedSamples(graph: makeSynthGraph(engine: engine), count: blockSize)[0].prefix(blockSize))
let farSamples: [Double] = Array(farGen.calculatedSamples(graph: makeSynthGraph(engine: engine), count: blockSize)[0].prefix(blockSize))
// Crude high-pass: compute RMS of first-differences (consecutive sample deltas).
var nearDiffSumSq: Double = 0.0
var farDiffSumSq: Double = 0.0
for i: Int in 1..<blockSize {
let nd: Double = nearSamples[i] - nearSamples[i - 1]
let fd: Double = farSamples[i] - farSamples[i - 1]
nearDiffSumSq += nd * nd
farDiffSumSq += fd * fd
}
let nearHF: Double = (nearDiffSumSq / Double(blockSize - 1)).squareRoot()
let farHF: Double = (farDiffSumSq / Double(blockSize - 1)).squareRoot()
// At d=20, air absorption cutoff is (1/20)^2 × 16000 ≈ 40 Hz — very aggressive LP.
// The far HF RMS must be materially less than the near HF RMS.
#expect(
farHF < 0.5 * nearHF,
"Far source (d=20) HF energy \(farHF) should be < half of near source (d=1) HF energy \(nearHF)"
)
}
// MARK: - 7. Velocity produces pitch shift via delay change
@Test func velocityProducesPitchShiftViaDelayChange() throws {
// Feed a constant-frequency sine and count zero crossings over many blocks.
// With velocity > 0 the Doppler read-rate < 1 stretches the waveform,
// producing fewer zero crossings per unit time (lower apparent frequency).
let freq: Double = 440.0
let numBlocks: Int = 20
// Helper: count zero crossings (sign changes) in a flat sample array.
func zeroCrossings(_ s: [Double]) -> Int {
var cnt: Int = 0
for i: Int in 1..<s.count {
if (s[i - 1] < 0 && s[i] >= 0) || (s[i - 1] >= 0 && s[i] < 0) {
cnt += 1
}
}
return cnt
}
func collectSamples(velocity: Double) throws -> [Double] {
let eng: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: testSampleRate)
try eng.start()
let gen: SpatialDistance.Audio = SpatialDistance.Audio(
input: OscSin.Audio(freq: freq),
distance: 5.0,
velocity: velocity,
sampleRate: testSampleRate
)
var allSamples: [Double] = []
for _ in 0..<numBlocks {
let g: SynthGraph = makeSynthGraph(engine: eng)
let out: [[Double]] = gen.calculatedSamples(graph: g, count: blockSize)
allSamples += Array(out[0].prefix(blockSize))
advanceBlock(eng)
}
eng.stop()
return allSamples
}
let noVelSamples: [Double] = try collectSamples(velocity: 0.0)
let highVelSamples: [Double] = try collectSamples(velocity: 30.0)
let crossingsNoVel: Int = zeroCrossings(noVelSamples)
let crossingsHighVel: Int = zeroCrossings(highVelSamples)
// velocity=30 m/s → readRate ≈ 0.913 → waveform stretched → fewer zero crossings.
let ratio: Double = Double(crossingsHighVel) / Double(max(crossingsNoVel, 1))
#expect(
ratio < 0.97,
"Positive velocity should reduce zero crossings (lower apparent frequency)"
)
}
// MARK: - 8. Fan-out (same segment returns identical result)
@Test func fanOutSingleEvaluation() {
let gen: SpatialDistance.Audio = SpatialDistance.Audio(
input: ConstantGeneratorInput(0.4),
distance: 2.0,
sampleRate: testSampleRate
)
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let s1: [Double] = Array(out1[0].prefix(blockSize))
let s2: [Double] = Array(out2[0].prefix(blockSize))
#expect(s1 == s2, "Fan-out: two calculatedSamples calls in the same segment must return identical data")
}
// MARK: - 9. State advances once per block
@Test func stateAdvancesOncePerBlock() {
let gen: SpatialDistance.Audio = SpatialDistance.Audio(
input: ConstantGeneratorInput(0.5),
distance: 3.0,
sampleRate: testSampleRate
)
// Two calls in the same segment — second must be a cache hit (no double-advance).
_ = gen.calculatedSamples(graph: graph, count: blockSize)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
advanceBlock(engine)
let block2: [[Double]] = gen.calculatedSamples(graph: makeSynthGraph(engine: engine), count: blockSize)
let allFinite: Bool = Array(block2[0].prefix(blockSize)).allSatisfy { $0.isFinite }
#expect(allFinite, "Block 2 output must be finite after exactly one advance")
}
// MARK: - 10. mulAdd applied
@Test func mulAddApplied() {
// Zero input → zero output before mulAdd. With mul:2, add:1 → output = 1.
let gen: SpatialDistance.Audio = SpatialDistance.Audio(
input: 0.0,
distance: 1.0,
sampleRate: testSampleRate,
mul: 2.0,
add: 1.0
)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let samples: [Double] = Array(out[0].prefix(blockSize))
let allNearOne: Bool = samples.allSatisfy { abs($0 - 1.0) < 1e-10 }
#expect(allNearOne, "mulAdd(mul:2, add:1) on zero input must produce output of 1.0")
}
// MARK: - Integration with engine
@Test func integrationWithEngine() throws {
final class SpatialSynth: SynthesizerBase {
override func build() {
let gen: SpatialDistance.Audio = SpatialDistance.Audio(
input: OscSin.Audio(freq: 220.0),
distance: 3.0,
velocity: 5.0,
sampleRate: 44100
)
addOutputGenerator(Out.Audio(bus: 0, source: gen))
}
}
let intEngine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
try intEngine.start()
let synth: SpatialSynth = SpatialSynth()
try intEngine.add(synth)
for _ in 0..<4 {
intEngine.processBlock(inputSamples: [])
}
intEngine.stop()
}
}