Files
Lyrebird/Tests/LyrebirdTests/Generators/Analysis/ZeroCrossingAudioTests.swift
T
2026-06-21 11:45:58 -07:00

195 lines
9.4 KiB
Swift

// 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..<blockSize {
#expect(out[0][i] == 0.0,
"constant positive DC input: freq should be 0 (no crossing), got \(out[0][i]) at sample \(i)")
}
}
/// Constant negative input: no rising zero crossing from the initial state (prevSample=0,
/// x=-1 — condition prevSample<=0 && x>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..<blockSize {
#expect(out[0][i] == 0.0,
"constant negative input should yield freq 0, got \(out[0][i]) at sample \(i)")
}
}
/// Square wave with period P samples yields freq = sampleRate / P after the second
/// measured rising zero crossing.
///
/// A square wave alternates every P/2 samples. The rising ZC (≤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..<blockSize {
#expect(abs(out[0][i] - expectedFreq) < 1e-9,
"sample \(i): expected \(expectedFreq) (stable period after 2nd crossing), got \(out[0][i])")
}
}
/// Frequency is held between crossings (output stays constant between rising edges).
///
/// Uses a signal starting at -1 so that `_prevSample` is lazy-initialised to -1 on
/// sample 0 and no spurious crossing fires. Signal: -1 for samples 0..9, +1 for
/// 10..19, -1 for 20..29, +1 for 30..39 …
///
/// Sample 0: lazy-init sets prevSample=-1. count incremented to 1. No crossing (x=-1).
/// First rising crossing fires at sample 10 with count = halfPeriod+1 = 11 (samples
/// 0..10 each increment count, 11 > 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..<halfPeriod {
#expect(out[0][i] == 0.0,
"sample \(i): expected 0 (no crossing yet), got \(out[0][i])")
}
// Sample 10: first rising crossing. Count at crossing = halfPeriod+1 = 11 (>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..<blockSize {
if out2[0][i] > 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..<blockSize {
#expect(out1[0][i] == out2[0][i])
}
}
/// mul/add: output is original*2+1.
@Test func mulAdd() {
let halfPeriod: Int = 8
let inputSignal: Closure = Closure { _, i in ((i / halfPeriod) % 2 == 0) ? -1.0 : 1.0 }
let genBase: ZeroCrossing.Audio = ZeroCrossing.Audio(input: inputSignal)
let genScaled: ZeroCrossing.Audio = ZeroCrossing.Audio(
input: inputSignal,
mul: 2.0,
add: 1.0
)
let base: [[Double]] = genBase.calculatedSamples(graph: graph, count: blockSize)
let scaled: [[Double]] = genScaled.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
let expected: Double = base[0][i] * 2.0 + 1.0
#expect(abs(scaled[0][i] - expected) < 1e-12,
"mulAdd sample \(i): expected \(expected) got \(scaled[0][i])")
}
}
}