3 Commits

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-07 21:20:49 -07:00
josh 844dc4d9cd v2.1.0 release: Swift 6.4 modernization
Typed throws across the closed-error-set APIs (OSC, MIDI, engine add/schedule,
bus/config/parameter, and the WAV/RF64/Spectral file codecs — source-compatible
narrowing, new .ioFailure cases), plus internal hardening: NSLock-guarded
scheduling/MIDI state moved to Mutex<State>, and the Spectral/FFT scratch owners
moved to a ~Copyable RTScratchBuffer RAII buffer. No API or behavioral change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-24 19:54:59 -07:00
josh 2c20b02e59 docs: consumer migration guide for Lyrebird 1.x → 2.0
Mirror of the dev-repo docs commit: add docs/migrating-to-2.0.md (module
rename + @UIParam/UIParamNode move into core LyrebirdSynth, with the fix)
and the cross-reference from DEVELOPMENT_AND_RELEASE.md. Docs-only; will be
reconciled by the next full release sync.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-23 21:21:45 -07:00
237 changed files with 2308 additions and 3188 deletions
+12 -5
View File
@@ -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<Double>, _ 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,11 +352,15 @@ 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`).
- `RTScratchBuffer<Element>` — `Buffers/RTScratchBuffer.swift`; a `~Copyable` single-owner heap scratch buffer that replaces hand-paired `allocate`/`deinitialize`/`deallocate` in scratch-owning generators (the Spectral/FFT family). `init(count:)` zero-fills (`Element: Numeric`); `init(count:repeating:)` fills any value. `@inline(__always)` `baseAddress`/`count`/`subscript` (`nonmutating set`) so the hot loop matches the raw pointer. Store as a `let` assigned in `init` — never a per-call local. Not for `[UnsafeMutablePointer]` per-channel arrays (a `~Copyable` cannot be `Array`-stored) or capacity-1 scalar boxes used via `.pointee`. `@_spi(LyrebirdExtensions) public`.
Full table, signatures, examples, and the per-generator exceptions (notably `MathGenerators.Control` and the non-standard ControlGenerator ramp paths) live in `docs/protocols/writing-generators.md` §13. That document is the single source of truth — when adding or removing a helper, update §13 and reference it from here.
## Code Review
+1 -1
View File
@@ -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).
+55
View File
@@ -7,6 +7,61 @@ 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
behavioral change, and the public surface stays source-compatible.
**Typed throws.** The closed-error-set APIs now declare their concrete error
type instead of untyped `throws`, so a caller gets an exhaustive `catch` with no
downcast: OSC (`OSCDecodeError` / `OSCServerError`), MIDI (`MIDIError`, on both
the CoreMIDI and ALSA backends), the engine's bus / config / parameter setters,
the public node-add surface — `add` / `schedule` — (`EngineAddError`), and the
self-contained file codecs (`WavFileError` / `RF64WriterError` /
`SpectralFileError`). Narrowing an API from `throws` to `throws(E)` is
source-compatible — existing `try` call sites are unaffected. The WAV and
Spectral codecs gain an `.ioFailure` case that funnels an underlying
`FileHandle` failure into the typed error.
**Concurrency & memory hardening (internal).** NSLock-guarded state in the
scheduling and MIDI classes moved into `Mutex<State>` for compiler-enforced lock
discipline, and the Spectral/FFT scratch owners moved from hand-managed raw
pointers to a `~Copyable` `RTScratchBuffer` (compiler-guaranteed single free, no
ARC on the handle). No API or behavioral change.
---
## 2.0.0 — Linux support
The major release: Lyrebird now runs on **Linux**, in addition to macOS and iOS.
+3 -3
View File
@@ -81,7 +81,7 @@ public final class RF64Writer {
format: AudioFileFormat,
sampleRate: Double,
channels: Int
) throws {
) throws(RF64WriterError) {
guard format == .rf64Float32 || format == .rf64Int24 else {
throw RF64WriterError.unsupportedFormat(format)
}
@@ -173,7 +173,7 @@ public final class RF64Writer {
/// Append `frames` interleaved frames of native Float32 samples, converting to the
/// file encoding. `samples` must contain at least `frames * channels` values.
public func writeFloat32Interleaved(_ samples: UnsafeBufferPointer<Float>, frames: Int) throws {
public func writeFloat32Interleaved(_ samples: UnsafeBufferPointer<Float>, frames: Int) throws(RF64WriterError) {
guard frames > 0 else { return }
let sampleCount: Int = frames * channels
@@ -212,7 +212,7 @@ public final class RF64Writer {
///
/// The `FileHandle` is closed unconditionally (even if patching throws) so a failed
/// finalise never leaks the descriptor.
public func close() throws {
public func close() throws(RF64WriterError) {
guard !closed else { return }
closed = true
defer { try? fileHandle.close() }
@@ -0,0 +1,111 @@
// RTScratchBuffer.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// A single-owner, heap-allocated scratch buffer with compiler-enforced lifetime.
///
/// `RTScratchBuffer` replaces the hand-paired `UnsafeMutablePointer.allocate` /
/// `deinitialize` / `deallocate` dance that scratch-owning generators (the
/// Spectral / FFT family) repeat across many buffers. Because the type is
/// `~Copyable`, the compiler guarantees:
///
/// - it is freed **exactly once**, at `deinit`, with the correct element count —
/// no forgotten free, no double free, no count mismatch;
/// - it cannot be copied, so two owners can never alias the same allocation.
///
/// It carries no ARC: the handle is a raw pointer, so reading or writing an
/// element is a plain load/store with no retain/release traffic. Every accessor
/// is `@inline(__always)`, so a generator's hot loop compiles to the same code
/// as the raw-pointer form it replaces.
///
/// **RT usage.** Allocation happens in `init` (off the render thread, at
/// generator setup); `deinit` runs when the owning generator is freed, which the
/// engine does off the RT thread via its free queue. Element access
/// (`subscript`, ``baseAddress``) is RT-safe — no allocation, no locking, no ARC.
/// Pass ``baseAddress`` to Accelerate / vDSP calls exactly as with a raw pointer.
///
/// ```swift
/// // In a generator:
/// private let _scratch: RTScratchBuffer<Float>
/// init(size: Int) {
/// _scratch = RTScratchBuffer(count: size) // allocated + zero-filled
/// }
/// // deinit is automatic — no teardown code needed.
///
/// func process(count: Int) {
/// vDSP_vsq(input, 1, _scratch.baseAddress, 1, vDSP_Length(count))
/// let peak: Float = _scratch[0]
/// }
/// ```
@_spi(LyrebirdExtensions)
public struct RTScratchBuffer<Element>: ~Copyable {
@usableFromInline let _base: UnsafeMutablePointer<Element>
@usableFromInline let _count: Int
/// Allocates `count` elements, each initialised to `value`.
///
/// Use this when the buffer needs a non-zero initial fill (e.g. a unity gain
/// table initialised to `1`), where the zero-filling ``init(count:)`` would
/// silently seed the wrong value.
///
/// - Parameters:
/// - count: Element capacity. Must be `> 0`.
/// - value: Value written to every element.
@inlinable
public init(count: Int, repeating value: Element) {
precondition(count > 0, "RTScratchBuffer requires count > 0")
_count = count
_base = UnsafeMutablePointer<Element>.allocate(capacity: count)
_base.initialize(repeating: value, count: count)
}
/// Allocates `count` elements, zero-filled. Convenience for numeric buffers.
///
/// - Parameter count: Element capacity. Must be `> 0`.
@inlinable
public init(count: Int) where Element: Numeric {
self.init(count: count, repeating: .zero)
}
/// Base pointer, for Accelerate / vDSP interop and raw indexing. Valid only
/// for the duration of the call — never persist it beyond the lifetime of the
/// buffer (i.e. of the generator that owns it), exactly as with the raw
/// `UnsafeMutablePointer` this replaces.
@inlinable @inline(__always)
public var baseAddress: UnsafeMutablePointer<Element> { _base }
/// Element capacity.
@inlinable @inline(__always)
public var count: Int { _count }
/// Element access. No bounds check — callers stay within `count`, exactly as
/// they must with the raw pointer this replaces.
///
/// The setter is `nonmutating`: writing an element stores through the base
/// pointer and leaves the struct's own fields untouched, so a buffer held as a
/// `let` (the usual case in a generator) is still writable — matching the raw
/// `UnsafeMutablePointer` this replaces.
@inlinable @inline(__always)
public subscript(_ index: Int) -> Element {
get {
#if DEBUG
precondition(index >= 0 && index < _count, "RTScratchBuffer index out of range")
#endif
return _base[index]
}
nonmutating set {
#if DEBUG
precondition(index >= 0 && index < _count, "RTScratchBuffer index out of range")
#endif
_base[index] = newValue
}
}
deinit {
_base.deinitialize(count: _count)
_base.deallocate()
}
}
@@ -24,4 +24,7 @@ public enum WavFileError: Error, Equatable {
/// A plain WAV cannot describe more than 4 GB — its RIFF and `data` sizes
/// are 32-bit. Writing past that needs RF64/W64 instead.
case fileTooLarge(bytes: Int)
/// An underlying file-system operation (`FileHandle` read / seek / write)
/// failed. Associated value is the system error's description.
case ioFailure(String)
}
+34 -13
View File
@@ -28,7 +28,7 @@ public final class WavFileReader {
private var framesRemaining: Int
/// Opens `url` and parses its WAVE header.
public init(url: URL) throws {
public init(url: URL) throws(WavFileError) {
guard let h: FileHandle = try? FileHandle(forReadingFrom: url) else {
throw WavFileError.cannotOpen(url)
}
@@ -51,9 +51,9 @@ public final class WavFileReader {
// File length, for clamping a `data` size the file cannot back. Taken
// by seeking to the end and back rather than stat-ing the path, so it
// describes the handle actually being read.
let scanStart: UInt64 = try h.offset()
let fileByteCount: Int = Int(try h.seekToEnd())
try h.seek(toOffset: scanStart)
let scanStart: UInt64 = try Self.fhOffset(h)
let fileByteCount: Int = Int(try Self.fhSeekToEnd(h))
try Self.fhSeek(h, to: scanStart)
// Walk chunks until the data chunk is located (its body is left unread
// so reads stream from the current file offset).
@@ -90,7 +90,7 @@ public final class WavFileReader {
// and believing it yields a nonsense frame count and a
// `.truncated` throw partway through a render instead of a
// clean EOF.
let remaining: Int = max(0, fileByteCount - Int(try h.offset()))
let remaining: Int = max(0, fileByteCount - Int(try Self.fhOffset(h)))
dataLength = min(size, remaining)
foundData = true
break
@@ -100,10 +100,10 @@ public final class WavFileReader {
// discard it, and a file with embedded artwork or a large
// "LIST" ahead of `data` makes that a real allocation.
let skip: Int = size + (size % 2)
let current: UInt64 = try h.offset()
let current: UInt64 = try Self.fhOffset(h)
let target: UInt64 = current + UInt64(max(0, skip))
guard target <= UInt64(fileByteCount) else { break }
try h.seek(toOffset: target)
try Self.fhSeek(h, to: target)
}
}
@@ -124,7 +124,7 @@ public final class WavFileReader {
/// Reads up to `frames` frames, returning interleaved `Float` samples. The
/// returned array holds `framesRead * channels` values; `framesRead` may be
/// smaller than requested at end of file (and zero once exhausted).
public func read(frames: Int) throws -> [Float] {
public func read(frames: Int) throws(WavFileError) -> [Float] {
let toRead: Int = min(frames, framesRemaining)
guard toRead > 0 else { return [] }
let byteCount: Int = toRead * bytesPerFrame
@@ -169,11 +169,11 @@ public final class WavFileReader {
/// end simply exhausts the reader.
///
/// - Parameter frames: Frames to advance by. Non-positive values do nothing.
public func skip(frames: Int) throws {
public func skip(frames: Int) throws(WavFileError) {
let toSkip: Int = min(frames, framesRemaining)
guard toSkip > 0 else { return }
let current: UInt64 = try handle.offset()
try handle.seek(toOffset: current + UInt64(toSkip * bytesPerFrame))
let current: UInt64 = try Self.fhOffset(handle)
try Self.fhSeek(handle, to: current + UInt64(toSkip * bytesPerFrame))
framesRemaining -= toSkip
}
@@ -202,9 +202,30 @@ public final class WavFileReader {
}
}
private static func readExact(_ h: FileHandle, _ count: Int) throws -> Data {
/// Wraps `FileHandle.offset()`, funneling its foreign error into `WavFileError`.
private static func fhOffset(_ h: FileHandle) throws(WavFileError) -> UInt64 {
do { return try h.offset() }
catch { throw WavFileError.ioFailure(String(describing: error)) }
}
/// Wraps `FileHandle.seekToEnd()`, funneling its foreign error into `WavFileError`.
private static func fhSeekToEnd(_ h: FileHandle) throws(WavFileError) -> UInt64 {
do { return try h.seekToEnd() }
catch { throw WavFileError.ioFailure(String(describing: error)) }
}
/// Wraps `FileHandle.seek(toOffset:)`, funneling its foreign error into `WavFileError`.
private static func fhSeek(_ h: FileHandle, to offset: UInt64) throws(WavFileError) {
do { try h.seek(toOffset: offset) }
catch { throw WavFileError.ioFailure(String(describing: error)) }
}
private static func readExact(_ h: FileHandle, _ count: Int) throws(WavFileError) -> Data {
guard count > 0 else { return Data() }
guard let d: Data = try h.read(upToCount: count), d.count == count else {
let d: Data?
do { d = try h.read(upToCount: count) }
catch { throw WavFileError.ioFailure(String(describing: error)) }
guard let d, d.count == count else {
throw WavFileError.truncated
}
return d
+51 -16
View File
@@ -62,7 +62,7 @@ public final class WavFileWriter {
channels: Int,
sampleRate: Double,
encoding: WavEncoding = .float32
) throws {
) throws(WavFileError) {
precondition(channels >= 1, "WavFileWriter requires at least one channel")
self.channels = channels
self.encoding = encoding
@@ -80,8 +80,11 @@ public final class WavFileWriter {
guard fm.createFile(atPath: url.path, contents: header) else {
throw WavFileError.cannotCreate(url)
}
self.handle = try FileHandle(forWritingTo: url)
try handle.seekToEnd()
let h: FileHandle
do { h = try FileHandle(forWritingTo: url) }
catch { throw WavFileError.ioFailure(String(describing: error)) }
self.handle = h
try Self.fhSeekToEnd(h)
}
/// Appends one block of interleaved `Float` samples.
@@ -89,7 +92,7 @@ public final class WavFileWriter {
/// - Parameters:
/// - samples: Interleaved buffer, length ≥ `frames * channels`.
/// - frames: Number of frames (per-channel sample groups) to write.
public func write(interleaved samples: [Float], frames: Int) throws {
public func write(interleaved samples: [Float], frames: Int) throws(WavFileError) {
let needed: Int = frames * channels
precondition(samples.count >= needed, "interleaved buffer shorter than frames * channels")
var out: Data = Data(capacity: needed * encoding.bytesPerSample)
@@ -121,7 +124,7 @@ public final class WavFileWriter {
out.append(UInt8(truncatingIfNeeded: v >> 16))
}
}
try handle.write(contentsOf: out)
try Self.fhWrite(handle, out)
dataBytesWritten += out.count
}
@@ -133,7 +136,7 @@ public final class WavFileWriter {
}
/// Patches the RIFF and `data` chunk sizes and closes the file. Idempotent.
public func finalize() throws {
public func finalize() throws(WavFileError) {
guard !finalized else { return }
// Chunks are word-aligned: an odd `data` payload (possible with int24)
// needs a pad byte, which counts toward the RIFF size but not the
@@ -143,8 +146,8 @@ public final class WavFileWriter {
// sizing the file for one.
let padByteCount: Int = dataBytesWritten % 2
if padByteCount > 0 && !padByteWritten {
try handle.seekToEnd()
try handle.write(contentsOf: [UInt8(0)])
try Self.fhSeekToEnd(handle)
try Self.fhWrite(handle, [UInt8(0)])
padByteWritten = true
}
let riffChunkSize: UInt32 = try Self.riffChunkSize(
@@ -153,8 +156,8 @@ public final class WavFileWriter {
)
let dataChunkSize: UInt32 = UInt32(dataBytesWritten)
try handle.seek(toOffset: Self.riffChunkSizeOffset)
try handle.write(contentsOf: Self.leBytes(riffChunkSize))
try Self.fhSeek(handle, to: Self.riffChunkSizeOffset)
try Self.fhWrite(handle, Self.leBytes(riffChunkSize))
if !encoding.isPCM {
// `fact` carries the per-channel sample count, which is only known
// now that writing has finished.
@@ -162,12 +165,12 @@ public final class WavFileWriter {
let frames: UInt32 = bytesPerFrame > 0
? UInt32(dataBytesWritten / bytesPerFrame)
: 0
try handle.seek(toOffset: Self.factSampleCountOffset)
try handle.write(contentsOf: Self.leBytes(frames))
try Self.fhSeek(handle, to: Self.factSampleCountOffset)
try Self.fhWrite(handle, Self.leBytes(frames))
}
try handle.seek(toOffset: dataChunkSizeOffset)
try handle.write(contentsOf: Self.leBytes(dataChunkSize))
try handle.close()
try Self.fhSeek(handle, to: dataChunkSizeOffset)
try Self.fhWrite(handle, Self.leBytes(dataChunkSize))
try Self.fhClose(handle)
// Set last: a throw above must leave the writer retryable rather than
// latching "finalized" over a file whose sizes are still zero.
finalized = true
@@ -181,7 +184,7 @@ public final class WavFileWriter {
///
/// - Throws: ``WavFileError/fileTooLarge(bytes:)`` past `UInt32.max`.
@_spi(LyrebirdExtensions)
public static func riffChunkSize(headerBytes: Int, dataBytes: Int) throws -> UInt32 {
public static func riffChunkSize(headerBytes: Int, dataBytes: Int) throws(WavFileError) -> UInt32 {
let payload: Int = headerBytes - 8 + dataBytes
guard payload <= Int(UInt32.max) else {
throw WavFileError.fileTooLarge(bytes: payload)
@@ -189,6 +192,38 @@ public final class WavFileWriter {
return UInt32(payload)
}
// MARK: - FileHandle wrappers (funnel foreign errors into WavFileError)
/// Wraps `FileHandle.seekToEnd()`, funneling its foreign error into `WavFileError`.
private static func fhSeekToEnd(_ h: FileHandle) throws(WavFileError) {
do { try h.seekToEnd() }
catch { throw WavFileError.ioFailure(String(describing: error)) }
}
/// Wraps `FileHandle.seek(toOffset:)`, funneling its foreign error into `WavFileError`.
private static func fhSeek(_ h: FileHandle, to offset: UInt64) throws(WavFileError) {
do { try h.seek(toOffset: offset) }
catch { throw WavFileError.ioFailure(String(describing: error)) }
}
/// Wraps `FileHandle.write(contentsOf:)`, funneling its foreign error into `WavFileError`.
private static func fhWrite(_ h: FileHandle, _ bytes: [UInt8]) throws(WavFileError) {
do { try h.write(contentsOf: bytes) }
catch { throw WavFileError.ioFailure(String(describing: error)) }
}
/// Wraps `FileHandle.write(contentsOf:)` for a `Data` payload.
private static func fhWrite(_ h: FileHandle, _ bytes: Data) throws(WavFileError) {
do { try h.write(contentsOf: bytes) }
catch { throw WavFileError.ioFailure(String(describing: error)) }
}
/// Wraps `FileHandle.close()`, funneling its foreign error into `WavFileError`.
private static func fhClose(_ h: FileHandle) throws(WavFileError) {
do { try h.close() }
catch { throw WavFileError.ioFailure(String(describing: error)) }
}
// MARK: - Header
private static func makeHeader(
+13 -7
View File
@@ -76,7 +76,7 @@ public final class BusAllocator: @unchecked Sendable {
/// Allocates the first contiguous block of `channelCount` free audio buses.
/// Throws `BusAllocatorError.noFreeBus` if no block of that size is available.
public func allocateAudioBus(channelCount: Int) throws -> AudioBus {
public func allocateAudioBus(channelCount: Int) throws(BusAllocatorError) -> AudioBus {
let index: Int = try _allocate(in: &audioFreeList, channelCount: channelCount)
return AudioBus(index: index, channelCount: channelCount)
}
@@ -94,7 +94,7 @@ public final class BusAllocator: @unchecked Sendable {
/// Allocates the first contiguous block of `channelCount` free control buses.
/// Throws `BusAllocatorError.noFreeBus` if no block of that size is available.
public func allocateControlBus(channelCount: Int = 1) throws -> ControlBus {
public func allocateControlBus(channelCount: Int = 1) throws(BusAllocatorError) -> ControlBus {
let index: Int = try _allocate(in: &controlFreeList, channelCount: channelCount)
return ControlBus(index: index, channelCount: channelCount)
}
@@ -113,13 +113,15 @@ public final class BusAllocator: @unchecked Sendable {
private func _allocate(
in freeList: inout [Bool],
channelCount: Int
) throws -> Int {
) throws(BusAllocatorError) -> Int {
precondition(channelCount >= 1, "BusAllocator: channelCount must be >= 1")
return try _lock.withLock {
// The search runs under the lock and returns the start index, or `nil`
// when no block of the requested size is free; the throw happens outside
// the lock because `NSLock.withLock` is `rethrows` and does not narrow to
// the closure's typed error.
let allocated: Int? = _lock.withLock { () -> Int? in
let n: Int = freeList.count
guard channelCount <= n else {
throw BusAllocatorError.noFreeBus(channelCount: channelCount)
}
guard channelCount <= n else { return nil }
var start: Int = 0
outer: while start <= n - channelCount {
for i: Int in start..<(start + channelCount) {
@@ -133,8 +135,12 @@ public final class BusAllocator: @unchecked Sendable {
}
return start
}
return nil
}
guard let index: Int = allocated else {
throw BusAllocatorError.noFreeBus(channelCount: channelCount)
}
return index
}
/// Marks `[startIndex, startIndex + channelCount)` slots back to free. When
@@ -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
+31 -7
View File
@@ -41,6 +41,30 @@ import Synchronization
/// it is callable from any non-RT thread. From a `LyrebirdRoutine` / `LyrebirdTask` body, go
/// through the context (``LyrebirdRoutineContext/add(_:)``, which dispatches to main) rather
/// than calling the engine directly. See `ARCHITECTURE.md` §1 and §9.
///
/// **Deliberately NOT `Sendable`.** This was evaluated and rejected on purpose:
/// - *Checked* `Sendable` is infeasible — the engine holds mutable per-block RT
/// state (node tree, bus memory, block cursors) whose safety comes from the
/// architecture (single-producer `pendingQueue`, atomics, the render-callback
/// happens-before barrier), not from the type system. Those fields cannot be
/// made Sendable-clean without dismantling the RT design.
/// - *`@unchecked`* `Sendable` would be a blanket "safe to share across threads"
/// assertion that is only true for *specific* access patterns (main-thread
/// mutation via the queue; RT-thread reads in `processBlock`) and false for
/// others (mutating config while running, or touching the engine from the RT
/// thread). Declaring it would erase the compiler friction that currently
/// forces each genuine cross-thread transfer to be spelled `nonisolated(unsafe)`
/// at the call site — and those few sites (e.g. `LyrebirdAudioUnit` config
/// hand-off, a UI closure capture) are a *feature*: each is a visible, reviewed
/// "verified safe here" marker on the most concurrency-sensitive object in the
/// system.
///
/// The cost of staying non-Sendable is tiny (a handful of `nonisolated(unsafe)`
/// captures) and the benefit is real (no false safety guarantee, every transfer
/// stays auditable). Classes that hold an engine reference therefore remain
/// `@unchecked Sendable` themselves, keeping their own mutable state in a `Mutex`
/// and naming the engine reference as the sole hand-verified item. Do not add a
/// `Sendable` conformance here without re-opening that trade-off.
public final class SynthesisEngine {
/// Process-unique identity. Used by the engine ownership-binding system
@@ -960,7 +984,7 @@ public final class SynthesisEngine {
/// - Throws: ``SynthesisEngineConfigError/engineIsRunning`` if the engine is
/// currently running; ``SynthesisEngineConfigError/invalidValue(_:)`` if
/// `rate` is non-finite or `<= 0`.
public func setSampleRate(_ rate: Double) throws {
public func setSampleRate(_ rate: Double) throws(SynthesisEngineConfigError) {
guard !isRunning else { throw SynthesisEngineConfigError.engineIsRunning }
guard rate.isFinite, rate > 0 else {
throw SynthesisEngineConfigError.invalidValue(
@@ -982,7 +1006,7 @@ public final class SynthesisEngine {
/// `numAudioBuses`.
/// - Throws: ``SynthesisEngineConfigError/engineIsRunning`` /
/// ``SynthesisEngineConfigError/invalidValue(_:)``.
public func setNumOutputChannels(_ count: Int) throws {
public func setNumOutputChannels(_ count: Int) throws(SynthesisEngineConfigError) {
guard !isRunning else { throw SynthesisEngineConfigError.engineIsRunning }
guard count >= 1 else {
throw SynthesisEngineConfigError.invalidValue(
@@ -1013,7 +1037,7 @@ public final class SynthesisEngine {
/// `numAudioBuses` together with `numOutputChannels`.
/// - Throws: ``SynthesisEngineConfigError/engineIsRunning`` /
/// ``SynthesisEngineConfigError/invalidValue(_:)``.
public func setNumInputChannels(_ count: Int) throws {
public func setNumInputChannels(_ count: Int) throws(SynthesisEngineConfigError) {
guard !isRunning else { throw SynthesisEngineConfigError.engineIsRunning }
guard count >= 0 else {
throw SynthesisEngineConfigError.invalidValue(
@@ -1410,7 +1434,7 @@ public final class SynthesisEngine {
@MainActor public func schedule(
_ synth: any Synthesizer,
at time: SampleTime
) throws {
) throws(EngineAddError) {
precondition(
synth !== rootGroup && synth !== mainGroup,
"Cannot add the engine's persistent rootGroup or mainGroup as a child Synthesizer"
@@ -1439,7 +1463,7 @@ public final class SynthesisEngine {
@MainActor public func schedule(
_ synth: any Synthesizer,
after seconds: Double
) throws {
) throws(EngineAddError) {
precondition(
synth !== rootGroup && synth !== mainGroup,
"Cannot add the engine's persistent rootGroup or mainGroup as a child Synthesizer"
@@ -1509,7 +1533,7 @@ public final class SynthesisEngine {
/// Equivalent to `schedule(_:at:currentTime)`. The synthesizer lands at the head of
/// `mainGroup` — newest-first order. Safe to call from the main thread.
/// - Throws: `EngineAddError` — see `schedule(_:at:)` for cases.
@MainActor public func add(_ synth: any Synthesizer) throws {
@MainActor public func add(_ synth: any Synthesizer) throws(EngineAddError) {
try schedule(synth, at: currentTime)
}
@@ -1526,7 +1550,7 @@ public final class SynthesisEngine {
@MainActor public func add(
_ synth: any Synthesizer,
position: NodePosition
) throws {
) throws(EngineAddError) {
precondition(
synth !== rootGroup && synth !== mainGroup,
"Cannot add the engine's persistent rootGroup or mainGroup as a child Synthesizer"
@@ -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)
}
}
+12 -13
View File
@@ -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,
@@ -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]] = [[]]
@@ -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]
}
+52 -37
View File
@@ -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<Double>) in
guard let base: UnsafeMutablePointer<Double> = 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`
@@ -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,
@@ -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,
@@ -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<Double> = 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
}
@@ -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<Double> = 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
}
@@ -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<Double> = 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
}
@@ -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<Double> = 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
}
@@ -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,
@@ -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..<channelCount {
@@ -444,7 +428,7 @@ public enum PlayBuffer {
/// Defaults to `0.0` (no trigger).
/// - 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, DoneActionWatchable {
public final class Control: _Base, BlockRateControlGenerator, DoneActionWatchable {
public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 0.0
@@ -490,19 +474,10 @@ public enum PlayBuffer {
startPos: startPos, rate: rate, trigger: trigger,
mul: mul, add: add
)
_setupSubBlockBuffer()
_registerAutoFreeIfNeeded(doneAction)
}
// Bypass sub-block loop: PlayBuffer.Control advances _phase once per audio block.
// Sub-blocking would advance it N times per block, running playback at N× speed.
public func calculatedSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_calculatedSamplesBlockRate(graph: graph, count: count)
}
public func _computeSamples(
graph: SynthGraph,
@@ -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,
+1 -12
View File
@@ -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.
+2 -11
View File
@@ -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,
@@ -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,
@@ -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..<count {
_result[0][i] = chaoticInterpolate(_interpolation, phase: _phase,
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
advancePhase(by: dphase)
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
/// Canonical `Control._computeSamples` body: advance the map by one audio block
/// and ramp from the previous block value to the new one. Shared by every
/// concrete chaotic `Control`.
func renderControlBlock(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)
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
}
}
@@ -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..<count {
_result[0][i] = chaoticInterpolate(_interpolation, phase: _phase,
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
advancePhase(by: dphase)
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
return renderAudioBlock(graph: graph, count: count)
}
}
@@ -130,10 +116,7 @@ public enum CuspStepped {
/// - interpolation: Bridging between iterations. Defaults to `.none`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Control: _Base, ControlGenerator {
public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 0.0
public final class Control: _Base, BlockRateControlGenerator {
public func floatValue(graph: SynthGraph) -> 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)
}
}
}
@@ -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..<count {
_result[0][i] = chaoticInterpolate(_interpolation, phase: _phase,
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
advancePhase(by: dphase)
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
return renderAudioBlock(graph: graph, count: count)
}
}
@@ -158,10 +144,7 @@ public enum FBSineStepped {
/// - interpolation: Bridging between iterations. Defaults to `.none`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Control: _Base, ControlGenerator {
public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 0.0
public final class Control: _Base, BlockRateControlGenerator {
public func floatValue(graph: SynthGraph) -> 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)
}
}
}
@@ -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..<count {
_result[0][i] = chaoticInterpolate(_interpolation, phase: _phase,
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
advancePhase(by: dphase)
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
return renderAudioBlock(graph: graph, count: count)
}
}
@@ -111,10 +99,7 @@ public enum GbmanStepped {
/// - interpolation: Bridging between iterations. Defaults to `.none`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Control: _Base, ControlGenerator {
public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 0.0
public final class Control: _Base, BlockRateControlGenerator {
public func floatValue(graph: SynthGraph) -> 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)
}
}
}
@@ -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..<count {
_result[0][i] = chaoticInterpolate(_interpolation, phase: _phase,
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
advancePhase(by: dphase)
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
return renderAudioBlock(graph: graph, count: count)
}
}
@@ -136,10 +122,7 @@ public enum HenonStepped {
/// - interpolation: Bridging between iterations. Defaults to `.none`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Control: _Base, ControlGenerator {
public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 0.0
public final class Control: _Base, BlockRateControlGenerator {
public func floatValue(graph: SynthGraph) -> 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)
}
}
}
@@ -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..<count {
_result[0][i] = chaoticInterpolate(_interpolation, phase: _phase,
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
advancePhase(by: dphase)
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
return renderAudioBlock(graph: graph, count: count)
}
}
@@ -159,10 +145,7 @@ public enum LatoocarfianStepped {
/// - interpolation: Bridging between iterations. Defaults to `.none`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Control: _Base, ControlGenerator {
public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 0.0
public final class Control: _Base, BlockRateControlGenerator {
public func floatValue(graph: SynthGraph) -> 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)
}
}
}
@@ -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..<count {
_result[0][i] = chaoticInterpolate(_interpolation, phase: _phase,
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
advancePhase(by: dphase)
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
return renderAudioBlock(graph: graph, count: count)
}
}
@@ -140,10 +126,7 @@ public enum LinCongStepped {
/// - interpolation: Bridging between iterations. Defaults to `.none`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Control: _Base, ControlGenerator {
public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 0.0
public final class Control: _Base, BlockRateControlGenerator {
public func floatValue(graph: SynthGraph) -> 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)
}
}
}
@@ -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..<count {
_result[0][i] = chaoticInterpolate(_interpolation, phase: _phase,
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
advancePhase(by: dphase)
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
return renderAudioBlock(graph: graph, count: count)
}
}
@@ -168,10 +154,7 @@ public enum LorenzLinear {
/// - interpolation: Bridging between iterations. Defaults to `.linear`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Control: _Base, ControlGenerator {
public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 0.0
public final class Control: _Base, BlockRateControlGenerator {
public func floatValue(graph: SynthGraph) -> 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)
}
}
}
@@ -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..<count {
_result[0][i] = chaoticInterpolate(_interpolation, phase: _phase,
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
advancePhase(by: dphase)
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
return renderAudioBlock(graph: graph, count: count)
}
}
@@ -138,10 +124,7 @@ public enum QuadStepped {
/// - interpolation: Bridging between iterations. Defaults to `.none`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Control: _Base, ControlGenerator {
public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 0.0
public final class Control: _Base, BlockRateControlGenerator {
public func floatValue(graph: SynthGraph) -> 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)
}
}
}
@@ -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..<count {
_result[0][i] = chaoticInterpolate(_interpolation, phase: _phase,
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
advancePhase(by: dphase)
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
return renderAudioBlock(graph: graph, count: count)
}
}
@@ -129,10 +115,7 @@ public enum StandardStepped {
/// - interpolation: Bridging between iterations. Defaults to `.none`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Control: _Base, ControlGenerator {
public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 0.0
public final class Control: _Base, BlockRateControlGenerator {
public func floatValue(graph: SynthGraph) -> 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)
}
}
}
@@ -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)
@@ -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)
@@ -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,
@@ -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,
@@ -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,
@@ -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,
@@ -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,
@@ -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,
@@ -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,
@@ -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
}
@@ -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
@@ -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<Double> = 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
}
}
@@ -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<Double> = 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
}
}
@@ -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<Double>) in
guard let base: UnsafeMutablePointer<Double> = 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
}
}
@@ -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..<count {
let x: Double
+4 -16
View File
@@ -128,8 +128,8 @@ public enum Lag {
/// Control-rate one-pole exponential 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`).
///
/// The coefficient is computed at the control rate (`sampleRate / blockSize`); `time`
/// stays in seconds and the filter converges in `time` wall-clock seconds regardless
@@ -140,7 +140,7 @@ public enum Lag {
/// - time: 60 dB lag time in seconds. `0` = transparent (no smoothing).
/// - 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
@@ -156,12 +156,6 @@ public enum Lag {
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]] {
@@ -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<Double> = 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
}
}
+4 -14
View File
@@ -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<Double> = 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
}
}
@@ -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<Double> = 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
}
}
@@ -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<Double> = 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
}
}
@@ -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<Double> = 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
}
}
@@ -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..<count {
let x: Double
@@ -326,7 +318,7 @@ public enum MuTronIII {
/// Control-rate Mu-Tron III auto-wah — block-rate envelope and filter evaluation.
///
/// Advances the envelope follower and Chamberlin SVF state once per audio block.
/// The sub-block loop is bypassed via a `calculatedSamples` override — IIR state
/// The sub-block loop is bypassed by conforming to `BlockRateControlGenerator` — IIR state
/// must advance exactly once per audio block, processing each input sample exactly
/// once.
///
@@ -342,7 +334,7 @@ public enum MuTronIII {
/// - releaseTime: Envelope release time in seconds. Defaults to `0.15`.
/// - 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
@@ -379,14 +371,8 @@ public enum MuTronIII {
attackTime: attackTime, releaseTime: releaseTime,
mul: mul, add: add
)
_setupSubBlockBuffer()
}
// Bypass sub-block loop: IIR state (envelope follower + SVF) must advance exactly
// once per audio block, processing each input sample exactly once.
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[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
+4 -17
View File
@@ -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,
+3 -18
View File
@@ -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<Double> = 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
}
}
@@ -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)
@@ -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)
@@ -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)
@@ -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..<count {
@@ -180,59 +180,19 @@ public enum KarplusStrong {
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 trigger block.
let triggerSamples: [Double]?
let scalarTrigger: Double
if _triggerIsGenerator {
triggerSamples = _triggerSource.calculatedSamples(graph: graph, count: count).first
scalarTrigger = 0
} else {
triggerSamples = nil
scalarTrigger = _triggerSource.floatValue(graph: graph)
}
let (triggerSamples, scalarTrigger) = resolveGeneratorOrScalar(_triggerSource, isGenerator: _triggerIsGenerator, 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..<count {
+2 -15
View File
@@ -10,20 +10,7 @@
///
/// - Parameter signal: Input signal.
public enum Abs {
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`.
@@ -71,7 +58,7 @@ public enum Abs {
) -> [[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
}
+2 -15
View File
@@ -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
}
+1 -4
View File
@@ -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
}
+2 -15
View File
@@ -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
}
+2 -16
View File
@@ -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
}
+2 -15
View File
@@ -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
}
@@ -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
}
@@ -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
}
+2 -15
View File
@@ -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
}
+1 -4
View File
@@ -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
}
@@ -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
}
@@ -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
}
+2 -15
View File
@@ -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
}
+1 -1
View File
@@ -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
}
+1 -1
View File
@@ -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
}
+1 -4
View File
@@ -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
}
@@ -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
}
@@ -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
}
+1 -1
View File
@@ -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
}
+1 -1
View File
@@ -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
}
+1 -1
View File
@@ -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
}
+1 -1
View File
@@ -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
}
+2 -15
View File
@@ -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
}
+2 -15
View File
@@ -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
}
+2 -15
View File
@@ -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
}
@@ -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
}
+2 -15
View File
@@ -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
}
+2 -15
View File
@@ -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
}
+2 -18
View File
@@ -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
}
@@ -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)
}
}
@@ -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
}
+1 -4
View File
@@ -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
}
@@ -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..<count {
let xA: Double = pathA[i]
@@ -200,35 +200,11 @@ public enum SpatialDistance {
let wrapOffset: Int = delayLineCount * 2
// Fetch input blocks once before the per-sample loop.
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)
let distanceSamples: [Double]?
let scalarDistance: Double
if _distanceIsGenerator {
distanceSamples = _distanceSource.calculatedSamples(graph: graph, count: count).first
scalarDistance = 0
} else {
distanceSamples = nil
scalarDistance = _distanceSource.floatValue(graph: graph)
}
let (distanceSamples, scalarDistance) = resolveGeneratorOrScalar(_distanceSource, isGenerator: _distanceIsGenerator, graph: graph, count: count)
let velocitySamples: [Double]?
let scalarVelocity: Double
if _velocityIsGenerator {
velocitySamples = _velocitySource.calculatedSamples(graph: graph, count: count).first
scalarVelocity = 0
} else {
velocitySamples = nil
scalarVelocity = _velocitySource.floatValue(graph: graph)
}
let (velocitySamples, scalarVelocity) = resolveGeneratorOrScalar(_velocitySource, isGenerator: _velocityIsGenerator, graph: graph, count: count)
let maxDelaySamples: Double = Double(delayLineCount - 2)

Some files were not shown because too many files have changed in this diff Show More