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

453 lines
18 KiB
Swift

// OnsetDetectorTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
/// Convenience: drive a detector directly with a sequence of magnitude profiles.
/// `magsByHop[h][k]` is the magnitude for bin `k` (`k` in `1..<halfSize`) on hop `h`.
private func runMagnitudeHops(
detector: OnsetDetector,
fftSize: Int,
hops: Int,
mag: (Int) -> Float
) {
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let halfSize: Int = fftSize / 2
for h: Int in 0..<hops {
for k: Int in 1..<halfSize {
buf[magnitude: k] = mag(h)
buf[phase: k] = 0
}
detector.process(spectral: buf, engine: makeTestEngine())
}
}
// MARK: - Construction
@MainActor
@Suite("OnsetDetector init validation")
struct OnsetDetectorInitTests {
@Test func acceptsValidParameters() {
_ = OnsetDetector(fftSize: 64, hopSize: 16)
_ = OnsetDetector(fftSize: 1024, hopSize: 256, method: .complexDomain,
threshold: 2.0, medianWindowFrames: 5, minHopsBetweenOnsets: 2)
}
@Test func defaultParametersApplied() {
let d: OnsetDetector = OnsetDetector(fftSize: 64, hopSize: 16)
#expect(d.threshold == 1.5)
#expect(d.minHopsBetweenOnsets == 3)
}
@Test func parameterUpdatesAreReadable() {
let d: OnsetDetector = OnsetDetector(fftSize: 64, hopSize: 16)
d.threshold = 2.5
#expect(d.threshold == 2.5)
d.minHopsBetweenOnsets = 7
#expect(d.minHopsBetweenOnsets == 7)
}
@Test func minHopsBetweenOnsetsClampsNegatives() {
let d: OnsetDetector = OnsetDetector(fftSize: 64, hopSize: 16)
d.minHopsBetweenOnsets = -5
#expect(d.minHopsBetweenOnsets == 0)
}
}
// MARK: - Spectral flux ODF
@MainActor
@Suite("OnsetDetector .spectralFlux")
struct OnsetDetectorFluxTests {
/// Steady silence over many hops produces no triggers.
@Test func silenceProducesNoTriggers() {
let fftSize: Int = 64
let detector: OnsetDetector = OnsetDetector(
fftSize: fftSize,
hopSize: 16,
method: .spectralFlux,
threshold: 1.5,
medianWindowFrames: 5,
minHopsBetweenOnsets: 0
)
let serialBefore: UInt64 = detector._loadOnsetSerial()
runMagnitudeHops(detector: detector, fftSize: fftSize, hops: 50) { _ in 0 }
#expect(detector._loadOnsetSerial() == serialBefore)
}
/// During the warmup window (first `medianWindowFrames` hops) no trigger
/// fires even on a large ODF spike.
@Test func warmupSuppressesTrigger() {
let fftSize: Int = 64
let medianWindow: Int = 5
let detector: OnsetDetector = OnsetDetector(
fftSize: fftSize,
hopSize: 16,
method: .spectralFlux,
threshold: 1.5,
medianWindowFrames: medianWindow,
minHopsBetweenOnsets: 0
)
let serialBefore: UInt64 = detector._loadOnsetSerial()
// Spike on hop 1 (within warmup).
runMagnitudeHops(detector: detector, fftSize: fftSize, hops: medianWindow) { h in
h == 1 ? 1.0 : 0
}
#expect(detector._loadOnsetSerial() == serialBefore,
"Should not trigger inside warmup window")
}
/// A big magnitude jump after warmup fires exactly one onset.
@Test func stepInputFiresOnce() {
let fftSize: Int = 64
let medianWindow: Int = 5
let detector: OnsetDetector = OnsetDetector(
fftSize: fftSize,
hopSize: 16,
method: .spectralFlux,
threshold: 1.5,
medianWindowFrames: medianWindow,
minHopsBetweenOnsets: 100 // huge refractory: only first onset can fire
)
// Hops 0..<medianWindow: silence (warmup).
runMagnitudeHops(detector: detector, fftSize: fftSize, hops: medianWindow) { _ in 0 }
let serialAfterWarmup: UInt64 = detector._loadOnsetSerial()
// One spike hop.
runMagnitudeHops(detector: detector, fftSize: fftSize, hops: 1) { _ in 1.0 }
#expect(detector._loadOnsetSerial() == serialAfterWarmup &+ 1)
// Continue with sustained magnitude — no further onsets.
runMagnitudeHops(detector: detector, fftSize: fftSize, hops: 20) { _ in 1.0 }
#expect(detector._loadOnsetSerial() == serialAfterWarmup &+ 1)
}
/// Refractory period suppresses adjacent onsets.
@Test func refractoryBlocksAdjacentOnsets() {
let fftSize: Int = 64
let medianWindow: Int = 5
let refractory: Int = 4
let detector: OnsetDetector = OnsetDetector(
fftSize: fftSize,
hopSize: 16,
method: .spectralFlux,
threshold: 1.2,
medianWindowFrames: medianWindow,
minHopsBetweenOnsets: refractory
)
runMagnitudeHops(detector: detector, fftSize: fftSize, hops: medianWindow) { _ in 0 }
let baseline: UInt64 = detector._loadOnsetSerial()
// Three magnitude jumps in immediate succession — all but the first should be
// suppressed by the 4-hop refractory.
runMagnitudeHops(detector: detector, fftSize: fftSize, hops: 1) { _ in 1.0 }
runMagnitudeHops(detector: detector, fftSize: fftSize, hops: 1) { _ in 2.0 }
runMagnitudeHops(detector: detector, fftSize: fftSize, hops: 1) { _ in 3.0 }
#expect(detector._loadOnsetSerial() == baseline &+ 1)
}
/// Falling magnitude (offset, not onset) does not fire — half-wave rectification.
@Test func fallingMagnitudeDoesNotFire() {
let fftSize: Int = 64
let medianWindow: Int = 5
let detector: OnsetDetector = OnsetDetector(
fftSize: fftSize,
hopSize: 16,
method: .spectralFlux,
threshold: 1.5,
medianWindowFrames: medianWindow,
minHopsBetweenOnsets: 0
)
// Saturate: large magnitude during warmup, then drop to zero.
runMagnitudeHops(detector: detector, fftSize: fftSize, hops: medianWindow) { _ in 1.0 }
let baseline: UInt64 = detector._loadOnsetSerial()
runMagnitudeHops(detector: detector, fftSize: fftSize, hops: 5) { _ in 0 }
#expect(detector._loadOnsetSerial() == baseline,
"Magnitude drop should not fire onset")
}
/// `lastODF` is non-zero immediately after a spike.
@Test func telemetryReflectsRecentODF() {
let fftSize: Int = 64
let detector: OnsetDetector = OnsetDetector(
fftSize: fftSize,
hopSize: 16,
method: .spectralFlux,
medianWindowFrames: 5
)
runMagnitudeHops(detector: detector, fftSize: fftSize, hops: 1) { _ in 0 }
runMagnitudeHops(detector: detector, fftSize: fftSize, hops: 1) { _ in 0.5 }
#expect(detector.lastODF > 0)
}
}
// MARK: - Complex-domain ODF
@MainActor
@Suite("OnsetDetector .complexDomain")
struct OnsetDetectorComplexDomainTests {
/// Phase-stable (predictable rotation) input never triggers.
@Test func stablePhaseDoesNotFire() {
let fftSize: Int = 64
let halfSize: Int = fftSize / 2
let medianWindow: Int = 5
let detector: OnsetDetector = OnsetDetector(
fftSize: fftSize,
hopSize: 16,
method: .complexDomain,
threshold: 2.0,
medianWindowFrames: medianWindow,
minHopsBetweenOnsets: 0
)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let phaseStep: Float = 0.5
// Drive each bin with constant magnitude and constant phase increment.
var phase: Float = 0
let totalHops: Int = medianWindow + 30
let serialBefore: UInt64 = detector._loadOnsetSerial()
for _ in 0..<totalHops {
for k: Int in 1..<halfSize {
buf[magnitude: k] = 1.0
buf[phase: k] = phase
}
phase += phaseStep
if phase > Float.pi { phase -= 2 * Float.pi }
detector.process(spectral: buf, engine: makeTestEngine())
}
#expect(detector._loadOnsetSerial() == serialBefore,
"Phase-stable input should not produce onsets")
}
/// A sudden magnitude jump on phase-stable input fires one onset.
@Test func magnitudeJumpFires() {
let fftSize: Int = 64
let halfSize: Int = fftSize / 2
let medianWindow: Int = 5
let detector: OnsetDetector = OnsetDetector(
fftSize: fftSize,
hopSize: 16,
method: .complexDomain,
threshold: 1.5,
medianWindowFrames: medianWindow,
minHopsBetweenOnsets: 100
)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
// Warm up with quiet, phase-stable signal.
var phase: Float = 0
let phaseStep: Float = 0.3
for _ in 0..<(medianWindow + 5) {
for k: Int in 1..<halfSize {
buf[magnitude: k] = 0.1
buf[phase: k] = phase
}
phase += phaseStep
if phase > Float.pi { phase -= 2 * Float.pi }
detector.process(spectral: buf, engine: makeTestEngine())
}
let baseline: UInt64 = detector._loadOnsetSerial()
// One hop with much larger magnitude — same phase progression.
for k: Int in 1..<halfSize {
buf[magnitude: k] = 5.0
buf[phase: k] = phase
}
phase += phaseStep
if phase > Float.pi { phase -= 2 * Float.pi }
detector.process(spectral: buf, engine: makeTestEngine())
#expect(detector._loadOnsetSerial() == baseline &+ 1)
}
}
// MARK: - .Control output
@MainActor
@Suite("OnsetDetector.Control output")
struct OnsetDetectorControlTests {
let engine: SynthesisEngine
var graph: SynthGraph { makeSynthGraph(engine: engine) }
let blockSize: Int = 64
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func rateIsControl() {
let detector: OnsetDetector = OnsetDetector(fftSize: 64, hopSize: 16)
let ctl: OnsetDetector.Control = OnsetDetector.Control(detector: detector)
#expect(ctl.rate == .control)
}
@Test func outputsZeroBeforeAnyOnset() {
let detector: OnsetDetector = OnsetDetector(fftSize: 64, hopSize: 16)
let ctl: OnsetDetector.Control = OnsetDetector.Control(detector: detector)
let result: [[Double]] = ctl.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
#expect(result[0][i] == 0.0)
}
}
@Test func outputsPulseAfterOnsetFires() {
let detector: OnsetDetector = OnsetDetector(fftSize: 64, hopSize: 16,
method: .spectralFlux,
threshold: 1.5,
medianWindowFrames: 5,
minHopsBetweenOnsets: 0)
let ctl: OnsetDetector.Control = OnsetDetector.Control(detector: detector)
// Drain initial-state read so the first calculatedSamples below sees no spurious change.
_ = ctl.calculatedSamples(graph: graph, count: blockSize)
engine.advanceSegmentSerial()
// Warm up + spike via direct processor calls.
runMagnitudeHops(detector: detector, fftSize: 64, hops: 5) { _ in 0 }
runMagnitudeHops(detector: detector, fftSize: 64, hops: 1) { _ in 1.0 }
let result: [[Double]] = ctl.calculatedSamples(graph: graph, count: blockSize)
#expect(result[0][0] == 1.0, "Pulse expected at sample 0 of triggered block")
for i: Int in 1..<blockSize {
#expect(result[0][i] == 0.0, "Sample \(i) should be 0 outside the pulse")
}
}
/// `count == 1` block must reset `previousOutputValue` to 0 — otherwise the
/// pulse sample IS the trailing sample and the next block's edge detection
/// would never see ≤0 again.
@Test func countOnePulseResetsPreviousOutputValue() {
let detector: OnsetDetector = OnsetDetector(fftSize: 64, hopSize: 16,
method: .spectralFlux,
threshold: 1.5,
medianWindowFrames: 5,
minHopsBetweenOnsets: 0)
let ctl: OnsetDetector.Control = OnsetDetector.Control(detector: detector)
_ = ctl.calculatedSamples(graph: graph, count: 1)
engine.advanceSegmentSerial()
runMagnitudeHops(detector: detector, fftSize: 64, hops: 5) { _ in 0 }
runMagnitudeHops(detector: detector, fftSize: 64, hops: 1) { _ in 1.0 }
let result: [[Double]] = ctl.calculatedSamples(graph: graph, count: 1)
#expect(result[0][0] == 1.0, "Pulse expected at sample 0")
#expect(ctl.previousOutputValue == 0.0,
"previousOutputValue must be cleared on count==1 pulse blocks")
}
@Test func subsequentBlockReturnsToZero() {
let detector: OnsetDetector = OnsetDetector(fftSize: 64, hopSize: 16,
method: .spectralFlux,
threshold: 1.5,
medianWindowFrames: 5,
minHopsBetweenOnsets: 0)
let ctl: OnsetDetector.Control = OnsetDetector.Control(detector: detector)
_ = ctl.calculatedSamples(graph: graph, count: blockSize)
engine.advanceSegmentSerial()
runMagnitudeHops(detector: detector, fftSize: 64, hops: 5) { _ in 0 }
runMagnitudeHops(detector: detector, fftSize: 64, hops: 1) { _ in 1.0 }
_ = ctl.calculatedSamples(graph: graph, count: blockSize)
engine.advanceSegmentSerial()
let next: [[Double]] = ctl.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
#expect(next[0][i] == 0.0)
}
}
}
// MARK: - End-to-end: real SpectralChain.Audio + impulse input
@MainActor
@Suite("OnsetDetector end-to-end via SpectralChain.Audio")
struct OnsetDetectorEndToEndTests {
/// Drive a real `SpectralChain.Audio → OnsetDetector → Control` chain with
/// a constant-DC input followed by a step to a much louder DC level. The
/// step produces a magnitude jump that the spectral-flux ODF must detect
/// after the median window fills.
@Test func detectsTransientThroughChain() throws {
let fftSize: Int = 128
let hopSize: Int = 64
let blockSize: Int = hopSize
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
defer { engine.stop() }
// Quiet input for the warmup; we'll swap in a louder one later.
let scaledInput: ParameterNode = ParameterNode(0.05)
let detector: OnsetDetector = OnsetDetector(
fftSize: fftSize,
hopSize: hopSize,
method: .spectralFlux,
threshold: 1.5,
medianWindowFrames: 5,
minHopsBetweenOnsets: 0
)
let analysis: SpectralChain.Audio = SpectralChain.Audio(
input: scaledInput,
fftSize: fftSize,
hopSize: hopSize,
stages: [.mono(detector)],
analyzeOnly: true
)
let ctl: OnsetDetector.Control = OnsetDetector.Control(detector: detector, analysis: analysis)
// Warm up — quiet signal, median ring fills with low ODF values.
for _ in 0..<12 {
let g: SynthGraph = makeSynthGraph(engine: engine)
_ = ctl.calculatedSamples(graph: g, count: blockSize)
advanceBlock(engine)
}
let baselineSerial: UInt64 = detector._loadOnsetSerial()
// Step up to a much louder level — magnitude jump → flux spike.
scaledInput.value = 1.0
var sawPulse: Bool = false
for _ in 0..<8 {
let g: SynthGraph = makeSynthGraph(engine: engine)
let out: [[Double]] = ctl.calculatedSamples(graph: g, count: blockSize)
if out[0][0] > 0.5 { sawPulse = true; break }
advanceBlock(engine)
}
#expect(detector._loadOnsetSerial() > baselineSerial,
"Detector should fire at least one onset on the level step")
#expect(sawPulse,
"Control should expose at least one ≤0→>0 pulse on the level step")
}
}
// MARK: - Registration precondition
@MainActor
@Suite("OnsetDetector.Control registration check")
struct OnsetDetectorRegistrationTests {
/// Constructing `OnsetDetector.Control(detector:analysis:)` against a
/// `SpectralChain.Audio` that does NOT include the detector must trap — a
/// silent "no triggers ever" outcome would be much harder to debug.
@Test func mismatchedAnalysisIsAccepted() {
// Smoke test of the happy path — wrong-analysis construction can't be
// probed via Swift Testing without `expectCrash` infrastructure, so we
// just confirm matching analysis succeeds. A misuse traps at runtime
// via the precondition in `OnsetDetector.Control(detector:analysis:)`.
let detector: OnsetDetector = OnsetDetector(fftSize: 64, hopSize: 16)
let analysis: SpectralChain.Audio = SpectralChain.Audio(
input: Double(0.1),
fftSize: 64,
hopSize: 16,
stages: [.mono(detector)],
analyzeOnly: true
)
_ = OnsetDetector.Control(detector: detector, analysis: analysis)
}
}