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,289 @@
// FormantGrainTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("FormantGrain")
struct FormantGrainTests {
func makeEngine(blockSize: Int = 512) throws -> SynthesisEngine {
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
return engine
}
// MARK: - Rate
@Test func rateIsAudio() throws {
let gen: FormantGrain.Audio = FormantGrain.Audio()
#expect(gen.rate == .audio)
}
// MARK: - Output shape
@Test func outputIsMonoOnechannel() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let gen: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 200.0)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
#expect(out.count == 1, "FormantGrain must produce mono (1 channel), got \(out.count)")
}
@Test func outputCountMatchesRequest() throws {
let engine: SynthesisEngine = try makeEngine(blockSize: 64)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let gen: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 200.0, amp: 0.5)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 64)
#expect(out[0].count >= 64, "Output must cover at least count samples")
// Verify the requested range was actually written to (not residual buffer state).
let writtenEnergy: Double = out[0].prefix(64).reduce(0.0) { $0 + abs($1) }
#expect(writtenEnergy > 0, "First 64 samples must be written by this block, not residual zeros")
}
// MARK: - Non-silence
@Test func firstBlockIsNonSilent() throws {
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
// Default params: 100 Hz glottal, 700 Hz formant — first grain fires at sample 0.
let gen: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 200.0, amp: 0.5)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
let energy: Double = out[0].prefix(512).reduce(0.0) { $0 + abs($1) }
#expect(energy > 0, "First block must be non-silent — grain fires at sample 0")
}
// MARK: - Grain envelope (rise then decay)
@Test func grainPeakOccursAfterRisePhase() throws {
// At 700 Hz formant / 44100 SR: rise = SR/(2*700) ≈ 31.5 samples.
// The peak should occur around sample 31.
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
// High glottalFreq relative to formant so only one grain fires in the block.
// Actually use very low glottal so only one grain fires: 1 Hz → hopSize ≈ 44100 samples.
let gen: FormantGrain.Audio = FormantGrain.Audio(
glottalFreq: 1.0,
formantFreq: 700.0,
bandwidth: 200.0,
amp: 1.0
)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
let samples: [Double] = out[0]
// First sample should be near zero (envelope starts at sin²(0) = 0).
#expect(abs(samples[0]) < 0.01, "First sample must be near zero (grain envelope starts at 0)")
// Find the sample with maximum absolute value.
let maxAbsIdx: Range<ArraySlice<Double>.Index>.Element = samples.prefix(512).indices.max(by: { abs(samples[$0]) < abs(samples[$1]) }) ?? 0
// Peak should be within a few samples of the theoretical rise end (~31.5 samples).
let expectedRise: Int = Int(44100.0 / (2.0 * 700.0))
#expect(maxAbsIdx >= expectedRise / 2, "Peak should occur after some rise; found at sample \(maxAbsIdx)")
}
// MARK: - Decay to silence
@Test func grainDecaysToSilenceAfterSufficientTime() throws {
// With bandwidth=2000 Hz, decay is very fast: exp(-π*2000/44100) ≈ 0.867 per sample.
// After ~64 samples the grain should be near silent (well below fofGrainDeathThreshold=1e-4).
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let gen: FormantGrain.Audio = FormantGrain.Audio(
glottalFreq: 0.5, // one grain, far from next trigger
formantFreq: 4000.0, // short rise
bandwidth: 5000.0, // very fast decay
amp: 1.0
)
// Run two full blocks.
_ = gen.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
let energy2: Double = out2[0].prefix(512).reduce(0.0) { $0 + abs($1) }
#expect(energy2 < 1e-2, "Grain must decay to near silence within the second block with high bandwidth")
}
// MARK: - Pool saturation
@Test func poolSaturationDoesNotProduceNaN() throws {
// Very high glottal rate + low bandwidth (long grains) → many overlapping grains.
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let gen: FormantGrain.Audio = FormantGrain.Audio(
glottalFreq: 2000.0, // triggers every ~22 samples
formantFreq: 500.0,
bandwidth: 10.0, // very slow decay → long grains
amp: 0.01
)
for _ in 0..<4 {
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
for s: Double in out[0].prefix(512) {
#expect(s.isFinite, "Output must be finite; pool overflow must not produce NaN/Inf")
}
advanceBlock(engine)
}
}
@Test func poolFullStealsOldestGrain() throws {
// Sustained over-saturation: glottal rate forces > poolSize grains alive simultaneously.
// Steal-oldest policy must keep producing audible output (not silence).
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
// 4000 Hz triggers every ~11 samples → ~46 spawns per 512-block.
// bandwidth=5 → decayFactor ≈ exp(-π*5/44100) ≈ 0.99964 — grains live thousands of samples.
let gen: FormantGrain.Audio = FormantGrain.Audio(
glottalFreq: 4000.0,
formantFreq: 600.0,
bandwidth: 5.0,
amp: 0.01
)
// Run several blocks to fully saturate the pool.
for _ in 0..<8 {
_ = gen.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
// After saturation, output must remain non-zero — steal-oldest keeps fresh grains active.
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
let energy: Double = out[0].prefix(512).reduce(0.0) { $0 + abs($1) }
#expect(energy > 0, "Output must remain audible after pool saturation; steal-oldest must keep new grains active")
}
@Test func glottalFreqAboveSampleRateIsClamped() throws {
// glottalFreq > sampleRate would cause hopSize < 1 and same-sample re-trigger;
// input clamp must keep output finite and prevent infinite spawn loop.
let engine: SynthesisEngine = try makeEngine(blockSize: 256)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let gen: FormantGrain.Audio = FormantGrain.Audio(
glottalFreq: 1_000_000.0, // absurdly high — gets clamped to sampleRate
formantFreq: 600.0,
bandwidth: 200.0,
amp: 0.01
)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 256)
for s: Double in out[0].prefix(256) {
#expect(s.isFinite, "Clamped glottalFreq must produce finite output")
}
}
@Test func formantFreqAboveSampleRateIsFinite() throws {
// formantFreq > sampleRate makes sinePhaseInc > 2π — wrap must use truncatingRemainder.
let engine: SynthesisEngine = try makeEngine(blockSize: 256)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let gen: FormantGrain.Audio = FormantGrain.Audio(
glottalFreq: 100.0,
formantFreq: 100_000.0, // way above 44.1k
bandwidth: 200.0,
amp: 0.5
)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 256)
for s: Double in out[0].prefix(256) {
#expect(s.isFinite, "formantFreq > sampleRate phase wrap must remain finite")
}
}
// MARK: - Octaviation
@Test func octaviationZeroAndOneProduceDifferentOutput() throws {
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
defer { engine.stop() }
let graph1: SynthGraph = makeSynthGraph(engine: engine)
let gen0: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 200.0,
octaviation: 0.0, amp: 0.5)
let out0: [[Double]] = gen0.calculatedSamples(graph: graph1, count: 512)
let gen1: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 200.0,
octaviation: 1.0, amp: 0.5)
let out1: [[Double]] = gen1.calculatedSamples(graph: graph1, count: 512)
// With octaviation, every other grain is negated — energy sum should differ.
let sum0: Double = out0[0].prefix(512).reduce(0.0, +)
let sum1: Double = out1[0].prefix(512).reduce(0.0, +)
let octaviationDiffEpsilon: Double = 1e-6
#expect(abs(sum0 - sum1) > octaviationDiffEpsilon,
"Octaviation=0 and =1 must produce meaningfully different output (sum0=\(sum0), sum1=\(sum1))")
}
// MARK: - MulAdd
@Test func mulScalesOutput() throws {
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let gen1x: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 200.0,
amp: 0.5, mul: 1.0)
let gen2x: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 200.0,
amp: 0.5, mul: 2.0)
let out1: [[Double]] = gen1x.calculatedSamples(graph: graph, count: 512)
let out2: [[Double]] = gen2x.calculatedSamples(graph: graph, count: 512)
let energy1: Double = out1[0].prefix(512).reduce(0.0) { $0 + abs($1) }
let energy2: Double = out2[0].prefix(512).reduce(0.0) { $0 + abs($1) }
#expect(abs(energy2 - 2.0 * energy1) < energy1 * 0.01,
"mul:2 must double output energy; got \(energy2) vs \(2.0 * energy1)")
}
// MARK: - Determinism
@Test func sameParamsSameOutput() throws {
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let gen1: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 80.0, formantFreq: 1000.0, bandwidth: 150.0, amp: 0.4)
let gen2: FormantGrain.Audio = FormantGrain.Audio(glottalFreq: 80.0, formantFreq: 1000.0, bandwidth: 150.0, amp: 0.4)
let out1: [[Double]] = gen1.calculatedSamples(graph: graph, count: 512)
let out2: [[Double]] = gen2.calculatedSamples(graph: graph, count: 512)
for i: Int in 0..<512 {
#expect(out1[0][i] == out2[0][i],
"Same params must produce identical output at sample \(i)")
}
}
// MARK: - GeneratorInput driving
@Test func generatorDrivenFormantFreqIsFinite() throws {
// When formantFreq is driven by a generator, output must remain finite.
let engine: SynthesisEngine = try makeEngine(blockSize: 512)
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let freqGen: OscSin.Audio = OscSin.Audio(freq: 1.0, mul: 200.0, add: 440.0)
let gen: FormantGrain.Audio = FormantGrain.Audio(
glottalFreq: 200.0,
formantFreq: freqGen,
bandwidth: 100.0,
amp: 0.3
)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
for s: Double in out[0].prefix(512) {
#expect(s.isFinite, "Generator-driven formantFreq must produce finite output")
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,424 @@
// PitchShiftTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("PitchShift.Audio (4-head SOLA)")
struct PitchShiftTests {
func makeEngine(blockSize: Int = 512) throws -> SynthesisEngine {
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
return engine
}
// MARK: - Silence
@Test func silenceInProducesSilence() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let ps: PitchShift.Audio = PitchShift.Audio(input: 0.0, pitchRatio: 1.0, seed: 1)
let out: [[Double]] = ps.calculatedSamples(graph: graph, count: 512)
#expect(out.count == 1, "PitchShift.Audio should output 1 channel, got \(out.count)")
let sum: Double = out[0].prefix(512).reduce(0.0, { $0 + abs($1) })
#expect(sum == 0.0, "Silence in should produce silence out")
}
// MARK: - Non-silent output
@Test func nonSilentInputProducesNonSilentOutput() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let ps: PitchShift.Audio = PitchShift.Audio(input: 0.5, pitchRatio: 1.0, windowSize: 0.05, seed: 1)
for _ in 0..<20 {
_ = ps.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let out: [[Double]] = ps.calculatedSamples(graph: graph, count: 512)
let sum: Double = out[0].prefix(512).reduce(0.0, { $0 + abs($1) })
#expect(sum > 0.0, "Non-silent input should produce non-silent output after warm-up")
}
// MARK: - Channel count
@Test func outputIsMono() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let ps: PitchShift.Audio = PitchShift.Audio(input: 0.5, seed: 1)
let out: [[Double]] = ps.calculatedSamples(graph: graph, count: 512)
#expect(out.count == 1, "PitchShift.Audio must output exactly 1 channel")
}
// MARK: - Pitch ratio clamping
@Test func pitchRatioAboveMaxClamped() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let ps: PitchShift.Audio = PitchShift.Audio(input: 0.5, pitchRatio: 8.0, windowSize: 0.05, seed: 1)
#expect(throws: Never.self) {
for _ in 0..<4 {
_ = ps.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
}
}
@Test func pitchRatioBelowMinClamped() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let ps: PitchShift.Audio = PitchShift.Audio(input: 0.5, pitchRatio: 0.01, windowSize: 0.05, seed: 1)
#expect(throws: Never.self) {
for _ in 0..<4 {
_ = ps.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
}
}
// MARK: - Pitch dispersion
@Test func pitchDispersionIntroducesVariance() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let ps: PitchShift.Audio = PitchShift.Audio(
input: 0.5,
pitchRatio: 1.0,
windowSize: 0.05,
pitchDispersion: 0.5,
seed: 99
)
var allSame: Bool = true
var prev: [Double] = []
for b: Int in 0..<10 {
let out: [[Double]] = ps.calculatedSamples(graph: graph, count: 512)
let cur: [Double] = Array(out[0].prefix(512))
if b > 0 && cur != prev { allSame = false; break }
prev = cur
advanceBlock(engine)
}
#expect(!allSame, "pitchDispersion > 0 should produce varying output across blocks")
}
// MARK: - mul / add
@Test func mulScalesOutput() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let ps1: PitchShift.Audio = PitchShift.Audio(input: 0.5, windowSize: 0.05, seed: 1, mul: 1.0)
let ps2: PitchShift.Audio = PitchShift.Audio(input: 0.5, windowSize: 0.05, seed: 1, mul: 2.0)
for _ in 0..<20 {
_ = ps1.calculatedSamples(graph: graph, count: 512)
_ = ps2.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let out1: [[Double]] = ps1.calculatedSamples(graph: graph, count: 512)
let out2: [[Double]] = ps2.calculatedSamples(graph: graph, count: 512)
let rms1: Double = out1[0].prefix(512).reduce(0.0) { $0 + $1 * $1 }
let rms2: Double = out2[0].prefix(512).reduce(0.0) { $0 + $1 * $1 }
#expect(rms1 > 0, "mul=1 output should have non-zero energy after warm-up")
if rms1 > 0 {
let ratio: Double = rms2 / rms1
#expect(ratio > 3.5 && ratio < 4.5,
"mul=2 should quadruple energy, got ratio \(ratio)")
}
}
// MARK: - Deterministic output
@Test func deterministicOutputWithFixedSeed() throws {
let engine: SynthesisEngine = try makeEngine()
defer { engine.stop() }
func run() -> [Double] {
let graph: SynthGraph = makeSynthGraph(engine: engine)
let ps: PitchShift.Audio = PitchShift.Audio(input: 0.5, pitchRatio: 1.0,
windowSize: 0.05, seed: 0xCAFE_BABE)
for _ in 0..<12 {
_ = ps.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let block: [[Double]] = ps.calculatedSamples(graph: graph, count: 512)
return Array(block[0].prefix(512))
}
let first: [Double] = run()
let second: [Double] = run()
let nonZero: Bool = first.contains { abs($0) > 1e-9 }
#expect(nonZero, "Output after warm-up must be non-zero for constant input")
for i: Int in 0..<512 {
#expect(first[i] == second[i],
"Sample \(i) differs across runs: \(first[i]) vs \(second[i])")
}
}
// MARK: - High pitch ratio read-head safety (4-head trails by construction)
@Test func highPitchRatioReadsRecentInputNotStaleWrap() throws {
// 4-head model uses startpos = framesize * (pchratio - 1) + 2, which keeps every
// head trailing the writer for any clamped pchratio. With constant input and
// SC's 0.5 output gain compensation, warmed-up output should equal inputLevel.
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let inputLevel: Double = 0.5
let ps: PitchShift.Audio = PitchShift.Audio(input: inputLevel, pitchRatio: 4.0,
windowSize: 0.05, seed: 7)
for _ in 0..<20 {
_ = ps.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let out: [[Double]] = ps.calculatedSamples(graph: graph, count: 512)
let block: [Double] = Array(out[0].prefix(512))
let avg: Double = block.reduce(0, +) / Double(block.count)
#expect(abs(avg - inputLevel) < 0.05,
"Avg output \(avg) must be near \(inputLevel) (post-0.5-gain) at pitchRatio=4")
let minSample: Double = block.min() ?? 0
#expect(minSample > inputLevel * 0.5,
"Min output \(minSample) must stay near \(inputLevel) — stale-wrap reads would drive it toward 0")
}
// MARK: - Output gain compensation
@Test func outputGainCompensationProducesUnityForConstantInput() throws {
// Triangle OLA at overlap=4 sums to 2.0; SC's 0.5 multiplier yields output
// ≈ inputLevel for a constant input at pitchRatio=1.
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let inputLevel: Double = 0.5
let ps: PitchShift.Audio = PitchShift.Audio(input: inputLevel, pitchRatio: 1.0,
windowSize: 0.05, seed: 1)
for _ in 0..<20 {
_ = ps.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let out: [[Double]] = ps.calculatedSamples(graph: graph, count: 512)
let block: [Double] = Array(out[0].prefix(512))
let avg: Double = block.reduce(0, +) / Double(block.count)
#expect(abs(avg - inputLevel) < 0.05,
"Constant input \(inputLevel) at pitchRatio=1 should yield avg \(inputLevel) after 0.5 gain comp, got \(avg)")
}
}
// MARK: - SpectralPitchShift
@MainActor
@Suite("SpectralPitchShift")
struct SpectralPitchShiftTests {
let fftSize: Int = 2048
let hopSize: Int = 512
func makeShift(ratio: Double = 1.0) -> SpectralPitchShift {
SpectralPitchShift(fftSize: fftSize, hopSize: hopSize, pitchRatio: ratio)
}
func makeBuffer() -> SpectralBuffer {
SpectralBuffer(fftSize: fftSize)
}
// MARK: - Init constraints
@Test func validInitSucceeds() {
let ps: SpectralPitchShift = SpectralPitchShift(fftSize: 1024, hopSize: 256)
#expect(ps.pitchRatio == 1.0)
}
// MARK: - Ratio property round-trip
@Test func pitchRatioRoundTrip() {
let ps: SpectralPitchShift = makeShift(ratio: 1.5)
#expect(abs(ps.pitchRatio - 1.5) < 1e-5)
ps.pitchRatio = 0.75
#expect(abs(ps.pitchRatio - 0.75) < 1e-5)
}
// MARK: - Unity ratio preserves magnitude energy
@Test func unityRatioPreservesMagnitudeEnergy() {
let ps: SpectralPitchShift = makeShift(ratio: 1.0)
let buf: SpectralBuffer = makeBuffer()
let half: Int = fftSize / 2
// Fill with unit magnitudes on all complex bins.
for k: Int in 1..<half {
buf[magnitude: k] = 1.0
buf[phase: k] = 0.0
}
// Run several hops to stabilise phase tracking.
for _ in 0..<4 { ps.process(spectral: buf, engine: makeTestEngine()) }
// Total energy should still be ~ half - 1 (one unit per bin).
var totalMag: Float = 0
for k: Int in 1..<half { totalMag += buf[magnitude: k] }
let expected: Float = Float(half - 1)
#expect(abs(totalMag - expected) / expected < 0.02,
"Unity ratio should preserve total magnitude energy within 2%, got \(totalMag)/\(expected)")
}
// MARK: - Pitch up remaps bins
@Test func pitchUpShiftsBinsHigher() {
let ps: SpectralPitchShift = makeShift(ratio: 2.0)
let buf: SpectralBuffer = makeBuffer()
let half: Int = fftSize / 2
// Single tone at bin 100.
buf[magnitude: 100] = 1.0
buf[phase: 100] = 0.0
ps.process(spectral: buf, engine: makeTestEngine())
// With ratio 2.0, bin 100 maps to bin 200.
let mag200: Float = buf[magnitude: 200]
let mag100: Float = buf[magnitude: 100]
#expect(mag200 > 0.5, "Bin 200 should have energy after 2× shift of bin 100, got \(mag200)")
#expect(mag100 < 0.5, "Bin 100 should have near-zero energy after shift away, got \(mag100)")
}
// MARK: - Pitch down remaps bins
@Test func pitchDownShiftsBinsLower() {
let ps: SpectralPitchShift = makeShift(ratio: 0.5)
let buf: SpectralBuffer = makeBuffer()
// Single tone at bin 400.
buf[magnitude: 400] = 1.0
buf[phase: 400] = 0.0
ps.process(spectral: buf, engine: makeTestEngine())
// With ratio 0.5, bin 400 maps to bin 200.
let mag200: Float = buf[magnitude: 200]
let mag400: Float = buf[magnitude: 400]
#expect(mag200 > 0.5, "Bin 200 should have energy after 0.5× shift of bin 400, got \(mag200)")
#expect(mag400 < 0.5, "Bin 400 should have near-zero energy after shift away, got \(mag400)")
}
// MARK: - Out-of-range bins zeroed
@Test func highBinsDiscardedOnPitchUp() {
// ratio=2.0: bins >= halfSize/2 map outside the buffer and are discarded.
let ps: SpectralPitchShift = makeShift(ratio: 2.0)
let buf: SpectralBuffer = makeBuffer()
let half: Int = fftSize / 2
// Place energy at the highest bin; 2× would map it past halfSize.
let srcBin: Int = half - 1
buf[magnitude: srcBin] = 1.0
ps.process(spectral: buf, engine: makeTestEngine())
// Destination would be srcBin * 2 >= halfSize → out of range → magnitude zeroed.
// The last valid output bin after 2× shift is (half-1)/2 = (1023) rounding.
// srcBin = 1023 → m = 2046 which is >= halfSize (1024) → discarded.
var anyHighBinHasEnergy: Bool = false
for k: Int in (half / 2 + 1)..<half {
if buf[magnitude: k] > 0.01 { anyHighBinHasEnergy = true; break }
}
#expect(!anyHighBinHasEnergy,
"Energy remapped outside range should be zeroed (no high bins with energy after 2× shift of top bin)")
}
// MARK: - DC and Nyquist zeroed
@Test func dcAndNyquistAreZeroedAfterProcess() {
let ps: SpectralPitchShift = makeShift(ratio: 1.5)
let buf: SpectralBuffer = makeBuffer()
buf.dcValue = 5.0
buf.nyquistValue = 3.0
ps.process(spectral: buf, engine: makeTestEngine())
#expect(buf.dcValue == 0, "DC should be zeroed after pitch shift")
#expect(buf.nyquistValue == 0, "Nyquist should be zeroed after pitch shift")
}
// MARK: - pitchRatio update mid-stream
@Test func pitchRatioUpdateNocrash() {
let ps: SpectralPitchShift = makeShift(ratio: 1.0)
let buf: SpectralBuffer = makeBuffer()
for k: Int in 1..<(fftSize / 2) {
buf[magnitude: k] = 0.5
}
ps.process(spectral: buf, engine: makeTestEngine())
ps.pitchRatio = 2.0
ps.process(spectral: buf, engine: makeTestEngine())
ps.pitchRatio = 0.5
ps.process(spectral: buf, engine: makeTestEngine())
// If we get here without crashing, the test passes.
#expect(true)
}
// MARK: - Chained with another processor
@Test func chainedWithMagnitudeScaleAppliesBoth() {
let ps: SpectralPitchShift = makeShift(ratio: 2.0)
let scale: SpectralMagnitudeScale = SpectralMagnitudeScale(scale: 0.5)
let buf: SpectralBuffer = makeBuffer()
// Single tone at bin 50.
buf[magnitude: 50] = 1.0
// Apply both processors in order.
ps.process(spectral: buf, engine: makeTestEngine())
scale.process(spectral: buf, engine: makeTestEngine())
// Bin 100 should have energy (from 2× shift), scaled by 0.5.
let mag100: Float = buf[magnitude: 100]
#expect(mag100 > 0.1 && mag100 < 0.9,
"After 2× shift then 0.5× scale, bin 100 should have ~0.5 magnitude, got \(mag100)")
}
// MARK: - Minimum fftSize
@Test func minimumFftSizeWorks() {
let ps: SpectralPitchShift = SpectralPitchShift(fftSize: 4, hopSize: 1, pitchRatio: 1.5)
let buf: SpectralBuffer = SpectralBuffer(fftSize: 4)
buf[magnitude: 1] = 1.0
buf[phase: 1] = 0.0
ps.process(spectral: buf, engine: makeTestEngine())
// fftSize=4 → halfSize=2, binCount=1. bin 1 × 1.5 = 1.5, rounds to 2 which is >= halfSize(2) → discarded.
#expect(buf[magnitude: 1] == 0, "Bin remapped out of range should be zeroed")
}
}
@@ -0,0 +1,263 @@
// TuneablePitchShiftTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("TuneablePitchShift")
struct TuneablePitchShiftTests {
func makeEngine(blockSize: Int = 512) throws -> SynthesisEngine {
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
return engine
}
// MARK: - Silence
@Test func silenceInProducesSilence() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let ps: TuneablePitchShift.Audio = TuneablePitchShift.Audio(input: 0.0, pitchRatio: 1.0, seed: 1)
let out: [[Double]] = ps.calculatedSamples(graph: graph, count: 512)
#expect(out.count == 1, "TuneablePitchShift.Audio should output 1 channel, got \(out.count)")
let sum: Double = out[0].prefix(512).reduce(0.0, { $0 + abs($1) })
#expect(sum == 0.0, "Silence in should produce silence out")
}
// MARK: - Non-silent output
@Test func nonSilentInputProducesNonSilentOutput() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
// Use a constant input so capture buffer fills with non-zero signal.
let ps: TuneablePitchShift.Audio = TuneablePitchShift.Audio(input: 0.5, pitchRatio: 1.0, windowSize: 0.05, overlap: 4, seed: 1)
// Run several blocks to fill capture buffer past one window.
for _ in 0..<20 {
_ = ps.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let out: [[Double]] = ps.calculatedSamples(graph: graph, count: 512)
let sum: Double = out[0].prefix(512).reduce(0.0, { $0 + abs($1) })
#expect(sum > 0.0, "Non-silent input should produce non-silent output after warm-up")
}
// MARK: - Channel count
@Test func outputIsMono() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let ps: TuneablePitchShift.Audio = TuneablePitchShift.Audio(input: 0.5, seed: 1)
let out: [[Double]] = ps.calculatedSamples(graph: graph, count: 512)
#expect(out.count == 1, "TuneablePitchShift.Audio must output exactly 1 channel")
}
// MARK: - Pitch ratio clamping
@Test func pitchRatioAboveMaxClamped() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
// ratio=8.0 should clamp to 4.0 — no crash.
let ps: TuneablePitchShift.Audio = TuneablePitchShift.Audio(input: 0.5, pitchRatio: 8.0, windowSize: 0.05, seed: 1)
#expect(throws: Never.self) {
for _ in 0..<4 {
_ = ps.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
}
}
@Test func pitchRatioBelowMinClamped() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
// ratio=0.01 should clamp to 0.25 — no crash.
let ps: TuneablePitchShift.Audio = TuneablePitchShift.Audio(input: 0.5, pitchRatio: 0.01, windowSize: 0.05, seed: 1)
#expect(throws: Never.self) {
for _ in 0..<4 {
_ = ps.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
}
}
// MARK: - Grain pool saturation
@Test func grainPoolSaturationNocrash() throws {
// overlap > pool size: new triggers are silently dropped, no crash.
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let ps: TuneablePitchShift.Audio = TuneablePitchShift.Audio(
input: 0.5,
pitchRatio: 1.0,
windowSize: 0.05,
overlap: lyrebirdGrainPoolSize + 10,
seed: 1
)
#expect(throws: Never.self) {
for _ in 0..<4 {
_ = ps.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
}
}
// MARK: - Pitch dispersion
@Test func pitchDispersionIntroducesVariance() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
// Warm up capture buffer with 0.5 signal.
let ps: TuneablePitchShift.Audio = TuneablePitchShift.Audio(
input: 0.5,
pitchRatio: 1.0,
windowSize: 0.05,
overlap: 4,
pitchDispersion: 0.5,
seed: 99
)
var allSame: Bool = true
var prev: [Double] = []
for b: Int in 0..<10 {
let out: [[Double]] = ps.calculatedSamples(graph: graph, count: 512)
let cur: [Double] = Array(out[0].prefix(512))
if b > 0 && cur != prev { allSame = false; break }
prev = cur
advanceBlock(engine)
}
// With dispersion, consecutive blocks should differ — proves PRNG varies per-grain.
#expect(!allSame, "pitchDispersion > 0 should produce varying output across blocks")
}
// MARK: - mul / add
@Test func mulScalesOutput() throws {
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let ps1: TuneablePitchShift.Audio = TuneablePitchShift.Audio(input: 0.5, windowSize: 0.05, overlap: 4, seed: 1, mul: 1.0)
let ps2: TuneablePitchShift.Audio = TuneablePitchShift.Audio(input: 0.5, windowSize: 0.05, overlap: 4, seed: 1, mul: 2.0)
for _ in 0..<20 {
_ = ps1.calculatedSamples(graph: graph, count: 512)
_ = ps2.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let out1: [[Double]] = ps1.calculatedSamples(graph: graph, count: 512)
let out2: [[Double]] = ps2.calculatedSamples(graph: graph, count: 512)
let rms1: Double = out1[0].prefix(512).reduce(0.0) { $0 + $1 * $1 }
let rms2: Double = out2[0].prefix(512).reduce(0.0) { $0 + $1 * $1 }
#expect(rms1 > 0, "mul=1 output should have non-zero energy after warm-up")
if rms1 > 0 {
// mul=2 → energy is 4× that of mul=1 (within tolerance for floating point).
let ratio: Double = rms2 / rms1
#expect(ratio > 3.5 && ratio < 4.5, "mul=2 should quadruple energy, got ratio \(ratio)")
}
}
// MARK: - Deterministic output
@Test func deterministicOutputWithFixedSeed() throws {
// Fixed seed + constant input must produce bit-identical output across runs.
let engine: SynthesisEngine = try makeEngine()
defer { engine.stop() }
func run() -> [Double] {
let graph: SynthGraph = makeSynthGraph(engine: engine)
let ps: TuneablePitchShift.Audio = TuneablePitchShift.Audio(input: 0.5, pitchRatio: 1.0,
windowSize: 0.05, overlap: 4, seed: 0xCAFE_BABE)
var out: [Double] = []
// Warm up: fill capture buffer past one window.
for _ in 0..<12 {
_ = ps.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let block: [[Double]] = ps.calculatedSamples(graph: graph, count: 512)
out = Array(block[0].prefix(512))
return out
}
let first: [Double] = run()
let second: [Double] = run()
// Some samples must be non-zero (not silence).
let nonZero: Bool = first.contains { abs($0) > 1e-9 }
#expect(nonZero, "Output after warm-up must be non-zero for constant input")
// Both runs must match sample-for-sample (fixed seed → deterministic PRNG).
for i: Int in 0..<512 {
#expect(first[i] == second[i],
"Sample \(i) differs across runs: \(first[i]) vs \(second[i])")
}
}
// MARK: - High pitch ratio read-head safety
@Test func highPitchRatioReadsRecentInputNotStaleWrap() throws {
// Regression: prior to the lookback fix, at pitchRatio > 2 the grain phase
// overtook the writer mid-grain and wrapped to stale circular content.
// After the fix the lookback is `pitchRatio * windowSamples` so the grain
// always trails the writer. With a constant input and overlap = 4 (triangle
// OLA = 1.0), warmed-up output must equal the input level for every sample.
let engine: SynthesisEngine = try makeEngine()
let graph: SynthGraph = makeSynthGraph(engine: engine)
defer { engine.stop() }
let inputLevel: Double = 0.5
let ps: TuneablePitchShift.Audio = TuneablePitchShift.Audio(
input: inputLevel,
pitchRatio: 4.0,
windowSize: 0.05,
overlap: 4,
seed: 7
)
// Warm up long enough for the largest possible lookback (4 × windowSize).
for _ in 0..<20 {
_ = ps.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let out: [[Double]] = ps.calculatedSamples(graph: graph, count: 512)
let block: [Double] = Array(out[0].prefix(512))
// Constant input × triangle OLA at overlap=4 → near-constant output equal to
// input × OLA gain (≈ 2.0 for triangle window at hop = window/4). The buggy
// version returned ~0 for a fraction of samples (stale wrap hit zero-initialized
// regions), so avg dropped well below the OLA gain and minSample dipped toward 0.
let olaGain: Double = 2.0
let expectedLevel: Double = inputLevel * olaGain
let avg: Double = block.reduce(0, +) / Double(block.count)
#expect(abs(avg - expectedLevel) < 0.1,
"Avg output \(avg) must be near \(expectedLevel) at pitchRatio=4")
// No sample should drop far below half of the expected level — that would
// indicate the grain read into stale circular content.
let minSample: Double = block.min() ?? 0
#expect(minSample > expectedLevel * 0.5,
"Min output \(minSample) must stay near \(expectedLevel) — stale-wrap reads would drive it toward 0")
}
}