Files
Lyrebird/Tests/LyrebirdTests/AdditiveSynthesizerTests.swift
T
2026-06-01 18:27:40 -07:00

304 lines
13 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// AdditiveSynthesizerTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@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: [])
}
}
}