diff --git a/CLAUDE.md b/CLAUDE.md index c7b1bac..39c1c1f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -135,9 +135,9 @@ One-liners. Detail and rationale lives in linked docs. - Open every `_computeSamples` with `_checkCount(count)` — the inherited helper that traps if `count > _result[0].count`. Replaces the long-form `precondition(...)` boilerplate. - `floatValue` is provided by the `AudioGenerator` protocol extension (returns `calculatedSamples(...).first?.first ?? 0`). Do not redeclare in `AudioGenerator` conformers unless you need different scalar semantics (e.g. `ConstantGeneratorInput`). `ControlGenerator` conformers must provide their own `floatValue` returning the block target. - Buffer factories `makeResultBuffer(channels:)` / `makeSampleBuffer(_:)` (in `ResultBuffer.swift`) replace `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)` literals when a generator owns a separately-allocated scratch buffer. -- Every `ControlGenerator.Control.init` calls `_setupSubBlockBuffer()` (or `_setupSubBlockBuffer(channels: N)`) after `super.init()`. Never call on the RT thread. +- Every sub-blocking `ControlGenerator.Control.init` calls `_setupSubBlockBuffer()` (or `_setupSubBlockBuffer(channels: N)`) after `super.init()`. Never call on the RT thread. **Exception:** `BlockRateControlGenerator` conformers never sub-block and omit the call (see the bypass bullet below). - `Control._computeSamples` uses `count` (not `graph.engine.blockSize`) for phase/state advancement — `_computeSamples` may run N times per audio block in sub-block mode. -- Generators with per-audio-block state (bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers) override `calculatedSamples` to bypass the sub-block loop. Canonical pattern: `Out.Control`. See `docs/protocols/writing-generators.md` §15 for the bypass list and decision rule. +- Control generators with per-audio-block state (bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers, analysers) must advance once per audio block, bypassing the sub-block loop. Conform to `BlockRateControlGenerator` (marker protocol in `GeneratorCore/BlockRateControlGenerator.swift`) — its `calculatedSamples` default routes to the block-rate gateway and the conformer skips `_setupSubBlockBuffer()`. This replaced the old per-generator `calculatedSamples { _calculatedSamplesBlockRate(...) }` forwarder. A true sub-blocking Control must NOT conform. See `docs/protocols/writing-generators.md` §15 for the decision rule. - Multi-row generators (any with `_result.count > 1`) override `var outputChannelCount: Int { get }` to return the fixed channel count set at `init`. `GeneratorBase` defaults to `1`. Missing override silently mono-izes the generator under `+ - * /` operators. Channel count must be derivable from a `let` at init — never runtime-mutable. Detail + cases: `docs/stdlib/multichannel.md`. - `mul:` / `add:` parameters are channel-aware: mono input broadcasts; equal-N applies element-wise; mismatched multi-row precondition-traps. Same policy as `BinaryOpGenerator`. Detail: `docs/stdlib/multichannel.md`. @@ -331,9 +331,12 @@ Tool: `Tools/AnnotateBindings/annotate_bindings.py` drives `sourcekit-lsp` to fi Module-level helpers exist to eliminate repeated boilerplate; inlining any of them in a new generator is a review violation: - `_checkCount(_:)` — `GeneratorBase` method; first line of every `_computeSamples` -- `_calculatedSamplesBlockRate(graph:count:)` — `Generator` extension; canonical body of any `calculatedSamples` override that bypasses the `ControlGenerator` sub-block path (IIR filters, bus writers, buffer-position advancers, trigger detectors, random drawers) +- `BlockRateControlGenerator` — `GeneratorCore/BlockRateControlGenerator.swift`; marker protocol a `ControlGenerator` conforms to when its state must advance once per audio block (IIR filters, bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers, analysers). Supplies the block-rate `calculatedSamples` gateway for free and lets the conformer skip `_setupSubBlockBuffer()`. The standard way to bypass sub-blocking — superseded the per-generator `_calculatedSamplesBlockRate` forwarder. A true sub-blocker must NOT conform. +- `_calculatedSamplesBlockRate(graph:count:)` — `Generator` extension; the block-rate gateway the `BlockRateControlGenerator` default calls. Call it directly only in the rare case a generator needs the bypass but cannot conform to the marker - `OscillatorBase` — `Generators/Oscillators/OscillatorBase.swift`; extend instead of declaring `_freqInput` / `_freqIsGenerator` / `_phase` / `_mulAdd` inline. Designated `init(freq:phase:mul:add:)` performs canonical phase normalisation. Used by LF / band-limited oscillators (LFSawtooth, LFSquare, LFTriangle, LFDutyCycle, OscSawtooth, OscSquare, OscTriangle, OscDutyCycle) and `Impulse` (post-super-init writes `_phase = 1.0 - initPhase` so `initPhase == 0` fires at sample 0). Table-lookup oscillators (`OscSin`, `OscTable`) intentionally excluded — they store `_phase` in table-index units to avoid a per-sample multiply in the inner loop. - `NoiseBase` — `Generators/Noise/NoiseBase.swift`; extend instead of declaring `rngState: UInt64` + `_mulAdd: MulAddSpec` inline. Designated `init(initialRngState:mul:add:)`. Used by 23 noise generators across 3 tiers (parameterless, extra-state, distribution-parameterised). LF noise variants and Crackle intentionally excluded. +- `UnaryMathBase` — `Generators/Math/UnaryMathBase.swift`; extend instead of declaring `inputSource` + `_mulAdd` inline. Designated `init(_:mul:add:)`. The shared `_Base` for the single-input math operators — each is `public class _Base: UnaryMathBase {}`, with `Audio`/`Control` supplying only the per-operator kernel. Used by 14 operators (Abs, Ceil, Floor, Round, Sign, Sqrt, Log, Exp, Sin, Cos, Tan, Tanh, Reciprocal, DbAmp). Multi-input math (Max, Min, Ring1–4, ExpExp, ExpLin, …) keeps its own `_Base`. +- `SpectralFeatureControlBase` — `Generators/Spectral/SpectralFeatureControlBase.swift`; shared base for the control-rate spectral feature analysers (SpectralCentroid, SpectralSpread, SpectralFlatness, SpectralEntropy, SpectralFlux, SpectralRolloff). Owns the analysis handle, spectral buffer, MulAddSpec, ramp state, sub-block bypass, and the drive-analysis → `computeFeature` → ramp body; each `Control` subclass adds only its own params/state and overrides `computeFeature(graph:count:) -> Double`. - `runRBJBiquadBlock(...)` — `Generators/Filters/RBJBiquadHelpers.swift`; module-internal helper holding the shared `_computeSamples` body for `(freq, q)` RBJ biquad filters (LP / HP / AP / Notch). Concrete filters pass the coefficient formula as a closure. - `runTwoPoleResonatorScalarBlock(input:into:y1:y2:b0:na1:na2:count:)` / `runTwoPoleResonatorInterpolatedBlock(input:into:y1:y2:start:end:count:)` — `Generators/Filters/FilterHelpers.swift`; shared per-sample loop body for two-pole resonator filters (`y[n] = b0·x[n] − na1·y[n−1] − na2·y[n−2]`). Consumed by `RingingFilter` + `ResonatingFilter` — concrete filter passes its coefficient-computation function and one-line helper calls. - `sampleOrFallback(_:scalar:at:)` — `Generators/Filters/FilterHelpers.swift`; per-sample coefficient lookup with zero-fallback past block end. Replaces the `xxxSamples.map { i < $0.count ? $0[i] : 0 } ?? scalarX` pattern. Used by `SecondOrderSection` (5 coefficient slots) + `FirstOrderSection` (3 slots). `Lag`/`Decay` family use a different end-clamp + `lagCoeff` wrapping convention; helper doesn't apply there. @@ -341,7 +344,7 @@ Module-level helpers exist to eliminate repeated boilerplate; inlining any of th - `leakyIntegratorStep(state:x:b1:)` — `Generators/Filters/FilterHelpers.swift`; `y = x + b1·state`, mutates state, returns y. SC `Decay`/`Decay2` convention (input not attenuated by `1 − b1`). 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 with direction selector (`.rising` for envelope followers; `.falling` for compressor/expander gain-target smoothing). Used by `AmplitudeFollower.Audio` (`.rising`) + `Compressor.Audio` / `Expander.Audio` (`.falling`). - `sampleOrZero(_ p: UnsafePointer, _ i: Int, _ n: Int) -> Double` — `GeneratorCore/HotLoopHelpers.swift`; `i < n ? p[i] : 0`. Replaces the per-sample `(i < n) ? srcP[i] : 0` boilerplate inside hot loops that read an input row via raw pointer. Module-internal helper used across Filters (Lag / Lag2 / LagUpDown / Lag2UpDown / LeakDC / Decay / Decay2 / SecondOrderSection / FirstOrderSection / RBJBiquad / CombFilter / AllpassFilter) and Delays (DelayLine / DelayLineFeedback). `@_spi(LyrebirdExtensions) public` so out-of-tree generators can adopt the same helper. -- `resolveGeneratorOrScalar(_:isGenerator:graph:count:) -> (samples: [Double]?, scalar: Double)` — `GeneratorCore/InputResolutionHelpers.swift`; block-rate input resolution. Replaces the 8-line `if _xxxIsGenerator { xxxSamples = ...; scalarXxx = 0 } else { xxxSamples = nil; scalarXxx = ... }` boilerplate at the top of any `_computeSamples` that pulls 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 CLAUDE.md-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. Replaces the 8-line `if _xxxIsGenerator { xxxSamples = ...; scalarXxx = 0 } else { xxxSamples = nil; scalarXxx = ... }` boilerplate at the top of any `_computeSamples` that pulls 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 CLAUDE.md-documented exception to the explicit-type-annotation rule. `@inline(__always) @_spi(LyrebirdExtensions) public`. - `applySpatialDistanceFiltering(...)` — `Generators/Panning/SpatialDistanceHelpers.swift`; module-internal shared per-sample pipeline for `PanXYDistance` (Cartesian) and `PanAzDistance` (polar). Both callers pre-compute `(panX, panY)` and the Chebyshev distance metric `posD` from their respective coordinate frames; the rest of the pipeline (amplitude attenuation, cutoff-coefficient caching, Doppler read-rate, delay-line write/read/wrap/clamp, one-pole lowpass, equal-power 4-corner pan) is identical and lives here. Mutates delay-line + one-pole state in place via `inout`. `@inline(__always) internal`. - `plateReverbInputDiffusion(...)` / `plateReverbTankHalf(...)` — `Generators/Reverb/PlateReverbHelpers.swift`; PlateReverb-specific per-sample sub-blocks. `plateReverbInputDiffusion` runs the 4-stage cascaded Schroeder allpass network on a single sample. `plateReverbTankHalf` runs one half of the figure-of-eight tank (modulated allpass → delay 1 → damping LP → decay scale → allpass 2 → delay 2 write). Consumed twice per sample by `PlateReverb._computeSamples` (left and right halves). All state mutated `inout`. `@inline(__always) internal`. - `gverbReadEarlyTaps(...)` / `gverbFDNDamperCascade(...)` — `Generators/Reverb/GVerbHelpers.swift`; GVerb-specific per-sample sub-blocks. `gverbReadEarlyTaps` reads four pre-FDN early-reflection taps with branchless wrap + per-tap gains and returns a 4-tuple. `gverbFDNDamperCascade` applies the FDN one-pole LP damper cascade `y = x*(1-damp) + prev*damp` to four raw FDN reads, mutates `fdnDampState[0..3]` with denormal flush, returns 4-tuple. Both `@inline(__always) internal`. @@ -349,7 +352,9 @@ Module-level helpers exist to eliminate repeated boilerplate; inlining any of th - `_mulAdd.applyIfNeeded(to:graph:count:)` - `fillRampedResult(into:from:to:mulAdd:graph:count:)` - `fillScalarRampedResult(into:previousOutputValue:target:count:)` — `MulAdd.swift`; canonical body of every `Math.Control` `_computeSamples` ramp (28 generators). Distinct from `fillRampedResult` because the caller has pre-folded `mul`/`add` into the scalar `target` — the helper writes the ramp without re-applying `MulAddSpec.apply`. -- `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` +- `fillHeldResult(into:value:previousOutputValue:mulAdd:graph:count:)` — `MulAdd.swift`; held-constant counterpart of `fillScalarRampedResult` — fills a block with one value, applies mul/add, sets `previousOutputValue` to the last sample. For block-rate `Control` paths whose output holds one value (one-pole smoothers `Lag`/`Decay`/`LeakDC`/`Slew`/`Formlet`, block-constant analysis `ZeroCrossing`/`Slope`/`RunningMin`/`Max`, trigger/counter latches `Trig`/`Schmidt`/`PulseCount`/`Stepper`; 20 sites). No-op at `count == 0`. NOT for per-sample-varying output. +- `MulAddSpec.applyScalar(_:graph:)` — `MulAdd.swift`; folds scalar `mul`/`add` into one block-constant `target` (returns it unchanged on identity). The scalar counterpart of `applyIfNeeded`; used by the 36 scalar-fold paths (Math.Control plus Routing/Waveshaping crossfades and shapers) before `fillScalarRampedResult`. +- `firstGeneratorSampleOrFloat(_:isGenerator:graph:count:)` / `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` — `GeneratorCore/InputResolutionHelpers.swift`; block-rate read of a generator-or-scalar input. `first…` reads the block's first sample (`0` if empty) — oscillator/LF/noise `Control` paths; `last…` reads the final sample (ramp endpoint) — dynamics + delay-time paths. Both fall back to `floatValue` for non-generators - `xorshift64Next(_:)` - `lyrebirdSeedXorshift64(from:mixConstant:)` / `lyrebirdSeedXorshift64(from:)` — `Math/LyrebirdConstants.swift`; init-time xorshift64 seed helper. Two-arg form decorrelates Audio/Control pairs via `mixConstant`; one-arg form is the convenience for stand-alone single-state owners (e.g. `DemandTemporalTendency` / `DemandTemporalBrownian`) - `catmullRomCubic(_:_:_:_:t:)` — `Math/CubicInterpolation.swift`; the single shared 4-point Catmull-Rom cubic kernel. Pass `(pM1, p0, p1, p2, t:)` — the sample before the segment, the two bracketing it, the one after, and `t ∈ [0, 1]`. Use instead of inlining the `t²`/`t³` expanded form. `@inline(__always) @_spi(LyrebirdExtensions) public`. Consumers: oscillator table reads (`OscSin` / `oscillatorTableReadCubic`), `PlayBuffer`, `chaoticInterpolate`, and the fractional-delay lines (`DelayLine` / `DelayLineFeedback` / `CombFilter` / `AllpassFilter`). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a872bc0..50737b5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -50,7 +50,7 @@ If a unit is useful at both rates, implement both via the **enum namespace patte - **First line of every `_computeSamples` is `_checkCount(count)`.** It traps if `count` exceeds the pre-allocated buffer. No grow path exists. - **Pre-allocate everything in `init`.** Bus memory, scratch buffers, vDSP setup objects. `init` runs off the RT thread; `_computeSamples` must only read/write existing storage. Use `makeResultBuffer(channels:)` / `makeSampleBuffer(_:)` instead of `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)` literals. - **Use `count`, never `engine.blockSize`,** for phase/state advancement — a `Control._computeSamples` may run several times per audio block in sub-block mode. -- **Generators with per-audio-block state** (bus writers, position advancers, gain smoothers, trigger detectors, random drawers) override `calculatedSamples` to bypass the sub-block loop via `_calculatedSamplesBlockRate(graph:count:)`. See §15 for the bypass list. +- **Control generators with per-audio-block state** (bus writers, position advancers, gain smoothers, trigger detectors, random drawers, analysers) conform the `Control` to `BlockRateControlGenerator` to bypass the sub-block loop (no `calculatedSamples` override, no `_setupSubBlockBuffer()`). See writing-generators.md §15. - **Multi-row generators** (`_result.count > 1`) call `super.init(channels: N)` and override `outputChannelCount`. Missing the override silently mono-izes the generator under `+ - * /`. Channel count must be a `let` fixed at init. - **Extend the right base** where one exists: `OscillatorBase`, `NoiseBase`. Don't re-declare `_phase` / `_mulAdd` / `rngState` inline. - **Denormal hygiene** — flush denormals to zero in feedback paths (filters, delays, reverbs). diff --git a/RELEASES.md b/RELEASES.md index b9b9a08..a73e688 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -7,6 +7,37 @@ functionality in a backward-compatible way. --- +## 2.1.1 — Delay-click fix + internal consolidation + +A patch release: one audible bug fix in the delay/comb/allpass family, plus a +large internal code-quality pass. No public API is removed or changed — the few +new types are internal-facing scaffolding — so this is drop-in over 2.1.0. + +**Fix — allpass fractional-delay click under modulation.** The allpass +interpolation mode (`.allpass`) of `DelayLine`, `CombFilter`, `AllpassFilter`, +and `DelayLineFeedback` mishandled its recursive filter state when a modulated +delay crossed an exact integer-sample boundary: `AllpassFilter` and +`DelayLineFeedback` produced an audible click (a sample-to-sample step several +times the surrounding signal), and the four generators disagreed on the +behavior. All four now record the integer-delayed sample as the interpolator's +previous output, which is click-free and consistent. Only `.allpass` +interpolation under a *modulated* delay was affected; `.none` / `.linear` / +`.cubic` and static delays were already correct. Guarded by a per-generator +regression suite. + +**Internal consolidation (no behavioral change).** Roughly 160 duplicated +call-site patterns and several near-identical generator shells were folded into +shared helpers and base classes — block-boundary input reads, the per-sample +phase wrap, the scalar mul/add fold, the held-constant control fill, the +single-input math operators (`UnaryMathBase`), the chaotic oscillators' +render body, the spectral FFT-size guards, the spectral feature analysers +(`SpectralFeatureControlBase`), and the ~96 block-rate control generators that +bypass sub-blocking (now a `BlockRateControlGenerator` marker protocol, which +also drops an unused ~4 KB per-instance buffer allocation). Output is +bit-identical across the generator library; the full test suite is unchanged. + +--- + ## 2.1.0 — Swift 6.4 modernization An internal-hardening release adopting modern Swift on the 6.4 toolchain. No diff --git a/Sources/Lyrebird/Capture/SpectrumCapture.swift b/Sources/Lyrebird/Capture/SpectrumCapture.swift index b16960c..b13f31e 100644 --- a/Sources/Lyrebird/Capture/SpectrumCapture.swift +++ b/Sources/Lyrebird/Capture/SpectrumCapture.swift @@ -65,10 +65,7 @@ public final class SpectrumCapture: SpectralProcessor, @unchecked Sendable { /// - fftSize: FFT frame size. Must match the `SpectralChain.Audio` this capture is registered on. /// Must be a power of two ≥ 4. Default: 2048. public init(fftSize: Int = 2048) { - precondition( - fftSize >= 4 && (fftSize & (fftSize - 1)) == 0, - "SpectrumCapture: fftSize must be a power of two >= 4, got \(fftSize)" - ) + lyrebirdRequireFFTSize(fftSize, typeName: "SpectrumCapture") self.fftSize = fftSize let bc: Int = fftSize / 2 + 1 self.binCount = bc diff --git a/Sources/Lyrebird/GeneratorCore/BlockRateControlGenerator.swift b/Sources/Lyrebird/GeneratorCore/BlockRateControlGenerator.swift new file mode 100644 index 0000000..ac5c2d4 --- /dev/null +++ b/Sources/Lyrebird/GeneratorCore/BlockRateControlGenerator.swift @@ -0,0 +1,46 @@ +// BlockRateControlGenerator.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// MARK: - BlockRateControlGenerator + +/// A `ControlGenerator` whose state must advance exactly once per audio block — +/// IIR filters, bus writers, buffer-position advancers, gain smoothers, trigger +/// detectors, random drawers, analysers, etc. These generators do **not** sub-block. +/// +/// Conforming to this marker supplies the block-rate `calculatedSamples` gateway for +/// free, replacing the per-generator forwarder: +/// +/// ```swift +/// // Before: every such Control hand-wrote this bypass … +/// public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { +/// _calculatedSamplesBlockRate(graph: graph, count: count) +/// } +/// // … and called _setupSubBlockBuffer() in init for a buffer it never used. +/// +/// // After: just conform. +/// public final class Control: _Base, BlockRateControlGenerator { … } +/// ``` +/// +/// Because `calculatedSamples` is a `ValidGeneratorInput` requirement, the witness for a +/// conformer resolves to the most-refined protocol extension that provides it — this one +/// — so it overrides the `ControlGenerator` sub-block gateway. A conformer therefore runs +/// `_computeSamples` once per audio block and never touches `_subBlockBuffer`, so it also +/// skips the `_setupSubBlockBuffer()` allocation. +/// +/// Conform **only** generators that genuinely bypass sub-blocking (previously via the +/// explicit `_calculatedSamplesBlockRate` forwarder). A true sub-blocking `ControlGenerator` +/// must NOT conform — it needs the `ControlGenerator` sub-block path and its +/// `_subBlockBuffer`. +public protocol BlockRateControlGenerator: ControlGenerator {} + +extension BlockRateControlGenerator { + public func calculatedSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } +} diff --git a/Sources/Lyrebird/GeneratorCore/Generator.swift b/Sources/Lyrebird/GeneratorCore/Generator.swift index 0f9fdcb..15ea0c7 100644 --- a/Sources/Lyrebird/GeneratorCore/Generator.swift +++ b/Sources/Lyrebird/GeneratorCore/Generator.swift @@ -135,8 +135,9 @@ public protocol ControlGenerator: Generator { /// /// Used by `calculatedSamples` when `controlBlockSize < count` to accumulate /// results from multiple `_computeSamples` calls without heap allocation. - /// Initialise to `[[]]` (via `GeneratorBase` default). Call `_setupSubBlockBuffer()` - /// in the designated `Control.init` to resize for sub-block assembly. Never call on the RT thread. + /// Initialise to `[[]]` (via `GeneratorBase` default). A sub-blocking `Control.init` + /// calls `_setupSubBlockBuffer()` to resize for sub-block assembly (never on the RT + /// thread); `BlockRateControlGenerator` conformers never sub-block and skip it. var _subBlockBuffer: [[Double]] { get set } } @@ -205,18 +206,16 @@ extension Generator { /// Bypass-sub-block fan-out cache helper. /// - /// Used by generators that override `calculatedSamples` to force `_computeSamples` to - /// run exactly once per audio block, bypassing the `ControlGenerator` extension's - /// sub-block path. Required for any generator whose state must advance once per audio - /// block (IIR filters, bus writers, buffer-position advancers, gain smoothers, trigger - /// detectors, random drawers). See `docs/protocols/writing-generators.md` §15. + /// The block-rate gateway: runs `_computeSamples` exactly once per audio block, + /// bypassing the `ControlGenerator` extension's sub-block path. Required for any + /// generator whose state must advance once per audio block (IIR filters, bus writers, + /// buffer-position advancers, gain smoothers, trigger detectors, random drawers, + /// analysers). See `docs/protocols/writing-generators.md` §15. /// - /// Drop-in replacement for the canonical bypass block: - /// ```swift - /// public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - /// _calculatedSamplesBlockRate(graph: graph, count: count) - /// } - /// ``` + /// The standard way to get this behaviour is to conform the control generator to + /// `BlockRateControlGenerator`, whose `calculatedSamples` default calls this method — + /// prefer that over hand-writing a `calculatedSamples` forwarder. Call this directly + /// only when the bypass is needed but the marker cannot apply. @inline(__always) public func _calculatedSamplesBlockRate( graph: SynthGraph, diff --git a/Sources/Lyrebird/GeneratorCore/GeneratorBase.swift b/Sources/Lyrebird/GeneratorCore/GeneratorBase.swift index b17ff06..f213b13 100644 --- a/Sources/Lyrebird/GeneratorCore/GeneratorBase.swift +++ b/Sources/Lyrebird/GeneratorCore/GeneratorBase.swift @@ -22,8 +22,10 @@ /// post-super reassignment. `outputChannelCount` must be overridden to return the /// fixed channel count. /// -/// `Audio` conformers inherit `_subBlockBuffer` as `[[]]` (no allocation); `Control` conformers -/// resize it to `lyrebirdDefaultResultBufferSize` via `_setupSubBlockBuffer()` in `init`. +/// `Audio` conformers inherit `_subBlockBuffer` as `[[]]` (no allocation); sub-blocking +/// `Control` conformers resize it to `lyrebirdDefaultResultBufferSize` via +/// `_setupSubBlockBuffer()` in `init`. `BlockRateControlGenerator` conformers never +/// sub-block and leave it unallocated. open class GeneratorBase { public var _segmentSerial: UInt64 = 0 public var _cachedResult: [[Double]] = [[]] diff --git a/Sources/Lyrebird/GeneratorCore/InputResolutionHelpers.swift b/Sources/Lyrebird/GeneratorCore/InputResolutionHelpers.swift index b797bc4..8150c6a 100644 --- a/Sources/Lyrebird/GeneratorCore/InputResolutionHelpers.swift +++ b/Sources/Lyrebird/GeneratorCore/InputResolutionHelpers.swift @@ -58,3 +58,63 @@ public func resolveGeneratorOrScalar( } return (nil, source.floatValue(graph: graph)) } + +// MARK: - Block-constant generator reads + +/// Reads the **first** sample of a generator's block output, or returns the scalar +/// `floatValue` when the input is not a Generator. RT-safe. +/// +/// Use for block-constant parameters read once at the top of a `Control._computeSamples`: +/// the first-sample read picks up the value at the block boundary while keeping the rest +/// of the per-block math at block-rate. The companion `lastGeneratorSampleOrFloat` reads +/// the block's final sample instead (ramp endpoint). +/// +/// - Parameters: +/// - input: Any `ValidGeneratorInput` — scalar, `ParameterNode`, or generator. +/// - isGenerator: Pre-computed at init (`input is any Generator`). Never use `is` on the RT thread. +/// - graph: The current synthesis graph. +/// - count: Number of samples in the current block. +/// - Returns: the first sample of `input.calculatedSamples(...)` (or `0` if the block is +/// empty) when `isGenerator` is true; `input.floatValue(graph:)` otherwise. +@inline(__always) +@_spi(LyrebirdExtensions) +public func firstGeneratorSampleOrFloat( + _ input: any ValidGeneratorInput, + isGenerator: Bool, + graph: SynthGraph, + count: Int +) -> Double { + guard isGenerator else { return input.floatValue(graph: graph) } + return input.calculatedSamples(graph: graph, count: count).first?.first ?? 0 +} + +/// Reads the **last** sample of a generator's block output, or returns the scalar +/// `floatValue` when the input is not a Generator. RT-safe. +/// +/// Use for block-constant parameters that must still capture `ParameterNode` ramps: +/// the last-sample read picks up the ramp endpoint while keeping coefficient math +/// at block-rate. The companion `firstGeneratorSampleOrFloat` reads the block's first +/// sample instead. +/// +/// - Parameters: +/// - input: Any `ValidGeneratorInput` — scalar, `ParameterNode`, or generator. +/// - isGenerator: Pre-computed at init (`input is any Generator`). Never use `is` on the RT thread. +/// - graph: The current synthesis graph. +/// - count: Number of samples in the current block. +/// - Returns: `buf[count - 1]` when `isGenerator` is true and the block is non-empty; +/// `input.floatValue(graph:)` otherwise. +@inline(__always) +@_spi(LyrebirdExtensions) +public func lastGeneratorSampleOrFloat( + _ input: any ValidGeneratorInput, + isGenerator: Bool, + graph: SynthGraph, + count: Int +) -> Double { + guard isGenerator else { return input.floatValue(graph: graph) } + guard let buf: [Double] = input.calculatedSamples(graph: graph, count: count).first, + count > 0 else { + return input.floatValue(graph: graph) + } + return buf[count - 1] +} diff --git a/Sources/Lyrebird/GeneratorCore/MulAdd.swift b/Sources/Lyrebird/GeneratorCore/MulAdd.swift index 37cf5d5..28c2159 100644 --- a/Sources/Lyrebird/GeneratorCore/MulAdd.swift +++ b/Sources/Lyrebird/GeneratorCore/MulAdd.swift @@ -6,38 +6,6 @@ import LyrebirdDSP -// MARK: - Block-constant generator read helper - -/// Reads the last sample of a generator's block output, or returns the scalar -/// `floatValue` when the input is not a Generator. RT-safe. -/// -/// Use for block-constant parameters that must still capture `ParameterNode` ramps: -/// the last-sample read picks up the ramp endpoint while keeping coefficient math -/// at block-rate. -/// -/// - Parameters: -/// - input: Any `ValidGeneratorInput` — scalar, `ParameterNode`, or generator. -/// - isGenerator: Pre-computed at init (`input is any Generator`). Never use `is` on the RT thread. -/// - graph: The current synthesis graph. -/// - count: Number of samples in the current block. -/// - Returns: `buf[count - 1]` when `isGenerator` is true and the block is non-empty; -/// `input.floatValue(graph:)` otherwise. -@_spi(LyrebirdExtensions) -@inline(__always) -public func lastGeneratorSampleOrFloat( - _ input: any ValidGeneratorInput, - isGenerator: Bool, - graph: SynthGraph, - count: Int -) -> Double { - guard isGenerator else { return input.floatValue(graph: graph) } - guard let buf: [Double] = input.calculatedSamples(graph: graph, count: count).first, - count > 0 else { - return input.floatValue(graph: graph) - } - return buf[count - 1] -} - // MARK: - Scalar extraction /// Returns the constant value for compile-time-known scalar inputs, nil for generators/strings. @@ -63,9 +31,9 @@ public func extractScalar(_ input: any ValidGeneratorInput) -> Double? { /// _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) /// ``` /// `applyIfNeeded` short-circuits internally on `isIdentity`, so the call site -/// never needs an `if !isIdentity` guard. `MathGenerators.Control` does not call -/// through this struct — it computes its scalar `target = input * mulFloat + addFloat` -/// before the ramp, documented in `docs/protocols/writing-generators.md` §13. +/// never needs an `if !isIdentity` guard. `MathGenerators.Control` applies mul/add to +/// its scalar `target` before the ramp (not to the output buffer after) via `applyScalar` +/// below — documented in `docs/protocols/writing-generators.md` §13. @_spi(LyrebirdExtensions) public struct MulAddSpec { public let mulInput: any ValidGeneratorInput @@ -115,6 +83,20 @@ public struct MulAddSpec { if !isIdentity { apply(to: &channels, graph: graph, count: count) } } + /// Applies the scalar `(target × mul) + add` to a single block-constant value, + /// short-circuiting to `target` on identity. Reads `mul`/`add` at block rate via + /// `floatValue`. + /// + /// For `Math.Control` paths that compute one scalar target per block and hand it to + /// `fillScalarRampedResult` — the documented exception to the buffer-based + /// `apply`/`applyIfNeeded`. Replaces the inline + /// `if !isIdentity { target = target * mulInput.floatValue + addInput.floatValue }`. + @inline(__always) + public func applyScalar(_ target: Double, graph: SynthGraph) -> Double { + guard !isIdentity else { return target } + return target * mulInput.floatValue(graph: graph) + addInput.floatValue(graph: graph) + } + /// Applies `(x × mul) + add` via vDSP to every channel in `channels`. /// /// **Channel-aware broadcast (matches `BinaryOpGenerator` policy).** When `mul` or @@ -247,8 +229,7 @@ public func fillRampedResult( /// Usage in a Math-style ControlGenerator._computeSamples: /// ```swift /// var target = someScalarOp(input.floatValue(graph: graph)) -/// if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) -/// + _mulAdd.addInput.floatValue(graph: graph) } +/// target = _mulAdd.applyScalar(target, graph: graph) /// fillScalarRampedResult( /// into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) /// return _result @@ -279,6 +260,40 @@ public func fillScalarRampedResult( } } +/// Fills `result[0]` with a single block-constant `value`, applies `mulAdd` if +/// non-identity, and sets `previousOutputValue` to the (post-mulAdd) last sample. +/// No-op when `count == 0` (leaving `previousOutputValue` unchanged). +/// +/// The held counterpart of `fillScalarRampedResult`: block-rate `ControlGenerator` +/// paths whose output holds one value for the whole block — one-pole/leaky +/// smoothers (`Lag`, `Decay`, `LeakDC`, `Slew`, `Formlet`), block-constant analysis +/// outputs (`ZeroCrossing`, `Slope`, `RunningMin`/`Max`), and trigger/counter latches +/// (`Trig`, `Schmidt`, `PulseCount`, `Stepper`, …). Replaces the repeated +/// `vDSP_vfillD` (or per-sample constant fill) + `applyIfNeeded` + last-sample tail. +@_spi(LyrebirdExtensions) +@inline(__always) +public func fillHeldResult( + into result: inout [[Double]], + value: Double, + previousOutputValue: inout Double, + mulAdd: MulAddSpec, + graph: SynthGraph, + count: Int +) { + guard count > 0 else { return } + precondition(!result.isEmpty, + "fillHeldResult: result has no rows") + precondition(count <= result[0].count, + "fillHeldResult: count exceeds result buffer") + var fillValue: Double = value + result[0].withUnsafeMutableBufferPointer { (buf: inout UnsafeMutableBufferPointer) in + guard let base: UnsafeMutablePointer = 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] +} + // MARK: - Per-channel vDSP dispatch /// Pure-scalar `(x * mulScalar) + addScalar` for one channel. No `Optional` diff --git a/Sources/Lyrebird/Generators/Analysis/BeatTrack.swift b/Sources/Lyrebird/Generators/Analysis/BeatTrack.swift index 827bc75..78c387e 100644 --- a/Sources/Lyrebird/Generators/Analysis/BeatTrack.swift +++ b/Sources/Lyrebird/Generators/Analysis/BeatTrack.swift @@ -42,7 +42,7 @@ public enum BeatTrack { /// once at init. Defaults to ``beatTrackPreferredBPM``. /// - windowSeconds: ODF history length for autocorrelation. Read once at /// init. Defaults to ``beatTrackMaxWindowSeconds``. - public final class Control: GeneratorBase, ControlGenerator { + public final class Control: GeneratorBase, BlockRateControlGenerator { /// Internal ODF source + the input refs each mode needs. Only one mode's /// state is live; the spectral-flux state (`_prevMag`, `_isFirstFrame`) @@ -197,19 +197,8 @@ public enum BeatTrack { featureRateHz: beatTrackFeatureRateHz ) super.init(channels: beatTrackOutputRowCount) - _setupSubBlockBuffer(channels: beatTrackOutputRowCount) } - // MARK: - Compute - - // Bypass the sub-block loop: the ODF advances once per audio block (the - // spectral buffer once per FFT hop) and the tracker state must too. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Analysis/Loudness.swift b/Sources/Lyrebird/Generators/Analysis/Loudness.swift index 2a95978..ae2e268 100644 --- a/Sources/Lyrebird/Generators/Analysis/Loudness.swift +++ b/Sources/Lyrebird/Generators/Analysis/Loudness.swift @@ -38,7 +38,7 @@ public enum Loudness { /// - calibrationDB: dBFS→SPL offset. Defaults to ``loudnessDefaultCalibrationDB``. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset (sones). Defaults to `0.0`. - public final class Control: GeneratorBase, ControlGenerator { + public final class Control: GeneratorBase, BlockRateControlGenerator { private let _analysis: SpectralChain.Audio? private let _spectral: SpectralBuffer @@ -127,17 +127,8 @@ public enum Loudness { ) self._mulAdd = MulAddSpec(mul: mul, add: add) super.init() - _setupSubBlockBuffer() } - // Bypass the sub-block loop: the spectral buffer advances once per FFT - // hop and the loudness state (temporal mask) advances once per block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Analysis/RunningMax.swift b/Sources/Lyrebird/Generators/Analysis/RunningMax.swift index 14ae322..186e908 100644 --- a/Sources/Lyrebird/Generators/Analysis/RunningMax.swift +++ b/Sources/Lyrebird/Generators/Analysis/RunningMax.swift @@ -143,7 +143,7 @@ public enum RunningMax { /// - trig: Reset trigger. ≤0 → >0 rising edges reset the running maximum. Defaults to `0.0`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 /// - Parameters: @@ -158,17 +158,8 @@ public enum RunningMax { add: any ValidGeneratorInput = 0.0 ) { super.init(input: input, trig: trig, mul: mul, add: add) - _setupSubBlockBuffer() } - /// Bypass sub-block loop: the running-maximum state machine must scan the full - /// audio-rate input block exactly once per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -203,16 +194,7 @@ public enum RunningMax { _prevTrig = prevTrig _initialized = initialized - var fillValue: Double = extreme - _result[0].withUnsafeMutableBufferPointer { buf in - guard let base: UnsafeMutablePointer = buf.baseAddress else { return } - vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count)) - } - - _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) - - guard count > 0 else { return _result } - previousOutputValue = _result[0][count - 1] + fillHeldResult(into: &_result, value: extreme, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Analysis/RunningMin.swift b/Sources/Lyrebird/Generators/Analysis/RunningMin.swift index b9876b9..0d13c30 100644 --- a/Sources/Lyrebird/Generators/Analysis/RunningMin.swift +++ b/Sources/Lyrebird/Generators/Analysis/RunningMin.swift @@ -143,7 +143,7 @@ public enum RunningMin { /// - trig: Reset trigger. ≤0 → >0 rising edges reset the running minimum. Defaults to `0.0`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 /// - Parameters: @@ -158,17 +158,8 @@ public enum RunningMin { add: any ValidGeneratorInput = 0.0 ) { super.init(input: input, trig: trig, mul: mul, add: add) - _setupSubBlockBuffer() } - /// Bypass sub-block loop: the running-minimum state machine must scan the full - /// audio-rate input block exactly once per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -203,16 +194,7 @@ public enum RunningMin { _prevTrig = prevTrig _initialized = initialized - var fillValue: Double = extreme - _result[0].withUnsafeMutableBufferPointer { buf in - guard let base: UnsafeMutablePointer = buf.baseAddress else { return } - vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count)) - } - - _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) - - guard count > 0 else { return _result } - previousOutputValue = _result[0][count - 1] + fillHeldResult(into: &_result, value: extreme, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Analysis/Slope.swift b/Sources/Lyrebird/Generators/Analysis/Slope.swift index 5422473..28ac927 100644 --- a/Sources/Lyrebird/Generators/Analysis/Slope.swift +++ b/Sources/Lyrebird/Generators/Analysis/Slope.swift @@ -132,7 +132,7 @@ public enum Slope { /// - input: Signal to differentiate. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 /// - Parameters: @@ -145,16 +145,8 @@ public enum Slope { add: any ValidGeneratorInput = 0.0 ) { super.init(input: input, mul: mul, add: add) - _setupSubBlockBuffer() } - /// Bypass sub-block loop: slope state must advance exactly once per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -178,16 +170,7 @@ public enum Slope { _prevSample = x } - var fillValue: Double = slope - _result[0].withUnsafeMutableBufferPointer { buf in - guard let base: UnsafeMutablePointer = buf.baseAddress else { return } - vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count)) - } - - _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) - - guard count > 0 else { return _result } - previousOutputValue = _result[0][count - 1] + fillHeldResult(into: &_result, value: slope, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Analysis/ZeroCrossing.swift b/Sources/Lyrebird/Generators/Analysis/ZeroCrossing.swift index 017cc85..74f0b7c 100644 --- a/Sources/Lyrebird/Generators/Analysis/ZeroCrossing.swift +++ b/Sources/Lyrebird/Generators/Analysis/ZeroCrossing.swift @@ -157,7 +157,7 @@ public enum ZeroCrossing { /// - input: Signal to analyse. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 /// - Parameters: @@ -170,17 +170,8 @@ public enum ZeroCrossing { add: any ValidGeneratorInput = 0.0 ) { super.init(input: input, mul: mul, add: add) - _setupSubBlockBuffer() } - /// Bypass sub-block loop: the zero-crossing state machine must scan the full - /// audio-rate input block exactly once per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -216,16 +207,7 @@ public enum ZeroCrossing { _freq = freq _initialized = initialized - var fillValue: Double = freq - _result[0].withUnsafeMutableBufferPointer { buf in - guard let base: UnsafeMutablePointer = buf.baseAddress else { return } - vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count)) - } - - _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) - - guard count > 0 else { return _result } - previousOutputValue = _result[0][count - 1] + fillHeldResult(into: &_result, value: freq, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/BufferIO/BufferRead.swift b/Sources/Lyrebird/Generators/BufferIO/BufferRead.swift index e16197f..c1d9f49 100644 --- a/Sources/Lyrebird/Generators/BufferIO/BufferRead.swift +++ b/Sources/Lyrebird/Generators/BufferIO/BufferRead.swift @@ -166,7 +166,7 @@ public enum BufferRead { /// - interpolation: Sample interpolation quality. Defaults to `.linear`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Offset added after multiplier. Defaults to `0.0`. - public final class Control: GeneratorBase, ControlGenerator { + public final class Control: GeneratorBase, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 @@ -203,7 +203,6 @@ public enum BufferRead { _mulAdd = MulAddSpec(mul: mul, add: add) _rampTargets = [Double](repeating: 0, count: buffer.channelCount) super.init(channels: buffer.channelCount) - _setupSubBlockBuffer(channels: buffer.channelCount) } /// Replace the buffer being read. Pass `nil` to silence the reader. @@ -226,14 +225,6 @@ public enum BufferRead { _slot.swap(buffer, engine: engine) } - // Bypass sub-block loop: position is block-rate — re-evaluating per sub-block has - // no benefit and would advance _rampTargets N times per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/BufferIO/PlayBuffer.swift b/Sources/Lyrebird/Generators/BufferIO/PlayBuffer.swift index 511a427..5388402 100644 --- a/Sources/Lyrebird/Generators/BufferIO/PlayBuffer.swift +++ b/Sources/Lyrebird/Generators/BufferIO/PlayBuffer.swift @@ -332,26 +332,10 @@ public enum PlayBuffer { // Evaluate rate input — generator path reads a full per-sample buffer; // scalar path computes one constant value and skips array allocation. - let rateSamples: [Double]? - let scalarRate: Double - if _rateIsGenerator { - rateSamples = _rateInput.calculatedSamples(graph: graph, count: count).first - scalarRate = 0 - } else { - rateSamples = nil - scalarRate = _rateInput.floatValue(graph: graph) - } + let (rateSamples, scalarRate) = resolveGeneratorOrScalar(_rateInput, isGenerator: _rateIsGenerator, graph: graph, count: count) // Evaluate trigger input — same two-path pattern. - let triggerSamples: [Double]? - let scalarTrigger: Double - if _triggerIsGenerator { - triggerSamples = _triggerInput.calculatedSamples(graph: graph, count: count).first - scalarTrigger = 0 - } else { - triggerSamples = nil - scalarTrigger = _triggerInput.floatValue(graph: graph) - } + let (triggerSamples, scalarTrigger) = resolveGeneratorOrScalar(_triggerInput, isGenerator: _triggerIsGenerator, graph: graph, count: count) guard let buffer: LyrebirdBuffer = _slot.load(engine: graph.engine), buffer.isValid else { for ch: Int in 0.. [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/BufferIO/RecordBuffer.swift b/Sources/Lyrebird/Generators/BufferIO/RecordBuffer.swift index e31c39a..70e9c1d 100644 --- a/Sources/Lyrebird/Generators/BufferIO/RecordBuffer.swift +++ b/Sources/Lyrebird/Generators/BufferIO/RecordBuffer.swift @@ -538,7 +538,7 @@ public enum RecordBuffer { /// `doneAction` and stops recording. Default `true`. /// - doneAction: Behaviour when the write head reaches the end of the /// buffer (`loop == false`). Default `.nothing`. - public final class Control: _Base, ControlGenerator, DoneActionWatchable, RootRegistering { + public final class Control: _Base, BlockRateControlGenerator, DoneActionWatchable, RootRegistering { public var previousOutputValue: Double = 0.0 @@ -566,20 +566,11 @@ public enum RecordBuffer { + "For multi-channel recording use RecordBuffer.Audio." ) super.init(input: input, buffer: buffer, loop: loop, doneAction: doneAction) - _setupSubBlockBuffer() _registerAutoFreeIfNeeded(doneAction) _registerAsRootIfBuilding() } - // Bypass sub-block loop: RecordBuffer.Control writes one buffer frame per audio block. - // Sub-blocking would write N frames per block, accelerating recording by N×. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/BusIO/In.swift b/Sources/Lyrebird/Generators/BusIO/In.swift index 3beb639..cc53d42 100644 --- a/Sources/Lyrebird/Generators/BusIO/In.swift +++ b/Sources/Lyrebird/Generators/BusIO/In.swift @@ -165,7 +165,7 @@ public enum In { /// consecutive buses with independent ramp state per channel). An ``AudioBus`` traps; use ``In/Audio``. /// - channels: Only available on the `Int`-index overload. Number of consecutive buses /// to read. Defaults to `1`. Fixed at init — no RT allocation. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { /// Per-channel ramp state. Updated by `_computeSamples` after each block. private var _previousOutputValues: [Double] @@ -187,7 +187,6 @@ public enum In { let ch: Int = _resolvedChannelCount(bus) _previousOutputValues = [Double](repeating: 0.0, count: ch) super.init(bus: bus.index, channels: ch) - _setupSubBlockBuffer(channels: ch) } /// Reads from a raw bus index with an explicit channel count. @@ -201,7 +200,6 @@ public enum In { ) { _previousOutputValues = [Double](repeating: 0.0, count: channels) super.init(bus: bus, channels: channels) - _setupSubBlockBuffer(channels: channels) } public func floatValue(graph: SynthGraph) -> Double { @@ -209,15 +207,6 @@ public enum In { return Double(graph.engine.controlBuses[bus]) } - // Bypass sub-block loop: control bus values are written once per audio block by Out.Control. - // Sub-blocking would reset _previousOutputValues after each partial ramp, compressing - // the interpolation into only the first controlBlockSize samples instead of the full block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } /// Produces a linearly-interpolated block for each channel, ramping from the previous /// block's end value to the current control bus value. diff --git a/Sources/Lyrebird/Generators/BusIO/Out.swift b/Sources/Lyrebird/Generators/BusIO/Out.swift index bc2ebc8..f1ab8d7 100644 --- a/Sources/Lyrebird/Generators/BusIO/Out.swift +++ b/Sources/Lyrebird/Generators/BusIO/Out.swift @@ -135,9 +135,9 @@ public enum Out { /// to `channelCount`). An ``AudioBus`` traps; use ``Out/Audio`` instead. /// - source: Signal to write. The last sample of each channel block is accumulated into /// the corresponding control bus. Multi-channel sources write to consecutive buses. - public final class Control: _Base, ControlGenerator, RootRegistering { + public final class Control: _Base, BlockRateControlGenerator, RootRegistering { - /// Satisfies ControlGenerator protocol requirement — unused, Control overrides calculatedSamples. + /// Satisfies ControlGenerator protocol requirement — unused; Control conforms to `BlockRateControlGenerator`. public var previousOutputValue: Double = 0.0 /// Number of channels to write. Governs `_result` row count. @@ -159,18 +159,9 @@ public enum Out { let ch: Int = _resolvedChannelCount(bus) self._channels = ch super.init(bus: bus.index, source: source, maxChannels: bus.channelCount, channels: ch) - _setupSubBlockBuffer(channels: ch) _registerAsRootIfBuilding() } - /// Bypasses the `ControlGenerator` sub-block loop so the bus write happens exactly - /// once per audio block regardless of `controlBlockSize`. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/BusIO/ReplaceOut.swift b/Sources/Lyrebird/Generators/BusIO/ReplaceOut.swift index a97592e..06066da 100644 --- a/Sources/Lyrebird/Generators/BusIO/ReplaceOut.swift +++ b/Sources/Lyrebird/Generators/BusIO/ReplaceOut.swift @@ -169,9 +169,9 @@ public enum ReplaceOut { /// ``ControlBus`` (clamped to `channelCount`). An ``AudioBus`` traps; use ``ReplaceOut/Audio``. /// - source: Signal to write. The last sample of each channel block is /// written to the corresponding control bus. - public final class Control: _Base, ControlGenerator, RootRegistering { + public final class Control: _Base, BlockRateControlGenerator, RootRegistering { - /// Satisfies ControlGenerator protocol requirement — unused, Control overrides calculatedSamples. + /// Satisfies ControlGenerator protocol requirement — unused; Control conforms to `BlockRateControlGenerator`. public var previousOutputValue: Double = 0.0 /// Number of channels to write. Governs `_result` row count. @@ -199,18 +199,9 @@ public enum ReplaceOut { let ch: Int = _resolvedChannelCount(bus) self._channels = ch super.init(bus: bus.index, source: source, maxChannels: bus.channelCount, channels: ch) - _setupSubBlockBuffer(channels: ch) _registerAsRootIfBuilding() } - /// Bypasses the `ControlGenerator` sub-block loop so the bus write happens - /// exactly once per audio block regardless of `controlBlockSize`. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Chaotic/ChaoticBase.swift b/Sources/Lyrebird/Generators/Chaotic/ChaoticBase.swift index 2bfb9c4..6aa5152 100644 --- a/Sources/Lyrebird/Generators/Chaotic/ChaoticBase.swift +++ b/Sources/Lyrebird/Generators/Chaotic/ChaoticBase.swift @@ -102,4 +102,61 @@ public class ChaoticBase: GeneratorBase { _h2 = iterate() } } + + // MARK: - Shared render bodies + + /// Ramp-target state for the `Control` render (the audio-block value the next + /// block ramps from). Lives on the base so `renderControlBlock` can own the + /// whole body; unused by `Audio`. + var _rampTarget: Double = 0.0 + + /// `ControlGenerator`'s ramp origin. Declared here so `renderControlBlock` can + /// update it; `Control` subclasses inherit it to satisfy the protocol, `Audio` + /// leaves it unused. + public var previousOutputValue: Double = 0.0 + + /// Snapshot the map's per-block parameters into the fields `iterate()` reads. + /// Overridden by maps that have parameters (Hénon's `a`/`b`, …); the default is + /// a no-op for parameterless maps (e.g. Gbman). + func readParams(graph: SynthGraph) {} + + /// Canonical `Audio._computeSamples` body: read params, prime the ring, then + /// bridge each sample between map iterations at `freq`. Shared by every concrete + /// chaotic `Audio`. + func renderAudioBlock(graph: SynthGraph, count: Int) -> [[Double]] { + guard count > 0 else { return _result } + + readParams(graph: graph) + primeIfNeeded() + let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) + + for i: Int in 0.. [[Double]] { + guard count > 0 else { return _result } + + readParams(graph: graph) + primeIfNeeded() + let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) + advancePhase(by: dphase * Double(count)) + let target: Double = chaoticInterpolate(_interpolation, phase: _phase, + hM1: _hM1, h0: _h0, h1: _h1, h2: _h2) + + let rampStart: Double = _rampTarget + _rampTarget = target + previousOutputValue = fillRampedResult( + into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count) + return _result + } } diff --git a/Sources/Lyrebird/Generators/Chaotic/CuspStepped.swift b/Sources/Lyrebird/Generators/Chaotic/CuspStepped.swift index 83d71f5..852318e 100644 --- a/Sources/Lyrebird/Generators/Chaotic/CuspStepped.swift +++ b/Sources/Lyrebird/Generators/Chaotic/CuspStepped.swift @@ -56,8 +56,7 @@ public enum CuspStepped { } /// Snapshot the per-block parameters into the fields `iterate()` reads. - @inline(__always) - func readParams(graph: SynthGraph) { + override func readParams(graph: SynthGraph) { _a = aInput.floatValue(graph: graph) _b = bInput.floatValue(graph: graph) } @@ -100,20 +99,7 @@ public enum CuspStepped { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) - guard count > 0 else { return _result } - - readParams(graph: graph) - primeIfNeeded() - let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) - - for i: Int in 0.. Double { previousOutputValue } @@ -156,30 +139,12 @@ public enum CuspStepped { ) { super.init(freq: freq, a: a, b: b, xi: xi, interpolation: interpolation, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: the map advances exactly one audio block per call. - public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) - guard count > 0 else { return _result } - - readParams(graph: graph) - primeIfNeeded() - let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) - advancePhase(by: dphase * Double(count)) - let target: Double = chaoticInterpolate(_interpolation, phase: _phase, - hM1: _hM1, h0: _h0, h1: _h1, h2: _h2) - - let rampStart: Double = _rampTarget - _rampTarget = target - previousOutputValue = fillRampedResult( - into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count) - return _result + return renderControlBlock(graph: graph, count: count) } } } diff --git a/Sources/Lyrebird/Generators/Chaotic/FBSineStepped.swift b/Sources/Lyrebird/Generators/Chaotic/FBSineStepped.swift index 1b45372..b96e56c 100644 --- a/Sources/Lyrebird/Generators/Chaotic/FBSineStepped.swift +++ b/Sources/Lyrebird/Generators/Chaotic/FBSineStepped.swift @@ -70,8 +70,7 @@ public enum FBSineStepped { } /// Snapshot the per-block parameters into the fields `iterate()` reads. - @inline(__always) - func readParams(graph: SynthGraph) { + override func readParams(graph: SynthGraph) { _im = imInput.floatValue(graph: graph) _fb = fbInput.floatValue(graph: graph) _a = aInput.floatValue(graph: graph) @@ -125,20 +124,7 @@ public enum FBSineStepped { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) - guard count > 0 else { return _result } - - readParams(graph: graph) - primeIfNeeded() - let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) - - for i: Int in 0.. Double { previousOutputValue } @@ -190,30 +173,12 @@ public enum FBSineStepped { ) { super.init(freq: freq, im: im, fb: fb, a: a, c: c, xi: xi, yi: yi, interpolation: interpolation, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: the map advances exactly one audio block per call. - public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) - guard count > 0 else { return _result } - - readParams(graph: graph) - primeIfNeeded() - let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) - advancePhase(by: dphase * Double(count)) - let target: Double = chaoticInterpolate(_interpolation, phase: _phase, - hM1: _hM1, h0: _h0, h1: _h1, h2: _h2) - - let rampStart: Double = _rampTarget - _rampTarget = target - previousOutputValue = fillRampedResult( - into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count) - return _result + return renderControlBlock(graph: graph, count: count) } } } diff --git a/Sources/Lyrebird/Generators/Chaotic/GbmanStepped.swift b/Sources/Lyrebird/Generators/Chaotic/GbmanStepped.swift index beeab09..635535d 100644 --- a/Sources/Lyrebird/Generators/Chaotic/GbmanStepped.swift +++ b/Sources/Lyrebird/Generators/Chaotic/GbmanStepped.swift @@ -83,19 +83,7 @@ public enum GbmanStepped { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) - guard count > 0 else { return _result } - - primeIfNeeded() - let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) - - for i: Int in 0.. Double { previousOutputValue } @@ -135,29 +120,12 @@ public enum GbmanStepped { ) { super.init(freq: freq, xi: xi, yi: yi, interpolation: interpolation, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: the map advances exactly one audio block per call. - public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) - guard count > 0 else { return _result } - - primeIfNeeded() - let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) - advancePhase(by: dphase * Double(count)) - let target: Double = chaoticInterpolate(_interpolation, phase: _phase, - hM1: _hM1, h0: _h0, h1: _h1, h2: _h2) - - let rampStart: Double = _rampTarget - _rampTarget = target - previousOutputValue = fillRampedResult( - into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count) - return _result + return renderControlBlock(graph: graph, count: count) } } } diff --git a/Sources/Lyrebird/Generators/Chaotic/HenonStepped.swift b/Sources/Lyrebird/Generators/Chaotic/HenonStepped.swift index ca23922..f6b16d8 100644 --- a/Sources/Lyrebird/Generators/Chaotic/HenonStepped.swift +++ b/Sources/Lyrebird/Generators/Chaotic/HenonStepped.swift @@ -58,8 +58,7 @@ public enum HenonStepped { } /// Snapshot the per-block parameters into the fields `iterate()` reads. - @inline(__always) - func readParams(graph: SynthGraph) { + override func readParams(graph: SynthGraph) { _a = aInput.floatValue(graph: graph) _b = bInput.floatValue(graph: graph) } @@ -105,20 +104,7 @@ public enum HenonStepped { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) - guard count > 0 else { return _result } - - readParams(graph: graph) - primeIfNeeded() - let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) - - for i: Int in 0.. Double { previousOutputValue } @@ -164,30 +147,12 @@ public enum HenonStepped { ) { super.init(freq: freq, a: a, b: b, x0: x0, x1: x1, interpolation: interpolation, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: the map advances exactly one audio block per call. - public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) - guard count > 0 else { return _result } - - readParams(graph: graph) - primeIfNeeded() - let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) - advancePhase(by: dphase * Double(count)) - let target: Double = chaoticInterpolate(_interpolation, phase: _phase, - hM1: _hM1, h0: _h0, h1: _h1, h2: _h2) - - let rampStart: Double = _rampTarget - _rampTarget = target - previousOutputValue = fillRampedResult( - into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count) - return _result + return renderControlBlock(graph: graph, count: count) } } } diff --git a/Sources/Lyrebird/Generators/Chaotic/LatoocarfianStepped.swift b/Sources/Lyrebird/Generators/Chaotic/LatoocarfianStepped.swift index 2cf35a4..1925654 100644 --- a/Sources/Lyrebird/Generators/Chaotic/LatoocarfianStepped.swift +++ b/Sources/Lyrebird/Generators/Chaotic/LatoocarfianStepped.swift @@ -71,8 +71,7 @@ public enum LatoocarfianStepped { } /// Snapshot the per-block parameters into the fields `iterate()` reads. - @inline(__always) - func readParams(graph: SynthGraph) { + override func readParams(graph: SynthGraph) { _a = aInput.floatValue(graph: graph) _b = bInput.floatValue(graph: graph) _c = cInput.floatValue(graph: graph) @@ -126,20 +125,7 @@ public enum LatoocarfianStepped { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) - guard count > 0 else { return _result } - - readParams(graph: graph) - primeIfNeeded() - let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) - - for i: Int in 0.. Double { previousOutputValue } @@ -191,30 +174,12 @@ public enum LatoocarfianStepped { ) { super.init(freq: freq, a: a, b: b, c: c, d: d, xi: xi, yi: yi, interpolation: interpolation, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: the map advances exactly one audio block per call. - public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) - guard count > 0 else { return _result } - - readParams(graph: graph) - primeIfNeeded() - let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) - advancePhase(by: dphase * Double(count)) - let target: Double = chaoticInterpolate(_interpolation, phase: _phase, - hM1: _hM1, h0: _h0, h1: _h1, h2: _h2) - - let rampStart: Double = _rampTarget - _rampTarget = target - previousOutputValue = fillRampedResult( - into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count) - return _result + return renderControlBlock(graph: graph, count: count) } } } diff --git a/Sources/Lyrebird/Generators/Chaotic/LinCongStepped.swift b/Sources/Lyrebird/Generators/Chaotic/LinCongStepped.swift index 6deffb4..85743ee 100644 --- a/Sources/Lyrebird/Generators/Chaotic/LinCongStepped.swift +++ b/Sources/Lyrebird/Generators/Chaotic/LinCongStepped.swift @@ -61,8 +61,7 @@ public enum LinCongStepped { } /// Snapshot the per-block parameters into the fields `iterate()` reads. - @inline(__always) - func readParams(graph: SynthGraph) { + override func readParams(graph: SynthGraph) { _a = aInput.floatValue(graph: graph) _c = cInput.floatValue(graph: graph) _m = mInput.floatValue(graph: graph) @@ -109,20 +108,7 @@ public enum LinCongStepped { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) - guard count > 0 else { return _result } - - readParams(graph: graph) - primeIfNeeded() - let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) - - for i: Int in 0.. Double { previousOutputValue } @@ -168,30 +151,12 @@ public enum LinCongStepped { ) { super.init(freq: freq, a: a, c: c, m: m, xi: xi, interpolation: interpolation, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: the map advances exactly one audio block per call. - public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) - guard count > 0 else { return _result } - - readParams(graph: graph) - primeIfNeeded() - let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) - advancePhase(by: dphase * Double(count)) - let target: Double = chaoticInterpolate(_interpolation, phase: _phase, - hM1: _hM1, h0: _h0, h1: _h1, h2: _h2) - - let rampStart: Double = _rampTarget - _rampTarget = target - previousOutputValue = fillRampedResult( - into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count) - return _result + return renderControlBlock(graph: graph, count: count) } } } diff --git a/Sources/Lyrebird/Generators/Chaotic/LorenzLinear.swift b/Sources/Lyrebird/Generators/Chaotic/LorenzLinear.swift index e4228eb..0ed127d 100644 --- a/Sources/Lyrebird/Generators/Chaotic/LorenzLinear.swift +++ b/Sources/Lyrebird/Generators/Chaotic/LorenzLinear.swift @@ -76,8 +76,7 @@ public enum LorenzLinear { } /// Snapshot the per-block parameters into the fields `iterate()` reads. - @inline(__always) - func readParams(graph: SynthGraph) { + override func readParams(graph: SynthGraph) { _s = sInput.floatValue(graph: graph) _r = rInput.floatValue(graph: graph) _b = bInput.floatValue(graph: graph) @@ -134,20 +133,7 @@ public enum LorenzLinear { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) - guard count > 0 else { return _result } - - readParams(graph: graph) - primeIfNeeded() - let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) - - for i: Int in 0.. Double { previousOutputValue } @@ -202,30 +185,12 @@ public enum LorenzLinear { ) { super.init(freq: freq, s: s, r: r, b: b, h: h, xi: xi, yi: yi, zi: zi, interpolation: interpolation, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: the map advances exactly one audio block per call. - public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) - guard count > 0 else { return _result } - - readParams(graph: graph) - primeIfNeeded() - let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) - advancePhase(by: dphase * Double(count)) - let target: Double = chaoticInterpolate(_interpolation, phase: _phase, - hM1: _hM1, h0: _h0, h1: _h1, h2: _h2) - - let rampStart: Double = _rampTarget - _rampTarget = target - previousOutputValue = fillRampedResult( - into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count) - return _result + return renderControlBlock(graph: graph, count: count) } } } diff --git a/Sources/Lyrebird/Generators/Chaotic/QuadStepped.swift b/Sources/Lyrebird/Generators/Chaotic/QuadStepped.swift index d6b425f..d80051a 100644 --- a/Sources/Lyrebird/Generators/Chaotic/QuadStepped.swift +++ b/Sources/Lyrebird/Generators/Chaotic/QuadStepped.swift @@ -59,8 +59,7 @@ public enum QuadStepped { } /// Snapshot the per-block parameters into the fields `iterate()` reads. - @inline(__always) - func readParams(graph: SynthGraph) { + override func readParams(graph: SynthGraph) { _a = aInput.floatValue(graph: graph) _b = bInput.floatValue(graph: graph) _c = cInput.floatValue(graph: graph) @@ -107,20 +106,7 @@ public enum QuadStepped { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) - guard count > 0 else { return _result } - - readParams(graph: graph) - primeIfNeeded() - let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) - - for i: Int in 0.. Double { previousOutputValue } @@ -166,30 +149,12 @@ public enum QuadStepped { ) { super.init(freq: freq, a: a, b: b, c: c, xi: xi, interpolation: interpolation, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: the map advances exactly one audio block per call. - public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) - guard count > 0 else { return _result } - - readParams(graph: graph) - primeIfNeeded() - let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) - advancePhase(by: dphase * Double(count)) - let target: Double = chaoticInterpolate(_interpolation, phase: _phase, - hM1: _hM1, h0: _h0, h1: _h1, h2: _h2) - - let rampStart: Double = _rampTarget - _rampTarget = target - previousOutputValue = fillRampedResult( - into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count) - return _result + return renderControlBlock(graph: graph, count: count) } } } diff --git a/Sources/Lyrebird/Generators/Chaotic/StandardStepped.swift b/Sources/Lyrebird/Generators/Chaotic/StandardStepped.swift index 31f26bf..8b9bfc9 100644 --- a/Sources/Lyrebird/Generators/Chaotic/StandardStepped.swift +++ b/Sources/Lyrebird/Generators/Chaotic/StandardStepped.swift @@ -56,8 +56,7 @@ public enum StandardStepped { } /// Snapshot the per-block parameter into the field `iterate()` reads. - @inline(__always) - func readParams(graph: SynthGraph) { + override func readParams(graph: SynthGraph) { _k = kInput.floatValue(graph: graph) } } @@ -99,20 +98,7 @@ public enum StandardStepped { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) - guard count > 0 else { return _result } - - readParams(graph: graph) - primeIfNeeded() - let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) - - for i: Int in 0.. Double { previousOutputValue } @@ -155,30 +138,12 @@ public enum StandardStepped { ) { super.init(freq: freq, k: k, xi: xi, yi: yi, interpolation: interpolation, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: the map advances exactly one audio block per call. - public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) - guard count > 0 else { return _result } - - readParams(graph: graph) - primeIfNeeded() - let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate) - advancePhase(by: dphase * Double(count)) - let target: Double = chaoticInterpolate(_interpolation, phase: _phase, - hM1: _hM1, h0: _h0, h1: _h1, h2: _h2) - - let rampStart: Double = _rampTarget - _rampTarget = target - previousOutputValue = fillRampedResult( - into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count) - return _result + return renderControlBlock(graph: graph, count: count) } } } diff --git a/Sources/Lyrebird/Generators/Delays/DelayLine.swift b/Sources/Lyrebird/Generators/Delays/DelayLine.swift index bca822f..583ac7f 100644 --- a/Sources/Lyrebird/Generators/Delays/DelayLine.swift +++ b/Sources/Lyrebird/Generators/Delays/DelayLine.swift @@ -180,7 +180,13 @@ public final class DelayLine: GeneratorBase, AudioGenerator { apPrev = out dstP[i] = out } else { - apPrev = 0 + // frac == 0: the output is exactly the integer-delayed sample, + // so the allpass interpolator's output here IS yn. Record that + // as its previous output. Zeroing apPrev clicks when a modulated + // delay crosses an integer boundary; freezing the old value + // clicks when the delay dwells on an integer and then moves off. + // apPrev = yn tracks the true state and stays click-free in both. + apPrev = yn dstP[i] = yn } bufP[writePosLocal & maskLocal] = sampleOrZero(srcP, i, inputCount) diff --git a/Sources/Lyrebird/Generators/Delays/DelayLineFeedback.swift b/Sources/Lyrebird/Generators/Delays/DelayLineFeedback.swift index f934bec..c1f79c4 100644 --- a/Sources/Lyrebird/Generators/Delays/DelayLineFeedback.swift +++ b/Sources/Lyrebird/Generators/Delays/DelayLineFeedback.swift @@ -270,9 +270,6 @@ public final class DelayLineFeedback: GeneratorBase, AudioGenerator { let frac: Double = d - Double(intD) let yn: Double = bufP[(writePosLocal - intD) & maskLocal] let delayed: Double - // When frac == 0, output is exactly yn. Do NOT reset apPrev — that - // would introduce a discontinuity (click) when modulated delay crosses an - // integer boundary. Preserving state across zero crossings keeps output smooth. if frac > 0 { let eta: Double = (1.0 - frac) / (1.0 + frac) let ynm1: Double = bufP[(writePosLocal - intD - 1) & maskLocal] @@ -280,6 +277,13 @@ public final class DelayLineFeedback: GeneratorBase, AudioGenerator { apPrev = out delayed = out } else { + // frac == 0: the output is exactly the integer-delayed sample, + // so the allpass interpolator's output here IS yn. Record that + // as its previous output. Zeroing apPrev clicks when a modulated + // delay crosses an integer boundary; freezing the old value + // clicks when the delay dwells on an integer and then moves off. + // apPrev = yn tracks the true state and stays click-free in both. + apPrev = yn delayed = yn } let x: Double = sampleOrZero(srcP, i, inputCount) diff --git a/Sources/Lyrebird/Generators/Demand/Demand.swift b/Sources/Lyrebird/Generators/Demand/Demand.swift index 1aad4ba..ffdc344 100644 --- a/Sources/Lyrebird/Generators/Demand/Demand.swift +++ b/Sources/Lyrebird/Generators/Demand/Demand.swift @@ -125,7 +125,7 @@ public enum Demand { /// /// `floatValue(graph:)` returns `previousOutputValue` without advancing the sequence — /// use the full `calculatedSamples` path for demand evaluation. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -136,18 +136,9 @@ public enum Demand { demand: any DemandGenerator ) { super.init(trig: trig, reset: reset, demand: demand) - _setupSubBlockBuffer() } - /// Bypasses `ControlGenerator` sub-block loop — trigger detection requires scanning - /// the full audio-rate trig input once per block, not per sub-block chunk. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Dynamics/AmplitudeFollower.swift b/Sources/Lyrebird/Generators/Dynamics/AmplitudeFollower.swift index 6508712..51c7105 100644 --- a/Sources/Lyrebird/Generators/Dynamics/AmplitudeFollower.swift +++ b/Sources/Lyrebird/Generators/Dynamics/AmplitudeFollower.swift @@ -153,7 +153,7 @@ public enum AmplitudeFollower { /// - input: Signal to track. /// - attackTime: Attack time constant in seconds. Formula: `exp(−1 / (sampleRate × t))`. Practical range 0.001–1.0. Defaults to `0.01`. /// - releaseTime: Release time constant in seconds. Practical range 0.01–5.0. Defaults to `0.1`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -167,17 +167,8 @@ public enum AmplitudeFollower { releaseTime: any ValidGeneratorInput = 0.1 ) { super.init(in: input, attackTime: attackTime, releaseTime: releaseTime) - _setupSubBlockBuffer() } - // Bypass sub-block loop: smoothing state must update once per audio block. - // Sub-blocking would apply the coeff N times per block, making time constants N× shorter. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Dynamics/Compressor.swift b/Sources/Lyrebird/Generators/Dynamics/Compressor.swift index bfd5dea..f4d5ea7 100644 --- a/Sources/Lyrebird/Generators/Dynamics/Compressor.swift +++ b/Sources/Lyrebird/Generators/Dynamics/Compressor.swift @@ -231,7 +231,7 @@ public enum Compressor { /// - release: Release time constant in seconds. Practical range 0.01–5.0. Defaults to `0.1`. /// - kneeWidth: Soft-knee width in dB (0 = hard knee). Must be ≥ 0. Defaults to `0.0`. /// - makeupGain: Output gain in dB applied after compression. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 1.0 // matches _prevGain initial value @@ -255,17 +255,8 @@ public enum Compressor { super.init(in: input, threshold: threshold, ratio: ratio, attack: attack, release: release, kneeWidth: kneeWidth, makeupGain: makeupGain) - _setupSubBlockBuffer() } - // Bypass sub-block loop: _prevGain must advance once per audio block. - // Sub-blocking would apply the gain smoother N times per block, shrinking time constants by N×. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Dynamics/Expander.swift b/Sources/Lyrebird/Generators/Dynamics/Expander.swift index db25350..4f11afb 100644 --- a/Sources/Lyrebird/Generators/Dynamics/Expander.swift +++ b/Sources/Lyrebird/Generators/Dynamics/Expander.swift @@ -226,7 +226,7 @@ public enum Expander { /// - attack: Attack time constant in seconds. Practical range 0.001–1.0. Defaults to `0.01`. /// - release: Release time constant in seconds. Practical range 0.01–5.0. Defaults to `0.1`. /// - kneeWidth: Soft-knee width in dB (0 = hard knee). Must be ≥ 0. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 1.0 // matches _prevGain initial value @@ -247,17 +247,8 @@ public enum Expander { ) { super.init(in: input, threshold: threshold, ratio: ratio, attack: attack, release: release, kneeWidth: kneeWidth) - _setupSubBlockBuffer() } - // Bypass sub-block loop: _prevGain must advance once per audio block. - // Sub-blocking would apply the gain smoother N times per block, shrinking time constants by N×. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Envelopes/ExponentialLine.swift b/Sources/Lyrebird/Generators/Envelopes/ExponentialLine.swift index 5bb282e..3cd82f0 100644 --- a/Sources/Lyrebird/Generators/Envelopes/ExponentialLine.swift +++ b/Sources/Lyrebird/Generators/Envelopes/ExponentialLine.swift @@ -43,7 +43,7 @@ public enum ExponentialLine { /// - doneAction: Action taken on completion. Defaults to `.nothing`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: GeneratorBase, ControlGenerator, DoneActionWatchable { + public final class Control: GeneratorBase, BlockRateControlGenerator, DoneActionWatchable { let start: Double let end: Double let dur: Double @@ -98,18 +98,10 @@ public enum ExponentialLine { self._rampTarget = start self.previousOutputValue = start super.init() - _setupSubBlockBuffer() _registerAutoFreeIfNeeded(doneAction) } - // Bypass sub-block loop: per-audio-block state advancement. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Envelopes/Line.swift b/Sources/Lyrebird/Generators/Envelopes/Line.swift index 3cb15a8..4950da5 100644 --- a/Sources/Lyrebird/Generators/Envelopes/Line.swift +++ b/Sources/Lyrebird/Generators/Envelopes/Line.swift @@ -37,7 +37,7 @@ public enum Line { /// - doneAction: Action taken on completion. Defaults to `.nothing`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: GeneratorBase, ControlGenerator, DoneActionWatchable { + public final class Control: GeneratorBase, BlockRateControlGenerator, DoneActionWatchable { let start: Double let end: Double let dur: Double @@ -80,18 +80,10 @@ public enum Line { self._rampTarget = start self.previousOutputValue = start super.init() - _setupSubBlockBuffer() _registerAutoFreeIfNeeded(doneAction) } - // Bypass sub-block loop: per-audio-block state advancement. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Envelopes/RateRamp.swift b/Sources/Lyrebird/Generators/Envelopes/RateRamp.swift index e1d4cea..d33f046 100644 --- a/Sources/Lyrebird/Generators/Envelopes/RateRamp.swift +++ b/Sources/Lyrebird/Generators/Envelopes/RateRamp.swift @@ -54,7 +54,7 @@ public enum RateRamp { /// Defaults to `0.0`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: GeneratorBase, ControlGenerator { + public final class Control: GeneratorBase, BlockRateControlGenerator { let trigInput: any ValidGeneratorInput let rateInput: any ValidGeneratorInput let startInput: any ValidGeneratorInput @@ -95,18 +95,9 @@ public enum RateRamp { self._rateIsGenerator = resolvedRate is any Generator self._mulAdd = MulAddSpec(mul: mul, add: add) super.init() - _setupSubBlockBuffer() } - // Bypass sub-block loop: scans the full audio-rate trigger block for a ≤0→>0 - // edge — must run exactly once per audio block, not once per sub-block chunk. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Filters/AllpassFilter.swift b/Sources/Lyrebird/Generators/Filters/AllpassFilter.swift index b9c87c5..03d53c9 100644 --- a/Sources/Lyrebird/Generators/Filters/AllpassFilter.swift +++ b/Sources/Lyrebird/Generators/Filters/AllpassFilter.swift @@ -234,8 +234,14 @@ public final class AllpassFilter: GeneratorBase, AudioGenerator { xD = xOut yD = yOut } else { - apPrevIn = 0 - apPrevOut = 0 + // frac == 0: both reads are exactly the integer-delayed + // samples, so each interpolator's output here IS xn / yn. + // Record those as the previous outputs. Zeroing clicks when a + // modulated delay crosses an integer boundary; freezing the + // old values clicks when the delay dwells on an integer and + // then moves off. Tracking the true state stays click-free. + apPrevIn = xn + apPrevOut = yn xD = xn yD = yn } diff --git a/Sources/Lyrebird/Generators/Filters/CombFilter.swift b/Sources/Lyrebird/Generators/Filters/CombFilter.swift index d6bde4e..03902ce 100644 --- a/Sources/Lyrebird/Generators/Filters/CombFilter.swift +++ b/Sources/Lyrebird/Generators/Filters/CombFilter.swift @@ -213,7 +213,13 @@ public final class CombFilter: GeneratorBase, AudioGenerator { apPrev = out delayed = out } else { - apPrev = 0 + // frac == 0: the output is exactly the integer-delayed sample, + // so the allpass interpolator's output here IS yn. Record that + // as its previous output. Zeroing apPrev clicks when a modulated + // delay crosses an integer boundary; freezing the old value + // clicks when the delay dwells on an integer and then moves off. + // apPrev = yn tracks the true state and stays click-free in both. + apPrev = yn delayed = yn } let y: Double = sampleOrZero(srcP, i, n) + g * delayed diff --git a/Sources/Lyrebird/Generators/Filters/Decay.swift b/Sources/Lyrebird/Generators/Filters/Decay.swift index d6c2733..d7893eb 100644 --- a/Sources/Lyrebird/Generators/Filters/Decay.swift +++ b/Sources/Lyrebird/Generators/Filters/Decay.swift @@ -123,15 +123,15 @@ public enum Decay { /// Control-rate leaky integrator. /// - /// Advances integrator state once per audio block. The sub-block loop is bypassed via - /// a `calculatedSamples` override (same pattern as `SVF.Control`). + /// Advances integrator state once per audio block. The sub-block loop is bypassed by conforming to + /// `BlockRateControlGenerator` (same pattern as `SVF.Control`). /// /// - Parameters: /// - input: Excitation signal (typically impulses). Each non-zero block value adds to the integrator state. /// - decayTime: Time in seconds for the output to decay by 60 dB. `0` = no memory. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 @@ -147,13 +147,9 @@ public enum Decay { add: any ValidGeneratorInput = 0.0 ) { super.init(input: input, decayTime: decayTime, mul: mul, add: add) - _setupSubBlockBuffer() } - public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) @@ -162,13 +158,7 @@ public enum Decay { let x: Double = inputSource.floatValue(graph: graph) let y: Double = x + b1 * y1 y1 = denormalsToZero(y) - var fillValue: Double = y - _result[0].withUnsafeMutableBufferPointer { buf in - guard let base: UnsafeMutablePointer = 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] + fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count) return _result } } diff --git a/Sources/Lyrebird/Generators/Filters/Decay2.swift b/Sources/Lyrebird/Generators/Filters/Decay2.swift index c2f82e0..c4c8820 100644 --- a/Sources/Lyrebird/Generators/Filters/Decay2.swift +++ b/Sources/Lyrebird/Generators/Filters/Decay2.swift @@ -143,8 +143,8 @@ public enum Decay2 { /// Control-rate two-integrator decay with rounded attack. /// - /// Advances both integrator states once per audio block. The sub-block loop is bypassed via - /// a `calculatedSamples` override (same pattern as `SVF.Control`). + /// Advances both integrator states once per audio block. The sub-block loop is bypassed by conforming to + /// `BlockRateControlGenerator` (same pattern as `SVF.Control`). /// /// - Parameters: /// - input: Excitation signal (typically impulses). @@ -152,7 +152,7 @@ public enum Decay2 { /// - decayTime: 60 dB decay time of the main decay integrator in seconds. `0` = no decay memory. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 @@ -170,13 +170,9 @@ public enum Decay2 { add: any ValidGeneratorInput = 0.0 ) { super.init(input: input, attackTime: attackTime, decayTime: decayTime, mul: mul, add: add) - _setupSubBlockBuffer() } - public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) @@ -189,13 +185,7 @@ public enum Decay2 { yA1 = denormalsToZero(newYA) yD1 = denormalsToZero(newYD) let y: Double = newYD - newYA - var fillValue: Double = y - _result[0].withUnsafeMutableBufferPointer { buf in - guard let base: UnsafeMutablePointer = 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] + fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count) return _result } } diff --git a/Sources/Lyrebird/Generators/Filters/Formlet.swift b/Sources/Lyrebird/Generators/Filters/Formlet.swift index 1beb719..6181fe1 100644 --- a/Sources/Lyrebird/Generators/Filters/Formlet.swift +++ b/Sources/Lyrebird/Generators/Filters/Formlet.swift @@ -197,8 +197,8 @@ public enum Formlet { /// Control-rate FOF-like resonant filter. /// /// Advances both resonators once per audio block at the control rate - /// (`sampleRate / blockSize`); the sub-block loop is bypassed via a - /// `calculatedSamples` override (same pattern as `Lag.Control`). + /// (`sampleRate / blockSize`); the sub-block loop is bypassed by conforming to + /// `BlockRateControlGenerator` (same pattern as `Lag.Control`). /// /// - Parameters: /// - input: Signal to excite the resonators. @@ -207,7 +207,7 @@ public enum Formlet { /// - decayTime: Fall time in seconds (60 dB time of the long resonator). /// - mul: Output multiplier applied after synthesis. Defaults to `1.0`. /// - add: Offset added after multiplier. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 @@ -228,13 +228,8 @@ public enum Formlet { ) { super.init(input: input, freq: freq, attackTime: attackTime, decayTime: decayTime, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: resonator state advances exactly once per audio block. - public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) @@ -256,13 +251,7 @@ public enum Formlet { yAttack2 = denormalsToZero(yAttack1) yAttack1 = denormalsToZero(yAttack) - var fillValue: Double = yDecay - yAttack - _result[0].withUnsafeMutableBufferPointer { (buf: inout UnsafeMutableBufferPointer) in - guard let base: UnsafeMutablePointer = 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] + fillHeldResult(into: &_result, value: yDecay - yAttack, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count) return _result } } diff --git a/Sources/Lyrebird/Generators/Filters/Hilbert.swift b/Sources/Lyrebird/Generators/Filters/Hilbert.swift index 222258e..b6e37bf 100644 --- a/Sources/Lyrebird/Generators/Filters/Hilbert.swift +++ b/Sources/Lyrebird/Generators/Filters/Hilbert.swift @@ -146,15 +146,7 @@ public enum Hilbert { let (b0, b1, b2, b3): (Double, Double, Double, Double) = Hilbert.hilbertCoeffB // Fetch input block (audio-rate or scalar). - let inputSamples: [Double]? - let scalarInput: Double - if _inputIsGenerator { - inputSamples = _inputSource.calculatedSamples(graph: graph, count: count).first - scalarInput = 0 - } else { - inputSamples = nil - scalarInput = _inputSource.floatValue(graph: graph) - } + let (inputSamples, scalarInput) = resolveGeneratorOrScalar(_inputSource, isGenerator: _inputIsGenerator, graph: graph, count: count) for i: Int in 0.. [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { @@ -171,13 +165,7 @@ public enum Lag { let x: Double = inputSource.floatValue(graph: graph) let y: Double = b1 * y1 + (1.0 - b1) * x y1 = denormalsToZero(y) - var fillValue: Double = y - _result[0].withUnsafeMutableBufferPointer { buf in - guard let base: UnsafeMutablePointer = 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] + fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count) return _result } } diff --git a/Sources/Lyrebird/Generators/Filters/Lag2.swift b/Sources/Lyrebird/Generators/Filters/Lag2.swift index f72c823..32de25c 100644 --- a/Sources/Lyrebird/Generators/Filters/Lag2.swift +++ b/Sources/Lyrebird/Generators/Filters/Lag2.swift @@ -128,15 +128,15 @@ public enum Lag2 { /// Control-rate two-cascaded one-pole smoother. /// - /// Advances both filter stages once per audio block. The sub-block loop is bypassed via - /// a `calculatedSamples` override (same pattern as `SVF.Control`). + /// Advances both filter stages once per audio block. The sub-block loop is bypassed by conforming to + /// `BlockRateControlGenerator` (same pattern as `SVF.Control`). /// /// - Parameters: /// - input: Signal to smooth. /// - time: 60 dB lag time in seconds per stage. `0` = transparent. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 @@ -152,13 +152,9 @@ public enum Lag2 { add: any ValidGeneratorInput = 0.0 ) { super.init(input: input, time: time, mul: mul, add: add) - _setupSubBlockBuffer() } - public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) @@ -170,13 +166,7 @@ public enum Lag2 { let y: Double = b1 * y1b + oneMinusB1 * s1 y1a = denormalsToZero(s1) y1b = denormalsToZero(y) - var fillValue: Double = y - _result[0].withUnsafeMutableBufferPointer { buf in - guard let base: UnsafeMutablePointer = 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] + fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count) return _result } } diff --git a/Sources/Lyrebird/Generators/Filters/Lag2UpDown.swift b/Sources/Lyrebird/Generators/Filters/Lag2UpDown.swift index 8e14c83..7861262 100644 --- a/Sources/Lyrebird/Generators/Filters/Lag2UpDown.swift +++ b/Sources/Lyrebird/Generators/Filters/Lag2UpDown.swift @@ -141,8 +141,8 @@ public enum Lag2UpDown { /// Control-rate two-cascaded asymmetric one-pole smoother. /// - /// Advances both filter stages once per audio block. The sub-block loop is bypassed via - /// a `calculatedSamples` override (same pattern as `SVF.Control`). + /// Advances both filter stages once per audio block. The sub-block loop is bypassed by conforming to + /// `BlockRateControlGenerator` (same pattern as `SVF.Control`). /// /// - Parameters: /// - input: Signal to smooth. @@ -150,7 +150,7 @@ public enum Lag2UpDown { /// - lagDown: 60 dB lag time in seconds for falling transitions per stage. `0` = instant. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 @@ -168,13 +168,9 @@ public enum Lag2UpDown { add: any ValidGeneratorInput = 0.0 ) { super.init(input: input, lagUp: lagUp, lagDown: lagDown, mul: mul, add: add) - _setupSubBlockBuffer() } - public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) @@ -188,13 +184,7 @@ public enum Lag2UpDown { let y: Double = sel2 * y1b + (1.0 - sel2) * s1 y1a = denormalsToZero(s1) y1b = denormalsToZero(y) - var fillValue: Double = y - _result[0].withUnsafeMutableBufferPointer { buf in - guard let base: UnsafeMutablePointer = 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] + fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count) return _result } } diff --git a/Sources/Lyrebird/Generators/Filters/LagUpDown.swift b/Sources/Lyrebird/Generators/Filters/LagUpDown.swift index 3c58d1d..124be95 100644 --- a/Sources/Lyrebird/Generators/Filters/LagUpDown.swift +++ b/Sources/Lyrebird/Generators/Filters/LagUpDown.swift @@ -143,8 +143,8 @@ public enum LagUpDown { /// Control-rate asymmetric one-pole smoother. /// - /// Advances filter state once per audio block. The sub-block loop is bypassed via - /// a `calculatedSamples` override (same pattern as `SVF.Control`). + /// Advances filter state once per audio block. The sub-block loop is bypassed by conforming to + /// `BlockRateControlGenerator` (same pattern as `SVF.Control`). /// /// - Parameters: /// - input: Signal to smooth. @@ -152,7 +152,7 @@ public enum LagUpDown { /// - lagDown: 60 dB lag time in seconds for falling transitions. `0` = instant. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 @@ -170,13 +170,9 @@ public enum LagUpDown { add: any ValidGeneratorInput = 0.0 ) { super.init(input: input, lagUp: lagUp, lagDown: lagDown, mul: mul, add: add) - _setupSubBlockBuffer() } - public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) @@ -187,13 +183,7 @@ public enum LagUpDown { let b1: Double = x >= y1 ? b1Up : b1Down let y: Double = b1 * y1 + (1.0 - b1) * x y1 = denormalsToZero(y) - var fillValue: Double = y - _result[0].withUnsafeMutableBufferPointer { buf in - guard let base: UnsafeMutablePointer = 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] + fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count) return _result } } diff --git a/Sources/Lyrebird/Generators/Filters/LeakDC.swift b/Sources/Lyrebird/Generators/Filters/LeakDC.swift index 8946726..918b1b8 100644 --- a/Sources/Lyrebird/Generators/Filters/LeakDC.swift +++ b/Sources/Lyrebird/Generators/Filters/LeakDC.swift @@ -139,15 +139,15 @@ public enum LeakDC { /// Control-rate one-pole DC blocker. /// - /// Advances filter state once per audio block. The sub-block loop is bypassed via - /// a `calculatedSamples` override (same pattern as `SVF.Control`). + /// Advances filter state once per audio block. The sub-block loop is bypassed by conforming to + /// `BlockRateControlGenerator` (same pattern as `SVF.Control`). /// /// - Parameters: /// - input: Signal from which to remove DC bias. /// - coef: Pole coefficient in `[0, 1)`. Higher values lower the corner frequency. Defaults to `leakDCDefaultControlCoef` (0.9). /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 @@ -163,13 +163,9 @@ public enum LeakDC { add: any ValidGeneratorInput = 0.0 ) { super.init(input: input, coef: coef, mul: mul, add: add) - _setupSubBlockBuffer() } - public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) @@ -178,13 +174,7 @@ public enum LeakDC { let y: Double = x - x1 + c * y1 x1 = x y1 = denormalsToZero(y) - var fillValue: Double = y - _result[0].withUnsafeMutableBufferPointer { buf in - guard let base: UnsafeMutablePointer = 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] + fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count) return _result } } diff --git a/Sources/Lyrebird/Generators/Filters/MuTronIII.swift b/Sources/Lyrebird/Generators/Filters/MuTronIII.swift index 6de28da..728ca09 100644 --- a/Sources/Lyrebird/Generators/Filters/MuTronIII.swift +++ b/Sources/Lyrebird/Generators/Filters/MuTronIII.swift @@ -261,15 +261,7 @@ public enum MuTronIII { // Read input — generator block or scalar fast path (avoids RT allocation in // `Double.calculatedSamples`). - let inputSamples: [Double]? - let scalarInput: Double - if _inputIsGenerator { - inputSamples = _inputSource.calculatedSamples(graph: graph, count: count).first - scalarInput = 0.0 - } else { - inputSamples = nil - scalarInput = _inputSource.floatValue(graph: graph) - } + let (inputSamples, scalarInput) = resolveGeneratorOrScalar(_inputSource, isGenerator: _inputIsGenerator, graph: graph, count: count) for i: Int in 0.. [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) @@ -439,15 +425,7 @@ public enum MuTronIII { // Bypass guarantees `_computeSamples` runs once per audio block, so `count` equals // the full audio block size for input generators. - let inputSamples: [Double]? - let scalarInput: Double - if _inputIsGenerator { - inputSamples = _inputSource.calculatedSamples(graph: graph, count: count).first - scalarInput = 0.0 - } else { - inputSamples = nil - scalarInput = _inputSource.floatValue(graph: graph) - } + let (inputSamples, scalarInput) = resolveGeneratorOrScalar(_inputSource, isGenerator: _inputIsGenerator, graph: graph, count: count) // Process all `count` input samples to advance state fully. var lastOut: Double = previousOutputValue diff --git a/Sources/Lyrebird/Generators/Filters/SVF.swift b/Sources/Lyrebird/Generators/Filters/SVF.swift index e88f705..2a43fc3 100644 --- a/Sources/Lyrebird/Generators/Filters/SVF.swift +++ b/Sources/Lyrebird/Generators/Filters/SVF.swift @@ -180,7 +180,7 @@ public enum SVF { /// Suitable for slow-moving filter sweeps or as a block-rate signal processor. /// /// IIR state must advance exactly once per audio block, processing each input sample - /// exactly once. The sub-block loop is bypassed via a `calculatedSamples` override + /// exactly once. The sub-block loop is bypassed by conforming to `BlockRateControlGenerator` /// (same pattern as `AmplitudeFollower.Control`). /// /// - Parameters: @@ -192,7 +192,7 @@ public enum SVF { /// divide-by-zero. Defaults to `svfButterworthQ`. /// - mul: Output multiplier applied to all four channels. Defaults to `1.0`. /// - add: Output offset applied to all four channels. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 @@ -216,24 +216,11 @@ public enum SVF { add: any ValidGeneratorInput = 0.0 ) { super.init(input: input, freq: freq, q: q, mul: mul, add: add) - // _setupSubBlockBuffer retained defensively; calculatedSamples bypass prevents - // sub-block engagement in practice. - _setupSubBlockBuffer(channels: svfChannelCount) + // No _setupSubBlockBuffer(): BlockRateControlGenerator conformance bypasses the + // sub-block loop, so _subBlockBuffer is never read. } - // MARK: - AmplitudeFollower.Control pattern - - // Bypass sub-block loop: IIR state must advance exactly once per audio block, - // processing each input sample exactly once. The default sub-block path would - // re-read the cached input prefix on every sub-block call, re-processing the - // same audio samples N times instead of advancing through the block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Filters/Slew.swift b/Sources/Lyrebird/Generators/Filters/Slew.swift index 3a55653..c1fb332 100644 --- a/Sources/Lyrebird/Generators/Filters/Slew.swift +++ b/Sources/Lyrebird/Generators/Filters/Slew.swift @@ -155,7 +155,7 @@ public enum Slew { /// Control-rate linear slew-rate limiter. Advances one slew step per audio block. /// - /// Override of `calculatedSamples` bypasses the sub-block loop — the slew step must + /// Conforming to `BlockRateControlGenerator` bypasses the sub-block loop — the slew step must /// advance exactly once per audio block. The coefficient is computed at the control rate /// (`sampleRate / blockSize`); `up` and `dn` remain in units per second and produce the /// same wall-clock slew time regardless of block size (matching `Lag.Control`). @@ -168,7 +168,7 @@ public enum Slew { /// - dn: Maximum falling slope in units per second. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 @@ -186,16 +186,8 @@ public enum Slew { add: any ValidGeneratorInput = 0.0 ) { super.init(input: input, up: up, dn: dn, mul: mul, add: add) - _setupSubBlockBuffer() } - /// Bypass sub-block loop: slew state must advance exactly once per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -222,14 +214,7 @@ public enum Slew { } } - var fillValue: Double = _state - _result[0].withUnsafeMutableBufferPointer { buf in - guard let base: UnsafeMutablePointer = buf.baseAddress else { return } - vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count)) - } - _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) - guard count > 0 else { return _result } - previousOutputValue = _result[0][count - 1] + fillHeldResult(into: &_result, value: _state, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count) return _result } } diff --git a/Sources/Lyrebird/Generators/Gendy/Gendy1.swift b/Sources/Lyrebird/Generators/Gendy/Gendy1.swift index 978029c..5639215 100644 --- a/Sources/Lyrebird/Generators/Gendy/Gendy1.swift +++ b/Sources/Lyrebird/Generators/Gendy/Gendy1.swift @@ -269,7 +269,7 @@ public enum Gendy1 { /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. /// - seed: Optional PRNG seed for deterministic output. `nil` uses a time-based seed. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -313,14 +313,9 @@ public enum Gendy1 { seed: seed, seedMixConstant: 0xFEDC_BA98_1357_2468 ) - _setupSubBlockBuffer() } - // Bypass sub-block loop: phase position and PRNG must advance exactly once per audio block. - public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) diff --git a/Sources/Lyrebird/Generators/Gendy/Gendy2.swift b/Sources/Lyrebird/Generators/Gendy/Gendy2.swift index 5a609ec..57944e7 100644 --- a/Sources/Lyrebird/Generators/Gendy/Gendy2.swift +++ b/Sources/Lyrebird/Generators/Gendy/Gendy2.swift @@ -273,7 +273,7 @@ public enum Gendy2 { /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. /// - seed: Optional PRNG seed for deterministic output. `nil` uses a time-based seed. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -317,14 +317,9 @@ public enum Gendy2 { seed: seed, seedMixConstant: 0xABCD_EF01_2468_1357 ) - _setupSubBlockBuffer() } - // Bypass sub-block loop: phase position and PRNG must advance exactly once per audio block. - public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) diff --git a/Sources/Lyrebird/Generators/Gendy/Gendy3.swift b/Sources/Lyrebird/Generators/Gendy/Gendy3.swift index 306828a..ead504c 100644 --- a/Sources/Lyrebird/Generators/Gendy/Gendy3.swift +++ b/Sources/Lyrebird/Generators/Gendy/Gendy3.swift @@ -222,7 +222,7 @@ public enum Gendy3 { /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. /// - seed: Optional PRNG seed for deterministic output. `nil` uses a time-based seed. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -256,14 +256,9 @@ public enum Gendy3 { seed: seed, seedMixConstant: 0x0123_4567_FEDC_BA98 ) - _setupSubBlockBuffer() } - // Bypass sub-block loop: phase position and PRNG must advance exactly once per audio block. - public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) diff --git a/Sources/Lyrebird/Generators/KarplusStrong/GatedKarplusStrong.swift b/Sources/Lyrebird/Generators/KarplusStrong/GatedKarplusStrong.swift index af5ac1f..e92e69f 100644 --- a/Sources/Lyrebird/Generators/KarplusStrong/GatedKarplusStrong.swift +++ b/Sources/Lyrebird/Generators/KarplusStrong/GatedKarplusStrong.swift @@ -178,59 +178,19 @@ public enum GatedKarplusStrong { let doublingOffset: Int = delayLineCount * 2 // Read exciter block unconditionally so upstream generator always advances state. - let exciterSamples: [Double]? - let scalarExciter: Double - if _exciterIsGenerator { - exciterSamples = _exciterSource.calculatedSamples(graph: graph, count: count).first - scalarExciter = 0 - } else { - exciterSamples = nil - scalarExciter = _exciterSource.floatValue(graph: graph) - } + let (exciterSamples, scalarExciter) = resolveGeneratorOrScalar(_exciterSource, isGenerator: _exciterIsGenerator, graph: graph, count: count) // Read gate block. - let gateSamples: [Double]? - let scalarGate: Double - if _gateIsGenerator { - gateSamples = _gateSource.calculatedSamples(graph: graph, count: count).first - scalarGate = 0 - } else { - gateSamples = nil - scalarGate = _gateSource.floatValue(graph: graph) - } + let (gateSamples, scalarGate) = resolveGeneratorOrScalar(_gateSource, isGenerator: _gateIsGenerator, graph: graph, count: count) // Read freq block. - let freqSamples: [Double]? - let scalarFreq: Double - if _freqIsGenerator { - freqSamples = _freqSource.calculatedSamples(graph: graph, count: count).first - scalarFreq = 0 - } else { - freqSamples = nil - scalarFreq = _freqSource.floatValue(graph: graph) - } + let (freqSamples, scalarFreq) = resolveGeneratorOrScalar(_freqSource, isGenerator: _freqIsGenerator, graph: graph, count: count) // Read feedback block. - let feedbackSamples: [Double]? - let scalarFeedback: Double - if _feedbackIsGenerator { - feedbackSamples = _feedbackSource.calculatedSamples(graph: graph, count: count).first - scalarFeedback = 0 - } else { - feedbackSamples = nil - scalarFeedback = _feedbackSource.floatValue(graph: graph) - } + let (feedbackSamples, scalarFeedback) = resolveGeneratorOrScalar(_feedbackSource, isGenerator: _feedbackIsGenerator, graph: graph, count: count) // Read coef block. - let coefSamples: [Double]? - let scalarCoef: Double - if _coefIsGenerator { - coefSamples = _coefSource.calculatedSamples(graph: graph, count: count).first - scalarCoef = 0 - } else { - coefSamples = nil - scalarCoef = _coefSource.floatValue(graph: graph) - } + let (coefSamples, scalarCoef) = resolveGeneratorOrScalar(_coefSource, isGenerator: _coefIsGenerator, graph: graph, count: count) // Per-sample loop. for i: Int in 0.. [[Double]] { _checkCount(count) var target: Double = Swift.abs(inputSource.floatValue(graph: graph)) - if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Ceil.swift b/Sources/Lyrebird/Generators/Math/Ceil.swift index 0e3eb09..373ff31 100644 --- a/Sources/Lyrebird/Generators/Math/Ceil.swift +++ b/Sources/Lyrebird/Generators/Math/Ceil.swift @@ -12,20 +12,7 @@ import Foundation /// /// - Parameter signal: Input signal. public enum Ceil { - public class _Base: GeneratorBase { - let inputSource: any ValidGeneratorInput - let _mulAdd: MulAddSpec - public init( - _ signal: any ValidGeneratorInput, - mul: any ValidGeneratorInput = 1.0, - add: any ValidGeneratorInput = 0.0 - ) { - - let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput() - inputSource = resolvedSignal - _mulAdd = MulAddSpec(mul: mul, add: add) - } - } + public class _Base: UnaryMathBase {} /// - Parameters: /// - signal: Input signal. /// - mul: Output multiplier. Defaults to `1.0`. @@ -73,7 +60,7 @@ public enum Ceil { ) -> [[Double]] { _checkCount(count) var target: Double = Foundation.ceil(inputSource.floatValue(graph: graph)) - if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Clip.swift b/Sources/Lyrebird/Generators/Math/Clip.swift index 08353a1..4d9b6dd 100644 --- a/Sources/Lyrebird/Generators/Math/Clip.swift +++ b/Sources/Lyrebird/Generators/Math/Clip.swift @@ -116,10 +116,7 @@ public enum Clip { let lo: Double = loInput.floatValue(graph: graph) let hi: Double = hiInput.floatValue(graph: graph) var target: Double = Swift.max(lo, Swift.min(hi, inputSource.floatValue(graph: graph))) - if !_mulAdd.isIdentity { - target = target * _mulAdd.mulInput.floatValue(graph: graph) - + _mulAdd.addInput.floatValue(graph: graph) - } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Cos.swift b/Sources/Lyrebird/Generators/Math/Cos.swift index cf2adbf..290ef3d 100644 --- a/Sources/Lyrebird/Generators/Math/Cos.swift +++ b/Sources/Lyrebird/Generators/Math/Cos.swift @@ -13,20 +13,7 @@ import Foundation /// /// - Parameter signal: Input signal in radians. public enum Cos { - public class _Base: GeneratorBase { - let inputSource: any ValidGeneratorInput - let _mulAdd: MulAddSpec - public init( - _ signal: any ValidGeneratorInput, - mul: any ValidGeneratorInput = 1.0, - add: any ValidGeneratorInput = 0.0 - ) { - - let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput() - inputSource = resolvedSignal - _mulAdd = MulAddSpec(mul: mul, add: add) - } - } + public class _Base: UnaryMathBase {} /// - Parameters: /// - signal: Input signal in radians. /// - mul: Output multiplier. Defaults to `1.0`. @@ -74,7 +61,7 @@ public enum Cos { ) -> [[Double]] { _checkCount(count) var target: Double = Foundation.cos(inputSource.floatValue(graph: graph)) - if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/DbAmp.swift b/Sources/Lyrebird/Generators/Math/DbAmp.swift index 3117163..ec18ad2 100644 --- a/Sources/Lyrebird/Generators/Math/DbAmp.swift +++ b/Sources/Lyrebird/Generators/Math/DbAmp.swift @@ -15,19 +15,7 @@ /// /// - Parameter signal: Input value in decibels. public enum DbAmp { - public class _Base: GeneratorBase { - let inputSource: any ValidGeneratorInput - let _mulAdd: MulAddSpec - public init( - _ signal: any ValidGeneratorInput, - mul: any ValidGeneratorInput = 1.0, - add: any ValidGeneratorInput = 0.0 - ) { - let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput() - inputSource = resolvedSignal - _mulAdd = MulAddSpec(mul: mul, add: add) - } - } + public class _Base: UnaryMathBase {} /// - Parameters: /// - signal: Input value in decibels. @@ -52,9 +40,7 @@ public enum DbAmp { ) -> [[Double]] { _checkCount(count) var target: Double = dbToAmp(inputSource.floatValue(graph: graph)) - if !_mulAdd.isIdentity { - target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) - } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Exp.swift b/Sources/Lyrebird/Generators/Math/Exp.swift index f178dc8..f045361 100644 --- a/Sources/Lyrebird/Generators/Math/Exp.swift +++ b/Sources/Lyrebird/Generators/Math/Exp.swift @@ -12,20 +12,7 @@ import Foundation /// /// - Parameter signal: Input signal. public enum Exp { - public class _Base: GeneratorBase { - let inputSource: any ValidGeneratorInput - let _mulAdd: MulAddSpec - public init( - _ signal: any ValidGeneratorInput, - mul: any ValidGeneratorInput = 1.0, - add: any ValidGeneratorInput = 0.0 - ) { - - let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput() - inputSource = resolvedSignal - _mulAdd = MulAddSpec(mul: mul, add: add) - } - } + public class _Base: UnaryMathBase {} /// - Parameters: /// - signal: Input signal. /// - mul: Output multiplier. Defaults to `1.0`. @@ -73,7 +60,7 @@ public enum Exp { ) -> [[Double]] { _checkCount(count) var target: Double = Foundation.exp(inputSource.floatValue(graph: graph)) - if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/ExpExp.swift b/Sources/Lyrebird/Generators/Math/ExpExp.swift index de9dcac..5301561 100644 --- a/Sources/Lyrebird/Generators/Math/ExpExp.swift +++ b/Sources/Lyrebird/Generators/Math/ExpExp.swift @@ -139,7 +139,7 @@ public enum ExpExp { let logOutRatio: Double = Foundation.log(outHi / outLo) let t: Double = Foundation.log(inputSource.floatValue(graph: graph) / inLo) / logInRange var target: Double = outLo * Foundation.exp(t * logOutRatio) - if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/ExpLin.swift b/Sources/Lyrebird/Generators/Math/ExpLin.swift index 65f0cfe..662eab4 100644 --- a/Sources/Lyrebird/Generators/Math/ExpLin.swift +++ b/Sources/Lyrebird/Generators/Math/ExpLin.swift @@ -138,7 +138,7 @@ public enum ExpLin { let logInRange: Double = Foundation.log(inHi / inLo) let t: Double = Foundation.log(inputSource.floatValue(graph: graph) / inLo) / logInRange var target: Double = outLo + t * (outHi - outLo) - if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Floor.swift b/Sources/Lyrebird/Generators/Math/Floor.swift index b4a7570..658abf9 100644 --- a/Sources/Lyrebird/Generators/Math/Floor.swift +++ b/Sources/Lyrebird/Generators/Math/Floor.swift @@ -12,20 +12,7 @@ import Foundation /// /// - Parameter signal: Input signal. public enum Floor { - public class _Base: GeneratorBase { - let inputSource: any ValidGeneratorInput - let _mulAdd: MulAddSpec - public init( - _ signal: any ValidGeneratorInput, - mul: any ValidGeneratorInput = 1.0, - add: any ValidGeneratorInput = 0.0 - ) { - - let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput() - inputSource = resolvedSignal - _mulAdd = MulAddSpec(mul: mul, add: add) - } - } + public class _Base: UnaryMathBase {} /// - Parameters: /// - signal: Input signal. /// - mul: Output multiplier. Defaults to `1.0`. @@ -73,7 +60,7 @@ public enum Floor { ) -> [[Double]] { _checkCount(count) var target: Double = Foundation.floor(inputSource.floatValue(graph: graph)) - if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Fold.swift b/Sources/Lyrebird/Generators/Math/Fold.swift index f18fad6..09d37d1 100644 --- a/Sources/Lyrebird/Generators/Math/Fold.swift +++ b/Sources/Lyrebird/Generators/Math/Fold.swift @@ -128,10 +128,7 @@ public enum Fold { let lo: Double = loInput.floatValue(graph: graph) let hi: Double = hiInput.floatValue(graph: graph) var target: Double = Fold._fold(inputSource.floatValue(graph: graph), lo: lo, hi: hi) - if !_mulAdd.isIdentity { - target = target * _mulAdd.mulInput.floatValue(graph: graph) - + _mulAdd.addInput.floatValue(graph: graph) - } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/LinExp.swift b/Sources/Lyrebird/Generators/Math/LinExp.swift index f88d6dc..43558ce 100644 --- a/Sources/Lyrebird/Generators/Math/LinExp.swift +++ b/Sources/Lyrebird/Generators/Math/LinExp.swift @@ -148,10 +148,7 @@ public enum LinExp { // outLo <= 0 produces NaN per IEEE 754. let t: Double = (inputSource.floatValue(graph: graph) - inLo) / inRange var target: Double = outLo * Foundation.exp(t * Foundation.log(outHi / outLo)) - if !_mulAdd.isIdentity { - target = target * _mulAdd.mulInput.floatValue(graph: graph) - + _mulAdd.addInput.floatValue(graph: graph) - } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/LinLin.swift b/Sources/Lyrebird/Generators/Math/LinLin.swift index b03604f..37f4be2 100644 --- a/Sources/Lyrebird/Generators/Math/LinLin.swift +++ b/Sources/Lyrebird/Generators/Math/LinLin.swift @@ -159,10 +159,7 @@ public enum LinLin { let outRange: Double = outHiInput.floatValue(graph: graph) - outLo // inRange == 0 produces NaN/±Inf per IEEE 754 — intentional. var target: Double = outLo + (inputSource.floatValue(graph: graph) - inLo) / inRange * outRange - if !_mulAdd.isIdentity { - target = target * _mulAdd.mulInput.floatValue(graph: graph) - + _mulAdd.addInput.floatValue(graph: graph) - } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Log.swift b/Sources/Lyrebird/Generators/Math/Log.swift index f0054e9..3e4b1a0 100644 --- a/Sources/Lyrebird/Generators/Math/Log.swift +++ b/Sources/Lyrebird/Generators/Math/Log.swift @@ -12,20 +12,7 @@ import Foundation /// /// - Parameter signal: Input signal. Non-positive input produces NaN or −Inf. public enum Log { - public class _Base: GeneratorBase { - let inputSource: any ValidGeneratorInput - let _mulAdd: MulAddSpec - public init( - _ signal: any ValidGeneratorInput, - mul: any ValidGeneratorInput = 1.0, - add: any ValidGeneratorInput = 0.0 - ) { - - let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput() - inputSource = resolvedSignal - _mulAdd = MulAddSpec(mul: mul, add: add) - } - } + public class _Base: UnaryMathBase {} /// - Parameters: /// - signal: Input signal. Non-positive input produces NaN or −Inf. /// - mul: Output multiplier. Defaults to `1.0`. @@ -73,7 +60,7 @@ public enum Log { ) -> [[Double]] { _checkCount(count) var target: Double = Foundation.log(inputSource.floatValue(graph: graph)) - if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Max.swift b/Sources/Lyrebird/Generators/Math/Max.swift index 6c362b8..d70d4ab 100644 --- a/Sources/Lyrebird/Generators/Math/Max.swift +++ b/Sources/Lyrebird/Generators/Math/Max.swift @@ -88,7 +88,7 @@ public enum Max { ) -> [[Double]] { _checkCount(count) var target: Double = Swift.max(inputA.floatValue(graph: graph), inputB.floatValue(graph: graph)) - if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Min.swift b/Sources/Lyrebird/Generators/Math/Min.swift index fd338fe..bd0188c 100644 --- a/Sources/Lyrebird/Generators/Math/Min.swift +++ b/Sources/Lyrebird/Generators/Math/Min.swift @@ -88,7 +88,7 @@ public enum Min { ) -> [[Double]] { _checkCount(count) var target: Double = Swift.min(inputA.floatValue(graph: graph), inputB.floatValue(graph: graph)) - if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Pow.swift b/Sources/Lyrebird/Generators/Math/Pow.swift index 84bd72b..80cbe46 100644 --- a/Sources/Lyrebird/Generators/Math/Pow.swift +++ b/Sources/Lyrebird/Generators/Math/Pow.swift @@ -105,10 +105,7 @@ public enum Pow { _checkCount(count) var target: Double = Foundation.pow(inputSource.floatValue(graph: graph), expInput.floatValue(graph: graph)) - if !_mulAdd.isIdentity { - target = target * _mulAdd.mulInput.floatValue(graph: graph) - + _mulAdd.addInput.floatValue(graph: graph) - } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/RangeMapper.swift b/Sources/Lyrebird/Generators/Math/RangeMapper.swift index ee8965d..6db99eb 100644 --- a/Sources/Lyrebird/Generators/Math/RangeMapper.swift +++ b/Sources/Lyrebird/Generators/Math/RangeMapper.swift @@ -184,10 +184,7 @@ public enum RangeMapper { let x: Double = inputSource.floatValue(graph: graph) let t: Double = (x + 1.0) * bipolarToUnipolarScale var target: Double = mapScalarRangeCurve(t: t, low: low, high: high, curve: curve) - if !_mulAdd.isIdentity { - target = target * _mulAdd.mulInput.floatValue(graph: graph) - + _mulAdd.addInput.floatValue(graph: graph) - } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Reciprocal.swift b/Sources/Lyrebird/Generators/Math/Reciprocal.swift index 98f5006..11dd783 100644 --- a/Sources/Lyrebird/Generators/Math/Reciprocal.swift +++ b/Sources/Lyrebird/Generators/Math/Reciprocal.swift @@ -10,20 +10,7 @@ /// /// - Parameter signal: Input signal. Zero input produces ±Inf. public enum Reciprocal { - public class _Base: GeneratorBase { - let inputSource: any ValidGeneratorInput - let _mulAdd: MulAddSpec - public init( - _ signal: any ValidGeneratorInput, - mul: any ValidGeneratorInput = 1.0, - add: any ValidGeneratorInput = 0.0 - ) { - - let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput() - inputSource = resolvedSignal - _mulAdd = MulAddSpec(mul: mul, add: add) - } - } + public class _Base: UnaryMathBase {} /// - Parameters: /// - signal: Input signal. Zero input produces ±Inf. /// - mul: Output multiplier. Defaults to `1.0`. @@ -73,7 +60,7 @@ public enum Reciprocal { ) -> [[Double]] { _checkCount(count) var target: Double = 1.0 / inputSource.floatValue(graph: graph) - if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Ring1.swift b/Sources/Lyrebird/Generators/Math/Ring1.swift index d9ce9c9..e002d17 100644 --- a/Sources/Lyrebird/Generators/Math/Ring1.swift +++ b/Sources/Lyrebird/Generators/Math/Ring1.swift @@ -93,7 +93,7 @@ public enum Ring1 { _checkCount(count) let a: Double = inputA.floatValue(graph: graph); let b: Double = inputB.floatValue(graph: graph) var target: Double = (a + 1.0) * b - if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Ring2.swift b/Sources/Lyrebird/Generators/Math/Ring2.swift index 2bbeb94..18d71ae 100644 --- a/Sources/Lyrebird/Generators/Math/Ring2.swift +++ b/Sources/Lyrebird/Generators/Math/Ring2.swift @@ -93,7 +93,7 @@ public enum Ring2 { _checkCount(count) let a: Double = inputA.floatValue(graph: graph); let b: Double = inputB.floatValue(graph: graph) var target: Double = (a + 1.0) * b + a - if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Ring3.swift b/Sources/Lyrebird/Generators/Math/Ring3.swift index 63ecf67..92e0e43 100644 --- a/Sources/Lyrebird/Generators/Math/Ring3.swift +++ b/Sources/Lyrebird/Generators/Math/Ring3.swift @@ -93,7 +93,7 @@ public enum Ring3 { _checkCount(count) let a: Double = inputA.floatValue(graph: graph); let b: Double = inputB.floatValue(graph: graph) var target: Double = a * a * b - if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Ring4.swift b/Sources/Lyrebird/Generators/Math/Ring4.swift index 1fee6dc..ab0221e 100644 --- a/Sources/Lyrebird/Generators/Math/Ring4.swift +++ b/Sources/Lyrebird/Generators/Math/Ring4.swift @@ -93,7 +93,7 @@ public enum Ring4 { _checkCount(count) let a: Double = inputA.floatValue(graph: graph); let b: Double = inputB.floatValue(graph: graph) var target: Double = a * a * b - a * b - if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Round.swift b/Sources/Lyrebird/Generators/Math/Round.swift index d1e6a8e..acb24c4 100644 --- a/Sources/Lyrebird/Generators/Math/Round.swift +++ b/Sources/Lyrebird/Generators/Math/Round.swift @@ -12,20 +12,7 @@ import Foundation /// /// - Parameter signal: Input signal. public enum Round { - public class _Base: GeneratorBase { - let inputSource: any ValidGeneratorInput - let _mulAdd: MulAddSpec - public init( - _ signal: any ValidGeneratorInput, - mul: any ValidGeneratorInput = 1.0, - add: any ValidGeneratorInput = 0.0 - ) { - - let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput() - inputSource = resolvedSignal - _mulAdd = MulAddSpec(mul: mul, add: add) - } - } + public class _Base: UnaryMathBase {} /// - Parameters: /// - signal: Input signal. /// - mul: Output multiplier. Defaults to `1.0`. @@ -74,7 +61,7 @@ public enum Round { ) -> [[Double]] { _checkCount(count) var target: Double = Foundation.round(inputSource.floatValue(graph: graph)) - if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Sign.swift b/Sources/Lyrebird/Generators/Math/Sign.swift index d42c762..6be2821 100644 --- a/Sources/Lyrebird/Generators/Math/Sign.swift +++ b/Sources/Lyrebird/Generators/Math/Sign.swift @@ -10,20 +10,7 @@ /// /// - Parameter signal: Input signal. public enum Sign { - public class _Base: GeneratorBase { - let inputSource: any ValidGeneratorInput - let _mulAdd: MulAddSpec - public init( - _ signal: any ValidGeneratorInput, - mul: any ValidGeneratorInput = 1.0, - add: any ValidGeneratorInput = 0.0 - ) { - - let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput() - inputSource = resolvedSignal - _mulAdd = MulAddSpec(mul: mul, add: add) - } - } + public class _Base: UnaryMathBase {} @inline(__always) static func _sign(_ x: Double) -> Double { x < 0 ? -1 : (x > 0 ? 1 : 0) } /// - Parameters: /// - signal: Input signal. @@ -73,7 +60,7 @@ public enum Sign { ) -> [[Double]] { _checkCount(count) var target: Double = Sign._sign(inputSource.floatValue(graph: graph)) - if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Sin.swift b/Sources/Lyrebird/Generators/Math/Sin.swift index 09fde38..10f7b1b 100644 --- a/Sources/Lyrebird/Generators/Math/Sin.swift +++ b/Sources/Lyrebird/Generators/Math/Sin.swift @@ -13,20 +13,7 @@ import Foundation /// /// - Parameter signal: Input signal in radians. public enum Sin { - public class _Base: GeneratorBase { - let inputSource: any ValidGeneratorInput - let _mulAdd: MulAddSpec - public init( - _ signal: any ValidGeneratorInput, - mul: any ValidGeneratorInput = 1.0, - add: any ValidGeneratorInput = 0.0 - ) { - - let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput() - inputSource = resolvedSignal - _mulAdd = MulAddSpec(mul: mul, add: add) - } - } + public class _Base: UnaryMathBase {} /// - Parameters: /// - signal: Input signal in radians. /// - mul: Output multiplier. Defaults to `1.0`. @@ -74,7 +61,7 @@ public enum Sin { ) -> [[Double]] { _checkCount(count) var target: Double = Foundation.sin(inputSource.floatValue(graph: graph)) - if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/SoftClip.swift b/Sources/Lyrebird/Generators/Math/SoftClip.swift index 015183c..ec9071d 100644 --- a/Sources/Lyrebird/Generators/Math/SoftClip.swift +++ b/Sources/Lyrebird/Generators/Math/SoftClip.swift @@ -119,10 +119,7 @@ public enum SoftClip { let tanhDrive: Double = tanh(drive) let signal: Double = inputSource.floatValue(graph: graph) var target: Double = tanhDrive == 0 ? signal : tanh(signal * drive) / tanhDrive - if !_mulAdd.isIdentity { - target = target * _mulAdd.mulInput.floatValue(graph: graph) - + _mulAdd.addInput.floatValue(graph: graph) - } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Sqrt.swift b/Sources/Lyrebird/Generators/Math/Sqrt.swift index ef97b76..1230dc7 100644 --- a/Sources/Lyrebird/Generators/Math/Sqrt.swift +++ b/Sources/Lyrebird/Generators/Math/Sqrt.swift @@ -12,20 +12,7 @@ import Foundation /// /// - Parameter signal: Input signal. Negative input produces NaN. public enum Sqrt { - public class _Base: GeneratorBase { - let inputSource: any ValidGeneratorInput - let _mulAdd: MulAddSpec - public init( - _ signal: any ValidGeneratorInput, - mul: any ValidGeneratorInput = 1.0, - add: any ValidGeneratorInput = 0.0 - ) { - - let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput() - inputSource = resolvedSignal - _mulAdd = MulAddSpec(mul: mul, add: add) - } - } + public class _Base: UnaryMathBase {} /// - Parameters: /// - signal: Input signal. Negative input produces NaN. /// - mul: Output multiplier. Defaults to `1.0`. @@ -73,7 +60,7 @@ public enum Sqrt { ) -> [[Double]] { _checkCount(count) var target: Double = Foundation.sqrt(inputSource.floatValue(graph: graph)) - if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Tan.swift b/Sources/Lyrebird/Generators/Math/Tan.swift index 5b6b8bd..f3507ca 100644 --- a/Sources/Lyrebird/Generators/Math/Tan.swift +++ b/Sources/Lyrebird/Generators/Math/Tan.swift @@ -14,20 +14,7 @@ import Foundation /// /// - Parameter signal: Input signal in radians. public enum Tan { - public class _Base: GeneratorBase { - let inputSource: any ValidGeneratorInput - let _mulAdd: MulAddSpec - public init( - _ signal: any ValidGeneratorInput, - mul: any ValidGeneratorInput = 1.0, - add: any ValidGeneratorInput = 0.0 - ) { - - let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput() - inputSource = resolvedSignal - _mulAdd = MulAddSpec(mul: mul, add: add) - } - } + public class _Base: UnaryMathBase {} /// - Parameters: /// - signal: Input signal in radians. /// - mul: Output multiplier. Defaults to `1.0`. @@ -76,7 +63,7 @@ public enum Tan { ) -> [[Double]] { _checkCount(count) var target: Double = Foundation.tan(inputSource.floatValue(graph: graph)) - if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Tanh.swift b/Sources/Lyrebird/Generators/Math/Tanh.swift index a68d5b0..5ee6107 100644 --- a/Sources/Lyrebird/Generators/Math/Tanh.swift +++ b/Sources/Lyrebird/Generators/Math/Tanh.swift @@ -17,20 +17,7 @@ import Foundation /// ``` public enum Tanh { - public class _Base: GeneratorBase { - let inputSource: any ValidGeneratorInput - let _mulAdd: MulAddSpec - public init( - _ signal: any ValidGeneratorInput, - mul: any ValidGeneratorInput = 1.0, - add: any ValidGeneratorInput = 0.0 - ) { - - let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput() - inputSource = resolvedSignal - _mulAdd = MulAddSpec(mul: mul, add: add) - } - } + public class _Base: UnaryMathBase {} /// Audio-rate `tanh` waveshaper. /// @@ -93,10 +80,7 @@ public enum Tanh { ) -> [[Double]] { _checkCount(count) var target: Double = tanh(inputSource.floatValue(graph: graph)) - if !_mulAdd.isIdentity { - target = target * _mulAdd.mulInput.floatValue(graph: graph) - + _mulAdd.addInput.floatValue(graph: graph) - } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/UnaryMathBase.swift b/Sources/Lyrebird/Generators/Math/UnaryMathBase.swift new file mode 100644 index 0000000..47a1fb5 --- /dev/null +++ b/Sources/Lyrebird/Generators/Math/UnaryMathBase.swift @@ -0,0 +1,33 @@ +// UnaryMathBase.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// MARK: - UnaryMathBase + +/// Shared base for the single-input math operators (`Abs`, `Ceil`, `Floor`, `Round`, +/// `Sign`, `Sqrt`, `Log`, `Exp`, `Sin`, `Cos`, `Tan`, `Tanh`, `Reciprocal`, `DbAmp`). +/// +/// Holds the one resolved input and the `MulAddSpec`, mirroring `OscillatorBase` / +/// `NoiseBase`. Each operator's `_Base` is `public class _Base: UnaryMathBase {}`; its +/// `Audio` / `Control` subclasses override `init` to forward to this designated +/// initializer and supply the per-operator kernel in `_computeSamples`. +public class UnaryMathBase: GeneratorBase { + let inputSource: any ValidGeneratorInput + let _mulAdd: MulAddSpec + + /// - Parameters: + /// - signal: Input signal. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public init( + _ signal: any ValidGeneratorInput, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0 + ) { + let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput() + inputSource = resolvedSignal + _mulAdd = MulAddSpec(mul: mul, add: add) + } +} diff --git a/Sources/Lyrebird/Generators/Math/UnipolarRangeMapper.swift b/Sources/Lyrebird/Generators/Math/UnipolarRangeMapper.swift index c414441..2a6b585 100644 --- a/Sources/Lyrebird/Generators/Math/UnipolarRangeMapper.swift +++ b/Sources/Lyrebird/Generators/Math/UnipolarRangeMapper.swift @@ -162,10 +162,7 @@ public enum UnipolarRangeMapper { let high: Double = lastGeneratorSampleOrFloat(highInput, isGenerator: highIsGenerator, graph: graph, count: count) let t: Double = inputSource.floatValue(graph: graph) var target: Double = mapScalarRangeCurve(t: t, low: low, high: high, curve: curve) - if !_mulAdd.isIdentity { - target = target * _mulAdd.mulInput.floatValue(graph: graph) - + _mulAdd.addInput.floatValue(graph: graph) - } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Math/Wrap.swift b/Sources/Lyrebird/Generators/Math/Wrap.swift index fb0105b..b5637b0 100644 --- a/Sources/Lyrebird/Generators/Math/Wrap.swift +++ b/Sources/Lyrebird/Generators/Math/Wrap.swift @@ -129,10 +129,7 @@ public enum Wrap { let lo: Double = loInput.floatValue(graph: graph) let range: Double = hiInput.floatValue(graph: graph) - lo var target: Double = Wrap._wrap(inputSource.floatValue(graph: graph), lo: lo, range: range) - if !_mulAdd.isIdentity { - target = target * _mulAdd.mulInput.floatValue(graph: graph) - + _mulAdd.addInput.floatValue(graph: graph) - } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result } diff --git a/Sources/Lyrebird/Generators/Modulation/FrequencyShifter.swift b/Sources/Lyrebird/Generators/Modulation/FrequencyShifter.swift index db149b1..eee2115 100644 --- a/Sources/Lyrebird/Generators/Modulation/FrequencyShifter.swift +++ b/Sources/Lyrebird/Generators/Modulation/FrequencyShifter.swift @@ -128,15 +128,7 @@ public enum FrequencyShifter { let pathB: [Double] = hilbertRows[1] // Fetch shift frequency block (audio-rate or scalar). - let shiftSamples: [Double]? - let scalarShift: Double - if _shiftIsGenerator { - shiftSamples = _shiftSource.calculatedSamples(graph: graph, count: count).first - scalarShift = 0 - } else { - shiftSamples = nil - scalarShift = _shiftSource.floatValue(graph: graph) - } + let (shiftSamples, scalarShift) = resolveGeneratorOrScalar(_shiftSource, isGenerator: _shiftIsGenerator, graph: graph, count: count) for i: Int in 0.. [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Noise/ArcsinNoise.swift b/Sources/Lyrebird/Generators/Noise/ArcsinNoise.swift index c703cc8..dafa263 100644 --- a/Sources/Lyrebird/Generators/Noise/ArcsinNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/ArcsinNoise.swift @@ -70,7 +70,7 @@ public enum ArcsinNoise { /// - seed: PRNG seed. Defaults to a time-derived value. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -89,17 +89,9 @@ public enum ArcsinNoise { let controlMixConstant: UInt64 = 0x6677_8899_AABB_CCDD let state: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(dispersion: dispersion, initialRngState: state, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: ArcsinNoise.Control draws one new value per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Noise/BetaRandNoise.swift b/Sources/Lyrebird/Generators/Noise/BetaRandNoise.swift index 973e3b1..812a950 100644 --- a/Sources/Lyrebird/Generators/Noise/BetaRandNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/BetaRandNoise.swift @@ -98,7 +98,7 @@ public enum BetaRandNoise { /// - seed: PRNG seed. Defaults to a time-derived value. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -123,17 +123,9 @@ public enum BetaRandNoise { let controlMixConstant: UInt64 = 0xA5A5_5A5A_C3C3_3C3C let state: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(lo: lo, hi: hi, alpha: alpha, beta: beta, initialRngState: state, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: BetaRandNoise.Control draws one new value per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Noise/BrownNoise.swift b/Sources/Lyrebird/Generators/Noise/BrownNoise.swift index 59bcb84..2b8ceda 100644 --- a/Sources/Lyrebird/Generators/Noise/BrownNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/BrownNoise.swift @@ -105,7 +105,7 @@ public enum BrownNoise { /// - seed: PRNG seed. Defaults to a time-derived value. /// - mul: Output multiplier applied after synthesis. Defaults to `1.0`. /// - add: Offset added after multiplier. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -123,18 +123,9 @@ public enum BrownNoise { let controlMixConstant: UInt64 = 0xB4B4_B4B4_4B4B_4B4B let initialRngState: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(initialRngState: initialRngState, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: BrownNoise.Control advances the random walk once per audio block. - // Sub-blocking would draw N steps per block, changing the walk's effective step rate. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Noise/CauchyNoise.swift b/Sources/Lyrebird/Generators/Noise/CauchyNoise.swift index 6b01b57..71eb288 100644 --- a/Sources/Lyrebird/Generators/Noise/CauchyNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/CauchyNoise.swift @@ -85,7 +85,7 @@ public enum CauchyNoise { /// - seed: PRNG seed. Defaults to a time-derived value. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -108,17 +108,9 @@ public enum CauchyNoise { let controlMixConstant: UInt64 = 0xBBBB_AAAA_9999_8888 let state: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(mean: mean, spread: spread, posOnly: posOnly, initialRngState: state, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: CauchyNoise.Control draws one new value per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Noise/ClipNoise.swift b/Sources/Lyrebird/Generators/Noise/ClipNoise.swift index d7e1e72..f7ca3cd 100644 --- a/Sources/Lyrebird/Generators/Noise/ClipNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/ClipNoise.swift @@ -95,7 +95,7 @@ public enum ClipNoise { /// - seed: PRNG seed. Defaults to a time-derived value. /// - mul: Output multiplier applied after synthesis. Defaults to `1.0`. /// - add: Offset added after multiplier. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -113,18 +113,9 @@ public enum ClipNoise { let controlMixConstant: UInt64 = 0xD2D2_D2D2_2D2D_2D2D let initialRngState: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(initialRngState: initialRngState, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: ClipNoise.Control draws one sign value per audio block. - // Sub-blocking would draw N values per block, changing its update rate to sampleRate/cbs. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Noise/Crackle.swift b/Sources/Lyrebird/Generators/Noise/Crackle.swift index 6dc931c..a2529ea 100644 --- a/Sources/Lyrebird/Generators/Noise/Crackle.swift +++ b/Sources/Lyrebird/Generators/Noise/Crackle.swift @@ -111,7 +111,7 @@ public enum Crackle { /// let crackle = Crackle.Control() /// let filter = RBJLowPass.Audio(input: signal, freq: crackle * 400.0 + 800.0, q: 0.707) /// ``` - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -127,18 +127,9 @@ public enum Crackle { ) { super.init(chaos: chaos, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: Crackle.Control advances the chaotic map once per audio block. - // Sub-blocking would advance the map N times per block, running the LFO N× too fast. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Noise/Dust.swift b/Sources/Lyrebird/Generators/Noise/Dust.swift index a0810d4..324456f 100644 --- a/Sources/Lyrebird/Generators/Noise/Dust.swift +++ b/Sources/Lyrebird/Generators/Noise/Dust.swift @@ -101,7 +101,7 @@ public enum Dust { /// - seed: PRNG seed. Defaults to a time-derived value. /// - mul: Output multiplier applied after synthesis. Defaults to `1.0`. /// - add: Offset added after multiplier. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { private let densityIsGenerator: Bool public var previousOutputValue: Double = 0.0 @@ -126,18 +126,9 @@ public enum Dust { let controlMixConstant: UInt64 = 0xE1E1_E1E1_1E1E_1E1E let initialRngState: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(density: resolvedDensity, initialRngState: initialRngState, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: Dust.Control draws one impulse-or-zero per audio block. - // Sub-blocking would draw N samples per block, changing its firing rate. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -145,12 +136,7 @@ public enum Dust { ) -> [[Double]] { _checkCount(count) let sampleRate: Double = graph.engine.sampleRate - let density: Double - if densityIsGenerator { - density = densityInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - density = densityInput.floatValue(graph: graph) - } + let density: Double = firstGeneratorSampleOrFloat(densityInput, isGenerator: densityIsGenerator, graph: graph, count: count) let threshold: Double = density / sampleRate let raw: UInt64 = xorshift64NextRaw(&rngState) let u: Double = Double(raw) * dustUnipolarScale diff --git a/Sources/Lyrebird/Generators/Noise/Dust2.swift b/Sources/Lyrebird/Generators/Noise/Dust2.swift index 4a4afbb..f0b41c5 100644 --- a/Sources/Lyrebird/Generators/Noise/Dust2.swift +++ b/Sources/Lyrebird/Generators/Noise/Dust2.swift @@ -104,7 +104,7 @@ public enum Dust2 { /// - seed: PRNG seed. Defaults to a time-derived value. /// - mul: Output multiplier applied after synthesis. Defaults to `1.0`. /// - add: Offset added after multiplier. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { private let densityIsGenerator: Bool public var previousOutputValue: Double = 0.0 @@ -128,18 +128,9 @@ public enum Dust2 { let controlMixConstant: UInt64 = 0xF0F0_F0F0_0F0F_0F0F let initialRngState: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(density: resolvedDensity, initialRngState: initialRngState, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: Dust2.Control draws one impulse-or-zero per audio block. - // Sub-blocking would draw N samples per block, changing its firing rate. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -147,12 +138,7 @@ public enum Dust2 { ) -> [[Double]] { _checkCount(count) let sampleRate: Double = graph.engine.sampleRate - let density: Double - if densityIsGenerator { - density = densityInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - density = densityInput.floatValue(graph: graph) - } + let density: Double = firstGeneratorSampleOrFloat(densityInput, isGenerator: densityIsGenerator, graph: graph, count: count) let threshold: Double = density / sampleRate let raw: UInt64 = xorshift64NextRaw(&rngState) let u: Double = Double(raw) * dustUnipolarScale diff --git a/Sources/Lyrebird/Generators/Noise/ExpRandNoise.swift b/Sources/Lyrebird/Generators/Noise/ExpRandNoise.swift index 7a01ca7..7a562e0 100644 --- a/Sources/Lyrebird/Generators/Noise/ExpRandNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/ExpRandNoise.swift @@ -77,7 +77,7 @@ public enum ExpRandNoise { /// - seed: PRNG seed. Defaults to a time-derived value. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -98,17 +98,9 @@ public enum ExpRandNoise { let controlMixConstant: UInt64 = 0x8888_9999_AAAA_BBBB let state: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(lo: lo, hi: hi, initialRngState: state, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: ExpRandNoise.Control draws one new value per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Noise/ExponentialNoise.swift b/Sources/Lyrebird/Generators/Noise/ExponentialNoise.swift index 1992c04..73a00c9 100644 --- a/Sources/Lyrebird/Generators/Noise/ExponentialNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/ExponentialNoise.swift @@ -66,7 +66,7 @@ public enum ExponentialNoise { /// - seed: PRNG seed. Defaults to a time-derived value. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -84,17 +84,9 @@ public enum ExponentialNoise { let state: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: 0xBBBB_CCCC_DDDD_EEEE) super.init(density: density, initialRngState: state, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: ExponentialNoise.Control draws one new value per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Noise/GammaNoise.swift b/Sources/Lyrebird/Generators/Noise/GammaNoise.swift index 88b000d..d037dbc 100644 --- a/Sources/Lyrebird/Generators/Noise/GammaNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/GammaNoise.swift @@ -70,7 +70,7 @@ public enum GammaNoise { /// - seed: PRNG seed. Defaults to a time-derived value. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -89,17 +89,9 @@ public enum GammaNoise { let controlMixConstant: UInt64 = 0xDEAD_1234_CAFE_5678 let state: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(shape: shape, initialRngState: state, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: GammaNoise.Control draws one new value per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Noise/GaussNoise.swift b/Sources/Lyrebird/Generators/Noise/GaussNoise.swift index f89d575..d142278 100644 --- a/Sources/Lyrebird/Generators/Noise/GaussNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/GaussNoise.swift @@ -79,7 +79,7 @@ public enum GaussNoise { /// - seed: PRNG seed. Defaults to a time-derived value. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -100,17 +100,9 @@ public enum GaussNoise { let controlMixConstant: UInt64 = 0xAAAA_BBBB_CCCC_DDDD let state: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(dev: dev, mean: mean, initialRngState: state, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: GaussNoise.Control draws one new value per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Noise/GrayNoise.swift b/Sources/Lyrebird/Generators/Noise/GrayNoise.swift index bef866b..e8a68ef 100644 --- a/Sources/Lyrebird/Generators/Noise/GrayNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/GrayNoise.swift @@ -117,7 +117,7 @@ public enum GrayNoise { /// - seed: PRNG seed. Defaults to a time-derived value. /// - mul: Output multiplier applied after synthesis. Defaults to `1.0`. /// - add: Offset added after multiplier. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -135,18 +135,9 @@ public enum GrayNoise { let controlMixConstant: UInt64 = 0xC3C3_C3C3_3C3C_3C3C let initialRngState: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(initialRngState: initialRngState, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: GrayNoise.Control flips one counter bit per audio block. - // Sub-blocking would flip N bits per block, changing the counter update rate. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Noise/HcosNoise.swift b/Sources/Lyrebird/Generators/Noise/HcosNoise.swift index a1f5fe1..ff4a8b2 100644 --- a/Sources/Lyrebird/Generators/Noise/HcosNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/HcosNoise.swift @@ -69,7 +69,7 @@ public enum HcosNoise { /// - seed: PRNG seed. Defaults to a time-derived value. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -88,17 +88,9 @@ public enum HcosNoise { let controlMixConstant: UInt64 = 0x1829_3A4B_5C6D_7E8F let state: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(dispersion: dispersion, initialRngState: state, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: HcosNoise.Control draws one new value per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Noise/HpRandNoise.swift b/Sources/Lyrebird/Generators/Noise/HpRandNoise.swift index e6f8ef8..26a443d 100644 --- a/Sources/Lyrebird/Generators/Noise/HpRandNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/HpRandNoise.swift @@ -78,7 +78,7 @@ public enum HpRandNoise { /// - seed: PRNG seed. Defaults to a time-derived value for unique instances. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -99,17 +99,9 @@ public enum HpRandNoise { let controlMixConstant: UInt64 = 0x0246_8ACE_1357_9BDF let state: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(lo: lo, hi: hi, initialRngState: state, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: HpRandNoise.Control draws one new value per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Noise/LFCurveNoise.swift b/Sources/Lyrebird/Generators/Noise/LFCurveNoise.swift index bac558e..85161be 100644 --- a/Sources/Lyrebird/Generators/Noise/LFCurveNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/LFCurveNoise.swift @@ -206,12 +206,7 @@ public enum LFCurveNoise { let countFloat: Double = Double(count) let sampleRate: Double = Double(graph.engine.sampleRate) - let freq: Double - if freqIsGenerator { - freq = freqInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - freq = freqInput.floatValue(graph: graph) - } + let freq: Double = firstGeneratorSampleOrFloat(freqInput, isGenerator: freqIsGenerator, graph: graph, count: count) let safeFreq: Double = max(0.0, freq) phase += safeFreq * countFloat / sampleRate diff --git a/Sources/Lyrebird/Generators/Noise/LFLineNoise.swift b/Sources/Lyrebird/Generators/Noise/LFLineNoise.swift index 522b948..07c6b17 100644 --- a/Sources/Lyrebird/Generators/Noise/LFLineNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/LFLineNoise.swift @@ -182,12 +182,7 @@ public enum LFLineNoise { let countFloat: Double = Double(count) let sampleRate: Double = Double(graph.engine.sampleRate) - let freq: Double - if freqIsGenerator { - freq = freqInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - freq = freqInput.floatValue(graph: graph) - } + let freq: Double = firstGeneratorSampleOrFloat(freqInput, isGenerator: freqIsGenerator, graph: graph, count: count) let safeFreq: Double = max(0.0, freq) phase += safeFreq * countFloat / sampleRate diff --git a/Sources/Lyrebird/Generators/Noise/LFStepNoise.swift b/Sources/Lyrebird/Generators/Noise/LFStepNoise.swift index 244db5f..efdb350 100644 --- a/Sources/Lyrebird/Generators/Noise/LFStepNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/LFStepNoise.swift @@ -172,12 +172,7 @@ public enum LFStepNoise { let countFloat: Double = Double(count) let sampleRate: Double = Double(graph.engine.sampleRate) - let freq: Double - if freqIsGenerator { - freq = freqInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - freq = freqInput.floatValue(graph: graph) - } + let freq: Double = firstGeneratorSampleOrFloat(freqInput, isGenerator: freqIsGenerator, graph: graph, count: count) let safeFreq: Double = max(0.0, freq) phase += safeFreq * countFloat / sampleRate diff --git a/Sources/Lyrebird/Generators/Noise/LaplaceNoise.swift b/Sources/Lyrebird/Generators/Noise/LaplaceNoise.swift index e56a05f..2a29957 100644 --- a/Sources/Lyrebird/Generators/Noise/LaplaceNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/LaplaceNoise.swift @@ -69,7 +69,7 @@ public enum LaplaceNoise { /// - seed: PRNG seed. Defaults to a time-derived value. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -88,17 +88,9 @@ public enum LaplaceNoise { let controlMixConstant: UInt64 = 0x9C8D_7E6F_5A4B_3C2D let state: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(dispersion: dispersion, initialRngState: state, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: LaplaceNoise.Control draws one new value per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Noise/LogisticNoise.swift b/Sources/Lyrebird/Generators/Noise/LogisticNoise.swift index 1b272cc..d2531a7 100644 --- a/Sources/Lyrebird/Generators/Noise/LogisticNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/LogisticNoise.swift @@ -69,7 +69,7 @@ public enum LogisticNoise { /// - seed: PRNG seed. Defaults to a time-derived value. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -88,17 +88,9 @@ public enum LogisticNoise { let controlMixConstant: UInt64 = 0xFEED_FACE_BABE_1234 let state: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(dispersion: dispersion, initialRngState: state, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: LogisticNoise.Control draws one new value per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Noise/LpRandNoise.swift b/Sources/Lyrebird/Generators/Noise/LpRandNoise.swift index 70d11ce..a95963d 100644 --- a/Sources/Lyrebird/Generators/Noise/LpRandNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/LpRandNoise.swift @@ -78,7 +78,7 @@ public enum LpRandNoise { /// - seed: PRNG seed. Defaults to a time-derived value for unique instances. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -103,17 +103,9 @@ public enum LpRandNoise { let controlMixConstant: UInt64 = 0xFEDC_BA98_7654_3210 let state: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(lo: lo, hi: hi, initialRngState: state, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: LpRandNoise.Control draws one new value per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Noise/MeanRandNoise.swift b/Sources/Lyrebird/Generators/Noise/MeanRandNoise.swift index fd107cc..9cf7c10 100644 --- a/Sources/Lyrebird/Generators/Noise/MeanRandNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/MeanRandNoise.swift @@ -79,7 +79,7 @@ public enum MeanRandNoise { /// - seed: PRNG seed. Defaults to a time-derived value for unique instances. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -100,17 +100,9 @@ public enum MeanRandNoise { let controlMixConstant: UInt64 = 0xC3C3_3C3C_A5A5_5A5A let state: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(lo: lo, hi: hi, initialRngState: state, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: MeanRandNoise.Control draws one new value per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Noise/PinkNoise.swift b/Sources/Lyrebird/Generators/Noise/PinkNoise.swift index 739269c..cb7b302 100644 --- a/Sources/Lyrebird/Generators/Noise/PinkNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/PinkNoise.swift @@ -136,7 +136,7 @@ public enum PinkNoise { /// - seed: PRNG seed. Defaults to a time-derived value. /// - mul: Output multiplier applied after synthesis. Defaults to `1.0`. /// - add: Offset added after multiplier. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -154,18 +154,9 @@ public enum PinkNoise { let controlMixConstant: UInt64 = 0x9696_9696_6969_6969 let initialRngState: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(initialRngState: initialRngState, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: PinkNoise.Control advances the IIR filter once per audio block. - // Sub-blocking would advance the filter N times per block, changing its spectral character. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Noise/PoissonNoise.swift b/Sources/Lyrebird/Generators/Noise/PoissonNoise.swift index e472dda..507e6aa 100644 --- a/Sources/Lyrebird/Generators/Noise/PoissonNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/PoissonNoise.swift @@ -70,7 +70,7 @@ public enum PoissonNoise { /// - seed: PRNG seed. Defaults to a time-derived value. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -89,17 +89,9 @@ public enum PoissonNoise { let controlMixConstant: UInt64 = 0xEEEE_FFFF_0000_1111 let state: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(mean: mean, initialRngState: state, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: PoissonNoise.Control draws one new value per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Noise/UniformNoise.swift b/Sources/Lyrebird/Generators/Noise/UniformNoise.swift index 1a91139..bd20ffb 100644 --- a/Sources/Lyrebird/Generators/Noise/UniformNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/UniformNoise.swift @@ -79,7 +79,7 @@ public enum UniformNoise { /// - seed: PRNG seed. Defaults to a time-derived value for unique instances. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -100,17 +100,9 @@ public enum UniformNoise { let controlMixConstant: UInt64 = 0x5555_CCCC_6666_DDDD let state: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(lo: lo, hi: hi, initialRngState: state, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: UniformNoise.Control draws one new value per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Noise/WhiteNoise.swift b/Sources/Lyrebird/Generators/Noise/WhiteNoise.swift index 9654977..5a9855a 100644 --- a/Sources/Lyrebird/Generators/Noise/WhiteNoise.swift +++ b/Sources/Lyrebird/Generators/Noise/WhiteNoise.swift @@ -122,7 +122,7 @@ public enum WhiteNoise { /// output when both are constructed within the same nanosecond. /// - mul: Output multiplier applied after synthesis. Defaults to `1.0`. /// - add: Offset added after multiplier. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { // MARK: - Fan-out cache (Generator protocol requirements) @@ -143,18 +143,9 @@ public enum WhiteNoise { let controlMixConstant: UInt64 = 0xA5A5_A5A5_A5A5_A5A5 let initialRngState: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(initialRngState: initialRngState, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: WhiteNoise.Control draws one new random value per audio block. - // Sub-blocking would draw N values per block, changing its update rate to sampleRate/cbs. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Oscillators/Impulse.swift b/Sources/Lyrebird/Generators/Oscillators/Impulse.swift index f06f69d..f8423bc 100644 --- a/Sources/Lyrebird/Generators/Oscillators/Impulse.swift +++ b/Sources/Lyrebird/Generators/Oscillators/Impulse.swift @@ -127,20 +127,13 @@ public enum Impulse { /// - initPhase: Starting phase in `[0, 1)`. `0.0` fires at the very first block. /// - mul: Output multiplier applied after synthesis. Defaults to `1.0`. /// - add: Offset added after multiplier. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { // MARK: - Fan-out cache (Generator protocol requirements) public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 - // Bypass sub-block loop: phase must advance exactly once per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } /// - Parameters: /// - freq: Frequency in Hz — rate at which impulses fire. Must be > 0. No internal clamping. @@ -155,7 +148,6 @@ public enum Impulse { ) { super.init(freq: freq, initPhase: initPhase, mul: mul, add: add) - _setupSubBlockBuffer() } @@ -168,12 +160,7 @@ public enum Impulse { let countFloat: Double = Double(count) let sampleRate: Double = Double(graph.engine.sampleRate) - let freq: Double - if _freqIsGenerator { - freq = _freqInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - freq = _freqInput.floatValue(graph: graph) - } + let freq: Double = firstGeneratorSampleOrFloat(_freqInput, isGenerator: _freqIsGenerator, graph: graph, count: count) _phase += freq * countFloat / sampleRate let fired: Bool = _phase >= 1.0 diff --git a/Sources/Lyrebird/Generators/Oscillators/LFDutyCycle.swift b/Sources/Lyrebird/Generators/Oscillators/LFDutyCycle.swift index 0001ed5..5403b69 100644 --- a/Sources/Lyrebird/Generators/Oscillators/LFDutyCycle.swift +++ b/Sources/Lyrebird/Generators/Oscillators/LFDutyCycle.swift @@ -119,12 +119,7 @@ public enum LFDutyCycle { _result[0][i] = _phase < duty ? 1.0 : -1.0 _phase += dt - if _phase >= 1.0 { _phase -= 1.0 } - else if _phase < 0.0 { _phase += 1.0 } - if _phase >= 1.0 || _phase < 0.0 { - _phase = _phase.truncatingRemainder(dividingBy: 1.0) - if _phase < 0.0 { _phase += 1.0 } - } + wrapUnitPhase(&_phase) } _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) @@ -136,7 +131,7 @@ public enum LFDutyCycle { /// Control-rate non-band-limited variable duty-cycle pulse LFO. Advances phase once per audio block. /// - /// Override `calculatedSamples` bypasses the sub-block loop — phase must advance exactly + /// Conforming to `BlockRateControlGenerator` bypasses the sub-block loop — phase must advance exactly /// once per audio block regardless of `controlBlockSize`. /// /// - Parameters: @@ -145,7 +140,7 @@ public enum LFDutyCycle { /// - phase: Initial phase offset in normalized cycles `[0, 1)`. Defaults to `0.0`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -164,17 +159,9 @@ public enum LFDutyCycle { add: any ValidGeneratorInput = 0.0 ) { super.init(freq: freq, dutyCycle: dutyCycle, phase: phase, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: phase must advance exactly once per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -185,19 +172,9 @@ public enum LFDutyCycle { let sampleRate: Double = Double(graph.engine.sampleRate) let countFloat: Double = Double(count) - let freq: Double - if _freqIsGenerator { - freq = _freqInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - freq = _freqInput.floatValue(graph: graph) - } + let freq: Double = firstGeneratorSampleOrFloat(_freqInput, isGenerator: _freqIsGenerator, graph: graph, count: count) - let rawDuty: Double - if _dutyCycleIsGenerator { - rawDuty = _dutyCycleInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - rawDuty = _dutyCycleInput.floatValue(graph: graph) - } + let rawDuty: Double = firstGeneratorSampleOrFloat(_dutyCycleInput, isGenerator: _dutyCycleIsGenerator, graph: graph, count: count) let duty: Double = min(max(rawDuty, 0.0), 1.0) let dt: Double = freq / sampleRate diff --git a/Sources/Lyrebird/Generators/Oscillators/LFGauss.swift b/Sources/Lyrebird/Generators/Oscillators/LFGauss.swift index 8092b4d..330455c 100644 --- a/Sources/Lyrebird/Generators/Oscillators/LFGauss.swift +++ b/Sources/Lyrebird/Generators/Oscillators/LFGauss.swift @@ -158,7 +158,7 @@ public enum LFGauss { /// Control-rate Gaussian oscillator. Advances phase once per audio block. /// - /// Override `calculatedSamples` bypasses the sub-block loop — phase must advance exactly + /// Conforming to `BlockRateControlGenerator` bypasses the sub-block loop — phase must advance exactly /// once per audio block regardless of `controlBlockSize`. The block output ramps from the /// previous bell value to the new one. /// @@ -168,7 +168,7 @@ public enum LFGauss { /// - phase: Initial phase offset in normalized cycles `[0, 1)`. `0` starts at a trough. Defaults to `0.0`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -187,13 +187,8 @@ public enum LFGauss { add: any ValidGeneratorInput = 0.0 ) { super.init(period: period, width: width, phase: phase, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: phase must advance exactly once per audio block. - public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) diff --git a/Sources/Lyrebird/Generators/Oscillators/LFOscillatorHelpers.swift b/Sources/Lyrebird/Generators/Oscillators/LFOscillatorHelpers.swift index 0b938ad..23cc45d 100644 --- a/Sources/Lyrebird/Generators/Oscillators/LFOscillatorHelpers.swift +++ b/Sources/Lyrebird/Generators/Oscillators/LFOscillatorHelpers.swift @@ -13,5 +13,6 @@ let lfHalfPhase: Double = 0.5 /// Amplitude spans 2 over a half period (0.5), so slope = 2 / 0.5 = 4. let lfTriangleSlope: Double = 4.0 -// Phase normalisation is provided by `normalizeOscPhase` in OscBandLimitedHelpers.swift, -// shared by all LF and band-limited oscillators. +// Phase normalisation is provided by `normalizeOscPhase` (block-rate increment) and +// `wrapUnitPhase` (per-sample increment, handles a negative step) in +// OscBandLimitedHelpers.swift, shared by all LF and band-limited oscillators. diff --git a/Sources/Lyrebird/Generators/Oscillators/LFSawtooth.swift b/Sources/Lyrebird/Generators/Oscillators/LFSawtooth.swift index 7290d4b..7a80bfd 100644 --- a/Sources/Lyrebird/Generators/Oscillators/LFSawtooth.swift +++ b/Sources/Lyrebird/Generators/Oscillators/LFSawtooth.swift @@ -77,12 +77,7 @@ public enum LFSawtooth { _result[0][i] = 2.0 * _phase - 1.0 _phase += dt - if _phase >= 1.0 { _phase -= 1.0 } - else if _phase < 0.0 { _phase += 1.0 } - if _phase >= 1.0 || _phase < 0.0 { - _phase = _phase.truncatingRemainder(dividingBy: 1.0) - if _phase < 0.0 { _phase += 1.0 } - } + wrapUnitPhase(&_phase) } _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) @@ -94,7 +89,7 @@ public enum LFSawtooth { /// Control-rate non-band-limited sawtooth LFO. Advances phase once per audio block. /// - /// Override `calculatedSamples` bypasses the sub-block loop — phase must advance exactly + /// Conforming to `BlockRateControlGenerator` bypasses the sub-block loop — phase must advance exactly /// once per audio block regardless of `controlBlockSize`. /// /// - Parameters: @@ -102,7 +97,7 @@ public enum LFSawtooth { /// - phase: Initial phase offset in normalized cycles `[0, 1)`. Defaults to `0.0`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -119,17 +114,9 @@ public enum LFSawtooth { add: any ValidGeneratorInput = 0.0 ) { super.init(freq: freq, phase: phase, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: phase must advance exactly once per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -140,12 +127,7 @@ public enum LFSawtooth { let sampleRate: Double = Double(graph.engine.sampleRate) let countFloat: Double = Double(count) - let freq: Double - if _freqIsGenerator { - freq = _freqInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - freq = _freqInput.floatValue(graph: graph) - } + let freq: Double = firstGeneratorSampleOrFloat(_freqInput, isGenerator: _freqIsGenerator, graph: graph, count: count) let dt: Double = freq / sampleRate _phase += dt * countFloat diff --git a/Sources/Lyrebird/Generators/Oscillators/LFSquare.swift b/Sources/Lyrebird/Generators/Oscillators/LFSquare.swift index d404b4f..954d7ed 100644 --- a/Sources/Lyrebird/Generators/Oscillators/LFSquare.swift +++ b/Sources/Lyrebird/Generators/Oscillators/LFSquare.swift @@ -77,12 +77,7 @@ public enum LFSquare { _result[0][i] = _phase < lfHalfPhase ? 1.0 : -1.0 _phase += dt - if _phase >= 1.0 { _phase -= 1.0 } - else if _phase < 0.0 { _phase += 1.0 } - if _phase >= 1.0 || _phase < 0.0 { - _phase = _phase.truncatingRemainder(dividingBy: 1.0) - if _phase < 0.0 { _phase += 1.0 } - } + wrapUnitPhase(&_phase) } _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) @@ -94,7 +89,7 @@ public enum LFSquare { /// Control-rate non-band-limited square wave LFO. Advances phase once per audio block. /// - /// Override `calculatedSamples` bypasses the sub-block loop — phase must advance exactly + /// Conforming to `BlockRateControlGenerator` bypasses the sub-block loop — phase must advance exactly /// once per audio block regardless of `controlBlockSize`. /// /// - Parameters: @@ -102,7 +97,7 @@ public enum LFSquare { /// - phase: Initial phase offset in normalized cycles `[0, 1)`. Defaults to `0.0`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -119,17 +114,9 @@ public enum LFSquare { add: any ValidGeneratorInput = 0.0 ) { super.init(freq: freq, phase: phase, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: phase must advance exactly once per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -140,12 +127,7 @@ public enum LFSquare { let sampleRate: Double = Double(graph.engine.sampleRate) let countFloat: Double = Double(count) - let freq: Double - if _freqIsGenerator { - freq = _freqInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - freq = _freqInput.floatValue(graph: graph) - } + let freq: Double = firstGeneratorSampleOrFloat(_freqInput, isGenerator: _freqIsGenerator, graph: graph, count: count) let dt: Double = freq / sampleRate _phase += dt * countFloat diff --git a/Sources/Lyrebird/Generators/Oscillators/LFTriangle.swift b/Sources/Lyrebird/Generators/Oscillators/LFTriangle.swift index d311c8e..28f0455 100644 --- a/Sources/Lyrebird/Generators/Oscillators/LFTriangle.swift +++ b/Sources/Lyrebird/Generators/Oscillators/LFTriangle.swift @@ -84,12 +84,7 @@ public enum LFTriangle { } _phase += dt - if _phase >= 1.0 { _phase -= 1.0 } - else if _phase < 0.0 { _phase += 1.0 } - if _phase >= 1.0 || _phase < 0.0 { - _phase = _phase.truncatingRemainder(dividingBy: 1.0) - if _phase < 0.0 { _phase += 1.0 } - } + wrapUnitPhase(&_phase) } _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) @@ -101,7 +96,7 @@ public enum LFTriangle { /// Control-rate non-band-limited triangle wave LFO. Advances phase once per audio block. /// - /// Override `calculatedSamples` bypasses the sub-block loop — phase must advance exactly + /// Conforming to `BlockRateControlGenerator` bypasses the sub-block loop — phase must advance exactly /// once per audio block regardless of `controlBlockSize`. /// /// - Parameters: @@ -109,7 +104,7 @@ public enum LFTriangle { /// - phase: Initial phase offset in normalized cycles `[0, 1)`. Defaults to `0.0`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -126,17 +121,9 @@ public enum LFTriangle { add: any ValidGeneratorInput = 0.0 ) { super.init(freq: freq, phase: phase, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: phase must advance exactly once per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -147,12 +134,7 @@ public enum LFTriangle { let sampleRate: Double = Double(graph.engine.sampleRate) let countFloat: Double = Double(count) - let freq: Double - if _freqIsGenerator { - freq = _freqInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - freq = _freqInput.floatValue(graph: graph) - } + let freq: Double = firstGeneratorSampleOrFloat(_freqInput, isGenerator: _freqIsGenerator, graph: graph, count: count) let dt: Double = freq / sampleRate _phase += dt * countFloat diff --git a/Sources/Lyrebird/Generators/Oscillators/OscBandLimitedHelpers.swift b/Sources/Lyrebird/Generators/Oscillators/OscBandLimitedHelpers.swift index 36ec6e5..8bb78b6 100644 --- a/Sources/Lyrebird/Generators/Oscillators/OscBandLimitedHelpers.swift +++ b/Sources/Lyrebird/Generators/Oscillators/OscBandLimitedHelpers.swift @@ -82,3 +82,21 @@ func normalizeOscPhase(_ phase: inout Double) { if phase < 0 { phase += 1.0 } } } + +/// Wraps `phase` back into `[0, 1)` after a **per-sample** increment. +/// +/// Unlike `normalizeOscPhase` (block path, increment always positive), the +/// per-sample increment can be negative — FM or a negative-frequency input can +/// push phase below zero — so the fast path has both a `-= 1.0` and an +/// `else if … += 1.0` branch before the `truncatingRemainder` slow path handles +/// extreme excursions. Keeps the exact branch shape the oscillator inner loops +/// used inline, so output is bit-identical and the common case stays branch-cheap. +@inline(__always) +func wrapUnitPhase(_ phase: inout Double) { + if phase >= 1.0 { phase -= 1.0 } + else if phase < 0.0 { phase += 1.0 } + if phase >= 1.0 || phase < 0.0 { + phase = phase.truncatingRemainder(dividingBy: 1.0) + if phase < 0.0 { phase += 1.0 } + } +} diff --git a/Sources/Lyrebird/Generators/Oscillators/OscDutyCycle.swift b/Sources/Lyrebird/Generators/Oscillators/OscDutyCycle.swift index f09d165..64c6924 100644 --- a/Sources/Lyrebird/Generators/Oscillators/OscDutyCycle.swift +++ b/Sources/Lyrebird/Generators/Oscillators/OscDutyCycle.swift @@ -136,12 +136,7 @@ public enum OscDutyCycle { _result[0][i] = rawPulse + blepRising - blepFalling _phase += dt - if _phase >= 1.0 { _phase -= 1.0 } - else if _phase < 0.0 { _phase += 1.0 } - if _phase >= 1.0 || _phase < 0.0 { - _phase = _phase.truncatingRemainder(dividingBy: 1.0) - if _phase < 0.0 { _phase += 1.0 } - } + wrapUnitPhase(&_phase) } _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) @@ -159,7 +154,7 @@ public enum OscDutyCycle { /// - phase: Initial phase offset in cycles `[0, 1)`. Defaults to `0.0`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -178,17 +173,9 @@ public enum OscDutyCycle { add: any ValidGeneratorInput = 0.0 ) { super.init(freq: freq, dutyCycle: dutyCycle, phase: phase, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: phase must advance exactly once per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -199,19 +186,9 @@ public enum OscDutyCycle { let sampleRate: Double = Double(graph.engine.sampleRate) let countFloat: Double = Double(count) - let freq: Double - if _freqIsGenerator { - freq = _freqInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - freq = _freqInput.floatValue(graph: graph) - } + let freq: Double = firstGeneratorSampleOrFloat(_freqInput, isGenerator: _freqIsGenerator, graph: graph, count: count) - let rawDuty: Double - if _dutyCycleIsGenerator { - rawDuty = _dutyCycleInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - rawDuty = _dutyCycleInput.floatValue(graph: graph) - } + let rawDuty: Double = firstGeneratorSampleOrFloat(_dutyCycleInput, isGenerator: _dutyCycleIsGenerator, graph: graph, count: count) let duty: Double = min(max(rawDuty, 0.0), 1.0) let dt: Double = freq / sampleRate diff --git a/Sources/Lyrebird/Generators/Oscillators/OscSawtooth.swift b/Sources/Lyrebird/Generators/Oscillators/OscSawtooth.swift index c43c127..c07555c 100644 --- a/Sources/Lyrebird/Generators/Oscillators/OscSawtooth.swift +++ b/Sources/Lyrebird/Generators/Oscillators/OscSawtooth.swift @@ -85,12 +85,7 @@ public enum OscSawtooth { _result[0][i] = rawSaw - blep _phase += dt - if _phase >= 1.0 { _phase -= 1.0 } - else if _phase < 0.0 { _phase += 1.0 } - if _phase >= 1.0 || _phase < 0.0 { - _phase = _phase.truncatingRemainder(dividingBy: 1.0) - if _phase < 0.0 { _phase += 1.0 } - } + wrapUnitPhase(&_phase) } _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) @@ -102,7 +97,7 @@ public enum OscSawtooth { /// Control-rate band-limited sawtooth oscillator. Advances phase once per block. /// - /// Override `calculatedSamples` bypasses sub-block loop — phase must advance exactly + /// Conforming to `BlockRateControlGenerator` bypasses the sub-block loop — phase must advance exactly /// once per audio block regardless of `controlBlockSize`. /// /// - Parameters: @@ -110,7 +105,7 @@ public enum OscSawtooth { /// - phase: Initial phase offset in cycles `[0, 1)`. Defaults to `0.0`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -127,17 +122,9 @@ public enum OscSawtooth { add: any ValidGeneratorInput = 0.0 ) { super.init(freq: freq, phase: phase, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: phase must advance exactly once per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -148,12 +135,7 @@ public enum OscSawtooth { let sampleRate: Double = Double(graph.engine.sampleRate) let countFloat: Double = Double(count) - let freq: Double - if _freqIsGenerator { - freq = _freqInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - freq = _freqInput.floatValue(graph: graph) - } + let freq: Double = firstGeneratorSampleOrFloat(_freqInput, isGenerator: _freqIsGenerator, graph: graph, count: count) let dt: Double = freq / sampleRate _phase += dt * countFloat diff --git a/Sources/Lyrebird/Generators/Oscillators/OscSin.swift b/Sources/Lyrebird/Generators/Oscillators/OscSin.swift index 3b2de52..a74c722 100644 --- a/Sources/Lyrebird/Generators/Oscillators/OscSin.swift +++ b/Sources/Lyrebird/Generators/Oscillators/OscSin.swift @@ -326,12 +326,7 @@ public enum OscSin { let countFloat: Double = Double(count) let sampleRate: Double = Double(graph.engine.sampleRate) - let freq: Double - if _freqIsGenerator { - freq = _freqInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - freq = _freqInput.floatValue(graph: graph) - } + let freq: Double = firstGeneratorSampleOrFloat(_freqInput, isGenerator: _freqIsGenerator, graph: graph, count: count) _phase += freq * tableSizeFloat * countFloat / sampleRate if _phase >= tableSizeFloat { _phase -= tableSizeFloat } diff --git a/Sources/Lyrebird/Generators/Oscillators/OscSquare.swift b/Sources/Lyrebird/Generators/Oscillators/OscSquare.swift index adc9042..3fbacf5 100644 --- a/Sources/Lyrebird/Generators/Oscillators/OscSquare.swift +++ b/Sources/Lyrebird/Generators/Oscillators/OscSquare.swift @@ -89,12 +89,7 @@ public enum OscSquare { _result[0][i] = rawSquare + blepRising - blepFalling _phase += dt - if _phase >= 1.0 { _phase -= 1.0 } - else if _phase < 0.0 { _phase += 1.0 } - if _phase >= 1.0 || _phase < 0.0 { - _phase = _phase.truncatingRemainder(dividingBy: 1.0) - if _phase < 0.0 { _phase += 1.0 } - } + wrapUnitPhase(&_phase) } _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) @@ -111,7 +106,7 @@ public enum OscSquare { /// - phase: Initial phase offset in cycles `[0, 1)`. Defaults to `0.0`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -128,17 +123,9 @@ public enum OscSquare { add: any ValidGeneratorInput = 0.0 ) { super.init(freq: freq, phase: phase, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: phase must advance exactly once per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -149,12 +136,7 @@ public enum OscSquare { let sampleRate: Double = Double(graph.engine.sampleRate) let countFloat: Double = Double(count) - let freq: Double - if _freqIsGenerator { - freq = _freqInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - freq = _freqInput.floatValue(graph: graph) - } + let freq: Double = firstGeneratorSampleOrFloat(_freqInput, isGenerator: _freqIsGenerator, graph: graph, count: count) let dt: Double = freq / sampleRate _phase += dt * countFloat diff --git a/Sources/Lyrebird/Generators/Oscillators/OscTable.swift b/Sources/Lyrebird/Generators/Oscillators/OscTable.swift index 45ed013..797e021 100644 --- a/Sources/Lyrebird/Generators/Oscillators/OscTable.swift +++ b/Sources/Lyrebird/Generators/Oscillators/OscTable.swift @@ -295,12 +295,7 @@ public enum OscTable { let countFloat: Double = Double(count) let sampleRate: Double = Double(graph.engine.sampleRate) - let freq: Double - if _freqIsGenerator { - freq = _freqInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - freq = _freqInput.floatValue(graph: graph) - } + let freq: Double = firstGeneratorSampleOrFloat(_freqInput, isGenerator: _freqIsGenerator, graph: graph, count: count) _phase += freq * tableSizeFloat * countFloat / sampleRate if _phase >= tableSizeFloat { _phase -= tableSizeFloat } diff --git a/Sources/Lyrebird/Generators/Oscillators/OscTriangle.swift b/Sources/Lyrebird/Generators/Oscillators/OscTriangle.swift index 94a148d..c3392c6 100644 --- a/Sources/Lyrebird/Generators/Oscillators/OscTriangle.swift +++ b/Sources/Lyrebird/Generators/Oscillators/OscTriangle.swift @@ -100,12 +100,7 @@ public enum OscTriangle { _result[0][i] = rawTriangle + blampCorrection _phase += dt - if _phase >= 1.0 { _phase -= 1.0 } - else if _phase < 0.0 { _phase += 1.0 } - if _phase >= 1.0 || _phase < 0.0 { - _phase = _phase.truncatingRemainder(dividingBy: 1.0) - if _phase < 0.0 { _phase += 1.0 } - } + wrapUnitPhase(&_phase) } _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) @@ -122,7 +117,7 @@ public enum OscTriangle { /// - phase: Initial phase offset in cycles `[0, 1)`. Defaults to `0.0`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -139,17 +134,9 @@ public enum OscTriangle { add: any ValidGeneratorInput = 0.0 ) { super.init(freq: freq, phase: phase, mul: mul, add: add) - _setupSubBlockBuffer() } - // Bypass sub-block loop: phase must advance exactly once per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -160,12 +147,7 @@ public enum OscTriangle { let sampleRate: Double = Double(graph.engine.sampleRate) let countFloat: Double = Double(count) - let freq: Double - if _freqIsGenerator { - freq = _freqInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - freq = _freqInput.floatValue(graph: graph) - } + let freq: Double = firstGeneratorSampleOrFloat(_freqInput, isGenerator: _freqIsGenerator, graph: graph, count: count) let dt: Double = freq / sampleRate _phase += dt * countFloat diff --git a/Sources/Lyrebird/Generators/Oscillators/Phasor.swift b/Sources/Lyrebird/Generators/Oscillators/Phasor.swift index 2b1d438..c9f9731 100644 --- a/Sources/Lyrebird/Generators/Oscillators/Phasor.swift +++ b/Sources/Lyrebird/Generators/Oscillators/Phasor.swift @@ -201,7 +201,7 @@ public enum Phasor { /// Control-rate linear phase accumulator. Advances phase once per audio block. /// - /// Override of `calculatedSamples` bypasses the sub-block loop — phase must advance + /// Conforming to `BlockRateControlGenerator` bypasses the sub-block loop — phase must advance /// exactly once per audio block regardless of `controlBlockSize`. When the accumulator /// wraps mid-block at control rate, the ramp output will exhibit a backward artifact on /// the wrap block; this is an accepted control-rate limitation identical to @@ -215,7 +215,7 @@ public enum Phasor { /// - resetPos: Phase value on a rising trigger edge. Defaults to `0.0`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -238,16 +238,8 @@ public enum Phasor { add: any ValidGeneratorInput = 0.0 ) { super.init(trig: trig, rate: rate, start: start, end: end, resetPos: resetPos, mul: mul, add: add) - _setupSubBlockBuffer() } - /// Bypass sub-block loop: phase must advance exactly once per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Oscillators/VectorOscillator.swift b/Sources/Lyrebird/Generators/Oscillators/VectorOscillator.swift index ec9134d..cc531dd 100644 --- a/Sources/Lyrebird/Generators/Oscillators/VectorOscillator.swift +++ b/Sources/Lyrebird/Generators/Oscillators/VectorOscillator.swift @@ -334,25 +334,9 @@ public enum VectorOscillator { scalarFreqIncrement = _freqInput.floatValue(graph: graph) * tableSizeFloat / sampleRate } - let xSamples: [Double]? - let scalarX: Double - if _xIsGenerator { - xSamples = _xInput.calculatedSamples(graph: graph, count: count).first - scalarX = 0 - } else { - xSamples = nil - scalarX = _xInput.floatValue(graph: graph) - } + let (xSamples, scalarX) = resolveGeneratorOrScalar(_xInput, isGenerator: _xIsGenerator, graph: graph, count: count) - let ySamples: [Double]? - let scalarY: Double - if _yIsGenerator { - ySamples = _yInput.calculatedSamples(graph: graph, count: count).first - scalarY = 0 - } else { - ySamples = nil - scalarY = _yInput.floatValue(graph: graph) - } + let (ySamples, scalarY) = resolveGeneratorOrScalar(_yInput, isGenerator: _yIsGenerator, graph: graph, count: count) let phaseSamples: [Double]? let scalarPhaseOffset: Double @@ -632,33 +616,13 @@ public enum VectorOscillator { let sampleRate: Double = Double(graph.engine.sampleRate) // Read each generator input once at control rate (first sample of the block). - let freq: Double - if _freqIsGenerator { - freq = _freqInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - freq = _freqInput.floatValue(graph: graph) - } + let freq: Double = firstGeneratorSampleOrFloat(_freqInput, isGenerator: _freqIsGenerator, graph: graph, count: count) - let rawX: Double - if _xIsGenerator { - rawX = _xInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - rawX = _xInput.floatValue(graph: graph) - } + let rawX: Double = firstGeneratorSampleOrFloat(_xInput, isGenerator: _xIsGenerator, graph: graph, count: count) - let rawY: Double - if _yIsGenerator { - rawY = _yInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - rawY = _yInput.floatValue(graph: graph) - } + let rawY: Double = firstGeneratorSampleOrFloat(_yInput, isGenerator: _yIsGenerator, graph: graph, count: count) - let phaseOffsetCycles: Double - if _phaseIsGenerator { - phaseOffsetCycles = _phaseInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - phaseOffsetCycles = _phaseInput.floatValue(graph: graph) - } + let phaseOffsetCycles: Double = firstGeneratorSampleOrFloat(_phaseInput, isGenerator: _phaseIsGenerator, graph: graph, count: count) // Advance phase by exactly `count` samples worth of frequency (not blockSize) — // this matches the sub-block contract: `_computeSamples` may be called multiple diff --git a/Sources/Lyrebird/Generators/Oscillators/WavetableMorph.swift b/Sources/Lyrebird/Generators/Oscillators/WavetableMorph.swift index f9e6381..486ddbb 100644 --- a/Sources/Lyrebird/Generators/Oscillators/WavetableMorph.swift +++ b/Sources/Lyrebird/Generators/Oscillators/WavetableMorph.swift @@ -222,15 +222,7 @@ public enum WavetableMorph { scalarFreqIncrement = _freqInput.floatValue(graph: graph) * tableSizeFloat / sampleRate } - let positionSamples: [Double]? - let scalarPosition: Double - if _positionIsGenerator { - positionSamples = _positionInput.calculatedSamples(graph: graph, count: count).first - scalarPosition = 0 - } else { - positionSamples = nil - scalarPosition = _positionInput.floatValue(graph: graph) - } + let (positionSamples, scalarPosition) = resolveGeneratorOrScalar(_positionInput, isGenerator: _positionIsGenerator, graph: graph, count: count) let phaseSamples: [Double]? let scalarPhaseOffset: Double @@ -428,26 +420,11 @@ public enum WavetableMorph { let sampleRate: Double = Double(graph.engine.sampleRate) // Read each generator input once at control rate (first sample of the block). - let freq: Double - if _freqIsGenerator { - freq = _freqInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - freq = _freqInput.floatValue(graph: graph) - } + let freq: Double = firstGeneratorSampleOrFloat(_freqInput, isGenerator: _freqIsGenerator, graph: graph, count: count) - let rawPosition: Double - if _positionIsGenerator { - rawPosition = _positionInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - rawPosition = _positionInput.floatValue(graph: graph) - } + let rawPosition: Double = firstGeneratorSampleOrFloat(_positionInput, isGenerator: _positionIsGenerator, graph: graph, count: count) - let phaseOffsetCycles: Double - if _phaseIsGenerator { - phaseOffsetCycles = _phaseInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 - } else { - phaseOffsetCycles = _phaseInput.floatValue(graph: graph) - } + let phaseOffsetCycles: Double = firstGeneratorSampleOrFloat(_phaseInput, isGenerator: _phaseIsGenerator, graph: graph, count: count) // Advance phase by exactly `count` samples worth of frequency (not blockSize). _phase += freq * tableSizeFloat * countFloat / sampleRate diff --git a/Sources/Lyrebird/Generators/Panning/AmbiEncoder1.swift b/Sources/Lyrebird/Generators/Panning/AmbiEncoder1.swift index 63c8563..31b3060 100644 --- a/Sources/Lyrebird/Generators/Panning/AmbiEncoder1.swift +++ b/Sources/Lyrebird/Generators/Panning/AmbiEncoder1.swift @@ -137,25 +137,9 @@ public final class AmbiEncoder1: GeneratorBase, AudioGenerator { let inputSamples: [[Double]] = _input.calculatedSamples(graph: graph, count: count) guard let ins: [Double] = inputSamples.first else { return _result } - let azSamples: [Double]? - let azScalar: Double - if _azimuthIsGenerator { - azSamples = _azimuth.calculatedSamples(graph: graph, count: count).first - azScalar = 0 - } else { - azSamples = nil - azScalar = _azimuth.floatValue(graph: graph) - } + let (azSamples, azScalar) = resolveGeneratorOrScalar(_azimuth, isGenerator: _azimuthIsGenerator, graph: graph, count: count) - let elSamples: [Double]? - let elScalar: Double - if _elevationIsGenerator { - elSamples = _elevation.calculatedSamples(graph: graph, count: count).first - elScalar = 0 - } else { - elSamples = nil - elScalar = _elevation.floatValue(graph: graph) - } + let (elSamples, elScalar) = resolveGeneratorOrScalar(_elevation, isGenerator: _elevationIsGenerator, graph: graph, count: count) for i: Int in 0.. [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Random/TriggeredRandom.swift b/Sources/Lyrebird/Generators/Random/TriggeredRandom.swift index 7444f6d..40f87cd 100644 --- a/Sources/Lyrebird/Generators/Random/TriggeredRandom.swift +++ b/Sources/Lyrebird/Generators/Random/TriggeredRandom.swift @@ -70,7 +70,7 @@ public enum TriggeredRandom { /// reproducible output in tests. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 private var _prevTrig: Double = 0.0 @@ -108,18 +108,9 @@ public enum TriggeredRandom { mul: mul, add: add ) - _setupSubBlockBuffer() } - // Bypass sub-block loop: TriggeredRandom.Control scans the full audio-rate trigger block - // for a ≤0→>0 edge — must run exactly once per audio block, not once per sub-block chunk. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Reverb/ConvolutionReverb.swift b/Sources/Lyrebird/Generators/Reverb/ConvolutionReverb.swift index 30b89d7..f94daaa 100644 --- a/Sources/Lyrebird/Generators/Reverb/ConvolutionReverb.swift +++ b/Sources/Lyrebird/Generators/Reverb/ConvolutionReverb.swift @@ -367,15 +367,7 @@ public enum ConvolutionReverb { _checkCount(count) // Resolve mono input. - let inputSamples: [Double]? - let scalarInput: Double - if _inputIsGenerator { - inputSamples = _input.calculatedSamples(graph: graph, count: count).first - scalarInput = 0.0 - } else { - inputSamples = nil - scalarInput = _input.floatValue(graph: graph) - } + let (inputSamples, scalarInput) = resolveGeneratorOrScalar(_input, isGenerator: _inputIsGenerator, graph: graph, count: count) let mix: Double = max(0.0, min(1.0, _mix.floatValue(graph: graph))) let dryGain: Double = 1.0 - mix diff --git a/Sources/Lyrebird/Generators/Reverb/SpringReverb.swift b/Sources/Lyrebird/Generators/Reverb/SpringReverb.swift index d187183..6ec24e5 100644 --- a/Sources/Lyrebird/Generators/Reverb/SpringReverb.swift +++ b/Sources/Lyrebird/Generators/Reverb/SpringReverb.swift @@ -258,15 +258,7 @@ public enum SpringReverb { let dryComp: Double = 1.0 - mixRaw // --- Fetch input block --- - let inputBlock: [Double]? - let scalarInput: Double - if _inputIsGenerator { - inputBlock = _input.calculatedSamples(graph: graph, count: count).first - scalarInput = 0.0 - } else { - inputBlock = nil - scalarInput = _input.floatValue(graph: graph) - } + let (inputBlock, scalarInput) = resolveGeneratorOrScalar(_input, isGenerator: _inputIsGenerator, graph: graph, count: count) // --- Per-sample loop --- for i: Int in 0.. Double { @@ -128,14 +127,6 @@ public enum ChannelSelect { return channels[_channel].first ?? 0.0 } - // Bypass sub-block loop: the source is evaluated at full block rate; previousOutputValue - // must only reset to target once per audio block, not once per sub-block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } /// Produces a linearly-interpolated block from `previousOutputValue` to the current /// channel value, filling `_result[0]` in-place (identical pattern to `In.Control`). diff --git a/Sources/Lyrebird/Generators/Routing/CrossFade.swift b/Sources/Lyrebird/Generators/Routing/CrossFade.swift index 3e8c4ad..a3003c4 100644 --- a/Sources/Lyrebird/Generators/Routing/CrossFade.swift +++ b/Sources/Lyrebird/Generators/Routing/CrossFade.swift @@ -196,10 +196,7 @@ public enum CrossFade { let gainA: Double = cos(p * crossFadeHalfPi) let gainB: Double = sin(p * crossFadeHalfPi) var target: Double = a * gainA + b * gainB - if !_mulAdd.isIdentity { - target = target * _mulAdd.mulInput.floatValue(graph: graph) - + _mulAdd.addInput.floatValue(graph: graph) - } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult( into: &_result, previousOutputValue: &previousOutputValue, diff --git a/Sources/Lyrebird/Generators/Routing/LinearCrossFade.swift b/Sources/Lyrebird/Generators/Routing/LinearCrossFade.swift index baa9107..1a10571 100644 --- a/Sources/Lyrebird/Generators/Routing/LinearCrossFade.swift +++ b/Sources/Lyrebird/Generators/Routing/LinearCrossFade.swift @@ -186,10 +186,7 @@ public enum LinearCrossFade { let gainA: Double = (1.0 - clampedPan) * 0.5 let gainB: Double = (1.0 + clampedPan) * 0.5 var target: Double = a * gainA + b * gainB - if !_mulAdd.isIdentity { - target = target * _mulAdd.mulInput.floatValue(graph: graph) - + _mulAdd.addInput.floatValue(graph: graph) - } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult( into: &_result, previousOutputValue: &previousOutputValue, diff --git a/Sources/Lyrebird/Generators/Routing/Select.swift b/Sources/Lyrebird/Generators/Routing/Select.swift index 47c7d1b..08a2fb5 100644 --- a/Sources/Lyrebird/Generators/Routing/Select.swift +++ b/Sources/Lyrebird/Generators/Routing/Select.swift @@ -197,10 +197,7 @@ public enum Select { let rawIdx: Double = _whichInput.floatValue(graph: graph) let idx: Int = Swift.max(0, Swift.min(lastIdx, Int(rawIdx))) var target: Double = _scratch[idx][0] - if !_mulAdd.isIdentity { - target = target * _mulAdd.mulInput.floatValue(graph: graph) - + _mulAdd.addInput.floatValue(graph: graph) - } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult( into: &_result, previousOutputValue: &previousOutputValue, diff --git a/Sources/Lyrebird/Generators/Spectral/OnsetDetector.swift b/Sources/Lyrebird/Generators/Spectral/OnsetDetector.swift index da88073..66a11c3 100644 --- a/Sources/Lyrebird/Generators/Spectral/OnsetDetector.swift +++ b/Sources/Lyrebird/Generators/Spectral/OnsetDetector.swift @@ -180,8 +180,7 @@ public final class OnsetDetector: SpectralProcessor { medianWindowFrames: Int = 7, minHopsBetweenOnsets: Int = 3 ) { - precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0, - "OnsetDetector: fftSize must be a power of two >= 4, got \(fftSize)") + lyrebirdRequireFFTSize(fftSize, typeName: "OnsetDetector") precondition(hopSize >= 1 && hopSize < fftSize, "OnsetDetector: hopSize must be in [1, fftSize), got \(hopSize)") precondition(threshold > 0, @@ -417,7 +416,7 @@ extension OnsetDetector { /// - detector: The onset detector to read from. /// - analysis: Paired `SpectralChain.Audio`. Stored as a generator input so /// engine traversal evaluates it each block automatically. - public final class Control: GeneratorBase, ControlGenerator { + public final class Control: GeneratorBase, BlockRateControlGenerator { private let _detector: OnsetDetector private let _analysis: SpectralChain.Audio? @@ -463,19 +462,9 @@ extension OnsetDetector { self._analysis = analysis self._lastSeenOnsetSerial = detector._loadOnsetSerial() super.init() - _setupSubBlockBuffer() } - // Bypass sub-block loop: onset state is published once per FFT hop, and the - // trigger pulse must be emitted exactly once per audio block — not once per - // sub-block chunk. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralBinDelay.swift b/Sources/Lyrebird/Generators/Spectral/SpectralBinDelay.swift index fe89395..15d3ad9 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralBinDelay.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralBinDelay.swift @@ -114,8 +114,7 @@ public final class SpectralBinDelay: SpectralProcessor { delayTimes: LyrebirdBuffer, feedbacks: LyrebirdBuffer ) { - precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0, - "SpectralBinDelay: fftSize must be a power of two >= 4, got \(fftSize)") + lyrebirdRequireFFTSize(fftSize, typeName: "SpectralBinDelay") precondition(hopSize >= 1 && hopSize < fftSize, "SpectralBinDelay: hopSize must be in [1, fftSize), got \(hopSize)") precondition(maxDelaySeconds > 0, diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralBlur.swift b/Sources/Lyrebird/Generators/Spectral/SpectralBlur.swift index 4d3a614..4ab585f 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralBlur.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralBlur.swift @@ -52,8 +52,7 @@ public final class SpectralBlur: SpectralProcessor { fftSize: Int, radius: Int = 0 ) { - precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0, - "SpectralBlur: fftSize must be a power of two >= 4, got \(fftSize)") + lyrebirdRequireFFTSize(fftSize, typeName: "SpectralBlur") _fftSize = fftSize _halfSize = fftSize / 2 _binCount = max(0, _halfSize - 1) diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralBrickwall.swift b/Sources/Lyrebird/Generators/Spectral/SpectralBrickwall.swift index c02ac62..8d9cde9 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralBrickwall.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralBrickwall.swift @@ -65,8 +65,7 @@ public final class SpectralBrickwall: SpectralProcessor { lowHz: Double = 0, highHz: Double? = nil ) { - precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0, - "SpectralBrickwall: fftSize must be a power of two >= 4, got \(fftSize)") + lyrebirdRequireFFTSize(fftSize, typeName: "SpectralBrickwall") precondition(sampleRate > 0, "SpectralBrickwall: sampleRate must be positive, got \(sampleRate)") _fftSize = fftSize diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralCentroid.swift b/Sources/Lyrebird/Generators/Spectral/SpectralCentroid.swift index aeb4792..7e63bba 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralCentroid.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralCentroid.swift @@ -39,14 +39,9 @@ public enum SpectralCentroid { /// - sampleRate: Sample rate in Hz. Used to convert bin index to frequency. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset in Hz. Defaults to `0.0`. - public final class Control: GeneratorBase, ControlGenerator { + public final class Control: SpectralFeatureControlBase { - private let _analysis: SpectralChain.Audio? - private let spectral: SpectralBuffer private let sampleRate: Double - private var _mulAdd: MulAddSpec - public var previousOutputValue: Double = 0.0 - private var _rampTarget: Double = 0.0 /// - Parameters: /// - analysis: Paired `SpectralChain.Audio`. Stored as a generator @@ -95,33 +90,11 @@ public enum SpectralCentroid { mul: any ValidGeneratorInput, add: any ValidGeneratorInput ) { - self._analysis = analysis - self.spectral = spectral self.sampleRate = sampleRate - self._mulAdd = MulAddSpec(mul: mul, add: add) - super.init() - _setupSubBlockBuffer() + super.init(analysis: analysis, spectral: spectral, mul: mul, add: add) } - - // Bypass sub-block loop: spectral buffer is written once per FFT hop (which spans - // multiple audio blocks). Reading it once per audio block is correct. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } - - public func _computeSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _checkCount(count) - - // Drive engine evaluation of the paired SpectralChain.Audio (when present). - _ = _analysis?.calculatedSamples(graph: graph, count: count) - + override func computeFeature(graph: SynthGraph, count: Int) -> Double { let binCount: Int = spectral.binCount let binHz: Double = sampleRate / Double(spectral.fftSize) @@ -133,21 +106,7 @@ public enum SpectralCentroid { totalMag += mag } - let centroid: Double = totalMag > 0.0 ? (weightedSum / totalMag) * binHz : 0.0 - - let target: Double = centroid - let rampStart: Double = _rampTarget - _rampTarget = target - guard count > 0 else { return _result } - previousOutputValue = fillRampedResult( - into: &_result, - from: rampStart, - to: target, - mulAdd: _mulAdd, - graph: graph, - count: count - ) - return _result + return totalMag > 0.0 ? (weightedSum / totalMag) * binHz : 0.0 } } } diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralChain.swift b/Sources/Lyrebird/Generators/Spectral/SpectralChain.swift index 5ee5c4d..cb700c9 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralChain.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralChain.swift @@ -312,8 +312,7 @@ public enum SpectralChain { mul: any ValidGeneratorInput, add: any ValidGeneratorInput ) { - precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0, - "SpectralChain.Audio: fftSize must be a power of two >= 4") + lyrebirdRequireFFTSize(fftSize, typeName: "SpectralChain.Audio") precondition(hopSize > 0 && hopSize <= fftSize, "SpectralChain.Audio: hopSize must be in 1...fftSize") for case .dual(_, let sideChain) in stages { diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralComplexClosure.swift b/Sources/Lyrebird/Generators/Spectral/SpectralComplexClosure.swift index 91607d9..6662c92 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralComplexClosure.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralComplexClosure.swift @@ -179,8 +179,7 @@ public final class SpectralComplexClosure: SpectralProcessor { sampleRate: Double, _ body: @escaping SpectralComplexClosureBody ) { - precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0, - "SpectralComplexClosure: fftSize must be a power of two >= 4, got \(fftSize)") + lyrebirdRequireFFTSize(fftSize, typeName: "SpectralComplexClosure") precondition(hopSize > 0, "SpectralComplexClosure: hopSize must be > 0, got \(hopSize)") _fftSize = fftSize diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralCrossMap.swift b/Sources/Lyrebird/Generators/Spectral/SpectralCrossMap.swift index 4629631..5b98a45 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralCrossMap.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralCrossMap.swift @@ -116,8 +116,7 @@ public final class SpectralCrossMap: SpectralProcessor2 { floor: Double = 0.0, mode: Double = 1.0 ) { - precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0, - "SpectralCrossMap: fftSize must be a power of two >= 4, got \(fftSize)") + lyrebirdRequireFFTSize(fftSize, typeName: "SpectralCrossMap") _halfSize = fftSize / 2 _binCount = _halfSize - 1 diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralDiffuse.swift b/Sources/Lyrebird/Generators/Spectral/SpectralDiffuse.swift index 07aceef..fc9340e 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralDiffuse.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralDiffuse.swift @@ -62,8 +62,7 @@ public final class SpectralDiffuse: SpectralProcessor { amount: Double = 0.0, seed: UInt64? = nil ) { - precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0, - "SpectralDiffuse: fftSize must be a power of two >= 4, got \(fftSize)") + lyrebirdRequireFFTSize(fftSize, typeName: "SpectralDiffuse") _fftSize = fftSize _halfSize = fftSize / 2 _binCount = max(0, _halfSize - 1) diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralEntropy.swift b/Sources/Lyrebird/Generators/Spectral/SpectralEntropy.swift index 5b17d48..e4b72a6 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralEntropy.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralEntropy.swift @@ -38,13 +38,7 @@ public enum SpectralEntropy { /// - analysis: Paired `SpectralChain.Audio`. Reads its `spectralBuffer` once per audio block. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: GeneratorBase, ControlGenerator { - - private let _analysis: SpectralChain.Audio? - private let spectral: SpectralBuffer - private var _mulAdd: MulAddSpec - public var previousOutputValue: Double = 0.0 - private var _rampTarget: Double = 0.0 + public final class Control: SpectralFeatureControlBase { /// - Parameters: /// - analysis: Paired `SpectralChain.Audio`. Stored as a generator input. @@ -67,36 +61,7 @@ public enum SpectralEntropy { self.init(analysis: nil, spectral: spectral, mul: mul, add: add) } - private init( - analysis: SpectralChain.Audio?, - spectral: SpectralBuffer, - mul: any ValidGeneratorInput, - add: any ValidGeneratorInput - ) { - self._analysis = analysis - self.spectral = spectral - self._mulAdd = MulAddSpec(mul: mul, add: add) - super.init() - _setupSubBlockBuffer() - } - - - // Bypass sub-block loop: spectral buffer is written once per FFT hop. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } - - public func _computeSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _checkCount(count) - - _ = _analysis?.calculatedSamples(graph: graph, count: count) - + override func computeFeature(graph: SynthGraph, count: Int) -> Double { let binCount: Int = spectral.binCount let log2BinCount: Double = log2(Double(binCount)) @@ -105,33 +70,15 @@ public enum SpectralEntropy { totalMag += Double(spectral.magnitude(at: k)) } - let entropy: Double - if totalMag == 0.0 { - entropy = 0.0 - } else { - var h: Double = 0.0 - for k: Int in 0.. 0.0 { - h -= p * log2(p) - } + guard totalMag != 0.0 else { return 0.0 } + var h: Double = 0.0 + for k: Int in 0.. 0.0 { + h -= p * log2(p) } - entropy = min(1.0, h / log2BinCount) } - - let target: Double = entropy - let rampStart: Double = _rampTarget - _rampTarget = target - guard count > 0 else { return _result } - previousOutputValue = fillRampedResult( - into: &_result, - from: rampStart, - to: target, - mulAdd: _mulAdd, - graph: graph, - count: count - ) - return _result + return min(1.0, h / log2BinCount) } } } diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralFeatureControlBase.swift b/Sources/Lyrebird/Generators/Spectral/SpectralFeatureControlBase.swift new file mode 100644 index 0000000..3e004ac --- /dev/null +++ b/Sources/Lyrebird/Generators/Spectral/SpectralFeatureControlBase.swift @@ -0,0 +1,70 @@ +// SpectralFeatureControlBase.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// MARK: - SpectralFeatureControlBase + +/// Shared base for the control-rate spectral *feature* analysers (`SpectralCentroid`, +/// `SpectralSpread`, `SpectralFlatness`, `SpectralEntropy`, `SpectralFlux`, +/// `SpectralRolloff`). +/// +/// Each reads the paired analysis buffer once per audio block and emits one scalar +/// per block, ramped from the previous block's value. This base owns everything that +/// is identical across them — the analysis handle, the spectral buffer, the +/// `MulAddSpec`, the ramp state, the sub-block bypass, and the +/// drive-analysis → `computeFeature` → ramp body. Each concrete `Control` subclass +/// adds only its own parameters/state and overrides `computeFeature(graph:count:)`. +public class SpectralFeatureControlBase: GeneratorBase, BlockRateControlGenerator { + + /// Paired `SpectralChain.Audio`, held as a generator input so engine traversal + /// evaluates it each block. `nil` when constructed against a pre-populated buffer. + let _analysis: SpectralChain.Audio? + /// The analysis buffer read once per audio block. + let spectral: SpectralBuffer + var _mulAdd: MulAddSpec + public var previousOutputValue: Double = 0.0 + var _rampTarget: Double = 0.0 + + init( + analysis: SpectralChain.Audio?, + spectral: SpectralBuffer, + mul: any ValidGeneratorInput, + add: any ValidGeneratorInput + ) { + self._analysis = analysis + self.spectral = spectral + self._mulAdd = MulAddSpec(mul: mul, add: add) + super.init() + } + + /// Compute the feature's value for the current block from `spectral` (and any + /// subclass state). Overridden by each analyser; the base returns `0`. + func computeFeature(graph: SynthGraph, count: Int) -> Double { 0.0 } + + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + + // Drive engine evaluation of the paired SpectralChain.Audio (when present). + _ = _analysis?.calculatedSamples(graph: graph, count: count) + + let target: Double = computeFeature(graph: graph, count: count) + let rampStart: Double = _rampTarget + _rampTarget = target + guard count > 0 else { return _result } + previousOutputValue = fillRampedResult( + into: &_result, + from: rampStart, + to: target, + mulAdd: _mulAdd, + graph: graph, + count: count + ) + return _result + } +} diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralFlatness.swift b/Sources/Lyrebird/Generators/Spectral/SpectralFlatness.swift index 8d80d04..f9e2a21 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralFlatness.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralFlatness.swift @@ -38,13 +38,7 @@ public enum SpectralFlatness { /// - analysis: Paired `SpectralChain.Audio`. Reads its `spectralBuffer` once per audio block. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: GeneratorBase, ControlGenerator { - - private let _analysis: SpectralChain.Audio? - private let spectral: SpectralBuffer - private var _mulAdd: MulAddSpec - public var previousOutputValue: Double = 0.0 - private var _rampTarget: Double = 0.0 + public final class Control: SpectralFeatureControlBase { /// - Parameters: /// - analysis: Paired `SpectralChain.Audio`. Stored as a generator input so @@ -70,37 +64,7 @@ public enum SpectralFlatness { self.init(analysis: nil, spectral: spectral, mul: mul, add: add) } - private init( - analysis: SpectralChain.Audio?, - spectral: SpectralBuffer, - mul: any ValidGeneratorInput, - add: any ValidGeneratorInput - ) { - self._analysis = analysis - self.spectral = spectral - self._mulAdd = MulAddSpec(mul: mul, add: add) - super.init() - _setupSubBlockBuffer() - } - - - // Bypass sub-block loop: spectral buffer is written once per FFT hop. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } - - public func _computeSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _checkCount(count) - - // Drive engine evaluation of the paired SpectralChain.Audio (when present). - _ = _analysis?.calculatedSamples(graph: graph, count: count) - + override func computeFeature(graph: SynthGraph, count: Int) -> Double { let binCount: Int = spectral.binCount var logSum: Double = 0.0 @@ -114,29 +78,11 @@ public enum SpectralFlatness { logSum += mag > 0.0 ? log(mag) : -.infinity } - let flatness: Double - if totalMag == 0.0 { - flatness = 0.0 - } else { - let arithmeticMean: Double = totalMag / Double(binCount) - let geometricMean: Double = exp(logSum / Double(binCount)) - // AM-GM guarantees geometric ≤ arithmetic, so flatness ∈ [0, 1]. - flatness = geometricMean / arithmeticMean - } - - let target: Double = flatness - let rampStart: Double = _rampTarget - _rampTarget = target - guard count > 0 else { return _result } - previousOutputValue = fillRampedResult( - into: &_result, - from: rampStart, - to: target, - mulAdd: _mulAdd, - graph: graph, - count: count - ) - return _result + guard totalMag != 0.0 else { return 0.0 } + let arithmeticMean: Double = totalMag / Double(binCount) + let geometricMean: Double = exp(logSum / Double(binCount)) + // AM-GM guarantees geometric ≤ arithmetic, so flatness ∈ [0, 1]. + return geometricMean / arithmeticMean } } } diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralFlux.swift b/Sources/Lyrebird/Generators/Spectral/SpectralFlux.swift index ff4c391..6b765bf 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralFlux.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralFlux.swift @@ -38,15 +38,10 @@ public enum SpectralFlux { /// - analysis: Paired `SpectralChain.Audio`. Reads its `spectralBuffer` once per audio block. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: GeneratorBase, ControlGenerator { + public final class Control: SpectralFeatureControlBase { - private let _analysis: SpectralChain.Audio? - private let spectral: SpectralBuffer private var _prevMag: [Float] private var _isFirstFrame: Bool - private var _mulAdd: MulAddSpec - public var previousOutputValue: Double = 0.0 - private var _rampTarget: Double = 0.0 /// - Parameters: /// - analysis: Paired `SpectralChain.Audio`. Stored as a generator input. @@ -69,74 +64,40 @@ public enum SpectralFlux { self.init(analysis: nil, spectral: spectral, mul: mul, add: add) } - private init( + override init( analysis: SpectralChain.Audio?, spectral: SpectralBuffer, mul: any ValidGeneratorInput, add: any ValidGeneratorInput ) { - self._analysis = analysis - self.spectral = spectral self._prevMag = [Float](repeating: 0, count: spectral.binCount) self._isFirstFrame = true - self._mulAdd = MulAddSpec(mul: mul, add: add) - super.init() - _setupSubBlockBuffer() + super.init(analysis: analysis, spectral: spectral, mul: mul, add: add) } - - // Bypass sub-block loop: spectral buffer is written once per FFT hop. - // _prevMag must update exactly once per audio block, not per sub-block chunk. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } - - public func _computeSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _checkCount(count) - - _ = _analysis?.calculatedSamples(graph: graph, count: count) - + // _prevMag updates exactly once per audio block (the base's bypass ensures + // computeFeature runs once per block, not per sub-block chunk). + override func computeFeature(graph: SynthGraph, count: Int) -> Double { let binCount: Int = spectral.binCount - let flux: Double if _isFirstFrame { // Populate _prevMag with current frame; output 0 (no previous frame to compare). for k: Int in 0.. 0 else { return _result } - previousOutputValue = fillRampedResult( - into: &_result, - from: rampStart, - to: target, - mulAdd: _mulAdd, - graph: graph, - count: count - ) - return _result + var sumSquares: Double = 0.0 + for k: Int in 0..= 4 && (fftSize & (fftSize - 1)) == 0, - "SpectralFormantShift: fftSize must be a power of two >= 4, got \(fftSize)") + lyrebirdRequireFFTSize(fftSize, typeName: "SpectralFormantShift") _fftSize = fftSize _halfSize = fftSize / 2 diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralFreeze.swift b/Sources/Lyrebird/Generators/Spectral/SpectralFreeze.swift index a4a6667..2a97765 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralFreeze.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralFreeze.swift @@ -62,8 +62,7 @@ public final class SpectralFreeze: SpectralProcessor { /// - Parameter fftSize: Must match the paired `SpectralChain.Audio.fftSize`. Power of two. public init(fftSize: Int) { - precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0, - "SpectralFreeze: fftSize must be a power of two >= 4, got \(fftSize)") + lyrebirdRequireFFTSize(fftSize, typeName: "SpectralFreeze") let halfSize: Int = fftSize / 2 _halfSize = halfSize _binCount = halfSize - 1 // complex bins 1 ..< halfSize diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralGate.swift b/Sources/Lyrebird/Generators/Spectral/SpectralGate.swift index c389a71..4e21b27 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralGate.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralGate.swift @@ -59,8 +59,7 @@ public final class SpectralGate: SpectralProcessor { threshold: Double, floor: Double = 0.0 ) { - precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0, - "SpectralGate: fftSize must be a power of two >= 4, got \(fftSize)") + lyrebirdRequireFFTSize(fftSize, typeName: "SpectralGate") _fftSize = fftSize _halfSize = fftSize / 2 _binCount = _halfSize - 1 diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralHarmonicEnhance.swift b/Sources/Lyrebird/Generators/Spectral/SpectralHarmonicEnhance.swift index d8dbf8f..8697aed 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralHarmonicEnhance.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralHarmonicEnhance.swift @@ -83,8 +83,7 @@ public final class SpectralHarmonicEnhance: SpectralProcessor { ratio: Double = 2.0, strength: Double = 0.2 ) { - precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0, - "SpectralHarmonicEnhance: fftSize must be a power of two >= 4, got \(fftSize)") + lyrebirdRequireFFTSize(fftSize, typeName: "SpectralHarmonicEnhance") _halfSize = fftSize / 2 _binCount = _halfSize - 1 _numPartials = Atomic(Float(numPartials)) diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralNoiseFilter.swift b/Sources/Lyrebird/Generators/Spectral/SpectralNoiseFilter.swift index 5e82138..032eb71 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralNoiseFilter.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralNoiseFilter.swift @@ -87,8 +87,7 @@ public final class SpectralNoiseFilter: SpectralProcessor { sampleRate: Double, threshold: Double = 1.0 ) { - precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0, - "SpectralNoiseFilter: fftSize must be a power of two >= 4, got \(fftSize)") + lyrebirdRequireFFTSize(fftSize, typeName: "SpectralNoiseFilter") precondition(numFrames >= 2, "SpectralNoiseFilter: numFrames must be >= 2, got \(numFrames)") precondition(hopSize >= 1 && hopSize < fftSize, diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralPartialFilter.swift b/Sources/Lyrebird/Generators/Spectral/SpectralPartialFilter.swift index 8916216..6ef65af 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralPartialFilter.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralPartialFilter.swift @@ -113,8 +113,7 @@ public final class SpectralPartialFilter: SpectralProcessor { sampleRate: Double, threshold: Double = 1.0 ) { - precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0, - "SpectralPartialFilter: fftSize must be a power of two >= 4, got \(fftSize)") + lyrebirdRequireFFTSize(fftSize, typeName: "SpectralPartialFilter") precondition(numFrames >= 2, "SpectralPartialFilter: numFrames must be >= 2, got \(numFrames)") precondition(hopSize >= 1 && hopSize < fftSize, diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralPhaseShift.swift b/Sources/Lyrebird/Generators/Spectral/SpectralPhaseShift.swift index 7f5b1dd..dfe2ab3 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralPhaseShift.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralPhaseShift.swift @@ -58,8 +58,7 @@ public final class SpectralPhaseShift: SpectralProcessor { fftSize: Int, shift: PhaseShiftAmount ) { - precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0, - "SpectralPhaseShift: fftSize must be a power of two >= 4, got \(fftSize)") + lyrebirdRequireFFTSize(fftSize, typeName: "SpectralPhaseShift") _fftSize = fftSize _halfSize = fftSize / 2 _binCount = _halfSize - 1 diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralPitchShift.swift b/Sources/Lyrebird/Generators/Spectral/SpectralPitchShift.swift index c9b2bf7..6e81b1c 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralPitchShift.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralPitchShift.swift @@ -82,8 +82,7 @@ public final class SpectralPitchShift: SpectralProcessor { hopSize: Int, pitchRatio: Double = 1.0 ) { - precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0, - "SpectralPitchShift: fftSize must be a power of two >= 4, got \(fftSize)") + lyrebirdRequireFFTSize(fftSize, typeName: "SpectralPitchShift") precondition(hopSize >= 1 && hopSize < fftSize, "SpectralPitchShift: hopSize must be in [1, fftSize), got \(hopSize)") diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralPolarClosure.swift b/Sources/Lyrebird/Generators/Spectral/SpectralPolarClosure.swift index 0d9e285..c954438 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralPolarClosure.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralPolarClosure.swift @@ -150,8 +150,7 @@ public final class SpectralPolarClosure: SpectralProcessor { sampleRate: Double, _ body: @escaping SpectralPolarClosureBody ) { - precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0, - "SpectralPolarClosure: fftSize must be a power of two >= 4, got \(fftSize)") + lyrebirdRequireFFTSize(fftSize, typeName: "SpectralPolarClosure") precondition(hopSize > 0, "SpectralPolarClosure: hopSize must be > 0, got \(hopSize)") _fftSize = fftSize diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralProcessor.swift b/Sources/Lyrebird/Generators/Spectral/SpectralProcessor.swift index 5ecdb67..55530c9 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralProcessor.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralProcessor.swift @@ -20,3 +20,26 @@ public protocol SpectralProcessor: AnyObject { /// `engine.bufferSwapKillQueue`. Processors with no swappable state can ignore it. func process(spectral: SpectralBuffer, engine: SynthesisEngine) } + +// MARK: - Maintainer note: no shared `SpectralProcessorBase` +// +// A code-quality pass (2026) evaluated hoisting the ~21 conformers' common +// surface — the `_fftSize` / `_halfSize` / `_binCount` derivation and the +// `guard spectral.fftSize == _fftSize` / `guard spectral.isValid` head guards — +// into a shared base class, and deliberately did NOT do it. Reasons, so this is +// not re-litigated: +// +// 1. Conformers are protocol-based `final class`es with per-processor +// `process(spectral:engine:)` bodies and their own scratch state. A base +// class would have to carry a no-op `process` default and would add a +// public type to the API for a very thin gain. +// 2. The shared surface is only ~3 init lines plus 1–2 guard lines, and the +// guards are NOT uniform (some check `fftSize == _fftSize`, some only +// `isValid`), so no single guard body fits all. +// 3. The genuinely duplicated weight was already removed elsewhere: FFT-size +// validation is `lyrebirdRequireFFTSize(_:typeName:)` (Math/PowerOfTwo.swift), +// and the paired scratch alloc/free is `RTScratchBuffer`. +// +// The size derivation `_halfSize = fftSize/2; _binCount = max(0, _halfSize-1)` is +// the only remaining duplication; if it ever grows or drifts, extract a small +// value helper (e.g. `spectralBinLayout(fftSize:)`) rather than a base class. diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralRolloff.swift b/Sources/Lyrebird/Generators/Spectral/SpectralRolloff.swift index 1c48ec0..42aa902 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralRolloff.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralRolloff.swift @@ -42,15 +42,10 @@ public enum SpectralRolloff { /// - rolloffPercent: Fraction of total energy in `[0, 1]`. Defaults to `0.85`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset in Hz. Defaults to `0.0`. - public final class Control: GeneratorBase, ControlGenerator { + public final class Control: SpectralFeatureControlBase { - private let _analysis: SpectralChain.Audio? - private let spectral: SpectralBuffer private let sampleRate: Double private let rolloffInput: any ValidGeneratorInput - private var _mulAdd: MulAddSpec - public var previousOutputValue: Double = 0.0 - private var _rampTarget: Double = 0.0 /// - Parameters: /// - analysis: Paired `SpectralChain.Audio`. Stored as a generator input. @@ -102,32 +97,12 @@ public enum SpectralRolloff { add: any ValidGeneratorInput ) { let resolvedRolloff: any ValidGeneratorInput = rolloffPercent._resolvedInput() - self._analysis = analysis - self.spectral = spectral self.sampleRate = sampleRate self.rolloffInput = resolvedRolloff - self._mulAdd = MulAddSpec(mul: mul, add: add) - super.init() - _setupSubBlockBuffer() + super.init(analysis: analysis, spectral: spectral, mul: mul, add: add) } - - // Bypass sub-block loop: spectral buffer is written once per FFT hop. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } - - public func _computeSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _checkCount(count) - - _ = _analysis?.calculatedSamples(graph: graph, count: count) - + override func computeFeature(graph: SynthGraph, count: Int) -> Double { let binCount: Int = spectral.binCount let binHz: Double = sampleRate / Double(spectral.fftSize) let rolloffPercent: Double = min(1.0, max(0.0, rolloffInput.floatValue(graph: graph))) @@ -158,19 +133,7 @@ public enum SpectralRolloff { rolloffHz = Double(rolloffBin) * binHz } - let target: Double = rolloffHz - let rampStart: Double = _rampTarget - _rampTarget = target - guard count > 0 else { return _result } - previousOutputValue = fillRampedResult( - into: &_result, - from: rampStart, - to: target, - mulAdd: _mulAdd, - graph: graph, - count: count - ) - return _result + return rolloffHz } } } diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralSpread.swift b/Sources/Lyrebird/Generators/Spectral/SpectralSpread.swift index f60695a..84fd9f6 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralSpread.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralSpread.swift @@ -41,14 +41,9 @@ public enum SpectralSpread { /// - sampleRate: Sample rate in Hz. Used to convert bin index to frequency. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset in Hz. Defaults to `0.0`. - public final class Control: GeneratorBase, ControlGenerator { + public final class Control: SpectralFeatureControlBase { - private let _analysis: SpectralChain.Audio? - private let spectral: SpectralBuffer private let sampleRate: Double - private var _mulAdd: MulAddSpec - public var previousOutputValue: Double = 0.0 - private var _rampTarget: Double = 0.0 /// - Parameters: /// - analysis: Paired `SpectralChain.Audio`. Stored as a generator input. @@ -93,31 +88,11 @@ public enum SpectralSpread { mul: any ValidGeneratorInput, add: any ValidGeneratorInput ) { - self._analysis = analysis - self.spectral = spectral self.sampleRate = sampleRate - self._mulAdd = MulAddSpec(mul: mul, add: add) - super.init() - _setupSubBlockBuffer() + super.init(analysis: analysis, spectral: spectral, mul: mul, add: add) } - - // Bypass sub-block loop: spectral buffer is written once per FFT hop. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } - - public func _computeSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _checkCount(count) - - _ = _analysis?.calculatedSamples(graph: graph, count: count) - + override func computeFeature(graph: SynthGraph, count: Int) -> Double { let binCount: Int = spectral.binCount let binHz: Double = sampleRate / Double(spectral.fftSize) @@ -130,35 +105,17 @@ public enum SpectralSpread { totalMag += mag } - let spread: Double - if totalMag == 0.0 { - spread = 0.0 - } else { - let centroidBin: Double = weightedSum / totalMag + guard totalMag != 0.0 else { return 0.0 } + let centroidBin: Double = weightedSum / totalMag - // Pass 2: variance around centroid - var varianceSum: Double = 0.0 - for k: Int in 0.. 0 else { return _result } - previousOutputValue = fillRampedResult( - into: &_result, - from: rampStart, - to: target, - mulAdd: _mulAdd, - graph: graph, - count: count - ) - return _result + return sqrt(varianceSum / totalMag) } } } diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralTilt.swift b/Sources/Lyrebird/Generators/Spectral/SpectralTilt.swift index bd1a892..dfb2843 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralTilt.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralTilt.swift @@ -48,8 +48,7 @@ public final class SpectralTilt: SpectralProcessor { slopeDBPerOctave: Double, pivotHz: Double = 1_000.0 ) { - precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0, - "SpectralTilt: fftSize must be a power of two >= 4, got \(fftSize)") + lyrebirdRequireFFTSize(fftSize, typeName: "SpectralTilt") precondition(sampleRate > 0, "SpectralTilt: sampleRate must be positive, got \(sampleRate)") precondition(pivotHz > 0 && pivotHz < sampleRate * 0.5, diff --git a/Sources/Lyrebird/Generators/TemporalDemand/TimedDemand.swift b/Sources/Lyrebird/Generators/TemporalDemand/TimedDemand.swift index 7cb8bea..6a10846 100644 --- a/Sources/Lyrebird/Generators/TemporalDemand/TimedDemand.swift +++ b/Sources/Lyrebird/Generators/TemporalDemand/TimedDemand.swift @@ -134,7 +134,7 @@ public enum TimedDemand { /// target at the last sample. /// /// `floatValue(graph:)` returns `previousOutputValue` without advancing the sequence. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -144,18 +144,9 @@ public enum TimedDemand { demand: any TimedDemandGenerator ) { super.init(trig: trig, reset: reset, demand: demand) - _setupSubBlockBuffer() } - /// Bypasses the `ControlGenerator` sub-block loop — trigger detection requires - /// scanning the full audio-rate trig input once per block, not per sub-block chunk. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Triggers/Gate.swift b/Sources/Lyrebird/Generators/Triggers/Gate.swift index a2ae8b3..e2aa10e 100644 --- a/Sources/Lyrebird/Generators/Triggers/Gate.swift +++ b/Sources/Lyrebird/Generators/Triggers/Gate.swift @@ -121,7 +121,7 @@ public enum Gate { /// - trig: Gate signal. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -137,18 +137,9 @@ public enum Gate { add: any ValidGeneratorInput = 0.0 ) { super.init(input: input, trig: trig, mul: mul, add: add) - _setupSubBlockBuffer() } - /// Bypasses `ControlGenerator` sub-block loop — gate scanning needs - /// the full audio-rate trigger input once per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Triggers/PulseCount.swift b/Sources/Lyrebird/Generators/Triggers/PulseCount.swift index 4553824..2d39556 100644 --- a/Sources/Lyrebird/Generators/Triggers/PulseCount.swift +++ b/Sources/Lyrebird/Generators/Triggers/PulseCount.swift @@ -143,7 +143,7 @@ public enum PulseCount { /// Defaults to `0.0` (never resets). /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 /// - Parameters: @@ -159,17 +159,8 @@ public enum PulseCount { add: any ValidGeneratorInput = 0.0 ) { super.init(trig: trig, reset: reset, mul: mul, add: add) - _setupSubBlockBuffer() } - /// Bypasses `ControlGenerator` sub-block loop — trigger detection requires scanning - /// the full audio-rate input once per audio block, not per sub-block chunk. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -205,11 +196,7 @@ public enum PulseCount { _prevTrig = prevTrig _prevReset = prevReset - for i: Int in 0.. 0 { previousOutputValue = _result[0][count - 1] } + fillHeldResult(into: &_result, value: count_, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count) return _result } } diff --git a/Sources/Lyrebird/Generators/Triggers/SampleAndHold.swift b/Sources/Lyrebird/Generators/Triggers/SampleAndHold.swift index 34a1305..8e65ca1 100644 --- a/Sources/Lyrebird/Generators/Triggers/SampleAndHold.swift +++ b/Sources/Lyrebird/Generators/Triggers/SampleAndHold.swift @@ -126,7 +126,7 @@ public enum SampleAndHold { /// - trig: Trigger signal. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -142,18 +142,9 @@ public enum SampleAndHold { add: any ValidGeneratorInput = 0.0 ) { super.init(input: input, trig: trig, mul: mul, add: add) - _setupSubBlockBuffer() } - /// Bypasses `ControlGenerator` sub-block loop — edge detection needs - /// the full audio-rate trigger input once per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Triggers/Schmidt.swift b/Sources/Lyrebird/Generators/Triggers/Schmidt.swift index fe6f2f8..effc605 100644 --- a/Sources/Lyrebird/Generators/Triggers/Schmidt.swift +++ b/Sources/Lyrebird/Generators/Triggers/Schmidt.swift @@ -149,7 +149,7 @@ public enum Schmidt { /// - hi: Switch-on threshold (any `ValidGeneratorInput`). Defaults to `0.0`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 /// - Parameters: @@ -168,17 +168,8 @@ public enum Schmidt { add: any ValidGeneratorInput = 0.0 ) { super.init(input: input, lo: lo, hi: hi, mul: mul, add: add) - _setupSubBlockBuffer() } - /// Bypasses `ControlGenerator` sub-block loop — state-machine scanning requires - /// the full audio-rate input once per audio block, not per sub-block chunk. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -207,11 +198,7 @@ public enum Schmidt { } _state = state - for i: Int in 0.. 0 { previousOutputValue = _result[0][count - 1] } + fillHeldResult(into: &_result, value: state, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count) return _result } } diff --git a/Sources/Lyrebird/Generators/Triggers/SendTrigger.swift b/Sources/Lyrebird/Generators/Triggers/SendTrigger.swift index e658547..f374fa6 100644 --- a/Sources/Lyrebird/Generators/Triggers/SendTrigger.swift +++ b/Sources/Lyrebird/Generators/Triggers/SendTrigger.swift @@ -104,7 +104,7 @@ public enum SendTrigger { /// Block-rate edge detection. Posts at most one `TriggerEvent` per block — /// the first ≤0→>0 crossing within the block wins. - public final class Control: _Base, ControlGenerator, RootRegistering { + public final class Control: _Base, BlockRateControlGenerator, RootRegistering { public var previousOutputValue: Double = 0.0 public override init( @@ -113,19 +113,10 @@ public enum SendTrigger { value: any ValidGeneratorInput = 0.0 ) { super.init(trig: trig, id: id, value: value) - _setupSubBlockBuffer() _registerAsRootIfBuilding() } - /// Bypasses `ControlGenerator` sub-block loop — trigger detection requires scanning - /// the full audio-rate trig input once per block, not per sub-block chunk. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Triggers/SignalChanged.swift b/Sources/Lyrebird/Generators/Triggers/SignalChanged.swift index 9adfd38..bc8087d 100644 --- a/Sources/Lyrebird/Generators/Triggers/SignalChanged.swift +++ b/Sources/Lyrebird/Generators/Triggers/SignalChanged.swift @@ -132,7 +132,7 @@ public enum SignalChanged { /// - threshold: Minimum `|Δ input|` to emit `1.0`. Defaults to `0.0`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 /// - Parameters: @@ -148,19 +148,9 @@ public enum SignalChanged { add: any ValidGeneratorInput = 0.0 ) { super.init(input: input, threshold: threshold, mul: mul, add: add) - _setupSubBlockBuffer() } - /// Bypasses `ControlGenerator` sub-block loop — change detection - /// requires scanning the full audio-rate input once per audio block, - /// not per sub-block chunk. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -190,11 +180,7 @@ public enum SignalChanged { _prevSample = prev let value: Double = anyChanged ? 1.0 : 0.0 - for i: Int in 0.. 0 { previousOutputValue = _result[0][count - 1] } + fillHeldResult(into: &_result, value: value, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count) return _result } } diff --git a/Sources/Lyrebird/Generators/Triggers/Stepper.swift b/Sources/Lyrebird/Generators/Triggers/Stepper.swift index f66e0b6..26753a7 100644 --- a/Sources/Lyrebird/Generators/Triggers/Stepper.swift +++ b/Sources/Lyrebird/Generators/Triggers/Stepper.swift @@ -201,7 +201,7 @@ public enum Stepper { /// Init-time scalar. Defaults to `0`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 /// - Parameters: @@ -235,17 +235,8 @@ public enum Stepper { mul: mul, add: add ) - _setupSubBlockBuffer() } - /// Bypasses `ControlGenerator` sub-block loop — trigger detection requires scanning - /// the full audio-rate input once per audio block, not per sub-block chunk. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -285,11 +276,7 @@ public enum Stepper { _prevTrig = prevTrig _prevReset = prevReset - for i: Int in 0.. 0 { previousOutputValue = _result[0][count - 1] } + fillHeldResult(into: &_result, value: Double(value), previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count) return _result } } diff --git a/Sources/Lyrebird/Generators/Triggers/Trig.swift b/Sources/Lyrebird/Generators/Triggers/Trig.swift index 38a3046..da94053 100644 --- a/Sources/Lyrebird/Generators/Triggers/Trig.swift +++ b/Sources/Lyrebird/Generators/Triggers/Trig.swift @@ -139,7 +139,7 @@ public enum Trig { /// - dur: Hold duration in seconds. Clamped to a minimum of 1 sample. Init-time scalar. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 /// - Parameters: @@ -154,17 +154,8 @@ public enum Trig { add: any ValidGeneratorInput = 0.0 ) { super.init(input: input, dur: dur, mul: mul, add: add) - _setupSubBlockBuffer() } - /// Bypasses `ControlGenerator` sub-block loop — trigger detection requires scanning - /// the full audio-rate input once per audio block, not per sub-block chunk. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -210,11 +201,7 @@ public enum Trig { let outputValue: Double = lastOutput - for i: Int in 0.. 0 { previousOutputValue = _result[0][count - 1] } + fillHeldResult(into: &_result, value: outputValue, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count) return _result } } diff --git a/Sources/Lyrebird/Generators/Triggers/Trig1.swift b/Sources/Lyrebird/Generators/Triggers/Trig1.swift index 6dc9d78..546194e 100644 --- a/Sources/Lyrebird/Generators/Triggers/Trig1.swift +++ b/Sources/Lyrebird/Generators/Triggers/Trig1.swift @@ -135,7 +135,7 @@ public enum Trig1 { /// - dur: Hold duration in seconds. Clamped to a minimum of 1 sample. Init-time scalar. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 /// - Parameters: @@ -150,17 +150,8 @@ public enum Trig1 { add: any ValidGeneratorInput = 0.0 ) { super.init(input: input, dur: dur, mul: mul, add: add) - _setupSubBlockBuffer() } - /// Bypasses `ControlGenerator` sub-block loop — trigger detection requires scanning - /// the full audio-rate input once per audio block, not per sub-block chunk. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -203,11 +194,7 @@ public enum Trig1 { let outputValue: Double = lastOutput - for i: Int in 0.. 0 { previousOutputValue = _result[0][count - 1] } + fillHeldResult(into: &_result, value: outputValue, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count) return _result } } diff --git a/Sources/Lyrebird/Generators/Triggers/TriggeredDelay.swift b/Sources/Lyrebird/Generators/Triggers/TriggeredDelay.swift index a31da8e..7000ec7 100644 --- a/Sources/Lyrebird/Generators/Triggers/TriggeredDelay.swift +++ b/Sources/Lyrebird/Generators/Triggers/TriggeredDelay.swift @@ -149,7 +149,7 @@ public enum TriggeredDelay { /// - dur: Delay duration in seconds. Clamped to a minimum of 1 sample. Init-time scalar. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 /// - Parameters: @@ -164,17 +164,8 @@ public enum TriggeredDelay { add: any ValidGeneratorInput = 0.0 ) { super.init(input: input, dur: dur, mul: mul, add: add) - _setupSubBlockBuffer() } - /// Bypasses `ControlGenerator` sub-block loop — trigger detection requires scanning - /// the full audio-rate input once per audio block, not per sub-block chunk. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -218,11 +209,7 @@ public enum TriggeredDelay { let outputValue: Double = fired ? 1.0 : 0.0 - for i: Int in 0.. 0 { previousOutputValue = _result[0][count - 1] } + fillHeldResult(into: &_result, value: outputValue, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count) return _result } } diff --git a/Sources/Lyrebird/Generators/UI/Mouse.swift b/Sources/Lyrebird/Generators/UI/Mouse.swift index 83537a4..64e7fa6 100644 --- a/Sources/Lyrebird/Generators/UI/Mouse.swift +++ b/Sources/Lyrebird/Generators/UI/Mouse.swift @@ -44,25 +44,15 @@ public enum Mouse { public enum X { /// Control-rate horizontal mouse position. - public final class Control: GeneratorBase, ControlGenerator { + public final class Control: GeneratorBase, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 public init() { super.init() - _setupSubBlockBuffer() } - // Bypass sub-block loop: `_rampTarget` advances once per audio block. - // Without this, sub-block dispatch produces N disjointed mini-ramps and - // the ramp state advances N times per block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -100,23 +90,15 @@ public enum Mouse { public enum Y { /// Control-rate vertical mouse position. - public final class Control: GeneratorBase, ControlGenerator { + public final class Control: GeneratorBase, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 public init() { super.init() - _setupSubBlockBuffer() } - // Bypass sub-block loop: see `Mouse.X.Control.calculatedSamples`. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, @@ -154,23 +136,15 @@ public enum Mouse { public enum Click { /// Control-rate left mouse button state (0 = up, 1 = down). - public final class Control: GeneratorBase, ControlGenerator { + public final class Control: GeneratorBase, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 public init() { super.init() - _setupSubBlockBuffer() } - // Bypass sub-block loop: see `Mouse.X.Control.calculatedSamples`. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) - } public func _computeSamples( graph: SynthGraph, diff --git a/Sources/Lyrebird/Generators/Waveshaping/CrossoverDistortion.swift b/Sources/Lyrebird/Generators/Waveshaping/CrossoverDistortion.swift index a94ceeb..4899f78 100644 --- a/Sources/Lyrebird/Generators/Waveshaping/CrossoverDistortion.swift +++ b/Sources/Lyrebird/Generators/Waveshaping/CrossoverDistortion.swift @@ -177,10 +177,7 @@ public enum CrossoverDistortion { let sm: Double = Swift.min(1.0, Swift.max(0.0, _smoothInput.floatValue(graph: graph))) var target: Double = crossoverDistortionSample(x: x, amp: amp, smooth: sm) - if !_mulAdd.isIdentity { - target = target * _mulAdd.mulInput.floatValue(graph: graph) - + _mulAdd.addInput.floatValue(graph: graph) - } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult( into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result diff --git a/Sources/Lyrebird/Generators/Waveshaping/Waveshaper.swift b/Sources/Lyrebird/Generators/Waveshaping/Waveshaper.swift index 0be70c6..0cf55d0 100644 --- a/Sources/Lyrebird/Generators/Waveshaping/Waveshaper.swift +++ b/Sources/Lyrebird/Generators/Waveshaping/Waveshaper.swift @@ -221,10 +221,7 @@ public enum Waveshaper { } else { target = 0.0 } - if !_mulAdd.isIdentity { - target = target * _mulAdd.mulInput.floatValue(graph: graph) - + _mulAdd.addInput.floatValue(graph: graph) - } + target = _mulAdd.applyScalar(target, graph: graph) fillScalarRampedResult( into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) return _result diff --git a/Sources/Lyrebird/Lyrebird.docc/Generators/SpectralFeatures.md b/Sources/Lyrebird/Lyrebird.docc/Generators/SpectralFeatures.md index 8e78027..d61511f 100644 --- a/Sources/Lyrebird/Lyrebird.docc/Generators/SpectralFeatures.md +++ b/Sources/Lyrebird/Lyrebird.docc/Generators/SpectralFeatures.md @@ -664,10 +664,11 @@ hop sizes improve temporal resolution. All six generators: - Pre-allocate their `_result` output buffer in `init` (`lyrebirdDefaultResultBufferSize` Doubles) -- Override `calculatedSamples` to bypass the sub-block loop — the spectral buffer is - written at FFT-hop rate, not sub-block rate, so reading it once per audio block is correct +- Bypass the sub-block loop by conforming to `BlockRateControlGenerator` (via their shared + `SpectralFeatureControlBase`) — the spectral buffer is written at FFT-hop rate, not + sub-block rate, so reading it once per audio block is correct. They therefore never + allocate a `_subBlockBuffer`. - Contain no heap allocation in `_computeSamples` -- Call `_setupSubBlockBuffer()` in their designated `init` ``SpectralFlux/Control`` additionally allocates a `[Float]` array of length `binCount` at init time for the previous-frame magnitude snapshot. diff --git a/Sources/Lyrebird/Lyrebird.docc/Generators/WritingGenerators.md b/Sources/Lyrebird/Lyrebird.docc/Generators/WritingGenerators.md index d6422fc..803b9d4 100644 --- a/Sources/Lyrebird/Lyrebird.docc/Generators/WritingGenerators.md +++ b/Sources/Lyrebird/Lyrebird.docc/Generators/WritingGenerators.md @@ -113,9 +113,10 @@ available for *separately-owned* scratch buffers (zero-fallback rows, sidechain **ControlGenerator pre-allocation** — the default `ControlGenerator._computeSamples` 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` -and must provide their own `floatValue` returning the block target (the `AudioGenerator` -default does not apply): +`_result`. Sub-blocking `ControlGenerator` conformers also must call `_setupSubBlockBuffer()` +from `init` (`BlockRateControlGenerator` conformers never sub-block and omit it) and must +provide their own `floatValue` returning the block target (the `AudioGenerator` default does +not apply): ```swift final class MyLFO: GeneratorBase, ControlGenerator { @@ -281,7 +282,7 @@ class FMSynth: SynthesizerBase { ## 5. Fan-Out Caching — Implement the Gateway Correctly -Implement `_computeSamples`, not `calculatedSamples`. Never override `calculatedSamples`. +Implement `_computeSamples`, not `calculatedSamples`. Never override `calculatedSamples`. (A control generator that must advance once per audio block conforms to `BlockRateControlGenerator` for a block-rate `calculatedSamples` default instead — it still does not override the method.) ```swift // CORRECT — implement _computeSamples diff --git a/Sources/Lyrebird/Lyrebird.docc/ValueComputable.md b/Sources/Lyrebird/Lyrebird.docc/ValueComputable.md index 1b21efe..fc86da9 100644 --- a/Sources/Lyrebird/Lyrebird.docc/ValueComputable.md +++ b/Sources/Lyrebird/Lyrebird.docc/ValueComputable.md @@ -27,7 +27,7 @@ Two return shapes: > Important: ValueComputable is for **non-RT** use. Do not call ``ValueComputable/compute(index:timestamp:)`` (or ``ValueComputable/intCompute(index:timestamp:)``) from any RT context: > - `Generator._computeSamples(graph:count:)` overrides (`AudioGenerator` inner loops) > - `ControlGenerator.Control._computeSamples(graph:count:)` overrides (sub-block loops) -> - `calculatedSamples(graph:count:)` overrides that bypass the sub-block path (bus writers, trigger detectors, gain smoothers, etc.) +> - `BlockRateControlGenerator` conformers' block-rate path (bus writers, trigger detectors, gain smoothers, etc.) > - ``Closure`` bodies (run per-sample on the RT thread) > - Any function reached transitively from the Core Audio render callback > diff --git a/Sources/Lyrebird/Math/PowerOfTwo.swift b/Sources/Lyrebird/Math/PowerOfTwo.swift index 0f639df..5d918e5 100644 --- a/Sources/Lyrebird/Math/PowerOfTwo.swift +++ b/Sources/Lyrebird/Math/PowerOfTwo.swift @@ -15,3 +15,19 @@ func lyrebirdNextPowerOfTwo(_ n: Int) -> Int { while result < n { result <<= 1 } return result } + +/// True when `n` is a positive power of two (`1, 2, 4, 8, …`). +@inline(__always) +func lyrebirdIsPowerOfTwo(_ n: Int) -> Bool { + n > 0 && (n & (n - 1)) == 0 +} + +/// Precondition guard shared by the spectral processors: `fftSize` must be a +/// power of two and at least 4. Called at `init` (not on the RT thread); the +/// message is only built if the check fails. `typeName` names the processor for +/// the trap message. +@inline(__always) +func lyrebirdRequireFFTSize(_ fftSize: Int, typeName: String) { + precondition(fftSize >= 4 && lyrebirdIsPowerOfTwo(fftSize), + "\(typeName): fftSize must be a power of two >= 4, got \(fftSize)") +} diff --git a/Sources/Lyrebird/Spectral/CepstralEnvelopeEstimator.swift b/Sources/Lyrebird/Spectral/CepstralEnvelopeEstimator.swift index 7d63541..f1d877e 100644 --- a/Sources/Lyrebird/Spectral/CepstralEnvelopeEstimator.swift +++ b/Sources/Lyrebird/Spectral/CepstralEnvelopeEstimator.swift @@ -73,8 +73,7 @@ internal final class CepstralEnvelopeEstimator { fftSize: Int, cutoffQuefrency: Int ) { - precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0, - "CepstralEnvelopeEstimator: fftSize must be a power of two >= 4, got \(fftSize)") + lyrebirdRequireFFTSize(fftSize, typeName: "CepstralEnvelopeEstimator") self.fftSize = fftSize self.halfSize = fftSize / 2 self.cutoffQuefrency = Swift.max(1, Swift.min(self.halfSize, cutoffQuefrency)) diff --git a/Sources/Lyrebird/Spectral/SpectralBuffer.swift b/Sources/Lyrebird/Spectral/SpectralBuffer.swift index 3899a7b..ed2b125 100644 --- a/Sources/Lyrebird/Spectral/SpectralBuffer.swift +++ b/Sources/Lyrebird/Spectral/SpectralBuffer.swift @@ -90,8 +90,7 @@ public final class SpectralBuffer: @unchecked Sendable { /// /// - Parameter fftSize: Must be a power of two ≥ 4 (e.g. 1024, 2048, 4096). public init(fftSize: Int) { - precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0, - "SpectralBuffer: fftSize must be a power of two >= 4, got \(fftSize)") + lyrebirdRequireFFTSize(fftSize, typeName: "SpectralBuffer") self.fftSize = fftSize self.binCount = fftSize / 2 + 1 let halfSize: Int = fftSize / 2 diff --git a/Sources/Lyrebird/Spectral/SpectralFrameBuffer.swift b/Sources/Lyrebird/Spectral/SpectralFrameBuffer.swift index 1790192..c2fdab5 100644 --- a/Sources/Lyrebird/Spectral/SpectralFrameBuffer.swift +++ b/Sources/Lyrebird/Spectral/SpectralFrameBuffer.swift @@ -106,7 +106,7 @@ public final class SpectralFrameBuffer: @unchecked Sendable { sampleRate: Double ) { precondition( - fftSize >= 4 && (fftSize & (fftSize - 1)) == 0 && frameCount > 0 && hopSize > 0, + fftSize >= 4 && lyrebirdIsPowerOfTwo(fftSize) && frameCount > 0 && hopSize > 0, "SpectralFrameBuffer: fftSize must be a power of two >= 4, frameCount > 0, hopSize > 0" ) self.fftSize = fftSize diff --git a/Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdGenerator.xctemplate/___FILEBASENAME___.swift b/Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdGenerator.xctemplate/___FILEBASENAME___.swift index 1173c79..654f8d5 100644 --- a/Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdGenerator.xctemplate/___FILEBASENAME___.swift +++ b/Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdGenerator.xctemplate/___FILEBASENAME___.swift @@ -110,10 +110,7 @@ public enum ___FILEBASENAMEASIDENTIFIER___ { var target = ___FILEBASENAMEASIDENTIFIER___._transform( inputSource.floatValue(graph: graph) ) - if !_mulAdd.isIdentity { - target = target * _mulAdd.mulInput.floatValue(graph: graph) - + _mulAdd.addInput.floatValue(graph: graph) - } + target = _mulAdd.applyScalar(target, graph: graph) guard count > 0 else { return _result } let rampStart: Double = previousOutputValue previousOutputValue = target diff --git a/Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdNoiseGenerator.xctemplate/___FILEBASENAME___.swift b/Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdNoiseGenerator.xctemplate/___FILEBASENAME___.swift index 0141ec5..4f94c16 100644 --- a/Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdNoiseGenerator.xctemplate/___FILEBASENAME___.swift +++ b/Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdNoiseGenerator.xctemplate/___FILEBASENAME___.swift @@ -79,15 +79,15 @@ public enum ___FILEBASENAMEASIDENTIFIER___ { } /// Control-rate ___FILEBASENAMEASIDENTIFIER___ — draws one new value per - /// audio block, emits a linear ramp to the new target. Override - /// `calculatedSamples` bypasses the sub-block loop so the draw rate stays - /// at one per audio block regardless of `controlBlockSize`. + /// audio block, emits a linear ramp to the new target. + /// Conforms to `BlockRateControlGenerator` so the draw rate stays at one per + /// audio block regardless of `controlBlockSize`. /// /// - Parameters: /// - seed: PRNG seed. Defaults to a time-derived value. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -104,15 +104,6 @@ public enum ___FILEBASENAMEASIDENTIFIER___ { let controlMixConstant: UInt64 = 0xB220_BBBB_A5A5_C3C3 let initialRngState = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant) super.init(initialRngState: initialRngState, mul: mul, add: add) - _setupSubBlockBuffer() - } - - // Bypass sub-block loop: one draw per audio block regardless of cbs. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) } public func _computeSamples( diff --git a/Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdOscillator.xctemplate/___FILEBASENAME___.swift b/Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdOscillator.xctemplate/___FILEBASENAME___.swift index 00a18fe..72684b1 100644 --- a/Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdOscillator.xctemplate/___FILEBASENAME___.swift +++ b/Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdOscillator.xctemplate/___FILEBASENAME___.swift @@ -111,7 +111,7 @@ public enum ___FILEBASENAMEASIDENTIFIER___ { /// - phase: Initial phase offset in normalized cycles `[0, 1)`. Defaults to `0.0`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. - public final class Control: _Base, ControlGenerator { + public final class Control: _Base, BlockRateControlGenerator { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 @@ -128,15 +128,6 @@ public enum ___FILEBASENAMEASIDENTIFIER___ { add: any ValidGeneratorInput = 0.0 ) { super.init(freq: freq, phase: phase, mul: mul, add: add) - _setupSubBlockBuffer() - } - - // Bypass sub-block loop: phase advances exactly once per audio block. - public func calculatedSamples( - graph: SynthGraph, - count: Int - ) -> [[Double]] { - _calculatedSamplesBlockRate(graph: graph, count: count) } public func _computeSamples( diff --git a/Sources/LyrebirdCLI/Version.swift b/Sources/LyrebirdCLI/Version.swift index 572ff70..ac6723c 100644 --- a/Sources/LyrebirdCLI/Version.swift +++ b/Sources/LyrebirdCLI/Version.swift @@ -5,7 +5,7 @@ // SPDX-License-Identifier: MIT /// The current Lyrebird framework and CLI version. -public let lyrebirdVersion: String = "2.1.0" +public let lyrebirdVersion: String = "2.1.1" /// The banner printed when the interactive shell or REPL session starts. public let welcomeBanner: String = """ diff --git a/Tests/LyrebirdTests/GeneratorCore/BlockRateControlGeneratorTests.swift b/Tests/LyrebirdTests/GeneratorCore/BlockRateControlGeneratorTests.swift new file mode 100644 index 0000000..a148962 --- /dev/null +++ b/Tests/LyrebirdTests/GeneratorCore/BlockRateControlGeneratorTests.swift @@ -0,0 +1,68 @@ +// BlockRateControlGeneratorTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +@MainActor +@Suite("BlockRateControlGenerator") +struct BlockRateControlGeneratorTests { + + /// A `BlockRateControlGenerator` must resolve `calculatedSamples` to the block-rate + /// gateway (the marker's protocol-extension default), NOT the `ControlGenerator` + /// sub-block path — even when `controlBlockSize < blockSize`. These generators drop + /// the `_setupSubBlockBuffer()` allocation, so if the sub-block path were wrongly + /// selected it would trap on the empty `_subBlockBuffer`. No trap + correct output + /// proves the marker default won the `ValidGeneratorInput.calculatedSamples` witness. + @Test func markedControlDoesNotEnterSubBlockPath() throws { + let engine: SynthesisEngine = SynthesisEngine( + blockSize: 512, controlBlockSize: 64, sampleRate: 44100, + numOutputChannels: 2, numInputChannels: 2, + numAudioBuses: 128, numControlBuses: 4096, + driver: OfflineDriver()) + try engine.start() + defer { engine.stop() } + #expect(engine.controlBlockSize < engine.blockSize) + + // Lag with time 0 is transparent; a unit input settles to ~1.0 within the block. + let lag: Lag.Control = Lag.Control(input: ConstantAudioGen(1.0), time: 0.0) + let g: SynthGraph = makeSynthGraph(engine: engine) + let out: [Double] = lag.calculatedSamples(graph: g, count: engine.blockSize)[0] + + #expect(out.count >= engine.blockSize) + #expect(out.prefix(engine.blockSize).allSatisfy { $0.isFinite }) + #expect(abs(out[engine.blockSize - 1] - 1.0) < 1e-6, "got \(out[engine.blockSize - 1])") + + // The real graph calls through `any ValidGeneratorInput`, which resolves via the + // witness table (not concrete-type overload ranking). Exercise that path too: a + // wrong witness (the ControlGenerator sub-block gateway) would still trap here. + let erased: any ValidGeneratorInput = lag + let g2: SynthGraph = makeSynthGraph(engine: engine) + advanceBlock(engine) + let out2: [Double] = erased.calculatedSamples(graph: g2, count: engine.blockSize)[0] + #expect(out2.prefix(engine.blockSize).allSatisfy { $0.isFinite }) + #expect(abs(out2[engine.blockSize - 1] - 1.0) < 1e-6, "got \(out2[engine.blockSize - 1])") + } + + /// Same guarantee through a `BlockRateControlGenerator` conformer that INHERITS the + /// conformance from a non-final base (`SpectralFeatureControlBase`) rather than + /// declaring it directly — the witness must still resolve to the block-rate default. + @Test func inheritedMarkerConformanceDoesNotSubBlock() throws { + let engine: SynthesisEngine = SynthesisEngine( + blockSize: 512, controlBlockSize: 64, sampleRate: 44100, + numOutputChannels: 2, numInputChannels: 2, + numAudioBuses: 128, numControlBuses: 4096, + driver: OfflineDriver()) + try engine.start() + defer { engine.stop() } + + let buffer: SpectralBuffer = SpectralBuffer(fftSize: 1024) + let centroid: any ValidGeneratorInput = SpectralCentroid.Control(spectral: buffer, sampleRate: 44100) + let g: SynthGraph = makeSynthGraph(engine: engine) + let out: [Double] = centroid.calculatedSamples(graph: g, count: engine.blockSize)[0] + #expect(out.prefix(engine.blockSize).allSatisfy { $0.isFinite }) + } +} diff --git a/Tests/LyrebirdTests/Generators/Delays/DelayLineAllpassModulationTests.swift b/Tests/LyrebirdTests/Generators/Delays/DelayLineAllpassModulationTests.swift new file mode 100644 index 0000000..bddbebf --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Delays/DelayLineAllpassModulationTests.swift @@ -0,0 +1,47 @@ +// DelayLineAllpassModulationTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - DelayLineAllpassModulationTests + +/// Regression guard for the allpass fractional-delay interpolator's recursive-state +/// handling. When the delay lands on an exact integer sample (`frac == 0`) the interpolator +/// bypasses to the integer-delayed sample; its recursive state must record that sample as +/// the previous output. Leaving it stale (freezing the pre-bypass value) clicks when the +/// delay dwells on an integer and then moves off. The timeline dwells on an exact integer +/// then ramps a fractional delay out, and the allpass step is compared against the same +/// modulation through `.linear` interpolation, which has no recursive state and stays smooth. +@MainActor +@Suite("DelayLine allpass modulation") +struct DelayLineAllpassModulationTests { + + /// Allpass-vs-linear sample-step ratio tolerated. Correct state handling keeps this + /// ~1×; freezing the stale state drives it past 3× for DelayLine. + let clickRatioLimit: Double = 2.0 + + @Test func modulatedAllpassDelayStaysClickFreeThroughIntegerDwell() throws { + let timeline: [Double] = modulatedDelayDwellTimeline() + let linear: [Double] = try renderModulatedDelay(delaySamples: timeline) { input, modulator, maxDelay in + DelayLine(input: input, maxDelay: maxDelay, delay: modulator, + sampleRate: delaySweepSampleRate, interpolation: .linear) + } + let allpass: [Double] = try renderModulatedDelay(delaySamples: timeline) { input, modulator, maxDelay in + DelayLine(input: input, maxDelay: maxDelay, delay: modulator, + sampleRate: delaySweepSampleRate, interpolation: .allpass) + } + + #expect(allpass.allSatisfy { $0.isFinite }, "allpass output must be finite") + let linearStep: Double = maxAbsDelta(linear) + let allpassStep: Double = maxAbsDelta(allpass) + #expect(linearStep > 0, "linear reference should have non-zero motion") + #expect( + allpassStep < clickRatioLimit * linearStep, + "modulated allpass delay clicks at integer dwell/crossing: allpass maxΔ \(allpassStep) vs linear \(linearStep)" + ) + } +} diff --git a/Tests/LyrebirdTests/Generators/Delays/DelayLineFeedbackAllpassModulationTests.swift b/Tests/LyrebirdTests/Generators/Delays/DelayLineFeedbackAllpassModulationTests.swift new file mode 100644 index 0000000..65854b1 --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Delays/DelayLineFeedbackAllpassModulationTests.swift @@ -0,0 +1,48 @@ +// DelayLineFeedbackAllpassModulationTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - DelayLineFeedbackAllpassModulationTests + +/// Regression guard for the allpass fractional-delay interpolator's recursive-state +/// handling in `DelayLineFeedback` under delay modulation. On an exact integer delay +/// (`frac == 0`) the interpolator must record the integer-delayed sample as its previous +/// output; freezing the stale value clicks when the delay moves back off the integer. Measured against +/// the same modulation through `.linear` interpolation. See +/// `DelayLineAllpassModulationTests` for the timeline rationale. +@MainActor +@Suite("DelayLineFeedback allpass modulation") +struct DelayLineFeedbackAllpassModulationTests { + + let clickRatioLimit: Double = 2.0 + /// Moderate feedback — high feedback rings enough to mask the click in the global metric. + let feedbackDecayTime: Double = 0.012 + + @Test func modulatedAllpassDelayStaysClickFreeThroughIntegerDwell() throws { + let timeline: [Double] = modulatedDelayDwellTimeline() + let linear: [Double] = try renderModulatedDelay(delaySamples: timeline) { input, modulator, maxDelay in + DelayLineFeedback(input: input, maxDelay: maxDelay, delay: modulator, + decayTime: feedbackDecayTime, sampleRate: delaySweepSampleRate, + interpolation: .linear) + } + let allpass: [Double] = try renderModulatedDelay(delaySamples: timeline) { input, modulator, maxDelay in + DelayLineFeedback(input: input, maxDelay: maxDelay, delay: modulator, + decayTime: feedbackDecayTime, sampleRate: delaySweepSampleRate, + interpolation: .allpass) + } + + #expect(allpass.allSatisfy { $0.isFinite }, "allpass output must be finite") + let linearStep: Double = maxAbsDelta(linear) + let allpassStep: Double = maxAbsDelta(allpass) + #expect(linearStep > 0, "linear reference should have non-zero motion") + #expect( + allpassStep < clickRatioLimit * linearStep, + "modulated allpass feedback delay clicks at integer dwell exit: allpass maxΔ \(allpassStep) vs linear \(linearStep)" + ) + } +} diff --git a/Tests/LyrebirdTests/Generators/Filters/AllpassFilterModulationTests.swift b/Tests/LyrebirdTests/Generators/Filters/AllpassFilterModulationTests.swift new file mode 100644 index 0000000..2f53b76 --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Filters/AllpassFilterModulationTests.swift @@ -0,0 +1,50 @@ +// AllpassFilterModulationTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - AllpassFilterModulationTests + +/// Regression guard for the allpass fractional-delay interpolator's recursive-state +/// handling in `AllpassFilter` under delay modulation. The Schroeder allpass reads both an +/// input- and an output-history buffer through the interpolator; at an exact integer delay +/// (`frac == 0`) each interpolator must record its integer-delayed read as the previous +/// output. This two-history form clicks both if the state is zeroed and if the stale +/// pre-bypass value is frozen across an integer dwell. Measured against +/// the same modulation through `.linear` interpolation. See +/// `DelayLineAllpassModulationTests` for the timeline rationale. +@MainActor +@Suite("AllpassFilter allpass modulation") +struct AllpassFilterModulationTests { + + let clickRatioLimit: Double = 2.0 + /// Moderate feedback — high feedback rings enough to mask the click in the global metric. + let feedbackDecayTime: Double = 0.012 + + @Test func modulatedAllpassDelayStaysClickFreeThroughIntegerDwell() throws { + let timeline: [Double] = modulatedDelayDwellTimeline() + let linear: [Double] = try renderModulatedDelay(delaySamples: timeline) { input, modulator, maxDelay in + AllpassFilter(input: input, maxDelay: maxDelay, delay: modulator, + decayTime: feedbackDecayTime, sampleRate: delaySweepSampleRate, + interpolation: .linear) + } + let allpass: [Double] = try renderModulatedDelay(delaySamples: timeline) { input, modulator, maxDelay in + AllpassFilter(input: input, maxDelay: maxDelay, delay: modulator, + decayTime: feedbackDecayTime, sampleRate: delaySweepSampleRate, + interpolation: .allpass) + } + + #expect(allpass.allSatisfy { $0.isFinite }, "allpass output must be finite") + let linearStep: Double = maxAbsDelta(linear) + let allpassStep: Double = maxAbsDelta(allpass) + #expect(linearStep > 0, "linear reference should have non-zero motion") + #expect( + allpassStep < clickRatioLimit * linearStep, + "modulated allpass filter clicks at integer dwell exit: allpass maxΔ \(allpassStep) vs linear \(linearStep)" + ) + } +} diff --git a/Tests/LyrebirdTests/Generators/Filters/CombFilterAllpassModulationTests.swift b/Tests/LyrebirdTests/Generators/Filters/CombFilterAllpassModulationTests.swift new file mode 100644 index 0000000..4365382 --- /dev/null +++ b/Tests/LyrebirdTests/Generators/Filters/CombFilterAllpassModulationTests.swift @@ -0,0 +1,50 @@ +// CombFilterAllpassModulationTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +// MARK: - CombFilterAllpassModulationTests + +/// Regression guard for the allpass fractional-delay interpolator's recursive-state +/// handling in `CombFilter` under delay modulation. On an exact integer delay +/// (`frac == 0`) the interpolator must record the integer-delayed sample as its previous +/// output; freezing the stale value clicks when the delay moves back off the integer. Measured against +/// the same modulation through `.linear` interpolation. See +/// `DelayLineAllpassModulationTests` for the timeline rationale. +@MainActor +@Suite("CombFilter allpass modulation") +struct CombFilterAllpassModulationTests { + + let clickRatioLimit: Double = 2.0 + /// Moderate feedback. High feedback rings strongly enough to mask the state-handling + /// click in the global step metric; this level keeps the stale-state (frozen) click well + /// above the linear-interpolation reference while the fix stays ~1×. + let feedbackDecayTime: Double = 0.012 + + @Test func modulatedAllpassDelayStaysClickFreeThroughIntegerDwell() throws { + let timeline: [Double] = modulatedDelayDwellTimeline() + let linear: [Double] = try renderModulatedDelay(delaySamples: timeline) { input, modulator, maxDelay in + CombFilter(input: input, maxDelay: maxDelay, delay: modulator, + decayTime: feedbackDecayTime, sampleRate: delaySweepSampleRate, + interpolation: .linear) + } + let allpass: [Double] = try renderModulatedDelay(delaySamples: timeline) { input, modulator, maxDelay in + CombFilter(input: input, maxDelay: maxDelay, delay: modulator, + decayTime: feedbackDecayTime, sampleRate: delaySweepSampleRate, + interpolation: .allpass) + } + + #expect(allpass.allSatisfy { $0.isFinite }, "allpass output must be finite") + let linearStep: Double = maxAbsDelta(linear) + let allpassStep: Double = maxAbsDelta(allpass) + #expect(linearStep > 0, "linear reference should have non-zero motion") + #expect( + allpassStep < clickRatioLimit * linearStep, + "modulated allpass comb clicks at integer dwell exit: allpass maxΔ \(allpassStep) vs linear \(linearStep)" + ) + } +} diff --git a/Tests/LyrebirdTests/MulAddTests.swift b/Tests/LyrebirdTests/MulAddTests.swift index cb4cc4a..3215c19 100644 --- a/Tests/LyrebirdTests/MulAddTests.swift +++ b/Tests/LyrebirdTests/MulAddTests.swift @@ -243,4 +243,54 @@ struct MulAddSpecChannelAwareTests { // 4-row generator as `mul:` to a 2-channel `Pan2` traps with "MulAddSpec: mul has // 4 channels but output has 2. mul/add must be mono (broadcast) or match the // output channel count." + + // MARK: - applyScalar (Math.Control scalar fold) + + @Test func applyScalarIdentityReturnsTargetUnchanged() { + let spec: MulAddSpec = MulAddSpec(mul: 1.0, add: 0.0) + #expect(spec.isIdentity) + #expect(spec.applyScalar(0.42, graph: graph) == 0.42) + } + + @Test func applyScalarFoldsScalarMulAdd() { + let spec: MulAddSpec = MulAddSpec(mul: 2.0, add: 1.0) + #expect(!spec.isIdentity) + // 3.0 × 2.0 + 1.0 = 7.0 + #expect(abs(spec.applyScalar(3.0, graph: graph) - 7.0) < 1e-12) + } + + @Test func applyScalarReadsGeneratorValuedMulAdd() { + let spec: MulAddSpec = MulAddSpec(mul: ConstantAudioGen(2.0), add: ConstantAudioGen(1.0)) + #expect(!spec.isIdentity) + #expect(abs(spec.applyScalar(3.0, graph: graph) - 7.0) < 1e-12) + } + + // MARK: - fillHeldResult (held-constant Control fill) + + @Test func fillHeldResultFillsConstantAndSetsPrevious() { + var result: [[Double]] = [[Double](repeating: 0.0, count: 8)] + var prev: Double = -1.0 + fillHeldResult(into: &result, value: 0.5, previousOutputValue: &prev, + mulAdd: .identity, graph: graph, count: 8) + #expect(result[0].allSatisfy { $0 == 0.5 }) + #expect(prev == 0.5) + } + + @Test func fillHeldResultAppliesMulAdd() { + var result: [[Double]] = [[Double](repeating: 0.0, count: 4)] + var prev: Double = 0.0 + let spec: MulAddSpec = MulAddSpec(mul: 2.0, add: 1.0) // 0.5 × 2 + 1 = 2.0 + fillHeldResult(into: &result, value: 0.5, previousOutputValue: &prev, + mulAdd: spec, graph: graph, count: 4) + #expect(result[0].allSatisfy { abs($0 - 2.0) < 1e-12 }) + #expect(abs(prev - 2.0) < 1e-12) + } + + @Test func fillHeldResultCountZeroLeavesStateUntouched() { + var result: [[Double]] = [[Double](repeating: 9.0, count: 4)] + var prev: Double = 7.0 + fillHeldResult(into: &result, value: 0.5, previousOutputValue: &prev, + mulAdd: .identity, graph: graph, count: 0) + #expect(prev == 7.0) + } } diff --git a/Tests/LyrebirdTests/TestHelpers.swift b/Tests/LyrebirdTests/TestHelpers.swift index 86356be..d109390 100644 --- a/Tests/LyrebirdTests/TestHelpers.swift +++ b/Tests/LyrebirdTests/TestHelpers.swift @@ -127,6 +127,125 @@ func rmsValue(_ samples: [Double]) -> Double { return (sumSq / Double(samples.count)).squareRoot() } +/// Largest absolute sample-to-sample difference in a buffer — a click/discontinuity +/// proxy. Returns 0 for buffers shorter than two samples. +func maxAbsDelta(_ samples: [Double]) -> Double { + guard samples.count > 1 else { return 0 } + var maxDelta: Double = 0.0 + for i: Int in 1.. [[Double]] { + _checkCount(count) + let lastIndex: Int = delaySamples.count - 1 + for i: Int in 0..= 0 ? delaySamples[index] : 0) / sr + pos += 1 + } + return _result + } +} + +// MARK: - Modulated-delay click-regression harness + +/// Power-of-two sample rate so a delay-in-samples value divided by it, then multiplied +/// back by the engine rate, recovers the exact integer — letting a delay line's +/// `frac == 0` branch be hit deterministically. +let delaySweepSampleRate: Double = 32768 +let delaySweepBlockSize: Int = 64 +/// Dropped from the front of a rendered timeline before measuring (buffer-fill transient). +let delaySweepWarmupSamples: Int = 256 +/// Headroom in samples added above the timeline's peak delay when sizing the ring buffer. +let delaySweepMaxDelayHeadroom: Double = 8 +private let delaySweepToneHz: Double = 1234.0 +private let delaySweepToneAmp: Double = 0.5 + +/// Builds a delay-in-samples timeline that **dwells on an exact integer** (`frac == 0`, +/// the interpolator bypass branch) for a stretch, then ramps a fractional delay back out. +/// The dwell lets the recursive allpass state settle; the ramp-out's first fractional +/// sample then reveals how the bypass branch left that state. Recording the integer-delayed +/// output as the interpolator's previous output stays click-free; freezing the pre-dwell +/// value emits a transient (it is now stale), and for the two-history Schroeder allpass +/// zeroing the state also emits one. A power-of-two engine rate keeps the integer delay +/// exact so the bypass branch is hit deterministically. +func modulatedDelayDwellTimeline() -> [Double] { + let holdSamples: Int = 1024 + let rampOutSamples: Int = 1024 + let holdDelay: Double = 56.0 // exact integer; exact on a power-of-two rate + let incPerSample: Double = 1.0 / 64.0 + + var timeline: [Double] = [] + timeline.reserveCapacity(holdSamples + rampOutSamples) + for _: Int in 0.. any Generator +) throws -> [Double] { + let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: sampleRate) + try engine.start() + defer { engine.stop() } + + let input: OscSin.Audio = OscSin.Audio(freq: delaySweepToneHz, mul: delaySweepToneAmp) + let modulator: TimelineDelayGenerator = TimelineDelayGenerator( + delaySamples: delaySamples, + sampleRate: sampleRate + ) + let peakDelaySamples: Double = (delaySamples.max() ?? 1) + delaySweepMaxDelayHeadroom + let node: any Generator = makeNode(input, modulator, peakDelaySamples / sampleRate) + + var out: [Double] = [] + let blockCount: Int = Int((Double(delaySamples.count) / Double(blockSize)).rounded(.up)) + for _: Int in 0.. Double { previousOutputValue } ### Control.init — must call _setupSubBlockBuffer() -Every `ControlGenerator.Control.init` must call `_setupSubBlockBuffer()` after `super.init()`. Multi-channel generators use `_setupSubBlockBuffer(channels: N)`. +Every SUB-BLOCKING `ControlGenerator.Control.init` must call `_setupSubBlockBuffer()` after `super.init()`. Multi-channel generators use `_setupSubBlockBuffer(channels: N)`. Exception: `BlockRateControlGenerator` conformers never sub-block and omit it (see Rule 2). ```swift public final class Control: _Base, ControlGenerator { @@ -111,7 +111,7 @@ public final class Control: _Base, ControlGenerator { public override init(...) { // init stored properties first super.init(...) - _setupSubBlockBuffer() // ← required; never call on RT thread + _setupSubBlockBuffer() // ← required for sub-blocking Controls; omit when conforming to BlockRateControlGenerator; never call on RT thread } } ``` @@ -202,40 +202,31 @@ freq = freqInput.calculatedSamples(graph: graph, count: graph.engine.blockSize). freq = freqInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0 ``` -### Rule 2 — Add calculatedSamples bypass for per-audio-block state +### Rule 2 — Conform to BlockRateControlGenerator for per-audio-block state -If the generator's state must advance exactly **once per audio block** (not once per sub-block), add a `calculatedSamples` bypass override. Without it, the sub-block loop calls `_computeSamples` N times per block. +If the generator's state must advance exactly **once per audio block** (not once per sub-block), conform the `Control` class to `BlockRateControlGenerator` instead of `ControlGenerator`. Without it, the sub-block loop calls `_computeSamples` N times per block. -**Generators requiring a bypass:** anything where `_computeSamples` writes to a bus, advances a buffer position, detects trigger edges, smooths a gain value, or draws a random sample that should update at audio-block rate. +**Generators requiring the marker:** anything where `_computeSamples` writes to a bus, advances a buffer position, detects trigger edges, smooths a gain value, draws a random sample, or runs an IIR step on an audio-rate input that should update at audio-block rate. -**Bypass pattern** (identical in every generator — copy verbatim): +**Pattern** — just conform; the marker supplies the block-rate `calculatedSamples` as a protocol default, and the generator skips `_setupSubBlockBuffer()` (it never touches `_subBlockBuffer`): ```swift -// Bypass sub-block loop: . -public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { - let currentSerial = graph.engine.segmentSerial - if _segmentSerial == currentSerial, - let cachedChannel = _cachedResult.first, cachedChannel.count >= count { - return _cachedResult - } - _segmentSerial = currentSerial - _cachedResult = [] - let result = _computeSamples(graph: graph, count: count) - _cachedResult = result - return result +public final class Control: _Base, BlockRateControlGenerator { + // no calculatedSamples override, no _setupSubBlockBuffer() call + public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { … } } ``` -**Decision rule:** if phase advancement is `phase += rate * Double(count) / sampleRate`, sub-blocking is correct and no bypass needed. If state advances once regardless of `count` (e.g. draw one random number, write one bus value, advance one buffer frame, run one IIR step on an audio-rate input), bypass is required. +**Decision rule:** if phase advancement is `phase += rate * Double(count) / sampleRate`, sub-blocking is correct and the marker is NOT needed (stay a plain `ControlGenerator`, call `_setupSubBlockBuffer()`). If state advances once regardless of `count` (e.g. draw one random number, write one bus value, advance one buffer frame, run one IIR step on an audio-rate input), conform to `BlockRateControlGenerator`. **Find prior art** instead of relying on a hand-list: ``` -# Generators that have a bypass override (look here for shape to copy) -grep -rn "public func calculatedSamples" Sources/Lyrebird/Generators/ +# Control generators that bypass sub-blocking (look here for shape to copy) +grep -rln "BlockRateControlGenerator" Sources/Lyrebird/Generators/ # Generators that do NOT (oscillators, LFOs, envelopes — sub-block-correct by construction) ls Sources/Lyrebird/Generators/Oscillators/ Sources/Lyrebird/Generators/Envelope*.swift ``` -The list is too long and changes too often to maintain inline. Apply the decision rule, then check 1–2 nearby generators of similar shape for the exact bypass body. +The list is too long and changes too often to maintain inline. Apply the decision rule, then check 1–2 nearby generators of similar shape. ## Shared Helper Functions — ALWAYS Use @@ -283,7 +274,7 @@ public enum MyGen { private var _rampTarget: Double = 0.0 // if using fillRampedResult public override init(...) { super.init(...) - _setupSubBlockBuffer() // ← required in every Control.init + _setupSubBlockBuffer() // ← required in every sub-blocking Control.init (omit for BlockRateControlGenerator conformers) } public func floatValue(...) -> Double { previousOutputValue } public func _computeSamples(...) -> [[Double]] { ... } @@ -338,7 +329,7 @@ Every new generator needs Swift Testing tests (`@Suite`, `@Test`, `#expect`) in For `ControlGenerator` add: 8. **Ramp** — last sample of first block equals target (use `samples[0][count-1]`, not `samples[0].last` — the pre-allocated buffer is 512 elements) -9. **Sub-block bypass** — if the generator has a `calculatedSamples` bypass override, verify `_computeSamples` is called exactly once even when `controlBlockSize < blockSize` +9. **Sub-block bypass** — if the generator conforms to `BlockRateControlGenerator`, verify `_computeSamples` is called exactly once even when `controlBlockSize < blockSize` Test helpers: `makeTestEngine`, `makeSynthGraph`, `advanceBlock` in `Tests/LyrebirdTests/TestHelpers.swift`. diff --git a/claude/agents/lyrebird_review_agent.md b/claude/agents/lyrebird_review_agent.md index 4e00883..7fdc3be 100644 --- a/claude/agents/lyrebird_review_agent.md +++ b/claude/agents/lyrebird_review_agent.md @@ -28,9 +28,9 @@ Group your review by these categories. Every item below is a blocking finding. ### Generator protocol violations - Redeclaring `_segmentSerial` / `_cachedResult` / `_subBlockBuffer` instead of inheriting from `GeneratorBase`. -- `ControlGenerator.Control.init` missing `_setupSubBlockBuffer()` (or `_setupSubBlockBuffer(channels: N)`) after `super.init()`. +- A sub-blocking `ControlGenerator.Control.init` missing `_setupSubBlockBuffer()` (or `_setupSubBlockBuffer(channels: N)`) after `super.init()`. `BlockRateControlGenerator` conformers are exempt — they never sub-block and must NOT call it. - `Control._computeSamples` using `graph.engine.blockSize` for phase/state advancement (must use `count`); same for any `calculatedSamples(graph:count:)` call on inputs. -- Generators that must advance once per audio block (bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers, IIR filters with audio-rate input) without a `calculatedSamples` bypass override (canonical pattern: `Out.Control`). To verify a `Control` variant in the diff has a bypass when it should: `grep -n "public func calculatedSamples" Sources/Lyrebird/Generators//.swift`. +- Control generators that must advance once per audio block (bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers, IIR filters with audio-rate input, analysers) that fail to conform to `BlockRateControlGenerator` — the marker protocol whose `calculatedSamples` default supplies the block-rate gateway (it replaced the old per-generator `calculatedSamples { _calculatedSamplesBlockRate(...) }` forwarder). To verify a `Control` variant in the diff bypasses sub-blocking when it should: `grep -n "BlockRateControlGenerator" Sources/Lyrebird/Generators//.swift`. A conforming class needs no `calculatedSamples` override and must NOT call `_setupSubBlockBuffer()`; conversely, a true sub-blocker must not conform. - Multi-row generators (`_result.count > 1`) without an `outputChannelCount` override returning the fixed init-time channel count. Missing override silently mono-izes under `+ - * /` operators. - Channel count derived from a runtime-mutable source rather than a `let` constant or `_result.count` set at init. - Static or global mutable state shared between generator instances. diff --git a/claude/skills/lyrebird_release_prep/prepare_release.sh b/claude/skills/lyrebird_release_prep/prepare_release.sh index 9d23dff..2212a29 100755 --- a/claude/skills/lyrebird_release_prep/prepare_release.sh +++ b/claude/skills/lyrebird_release_prep/prepare_release.sh @@ -33,6 +33,8 @@ EXCLUSIONS=( "DOC_UPDATE_PLAN.md" "docs/00-working-order.md" "docs/01-completed-working-order.md" + "docs/plans" + "spikes" ".claude" ".githooks" ".swiftpm" diff --git a/docs/extension-authors-guide.md b/docs/extension-authors-guide.md index 1b6bc10..ce94a7e 100644 --- a/docs/extension-authors-guide.md +++ b/docs/extension-authors-guide.md @@ -168,7 +168,8 @@ points to internalise: 1. Subclass `GeneratorBase`. Inherit `_segmentSerial` / `_cachedResult` / `_subBlockBuffer` — do **not** redeclare them. `_setupSubBlockBuffer()` is - called from `ControlGenerator.Control.init` after `super.init()`. + called from a sub-blocking `ControlGenerator.Control.init` after `super.init()` + (a `BlockRateControlGenerator` conformer never sub-blocks and skips it). 2. Use the shared RT-safe helpers. Inlining them is a review violation. Full table: writing-generators.md §13. SPI surface: extension-sdk.md. diff --git a/docs/protocols/extension-sdk.md b/docs/protocols/extension-sdk.md index 711ec12..869c61c 100644 --- a/docs/protocols/extension-sdk.md +++ b/docs/protocols/extension-sdk.md @@ -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`) diff --git a/docs/protocols/writing-generators.md b/docs/protocols/writing-generators.md index 083b2cb..d219583 100644 --- a/docs/protocols/writing-generators.md +++ b/docs/protocols/writing-generators.md @@ -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, _ 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. diff --git a/docs/stdlib/analysis.md b/docs/stdlib/analysis.md index bfcba4e..a77f5ce 100644 --- a/docs/stdlib/analysis.md +++ b/docs/stdlib/analysis.md @@ -3,8 +3,7 @@ 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 +that advance their internal state exactly once per audio block (via `BlockRateControlGenerator` conformance) so the analysis never double-counts under sub-block control evaluation. ## Catalog