v2.1.1 release: delay-click fix + internal consolidation

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-10-07 21:20:49 -07:00
parent 844dc4d9cd
commit f8878324fd
212 changed files with 1386 additions and 2549 deletions
+7 -1
View File
@@ -91,7 +91,13 @@ when Lyrebird's MINOR rolls over.
| `MulAddSpec.identity` | static — for generators with no `mul`/`add` knobs |
| `func extractScalar(_:)` | init-time scalar detection |
| `func fillRampedResult(into:from:to:mulAdd:graph:count:)` | ControlGenerator ramp helper |
| `func lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` | block-constant capture from a generator input |
### Input resolution helpers (`GeneratorCore/InputResolutionHelpers.swift`)
| Symbol | Signature |
|---|---|
| `func firstGeneratorSampleOrFloat(_:isGenerator:graph:count:)` | block-constant capture — *first* sample of a generator input (ramp start); oscillator/LF/noise `Control` paths |
| `func lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` | block-constant capture — *last* sample of a generator input (ramp endpoint); dynamics + delay-time paths |
### Scratch buffers (`Buffers/RTScratchBuffer.swift`)
+84 -6
View File
@@ -166,7 +166,7 @@ output(bus: 0, source: dry2ch * 0.7 + wet2ch * 0.3) // element-wise stereo mix
> to every output channel; matched-channel-count `mul`/`add` applies per-channel; mismatched
> multi-row inputs trap via `precondition` at the apply site.
**`ControlGenerator` pre-allocation** — the default `ControlGenerator._computeSamples` allocates on every call and must not be used in production. Override it and write the interpolated ramp into the inherited `_result`. `ControlGenerator` conformers also must call `_setupSubBlockBuffer()` from `init` to allocate `_subBlockBuffer`, and must provide their own `floatValue` returning the block target (the `AudioGenerator` default impl does not apply).
**`ControlGenerator` pre-allocation** — the default `ControlGenerator._computeSamples` allocates on every call and must not be used in production. Override it and write the interpolated ramp into the inherited `_result`. Sub-blocking `ControlGenerator` conformers also must call `_setupSubBlockBuffer()` from `init` to allocate `_subBlockBuffer` (block-rate conformers of `BlockRateControlGenerator` never sub-block and omit it — see §15), and must provide their own `floatValue` returning the block target (the `AudioGenerator` default impl does not apply).
```swift
final class MyLFO: GeneratorBase, ControlGenerator {
@@ -400,7 +400,7 @@ class FMSynth: SynthesizerBase {
## 5. Fan-out Caching — Implement the Gateway
The `Generator` protocol extension provides `calculatedSamples` as a segment-serial caching gateway around your `_computeSamples`. You must **implement `_computeSamples`**, not `calculatedSamples`. Never override `calculatedSamples`.
The `Generator` protocol extension provides `calculatedSamples` as a segment-serial caching gateway around your `_computeSamples`. You must **implement `_computeSamples`**, not `calculatedSamples`. Never override `calculatedSamples`. (A control generator that must advance once per audio block instead conforms to `BlockRateControlGenerator`, which supplies the block-rate gateway as a protocol default — it still does not override `calculatedSamples`. See §15.)
```swift
// CORRECT — implement _computeSamples
@@ -1122,6 +1122,42 @@ fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue
The helper updates `previousOutputValue` to `target` and returns void. `@inline(__always)`, allocates nothing, traps if `count > result[0].count`. Use whenever the standard `Math.Control` shape applies — scalar op + scalar mul/add fold + ramp.
### `fillHeldResult`
The *held* counterpart of `fillScalarRampedResult`: for block-rate `ControlGenerator` paths whose output is one constant for the whole block (no ramp) — one-pole/leaky smoothers (`Lag`, `Decay`, `LeakDC`, `Slew`, `Formlet`), block-constant analysis outputs (`ZeroCrossing`, `Slope`, `RunningMin`/`Max`), trigger/counter latches (`Trig`, `Schmidt`, `PulseCount`, `Stepper`, …). It fills `result[0]` with the constant, applies `mulAdd` if non-identity, and sets `previousOutputValue` to the post-mulAdd last sample.
```swift
// WRONG — inline fill + applyIfNeeded + tail (20-site duplication)
var fillValue: Double = y
_result[0].withUnsafeMutableBufferPointer { buf in
guard let base = buf.baseAddress else { return }
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
previousOutputValue = _result[0][count - 1]
// RIGHT
fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
```
No-op when `count == 0` (leaves `previousOutputValue` unchanged) — so it also subsumes the `guard count > 0` the per-sample variants carried. Do NOT use it for a block whose output varies per sample (a real signal path, a ramp, or per-channel content); that is not a held constant.
### `MulAddSpec.applyScalar`
The scalar mul/add fold that precedes `fillScalarRampedResult` in the `Math.Control` family has its own one-liner. Fold `mul`/`add` into the block-constant `target` with `applyScalar`, which short-circuits on identity:
```swift
// WRONG — inline identity guard (36-site duplication)
if !_mulAdd.isIdentity {
target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph)
}
// RIGHT
target = _mulAdd.applyScalar(target, graph: graph)
```
`@inline(__always)`; returns `target` unchanged when the spec is identity. This is the scalar counterpart of `applyIfNeeded` (which applies mul/add to a whole buffer) — use it only on the `Math.Control` scalar-fold path, never as a substitute for `applyIfNeeded` on the output buffer.
### `xorshift64Next`
All noise generators share one xorshift64 PRNG. Use the free function instead of inlining the three bit-twist lines:
@@ -1148,6 +1184,30 @@ self.rngState = state
`xorshift64Next` is `@inline(__always)` and takes a direct `inout UInt64` — zero overhead.
### `firstGeneratorSampleOrFloat`
Oscillator and LF/noise `Control` paths read a generator-or-scalar parameter once at the *start* of `_computeSamples` — the value at the block boundary — then advance their own per-sample state from it:
- If the input is a generator → read the first sample of its `calculatedSamples` block (`0` if the block is empty).
- If the input is a scalar / `ParameterNode` / closure → read `floatValue(graph:)`.
This was repeated verbatim in 25 oscillator + noise sites before being extracted. Use the helper instead of inlining:
```swift
// WRONG — inline branching
let freq: Double
if _freqIsGenerator {
freq = _freqInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0
} else {
freq = _freqInput.floatValue(graph: graph)
}
// RIGHT
let freq: Double = firstGeneratorSampleOrFloat(_freqInput, isGenerator: _freqIsGenerator, graph: graph, count: count)
```
`isGenerator` must be classified at `init` — never call `is` on the RT thread. The helper is `@inline(__always)`. Its sibling `lastGeneratorSampleOrFloat` reads the block's *final* sample instead (ramp endpoint); both live in `InputResolutionHelpers.swift`.
### `lastGeneratorSampleOrFloat`
Many block-rate generators (dynamics, delay-time inputs, `ControlGenerator.Control` paths) need the most recent value of a `ValidGeneratorInput` at the *end* of the current block:
@@ -1171,7 +1231,7 @@ if _xIsGenerator {
}
// RIGHT
let v = lastGeneratorSampleOrFloat(input, isGenerator: _xIsGenerator, graph: graph, count: count)
let v: Double = lastGeneratorSampleOrFloat(input, isGenerator: _xIsGenerator, graph: graph, count: count)
```
`isGenerator` must be classified at `init` (`self._xIsGenerator = input is any Generator`) — never call `is` on the RT thread. The helper is `@inline(__always)`. Use it whenever a generator-or-scalar input needs to be sampled once per (sub-)block at block-rate granularity.
@@ -1219,9 +1279,12 @@ These wrap the common pattern *"vectorise the full-block case, fall back to a sc
| Helper | Location | Use when |
|--------|----------|----------|
| `_checkCount(_:)` | `GeneratorBase.swift` | Every `_computeSamples` — first line, traps on oversize block |
| `_calculatedSamplesBlockRate(graph:count:)` | `Generator.swift` | Body of any `calculatedSamples` override that bypasses the `ControlGenerator` sub-block path (§15) — IIR filters, bus writers, buffer-position advancers, trigger detectors, random drawers |
| `BlockRateControlGenerator` (marker protocol) | `GeneratorCore/BlockRateControlGenerator.swift` | A `ControlGenerator` conforms to it to advance once per audio block (bypass sub-blocking) — IIR filters, bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers, analysers. Supplies the block-rate `calculatedSamples` default; conformer skips `_setupSubBlockBuffer()`. See §15. |
| `_calculatedSamplesBlockRate(graph:count:)` | `Generator.swift` | The block-rate gateway the `BlockRateControlGenerator` default calls. Use directly only when the bypass is needed but the marker cannot apply |
| `OscillatorBase` (base class) | `Generators/Oscillators/OscillatorBase.swift` | Phase-accumulator oscillators (LF / band-limited saw / square / triangle / dutycycle / Impulse). Inherit instead of declaring `_freqInput` / `_freqIsGenerator` / `_phase` / `_mulAdd` inline. Table-lookup oscillators (`OscSin`, `OscTable`) excluded — they store `_phase` in table-index units to avoid a per-sample multiply. |
| `NoiseBase` (base class) | `Generators/Noise/NoiseBase.swift` | xorshift64 noise generators. Inherit instead of declaring `rngState` / `_mulAdd` inline. Distribution-parameterised subclasses add their own params, forward `super.init(initialRngState:mul:add:)`. Crackle (no PRNG) and LF noise variants excluded. |
| `UnaryMathBase` (base class) | `Generators/Math/UnaryMathBase.swift` | Single-input math operators (Abs, Ceil, Floor, Round, Sign, Sqrt, Log, Exp, Sin, Cos, Tan, Tanh, Reciprocal, DbAmp). Each operator's `_Base` is `public class _Base: UnaryMathBase {}`; inherit instead of declaring `inputSource` / `_mulAdd` inline. Multi-input math (Max, Min, Ring1–4, ExpExp, ExpLin, …) keeps its own `_Base`. |
| `SpectralFeatureControlBase` (base class) | `Generators/Spectral/SpectralFeatureControlBase.swift` | Control-rate spectral feature analysers (Centroid, Spread, Flatness, Entropy, Flux, Rolloff). Inherit instead of re-declaring the analysis/buffer/mulAdd/ramp shell + sub-block bypass; override `computeFeature(graph:count:)` with the per-feature math. |
| `runRBJBiquadBlock(...)` | `Generators/Filters/RBJBiquadHelpers.swift` | `(freq, q)` RBJ biquad filters (LP / HP / AP / Notch). Pass coefficient formula as closure; helper owns the shared input-pull / generator-vs-scalar branch / `processBlock` / `applyIfNeeded` tail. |
| `runTwoPoleResonatorScalarBlock(input:into:y1:y2:b0:na1:na2:count:)` / `runTwoPoleResonatorInterpolatedBlock(input:into:y1:y2:start:end:count:)` | `Generators/Filters/FilterHelpers.swift` | Two-pole resonator inner loop `y[n] = b0·x[n] − na1·y[n−1] − na2·y[n−2]`. Scalar variant for block-constant coefficients; interpolated variant for per-sample coefficient sweeps from `start` to `end`. State (`y1` / `y2`) passed as `inout`; denormal flush at the end of the helper. Used by `RingingFilter` + `ResonatingFilter` — pass the coefficient-computation function from the call site. |
| `sampleOrFallback(_:scalar:at:)` | `Generators/Filters/FilterHelpers.swift` | Per-sample coefficient lookup with zero-fallback past block end (`i < $0.count ? $0[i] : 0`). Replaces the verbose `xxxSamples.map { i < $0.count ? $0[i] : 0 } ?? scalarX` pattern. Used by `SecondOrderSection` (5 coefficient slots) + `FirstOrderSection` (3 slots). `Lag` / `Decay` family uses a different end-clamp + `lagCoeff` wrapping convention — helper does not apply there. |
@@ -1229,7 +1292,7 @@ These wrap the common pattern *"vectorise the full-block case, fall back to a sc
| `leakyIntegratorStep(state:x:b1:)` | `Generators/Filters/FilterHelpers.swift` | Leaky integrator step `y = x + b1·state` (SC `Decay` / `Decay2` convention — input not attenuated by `1 − b1`). Mutates `state` `inout`; returns `y`. Used by `Decay.Audio`, `Decay2.Audio` (cascade two for attack/decay difference). |
| `attackReleaseSmoother(state:target:attackCoeff:attackComp:releaseCoeff:releaseComp:direction:)` | `Generators/Dynamics/DynamicsHelpers.swift` | Asymmetric attack/release smoother step. `direction: .rising` selects attack-coeff when `target > state` (envelope-follower convention); `.falling` selects attack-coeff when `target < state` (compressor / expander gain-target convention). `comp = 1 − coeff` precomputed by caller for both pairs. Mutates `state` `inout`. Used by `AmplitudeFollower.Audio` (`.rising`) + `Compressor.Audio` / `Expander.Audio` (`.falling`). |
| `sampleOrZero(_ p: UnsafePointer<Double>, _ i: Int, _ n: Int) -> Double` | `GeneratorCore/HotLoopHelpers.swift` | `i < n ? p[i] : 0`. Per-sample input fetch with zero-pad past block end. Replaces the per-sample `(i < n) ? srcP[i] : 0` boilerplate inside `withUnsafeBufferPointer` hot loops. Across Filters (Lag / Lag2 / LagUpDown / Lag2UpDown / LeakDC / Decay / Decay2 / SecondOrderSection / FirstOrderSection / RBJBiquad / CombFilter / AllpassFilter) and Delays (DelayLine / DelayLineFeedback). `@_spi(LyrebirdExtensions) public` for out-of-tree generators. |
| `resolveGeneratorOrScalar(_:isGenerator:graph:count:) -> (samples: [Double]?, scalar: Double)` | `GeneratorCore/InputResolutionHelpers.swift` | Block-rate input resolution. Returns `(samples: [Double]?, scalar: Double)` — `samples != nil` means the input was a `Generator`, otherwise scalar via `floatValue(graph:)`. Replaces the 8-line `if _xxxIsGenerator { ... } else { ... }` boilerplate at the top of `_computeSamples` paths that pull multiple `ValidGeneratorInput` parameters. Used by `Flute` (6 params), `Clarinet` (4 params), `PanXYDistance` (4 params), `PanAzDistance` (4 params). Tuple destructure at the call site is the documented exception to the explicit-type-annotation rule. `@inline(__always) @_spi(LyrebirdExtensions) public`. |
| `resolveGeneratorOrScalar(_:isGenerator:graph:count:) -> (samples: [Double]?, scalar: Double)` | `GeneratorCore/InputResolutionHelpers.swift` | Block-rate input resolution. Returns `(samples: [Double]?, scalar: Double)` — `samples != nil` means the input was a `Generator`, otherwise scalar via `floatValue(graph:)`. Replaces the 8-line `if _xxxIsGenerator { ... } else { ... }` boilerplate at the top of `_computeSamples` paths that pull multiple `ValidGeneratorInput` parameters. Used across many multi-input generators (`Flute`, `Clarinet`, `KarplusStrong`/`GatedKarplusStrong`, `BowedString`, `PlayBuffer`, `SpatialDistance`, `MuTronIII`, `Hilbert`, the spatial panners, and more). Tuple destructure at the call site is the documented exception to the explicit-type-annotation rule. `@inline(__always) @_spi(LyrebirdExtensions) public`. |
| `applySpatialDistanceFiltering(...)` | `Generators/Panning/SpatialDistanceHelpers.swift` | Shared per-sample distance-shaping + delay-line + lowpass + 4-corner equal-power pan pipeline for `PanXYDistance` (Cartesian) and `PanAzDistance` (polar). Caller pre-computes `(panX, panY)` and the Chebyshev distance metric `posD` from its coordinate frame; the helper handles steps 3-11 of the pipeline (amplitude attenuation `1/posD`, cutoff-coefficient caching, Doppler read-rate, delay-line write/read/wrap/clamp, one-pole lowpass with denormal flush, then calls `writeEqualPowerSquarePanSample`). Mutates `delayLine` / `writePos` / `readPos` / `lpZ1` / `lastCutoff` / `lastLPCoeff` `inout`. `@inline(__always) internal`. |
| `plateReverbInputDiffusion(...)` | `Generators/Reverb/PlateReverbHelpers.swift` | 4-stage cascaded `plateAllpassStep` — the Dattorro input diffusion network on a single sample. Each stage uses its own circular buffer, position, size, and coefficient. All state mutated `inout`. Consumed by `PlateReverb.Audio._computeSamples`. `@inline(__always) internal`. |
| `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`. |
@@ -1240,7 +1303,10 @@ These wrap the common pattern *"vectorise the full-block case, fall back to a sc
| `_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 |
| `fillScalarRampedResult(into:previousOutputValue:target:count:)` | `MulAdd.swift` | `Math.Control` ramp pattern (28 generators) — caller pre-folds `mul`/`add` into the scalar `target`; helper writes ramp without re-applying mulAdd |
| `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` | `MulAdd.swift` | Block-rate read of a generator-or-scalar input — reads last sample of generator block, falls back to `floatValue` |
| `fillHeldResult(into:value:previousOutputValue:mulAdd:graph:count:)` | `MulAdd.swift` | Held-constant counterpart of `fillScalarRampedResult` — fill block with one value + `applyIfNeeded` + last-sample tail. Smoothers, block-constant analysis, trigger/counter latches (20 sites). No-op at `count == 0`. |
| `MulAddSpec.applyScalar(_:graph:)` | `MulAdd.swift` | Fold scalar `mul`/`add` into one block-constant `target` (short-circuits on identity). `Math.Control` scalar path, before `fillScalarRampedResult`. |
| `firstGeneratorSampleOrFloat(_:isGenerator:graph:count:)` | `InputResolutionHelpers.swift` | Block-rate read of a generator-or-scalar input — reads *first* sample of generator block (`0` if empty), falls back to `floatValue`. Oscillator/LF/noise `Control` paths |
| `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` | `InputResolutionHelpers.swift` | Block-rate read of a generator-or-scalar input — reads *last* sample of generator block, falls back to `floatValue`. Dynamics + delay-time paths |
| `xorshift64Next(_:)` | `WhiteNoise.swift` | Any generator that needs an xorshift64 PRNG sample |
| `lyrebirdSeedXorshift64(from:mixConstant:)` | `LyrebirdConstants.swift` | Init-time PRNG seeding for Audio/Control pairs that must decorrelate via a per-variant `mixConstant` |
| `lyrebirdSeedXorshift64(from:)` | `LyrebirdConstants.swift` | Init-time PRNG seeding for stand-alone single-state owners (e.g. `DemandTemporalTendency`, `DemandTemporalBrownian`) — convenience for the two-arg form with `mixConstant: 0` |
@@ -1331,6 +1397,18 @@ For each audio callback segment of `count` samples, `AudioGenerator.calculatedSa
The sub-block loop is in the `ControlGenerator` protocol extension (`Generator.swift`). Never replicate it in `_computeSamples`.
### Bypassing the sub-block loop — `BlockRateControlGenerator`
Some control generators must advance their state **exactly once per audio block**, not once per sub-block: IIR filters, bus writers, buffer-position advancers, gain smoothers, trigger/edge detectors, random drawers, and analysers — anything whose state is not a pure function of the current input sample. Conform such a generator to `BlockRateControlGenerator` (a `ControlGenerator` marker in `GeneratorCore/BlockRateControlGenerator.swift`):
```swift
public final class Control: _Base, BlockRateControlGenerator { … } // no calculatedSamples override, no _setupSubBlockBuffer()
```
Its `calculatedSamples` default routes to the block-rate gateway (`_calculatedSamplesBlockRate`), so `_computeSamples` runs once per audio block regardless of `controlBlockSize`. Because the conformer never enters the sub-block path it also skips `_setupSubBlockBuffer()` — it never touches `_subBlockBuffer`. (This replaced the old per-generator `calculatedSamples { _calculatedSamplesBlockRate(...) }` forwarder; `calculatedSamples` is a `ValidGeneratorInput` requirement, so the marker's refined-protocol default wins the witness slot over the `ControlGenerator` sub-block gateway.)
**Decision rule:** conform **iff** the generator would produce wrong output if `_computeSamples` ran several times per audio block. A memoryless control generator (output depends only on the current block's inputs) must **not** conform — it uses the sub-block path for finer modulation resolution.
### Configuring `controlBlockSize`
Pass `controlBlockSize:` to `SynthesisEngine.init`. If omitted, the engine uses `driver.suggestedControlBlockSize`, which defaults to `lyrebirdDefaultControlBlockSize` (64). The value must be a positive power of two that divides `blockSize` evenly.