// HilbertTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing import Foundation @testable @_spi(LyrebirdExtensions) import LyrebirdSynth @Suite("Hilbert") struct HilbertTests { let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100) var graph: SynthGraph { makeSynthGraph(engine: engine) } let testSampleRate: Double = 44100 init() throws { try engine.start() } // MARK: - Helpers /// Render `totalSamples` of a Hilbert pair driven by a sine at `freqHz`. /// Returns (pathA, pathB) arrays of length `totalSamples`. private func renderSine( freqHz: Double, totalSamples: Int ) -> (a: [Double], b: [Double]) { let osc: OscSin.Audio = OscSin.Audio(freq: freqHz) let h: Hilbert.Audio = Hilbert.Audio(input: osc) let blockSize: Int = engine.blockSize var a: [Double] = [] var b: [Double] = [] a.reserveCapacity(totalSamples) b.reserveCapacity(totalSamples) var rendered: Int = 0 while rendered < totalSamples { let g: SynthGraph = makeSynthGraph(engine: engine) let n: Int = min(blockSize, totalSamples - rendered) let out: [[Double]] = h.calculatedSamples(graph: g, count: n) a.append(contentsOf: out[0].prefix(n)) b.append(contentsOf: out[1].prefix(n)) advanceBlock(engine) rendered += n } return (a, b) } // MARK: - 1. Rate / channel count @Test func rateIsAudio() { let h: Hilbert.Audio = Hilbert.Audio(input: 0.0) #expect(h.rate == .audio) } @Test func outputCountTwoChannels() { let h: Hilbert.Audio = Hilbert.Audio(input: ConstantGeneratorInput(0.5)) let out: [[Double]] = h.calculatedSamples(graph: graph, count: 64) #expect(out.count == 2) #expect(h.outputChannelCount == 2) } // MARK: - 2. Analytic-signal magnitude — sqrt(xA² + xB²) ≈ input amplitude @Test func analyticMagnitudeWithinHalfDbAt1kHz() { verifyAnalyticMagnitude(freqHz: 1_000, toleranceDb: 0.5) } @Test func analyticMagnitudeWithinHalfDbAt5kHz() { verifyAnalyticMagnitude(freqHz: 5_000, toleranceDb: 0.5) } @Test func analyticMagnitudeWithinHalfDbAt10kHz() { verifyAnalyticMagnitude(freqHz: 10_000, toleranceDb: 0.5) } private func verifyAnalyticMagnitude(freqHz: Double, toleranceDb: Double) { let warmup: Int = 4096 let measure: Int = 4096 let (a, b): ([Double], [Double]) = renderSine(freqHz: freqHz, totalSamples: warmup + measure) var envSqSum: Double = 0 for i: Int in warmup..<(warmup + measure) { envSqSum += a[i] * a[i] + b[i] * b[i] } let meanEnvSq: Double = envSqSum / Double(measure) // Input sine has amplitude 1 → mean(xA² + xB²) should be 1.0 for a perfect Hilbert. let errorDb: Double = 10.0 * log10(meanEnvSq) #expect(abs(errorDb) < toleranceDb, "\(freqHz) Hz: analytic magnitude error \(errorDb) dB exceeds ±\(toleranceDb) dB") } // MARK: - 3. Envelope flatness — (xA² + xB²) should be near constant for a Hilbert pair // // For sin input through an ideal Hilbert pair (pathA in-phase, pathB 90° leading), // pathA² + pathB² ≈ sin²(θ) + cos²(θ) = const. If the two paths were identical // (no Hilbert action), the same sum would be 2·sin²(θ) — oscillating between 0 // and 2 with mean 1. Variance of the envelope distinguishes the two cases — a true // Hilbert pair has near-zero envelope variance. @Test func envelopeFlatnessAt1kHz() { verifyEnvelopeFlatness(freqHz: 1_000, maxVarianceRatio: 0.05) } @Test func envelopeFlatnessAt5kHz() { verifyEnvelopeFlatness(freqHz: 5_000, maxVarianceRatio: 0.05) } @Test func envelopeFlatnessAt10kHz() { verifyEnvelopeFlatness(freqHz: 10_000, maxVarianceRatio: 0.05) } private func verifyEnvelopeFlatness(freqHz: Double, maxVarianceRatio: Double) { let warmup: Int = 4096 let measure: Int = 4096 let (a, b): ([Double], [Double]) = renderSine(freqHz: freqHz, totalSamples: warmup + measure) var sum: Double = 0 for i: Int in warmup..<(warmup + measure) { sum += a[i] * a[i] + b[i] * b[i] } let mean: Double = sum / Double(measure) var ssDev: Double = 0 for i: Int in warmup..<(warmup + measure) { let env: Double = a[i] * a[i] + b[i] * b[i] let d: Double = env - mean ssDev += d * d } let variance: Double = ssDev / Double(measure) let ratio: Double = variance / (mean * mean) #expect(ratio < maxVarianceRatio, "\(freqHz) Hz: envelope variance / mean² = \(ratio), expected < \(maxVarianceRatio) for a quadrature pair") } // MARK: - 4. SSB integration — Hilbert pair drives proper single-sideband recovery // // End-to-end smoke: feed a 1 kHz sine through FrequencyShifter (which consumes // Hilbert.Audio post-refactor) shifted up by 200 Hz. Upper sideband should contain // 1200 Hz; lower sideband should contain 800 Hz. Confirms the extracted Hilbert // produces a Hilbert pair sufficient for SSB modulation — the canonical downstream // use case. @Test func ssbIntegrationViaFrequencyShifter() { let sourceFreqHz: Double = 1_000 let shiftHz: Double = 200 let shifter: FrequencyShifter.Audio = FrequencyShifter.Audio( input: OscSin.Audio(freq: sourceFreqHz), shiftHz: shiftHz, sampleRate: testSampleRate ) let warmup: Int = 4096 let measure: Int = 4096 let blockSize: Int = engine.blockSize var upper: [Double] = [] var lower: [Double] = [] upper.reserveCapacity(warmup + measure) lower.reserveCapacity(warmup + measure) var rendered: Int = 0 while rendered < warmup + measure { let g: SynthGraph = makeSynthGraph(engine: engine) let n: Int = min(blockSize, warmup + measure - rendered) let out: [[Double]] = shifter.calculatedSamples(graph: g, count: n) upper.append(contentsOf: out[0].prefix(n)) lower.append(contentsOf: out[1].prefix(n)) advanceBlock(engine) rendered += n } // Goertzel single-bin power at expected and unexpected target frequencies. func goertzelPower(_ samples: ArraySlice, freqHz: Double) -> Double { let omega: Double = 2.0 * .pi * freqHz / testSampleRate let coeff: Double = 2.0 * cos(omega) var s0: Double = 0 var s1: Double = 0 var s2: Double = 0 for x: Double in samples { s0 = x + coeff * s1 - s2 s2 = s1 s1 = s0 } return s1 * s1 + s2 * s2 - coeff * s1 * s2 } let upperSlice: ArraySlice = upper[warmup..<(warmup + measure)] let lowerSlice: ArraySlice = lower[warmup..<(warmup + measure)] let upperAtTarget: Double = goertzelPower(upperSlice, freqHz: sourceFreqHz + shiftHz) // 1200 let upperAtOpposite: Double = goertzelPower(upperSlice, freqHz: sourceFreqHz - shiftHz) // 800 let lowerAtTarget: Double = goertzelPower(lowerSlice, freqHz: sourceFreqHz - shiftHz) // 800 let lowerAtOpposite: Double = goertzelPower(lowerSlice, freqHz: sourceFreqHz + shiftHz) // 1200 // Suppression ratio target / opposite > 20 dB (factor 100 in power). The Niemitalo // IIR Hilbert is approximate — measured suppression at 1 kHz with 200 Hz shift sits // around 30 dB, well above the 20 dB practical-use threshold. let minRatio: Double = 100 #expect(upperAtTarget > minRatio * upperAtOpposite, "Upper sideband: target / opposite = \(upperAtTarget / upperAtOpposite), expected > \(minRatio)") #expect(lowerAtTarget > minRatio * lowerAtOpposite, "Lower sideband: target / opposite = \(lowerAtTarget / lowerAtOpposite), expected > \(minRatio)") } // MARK: - 5. Scalar input (DC) — both rows settle to a finite value @Test func dcInputSettlesToFiniteValue() { let h: Hilbert.Audio = Hilbert.Audio(input: 0.5) // Highest-Q pole at radius ~0.9994 → τ ≈ 1500 samples. 24576 ≈ 16τ // gives ~1e-7 settling on the slow pole — comfortably under 1e-4. let settleSamples: Int = 24576 var rendered: Int = 0 let blockSize: Int = engine.blockSize var lastA: Double = 0 var lastB: Double = 0 while rendered < settleSamples { let g: SynthGraph = makeSynthGraph(engine: engine) let out: [[Double]] = h.calculatedSamples(graph: g, count: blockSize) lastA = out[0][blockSize - 1] lastB = out[1][blockSize - 1] advanceBlock(engine) rendered += blockSize } #expect(lastA.isFinite) #expect(lastB.isFinite) // For DC input, both all-pass paths converge to the same steady-state value (the input). #expect(abs(lastA - 0.5) < 1e-4, "Path A DC steady-state \(lastA), expected 0.5") #expect(abs(lastB - 0.5) < 1e-4, "Path B DC steady-state \(lastB), expected 0.5") } // MARK: - 6. Denormal safety — silence after signal doesn't blow up @Test func silenceAfterSignalIsDenormalSafe() { // Burst of noise, then silence — confirm no denormals accumulate. let osc: OscSin.Audio = OscSin.Audio(freq: 440.0) let h: Hilbert.Audio = Hilbert.Audio(input: osc) // 4 blocks of signal. for _: Int in 0..<4 { let g: SynthGraph = makeSynthGraph(engine: engine) _ = h.calculatedSamples(graph: g, count: engine.blockSize) advanceBlock(engine) } // Replace source with silence by constructing a fresh chain. (Cannot null the // input mid-stream; this just confirms the existing chain keeps running cleanly // when sustained at a constant value.) let silentH: Hilbert.Audio = Hilbert.Audio(input: 0.0) for _: Int in 0..<8 { let g: SynthGraph = makeSynthGraph(engine: engine) let out: [[Double]] = silentH.calculatedSamples(graph: g, count: engine.blockSize) for s: Double in out[0].prefix(engine.blockSize) { #expect(s.isFinite) } for s: Double in out[1].prefix(engine.blockSize) { #expect(s.isFinite) } advanceBlock(engine) } } // MARK: - 7. Named aliases match subscripts @Test func realAndImagAliasesMatchSubscripts() { let osc: OscSin.Audio = OscSin.Audio(freq: 440.0) let h: Hilbert.Audio = Hilbert.Audio(input: osc) let real: ChannelSelect.Audio = h.real let imag: ChannelSelect.Audio = h.imag let out: [[Double]] = h.calculatedSamples(graph: graph, count: 64) let realOut: [[Double]] = real.calculatedSamples(graph: graph, count: 64) let imagOut: [[Double]] = imag.calculatedSamples(graph: graph, count: 64) for i: Int in 0..<64 { #expect(realOut[0][i] == out[0][i]) #expect(imagOut[0][i] == out[1][i]) } } // MARK: - 8. mul/add applies to both rows @Test func mulAddAppliesToBothRows() { let h: Hilbert.Audio = Hilbert.Audio(input: 0.5, mul: 2.0, add: 0.1) // Long settle for the slow IIR pole — see dcInputSettlesToFiniteValue. let settleSamples: Int = 24576 var rendered: Int = 0 var lastA: Double = 0 var lastB: Double = 0 while rendered < settleSamples { let g: SynthGraph = makeSynthGraph(engine: engine) let out: [[Double]] = h.calculatedSamples(graph: g, count: engine.blockSize) lastA = out[0][engine.blockSize - 1] lastB = out[1][engine.blockSize - 1] advanceBlock(engine) rendered += engine.blockSize } // DC 0.5 × 2.0 + 0.1 = 1.1 on both rows once settled. #expect(abs(lastA - 1.1) < 1e-4, "Path A mul/add steady-state \(lastA), expected 1.1") #expect(abs(lastB - 1.1) < 1e-4, "Path B mul/add steady-state \(lastB), expected 1.1") } }