Files
Lyrebird/Sources/Lyrebird/Generators/Analysis/BeatTrack.swift
T
josh f8878324fd v2.1.1 release: delay-click fix + internal consolidation
Mirror of Lyrebird dev HEAD (9f791c7c) minus maintainer-only paths. Patch release:
fixes the allpass fractional-delay click (DelayLine/CombFilter/AllpassFilter/
DelayLineFeedback under a modulated delay) and lands the internal code-quality
consolidation pass (~160 deduped sites + shared base classes/helpers, bit-identical
output). No public API removed or changed. See RELEASES.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-07 21:20:49 -07:00

270 lines
11 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.
// BeatTrack.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Real-time beat / tempo tracker.
///
/// Estimates the period and phase of a musical pulse from an **onset detection
/// function** (ODF) by autocorrelation with phase locking, emitting
/// beat-synchronous triggers plus a continuous tempo estimate. The ODF source
/// is selected by ``BeatTrackODF``:
///
/// - ``BeatTrackODF/spectralFlux(analysis:)`` — FFT-fed; the tracker computes
/// its own ODF as the spectral flux of a paired ``SpectralChain/Audio``
/// (drop-in; equivalent to SuperCollider's `BeatTrack`).
/// - ``BeatTrackODF/feature(_:)`` — feature-fed; you supply the ODF as any
/// signal (equivalent to SuperCollider's `BeatTrack2`).
///
/// Control-rate, 4-output: see ``BeatTrack/Control`` for the row layout.
///
/// > This is an independent implementation of standard autocorrelation tempo
/// > induction with phase locking (see `BeatTrackerCore`), not a port of any
/// > SuperCollider source.
public enum BeatTrack {
/// Control-rate beat tracker. ODF source chosen at init via ``BeatTrackODF``.
///
/// Emits four output rows:
/// - `0` — **beat** trigger (`1.0` for the block a beat fires on, else `0.0`)
/// - `1` — **eighth** trigger (2× the beat rate)
/// - `2` — **sixteenth** trigger (4× the beat rate)
/// - `3` — **tempo** in BPM (continuous)
///
/// - Parameters:
/// - odf: Onset-detection-function source — FFT-fed or feature-fed.
/// - minBPM: Slowest detectable tempo. Read once at init. Defaults to ``beatTrackMinBPM``.
/// - maxBPM: Fastest detectable tempo. Read once at init. Defaults to ``beatTrackMaxBPM``.
/// - preferredBPM: Preference-weight centre + pre-lock default tempo. Read
/// once at init. Defaults to ``beatTrackPreferredBPM``.
/// - windowSeconds: ODF history length for autocorrelation. Read once at
/// init. Defaults to ``beatTrackMaxWindowSeconds``.
public final class Control: GeneratorBase, BlockRateControlGenerator {
/// Internal ODF source + the input refs each mode needs. Only one mode's
/// state is live; the spectral-flux state (`_prevMag`, `_isFirstFrame`)
/// is dormant in feature mode.
private enum Source {
case spectralFlux(analysis: SpectralChain.Audio?, spectral: SpectralBuffer)
case feature(input: any ValidGeneratorInput, isGenerator: Bool)
}
private let _source: Source
private var _prevMag: [Float]
private var _isFirstFrame: Bool = true
private let _core: BeatTrackerCore
public var previousOutputValue: Double = 0.0
public override var outputChannelCount: Int { beatTrackOutputRowCount }
// MARK: - Public inits
/// - Parameters:
/// - odf: Onset-detection-function source — FFT-fed or feature-fed.
/// - minBPM: Slowest detectable tempo. Read once at init. Defaults to ``beatTrackMinBPM``.
/// - maxBPM: Fastest detectable tempo. Read once at init. Defaults to ``beatTrackMaxBPM``.
/// - preferredBPM: Preference-weight centre + pre-lock default tempo.
/// Read once at init. Defaults to ``beatTrackPreferredBPM``.
/// - windowSeconds: ODF history length for autocorrelation. Read once
/// at init. Defaults to ``beatTrackMaxWindowSeconds``.
public convenience init(
odf: BeatTrackODF,
minBPM: Double = beatTrackMinBPM,
maxBPM: Double = beatTrackMaxBPM,
preferredBPM: Double = beatTrackPreferredBPM,
windowSeconds: Double = beatTrackMaxWindowSeconds
) {
let source: Source
switch odf {
case .spectralFlux(let chain):
source = .spectralFlux(analysis: chain, spectral: chain.spectralBuffer)
case .feature(let signal):
let resolved: any ValidGeneratorInput = signal._resolvedInput()
source = .feature(input: resolved, isGenerator: resolved is any Generator)
}
self.init(
source: source,
minBPM: minBPM,
maxBPM: maxBPM,
preferredBPM: preferredBPM,
windowSeconds: windowSeconds
)
}
/// FFT-fed convenience: track the spectral flux of `analysis`.
///
/// - Parameters:
/// - analysis: Paired ``SpectralChain/Audio`` (analyze-only). Its
/// `spectralBuffer` is read once per audio block to compute spectral flux.
/// - minBPM: Slowest detectable tempo. Defaults to ``beatTrackMinBPM``.
/// - maxBPM: Fastest detectable tempo. Defaults to ``beatTrackMaxBPM``.
/// - preferredBPM: Preference-weight centre + pre-lock default tempo.
/// Defaults to ``beatTrackPreferredBPM``.
/// - windowSeconds: ODF history length. Defaults to ``beatTrackMaxWindowSeconds``.
public convenience init(
analysis: SpectralChain.Audio,
minBPM: Double = beatTrackMinBPM,
maxBPM: Double = beatTrackMaxBPM,
preferredBPM: Double = beatTrackPreferredBPM,
windowSeconds: Double = beatTrackMaxWindowSeconds
) {
self.init(
source: .spectralFlux(analysis: analysis, spectral: analysis.spectralBuffer),
minBPM: minBPM,
maxBPM: maxBPM,
preferredBPM: preferredBPM,
windowSeconds: windowSeconds
)
}
/// Feature-fed convenience: track an externally supplied ODF signal.
///
/// - Parameters:
/// - feature: Onset detection function signal. Reduced to one ODF value
/// per audio block (block max).
/// - minBPM: Slowest detectable tempo. Defaults to ``beatTrackMinBPM``.
/// - maxBPM: Fastest detectable tempo. Defaults to ``beatTrackMaxBPM``.
/// - preferredBPM: Preference-weight centre + pre-lock default tempo.
/// Defaults to ``beatTrackPreferredBPM``.
/// - windowSeconds: ODF history length. Defaults to ``beatTrackMaxWindowSeconds``.
public convenience init(
feature: any ValidGeneratorInput,
minBPM: Double = beatTrackMinBPM,
maxBPM: Double = beatTrackMaxBPM,
preferredBPM: Double = beatTrackPreferredBPM,
windowSeconds: Double = beatTrackMaxWindowSeconds
) {
let resolved: any ValidGeneratorInput = feature._resolvedInput()
self.init(
source: .feature(input: resolved, isGenerator: resolved is any Generator),
minBPM: minBPM,
maxBPM: maxBPM,
preferredBPM: preferredBPM,
windowSeconds: windowSeconds
)
}
/// Buffer-only FFT-fed convenience. For tests / advanced use; no analysis
/// auto-pull (the caller drives the chain populating `spectral`).
///
/// - Parameters:
/// - spectral: Spectral frame buffer read each block for flux.
/// - minBPM: Slowest detectable tempo. Defaults to ``beatTrackMinBPM``.
/// - maxBPM: Fastest detectable tempo. Defaults to ``beatTrackMaxBPM``.
/// - preferredBPM: Preference-weight centre + pre-lock default tempo.
/// Defaults to ``beatTrackPreferredBPM``.
/// - windowSeconds: ODF history length. Defaults to ``beatTrackMaxWindowSeconds``.
public convenience init(
spectral: SpectralBuffer,
minBPM: Double = beatTrackMinBPM,
maxBPM: Double = beatTrackMaxBPM,
preferredBPM: Double = beatTrackPreferredBPM,
windowSeconds: Double = beatTrackMaxWindowSeconds
) {
self.init(
source: .spectralFlux(analysis: nil, spectral: spectral),
minBPM: minBPM,
maxBPM: maxBPM,
preferredBPM: preferredBPM,
windowSeconds: windowSeconds
)
}
// MARK: - Designated init
private init(
source: Source,
minBPM: Double,
maxBPM: Double,
preferredBPM: Double,
windowSeconds: Double
) {
self._source = source
switch source {
case .spectralFlux(_, let spectral):
self._prevMag = [Float](repeating: 0, count: spectral.binCount)
case .feature:
self._prevMag = []
}
self._core = BeatTrackerCore(
minBPM: minBPM,
maxBPM: maxBPM,
preferredBPM: preferredBPM,
windowSeconds: windowSeconds,
featureRateHz: beatTrackFeatureRateHz
)
super.init(channels: beatTrackOutputRowCount)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
let odf: Double = computeODF(graph: graph, count: count)
_core.processBlock(
odf: odf,
sampleCount: count,
sampleRate: graph.engine.sampleRate
)
previousOutputValue = fillBeatTrackerOutput(
into: &_result, core: _core, count: count)
return _result
}
/// Per-block onset-detection-function value for the active source.
private func computeODF(graph: SynthGraph, count: Int) -> Double {
switch _source {
case .spectralFlux(let analysis, let spectral):
_ = analysis?.calculatedSamples(graph: graph, count: count)
return spectralFlux(spectral)
case .feature(let input, let isGenerator):
// Scalar feature → constant ODF (no per-block heap alloc);
// generator feature → block-max of its output row.
if isGenerator {
let row: [Double] = input.calculatedSamples(
graph: graph, count: count).first ?? []
return blockMaxODF(row, count: count)
}
return max(0.0, input.floatValue(graph: graph))
}
}
/// Frame-to-frame magnitude-change flux (onset proxy). Identical measure
/// to ``SpectralFlux``: RMS of per-bin magnitude differences. Returns `0`
/// on the first block (no previous frame to compare).
private func spectralFlux(_ spectral: SpectralBuffer) -> Double {
let binCount: Int = spectral.binCount
guard binCount > 0 else { return 0.0 }
if _isFirstFrame {
for k: Int in 0..<binCount {
_prevMag[k] = spectral.magnitude(at: k)
}
_isFirstFrame = false
return 0.0
}
var sumSquares: Double = 0.0
for k: Int in 0..<binCount {
let mag: Double = Double(spectral.magnitude(at: k))
let prev: Double = Double(_prevMag[k])
let diff: Double = mag - prev
sumSquares += diff * diff
_prevMag[k] = Float(mag)
}
return (sumSquares / Double(binCount)).squareRoot()
}
}
}
// MARK: - GeneratorEnum
// GeneratorEnum conformance omitted: BeatTrack is Control-rate only.