// FormantGrainTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing @testable @_spi(LyrebirdExtensions) import LyrebirdSynth @Suite("FormantGrain") struct FormantGrainTests { func makeEngine(blockSize: Int = 512) throws -> SynthesisEngine { let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize) try engine.start() return engine } // MARK: - Rate @Test func rateIsAudio() throws { let gen: FormantGrain.Audio = FormantGrain.Audio() #expect(gen.rate == .audio) } // MARK: - Output shape @Test func outputIsMonoOnechannel() throws { let engine: SynthesisEngine = try makeEngine() let graph: SynthGraph = makeSynthGraph(engine: engine) defer { engine.stop() } let gen: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 200.0) let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512) #expect(out.count == 1, "FormantGrain must produce mono (1 channel), got \(out.count)") } @Test func outputCountMatchesRequest() throws { let engine: SynthesisEngine = try makeEngine(blockSize: 64) let graph: SynthGraph = makeSynthGraph(engine: engine) defer { engine.stop() } let gen: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 200.0, amp: 0.5) let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64) #expect(out[0].count >= 64, "Output must cover at least count samples") // Verify the requested range was actually written to (not residual buffer state). let writtenEnergy: Double = out[0].prefix(64).reduce(0.0) { $0 + abs($1) } #expect(writtenEnergy > 0, "First 64 samples must be written by this block, not residual zeros") } // MARK: - Non-silence @Test func firstBlockIsNonSilent() throws { let engine: SynthesisEngine = try makeEngine(blockSize: 512) let graph: SynthGraph = makeSynthGraph(engine: engine) defer { engine.stop() } // Default params: 100 Hz glottal, 700 Hz formant — first grain fires at sample 0. let gen: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 200.0, amp: 0.5) let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512) let energy: Double = out[0].prefix(512).reduce(0.0) { $0 + abs($1) } #expect(energy > 0, "First block must be non-silent — grain fires at sample 0") } // MARK: - Grain envelope (rise then decay) @Test func grainPeakOccursAfterRisePhase() throws { // At 700 Hz formant / 44100 SR: rise = SR/(2*700) ≈ 31.5 samples. // The peak should occur around sample 31. let engine: SynthesisEngine = try makeEngine(blockSize: 512) let graph: SynthGraph = makeSynthGraph(engine: engine) defer { engine.stop() } // High glottalFreq relative to formant so only one grain fires in the block. // Actually use very low glottal so only one grain fires: 1 Hz → hopSize ≈ 44100 samples. let gen: FormantGrain.Audio = FormantGrain.Audio( glottalFreq: 1.0, formantFreq: 700.0, bandwidth: 200.0, amp: 1.0 ) let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512) let samples: [Double] = out[0] // First sample should be near zero (envelope starts at sin²(0) = 0). #expect(abs(samples[0]) < 0.01, "First sample must be near zero (grain envelope starts at 0)") // Find the sample with maximum absolute value. let maxAbsIdx: Range.Index>.Element = samples.prefix(512).indices.max(by: { abs(samples[$0]) < abs(samples[$1]) }) ?? 0 // Peak should be within a few samples of the theoretical rise end (~31.5 samples). let expectedRise: Int = Int(44100.0 / (2.0 * 700.0)) #expect(maxAbsIdx >= expectedRise / 2, "Peak should occur after some rise; found at sample \(maxAbsIdx)") } // MARK: - Decay to silence @Test func grainDecaysToSilenceAfterSufficientTime() throws { // With bandwidth=2000 Hz, decay is very fast: exp(-π*2000/44100) ≈ 0.867 per sample. // After ~64 samples the grain should be near silent (well below fofGrainDeathThreshold=1e-4). let engine: SynthesisEngine = try makeEngine(blockSize: 512) let graph: SynthGraph = makeSynthGraph(engine: engine) defer { engine.stop() } let gen: FormantGrain.Audio = FormantGrain.Audio( glottalFreq: 0.5, // one grain, far from next trigger formantFreq: 4000.0, // short rise bandwidth: 5000.0, // very fast decay amp: 1.0 ) // Run two full blocks. _ = gen.calculatedSamples(graph: graph, count: 512) advanceBlock(engine) let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: 512) let energy2: Double = out2[0].prefix(512).reduce(0.0) { $0 + abs($1) } #expect(energy2 < 1e-2, "Grain must decay to near silence within the second block with high bandwidth") } // MARK: - Pool saturation @Test func poolSaturationDoesNotProduceNaN() throws { // Very high glottal rate + low bandwidth (long grains) → many overlapping grains. let engine: SynthesisEngine = try makeEngine(blockSize: 512) let graph: SynthGraph = makeSynthGraph(engine: engine) defer { engine.stop() } let gen: FormantGrain.Audio = FormantGrain.Audio( glottalFreq: 2000.0, // triggers every ~22 samples formantFreq: 500.0, bandwidth: 10.0, // very slow decay → long grains amp: 0.01 ) for _ in 0..<4 { let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512) for s: Double in out[0].prefix(512) { #expect(s.isFinite, "Output must be finite; pool overflow must not produce NaN/Inf") } advanceBlock(engine) } } @Test func poolFullStealsOldestGrain() throws { // Sustained over-saturation: glottal rate forces > poolSize grains alive simultaneously. // Steal-oldest policy must keep producing audible output (not silence). let engine: SynthesisEngine = try makeEngine(blockSize: 512) let graph: SynthGraph = makeSynthGraph(engine: engine) defer { engine.stop() } // 4000 Hz triggers every ~11 samples → ~46 spawns per 512-block. // bandwidth=5 → decayFactor ≈ exp(-π*5/44100) ≈ 0.99964 — grains live thousands of samples. let gen: FormantGrain.Audio = FormantGrain.Audio( glottalFreq: 4000.0, formantFreq: 600.0, bandwidth: 5.0, amp: 0.01 ) // Run several blocks to fully saturate the pool. for _ in 0..<8 { _ = gen.calculatedSamples(graph: graph, count: 512) advanceBlock(engine) } // After saturation, output must remain non-zero — steal-oldest keeps fresh grains active. let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512) let energy: Double = out[0].prefix(512).reduce(0.0) { $0 + abs($1) } #expect(energy > 0, "Output must remain audible after pool saturation; steal-oldest must keep new grains active") } @Test func glottalFreqAboveSampleRateIsClamped() throws { // glottalFreq > sampleRate would cause hopSize < 1 and same-sample re-trigger; // input clamp must keep output finite and prevent infinite spawn loop. let engine: SynthesisEngine = try makeEngine(blockSize: 256) let graph: SynthGraph = makeSynthGraph(engine: engine) defer { engine.stop() } let gen: FormantGrain.Audio = FormantGrain.Audio( glottalFreq: 1_000_000.0, // absurdly high — gets clamped to sampleRate formantFreq: 600.0, bandwidth: 200.0, amp: 0.01 ) let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 256) for s: Double in out[0].prefix(256) { #expect(s.isFinite, "Clamped glottalFreq must produce finite output") } } @Test func formantFreqAboveSampleRateIsFinite() throws { // formantFreq > sampleRate makes sinePhaseInc > 2π — wrap must use truncatingRemainder. let engine: SynthesisEngine = try makeEngine(blockSize: 256) let graph: SynthGraph = makeSynthGraph(engine: engine) defer { engine.stop() } let gen: FormantGrain.Audio = FormantGrain.Audio( glottalFreq: 100.0, formantFreq: 100_000.0, // way above 44.1k bandwidth: 200.0, amp: 0.5 ) let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 256) for s: Double in out[0].prefix(256) { #expect(s.isFinite, "formantFreq > sampleRate phase wrap must remain finite") } } // MARK: - Octaviation @Test func octaviationZeroAndOneProduceDifferentOutput() throws { let engine: SynthesisEngine = try makeEngine(blockSize: 512) defer { engine.stop() } let graph1: SynthGraph = makeSynthGraph(engine: engine) let gen0: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 200.0, octaviation: 0.0, amp: 0.5) let out0: [[Double]] = gen0.calculatedSamples(graph: graph1, count: 512) let gen1: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 200.0, octaviation: 1.0, amp: 0.5) let out1: [[Double]] = gen1.calculatedSamples(graph: graph1, count: 512) // With octaviation, every other grain is negated — energy sum should differ. let sum0: Double = out0[0].prefix(512).reduce(0.0, +) let sum1: Double = out1[0].prefix(512).reduce(0.0, +) let octaviationDiffEpsilon: Double = 1e-6 #expect(abs(sum0 - sum1) > octaviationDiffEpsilon, "Octaviation=0 and =1 must produce meaningfully different output (sum0=\(sum0), sum1=\(sum1))") } // MARK: - MulAdd @Test func mulScalesOutput() throws { let engine: SynthesisEngine = try makeEngine(blockSize: 512) let graph: SynthGraph = makeSynthGraph(engine: engine) defer { engine.stop() } let gen1x: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 200.0, amp: 0.5, mul: 1.0) let gen2x: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 200.0, amp: 0.5, mul: 2.0) let out1: [[Double]] = gen1x.calculatedSamples(graph: graph, count: 512) let out2: [[Double]] = gen2x.calculatedSamples(graph: graph, count: 512) let energy1: Double = out1[0].prefix(512).reduce(0.0) { $0 + abs($1) } let energy2: Double = out2[0].prefix(512).reduce(0.0) { $0 + abs($1) } #expect(abs(energy2 - 2.0 * energy1) < energy1 * 0.01, "mul:2 must double output energy; got \(energy2) vs \(2.0 * energy1)") } // MARK: - Determinism @Test func sameParamsSameOutput() throws { let engine: SynthesisEngine = try makeEngine(blockSize: 512) let graph: SynthGraph = makeSynthGraph(engine: engine) defer { engine.stop() } let gen1: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 80.0, formantFreq: 1000.0, bandwidth: 150.0, amp: 0.4) let gen2: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 80.0, formantFreq: 1000.0, bandwidth: 150.0, amp: 0.4) let out1: [[Double]] = gen1.calculatedSamples(graph: graph, count: 512) let out2: [[Double]] = gen2.calculatedSamples(graph: graph, count: 512) for i: Int in 0..<512 { #expect(out1[0][i] == out2[0][i], "Same params must produce identical output at sample \(i)") } } // MARK: - GeneratorInput driving @Test func generatorDrivenFormantFreqIsFinite() throws { // When formantFreq is driven by a generator, output must remain finite. let engine: SynthesisEngine = try makeEngine(blockSize: 512) let graph: SynthGraph = makeSynthGraph(engine: engine) defer { engine.stop() } let freqGen: OscSin.Audio = OscSin.Audio(freq: 1.0, mul: 200.0, add: 440.0) let gen: FormantGrain.Audio = FormantGrain.Audio( glottalFreq: 200.0, formantFreq: freqGen, bandwidth: 100.0, amp: 0.3 ) let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512) for s: Double in out[0].prefix(512) { #expect(s.isFinite, "Generator-driven formantFreq must produce finite output") } } }