prep for 1.2.0 release updates

This commit is contained in:
2026-06-21 11:45:58 -07:00
parent 73191c958f
commit 032b7c39d3
286 changed files with 21116 additions and 121 deletions
@@ -0,0 +1,304 @@
// AdditiveSynthesizerTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("AdditiveSynthesizer")
struct AdditiveSynthesizerTests {
// MARK: - Helpers
/// Make a frame buffer populated with all-zero magnitudes.
private func makeZeroFrameBuffer(fftSize: Int = 64, frameCount: Int = 2) -> SpectralFrameBuffer {
SpectralFrameBuffer(
fftSize: fftSize,
hopSize: fftSize / 4,
frameCount: frameCount,
sampleRate: 44100
)
}
// MARK: - 1. Rate
@Test func rateIsAudio() {
let fb: SpectralFrameBuffer = makeZeroFrameBuffer()
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb)
#expect(gen.rate == .audio)
}
// MARK: - 2. Output count
@Test func outputCountMatchesRequest() throws {
let fb: SpectralFrameBuffer = makeZeroFrameBuffer()
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
try engine.start()
defer { engine.stop() }
let graph: SynthGraph = makeSynthGraph(engine: engine)
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
// The pre-allocated buffer has lyrebirdDefaultResultBufferSize (512) slots; check first 64 are accessible.
#expect(Array(out[0].prefix(64)).count == 64)
}
// MARK: - 3. Silent when all magnitudes are zero
@Test func silentWhenAllMagnitudesZero() throws {
let fb: SpectralFrameBuffer = makeZeroFrameBuffer()
// Buffer is zero-initialized by default — all magnitudes are 0.
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
try engine.start()
defer { engine.stop() }
let graph: SynthGraph = makeSynthGraph(engine: engine)
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: 0.0)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
let rms: Double = rmsValue(Array(out[0].prefix(64)))
#expect(rms < 1e-10)
}
// MARK: - 4. Non-silent with non-zero magnitude on bin 1
@Test func nonSilentWithNonZeroMagnitude() throws {
let fftSize: Int = 64
let fb: SpectralFrameBuffer = SpectralFrameBuffer(
fftSize: fftSize, hopSize: 16, frameCount: 2, sampleRate: 44100
)
// Set bin 1 magnitude in frame 0 to 1.0 via direct _mag pointer access.
// Layout: _mag[frame * halfSize + k] = magnitude for bin k in frame.
let halfSize: Int = fftSize / 2 // 32
fb._mag[0 * halfSize + 1] = 1.0
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
try engine.start()
defer { engine.stop() }
let graph: SynthGraph = makeSynthGraph(engine: engine)
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: 0.0)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
let rms: Double = rmsValue(Array(out[0].prefix(64)))
#expect(rms > 1e-6)
}
// MARK: - 5. Fan-out — same segment returns identical first-channel output
@Test func fanOutReturnsCachedResult() throws {
let fftSize: Int = 64
let fb: SpectralFrameBuffer = SpectralFrameBuffer(
fftSize: fftSize, hopSize: 16, frameCount: 2, sampleRate: 44100
)
let halfSize: Int = fftSize / 2
fb._mag[0 * halfSize + 1] = 0.5
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
try engine.start()
defer { engine.stop() }
let graph: SynthGraph = makeSynthGraph(engine: engine)
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: 0.0)
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
#expect(Array(out1[0].prefix(64)) == Array(out2[0].prefix(64)))
}
// MARK: - 6. State advances exactly once per block
@Test func stateAdvancesOncePerBlock() throws {
let fftSize: Int = 64
let fb: SpectralFrameBuffer = SpectralFrameBuffer(
fftSize: fftSize, hopSize: 16, frameCount: 2, sampleRate: 44100
)
let halfSize: Int = fftSize / 2
fb._mag[0 * halfSize + 1] = 1.0
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
try engine.start()
defer { engine.stop() }
var graph: SynthGraph = makeSynthGraph(engine: engine)
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: 0.0)
let block1a: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
// Second call in same segment — must be cache hit.
let block1b: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
#expect(block1a == block1b)
advanceBlock(engine)
graph = makeSynthGraph(engine: engine)
let block2: [Double] = Array(gen.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
// Phase advanced: block2 must differ from block1.
#expect(block1a != block2)
}
// MARK: - 7. maxPartials = 0 uses all bins
@Test func maxPartialsZeroUsesAllBins() throws {
let fftSize: Int = 64
let fb: SpectralFrameBuffer = makeZeroFrameBuffer(fftSize: fftSize)
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, maxPartials: 0)
// Internal _activePartials == halfSize - 1 == binCount
let expectedActive: Int = fftSize / 2 - 1
// Access via reflection is not possible; verify indirectly via output count matching
// a known non-zero-magnitude bin at the highest active index.
let halfSize: Int = fftSize / 2
fb._mag[0 * halfSize + expectedActive] = 1.0
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
try engine.start()
defer { engine.stop() }
let graph: SynthGraph = makeSynthGraph(engine: engine)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
let rms: Double = rmsValue(Array(out[0].prefix(64)))
// If maxPartials==0 is honouring all bins, the highest bin contributes signal.
#expect(rms > 0.0)
}
// MARK: - 8. maxPartials cap
@Test func maxPartialsCap() throws {
let fftSize: Int = 64
let fb: SpectralFrameBuffer = makeZeroFrameBuffer(fftSize: fftSize)
// With maxPartials=10, bin 11 should NOT contribute even when its magnitude is non-zero.
let halfSize: Int = fftSize / 2
fb._mag[0 * halfSize + 11] = 1.0 // frame 0, bin 11
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
try engine.start()
defer { engine.stop() }
let graph: SynthGraph = makeSynthGraph(engine: engine)
// maxPartials=10: only bins 1..10 are active; bin 11 is beyond the cap → silence.
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: 0.0, maxPartials: 10)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
let rms: Double = rmsValue(Array(out[0].prefix(64)))
#expect(rms < 1e-10)
}
// MARK: - 9. Position clamping — no crash on out-of-range positions
@Test func positionClampAbove() throws {
let fb: SpectralFrameBuffer = makeZeroFrameBuffer()
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
try engine.start()
defer { engine.stop() }
let graph: SynthGraph = makeSynthGraph(engine: engine)
// position = 2.0 > 1.0 — must clamp to last frame without crashing.
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: 2.0)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
#expect(out.count == 1)
}
@Test func positionClampBelow() throws {
let fb: SpectralFrameBuffer = makeZeroFrameBuffer()
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
try engine.start()
defer { engine.stop() }
let graph: SynthGraph = makeSynthGraph(engine: engine)
// position = -0.5 < 0.0 — must clamp to first frame without crashing.
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: -0.5)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
#expect(out.count == 1)
}
// MARK: - 10. Anti-aliasing — bin above Nyquist is zeroed
@Test func antialiasingZerosBinAboveNyquist() throws {
// At 44100 Hz playback, Nyquist = 22050 Hz.
// With fftSize=64 and sampleRate=44100: freqPerBin = 44100/64 ≈ 689 Hz.
// Bin 32 would be at 32 × 689 ≈ 22050 Hz — exactly at or above Nyquist.
// Use a very small fftSize to make a bin clearly above Nyquist.
// fftSize=8: halfSize=4, binCount=3, freqPerBin=44100/8=5512.5 Hz.
// Bin 3 → 3 × 5512.5 = 16537.5 Hz (below Nyquist=22050) → NOT zeroed.
// Use different sampleRate: recordSR matches but a bin whose k*freqPerBin > nyquist.
// fftSize=8 at recordSR=44100: freqPerBin = 5512.5 Hz
// bin 1 → 5512.5 Hz (below 22050) → active
// bin 3 → 16537.5 Hz (below 22050) → active
// To get above Nyquist: use a buffer recorded at 192000 Hz but played at 44100 Hz.
// freqPerBin = 192000/8 = 24000 Hz
// bin 1 → 24000 Hz > 22050 Hz → zeroed!
let fftSize: Int = 8
let fb: SpectralFrameBuffer = SpectralFrameBuffer(
fftSize: fftSize, hopSize: 2, frameCount: 2, sampleRate: 192000
)
let halfSize: Int = fftSize / 2 // 4
// Set bin 1 of frame 0 to a non-zero magnitude.
fb._mag[0 * halfSize + 1] = 1.0
// Play back at 44100 Hz — bin 1's frequency (192000/8 = 24000 Hz) > Nyquist (22050 Hz).
let engine: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
defer { engine.stop() }
let graph: SynthGraph = makeSynthGraph(engine: engine)
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: 0.0)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
let rms: Double = rmsValue(Array(out[0].prefix(64)))
// All bins are above Nyquist → output should be silence.
#expect(rms < 1e-10)
}
// MARK: - 11. mulAdd — with mul:2.0 add:1.0, output is original × 2 + 1
@Test func mulAddApplied() throws {
let fftSize: Int = 64
let fb: SpectralFrameBuffer = SpectralFrameBuffer(
fftSize: fftSize, hopSize: 16, frameCount: 2, sampleRate: 44100
)
let halfSize: Int = fftSize / 2
fb._mag[0 * halfSize + 1] = 0.5 // bin 1 has magnitude 0.5
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
try engine.start()
defer { engine.stop() }
// Plain generator (no mulAdd).
var graph: SynthGraph = makeSynthGraph(engine: engine)
let genPlain: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: 0.0)
let outPlain: [Double] = Array(genPlain.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
advanceBlock(engine)
graph = makeSynthGraph(engine: engine)
// Generator with mul:2.0, add:1.0.
let genMulAdd: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: 0.0, mul: 2.0, add: 1.0)
let outMulAdd: [Double] = Array(genMulAdd.calculatedSamples(graph: graph, count: 64)[0].prefix(64))
// Both generators share the same frame buffer and start from the same zero phase,
// so their base outputs are identical. Verify the relationship holds sample-by-sample.
for i: Int in 0..<64 {
let expected: Double = outPlain[i] * 2.0 + 1.0
#expect(abs(outMulAdd[i] - expected) < 1e-10)
}
}
// MARK: - 12. Integration — runs inside a Synthesizer on the engine without crash
@Test func integrationWithEngine() throws {
let fftSize: Int = 64
let fb: SpectralFrameBuffer = SpectralFrameBuffer(
fftSize: fftSize, hopSize: 16, frameCount: 2, sampleRate: 44100
)
let halfSize: Int = fftSize / 2
fb._mag[0 * halfSize + 1] = 0.5
final class AddSynth: SynthesizerBase {
let fb: SpectralFrameBuffer
init(fb: SpectralFrameBuffer) { self.fb = fb; super.init() }
override func build() {
let gen: AdditiveSynthesizer.Audio = AdditiveSynthesizer.Audio(frameBuffer: fb, position: 0.0)
addOutputGenerator(Out.Audio(bus: 0, source: gen))
}
}
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
try engine.start()
defer { engine.stop() }
let synth: AddSynth = AddSynth(fb: fb)
try engine.add(synth)
// Run a few blocks — must not crash.
for _ in 0..<4 {
engine.processBlock(inputSamples: [])
}
}
}
@@ -0,0 +1,452 @@
// 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)
}
}
@@ -0,0 +1,99 @@
// SpectralAutoPullTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
/// Verifies that the analysis-form constructors on spectral consumer
/// generators (`SpectralCentroid.Control`, etc.) drive the paired
/// `SpectralChain.Audio` evaluation themselves — callers do not need to add
/// the chain via `addOutputGenerator(...)` or to manually call
/// `chain.calculatedSamples(...)` each block.
@MainActor
@Suite("Spectral consumer auto-pull")
struct SpectralAutoPullTests {
@Test func spectralChainStandaloneProducesAudio() 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() }
// Constant DC input → chain populates the DC bin → IFFT bank
// resynthesises a constant scaled by the WOLA normalisation factor.
let chain: SpectralChain.Audio = SpectralChain.Audio(input: Double(1.0),
fftSize: fftSize, hopSize: hopSize)
var anyNonZero: Bool = false
for _ in 0..<8 {
let g: SynthGraph = makeSynthGraph(engine: engine)
let out: [[Double]] = chain.calculatedSamples(graph: g, count: blockSize)
for s: Double in out[0].prefix(blockSize) where s != 0 {
anyNonZero = true
break
}
advanceBlock(engine)
}
#expect(anyNonZero,
"SpectralChain.Audio should produce non-zero output for non-zero DC input")
}
@Test func spectralCentroidAutoPullsAnalysis() 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() }
let analysis: SpectralChain.Audio = SpectralChain.Audio(input: Double(1.0),
fftSize: fftSize, hopSize: hopSize,
analyzeOnly: true)
let centroid: SpectralCentroid.Control = SpectralCentroid.Control(analysis: analysis, sampleRate: 44_100)
// Run several blocks; centroid should track the DC bin (returns ≈ 0 Hz
// since DC is the dominant bin). The exact value isn't important — what
// matters is that the analysis got pulled (otherwise centroid would
// never see any spectral data). We assert centroid finishes finite.
for _ in 0..<8 {
let g: SynthGraph = makeSynthGraph(engine: engine)
_ = centroid.calculatedSamples(graph: g, count: blockSize)
advanceBlock(engine)
}
#expect(centroid.previousOutputValue.isFinite,
"Centroid should produce a finite value via auto-pull, got \(centroid.previousOutputValue)")
}
@Test func spectralFluxAutoPullsAnalysis() 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() }
let analysis: SpectralChain.Audio = SpectralChain.Audio(input: Double(1.0),
fftSize: fftSize, hopSize: hopSize,
analyzeOnly: true)
let flux: SpectralFlux.Control = SpectralFlux.Control(analysis: analysis)
for _ in 0..<8 {
let g: SynthGraph = makeSynthGraph(engine: engine)
_ = flux.calculatedSamples(graph: g, count: blockSize)
advanceBlock(engine)
}
// Flux on a steady DC signal should be ≈ 0 after the first block (no
// spectral change). It should NOT be NaN/inf.
#expect(flux.previousOutputValue.isFinite,
"Flux should produce a finite value via auto-pull, got \(flux.previousOutputValue)")
}
}
@@ -0,0 +1,218 @@
// SpectralBinDelayTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpectralBinDelay")
struct SpectralBinDelayTests {
/// `delayTime = 0` for every bin should make the processor a pass-through.
@Test func zeroDelayPassesThrough() {
let fftSize: Int = 64
let halfSize: Int = fftSize / 2
let hopSize: Int = 16
let testBin: Int = 5
let delays: LyrebirdBuffer = LyrebirdBuffer(count: halfSize)
delays.fill(with: 0.0)
let feedbacks: LyrebirdBuffer = LyrebirdBuffer(count: halfSize)
feedbacks.fill(with: 0.0)
let bd: SpectralBinDelay = SpectralBinDelay(
fftSize: fftSize,
hopSize: hopSize,
maxDelaySeconds: 0.05,
sampleRate: 44_100,
delayTimes: delays,
feedbacks: feedbacks
)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let inputMag: Float = 0.7
buf[magnitude: testBin] = inputMag
buf[phase: testBin] = 0
bd.process(spectral: buf, engine: makeTestEngine())
#expect(abs(buf[magnitude: testBin] - inputMag) < 1e-4,
"Zero delay should pass mag through, got \(buf[magnitude: testBin])")
}
/// With a fixed delay of N hops and zero feedback, the output should be the
/// input from N hops earlier.
@Test func fixedDelayProducesNHopLatency() {
let fftSize: Int = 64
let halfSize: Int = fftSize / 2
let hopSize: Int = 16
let sampleRate: Double = 44_100.0
let testBin: Int = 5
let delayHops: Int = 2
let delaySeconds: Double = Double(delayHops) * Double(hopSize) / sampleRate
let delays: LyrebirdBuffer = LyrebirdBuffer(count: halfSize)
delays.fill(with: 0.0)
delays.setValue(delaySeconds, at: testBin)
let feedbacks: LyrebirdBuffer = LyrebirdBuffer(count: halfSize)
feedbacks.fill(with: 0.0)
let bd: SpectralBinDelay = SpectralBinDelay(
fftSize: fftSize,
hopSize: hopSize,
maxDelaySeconds: 0.05,
sampleRate: sampleRate,
delayTimes: delays,
feedbacks: feedbacks
)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let inputMags: [Float] = [1.0, 2.0, 3.0, 4.0]
var outputMags: [Float] = []
for mag: Float in inputMags {
buf[magnitude: testBin] = mag
buf[phase: testBin] = 0
bd.process(spectral: buf, engine: makeTestEngine())
outputMags.append(buf[magnitude: testBin])
}
// First two hops: ring slots not yet populated → zero output.
#expect(abs(outputMags[0]) < 1e-4, "Hop 0 output should be zero, got \(outputMags[0])")
#expect(abs(outputMags[1]) < 1e-4, "Hop 1 output should be zero, got \(outputMags[1])")
// Hops 2 and 3: should equal inputs 0 and 1.
#expect(abs(outputMags[2] - inputMags[0]) < 1e-3,
"Hop 2 output should equal input 0, got \(outputMags[2]) vs \(inputMags[0])")
#expect(abs(outputMags[3] - inputMags[1]) < 1e-3,
"Hop 3 output should equal input 1, got \(outputMags[3]) vs \(inputMags[1])")
}
/// Bins with `delayTimes == 0` and `feedbacks == 0` are not affected by
/// other bins' settings.
@Test func untouchedBinsArePassThrough() {
let fftSize: Int = 64
let halfSize: Int = fftSize / 2
let testBin: Int = 7
let otherBin: Int = 11
let delays: LyrebirdBuffer = LyrebirdBuffer(count: halfSize)
delays.fill(with: 0.0)
delays.setValue(0.001, at: otherBin) // some delay on a different bin
let feedbacks: LyrebirdBuffer = LyrebirdBuffer(count: halfSize)
feedbacks.fill(with: 0.0)
feedbacks.setValue(0.5, at: otherBin)
let bd: SpectralBinDelay = SpectralBinDelay(
fftSize: fftSize,
hopSize: 16,
maxDelaySeconds: 0.05,
sampleRate: 44_100,
delayTimes: delays,
feedbacks: feedbacks
)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
buf[magnitude: testBin] = 0.5
buf[phase: testBin] = 0
bd.process(spectral: buf, engine: makeTestEngine())
#expect(abs(buf[magnitude: testBin] - 0.5) < 1e-4,
"Untouched bin should pass through")
}
/// With a non-zero feedback gain and a fixed N-hop delay, repeatedly
/// driving the same input magnitude should produce a delayed output that
/// builds up over time as the head slot accumulates the attenuated
/// delayed bin on each hop.
@Test func feedbackAccumulatesEnergy() {
let fftSize: Int = 64
let halfSize: Int = fftSize / 2
let hopSize: Int = 16
let sampleRate: Double = 44_100.0
let testBin: Int = 5
let delayHops: Int = 1
let delaySeconds: Double = Double(delayHops) * Double(hopSize) / sampleRate
let feedback: Double = 0.7
let delays: LyrebirdBuffer = LyrebirdBuffer(count: halfSize)
delays.fill(with: 0.0)
delays.setValue(delaySeconds, at: testBin)
let feedbacks: LyrebirdBuffer = LyrebirdBuffer(count: halfSize)
feedbacks.fill(with: 0.0)
feedbacks.setValue(feedback, at: testBin)
let bd: SpectralBinDelay = SpectralBinDelay(
fftSize: fftSize,
hopSize: hopSize,
maxDelaySeconds: 0.05,
sampleRate: sampleRate,
delayTimes: delays,
feedbacks: feedbacks
)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
// Steady input magnitude, run several hops; inspect the magnitude at the
// delayed output. With feedback > 0, head slot accumulates attenuated
// history each hop, so the delayed read at hop t should grow as t grows
// (until it asymptotes near `input / (1 - feedback)`).
let inputMag: Float = 1.0
var outputs: [Float] = []
for _ in 0..<8 {
buf[magnitude: testBin] = inputMag
buf[phase: testBin] = 0
bd.process(spectral: buf, engine: makeTestEngine())
outputs.append(buf[magnitude: testBin])
}
// First hop reads zero ring slot — output is zero.
#expect(outputs[0] < inputMag,
"First-hop output should be below input (ring not yet populated), got \(outputs[0])")
// Later hops should exceed `inputMag` as feedback accumulates the
// delayed magnitude into the head slot before the next read.
let lateMax: Float = outputs[3...].max() ?? 0
let msg: String = "Feedback should accumulate magnitude past inputMag (\(inputMag)) over multiple hops, got max \(lateMax) in outputs \(outputs)"
#expect(lateMax > inputMag, "\(msg)")
}
/// Live `LyrebirdBuffer.setValue` calls between hops are picked up by the
/// processor on the next hop.
@Test func liveDelayUpdate() {
let fftSize: Int = 64
let halfSize: Int = fftSize / 2
let testBin: Int = 3
let delays: LyrebirdBuffer = LyrebirdBuffer(count: halfSize)
delays.fill(with: 0.0)
let feedbacks: LyrebirdBuffer = LyrebirdBuffer(count: halfSize)
feedbacks.fill(with: 0.0)
let bd: SpectralBinDelay = SpectralBinDelay(
fftSize: fftSize,
hopSize: 16,
maxDelaySeconds: 0.05,
sampleRate: 44_100,
delayTimes: delays,
feedbacks: feedbacks
)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
// First two hops with delay 0 — pass-through.
buf[magnitude: testBin] = 0.4
buf[phase: testBin] = 0
bd.process(spectral: buf, engine: makeTestEngine())
let firstOutput: Float = buf[magnitude: testBin]
#expect(abs(firstOutput - 0.4) < 1e-4)
// Update the delay buffer between hops — must not crash and must take
// effect on the next hop. We can't easily measure the delayed sample
// exactly without orchestrating the ring; just assert that the process
// call after a live update returns a finite value and does not trap.
delays.setValue(0.001, at: testBin)
buf[magnitude: testBin] = 0.6
buf[phase: testBin] = 0
bd.process(spectral: buf, engine: makeTestEngine())
#expect(buf[magnitude: testBin].isFinite,
"Output after live update must be finite, got \(buf[magnitude: testBin])")
}
}
@@ -0,0 +1,137 @@
// SpectralBlurTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpectralBlur")
struct SpectralBlurTests {
@Test func radiusZeroIsBypass() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let halfSize: Int = fftSize / 2
for k: Int in 1..<halfSize {
buf[magnitude: k] = Float(k)
buf[phase: k] = 0.6
}
let b: SpectralBlur = SpectralBlur(fftSize: fftSize, radius: 0)
b.process(spectral: buf, engine: makeTestEngine())
for k: Int in 1..<halfSize {
#expect(buf[magnitude: k] == Float(k), "bin \(k) altered with r=0")
}
}
@Test func deltaPeakSmearsToPlateau() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let halfSize: Int = fftSize / 2
// Single delta at bin 16.
let peakBin: Int = 16
for k: Int in 1..<halfSize { buf[magnitude: k] = 0 }
buf[magnitude: peakBin] = 1.0
let r: Int = 3
let b: SpectralBlur = SpectralBlur(fftSize: fftSize, radius: r)
b.process(spectral: buf, engine: makeTestEngine())
// The window of width 2r+1 = 7 around bin 16 should be a plateau of
// (1.0 / 7) ≈ 0.142857 — but the delta lives in only the centre bin,
// so each output i in [13, 19] sees the delta within its window:
// averaged value = 1 / (2r + 1) at the centre, but at edges the window
// shrinks: e.g. bin 13 has window [10, 16] = 7 bins, still includes the
// delta. Bin 19 has window [16, 22] = 7 bins, also includes delta.
// Bin 20 has window [17, 23] = 7 bins, no delta.
let expected: Float = 1.0 / 7.0
for k: Int in (peakBin - r)...(peakBin + r) {
#expect(abs(buf[magnitude: k] - expected) < 1e-5,
"bin \(k) plateau value \(buf[magnitude: k]) ≠ \(expected)")
}
for k: Int in 1..<(peakBin - r) {
#expect(buf[magnitude: k] == 0,
"bin \(k) outside window should be 0, got \(buf[magnitude: k])")
}
for k: Int in (peakBin + r + 1)..<halfSize {
#expect(buf[magnitude: k] == 0,
"bin \(k) outside window should be 0, got \(buf[magnitude: k])")
}
}
@Test func edgeBinsShrinkWindow() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let halfSize: Int = fftSize / 2
// Constant magnitude 1.0 on every bin (plus edge).
for k: Int in 1..<halfSize { buf[magnitude: k] = 1.0 }
let b: SpectralBlur = SpectralBlur(fftSize: fftSize, radius: 5)
b.process(spectral: buf, engine: makeTestEngine())
// Average of constant 1.0 is still 1.0 at every output, even at edges,
// because window shrinks but values are uniform.
for k: Int in 1..<halfSize {
#expect(abs(buf[magnitude: k] - 1.0) < 1e-5)
}
}
@Test func phaseUntouched() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let halfSize: Int = fftSize / 2
for k: Int in 1..<halfSize {
buf[magnitude: k] = Float(k)
buf[phase: k] = 0.6
}
let b: SpectralBlur = SpectralBlur(fftSize: fftSize, radius: 4)
b.process(spectral: buf, engine: makeTestEngine())
for k: Int in 1..<halfSize {
#expect(buf[phase: k] == 0.6, "phase on bin \(k) altered")
}
}
@Test func liveRadiusUpdate() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let halfSize: Int = fftSize / 2
for k: Int in 1..<halfSize { buf[magnitude: k] = 0 }
buf[magnitude: 10] = 1.0
let b: SpectralBlur = SpectralBlur(fftSize: fftSize, radius: 0)
b.process(spectral: buf, engine: makeTestEngine())
#expect(buf[magnitude: 10] == 1.0, "radius=0 should bypass")
// Restore peak (was preserved), set new radius.
b.radius = 2
b.process(spectral: buf, engine: makeTestEngine())
// Now smeared.
#expect(abs(buf[magnitude: 10] - 1.0 / 5.0) < 1e-5)
}
@Test func radiusClampedToHalfSizeOver2() {
let fftSize: Int = 64
// halfSize = 32, max radius = 16.
let b: SpectralBlur = SpectralBlur(fftSize: fftSize, radius: 999)
#expect(b.radius == 16)
}
@Test func invalidBufferIsBypassed() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
for k: Int in 1..<(fftSize / 2) { buf[magnitude: k] = 0 }
buf[magnitude: 10] = 1.0
buf.invalidate()
let b: SpectralBlur = SpectralBlur(fftSize: fftSize, radius: 4)
b.process(spectral: buf, engine: makeTestEngine())
#expect(buf[magnitude: 10] == 1.0)
}
}
@@ -0,0 +1,286 @@
// SpectralBrickwallTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpectralBrickwall")
struct SpectralBrickwallTests {
private static let sampleRate: Double = 48_000
// MARK: - Helpers
/// Fill every bin (DC, complex, Nyquist) with magnitude `1.0`.
private static func fillAllBins(_ buf: SpectralBuffer) {
buf.dcValue = 1.0
buf.nyquistValue = 1.0
let halfSize: Int = buf.fftSize / 2
for k: Int in 1..<halfSize {
buf[magnitude: k] = 1.0
buf[phase: k] = 0.5 // arbitrary non-zero phase
}
}
/// Convert Hz → nearest bin (matches binFromHz behaviour).
private static func binAt(_ hz: Double, fftSize: Int) -> Int {
let halfSize: Int = fftSize / 2
let f: Double = hz * Double(fftSize) / sampleRate
if f <= 0 { return 0 }
if f >= Double(halfSize) { return halfSize }
return Int(f.rounded())
}
// MARK: - .lp
@Test func lpZeroesAboveCutoffPreservesBelow() {
let fftSize: Int = 64
let cutoffHz: Double = 6_000 // bin 8 at SR 48k, fft 64 (8 * 750 = 6000)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillAllBins(buf)
let f: SpectralBrickwall = SpectralBrickwall(
fftSize: fftSize,
sampleRate: Self.sampleRate,
mode: .lp,
highHz: cutoffHz
)
f.process(spectral: buf, engine: makeTestEngine())
let cutoffBin: Int = Self.binAt(cutoffHz, fftSize: fftSize)
let halfSize: Int = fftSize / 2
// Below + at cutoff preserved.
#expect(buf.dcValue == 1.0)
for k: Int in 1...cutoffBin {
if k < halfSize {
#expect(buf[magnitude: k] == 1.0, "bin \(k) should be preserved")
}
}
// Above cutoff zeroed (complex bins).
for k: Int in (cutoffBin + 1)..<halfSize {
#expect(buf[magnitude: k] == 0.0, "bin \(k) should be zeroed")
}
// Nyquist zeroed (above cutoff).
#expect(buf.nyquistValue == 0.0)
// Phase preserved on a passing bin.
if cutoffBin >= 1 && cutoffBin < halfSize {
#expect(buf[phase: cutoffBin] == 0.5, "phase should be untouched")
}
}
// MARK: - .hp
@Test func hpZeroesBelowCutoffPreservesAbove() {
let fftSize: Int = 64
let cutoffHz: Double = 6_000 // bin 8
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillAllBins(buf)
let f: SpectralBrickwall = SpectralBrickwall(
fftSize: fftSize,
sampleRate: Self.sampleRate,
mode: .hp,
lowHz: cutoffHz
)
f.process(spectral: buf, engine: makeTestEngine())
let cutoffBin: Int = Self.binAt(cutoffHz, fftSize: fftSize)
let halfSize: Int = fftSize / 2
// DC zeroed (below cutoff).
#expect(buf.dcValue == 0.0)
// Below cutoff zeroed.
for k: Int in 1..<cutoffBin {
#expect(buf[magnitude: k] == 0.0, "bin \(k) should be zeroed")
}
// At + above cutoff preserved.
for k: Int in cutoffBin..<halfSize {
if k >= 1 {
#expect(buf[magnitude: k] == 1.0, "bin \(k) should be preserved")
}
}
#expect(buf.nyquistValue == 1.0)
}
// MARK: - .bp
@Test func bpKeepsBandZeroesEnds() {
let fftSize: Int = 128
let lowHz: Double = 3_000 // bin 8
let highHz: Double = 9_000 // bin 24
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillAllBins(buf)
let f: SpectralBrickwall = SpectralBrickwall(
fftSize: fftSize,
sampleRate: Self.sampleRate,
mode: .bp,
lowHz: lowHz,
highHz: highHz
)
f.process(spectral: buf, engine: makeTestEngine())
let bLow: Int = Self.binAt(lowHz, fftSize: fftSize)
let bHigh: Int = Self.binAt(highHz, fftSize: fftSize)
let halfSize: Int = fftSize / 2
#expect(buf.dcValue == 0.0)
for k: Int in 1..<bLow {
#expect(buf[magnitude: k] == 0.0)
}
for k: Int in bLow...bHigh {
#expect(buf[magnitude: k] == 1.0)
}
for k: Int in (bHigh + 1)..<halfSize {
#expect(buf[magnitude: k] == 0.0)
}
#expect(buf.nyquistValue == 0.0)
}
// MARK: - .br
@Test func brZeroesBandKeepsEnds() {
let fftSize: Int = 128
let lowHz: Double = 3_000
let highHz: Double = 9_000
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillAllBins(buf)
let f: SpectralBrickwall = SpectralBrickwall(
fftSize: fftSize,
sampleRate: Self.sampleRate,
mode: .br,
lowHz: lowHz,
highHz: highHz
)
f.process(spectral: buf, engine: makeTestEngine())
let bLow: Int = Self.binAt(lowHz, fftSize: fftSize)
let bHigh: Int = Self.binAt(highHz, fftSize: fftSize)
let halfSize: Int = fftSize / 2
#expect(buf.dcValue == 1.0)
for k: Int in 1..<bLow {
#expect(buf[magnitude: k] == 1.0)
}
for k: Int in bLow...bHigh {
if k >= 1 && k < halfSize {
#expect(buf[magnitude: k] == 0.0)
}
}
for k: Int in (bHigh + 1)..<halfSize {
#expect(buf[magnitude: k] == 1.0)
}
#expect(buf.nyquistValue == 1.0)
}
// MARK: - DC + Nyquist edge cases
@Test func lpAtDCZerosEverythingExceptDC() {
let fftSize: Int = 32
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillAllBins(buf)
let f: SpectralBrickwall = SpectralBrickwall(
fftSize: fftSize,
sampleRate: Self.sampleRate,
mode: .lp,
highHz: 0
)
f.process(spectral: buf, engine: makeTestEngine())
#expect(buf.dcValue == 1.0)
#expect(buf.nyquistValue == 0.0)
for k: Int in 1..<(fftSize / 2) {
#expect(buf[magnitude: k] == 0.0)
}
}
@Test func hpAboveNyquistZerosEverything() {
let fftSize: Int = 32
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillAllBins(buf)
// lowHz at sample rate (well above Nyquist) clamps to halfSize.
let f: SpectralBrickwall = SpectralBrickwall(
fftSize: fftSize,
sampleRate: Self.sampleRate,
mode: .hp,
lowHz: Self.sampleRate
)
f.process(spectral: buf, engine: makeTestEngine())
#expect(buf.dcValue == 0.0)
for k: Int in 1..<(fftSize / 2) {
#expect(buf[magnitude: k] == 0.0)
}
// Nyquist preserved (lowHz clamps to halfSize, so cutoffBin == halfSize, kept).
#expect(buf.nyquistValue == 1.0)
}
// MARK: - Live cutoff update
@Test func liveLowHzUpdateAffectsNextHop() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillAllBins(buf)
let f: SpectralBrickwall = SpectralBrickwall(
fftSize: fftSize,
sampleRate: Self.sampleRate,
mode: .hp,
lowHz: 0
)
// First process: lowHz=0, no zeroing.
f.process(spectral: buf, engine: makeTestEngine())
#expect(buf[magnitude: 5] == 1.0)
// Update cutoff and reprocess.
f.lowHz = 12_000 // bin 16 at SR 48k, fft 64
f.process(spectral: buf, engine: makeTestEngine())
#expect(buf[magnitude: 5] == 0.0)
}
// MARK: - Phase untouched
@Test func phaseLeftUnchangedAcrossModes() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillAllBins(buf)
let halfSize: Int = fftSize / 2
let f: SpectralBrickwall = SpectralBrickwall(
fftSize: fftSize,
sampleRate: Self.sampleRate,
mode: .bp,
lowHz: 3_000,
highHz: 9_000
)
f.process(spectral: buf, engine: makeTestEngine())
for k: Int in 1..<halfSize {
#expect(buf[phase: k] == 0.5, "phase on bin \(k) should be untouched, got \(buf[phase: k])")
}
}
// MARK: - Invalid buffer
@Test func invalidBufferIsBypassed() {
let fftSize: Int = 32
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillAllBins(buf)
buf.invalidate()
let f: SpectralBrickwall = SpectralBrickwall(
fftSize: fftSize,
sampleRate: Self.sampleRate,
mode: .lp,
highHz: 0
)
f.process(spectral: buf, engine: makeTestEngine())
// Buffer was filled then invalidated; processor should not have zeroed bins.
#expect(buf[magnitude: 5] == 1.0)
}
}
@@ -0,0 +1,360 @@
// SpectralChainTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpectralChain.Audio — basic shape") struct SpectralChainBasicTests {
@Test func rateIsAudio() {
let chain: SpectralChain.Audio = SpectralChain.Audio(input: Double(0.0), fftSize: 64, hopSize: 32)
#expect(chain.rate == .audio)
}
@Test func defaultOutputIsMono() {
let chain: SpectralChain.Audio = SpectralChain.Audio(input: Double(0.0), fftSize: 64, hopSize: 32)
#expect(chain.outputChannelCount == 1)
}
@Test func fanOutControlsChannelCount() {
let diffuser: SpectralStereoDiffuse = SpectralStereoDiffuse(amount: 0.5, seed: 1)
let chain: SpectralChain.Audio = SpectralChain.Audio(
input: Double(0.0),
fftSize: 64, hopSize: 32,
fanOut: diffuser
)
#expect(chain.outputChannelCount == 2)
}
@Test func analyzeOnlyForcesMono() {
let chain: SpectralChain.Audio = SpectralChain.Audio(
input: Double(0.0),
fftSize: 64, hopSize: 32,
analyzeOnly: true
)
#expect(chain.outputChannelCount == 1)
}
}
@MainActor
@Suite("SpectralChain.Audio — analysis hop") struct SpectralChainAnalysisHopTests {
@Test func dcBinDominatesForConstantInput() 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() }
let chain: SpectralChain.Audio = SpectralChain.Audio(
input: Double(1.0),
fftSize: fftSize, hopSize: hopSize
)
// Run 4 blocks to reach steady state (ring fully filled with DC).
for _ in 0..<4 {
let g: SynthGraph = makeSynthGraph(engine: engine)
_ = chain.calculatedSamples(graph: g, count: blockSize)
advanceBlock(engine)
}
let dcMag: Float = chain.spectralBuffer.magnitude(at: 0)
#expect(dcMag > 0, "DC magnitude must be positive for constant input")
let halfSize: Int = fftSize / 2
for bin: Int in 1..<halfSize {
let binMag: Float = chain.spectralBuffer.magnitude(at: bin)
#expect(dcMag > binMag,
"DC magnitude \(dcMag) should exceed bin \(bin) magnitude \(binMag)")
}
}
@Test func analyzeOnlyOutputIsSilence() throws {
let blockSize: Int = 32
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
defer { engine.stop() }
let graph: SynthGraph = makeSynthGraph(engine: engine)
let chain: SpectralChain.Audio = SpectralChain.Audio(
input: Double(1.0),
fftSize: 64, hopSize: 32,
analyzeOnly: true
)
let out: [[Double]] = chain.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
#expect(out[0][i] == 0.0, "analyzeOnly chain should output silence")
}
}
@Test func processorsCalledInOrder() throws {
final class TaggingProcessor: SpectralProcessor {
let id: Int
let log: TagLog
init(id: Int, log: TagLog) { self.id = id; self.log = log }
func process(spectral: SpectralBuffer, engine: SynthesisEngine) { log.append(id) }
}
final class TagLog { var ids: [Int] = []; func append(_ id: Int) { ids.append(id) } }
let fftSize: Int = 64
let hopSize: Int = 32
let blockSize: Int = hopSize
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
defer { engine.stop() }
let log: TagLog = TagLog()
let chain: SpectralChain.Audio = SpectralChain.Audio(
input: Double(1.0),
fftSize: fftSize, hopSize: hopSize,
stages: [
.mono(TaggingProcessor(id: 1, log: log)),
.mono(TaggingProcessor(id: 2, log: log)),
.mono(TaggingProcessor(id: 3, log: log)),
]
)
let g: SynthGraph = makeSynthGraph(engine: engine)
_ = chain.calculatedSamples(graph: g, count: blockSize)
#expect(log.ids == [1, 2, 3])
}
@Test func sideChainProcessorReceivesBothBuffers() throws {
final class CrossProcessor: SpectralProcessor2 {
var seen: (Int, Int)?
func process(spectral: SpectralBuffer,
sideChain: SpectralBuffer, engine: SynthesisEngine) {
seen = (spectral.fftSize, sideChain.fftSize)
}
}
let fftSize: Int = 64
let hopSize: Int = 32
let blockSize: Int = hopSize
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
defer { engine.stop() }
let sideChain: SpectralChain.Audio = SpectralChain.Audio(
input: Double(0.5),
fftSize: fftSize, hopSize: hopSize,
analyzeOnly: true
)
let cross: CrossProcessor = CrossProcessor()
let chain: SpectralChain.Audio = SpectralChain.Audio(
input: Double(1.0),
fftSize: fftSize, hopSize: hopSize,
stages: [.dual(cross, sideChain: sideChain)]
)
let g: SynthGraph = makeSynthGraph(engine: engine)
_ = chain.calculatedSamples(graph: g, count: blockSize)
#expect(cross.seen != nil)
#expect(cross.seen?.0 == fftSize)
#expect(cross.seen?.1 == fftSize)
}
@Test func mixedMonoDualStagesDispatchInInsertionOrder() throws {
// The new `stages` slot lets `.mono` and `.dual` interleave. The prior
// two-array layout fixed the order to "all monos first, then all duals";
// this test pins the new contract that order is whatever the user passed.
final class TagLog { var ids: [String] = []; func append(_ id: String) { ids.append(id) } }
final class TaggingMono: SpectralProcessor {
let id: String
let log: TagLog
init(id: String, log: TagLog) { self.id = id; self.log = log }
func process(spectral: SpectralBuffer, engine: SynthesisEngine) { log.append(id) }
}
final class TaggingDual: SpectralProcessor2 {
let id: String
let log: TagLog
init(id: String, log: TagLog) { self.id = id; self.log = log }
func process(spectral: SpectralBuffer,
sideChain: SpectralBuffer, engine: SynthesisEngine) {
log.append(id)
}
}
let fftSize: Int = 64
let hopSize: Int = 32
let blockSize: Int = hopSize
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
defer { engine.stop() }
let log: TagLog = TagLog()
let sideChain: SpectralChain.Audio = SpectralChain.Audio(
input: Double(0.5),
fftSize: fftSize, hopSize: hopSize,
analyzeOnly: true
)
let chain: SpectralChain.Audio = SpectralChain.Audio(
input: Double(1.0),
fftSize: fftSize, hopSize: hopSize,
stages: [
.mono(TaggingMono(id: "a", log: log)),
.dual(TaggingDual(id: "b", log: log), sideChain: sideChain),
.mono(TaggingMono(id: "c", log: log)),
.dual(TaggingDual(id: "d", log: log), sideChain: sideChain),
]
)
let g: SynthGraph = makeSynthGraph(engine: engine)
_ = chain.calculatedSamples(graph: g, count: blockSize)
#expect(log.ids == ["a", "b", "c", "d"])
}
}
@MainActor
@Suite("SpectralChain.Audio — resynthesis") struct SpectralChainResynthesisTests {
@Test func monoResynthesisReachesUnityGainForDC() throws {
// Constant DC input through the consolidated chain: after WOLA
// warmup the resynthesised output should match the input within
// round-trip float tolerance.
let fftSize: Int = 64
let hopSize: Int = 32
let blockSize: Int = hopSize
let dcInput: Double = 0.3
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
defer { engine.stop() }
let chain: SpectralChain.Audio = SpectralChain.Audio(input: dcInput,
fftSize: fftSize, hopSize: hopSize)
let warmUpBlocks: Int = 4
let measureBlocks: Int = 4
var sum: Double = 0
var n: Int = 0
for block: Int in 0..<(warmUpBlocks + measureBlocks) {
let g: SynthGraph = makeSynthGraph(engine: engine)
let out: [[Double]] = chain.calculatedSamples(graph: g, count: blockSize)
if block >= warmUpBlocks {
for i: Int in 0..<blockSize { sum += out[0][i]; n += 1 }
}
advanceBlock(engine)
}
let mean: Double = sum / Double(n)
#expect(abs(mean - dcInput) < 0.05,
"Round-trip DC mean \(mean) should be ≈ \(dcInput)")
}
@Test func fanOutProducesNRows() throws {
let fftSize: Int = 64
let hopSize: Int = 32
let blockSize: Int = hopSize
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
defer { engine.stop() }
let diffuser: SpectralStereoDiffuse = SpectralStereoDiffuse(amount: 0.0, seed: 42)
let chain: SpectralChain.Audio = SpectralChain.Audio(
input: Double(0.3),
fftSize: fftSize, hopSize: hopSize,
fanOut: diffuser
)
let g: SynthGraph = makeSynthGraph(engine: engine)
let out: [[Double]] = chain.calculatedSamples(graph: g, count: blockSize)
#expect(out.count == 2)
#expect(out[0].count >= blockSize)
#expect(out[1].count >= blockSize)
}
}
@MainActor
@Suite("SpectralChain.Audio — synthOnly mode") struct SpectralChainSynthOnlyTests {
/// Build a frame buffer with a constant non-zero DC magnitude on every
/// frame so playback through synthOnly produces a non-silent signal.
private func makeDCFrameBuffer(fftSize: Int, hopSize: Int, frames: Int)
-> SpectralFrameBuffer
{
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: fftSize, hopSize: hopSize,
frameCount: frames, sampleRate: 48_000)
let scratch: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
scratch.dcValue = 100.0 // strong DC tone
for f: Int in 0..<frames {
fb.writeFrame(from: scratch, at: f)
}
return fb
}
@Test func synthOnlyResynthesisProducesNonZeroAudio() throws {
let fftSize: Int = 64
let hopSize: Int = 32
let blockSize: Int = hopSize
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
defer { engine.stop() }
let frames: SpectralFrameBuffer = makeDCFrameBuffer(fftSize: fftSize, hopSize: hopSize, frames: 64)
let player: SpectralPlayBuffer = SpectralPlayBuffer(frameBuffer: frames,
fftSize: fftSize, hopSize: hopSize,
rate: 1.0, loop: true)
let chain: SpectralChain.Audio = SpectralChain.Audio(spectralSource: player,
fftSize: fftSize, hopSize: hopSize)
// Warm up so the IFFT bank's one-hop latency clears.
var anyNonZero: Bool = false
for _ in 0..<8 {
let g: SynthGraph = makeSynthGraph(engine: engine)
let out: [[Double]] = chain.calculatedSamples(graph: g, count: blockSize)
for s: Double in out[0].prefix(blockSize) where s != 0 {
anyNonZero = true
break
}
advanceBlock(engine)
}
#expect(anyNonZero,
"SpectralChain.Audio(spectralSource:) should produce non-zero audio for a constant-DC frame buffer")
}
/// Confirm that registered single-input processors run on the aliased
/// source spectralBuffer in synthOnly mode.
private final class CountingProcessor: SpectralProcessor {
var callCount: Int = 0
var lastSeenDC: Float = 0
func process(spectral: SpectralBuffer, engine: SynthesisEngine) {
callCount += 1
lastSeenDC = spectral.dcValue
}
}
@Test func synthOnlyDispatchesProcessorsOnAliasedBuffer() throws {
let fftSize: Int = 64
let hopSize: Int = 32
let blockSize: Int = hopSize
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
defer { engine.stop() }
let frames: SpectralFrameBuffer = makeDCFrameBuffer(fftSize: fftSize, hopSize: hopSize, frames: 64)
let player: SpectralPlayBuffer = SpectralPlayBuffer(frameBuffer: frames,
fftSize: fftSize, hopSize: hopSize,
rate: 1.0, loop: true)
let counter: SpectralChainSynthOnlyTests.CountingProcessor = CountingProcessor()
let chain: SpectralChain.Audio = SpectralChain.Audio(spectralSource: player,
fftSize: fftSize, hopSize: hopSize,
stages: [.mono(counter)])
for _ in 0..<8 {
let g: SynthGraph = makeSynthGraph(engine: engine)
_ = chain.calculatedSamples(graph: g, count: blockSize)
advanceBlock(engine)
}
#expect(counter.callCount > 0,
"Processor must be dispatched on the aliased source spectralBuffer")
#expect(counter.lastSeenDC == 100.0,
"Processor should see the DC the source wrote into the shared buffer")
#expect(chain.spectralBuffer === player.spectralBuffer,
"SynthOnly chain.spectralBuffer must alias spectralSource.spectralBuffer")
}
}
@@ -0,0 +1,415 @@
// SpectralComplexClosureTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpectralComplexClosure")
struct SpectralComplexClosureTests {
// MARK: - Helpers
private static func fillKnownPolar(_ buf: SpectralBuffer) {
buf.dcValue = 0.5
buf.nyquistValue = -0.25
let halfSize: Int = buf.fftSize / 2
for k: Int in 1..<halfSize {
buf[magnitude: k] = Float(k) * 0.01
buf[phase: k] = 0.3
}
}
// MARK: - Basic structural tests
@Test func identityClosureDoesNotMutate() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillKnownPolar(buf)
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { _ in }
proc.process(spectral: buf, engine: makeTestEngine())
// After a no-op closure, the round-trip (polar→complex→polar) should
// reproduce magnitudes and phases within Float trigonometric error (~1e-6).
let halfSize: Int = fftSize / 2
for k: Int in 1..<halfSize {
let expectedMag: Float = Float(k) * 0.01
#expect(abs(buf[magnitude: k] - expectedMag) < 1e-4,
"magnitude of bin \(k) drifted after identity: \(buf[magnitude: k]) vs \(expectedMag)")
#expect(abs(buf[phase: k] - 0.3) < 1e-4,
"phase of bin \(k) drifted after identity: \(buf[phase: k])")
}
// DC and Nyquist pass through as-is.
#expect(abs(buf.dcValue - 0.5) < 1e-6)
#expect(abs(buf.nyquistValue - (-0.25)) < 1e-6)
}
@Test func closureReceivesCorrectBinCount() {
let fftSize: Int = 128
var observedBinCount: Int = 0
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 64, sampleRate: 44100
) { ctx in
observedBinCount = ctx.binCount
}
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
proc.process(spectral: buf, engine: makeTestEngine())
// binCount = fftSize/2 (includes packed DC[0] and Nyquist imag[0])
#expect(observedBinCount == fftSize / 2)
}
@Test func closureReceivesCorrectMetadata() {
let fftSize: Int = 256
let hopSize: Int = 64
let sampleRate: Double = 48000.0
var seenFFTSize: Int = 0
var seenHopSize: Int = 0
var seenSampleRate: Double = 0.0
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: hopSize, sampleRate: sampleRate
) { ctx in
seenFFTSize = ctx.fftSize
seenHopSize = ctx.hopSize
seenSampleRate = ctx.sampleRate
}
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
proc.process(spectral: buf, engine: makeTestEngine())
#expect(seenFFTSize == fftSize)
#expect(seenHopSize == hopSize)
#expect(seenSampleRate == sampleRate)
}
// MARK: - Split-complex layout
@Test func dcPackedAtRealIndex0() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
buf.dcValue = 7.0
var observedDC: Float = 0
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
observedDC = ctx.real[0]
}
proc.process(spectral: buf, engine: makeTestEngine())
#expect(abs(observedDC - 7.0) < 1e-6,
"DC should be packed at real[0], got \(observedDC)")
}
@Test func nyquistPackedAtImagIndex0() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
buf.nyquistValue = -3.0
var observedNyquist: Float = 0
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
observedNyquist = ctx.imag[0]
}
proc.process(spectral: buf, engine: makeTestEngine())
#expect(abs(observedNyquist - (-3.0)) < 1e-6,
"Nyquist should be packed at imag[0], got \(observedNyquist)")
}
@Test func zeroBinHasZeroCartesian() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let halfSize: Int = fftSize / 2
// All bins zeroed.
buf.dcValue = 0
buf.nyquistValue = 0
for k: Int in 1..<halfSize {
buf[magnitude: k] = 0
buf[phase: k] = 0
}
var anyNonZero: Bool = false
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
for i: Int in 0..<ctx.binCount {
if abs(ctx.real[i]) > 1e-6 || abs(ctx.imag[i]) > 1e-6 {
anyNonZero = true
}
}
}
proc.process(spectral: buf, engine: makeTestEngine())
#expect(!anyNonZero, "Zero-magnitude bins should yield zero Cartesian values")
}
// MARK: - Mutation round-trip
@Test func zeroClearsSingleBinInPolar() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let halfSize: Int = fftSize / 2
for k: Int in 1..<halfSize {
buf[magnitude: k] = 1.0
buf[phase: k] = 0.5
}
// Zero out bin 3 in Cartesian space (index 3 in real/imag maps to spectral bin 3).
let targetBin: Int = 3
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
ctx.real[targetBin] = 0
ctx.imag[targetBin] = 0
}
proc.process(spectral: buf, engine: makeTestEngine())
// After zeroing, magnitude of the target bin should be ≈ 0.
#expect(buf[magnitude: targetBin] < 1e-6,
"Zeroed Cartesian bin should have ≈ 0 magnitude, got \(buf[magnitude: targetBin])")
}
@Test func dcMutationWritesBackThroughPolar() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
buf.dcValue = 2.0
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
ctx.real[0] = 5.0
}
proc.process(spectral: buf, engine: makeTestEngine())
#expect(abs(buf.dcValue - 5.0) < 1e-6,
"DC write-back failed: \(buf.dcValue)")
}
@Test func nyquistMutationWritesBackThroughPolar() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
buf.nyquistValue = -1.0
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
ctx.imag[0] = 4.0
}
proc.process(spectral: buf, engine: makeTestEngine())
#expect(abs(buf.nyquistValue - 4.0) < 1e-6,
"Nyquist write-back failed: \(buf.nyquistValue)")
}
// MARK: - Frame index
@Test func frameIndexIncrementsAcrossHops() {
let fftSize: Int = 64
var observedIndices: [Int] = []
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
observedIndices.append(ctx.frameIndex)
}
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
for _ in 0..<5 {
proc.process(spectral: buf, engine: makeTestEngine())
}
#expect(observedIndices == [0, 1, 2, 3, 4])
}
// MARK: - Guard conditions
@Test func fftSizeMismatchIsBypassed() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: 128)
buf[magnitude: 1] = 99.0
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
for i: Int in 0..<ctx.binCount { ctx.real[i] = 0; ctx.imag[i] = 0 }
}
proc.process(spectral: buf, engine: makeTestEngine())
#expect(buf[magnitude: 1] == 99.0)
}
@Test func invalidBufferIsBypassed() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
buf[magnitude: 4] = 5.0
buf.invalidate()
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
for i: Int in 0..<ctx.binCount { ctx.real[i] = 0; ctx.imag[i] = 0 }
}
proc.process(spectral: buf, engine: makeTestEngine())
#expect(buf[magnitude: 4] == 5.0)
}
// MARK: - SpectralChain integration
/// Complex identity closure: round-trip through SpectralChain.Audio
/// should produce the same mean level as the no-processor path
/// within polar↔Cartesian round-trip tolerance.
@Test func identityClosureRoundTripEquivalentToNoProcessor() throws {
let fftSize: Int = 64
let hopSize: Int = 32
let blockSize: Int = hopSize
let dcInput: Double = 0.4
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
defer { engine.stop() }
let chainNone: SpectralChain.Audio = SpectralChain.Audio(input: dcInput, fftSize: fftSize, hopSize: hopSize)
let identity: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: hopSize, sampleRate: engine.sampleRate
) { _ in }
let chainIdentity: SpectralChain.Audio = SpectralChain.Audio(
input: dcInput, fftSize: fftSize, hopSize: hopSize, stages: [.mono(identity)]
)
let warmUpBlocks: Int = 4
let measureBlocks: Int = 4
var sumNone: Double = 0.0
var sumId: Double = 0.0
for block: Int in 0..<(warmUpBlocks + measureBlocks) {
let g: SynthGraph = makeSynthGraph(engine: engine)
let outNone: [[Double]] = chainNone.calculatedSamples(graph: g, count: blockSize)
let outId: [[Double]] = chainIdentity.calculatedSamples(graph: g, count: blockSize)
if block >= warmUpBlocks {
for i: Int in 0..<blockSize {
sumNone += outNone[0][i]
sumId += outId[0][i]
}
}
advanceBlock(engine)
}
let n: Double = Double(measureBlocks * blockSize)
let meanNone: Double = sumNone / n
let meanId: Double = sumId / n
// Both should have the same mean. Allow 0.01 for round-trip trig error.
#expect(abs(meanNone - meanId) < 0.01,
"Identity closure shifted mean from \(meanNone) to \(meanId)")
}
/// Complex all-zero closure: zeroing all Cartesian bins produces silence.
@Test func zeroClearAllBinsProducesSilence() throws {
let fftSize: Int = 64
let hopSize: Int = 32
let blockSize: Int = hopSize
let sineFreq: Double = 880.0
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
defer { engine.stop() }
let osc: OscSin.Audio = OscSin.Audio(freq: sineFreq)
let mute: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: hopSize, sampleRate: engine.sampleRate
) { ctx in
for i: Int in 0..<ctx.binCount {
ctx.real[i] = 0
ctx.imag[i] = 0
}
}
let chain: SpectralChain.Audio = SpectralChain.Audio(
input: osc, fftSize: fftSize, hopSize: hopSize, stages: [.mono(mute)]
)
let warmUpBlocks: Int = 4
let measureBlocks: Int = 4
var sumSq: Double = 0.0
for block: Int in 0..<(warmUpBlocks + measureBlocks) {
let g: SynthGraph = makeSynthGraph(engine: engine)
let out: [[Double]] = chain.calculatedSamples(graph: g, count: blockSize)
if block >= warmUpBlocks {
for i: Int in 0..<blockSize { let s: Double = out[0][i]; sumSq += s * s }
}
advanceBlock(engine)
}
let rms: Double = (sumSq / Double(measureBlocks * blockSize)).squareRoot()
// Spectral mute — all Cartesian bins zeroed. Output should be ≈ silence.
#expect(rms < 0.01, "Zeroed complex closure should produce near-silence, got RMS \(rms)")
}
/// Complex spectral freeze: latch real/imag arrays on the first hop
/// using pre-allocated scratch (RT-safe), then replay each subsequent hop.
/// After the input goes silent, the output should sustain the latched spectrum.
@Test func complexFreezeLatchesSpectrum() throws {
let fftSize: Int = 64
let hopSize: Int = 32
let blockSize: Int = hopSize
let sineFreq: Double = 440.0
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
defer { engine.stop() }
// Pre-allocate latch buffers (non-RT allocation).
let halfSize: Int = fftSize / 2
let latchReal: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
let latchImag: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
latchReal.initialize(repeating: 0, count: halfSize)
latchImag.initialize(repeating: 0, count: halfSize)
defer {
latchReal.deinitialize(count: halfSize)
latchReal.deallocate()
latchImag.deinitialize(count: halfSize)
latchImag.deallocate()
}
var latched: Bool = false
let freeze: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: hopSize, sampleRate: engine.sampleRate
) { ctx in
if !latched {
// Capture first frame into pre-allocated scratch.
for i: Int in 0..<ctx.binCount {
latchReal[i] = ctx.real[i]
latchImag[i] = ctx.imag[i]
}
latched = true
} else {
// Replay latched frame.
for i: Int in 0..<ctx.binCount {
ctx.real[i] = latchReal[i]
ctx.imag[i] = latchImag[i]
}
}
}
// Warm up: drive several blocks with the oscillator so the freeze
// latches a real non-silent spectrum.
let oscForFreeze: OscSin.Audio = OscSin.Audio(freq: sineFreq)
let chainFreeze: SpectralChain.Audio = SpectralChain.Audio(
input: oscForFreeze, fftSize: fftSize, hopSize: hopSize, stages: [.mono(freeze)]
)
let warmUpBlocks: Int = 4
for _ in 0..<warmUpBlocks {
let g: SynthGraph = makeSynthGraph(engine: engine)
_ = chainFreeze.calculatedSamples(graph: g, count: blockSize)
advanceBlock(engine)
}
// Measure RMS over several blocks — latched spectrum should be sustained.
let measureBlocks: Int = 4
var sumSq: Double = 0.0
for _ in 0..<measureBlocks {
let g: SynthGraph = makeSynthGraph(engine: engine)
let out: [[Double]] = chainFreeze.calculatedSamples(graph: g, count: blockSize)
for i: Int in 0..<blockSize { let s: Double = out[0][i]; sumSq += s * s }
advanceBlock(engine)
}
let rms: Double = (sumSq / Double(measureBlocks * blockSize)).squareRoot()
// Frozen spectrum should produce non-silence.
#expect(rms > 0.001, "Frozen complex spectrum produced near-silence (RMS \(rms)); expected sustained tone")
}
}
@@ -0,0 +1,105 @@
// SpectralConvolveTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpectralConvolve")
struct SpectralConvolveTests {
private static func angularDelta(_ a: Float, _ b: Float) -> Float {
let twoPi: Float = 2 * Float.pi
var d: Float = a - b
if d > Float.pi { d -= twoPi }
else if d < -Float.pi { d += twoPi }
return d
}
@Test func magnitudesMultiplyPhasesAddOnSingleBin() {
let fftSize: Int = 32
let live: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let other: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let halfSize: Int = fftSize / 2
for k: Int in 1..<halfSize {
live[magnitude: k] = 0
live[phase: k] = 0
other[magnitude: k] = 0
other[phase: k] = 0
}
let testBin: Int = 5
live[magnitude: testBin] = 2.0
live[phase: testBin] = 0.7
other[magnitude: testBin] = 3.0
other[phase: testBin] = 1.2
let c: SpectralConvolve = SpectralConvolve(spectralBuffer: live, other: other)
c.process(spectral: live, engine: makeTestEngine())
#expect(abs(live[magnitude: testBin] - 6.0) < 1e-5,
"mag product: \(live[magnitude: testBin]) ≠ 6.0")
let dPhase: Float = Self.angularDelta(live[phase: testBin], 1.9) // 0.7 + 1.2
#expect(abs(dPhase) < 1e-5,
"phase sum: residual \(dPhase)")
}
@Test func dcAndNyquistMultiplyAsSignedScalars() {
let fftSize: Int = 32
let live: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let other: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
live.dcValue = 2.0
live.nyquistValue = -1.0
other.dcValue = -3.0
other.nyquistValue = 4.0
let c: SpectralConvolve = SpectralConvolve(spectralBuffer: live, other: other)
c.process(spectral: live, engine: makeTestEngine())
#expect(live.dcValue == -6.0)
#expect(live.nyquistValue == -4.0)
}
@Test func zeroOtherProducesSilence() {
let fftSize: Int = 32
let live: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let other: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let halfSize: Int = fftSize / 2
for k: Int in 1..<halfSize {
live[magnitude: k] = Float(k)
live[phase: k] = 0.5
}
// other already initialised to all zeros.
let c: SpectralConvolve = SpectralConvolve(spectralBuffer: live, other: other)
c.process(spectral: live, engine: makeTestEngine())
for k: Int in 1..<halfSize {
#expect(live[magnitude: k] == 0.0, "bin \(k) not silenced")
}
}
@Test func eitherBufferInvalidClearsLive() {
let fftSize: Int = 32
let live: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let other: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let halfSize: Int = fftSize / 2
for k: Int in 1..<halfSize {
live[magnitude: k] = Float(k)
other[magnitude: k] = 1.0
}
live.dcValue = 5
live.nyquistValue = -3
let c: SpectralConvolve = SpectralConvolve(spectralBuffer: live, other: other)
other.invalidate()
c.process(spectral: live, engine: makeTestEngine())
#expect(live.dcValue == 0.0)
#expect(live.nyquistValue == 0.0)
for k: Int in 1..<halfSize {
#expect(live[magnitude: k] == 0.0)
}
}
}
@@ -0,0 +1,161 @@
// SpectralCrossMapTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpectralCrossMap")
struct SpectralCrossMapTests {
/// Identity template (uniform mags) at `mode = 1` with max-magnitude
/// normalisation produces a unit gain mask — main spectrum passes through.
@Test func uniformTemplatePassesThrough() {
let fftSize: Int = 64
let halfSize: Int = fftSize / 2
let main: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let side: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
for k: Int in 1..<halfSize {
main[magnitude: k] = Float(k) * 0.1
side[magnitude: k] = 0.5 // uniform — normalises to 1.0 across bins
}
let cm: SpectralCrossMap = SpectralCrossMap(fftSize: fftSize, normalization: .maxMagnitude, mode: 1.0)
cm.process(spectral: main, sideChain: side, engine: makeTestEngine())
for k: Int in 1..<halfSize {
let expected: Float = Float(k) * 0.1
#expect(abs(main[magnitude: k] - expected) < 1e-4,
"Bin \(k) should pass through (\(expected)), got \(main[magnitude: k])")
}
}
/// Sparse template (one bin loud, rest zero) at `mode = 1` keeps only that
/// bin. With `floor` between 0 and 1, all-zero template bins fall below floor
/// and get gain `1 - |mode| = 0`.
@Test func sparseTemplateBandpasses() {
let fftSize: Int = 64
let halfSize: Int = fftSize / 2
let templateBin: Int = 7
let main: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let side: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
for k: Int in 1..<halfSize {
main[magnitude: k] = 1.0
}
side[magnitude: templateBin] = 1.0
let cm: SpectralCrossMap = SpectralCrossMap(fftSize: fftSize,
normalization: .maxMagnitude,
floor: 0.5,
mode: 1.0)
cm.process(spectral: main, sideChain: side, engine: makeTestEngine())
// Template bin: normalised to 1.0 → above floor → gain = 1.0
#expect(abs(main[magnitude: templateBin] - 1.0) < 1e-4,
"Template bin should be preserved")
// Other bins: template = 0 → below floor → gain = 1 - |1| = 0
for k: Int in 1..<halfSize where k != templateBin {
#expect(abs(main[magnitude: k]) < 1e-4,
"Bin \(k) should be silenced, got \(main[magnitude: k])")
}
}
/// `mode = 0` produces a passthrough regardless of template content.
@Test func zeroModeIsPassThrough() {
let fftSize: Int = 64
let halfSize: Int = fftSize / 2
let main: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let side: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
for k: Int in 1..<halfSize {
main[magnitude: k] = 0.5
side[magnitude: k] = Float(k) * 0.05 // arbitrary template
}
let cm: SpectralCrossMap = SpectralCrossMap(fftSize: fftSize, mode: 0.0)
cm.process(spectral: main, sideChain: side, engine: makeTestEngine())
for k: Int in 1..<halfSize {
#expect(abs(main[magnitude: k] - 0.5) < 1e-4,
"mode=0 should pass bin \(k) through, got \(main[magnitude: k])")
}
}
/// Bandreject (`mode = -1`) with a uniform template silences everything
/// (gain = 1 - 1 = 0 for every bin above floor).
@Test func uniformTemplateBandRejectSilences() {
let fftSize: Int = 64
let halfSize: Int = fftSize / 2
let main: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let side: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
for k: Int in 1..<halfSize {
main[magnitude: k] = 1.0
side[magnitude: k] = 0.5
}
let cm: SpectralCrossMap = SpectralCrossMap(fftSize: fftSize, mode: -1.0)
cm.process(spectral: main, sideChain: side, engine: makeTestEngine())
for k: Int in 1..<halfSize {
#expect(abs(main[magnitude: k]) < 1e-4,
"Uniform template + mode=-1 should silence bin \(k)")
}
}
/// `freeze = true` ignores subsequent side-chain content — it reuses the
/// template captured on the previous (unfrozen) hop.
@Test func freezeHoldsTemplate() {
let fftSize: Int = 64
let halfSize: Int = fftSize / 2
let templateBin: Int = 9
let main: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let side: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let cm: SpectralCrossMap = SpectralCrossMap(fftSize: fftSize, floor: 0.5, mode: 1.0)
// Hop 1: capture sparse template at templateBin.
for k: Int in 1..<halfSize {
main[magnitude: k] = 1.0
}
side[magnitude: templateBin] = 1.0
cm.process(spectral: main, sideChain: side, engine: makeTestEngine())
// Now freeze and feed a totally different sidechain.
cm.freeze = true
for k: Int in 1..<halfSize {
main[magnitude: k] = 1.0
side[magnitude: k] = 0.5 // uniform — would change the mask if not frozen
}
cm.process(spectral: main, sideChain: side, engine: makeTestEngine())
// Frozen template still has only templateBin above floor.
#expect(abs(main[magnitude: templateBin] - 1.0) < 1e-4,
"Frozen template bin should still pass")
for k: Int in 1..<halfSize where k != templateBin {
#expect(abs(main[magnitude: k]) < 1e-4,
"Frozen non-template bin \(k) should still be silenced")
}
}
/// Live parameter setters round-trip via the public Double-typed API.
@Test func livePropertiesRoundTrip() {
let cm: SpectralCrossMap = SpectralCrossMap(fftSize: 64)
#expect(cm.freeze == false)
#expect(abs(cm.floor - 0.0) < 1e-5)
#expect(abs(cm.mode - 1.0) < 1e-5)
cm.freeze = true
cm.floor = 0.25
cm.mode = -0.75
#expect(cm.freeze == true)
#expect(abs(cm.floor - 0.25) < 1e-5)
#expect(abs(cm.mode - (-0.75)) < 1e-5)
}
}
@@ -0,0 +1,159 @@
// SpectralDiffuseTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpectralDiffuse")
struct SpectralDiffuseTests {
private static func angularDelta(_ a: Float, _ b: Float) -> Float {
let twoPi: Float = 2 * Float.pi
var d: Float = a - b
if d > Float.pi { d -= twoPi }
else if d < -Float.pi { d += twoPi }
return d
}
private static func fillBins(_ buf: SpectralBuffer, phase: Float = 0.4) {
let halfSize: Int = buf.fftSize / 2
for k: Int in 1..<halfSize {
buf[magnitude: k] = Float(k)
buf[phase: k] = phase
}
}
@Test func amountZeroIsBypass() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillBins(buf)
let halfSize: Int = fftSize / 2
let d: SpectralDiffuse = SpectralDiffuse(fftSize: fftSize, amount: 0, seed: 12345)
d.process(spectral: buf, engine: makeTestEngine())
for k: Int in 1..<halfSize {
#expect(buf[phase: k] == 0.4, "bin \(k) phase changed with amount=0")
}
}
@Test func magnitudeUntouched() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillBins(buf)
let halfSize: Int = fftSize / 2
let d: SpectralDiffuse = SpectralDiffuse(fftSize: fftSize, amount: 1, seed: 42)
d.process(spectral: buf, engine: makeTestEngine())
for k: Int in 1..<halfSize {
#expect(buf[magnitude: k] == Float(k), "bin \(k) magnitude altered")
}
}
@Test func amountOnePhaseDistributionRoughlyUniform() {
// With amount=1, output phases over many bins + many hops should
// approximately fill (-π, π] uniformly.
let fftSize: Int = 1024
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let halfSize: Int = fftSize / 2
for k: Int in 1..<halfSize { buf[magnitude: k] = 1 }
let d: SpectralDiffuse = SpectralDiffuse(fftSize: fftSize, amount: 1, seed: 99)
// Run several hops, collect a histogram of bin 100 phase across hops.
var bins: [Int] = [Int](repeating: 0, count: 8) // 8 angular buckets over (-π, π]
let twoPi: Float = 2 * Float.pi
let hops: Int = 4_000
for _ in 0..<hops {
d.process(spectral: buf, engine: makeTestEngine())
let p: Float = buf[phase: 100]
// Map p ∈ (-π, π] to [0, 8).
var u: Float = (p + Float.pi) / twoPi
if u >= 1 { u = 0.999_999 }
if u < 0 { u = 0 }
let idx: Int = min(7, max(0, Int(u * 8)))
bins[idx] += 1
}
// Each bucket should hold roughly hops/8 = 500. Tolerate ±50%.
for (i, c) in bins.enumerated() {
#expect(c > 200 && c < 800,
"bucket \(i) count \(c) outside expected range — distribution not uniform")
}
}
@Test func deterministicWithFixedSeed() {
let fftSize: Int = 64
let buf1: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let buf2: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillBins(buf1)
Self.fillBins(buf2)
let d1: SpectralDiffuse = SpectralDiffuse(fftSize: fftSize, amount: 0.7, seed: 0xABCDEF)
let d2: SpectralDiffuse = SpectralDiffuse(fftSize: fftSize, amount: 0.7, seed: 0xABCDEF)
d1.process(spectral: buf1, engine: makeTestEngine())
d2.process(spectral: buf2, engine: makeTestEngine())
let halfSize: Int = fftSize / 2
for k: Int in 1..<halfSize {
#expect(buf1[phase: k] == buf2[phase: k],
"deterministic seed mismatch on bin \(k)")
}
}
@Test func intermediateAmountMovesByFractionOfDelta() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillBins(buf)
let pre: Float = 0.4
let d: SpectralDiffuse = SpectralDiffuse(fftSize: fftSize, amount: 0.5, seed: 7)
d.process(spectral: buf, engine: makeTestEngine())
// For amount=0.5, every bin moved exactly half the angular distance to
// its drawn target. We can't predict the target, but |delta| should be
// ≤ π/2 (since full delta is ≤ π and we moved half).
let halfSize: Int = fftSize / 2
for k: Int in 1..<halfSize {
let d_: Float = abs(Self.angularDelta(buf[phase: k], pre))
#expect(d_ <= Float.pi * 0.5 + 1e-5,
"bin \(k) moved \(d_) > π/2 with amount=0.5")
}
}
@Test func liveAmountUpdate() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillBins(buf)
let d: SpectralDiffuse = SpectralDiffuse(fftSize: fftSize, amount: 0, seed: 1)
d.process(spectral: buf, engine: makeTestEngine())
#expect(buf[phase: 5] == 0.4, "amount=0 should bypass")
d.amount = 1.0
d.process(spectral: buf, engine: makeTestEngine())
// Highly likely to differ from 0.4 with amount=1 (probability of exact
// match is essentially zero with float-precision random draw).
#expect(buf[phase: 5] != 0.4)
}
@Test func amountClampedToUnitRange() {
let fftSize: Int = 64
let d: SpectralDiffuse = SpectralDiffuse(fftSize: fftSize, amount: 5.0)
#expect(d.amount == 1.0)
let d2: SpectralDiffuse = SpectralDiffuse(fftSize: fftSize, amount: -1.0)
#expect(d2.amount == 0.0)
}
@Test func invalidBufferIsBypassed() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillBins(buf)
buf.invalidate()
let d: SpectralDiffuse = SpectralDiffuse(fftSize: fftSize, amount: 1.0, seed: 1)
d.process(spectral: buf, engine: makeTestEngine())
#expect(buf[phase: 5] == 0.4)
}
}
@@ -0,0 +1,461 @@
// 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
@MainActor
@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
@MainActor
@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
@MainActor
@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
@MainActor
@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
@MainActor
@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
@MainActor
@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)
}
}
@@ -0,0 +1,262 @@
// SpectralFormantShiftTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpectralFormantShift")
struct SpectralFormantShiftTests {
// MARK: - Helpers
/// Gaussian-shaped magnitude envelope centred on `center`.
private static func gaussian(
bins: Int,
center: Float,
sigma: Float
) -> [Float] {
var out: [Float] = [Float](repeating: 0, count: bins)
for k: Int in 0..<bins {
let d: Float = (Float(k) - center) / sigma
out[k] = exp(-0.5 * d * d)
}
return out
}
private static func argMax(_ a: [Float]) -> Int {
var best: Int = 0
var bestVal: Float = a[0]
for i: Int in 1..<a.count {
if a[i] > bestVal { bestVal = a[i]; best = i }
}
return best
}
// MARK: - Tests
@Test func ratioOneIsBypass() {
let fftSize: Int = 256
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let halfSize: Int = fftSize / 2
let envelope: [Float] = Self.gaussian(bins: halfSize + 1, center: 60, sigma: 12)
buf.dcValue = 0.3
buf.nyquistValue = -0.4
for k: Int in 1..<halfSize {
buf[magnitude: k] = envelope[k]
buf[phase: k] = 0.25 * Float(k)
}
let fs: SpectralFormantShift = SpectralFormantShift(fftSize: fftSize, shiftRatio: 1.0)
fs.process(spectral: buf, engine: makeTestEngine())
#expect(buf.dcValue == 0.3)
#expect(buf.nyquistValue == -0.4)
for k: Int in 1..<halfSize {
#expect(buf[magnitude: k] == envelope[k])
#expect(buf[phase: k] == 0.25 * Float(k))
}
}
@Test func cepstralPeakShiftsUp() {
let fftSize: Int = 512
let halfSize: Int = fftSize / 2
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let srcCenter: Float = 40
let envelope: [Float] = Self.gaussian(bins: halfSize + 1, center: srcCenter, sigma: 12)
for k: Int in 1..<halfSize {
buf[magnitude: k] = envelope[k]
buf[phase: k] = 0
}
let fs: SpectralFormantShift = SpectralFormantShift(
fftSize: fftSize,
shiftRatio: 2.0,
method: .cepstral,
cepstralCutoffQuefrency: 24
)
fs.process(spectral: buf, engine: makeTestEngine())
var out: [Float] = [Float](repeating: 0, count: halfSize)
for k: Int in 0..<halfSize { out[k] = buf.magnitude(at: k) }
let peakBin: Int = Self.argMax(out)
let expectedBin: Int = Int(srcCenter * 2)
// Cepstral lifter introduces a small bias relative to a true bin-axis
// resampling; ±8 bins is comfortably within the formant feature width.
#expect(abs(peakBin - expectedBin) <= 8,
"expected peak near bin \(expectedBin), got \(peakBin)")
}
@Test func cepstralEnvelopeIsSmootherThanHarmonicInput() {
// The cepstral lifter should separate slow formant structure from fast
// harmonic structure. Feed a harmonic comb modulated by a smooth
// gaussian formant; the estimated envelope should have far lower
// bin-to-bin variation than the input magnitude spectrum.
let fftSize: Int = 512
let halfSize: Int = fftSize / 2
let n: Int = halfSize + 1
let formant: [Float] = Self.gaussian(bins: n, center: 80, sigma: 30)
let harmonicSpacing: Int = 8
let magPtr: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: n)
defer { magPtr.deinitialize(count: n); magPtr.deallocate() }
let envPtr: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: n)
defer { envPtr.deinitialize(count: n); envPtr.deallocate() }
magPtr.initialize(repeating: 0, count: n)
envPtr.initialize(repeating: 0, count: n)
for k: Int in 0..<n {
magPtr[k] = (k % harmonicSpacing == 0) ? formant[k] : 0
}
let est: CepstralEnvelopeEstimator = CepstralEnvelopeEstimator(fftSize: fftSize, cutoffQuefrency: 24)
est.estimate(magnitudes: magPtr, into: envPtr)
// Total-variation-style metric: sum of |x[k+1] − x[k]|.
var tvInput: Float = 0
var tvEnv: Float = 0
for k: Int in 0..<(n - 1) {
tvInput += abs(magPtr[k + 1] - magPtr[k])
tvEnv += abs(envPtr[k + 1] - envPtr[k])
}
#expect(tvEnv < tvInput * 0.5,
"estimated envelope total-variation \(tvEnv) is not < 0.5× input \(tvInput) — lifter did not smooth harmonics")
}
@Test func residualReapplyIsIdentity() {
// Math identity: (mag / (env + ε)) × env ≈ mag, independent of env
// quality. Guards against precision regressions in the residual /
// reapply formula used by `process(spectral:)`.
let fftSize: Int = 256
let halfSize: Int = fftSize / 2
let n: Int = halfSize + 1
let envIn: [Float] = Self.gaussian(bins: n, center: 30, sigma: 10)
let est: CepstralEnvelopeEstimator = CepstralEnvelopeEstimator(fftSize: fftSize, cutoffQuefrency: 32)
let magPtr: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: n)
defer { magPtr.deinitialize(count: n); magPtr.deallocate() }
let envPtr: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: n)
defer { envPtr.deinitialize(count: n); envPtr.deallocate() }
magPtr.initialize(repeating: 0, count: n)
envPtr.initialize(repeating: 0, count: n)
for k: Int in 0..<n { magPtr[k] = envIn[k] + 1e-6 }
est.estimate(magnitudes: magPtr, into: envPtr)
let eps: Float = 1e-9
var maxRelErr: Float = 0
for k: Int in 0..<n {
let mag: Float = magPtr[k]
let rec: Float = (mag / (envPtr[k] + eps)) * envPtr[k]
let denom: Float = max(mag, 1e-6)
let err: Float = abs(rec - mag) / denom
if err > maxRelErr { maxRelErr = err }
}
#expect(maxRelErr < 5e-3,
"residual×envelope round-trip max relative error \(maxRelErr) exceeds 5e-3")
}
@Test func phaseUntouched() {
let fftSize: Int = 256
let halfSize: Int = fftSize / 2
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let envelope: [Float] = Self.gaussian(bins: halfSize + 1, center: 30, sigma: 10)
let phases: [Float] = (1..<halfSize).map { Float($0) * 0.17 }
for k: Int in 1..<halfSize {
buf[magnitude: k] = envelope[k]
buf[phase: k] = phases[k - 1]
}
let fs: SpectralFormantShift = SpectralFormantShift(fftSize: fftSize, shiftRatio: 1.7)
fs.process(spectral: buf, engine: makeTestEngine())
for k: Int in 1..<halfSize {
#expect(buf[phase: k] == phases[k - 1],
"phase at bin \(k) changed: \(buf[phase: k]) vs \(phases[k - 1])")
}
}
@Test func magnitudeSmoothingFallbackSmoke() {
let fftSize: Int = 256
let halfSize: Int = fftSize / 2
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
// Flat input — envelope estimator returns a constant, residual ≈ 1
// across all bins, so the resampled envelope (also flat) produces a
// non-zero, near-flat output. Verifies the smoothing path runs and
// does not crash.
for k: Int in 1..<halfSize { buf[magnitude: k] = 0.5 }
let fs: SpectralFormantShift = SpectralFormantShift(
fftSize: fftSize,
shiftRatio: 1.5,
method: .magnitudeSmoothing(radiusBins: 4)
)
fs.process(spectral: buf, engine: makeTestEngine())
var nonZeroCount: Int = 0
for k: Int in 1..<halfSize where buf[magnitude: k] > 1e-3 { nonZeroCount += 1 }
#expect(nonZeroCount > halfSize / 2,
"smoothing path should leave most bins non-zero on flat input, got \(nonZeroCount)")
}
@Test func dcSignPreserved() {
let fftSize: Int = 128
let halfSize: Int = fftSize / 2
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
buf.dcValue = -0.7
buf.nyquistValue = -0.3
// Wider envelope keeps DC and Nyquist envelope values appreciably > 0
// so the resampled envelope never collapses to 0 at the edges.
let envelope: [Float] = Self.gaussian(bins: halfSize + 1, center: 32, sigma: 24)
for k: Int in 1..<halfSize { buf[magnitude: k] = envelope[k] }
let fs: SpectralFormantShift = SpectralFormantShift(
fftSize: fftSize,
shiftRatio: 1.5,
method: .magnitudeSmoothing(radiusBins: 4)
)
fs.process(spectral: buf, engine: makeTestEngine())
// `< 0` (strict) — `<= 0` would vacuously accept a zero collapse and
// miss an accidental sign flip to `+0`.
#expect(buf.dcValue < 0, "DC sign not preserved, got \(buf.dcValue)")
#expect(buf.nyquistValue < 0, "Nyquist sign not preserved, got \(buf.nyquistValue)")
}
@Test func invalidBufferIsNoOp() {
let fftSize: Int = 128
let halfSize: Int = fftSize / 2
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
for k: Int in 1..<halfSize { buf[magnitude: k] = Float(k) }
buf.invalidate()
let fs: SpectralFormantShift = SpectralFormantShift(fftSize: fftSize, shiftRatio: 2.0)
fs.process(spectral: buf, engine: makeTestEngine())
for k: Int in 1..<halfSize {
#expect(buf[magnitude: k] == Float(k), "invalid buffer was modified at bin \(k)")
}
}
@Test func shiftRatioClampedOnLiveUpdate() {
let fs: SpectralFormantShift = SpectralFormantShift(fftSize: 64, shiftRatio: 1.0)
fs.shiftRatio = 10.0
#expect(fs.shiftRatio == 4.0)
fs.shiftRatio = 0.01
#expect(fs.shiftRatio == 0.25)
}
@Test func mismatchedFftSizeIsNoOp() {
let fs: SpectralFormantShift = SpectralFormantShift(fftSize: 128, shiftRatio: 2.0)
let buf: SpectralBuffer = SpectralBuffer(fftSize: 256)
let halfSize: Int = 128
for k: Int in 1..<halfSize { buf[magnitude: k] = Float(k) }
fs.process(spectral: buf, engine: makeTestEngine())
for k: Int in 1..<halfSize {
#expect(buf[magnitude: k] == Float(k))
}
}
}
@@ -0,0 +1,145 @@
// SpectralGateTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpectralGate")
struct SpectralGateTests {
private static func fillRamp(_ buf: SpectralBuffer) {
// mag k = k * 0.1, phase k = 0.7
buf.dcValue = 0.05
buf.nyquistValue = -0.3
let halfSize: Int = buf.fftSize / 2
for k: Int in 1..<halfSize {
buf[magnitude: k] = Float(k) * 0.1
buf[phase: k] = 0.7
}
}
@Test func floorZeroHardGatesBelowThreshold() {
let fftSize: Int = 32
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillRamp(buf)
let g: SpectralGate = SpectralGate(fftSize: fftSize, threshold: 0.5, floor: 0)
g.process(spectral: buf, engine: makeTestEngine())
let halfSize: Int = fftSize / 2
for k: Int in 1..<halfSize {
let expected: Float = (Float(k) * 0.1) < 0.5 ? 0.0 : Float(k) * 0.1
#expect(buf[magnitude: k] == expected,
"bin \(k) gate failed: got \(buf[magnitude: k]) expected \(expected)")
}
}
@Test func floorOneIsBypass() {
let fftSize: Int = 32
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillRamp(buf)
let g: SpectralGate = SpectralGate(fftSize: fftSize, threshold: 999.0, floor: 1.0)
g.process(spectral: buf, engine: makeTestEngine())
let halfSize: Int = fftSize / 2
for k: Int in 1..<halfSize {
#expect(buf[magnitude: k] == Float(k) * 0.1,
"bin \(k) altered with floor=1 (bypass)")
}
#expect(buf.dcValue == 0.05)
#expect(buf.nyquistValue == -0.3)
}
@Test func dcAndNyquistGatedOnAbsPreserveSign() {
let fftSize: Int = 32
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillRamp(buf)
// DC = 0.05 (below threshold 0.1), Nyquist = -0.3 (above threshold).
let g: SpectralGate = SpectralGate(fftSize: fftSize, threshold: 0.1, floor: 0)
g.process(spectral: buf, engine: makeTestEngine())
#expect(buf.dcValue == 0.0)
#expect(buf.nyquistValue == -0.3) // |−0.3| > 0.1, passes through with sign.
}
@Test func phaseUntouched() {
let fftSize: Int = 32
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillRamp(buf)
let g: SpectralGate = SpectralGate(fftSize: fftSize, threshold: 0.5, floor: 0)
g.process(spectral: buf, engine: makeTestEngine())
let halfSize: Int = fftSize / 2
for k: Int in 1..<halfSize {
#expect(buf[phase: k] == 0.7, "phase on bin \(k) altered")
}
}
@Test func intermediateFloorScales() {
let fftSize: Int = 32
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillRamp(buf)
let g: SpectralGate = SpectralGate(fftSize: fftSize, threshold: 0.5, floor: 0.25)
g.process(spectral: buf, engine: makeTestEngine())
// Bin 3: mag 0.3 < 0.5 → 0.3 * 0.25 = 0.075.
#expect(abs(buf[magnitude: 3] - 0.075) < 1e-6)
// Bin 8: mag 0.8 ≥ 0.5 → unchanged.
#expect(buf[magnitude: 8] == 0.8)
}
@Test func dbConvenienceMatchesLinear() {
let fftSize: Int = 32
let buf1: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let buf2: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillRamp(buf1)
Self.fillRamp(buf2)
let lin: Double = pow(10.0, -20.0 / 20.0) // 0.1
let gLin: SpectralGate = SpectralGate(fftSize: fftSize, threshold: lin, floor: 0)
let gDB: SpectralGate = SpectralGate(fftSize: fftSize, thresholdDB: -20.0, floor: 0)
gLin.process(spectral: buf1, engine: makeTestEngine())
gDB.process(spectral: buf2, engine: makeTestEngine())
let halfSize: Int = fftSize / 2
for k: Int in 1..<halfSize {
#expect(abs(buf1[magnitude: k] - buf2[magnitude: k]) < 1e-6)
}
}
@Test func liveThresholdUpdate() {
let fftSize: Int = 32
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillRamp(buf)
let g: SpectralGate = SpectralGate(fftSize: fftSize, threshold: 999.0, floor: 0)
g.process(spectral: buf, engine: makeTestEngine())
// All gated to 0.
#expect(buf[magnitude: 5] == 0.0)
// Refill, lower threshold.
Self.fillRamp(buf)
g.threshold = 0.0
g.process(spectral: buf, engine: makeTestEngine())
// Nothing gated.
#expect(buf[magnitude: 5] == 0.5)
}
@Test func invalidBufferIsBypassed() {
let fftSize: Int = 32
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillRamp(buf)
buf.invalidate()
let g: SpectralGate = SpectralGate(fftSize: fftSize, threshold: 999.0, floor: 0)
g.process(spectral: buf, engine: makeTestEngine())
#expect(buf[magnitude: 5] == 0.5)
}
}
@@ -0,0 +1,92 @@
// SpectralHarmonicEnhanceTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpectralHarmonicEnhance")
struct SpectralHarmonicEnhanceTests {
/// Single source bin produces magnitudes at expected harmonic targets with 1/i scaling.
@Test func singleBinProducesHarmonics() {
let fftSize: Int = 256 // halfSize = 128 — plenty of headroom for 4 harmonics of bin 8 at ratio 2
let sourceBin: Int = 8
let sourceMag: Float = 1.0
let strength: Float = 0.5
let ratio: Float = 2.0
let numPartials: Int = 3
let enh: SpectralHarmonicEnhance = SpectralHarmonicEnhance(
fftSize: fftSize,
numPartials: Double(numPartials),
ratio: Double(ratio),
strength: Double(strength)
)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
buf[magnitude: sourceBin] = sourceMag
enh.process(spectral: buf, engine: makeTestEngine())
// Source bin keeps its mag (only added-to never zeroed by the algorithm).
// Targets at i=1: bin 16 → += 1.0 * 0.5 / 1 = 0.5
// Targets at i=2: bin 32 → += 1.0 * 0.5 / 2 = 0.25
// Targets at i=3: bin 48 → += 1.0 * 0.5 / 3 ≈ 0.1667
#expect(abs(buf[magnitude: 16] - 0.5) < 1e-5,
"Harmonic 1 at bin 16 should be 0.5, got \(buf[magnitude: 16])")
#expect(abs(buf[magnitude: 32] - 0.25) < 1e-5,
"Harmonic 2 at bin 32 should be 0.25, got \(buf[magnitude: 32])")
#expect(abs(buf[magnitude: 48] - (0.5 / 3.0)) < 1e-5,
"Harmonic 3 at bin 48 should be 0.1667, got \(buf[magnitude: 48])")
}
/// Out-of-range targets must be silently skipped — no crash, no out-of-bounds writes.
@Test func outOfRangeHarmonicsSkipped() {
let fftSize: Int = 64 // halfSize = 32
let sourceBin: Int = 12 // ratio 2 × 12 = 24, ratio 2 × 24 = 48 (out of range)
let enh: SpectralHarmonicEnhance = SpectralHarmonicEnhance(fftSize: fftSize, numPartials: 4, ratio: 2.0, strength: 1.0)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
buf[magnitude: sourceBin] = 1.0
// Should not crash and should produce only the in-range partial.
enh.process(spectral: buf, engine: makeTestEngine())
#expect(buf[magnitude: 24] > 0, "First harmonic at bin 24 should have been added")
// Higher harmonics at 48, 72, 96 are out of range and silently skipped.
}
/// `ratio <= 1.0` produces no change (start bin collapses).
@Test func ratioOneIsNoOp() {
let fftSize: Int = 64
let enh: SpectralHarmonicEnhance = SpectralHarmonicEnhance(fftSize: fftSize, numPartials: 4, ratio: 1.0, strength: 1.0)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
buf[magnitude: 8] = 1.0
buf[magnitude: 16] = 0.0
enh.process(spectral: buf, engine: makeTestEngine())
#expect(buf[magnitude: 8] == 1.0, "Source bin must not change with ratio=1")
#expect(buf[magnitude: 16] == 0.0, "No harmonic should be added with ratio=1")
}
/// Live parameter update path. Values are stored as `Float` internally; the
/// `Double`-typed accessor returns the Float-rounded approximation, so we
/// compare with a tolerance.
@Test func parametersAreLive() {
let enh: SpectralHarmonicEnhance = SpectralHarmonicEnhance(fftSize: 64, numPartials: 4, ratio: 2.0, strength: 0.2)
#expect(abs(enh.numPartials - 4.0) < 1e-5)
#expect(abs(enh.ratio - 2.0) < 1e-5)
#expect(abs(enh.strength - 0.2) < 1e-5)
enh.numPartials = 6
enh.ratio = 3.0
enh.strength = 0.5
#expect(abs(enh.numPartials - 6.0) < 1e-5)
#expect(abs(enh.ratio - 3.0) < 1e-5)
#expect(abs(enh.strength - 0.5) < 1e-5)
}
}
@@ -0,0 +1,112 @@
// SpectralMagnitudeMapTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpectralMagnitudeMap")
struct SpectralMagnitudeMapTests {
/// Identity transfer (linear ramp 0 → 1) should leave magnitudes unchanged
/// within float precision.
@Test func identityTransferPreservesMagnitudes() {
let fftSize: Int = 64
let halfSize: Int = fftSize / 2
let curve: LyrebirdBuffer = LyrebirdBuffer(count: 256)
curve.fill { i, n in Double(i) / Double(n - 1) }
let map: SpectralMagnitudeMap = SpectralMagnitudeMap(buffer: curve)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
// Populate bins with known magnitudes; mag at testBin sets the maximum.
let inputs: [Float] = [0.0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0]
for k: Int in 1..<halfSize {
buf[magnitude: k] = inputs[k % inputs.count]
}
map.process(spectral: buf, engine: makeTestEngine())
for k: Int in 1..<halfSize {
let expected: Float = inputs[k % inputs.count]
let got: Float = buf[magnitude: k]
#expect(abs(got - expected) < 1e-3,
"Identity transfer should preserve mag[\(k)] = \(expected), got \(got)")
}
}
/// Constant 0.5 transfer collapses every bin to `0.5 × max` (the same value)
/// regardless of original magnitude — the transfer ignores the lookup index.
@Test func constantHalfTransferCollapsesToHalfMax() {
let fftSize: Int = 64
let halfSize: Int = fftSize / 2
let curve: LyrebirdBuffer = LyrebirdBuffer(count: 256)
curve.fill { _, _ in 0.5 }
let map: SpectralMagnitudeMap = SpectralMagnitudeMap(buffer: curve)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
for k: Int in 1..<halfSize {
buf[magnitude: k] = Float(k) / Float(halfSize)
}
let maxMag: Float = Float(halfSize - 1) / Float(halfSize)
let expected: Float = 0.5 * maxMag
map.process(spectral: buf, engine: makeTestEngine())
for k: Int in 1..<halfSize {
let got: Float = buf[magnitude: k]
#expect(abs(got - expected) < 1e-4,
"Constant 0.5 transfer should collapse mag[\(k)] to 0.5 × max = \(expected), got \(got)")
}
}
/// A frame whose maximum magnitude is below the floor must be left untouched.
@Test func belowFloorIsUntouched() {
let fftSize: Int = 64
let halfSize: Int = fftSize / 2
let curve: LyrebirdBuffer = LyrebirdBuffer(count: 256)
curve.fill { _, _ in 0.0 } // would zero everything if it ran
let map: SpectralMagnitudeMap = SpectralMagnitudeMap(buffer: curve, magnitudeFloor: 1e-3)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let tinyMag: Float = 1e-6
for k: Int in 1..<halfSize {
buf[magnitude: k] = tinyMag
}
map.process(spectral: buf, engine: makeTestEngine())
for k: Int in 1..<halfSize {
#expect(buf[magnitude: k] == tinyMag,
"Below-floor frame must not be touched at bin \(k), got \(buf[magnitude: k])")
}
}
/// Step transfer: zero below halfway, identity above. Quiet bins should be
/// zeroed; loud bins should pass.
@Test func stepTransferGate() {
let fftSize: Int = 64
let halfSize: Int = fftSize / 2
let curve: LyrebirdBuffer = LyrebirdBuffer(count: 256)
curve.fill { i, n in Double(i) / Double(n - 1) >= 0.5 ? Double(i) / Double(n - 1) : 0.0 }
let map: SpectralMagnitudeMap = SpectralMagnitudeMap(buffer: curve)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
// Set max at one bin; everything else proportionally.
buf[magnitude: 5] = 1.0 // max → normalised 1.0 → above gate
buf[magnitude: 10] = 0.2 // 0.2 → below gate
buf[magnitude: 15] = 0.6 // 0.6 → above gate
map.process(spectral: buf, engine: makeTestEngine())
#expect(buf[magnitude: 5] > 0.5, "Loud bin 5 should pass through, got \(buf[magnitude: 5])")
#expect(buf[magnitude: 10] == 0.0, "Quiet bin 10 should be gated, got \(buf[magnitude: 10])")
#expect(buf[magnitude: 15] > 0.0, "Above-gate bin 15 should pass, got \(buf[magnitude: 15])")
}
}
@@ -0,0 +1,129 @@
// SpectralNoiseFilterTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpectralNoiseFilter")
struct SpectralNoiseFilterTests {
@Test func phaseModeStableBinZeroed() {
let fftSize: Int = 64
let numFrames: Int = 4
let testBin: Int = 5
let stablePhaseStep: Float = 0.5
let filt: SpectralNoiseFilter = SpectralNoiseFilter(
fftSize: fftSize,
numFrames: numFrames,
mode: .phase,
hopSize: 16,
sampleRate: 44_100,
threshold: 0.05
)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
var phase: Float = 0
for _ in 0...numFrames {
phase += stablePhaseStep
if phase > Float.pi { phase -= 2 * Float.pi }
buf[magnitude: testBin] = 1.0
buf[phase: testBin] = phase
filt.process(spectral: buf, engine: makeTestEngine())
}
#expect(buf[magnitude: testBin] == 0.0,
"Stable bin should be zeroed by NoiseFilter, got mag=\(buf[magnitude: testBin])")
}
@Test func phaseModeUnstableBinSurvives() {
let fftSize: Int = 64
let numFrames: Int = 4
let testBin: Int = 5
let filt: SpectralNoiseFilter = SpectralNoiseFilter(
fftSize: fftSize,
numFrames: numFrames,
mode: .phase,
hopSize: 16,
sampleRate: 44_100,
threshold: 0.05
)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let phases: [Float] = [0.0, 1.5, -2.5, 0.7, -1.2, 2.8]
for hop: Int in 0..<phases.count {
buf[magnitude: testBin] = 1.0
buf[phase: testBin] = phases[hop]
filt.process(spectral: buf, engine: makeTestEngine())
}
#expect(buf[magnitude: testBin] == 1.0,
"Unstable (noisy) bin should survive NoiseFilter, got mag=\(buf[magnitude: testBin])")
}
@Test func frequencyModeStableBinZeroed() {
let fftSize: Int = 64
let numFrames: Int = 4
let testBin: Int = 5
let filt: SpectralNoiseFilter = SpectralNoiseFilter(
fftSize: fftSize,
numFrames: numFrames,
mode: .frequency,
hopSize: 16,
sampleRate: 44_100,
threshold: 1.0 // 1 Hz tolerance
)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
// Same expected-step setup as PartialFilter's frequency-mode test —
// produces a stable Hz estimate, which NoiseFilter should zero.
let twoPi: Float = 2 * Float.pi
let expectedStep: Float = twoPi * 16.0 / Float(fftSize) * Float(testBin)
var phase: Float = 0
for _ in 0...numFrames {
phase += expectedStep
phase = phase.remainder(dividingBy: twoPi)
buf[magnitude: testBin] = 1.0
buf[phase: testBin] = phase
filt.process(spectral: buf, engine: makeTestEngine())
}
#expect(buf[magnitude: testBin] == 0.0,
"Stable bin (.frequency) should be zeroed by NoiseFilter, got mag=\(buf[magnitude: testBin])")
}
@Test func warmupPreservesMagnitudes() {
let fftSize: Int = 64
let numFrames: Int = 4
let testBin: Int = 5
let filt: SpectralNoiseFilter = SpectralNoiseFilter(
fftSize: fftSize,
numFrames: numFrames,
mode: .phase,
hopSize: 16,
sampleRate: 44_100,
threshold: 100.0 // very loose — would zero everything if applied
)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
// Run exactly numFrames hops with constant phase step (stable). Without
// warmup guard, NoiseFilter would zero this. With warmup, it survives.
for _ in 0..<numFrames {
buf[magnitude: testBin] = 1.0
buf[phase: testBin] = 0.5
filt.process(spectral: buf, engine: makeTestEngine())
}
#expect(buf[magnitude: testBin] == 1.0,
"Magnitude must survive every hop during warmup, got mag=\(buf[magnitude: testBin])")
}
}
@@ -0,0 +1,164 @@
// SpectralPartialFilterTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpectralPartialFilter")
struct SpectralPartialFilterTests {
// MARK: - .phase mode
/// A bin with constant hop-to-hop phase difference is "stable" — its mag should
/// survive after the warmup window.
@Test func phaseModeStableBinSurvives() {
let fftSize: Int = 64
let numFrames: Int = 4
let testBin: Int = 5
let stablePhaseStep: Float = 0.5
let filt: SpectralPartialFilter = SpectralPartialFilter(
fftSize: fftSize,
numFrames: numFrames,
mode: .phase,
hopSize: 16,
sampleRate: 44_100,
threshold: 0.05
)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
// Drive the bin with a constant phase increment for numFrames + 1 hops.
var phase: Float = 0
for _ in 0...numFrames {
phase += stablePhaseStep
// Wrap to (-π, π].
if phase > Float.pi { phase -= 2 * Float.pi }
buf[magnitude: testBin] = 1.0
buf[phase: testBin] = phase
filt.process(spectral: buf, engine: makeTestEngine())
}
// After warmup the magnitude should still be 1.0 (stable bin survives).
#expect(buf[magnitude: testBin] == 1.0,
"Stable bin should survive PartialFilter, got mag=\(buf[magnitude: testBin])")
}
/// A bin with random phase has noisy hop-to-hop phase difference — its mag
/// should be zeroed after warmup.
@Test func phaseModeUnstableBinZeroed() {
let fftSize: Int = 64
let numFrames: Int = 4
let testBin: Int = 5
let filt: SpectralPartialFilter = SpectralPartialFilter(
fftSize: fftSize,
numFrames: numFrames,
mode: .phase,
hopSize: 16,
sampleRate: 44_100,
threshold: 0.05
)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
// Pseudo-random but deterministic phases — large hop-to-hop swings.
let phases: [Float] = [0.0, 1.5, -2.5, 0.7, -1.2, 2.8]
for hop: Int in 0..<phases.count {
buf[magnitude: testBin] = 1.0
buf[phase: testBin] = phases[hop]
filt.process(spectral: buf, engine: makeTestEngine())
}
#expect(buf[magnitude: testBin] == 0.0,
"Unstable bin should be zeroed, got mag=\(buf[magnitude: testBin])")
}
// MARK: - Warmup
/// During warmup, magnitudes must not be modified even if metric is unstable.
@Test func warmupPreservesMagnitudes() {
let fftSize: Int = 64
let numFrames: Int = 4
let testBin: Int = 5
let filt: SpectralPartialFilter = SpectralPartialFilter(
fftSize: fftSize,
numFrames: numFrames,
mode: .phase,
hopSize: 16,
sampleRate: 44_100,
threshold: 0.001 // very strict — would zero everything if applied
)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
// Run exactly numFrames hops (warmup window). Magnitude must survive even
// with erratic phases.
let phases: [Float] = [0.0, 1.0, -1.0, 2.0]
for hop: Int in 0..<numFrames {
buf[magnitude: testBin] = 1.0
buf[phase: testBin] = phases[hop]
filt.process(spectral: buf, engine: makeTestEngine())
}
#expect(buf[magnitude: testBin] == 1.0,
"Magnitude must survive every hop during warmup, got mag=\(buf[magnitude: testBin])")
}
// MARK: - .frequency mode
@Test func frequencyModeStableBinSurvives() {
let fftSize: Int = 64
let numFrames: Int = 4
let testBin: Int = 5
let filt: SpectralPartialFilter = SpectralPartialFilter(
fftSize: fftSize,
numFrames: numFrames,
mode: .frequency,
hopSize: 16,
sampleRate: 44_100,
threshold: 1.0 // 1 Hz tolerance
)
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
// For .frequency mode a stable phase-step around the bin's expected step
// produces a stable Hz estimate. Use the centre-bin expected step exactly.
let twoPi: Float = 2 * Float.pi
let expectedStep: Float = twoPi * 16.0 / Float(fftSize) * Float(testBin)
var phase: Float = 0
for _ in 0...numFrames {
phase += expectedStep
phase = phase.remainder(dividingBy: twoPi)
buf[magnitude: testBin] = 1.0
buf[phase: testBin] = phase
filt.process(spectral: buf, engine: makeTestEngine())
}
#expect(buf[magnitude: testBin] == 1.0,
"Stable bin (.frequency) should survive PartialFilter, got mag=\(buf[magnitude: testBin])")
}
// MARK: - Threshold update
/// `threshold` is settable from any thread; the new value takes effect on the
/// next process() call.
@Test func thresholdUpdateLive() {
let fftSize: Int = 64
let filt: SpectralPartialFilter = SpectralPartialFilter(
fftSize: fftSize,
numFrames: 2,
mode: .phase,
hopSize: 16,
sampleRate: 44_100,
threshold: 100.0
)
#expect(filt.threshold == 100.0)
filt.threshold = 5.0
#expect(filt.threshold == 5.0)
}
}
@@ -0,0 +1,200 @@
// SpectralPhaseShiftTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpectralPhaseShift")
struct SpectralPhaseShiftTests {
private static let phaseTolerance: Float = 1e-5
/// Smallest signed angular distance from a to b, accounting for ±2π wrap.
private static func angularDelta(_ a: Float, _ b: Float) -> Float {
let twoPi: Float = 2 * Float.pi
var d: Float = a - b
if d > Float.pi { d -= twoPi }
else if d < -Float.pi { d += twoPi }
return d
}
private static func fillBinsWithPhases(_ buf: SpectralBuffer, basePhase: Float = 0.3) {
buf.dcValue = 1.5
buf.nyquistValue = -0.7
let halfSize: Int = buf.fftSize / 2
for k: Int in 1..<halfSize {
buf[magnitude: k] = Float(k)
buf[phase: k] = basePhase + Float(k) * 0.01
}
}
// MARK: - .deg90
@Test func deg90AddsHalfPiToEveryBinPhase() {
let fftSize: Int = 32
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillBinsWithPhases(buf)
let halfSize: Int = fftSize / 2
var pre: [Float] = []
for k: Int in 1..<halfSize { pre.append(buf[phase: k]) }
let p: SpectralPhaseShift = SpectralPhaseShift(fftSize: fftSize, shift: .deg90)
p.process(spectral: buf, engine: makeTestEngine())
let halfPi: Float = Float(Double.pi * 0.5)
for k: Int in 1..<halfSize {
let delta: Float = Self.angularDelta(buf[phase: k], pre[k - 1])
#expect(abs(delta - halfPi) < Self.phaseTolerance,
"bin \(k) phase delta \(delta) ≠ π/2")
}
// DC/Nyquist not flipped on 90°.
#expect(buf.dcValue == 1.5)
#expect(buf.nyquistValue == -0.7)
}
// MARK: - .deg180
@Test func deg180FlipsSignOfDCAndNyquistAndAddsPiToBins() {
let fftSize: Int = 32
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillBinsWithPhases(buf)
let halfSize: Int = fftSize / 2
var pre: [Float] = []
for k: Int in 1..<halfSize { pre.append(buf[phase: k]) }
let p: SpectralPhaseShift = SpectralPhaseShift(fftSize: fftSize, shift: .deg180)
p.process(spectral: buf, engine: makeTestEngine())
let pi: Float = Float(Double.pi)
for k: Int in 1..<halfSize {
let delta: Float = Self.angularDelta(buf[phase: k], pre[k - 1])
#expect(abs(abs(delta) - pi) < Self.phaseTolerance,
"bin \(k) phase delta \(delta) magnitude not π")
}
#expect(buf.dcValue == -1.5)
#expect(buf.nyquistValue == 0.7)
}
// MARK: - .deg270
@Test func deg270FourTimesEqualsIdentity() {
let fftSize: Int = 32
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillBinsWithPhases(buf)
let halfSize: Int = fftSize / 2
var pre: [Float] = []
for k: Int in 1..<halfSize { pre.append(buf[phase: k]) }
let p: SpectralPhaseShift = SpectralPhaseShift(fftSize: fftSize, shift: .deg270)
for _ in 0..<4 {
p.process(spectral: buf, engine: makeTestEngine())
}
for k: Int in 1..<halfSize {
let delta: Float = Self.angularDelta(buf[phase: k], pre[k - 1])
#expect(abs(delta) < 1e-4,
"bin \(k) round-trip residual \(delta) too large")
}
}
// MARK: - .radians arbitrary
@Test func arbitraryRadiansAddsExactOffset() {
let fftSize: Int = 32
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillBinsWithPhases(buf)
let halfSize: Int = fftSize / 2
var pre: [Float] = []
for k: Int in 1..<halfSize { pre.append(buf[phase: k]) }
let offset: Double = 1.234
let p: SpectralPhaseShift = SpectralPhaseShift(fftSize: fftSize, shift: .radians(offset))
p.process(spectral: buf, engine: makeTestEngine())
let target: Float = Float(offset)
for k: Int in 1..<halfSize {
let delta: Float = Self.angularDelta(buf[phase: k], pre[k - 1])
#expect(abs(delta - target) < Self.phaseTolerance,
"bin \(k) delta \(delta) ≠ \(target)")
}
}
// MARK: - Magnitude untouched
@Test func magnitudeUnchangedAcrossShifts() {
let fftSize: Int = 32
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillBinsWithPhases(buf)
let halfSize: Int = fftSize / 2
let p: SpectralPhaseShift = SpectralPhaseShift(fftSize: fftSize, shift: .deg90)
p.process(spectral: buf, engine: makeTestEngine())
for k: Int in 1..<halfSize {
#expect(buf[magnitude: k] == Float(k), "bin \(k) magnitude altered")
}
}
// MARK: - Live radians update
@Test func liveRadiansUpdateAffectsNextHop() {
let fftSize: Int = 32
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillBinsWithPhases(buf)
let phaseBefore: Float = buf[phase: 5]
let p: SpectralPhaseShift = SpectralPhaseShift(fftSize: fftSize, shift: .radians(0))
p.process(spectral: buf, engine: makeTestEngine())
// No change with offset 0 (within wrap precision).
#expect(abs(Self.angularDelta(buf[phase: 5], phaseBefore)) < Self.phaseTolerance)
p.radians = 0.5
p.process(spectral: buf, engine: makeTestEngine())
let delta: Float = Self.angularDelta(buf[phase: 5], phaseBefore)
#expect(abs(delta - 0.5) < Self.phaseTolerance,
"expected delta 0.5, got \(delta)")
}
// MARK: - Out-of-range radians normalised
@Test func radiansBeyond2PiNormaliseCorrectly() {
let fftSize: Int = 32
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillBinsWithPhases(buf)
let halfSize: Int = fftSize / 2
var pre: [Float] = []
for k: Int in 1..<halfSize { pre.append(buf[phase: k]) }
// 5π/2 normalised is π/2.
let off: Double = Double.pi * 2.5
let p: SpectralPhaseShift = SpectralPhaseShift(fftSize: fftSize, shift: .radians(off))
p.process(spectral: buf, engine: makeTestEngine())
let target: Float = Float(Double.pi * 0.5)
for k: Int in 1..<halfSize {
let d: Float = Self.angularDelta(buf[phase: k], pre[k - 1])
#expect(abs(d - target) < Self.phaseTolerance,
"bin \(k) delta \(d) ≠ π/2 (after normalise)")
}
}
// MARK: - Invalid buffer
@Test func invalidBufferIsBypassed() {
let fftSize: Int = 32
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillBinsWithPhases(buf)
let phaseBefore: Float = buf[phase: 5]
buf.invalidate()
let p: SpectralPhaseShift = SpectralPhaseShift(fftSize: fftSize, shift: .deg90)
p.process(spectral: buf, engine: makeTestEngine())
#expect(buf[phase: 5] == phaseBefore)
}
}
@@ -0,0 +1,789 @@
// SpectralPlayBufTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("Spectral Frame Buffer Playback")
struct SpectralPlayBufferTests {
// MARK: - Helpers
private func makeFrameBuffer(fftSize: Int = 64, hopSize: Int = 16, frameCount: Int = 4) -> SpectralFrameBuffer {
SpectralFrameBuffer(fftSize: fftSize, hopSize: hopSize, frameCount: frameCount, sampleRate: 44100)
}
private func makeSpectralBuffer(fftSize: Int = 64) -> SpectralBuffer {
SpectralBuffer(fftSize: fftSize)
}
// MARK: - SpectralFrameBuffer — round-trip
@Test func frameBufferRoundTrip() {
let fb: SpectralFrameBuffer = makeFrameBuffer()
let src: SpectralBuffer = makeSpectralBuffer()
src.dcValue = 1.5
src.nyquistValue = -0.7
src[magnitude: 1] = 2.0
src[phase: 1] = Float.pi / 3
src[magnitude: 3] = 0.5
src[phase: 3] = -Float.pi / 6
fb.writeFrame(from: src, at: 0)
let dst: SpectralBuffer = makeSpectralBuffer()
fb.readFrame(into: dst, at: 0)
#expect(abs(dst.dcValue - 1.5) < 1e-6)
#expect(abs(dst.nyquistValue - (-0.7)) < 1e-6)
#expect(abs(dst[magnitude: 1] - 2.0) < 1e-6)
#expect(abs(dst[phase: 1] - Float.pi / 3) < 1e-6)
#expect(abs(dst[magnitude: 3] - 0.5) < 1e-6)
#expect(abs(dst[phase: 3] - (-Float.pi / 6)) < 1e-6)
}
@Test func frameBufferMultipleFramesRoundTrip() {
let fb: SpectralFrameBuffer = makeFrameBuffer(frameCount: 3)
for f: Int in 0..<3 {
let s: SpectralBuffer = makeSpectralBuffer()
s[magnitude: 1] = Float(f + 1) * 10.0
s[phase: 1] = Float(f) * 0.3
fb.writeFrame(from: s, at: f)
}
for f: Int in 0..<3 {
let d: SpectralBuffer = makeSpectralBuffer()
fb.readFrame(into: d, at: f)
#expect(abs(d[magnitude: 1] - Float(f + 1) * 10.0) < 1e-5)
#expect(abs(d[phase: 1] - Float(f) * 0.3) < 1e-5)
}
}
// MARK: - interpolateMagnitudes
@Test func interpolateMagnitudesFracZero() {
let fb: SpectralFrameBuffer = makeFrameBuffer(frameCount: 2)
let s0: SpectralBuffer = makeSpectralBuffer(); s0[magnitude: 1] = 2.0
let s1: SpectralBuffer = makeSpectralBuffer(); s1[magnitude: 1] = 6.0
fb.writeFrame(from: s0, at: 0)
fb.writeFrame(from: s1, at: 1)
let out: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: fb.halfSize)
out.initialize(repeating: 0, count: fb.halfSize)
defer { out.deinitialize(count: fb.halfSize); out.deallocate() }
fb.interpolateMagnitudes(into: out, frameA: 0, frameB: 1, frac: 0.0)
#expect(abs(out[1] - 2.0) < 1e-5) // frac=0 → frameA
}
@Test func interpolateMagnitudesFracOne() {
let fb: SpectralFrameBuffer = makeFrameBuffer(frameCount: 2)
let s0: SpectralBuffer = makeSpectralBuffer(); s0[magnitude: 1] = 2.0
let s1: SpectralBuffer = makeSpectralBuffer(); s1[magnitude: 1] = 6.0
fb.writeFrame(from: s0, at: 0)
fb.writeFrame(from: s1, at: 1)
let out: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: fb.halfSize)
out.initialize(repeating: 0, count: fb.halfSize)
defer { out.deinitialize(count: fb.halfSize); out.deallocate() }
fb.interpolateMagnitudes(into: out, frameA: 0, frameB: 1, frac: 1.0)
#expect(abs(out[1] - 6.0) < 1e-5) // frac=1 → frameB
}
@Test func interpolateMagnitudesFracHalf() {
let fb: SpectralFrameBuffer = makeFrameBuffer(frameCount: 2)
let s0: SpectralBuffer = makeSpectralBuffer(); s0[magnitude: 1] = 2.0
let s1: SpectralBuffer = makeSpectralBuffer(); s1[magnitude: 1] = 6.0
fb.writeFrame(from: s0, at: 0)
fb.writeFrame(from: s1, at: 1)
let out: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: fb.halfSize)
out.initialize(repeating: 0, count: fb.halfSize)
defer { out.deinitialize(count: fb.halfSize); out.deallocate() }
fb.interpolateMagnitudes(into: out, frameA: 0, frameB: 1, frac: 0.5)
#expect(abs(out[1] - 4.0) < 1e-5) // midpoint = 4
}
// MARK: - phaseDelta wrapping
@Test func phaseDeltaNoWrap() {
let fb: SpectralFrameBuffer = makeFrameBuffer(frameCount: 2)
let s0: SpectralBuffer = makeSpectralBuffer(); s0[phase: 1] = 0.5
let s1: SpectralBuffer = makeSpectralBuffer(); s1[phase: 1] = 1.5
fb.writeFrame(from: s0, at: 0)
fb.writeFrame(from: s1, at: 1)
let out: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: fb.halfSize)
out.initialize(repeating: 0, count: fb.halfSize)
defer { out.deinitialize(count: fb.halfSize); out.deallocate() }
fb.phaseDelta(frameA: 0, frameB: 1, into: out)
#expect(abs(out[1] - 1.0) < 1e-5)
}
@Test func phaseDeltaWrapsNegative() {
// phaseA = π-0.1, phaseB = -(π-0.1)
// raw delta = -(π-0.1)-(π-0.1) = -2(π-0.1) ≈ -6.08, wraps to ≈ +0.2
let fb: SpectralFrameBuffer = makeFrameBuffer(frameCount: 2)
let phaseA: Float = Float.pi - 0.1
let phaseB: Float = -(Float.pi - 0.1)
let s0: SpectralBuffer = makeSpectralBuffer(); s0[phase: 1] = phaseA
let s1: SpectralBuffer = makeSpectralBuffer(); s1[phase: 1] = phaseB
fb.writeFrame(from: s0, at: 0)
fb.writeFrame(from: s1, at: 1)
let out: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: fb.halfSize)
out.initialize(repeating: 0, count: fb.halfSize)
defer { out.deinitialize(count: fb.halfSize); out.deallocate() }
fb.phaseDelta(frameA: 0, frameB: 1, into: out)
// Expected: 0.2 (wrapped from ≈ -6.08 to ≈ +0.2)
#expect(abs(out[1] - 0.2) < 1e-4)
}
@Test func phaseDeltaWrapsPositive() {
// phaseA = -(π-0.1), phaseB = π-0.1
// raw delta = (π-0.1)-(-(π-0.1)) = 2(π-0.1) ≈ +6.08, wraps to ≈ -0.2
let fb: SpectralFrameBuffer = makeFrameBuffer(frameCount: 2)
let phaseA: Float = -(Float.pi - 0.1)
let phaseB: Float = Float.pi - 0.1
let s0: SpectralBuffer = makeSpectralBuffer(); s0[phase: 1] = phaseA
let s1: SpectralBuffer = makeSpectralBuffer(); s1[phase: 1] = phaseB
fb.writeFrame(from: s0, at: 0)
fb.writeFrame(from: s1, at: 1)
let out: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: fb.halfSize)
out.initialize(repeating: 0, count: fb.halfSize)
defer { out.deinitialize(count: fb.halfSize); out.deallocate() }
fb.phaseDelta(frameA: 0, frameB: 1, into: out)
// Expected: -0.2 (wrapped from ≈ +6.08 to ≈ -0.2)
#expect(abs(out[1] - (-0.2)) < 1e-4)
}
// MARK: - SpectralRecordBuffer
@Test func recordBufferStopsAtFrameCount() {
let fb: SpectralFrameBuffer = makeFrameBuffer(frameCount: 4)
let rec: SpectralRecordBuffer = SpectralRecordBuffer(frameBuffer: fb)
rec.run = true
let s: SpectralBuffer = makeSpectralBuffer()
for _ in 0..<4 {
rec.process(spectral: s, engine: makeTestEngine())
}
#expect(rec.run == false)
#expect(rec.framesRecorded == 4)
}
@Test func recordBufferLoops() {
let fb: SpectralFrameBuffer = makeFrameBuffer(frameCount: 4)
let rec: SpectralRecordBuffer = SpectralRecordBuffer(frameBuffer: fb, loop: true)
rec.run = true
let s: SpectralBuffer = makeSpectralBuffer()
for _ in 0..<4 { rec.process(spectral: s, engine: makeTestEngine()) }
// After 4 frames the buffer is full and wrapped; still running in loop mode.
#expect(rec.run == true)
// framesRecorded is monotonically increasing (4 total frames written so far).
#expect(rec.framesRecorded == 4)
// framesWritten reflects the full buffer (all 4 frames valid after the first pass).
#expect(fb.framesWritten == 4)
// One more frame — writes to frame 0 again (second pass), totalRecorded = 5.
rec.process(spectral: s, engine: makeTestEngine())
#expect(rec.run == true)
#expect(rec.framesRecorded == 5)
#expect(fb.framesWritten == 4)
}
@Test func recordBufferPassThrough() {
// Processor must not modify spectral content.
let fb: SpectralFrameBuffer = makeFrameBuffer(frameCount: 4)
let rec: SpectralRecordBuffer = SpectralRecordBuffer(frameBuffer: fb)
rec.run = true
let s: SpectralBuffer = makeSpectralBuffer()
s[magnitude: 1] = 3.0
rec.process(spectral: s, engine: makeTestEngine())
#expect(s[magnitude: 1] == 3.0) // unchanged
}
@Test func recordBufferDoesNothingWhenNotRunning() {
let fb: SpectralFrameBuffer = makeFrameBuffer(frameCount: 4)
let rec: SpectralRecordBuffer = SpectralRecordBuffer(frameBuffer: fb)
// run = false (default)
let s: SpectralBuffer = makeSpectralBuffer()
s[magnitude: 1] = 7.0
for _ in 0..<10 { rec.process(spectral: s, engine: makeTestEngine()) }
// Buffer should remain all zeros (no frames written)
let d: SpectralBuffer = makeSpectralBuffer()
fb.readFrame(into: d, at: 0)
#expect(d[magnitude: 1] == 0.0)
}
// MARK: - SpectralPlayBuffer — rate = 1.0
@Test func spectralPlayBufferRateOne() {
// Set up a 3-frame buffer with distinct magnitudes per frame.
let fftSize: Int = 64
let hopSize: Int = 16
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: fftSize, hopSize: hopSize, frameCount: 3, sampleRate: 44100)
for f: Int in 0..<3 {
let s: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
s[magnitude: 1] = Float(f + 1) * 1.0 // frame 0→1.0, frame 1→2.0, frame 2→3.0
fb.writeFrame(from: s, at: f)
}
let player: SpectralPlayBuffer = SpectralPlayBuffer(frameBuffer: fb, fftSize: fftSize, hopSize: hopSize, rate: 1.0)
let engine: SynthesisEngine = makeTestEngine(blockSize: hopSize)
let graph: SynthGraph = makeSynthGraph(engine: engine)
// First block — hop fires at sample hopSize; playPos was 0.0 → frame 0 mags
_ = player.calculatedSamples(graph: graph, count: hopSize)
#expect(abs(player.spectralBuffer[magnitude: 1] - 1.0) < 1e-5)
advanceBlock(engine)
let graph2: SynthGraph = makeSynthGraph(engine: engine)
// Second block — playPos was 1.0 → frame 1 mags
_ = player.calculatedSamples(graph: graph2, count: hopSize)
#expect(abs(player.spectralBuffer[magnitude: 1] - 2.0) < 1e-5)
}
// MARK: - SpectralPlayBuffer — rate = 0.5 (time-stretch)
@Test func spectralPlayBufferRateHalf() {
let fftSize: Int = 64
let hopSize: Int = 16
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: fftSize, hopSize: hopSize, frameCount: 4, sampleRate: 44100)
// frame 0: mag=2.0, frame 1: mag=6.0
let s0: SpectralBuffer = SpectralBuffer(fftSize: fftSize); s0[magnitude: 1] = 2.0
let s1: SpectralBuffer = SpectralBuffer(fftSize: fftSize); s1[magnitude: 1] = 6.0
fb.writeFrame(from: s0, at: 0)
fb.writeFrame(from: s1, at: 1)
let player: SpectralPlayBuffer = SpectralPlayBuffer(frameBuffer: fb, fftSize: fftSize, hopSize: hopSize, rate: 0.5)
let engine: SynthesisEngine = makeTestEngine(blockSize: hopSize)
// Block 1: playPos=0.0 → frame 0 mags (2.0); playPos advances to 0.5
let g1: SynthGraph = makeSynthGraph(engine: engine)
_ = player.calculatedSamples(graph: g1, count: hopSize)
#expect(abs(player.spectralBuffer[magnitude: 1] - 2.0) < 1e-5)
advanceBlock(engine)
// Block 2: playPos=0.5 → interpolated between frame 0 (2.0) and frame 1 (6.0) at frac=0.5 → 4.0
let g2: SynthGraph = makeSynthGraph(engine: engine)
_ = player.calculatedSamples(graph: g2, count: hopSize)
#expect(abs(player.spectralBuffer[magnitude: 1] - 4.0) < 1e-4)
}
// MARK: - SpectralPlayBuffer — rate = 2.0 (time-compress)
@Test func spectralPlayBufferRateDouble() {
let fftSize: Int = 64
let hopSize: Int = 16
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: fftSize, hopSize: hopSize, frameCount: 5, sampleRate: 44100)
for f: Int in 0..<5 {
let s: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
s[magnitude: 1] = Float(f + 1) * 1.0
fb.writeFrame(from: s, at: f)
}
// frame 0: 1.0, frame 1: 2.0, frame 2: 3.0, frame 3: 4.0, frame 4: 5.0
let player: SpectralPlayBuffer = SpectralPlayBuffer(frameBuffer: fb, fftSize: fftSize, hopSize: hopSize, rate: 2.0)
let engine: SynthesisEngine = makeTestEngine(blockSize: hopSize)
// Block 1: playPos=0.0 → frame 0 (1.0); playPos advances to 2.0
let g1: SynthGraph = makeSynthGraph(engine: engine)
_ = player.calculatedSamples(graph: g1, count: hopSize)
#expect(abs(player.spectralBuffer[magnitude: 1] - 1.0) < 1e-5)
advanceBlock(engine)
// Block 2: playPos=2.0 → frameA=2, frac=0.0 → frame 2 (3.0)
let g2: SynthGraph = makeSynthGraph(engine: engine)
_ = player.calculatedSamples(graph: g2, count: hopSize)
#expect(abs(player.spectralBuffer[magnitude: 1] - 3.0) < 1e-4)
}
// MARK: - SpectralPlayBuffer — loop
@Test func spectralPlayBufferLoops() {
let fftSize: Int = 64
let hopSize: Int = 16
let frameCount: Int = 3
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: fftSize, hopSize: hopSize, frameCount: frameCount, sampleRate: 44100)
for f: Int in 0..<frameCount {
let s: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
s[magnitude: 1] = Float(f + 1) * 1.0
fb.writeFrame(from: s, at: f)
}
let player: SpectralPlayBuffer = SpectralPlayBuffer(frameBuffer: fb, fftSize: fftSize, hopSize: hopSize, rate: 1.0, loop: true)
let engine: SynthesisEngine = makeTestEngine(blockSize: hopSize)
for blk: Int in 0..<6 {
let g: SynthGraph = makeSynthGraph(engine: engine)
_ = player.calculatedSamples(graph: g, count: hopSize)
let expectedFrame: Int = blk % frameCount
let expectedMag: Float = Float(expectedFrame + 1) * 1.0
#expect(abs(player.spectralBuffer[magnitude: 1] - expectedMag) < 1e-4)
if blk < 5 { advanceBlock(engine) }
}
// Loop mode: buffer stays valid.
#expect(player.spectralBuffer.isValid)
#expect(player.needsFree == false)
}
// MARK: - SpectralPlayBuffer — doneAction
@Test func spectralPlayBufferDoneActionFreeNode() {
let fftSize: Int = 64
let hopSize: Int = 16
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: fftSize, hopSize: hopSize, frameCount: 2, sampleRate: 44100)
let s: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
fb.writeFrame(from: s, at: 0)
fb.writeFrame(from: s, at: 1)
let player: SpectralPlayBuffer = SpectralPlayBuffer(frameBuffer: fb, fftSize: fftSize, hopSize: hopSize,
rate: 1.0, loop: false, doneAction: .freeNode)
let engine: SynthesisEngine = makeTestEngine(blockSize: hopSize)
// Block 1: playPos=0 → frame 0; advances to 1.0
let g1: SynthGraph = makeSynthGraph(engine: engine); _ = player.calculatedSamples(graph: g1, count: hopSize); advanceBlock(engine)
// Block 2: playPos=1 → frame 1; advances to 2.0 → end detected, _isDone = true, needsFree set
let g2: SynthGraph = makeSynthGraph(engine: engine); _ = player.calculatedSamples(graph: g2, count: hopSize); advanceBlock(engine)
// Block 3: _runHop sees _isDone → invalidates spectralBuffer
let g3: SynthGraph = makeSynthGraph(engine: engine); _ = player.calculatedSamples(graph: g3, count: hopSize)
#expect(player.needsFree == true)
#expect(player.spectralBuffer.isValid == false)
}
@Test func spectralPlayBufferReset() {
let fftSize: Int = 64
let hopSize: Int = 16
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: fftSize, hopSize: hopSize, frameCount: 4, sampleRate: 44100)
for f: Int in 0..<4 {
let s: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
s[magnitude: 1] = Float(f + 1) * 1.0
fb.writeFrame(from: s, at: f)
}
let player: SpectralPlayBuffer = SpectralPlayBuffer(frameBuffer: fb, fftSize: fftSize, hopSize: hopSize, rate: 1.0)
let engine: SynthesisEngine = makeTestEngine(blockSize: hopSize)
// Advance to frame 2
for blk: Int in 0..<3 {
let g: SynthGraph = makeSynthGraph(engine: engine); _ = player.calculatedSamples(graph: g, count: hopSize)
if blk < 2 { advanceBlock(engine) }
}
advanceBlock(engine)
// Reset to frame 0
player.reset(to: 0)
let gr: SynthGraph = makeSynthGraph(engine: engine)
_ = player.calculatedSamples(graph: gr, count: hopSize)
// Should output frame 0 mags again
#expect(abs(player.spectralBuffer[magnitude: 1] - 1.0) < 1e-4)
}
// MARK: - File I/O round-trip
@Test func fileIORoundTrip() throws {
let fb: SpectralFrameBuffer = makeFrameBuffer(fftSize: 64, hopSize: 16, frameCount: 3)
for f: Int in 0..<3 {
let s: SpectralBuffer = makeSpectralBuffer(fftSize: 64)
s.dcValue = Float(f) * 0.5
s.nyquistValue = Float(f) * -0.3
s[magnitude: 1] = Float(f + 1) * 2.0
s[phase: 1] = Float(f) * 0.5 - 0.5
fb.writeFrame(from: s, at: f)
}
let tmpURL: URL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("test_phase64.lbsf")
defer { try? FileManager.default.removeItem(at: tmpURL) }
try fb.write(to: tmpURL)
let loaded: SpectralFrameBuffer = try SpectralFrameBuffer.load(url: tmpURL)
#expect(loaded.fftSize == 64)
#expect(loaded.hopSize == 16)
#expect(loaded.frameCount == 3)
#expect(abs(loaded.sampleRate - 44100) < 1)
for f: Int in 0..<3 {
let d: SpectralBuffer = makeSpectralBuffer(fftSize: 64)
loaded.readFrame(into: d, at: f)
#expect(abs(d.dcValue - Float(f) * 0.5) < 1e-6)
#expect(abs(d.nyquistValue - Float(f) * -0.3) < 1e-6)
#expect(abs(d[magnitude: 1] - Float(f + 1) * 2.0) < 1e-5)
#expect(abs(d[phase: 1] - (Float(f) * 0.5 - 0.5)) < 1e-5)
}
}
// MARK: - File I/O errors
@Test func fileIOInvalidMagic() throws {
let tmpURL: URL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("test_bad_magic.lbsf")
defer { try? FileManager.default.removeItem(at: tmpURL) }
let garbage: Data = Data([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07])
try garbage.write(to: tmpURL)
#expect(throws: SpectralFileError.invalidMagic) {
_ = try SpectralFrameBuffer.load(url: tmpURL)
}
}
@Test func fileIOUnsupportedVersion() throws {
let tmpURL: URL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("test_bad_version.lbsf")
defer { try? FileManager.default.removeItem(at: tmpURL) }
// Write a valid 40-byte header with version = 99
var header: Data = Data(count: 40)
header[0] = 0x4C; header[1] = 0x42; header[2] = 0x53; header[3] = 0x46
let version: UInt32 = 99
withUnsafeBytes(of: version) { raw in
for i: Int in 0..<4 { header[4 + i] = raw[i] }
}
try header.write(to: tmpURL)
#expect(throws: SpectralFileError.unsupportedVersion(99)) {
_ = try SpectralFrameBuffer.load(url: tmpURL)
}
}
@Test func fileIOMissingFile() {
let missingURL: URL = URL(fileURLWithPath: "/tmp/definitely_does_not_exist_phase64.lbsf")
#expect(throws: SpectralFileError.cannotOpenFile) {
_ = try SpectralFrameBuffer.load(url: missingURL)
}
}
// MARK: - framesWritten
@Test func framesWrittenDefaultsToFrameCount() {
let fb: SpectralFrameBuffer = makeFrameBuffer(frameCount: 8)
#expect(fb.framesWritten == 8)
}
@Test func framesWrittenUpdatedBySpectralRecordBuffer() {
let fftSize: Int = 64
let hopSize: Int = 16
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: fftSize, hopSize: hopSize, frameCount: 4, sampleRate: 44100)
let recorder: SpectralRecordBuffer = SpectralRecordBuffer(frameBuffer: fb)
recorder.run = true
let spectral: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
recorder.process(spectral: spectral, engine: makeTestEngine()) // write frame 0 → _writePos=1
#expect(fb.framesWritten == 1)
recorder.process(spectral: spectral, engine: makeTestEngine()) // write frame 1 → _writePos=2
#expect(fb.framesWritten == 2)
recorder.process(spectral: spectral, engine: makeTestEngine())
recorder.process(spectral: spectral, engine: makeTestEngine()) // fills buffer → run=false, _writePos=4
#expect(fb.framesWritten == 4)
#expect(recorder.run == false)
}
// MARK: - interpolatePhases
@Test func interpolatePhasesHalfwayShortestPath() {
let fftSize: Int = 64
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: fftSize, hopSize: 16, frameCount: 2, sampleRate: 44100)
// bin 1 of frame 0: phase = π/2; bin 1 of frame 1: phase = -π/2
// Shortest path delta = -π (wrapped: the two paths are equal length, pick negative)
// For a clear test: frameA phase = 0, frameB phase = π/4 → delta = π/4 → at frac=0.5: π/8
let s0: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let s1: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
s0[phase: 1] = 0.0
s1[phase: 1] = Float.pi / 4
fb.writeFrame(from: s0, at: 0)
fb.writeFrame(from: s1, at: 1)
let dst: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: fftSize / 2)
defer { dst.deallocate() }
fb.interpolatePhases(into: dst, frameA: 0, frameB: 1, frac: 0.5)
let expected: Float = Float.pi / 8
#expect(abs(dst[1] - expected) < 1e-5)
}
@Test func interpolatePhasesWrapsCorrectly() {
let fftSize: Int = 64
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: fftSize, hopSize: 16, frameCount: 2, sampleRate: 44100)
// phaseA = π - 0.1, phaseB = -(π - 0.1)
// Raw diff = -2π + 0.2 → wraps to +0.2 (add 2π? no: d < -π → d += 2π → d = 0.2)
// Shortest-path lerp at frac=1.0 → phaseA + 1.0 * 0.2 = (π - 0.1) + 0.2 = π + 0.1 → not right
// Actually: at frac=0.0 → phaseA; at frac=1.0 → phaseA + delta = (π-0.1) + 0.2 = π+0.1
// Let's just verify the delta is wrapped to ≈ +0.2 rather than ≈ -6.08
let phaseA: Float = Float.pi - 0.1
let phaseB: Float = -(Float.pi - 0.1)
let s0: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let s1: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
s0[phase: 1] = phaseA
s1[phase: 1] = phaseB
fb.writeFrame(from: s0, at: 0)
fb.writeFrame(from: s1, at: 1)
let dst: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: fftSize / 2)
defer { dst.deallocate() }
// frac=0.0 → returns phaseA exactly
fb.interpolatePhases(into: dst, frameA: 0, frameB: 1, frac: 0.0)
#expect(abs(dst[1] - phaseA) < 1e-5)
// frac=0.5 → phaseA + 0.5*delta where delta ≈ +0.2
fb.interpolatePhases(into: dst, frameA: 0, frameB: 1, frac: 0.5)
let approxMidpoint: Float = phaseA + 0.5 * 0.2 // ≈ π - 0.1 + 0.1 = π
#expect(abs(dst[1] - approxMidpoint) < 0.01)
}
// MARK: - trimmed()
@Test func trimmedProducesCorrectFrameCount() {
let fftSize: Int = 64
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: fftSize, hopSize: 16, frameCount: 8, sampleRate: 44100)
// Manually set framesWritten to 3 via SpectralRecordBuffer
let recorder: SpectralRecordBuffer = SpectralRecordBuffer(frameBuffer: fb)
recorder.run = true
let spectral: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
for f: Int in 0..<3 {
spectral[magnitude: 1] = Float(f + 1)
recorder.process(spectral: spectral, engine: makeTestEngine())
}
recorder.run = false
let trimmed: SpectralFrameBuffer = fb.trimmed()
#expect(trimmed.frameCount == 3)
#expect(trimmed.framesWritten == 3)
// Verify frame data copied correctly
for f: Int in 0..<3 {
let d: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
trimmed.readFrame(into: d, at: f)
#expect(abs(d[magnitude: 1] - Float(f + 1)) < 1e-5)
}
}
@Test func trimmedDefaultFrameCountEqualsFrameCount() {
// Buffer not written by recorder → framesWritten == frameCount → trim is a full copy
let fb: SpectralFrameBuffer = makeFrameBuffer(frameCount: 4)
let s: SpectralBuffer = makeSpectralBuffer()
s[magnitude: 2] = 7.5
fb.writeFrame(from: s, at: 2)
let trimmed: SpectralFrameBuffer = fb.trimmed()
#expect(trimmed.frameCount == 4)
let d: SpectralBuffer = makeSpectralBuffer()
trimmed.readFrame(into: d, at: 2)
#expect(abs(d[magnitude: 2] - 7.5) < 1e-5)
}
// MARK: - write(to:) uses framesWritten
@Test func fileIOWritesOnlyFramesWritten() throws {
let tmpURL: URL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("test_frames_written.lbsf")
defer { try? FileManager.default.removeItem(at: tmpURL) }
let fftSize: Int = 64
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: fftSize, hopSize: 16, frameCount: 8, sampleRate: 44100)
let recorder: SpectralRecordBuffer = SpectralRecordBuffer(frameBuffer: fb)
recorder.run = true
let spectral: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
for f: Int in 0..<3 {
spectral[magnitude: 1] = Float(f + 1) * 10.0
recorder.process(spectral: spectral, engine: makeTestEngine())
}
recorder.run = false
// framesWritten == 3 even though frameCount == 8
try fb.write(to: tmpURL)
let loaded: SpectralFrameBuffer = try SpectralFrameBuffer.load(url: tmpURL)
#expect(loaded.frameCount == 3)
#expect(loaded.fftSize == fftSize)
for f: Int in 0..<3 {
let d: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
loaded.readFrame(into: d, at: f)
#expect(abs(d[magnitude: 1] - Float(f + 1) * 10.0) < 1e-5)
}
}
// MARK: - SpectralPlayBuffer startPos
@Test func spectralPlayBufferStartPos() {
let fftSize: Int = 64
let hopSize: Int = 16
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: fftSize, hopSize: hopSize, frameCount: 4, sampleRate: 44100)
for f: Int in 0..<4 {
let s: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
s[magnitude: 1] = Float(f + 1) * 1.0 // frame 0→1.0, 1→2.0, 2→3.0, 3→4.0
fb.writeFrame(from: s, at: f)
}
// startPos=2.0 → first hop reads frame 2 (mag=3.0)
let player: SpectralPlayBuffer = SpectralPlayBuffer(frameBuffer: fb, fftSize: fftSize, hopSize: hopSize,
rate: 1.0, startPos: 2.0)
let engine: SynthesisEngine = makeTestEngine(blockSize: hopSize)
let graph: SynthGraph = makeSynthGraph(engine: engine)
_ = player.calculatedSamples(graph: graph, count: hopSize)
#expect(abs(player.spectralBuffer[magnitude: 1] - 3.0) < 1e-5)
}
// MARK: - SpectralBufferRead
@Test func spectralBufferReadPositionZero() {
let fftSize: Int = 64
let hopSize: Int = 16
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: fftSize, hopSize: hopSize, frameCount: 4, sampleRate: 44100)
for f: Int in 0..<4 {
let s: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
s[magnitude: 1] = Float(f + 1) * 1.0
fb.writeFrame(from: s, at: f)
}
// position=0.0 → first frame (mag=1.0)
let reader: SpectralBufferRead = SpectralBufferRead(frameBuffer: fb, fftSize: fftSize, hopSize: hopSize, position: 0.0)
let engine: SynthesisEngine = makeTestEngine(blockSize: hopSize)
let graph: SynthGraph = makeSynthGraph(engine: engine)
_ = reader.calculatedSamples(graph: graph, count: hopSize)
#expect(abs(reader.spectralBuffer[magnitude: 1] - 1.0) < 1e-5)
}
@Test func spectralBufferReadPositionOne() {
let fftSize: Int = 64
let hopSize: Int = 16
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: fftSize, hopSize: hopSize, frameCount: 4, sampleRate: 44100)
for f: Int in 0..<4 {
let s: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
s[magnitude: 1] = Float(f + 1) * 1.0
fb.writeFrame(from: s, at: f)
}
// position=1.0 → last frame (frameCount-1=3, mag=4.0)
let reader: SpectralBufferRead = SpectralBufferRead(frameBuffer: fb, fftSize: fftSize, hopSize: hopSize, position: 1.0)
let engine: SynthesisEngine = makeTestEngine(blockSize: hopSize)
let graph: SynthGraph = makeSynthGraph(engine: engine)
_ = reader.calculatedSamples(graph: graph, count: hopSize)
#expect(abs(reader.spectralBuffer[magnitude: 1] - 4.0) < 1e-5)
}
@Test func spectralBufferReadPositionMidpoint() {
let fftSize: Int = 64
let hopSize: Int = 16
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: fftSize, hopSize: hopSize, frameCount: 3, sampleRate: 44100)
// frame 0: mag=2.0, frame 1: mag=6.0, frame 2: mag=10.0
for f: Int in 0..<3 {
let s: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
s[magnitude: 1] = Float(f * 4 + 2)
fb.writeFrame(from: s, at: f)
}
// position=0.5 → playPos = 0.5 * (3-1) = 1.0 → frameA=1, frac=0.0 → mag=6.0
let reader: SpectralBufferRead = SpectralBufferRead(frameBuffer: fb, fftSize: fftSize, hopSize: hopSize, position: 0.5)
let engine: SynthesisEngine = makeTestEngine(blockSize: hopSize)
let graph: SynthGraph = makeSynthGraph(engine: engine)
_ = reader.calculatedSamples(graph: graph, count: hopSize)
#expect(abs(reader.spectralBuffer[magnitude: 1] - 6.0) < 1e-4)
}
@Test func spectralBufferReadClampsOutOfRange() {
let fftSize: Int = 64
let hopSize: Int = 16
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: fftSize, hopSize: hopSize, frameCount: 4, sampleRate: 44100)
for f: Int in 0..<4 {
let s: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
s[magnitude: 1] = Float(f + 1)
fb.writeFrame(from: s, at: f)
}
// position=2.5 (> 1.0) → clamped to 1.0 → last frame (mag=4.0)
let reader: SpectralBufferRead = SpectralBufferRead(frameBuffer: fb, fftSize: fftSize, hopSize: hopSize, position: 2.5)
let engine: SynthesisEngine = makeTestEngine(blockSize: hopSize)
let graph: SynthGraph = makeSynthGraph(engine: engine)
_ = reader.calculatedSamples(graph: graph, count: hopSize)
#expect(abs(reader.spectralBuffer[magnitude: 1] - 4.0) < 1e-5)
}
@Test func spectralBufferReadUsesFramesWritten() {
let fftSize: Int = 64
let hopSize: Int = 16
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: fftSize, hopSize: hopSize, frameCount: 8, sampleRate: 44100)
let recorder: SpectralRecordBuffer = SpectralRecordBuffer(frameBuffer: fb)
recorder.run = true
let spectral: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
for f: Int in 0..<4 {
spectral[magnitude: 1] = Float(f + 1)
recorder.process(spectral: spectral, engine: makeTestEngine())
}
recorder.run = false
// framesWritten == 4; frames 4-7 contain zeros
// position=1.0 → last *recorded* frame (index 3, mag=4.0), not frame 7 (mag=0.0)
let reader: SpectralBufferRead = SpectralBufferRead(frameBuffer: fb, fftSize: fftSize, hopSize: hopSize, position: 1.0)
let engine: SynthesisEngine = makeTestEngine(blockSize: hopSize)
let graph: SynthGraph = makeSynthGraph(engine: engine)
_ = reader.calculatedSamples(graph: graph, count: hopSize)
#expect(abs(reader.spectralBuffer[magnitude: 1] - 4.0) < 1e-5)
}
@Test func spectralBufferReadOutputIsSilent() {
let fftSize: Int = 64
let hopSize: Int = 16
let fb: SpectralFrameBuffer = makeFrameBuffer(fftSize: fftSize, hopSize: hopSize, frameCount: 4)
let reader: SpectralBufferRead = SpectralBufferRead(frameBuffer: fb, fftSize: fftSize, hopSize: hopSize)
let engine: SynthesisEngine = makeTestEngine(blockSize: hopSize)
let graph: SynthGraph = makeSynthGraph(engine: engine)
let result: [[Double]] = reader.calculatedSamples(graph: graph, count: hopSize)
#expect(result[0].prefix(hopSize).allSatisfy { $0 == 0.0 })
}
// MARK: - SpectralFrameBuffer duration / phasorFrequency
@Test func spectralFrameBufferDurationFullBuffer() {
let hopSize: Int = 512
let frameCount: Int = 100
let sr: Double = 44100.0
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: 1024, hopSize: hopSize,
frameCount: frameCount, sampleRate: sr)
let expected: Double = Double(hopSize * frameCount) / sr
#expect(abs(fb.duration - expected) < 1e-12)
}
@Test func spectralFrameBufferDurationPartialBuffer() {
let hopSize: Int = 256
let frameCount: Int = 50
let sr: Double = 48000.0
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: 512, hopSize: hopSize,
frameCount: frameCount, sampleRate: sr)
// Simulate partial recording — framesWritten defaults to frameCount, override via _framesWritten
// Default: framesWritten == frameCount, so duration uses full count
let expected: Double = Double(hopSize * frameCount) / sr
#expect(abs(fb.duration - expected) < 1e-12)
}
@Test func spectralFrameBufferDurationZeroWhenSampleRateZero() {
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: 64, hopSize: 16,
frameCount: 8, sampleRate: 0)
#expect(fb.duration == 0.0)
#expect(fb.phasorFrequency == nil)
}
@Test func spectralFrameBufferPhasorFrequencyIsReciprocal() {
let hopSize: Int = 512
let frameCount: Int = 86 // ~1 second at 44100 Hz
let sr: Double = 44100.0
let fb: SpectralFrameBuffer = SpectralFrameBuffer(fftSize: 1024, hopSize: hopSize,
frameCount: frameCount, sampleRate: sr)
let dur: Double = Double(hopSize * frameCount) / sr
#expect(abs(fb.phasorFrequency! - (1.0 / dur)) < 1e-12)
}
}
@@ -0,0 +1,313 @@
// SpectralPolarClosureTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpectralPolarClosure")
struct SpectralPolarClosureTests {
// MARK: - Helpers
private static func fillKnownPolar(_ buf: SpectralBuffer) {
buf.dcValue = 0.5
buf.nyquistValue = -0.25
let halfSize: Int = buf.fftSize / 2
for k: Int in 1..<halfSize {
buf[magnitude: k] = Float(k) * 0.01
buf[phase: k] = 0.3
}
}
// MARK: - Basic structural tests
@Test func identityClosureDoesNotMutate() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillKnownPolar(buf)
let proc: SpectralPolarClosure = SpectralPolarClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { _ in }
proc.process(spectral: buf, engine: makeTestEngine())
let halfSize: Int = fftSize / 2
for k: Int in 1..<halfSize {
#expect(abs(buf[magnitude: k] - Float(k) * 0.01) < 1e-6,
"magnitude of bin \(k) mutated by identity closure")
#expect(abs(buf[phase: k] - 0.3) < 1e-6,
"phase of bin \(k) mutated by identity closure")
}
#expect(abs(buf.dcValue - 0.5) < 1e-6)
#expect(abs(buf.nyquistValue - (-0.25)) < 1e-6)
}
@Test func closureReceivesCorrectBinCount() {
let fftSize: Int = 128
var observedBinCount: Int = 0
let proc: SpectralPolarClosure = SpectralPolarClosure(
fftSize: fftSize, hopSize: 64, sampleRate: 44100
) { ctx in
observedBinCount = ctx.binCount
}
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
proc.process(spectral: buf, engine: makeTestEngine())
// binCount = fftSize/2 - 1
#expect(observedBinCount == fftSize / 2 - 1)
}
@Test func closureReceivesCorrectMetadata() {
let fftSize: Int = 256
let hopSize: Int = 64
let sampleRate: Double = 48000.0
var seenFFTSize: Int = 0
var seenHopSize: Int = 0
var seenSampleRate: Double = 0.0
let proc: SpectralPolarClosure = SpectralPolarClosure(
fftSize: fftSize, hopSize: hopSize, sampleRate: sampleRate
) { ctx in
seenFFTSize = ctx.fftSize
seenHopSize = ctx.hopSize
seenSampleRate = ctx.sampleRate
}
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
proc.process(spectral: buf, engine: makeTestEngine())
#expect(seenFFTSize == fftSize)
#expect(seenHopSize == hopSize)
#expect(seenSampleRate == sampleRate)
}
// MARK: - Magnitude mutation
@Test func magnitudeHalvingDropsAllBins() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillKnownPolar(buf)
let originalMags: [Float] = (1..<(fftSize / 2)).map { k in buf[magnitude: k] }
let proc: SpectralPolarClosure = SpectralPolarClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
for i: Int in 0..<ctx.binCount {
ctx.magnitudes[i] *= 0.5
}
}
proc.process(spectral: buf, engine: makeTestEngine())
for (i, k) in (1..<(fftSize / 2)).enumerated() {
#expect(abs(buf[magnitude: k] - originalMags[i] * 0.5) < 1e-6,
"bin \(k) magnitude not halved")
}
}
@Test func closureCanMutateDCValue() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
buf.dcValue = 2.0
let proc: SpectralPolarClosure = SpectralPolarClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
ctx.dcValue.pointee *= 2
}
proc.process(spectral: buf, engine: makeTestEngine())
#expect(abs(buf.dcValue - 4.0) < 1e-6)
}
@Test func closureCanMutateNyquistValue() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
buf.nyquistValue = -1.0
let proc: SpectralPolarClosure = SpectralPolarClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
ctx.nyquistValue.pointee = 3.0
}
proc.process(spectral: buf, engine: makeTestEngine())
#expect(abs(buf.nyquistValue - 3.0) < 1e-6)
}
// MARK: - Phase mutation
@Test func phaseMutationPersists() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let halfSize: Int = fftSize / 2
for k: Int in 1..<halfSize { buf[phase: k] = 0.0 }
let proc: SpectralPolarClosure = SpectralPolarClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
for i: Int in 0..<ctx.binCount {
ctx.phases[i] = Float.pi / 4
}
}
proc.process(spectral: buf, engine: makeTestEngine())
let expected: Float = Float.pi / 4
for k: Int in 1..<halfSize {
#expect(abs(buf[phase: k] - expected) < 1e-6,
"phase of bin \(k) not written: \(buf[phase: k])")
}
}
// MARK: - Frame index
@Test func frameIndexIncrementsAcrossHops() {
let fftSize: Int = 64
var observedIndices: [Int] = []
let proc: SpectralPolarClosure = SpectralPolarClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
observedIndices.append(ctx.frameIndex)
}
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
for _ in 0..<5 {
proc.process(spectral: buf, engine: makeTestEngine())
}
#expect(observedIndices == [0, 1, 2, 3, 4])
}
// MARK: - Guard conditions
@Test func fftSizeMismatchIsBypassed() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: 128) // different fftSize
buf[magnitude: 1] = 99.0
let proc: SpectralPolarClosure = SpectralPolarClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
for i: Int in 0..<ctx.binCount { ctx.magnitudes[i] = 0 }
}
proc.process(spectral: buf, engine: makeTestEngine())
// Buffer untouched — fftSize mismatch bypasses process.
#expect(buf[magnitude: 1] == 99.0)
}
@Test func invalidBufferIsBypassed() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
buf[magnitude: 4] = 5.0
buf.invalidate()
let proc: SpectralPolarClosure = SpectralPolarClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
for i: Int in 0..<ctx.binCount { ctx.magnitudes[i] = 0 }
}
proc.process(spectral: buf, engine: makeTestEngine())
#expect(buf[magnitude: 4] == 5.0)
}
// MARK: - SpectralChain integration
/// Polar identity closure: round-trip through SpectralChain.Audio
/// should be equivalent to no-processor path within round-trip tolerance.
@Test func identityClosureRoundTripEquivalentToNoProcessor() throws {
let fftSize: Int = 64
let hopSize: Int = 32
let blockSize: Int = hopSize
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
defer { engine.stop() }
let dcInput: Double = 0.4
let chainNone: SpectralChain.Audio = SpectralChain.Audio(input: dcInput, fftSize: fftSize, hopSize: hopSize)
let identity: SpectralPolarClosure = SpectralPolarClosure(
fftSize: fftSize, hopSize: hopSize, sampleRate: engine.sampleRate
) { _ in }
let chainIdentity: SpectralChain.Audio = SpectralChain.Audio(
input: dcInput, fftSize: fftSize, hopSize: hopSize, stages: [.mono(identity)]
)
let warmUpBlocks: Int = 4
let measureBlocks: Int = 4
var sumNone: Double = 0.0
var sumId: Double = 0.0
for block: Int in 0..<(warmUpBlocks + measureBlocks) {
let g: SynthGraph = makeSynthGraph(engine: engine)
let outNone: [[Double]] = chainNone.calculatedSamples(graph: g, count: blockSize)
let outId: [[Double]] = chainIdentity.calculatedSamples(graph: g, count: blockSize)
if block >= warmUpBlocks {
for i: Int in 0..<blockSize {
sumNone += outNone[0][i]
sumId += outId[0][i]
}
}
advanceBlock(engine)
}
let n: Double = Double(measureBlocks * blockSize)
let meanNone: Double = sumNone / n
let meanId: Double = sumId / n
// Both chains should produce the same mean level; the identity closure
// must not shift amplitude. Tolerance 0.01 is tighter than DCmatch tolerance.
#expect(abs(meanNone - meanId) < 0.01,
"Identity closure shifted mean from \(meanNone) to \(meanId)")
}
/// Half-magnitude polar closure: output drops by 6 dB ±0.1 dB.
@Test func halfMagnitudeDropsSixDB() throws {
let fftSize: Int = 64
let hopSize: Int = 32
let blockSize: Int = hopSize
let sineFreq: Double = 440.0
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
defer { engine.stop() }
let osc: OscSin.Audio = OscSin.Audio(freq: sineFreq)
let chainFull: SpectralChain.Audio = SpectralChain.Audio(input: osc, fftSize: fftSize, hopSize: hopSize)
let osc2: OscSin.Audio = OscSin.Audio(freq: sineFreq)
let halver: SpectralPolarClosure = SpectralPolarClosure(
fftSize: fftSize, hopSize: hopSize, sampleRate: engine.sampleRate
) { ctx in
for i: Int in 0..<ctx.binCount { ctx.magnitudes[i] *= 0.5 }
ctx.dcValue.pointee *= 0.5
ctx.nyquistValue.pointee *= 0.5
}
let chainHalf: SpectralChain.Audio = SpectralChain.Audio(
input: osc2, fftSize: fftSize, hopSize: hopSize, stages: [.mono(halver)]
)
let warmUpBlocks: Int = 4
let measureBlocks: Int = 8
var rmsFull: Double = 0.0
var rmsHalf: Double = 0.0
for block: Int in 0..<(warmUpBlocks + measureBlocks) {
let g: SynthGraph = makeSynthGraph(engine: engine)
let outFull: [[Double]] = chainFull.calculatedSamples(graph: g, count: blockSize)
let outHalf: [[Double]] = chainHalf.calculatedSamples(graph: g, count: blockSize)
if block >= warmUpBlocks {
for i: Int in 0..<blockSize {
let f: Double = outFull[0][i]
let h: Double = outHalf[0][i]
rmsFull += f * f
rmsHalf += h * h
}
}
advanceBlock(engine)
}
let n: Double = Double(measureBlocks * blockSize)
let rmsFullVal: Double = (rmsFull / n).squareRoot()
let rmsHalfVal: Double = (rmsHalf / n).squareRoot()
guard rmsFullVal > 1e-6 else { return } // skip if no signal
let dbDrop: Double = 20 * log10(rmsHalfVal / rmsFullVal)
// Expect ≈ −6 dB; allow ±1 dB for round-trip tolerance.
#expect(abs(dbDrop - (-6.0)) < 1.0,
"Expected ≈ -6 dB drop, got \(dbDrop) dB")
}
}
@@ -0,0 +1,66 @@
// SpectralProcessor2Tests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpectralProcessor2 dispatch")
struct SpectralProcessor2Tests {
/// Counts calls and records the buffer references it received. Lets us
/// verify SpectralChain.Audio is dispatching with the correct host +
/// side-chain spectral buffers.
private final class CountingDualProcessor: SpectralProcessor2 {
var callCount: Int = 0
var lastHost: SpectralBuffer?
var lastSide: SpectralBuffer?
func process(spectral: SpectralBuffer,
sideChain: SpectralBuffer, engine: SynthesisEngine) {
callCount += 1
lastHost = spectral
lastSide = sideChain
}
}
@Test func dualProcessorReceivesHostAndSideChainBuffers() throws {
let fftSize: Int = 64
let hopSize: Int = 32
let blockSize: Int = hopSize
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
defer { engine.stop() }
let sideAnalysis: SpectralChain.Audio = SpectralChain.Audio(input: Double(1.0),
fftSize: fftSize, hopSize: hopSize,
analyzeOnly: true)
let counter: SpectralProcessor2Tests.CountingDualProcessor = CountingDualProcessor()
let mainAnalysis: SpectralChain.Audio = SpectralChain.Audio(
input: Double(0.5),
fftSize: fftSize, hopSize: hopSize,
stages: [.dual(counter, sideChain: sideAnalysis)],
analyzeOnly: true
)
// Run several blocks. Side-chain must be evaluated before main so its
// spectralBuffer is fresh when the main hop fires.
for _ in 0..<4 {
let g: SynthGraph = makeSynthGraph(engine: engine)
_ = sideAnalysis.calculatedSamples(graph: g, count: blockSize)
_ = mainAnalysis.calculatedSamples(graph: g, count: blockSize)
advanceBlock(engine)
}
#expect(counter.callCount > 0,
"Dual processor should be called at least once after several hops")
#expect(counter.lastHost === mainAnalysis.spectralBuffer,
"Host buffer should be the main analysis spectralBuffer")
#expect(counter.lastSide === sideAnalysis.spectralBuffer,
"Side-chain buffer should be the side analysis spectralBuffer")
}
}
@@ -0,0 +1,142 @@
// SpectralStereoDiffuseTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpectralStereoDiffuse — shape") struct SpectralStereoDiffuseShapeTests {
@Test func outputChannelCountIsTwo() {
let diff: SpectralStereoDiffuse = SpectralStereoDiffuse(amount: 0.5)
#expect(diff.outputChannelCount == 2)
}
@Test func defaultAmountIsHalf() {
let diff: SpectralStereoDiffuse = SpectralStereoDiffuse()
#expect(abs(diff.amount - 0.5) < 1e-9)
}
@Test func amountClampsTo01() {
let diff: SpectralStereoDiffuse = SpectralStereoDiffuse(amount: 0.5)
diff.amount = -1.0
#expect(diff.amount == 0.0)
diff.amount = 5.0
#expect(diff.amount == 1.0)
}
}
@MainActor
@Suite("SpectralStereoDiffuse — magnitude conservation + bypass") struct SpectralStereoDiffuseMagnitudeTests {
@Test func amountZeroIsExactBypass() {
let fftSize: Int = 64
let source: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let destA: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let destB: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
// Seed source with deterministic pattern.
source.dcValue = 0.7
source.nyquistValue = -0.3
for bin: Int in 1..<(source.fftSize / 2) {
source[magnitude: bin] = Float(bin) * 0.1
source[phase: bin] = Float(bin) * 0.05 - 0.7
}
let diff: SpectralStereoDiffuse = SpectralStereoDiffuse(amount: 0.0, seed: 1)
diff.process(source: source, into: destA, channel: 0)
diff.process(source: source, into: destB, channel: 1)
#expect(destA.dcValue == source.dcValue)
#expect(destA.nyquistValue == source.nyquistValue)
#expect(destB.dcValue == source.dcValue)
#expect(destB.nyquistValue == source.nyquistValue)
for bin: Int in 1..<(source.fftSize / 2) {
#expect(destA.magnitude(at: bin) == source.magnitude(at: bin))
#expect(destB.magnitude(at: bin) == source.magnitude(at: bin))
#expect(abs(destA.phase(at: bin) - source.phase(at: bin)) < 1e-6)
#expect(abs(destB.phase(at: bin) - source.phase(at: bin)) < 1e-6)
}
}
@Test func magnitudesPreservedAcrossAmountRange() {
let fftSize: Int = 64
let source: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let destA: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let destB: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
for bin: Int in 1..<(source.fftSize / 2) {
source[magnitude: bin] = Float(bin) * 0.05 + 0.01
source[phase: bin] = Float(bin) * 0.03
}
for amt: Double in [0.0, 0.25, 0.5, 0.75, 1.0] {
let diff: SpectralStereoDiffuse = SpectralStereoDiffuse(amount: amt, seed: 99)
diff.process(source: source, into: destA, channel: 0)
diff.process(source: source, into: destB, channel: 1)
for bin: Int in 1..<(source.fftSize / 2) {
#expect(destA.magnitude(at: bin) == source.magnitude(at: bin),
"amount=\(amt) bin=\(bin) ch0 magnitude must equal source")
#expect(destB.magnitude(at: bin) == source.magnitude(at: bin),
"amount=\(amt) bin=\(bin) ch1 magnitude must equal source")
}
}
}
}
@MainActor
@Suite("SpectralStereoDiffuse — channel decorrelation") struct SpectralStereoDiffuseDecorrelationTests {
@Test func channelsDifferAtAmountOne() {
let fftSize: Int = 256
let source: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let destA: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let destB: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
for bin: Int in 1..<(source.fftSize / 2) {
source[magnitude: bin] = 1.0
source[phase: bin] = 0.0
}
let diff: SpectralStereoDiffuse = SpectralStereoDiffuse(amount: 1.0, seed: 12345)
diff.process(source: source, into: destA, channel: 0)
diff.process(source: source, into: destB, channel: 1)
var matches: Int = 0
for bin: Int in 1..<(source.fftSize / 2) {
if abs(destA.phase(at: bin) - destB.phase(at: bin)) < 1e-3 {
matches += 1
}
}
// Expect almost no bin-by-bin phase agreement between the two
// anti-correlated PRNG streams across all bins.
let total: Int = source.binCount - 1
let matchRatio: Double = Double(matches) / Double(total)
#expect(matchRatio < 0.05,
"channels should rarely agree on phase at amount=1; got \(matchRatio)")
}
@Test func determinismGivenFixedSeed() {
let fftSize: Int = 128
let source: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let destA1: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let destA2: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
for bin: Int in 1..<(source.fftSize / 2) {
source[magnitude: bin] = Float(bin) * 0.1
source[phase: bin] = 0
}
// Two independent processors with the same seed produce identical
// output on channel 0.
let diff1: SpectralStereoDiffuse = SpectralStereoDiffuse(amount: 0.75, seed: 0xDEADBEEF)
let diff2: SpectralStereoDiffuse = SpectralStereoDiffuse(amount: 0.75, seed: 0xDEADBEEF)
diff1.process(source: source, into: destA1, channel: 0)
diff2.process(source: source, into: destA2, channel: 0)
for bin: Int in 1..<(source.fftSize / 2) {
#expect(abs(destA1.phase(at: bin) - destA2.phase(at: bin)) < 1e-6,
"fixed-seed determinism failed at bin \(bin)")
}
}
}
@@ -0,0 +1,155 @@
// SpectralTiltTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpectralTilt")
struct SpectralTiltTests {
private static let sampleRate: Double = 48_000
private static func fillFlat(_ buf: SpectralBuffer) {
buf.dcValue = 1.0
buf.nyquistValue = 1.0
let halfSize: Int = buf.fftSize / 2
for k: Int in 1..<halfSize {
buf[magnitude: k] = 1.0
buf[phase: k] = 0.4
}
}
/// Bin index nearest to a given frequency.
private static func bin(_ hz: Double, fftSize: Int) -> Int {
let halfSize: Int = fftSize / 2
let f: Double = hz * Double(fftSize) / sampleRate
return min(halfSize - 1, max(1, Int(f.rounded())))
}
@Test func plus6dBPerOctaveDoublesAtTwoTimesPivot() {
let fftSize: Int = 1024
let pivotHz: Double = 2_000
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillFlat(buf)
let t: SpectralTilt = SpectralTilt(
fftSize: fftSize,
sampleRate: Self.sampleRate,
slopeDBPerOctave: 6.0,
pivotHz: pivotHz
)
t.process(spectral: buf, engine: makeTestEngine())
let bPivot: Int = Self.bin(pivotHz, fftSize: fftSize)
let bDouble: Int = Self.bin(pivotHz * 2.0, fftSize: fftSize)
// At pivot: gain ≈ 1.
#expect(abs(buf[magnitude: bPivot] - 1.0) < 0.01,
"pivot gain \(buf[magnitude: bPivot]) ≠ 1.0")
// At 2× pivot: gain ≈ 2.
#expect(abs(buf[magnitude: bDouble] - 2.0) < 0.05,
"2× pivot gain \(buf[magnitude: bDouble]) ≠ 2.0")
}
@Test func minus6dBPerOctaveHalvesAtTwoTimesPivot() {
let fftSize: Int = 1024
let pivotHz: Double = 2_000
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillFlat(buf)
let t: SpectralTilt = SpectralTilt(
fftSize: fftSize,
sampleRate: Self.sampleRate,
slopeDBPerOctave: -6.0,
pivotHz: pivotHz
)
t.process(spectral: buf, engine: makeTestEngine())
let bDouble: Int = Self.bin(pivotHz * 2.0, fftSize: fftSize)
#expect(abs(buf[magnitude: bDouble] - 0.5) < 0.02,
"2× pivot gain \(buf[magnitude: bDouble]) ≠ 0.5")
}
@Test func zeroSlopeIsUnityEverywhere() {
let fftSize: Int = 256
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillFlat(buf)
let t: SpectralTilt = SpectralTilt(
fftSize: fftSize,
sampleRate: Self.sampleRate,
slopeDBPerOctave: 0.0,
pivotHz: 1_000
)
t.process(spectral: buf, engine: makeTestEngine())
let halfSize: Int = fftSize / 2
for k: Int in 1..<halfSize {
#expect(abs(buf[magnitude: k] - 1.0) < 1e-5,
"bin \(k) gain \(buf[magnitude: k]) ≠ 1.0 with slope=0")
}
#expect(abs(buf.dcValue - 1.0) < 1e-5)
#expect(abs(buf.nyquistValue - 1.0) < 1e-5)
}
@Test func phaseUntouched() {
let fftSize: Int = 256
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillFlat(buf)
let t: SpectralTilt = SpectralTilt(
fftSize: fftSize,
sampleRate: Self.sampleRate,
slopeDBPerOctave: 6.0,
pivotHz: 2_000
)
t.process(spectral: buf, engine: makeTestEngine())
let halfSize: Int = fftSize / 2
for k: Int in 1..<halfSize {
#expect(buf[phase: k] == 0.4)
}
}
@Test func nyquistGainAppliedToSignedValue() {
let fftSize: Int = 256
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillFlat(buf)
buf.nyquistValue = -2.0
let t: SpectralTilt = SpectralTilt(
fftSize: fftSize,
sampleRate: Self.sampleRate,
slopeDBPerOctave: -6.0,
pivotHz: 1_000
)
t.process(spectral: buf, engine: makeTestEngine())
// Nyquist freq for 256-bin FFT @ 48k = 24000 Hz; pivot 1000.
// 24000 / 1000 = 24, log2(24) ≈ 4.585 octaves; -6 dB/oct → 0.5^4.585 ≈ 0.0414.
let expected: Float = -2.0 * Float(pow(0.5, log2(24.0)))
#expect(abs(buf.nyquistValue - expected) < 1e-3,
"Nyquist gain incorrect: got \(buf.nyquistValue), expected \(expected)")
}
@Test func invalidBufferIsBypassed() {
let fftSize: Int = 256
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillFlat(buf)
buf.invalidate()
let t: SpectralTilt = SpectralTilt(
fftSize: fftSize,
sampleRate: Self.sampleRate,
slopeDBPerOctave: 6.0,
pivotHz: 1_000
)
t.process(spectral: buf, engine: makeTestEngine())
#expect(buf[magnitude: 8] == 1.0)
}
}
@@ -0,0 +1,129 @@
// SpectrumCaptureTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpectrumCapture")
final class SpectrumCaptureTests {
// MARK: - Init
@Test func initBinCount() {
let capture: SpectrumCapture = SpectrumCapture(fftSize: 1024)
#expect(capture.fftSize == 1024)
#expect(capture.binCount == 513) // 1024/2 + 1
}
@Test func initBinCountDefaultFFTSize() {
let capture: SpectrumCapture = SpectrumCapture()
#expect(capture.fftSize == 2048)
#expect(capture.binCount == 1025)
}
// MARK: - Initial snapshot
@Test func snapshotInitiallyZero() {
let capture: SpectrumCapture = SpectrumCapture(fftSize: 512)
let snap: [Float] = capture.snapshot()
#expect(snap.count == 257) // 512/2 + 1
#expect(snap.allSatisfy { $0 == 0 })
}
// MARK: - Round-trip through process()
@Test func processUpdatesComplexBins() {
let fftSize: Int = 512
let capture: SpectrumCapture = SpectrumCapture(fftSize: fftSize)
let spectral: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
spectral[magnitude: 1] = 0.5
spectral[magnitude: 10] = 1.0
spectral[magnitude: 50] = 0.25
capture.process(spectral: spectral, engine: makeTestEngine())
let snap: [Float] = capture.snapshot()
#expect(abs(snap[1] - 0.5) < 1e-6)
#expect(abs(snap[10] - 1.0) < 1e-6)
#expect(abs(snap[50] - 0.25) < 1e-6)
}
@Test func processDCAndNyquistStoredAsAbsoluteValue() {
let fftSize: Int = 512
let capture: SpectrumCapture = SpectrumCapture(fftSize: fftSize)
let spectral: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
spectral.dcValue = -0.8 // negative — should be stored as 0.8
spectral.nyquistValue = 0.6
capture.process(spectral: spectral, engine: makeTestEngine())
let snap: [Float] = capture.snapshot()
#expect(abs(snap[0] - 0.8) < 1e-6) // bin 0 = |DC|
#expect(abs(snap[fftSize / 2] - 0.6) < 1e-6) // bin halfSize = |Nyquist|
}
@Test func negativeDCStoredAbsolute() {
let fftSize: Int = 256
let capture: SpectrumCapture = SpectrumCapture(fftSize: fftSize)
let spectral: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
spectral.dcValue = -1.0
capture.process(spectral: spectral, engine: makeTestEngine())
let snap: [Float] = capture.snapshot()
#expect(abs(snap[0] - 1.0) < 1e-6)
}
// MARK: - Multi-hop updates
@Test func consecutiveHopsUpdateSnapshot() {
let fftSize: Int = 256
let capture: SpectrumCapture = SpectrumCapture(fftSize: fftSize)
let spectral: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
spectral[magnitude: 5] = 0.3
capture.process(spectral: spectral, engine: makeTestEngine())
let snap1: [Float] = capture.snapshot()
#expect(abs(snap1[5] - 0.3) < 1e-6)
spectral[magnitude: 5] = 0.7
capture.process(spectral: spectral, engine: makeTestEngine())
let snap2: [Float] = capture.snapshot()
#expect(abs(snap2[5] - 0.7) < 1e-6)
}
@Test func snapshotCountMatchesBinCount() {
let fftSize: Int = 1024
let capture: SpectrumCapture = SpectrumCapture(fftSize: fftSize)
let spectral: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
capture.process(spectral: spectral, engine: makeTestEngine())
let snap: [Float] = capture.snapshot()
#expect(snap.count == capture.binCount)
}
@Test func manyHopsAllBinsUpdated() {
let fftSize: Int = 256
let halfSize: Int = fftSize / 2
let capture: SpectrumCapture = SpectrumCapture(fftSize: fftSize)
let spectral: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let expected: Float = Float(0.42)
for k: Int in 1..<halfSize {
spectral[magnitude: k] = expected
}
// Drive 10 hops to stress the ping-pong
for _ in 0..<10 {
capture.process(spectral: spectral, engine: makeTestEngine())
}
let snap: [Float] = capture.snapshot()
for k: Int in 1..<halfSize {
#expect(abs(snap[k] - expected) < 1e-6)
}
}
}