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

1404 lines
61 KiB
Swift

// GranularTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@Suite("BufferGrain")
struct GranularTests {
// MARK: - Helpers
func makeEngine(blockSize: Int = 512) throws -> SynthesisEngine {
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
return engine
}
/// Fill buffer with a constant value on all channels.
func makeConstantBuffer(frames: Int, channelCount: Int = 1, value: Double = 1.0) -> LyrebirdBuffer {
let buf: LyrebirdBuffer = LyrebirdBuffer(count: frames, channelCount: channelCount)
for frame: Int in 0..<frames {
for ch: Int in 0..<channelCount {
buf.write(value, frame: frame, channel: ch)
}
}
return buf
}
// MARK: - Basic output
@Test func outputIsNonSilentWithPositiveDensity() throws {
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 1.0)
let grains: BufferGrain = BufferGrain(buffer: buf, duration: 0.01, seed: 42)
grains.density = 50.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
#expect(out.count == 2, "Expected 2 output channels, got \(out.count)")
let sumL: Double = out[0].prefix(512).reduce(0, { $0 + abs($1) })
let sumR: Double = out[1].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sumL > 0, "Left channel should be non-silent with density > 0")
#expect(sumR > 0, "Right channel should be non-silent with density > 0")
}
@Test func lowDensityProducesSilenceAfterFirstGrainExpires() throws {
// density=0.001 → hopSize ≈ 44,100,000 samples >> blockSize(512).
// One grain fires immediately at sample 0 (first-block convention),
// then the pool is empty for the rest of the session since the next hop
// is ~44 million samples away.
// With duration=0.001 s (≈44 samples), the grain expires well within the first block.
// On the second block, no grains should be active → silence.
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 1.0)
let grains: BufferGrain = BufferGrain(buffer: buf, duration: 0.001, seed: 1)
grains.density = 0.001 // ~1 grain per 1000 seconds
// First block: single grain fires and expires.
_ = grains.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
// Second block: no active grains, no new trigger.
let out2: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
let sumL2: Double = out2[0].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sumL2 == 0, "After initial grain expires, low density produces silence")
}
// MARK: - Pool saturation
@Test func activeGrainCountNeverExceedsPoolSize() throws {
// Very high density + very long grains → pool should saturate but not overflow.
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 1.0)
let grains: BufferGrain = BufferGrain(buffer: buf, duration: 10.0, loop: true, seed: 7)
grains.density = 10000.0 // fires every ~4 samples
// Run several blocks; pool must never exceed lyrebirdGrainPoolSize.
for _ in 0..<4 {
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
// Output must be finite (no NaN/Inf from overflow).
for sample: Double in out[0].prefix(512) {
#expect(sample.isFinite, "Output must be finite; pool overflow would produce NaN/Inf")
}
advanceBlock(engine)
}
}
// MARK: - Stereo output shape
@Test func outputHasTwoChannels() throws {
let engine: SynthesisEngine = try makeEngine(blockSize: 64)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 4096, value: 0.5)
let grains: BufferGrain = BufferGrain(buffer: buf, seed: 3)
grains.density = 100.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 64)
#expect(out.count == 2, "BufferGrain must produce exactly 2 channels")
#expect(out[0].count >= 64)
#expect(out[1].count >= 64)
}
@Test func outputChannelCountSurvivesBinaryOp() throws {
// Pins the `outputChannelCount` override fix: without the override BinaryOpGenerator
// reads the GeneratorBase default of 1 and silently mono-izes channel 1.
let engine: SynthesisEngine = try makeEngine(blockSize: 64)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 4096, value: 0.5)
let grains: BufferGrain = BufferGrain(buffer: buf, seed: 3)
grains.density = 100.0
let scaled: BinaryOpGenerator = grains * 0.5
#expect(scaled.outputChannelCount == 2, "binary op must preserve 2-channel output")
let out: [[Double]] = scaled.calculatedSamples(graph: graph, count: 64)
#expect(out.count == 2, "BufferGrain * 0.5 must produce 2 channels, got \(out.count)")
}
@Test func centredPanProducesEqualLeftRight() throws {
// All grains at pan = 0 (centre): cos(π/4) == sin(π/4), so L ≈ R per grain.
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 1.0)
let grains: BufferGrain = BufferGrain(buffer: buf, duration: 0.01, loop: true, seed: 99)
grains.density = 100.0
grains.rateSpread = 0.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
// L and R should be identical (all grains centred, same window, same buffer).
var maxDiff: Double = 0
for i: Int in 0..<512 {
maxDiff = max(maxDiff, abs(out[0][i] - out[1][i]))
}
#expect(maxDiff < 1e-5, "Centred grains: L/R diff \(maxDiff) exceeds tolerance")
}
@Test func panSpreadProducesAsymmetryAndFiniteOutput() throws {
// Non-zero panSpread randomises per-grain pan; fixed seed makes output deterministic.
// L and R must differ (asymmetric) and all samples must be finite.
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 1.0)
let grains: BufferGrain = BufferGrain(buffer: buf, duration: 0.01, loop: true, seed: 7)
grains.density = 100.0
grains.panSpread = 1.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
var maxDiff: Double = 0
for i: Int in 0..<512 {
#expect(out[0][i].isFinite, "BufferGrain panSpread: L[\(i)] not finite")
#expect(out[1][i].isFinite, "BufferGrain panSpread: R[\(i)] not finite")
maxDiff = max(maxDiff, abs(out[0][i] - out[1][i]))
}
#expect(maxDiff > 1e-5, "BufferGrain panSpread=1: L and R must differ; maxDiff=\(maxDiff)")
}
// MARK: - Custom window buffer
@Test func customWindowBufferIsUsed() throws {
// A rectangular window (all ones) vs Hanning: with rect window, grain energy
// is uniformly distributed over the grain duration rather than bell-shaped.
// Verify the generator accepts and runs without crashing.
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 1.0)
let rectWin: LyrebirdBuffer = makeConstantBuffer(frames: 1024, value: 1.0) // rectangular window
let grains: BufferGrain = BufferGrain(buffer: buf, duration: 0.01, window: rectWin, loop: true, seed: 5)
grains.density = 20.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
let sum: Double = out[0].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sum > 0, "Custom window: output should be non-silent")
}
// MARK: - loop = false
@Test func loopFalseGrainsSilenceAfterBufferEnd() throws {
// Very short buffer; grains with high rate run off the end quickly.
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
// 8-frame buffer, pitchRatio=4.0 → each grain runs off end in ~2 samples.
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 8, value: 1.0)
let grains: BufferGrain = BufferGrain(buffer: buf, duration: 1.0, pitchRatio: 4.0, loop: false, seed: 11)
grains.density = 1000.0 // many grains per block
// Just check it doesn't crash and produces finite output.
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
for sample: Double in out[0].prefix(512) {
#expect(sample.isFinite)
}
}
// MARK: - Fan-out cache
@Test func fanOutCacheProducesIdenticalOutput() throws {
// Two downstream generators sharing the same BufferGrain should get identical blocks.
let engine: SynthesisEngine = try makeEngine(blockSize: 128)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 0.8)
let grains: BufferGrain = BufferGrain(buffer: buf, duration: 0.02, seed: 77)
grains.density = 30.0
let out1: [[Double]] = grains.calculatedSamples(graph: graph, count: 128)
let out2: [[Double]] = grains.calculatedSamples(graph: graph, count: 128) // should hit cache
for i: Int in 0..<128 {
#expect(out1[0][i] == out2[0][i],
"Fan-out cache: sample \(i) L differs: \(out1[0][i]) vs \(out2[0][i])")
#expect(out1[1][i] == out2[1][i],
"Fan-out cache: sample \(i) R differs: \(out1[1][i]) vs \(out2[1][i])")
}
}
// MARK: - Position spread
@Test func positionSpreadDoesNotCrash() throws {
let engine: SynthesisEngine = try makeEngine(blockSize: 256)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 0.5)
let grains: BufferGrain = BufferGrain(buffer: buf, positionSpread: 0.5, duration: 0.01, seed: 13)
grains.density = 50.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 256)
for sample: Double in out[0].prefix(256) {
#expect(sample.isFinite, "positionSpread must not produce NaN/Inf")
}
}
// MARK: - Amplitude
@Test func amplitudeScalesOutput() throws {
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph1: SynthGraph = makeSynthGraph(engine: engine)
let graph2: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 1.0)
// Same seed → identical grain timing and spread.
let g1: BufferGrain = BufferGrain(buffer: buf, duration: 0.01, amp: 1.0, seed: 22)
g1.density = 50.0
let g2: BufferGrain = BufferGrain(buffer: buf, duration: 0.01, amp: 0.5, seed: 22)
g2.density = 50.0
let out1: [[Double]] = g1.calculatedSamples(graph: graph1, count: 512)
let out2: [[Double]] = g2.calculatedSamples(graph: graph2, count: 512)
var allHalfAmplitude: Bool = true
for i: Int in 0..<512 {
let expected: Double = out1[0][i] * 0.5
if abs(out2[0][i] - expected) > 1e-5 {
allHalfAmplitude = false
break
}
}
#expect(allHalfAmplitude, "amp = 0.5 should produce half the amplitude of amp = 1.0")
}
// MARK: - Determinism
@Test func deterministicOutputWithSameSeed() throws {
// Two BufferGrain instances with identical seed and non-zero spread must produce
// bit-identical output — verifies PRNG determinism across instances.
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph1: SynthGraph = makeSynthGraph(engine: engine)
let graph2: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 1.0)
let g1: BufferGrain = BufferGrain(buffer: buf, positionSpread: 0.5, duration: 0.01, seed: 42)
g1.density = 50.0; g1.rateSpread = 0.1
let g2: BufferGrain = BufferGrain(buffer: buf, positionSpread: 0.5, duration: 0.01, seed: 42)
g2.density = 50.0; g2.rateSpread = 0.1
let out1: [[Double]] = g1.calculatedSamples(graph: graph1, count: 512)
let out2: [[Double]] = g2.calculatedSamples(graph: graph2, count: 512)
#expect(out1[0] == out2[0], "Same seed must produce identical L channel")
#expect(out1[1] == out2[1], "Same seed must produce identical R channel")
}
// MARK: - Generator-driven parameter tests
@Test func durationGeneratorInput() throws {
// Connect a ConstantGeneratorInput as duration — verify non-silent output.
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 1.0)
let durGen: ConstantGeneratorInput = ConstantGeneratorInput(0.02)
let grains: BufferGrain = BufferGrain(buffer: buf, duration: durGen, seed: 100)
grains.density = 30.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
let sum: Double = out[0].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sum > 0, "BufferGrain with generator duration input must be non-silent")
}
@Test func pitchDispersionSpread() throws {
// pitchDispersion > 0 must produce finite output.
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 1.0)
let grains: BufferGrain = BufferGrain(buffer: buf, duration: 0.02, pitchDispersion: 0.5, seed: 200)
grains.density = 30.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
for i: Int in 0..<512 {
#expect(out[0][i].isFinite, "pitchDispersion: sample \(i) L not finite")
#expect(out[1][i].isFinite, "pitchDispersion: sample \(i) R not finite")
}
let sum: Double = out[0].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sum > 0, "pitchDispersion > 0 must produce non-silent output")
}
@Test func pitchRatioGeneratorInput() throws {
// Connect a ConstantGeneratorInput as pitchRatio — must not crash, must be non-silent.
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 1.0)
let pitchGen: ConstantGeneratorInput = ConstantGeneratorInput(2.0)
let grains: BufferGrain = BufferGrain(buffer: buf, duration: 0.02, pitchRatio: pitchGen, seed: 300)
grains.density = 30.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
let sum: Double = out[0].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sum > 0, "BufferGrain with generator pitchRatio input must be non-silent")
for i: Int in 0..<512 {
#expect(out[0][i].isFinite, "BufferGrain pitchRatio generator: sample \(i) L not finite")
}
}
}
// MARK: - SineGrain
@Suite("SineGrain")
struct SineGrainTests {
func makeEngine(blockSize: Int = 512) throws -> SynthesisEngine {
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
return engine
}
@Test func outputIsStereoAndNonSilent() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let grains: SineGrain = SineGrain(freq: 440.0, amp: 0.5, duration: 0.02, seed: 1)
grains.density = 20.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
#expect(out.count == 2, "SineGrain must produce 2 channels")
let sumL: Double = out[0].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sumL > 0, "SineGrain: left channel must be non-silent")
}
@Test func outputChannelCountSurvivesBinaryOp() throws {
// Pins outputChannelCount override — without it `* 0.5` collapses to mono.
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let grains: SineGrain = SineGrain(freq: 440.0, amp: 0.5, duration: 0.02, seed: 1)
let scaled: BinaryOpGenerator = grains * 0.5
#expect(scaled.outputChannelCount == 2)
let out: [[Double]] = scaled.calculatedSamples(graph: graph, count: 64)
#expect(out.count == 2, "SineGrain * 0.5 must produce 2 channels, got \(out.count)")
}
@Test func outputIsFinite() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let grains: SineGrain = SineGrain(freq: 1000.0, amp: 0.3, duration: 0.01, seed: 2)
grains.density = 50.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
for i: Int in 0..<512 {
#expect(out[0][i].isFinite, "SineGrain sample \(i) L is not finite")
#expect(out[1][i].isFinite, "SineGrain sample \(i) R is not finite")
}
}
@Test func centredPanIsSymmetric() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let grains: SineGrain = SineGrain(freq: 220.0, amp: 0.5, duration: 0.02, seed: 3)
grains.density = 30.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
var maxDiff: Double = 0
for i: Int in 0..<512 {
maxDiff = max(maxDiff, abs(out[0][i] - out[1][i]))
}
#expect(maxDiff < 1e-5, "SineGrain centred pan: L/R diff \(maxDiff)")
}
@Test func panSpreadProducesAsymmetryAndFiniteOutput() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let grains: SineGrain = SineGrain(freq: 440.0, amp: 0.5, duration: 0.02, seed: 11)
grains.density = 30.0
grains.panSpread = 1.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
var maxDiff: Double = 0
for i: Int in 0..<512 {
#expect(out[0][i].isFinite, "SineGrain panSpread: L[\(i)] not finite")
#expect(out[1][i].isFinite, "SineGrain panSpread: R[\(i)] not finite")
maxDiff = max(maxDiff, abs(out[0][i] - out[1][i]))
}
#expect(maxDiff > 1e-5, "SineGrain panSpread=1: L and R must differ; maxDiff=\(maxDiff)")
}
@Test func higherAmpProducesLargerOutput() throws {
let engine: SynthesisEngine = try makeEngine()
let graph1: SynthGraph = makeSynthGraph(engine: engine)
let graph2: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let g1: SineGrain = SineGrain(freq: 440.0, amp: 1.0, duration: 0.02, seed: 4)
g1.density = 30.0
let g2: SineGrain = SineGrain(freq: 440.0, amp: 0.5, duration: 0.02, seed: 4)
g2.density = 30.0
let out1: [[Double]] = g1.calculatedSamples(graph: graph1, count: 512)
let out2: [[Double]] = g2.calculatedSamples(graph: graph2, count: 512)
let sum1: Double = out1[0].prefix(512).reduce(0, { $0 + abs($1) })
let sum2: Double = out2[0].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sum1 > sum2, "Higher amp grain should produce larger summed output")
}
@Test func poolSaturationDoesNotCrash() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let grains: SineGrain = SineGrain(freq: 440.0, amp: 0.1, duration: 10.0, seed: 5)
grains.density = 10000.0 // saturates pool
for _ in 0..<4 {
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
for s: Double in out[0].prefix(512) { #expect(s.isFinite) }
advanceBlock(engine)
}
}
@Test func fanOutCacheProducesIdenticalOutput() throws {
let engine: SynthesisEngine = try makeEngine(blockSize: 128)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let grains: SineGrain = SineGrain(freq: 330.0, amp: 0.4, duration: 0.01, seed: 6)
grains.density = 40.0
let out1: [[Double]] = grains.calculatedSamples(graph: graph, count: 128)
let out2: [[Double]] = grains.calculatedSamples(graph: graph, count: 128)
for i: Int in 0..<128 {
#expect(out1[0][i] == out2[0][i], "SineGrain fan-out cache mismatch at \(i)")
}
}
@Test func generatorFreqInputPolledAtTrigger() throws {
// Connect a constant-value generator as freq input — must not crash.
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let constFreq: ConstantGeneratorInput = ConstantGeneratorInput(880.0)
let grains: SineGrain = SineGrain(freq: constFreq, amp: 0.3, duration: 0.02, seed: 7)
grains.density = 20.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
let sum: Double = out[0].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sum > 0, "Generator freq input: output must be non-silent")
}
@Test func customWindowUsed() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let rectWin: LyrebirdBuffer = LyrebirdBuffer(count: 512)
rectWin.fill(with: 1.0)
let grains: SineGrain = SineGrain(freq: 440.0, amp: 0.5, duration: 0.01, window: rectWin, seed: 8)
grains.density = 20.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
#expect(out[0].prefix(512).reduce(0, { $0 + abs($1) }) > 0,
"Custom window SineGrain must produce output")
}
// MARK: - Determinism
@Test func deterministicOutputWithSameSeed() throws {
// Two instances with the same seed, freq, amp must produce bit-identical output.
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph1: SynthGraph = makeSynthGraph(engine: engine)
let graph2: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let g1: SineGrain = SineGrain(freq: 440.0, amp: 0.5, duration: 0.02, seed: 42)
g1.density = 30.0
let g2: SineGrain = SineGrain(freq: 440.0, amp: 0.5, duration: 0.02, seed: 42)
g2.density = 30.0
let out1: [[Double]] = g1.calculatedSamples(graph: graph1, count: 512)
let out2: [[Double]] = g2.calculatedSamples(graph: graph2, count: 512)
#expect(out1[0] == out2[0], "SineGrain: same seed must produce identical L channel")
#expect(out1[1] == out2[1], "SineGrain: same seed must produce identical R channel")
}
// MARK: - Generator-driven parameter tests
@Test func durationGeneratorInput() throws {
// Connect a ConstantGeneratorInput as duration — verify non-silent output.
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let durGen: ConstantGeneratorInput = ConstantGeneratorInput(0.02)
let grains: SineGrain = SineGrain(freq: 440.0, amp: 0.5, duration: durGen, seed: 300)
grains.density = 20.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
let sum: Double = out[0].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sum > 0, "SineGrain with generator duration input must be non-silent")
}
@Test func panGeneratorInput() throws {
// Connect a ConstantGeneratorInput as pan — verify output is finite.
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let panGen: ConstantGeneratorInput = ConstantGeneratorInput(0.5)
let grains: SineGrain = SineGrain(freq: 440.0, amp: 0.5, duration: 0.02, pan: panGen, seed: 301)
grains.density = 20.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
for i: Int in 0..<512 {
#expect(out[0][i].isFinite, "SineGrain pan generator: sample \(i) not finite")
}
}
}
// MARK: - FMGrain
@Suite("FMGrain")
struct FMGrainTests {
func makeEngine(blockSize: Int = 512) throws -> SynthesisEngine {
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
return engine
}
@Test func outputIsStereoAndNonSilent() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let grains: FMGrain = FMGrain(carrierFreq: 440.0, modFreq: 220.0, modIndex: 2.0, amp: 0.4,
duration: 0.02, seed: 1)
grains.density = 20.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
#expect(out.count == 2, "FMGrain must produce 2 channels")
let sumL: Double = out[0].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sumL > 0, "FMGrain: output must be non-silent")
}
@Test func outputChannelCountSurvivesBinaryOp() throws {
// Pins outputChannelCount override — without it `* 0.5` collapses to mono.
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let grains: FMGrain = FMGrain(carrierFreq: 440.0, modFreq: 220.0, modIndex: 2.0, amp: 0.4,
duration: 0.02, seed: 1)
let scaled: BinaryOpGenerator = grains * 0.5
#expect(scaled.outputChannelCount == 2)
let out: [[Double]] = scaled.calculatedSamples(graph: graph, count: 64)
#expect(out.count == 2, "FMGrain * 0.5 must produce 2 channels, got \(out.count)")
}
@Test func outputIsFinite() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
// High modulation index → large FM displacement; must not produce NaN/Inf.
let grains: FMGrain = FMGrain(carrierFreq: 440.0, modFreq: 880.0, modIndex: 20.0, amp: 0.3,
duration: 0.02, seed: 2)
grains.density = 30.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
for i: Int in 0..<512 {
#expect(out[0][i].isFinite, "FMGrain sample \(i) not finite (modIndex=20)")
#expect(out[1][i].isFinite, "FMGrain sample \(i) R not finite")
}
}
@Test func zeroModIndexApproachesSine() throws {
// At modIndex=0, FM output = sin(carrierPhase) — identical to SineGrain
// with same freq/amp/seed. Compare summed energy to verify they're similar.
let engine: SynthesisEngine = try makeEngine()
let graph1: SynthGraph = makeSynthGraph(engine: engine)
let graph2: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let fm: FMGrain = FMGrain(carrierFreq: 440.0, modFreq: 440.0, modIndex: 0.0, amp: 0.5,
duration: 0.02, seed: 10)
fm.density = 20.0
let sine: SineGrain = SineGrain(freq: 440.0, amp: 0.5, duration: 0.02, seed: 10)
sine.density = 20.0
let outFM: [[Double]] = fm.calculatedSamples(graph: graph1, count: 512)
let outSine: [[Double]] = sine.calculatedSamples(graph: graph2, count: 512)
// Energies should match within a small tolerance (different PRNG states at alloc).
let energyFM: Double = outFM[0].prefix(512).reduce(0.0, { $0 + $1 * $1 })
let energySine: Double = outSine[0].prefix(512).reduce(0.0, { $0 + $1 * $1 })
let ratio: Double = energyFM / max(energySine, 1e-9)
#expect(ratio > 0.9 && ratio < 1.1,
"FM with modIndex=0 energy ratio \(ratio) should be ≈1 vs SineGrain")
}
@Test func generatorModIndexInput() throws {
// Connect a ConstantGeneratorInput as modIndex — must not crash.
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let idxGen: ConstantGeneratorInput = ConstantGeneratorInput(3.0)
let grains: FMGrain = FMGrain(carrierFreq: 440.0, modFreq: 220.0, modIndex: idxGen, amp: 0.3,
duration: 0.02, seed: 3)
grains.density = 20.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
let sum: Double = out[0].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sum > 0, "FMGrain with generator modIndex must be non-silent")
}
@Test func poolSaturationDoesNotCrash() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let grains: FMGrain = FMGrain(carrierFreq: 330.0, modFreq: 660.0, modIndex: 5.0, amp: 0.1,
duration: 10.0, seed: 4)
grains.density = 10000.0
for _ in 0..<4 {
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
for s: Double in out[0].prefix(512) { #expect(s.isFinite) }
advanceBlock(engine)
}
}
@Test func fanOutCacheProducesIdenticalOutput() throws {
let engine: SynthesisEngine = try makeEngine(blockSize: 128)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let grains: FMGrain = FMGrain(carrierFreq: 220.0, modFreq: 110.0, modIndex: 2.0, amp: 0.4,
duration: 0.015, seed: 5)
grains.density = 30.0
let out1: [[Double]] = grains.calculatedSamples(graph: graph, count: 128)
let out2: [[Double]] = grains.calculatedSamples(graph: graph, count: 128)
for i: Int in 0..<128 {
#expect(out1[0][i] == out2[0][i], "FMGrain fan-out cache mismatch at \(i)")
}
}
@Test func centredPanIsSymmetric() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let grains: FMGrain = FMGrain(carrierFreq: 440.0, modFreq: 220.0, modIndex: 1.0, amp: 0.4,
duration: 0.02, seed: 6)
grains.density = 30.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
var maxDiff: Double = 0
for i: Int in 0..<512 { maxDiff = max(maxDiff, abs(out[0][i] - out[1][i])) }
#expect(maxDiff < 1e-5, "FMGrain centred pan L/R diff \(maxDiff)")
}
@Test func panSpreadProducesAsymmetryAndFiniteOutput() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let grains: FMGrain = FMGrain(carrierFreq: 440.0, modFreq: 220.0, modIndex: 2.0, amp: 0.4,
duration: 0.02, seed: 13)
grains.density = 30.0
grains.panSpread = 1.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
var maxDiff: Double = 0
for i: Int in 0..<512 {
#expect(out[0][i].isFinite, "FMGrain panSpread: L[\(i)] not finite")
#expect(out[1][i].isFinite, "FMGrain panSpread: R[\(i)] not finite")
maxDiff = max(maxDiff, abs(out[0][i] - out[1][i]))
}
#expect(maxDiff > 1e-5, "FMGrain panSpread=1: L and R must differ; maxDiff=\(maxDiff)")
}
// MARK: - Determinism
@Test func deterministicOutputWithSameSeed() throws {
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph1: SynthGraph = makeSynthGraph(engine: engine)
let graph2: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let g1: FMGrain = FMGrain(carrierFreq: 440.0, modFreq: 220.0, modIndex: 2.0, amp: 0.4,
duration: 0.02, seed: 42)
g1.density = 30.0
let g2: FMGrain = FMGrain(carrierFreq: 440.0, modFreq: 220.0, modIndex: 2.0, amp: 0.4,
duration: 0.02, seed: 42)
g2.density = 30.0
let out1: [[Double]] = g1.calculatedSamples(graph: graph1, count: 512)
let out2: [[Double]] = g2.calculatedSamples(graph: graph2, count: 512)
#expect(out1[0] == out2[0], "FMGrain: same seed must produce identical L channel")
#expect(out1[1] == out2[1], "FMGrain: same seed must produce identical R channel")
}
// MARK: - Generator-driven parameter tests
@Test func durationGeneratorInput() throws {
// Connect a ConstantGeneratorInput as duration — verify non-silent output.
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let durGen: ConstantGeneratorInput = ConstantGeneratorInput(0.02)
let grains: FMGrain = FMGrain(carrierFreq: 440.0, modFreq: 220.0, modIndex: 1.0, amp: 0.4,
duration: durGen, seed: 400)
grains.density = 20.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
let sum: Double = out[0].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sum > 0, "FMGrain with generator duration input must be non-silent")
}
@Test func panGeneratorInput() throws {
// Connect a ConstantGeneratorInput as pan — verify output is finite.
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let panGen: ConstantGeneratorInput = ConstantGeneratorInput(-0.5)
let grains: FMGrain = FMGrain(carrierFreq: 440.0, modFreq: 220.0, modIndex: 1.0, amp: 0.4,
duration: 0.02, pan: panGen, seed: 401)
grains.density = 20.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
for i: Int in 0..<512 {
#expect(out[0][i].isFinite, "FMGrain pan generator: sample \(i) not finite")
}
}
}
// MARK: - InputGrain
@Suite("InputGrain")
struct InputGrainTests {
func makeEngine(blockSize: Int = 512) throws -> SynthesisEngine {
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
return engine
}
@Test func outputIsStereoAndNonSilentWithSignalInput() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
// Feed a constant 1.0 as input; granulator should produce non-zero output.
let grains: InputGrain = InputGrain(input: 1.0, duration: 0.02, seed: 1)
grains.density = 20.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
#expect(out.count == 2, "InputGrain must produce 2 channels")
let sumL: Double = out[0].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sumL > 0, "InputGrain with constant input must be non-silent")
}
@Test func outputChannelCountSurvivesBinaryOp() throws {
// Pins outputChannelCount override — without it `* 0.5` collapses to mono.
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let grains: InputGrain = InputGrain(input: 1.0, duration: 0.02, seed: 1)
let scaled: BinaryOpGenerator = grains * 0.5
#expect(scaled.outputChannelCount == 2)
let out: [[Double]] = scaled.calculatedSamples(graph: graph, count: 64)
#expect(out.count == 2, "InputGrain * 0.5 must produce 2 channels, got \(out.count)")
}
@Test func outputIsFinite() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let grains: InputGrain = InputGrain(input: 0.8, duration: 0.01, seed: 2)
grains.density = 50.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
for i: Int in 0..<512 {
#expect(out[0][i].isFinite, "InputGrain sample \(i) L not finite")
#expect(out[1][i].isFinite, "InputGrain sample \(i) R not finite")
}
}
@Test func silentInputProducesSilentOutput() throws {
// With input = 0.0, capture buffer stays zero → output must be zero.
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let grains: InputGrain = InputGrain(input: 0.0, duration: 0.02, seed: 3)
grains.density = 30.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
let sumL: Double = out[0].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sumL == 0, "Zero input must produce zero output")
}
@Test func ampScalesOutput() throws {
let engine: SynthesisEngine = try makeEngine()
let graph1: SynthGraph = makeSynthGraph(engine: engine)
let graph2: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let g1: InputGrain = InputGrain(input: 1.0, duration: 0.02, amp: 1.0, seed: 4)
g1.density = 20.0
let g2: InputGrain = InputGrain(input: 1.0, duration: 0.02, amp: 0.5, seed: 4)
g2.density = 20.0
let out1: [[Double]] = g1.calculatedSamples(graph: graph1, count: 512)
let out2: [[Double]] = g2.calculatedSamples(graph: graph2, count: 512)
var allHalf: Bool = true
for i: Int in 0..<512 {
if abs(out2[0][i] - out1[0][i] * 0.5) > 1e-5 { allHalf = false; break }
}
#expect(allHalf, "InputGrain amp=0.5 should be half of amp=1.0")
}
@Test func positionSpreadDoesNotCrash() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let grains: InputGrain = InputGrain(input: 0.5, positionSpread: 0.5, duration: 0.02, seed: 5)
grains.density = 30.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
for s: Double in out[0].prefix(512) { #expect(s.isFinite) }
}
@Test func poolSaturationDoesNotCrash() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let grains: InputGrain = InputGrain(input: 0.7, duration: 10.0, seed: 6)
grains.density = 10000.0
for _ in 0..<4 {
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
for s: Double in out[0].prefix(512) { #expect(s.isFinite) }
advanceBlock(engine)
}
}
@Test func fanOutCacheProducesIdenticalOutput() throws {
let engine: SynthesisEngine = try makeEngine(blockSize: 128)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let grains: InputGrain = InputGrain(input: 0.6, duration: 0.015, seed: 7)
grains.density = 30.0
let out1: [[Double]] = grains.calculatedSamples(graph: graph, count: 128)
let out2: [[Double]] = grains.calculatedSamples(graph: graph, count: 128)
for i: Int in 0..<128 {
#expect(out1[0][i] == out2[0][i], "InputGrain fan-out cache mismatch at \(i)")
}
}
@Test func generatorInputIsRecorded() throws {
// Feed a ConstantGeneratorInput as input source — must not crash and be non-silent.
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let src: ConstantGeneratorInput = ConstantGeneratorInput(0.75)
let grains: InputGrain = InputGrain(input: src, duration: 0.02, seed: 8)
grains.density = 20.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
let sum: Double = out[0].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sum > 0, "ConstantGeneratorInput source: InputGrain must be non-silent")
}
@Test func centredPanIsSymmetric() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let grains: InputGrain = InputGrain(input: 1.0, duration: 0.02, seed: 9)
grains.density = 30.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
var maxDiff: Double = 0
for i: Int in 0..<512 { maxDiff = max(maxDiff, abs(out[0][i] - out[1][i])) }
#expect(maxDiff < 1e-5, "InputGrain centred pan L/R diff \(maxDiff)")
}
@Test func panSpreadProducesAsymmetryAndFiniteOutput() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let grains: InputGrain = InputGrain(input: 1.0, duration: 0.02, seed: 17)
grains.density = 30.0
grains.panSpread = 1.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
var maxDiff: Double = 0
for i: Int in 0..<512 {
#expect(out[0][i].isFinite, "InputGrain panSpread: L[\(i)] not finite")
#expect(out[1][i].isFinite, "InputGrain panSpread: R[\(i)] not finite")
maxDiff = max(maxDiff, abs(out[0][i] - out[1][i]))
}
#expect(maxDiff > 1e-5, "InputGrain panSpread=1: L and R must differ; maxDiff=\(maxDiff)")
}
// MARK: - Determinism
@Test func deterministicOutputWithSameSeed() throws {
// Two instances with the same seed and positionSpread must produce identical output.
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph1: SynthGraph = makeSynthGraph(engine: engine)
let graph2: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let g1: InputGrain = InputGrain(input: 1.0, positionSpread: 0.5, duration: 0.02, seed: 42)
g1.density = 30.0
let g2: InputGrain = InputGrain(input: 1.0, positionSpread: 0.5, duration: 0.02, seed: 42)
g2.density = 30.0
let out1: [[Double]] = g1.calculatedSamples(graph: graph1, count: 512)
let out2: [[Double]] = g2.calculatedSamples(graph: graph2, count: 512)
#expect(out1[0] == out2[0], "InputGrain: same seed must produce identical L channel")
#expect(out1[1] == out2[1], "InputGrain: same seed must produce identical R channel")
}
// MARK: - Generator-driven parameter tests
@Test func pitchRatioGeneratorInput() throws {
// Connect a ConstantGeneratorInput as pitchRatio — must not crash and be non-silent.
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let ratioGen: ConstantGeneratorInput = ConstantGeneratorInput(1.5)
let grains: InputGrain = InputGrain(input: 1.0, duration: 0.02, pitchRatio: ratioGen, seed: 500)
grains.density = 20.0
let out: [[Double]] = grains.calculatedSamples(graph: graph, count: 512)
for i: Int in 0..<512 {
#expect(out[0][i].isFinite, "InputGrain pitchRatio generator: sample \(i) not finite")
}
let sum: Double = out[0].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sum > 0, "InputGrain with pitchRatio generator must be non-silent")
}
}
// MARK: - TimeStretch
@Suite("TimeStretch")
struct TimeStretchTests {
func makeEngine(blockSize: Int = 512) throws -> SynthesisEngine {
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
return engine
}
func makeConstantBuffer(frames: Int, value: Double = 1.0) -> LyrebirdBuffer {
let buf: LyrebirdBuffer = LyrebirdBuffer(count: frames)
for frame: Int in 0..<frames {
buf.write(value, frame: frame, channel: 0)
}
return buf
}
@Test func monoBufferProducesOneChannel() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 1.0)
let ts: TimeStretch.Audio = TimeStretch.Audio(buffer: buf, pos: 0.5, windowSize: 0.05, overlap: 4, seed: 9)
ts.amp = 1.0
let out: [[Double]] = ts.calculatedSamples(graph: graph, count: 512)
#expect(out.count == 1, "Mono buffer must produce 1-channel output")
let sum: Double = out[0].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sum > 0, "TimeStretch mono: channel must be non-silent")
}
@Test func stereoBufferProducesTwoChannels() throws {
// 2-channel buffer → 2-channel output, both channels populated
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 44100, channelCount: 2)
for frame: Int in 0..<44100 {
buf.write(1.0, frame: frame, channel: 0)
buf.write(0.5, frame: frame, channel: 1)
}
let ts: TimeStretch.Audio = TimeStretch.Audio(buffer: buf, pos: 0.5, windowSize: 0.05, overlap: 4, seed: 10)
ts.amp = 1.0
let out: [[Double]] = ts.calculatedSamples(graph: graph, count: 512)
#expect(out.count == 2, "Stereo buffer must produce 2-channel output")
let sumL: Double = out[0].prefix(512).reduce(0, { $0 + abs($1) })
let sumR: Double = out[1].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sumL > 0, "TimeStretch stereo: left channel must be non-silent")
#expect(sumR > 0, "TimeStretch stereo: right channel must be non-silent")
}
@Test func fourChannelBufferProducesFourChannels() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 44100, channelCount: 4)
for frame: Int in 0..<44100 {
for ch: Int in 0..<4 { buf.write(Double(ch + 1) * 0.25, frame: frame, channel: ch) }
}
let ts: TimeStretch.Audio = TimeStretch.Audio(buffer: buf, pos: 0.5, windowSize: 0.05, overlap: 4, seed: 11)
ts.amp = 1.0
let out: [[Double]] = ts.calculatedSamples(graph: graph, count: 512)
#expect(out.count == 4, "4-channel buffer must produce 4-channel output")
for ch: Int in 0..<4 {
let sum: Double = out[ch].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sum > 0, "TimeStretch 4ch: channel \(ch) must be non-silent")
}
}
@Test func outputIsFinite() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 0.8)
let ts: TimeStretch.Audio = TimeStretch.Audio(buffer: buf, pos: 0.3, windowSize: 0.04, overlap: 4, seed: 2)
ts.amp = 1.0
let out: [[Double]] = ts.calculatedSamples(graph: graph, count: 512)
for ch: Int in 0..<out.count {
for i: Int in 0..<512 {
#expect(out[ch][i].isFinite, "TimeStretch sample \(i) ch\(ch) not finite")
}
}
}
@Test func differentPosProducesDifferentOutput() throws {
// Two instances at different pos values should produce different output.
let engine: SynthesisEngine = try makeEngine()
let graph1: SynthGraph = makeSynthGraph(engine: engine)
let graph2: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 44100)
// Fill with a ramp so pos affects the output value.
for frame: Int in 0..<44100 {
buf.write(Double(frame) / 44100.0, frame: frame, channel: 0)
}
let ts1: TimeStretch.Audio = TimeStretch.Audio(buffer: buf, pos: 0.1, windowSize: 0.05, overlap: 4, seed: 3)
ts1.amp = 1.0
let ts2: TimeStretch.Audio = TimeStretch.Audio(buffer: buf, pos: 0.9, windowSize: 0.05, overlap: 4, seed: 3)
ts2.amp = 1.0
let out1: [[Double]] = ts1.calculatedSamples(graph: graph1, count: 512)
let out2: [[Double]] = ts2.calculatedSamples(graph: graph2, count: 512)
let sum1: Double = out1[0].prefix(512).reduce(0, +)
let sum2: Double = out2[0].prefix(512).reduce(0, +)
#expect(sum1 != sum2, "Different pos values should produce different output sums")
}
@Test func pitchRatioAboveOneIsNonSilent() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 1.0)
let ts: TimeStretch.Audio = TimeStretch.Audio(buffer: buf, pos: 0.5, pitchRatio: 2.0,
windowSize: 0.05, overlap: 4, seed: 4)
ts.amp = 1.0
let out: [[Double]] = ts.calculatedSamples(graph: graph, count: 512)
let sumL: Double = out[0].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sumL > 0, "TimeStretch pitchRatio=2.0 must produce non-silent output")
}
@Test func poolSaturationDoesNotCrash() throws {
// High overlap increases grains-per-block significantly; pool saturation must not crash.
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 1.0)
let ts: TimeStretch.Audio = TimeStretch.Audio(buffer: buf, pos: 0.5, windowSize: 1.0, overlap: 64, seed: 5)
ts.amp = 1.0
for _ in 0..<4 {
let out: [[Double]] = ts.calculatedSamples(graph: graph, count: 512)
for s: Double in out[0].prefix(512) { #expect(s.isFinite) }
advanceBlock(engine)
}
}
@Test func fanOutCacheProducesIdenticalOutput() throws {
let engine: SynthesisEngine = try makeEngine(blockSize: 128)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 0.7)
let ts: TimeStretch.Audio = TimeStretch.Audio(buffer: buf, pos: 0.5, windowSize: 0.05, overlap: 4, seed: 6)
ts.amp = 1.0
let out1: [[Double]] = ts.calculatedSamples(graph: graph, count: 128)
let out2: [[Double]] = ts.calculatedSamples(graph: graph, count: 128)
for ch: Int in 0..<out1.count {
for i: Int in 0..<128 {
#expect(out1[ch][i] == out2[ch][i],
"TimeStretch fan-out cache: ch\(ch)[\(i)] differs: \(out1[ch][i]) vs \(out2[ch][i])")
}
}
}
@Test func deterministicWithSameSeed() throws {
// Two instances with same seed and same pos must produce identical output.
let engine: SynthesisEngine = try makeEngine()
let graph1: SynthGraph = makeSynthGraph(engine: engine)
let graph2: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 1.0)
let ts1: TimeStretch.Audio = TimeStretch.Audio(buffer: buf, pos: 0.5, windowSize: 0.05, overlap: 4, seed: 42)
ts1.amp = 1.0
let ts2: TimeStretch.Audio = TimeStretch.Audio(buffer: buf, pos: 0.5, windowSize: 0.05, overlap: 4, seed: 42)
ts2.amp = 1.0
let out1: [[Double]] = ts1.calculatedSamples(graph: graph1, count: 512)
let out2: [[Double]] = ts2.calculatedSamples(graph: graph2, count: 512)
#expect(out1[0] == out2[0], "TimeStretch: same seed must produce identical output channel 0")
}
@Test func pitchDispersionSpread() throws {
// pitchDispersion > 0 must produce finite output.
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 1.0)
let ts: TimeStretch.Audio = TimeStretch.Audio(buffer: buf, pos: 0.5, windowSize: 0.05, overlap: 4,
pitchDispersion: 0.3, seed: 7)
ts.amp = 1.0
let out: [[Double]] = ts.calculatedSamples(graph: graph, count: 512)
for ch: Int in 0..<out.count {
for i: Int in 0..<512 {
#expect(out[ch][i].isFinite, "TimeStretch pitchDispersion: sample \(i) ch\(ch) not finite")
}
}
let sum: Double = out[0].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sum > 0, "TimeStretch with pitchDispersion must produce non-silent output")
}
@Test func posGeneratorInput() throws {
// Drive pos: from a ConstantGeneratorInput — the defining feature of TimeStretch.
// Must produce non-silent, finite output.
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 1.0)
let posGen: ConstantGeneratorInput = ConstantGeneratorInput(0.5)
let ts: TimeStretch.Audio = TimeStretch.Audio(buffer: buf, pos: posGen, windowSize: 0.05, overlap: 4, seed: 8)
ts.amp = 1.0
let out: [[Double]] = ts.calculatedSamples(graph: graph, count: 512)
let sum: Double = out[0].prefix(512).reduce(0, { $0 + abs($1) })
#expect(sum > 0, "TimeStretch with generator pos input must be non-silent")
for ch: Int in 0..<out.count {
for i: Int in 0..<512 {
#expect(out[ch][i].isFinite, "TimeStretch posGen: sample \(i) ch\(ch) not finite")
}
}
}
// MARK: - Per-channel decorrelation (Warp1 architecture)
@Test func multiChannelOutputIsDecorrelated() throws {
// With per-channel grain pools, two output channels reading two distinct buffer
// channels should diverge sample-by-sample even when both buffer channels share
// the same constant content (different grain trigger schedules per channel).
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
// Buffer channels carry different content so per-channel reads differ.
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 44100, channelCount: 2)
for frame: Int in 0..<44100 {
// Channel 0: sine at 220 Hz, channel 1: sine at 330 Hz.
let phase0: Double = Double(frame) / 44100.0 * 220.0 * 2.0 * .pi
let phase1: Double = Double(frame) / 44100.0 * 330.0 * 2.0 * .pi
buf.write(sin(phase0), frame: frame, channel: 0)
buf.write(sin(phase1), frame: frame, channel: 1)
}
let ts: TimeStretch.Audio = TimeStretch.Audio(buffer: buf, pos: 0.5, windowSize: 0.05,
overlap: 4, seed: 100)
ts.amp = 1.0
let out: [[Double]] = ts.calculatedSamples(graph: graph, count: 512)
#expect(out.count == 2)
// Output channels must differ on at least many samples.
var differingSamples: Int = 0
for i: Int in 0..<512 where out[0][i] != out[1][i] {
differingSamples += 1
}
#expect(differingSamples > 256,
"Per-channel decorrelation: expected most samples to differ between channels, got \(differingSamples)/512")
}
@Test func timeDispersionVariesGrainDuration() throws {
// With timeDispersion > 0, the new Warp1-style behaviour jitters grain duration
// (and hence hop). The total sample count between successive trigger events
// should not be constant across the run.
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 88200, value: 1.0)
let ts: TimeStretch.Audio = TimeStretch.Audio(buffer: buf, pos: 0.5, windowSize: 0.05,
overlap: 4, timeDispersion: 0.01, seed: 200)
ts.amp = 1.0
// Run many blocks so multiple grains trigger per channel.
var allFinite: Bool = true
var anyNonZero: Bool = false
for _ in 0..<8 {
let out: [[Double]] = ts.calculatedSamples(graph: graph, count: 512)
for ch: Int in 0..<out.count {
for i: Int in 0..<512 {
if !out[ch][i].isFinite { allFinite = false }
if out[ch][i] != 0 { anyNonZero = true }
}
}
advanceBlock(engine)
}
#expect(allFinite, "TimeStretch with timeDispersion: all samples finite")
#expect(anyNonZero, "TimeStretch with timeDispersion: produces non-zero output")
}
@Test func grainDurationJitterFiniteOutput() throws {
// Opt-in Warp1 `winrandamt`-style multiplicative jitter on grain length.
// Verify finite output and that variation is present across blocks.
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 88200, value: 1.0)
let ts: TimeStretch.Audio = TimeStretch.Audio(buffer: buf, pos: 0.5, windowSize: 0.05,
overlap: 4, grainDurationJitter: 0.1, seed: 250)
ts.amp = 1.0
var allFinite: Bool = true
var anyNonZero: Bool = false
for _ in 0..<8 {
let out: [[Double]] = ts.calculatedSamples(graph: graph, count: 512)
for ch: Int in 0..<out.count {
for i: Int in 0..<512 {
if !out[ch][i].isFinite { allFinite = false }
if out[ch][i] != 0 { anyNonZero = true }
}
}
advanceBlock(engine)
}
#expect(allFinite, "TimeStretch with grainDurationJitter: all samples finite")
#expect(anyNonZero, "TimeStretch with grainDurationJitter: produces non-zero output")
}
@Test func zeroTimeDispersionMatchesNominalSchedule() throws {
// With timeDispersion == 0, grain durations all equal _windowSizeSamples and
// the schedule is fully periodic — same seed across two instances must
// produce identical output.
let engine: SynthesisEngine = try makeEngine()
let g1: SynthGraph = makeSynthGraph(engine: engine)
let g2: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let buf: LyrebirdBuffer = makeConstantBuffer(frames: 44100, value: 1.0)
let ts1: TimeStretch.Audio = TimeStretch.Audio(buffer: buf, pos: 0.5, windowSize: 0.05,
overlap: 4, timeDispersion: 0.0, seed: 300)
ts1.amp = 1.0
let ts2: TimeStretch.Audio = TimeStretch.Audio(buffer: buf, pos: 0.5, windowSize: 0.05,
overlap: 4, timeDispersion: 0.0, seed: 300)
ts2.amp = 1.0
let out1: [[Double]] = ts1.calculatedSamples(graph: g1, count: 512)
let out2: [[Double]] = ts2.calculatedSamples(graph: g2, count: 512)
#expect(out1[0] == out2[0])
}
}