// PitchShiftTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing @testable @_spi(LyrebirdExtensions) import LyrebirdSynth @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 @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.. 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).. 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") } }