improve freq trackers

This commit is contained in:
2026-07-02 14:48:37 -07:00
parent 676e8d3278
commit 8a2eb191a2
2 changed files with 112 additions and 22 deletions
@@ -285,6 +285,55 @@ struct FreqTrackerTests {
#expect(avgFreq > 800.0 && avgFreq < 960.0)
}
}
@Test func decimationEnablesLowFrequencyTracking() {
// Low-E guitar string (E2 ≈ 82.4 Hz). At 44100 Hz with fftSize 512 (halfSize 256),
// the undecimated tracker floors out around 173 Hz and cannot see this pitch. With
// 4× decimation the effective rate is ~11025 Hz, dropping the floor to ~43 Hz, so
// the fundamental is now trackable with the same (cheap) 256-lag YIN window.
let e2: Double = 82.41
let sine: OscSin.Audio = OscSin.Audio(freq: e2, mul: 0.8)
let tracker: FreqTracker = FreqTracker(
in: sine,
fftSize: 512,
hopSize: 256,
minFreq: 40.0,
maxFreq: 660.0,
decimation: 4
)
// Decimation means each hop needs 4× more input samples, so render longer.
let blocks: Int = (512 * 4 / engine.blockSize) + 60
let (freqs, _) = collect2ch(tracker, engine: engine, blocks: blocks)
let tail: [Double] = Array(freqs.suffix(engine.blockSize * 5))
let nonZero: [Double] = tail.filter { $0 > 0 }
#expect(!nonZero.isEmpty, "4× decimation should let FreqTracker detect an 82 Hz tone")
if !nonZero.isEmpty {
let avgFreq: Double = nonZero.reduce(0.0, +) / Double(nonZero.count)
#expect(avgFreq > 78.0 && avgFreq < 87.0, "Expected ~82 Hz, got \(avgFreq)")
}
}
@Test func decimationDefaultsToUnchangedBehaviour() {
// decimation: 1 (default) must reproduce the plain-A440 tracking result.
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.8)
let tracker: FreqTracker = FreqTracker(
in: sine,
fftSize: 512,
hopSize: 128,
minFreq: 60.0,
maxFreq: 3000.0,
decimation: 1
)
let warmUpBlocks: Int = (512 / engine.blockSize) + 10
let (freqs, _) = collect2ch(tracker, engine: engine, blocks: warmUpBlocks)
let tail: [Double] = Array(freqs.suffix(engine.blockSize * 5))
let nonZero: [Double] = tail.filter { $0 > 0 }
#expect(!nonZero.isEmpty, "decimation: 1 must still track A440 (regression guard)")
if !nonZero.isEmpty {
let avgFreq: Double = nonZero.reduce(0.0, +) / Double(nonZero.count)
#expect(avgFreq > 420.0 && avgFreq < 460.0)
}
}
}
// MARK: - LookAheadLimiter Tests