Files
Lyrebird/Sources/Lyrebird/Generators/Spectral/OnsetDetector.swift
T
josh 844dc4d9cd v2.1.0 release: Swift 6.4 modernization
Typed throws across the closed-error-set APIs (OSC, MIDI, engine add/schedule,
bus/config/parameter, and the WAV/RF64/Spectral file codecs — source-compatible
narrowing, new .ioFailure cases), plus internal hardening: NSLock-guarded
scheduling/MIDI state moved to Mutex<State>, and the Spectral/FFT scratch owners
moved to a ~Copyable RTScratchBuffer RAII buffer. No API or behavioral change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-24 19:54:59 -07:00

517 lines
21 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.
// OnsetDetector.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdDSP
import Foundation
import Synchronization
// MARK: - Constants
/// Floor added to the rolling median before applying `threshold`. Prevents
/// near-silence (median ≈ 0) from triggering on any non-zero ODF.
private let onsetDetectorMedianFloor: Float = 1.0e-6
/// Smallest legal `medianWindowFrames` — needed for any meaningful median.
private let onsetDetectorMinMedianWindow: Int = 2
/// Largest legal `medianWindowFrames` — keeps the per-hop selection cost trivial.
private let onsetDetectorMaxMedianWindow: Int = 64
/// Two-pi as `Float`, used to wrap predicted phases before `vvsincosf`. Keeping
/// inputs to the vectorised trig in `(−π, π]` avoids argument-reduction precision
/// loss that becomes visible across `binCount` accumulations.
private let onsetDetectorTwoPi: Float = 2 * Float.pi
// MARK: - OnsetDetector
/// Per-hop spectral onset detector.
///
/// Computes an onset-detection function (ODF) — either half-wave-rectified
/// spectral flux or complex-domain prediction error — on every FFT hop, smooths
/// the ODF with a rolling median to derive an adaptive threshold, and increments
/// an atomic onset counter when the latest ODF exceeds `median * threshold`. A
/// configurable refractory window (`minHopsBetweenOnsets`) suppresses
/// double-triggering on the tail of an attack.
///
/// `OnsetDetector` is a `SpectralProcessor`. Register it on a paired
/// `SpectralChain.Audio` and pair it with an ``OnsetDetector/Control`` generator
/// so the onset events become a trigger signal in the synthesis graph:
///
/// ```swift
/// let detector = OnsetDetector(
/// fftSize: 2048,
/// hopSize: 512,
/// method: .spectralFlux,
/// threshold: 1.5,
/// medianWindowFrames: 7,
/// minHopsBetweenOnsets: 3
/// )
/// let chain = SpectralChain.Audio(input: micIn, fftSize: 2048, hopSize: 512,
/// stages: [.mono(detector)], analyzeOnly: true)
/// let trig = OnsetDetector.Control(detector: detector, analysis: chain)
/// addOutputGenerator(SendTrigger.Control(trig: trig, id: 1))
/// ```
///
/// ## Thread safety
///
/// `threshold`, `minHopsBetweenOnsets`, `lastODF`, `lastMedian`, and the pending
/// onset counter are all backed by `Atomic` storage. All ring buffers and per-bin
/// state are pre-allocated in `init`; `process()` performs no heap allocation.
///
/// ## References
///
/// Bello, Daudet, Abdallah, Davies, Davies, Plumbley,
/// "A Tutorial on Onset Detection in Music Signals", IEEE TSAP 2005.
public final class OnsetDetector: SpectralProcessor {
// MARK: - Geometry (immutable)
private let _binCount: Int // complex bins 1 ..< halfSize
private let _method: OnsetDetectionMethod
private let _medianWindowFrames: Int
// MARK: - Cross-thread parameters
private let _thresholdAtomic: Atomic<Float>
private let _minHopsBetweenOnsetsAtomic: Atomic<Int>
/// Trigger sensitivity. ODF must exceed `max(rollingMedian, floor) * threshold`
/// to fire an onset. Higher values mean fewer, more confident onsets.
/// Typical: 1.2 – 3.0. Default: 1.5.
public var threshold: Double {
get { Double(_thresholdAtomic.load(ordering: .acquiring)) }
set { _thresholdAtomic.store(Float(newValue), ordering: .releasing) }
}
/// Refractory period in FFT hops — minimum hops between consecutive onset
/// fires. Suppresses double-trigger on long attack tails. Typical: 1 – 10.
/// Default: 3.
public var minHopsBetweenOnsets: Int {
get { _minHopsBetweenOnsetsAtomic.load(ordering: .acquiring) }
set {
let clamped: Int = max(0, newValue)
_minHopsBetweenOnsetsAtomic.store(clamped, ordering: .releasing)
}
}
// MARK: - Telemetry (RT-write, language-read)
private let _lastODFAtomic: Atomic<Float>
private let _lastMedianAtomic: Atomic<Float>
/// Most recent ODF value computed by the RT thread. Updated each FFT hop.
public var lastODF: Double {
Double(_lastODFAtomic.load(ordering: .acquiring))
}
/// Current rolling-median ODF (before applying `threshold`). Updated each FFT hop
/// once the warmup window has elapsed; otherwise reads `0`.
public var lastMedian: Double {
Double(_lastMedianAtomic.load(ordering: .acquiring))
}
// MARK: - Onset counter (RT-increment, Control-reads)
/// Monotonically-increasing serial — incremented exactly once per detected
/// onset on the RT thread. The paired `Control` generator caches the last
/// observed value and emits a trigger whenever it changes.
private let _onsetSerial: Atomic<UInt64>
/// RT-thread-only read accessor for the paired `Control`. Acquiring-load so
/// the trigger publish happens-after the ODF state write.
internal func _loadOnsetSerial() -> UInt64 {
_onsetSerial.load(ordering: .acquiring)
}
// MARK: - Per-bin state (RT thread only)
private let _prevMag: RTScratchBuffer<Float>
private let _prevPhase: RTScratchBuffer<Float>
private let _prevPrevPhase: RTScratchBuffer<Float>
/// Scratch buffers for vectorised complex-domain trig. Allocated only when
/// `method == .complexDomain` (zero-overhead pointer when unused). Each
/// buffer is `halfSize` long; complex bins live at indices `1..<halfSize`.
private let _curPhaseScratch: RTScratchBuffer<Float>
private let _predPhaseScratch: RTScratchBuffer<Float>
private let _curCosBuf: RTScratchBuffer<Float>
private let _curSinBuf: RTScratchBuffer<Float>
private let _predCosBuf: RTScratchBuffer<Float>
private let _predSinBuf: RTScratchBuffer<Float>
// MARK: - Median ring (RT thread only)
private let _odfRing: RTScratchBuffer<Float>
private let _medianScratch: RTScratchBuffer<Float>
private var _odfRingIndex: Int = 0
// MARK: - Counters (RT thread only)
private var _warmupRemaining: Int
private var _hopsSinceLastOnset: Int
private var _havePrevMag: Bool = false
private var _havePrevPhase: Bool = false
private var _havePrevPrevPhase: Bool = false
// MARK: - Init
/// - Parameters:
/// - fftSize: Must match the paired `SpectralChain.Audio.fftSize`. Power of two ≥ 4.
/// - hopSize: Must match the paired `SpectralChain.Audio.hopSize`. In `[1, fftSize)`.
/// - method: ODF formulation. `.spectralFlux` for percussive material;
/// `.complexDomain` for pitched / soft onsets where phase deviation
/// carries the cue. Defaults to `.spectralFlux`.
/// - threshold: Sensitivity multiplier on the rolling median. ODF must
/// exceed `max(median, floor) * threshold` to fire. Typical 1.2–3.0.
/// Defaults to `1.5`.
/// - medianWindowFrames: Length of the rolling-median window in hops.
/// Must be in `[2, 64]`. Larger values smooth the threshold but lengthen
/// adaptation time. Defaults to `7`.
/// - minHopsBetweenOnsets: Refractory period in hops; must be ≥ 0.
/// Defaults to `3`.
public init(
fftSize: Int,
hopSize: Int,
method: OnsetDetectionMethod = .spectralFlux,
threshold: Double = 1.5,
medianWindowFrames: Int = 7,
minHopsBetweenOnsets: Int = 3
) {
precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0,
"OnsetDetector: fftSize must be a power of two >= 4, got \(fftSize)")
precondition(hopSize >= 1 && hopSize < fftSize,
"OnsetDetector: hopSize must be in [1, fftSize), got \(hopSize)")
precondition(threshold > 0,
"OnsetDetector: threshold must be > 0, got \(threshold)")
precondition(medianWindowFrames >= onsetDetectorMinMedianWindow
&& medianWindowFrames <= onsetDetectorMaxMedianWindow,
"OnsetDetector: medianWindowFrames must be in "
+ "[\(onsetDetectorMinMedianWindow), \(onsetDetectorMaxMedianWindow)], "
+ "got \(medianWindowFrames)")
precondition(minHopsBetweenOnsets >= 0,
"OnsetDetector: minHopsBetweenOnsets must be >= 0, got \(minHopsBetweenOnsets)")
let halfSize: Int = fftSize / 2
_binCount = halfSize - 1
_method = method
_medianWindowFrames = medianWindowFrames
_thresholdAtomic = Atomic(Float(threshold))
_minHopsBetweenOnsetsAtomic = Atomic(minHopsBetweenOnsets)
_lastODFAtomic = Atomic(Float(0))
_lastMedianAtomic = Atomic(Float(0))
_onsetSerial = Atomic(0)
_prevMag = RTScratchBuffer<Float>(count: halfSize)
_prevPhase = RTScratchBuffer<Float>(count: halfSize)
_prevPrevPhase = RTScratchBuffer<Float>(count: halfSize)
_odfRing = RTScratchBuffer<Float>(count: medianWindowFrames)
_medianScratch = RTScratchBuffer<Float>(count: medianWindowFrames)
// Trig scratch is only required for `.complexDomain`. Allocate one slot
// when unused so the stored buffers always reference valid memory.
let trigCount: Int = (method == .complexDomain) ? halfSize : 1
_curPhaseScratch = RTScratchBuffer<Float>(count: trigCount)
_predPhaseScratch = RTScratchBuffer<Float>(count: trigCount)
_curCosBuf = RTScratchBuffer<Float>(count: trigCount)
_curSinBuf = RTScratchBuffer<Float>(count: trigCount)
_predCosBuf = RTScratchBuffer<Float>(count: trigCount)
_predSinBuf = RTScratchBuffer<Float>(count: trigCount)
_warmupRemaining = medianWindowFrames
// Init high so the first post-warmup onset is never blocked by the
// refractory check, regardless of `minHopsBetweenOnsets`.
_hopsSinceLastOnset = Int.max / 2
}
// No deinit: each `RTScratchBuffer` frees its own allocation exactly once when
// this object is deallocated (off the RT thread, via the engine's free queue).
// MARK: - SpectralProcessor
public func process(spectral: SpectralBuffer, engine: SynthesisEngine) {
guard _binCount > 0 else { return }
let odf: Float = computeODF(spectral: spectral)
_lastODFAtomic.store(odf, ordering: .releasing)
// Advance ring with this hop's ODF.
_odfRing[_odfRingIndex] = odf
_odfRingIndex = (_odfRingIndex + 1) % _medianWindowFrames
// Refractory counter ticks regardless of warmup. Saturate at the init cap
// so a long quiet run never wraps to a negative value.
if _hopsSinceLastOnset < Int.max / 2 {
_hopsSinceLastOnset += 1
}
if _warmupRemaining > 0 {
_warmupRemaining -= 1
_lastMedianAtomic.store(0, ordering: .releasing)
return
}
let median: Float = rollingMedian()
_lastMedianAtomic.store(median, ordering: .releasing)
let thresh: Float = _thresholdAtomic.load(ordering: .acquiring)
let refractory: Int = _minHopsBetweenOnsetsAtomic.load(ordering: .acquiring)
let triggerLevel: Float = max(median, onsetDetectorMedianFloor) * thresh
if odf > triggerLevel && _hopsSinceLastOnset >= refractory {
_onsetSerial.wrappingAdd(1, ordering: .releasing)
_hopsSinceLastOnset = 0
}
}
// MARK: - ODF computation
private func computeODF(spectral: SpectralBuffer) -> Float {
switch _method {
case .spectralFlux:
return computeFluxODF(spectral: spectral)
case .complexDomain:
return computeComplexDomainODF(spectral: spectral)
}
}
private func computeFluxODF(spectral: SpectralBuffer) -> Float {
var sumSquares: Float = 0
spectral.withUnsafeMagnitudePointer { mp in
if _havePrevMag {
for i: Int in 0..<_binCount {
let k: Int = i + 1
let mag: Float = mp[i]
let diff: Float = mag - _prevMag[k]
if diff > 0 {
sumSquares += diff * diff
}
_prevMag[k] = mag
}
} else {
for i: Int in 0..<_binCount {
_prevMag[i + 1] = mp[i]
}
_havePrevMag = true
}
}
return sumSquares > 0 ? sqrt(sumSquares) : 0
}
private func computeComplexDomainODF(spectral: SpectralBuffer) -> Float {
// Predict each bin from `predMag = |Xprev|` and
// `predPhase = 2*phasePrev - phasePrevPrev` (linear phase extrapolation).
// ODF = Σ |X[k] - Xpred[k]|.
//
// Phase wrapping is unnecessary — sin/cos are 2π-periodic.
//
// Per-bin trig is replaced with two `vvsincosf` batches over `_binCount`
// entries and a single accumulation pass; this turns the 4 × binCount
// scalar trig calls into one vector pass each for cur and pred.
var sum: Float = 0
let binCount: Int = _binCount
spectral.withUnsafeMagnitudePointer { mp in
spectral.withUnsafePhasePointer { pp in
if _havePrevMag && _havePrevPhase && _havePrevPrevPhase {
// Build cur and pred phase arrays into pre-allocated scratch.
// Both scratch buffers use index 0 for bin 1 (densely packed).
// Wrap predicted phases to `(−π, π]`; raw `2·prev − prevPrev`
// can drift far out of range across phase wraps and degrades
// `vvsincosf` precision when accumulated across `binCount` bins.
let twoPi: Float = onsetDetectorTwoPi
for i: Int in 0..<binCount {
let k: Int = i + 1
_curPhaseScratch[i] = pp[i]
let raw: Float = 2 * _prevPhase[k] - _prevPrevPhase[k]
_predPhaseScratch[i] = raw.remainder(dividingBy: twoPi)
}
var n: Int32 = Int32(binCount)
vvsincosf(_curSinBuf.baseAddress, _curCosBuf.baseAddress, _curPhaseScratch.baseAddress, &n)
vvsincosf(_predSinBuf.baseAddress, _predCosBuf.baseAddress, _predPhaseScratch.baseAddress, &n)
for i: Int in 0..<binCount {
let k: Int = i + 1
let mag: Float = mp[i]
let predMag: Float = _prevMag[k]
let dx: Float = mag * _curCosBuf[i] - predMag * _predCosBuf[i]
let dy: Float = mag * _curSinBuf[i] - predMag * _predSinBuf[i]
sum += sqrt(dx * dx + dy * dy)
}
}
// Advance per-bin history: prevPrev <- prev, prev <- current.
for i: Int in 0..<binCount {
let k: Int = i + 1
_prevPrevPhase[k] = _prevPhase[k]
_prevPhase[k] = pp[i]
_prevMag[k] = mp[i]
}
}
}
// Warm-up flag chain: hop 1 sets _havePrevMag, hop 2 sets _havePrevPhase,
// hop 3 sets _havePrevPrevPhase. The prediction guard succeeds starting on
// the fourth hop, when prev = hop-3 and prevPrev = hop-2.
if !_havePrevMag {
_havePrevMag = true
} else if !_havePrevPhase {
_havePrevPhase = true
} else if !_havePrevPrevPhase {
_havePrevPrevPhase = true
}
return sum
}
// MARK: - Rolling median
/// Returns the median of `_odfRing`. Copies into pre-allocated scratch and
/// performs a partial selection sort up to the middle index — `O(N²/2)` worst
/// case but `N ≤ 64`, no allocation, no Swift `sort` (which can heap-allocate
/// internal scratch).
private func rollingMedian() -> Float {
let n: Int = _medianWindowFrames
for i: Int in 0..<n {
_medianScratch[i] = _odfRing[i]
}
let mid: Int = n / 2
// Partial selection sort: bring the smallest mid+1 elements to the front
// in ascending order; then `_medianScratch[mid]` is the median (n odd) or
// upper-mid (n even — biases slightly high, acceptable for thresholding).
for i: Int in 0...mid {
var minIdx: Int = i
var minVal: Float = _medianScratch[i]
for j: Int in (i + 1)..<n {
if _medianScratch[j] < minVal {
minVal = _medianScratch[j]
minIdx = j
}
}
if minIdx != i {
_medianScratch[minIdx] = _medianScratch[i]
_medianScratch[i] = minVal
}
}
return _medianScratch[mid]
}
}
// MARK: - OnsetDetector.Control
extension OnsetDetector {
/// Control-rate trigger output for an `OnsetDetector`.
///
/// Outputs `1.0` for one audio block whenever the paired detector reported one
/// or more onsets since the last block. The trigger is a single-sample pulse
/// at index 0 of the block (rest of the block is zero), which guarantees a
/// clean ≤0 → >0 edge for downstream `SendTrigger.Control` even when onsets
/// fire on consecutive audio blocks.
///
/// - Parameters:
/// - detector: The onset detector to read from.
/// - analysis: Paired `SpectralChain.Audio`. Stored as a generator input so
/// engine traversal evaluates it each block automatically.
public final class Control: GeneratorBase, ControlGenerator {
private let _detector: OnsetDetector
private let _analysis: SpectralChain.Audio?
private var _lastSeenOnsetSerial: UInt64 = 0
public var previousOutputValue: Double = 0.0
/// - Parameters:
/// - detector: The detector instance whose onset events should be
/// surfaced as a trigger signal.
/// - analysis: Paired `SpectralChain.Audio`. The detector must already
/// be registered as a `.mono(_)` stage in this chain's `stages`
/// for the wiring to be correct.
public convenience init(
detector: OnsetDetector,
analysis: SpectralChain.Audio
) {
// Catch the easy mistake of constructing the Control with the wrong
// chain (or forgetting to register the detector in `stages:`).
// Without this check the trigger output would silently stay at zero —
// much harder to diagnose at runtime.
precondition(
analysis.stages.contains(where: { stage in
if case .mono(let p) = stage, p === detector { return true }
return false
}),
"OnsetDetector.Control: the supplied detector is not registered "
+ "in analysis.stages. Construct the SpectralChain.Audio with "
+ "`stages: [.mono(detector)]` (or pass the matching chain)."
)
self.init(detector: detector, analysis: analysis as SpectralChain.Audio?)
}
/// Detector-only init for tests / advanced use; no analysis auto-pull.
public convenience init(detector: OnsetDetector) {
self.init(detector: detector, analysis: nil)
}
private init(
detector: OnsetDetector,
analysis: SpectralChain.Audio?
) {
self._detector = detector
self._analysis = analysis
self._lastSeenOnsetSerial = detector._loadOnsetSerial()
super.init()
_setupSubBlockBuffer()
}
// Bypass sub-block loop: onset state is published once per FFT hop, and the
// trigger pulse must be emitted exactly once per audio block — not once per
// sub-block chunk.
public func calculatedSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_calculatedSamplesBlockRate(graph: graph, count: count)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
_ = _analysis?.calculatedSamples(graph: graph, count: count)
let currentSerial: UInt64 = _detector._loadOnsetSerial()
let fired: Bool = currentSerial != _lastSeenOnsetSerial
_lastSeenOnsetSerial = currentSerial
guard count > 0 else { return _result }
// Single-sample pulse at index 0 — guarantees ≤0 → >0 edge for
// downstream SendTrigger even on back-to-back onset blocks.
_result[0].withUnsafeMutableBufferPointer { buf in
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
vDSP_vclrD(base, 1, vDSP_Length(count))
if fired {
base[0] = 1.0
}
}
// `previousOutputValue` must reflect the trailing sample so the next
// block's SendTrigger sees a clean ≤0 reference. When `count == 1`
// the pulse and the trailing sample are the same; force ≤0 so a
// back-to-back pulse on the next block still produces an edge.
previousOutputValue = (count > 1) ? _result[0][count - 1] : 0.0
return _result
}
}
}
// MARK: - GeneratorEnum
// GeneratorEnum conformance omitted: OnsetDetector.Control is the only generator,
// and its construction requires a paired `OnsetDetector` reference which has no
// scalar/literal interpretation.