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
+12 -1
View File
@@ -2,7 +2,7 @@
Phases are ordered by dependency. Each phase should have tests before moving on.
Completed phases (1–34, 36–95, 96a, 97, 99, 101, 102a, 102b, 103, 104a, 104b, 104c, 104d, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 159, 160, 161, 162, 163, 170, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 196, 197, 198, 88b, MCE-A, MCE-B, 85.5, 86.75a, 86.75b, LyrebirdBufferUpdates, 77-review-cleanup, 71b, 49b, 46, iOS-1–iOS-4, Score Phases A–D, 204, 222) are archived in `docs/01-completed-working-order.md`.
Completed phases (1–34, 36–95, 96a, 97, 99, 101, 102a, 102b, 103, 104a, 104b, 104c, 104d, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 159, 160, 161, 162, 163, 170, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 196, 197, 198, 88b, MCE-A, MCE-B, 85.5, 86.75a, 86.75b, LyrebirdBufferUpdates, 77-review-cleanup, 71b, 49b, 46, iOS-1–iOS-4, Score Phases A–D, 204, 222, GC-1–GC-9B, GC-11, GC-12) are archived in `docs/01-completed-working-order.md`.
## Phase Completion Checklist
@@ -433,6 +433,17 @@ GP-8. Each lands on `main` via `--no-ff` before the next starts, per policy.
choice (three branchless loops vs per-sample function call); leave as-is, revisit
only if `OscillatorTableReadHelpers` gains a bitmask-wrap variant.
### Generator Catalog Expansion — 1.2 (SuperCollider parity gaps) ✓ *(complete)*
Closed the most-noticed UGen gaps relative to SuperCollider (trigger/timing
logic, control-signal conditioning, filters, waveshaping/routing, chaotic
oscillators, analysis). **The whole 1.2 group is complete** — GC-1…GC-9B, GC-11,
and GC-12 merged to main; GC-10 (`DFM1`) skipped on license grounds (GPL source +
baked GPL LUT). All phase records are archived in
`docs/01-completed-working-order.md` (§ Generator Catalog Expansion — 1.2).
`TGrains` and `PingPongDelay` were explicitly excluded from this group (deferred
separately).
### Longer-term — Not planned
#### Phase 96b — Ableton Link *(not planned)*
+172
View File
@@ -10588,3 +10588,175 @@ cleanup + CLAUDE.md rule · 229 polymeter. The Score system now places notes at
explicit/musical beats with rest auto-fill, addresses beats across simple/compound/
additive meters, handles overlaps + multi-voice, and renders mid-piece meter changes,
anacrusis, and polymeter — all MusicXML-export-faithful.
---
## Generator Catalog Expansion — 1.2 (GC group)
Closed the most-noticed UGen gaps relative to SuperCollider, sourced from a full
catalog sweep against the existing built-ins. Gaps clustered in trigger/timing
logic, control-signal conditioning, a few filters, waveshaping/routing, and the
chaotic-oscillator family. `TGrains` and `PingPongDelay` were explicitly excluded
(deferred separately). GC-10 was skipped on license grounds (see below). GC-12
(`Loudness`) remains pending in `docs/00-working-order.md`.
### Phase GC-1 — Trigger / timing primitives ✓ *(merged to main)*
`Generators/Triggers/`. The weakest family vs SC; bread-and-butter of drum
machines, arpeggiators, and gate logic. Trivial state machines on `GeneratorBase`;
per-audio-block trigger state → `_calculatedSamplesBlockRate` bypass (canonical
edge-detect pattern). Audio + Control each.
- **`Trig` / `Trig1`** (SC `Trig`/`Trig1`) — on a rising edge, output `1.0` for
`dur` seconds, then `0`. One-shot pulse stretcher. Distinct from `SendTrigger`.
- **`TriggeredDelay`** (SC `TDelay`) — re-fire a trigger after `dur` seconds.
- **`PulseCount`** (SC `PulseCount`) — count rising edges; optional `reset`.
- **`Stepper`** (SC `Stepper`) — step through `min…max` by `step` on each trigger,
wrapping. Optional `reset`.
- **`Schmidt`** (SC `Schmidt`) — Schmitt trigger with hysteresis band.
### Phase GC-2 — Sync + slew conditioning ✓ *(merged to main)*
- **`Phasor`** (SC `Phasor`) — normalized `[start, end)` phase accumulator with
`freq` + `trig` reset. `Generators/Oscillators/`; shares `OscillatorBase` for
`freq` classification but not the `[-1, 1]` phase normalisation. Audio + Control.
- **`Slew`** (SC `Slew`) — linear rate-limiter (`up`/`dn` units/sec), distinct
algorithm from exponential `Lag`. `Generators/Filters/`. Audio + Control.
### Phase GC-3 — Analysis / tracking primitives ✓ *(merged to main)*
`Generators/Analysis/`. All single-state, trivial.
- **`ZeroCrossing`** (SC `ZeroCrossing`) — zero-crossing rate in Hz. Audio + Control.
- **`Slope`** (SC `Slope`) — per-sample first difference. Audio + Control.
- **`RunningMin` / `RunningMax`** — running extreme with optional `trig` reset.
Audio + Control.
### Phase GC-4 — Routing / morph ✓ *(merged to main)*
- **`Select`** (SC `Select`) — pick one of N input generators by integer index;
inputs classified at `init` (no RT `is`/`as?`). `Generators/Routing/`. Audio + Control.
- **`CrossFade` / `LinearCrossFade`** (SC `XFade2`/`LinXFade2`) — equal-power /
linear crossfade on a `[-1, 1]` `pos`. Audio + Control.
### Phase GC-5 — Waveshaping / distortion ✓ *(merged to main; `Shaper` renamed `Waveshaper`)*
New `Generators/Waveshaping/` subfolder.
- **`Waveshaper`** (SC `Shaper`) — table-lookup waveshaper; `[-1, 1]` input indexes
a `LyrebirdBuffer` transfer curve via the `OscillatorTableReadHelpers` read path.
Audio + Control.
- **`CrossoverDistortion`** (SC `CrossoverDistortion`) — dead-zone distortion.
Audio + Control.
- **`Disintegrator`** (SC `Disintegrator`) — stochastic sample-zeroing via
`xorshift64Next`. Audio.
### Phase GC-6 — Resonant-shape filter + Gaussian LFO ✓ *(merged to main)*
Implemented as the difference of two two-pole Ringz resonators (`Formlet ==
Ringz(decay) − Ringz(attack)`) reusing `runTwoPoleResonatorScalarBlock` /
`…InterpolatedBlock` + `resonatingCoeffs`. `LFGauss` parameterized by `period`
(seconds); bell `out = exp(−0.5·(x/width)²)`, `x = 2·phase − 1`.
- **`Formlet`** (SC `Formlet`) — resonant filter by `attackTime` / `decayTime`.
Audio + Control.
- **`LFGauss`** (SC `LFGauss`) — Gaussian bell oscillator (`period`, `width`,
`phase`). `Generators/Oscillators/`. Audio + Control.
### Phase GC-7 — Chaotic / strange-attractor oscillators ✓ *(merged to main; nine chaotic oscillators on `ChaoticBase`)*
`ChaoticBase` (holds `freq`/`_mulAdd`/`interpolation` + 4-value history ring +
sub-iteration phase accumulator; `iterate()` per map; `stepRate` clamps per-sample
iteration count for RT safety), `ChaoticHelpers` (`chaoticInterpolate`
`.none`/`.linear`/`.cubic` via shared `catmullRomCubic`). Maps iterate at `freq` Hz
(read per block) and bridge iterations by interpolation. New `Generators/Chaotic/`.
- **`LorenzLinear`** (SC `LorenzL`, default `.linear`; default Euler `h` = `0.02`).
- **`HenonStepped`** (SC `HenonN`), **`QuadStepped`** (SC `QuadN`),
**`LinCongStepped`** (SC `LinCongN`, output `[0,m)`), **`GbmanStepped`** (SC `GbmanN`).
- Follow-ons on the same base: `StandardN`/`FBSineN`/`LatoocarfianN`/`CuspN`.
Interpolation-suffix convention: SC `N`/`L`/`C` (non/linear/cubic bridging)
replaced by an explicit Lyrebird name + an `interpolation: TableInterpolation`
parameter where more than one bridging mode is wanted.
### Phase GC-8 — Runtime-respecifiable resonator / partial banks ✓ *(merged to main)*
- **`Klank`** (SC `Klank`) — parallel two-pole resonator bank reading a
`[freq, amp, decay]` spec buffer, plus `freqscale` / `freqoffset` / `decayscale`
modulation; whole spec live-swappable via `setBuffer` (RT-safe `RTBufferSlot`).
Reuses `ResonatorBank`'s vDSP kernel. `Generators/Filters/`. Audio-only.
- **`Klang`** (SC `Klang`) — additive sinusoidal-partial bank summing N table sines
from a `[freq, amp, phase]` spec; `phase` seeds each accumulator at init so live
`setBuffer` retunes keep phase continuity. `Generators/Oscillators/`. Audio-only.
### Phase GC-9 — `Normalizer` ✓ *(merged to main)*
- **`Normalizer`** (SC `Normalizer`) — look-ahead peak normalizer; scans ahead
`dur` seconds, scales **up AND down** to `level` (vs `LookAheadLimiter`, which
only attenuates). Reuses the limiter's pre-allocated delay ring + monotonic
sliding-window-max deque; gain `level / windowPeak` (instant attack, one-pole
smoothed release; silence holds gain). Latency `Int(dur·sr)`. `Generators/Dynamics/`.
Audio-only.
### Phase GC-9B — `Balance` (sc3-plugins JoshUGens) ✓ *(merged to main)*
- **`Balance`** (SC `Balance.ar(in, test, hp = 10)`) — RMS level matcher; scales
`in` so its running RMS tracks reference `test`. Running mean-square via
`onePoleLowPassStep` on `x²` (pole `b1 = exp(-2π·hp/sr)`); `out = in ·
sqrt(ms_test / (ms_in + tiny))`. Gain is a ratio of like-normalised mean-squares
so the one-pole normalisation cancels (matches SC's unnormalised running-sum,
bounded + denormal-safe). Two-input Ring4-style wiring. `Generators/Dynamics/`.
Audio-only.
- Follow-on (`balance-improvements` → `balance-fold-logdomain`): decoupled gain lag
(`smooth`, default `0` = bit-identical to the classic single-pole) decouples
detection speed (`hp`) from gain-change rate; log-domain smoothing (lag
`log10(ms_test/ms_in)` then exp — symmetric perceptual glide) folded into the same
type behind `logDomain: Bool = false` (initially a separate `BalanceDB`, then
merged). Final signature: `Balance(in:test:hp:10, smooth:0, logDomain:false, mul:, add:)`.
### Phase GC-10 — `DFM1` ✗ *(skipped — license incompatible)*
- **`DFM1`** (SC `DFM1`) — digital filter with nonlinear feedback saturation.
**Skipped:** the SC `Dfm1` source (`sc3-plugins/source/TJUGens/Dfm1.cpp`,
Hardie-Bick / Stutters) is **GPL v2+**, and the model *is* a baked 16-octave ×
32-step coefficient LUT (no closed form in the source) — a faithful port would
copy GPL data into the MIT codebase. A clean-room reimplementation of the
topology (two leaky integrators + cubic feedback distortion) is possible but was
de-prioritised in favour of GC-11; revisit only if a clean-room DFM-style filter
is wanted.
### Phase GC-11 — `BeatTrack` ✓ *(merged to main)*
- **`BeatTrack`** (SC `BeatTrack` + `BeatTrack2`, folded into one type) —
real-time tempo + beat-phase tracker. Clean-room (autocorrelation tempo induction
+ log-Gaussian tempo preference + phase locking; **not** a port of the GPL SC
sources). One `BeatTrack.Control` backed by an internal `BeatTrackerCore` (ODF
decimation → whitening → power-of-two ring → weighted autocorrelation → phase
accumulator), emitting 4 control-rate rows: beat / eighth / sixteenth triggers +
tempo (BPM). ODF source is a `BeatTrackODF` flag (mirroring the `Balance`
`logDomain:` fold): `.spectralFlux(analysis:)` computes flux from a paired
`SpectralChain.Audio` (FFT-fed = SC `BeatTrack`); `.feature(_:)` takes an external
onset-detection signal (feature-fed = SC `BeatTrack2`). `Generators/Analysis/`.
Design + algorithm: `docs/stdlib/analysis.md`.
### Phase GC-12 — `Loudness` ✓ *(merged to main)*
- **`Loudness`** (SC `Loudness`) — psychoacoustic loudness meter in **sones** from
a paired analyze-only `SpectralChain.Audio`. Clean-room implementation of the
published Zwicker model and ISO 532 B / DIN 45631 (tables transcribed from the
Apache-2.0 MoSQITo project + the standard) — **not** a port of the GPL SC
`Loudness`. Three fidelity models folded into one `Loudness.Control` behind a
`LoudnessModel` flag (mirroring the `Balance` `logDomain:` / `BeatTrack`
`BeatTrackODF` folds): `.barkEstimate` (Stevens power law over third-octave band
intensities), `.realtimeZwicker(smask:tmask:)` (critical-band Zwicker specific
loudness with spectral-masking constant + temporal-mask one-pole), and
`.iso532b(field:)` (full stationary Zwicker — low-band RAP/DLL correction → LCB
combination → critical-band excitation with LTQ/A0/DDF/DCB → upper-slope
integration). Shared `LoudnessBandCore` does FFT→third-octave (28-band) binning
(precomputed bin→band map) then per-model specific loudness; `LoudnessField`
(free/diffuse) in its own file. Calibration via a `calibrationDB` dBFS→SPL
offset. `Generators/Analysis/`. Control-rate, single-row (sones) output.
Validated against the **1 kHz @ 40 dB SPL = 1 sone** definition anchor (all
models), +10 dB ≈ 2× (Stevens), monotonicity, silence→0, free≠diffuse. Design +
algorithm + tables: `docs/stdlib/analysis.md`. This completes the GC 1.2 group.
+1
View File
@@ -1200,6 +1200,7 @@ These wrap the common pattern *"vectorise the full-block case, fall back to a sc
| `plateReverbTankHalf(...)` | `Generators/Reverb/PlateReverbHelpers.swift` | One half of the Dattorro figure-of-eight tank: modulated allpass → delay 1 → damping LP → decay scale → allpass 2 → delay 2 write. Used twice per sample in `PlateReverb.Audio._computeSamples` (left + right halves). All state mutated `inout`; opposite-half feedback is read by the caller as `dl2Buf[dl2Pos]` (oldest sample) before invoking this helper. `@inline(__always) internal`. |
| `gverbReadEarlyTaps(...)` | `Generators/Reverb/GVerbHelpers.swift` | Reads four pre-FDN early-reflection taps from `tapBuf` with branchless wrap + per-tap gains; returns the four samples as `(u0, u1, u2, u3)`. Consumed by `GVerb.Audio._computeSamples`. `@inline(__always) internal`. |
| `gverbFDNDamperCascade(...)` | `Generators/Reverb/GVerbHelpers.swift` | Applies four one-pole LP damper steps `y = x*(1-damp) + prev*damp` to the four raw FDN delay-line reads. Mutates `fdnDampState[0..3]` `inout` with denormal flush; returns `(d0, d1, d2, d3)`. Caller pre-computes `fdnPassThrough = 1 - dampingVal`. `@inline(__always) internal`. |
| `catmullRomCubic(_:_:_:_:t:)` | `Math/CubicInterpolation.swift` | The single shared 4-point Catmull-Rom cubic kernel. Args `(pM1, p0, p1, p2, t:)` — sample before the segment, the two bracketing it, the one after, `t ∈ [0, 1]`. Use instead of inlining the `t²`/`t³` expanded form. Consumers: oscillator table reads (`OscSin`, `oscillatorTableReadCubic`), `PlayBuffer`, `chaoticInterpolate`, fractional-delay lines (`DelayLine` / `DelayLineFeedback` / `CombFilter` / `AllpassFilter`). `@inline(__always) @_spi(LyrebirdExtensions) public`. |
| `makeSampleBuffer(_:)` / `makeResultBuffer(channels:)` | `ResultBuffer.swift` | Separately-owned scratch buffer or non-`GeneratorBase`-managed `_result` |
| `_mulAdd.applyIfNeeded(to:graph:count:)` | `MulAdd.swift` | Any generator with a `MulAddSpec` — audio or control rate |
| `fillRampedResult(into:from:to:mulAdd:graph:count:)` | `MulAdd.swift` | `ControlGenerator` with `_rampTarget` + `_mulAdd` following the standard ramp pattern |
+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.
+373 -2
View File
@@ -16,7 +16,7 @@ extension OscSin: GeneratorEnum {
}
```
All paired built-in generators (`OscSin`, `OscTable`, `Impulse`, `WhiteNoise`, `LFStepNoise`, `LFLineNoise`, `PinkNoise`, `BrownNoise`, `GrayNoise`, `ClipNoise`, `Dust`, `Dust2`, `Crackle`, `LFCurveNoise`, `UniformNoise`, `GaussNoise`, `LpRandNoise`, `HpRandNoise`, `MeanRandNoise`, `ExpRandNoise`, `ExponentialNoise`, `GammaNoise`, `LaplaceNoise`, `ALaplaceNoise`, `HcosNoise`, `LogisticNoise`, `PoissonNoise`, `ArcsinNoise`, `BetaRandNoise`, `CauchyNoise`, `EnvelopeGen`, `PlayBuffer`, `RecordBuffer`, `In`, `Out`, `SendTrigger`, `Demand`, `TimedDemand`) conform to `GeneratorEnum`. New paired generators must do the same — see `docs/protocols/writing-generators.md`.
All paired built-in generators (`OscSin`, `OscTable`, `Impulse`, `Phasor`, `WhiteNoise`, `LFStepNoise`, `LFLineNoise`, `PinkNoise`, `BrownNoise`, `GrayNoise`, `ClipNoise`, `Dust`, `Dust2`, `Crackle`, `LFCurveNoise`, `UniformNoise`, `GaussNoise`, `LpRandNoise`, `HpRandNoise`, `MeanRandNoise`, `ExpRandNoise`, `ExponentialNoise`, `GammaNoise`, `LaplaceNoise`, `ALaplaceNoise`, `HcosNoise`, `LogisticNoise`, `PoissonNoise`, `ArcsinNoise`, `BetaRandNoise`, `CauchyNoise`, `EnvelopeGen`, `PlayBuffer`, `RecordBuffer`, `In`, `Out`, `SendTrigger`, `Demand`, `TimedDemand`, `Trig`, `Trig1`, `TriggeredDelay`, `PulseCount`, `Stepper`, `Schmidt`, `Slew`, `ZeroCrossing`, `Slope`, `RunningMin`, `RunningMax`, `CrossFade`, `LinearCrossFade`, `Select`, `Waveshaper`, `CrossoverDistortion`, `Formlet`, `LFGauss`, `LorenzLinear`, `HenonStepped`, `QuadStepped`, `LinCongStepped`, `GbmanStepped`, `StandardStepped`, `FBSineStepped`, `LatoocarfianStepped`, `CuspStepped`) conform to `GeneratorEnum`. New paired generators must do the same — see `docs/protocols/writing-generators.md`.
## RT-allocation model (all generators)
@@ -184,6 +184,21 @@ Impulse.Audio(freq: 1.0, initPhase: 0.5) // first fire at half-period offset
- `initPhase` is a fraction [0, 1) — `0.0` fires at sample 0 of the first block.
- State: `LyrebirdFloat` phase accumulator.
#### Phasor
Linear phase accumulator (ramp generator). Equivalent to SuperCollider `Phasor`. Accumulates `rate` units per sample within the half-open range `[start, end)`. On a ≤0 → >0 rising edge of `trig`, phase resets to `resetPos`.
```swift
Phasor.Audio() // default: ramp 0..1 at 1/sample
Phasor.Audio(rate: 440.0 * 1024.0 / 44100.0, start: 0, end: 1024) // 1024-sample wavetable scan at 440 Hz
Phasor.Audio(trig: Impulse.Audio(freq: 2.0), rate: 0.01, resetPos: 0) // reset on trigger
Phasor.Control(rate: 0.001) // slow ramp at control rate
```
- `rate` is the **per-sample phase increment** (not Hz). For table scanning: `rate = freq * tableSize / sampleRate`.
- `start` / `end` define the half-open range `[start, end)`. Wrapping is via `truncatingRemainder` — safe for rates larger than the span.
- `trig` scans the full audio-rate trigger block per audio block in both `.Audio` and `.Control` variants.
- Standalone sync/ramp primitive; works at any rate in the signal graph.
---
### Noise
@@ -862,6 +877,36 @@ All `AudioGenerator` and `ControlGenerator` instances inherit a `[n]` subscript
Out-of-range `n` returns silence. See `docs/stdlib/multichannel.md` for full examples.
### CrossFade.Audio / CrossFade.Control (SC `XFade2`)
Equal-power crossfade between two inputs. Maps `pan ∈ [−1, 1]` to a quarter-sine/cosine
gain pair so that `gainA² + gainB² = 1` at every position. `mul` plays the role of SC's
`level` argument. Mono output (channel 0 of each input). Both `Audio` and `Control` variants.
```swift
let xfade = CrossFade.Audio(inA: osc1, inB: osc2, pan: modLFO)
```
### LinearCrossFade.Audio / LinearCrossFade.Control (SC `LinXFade2`)
Linear crossfade between two inputs. `gainA = (1 − pan) * 0.5`, `gainB = (1 + pan) * 0.5`
so `gainA + gainB = 1` everywhere. Useful when constant-amplitude sum is preferred over
constant power. `mul` plays the role of SC's `level` argument. Mono output. Both variants.
```swift
let xfade = LinearCrossFade.Audio(inA: dry, inB: wet, pan: sendLevel)
```
### Select.Audio / Select.Control (SC `Select`)
Index-selected N-input switch. Outputs the input at integer index `which` (truncated toward
zero, clamped to `[0, N−1]`). All inputs are pulled every block regardless of selection —
SC parity: non-selected sources advance their internal state. Both `Audio` and `Control` variants.
```swift
let sel = Select.Audio(which: modLFO, inputs: [osc1, osc2, osc3])
```
---
## LyrebirdMusicMath — Musical Conversion Utilities
@@ -998,16 +1043,24 @@ let freqCR = LinExp.Control(env, inLo: 0.0, inHi: 1.0, outLo: 80.0, outHi: 8000
## Dynamics
Five signal-processing generators for amplitude tracking, pitch detection, limiting, compression, and expansion. Full API reference: `docs/stdlib/dynamics.md`.
Seven signal-processing generators for amplitude tracking, pitch detection, limiting, normalizing, RMS matching, compression, and expansion. Full API reference: `docs/stdlib/dynamics.md`.
| Generator | Variants | Description |
|-----------|----------|-------------|
| `AmplitudeFollower` | Audio + Control | Envelope follower; asymmetric attack/release one-pole smoother |
| `FreqTracker` | Audio only | YIN-based pitch tracker; 2-channel out (Hz + confidence 0..1) |
| `LookAheadLimiter` | Audio only | True look-ahead limiter; no overshoot; `lookAheadTime` latency |
| `Normalizer` | Audio only | Look-ahead peak normalizer; scales up AND down to `level`; `dur` latency |
| `Balance` | Audio only | RMS level matcher; scales `in` to track the running RMS of `test`; decoupled `hp`/`smooth`; optional `logDomain` glide |
| `Compressor` | Audio + Control | Feed-forward compressor; threshold/ratio/attack/release/knee/makeup |
| `Expander` | Audio + Control | Downward expander/gate; mirrors `Compressor` below threshold |
`Balance` (sc3-plugins `Balance`, JoshUGens) tracks the running mean-square of two signals via a one-pole lowpass on squared samples (pole `b1 = exp(-2π·hp/sr)` from the `hp` cutoff in Hz, snapshotted per block) and outputs `in · sqrt(ms_test / (ms_in + tiny))`. Because the gain is a ratio of two identically-normalised mean-squares, the normalisation cancels — only the `hp` window length matters (equivalent to SC's unnormalised running-sum form, but bounded + denormal-safe). Canonical use: bring a filtered signal back up to the level of the unfiltered source. Silent `in` stays silent; silent `test` drives `in` toward zero; `tiny` (1e-10) guards the divide. Takes `mul`/`add`.
A single one-pole on `x²` ripples at twice the signal frequency, so a high `hp` lets that ripple modulate the gain (amplitude-modulation sidebands, worst on bass). `Balance` adds a second, **decoupled** one-pole on the gain via `smooth` (seconds): raise `hp` for fast level detection, then raise `smooth` to suppress the ripple independently. `smooth == 0` (default) bypasses the lag — bit-identical to the classic single-pole form. Set `logDomain: true` to smooth the gain in the **decibel (log) domain** instead: it smooths the level *difference in dB* (`log10(ms_test/ms_in)`) then exps back, so a `+6 dB` and a `−6 dB` correction glide with the same shape and time (symmetric, perceptually even — like an analogue auto-leveller), versus the default linear-gain lag which is faster on boosts than cuts. The log path costs one `log10` + one `exp` per sample and floors the power so silence stays finite.
`Normalizer` (SC `Normalizer`) shares `LookAheadLimiter`'s ring-buffer + monotonic sliding-window-max deque, but its gain law is `level / windowPeak` applied unconditionally (vs the limiter's `maxAmp / windowPeak` only when over the ceiling), so quiet passages are scaled **up** and loud ones **down** to track `level`. Instant attack (no overshoot) + one-pole smoothed release (time constant `dur`); output delayed by `Int(dur·sampleRate)`. `sampleRate` is required at init. An exactly-silent window holds gain (no `level/0`); a near-silent non-zero window amplifies its noise floor toward `level` (intended normalizer behaviour).
All generators are single-channel in/out. Multi-channel use via MCE. `AmplitudeFollower`, `Compressor`, `Expander` conform to `GeneratorEnum`.
---
@@ -1247,6 +1300,20 @@ LFTriangle.Audio(freq: 4.0, mul: 0.1) // gentle tremolo LFO
LFDutyCycle.Audio(freq: 6.0, dutyCycle: 0.2)
```
### LFGauss (SC `LFGauss`)
Gaussian bell-shaped oscillator. Over each `period` (seconds) the output traces a Gaussian bell — near `0` at the period boundaries, peaking at `1.0` at the period midpoint. `width` is the standard deviation as a fraction of the half-period (smaller → narrower spike). Output range `(0, 1]`. A smooth non-band-limited LFO and a ready-made grain-window shape. Paired `GeneratorEnum` (Audio + Control). `period` and `width` accept generator inputs; `phase` is an init-only `[0, 1)` offset (`0` starts at a trough, `0.5` at the peak).
```
x = 2·phase − 1 (phase advances 1 / (period · sr) per sample)
out = exp(−0.5 · (x / width)²)
```
```swift
LFGauss.Audio(period: 0.02, width: 0.15) // ~50 Hz bell-train LFO
LFGauss.Audio(period: 0.5, width: 0.1, phase: 0.0) // grain envelope, starts at trough
LFGauss.Control(period: 2.0, width: 0.25) // slow swell
```
### WavetableMorph
Linear-interpolation wavetable scanner across an array of equal-length mono `LyrebirdBuffer` tables. `position` ∈ `[0, table_count − 1]` selects between adjacent tables; fractional positions blend.
@@ -1266,6 +1333,78 @@ WavetableMorph.Audio(
---
## Chaotic / Strange-Attractor Oscillators
`Generators/Chaotic/`. Oscillators that iterate a discrete chaotic map at a chosen `freq` (iterations/sec, **not** once per sample) and bridge successive iterations with `interpolation` (`.none` held/aliased, `.linear`, `.cubic`). Shared base `ChaoticBase` (analogous to `NoiseBase`) owns `freq`, `mulAdd`, the interpolation kernel, a 4-value history ring, and the sub-iteration phase accumulator; per-map `_Base` subclasses add the map variables + `iterate()`. `freq` and map parameters are read once per block (no per-sample audio-rate modulation). `Control` advances one audio block per call and ramps via `fillRampedResult`. `Crackle` (under Noise) is the only per-sample chaotic map and is unrelated to this family.
### LorenzLinear (SC `LorenzL`)
Lorenz strange attractor by forward Euler (`x' = x + h·s·(y−x)`, etc.), output = `x`. Default `interpolation: .linear`. Output is the **raw** `x` coordinate (`|x|` ≲ 25 on the attractor) — scale with `mul`. The Euler step `h` defaults to `0.02`: SC's nominal `0.05` diverges under plain forward Euler (verified — blows up within ~25 steps), so keep `h` below ~0.03.
```swift
LorenzLinear.Audio(freq: 22050.0, mul: 0.05) // classic attractor tone, scaled to ~[-1,1]
LorenzLinear.Control(freq: 200.0, mul: 0.05) // slow chaotic LFO
```
### HenonStepped (SC `HenonN`)
Hénon map `x[n+1] = 1 − a·x[n]² + b·x[n−1]`, output = `x`. Default `interpolation: .none` (held/stepped — the aliased SC `HenonN` character). Canonical `a = 1.4`, `b = 0.3` → bounded chaotic orbit in roughly `[-1.5, 1.5]`.
```swift
HenonStepped.Audio(freq: 22050.0) // gritty stepped chaos
HenonStepped.Audio(freq: 8000.0, interpolation: .cubic) // smoothed
```
### QuadStepped (SC `QuadN`)
General quadratic map `x[n+1] = a·x[n]² + b·x[n] + c`, output `x`, default `.none`. Canonical `a = 1`, `b = −1`, `c = −0.75` → chaotic, bounded ~`[-1.25, 1.25]` (conjugate to the logistic map).
```swift
QuadStepped.Audio(freq: 6000.0)
```
### LinCongStepped (SC `LinCongN`)
Linear-congruential map `x[n+1] = (a·x[n] + c) mod m`, output stays in `[0, m)`, default `.none`. Canonical `a = 1.1`, `c = 0.13`, `m = 1`.
```swift
LinCongStepped.Audio(freq: 6000.0) // output in [0, 1)
LinCongStepped.Audio(freq: 6000.0, mul: 2.0, add: -1.0) // bipolarised to [-1, 1)
```
### GbmanStepped (SC `GbmanN`)
Gingerbreadman map `x[n+1] = 1 − y[n] + |x[n]|`, `y[n+1] = x[n]`; output `x`, default `.none`. No shape parameters — only initial conditions `xi`/`yi`. Bounded chaotic (`|x| ≲ 8`).
```swift
GbmanStepped.Audio(freq: 6000.0, mul: 0.2)
```
### StandardStepped (SC `StandardN`)
Chirikov standard map (kicked rotor): `y' = (y + k·sin(x)) mod 2π`, `x' = (x + y') mod 2π`; output `x` ∈ `[0, 2π)`. Larger `k` → stronger chaos (default `1`). Scale with `mul: 1/π, add: -1` for `[-1, 1)`.
```swift
StandardStepped.Audio(freq: 6000.0, k: 1.0)
```
### FBSineStepped (SC `FBSineN`)
Feedback sine map: `x' = sin(im·y + fb·x)`, `y' = (a·y + c) mod 2π`; output `x` ∈ `[-1, 1]`. Defaults `im=1`, `fb=0.1`, `a=1.1`, `c=0.5`.
```swift
FBSineStepped.Audio(freq: 6000.0)
```
### LatoocarfianStepped (SC `LatoocarfianN`)
Pickover's Latoocarfian: `x' = sin(b·y) + c·sin(b·x)`, `y' = sin(a·x) + d·sin(a·y)`; output `x` ∈ ~`[-1.5, 1.5]`. Chaos generally needs `|a|, |b| ≤ 3` (defaults `a=1`, `b=3`, `c=d=0.5`).
```swift
LatoocarfianStepped.Audio(freq: 6000.0)
```
### CuspStepped (SC `CuspN`)
Cusp map: `x' = a − b·√|x|`; output `x`. Canonical `a=1`, `b=1.9` → chaotic, bounded ~`[-0.9, 1.0]`.
```swift
CuspStepped.Audio(freq: 6000.0)
```
---
## EnvelopePoll
Read a fixed-shape `Envelope` at arbitrary times. Output is the envelope's level at `time` seconds. No internal phase or trigger — purely a value lookup. Useful for driving filter cutoff curves, panning trajectories, or pattern-driven scoring.
@@ -1323,6 +1462,18 @@ Lag2UpDown.Control(input: $sig, lagUp: 0.01, lagDown: 0.3) // cascade asymmetri
- `time`, `lagUp`, `lagDown` are 60 dB time constants in seconds.
- All accept audio-rate inputs; coefficient recomputation per block.
### Slew
Linear slew-rate limiter. Equivalent to SuperCollider `Slew`. Moves the output toward `input` at a maximum rate of `up` units per second when rising and `dn` units per second when falling. On the first block the output is initialised directly to the first input value.
```swift
Slew.Audio(input: controlSignal, up: 500.0, dn: 200.0) // asymmetric slopes
Slew.Control(input: $cv, up: 100.0, dn: 100.0) // smooth CV at control rate
```
- `up` / `dn` are slopes in **units per second** (not per sample). The per-sample step is `up / sampleRate` (audio) or `up / (sampleRate / blockSize)` (control).
- **Linear** rate-limiting — distinct from the **exponential** smoothing produced by the `Lag` family. Use `Lag` for an RC-filter curve; use `Slew` for a linear ramp at a controlled maximum slope.
- `Slew.Control` produces a flat output block (like `Lag.Control`); use `Slew.Audio` for smoothly interpolated output.
### Decay / Decay2 / LeakDC
- **`Decay`**: One-pole exponential decay tail on each non-zero input sample. `decayTime` is the 60 dB decay time in seconds.
- **`Decay2`**: Differenced pair of Decays — produces a percussive attack-then-release envelope from an impulse train.
@@ -1358,6 +1509,36 @@ ResonatorBank.Audio(input: excitation, buffer: buffer)
- Buffer `channelCount` precondition: `resonatorBankChannelCount` (= 3).
- Each row is a complex resonator; bank is summed to mono output.
### Klank.Audio (SC `Klank`)
Modulatable counterpart of `ResonatorBank` — parallel two-pole resonator bank with the three SC `Klank` block-rate modulation parameters. Spec buffer rows are `(freq, amp, decay)` (SC channel order). Audio-only.
```swift
let spec = LyrebirdBuffer(count: 3, channelCount: klankSpecChannelCount) // freq, amp, decay
// fill rows with N resonator specs
Klank.Audio(input: excitation, buffer: spec,
freqscale: 1.0, freqoffset: 0.0, decayscale: 1.0)
```
- `freqscale` / `freqoffset` / `decayscale` are any `ValidGeneratorInput`, snapshotted once per audio block: `freq_eff = freq·freqscale + freqoffset`, `decay_eff = decay·decayscale`.
- Buffer `channelCount` precondition: `klankSpecChannelCount` (= 3); channel indices `klankFreqChannel` / `klankAmpChannel` / `klankDecayChannel`.
- Whole-table live swap via `setBuffer(_:engine:)` (RT-safe `RTBufferSlot`); new buffer must match the initial bank size. `freq_eff` floored at `0.1` Hz, `decay_eff` at `1e-6` s; `amp` unclamped.
- Same vDSP per-sample kernel as `ResonatorBank`; summed to mono.
### Klang.Audio (SC `Klang`)
Additive sine-partial bank — the source counterpart of `Klank` (no input). Outputs the sum of N table-lookup sines. Spec buffer rows are `(freq, amp, phase)` (SC channel order). Audio-only.
```swift
let spec = LyrebirdBuffer(count: 4, channelCount: klangSpecChannelCount) // freq, amp, phase
// fill rows with N partial specs
Klang.Audio(buffer: spec, freqscale: 1.0, freqoffset: 0.0,
interpolation: .linear)
```
- `freqscale` / `freqoffset` snapshotted once per block: `freq_eff = freq·freqscale + freqoffset`.
- `freq` / `amp` re-read from the table each block (live `setValue` + `setBuffer(_:engine:)` swap retune the bank). The `phase` channel seeds each partial's phase accumulator at `init` only — phases free-run thereafter, so table swaps never click.
- Buffer `channelCount` precondition: `klangSpecChannelCount` (= 3); channel indices `klangFreqChannel` / `klangAmpChannel` / `klangPhaseChannel`.
- `interpolation: TableInterpolation` (`.none` / `.linear` / `.cubic`) on the shared sine table; `amp` and `freq_eff` unclamped (negatives invert / reverse).
### MuTronIII.Audio / .Control
*See [MuTronIII](#mutroniii) under Filters above for full description.*
@@ -1374,6 +1555,20 @@ RingingFilter(input: trig, freq: 440.0, bandwidth: 80.0) // tuned ringing
- `Comb` / `Allpass` use a circular delay line allocated to `maxDelay × sampleRate`; `delay` and `decayTime` can be retuned per block. Feedback coefficient derives from the shared `combFeedbackCoeff(decayTime:delay:)` helper.
- `Resonating` and `Ringing` are biquads tuned by `freq` + (`decayTime` | `bandwidth`).
### Formlet (SC `Formlet`)
FOF-like resonant filter parameterised by `attackTime` / `decayTime` rather than `freq` + `Q`. The impulse response is a sine at `freq` under a rise-then-fall (Decay2-style) envelope — the basis of formant / vowel synthesis. Defined as the difference of two `ResonatingFilter` (Ringz) outputs at the same `freq`:
```
Formlet(in, freq, attack, decay) == ResonatingFilter(in, freq, decay) − ResonatingFilter(in, freq, attack)
```
Paired `GeneratorEnum` (Audio + Control). Reuses `runTwoPoleResonatorScalarBlock` / `…InterpolatedBlock` and `resonatingCoeffs`. `freq`, `attackTime`, `decayTime` all accept generator inputs (block-boundary coefficient interpolation).
```swift
Formlet.Audio(input: impulse, freq: 880.0, attackTime: 0.001, decayTime: 0.1)
Formlet.Control(input: trig, freq: 220.0, attackTime: 0.01, decayTime: 0.5)
```
---
## Triggers
@@ -1414,6 +1609,74 @@ SendTrigger.Control(trig: Impulse.Control(freq: 4.0), id: 7, value: $cutoff)
- `id` is `Int32`, init-only.
- Events delivered via the engine's lock-free `TriggerListener` queue.
### Trig
SC `Trig`. On each ≤0 → >0 rising edge of `input`, captures the input value at that frame and outputs it for `dur` seconds, then returns to `0.0`. A new edge during the hold restarts the timer and re-captures the level.
```swift
Trig.Audio(input: Impulse.Audio(freq: 4.0), dur: 0.1)
Trig.Control(input: envTrig, dur: 0.5)
```
- `dur`: hold duration in seconds (init-time scalar; converted to samples via engine sample rate; minimum 1 sample).
- The `input` signal is both the trigger source and the level captured on each rising edge.
### Trig1
SC `Trig1`. Identical to `Trig` but always outputs `1.0` (unity) regardless of the input level for `dur` seconds after each ≤0 → >0 rising edge. Useful for generating fixed-amplitude gate pulses.
```swift
Trig1.Audio(input: Impulse.Audio(freq: 4.0), dur: 0.05)
Trig1.Control(input: envTrig, dur: 0.2)
```
- `dur`: hold duration in seconds (init-time scalar; minimum 1 sample).
### TriggeredDelay
SC `TDelay`. Delays a trigger by `dur` seconds: on a ≤0 → >0 rising edge of `input`, starts a countdown. When the countdown elapses, emits a single-sample `1.0`. Additional edges arriving while the countdown is active are **ignored** (only the first edge per idle cycle is honoured).
```swift
TriggeredDelay.Audio(input: Impulse.Audio(freq: 2.0), dur: 0.2)
TriggeredDelay.Control(input: clockTrig, dur: 0.1)
```
- `dur`: delay duration in seconds (init-time scalar; minimum 1 sample).
### PulseCount
SC `PulseCount`. Running counter that increments by 1 on each ≤0 → >0 rising edge of `trig`. A rising edge of `reset` clears the counter to `0.0` before the `trig` increment at that sample.
```swift
PulseCount.Audio(trig: Impulse.Audio(freq: 4.0))
PulseCount.Control(trig: clock, reset: resetTrig)
```
- Counter is never clamped and grows without bound.
### Stepper
SC `Stepper`. Wrapping integer step counter. On each rising edge of `trig`, advances by `step` within `[min, max]`, wrapping at the boundaries. `reset` returns the value to `resetval`. All range/step/reset parameters are init-time scalars.
```swift
// 8-step sequencer index cycling 0..7
Stepper.Audio(trig: Impulse.Audio(freq: 4.0), min: 0, max: 7, step: 1, resetval: 0)
Stepper.Control(trig: clock, reset: resetSig, min: 0, max: 15)
```
- `min`, `max`: range (inclusive). `max` must be ≥ `min`. Defaults: `0` / `7`.
- `step`: signed increment per edge. Defaults to `1`. Negative values step downward.
- `resetval`: value written on a reset edge; clamped to `[min, max]`. Defaults to `0`.
### Schmidt
SC `Schmidt`. Schmitt trigger with hysteresis. Maintains binary `0.0` / `1.0` state with separate switch-on (`hi`) and switch-off (`lo`) thresholds. Prevents chatter near the threshold.
- State `0.0` → `1.0`: when `input > hi`.
- State `1.0` → `0.0`: when `input < lo`.
- In the hysteresis band `[lo, hi]`: state unchanged.
```swift
Schmidt.Audio(input: amp, lo: 0.1, hi: 0.3)
Schmidt.Control(input: $cv, lo: 0.2, hi: 0.8)
```
- `lo`, `hi`: any `ValidGeneratorInput` — scalar literals, `ParameterNode`, `@LiveParam`, or audio/control-rate generators. When using audio-rate generators for per-sample varying thresholds, ensure they conform to `Generator` (not `Closure`).
---
## Random Generators
@@ -2255,3 +2518,111 @@ let onset = OnsetDetector.Control(analysis: analysis, method: .spectralFlux,
- `OnsetDetector` exposes `OnsetDetectionMethod` enum (`.spectralFlux`, `.complexDomain`, etc.); fires `1.0` for one block at each detected onset.
---
## Time-Domain Analysis
Four SuperCollider-parity time-domain analysis and measurement generators. Source files live in `Sources/Lyrebird/Generators/Analysis/`.
| Generator | SC equivalent | Audio | Control | Description |
|-----------|--------------|-------|---------|-------------|
| `ZeroCrossing` | `ZeroCrossing` | yes | yes | Frequency estimate (Hz) from rising zero-crossing spacing. Output held between crossings; `0.0` until the first full period is measured. |
| `Slope` | `Slope` | yes | yes | Per-second rate of change: `(x[n] − x[n−1]) × sampleRate`. First sample/block outputs `0.0` (lazy init — no startup spike). |
| `RunningMin` | `RunningMin` | yes | yes | Running minimum since the last trigger reset. Lazy-initialised to the first input value. Rising `trig` edge resets to the current input. |
| `RunningMax` | `RunningMax` | yes | yes | Running maximum since the last trigger reset. Identical behaviour to `RunningMin` but tracking the maximum. |
All four are paired generators conforming to `GeneratorEnum`. `Control` variants bypass the sub-block loop (scan the full audio-rate input block once per audio cycle and output a flat result).
```swift
// Frequency estimation.
let zcFreq = ZeroCrossing.Audio(input: audioSignal)
let zcFreqCtl = ZeroCrossing.Control(input: audioSignal) // block-rate measurement
// Rate-of-change differentiation.
let diff = Slope.Audio(input: envelope) // per-sample differentiation
let diffCtl = Slope.Control(input: $cv) // block-rate differentiation
// Peak / trough tracking.
let peakTracker = RunningMax.Audio(input: signal)
let peakTrackerReset = RunningMax.Audio(input: signal, trig: resetClock)
let troughTracker = RunningMin.Control(input: $cv, trig: gate)
```
Parameters common to all four:
- `input`: signal to analyse (`any ValidGeneratorInput`)
- `mul`: output multiplier, default `1.0`
- `add`: output offset, default `0.0`
- `RunningMin` / `RunningMax` additionally accept `trig` (default `0.0`)
---
## Waveshaping / Distortion
Transfer-function and stochastic distortion generators. Source files live in
`Sources/Lyrebird/Generators/Waveshaping/`.
| Generator | SC equivalent | Audio | Control | Description |
|-----------|--------------|-------|---------|-------------|
| `Waveshaper` | `Shaper` | yes | yes | Table-lookup transfer-function waveshaper. Input clamped to `[-1, 1]` before linear-interpolated table lookup. RT-safe live table swap via `setTable(_:engine:)`. |
| `CrossoverDistortion` | `CrossoverDistortion` | yes | yes | Dead-zone / crossover distortion. Signals in `[-amp, amp]` are silenced; signals outside that range are shifted toward zero. Optional C¹ smooth knee. |
| `Disintegrator` | `Disintegrator` | yes | — | Stochastic sample-dropping distortion. Each sample is independently disintegrated (replaced by `input × multiplier`) with probability `probability`. Audio-only. |
`Waveshaper` and `CrossoverDistortion` conform to `GeneratorEnum`. `Disintegrator` is Audio-only and does not.
### Waveshaper (SC `Shaper`)
Transfer-function waveshaper using a `LyrebirdBuffer` as the transfer curve.
```swift
let table = LyrebirdBuffer(count: 1024)
table.fill { i, n in
let x = Double(i) / Double(n - 1) * 2.0 - 1.0
return tanh(x * 4.0) // soft saturation
}
let shaper = Waveshaper.Audio(table: table, input: signal)
let lfoShaper = Waveshaper.Control(table: table, input: lfoSignal)
```
- `table`: mono `LyrebirdBuffer` (at least 2 samples). The transfer curve is indexed by the clamped input `x ∈ [-1, 1]` via `pos = (x × 0.5 + 0.5) × (tableSize − 1)` with linear interpolation.
- `input`: signal to waveshape. Values outside `[-1, 1]` are clamped (saturating, not wrapping).
- `mul` / `add`: standard output multiplier and offset.
- `setTable(_:engine:)`: RT-safe live table swap. New table must be mono and same size as the initial table.
### CrossoverDistortion (inspired by SC `CrossoverDistortion`)
Crossover / dead-zone distortion with optional smooth knee. The implementation is a clean
owned formula — not claimed bit-exact with SuperCollider, but sharing the same conceptual model.
```swift
// Hard-knee crossover: dead zone ±0.5, then linear continuation.
let dist = CrossoverDistortion.Audio(input: signal, amp: 0.5, smooth: 0.0)
// Soft-knee: C¹ quadratic ease-in at the dead-zone boundary.
let softDist = CrossoverDistortion.Audio(input: signal, amp: 0.3, smooth: 0.5)
```
- `amp`: dead-zone half-width (≥ 0). Signals in `[−amp, amp]` are zeroed. **Not an output gain** — use `mul` for gain. SC also names this `amp`.
- `smooth`: knee smoothness `[0, 1]`. `0` = hard knee (instantaneous transition); `1` = full-width C¹ ease-in over the full dead-zone width.
- Transfer function: for `|x| > amp`, `over = |x| − amp`. Hard-knee: `out = sign(x) × over`. Soft-knee: `out = sign(x) × over² / (2 × kneeWidth)` within the knee, then linear continuation maintaining C¹ continuity.
### Disintegrator (SC `Disintegrator`)
Stochastic sample-dropping distortion. Audio-only — "block-rate disintegration" has no
meaningful physical interpretation; the random draw must happen per sample.
```swift
// Drop ~50 % of samples to silence.
let dist = Disintegrator.Audio(input: signal, probability: 0.5, multiplier: 0.0)
// Attenuate ~30 % of samples by half.
let grit = Disintegrator.Audio(input: signal, probability: 0.3, multiplier: 0.5)
// Deterministic seed for tests.
let det = Disintegrator.Audio(input: signal, probability: 0.5, seed: 42)
```
- `probability`: `[0, 1]` chance per sample of disintegration. Clamped internally.
- `multiplier`: scale factor applied to disintegrated samples. `0.0` → silence; `1.0` → no change (same as `probability = 0`).
- `seed`: optional PRNG seed. `nil` = time-derived unique seed; explicit value = deterministic/reproducible output.
- `mul` / `add`: applied after disintegration to all samples (including undisintegrated ones).
---
+349
View File
@@ -0,0 +1,349 @@
# ShoeGaze — Guitar Pedalboard Framework
ShoeGaze is a nested SwiftPM sub-package (`ShoeGaze/`) that models a guitar-effect signal chain as a sequence of `Pedal` objects managed by a `PedalBoard`, all hosted by a `ShoeGaze` manager that owns the `SynthesisEngine`.
---
## Core Concepts
### `Pedal`
A `Pedal` is a `SynthesizerBase` subclass that reads a mono signal from its input bus, runs it through a subclass-supplied `effect(_:)` stage, blends wet/dry with an equal-power crossfade (`mix`), applies a click-free `bypass` crossfade, scales by `level`, and writes to its output bus. Each pedal exposes its knobs as `@UIParam` properties and publishes a `knobs: [PedalKnob]` list so `PedalView` (from `LyrebirdShoeGazeUI`) renders a control per parameter.
Eight built-in pedals (the signal chain is mono; stereo-native effects fold to mono internally):
| Type | Effect |
|---|---|
| `OverdrivePedal` | Soft-clip saturation → RBJ low-pass tone. Knobs: `drive`, `tone` |
| `DelayPedal` | Feedback delay line. Knobs: `time`, `feedback` |
| `ReverbPedal` | Freeverb (stereo, summed to mono). Knobs: `roomSize`, `damping` |
| `ModulationPedal` | Chorus (stereo, summed to mono). Knobs: `rate`, `depth` |
| `FuzzPedal` | High-gain `tanh` saturation (drive → square-up) → RBJ low-pass tone. Knobs: `fuzz`, `tone` |
| `TremoloPedal` | Unipolar sine LFO amplitude modulation. Knobs: `rate`, `depth` |
| `PhaserPedal` | Cascaded all-pass stages swept by a sine LFO. Knobs: `rate`, `feedback` |
| `CompressorPedal` | Feed-forward dynamic range compressor. Knobs: `threshold`, `ratio` |
Every pedal also inherits the common `mix`, `bypass`, and `level` controls from `Pedal`.
Write a custom pedal by subclassing `Pedal`, overriding `effect(_:)` to return a mono processed signal, and overriding `effectKnobs` to publish its `@UIParam` knobs. The base class handles wet/dry mixing, bypass, and output gain.
### `PedalBoard`
A `PedalBoard` is an ordered collection of pedals. Pedals are appended in signal-flow order with `board.add(pedal)`. A board must be finalised with `shoeGaze.finalizeBoard(board)` before audio flows through it — finalisation wires the signal chain and adds all pedals to the engine.
### `ShoeGaze`
`ShoeGaze` owns the `SynthesisEngine` and manages one or more `PedalBoard` instances. The engine lifecycle is caller-owned: `ShoeGaze` itself has no `start()` / `stop()` methods. `ShoeGazeView` provides Start/Stop transport buttons that call `engine.start()` / `engine.stop()`, or the app can drive the engine directly.
```swift
let shoeGaze = ShoeGaze(engine: engine)
let board = try shoeGaze.addBoard()
try board.add(OverdrivePedal())
try board.add(DelayPedal())
try shoeGaze.finalizeBoard(board)
```
### Input sources
Every `PedalBoard` has an `InputSource` that determines what feeds the first pedal in the chain:
| Source | Description |
|---|---|
| `.testLoop` (default) | Built-in synthesized test signal — no audio hardware input needed |
| `.liveInput(channel:)` | Routes a hardware input channel (zero-based; bus `numOutputChannels + channel`) from the microphone / audio interface |
The source is set on the `ShoeGaze` manager at init; every board it creates uses it:
```swift
let shoeGaze = ShoeGaze(engine: engine, inputSource: .liveInput(channel: 0))
let board = try shoeGaze.addBoard()
```
`liveInput` requires `numInputChannels > 0` in the `SynthesisEngine` init and the appropriate OS permission (microphone entitlement on macOS, `NSMicrophoneUsageDescription` in Info.plist for iOS).
### Recording
`ShoeGaze` can record the raw **input** and the overall **output** to timestamped WAV
files (via core `DiskOut.Audio`):
- `ShoeGaze.recordingFolder: URL?` — destination folder (set from the UI's folder picker).
- `ShoeGaze.startRecording() throws` — writes `output-<yyyyMMdd-HHmmss>.wav` (stereo hardware
output) and `input-<…>.wav` (the raw input: the hardware input channel for `.liveInput`,
or the first board's head bus for `.testLoop`). Throws `ShoeGazeError.recordingFolderNotSet`
if no folder is set; creates the folder if missing.
- `ShoeGaze.stopRecording()` — removes the taps and flushes/closes the files.
- `ShoeGaze.isRecording: Bool`.
The record taps are inserted `.after(engine.mainGroup)` so they capture each block's fully
processed bus values. `ShoeGazeView` provides a **Choose Folder…** button and a **Record/Stop**
button (disabled until a folder is chosen). For the cleanest tail of the file, stop the engine
before `stopRecording()` (engine node removal is asynchronous, so the last block or two may be
dropped otherwise).
### Board selection & crossfade
By default every board's output sums to the hardware output. To make only one board
audible at a time — switching between them without clicks — use:
- `ShoeGaze.selectBoard(_ board:, crossfadeSeconds:)` — solo `board`, crossfading the others out.
- `ShoeGaze.selectAllBoards(crossfadeSeconds:)` — restore the summed (all-audible) state.
- `ShoeGaze.activeBoardIndex: Int?` — the soloed board index, or `nil` when all are audible.
Each board's output master carries a lagged board-select gain (separate from the master
volume knob); `crossfadeSeconds` sets the lag time, so a switch is a click-free crossfade
of that duration (`0` = instant). `ShoeGazeView` exposes an "Active" board picker plus a
crossfade-seconds field driving these calls.
---
## Parallel routing (split / merge)
Two routing primitives let a signal fan out to two parallel paths and recombine:
- **`Splitter`** — one input bus → two branch buses, each gated by a click-free, lagged enable (`@UIParam branchAEnabled` / `branchBEnabled`). The `mode: SplitMode` convenience selects `.a` (branch A only), `.b` (branch B only), or `.both` (parallel). A/B switching is click-free.
- **`Merger`** — two branch buses → one output bus, each scaled by `@UIParam levelA` / `levelB`, summed.
Both are `SynthesizerBase` routing nodes (not `Pedal`s — multi-bus, no wet/dry). They power two layers:
### Intra-board: a parallel section inside one board
`PedalBoard.split()` inserts a splitter at the current chain tail and returns a `ParallelSection` with two `BranchChain`s; populate each branch, then `PedalBoard.merge(_:)` sums them back into the chain. Series pedals before and after compose normally.
```swift
let board = try shoeGaze.addBoard()
try board.add(OverdrivePedal()) // series pre
let section = try board.split() // → splitter
try section.branchA.add(DelayPedal()) // branch A
try section.branchB.add(FuzzPedal()) // branch B
try board.merge(section) // → merger
try board.add(ReverbPedal()) // series post
try shoeGaze.finalizeBoard(board)
section.splitter.mode = .both // run both branches
```
Branches use independent buses; the merge node is inserted after both branches so they evaluate first. Node-tree order: `pre → splitter → branch pedals → merger → post`.
### Inter-board: an A/B chain router
`ShoeGaze.makeChainRouter()` returns a `ChainRouter` that feeds one shared input through a splitter to **two whole boards** (`boardA` / `boardB`), then a merger + master to the hardware output. `router.mode` toggles which chain is audible (or both).
```swift
let router = try shoeGaze.makeChainRouter()
try router.boardA.add(OverdrivePedal())
try router.boardA.add(DelayPedal())
try router.boardB.add(FuzzPedal())
try router.boardB.add(ReverbPedal())
try router.finalize()
router.mode = .a // chain A live; toggle to .b / .both
```
The router owns its source, splitter, merger, and master (it does not use the per-board source/master of `addBoard`/`finalizeBoard`). `ChainRouter.teardown()` removes all nodes before releasing buses; `ShoeGaze.teardown()` tears down routers too.
---
## SwiftUI — `LyrebirdShoeGazeUI`
`LyrebirdShoeGazeUI` provides ready-made SwiftUI views:
| View | Description |
|---|---|
| `ShoeGazeView(shoeGaze:)` | Top-level view: transport controls + all boards |
| `PedalBoardView(board:)` | Horizontal scroll of `PedalView` tiles for one board |
| `PedalView(pedal:)` | Single pedal tile: bypass toggle + one knob per entry in `pedal.knobs` |
| `SplitterView(splitter:)` | 3-way A / B / Both mode selector + per-branch enable LEDs |
| `MergerView(merger:)` | Branch A / B level knobs |
| `ParallelSectionView(section:)` | Splitter + the two branch pedal rows for an intra-board section |
| `ChainRouterView(router:)` | Splitter + master knob, boards A/B, and the merger for an A/B chain router |
| `BoardEditorView(shoeGaze:boardIndex:versionStore:)` | Auto-laid-out board editor: wrap-to-fit pedal grid + save/load version toolbar |
| `FlowLayout` | A `Layout` that wraps subviews left-to-right to fit the available width (used by the editor) |
`PedalView` renders the descriptors a pedal publishes via its `knobs: [PedalKnob]` list (effect knobs, then the common `mix` and `level`). A custom pedal gets knobs by overriding `effectKnobs` — no view code is required.
---
## Board versions & auto-layout editor
`BoardEditorView(shoeGaze:boardIndex:versionStore:)` visualizes one board: its pedals are arranged by `FlowLayout`, a SwiftUI `Layout` that flows pedals left-to-right and wraps to the next row to fit the window width (a real pedalboard look). A toolbar saves and recalls **versions** of the board.
Backend:
- `PedalBoard.captureState() -> BoardState` snapshots a board (label + each pedal's type + knob/bypass values).
- `ShoeGaze.rebuildBoard(_:from:) throws -> PedalBoard` tears the board down and recreates it from a `BoardState` — recreating pedals via `PedalRegistry` and restoring knob values — **at the same index** in `boards` (unknown pedal types are skipped). Call with the engine stopped (same async-removal caveat as `teardown`).
- `BoardVersionStore` (`@Observable`) holds named `BoardVersion`s (`id`, `name`, `savedAt`, `state`) in memory and persists them as JSON:
- `capture(board, name:)` snapshots the current board.
- `writeAllToDisk(in:)` / `loadAllFromDisk(in:)` round-trip versions to a directory (`BoardVersionStore.defaultDirectory()` = `<Application Support>/LyrebirdShoeGaze/ShoeGazeVersions/`).
```swift
let store = BoardVersionStore()
store.capture(board, name: "Crunch rhythm") // snapshot current knobs
try store.writeAllToDisk(in: BoardVersionStore.defaultDirectory())
// later — recall, rebuilding the board from the saved version:
_ = try shoeGaze.rebuildBoard(board, from: store.versions[0].state)
```
In the UI, "Save Version" snapshots the live board, the Versions menu loads one (rebuilding in place), and Save/Load-to-disk persist the set. Because `ShoeGaze` and `BoardVersionStore` are `@Observable`, the editor re-renders automatically after a capture or rebuild.
---
## Demo apps
The package ships two in-repo demo apps in the workspace — a macOS app and an iOS app.
Both live under `ShoeGaze/Demo/` and share the same workspace:
```sh
open ShoeGaze/ShoeGaze.xcworkspace
```
The workspace contains three entries: the `ShoeGaze` SwiftPM package (library targets),
`Demo/ShoeGazeDemo.xcodeproj` (macOS), and `Demo/ShoeGazeiOSDemo.xcodeproj` (iOS). Xcode
resolves the two local package references (`..` for `LyrebirdShoeGaze`/`LyrebirdShoeGazeUI`,
`../..` for `Lyrebird`/`LyrebirdUI`) automatically when you first open the workspace.
### `ShoeGazeDemo` (macOS)
Showcases every feature via a mode picker (Boards / Editor / Parallel / Router), an input
dropdown, transport, and the board selector + crossfade. Build & Run produces `ShoeGazeDemo.app`
with a full menu bar — **Quit ⌘Q**, **Audio ▸ Mute ⌘M** (checkmark while muted):
```sh
open ShoeGaze/ShoeGaze.xcworkspace # select the "ShoeGazeDemo" scheme → Run
```
### `ShoeGazeiOSDemo` (iPhone + iPad)
A minimal iOS app wrapping `ShoeGazeView` in a `NavigationStack` + `ScrollView` so the
pedalboard scrolls on compact screens. Shows a default board (Overdrive → Delay → Reverb →
Modulation) fed by the built-in `.testLoop` source — no microphone permission required.
To run:
1. Open `ShoeGaze/ShoeGaze.xcworkspace` in Xcode.
2. Select the **ShoeGazeiOSDemo** scheme.
3. Pick an iPhone or iPad simulator (or a physical device with a provisioning profile).
4. Click **Run**.
The app uses `AVAudioSession` to read the hardware sample rate at launch, so pitch and timing
are accurate on all devices. To switch to live microphone input: set
`numInputChannels: 1` and `.playAndRecord` in `ShoeGazeiOSDemoAppModel.swift`, then pass
`.liveInput(channel: 0)` to the `ShoeGaze` init.
Note: the CLI `lyrebird new --template shoegaze` / `--template shoegaze-ios` (below) is still
the way to scaffold your OWN app project. The demo apps are in-repo only.
---
## `lyrebird new --template shoegaze` Workflow (macOS Xcode app)
```sh
lyrebird new MyRig --template shoegaze \
--lyrebird-path /path/to/LyrebirdII \
--shoegaze-path /path/to/LyrebirdII/ShoeGaze
```
Generates a full `.xcodeproj` macOS application (macOS 15+):
```
MyRig/
├── MyRig.xcodeproj/
│ ├── project.pbxproj
│ └── xcshareddata/xcschemes/MyRig.xcscheme
├── MyRig.xcworkspace/
│ └── contents.xcworkspacedata (references MyRig.xcodeproj)
└── MyRig/
├── Info.plist (NSMicrophoneUsageDescription pre-wired)
├── MyRigApp.swift (@main SwiftUI App — ShoeGazeView root + Mute menu)
└── MyRigAppModel.swift (@Observable model — engine + ShoeGaze)
```
Open `MyRig.xcworkspace` in Xcode and run. The generated app:
- Wires `CoreAudioDriver` at 48 000 Hz with 256 audio buses.
- Builds a default board (Overdrive → Delay → Reverb → Modulation) with the `.testLoop` input source.
- Exposes an **Audio ▸ Mute ⌘M** command (stops/starts the engine).
- Ships `NSMicrophoneUsageDescription` in `Info.plist` so switching to `.liveInput` doesn't require an extra plist edit.
- `ShoeGazeView` already provides Choose Folder / Record / Stop recording controls.
Key differences between the macOS and iOS shoegaze templates:
| | `shoegaze` (macOS Xcode) | `shoegaze-ios` (iOS Xcode) |
|---|---|---|
| Project type | `.xcodeproj` app bundle | `.xcodeproj` app bundle |
| Driver | `CoreAudioDriver` | `iOSAudioDriver` |
| Session | — | `AVAudioSession(.playback)` |
| Entry point | SwiftUI `@main App` | SwiftUI `@main App` |
| Window sizing | `.frame(minWidth:minHeight:)` | device-fill, no min size |
| Menu | Audio ▸ Mute ⌘M | — |
### `--shoegaze-path`
ShoeGaze is not yet published at a stable remote URL. Passing `--shoegaze-path <abs path to ShoeGaze/>` wires it as an `XCLocalSwiftPackageReference` in the generated `.xcodeproj`. If you omit the flag, the pbxproj uses a placeholder URL (`https://github.com/realizedsound/LyrebirdShoeGaze`) — edit `project.pbxproj` or re-generate once ShoeGaze is published.
The placeholder URL is stored in `ProjectScaffolder.shoegazePackageURL`.
### Live audio input on macOS
The generated template uses `.testLoop` and `numInputChannels: 0`. To switch to microphone or audio interface input:
1. Change `numInputChannels: 0` to the desired channel count in `MyRigAppModel.swift`.
2. Change `ShoeGaze(engine: eng)` to `ShoeGaze(engine: eng, inputSource: .liveInput(channel: 0))`.
3. `NSMicrophoneUsageDescription` is already in `Info.plist` — update the string to describe your use case.
4. If running under App Sandbox, add `com.apple.security.device.audio-input` to the `.entitlements` file. The `shoegaze` template is unsandboxed by default (Hardened Runtime without sandbox), so no entitlement file is needed in the common development workflow.
---
## `lyrebird new --template shoegaze-ios` Workflow (iOS)
```sh
lyrebird new MyRig --template shoegaze-ios \
--lyrebird-path /path/to/LyrebirdII \
--shoegaze-path /path/to/LyrebirdII/ShoeGaze
```
Generates a full `.xcodeproj` iOS application (iPhone + iPad, iOS 18+):
```
MyRig/
├── MyRig.xcodeproj/
│ ├── project.pbxproj
│ └── xcshareddata/xcschemes/MyRig.xcscheme
├── MyRig.xcworkspace/
│ └── contents.xcworkspacedata (references MyRig.xcodeproj)
└── MyRig/
├── Info.plist
├── MyRigApp.swift (@main SwiftUI App — ShoeGazeView root)
└── MyRigAppModel.swift (@Observable model — engine + ShoeGaze)
```
Open `MyRig.xcworkspace` in Xcode, select an iPhone/iPad simulator or device, and run. The generated app:
- Activates `AVAudioSession(.playback)` and queries the hardware sample rate at init so pitch and timing are accurate on all devices.
- Builds a default board (Overdrive → Delay → Reverb → Modulation) with the `.testLoop` input source.
- Wraps `ShoeGazeView` in a `NavigationStack` + `ScrollView` for compact-screen compatibility.
Key differences from the macOS `shoegaze` template:
| | `shoegaze` (macOS Xcode) | `shoegaze-ios` (iOS Xcode) |
|---|---|---|
| Project type | `.xcodeproj` app bundle | `.xcodeproj` app bundle |
| Driver | `CoreAudioDriver` | `iOSAudioDriver` |
| Session | — | `AVAudioSession(.playback)` |
| Entry point | SwiftUI `@main App` | SwiftUI `@main App` |
| Window sizing | `.frame(minWidth:minHeight:)` | device-fill, no min size |
| Menu | Audio ▸ Mute ⌘M | — |
### Live audio input on iOS
The generated template uses `.testLoop` and `numInputChannels: 0`. To switch to microphone input:
1. Change `numInputChannels: 0` to `numInputChannels: 1` in `MyRigAppModel.swift`.
2. Change `.playback` to `.playAndRecord` (mode: `.default`, options: `[.defaultToSpeaker]`) in the `AVAudioSession` setup.
3. Add `NSMicrophoneUsageDescription` to `Info.plist` (required for App Store submission and the system permission prompt).
4. Change `ShoeGaze(engine: eng)` to `ShoeGaze(engine: eng, inputSource: .liveInput(channel: 0))`.
---
## Extending the starter app
- Add more pedals in `applicationDidFinishLaunching` with additional `board.add(...)` calls.
- Create a second board with `shoeGaze.addBoard()` — `ShoeGazeView` shows all boards.
- Write a custom pedal: subclass `Pedal`, override `effect(_:)` (return a mono signal) and `effectKnobs`. The base class handles wet/dry, bypass, and level; `PedalView` picks up the knobs automatically.
- Switch to live audio: construct `ShoeGaze(engine:, inputSource: .liveInput(channel: 0))` and set `numInputChannels` ≥ 1 in the engine init (plus the microphone entitlement / `NSMicrophoneUsageDescription`).
+14 -2
View File
@@ -85,12 +85,16 @@ lyrebird new 1stPiece # error: not a valid Swift module name
**Templates** — `--template <name>`:
- SPM-only (open `Package.swift` in Xcode): `basic` (default), `demo`, `ui-demo`, `nrt`, `score`
- Xcode-project (ships `.xcodeproj` + `.xcworkspace`): `macos-ui-xcode`, `ios-ui`, `auv3`
- Xcode-project (ships `.xcodeproj` + `.xcworkspace`, builds to `.app` or `.appex`): `shoegaze`, `shoegaze-ios`, `macos-ui-xcode`, `ios-ui`, `auv3`
```sh
lyrebird new MyApp --template macos-ui-xcode # macOS .app
lyrebird new MyApp --template ios-ui # iOS .app
lyrebird new MyPlugin --template auv3 # AUv3 host + .appex
lyrebird new MyRig --template shoegaze \
--shoegaze-path /path/to/ShoeGaze # macOS guitar pedalboard (.xcodeproj, .app)
lyrebird new MyRig --template shoegaze-ios \
--shoegaze-path /path/to/ShoeGaze # iOS guitar pedalboard (.xcodeproj, .app)
```
**Local Lyrebird checkout** — `--lyrebird-path <abs-path>` makes the generated project depend on a local Lyrebird checkout (via `.package(name: "Lyrebird", path: ...)` in `Package.swift`, `XCLocalSwiftPackageReference` in `<name>.xcodeproj`). Use while the published repo URL isn't yet accessible:
@@ -100,7 +104,15 @@ lyrebird new MyApp --template macos-ui-xcode \
--lyrebird-path /Users/me/Documents/LyrebirdII
```
See `docs/tooling/project-system.md` for the layout each template emits.
**Local ShoeGaze checkout** — `--shoegaze-path <abs-path>` (shoegaze / shoegaze-ios templates) wires the `LyrebirdShoeGaze` package as a local SPM dependency. Omitting this flag emits a placeholder remote URL in the generated project; edit it or re-run with `--shoegaze-path` once ShoeGaze is published. The placeholder URL is `ProjectScaffolder.shoegazePackageURL`.
```sh
lyrebird new MyRig --template shoegaze-ios \
--lyrebird-path /Users/me/Documents/LyrebirdII \
--shoegaze-path /Users/me/Documents/LyrebirdII/ShoeGaze
```
See `docs/tooling/project-system.md` for the layout each template emits. See `docs/stdlib/shoegaze.md` for the ShoeGaze package concepts and workflow.
If the directory already exists, the command fails cleanly and leaves the filesystem unchanged.
+2
View File
@@ -48,9 +48,11 @@ Xcode-project templates (ship a real `.xcodeproj` for deliverables SwiftPM can't
| Template | Command | Description |
|---|---|---|
| `shoegaze` | `lyrebird new MyRig --template shoegaze --shoegaze-path <path>` | macOS guitar-pedalboard `.app` (Xcode, SwiftUI `@main`). Generates a full `.xcodeproj` with a `ShoeGazeView` root view, an `@Observable` app model wiring `CoreAudioDriver` + `ShoeGaze`, and an **Audio ▸ Mute ⌘M** menu command. `NSMicrophoneUsageDescription` pre-wired for `.liveInput`. Default board: Overdrive→Delay→Reverb→Modulation fed by the built-in test loop. Requires `--shoegaze-path` until `LyrebirdShoeGaze` is published |
| `macos-ui-xcode` | `lyrebird new MyApp --template macos-ui-xcode` | macOS `.app` (AppKit + SwiftUI), `@UIParam` synth, hardened runtime |
| `ios-ui` | `lyrebird new MyApp --template ios-ui` | iOS `.app` (SwiftUI + `iOSAudioDriver`), `AVAudioSession` activation, iPhone + iPad device family |
| `auv3` | `lyrebird new MyPlugin --template auv3` | AUv3 host `.app` + `aumu` `.appex` subclassing `LyrebirdAudioUnit`. Entitlements for both. Subtype + manufacturer pre-filled (manufacturer = `LYRB` placeholder — rewrite for distribution) |
| `shoegaze-ios` | `lyrebird new MyRig --template shoegaze-ios --shoegaze-path <path>` | iOS guitar-pedalboard `.app` (SwiftUI + `iOSAudioDriver`). Generates a full `.xcodeproj` with a `ShoeGazeView` root view and an `@Observable` app model wiring `AVAudioSession` + `ShoeGaze`. Default board: Overdrive→Delay→Reverb→Modulation fed by the built-in test loop. Adds `LyrebirdShoeGaze` + `LyrebirdShoeGazeUI` to the project's SPM deps. Requires `--shoegaze-path` until `LyrebirdShoeGaze` is published |
Each Xcode-project template lays out:
+11
View File
@@ -108,6 +108,17 @@ All six Tier 3 templates compile in projects depending on Lyrebird as a Swift
Package and are reported as `OK (external)` by the validator. None require
LyrebirdUI.
### Tier 4 — sample-project templates (ShoeGaze)
| Template | Generates | Use when |
|---|---|---|
| **ShoeGaze Pedal** | `final class <Name>: Pedal` with an `@UIParam` knob, a stubbed `effect(_:)` returning the processed mono signal, and an `effectKnobs` override publishing its knobs | Adding a new guitar pedal to a project using the ShoeGaze sample package. The base `Pedal` handles wet/dry `mix`, click-free `bypass`, and `level`; `PedalView` renders the published knobs. |
The ShoeGaze Pedal template requires the **LyrebirdShoeGaze** package (it imports
`LyrebirdShoeGaze` and `LyrebirdUI`), not just core Lyrebird. Use it inside a
project scaffolded with `lyrebird new --template shoegaze`, or any target that
depends on the ShoeGaze package. See [`../stdlib/shoegaze.md`](../stdlib/shoegaze.md).
Each template prompts for a name in Xcode's dialog. The name becomes both the file
name and the top-level identifier inside the file.