// SpectralFeatureTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing import Foundation @testable @_spi(LyrebirdExtensions) import LyrebirdSynth /// Shared test helpers for spectral feature generators. /// /// fftSize=8, sampleRate=8: binHz = 1.0 Hz, binCount = 5 (bins 0..4). /// Complex bins 1..3 are settable via spectral[magnitude: k]. /// DC (bin 0) and Nyquist (bin 4) use dcValue / nyquistValue. private func makeSpectral(fftSize: Int = 8) -> SpectralBuffer { SpectralBuffer(fftSize: fftSize) } private let testSampleRate: Double = 8.0 private let testFftSize: Int = 8 private let testBinHz: Double = testSampleRate / Double(testFftSize) // 1.0 Hz/bin private let testBlockSize: Int = 64 // MARK: - SpectralCentroid.Control @Suite("SpectralCentroid.Control") struct SpectralCentroidTests { let engine: SynthesisEngine var graph: SynthGraph { makeSynthGraph(engine: engine) } init() throws { engine = makeTestEngine(blockSize: testBlockSize, sampleRate: testSampleRate) try engine.start() } @Test func rateIsControl() { let s: SpectralBuffer = makeSpectral() let gen: SpectralCentroid.Control = SpectralCentroid.Control(spectral: s, sampleRate: testSampleRate) #expect(gen.rate == .control) } @Test func silenceOutputsZero() { let s: SpectralBuffer = makeSpectral() let gen: SpectralCentroid.Control = SpectralCentroid.Control(spectral: s, sampleRate: testSampleRate) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) #expect(abs(gen.previousOutputValue) < 1e-10) } @Test func singleBinAtKTwoOutputsKTimesBindHz() { let s: SpectralBuffer = makeSpectral() s[magnitude: 2] = 1.0 let gen: SpectralCentroid.Control = SpectralCentroid.Control(spectral: s, sampleRate: testSampleRate) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) // centroid_bin = 2, centroid_hz = 2 * 1.0 = 2.0 #expect(abs(gen.previousOutputValue - 2.0) < 1e-6) } @Test func equalBinsSymmetricAroundCenterOutputsCenterFrequency() { let s: SpectralBuffer = makeSpectral() s[magnitude: 1] = 1.0 s[magnitude: 3] = 1.0 let gen: SpectralCentroid.Control = SpectralCentroid.Control(spectral: s, sampleRate: testSampleRate) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) // centroid_bin = (1 + 3) / 2 = 2.0, centroid_hz = 2.0 #expect(abs(gen.previousOutputValue - 2.0) < 1e-6) } @Test func largerMagnitudeAtHigherBinPullsCentroidUp() { let s: SpectralBuffer = makeSpectral() s[magnitude: 1] = 1.0 // weight 1 at bin 1 s[magnitude: 3] = 3.0 // weight 3 at bin 3 let gen: SpectralCentroid.Control = SpectralCentroid.Control(spectral: s, sampleRate: testSampleRate) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) // weightedSum = 1*1 + 3*3 = 10, totalMag = 4, centroid_bin = 10/4 = 2.5 // centroid_hz = 2.5 * 1.0 = 2.5 #expect(abs(gen.previousOutputValue - 2.5) < 1e-6) } @Test func floatValueReturnsPreviousOutputValue() { let s: SpectralBuffer = makeSpectral() s[magnitude: 2] = 1.0 let gen: SpectralCentroid.Control = SpectralCentroid.Control(spectral: s, sampleRate: testSampleRate) #expect(gen.floatValue(graph: graph) == 0.0) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) #expect(gen.floatValue(graph: graph) == gen.previousOutputValue) } @Test func mulAddScalesOutput() { let s: SpectralBuffer = makeSpectral() s[magnitude: 2] = 1.0 let gen: SpectralCentroid.Control = SpectralCentroid.Control(spectral: s, sampleRate: testSampleRate, mul: 2.0, add: 1.0) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) // centroid = 2.0, * 2 + 1 = 5.0 #expect(abs(gen.previousOutputValue - 5.0) < 1e-6) } } // MARK: - SpectralFlatness.Control @Suite("SpectralFlatness.Control") struct SpectralFlatnessTests { let engine: SynthesisEngine var graph: SynthGraph { makeSynthGraph(engine: engine) } init() throws { engine = makeTestEngine(blockSize: testBlockSize, sampleRate: testSampleRate) try engine.start() } @Test func rateIsControl() { let s: SpectralBuffer = makeSpectral() #expect(SpectralFlatness.Control(spectral: s).rate == .control) } @Test func silenceOutputsZero() { let s: SpectralBuffer = makeSpectral() let gen: SpectralFlatness.Control = SpectralFlatness.Control(spectral: s) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) #expect(abs(gen.previousOutputValue) < 1e-10) } @Test func singleNonZeroBinOutputsNearZero() { // A single non-zero bin → most bins are zero → geometric mean collapses to 0. let s: SpectralBuffer = makeSpectral() s[magnitude: 2] = 1.0 let gen: SpectralFlatness.Control = SpectralFlatness.Control(spectral: s) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) #expect(gen.previousOutputValue < 1e-10) } @Test func allBinsEqualOutputsOne() { // All bins equal → geometric mean = arithmetic mean → flatness = 1. let s: SpectralBuffer = makeSpectral() s.dcValue = 1.0 s[magnitude: 1] = 1.0 s[magnitude: 2] = 1.0 s[magnitude: 3] = 1.0 s.nyquistValue = 1.0 let gen: SpectralFlatness.Control = SpectralFlatness.Control(spectral: s) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) #expect(abs(gen.previousOutputValue - 1.0) < 1e-6) } @Test func outputInZeroOneRange() { // Arbitrary magnitudes: flatness must stay in [0, 1]. let s: SpectralBuffer = makeSpectral() s[magnitude: 1] = 0.5 s[magnitude: 2] = 2.0 s[magnitude: 3] = 0.1 let gen: SpectralFlatness.Control = SpectralFlatness.Control(spectral: s) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) #expect(gen.previousOutputValue >= 0.0) #expect(gen.previousOutputValue <= 1.0) } @Test func tonerSpectrumLessFlatThanWhiteNoise() { // Tonal (one bin) should be less flat than balanced (all bins equal). let sr: SpectralBuffer = makeSpectral() let sn: SpectralBuffer = makeSpectral() let e: SynthesisEngine = engine sr[magnitude: 2] = 1.0 // tonal sn.dcValue = 1.0 sn[magnitude: 1] = 1.0 sn[magnitude: 2] = 1.0 sn[magnitude: 3] = 1.0 sn.nyquistValue = 1.0 // flat let genTonal: SpectralFlatness.Control = SpectralFlatness.Control(spectral: sr) let genFlat: SpectralFlatness.Control = SpectralFlatness.Control(spectral: sn) _ = genTonal.calculatedSamples(graph: makeSynthGraph(engine: e), count: testBlockSize) _ = genFlat.calculatedSamples(graph: makeSynthGraph(engine: e), count: testBlockSize) #expect(genTonal.previousOutputValue < genFlat.previousOutputValue) } } // MARK: - SpectralSpread.Control @Suite("SpectralSpread.Control") struct SpectralSpreadTests { let engine: SynthesisEngine var graph: SynthGraph { makeSynthGraph(engine: engine) } init() throws { engine = makeTestEngine(blockSize: testBlockSize, sampleRate: testSampleRate) try engine.start() } @Test func rateIsControl() { let s: SpectralBuffer = makeSpectral() #expect(SpectralSpread.Control(spectral: s, sampleRate: testSampleRate).rate == .control) } @Test func silenceOutputsZero() { let s: SpectralBuffer = makeSpectral() let gen: SpectralSpread.Control = SpectralSpread.Control(spectral: s, sampleRate: testSampleRate) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) #expect(abs(gen.previousOutputValue) < 1e-10) } @Test func singleBinOutputsZeroSpread() { // All energy in one bin → no variance around centroid. let s: SpectralBuffer = makeSpectral() s[magnitude: 2] = 1.0 let gen: SpectralSpread.Control = SpectralSpread.Control(spectral: s, sampleRate: testSampleRate) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) #expect(abs(gen.previousOutputValue) < 1e-10) } @Test func symmetricBinsAroundCenterHasKnownSpread() { // Bins 1 and 3, equal magnitude. Centroid = 2.0 Hz. // Variance = ((1−2)²*1 + (3−2)²*1) / 2 = 1.0 Hz²; spread = 1.0 Hz. let s: SpectralBuffer = makeSpectral() s[magnitude: 1] = 1.0 s[magnitude: 3] = 1.0 let gen: SpectralSpread.Control = SpectralSpread.Control(spectral: s, sampleRate: testSampleRate) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) #expect(abs(gen.previousOutputValue - 1.0) < 1e-6) } @Test func widerSeparationIncreasesSpread() { // Bins 1 and 3 vs bins 1 and 2 — wider separation should yield higher spread. let e: SynthesisEngine = engine let sWide: SpectralBuffer = makeSpectral() sWide[magnitude: 1] = 1.0; sWide[magnitude: 3] = 1.0 let sNarrow: SpectralBuffer = makeSpectral() sNarrow[magnitude: 1] = 1.0; sNarrow[magnitude: 2] = 1.0 let genWide: SpectralSpread.Control = SpectralSpread.Control(spectral: sWide, sampleRate: testSampleRate) let genNarrow: SpectralSpread.Control = SpectralSpread.Control(spectral: sNarrow, sampleRate: testSampleRate) _ = genWide.calculatedSamples(graph: makeSynthGraph(engine: e), count: testBlockSize) _ = genNarrow.calculatedSamples(graph: makeSynthGraph(engine: e), count: testBlockSize) #expect(genWide.previousOutputValue > genNarrow.previousOutputValue) } } // MARK: - SpectralFlux.Control @Suite("SpectralFlux.Control") struct SpectralFluxTests { let engine: SynthesisEngine var graph: SynthGraph { makeSynthGraph(engine: engine) } init() throws { engine = makeTestEngine(blockSize: testBlockSize, sampleRate: testSampleRate) try engine.start() } @Test func rateIsControl() { let s: SpectralBuffer = makeSpectral() #expect(SpectralFlux.Control(spectral: s).rate == .control) } @Test func firstBlockOutputsZero() { // No previous frame to compare — flux is undefined, so 0 is returned. let s: SpectralBuffer = makeSpectral() s[magnitude: 2] = 1.0 let gen: SpectralFlux.Control = SpectralFlux.Control(spectral: s) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) #expect(abs(gen.previousOutputValue) < 1e-10) } @Test func identicalFramesOutputsZero() { let s: SpectralBuffer = makeSpectral() s[magnitude: 2] = 1.0 let gen: SpectralFlux.Control = SpectralFlux.Control(spectral: s) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) advanceBlock(engine) _ = gen.calculatedSamples(graph: makeSynthGraph(engine: engine), count: testBlockSize) #expect(abs(gen.previousOutputValue) < 1e-10) } @Test func changingFrameOutputsPositiveFlux() { let s: SpectralBuffer = makeSpectral() let gen: SpectralFlux.Control = SpectralFlux.Control(spectral: s) // Block 1 — all zeros _ = gen.calculatedSamples(graph: graph, count: testBlockSize) advanceBlock(engine) // Block 2 — introduce energy at bin 2 s[magnitude: 2] = 1.0 _ = gen.calculatedSamples(graph: makeSynthGraph(engine: engine), count: testBlockSize) #expect(gen.previousOutputValue > 0.0) } @Test func knownFluxValue() { // Frame 1: all zeros. Frame 2: bin2 = 1.0. // diff[2] = 1.0, all others = 0; sumSquares = 1, flux = sqrt(1/5) ≈ 0.4472 let s: SpectralBuffer = makeSpectral() let gen: SpectralFlux.Control = SpectralFlux.Control(spectral: s) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) advanceBlock(engine) s[magnitude: 2] = 1.0 _ = gen.calculatedSamples(graph: makeSynthGraph(engine: engine), count: testBlockSize) let expected: Double = sqrt(1.0 / Double(s.binCount)) #expect(abs(gen.previousOutputValue - expected) < 1e-6) } } // MARK: - SpectralEntropy.Control @Suite("SpectralEntropy.Control") struct SpectralEntropyTests { let engine: SynthesisEngine var graph: SynthGraph { makeSynthGraph(engine: engine) } init() throws { engine = makeTestEngine(blockSize: testBlockSize, sampleRate: testSampleRate) try engine.start() } @Test func rateIsControl() { let s: SpectralBuffer = makeSpectral() #expect(SpectralEntropy.Control(spectral: s).rate == .control) } @Test func silenceOutputsZero() { let s: SpectralBuffer = makeSpectral() let gen: SpectralEntropy.Control = SpectralEntropy.Control(spectral: s) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) #expect(abs(gen.previousOutputValue) < 1e-10) } @Test func singleBinOutputsZeroEntropy() { // All energy concentrated in one bin → H = 0. let s: SpectralBuffer = makeSpectral() s[magnitude: 2] = 1.0 let gen: SpectralEntropy.Control = SpectralEntropy.Control(spectral: s) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) #expect(abs(gen.previousOutputValue) < 1e-10) } @Test func allBinsEqualOutputsOneEntropy() { // Uniform distribution → maximum entropy → normalized H = 1.0. let s: SpectralBuffer = makeSpectral() s.dcValue = 1.0 s[magnitude: 1] = 1.0 s[magnitude: 2] = 1.0 s[magnitude: 3] = 1.0 s.nyquistValue = 1.0 let gen: SpectralEntropy.Control = SpectralEntropy.Control(spectral: s) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) #expect(abs(gen.previousOutputValue - 1.0) < 1e-6) } @Test func outputInZeroOneRange() { let s: SpectralBuffer = makeSpectral() s[magnitude: 1] = 3.0 s[magnitude: 2] = 1.0 s[magnitude: 3] = 0.5 let gen: SpectralEntropy.Control = SpectralEntropy.Control(spectral: s) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) #expect(gen.previousOutputValue >= 0.0) #expect(gen.previousOutputValue <= 1.0) } @Test func moreUniformDistributionHasHigherEntropy() { // Uniform bins should have higher entropy than a single spike. let e: SynthesisEngine = engine let sSpike: SpectralBuffer = makeSpectral() sSpike[magnitude: 2] = 1.0 let sUniform: SpectralBuffer = makeSpectral() sUniform[magnitude: 1] = 1.0 sUniform[magnitude: 2] = 1.0 sUniform[magnitude: 3] = 1.0 let genSpike: SpectralEntropy.Control = SpectralEntropy.Control(spectral: sSpike) let genUniform: SpectralEntropy.Control = SpectralEntropy.Control(spectral: sUniform) _ = genSpike.calculatedSamples(graph: makeSynthGraph(engine: e), count: testBlockSize) _ = genUniform.calculatedSamples(graph: makeSynthGraph(engine: e), count: testBlockSize) #expect(genSpike.previousOutputValue < genUniform.previousOutputValue) } } // MARK: - SpectralRolloff.Control @Suite("SpectralRolloff.Control") struct SpectralRolloffTests { let engine: SynthesisEngine var graph: SynthGraph { makeSynthGraph(engine: engine) } init() throws { engine = makeTestEngine(blockSize: testBlockSize, sampleRate: testSampleRate) try engine.start() } @Test func rateIsControl() { let s: SpectralBuffer = makeSpectral() #expect(SpectralRolloff.Control(spectral: s, sampleRate: testSampleRate).rate == .control) } @Test func silenceOutputsZero() { let s: SpectralBuffer = makeSpectral() let gen: SpectralRolloff.Control = SpectralRolloff.Control(spectral: s, sampleRate: testSampleRate) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) #expect(abs(gen.previousOutputValue) < 1e-10) } @Test func singleBinRolloffEqualsItsBinFrequency() { // All energy at bin 2. Any rolloffPercent > 0 should give k_r = 2 → 2.0 Hz. let s: SpectralBuffer = makeSpectral() s[magnitude: 2] = 1.0 let gen: SpectralRolloff.Control = SpectralRolloff.Control(spectral: s, sampleRate: testSampleRate, rolloffPercent: 0.85) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) #expect(abs(gen.previousOutputValue - 2.0) < 1e-6) } @Test func knownDistributionRolloff85Percent() { // bin1=2.0, bin2=1.0, bin3=1.0 → energies: 4, 1, 1 (DC/Nyquist = 0) // Total energy = 6. 85% threshold = 5.1. // Cumulative: k=0: 0, k=1: 4, k=2: 5, k=3: 6 ≥ 5.1 → rolloff at bin 3 = 3.0 Hz. let s: SpectralBuffer = makeSpectral() s[magnitude: 1] = 2.0 s[magnitude: 2] = 1.0 s[magnitude: 3] = 1.0 let gen: SpectralRolloff.Control = SpectralRolloff.Control(spectral: s, sampleRate: testSampleRate, rolloffPercent: 0.85) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) #expect(abs(gen.previousOutputValue - 3.0) < 1e-6) } @Test func rolloffAt50PercentLowerThanAt90Percent() { // With asymmetric distribution, 50% rolloff < 90% rolloff. let e: SynthesisEngine = engine let s1: SpectralBuffer = makeSpectral() s1[magnitude: 1] = 2.0; s1[magnitude: 2] = 1.0; s1[magnitude: 3] = 1.0 let s2: SpectralBuffer = makeSpectral() s2[magnitude: 1] = 2.0; s2[magnitude: 2] = 1.0; s2[magnitude: 3] = 1.0 let gen50: SpectralRolloff.Control = SpectralRolloff.Control(spectral: s1, sampleRate: testSampleRate, rolloffPercent: 0.50) let gen90: SpectralRolloff.Control = SpectralRolloff.Control(spectral: s2, sampleRate: testSampleRate, rolloffPercent: 0.90) _ = gen50.calculatedSamples(graph: makeSynthGraph(engine: e), count: testBlockSize) _ = gen90.calculatedSamples(graph: makeSynthGraph(engine: e), count: testBlockSize) #expect(gen50.previousOutputValue <= gen90.previousOutputValue) } @Test func rolloffPercentClampedToValidRange() { // rolloffPercent > 1.0 should be clamped to 1.0 (last bin). let s: SpectralBuffer = makeSpectral() s[magnitude: 2] = 1.0 let gen: SpectralRolloff.Control = SpectralRolloff.Control(spectral: s, sampleRate: testSampleRate, rolloffPercent: 2.0) _ = gen.calculatedSamples(graph: graph, count: testBlockSize) // Should not crash; output should be finite. #expect(gen.previousOutputValue.isFinite) } }