// HalfbandRoundTripTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing import Foundation @testable @_spi(LyrebirdExtensions) import LyrebirdSynth @MainActor @Suite("Halfband oversampling round-trip") struct HalfbandRoundTripTests { @Test("2× up → 2× down preserves DC at unity gain") func roundTripDC2x() { var up: HalfbandUpsampler2x = HalfbandUpsampler2x() var dn: HalfbandDownsampler2x = HalfbandDownsampler2x() var last: Double = 0.0 for _ in 0..<128 { let (a, b) = up.process(1.0) last = dn.process(a, b) } #expect(abs(last - 1.0) < 1e-9) } @Test("2× up → 2× down preserves a low-frequency sine RMS within tight tolerance") func roundTripSineRMS2x() { var up: HalfbandUpsampler2x = HalfbandUpsampler2x() var dn: HalfbandDownsampler2x = HalfbandDownsampler2x() let length: Int = 4096 let warmup: Int = 128 let normalisedFreq: Double = 1.0 / 32.0 // cycles per input sample, well below Fs/4 let twoPi: Double = 2.0 * .pi var inputs: [Double] = [Double](repeating: 0.0, count: length) var outputs: [Double] = [Double](repeating: 0.0, count: length) for n: Int in 0..0.25 of working rate), simulating a typical // image generated by a non-bandlimited 2× zero-stuff or by a // nonlinearity inserted between up and down stages. The downsampler // alone must attenuate it heavily. let length: Int = 4096 let warmup: Int = 256 let normalisedFreq: Double = 0.45 // cycles per upsampled-rate sample let twoPi: Double = 2.0 * .pi var inputs: [Double] = [Double](repeating: 0.0, count: length) var outputs: [Double] = [Double](repeating: 0.0, count: length / 2) for n: Int in 0..