Files
Lyrebird/Tests/LyrebirdTests/HalfbandDownsampler2xTests.swift
T

85 lines
3.2 KiB
Swift

// HalfbandDownsampler2xTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("HalfbandDownsampler2x")
struct HalfbandDownsampler2xTests {
@Test("DC input becomes DC output (gain = 1.0)")
func dcGainIsUnity() {
var dn: HalfbandDownsampler2x = HalfbandDownsampler2x()
let warmupPairs: Int = HalfbandFIR.length
var y: Double = 0.0
for _ in 0..<warmupPairs {
y = dn.process(1.0, 1.0)
}
for _ in 0..<64 {
y = dn.process(1.0, 1.0)
}
#expect(abs(y - 1.0) < 1e-9)
}
@Test("Reset clears state to zero")
func resetClearsState() {
var dn: HalfbandDownsampler2x = HalfbandDownsampler2x()
for _ in 0..<HalfbandFIR.length {
_ = dn.process(1.0, 1.0)
}
dn.reset()
let y: Double = dn.process(0.0, 0.0)
#expect(y == 0.0)
}
@Test("Impulse on even upsampled phase hits only the center tap (0.5 at frame 5)")
func impulseAtEvenPhaseHitsCenterTap() {
var dn: HalfbandDownsampler2x = HalfbandDownsampler2x()
// x0 = 1 → impulse at upsampled index 0 (even phase). Even-phase
// impulses are filtered only by odd-absolute-index taps, all of
// which are zero in a halfband FIR except the center tap h[11] = 0.5.
// Group delay 11 upsampled samples = 5 input pairs → output is 0.5
// at decimated frame 5, zero elsewhere.
var outs: [Double] = []
outs.append(dn.process(1.0, 0.0))
for _ in 0..<10 {
outs.append(dn.process(0.0, 0.0))
}
#expect(abs(outs[5] - HalfbandFIR.centerCoef) < 1e-12)
for i: Int in 0..<outs.count where i != 5 {
#expect(outs[i] == 0.0)
}
}
@Test("Impulse on odd upsampled phase hits only even-absolute-index taps (folded ringing)")
func impulseAtOddPhaseHitsFoldedTaps() {
var dn: HalfbandDownsampler2x = HalfbandDownsampler2x()
// x1 = 1 → impulse at upsampled index 1 (odd phase). Odd-phase
// impulses are filtered only by even-absolute-index taps. The
// resulting decimated impulse response visits h[0], h[2], …, h[22]
// in order. By symmetry these equal `foldedCoefs[i]` and
// `foldedCoefs[foldedCount-1-i]` paired around frames 5 and 6.
var outs: [Double] = []
outs.append(dn.process(0.0, 1.0))
for _ in 0..<14 {
outs.append(dn.process(0.0, 0.0))
}
// Frames 0..5 walk through folded[0] → folded[5]; 6..11 mirror back.
for i: Int in 0...5 {
#expect(abs(outs[i] - HalfbandFIR.foldedCoefs[i]) < 1e-12)
#expect(abs(outs[11 - i] - HalfbandFIR.foldedCoefs[i]) < 1e-12)
}
// Sum of the visible response = 2 · sumFolded = 2 · 0.25 = 0.5
// (the even-absolute-index taps contribute exactly half of the
// FIR's total DC gain of 1.0; the other half lives in the center tap,
// which is invisible to odd-phase impulses).
let sum: Double = outs.prefix(12).reduce(0.0, +)
#expect(abs(sum - 0.5) < 1e-9)
}
}