// TunerPitchCapture.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import LyrebirdSynth import Synchronization /// Wraps a YIN `FreqTracker` and atomically snapshots its per-block frequency **and /// confidence** into plain `Double`s readable from any thread — the same RT-writes/non-RT- /// polls contract as `ParameterNode`'s atomic value storage, sized down to two scalars. /// /// YIN (via `FreqTracker`) is far steadier than zero-crossing detection on a plucked/ /// harmonic-rich guitar signal, and its confidence output lets the UI latch the last stable /// reading through low-confidence transients (note attacks, restrikes) instead of ramping /// toward the new pitch. No smoothing is applied here — the raw YIN estimate is stable /// enough, and any smoothing would re-introduce the ramp-on-restrike the latch is meant to /// avoid. /// /// Bypasses the `ControlGenerator` sub-block ramp path (matching `SendTrigger.Control`'s /// convention for side-effecting analysis generators). final class TunerPitchCapture: GeneratorBase, ControlGenerator { var previousOutputValue: Double = 0.0 /// Input decimation factor for the YIN tracker. Lowers the effective analysis rate so a /// fixed 512-sample window reaches down to the low guitar / bass range. At 48 kHz, 8× /// gives an effective 6 kHz rate → ~23 Hz detection floor. The caller (`TunerTap`) must /// band-limit the input below the decimated Nyquist (`sampleRate / 16`) first. static let decimation: Int = 8 /// YIN analysis window, in decimated samples (512 is `FreqTracker`'s RT-safe maximum). private static let fftSize: Int = 512 /// Minimum tracked frequency in Hz — below standard bass E1 (≈41 Hz) for headroom. private static let minFreqHz: Double = 38.0 /// Maximum tracked frequency in Hz — above guitar high-E (E4 ≈330 Hz) with room for /// upper strings / light bends, and well below the decimated Nyquist. private static let maxFreqHz: Double = 660.0 private let tracker: FreqTracker private let _hzBits: Atomic private let _confidenceBits: Atomic /// The most recent tracked frequency, in Hz. Safe to read from any thread. var detectedFrequencyHz: Double { Double(bitPattern: _hzBits.load(ordering: .acquiring)) } /// The most recent tracking confidence in `[0, 1]`. Safe to read from any thread. var detectedConfidence: Double { Double(bitPattern: _confidenceBits.load(ordering: .acquiring)) } /// - Parameter input: Signal to analyse for pitch — must already be band-limited below /// the decimated Nyquist (see `TunerTap`, which applies the anti-alias lowpass). init(input: any ValidGeneratorInput) { let resolvedInput: any ValidGeneratorInput = input._resolvedInput() tracker = FreqTracker( in: resolvedInput, fftSize: TunerPitchCapture.fftSize, minFreq: TunerPitchCapture.minFreqHz, maxFreq: TunerPitchCapture.maxFreqHz, decimation: TunerPitchCapture.decimation ) _hzBits = Atomic(Double(0.0).bitPattern) _confidenceBits = Atomic(Double(0.0).bitPattern) super.init() _setupSubBlockBuffer() } // Bypass sub-block loop — one capture per audio block. `FreqTracker` processes the full // block internally (per-sample ring fill + periodic YIN hops). func calculatedSamples( graph: SynthGraph, count: Int ) -> [[Double]] { _calculatedSamplesBlockRate(graph: graph, count: count) } func _computeSamples( graph: SynthGraph, count: Int ) -> [[Double]] { _checkCount(count) // `_checkCount` only bounds the top; guard the empty block so the `count - 1` last-sample // reads below can't index `-1` (engine blockSize is ≥1 today, so this is defensive). guard count > 0 else { return _result } // FreqTracker is a two-channel AudioGenerator: channel 0 = Hz, channel 1 = confidence. // Both rows are fully populated for `count` samples. let trackerBlock: [[Double]] = tracker.calculatedSamples(graph: graph, count: count) let hz: Double = trackerBlock[0][count - 1] let confidence: Double = trackerBlock[1][count - 1] _hzBits.store(hz.bitPattern, ordering: .releasing) _confidenceBits.store(confidence.bitPattern, ordering: .releasing) previousOutputValue = hz for i: Int in 0..