// 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.. Int { var best: Int = 0 var bestVal: Float = a[0] for i: Int in 1.. 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.. = UnsafeMutablePointer.allocate(capacity: n) defer { magPtr.deinitialize(count: n); magPtr.deallocate() } let envPtr: UnsafeMutablePointer = UnsafeMutablePointer.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.. = UnsafeMutablePointer.allocate(capacity: n) defer { magPtr.deinitialize(count: n); magPtr.deallocate() } let envPtr: UnsafeMutablePointer = UnsafeMutablePointer.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.. 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.. 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..