1 Commits

Author SHA1 Message Date
josh 8a2eb191a2 improve freq trackers 2026-07-02 14:48:37 -07:00
2 changed files with 112 additions and 22 deletions
@@ -10,7 +10,9 @@ import Darwin
///
/// Accumulates samples into a ring buffer and re-evaluates every `hopSize` samples.
/// Between hops the output holds the previous result — frequency stabilises after
/// one or two hops (~46 ms at the default settings and 44100 Hz sample rate).
/// one or two hops (~46 ms at the default settings, `decimation: 1`, and 44100 Hz sample
/// rate). Settle time scales with `decimation` (each hop spans `decimation×` more
/// wall-clock time), so `decimation: 4` stabilises in ~184 ms.
///
/// ## Output
/// Returns a two-channel buffer:
@@ -19,10 +21,13 @@ import Darwin
///
/// ## Parameters
/// - `in`: signal to analyse (Audio-rate input evaluated per sample)
/// - `fftSize`: analysis window in samples (must be power of 2, set at init)
/// - `hopSize`: samples between re-analyses (set at init; default `fftSize / 2`)
/// - `fftSize`: analysis window in **decimated** samples (must be power of 2, set at init)
/// - `hopSize`: decimated samples between re-analyses (set at init; default `fftSize / 2`)
/// - `minFreq`: lower search bound in Hz (default 60.0)
/// - `maxFreq`: upper search bound in Hz (default 3000.0)
/// - `decimation`: keep only every Nth input sample before analysis (default `1`), lowering
/// the effective rate to `sampleRate / decimation` to reach lower fundamentals. Caller must
/// band-limit below the decimated Nyquist first. See the `init` doc for full detail.
///
/// ## Usage
/// ```swift
@@ -62,6 +67,7 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
private let _hopSize: Int
private let _minFreq: Double
private let _maxFreq: Double
private let _decimation: Int
// MARK: - Input
@@ -82,6 +88,11 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
private var _lastFreq: Double = 0.0
private var _lastConfidence: Double = 0.0
// Counts raw input samples toward the next decimated (stored) sample. Only every
// `_decimation`-th input sample is written into the ring; the ring/hop machinery then
// operates entirely in the decimated time base.
private var _decimationCounter: Int = 0
// MARK: - Output
// MARK: - Fan-out cache
@@ -89,18 +100,32 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
/// - Parameters:
/// - input: Signal to track.
/// - fftSize: Analysis window in samples. Power of 2 in [64, 512]. Default 512.
/// Larger values increase latency and YIN cost (O(halfSize²) per hop);
/// 512 gives ~5.8 ms at 44100 Hz and is the maximum RT-safe value.
/// - hopSize: Samples between analysis updates. Default `fftSize / 2`.
/// - fftSize: Analysis window in **decimated** samples. Power of 2 in [64, 512].
/// Default 512. Larger values increase latency and YIN cost (O(halfSize²)
/// per hop); 512 gives ~5.8 ms at 44100 Hz and is the maximum RT-safe value.
/// - hopSize: Decimated samples between analysis updates. Default `fftSize / 2`.
/// - minFreq: Minimum tracked frequency in Hz. Default 60.0.
/// - maxFreq: Maximum tracked frequency in Hz. Default 3000.0.
/// - decimation: Keep only every `decimation`-th input sample before analysis, lowering
/// the effective sample rate to `sampleRate / decimation`. Default `1` (no
/// decimation — original behaviour). A 512-sample window can then span
/// `decimation ×` more time, extending the **minimum** detectable frequency
/// down to roughly `sampleRate / (decimation × (fftSize/2 − 1))` while keeping
/// YIN's O(halfSize²) cost fixed — ideal for low-pitched monophonic sources
/// (bass, low guitar strings) where high-frequency resolution isn't needed.
/// **The caller must band-limit the input below the decimated Nyquist
/// (`sampleRate / (2 × decimation)`) first** — decimation does no anti-alias
/// filtering of its own. The `maxFreq` search bound must also stay below that
/// decimated Nyquist. Latency to a stable reading scales with `decimation`
/// (each hop spans `decimation×` more wall-clock time), so `decimation: 4`
/// settles in ~4× the undecimated hop-based time.
public init(
in input: any ValidGeneratorInput,
fftSize: Int = 512,
hopSize: Int? = nil,
minFreq: Double = 60.0,
maxFreq: Double = 3000.0
maxFreq: Double = 3000.0,
decimation: Int = 1
) {
precondition(fftSize >= 64 && fftSize <= 512 && (fftSize & (fftSize - 1)) == 0,
"FreqTracker: fftSize must be a power of 2 in [64, 512]; got \(fftSize). "
@@ -108,6 +133,8 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
+ "Reduce fftSize or implement background-thread YIN in a future phase.")
precondition(minFreq > 0 && maxFreq > minFreq,
"FreqTracker: minFreq must be > 0 and < maxFreq")
precondition(decimation >= 1,
"FreqTracker: decimation must be >= 1; got \(decimation).")
_fftSize = fftSize
_hopSize = hopSize ?? fftSize / 2
@@ -119,6 +146,7 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
+ "Larger values cause the YIN window to read stale data.")
_minFreq = minFreq
_maxFreq = maxFreq
_decimation = decimation
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
_input = resolvedInput
_inputRing = [Double](repeating: 0.0, count: fftSize)
@@ -135,16 +163,23 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
_checkCount(count)
let sr: Double = graph.engine.sampleRate
// Analysis runs in the decimated time base: the ring holds every `_decimation`-th
// input sample, so lag→frequency conversion uses the decimated effective rate.
let effectiveRate: Double = sr / Double(_decimation)
let inputSamples: [[Double]] = _input.calculatedSamples(graph: graph, count: count)
guard let ins: [Double] = inputSamples.first else {
// No input — advance ring with zeros, still fire hops so state advances correctly.
for _ in 0..<count {
_inputRing[_ringPos % _fftSize] = 0.0
_ringPos &+= 1
_samplesUntilHop -= 1
if _samplesUntilHop <= 0 {
_samplesUntilHop = _hopSize
_runYIN(sampleRate: sr)
_decimationCounter &+= 1
if _decimationCounter >= _decimation {
_decimationCounter = 0
_inputRing[_ringPos % _fftSize] = 0.0
_ringPos &+= 1
_samplesUntilHop -= 1
if _samplesUntilHop <= 0 {
_samplesUntilHop = _hopSize
_runYIN(sampleRate: effectiveRate)
}
}
}
for i: Int in 0..<count {
@@ -155,15 +190,21 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
}
for i: Int in 0..<count {
// Write incoming sample into ring buffer.
let sample: Double = Double(ins[i])
_inputRing[_ringPos % _fftSize] = sample
_ringPos &+= 1
// Write every `_decimation`-th incoming sample into the ring buffer. Naive
// decimation (take-every-Nth) is correct because the caller band-limits below
// the decimated Nyquist — see the `decimation` parameter docs.
_decimationCounter &+= 1
if _decimationCounter >= _decimation {
_decimationCounter = 0
let sample: Double = Double(ins[i])
_inputRing[_ringPos % _fftSize] = sample
_ringPos &+= 1
_samplesUntilHop -= 1
if _samplesUntilHop <= 0 {
_samplesUntilHop = _hopSize
_runYIN(sampleRate: sr)
_samplesUntilHop -= 1
if _samplesUntilHop <= 0 {
_samplesUntilHop = _hopSize
_runYIN(sampleRate: effectiveRate)
}
}
_result[0][i] = _lastFreq
_result[1][i] = _lastConfidence
@@ -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