// ZeroCrossingAudioTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing import Foundation @testable @_spi(LyrebirdExtensions) import LyrebirdSynth @MainActor @Suite("ZeroCrossing.Audio") struct ZeroCrossingAudioTests { let engine: SynthesisEngine var graph: SynthGraph { makeSynthGraph(engine: engine) } let blockSize: Int = 64 let sampleRate: Double = 44100 init() throws { engine = makeTestEngine(blockSize: 64, sampleRate: 44100) try engine.start() } @Test func rateIsAudio() { let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: 0.0) #expect(gen.rate == .audio) } /// Output count matches request. @Test func outputCountMatchesRequest() { let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: 0.5) let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) #expect(Array(out[0].prefix(blockSize)).count == blockSize) } /// Constant positive (DC) input produces no zero crossing and freq stays at `0.0`. /// /// `_prevSample` is lazy-initialised to the first input sample (`+1`). Since `prevSample` /// equals `x` on every subsequent sample, the rising-edge condition /// `prevSample <= 0 && x > 0` is never satisfied. SuperCollider `ZeroCrossing` /// exhibits identical behaviour (`m_previn = ZIN0(0)`). @Test func constantPositiveDCInputYieldsZeroFreq() { let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: 1.0) let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) for i: Int in 0..0 is false). Freq stays 0. @Test func constantNegativeInputNoZeroCrossing() { let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: -1.0) let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) for i: Int in 0..0) fires every P /// samples from the second crossing onward. `_prevSample` is lazy-initialised to the /// first input sample (-1), so no spurious crossing fires on sample 0. The first /// crossing at sample 8 has a count of 9 (incremented for samples 0..8); the second /// and subsequent crossings measure exactly P = 16. @Test func squareWaveKnownPeriodYieldsExpectedFreq() { // Period = 16 samples. Signal: -1 for samples 0..7, +1 for 8..15, -1 for 16..23, +1 for 24..31 ... // Sample 0: lazy-init sets prevSample=-1. count=1. No crossing (x=-1). // Sample 8: count=9 (>4). prevSample=-1<=0, x=+1>0 → crossing fires. freq=sr/9. count=0. // Sample 24: count=16 (>4). prev=-1<=0, x=+1>0 → crossing. freq=sr/16. // From sample 24 onward, freq is sr/16. let period: Int = 16 let halfPeriod: Int = period / 2 let expectedFreq: Double = sampleRate / Double(period) let inputSignal: Closure = Closure { _, i in ((i / halfPeriod) % 2 == 0) ? -1.0 : 1.0 } let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: inputSignal) let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) // The second rising crossing is at sample 24 (period=16, half=8: -1 @ 0..7, +1 @ 8..15, // -1 @ 16..23, +1 @ 24..31). From sample 24 onward, freq should be sr/16. let secondCrossingAt: Int = period + halfPeriod // 24 for i: Int in secondCrossingAt.. zeroCrossingMinCount). Freq = sr/11. Count resets. /// Second rising crossing fires at sample 30 with count = halfPeriod*2 = 20. Freq = sr/20. /// Between crossings the output holds the last measured freq. @Test func freqHeldBetweenCrossings() { let halfPeriod: Int = 10 // Start with -1 for first half-period so lazy-init sets prevSample=-1 (no crossing). let inputSignal: Closure = Closure { _, i in ((i / halfPeriod) % 2 == 0) ? -1.0 : 1.0 } let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: inputSignal) let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) // Samples 0..9: no crossing yet (count stays below threshold or x never >0), freq = 0. for i: Int in 0..4). Freq = sr/11. let firstCrossingCount: Int = halfPeriod + 1 let freqAfterFirstCrossing: Double = sampleRate / Double(firstCrossingCount) // Samples 10..29: freq held at freqAfterFirstCrossing (next crossing not until sample 30). for i: Int in halfPeriod..<(halfPeriod * 3) { #expect(abs(out[0][i] - freqAfterFirstCrossing) < 1e-9, "sample \(i): expected \(freqAfterFirstCrossing) (held after 1st crossing), got \(out[0][i])") } // Sample 30: second rising crossing. Count since reset = halfPeriod*2 = 20 (>4). Freq = sr/20. let secondCrossingCount: Int = halfPeriod * 2 let freqAfterSecondCrossing: Double = sampleRate / Double(secondCrossingCount) // Samples 30..49: freq held at freqAfterSecondCrossing. for i: Int in (halfPeriod * 3)..<(halfPeriod * 5) { #expect(abs(out[0][i] - freqAfterSecondCrossing) < 1e-9, "sample \(i): expected \(freqAfterSecondCrossing) (held after 2nd crossing), got \(out[0][i])") } } /// Cross-block continuity: state (counter) carries across audio blocks. @Test func crossBlockContinuity() { // Square wave with period 32: crossing happens at sample 16 and 32 (=0 of block 2). // Block 1 measures 32 samples between crossings (at sample 16 the count includes samples // from the previous block which starts at 0, so count = 16+prev if counter carried). // This test verifies counter survives block boundary — non-zero freq in block 2. let halfPeriod: Int = 16 let inputSignal: Closure = Closure { _, i in ((i / halfPeriod) % 2 == 0) ? 1.0 : -1.0 } let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: inputSignal) _ = gen.calculatedSamples(graph: graph, count: blockSize) advanceBlock(engine) let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) // Block 2 should still detect crossings and emit a non-zero freq. var hasNonZero: Bool = false for i: Int in 0.. 0.0 { hasNonZero = true break } } #expect(hasNonZero, "expected non-zero freq in block 2 (counter should carry across blocks)") } /// Fan-out: two calls same segment return identical first channel. @Test func fanOut() { let inputSignal: Closure = Closure { _, i in i % 8 < 4 ? 1.0 : -1.0 } let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: inputSignal) let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize) for i: Int in 0..