Files
ShoeGaze/Sources/LyrebirdShoeGaze/Tuner/TunerPitchCapture.swift
T
josh 947dfe427a Add looper pedal: beat-quantized transport, undo, reverse, timeline
Extend the looper into a double-width tempo-aware pedal:

- Beat-quantized transport: record start and loop close both snap to the
  next beat via a LyrebirdRoutine waiting on the shared clock; loop length
  is an exact whole-beat span. Falls back to immediate/unquantized when no
  clock is present.
- Loop-length read-outs (frames/seconds/beats), transport state, and a
  sample-clock-derived play-head position for the UI timeline.
- Overdub undo (pre-dub snapshot + restore), reverse playback (live rate
  flip), and feedback-decay overdub (overdub preLevel via a Feedback knob).
- Inject the shared LyrebirdClock + SynthesisEngine into Pedal via
  PedalBoard/ChainRouter so tempo-aware pedals can reach them.
- New double-width LooperTimelineView (state badge, length read-out,
  sweeping play-head) wired into PedalView via Pedal.widthUnits.

Concurrency hardening from RT-safety review: a transportGeneration counter
drops superseded deferred beat/undo callbacks that LyrebirdRoutine.stop()
cannot recall once enqueued; the undo restore is deferred past the RT
overdub gate-close; transport routines use non-blocking stop().

Note: this commit also snapshots pre-existing uncommitted work-in-progress
already in the tree (MIDI control refactor, Tuner, Tempo, preset changes),
which is interleaved with the looper changes through shared files and could
not be split into a separately-building commit.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 09:22:20 -07:00

104 lines
4.6 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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<UInt64>
private let _confidenceBits: Atomic<UInt64>
/// 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..<count {
_result[0][i] = trackerBlock[0][i]
}
return _result
}
}