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

262 lines
10 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SpectralFormantShiftTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@Suite("SpectralFormantShift")
struct SpectralFormantShiftTests {
// MARK: - Helpers
/// Gaussian-shaped magnitude envelope centred on `center`.
private static func gaussian(
bins: Int,
center: Float,
sigma: Float
) -> [Float] {
var out: [Float] = [Float](repeating: 0, count: bins)
for k: Int in 0..<bins {
let d: Float = (Float(k) - center) / sigma
out[k] = exp(-0.5 * d * d)
}
return out
}
private static func argMax(_ a: [Float]) -> Int {
var best: Int = 0
var bestVal: Float = a[0]
for i: Int in 1..<a.count {
if a[i] > bestVal { bestVal = a[i]; best = i }
}
return best
}
// MARK: - Tests
@Test func ratioOneIsBypass() {
let fftSize: Int = 256
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let halfSize: Int = fftSize / 2
let envelope: [Float] = Self.gaussian(bins: halfSize + 1, center: 60, sigma: 12)
buf.dcValue = 0.3
buf.nyquistValue = -0.4
for k: Int in 1..<halfSize {
buf[magnitude: k] = envelope[k]
buf[phase: k] = 0.25 * Float(k)
}
let fs: SpectralFormantShift = SpectralFormantShift(fftSize: fftSize, shiftRatio: 1.0)
fs.process(spectral: buf, engine: makeTestEngine())
#expect(buf.dcValue == 0.3)
#expect(buf.nyquistValue == -0.4)
for k: Int in 1..<halfSize {
#expect(buf[magnitude: k] == envelope[k])
#expect(buf[phase: k] == 0.25 * Float(k))
}
}
@Test func cepstralPeakShiftsUp() {
let fftSize: Int = 512
let halfSize: Int = fftSize / 2
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let srcCenter: Float = 40
let envelope: [Float] = Self.gaussian(bins: halfSize + 1, center: srcCenter, sigma: 12)
for k: Int in 1..<halfSize {
buf[magnitude: k] = envelope[k]
buf[phase: k] = 0
}
let fs: SpectralFormantShift = SpectralFormantShift(
fftSize: fftSize,
shiftRatio: 2.0,
method: .cepstral,
cepstralCutoffQuefrency: 24
)
fs.process(spectral: buf, engine: makeTestEngine())
var out: [Float] = [Float](repeating: 0, count: halfSize)
for k: Int in 0..<halfSize { out[k] = buf.magnitude(at: k) }
let peakBin: Int = Self.argMax(out)
let expectedBin: Int = Int(srcCenter * 2)
// Cepstral lifter introduces a small bias relative to a true bin-axis
// resampling; ±8 bins is comfortably within the formant feature width.
#expect(abs(peakBin - expectedBin) <= 8,
"expected peak near bin \(expectedBin), got \(peakBin)")
}
@Test func cepstralEnvelopeIsSmootherThanHarmonicInput() {
// The cepstral lifter should separate slow formant structure from fast
// harmonic structure. Feed a harmonic comb modulated by a smooth
// gaussian formant; the estimated envelope should have far lower
// bin-to-bin variation than the input magnitude spectrum.
let fftSize: Int = 512
let halfSize: Int = fftSize / 2
let n: Int = halfSize + 1
let formant: [Float] = Self.gaussian(bins: n, center: 80, sigma: 30)
let harmonicSpacing: Int = 8
let magPtr: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: n)
defer { magPtr.deinitialize(count: n); magPtr.deallocate() }
let envPtr: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: n)
defer { envPtr.deinitialize(count: n); envPtr.deallocate() }
magPtr.initialize(repeating: 0, count: n)
envPtr.initialize(repeating: 0, count: n)
for k: Int in 0..<n {
magPtr[k] = (k % harmonicSpacing == 0) ? formant[k] : 0
}
let est: CepstralEnvelopeEstimator = CepstralEnvelopeEstimator(fftSize: fftSize, cutoffQuefrency: 24)
est.estimate(magnitudes: magPtr, into: envPtr)
// Total-variation-style metric: sum of |x[k+1] − x[k]|.
var tvInput: Float = 0
var tvEnv: Float = 0
for k: Int in 0..<(n - 1) {
tvInput += abs(magPtr[k + 1] - magPtr[k])
tvEnv += abs(envPtr[k + 1] - envPtr[k])
}
#expect(tvEnv < tvInput * 0.5,
"estimated envelope total-variation \(tvEnv) is not < 0.5× input \(tvInput) — lifter did not smooth harmonics")
}
@Test func residualReapplyIsIdentity() {
// Math identity: (mag / (env + ε)) × env ≈ mag, independent of env
// quality. Guards against precision regressions in the residual /
// reapply formula used by `process(spectral:)`.
let fftSize: Int = 256
let halfSize: Int = fftSize / 2
let n: Int = halfSize + 1
let envIn: [Float] = Self.gaussian(bins: n, center: 30, sigma: 10)
let est: CepstralEnvelopeEstimator = CepstralEnvelopeEstimator(fftSize: fftSize, cutoffQuefrency: 32)
let magPtr: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: n)
defer { magPtr.deinitialize(count: n); magPtr.deallocate() }
let envPtr: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: n)
defer { envPtr.deinitialize(count: n); envPtr.deallocate() }
magPtr.initialize(repeating: 0, count: n)
envPtr.initialize(repeating: 0, count: n)
for k: Int in 0..<n { magPtr[k] = envIn[k] + 1e-6 }
est.estimate(magnitudes: magPtr, into: envPtr)
let eps: Float = 1e-9
var maxRelErr: Float = 0
for k: Int in 0..<n {
let mag: Float = magPtr[k]
let rec: Float = (mag / (envPtr[k] + eps)) * envPtr[k]
let denom: Float = max(mag, 1e-6)
let err: Float = abs(rec - mag) / denom
if err > maxRelErr { maxRelErr = err }
}
#expect(maxRelErr < 5e-3,
"residual×envelope round-trip max relative error \(maxRelErr) exceeds 5e-3")
}
@Test func phaseUntouched() {
let fftSize: Int = 256
let halfSize: Int = fftSize / 2
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let envelope: [Float] = Self.gaussian(bins: halfSize + 1, center: 30, sigma: 10)
let phases: [Float] = (1..<halfSize).map { Float($0) * 0.17 }
for k: Int in 1..<halfSize {
buf[magnitude: k] = envelope[k]
buf[phase: k] = phases[k - 1]
}
let fs: SpectralFormantShift = SpectralFormantShift(fftSize: fftSize, shiftRatio: 1.7)
fs.process(spectral: buf, engine: makeTestEngine())
for k: Int in 1..<halfSize {
#expect(buf[phase: k] == phases[k - 1],
"phase at bin \(k) changed: \(buf[phase: k]) vs \(phases[k - 1])")
}
}
@Test func magnitudeSmoothingFallbackSmoke() {
let fftSize: Int = 256
let halfSize: Int = fftSize / 2
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
// Flat input — envelope estimator returns a constant, residual ≈ 1
// across all bins, so the resampled envelope (also flat) produces a
// non-zero, near-flat output. Verifies the smoothing path runs and
// does not crash.
for k: Int in 1..<halfSize { buf[magnitude: k] = 0.5 }
let fs: SpectralFormantShift = SpectralFormantShift(
fftSize: fftSize,
shiftRatio: 1.5,
method: .magnitudeSmoothing(radiusBins: 4)
)
fs.process(spectral: buf, engine: makeTestEngine())
var nonZeroCount: Int = 0
for k: Int in 1..<halfSize where buf[magnitude: k] > 1e-3 { nonZeroCount += 1 }
#expect(nonZeroCount > halfSize / 2,
"smoothing path should leave most bins non-zero on flat input, got \(nonZeroCount)")
}
@Test func dcSignPreserved() {
let fftSize: Int = 128
let halfSize: Int = fftSize / 2
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
buf.dcValue = -0.7
buf.nyquistValue = -0.3
// Wider envelope keeps DC and Nyquist envelope values appreciably > 0
// so the resampled envelope never collapses to 0 at the edges.
let envelope: [Float] = Self.gaussian(bins: halfSize + 1, center: 32, sigma: 24)
for k: Int in 1..<halfSize { buf[magnitude: k] = envelope[k] }
let fs: SpectralFormantShift = SpectralFormantShift(
fftSize: fftSize,
shiftRatio: 1.5,
method: .magnitudeSmoothing(radiusBins: 4)
)
fs.process(spectral: buf, engine: makeTestEngine())
// `< 0` (strict) — `<= 0` would vacuously accept a zero collapse and
// miss an accidental sign flip to `+0`.
#expect(buf.dcValue < 0, "DC sign not preserved, got \(buf.dcValue)")
#expect(buf.nyquistValue < 0, "Nyquist sign not preserved, got \(buf.nyquistValue)")
}
@Test func invalidBufferIsNoOp() {
let fftSize: Int = 128
let halfSize: Int = fftSize / 2
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
for k: Int in 1..<halfSize { buf[magnitude: k] = Float(k) }
buf.invalidate()
let fs: SpectralFormantShift = SpectralFormantShift(fftSize: fftSize, shiftRatio: 2.0)
fs.process(spectral: buf, engine: makeTestEngine())
for k: Int in 1..<halfSize {
#expect(buf[magnitude: k] == Float(k), "invalid buffer was modified at bin \(k)")
}
}
@Test func shiftRatioClampedOnLiveUpdate() {
let fs: SpectralFormantShift = SpectralFormantShift(fftSize: 64, shiftRatio: 1.0)
fs.shiftRatio = 10.0
#expect(fs.shiftRatio == 4.0)
fs.shiftRatio = 0.01
#expect(fs.shiftRatio == 0.25)
}
@Test func mismatchedFftSizeIsNoOp() {
let fs: SpectralFormantShift = SpectralFormantShift(fftSize: 128, shiftRatio: 2.0)
let buf: SpectralBuffer = SpectralBuffer(fftSize: 256)
let halfSize: Int = 128
for k: Int in 1..<halfSize { buf[magnitude: k] = Float(k) }
fs.process(spectral: buf, engine: makeTestEngine())
for k: Int in 1..<halfSize {
#expect(buf[magnitude: k] == Float(k))
}
}
}