prep for 1.2.0 release updates

This commit is contained in:
2026-06-21 11:45:58 -07:00
parent 73191c958f
commit 032b7c39d3
286 changed files with 21116 additions and 121 deletions
+441
View File
@@ -0,0 +1,441 @@
# Signal Analysis
Control-rate feature-extraction and tracking generators. These read an audio (or
control) signal and emit a *measurement* — a frequency, a rate, a running
extreme, a tempo — rather than an audible signal. All are `ControlGenerator`s
that advance their internal state exactly once per audio block (the
`_calculatedSamplesBlockRate` bypass) so the analysis never double-counts under
sub-block control evaluation.
## Catalog
| Generator | Folder | Input | Output | Notes |
|---|---|---|---|---|
| `ZeroCrossing` | `Generators/Analysis/` | audio | est. frequency (Hz) | zero-crossing-rate pitch/noisiness proxy |
| `Slope` | `Generators/Analysis/` | audio | first difference | `x[n] − x[n−1]` |
| `RunningMin` / `RunningMax` | `Generators/Analysis/` | audio | running extreme | optional `trig` reset |
| `BeatTrack` | `Generators/Analysis/` | `BeatTrackODF` | 4 rows | beat/tempo tracker (FFT- or feature-fed) |
| `Loudness` | `Generators/Analysis/` | `SpectralChain.Audio` | sones | Zwicker psychoacoustic loudness (3 models) |
`ZeroCrossing` / `Slope` / `RunningMin` / `RunningMax` are documented in
`docs/stdlib/generators.md`; this file is the design reference for the beat
tracker and the loudness meter.
---
# Beat tracking — `BeatTrack`
Real-time tempo + beat-phase tracker. Estimates the period and phase of a
musical pulse from an **onset detection function** (ODF) — a one-dimensional
stream whose peaks coincide with note onsets — and emits beat-synchronous
triggers plus a continuous tempo estimate.
A single generator covers both SuperCollider beat-tracker flavours; the ODF
source is chosen at init by the `BeatTrackODF` enum (the implementation flag,
mirroring how `Balance` folds its log-domain variant behind `logDomain:`). The
selector is an enum rather than a `Bool` because the two modes carry different
inputs — an FFT chain vs an arbitrary signal:
- **`.spectralFlux(analysis:)`** — FFT-fed. The tracker computes its own ODF as
the **spectral flux** of a paired `SpectralChain.Audio` (the same flux measure
as `SpectralFlux`). Wire an analyze-only chain in; nothing else upstream is
required. Equivalent to SuperCollider's `BeatTrack`. Convenience init:
`BeatTrack.Control(analysis:)`.
- **`.feature(_:)`** — feature-fed. Takes an **externally supplied ODF** as any
`ValidGeneratorInput` (control or audio). Use it when you already have a
detection function — `SpectralFlux`, `OnsetDetector`, an `AmplitudeFollower`
difference, a hand-built feature — or want to combine several. Equivalent to
SuperCollider's `BeatTrack2`. Convenience init: `BeatTrack.Control(feature:)`.
> **Clean-room note.** This is an independent implementation of standard
> autocorrelation-based tempo induction with phase locking (Davies & Plumbley,
> *Context-Dependent Beat Tracking of Musical Audio*, 2007; Ellis, *Beat
> Tracking by Dynamic Programming*, 2007). It is **not** a port of any
> SuperCollider `BeatTrack`/`BeatTrack2` source (which is GPL). Channel
> semantics, parameters, and the internal algorithm are Lyrebird's own; do not
> expect bit-exact parity with SC.
## Outputs (4 rows)
`BeatTrack.Control` is a 4-row `ControlGenerator` (`outputChannelCount == 4`):
| Row | Meaning | Form |
|---|---|---|
| `0` | **beat** trigger | `1.0` for the block on which a beat fires, else `0.0` |
| `1` | **eighth** trigger | fires at 2× the beat rate |
| `2` | **sixteenth** trigger | fires at 4× the beat rate |
| `3` | **tempo** | current estimate in **BPM** (continuous, smoothed) |
Access individual rows with the channel subscript (`tracker[0]` … `tracker[3]`)
exactly like any multi-row generator. `floatValue` / scalar reads return row 0
(the beat trigger), per the `ControlGenerator` default.
Triggers land on **block boundaries** (the analysis is decimated to a feature
rate — see below), so beat timing is quantised to the control block, not
sample-accurate. This is appropriate for a tempo follower driving sequencers,
LFО re-triggers, or visualisation; it is not a sample-accurate clock.
## Algorithm
### 1. Onset detection function (ODF) and decimation
The raw per-block ODF value is reduced to a fixed **feature rate** so the
autocorrelation window stays bounded regardless of block size:
- A **feature hop** `Hf = round(sampleRate / featureRateHz)` samples groups
consecutive audio blocks. `featureRateHz` defaults to **≈ 86 Hz**
(`beatTrackFeatureRateHz = 86.0`), matching the conventional 512-sample STFT
hop at 44.1 kHz.
- Within one feature hop the per-block ODF values are combined by **max**
(onset energy is impulsive; max preserves the peak regardless of where in the
hop it lands). When the accumulated sample count reaches `Hf`, one ODF
feature is emitted and the accumulator resets.
- **`.spectralFlux` mode**: the per-block ODF is the spectral flux
`sqrt(Σ_k (mag_k − prevMag_k)² / binCount)` read from the chain's
`spectralBuffer` (identical to `SpectralFlux`; flux is ≈0 on blocks where the
FFT frame has not advanced, so the per-hop max captures each new frame's
onset).
- **`.feature` mode**: the per-block ODF is the max of the input feature row over
the block (a scalar feature input yields a constant ODF, with no per-block
heap allocation).
Each emitted feature is **half-wave rectified and adaptively whitened**: the
running mean of recent features is subtracted and negatives clamped to 0, so a
DC offset or slow drift in the ODF does not bias the autocorrelation.
### 2. ODF history ring
Emitted features are pushed into a pre-allocated power-of-two **ring buffer**
sized for `beatTrackMaxWindowSeconds` (default **6 s** →
`Lmax = ceil(6 · featureRateHz) ≈ 516` features, ring rounded up to 1024). The
ring is allocated at `init`; nothing resizes on the RT thread.
### 3. Tempo induction (autocorrelation)
Periodically (every `beatTrackAnalysisHopFeatures` features, default **note: a
small power of two so re-analysis cost amortises**; not every feature), the
windowed ODF history is autocorrelated over the lag range corresponding to the
tempo bounds:
```
lagMin = featureRateHz · 60 / maxBPM // maxBPM = beatTrackMaxBPM = 200
lagMax = featureRateHz · 60 / minBPM // minBPM = beatTrackMinBPM = 60
acf[lag] = Σ_n odf[n] · odf[n − lag] // over the analysis window
```
The ACF is multiplied by a **tempo-preference weight** — a log-Gaussian centred
on `beatTrackPreferredBPM` (default **120 BPM**, width ~0.9 octave) — to
resolve octave ambiguity (a strong pulse at 60 BPM and its harmonic at 120 BPM
both peak; the weight biases toward the perceptually preferred range). The lag
with maximum weighted ACF is the **beat period** `P` (feature samples). `P` is
exponentially smoothed across analyses (`beatTrackTempoSmoothing`) so the tempo
output and the phase rate do not jump.
`tempoBPM = 60 · featureRateHz / P`, clamped to `[minBPM, maxBPM]`.
### 4. Phase locking
A continuous **phase accumulator** `φ ∈ [0, 1)` advances by `1/P` per feature.
At each re-analysis the phase is re-aligned by finding the offset `δ ∈ [0, P)`
that maximises the correlation of an impulse train of period `P` with the recent
ODF (equivalently: the recent ODF peak position modulo `P`), then setting `φ`
so the next integer crossing coincides with the predicted next beat. Between
analyses `φ` free-runs at the current tempo, so beats keep firing even through
gaps in the ODF (a held note, a rest).
Triggers are emitted when `φ` crosses an integer (beat, row 0), a half
(eighth, row 1), or a quarter (sixteenth, row 2) during the feature just
processed.
### 5. Steady state and edge cases
- **Silence / zero ODF**: the ACF is ~0, no clear peak; tempo holds its last
estimate (or the default `preferredBPM` before any lock). Phase keeps
free-running so triggers continue at the held tempo. No NaN/Inf — the ACF
normalisation and `P` are guarded against divide-by-zero, and feature state is
denormal-flushed each block.
- **Before first lock**: tempo output is `beatTrackPreferredBPM`; beat triggers
free-run at that tempo.
- **Constant (DC) ODF**: whitening removes the offset → no spurious periodicity.
## Constants (named, no magic numbers)
| Constant | Default | Meaning |
|---|---|---|
| `beatTrackFeatureRateHz` | `86.0` | ODF decimation target rate (Hz) |
| `beatTrackMaxWindowSeconds` | `6.0` | ODF history length for autocorrelation |
| `beatTrackMinBPM` | `60.0` | slowest detectable tempo |
| `beatTrackMaxBPM` | `200.0` | fastest detectable tempo |
| `beatTrackPreferredBPM` | `120.0` | centre of the tempo-preference weight + pre-lock default |
| `beatTrackPreferenceWidthOctaves` | `0.9` | log-Gaussian width of the preference weight |
| `beatTrackTempoSmoothing` | `0.9` | one-pole smoothing of the beat period across analyses |
| `beatTrackAnalysisHopFeatures` | `8` | re-run tempo induction every N features |
## Usage
```swift
// FFT-fed (.spectralFlux): drop on any audio source.
let chain = SpectralChain.Audio(input: drums, fftSize: 1024, hopSize: 512, analyzeOnly: true)
let bt = BeatTrack.Control(analysis: chain) // == BeatTrack.Control(odf: .spectralFlux(analysis: chain))
// bt[0] = beat trigger, bt[3] = tempo BPM
// Feature-fed (.feature): supply your own detection function.
let flux = SpectralFlux.Control(analysis: chain)
let bt2 = BeatTrack.Control(feature: flux) // == BeatTrack.Control(odf: .feature(flux))
```
## Parameters
### `BeatTrack.Control`
The designated init takes `odf: BeatTrackODF`; `analysis:` / `feature:` /
`spectral:` are convenience inits that build the corresponding case.
| Param | Type | Default | Meaning |
|---|---|---|---|
| `odf` | `BeatTrackODF` | — | ODF source: `.spectralFlux(analysis:)` or `.feature(_:)` |
| `minBPM` | `Double` | `60.0` | tempo search lower bound |
| `maxBPM` | `Double` | `200.0` | tempo search upper bound |
| `preferredBPM` | `Double` | `120.0` | preference-weight centre + pre-lock default |
| `windowSeconds` | `Double` | `6.0` | ODF history length |
Convenience inits: `BeatTrack.Control(analysis: SpectralChain.Audio, …)`,
`BeatTrack.Control(feature: any ValidGeneratorInput, …)`, and
`BeatTrack.Control(spectral: SpectralBuffer, …)` (buffer-only, for tests /
advanced use — no analysis auto-pull).
`minBPM` / `maxBPM` / `preferredBPM` / `windowSeconds` are read **once at
`init`** (they size the ring and the lag range — not RT-mutable). Audio-input
driven, Control-rate output only; no `Audio` variant exists.
## Implementation layout
- `Generators/Analysis/BeatTrackerCore.swift` — shared, non-`Generator` class
holding the ODF ring, decimation accumulator, autocorrelation/tempo state,
phase accumulator, and the 4-output computation. Fed one per-block ODF value
at a time; mutated in place (no allocation after `init`).
- `Generators/Analysis/BeatTrack.swift` — the `BeatTrack.Control` generator; a
private `Source` enum selects spectral-flux vs feature ODF per block.
- `Generators/Analysis/BeatTrackODF.swift` — the public `BeatTrackODF` source
selector (the implementation flag).
- `Generators/Analysis/BeatTrackHelpers.swift` — `blockMaxODF` + the flat-row
output fill.
- `Generators/Analysis/BeatTrackConstants.swift` — the named constants above.
Each is a separate file (one public type per file). `BeatTrackerCore` is
`internal`.
## Test plan (tests-first)
Deterministic synthetic ODF feeds (no audio hardware):
1. **Tempo lock** — feed a periodic impulse ODF at 120 BPM for several seconds;
assert row 3 converges to 120 ± 5 %.
2. **Different tempo** — repeat at 90 BPM; assert lock at 90 ± 5 % (guards
against a hard-coded period).
3. **Beat spacing** — count row-0 triggers over N seconds; assert ≈
`N · BPM / 60` beats and mean inter-trigger interval ≈ the beat period.
4. **Subdivisions** — assert row 1 fires ~2× and row 2 ~4× as often as row 0.
5. **Silence safe** — zero ODF: no NaN/Inf in any row, tempo finite.
6. **DC ODF** — constant non-zero ODF: no spurious lock to a degenerate period.
7. **Multi-row shape** — `outputChannelCount == 4`; all four rows length
`count`.
8. **`BeatTrack` integration** — build a `SpectralChain` on a synthetic click
track (an `Impulse` at the beat rate) and assert the FFT-fed path locks tempo.
---
# Loudness — Zwicker psychoacoustic loudness
`Loudness.Control` estimates perceived **loudness in sones** from the magnitude
spectrum of a paired analyze-only `SpectralChain.Audio`. One sone is, by
definition, the loudness of a 1 kHz pure tone at 40 dB SPL; perceived loudness
roughly doubles per +10 dB (Stevens' power law).
Three fidelity models are folded into the one generator behind a `LoudnessModel`
flag (mirroring the `Balance` `logDomain:` and `BeatTrack` `BeatTrackODF` folds).
The selector is an enum because the models carry different parameters:
- **`.barkEstimate`** — cheapest. Power summed into ~24 Bark critical bands → a
Stevens power-law specific loudness per band → sum. No masking, no
equal-loudness contour. Rough but stable; no SC parity claim.
- **`.realtimeZwicker(smask:tmask:)`** — SC `Loudness` ergonomics. Bark-band
excitation, equal-loudness/threshold weighting, specific loudness
`N' = (E/E₀)^0.23`, an upper-slope **spectral mask** (`smask`, spreads
excitation toward higher bands) and a **temporal mask** (`tmask`, one-pole
decay on the running total). Clean-room real-time Zwicker.
- **`.iso532b(field:)`** — full **ISO 532 B / DIN 45631** stationary Zwicker
loudness. Third-octave band levels (28 bands, 25 Hz … 12.5 kHz) → core
loudness via the standard's RAP/DLL correction tables → critical-band level
excitation with the LTQ/A0/DDF/DCB tables → upper-slope spreading (USL) →
integrate the specific-loudness function. `field` selects free vs
diffuse field. Highest fidelity; heaviest. Clean-room from Zwicker's published
algorithm (Zwicker, Fastl & Dallmayr 1991; DIN 45631) — **not** a port of the
GPL SuperCollider `Loudness` source.
> **Clean-room note.** SuperCollider's `Loudness` (Nick Collins) is GPL and uses
> baked Bark/equal-loudness tables. This is an independent implementation from
> the published Zwicker model and the ISO 532 B / DIN 45631 standard. Output is
> in sones; do not expect bit-exact parity with SC.
## Output
`Loudness.Control` is a single-row `ControlGenerator`: total instantaneous
loudness in **sones** (≥ 0), ramped across the block like other control features
(`fillRampedResult`). `floatValue` returns the latest value.
## Calibration
Loudness needs absolute level (dB SPL), but the FFT magnitudes are in arbitrary
digital units (the exact scale depends on window + FFT normalisation). A single
`calibrationDB` parameter bridges the two: it is the dB offset added to each
bin's power level so that digital level maps to assumed SPL. Per bin:
```
P_k = magnitude(k)² // power, arbitrary units
L_k = 10·log10(P_k + tiny) + calibrationDB // dB SPL
```
`calibrationDB` defaults to `loudnessDefaultCalibrationDB` (chosen so a
full-scale 1 kHz sine lands near the top of the musical range). It is read once
at init. The **relative** behaviour (doubling per +10 dB, monotonicity) is
calibration-independent; only the absolute sone value depends on it. Set it per
your monitoring chain if absolute SPL matters; the documented anchor (1 kHz @
40 dB SPL = 1 sone) holds once `calibrationDB` is set so the test tone reads
40 dB SPL.
## Algorithm
### Shared front-end (all models)
1. Per bin `k`: power `P_k = magnitude(k)²`, centre frequency
`f_k = k · sampleRate / fftSize`.
2. Accumulate bin power into the model's band set:
- `.barkEstimate` / `.realtimeZwicker` → ~24 **Bark** critical bands
(band edges from the standard Bark scale).
- `.iso532b` → 28 **third-octave** bands (25 Hz … 12.5 kHz).
3. Band power → band level `L_band = 10·log10(P_band + tiny) + calibrationDB`.
The bin→band index map is precomputed at init from `fftSize` + `sampleRate`
(no per-block branching on frequency); band accumulation is a single pass over
bins.
### `.barkEstimate`
Per Bark band: specific loudness `N'_z = max(0, (I_z / I₀)^0.3)` where `I_z` is
band intensity and `I₀` the reference intensity (`loudnessReferenceIntensity`).
Total `N = Σ N'_z` scaled by `loudnessBarkSpecificScale`. Stevens' exponent
`0.3` gives the +10 dB → 2× behaviour.
### `.realtimeZwicker(smask:tmask:)`
Per Bark band: excitation `E_z` from band level minus the band threshold-in-quiet
(`loudnessBarkThreshold[z]`); specific loudness
`N'_z = loudnessZwickerConst · (E_z/E₀)^0.23 · ((1 - s + s·E_z/E_thr)^0.23 - 1)`
in the Zwicker simplified form. `smask ∈ [0,1]` mixes an upper-slope spread of
excitation into higher bands before the exponent (spectral masking). The summed
loudness is then temporally masked by a one-pole release controlled by `tmask`
(seconds-ish; larger = slower decay, more masking of transients). Defaults
`smask = 0.25`, `tmask = 1.0` (SC defaults).
### `.iso532b(field:)`
The stationary Zwicker procedure (DIN 45631):
1. Third-octave band levels → **core loudness** per critical band using the
`loudnessISORAP` range thresholds and the `loudnessISODLL` 8×28 correction
matrix (level-dependent transmission), the three lowest bands combined per
the standard.
2. Critical-band excitation level with `loudnessISOLTQ` (threshold in quiet),
`loudnessISOA0` (transfer ear), `loudnessISODDF` (free→diffuse, applied when
`field == .diffuse`), `loudnessISODCB` (core-loudness correction).
3. Specific loudness per critical band; **upper-slope spreading** down the
critical-band-rate (Bark) scale using `loudnessISOUSL` (18×8 slope table),
`loudnessISORNS`, and `loudnessISOZUP`.
4. Integrate the specific-loudness function (trapezoidal, band by band) → total
loudness `N` (sones).
`field: LoudnessField` is `.free` (default) or `.diffuse`. Tables are transcribed
from the published standard; validated against the 1 kHz @ 40 dB = 1 sone anchor.
### Edge cases
- **Silence / zero spectrum**: all band powers ≈ 0 → `N → 0` sones; no NaN/Inf
(the `+ tiny` floor guards `log10(0)`, and specific loudness clamps at 0).
- **Monotonic**: more input power ⇒ more sones (all models).
- State (the `.realtimeZwicker` temporal-mask one-pole) is denormal-flushed each
block.
## Constants (named, no magic numbers)
| Constant | Meaning |
|---|---|
| `loudnessDefaultCalibrationDB` | default dBFS→SPL offset |
| `loudnessReferenceIntensity` | `I₀`, reference intensity for specific loudness |
| `loudnessTinyPower` | `log10` divide-by-zero floor |
| `loudnessBarkBandCount` | 24 (Bark critical bands) |
| `loudnessBarkEdgesHz` | Bark band edge frequencies |
| `loudnessBarkThreshold` | per-Bark threshold in quiet |
| `loudnessStevensExponent` | `0.3` (barkEstimate power law) |
| `loudnessZwickerExponent` | `0.23` (realtime Zwicker) |
| `loudnessZwickerConst`, `loudnessBarkSpecificScale` | model output scalings |
| `loudnessISOThirdOctaveCount` | 28 |
| `loudnessISOCenterFreqsHz`, `loudnessISORAP`, `loudnessISODLL`, `loudnessISOLTQ`, `loudnessISOA0`, `loudnessISODDF`, `loudnessISODCB`, `loudnessISOZUP`, `loudnessISORNS`, `loudnessISOUSL` | ISO 532 B tables |
## Usage
```swift
let chain = SpectralChain.Audio(input: mix, fftSize: 2048, hopSize: 512, analyzeOnly: true)
// Cheap real-time meter:
let n1 = Loudness.Control(model: .barkEstimate, analysis: chain, sampleRate: sr)
// SC-style:
let n2 = Loudness.Control(model: .realtimeZwicker(smask: 0.25, tmask: 1.0), analysis: chain, sampleRate: sr)
// Full standard:
let n3 = Loudness.Control(model: .iso532b(field: .free), analysis: chain, sampleRate: sr)
// n[*] output is loudness in sones (single row).
```
## Parameters — `Loudness.Control`
The designated init takes `model: LoudnessModel`; convenience inits may default it.
| Param | Type | Default | Meaning |
|---|---|---|---|
| `model` | `LoudnessModel` | `.realtimeZwicker(smask:0.25,tmask:1.0)` | fidelity model + its params |
| `analysis` | `SpectralChain.Audio` | — | analyze-only chain (read each block) |
| `sampleRate` | `Double` | — | for bin→Hz band mapping |
| `calibrationDB` | `Double` | `loudnessDefaultCalibrationDB` | dBFS→SPL offset |
| `mul` / `add` | `ValidGeneratorInput` | `1.0` / `0.0` | output scaling |
`model` / `sampleRate` / `calibrationDB` are read once at init (they size the
band map and tables — not RT-mutable). Audio-input driven, Control-rate output;
no `Audio` variant.
## Implementation layout
- `Generators/Analysis/Loudness.swift` — `Loudness.Control`; a private model
switch selects the backend per block.
- `Generators/Analysis/LoudnessModel.swift` — public `LoudnessModel` enum +
`LoudnessField`.
- `Generators/Analysis/LoudnessBandCore.swift` — shared FFT→band-power binning
(Bark + third-octave maps) + the per-model specific-loudness backends.
- `Generators/Analysis/LoudnessConstants.swift` — named constants + the ISO 532 B
tables.
## Test plan (tests-first)
Synthetic spectra fed through a `SpectralChain` (or a directly populated
`SpectralBuffer`):
1. **Silence → ~0 sones** for all three models; finite, no NaN/Inf.
2. **Monotonic with level** — louder sine ⇒ more sones (all models).
3. **+10 dB ≈ 2×** — a sine 10 dB louder ≈ doubles sones (Stevens range),
tolerance ~30 % (model-dependent).
4. **Calibration anchor** — a 1 kHz sine with `calibrationDB` set so it reads
40 dB SPL → ≈ 1 sone (±~25 %), per model where defined (strongest for
`.iso532b` and `.realtimeZwicker`).
5. **Each model runs + finite** over many blocks; control-rate output shape
(single row, length `count`, ramped).
6. **`field` effect** — `.iso532b(.diffuse)` differs from `.free` for an HF tone.
7. **Enum-vs-convenience init equivalence** if convenience inits are added.