15 Commits

Author SHA1 Message Date
josh 6da3615707 v2.4.0 release: event patterns + live event conductor 2026-12-03 08:45:07 -08:00
josh a175c437de v2.3.3 release: cross-platform driver in docs (makeDefaultAudioDriver) 2026-12-01 21:32:39 -08:00
josh 56726223f6 v2.3.2 release: README — add a 'write your own Generator' example
Adds a complete HardClip audio-rate distortion to the quick-taste section,
showing GeneratorBase + AudioGenerator conformance, init-time input
resolution, the _checkCount guard, and filling/returning the pre-allocated
_result in place — the Generator-authoring counterpart to the existing
graph-composition example.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-29 13:57:47 -08:00
josh 8e600f3a66 v2.3.1: add LyrebirdGUIDemo to the Xcode workspace scheme list
Follow-up to the v2.3.1 content: reference the LyrebirdGUIDemo package from
Lyrebird.xcworkspace so Xcode surfaces its scheme, and note it in the README
schemes table.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-29 11:41:18 -08:00
josh 06bdcbbe92 v2.3.1 release: cross-platform LyrebirdGUIDemo + Linux demo ports + doc refresh
- New Demos/LyrebirdGUIDemo: one shared source (synths + node-based views) that
  bootstraps SwiftUI on macOS and GTK4/SwiftOpenUI on Linux; LYREBIRD_DEMO=vector|sine.
- The four CLI demos (Quickstart/Demo/NRT/Score) now build and run on Linux.
- README + Linux getting-started refreshed; LyrebirdATK row removed from the
  Extensions section pending collaborator sign-off.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-29 11:34:24 -08:00
josh 162da89319 docs: point package URLs at git.lyrebirdsynth.net
Mirror of the dev-repo URL rename. The public gitea host is now reached at
git.lyrebirdsynth.net (a DNS CNAME to realizedsound.mooo.com, the former
hostname; both resolve to the same server). Updates the consumer-facing package
URLs in the README, CONTRIBUTING, install/getting-started docs, the
ProjectScaffolder.lyrebirdPackageURL constant, and the release-prep skill notes.
Doc-only; legacy mooo URLs still resolve, so non-breaking. No tag.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-28 15:19:03 -08:00
josh 9f244b1939 v2.3.0 release: onEditingEnded edit-ended callback on continuous controls
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-25 13:59:52 -08:00
josh 24ea32e47c v2.2.0 release: live-parameter ramp origin primed at synth add
A @UIParam/@LiveParam value assigned after construction but before the first render
is now delivered flat on the first block instead of ramping from the property-
declaration default (fixes e.g. a NoiseGate restored from saved rig state latching
open and ignoring its threshold). Backed by a new internal-facing
LiveParameterValue._primeRampOrigin() (default no-op, source-compatible); live
changes after start still ramp. See RELEASES.md for the full behavior-change note.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-03 12:25:29 -08:00
josh c14efe998a docs(readme): add Linux equivalents for adding the package and opening the project
Mirror of Lyrebird dev HEAD. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-18 18:44:50 -07:00
josh 63b630b317 docs(readme): name VS Code as the Linux IDE in Requirements
Mirror of Lyrebird dev HEAD. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-18 16:40:58 -07:00
josh 3668739d20 docs(readme): add Linux row to the Requirements table
Mirror of Lyrebird dev HEAD. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-18 16:40:05 -07:00
josh 6e7f4c0076 docs(readme): note Linux support alongside macOS/iOS
Mirror of Lyrebird dev HEAD (c8cbb52f). README intro + quick-taste engine line now
name the platform audio backends (Core Audio on Apple, ALSA on Linux). No code change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-18 16:36:10 -07:00
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
321 changed files with 7988 additions and 3313 deletions
+14 -6
View File
@@ -46,7 +46,7 @@ These guards catch classes of regression that **`swift build` / `swift test` str
**Golden values need a test, not a guard.** A typecheck proves an example still *compiles*; it cannot see a documented result drift. Where a doc asserts concrete output (`// → 0.744, 0.046, …`), pin it with a test — `DistributionKindGoldenValueTests` and `_DocTheorySnippetCheckTests` are the two instances. This is not optional pedantry: three of the four `DistributionKind` sequences had silently drifted, and their fences also passed a `seed:` argument to a type that has no such parameter. **Golden values need a test, not a guard.** A typecheck proves an example still *compiles*; it cannot see a documented result drift. Where a doc asserts concrete output (`// → 0.744, 0.046, …`), pin it with a test — `DistributionKindGoldenValueTests` and `_DocTheorySnippetCheckTests` are the two instances. This is not optional pedantry: three of the four `DistributionKind` sequences had silently drifted, and their fences also passed a `seed:` argument to a type that has no such parameter.
`check-doc-snippets.sh` checks the fences recorded in `scripts/doc-snippets-manifest.txt` (currently **426** of 1458). That set is produced by asking the **compiler** which fences compile — `--classify` — never by hand-annotating fences. A fence that compiles under no preamble self-excludes, which is how iOS-only examples, `Package.swift` snippets and pseudo-code drop out with no skip list. **Coverage is therefore partial by construction**: a fragment like `try engine.add(MySynth())`, which needs both an `engine` and a `MySynth` in scope, is *not* checked. The fix for an important uncovered example is to make it self-contained in the doc — which is better documentation anyway — not to grow the preamble table. Re-run `--classify` after adding examples or deliberately changing what is checkable. `check-doc-snippets.sh` checks the fences recorded in `scripts/doc-snippets-manifest.txt` (currently **578** of 1584). That set is produced by asking the **compiler** which fences compile — `--classify` — never by hand-annotating fences. A fence that compiles under no preamble self-excludes, which is how iOS-only examples, `Package.swift` snippets and pseudo-code drop out with no skip list. **Coverage is therefore partial by construction**: a fragment like `try engine.add(MySynth())`, which needs both an `engine` and a `MySynth` in scope, is *not* checked. The fix for an important uncovered example is to make it self-contained in the doc — which is better documentation anyway — not to grow the preamble table. Re-run `--classify` after adding examples or deliberately changing what is checkable.
## Task → Doc Map ## Task → Doc Map
@@ -76,6 +76,7 @@ These guards catch classes of regression that **`swift build` / `swift test` str
- Node tree / Group nesting / bus routing → `docs/protocols/node-tree.md` - Node tree / Group nesting / bus routing → `docs/protocols/node-tree.md`
- Routines / tasks / clock / MIDI / OSC → `docs/tooling/routine-task.md` - Routines / tasks / clock / MIDI / OSC → `docs/tooling/routine-task.md`
- `Pattern<T>` factory catalog (sequence, series, geometric, uniformRandom, brownian, gaussian, cauchy, beta, shuffle, nonRepeatingRandom, weightedRandom, closure, repeating, limit, drop, stutter, switching, concatenate, roundRobin, tuple, interleave, map, filter, reject, accumulate, difference, wrap, clip, round, smooth) → `docs/tooling/routine-task.md` (§ Pattern Factory Reference) + `Sources/Lyrebird/Lyrebird.docc/RoutineTask.md` - `Pattern<T>` factory catalog (sequence, series, geometric, uniformRandom, brownian, gaussian, cauchy, beta, shuffle, nonRepeatingRandom, weightedRandom, closure, repeating, limit, drop, stutter, switching, concatenate, roundRobin, tuple, interleave, map, filter, reject, accumulate, difference, wrap, clip, round, smooth) → `docs/tooling/routine-task.md` (§ Pattern Factory Reference) + `Sources/Lyrebird/Lyrebird.docc/RoutineTask.md`
- Event patterns — `EventPattern` (SC `Pbind`: typed keyPath bindings → voice `@LiveParam`s, dur/legato scheduling, `EventGated` gate note-off or `EventSustainAware` self-timed release; non-blocking gate close via `LyrebirdRoutineContext.set(_:to:afterBeats:)`), `MonoEventPattern` (SC `Pmono`/`PmonoArtic`: one reused voice, params updated per event, optional `EventRetriggerable` re-strike), `ParallelEventPattern` (SC `Ppar`: heterogeneous `EventPatternPlayable` children started together, one merged `EventPatternHandle`; `add` = enter-with-group, `addAfter(beats:)` = staggered entry via `startAfterBeats` lead-in), `EventConductor` (live, clock-driven ensemble — thread-safe `add(_:quantize:)` from UI/OSC/MIDI while running, returns an `EventConductorHandle` for per-part stop; clock-deferred entry quantised by `EventQuantum` against the conductor's own clock, tempo-independent; patterns keep own timing after entry), `EventConductorHandle` (stop one part: cancels if pending, stops if playing), `EventPatternHandle` → `docs/tooling/routine-task.md` (§ EventPattern / § EventConductor) + `Sources/Lyrebird/Patterns/Events/`
- MIDI clock sync (`MIDIClockFollower`) → `docs/tooling/midi-clock-sync.md` - MIDI clock sync (`MIDIClockFollower`) → `docs/tooling/midi-clock-sync.md`
- Linux MIDI (`MIDI` via ALSA sequencer — `MIDI/ALSAMIDI.swift`, `ALSASeqMIDIEvent` mapping; needs CALSA/libasound) → `Sources/Lyrebird/MIDI/ALSAMIDI.swift` - Linux MIDI (`MIDI` via ALSA sequencer — `MIDI/ALSAMIDI.swift`, `ALSASeqMIDIEvent` mapping; needs CALSA/libasound) → `Sources/Lyrebird/MIDI/ALSAMIDI.swift`
- Linux OSC (`OSCClient` / `OSCServer` POSIX-UDP transport off Apple, `OSCServerError`; codec unchanged) → `Sources/Lyrebird/OSC/OSCServer.swift` - Linux OSC (`OSCClient` / `OSCServer` POSIX-UDP transport off Apple, `OSCServerError`; codec unchanged) → `Sources/Lyrebird/OSC/OSCServer.swift`
@@ -135,9 +136,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. - 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. - `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. - 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. - `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`. - 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`. - `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 +332,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: 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` - `_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. - `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. - `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. - `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. - `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. - `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 +345,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). - `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`). - `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. - `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`. - `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`. - `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`. - `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 +353,15 @@ Module-level helpers exist to eliminate repeated boilerplate; inlining any of th
- `_mulAdd.applyIfNeeded(to:graph:count:)` - `_mulAdd.applyIfNeeded(to:graph:count:)`
- `fillRampedResult(into:from:to:mulAdd: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`. - `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(_:)` - `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`) - `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`). - `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. 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 ## Code Review
+2 -2
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. - **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. - **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. - **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. - **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. - **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). - **Denormal hygiene** — flush denormals to zero in feedback paths (filters, delays, reverbs).
@@ -127,7 +127,7 @@ let package = Package(
.library(name: "LyrebirdMyExtension", targets: ["LyrebirdMyExtension"]), .library(name: "LyrebirdMyExtension", targets: ["LyrebirdMyExtension"]),
], ],
dependencies: [ dependencies: [
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.0.0"), .package(url: "https://git.lyrebirdsynth.net/josh/Lyrebird", from: "1.0.0"),
], ],
targets: [ targets: [
.target( .target(
@@ -9,6 +9,7 @@
/* Begin PBXBuildFile section */ /* Begin PBXBuildFile section */
0306C7C02FAC451300952EAF /* GVerbTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0306C7BF2FAC451300952EAF /* GVerbTest.swift */; }; 0306C7C02FAC451300952EAF /* GVerbTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0306C7BF2FAC451300952EAF /* GVerbTest.swift */; };
0306C7C22FAC45F200952EAF /* ReverbDemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0306C7C12FAC45F200952EAF /* ReverbDemo.swift */; }; 0306C7C22FAC45F200952EAF /* ReverbDemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0306C7C12FAC45F200952EAF /* ReverbDemo.swift */; };
631D4C5B1150427CB8D15210 /* EventPatternDemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 99B83EC83F6C48D98441D7F7 /* EventPatternDemo.swift */; };
035A2F422FAA4F67007F6289 /* PercPitchShift.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F3F2FAA4F67007F6289 /* PercPitchShift.swift */; }; 035A2F422FAA4F67007F6289 /* PercPitchShift.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F3F2FAA4F67007F6289 /* PercPitchShift.swift */; };
035A2F432FAA4F67007F6289 /* PercSpectralPitchShift.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F412FAA4F67007F6289 /* PercSpectralPitchShift.swift */; }; 035A2F432FAA4F67007F6289 /* PercSpectralPitchShift.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F412FAA4F67007F6289 /* PercSpectralPitchShift.swift */; };
035A2F482FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F492FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift */; }; 035A2F482FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F492FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift */; };
@@ -26,6 +27,7 @@
/* Begin PBXFileReference section */ /* Begin PBXFileReference section */
0306C7BF2FAC451300952EAF /* GVerbTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GVerbTest.swift; sourceTree = "<group>"; }; 0306C7BF2FAC451300952EAF /* GVerbTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GVerbTest.swift; sourceTree = "<group>"; };
0306C7C12FAC45F200952EAF /* ReverbDemo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReverbDemo.swift; sourceTree = "<group>"; }; 0306C7C12FAC45F200952EAF /* ReverbDemo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReverbDemo.swift; sourceTree = "<group>"; };
99B83EC83F6C48D98441D7F7 /* EventPatternDemo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EventPatternDemo.swift; sourceTree = "<group>"; };
035A2F3E2FAA4F67007F6289 /* PercBufferRead.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercBufferRead.swift; sourceTree = "<group>"; }; 035A2F3E2FAA4F67007F6289 /* PercBufferRead.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercBufferRead.swift; sourceTree = "<group>"; };
035A2F3F2FAA4F67007F6289 /* PercPitchShift.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercPitchShift.swift; sourceTree = "<group>"; }; 035A2F3F2FAA4F67007F6289 /* PercPitchShift.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercPitchShift.swift; sourceTree = "<group>"; };
035A2F402FAA4F67007F6289 /* PercPlayBuffer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercPlayBuffer.swift; sourceTree = "<group>"; }; 035A2F402FAA4F67007F6289 /* PercPlayBuffer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercPlayBuffer.swift; sourceTree = "<group>"; };
@@ -56,6 +58,7 @@
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
0306C7C12FAC45F200952EAF /* ReverbDemo.swift */, 0306C7C12FAC45F200952EAF /* ReverbDemo.swift */,
99B83EC83F6C48D98441D7F7 /* EventPatternDemo.swift */,
035B00032FAB0000007F0001 /* DemoProtocol.swift */, 035B00032FAB0000007F0001 /* DemoProtocol.swift */,
035B00042FAB0000007F0001 /* BufferDemos.swift */, 035B00042FAB0000007F0001 /* BufferDemos.swift */,
); );
@@ -207,6 +210,7 @@
035A2F482FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift in Sources */, 035A2F482FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift in Sources */,
035A2F442FAA4F67007F6289 /* PercBufferRead.swift in Sources */, 035A2F442FAA4F67007F6289 /* PercBufferRead.swift in Sources */,
0306C7C22FAC45F200952EAF /* ReverbDemo.swift in Sources */, 0306C7C22FAC45F200952EAF /* ReverbDemo.swift in Sources */,
631D4C5B1150427CB8D15210 /* EventPatternDemo.swift in Sources */,
035A2F452FAA4F67007F6289 /* PercPlayBuffer.swift in Sources */, 035A2F452FAA4F67007F6289 /* PercPlayBuffer.swift in Sources */,
C1A000000000000000000007 /* main.swift in Sources */, C1A000000000000000000007 /* main.swift in Sources */,
C1A000000000000000000016 /* SineTone.swift in Sources */, C1A000000000000000000016 /* SineTone.swift in Sources */,
@@ -0,0 +1,110 @@
// EventPatternDemo.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
/// Demonstrates ``EventPattern`` — Lyrebird's event-driven player: bound value patterns drive a
/// fresh self-freeing voice per event, played as a dur/legato-timed stream.
///
/// Also shows two patterns running together via ``ParallelEventPattern``: a lead phrase and a
/// bass line that enters a few beats in on the same beat grid, with a single
/// ``EventPatternHandle/waitUntilComplete(releasePadding:)`` blocking until the longer of the two
/// finishes.
final class EventPatternDemo: DemoProtocol {
private let engine: SynthesisEngine
init(engine: SynthesisEngine) {
self.engine = engine
}
/// A gated voice (``EventGated``): a sine through an `EnvelopeGen` whose gate holds it at full
/// level while the note sounds, then plays a release and frees the voice via
/// `doneAction: .freeNode` when `EventPattern` closes the gate at the note's sustain. No
/// external removal, so the release is never hard-cut — nothing to tune, no click.
private final class BlipVoice: SynthesizerBase, EventGated {
/// Envelope release length in seconds — how long a note rings after its gate closes.
/// Exposed so the demo can let the final note's tail finish before stopping the engine.
nonisolated static let releaseSeconds: Double = 0.3
/// Envelope attack length in seconds.
nonisolated static let attackSeconds: Double = 0.01
@LiveParam var freq: Double = 440.0
@LiveParam var amp: Double = 0.2
@LiveParam var gate: Double = 1.0 // open by default so the attack fires on add
var eventGate: ParameterNode { $gate }
override func build() {
// `releaseNode: 1` holds at `levels[1]` (full) while the gate is open; when the gate
// drops to 0 the generator plays segment 1 (the release to 0) and then self-frees.
let envelope: Envelope = Envelope(
levels: [0.0, 1.0, 0.0],
durations: [BlipVoice.attackSeconds, BlipVoice.releaseSeconds],
curves: [.welch, .welch],
releaseNode: 1
)
let shaped: EnvelopeGen.Audio = EnvelopeGen.Audio(
envelope: envelope,
gate: $gate,
doneAction: .freeNode
)
let source: OscSin.Audio = OscSin.Audio(freq: $freq, mul: $amp)
output(bus: 0, source: source * shaped)
}
}
func runDemo() {
print("\n── EventPattern demo ──")
let tempoBPM: Double = 132.0
// Pattern 1 — the lead: a short A-minor-pentatonic phrase, written as named pitches rather
// than raw Hz (equivalent MIDI form: `Pitch.midi(69).frequency`, etc.), played three times.
let phrase: [Pitch] = [
.named(.a, 4), .named(.c, 5), .named(.d, 5), .named(.e, 5),
.named(.g, 5), .named(.e, 5), .named(.d, 5), .named(.c, 5),
]
let leadFreqs: [Double] = phrase.compactMap(\.frequency)
let lead: EventPattern<BlipVoice> = EventPattern(make: { BlipVoice() })
.bind(\.freq, .sequence(leadFreqs, repeats: 1))
.bind(\.amp, .uniformRandom(low: 0.15, high: 0.3))
.dur(.sequence([0.25, 0.25, 0.25, 0.5]))
.legato(0.8)
.tempo(tempoBPM)
.repeats(3)
// Pattern 2 — a bass line that enters `leadInBeats` after the lead and outlasts it.
// There is no cross-pattern clock: `ParallelEventPattern` launches both children from the
// one `play` call, so they share a start instant, and at the SAME tempo they share a beat
// grid. `addAfter(beats:)` staggers the bass's entry on that grid — the bass simply waits
// `leadInBeats` beats before its first note.
let leadInBeats: Double = 2.0
let bassPhrase: [Pitch] = [.named(.a, 2), .named(.a, 2), .named(.g, 2), .named(.e, 2)]
let bassFreqs: [Double] = bassPhrase.compactMap(\.frequency)
let bass: EventPattern<BlipVoice> = EventPattern(make: { BlipVoice() })
.bind(\.freq, .sequence(bassFreqs, repeats: 1))
.bind(\.amp, .uniformRandom(low: 0.2, high: 0.3))
.dur(.sequence([1.0]))
.legato(0.9)
.tempo(tempoBPM)
.repeats(1)
// Start both together, staggering the bass two beats in, and control them as one handle.
let ensemble: ParallelEventPattern = ParallelEventPattern()
ensemble.add(lead)
ensemble.addAfter(beats: leadInBeats, eventPattern: bass)
let handle: EventPatternHandle = ensemble.play(on: engine)
// `waitUntilComplete` blocks until EVERY child task has finished — so it waits for the
// longer-running bass, not just the lead. `releasePadding` then lets the final note's
// envelope release ring out before `main.swift` stops the engine — without it,
// `engine.stop()` would cut the tail (an end-of-phrase click).
handle.waitUntilComplete(releasePadding: BlipVoice.releaseSeconds)
print("\nEventPattern demo complete.")
}
}
+16 -4
View File
@@ -7,12 +7,21 @@
import Foundation import Foundation
import LyrebirdSynth import LyrebirdSynth
// ── Demo selector ─────────────────────────────────────────────────────────────
// Change `demo` to `.buffer`, `.reverb`, or `.eventPattern` to switch demos.
private enum Demo { case buffer, reverb, eventPattern }
private let demo: Demo = .eventPattern
// ──────────────────────────────────────────────────────────────────────────────
// `makeDefaultAudioDriver()` selects the platform backend — Core Audio on Apple,
// ALSA on Linux (needs libasound) — so the demo builds and runs on both.
let engine = SynthesisEngine( let engine = SynthesisEngine(
blockSize: 512, blockSize: 512,
sampleRate: 44100, controlBlockSize: 64,
sampleRate: 48000,
numOutputChannels: 2, numOutputChannels: 2,
numInputChannels: 2, numInputChannels: 2,
driver: CoreAudioDriver() driver: makeDefaultAudioDriver()
) )
do { do {
@@ -22,7 +31,10 @@ do {
exit(1) exit(1)
} }
// BufferDemos(engine: engine).runDemo() switch demo {
ReverbDemo(engine: engine).runDemo() case .buffer: BufferDemos(engine: engine).runDemo()
case .reverb: ReverbDemo(engine: engine).runDemo()
case .eventPattern: EventPatternDemo(engine: engine).runDemo()
}
engine.stop() engine.stop()
+24
View File
@@ -0,0 +1,24 @@
{
"originHash" : "c2996d6577ec0139a89be2f2d57d304047b7d5bf7f7eba2577fde9dc2fdc0b91",
"pins" : [
{
"identity" : "linenoise-swift",
"kind" : "remoteSourceControl",
"location" : "https://github.com/andybest/linenoise-swift",
"state" : {
"revision" : "afc897c02b030af7333105c4fedcd843a8339238",
"version" : "0.0.3"
}
},
{
"identity" : "nimble",
"kind" : "remoteSourceControl",
"location" : "https://github.com/Quick/Nimble.git",
"state" : {
"revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0",
"version" : "7.3.4"
}
}
],
"version" : 3
}
+48
View File
@@ -0,0 +1,48 @@
// Package.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// swift-tools-version: 6.0
import PackageDescription
// A single cross-platform GUI demo: one shared library of synths + views, and a
// thin executable entry point that bootstraps the native toolkit per platform —
// AppKit/SwiftUI on macOS, GTK4/SwiftOpenUI on Linux. The view bodies are written
// to the subset of the View DSL that both backends share, so the UI is one source.
//
// macOS: swift run LyrebirdGUIDemo (or open the thin Xcode project)
// Linux: swift run LyrebirdGUIDemo (needs libgtk-4-dev + libasound2-dev)
//
// Select the synth with LYREBIRD_DEMO=vector (default), sine, or conductor.
let package = Package(
name: "LyrebirdGUIDemo",
platforms: [.macOS(.v15)],
products: [
.library(name: "LyrebirdGUIDemoKit", targets: ["LyrebirdGUIDemoKit"]),
.executable(name: "LyrebirdGUIDemo", targets: ["LyrebirdGUIDemo"]),
],
dependencies: [
.package(path: "../.."),
],
targets: [
.target(
name: "LyrebirdGUIDemoKit",
dependencies: [
.product(name: "Lyrebird", package: "Lyrebird"),
.product(name: "LyrebirdUI", package: "Lyrebird"),
],
path: "Sources/LyrebirdGUIDemoKit"
),
.executableTarget(
name: "LyrebirdGUIDemo",
dependencies: [
"LyrebirdGUIDemoKit",
.product(name: "Lyrebird", package: "Lyrebird"),
.product(name: "LyrebirdUI", package: "Lyrebird"),
],
path: "Sources/LyrebirdGUIDemo"
),
]
)
+58
View File
@@ -0,0 +1,58 @@
<!--
README.md
Lyrebird
Copyright (c) 2026 Joshua Parmenter / realizedsound
SPDX-License-Identifier: MIT
-->
# LyrebirdGUIDemo — one GUI demo, two platforms
A live-controllable synth GUI that builds and runs from a single source tree on
**macOS** (AppKit + SwiftUI) and **Linux** (GTK4 + SwiftOpenUI). It is the
cross-platform counterpart to the richer, macOS-only `LyrebirdMacOSDemo` Xcode
project.
The split follows the "mostly in a package, thin entry points" shape:
| Piece | Where | Platform |
|---|---|---|
| Synths + views | `Sources/LyrebirdGUIDemoKit/` | shared — one source |
| App bootstrap | `Sources/LyrebirdGUIDemo/main.swift` | one `#if` (AppKit vs GTK4) |
The view bodies are written to the subset of the View DSL that SwiftUI and
SwiftOpenUI share, so there is **one** body per view — not a macOS copy and a
Linux copy. Both back ends bind the same core `@UIParam` / `UIParamNode` model,
so the controls, the oscilloscope, and the CPU meters are identical.
## Run it
```bash
swift run LyrebirdGUIDemo # vector oscillator (default)
LYREBIRD_DEMO=sine swift run LyrebirdGUIDemo # stereo sine tone
```
- **macOS** — no extra setup; a native window opens with live audio via Core Audio.
- **Linux** — needs `libgtk-4-dev` (GUI) and `libasound2-dev` + a sound device
(audio). Without a sound backend the window still opens and the controls work;
there is just no sound (`isLiveAudioAvailable` reports it, and the console says so).
## Open in an IDE
- **Xcode (macOS)** — open the folder (or `Package.swift`); Xcode treats it as a
SwiftPM package. Pick the `LyrebirdGUIDemo` scheme and Run. No `.xcodeproj` to
maintain — the package *is* the project.
- **VS Code (Linux)** — open the folder with the Swift extension
(`swiftlang.swift-vscode`); it picks up `Package.swift`. Run `LyrebirdGUIDemo`
from the test/run explorer or a terminal.
## What each demo shows
- **vector** — `VectorOscillatorUI`: an XY pad crossfades four corner wavetables
(sine / saw-ish / triangle / Hanning); frequency and amplitude knobs; a live
oscilloscope and CPU-load strip.
- **sine** — `SineToneUI`: a frequency slider, amplitude and pan knobs, a level
readout, the scope and CPU strip, and a static envelope plot.
Add a synth by dropping a `SynthesizerBase` subclass and a node-based view into
`LyrebirdGUIDemoKit`, then extend `DemoSelection` and the `demoContent()` switch
in `main.swift`.
@@ -0,0 +1,186 @@
// main.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// Thin cross-platform entry point. The shared synths + views live in
// `LyrebirdGUIDemoKit`; this file only bootstraps the native toolkit and opens a
// window hosting the selected demo view:
//
// • macOS — AppKit `NSApplication` + `LyrebirdWindow` (SwiftUI content).
// • Linux — a GTK4 `App`/`WindowGroup` scene run by `GTK4Backend`.
//
// Run either with `swift run LyrebirdGUIDemo`. Pick the synth with
// `LYREBIRD_DEMO=vector` (default), `sine`, or `conductor`.
//
// `@ViewBuilder` and the window hosts come from SwiftUI on macOS and from
// SwiftOpenUI (re-exported through `LyrebirdUI`) on Linux — hence the single
// `#if canImport(SwiftUI)` import guard.
#if canImport(SwiftUI)
import SwiftUI
#endif
import Foundation
import LyrebirdSynth
import LyrebirdUI
import LyrebirdGUIDemoKit
// MARK: - Shared setup (runs on both platforms)
let selection: DemoSelection = DemoSelection.fromEnvironment()
private let demoBlockSize: Int = 512
private let demoSampleRate: Double = 48_000.0
private let demoScopeBufferSize: Int = 2048
// Oscilloscope tap on the stereo output buses. Must be set before `start()`.
let demoScope: ScopeCapture = ScopeCapture(buses: [0, 1], bufferSize: demoScopeBufferSize)
// Core Audio on Apple, ALSA on a Linux build with libasound, else a silent
// OfflineDriver. The GUI runs either way; `isLiveAudioAvailable` reports which.
let demoDriver: any AudioDriver = makeDefaultAudioDriver()
let demoEngine: SynthesisEngine = SynthesisEngine(
blockSize: demoBlockSize,
sampleRate: demoSampleRate,
numOutputChannels: 2,
numInputChannels: 0,
driver: demoDriver
)
demoEngine.scopeTap = demoScope
// Both synths are cheap to build; only the selected one is added to the engine.
// Building both keeps the node extraction below branch-free (no force-unwrap).
let vectorSynth: VectorOscillatorUI = VectorOscillatorUI()
let sineSynth: SineToneUI = SineToneUI()
let activeSynth: SynthesizerBase = (selection == .vector) ? vectorSynth : sineSynth
// Extract the projected parameter nodes here, in main.swift's top-level
// `@MainActor` context: `SynthesizerBase` is `@MainActor`, so `synth.$…` is only
// reachable on the main actor. The nodes are not actor-isolated, so the
// (nonisolated, on Linux) view body can read them freely.
let vectorX: UIParamNode = vectorSynth.$x
let vectorY: UIParamNode = vectorSynth.$y
let vectorFreq: UIParamNode = vectorSynth.$frequency
let vectorAmp: UIParamNode = vectorSynth.$amplitude
let sineFreq: UIParamNode = sineSynth.$frequency
let sineAmp: UIParamNode = sineSynth.$amplitude
let sinePan: UIParamNode = sineSynth.$pan
// A static example envelope for the sine demo's envelope plot.
let demoEnvelope: Envelope = Envelope(
levels: [0.0001, 1.0, 0.6, 0.4, 0.0001],
durations: [0.05, 0.15, 0.4, 0.3],
curves: [.exponential, .exponential, .lin, .exponential],
loopNode: 2,
releaseNode: 4
)
// `SynthesisEngine` is not Sendable; the status view only reads plain CPU-load
// doubles off it, and this demo runs entirely on the UI thread, so a nonisolated
// handle is safe (mirrors the Linux UI demo).
nonisolated(unsafe) let statusEngine: SynthesisEngine = demoEngine
/// Builds the view for the active selection. `if`/`else` maps to the DSL's
/// `buildEither`, which both backends provide.
///
/// Isolation differs by backend: SwiftUI's `View` is `@MainActor`, so on macOS
/// this must be `@MainActor` to construct the view (and it is called from
/// AppKit's main-actor launch). SwiftOpenUI's `View` is nonisolated, so on Linux
/// this stays nonisolated and is callable from the nonisolated scene closure.
#if canImport(SwiftUI)
@MainActor
#endif
@ViewBuilder
func demoContent() -> some View {
if selection == .vector {
VectorOscillatorDemoView(
xNode: vectorX,
yNode: vectorY,
frequencyNode: vectorFreq,
amplitudeNode: vectorAmp,
scope: demoScope,
engine: statusEngine
)
} else if selection == .conductor {
ConductorDemoView(scope: demoScope, engine: statusEngine)
} else {
SineToneDemoView(
frequencyNode: sineFreq,
amplitudeNode: sineAmp,
panNode: sinePan,
scope: demoScope,
engine: statusEngine,
envelope: demoEnvelope
)
}
}
// Start the engine and add the selected synth. `engine.start()` / `add` are
// @MainActor; main.swift's top level is main-actor isolated, so these are direct
// calls. On a build with no live backend the GUI still runs (silently).
// The conductor demo is the exception: its view starts and stops the engine itself.
if selection != .conductor {
do {
try demoEngine.start()
try demoEngine.add(activeSynth)
} catch {
print("[Lyrebird] demo engine setup failed: \(error)")
}
}
if !isLiveAudioAvailable {
print("[Lyrebird] no live audio backend — the controls still work, but there is no sound.")
}
// MARK: - macOS front end (AppKit + SwiftUI)
#if os(macOS)
import AppKit
final class DemoAppDelegate: NSObject, NSApplicationDelegate {
var window: LyrebirdWindow?
func applicationDidFinishLaunching(_ notification: Notification) {
let w: LyrebirdWindow = LyrebirdWindow(
title: selection.windowTitle,
width: 380,
height: 620
)
w.open { demoContent() }
window = w
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
true
}
func applicationWillTerminate(_ notification: Notification) {
demoEngine.stop()
}
}
MainActor.assumeIsolated {
let app: NSApplication = NSApplication.shared
app.setActivationPolicy(.regular)
let delegate: DemoAppDelegate = DemoAppDelegate()
app.delegate = delegate
app.run()
}
// MARK: - Linux front end (GTK4 + SwiftOpenUI)
#else
struct DemoApp: App {
var body: some Scene {
WindowGroup(selection.windowTitle) {
demoContent()
}
}
}
GTK4Backend().run(DemoApp.self)
#endif
@@ -0,0 +1,156 @@
// ConductorDemoController.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Observation
import LyrebirdSynth
/// Owns the engine lifecycle, the ``EventConductor`` and the on/off state of the two parts for
/// ``ConductorDemoView``.
///
/// A pattern is single-shot, so each toggle-on builds a fresh ``EventPattern`` and hands it to the
/// conductor, entering on the next beat. ``EventConductor/add(_:quantize:)`` returns an
/// ``EventConductorHandle``; toggling a part off calls ``EventConductorHandle/stop()`` on its
/// handle, which releases that part alone (its gated voices ring out) without touching the other.
///
/// `@unchecked Sendable`: main-thread-confined — every method is called from a button action.
@Observable
final class ConductorDemoController: @unchecked Sendable {
/// Shared tempo of the conductor and both parts, in beats per minute.
private static let tempoBPM: Double = 120.0
/// Top part: events per beat grid, in beats.
private static let topEventBeats: Double = 0.5
/// Bottom part: one event per beat.
private static let bottomEventBeats: Double = 1.0
/// Sustain fraction of each event's duration.
private static let legato: Double = 0.8
/// Top part: A-minor pentatonic phrase.
private static let topPhrase: [Pitch] = [
.named(.a, 4), .named(.c, 5), .named(.d, 5), .named(.e, 5),
.named(.g, 5), .named(.e, 5), .named(.d, 5), .named(.c, 5),
]
/// Bottom part: a simple root-fifth bass figure.
private static let bottomPhrase: [Pitch] = [
.named(.a, 2), .named(.a, 2), .named(.g, 2), .named(.e, 2),
]
private static let topAmpLow: Double = 0.10
private static let topAmpHigh: Double = 0.18
private static let bottomAmpLow: Double = 0.20
private static let bottomAmpHigh: Double = 0.28
private let engine: SynthesisEngine
/// `true` while the engine (and conductor) is running.
private(set) var engineRunning: Bool = false
/// `true` while the top part is switched on.
private(set) var topOn: Bool = false
/// `true` while the bottom part is switched on.
private(set) var bottomOn: Bool = false
@ObservationIgnored private var conductor: EventConductor?
@ObservationIgnored private var topHandle: EventConductorHandle?
@ObservationIgnored private var bottomHandle: EventConductorHandle?
init(engine: SynthesisEngine) {
self.engine = engine
}
/// Starts the engine and a fresh conductor, or stops both (releasing any playing parts).
func toggleEngine() {
if engineRunning {
topHandle?.stop()
bottomHandle?.stop()
conductor?.stop()
conductor = nil
topHandle = nil
bottomHandle = nil
topOn = false
bottomOn = false
MainActor.assumeIsolated { engine.stop() }
engineRunning = false
} else {
do {
try MainActor.assumeIsolated { try engine.start() }
} catch {
print("[Lyrebird] engine.start failed: \(error)")
return
}
let newConductor: EventConductor = EventConductor(tempo: ConductorDemoController.tempoBPM)
MainActor.assumeIsolated { newConductor.start(on: engine) }
conductor = newConductor
engineRunning = true
}
}
/// Toggles the top (melodic) part. Entering is quantised to the next beat; stopping releases it
/// immediately through its handle.
func toggleTop() {
guard let active: EventConductor = conductor else { return }
if topOn {
topHandle?.stop()
topHandle = nil
topOn = false
} else {
let pattern: EventPattern<ConductorDemoVoice> = makePattern(
phrase: ConductorDemoController.topPhrase,
eventBeats: ConductorDemoController.topEventBeats,
ampLow: ConductorDemoController.topAmpLow,
ampHigh: ConductorDemoController.topAmpHigh
)
topHandle = active.add(pattern, quantize: .nextBeat)
topOn = true
}
}
/// Toggles the bottom (bass) part. Entering is quantised to the next beat; stopping releases it
/// immediately through its handle.
func toggleBottom() {
guard let active: EventConductor = conductor else { return }
if bottomOn {
bottomHandle?.stop()
bottomHandle = nil
bottomOn = false
} else {
let pattern: EventPattern<ConductorDemoVoice> = makePattern(
phrase: ConductorDemoController.bottomPhrase,
eventBeats: ConductorDemoController.bottomEventBeats,
ampLow: ConductorDemoController.bottomAmpLow,
ampHigh: ConductorDemoController.bottomAmpHigh
)
bottomHandle = active.add(pattern, quantize: .nextBeat)
bottomOn = true
}
}
/// Builds a fresh, endlessly looping pattern: both the phrase and the duration are infinite
/// `.sequence` patterns, so the part plays until its handle is stopped.
private func makePattern(
phrase: [Pitch],
eventBeats: Double,
ampLow: Double,
ampHigh: Double
) -> EventPattern<ConductorDemoVoice> {
let freqs: [Double] = phrase.compactMap(\.frequency)
// Key-path formation on a `@LiveParam` needs the main actor.
return MainActor.assumeIsolated {
EventPattern(make: { ConductorDemoVoice() })
.bind(\.freq, .sequence(freqs))
.bind(\.amp, .uniformRandom(low: ampLow, high: ampHigh))
.dur(.sequence([eventBeats]))
.legato(ConductorDemoController.legato)
.tempo(ConductorDemoController.tempoBPM)
}
}
}
@@ -0,0 +1,62 @@
// ConductorDemoView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if canImport(SwiftUI)
import SwiftUI
#endif
import LyrebirdSynth
import LyrebirdUI
/// Demonstrates ``EventConductor``: start the engine, then toggle a top and a bottom part on and
/// off. Each part loops forever while on and enters on the next beat of the conductor's clock, so
/// the two lock together however late they are pressed. Includes the CPU status strip and an
/// oscilloscope.
///
/// Written to the View-DSL subset shared by SwiftUI and SwiftOpenUI, so it runs on macOS and Linux.
/// Buttons use the `action:label:` form, which fires reliably on both backends.
public struct ConductorDemoView: View {
let scope: ScopeCapture
let engine: SynthesisEngine
@State private var controller: ConductorDemoController
public init(scope: ScopeCapture, engine: SynthesisEngine) {
self.scope = scope
self.engine = engine
_controller = State(wrappedValue: ConductorDemoController(engine: engine))
}
public var body: some View {
VStack {
Text("Lyrebird — Event Conductor")
.font(.headline)
Button {
controller.toggleEngine()
} label: {
Text(controller.engineRunning ? "Stop Engine" : "Start Engine")
}
Button {
controller.toggleTop()
} label: {
Text(controller.topOn ? "Top Part: ON (tap to stop)" : "Top Part: off (starts on next beat)")
}
.disabled(!controller.engineRunning)
Button {
controller.toggleBottom()
} label: {
Text(controller.bottomOn
? "Bottom Part: ON (tap to stop)"
: "Bottom Part: off (starts on next beat)")
}
.disabled(!controller.engineRunning)
LyrebirdStatusView(engine: engine)
LyrebirdScopeView(capture: scope)
.frame(height: 120)
}
.padding()
}
}
@@ -0,0 +1,47 @@
// ConductorDemoVoice.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// A gated sine voice for the conductor demo. ``EventPattern`` holds its gate open for the note's
/// sustain, then closes it; the envelope plays its release and frees the voice, so a part that is
/// toggled off rings out cleanly instead of being cut.
final class ConductorDemoVoice: SynthesizerBase, EventGated {
/// Envelope attack length in seconds.
nonisolated static let attackSeconds: Double = 0.01
/// Envelope release length in seconds — how long a note rings after its gate closes.
nonisolated static let releaseSeconds: Double = 0.3
/// Oscillator frequency in Hz. Bound per event by the pattern.
@LiveParam var freq: Double = 440.0
/// Linear output gain, 0...1. Bound per event by the pattern.
@LiveParam var amp: Double = 0.2
/// Envelope gate. Open by default so the attack fires when the voice is added.
@LiveParam var gate: Double = 1.0
var eventGate: ParameterNode { $gate }
override func build() {
let envelope: Envelope = Envelope(
levels: [0.0, 1.0, 0.0],
durations: [ConductorDemoVoice.attackSeconds, ConductorDemoVoice.releaseSeconds],
curves: [.welch, .welch],
releaseNode: 1
)
let shaped: EnvelopeGen.Audio = EnvelopeGen.Audio(
envelope: envelope,
gate: $gate,
doneAction: .freeNode
)
let source: OscSin.Audio = OscSin.Audio(freq: $freq, mul: $amp)
let mono: any ValidGeneratorInput = source * shaped
output(bus: 0, source: Pan2(input: mono, pan: 0.0))
}
}
@@ -0,0 +1,38 @@
// DemoSelection.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Which synthesizer the demo runs, chosen by the `LYREBIRD_DEMO` environment
/// variable. Both front ends (AppKit on macOS, GTK4 on Linux) read the same
/// selection so one binary covers every patch.
public enum DemoSelection: String, Sendable {
/// Vector oscillator with an XY blend pad (the default).
case vector
/// Stereo sine tone with frequency / amplitude / pan controls.
case sine
/// Live event ensemble: engine start/stop plus top and bottom parts driven by an
/// ``EventConductor``. The view owns the engine, so nothing starts at launch.
case conductor
/// Resolve the selection from `LYREBIRD_DEMO` (defaults to `.vector`).
public static func fromEnvironment() -> DemoSelection {
let raw: String = ProcessInfo.processInfo.environment["LYREBIRD_DEMO"]?.lowercased() ?? "conductor"
return DemoSelection(rawValue: raw) ?? .conductor
}
/// Title-bar text for the window hosting this demo.
public var windowTitle: String {
switch self {
case .vector: return "Lyrebird — Vector Oscillator"
case .sine: return "Lyrebird — Sine Tone"
case .conductor: return "Lyrebird — Event Conductor"
}
}
}
@@ -0,0 +1,60 @@
// SineToneDemoView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if canImport(SwiftUI)
import SwiftUI
#endif
import LyrebirdSynth
import LyrebirdUI
/// Live controls for ``SineToneUI``: a frequency slider, amplitude and pan knobs,
/// a level readout, a CPU-load strip, an oscilloscope, and a static envelope plot.
///
/// Node-based for the same reason as ``VectorOscillatorDemoView`` — the body must
/// compile under both SwiftUI's `@MainActor` body and SwiftOpenUI's nonisolated one.
public struct SineToneDemoView: View {
let frequencyNode: UIParamNode
let amplitudeNode: UIParamNode
let panNode: UIParamNode
let scope: ScopeCapture
let engine: SynthesisEngine
let envelope: Envelope
public init(
frequencyNode: UIParamNode,
amplitudeNode: UIParamNode,
panNode: UIParamNode,
scope: ScopeCapture,
engine: SynthesisEngine,
envelope: Envelope
) {
self.frequencyNode = frequencyNode
self.amplitudeNode = amplitudeNode
self.panNode = panNode
self.scope = scope
self.engine = engine
self.envelope = envelope
}
public var body: some View {
VStack {
Text("Lyrebird — Sine Tone")
.font(.headline)
ParameterSlider("Frequency", node: frequencyNode, range: 440.0...880.0)
HStack {
ParameterKnob("Amplitude", node: amplitudeNode, range: 0.0...1.0)
ParameterKnob("Pan", node: panNode, range: -1.0...1.0)
ParameterLabel("Level", node: amplitudeNode, decimalPlaces: 2)
}
LyrebirdStatusView(engine: engine)
LyrebirdScopeView(capture: scope)
.frame(height: 120)
LyrebirdEnvelopeView(envelope)
}
.padding()
}
}
@@ -0,0 +1,31 @@
// SineToneUI.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// A stereo sine tone whose frequency, amplitude, and pan are live-controllable
/// from the UI. The `@UIParam` slots are the same model both the SwiftUI (macOS)
/// and SwiftOpenUI (Linux) controls bind to — one synthesizer, two front ends.
public final class SineToneUI: SynthesizerBase {
/// Frequency in Hz. Slider range: 440–880 Hz.
@UIParam public var frequency: Double = 440.0
/// Output amplitude (linear gain). Knob range: 0–1.
@UIParam public var amplitude: Double = 0.25
/// Stereo pan position. Knob range: -1 (hard left) … 0 (center) … +1 (hard right).
@UIParam public var pan: Double = 0.0
public override init() {
super.init()
}
public override func build() {
let osc: OscSin.Audio = OscSin.Audio(freq: $frequency)
output(bus: 0, source: Pan2(input: osc * $amplitude, pan: $pan))
}
}
@@ -0,0 +1,70 @@
// VectorOscillatorDemoView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// One platform `#if` at the import site; identical body beneath. On macOS SwiftUI
// supplies the View DSL; on Linux `LyrebirdUI` re-exports the SwiftOpenUI DSL, so
// `VStack` / `Text` / `.padding()` resolve on both. The Lyrebird controls
// (`ParameterXY`, `ParameterKnob`, …) and views live in `LyrebirdUI` on every
// platform and bind the same core `UIParamNode`s this view is handed.
#if canImport(SwiftUI)
import SwiftUI
#endif
import LyrebirdSynth
import LyrebirdUI
/// Live controls for ``VectorOscillatorUI``: an XY blend pad, frequency and
/// amplitude knobs, a CPU-load strip, and an oscilloscope of the stereo output.
///
/// The view holds the projected `UIParamNode`s rather than the `@MainActor`
/// synthesizer, because SwiftOpenUI's `body` is nonisolated (unlike SwiftUI's).
/// The caller extracts the nodes on the main actor and hands them in; the nodes
/// themselves are not actor-isolated, so a nonisolated body reads them freely.
public struct VectorOscillatorDemoView: View {
let xNode: UIParamNode
let yNode: UIParamNode
let frequencyNode: UIParamNode
let amplitudeNode: UIParamNode
let scope: ScopeCapture
let engine: SynthesisEngine
public init(
xNode: UIParamNode,
yNode: UIParamNode,
frequencyNode: UIParamNode,
amplitudeNode: UIParamNode,
scope: ScopeCapture,
engine: SynthesisEngine
) {
self.xNode = xNode
self.yNode = yNode
self.frequencyNode = frequencyNode
self.amplitudeNode = amplitudeNode
self.scope = scope
self.engine = engine
}
public var body: some View {
VStack {
Text("Lyrebird — Vector Oscillator")
.font(.headline)
ParameterXY(
xLabel: "X (A↔B)", xNode: xNode, xRange: 0.0...1.0,
yLabel: "Y (AB↔CD)", yNode: yNode, yRange: 0.0...1.0
)
.frame(width: 240, height: 240)
HStack {
ParameterKnob("Frequency", node: frequencyNode, range: 40.0...2000.0)
ParameterKnob("Amplitude", node: amplitudeNode, range: 0.0...1.0)
ParameterLabel("Freq (Hz)", node: frequencyNode, decimalPlaces: 1)
}
LyrebirdStatusView(engine: engine)
LyrebirdScopeView(capture: scope)
.frame(height: 120)
}
.padding()
}
}
@@ -0,0 +1,75 @@
// VectorOscillatorUI.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// A stereo vector oscillator whose XY position, frequency, and amplitude are
/// live-controllable from the UI.
///
/// Four corner wavetables are crossfaded on a 2D XY plane:
///
/// C (triangle) ── D (Hanning) (y = 1)
/// │ │
/// A (sine) ──── B (saw-ish) (y = 0)
/// x=0 x=1
///
/// Moving X blends A↔B (and C↔D); moving Y blends the AB mix into the CD mix.
public final class VectorOscillatorUI: SynthesizerBase {
/// X-axis blend position. 0 = corner A/C, 1 = corner B/D. Normalized [0, 1].
@UIParam public var x: Double = 0.5
/// Y-axis blend position. 0 = bottom (A, B), 1 = top (C, D). Normalized [0, 1].
@UIParam public var y: Double = 0.5
/// Oscillator frequency in Hz. Slider range: 40–2000 Hz.
@UIParam public var frequency: Double = 220.0
/// Output amplitude (linear gain). Knob range: 0–1.
@UIParam public var amplitude: Double = 0.25
private let bufferA: LyrebirdBuffer // corner A: sine
private let bufferB: LyrebirdBuffer // corner B: 16-partial saw-ish
private let bufferC: LyrebirdBuffer // corner C: triangle
private let bufferD: LyrebirdBuffer // corner D: Hanning window shape
public override init() {
let tableSize: Int = lyrebirdDefaultTableSize
let a: LyrebirdBuffer = LyrebirdBuffer(count: tableSize)
a.fillSine()
let b: LyrebirdBuffer = LyrebirdBuffer(count: tableSize)
b.fill(partials: 16)
let c: LyrebirdBuffer = LyrebirdBuffer(count: tableSize)
c.fillTriangle()
let d: LyrebirdBuffer = LyrebirdBuffer(count: tableSize)
d.fillHanning()
self.bufferA = a
self.bufferB = b
self.bufferC = c
self.bufferD = d
super.init()
}
public override func build() {
let osc: VectorOscillator.Audio = VectorOscillator.Audio(
bufferA: bufferA,
bufferB: bufferB,
bufferC: bufferC,
bufferD: bufferD,
freq: $frequency,
x: $x,
y: $y,
mul: $amplitude
)
output(bus: 0, source: Pan2(input: osc, pan: 0.0))
}
}
@@ -12,7 +12,7 @@ import LyrebirdUI
// ── Demo selector ───────────────────────────────────────────────────────────── // ── Demo selector ─────────────────────────────────────────────────────────────
// Change `demo` to `.sineTone` or `.binDelay` to switch demos. // Change `demo` to `.sineTone` or `.binDelay` to switch demos.
private enum Demo { case vector, binDelay, sineTone } private enum Demo { case vector, binDelay, sineTone }
private let demo: Demo = .vector private let demo: Demo = .binDelay
// ────────────────────────────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────────────────────────────
final class AppDelegate: NSObject, NSApplicationDelegate { final class AppDelegate: NSObject, NSApplicationDelegate {
@@ -9,7 +9,7 @@ import LyrebirdSynth
let engine = SynthesisEngine( let engine = SynthesisEngine(
blockSize: 512, blockSize: 512,
sampleRate: 44100, sampleRate: 48_000,
numOutputChannels: 2, numOutputChannels: 2,
numInputChannels: 0, numInputChannels: 0,
driver: CoreAudioDriver() driver: CoreAudioDriver()
@@ -7,9 +7,21 @@
import Foundation import Foundation
import LyrebirdSynth import LyrebirdSynth
// Output to the Desktop — triggers the NSDesktopFolderUsageDescription TCC prompt on first run. // Offline render has no audio device, so this demo runs the same on macOS and Linux.
let outputURL = FileManager.default.homeDirectoryForCurrentUser // Only the output container differs: CAF is Apple-only (it goes through `ExtAudioFile`),
// so off Apple we write the portable WAV codec instead.
#if canImport(AudioToolbox)
// Apple: CAF on the Desktop — triggers the NSDesktopFolderUsageDescription TCC prompt on first run.
let outputURL: URL = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent("Desktop/nrt_output.caf") .appendingPathComponent("Desktop/nrt_output.caf")
let outputFormat: AudioFileFormat = .cafFloat32
#else
// Linux (and any non-Apple): WAV in the current working directory — no special-folder
// permission needed, and `WavFileWriter` is the portable encoder off Apple.
let outputURL: URL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
.appendingPathComponent("nrt_output.wav")
let outputFormat: AudioFileFormat = .wavFloat32
#endif
// Render parameters. // Render parameters.
let sampleRate: Double = 48000 let sampleRate: Double = 48000
@@ -43,7 +55,7 @@ let tailDuration: Double = 0.1
let lastStart = voices.map(\.start).max() ?? 0.0 let lastStart = voices.map(\.start).max() ?? 0.0
let totalDur = lastStart + interSetDelay + voiceLength + tailDuration let totalDur = lastStart + interSetDelay + voiceLength + tailDuration
let driver = NRTDriver(outputURL: outputURL, duration: totalDur) let driver = NRTDriver(outputURL: outputURL, duration: totalDur, format: outputFormat)
let engine = SynthesisEngine( let engine = SynthesisEngine(
blockSize: blockSize, blockSize: blockSize,
sampleRate: sampleRate, sampleRate: sampleRate,
@@ -77,7 +89,7 @@ do {
) )
} }
} catch { } catch {
fputs("engine.schedule failed: \(error)\n", stderr) FileHandle.standardError.write(Data("engine.schedule failed: \(error)\n".utf8))
exit(1) exit(1)
} }
@@ -87,7 +99,7 @@ do {
try engine.start() try engine.start()
print("Done.") print("Done.")
} catch { } catch {
fputs("Render failed: \(error)\n", stderr) FileHandle.standardError.write(Data("Render failed: \(error)\n".utf8))
exit(1) exit(1)
} }
@@ -17,13 +17,15 @@ import LyrebirdSynth
let quickstartDuration: Double = 5.0 let quickstartDuration: Double = 5.0
do { do {
// The engine owns Core Audio and runs the graph on the RT thread. // The engine owns the audio device and runs the graph on the RT thread.
// `makeDefaultAudioDriver()` picks the platform backend — Core Audio on Apple,
// ALSA on Linux (needs libasound) — so this demo builds and runs on both.
let engine = SynthesisEngine( let engine = SynthesisEngine(
blockSize: 512, blockSize: 512,
sampleRate: 48000, sampleRate: 48000,
numOutputChannels: 2, numOutputChannels: 2,
numInputChannels: 0, numInputChannels: 0,
driver: CoreAudioDriver() driver: makeDefaultAudioDriver()
) )
try engine.start() try engine.start()
@@ -39,6 +41,6 @@ do {
engine.stop() // closes the device engine.stop() // closes the device
print("Done.") print("Done.")
} catch { } catch {
fputs("Lyrebird quickstart failed to start: \(error)\n", stderr) FileHandle.standardError.write(Data("Lyrebird quickstart failed to start: \(error)\n".utf8))
exit(1) exit(1)
} }
@@ -7,6 +7,17 @@
import Foundation import Foundation
import LyrebirdSynth import LyrebirdSynth
/// Directory this demo writes its output files to: the Desktop on Apple (matching the
/// Xcode scheme), the current working directory elsewhere (Linux has no Desktop folder
/// to grant, and `swift run` starts from a known location).
func demoOutputDirectory() -> URL {
#if canImport(AudioToolbox)
return FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Desktop")
#else
return URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
#endif
}
/// Builds a multi-part Score using every DSL node type, exports MusicXML, round-trips /// Builds a multi-part Score using every DSL node type, exports MusicXML, round-trips
/// the document, and reports render statistics. /// the document, and reports render statistics.
/// ///
@@ -58,15 +69,15 @@ final class ScoreDemo: DemoProtocol {
/// Export MusicXML and print the round-trip event count. Does not interact with /// Export MusicXML and print the round-trip event count. Does not interact with
/// the engine or schedule any voices. /// the engine or schedule any voices.
func runDemo() { func runDemo() {
// Step 1 — write MusicXML to Desktop. // Step 1 — write MusicXML to the demo output directory.
let xmlURL: URL = FileManager.default.homeDirectoryForCurrentUser let xmlURL: URL = demoOutputDirectory()
.appendingPathComponent("Desktop/LyrebirdScoreDemo.musicxml") .appendingPathComponent("LyrebirdScoreDemo.musicxml")
let xmlString: String = score.toMusicXMLString() let xmlString: String = score.toMusicXMLString()
do { do {
try xmlString.write(to: xmlURL, atomically: true, encoding: .utf8) try xmlString.write(to: xmlURL, atomically: true, encoding: .utf8)
print("MusicXML written → \(xmlURL.path)") print("MusicXML written → \(xmlURL.path)")
} catch { } catch {
fputs("Failed to write MusicXML: \(error)\n", stderr) FileHandle.standardError.write(Data("Failed to write MusicXML: \(error)\n".utf8))
} }
// Step 2 — round-trip sanity check. // Step 2 — round-trip sanity check.
@@ -105,7 +116,7 @@ final class ScoreDemo: DemoProtocol {
print("Score key (G major): \(rt.keySignature == .gMajor ? "OK" : "MISMATCH(\(rt.keySignature))")") print("Score key (G major): \(rt.keySignature == .gMajor ? "OK" : "MISMATCH(\(rt.keySignature))")")
} }
} catch { } catch {
fputs("MusicXML round-trip failed: \(error)\n", stderr) FileHandle.standardError.write(Data("MusicXML round-trip failed: \(error)\n".utf8))
} }
// Step 2b — sectioned showcase: multiple Sections assembled into one // Step 2b — sectioned showcase: multiple Sections assembled into one
@@ -119,8 +130,8 @@ final class ScoreDemo: DemoProtocol {
// `rehearsalMarksAsStaffText: true` option emits boxed <words> staff text // `rehearsalMarksAsStaffText: true` option emits boxed <words> staff text
// instead, but that attaches to a staff and can collide with notation. // instead, but that attaches to a staff and can collide with notation.
let showcase: Score = ScoreDemo.makeSectionedShowcase() let showcase: Score = ScoreDemo.makeSectionedShowcase()
let showcaseURL: URL = FileManager.default.homeDirectoryForCurrentUser let showcaseURL: URL = demoOutputDirectory()
.appendingPathComponent("Desktop/LyrebirdScoreSections.musicxml") .appendingPathComponent("LyrebirdScoreSections.musicxml")
do { do {
try showcase.toMusicXMLString().write(to: showcaseURL, atomically: true, encoding: .utf8) try showcase.toMusicXMLString().write(to: showcaseURL, atomically: true, encoding: .utf8)
print("Sectioned showcase written → \(showcaseURL.path)") print("Sectioned showcase written → \(showcaseURL.path)")
@@ -132,7 +143,7 @@ final class ScoreDemo: DemoProtocol {
print("Sections → rehearsal marks: \(markList)") print("Sections → rehearsal marks: \(markList)")
print("Sectioned showcase parts: \(showcase.parts.map { $0.name }.joined(separator: ", "))") print("Sectioned showcase parts: \(showcase.parts.map { $0.name }.joined(separator: ", "))")
} catch { } catch {
fputs("Failed to write sectioned showcase: \(error)\n", stderr) FileHandle.standardError.write(Data("Failed to write sectioned showcase: \(error)\n".utf8))
} }
// Step 3 — report render parameters. // Step 3 — report render parameters.
@@ -185,7 +196,7 @@ final class ScoreDemo: DemoProtocol {
try engine.schedule(voice, after: startSeconds) try engine.schedule(voice, after: startSeconds)
scheduledCount += 1 scheduledCount += 1
} catch { } catch {
fputs("engine.schedule failed for beat \(event.beat): \(error)\n", stderr) FileHandle.standardError.write(Data("engine.schedule failed for beat \(event.beat): \(error)\n".utf8))
failedCount += 1 failedCount += 1
} }
} }
@@ -7,9 +7,16 @@
import Foundation import Foundation
import LyrebirdSynth import LyrebirdSynth
// Output paths — both land on the Desktop. // Audio output. CAF is Apple-only (ExtAudioFile), so off Apple we render the
let cafURL: URL = FileManager.default.homeDirectoryForCurrentUser // portable WAV codec; `demoOutputDirectory()` is the Desktop on Apple and the
.appendingPathComponent("Desktop/LyrebirdScoreDemo.caf") // current working directory elsewhere (see ScoreDemo.swift).
#if canImport(AudioToolbox)
let outputFormat: AudioFileFormat = .cafFloat32
let audioURL: URL = demoOutputDirectory().appendingPathComponent("LyrebirdScoreDemo.caf")
#else
let outputFormat: AudioFileFormat = .wavFloat32
let audioURL: URL = demoOutputDirectory().appendingPathComponent("LyrebirdScoreDemo.wav")
#endif
// Render parameters. // Render parameters.
let sampleRate: Double = 48000 let sampleRate: Double = 48000
@@ -23,7 +30,7 @@ let totalDuration: Double = demo.totalDuration
demo.runDemo() demo.runDemo()
// Create NRTDriver and engine. // Create NRTDriver and engine.
let driver: NRTDriver = NRTDriver(outputURL: cafURL, duration: totalDuration) let driver: NRTDriver = NRTDriver(outputURL: audioURL, duration: totalDuration, format: outputFormat)
let engine: SynthesisEngine = SynthesisEngine( let engine: SynthesisEngine = SynthesisEngine(
blockSize: blockSize, blockSize: blockSize,
sampleRate: sampleRate, sampleRate: sampleRate,
@@ -37,12 +44,12 @@ let engine: SynthesisEngine = SynthesisEngine(
// isolated, so this is a plain direct call — no MainActor hop needed. // isolated, so this is a plain direct call — no MainActor hop needed.
demo.scheduleVoices(engine: engine) demo.scheduleVoices(engine: engine)
print(String(format: "Rendering %.2f s → %@", totalDuration, cafURL.path)) print(String(format: "Rendering %.2f s → %@", totalDuration, audioURL.path))
do { do {
try engine.start() try engine.start()
print("Done.") print("Done.")
} catch { } catch {
fputs("Render failed: \(error)\n", stderr) FileHandle.standardError.write(Data("Render failed: \(error)\n".utf8))
exit(1) exit(1)
} }
+3 -3
View File
@@ -2,7 +2,7 @@
How to add Lyrebird to a project and scaffold the five kinds of app it supports: real-time, real-time + UI, non-real-time (offline) render, AUv3 plugin, and iOS. How to add Lyrebird to a project and scaffold the five kinds of app it supports: real-time, real-time + UI, non-real-time (offline) render, AUv3 plugin, and iOS.
The package is hosted at <https://realizedsound.mooo.com/josh/Lyrebird>. The package is hosted at <https://git.lyrebirdsynth.net/josh/Lyrebird>.
--- ---
@@ -29,7 +29,7 @@ let package = Package(
name: "MyPiece", name: "MyPiece",
platforms: [.macOS(.v15), .iOS(.v18)], platforms: [.macOS(.v15), .iOS(.v18)],
dependencies: [ dependencies: [
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.0.0"), .package(url: "https://git.lyrebirdsynth.net/josh/Lyrebird", from: "1.0.0"),
], ],
targets: [ targets: [
.executableTarget( .executableTarget(
@@ -156,7 +156,7 @@ let engine = SynthesisEngine(
sampleRate: 48_000, sampleRate: 48_000,
numOutputChannels: 2, numOutputChannels: 2,
numInputChannels: 0, numInputChannels: 0,
driver: CoreAudioDriver()) driver: makeDefaultAudioDriver())
try engine.start() try engine.start()
try engine.add(SineTone()) try engine.add(SineTone())
+3
View File
@@ -10,6 +10,9 @@
<FileRef <FileRef
location = "group:Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo.xcodeproj"> location = "group:Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo.xcodeproj">
</FileRef> </FileRef>
<FileRef
location = "group:Demos/LyrebirdGUIDemo">
</FileRef>
<FileRef <FileRef
location = "group:Demos/LyrebirdiOSDemo/LyrebirdiOSDemo.xcodeproj"> location = "group:Demos/LyrebirdiOSDemo/LyrebirdiOSDemo.xcodeproj">
</FileRef> </FileRef>
+132 -27
View File
@@ -1,14 +1,33 @@
# Lyrebird # Lyrebird
A native macOS/iOS audio synthesis framework written in Swift. Implement `Generator` and `Synthesizer` protocols; the Lyrebird engine handles Core Audio I/O and signal graph evaluation with no heap allocation on the real-time thread. A native macOS, iOS, and Linux audio synthesis framework written in Swift. Implement `Generator` and `Synthesizer` protocols; the Lyrebird engine handles platform audio I/O (Core Audio on Apple, ALSA on Linux) and signal graph evaluation with no heap allocation on the real-time thread.
Informed by 20+ years of SuperCollider practice, adapted to Swift idioms and a single-process architecture. Informed by 20+ years of SuperCollider practice, adapted to Swift idioms and a single-process architecture.
--- ---
## Try it — run a demo
The fastest way in is a demo project, not a snippet to copy. Each demo under [`Demos/`](Demos/) is a standalone SwiftPM package that depends on this checkout, so `swift run` from its folder builds and runs it — on **macOS** (Xcode optional) and **Linux** (VS Code optional), no project file to open:
```bash
git clone https://git.lyrebirdsynth.net/josh/Lyrebird.git
cd Lyrebird
(cd Demos/LyrebirdQuickstartDemo && swift run) # a 440 Hz sine — the shortest path to sound
(cd Demos/LyrebirdNRTDemo && swift run) # offline render → an audio file, no sound device needed
(cd Demos/LyrebirdDemo && swift run) # a fuller reverb smoke-test through your default output
```
These three run the same on macOS and Linux. Each has a `Synthesizers/` folder — drop a `SynthesizerBase` subclass in, re-run, and you are building your own voice. The GUI demos (SwiftUI on macOS/iOS; the GTK4 UI on Linux) and the full list are under [Demo projects](#demo-projects).
On Linux the live-audio demos need `libasound2-dev`; the offline NRT demo needs nothing. Full Linux setup is in the [On Linux](#on-linux--vs-code-or-any-editor-no-xcode) notes and [`docs/linux-getting-started.md`](docs/linux-getting-started.md).
---
## A quick taste ## A quick taste
Three layers, each usable on its own: **Generators** are the unit signal graph, **Synthesizers** package a graph plus live parameters into a playable voice, and the **Engine** drives Core Audio and schedules voices sample-accurately. Three layers, each usable on its own: **Generators** are the unit signal graph, **Synthesizers** package a graph plus live parameters into a playable voice, and the **Engine** drives the platform audio backend (Core Audio on Apple, ALSA on Linux) and schedules voices sample-accurately.
### Generators — compose a signal graph with operators ### Generators — compose a signal graph with operators
@@ -28,6 +47,42 @@ let env = EnvelopeGen.Control(envelope: Envelope(
let voice = carrier * env * 0.2 // ready to route to a bus let voice = carrier * env * 0.2 // ready to route to a bus
``` ```
### Generators — or write your own
A Generator is an RT-safe DSP node: subclass `GeneratorBase`, conform to `AudioGenerator`, fill the inherited pre-allocated `_result` buffer, and return it. No allocation, locks, or runtime type checks on the render thread — inputs are classified once at `init`. This is a complete hard-clip distortion:
```swift
import LyrebirdSynth
/// Hard-clip distortion — clamps its input signal to ±`level`.
final class HardClip: GeneratorBase, AudioGenerator {
private let input: any ValidGeneratorInput
private let level: Double
init(input: any ValidGeneratorInput, level: Double = 0.5) {
self.input = input._resolvedInput() // resolve/classify inputs off the RT thread
self.level = level
super.init() // allocates _result: one mono channel, 512 frames
}
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) // bounds guard — no force-unwraps on the RT thread
guard let signal = input.calculatedSamples(graph: graph, count: count).first else {
return _result
}
for i in 0..<count {
_result[0][i] = max(-level, min(level, signal[i])) // clamp, in place
}
return _result // pre-allocated buffer; the engine reads it directly
}
}
// Wire it like any built-in generator — operators and literals compose it the same way:
let dirty = HardClip(input: OscSin.Audio(freq: 220.0), level: 0.2) * 0.5
```
`floatValue` comes free from the `AudioGenerator` extension. A generator that also makes sense at control rate (LFOs, envelopes) uses a paired `enum Name { class Audio; class Control }` namespace instead — see [`docs/protocols/writing-generators.md`](docs/protocols/writing-generators.md) for the full guide, shared helpers, and the multi-channel rules.
### Synthesizers — a graph plus live parameters ### Synthesizers — a graph plus live parameters
A `SynthesizerBase` subclass owns a graph built in `build()` and exposes `@LiveParam` (atomic, RT-safe) or `@UIParam` (SwiftUI-bindable) properties. The `$name` projection injects each parameter into the graph as a smoothed control-rate node: A `SynthesizerBase` subclass owns a graph built in `build()` and exposes `@LiveParam` (atomic, RT-safe) or `@UIParam` (SwiftUI-bindable) properties. The `$name` projection injects each parameter into the graph as a smoothed control-rate node:
@@ -57,7 +112,7 @@ let engine = SynthesisEngine(
sampleRate: 48_000, sampleRate: 48_000,
numOutputChannels: 2, numOutputChannels: 2,
numInputChannels: 0, numInputChannels: 0,
driver: CoreAudioDriver()) // NRTDriver for offline, iOSAudioDriver for iOS driver: makeDefaultAudioDriver()) // CoreAudio on macOS, iOS driver on iOS, ALSA on Linux; NRTDriver for offline
try engine.start() try engine.start()
try engine.add(FMTone()) // sounds immediately try engine.add(FMTone()) // sounds immediately
@@ -66,7 +121,7 @@ try engine.schedule(tone, after: 2.5) // sample-accurate, 2.5 s from now
tone.carrierFreq = 660 // live, atomic, no glitch tone.carrierFreq = 660 // live, atomic, no glitch
``` ```
Swap `CoreAudioDriver()` for `NRTDriver(outputURL:duration:)` and the identical graph renders offline to a CAF file. See [`INSTALLATION_AND_USAGE.md`](INSTALLATION_AND_USAGE.md) to add the package and scaffold projects, and [`ARCHITECTURE.md`](ARCHITECTURE.md) for how the threading and scheduling work underneath. Swap `makeDefaultAudioDriver()` for `NRTDriver(outputURL:duration:)` and the identical graph renders offline to a CAF file. See [`INSTALLATION_AND_USAGE.md`](INSTALLATION_AND_USAGE.md) to add the package and scaffold projects, and [`ARCHITECTURE.md`](ARCHITECTURE.md) for how the threading and scheduling work underneath.
### Live coding — prototype in the interpreter ### Live coding — prototype in the interpreter
@@ -81,7 +136,7 @@ import LyrebirdSynth
let engine = SynthesisEngine( let engine = SynthesisEngine(
blockSize: 512, sampleRate: 48_000, blockSize: 512, sampleRate: 48_000,
numOutputChannels: 2, numInputChannels: 0, numOutputChannels: 2, numInputChannels: 0,
driver: CoreAudioDriver()) driver: makeDefaultAudioDriver())
try engine.start() try engine.start()
// Define a synth right in the session. // Define a synth right in the session.
@@ -128,10 +183,15 @@ The REPL is text-only and works from any project that depends on Lyrebird; the s
## Requirements ## Requirements
| Platform | OS | Xcode | Swift | | Platform | OS | IDE | Swift |
|---|---|---|---| |---|---|---|---|
| macOS | 15+ | 16+ | 6.0 | | macOS | 15+ | Xcode 16+ | 6.0 |
| iOS | 18+ | 16+ | 6.0 | | iOS | 18+ | Xcode 16+ | 6.0 |
| Linux | Ubuntu 22.04+ ¹ | VS Code ² | 6.0 |
¹ Any swift.org-supported distribution with a Swift 6.0+ toolchain. Install `libasound2-dev` for live audio via the ALSA driver; offline/NRT rendering needs no audio device or ALSA.
² VS Code with the [Swift extension](https://marketplace.visualstudio.com/items?itemName=swiftlang.swift-vscode) (build/debug via SourceKit-LSP); any editor works with the `swift` CLI. Linux setup walk-through: [`docs/linux-getting-started.md`](docs/linux-getting-started.md).
--- ---
@@ -140,7 +200,7 @@ The REPL is text-only and works from any project that depends on Lyrebird; the s
Add the package: Add the package:
``` ```
https://realizedsound.mooo.com/josh/Lyrebird.git https://git.lyrebirdsynth.net/josh/Lyrebird.git
``` ```
**File ▸ Add Package Dependencies…** → that URL → **Up to Next Major** from `1.0.0` → add the `Lyrebird` product (and `LyrebirdUI` for the SwiftUI controls). Write `import LyrebirdSynth` in your code (the product is `Lyrebird`; the module it vends is `LyrebirdSynth`). **File ▸ Add Package Dependencies…** → that URL → **Up to Next Major** from `1.0.0` → add the `Lyrebird` product (and `LyrebirdUI` for the SwiftUI controls). Write `import LyrebirdSynth` in your code (the product is `Lyrebird`; the module it vends is `LyrebirdSynth`).
@@ -149,7 +209,24 @@ That's it — the `Lyrebird` product links **statically**, so there's no dynamic
Full walk-through (SPM manifest form, local-path dev dependency, per-template details): [`INSTALLATION_AND_USAGE.md`](INSTALLATION_AND_USAGE.md). DocC version: **Getting Started ▸ Adding Lyrebird to your own Xcode project**. Full walk-through (SPM manifest form, local-path dev dependency, per-template details): [`INSTALLATION_AND_USAGE.md`](INSTALLATION_AND_USAGE.md). DocC version: **Getting Started ▸ Adding Lyrebird to your own Xcode project**.
**On Linux?** The non-UI core — engine, generators, CLI, offline render, live ALSA audio, MIDI, and OSC — builds and runs on Linux (no Xcode, no SwiftUI). Start here: [`docs/linux-getting-started.md`](docs/linux-getting-started.md). **On Linux (or any SwiftPM project without the Xcode UI)** — there's no "Add Package Dependencies" dialog, so declare it in `Package.swift`:
```swift
dependencies: [
.package(url: "https://git.lyrebirdsynth.net/josh/Lyrebird", from: "1.0.0"),
],
targets: [
.executableTarget(
name: "MyApp",
dependencies: [
.product(name: "Lyrebird", package: "Lyrebird"),
// .product(name: "LyrebirdUI", package: "Lyrebird"), // Apple-only — SwiftUI controls
]
),
]
```
Then `import LyrebirdSynth`. On Linux the non-UI core — engine, generators, CLI, offline render, live ALSA audio, MIDI, and OSC — builds and runs with no Xcode and no SwiftUI (`LyrebirdUI` is Apple-only; a GTK4 UI ships as a separate demo). Full setup: [`docs/linux-getting-started.md`](docs/linux-getting-started.md).
--- ---
@@ -165,18 +242,19 @@ xed . # opens Package.swift — Xcode auto-generates schemes for every target
### Schemes ### Schemes
Workspace scheme selector exposes ten entries: Workspace scheme selector exposes eleven entries:
| Scheme | Purpose | Platform | | Scheme | Purpose | Platform |
|---|---|---| |---|---|---|
| `Lyrebird-Package` | Umbrella — builds Lyrebird + LyrebirdUI + LyrebirdLiveCompile + LyrebirdC + LyrebirdBenchmark + LyrebirdCLI, runs the test suites, launches/profiles `LyrebirdCLI` | macOS | | `Lyrebird-Package` | Umbrella — builds Lyrebird + LyrebirdUI + LyrebirdLiveCompile + LyrebirdC + LyrebirdBenchmark + LyrebirdCLI, runs the test suites, launches/profiles `LyrebirdCLI` | macOS |
| `LyrebirdQuickstartDemo` | CLI — fastest sound: a one-oscillator `SineTone` that plays 440 Hz for 10 s and exits | macOS | | `LyrebirdQuickstartDemo` | CLI — fastest sound: a one-oscillator `SineTone` that plays 440 Hz for 10 s and exits | macOS · Linux |
| `LyrebirdUI` | Builds the `LyrebirdUI` module only (SwiftUI parameter controls + visualisations) | macOS | | `LyrebirdUI` | Builds the `LyrebirdUI` module only (SwiftUI parameter controls + visualisations) | macOS |
| `LyrebirdDemo` | CLI — plays through default output via `CoreAudioDriver` | macOS | | `LyrebirdDemo` | CLI — plays through default output via `makeDefaultAudioDriver()` | macOS · Linux |
| `LyrebirdMacOSDemo` | SwiftUI app — live oscilloscope, `@UIParam` knobs | macOS | | `LyrebirdMacOSDemo` | SwiftUI app — live oscilloscope, `@UIParam` knobs | macOS |
| `LyrebirdGUIDemo` | Cross-platform GUI — one shared source; SwiftUI here, GTK4 on Linux (`LYREBIRD_DEMO=vector`/`sine`) | macOS · Linux |
| `LyrebirdiOSDemo` | SwiftUI app — same UI via `iOSAudioDriver` (RemoteIO) | iOS | | `LyrebirdiOSDemo` | SwiftUI app — same UI via `iOSAudioDriver` (RemoteIO) | iOS |
| `LyrebirdNRTDemo` | CLI — offline render to CAF via `NRTDriver` | macOS | | `LyrebirdNRTDemo` | CLI — offline render via `NRTDriver` (CAF on macOS, WAV on Linux) | macOS · Linux |
| `LyrebirdScoreDemo` | CLI — builds notated `Score`s (result-builder DSL), exports MusicXML, renders to CAF via `NRTDriver` | macOS | | `LyrebirdScoreDemo` | CLI — builds notated `Score`s (result-builder DSL), exports MusicXML, renders via `NRTDriver` (CAF on macOS, WAV on Linux) | macOS · Linux |
| `LyrebirdAUv3Demo` | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro, etc. Run the host app once to register the extension. | macOS | | `LyrebirdAUv3Demo` | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro, etc. Run the host app once to register the extension. | macOS |
| `LyrebirdScratch` | Live-coding scratchpad — type Swift snippets, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS | | `LyrebirdScratch` | Live-coding scratchpad — type Swift snippets, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
@@ -192,6 +270,35 @@ Use `Lyrebird-Package` for day-to-day development of the engine and tests.
| Build fails with Swift driver errors | Xcode 26 bug affecting the **demo workspace** (which dynamic-links for live-coding) — it already sets `SWIFT_USE_INTEGRATED_DRIVER = NO` + `parallelizeBuildables = NO`. Your own project links Lyrebird statically and is unaffected. | | Build fails with Swift driver errors | Xcode 26 bug affecting the **demo workspace** (which dynamic-links for live-coding) — it already sets `SWIFT_USE_INTEGRATED_DRIVER = NO` + `parallelizeBuildables = NO`. Your own project links Lyrebird statically and is unaffected. |
| `dyld: Library not loaded` | Only the bundled demos/AUv3 use the dynamic `LyrebirdDynamic` product; their entitlements already set `disable-library-validation`. External consumers link the static `Lyrebird` product and never hit this. | | `dyld: Library not loaded` | Only the bundled demos/AUv3 use the dynamic `LyrebirdDynamic` product; their entitlements already set `disable-library-validation`. External consumers link the static `Lyrebird` product and never hit this. |
### On Linux — VS Code or any editor (no Xcode)
Xcode, the `.xcworkspace`, and the schemes above are Apple-only. On Linux there's no workspace to open — point an editor at the package directory and drive it from the terminal:
```bash
code --install-extension swiftlang.swift-vscode # once: the official Swift extension (SourceKit-LSP: autocomplete, jump-to-def, debug)
code . # open the package in VS Code
```
There are no schemes — run targets directly:
```bash
swift build && swift test # build + run the Linux test suites
swift run LyrebirdCLI repl # the CLI (also `new`, scaffolding, …)
LYREBIRD_ENABLE_LINUX_UI=1 swift run LyrebirdUILinuxDemo # the GTK4 UI demo
```
The CLI demo projects build and run on Linux too — each is its own package, so run it from its folder (`swift run` picks up the single executable):
```bash
(cd Demos/LyrebirdNRTDemo && swift run) # offline render → ./nrt_output.wav (no audio device needed)
(cd Demos/LyrebirdQuickstartDemo && swift run) # a 440 Hz sine (needs libasound + a sound device)
(cd Demos/LyrebirdDemo && swift run) # reverb smoke-test through default output
(cd Demos/LyrebirdScoreDemo && swift run) # notated Score → MusicXML + a rendered WAV (no device)
(cd Demos/LyrebirdGUIDemo && swift run) # cross-platform GUI via GTK4 (needs libgtk-4-dev); LYREBIRD_DEMO=vector|sine
```
The four CLI demos plus `LyrebirdGUIDemo` (a GTK4 window here, SwiftUI on macOS) run on Linux; the AUv3 / iOS / `LyrebirdMacOSDemo` GUI demos are Apple-only. Full walk-through — toolchain, VS Code, building, running a sample: [`docs/linux-getting-started.md`](docs/linux-getting-started.md).
--- ---
## Building and testing from the terminal ## Building and testing from the terminal
@@ -202,23 +309,24 @@ swift test # run all 5481 tests
swift test --filter LyrebirdTests # run one suite swift test --filter LyrebirdTests # run one suite
swift run lyrebird # run the CLI swift run lyrebird # run the CLI
swift run lyrebird repl # Swift REPL with Lyrebird available swift run lyrebird repl # Swift REPL with Lyrebird available
swift run LyrebirdDemo # run the hardware smoke-test demo (cd Demos/LyrebirdDemo && swift run) # run a demo project (each Demos/* is its own package)
``` ```
--- ---
## Demo projects ## Demo projects
All eight live in [`Demos/`](Demos/). Open via `Lyrebird.xcworkspace`. All nine live in [`Demos/`](Demos/). Each is its own SwiftPM package depending on the local checkout, so a demo runs with `swift run` from its folder on **any** platform it supports — no Xcode needed. On macOS you can also open them together via `Lyrebird.xcworkspace`. The demos marked **Linux** build and run on Linux as well (see the Linux VS Code section above); `LyrebirdGUIDemo` is the cross-platform GUI — SwiftUI on macOS, GTK4 on Linux, one source.
| Demo | What it does | Platform | | Demo | What it does | Platform |
|---|---|---| |---|---|---|
| [`LyrebirdQuickstartDemo`](Demos/LyrebirdQuickstartDemo/) | CLI — fastest sound: a one-oscillator `SineTone` plays 440 Hz for 10 s, then exits (mirrors the `quickstart` template) | macOS | | [`LyrebirdQuickstartDemo`](Demos/LyrebirdQuickstartDemo/) | CLI — fastest sound: a one-oscillator `SineTone` plays 440 Hz for 10 s, then exits (mirrors the `quickstart` template) | macOS · Linux |
| [`LyrebirdDemo`](Demos/LyrebirdDemo/) | CLI — plays through default output via `CoreAudioDriver` | macOS | | [`LyrebirdDemo`](Demos/LyrebirdDemo/) | CLI — plays through default output via `makeDefaultAudioDriver()` (Core Audio on macOS, ALSA on Linux) | macOS · Linux |
| [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | SwiftUI app — live oscilloscope, `@UIParam` knobs | macOS | | [`LyrebirdGUIDemo`](Demos/LyrebirdGUIDemo/) | GUI — live `@UIParam` controls, XY pad, oscilloscope, CPU meters, from one shared source; AppKit/SwiftUI on macOS, GTK4/SwiftOpenUI on Linux (`LYREBIRD_DEMO=vector`/`sine`) | macOS · Linux |
| [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | SwiftUI app — live oscilloscope, `@UIParam` knobs, vector / sine / spectral-bin-delay patches | macOS |
| [`LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/) | SwiftUI app — same UI system via `iOSAudioDriver` (RemoteIO) | iOS | | [`LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/) | SwiftUI app — same UI system via `iOSAudioDriver` (RemoteIO) | iOS |
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | CLI — offline render to CAF file via `NRTDriver` | macOS | | [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | CLI — offline render via `NRTDriver` (CAF on macOS, WAV on Linux) | macOS · Linux |
| [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | CLI — notated `Score` → MusicXML export + offline render to CAF via `NRTDriver` | macOS | | [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | CLI — notated `Score` → MusicXML export + offline render via `NRTDriver` (CAF on macOS, WAV on Linux) | macOS · Linux |
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro | macOS | | [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro | macOS |
| [`LyrebirdScratch`](Demos/LyrebirdScratch/) | Live-coding scratchpad — type Swift, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS | | [`LyrebirdScratch`](Demos/LyrebirdScratch/) | Live-coding scratchpad — type Swift, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
@@ -256,14 +364,10 @@ Arrow-key editing, tab completion, persistent history (`~/.lyrebird_history`). `
Lyrebird supports out-of-tree Swift packages that add `Generator` or `Synthesizer` implementations. Extension packages depend on Lyrebird via SwiftPM, host their own source, and ship their own version releases — core users pin the version range they want. Lyrebird supports out-of-tree Swift packages that add `Generator` or `Synthesizer` implementations. Extension packages depend on Lyrebird via SwiftPM, host their own source, and ship their own version releases — core users pin the version range they want.
| Package | Description |
|---|---|
| [`LyrebirdATK`](#) | First-order Ambisonics toolkit (37 `Foa*` UGens, MIT KEMAR HRIR set, binaural decoder). Worked example for the Extension SDK. |
Building your own extension package: Building your own extension package:
- **API contract**: [`docs/protocols/extension-sdk.md`](docs/protocols/extension-sdk.md) — tier-1 stable public surface + tier-2 `@_spi(LyrebirdExtensions)` symbols and versioning policy. - **API contract**: [`docs/protocols/extension-sdk.md`](docs/protocols/extension-sdk.md) — tier-1 stable public surface + tier-2 `@_spi(LyrebirdExtensions)` symbols and versioning policy.
- **Walk-through**: [`docs/extension-authors-guide.md`](docs/extension-authors-guide.md) — end-to-end build a new extension package using LyrebirdATK as the reference. - **Walk-through**: [`docs/extension-authors-guide.md`](docs/extension-authors-guide.md) — end-to-end build a new extension package.
--- ---
@@ -281,6 +385,7 @@ LyrebirdII/
├── Demos/ ├── Demos/
│ ├── LyrebirdQuickstartDemo/ # fastest sound — SineTone plays 10 s then exits │ ├── LyrebirdQuickstartDemo/ # fastest sound — SineTone plays 10 s then exits
│ ├── LyrebirdDemo/ # (same as Sources/LyrebirdDemo — workspace target) │ ├── LyrebirdDemo/ # (same as Sources/LyrebirdDemo — workspace target)
│ ├── LyrebirdGUIDemo/ # cross-platform GUI — SwiftUI (macOS) + GTK4 (Linux), one source
│ ├── LyrebirdMacOSDemo/ # macOS SwiftUI app │ ├── LyrebirdMacOSDemo/ # macOS SwiftUI app
│ ├── LyrebirdiOSDemo/ # iOS SwiftUI app │ ├── LyrebirdiOSDemo/ # iOS SwiftUI app
│ ├── LyrebirdNRTDemo/ # offline renderer │ ├── LyrebirdNRTDemo/ # offline renderer
+168
View File
@@ -7,6 +7,174 @@ functionality in a backward-compatible way.
--- ---
## 2.4.0 — Event patterns and the live event conductor
An additive, source-compatible release that adds a declarative, event-driven
layer on top of the existing routine/clock system. It is modelled on the
pattern-event idea familiar from other synthesis environments, but the public
API is named for what each type does rather than after any one of them.
**New — `EventPattern`.** A declarative pattern that binds typed key paths on a
voice to value patterns and plays one voice per event, scheduling each event's
start and release from a duration/`legato` pattern. A voice releases in one of
two ways, and never both: a self-timed envelope if it conforms to
`EventSustainAware` (it is handed the event's sustain in seconds), or a
pattern-driven gate note-off if it conforms to `EventGated`. When a voice
conforms to both, the **gate wins** — `setEventSustain` is skipped so the two
release paths never fire together. A plain voice (neither conformance) is
removed by the pattern after `sustain + releaseTail`.
**New — `MonoEventPattern`.** One reused voice whose parameters are rewritten
per event, with an optional `EventRetriggerable` re-strike. Gains a
`play(on:startAfterBeats:)` lead-in so a mono part can enter an ensemble on a
delayed beat.
**New — `ParallelEventPattern`.** Heterogeneous `EventPatternPlayable` children
started together under one merged `EventPatternHandle`; `add` enters with the
group and `addAfter(beats:)` staggers a child's entry.
**New — `EventConductor` + `EventConductorHandle`.** A live, clock-driven
ensemble you can feed while it runs: `add(_:quantize:)` is thread-safe from a
UI, OSC, or MIDI callback, and entry is **clock-deferred** — quantised by an
`EventQuantum` (`.now`, `.nextBeat`, `.nextMultiple(ofBeats:)`, `.atBeat`,
`.afterBeats`) against the conductor's own clock, so entry is tempo-independent
and each part keeps its own timing afterward. `add` returns an
`EventConductorHandle` that stops a single part — cancelling it if it is still
pending, stopping it if it is already playing.
All new types; no existing API changed, so this is drop-in over 2.3.x. See
`docs/tooling/routine-task.md` (§ EventPattern / § EventConductor) and the new
`.conductor` demo in `LyrebirdGUIDemo`.
---
## 2.3.0 — Edit-ended callback on continuous controls
A small, additive, source-compatible release. The continuous `LyrebirdUI`
controls drive their parameter node(s) continuously while dragging, which gives
a host no single "the user finished this edit" signal. This adds one.
**New — `.onEditingEnded` on the continuous controls.** `ParameterKnob`,
`ParameterSlider`, `ParameterXY`, and `MultiSlider` gain an `.onEditingEnded`
modifier (both the SwiftUI and the Linux/GTK4 variants) that fires **once per
drag gesture**, reporting the value(s) at the start and end of the drag. A host
can use it to record a single edit per gesture — an undo checkpoint, say —
instead of one per intermediate update. The payload matches each control:
`(previous, new)` doubles for the knob and slider, a pair of `(x, y)` tuples for
the XY pad, and the before/after cell-value arrays for the multi-slider.
Additive and drop-in over 2.2.x: every control's public initializer is
unchanged (the callback is attached by the modifier), so existing call sites and
DocC links are unaffected. See `docs/ui/gui-system.md` for examples.
---
## 2.2.0 — Live-parameter ramp origin primed at synth add
A small-but-behavioral release. One fix to how `@UIParam` / `@LiveParam` values
are delivered on a synth's first rendered block, plus the internal hook that
backs it. The public API is source-compatible — the one new protocol member is
internal-facing and ships with a default implementation — so this is drop-in
over 2.1.x, but the delivery change is observable and is called out below.
**Fix — a parameter set before the first render is now delivered flat.** When a
value is assigned to an `@UIParam` / `@LiveParam` *after the synth is
constructed but before it first renders* — most commonly when restoring saved
state onto a freshly built synth — the parameter is now delivered as a flat
block at that value from sample 0. Previously the first rendered block ramped
from the property-declaration default up to the assigned value over one
(sub-)block, because the property-wrapper setter advances the atomic target but
not the interpolation origin, which stayed at the construction-time default.
For most parameters that one-block (~a few ms) glide was benign. For a value
feeding a decision stage it was not: a `Schmidt` trigger fed a threshold that
swept up from the default would latch on the transient and, if the steady signal
sat inside the hysteresis band, never reset — e.g. a `NoiseGate` restored from a
saved rig would open on load and ignore its threshold. Priming the origin at add
removes the sweep.
Mechanically: `SynthesizerBase`, as part of the `Mirror`-based live-parameter
auto-registration it already runs at add time (`rebuildGraph()`, main thread,
before the node is visible to the RT thread), now also primes each parameter's
ramp origin to its current value via a new `LiveParameterValue._primeRampOrigin()`.
`ParameterNode` and `UIParamNode` implement it; external conformers inherit a
no-op default, so nothing is source-broken. A re-add (`remove` → change value →
`add`) likewise re-primes to the then-current value.
**Behavior change to be aware of.** Two deliveries changed, both toward "the
value you set before starting is the value you get":
- A value assigned between construction and first render is **flat** on block
one, not a ramp from the declaration default. Code that (knowingly or not)
relied on that opening glide will no longer see it. If you want an opening
ramp, drive the parameter from a source/envelope or change it after start.
- A synth removed, re-assigned while out of the tree, then re-added starts
**flat at the new value** rather than gliding from the value it last rendered.
Live changes made **while the synth is running** are unchanged — they still ramp
per (sub-)block from the last rendered value, as before. The source-slot /
crossfade path is unaffected (the source overwrites the origin each block).
Pinned by `LiveParamRampOriginTests` (flat delivery for `@UIParam` and
`@LiveParam`, live-change-still-ramps, remove/change/re-add, and source-slot
non-interference).
---
## 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 ## 2.0.0 — Linux support
The major release: Lyrebird now runs on **Linux**, in addition to macOS and iOS. 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, format: AudioFileFormat,
sampleRate: Double, sampleRate: Double,
channels: Int channels: Int
) throws { ) throws(RF64WriterError) {
guard format == .rf64Float32 || format == .rf64Int24 else { guard format == .rf64Float32 || format == .rf64Int24 else {
throw RF64WriterError.unsupportedFormat(format) throw RF64WriterError.unsupportedFormat(format)
} }
@@ -173,7 +173,7 @@ public final class RF64Writer {
/// Append `frames` interleaved frames of native Float32 samples, converting to the /// Append `frames` interleaved frames of native Float32 samples, converting to the
/// file encoding. `samples` must contain at least `frames * channels` values. /// 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 } guard frames > 0 else { return }
let sampleCount: Int = frames * channels 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 /// The `FileHandle` is closed unconditionally (even if patching throws) so a failed
/// finalise never leaks the descriptor. /// finalise never leaks the descriptor.
public func close() throws { public func close() throws(RF64WriterError) {
guard !closed else { return } guard !closed else { return }
closed = true closed = true
defer { try? fileHandle.close() } 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 /// A plain WAV cannot describe more than 4 GB — its RIFF and `data` sizes
/// are 32-bit. Writing past that needs RF64/W64 instead. /// are 32-bit. Writing past that needs RF64/W64 instead.
case fileTooLarge(bytes: Int) 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 private var framesRemaining: Int
/// Opens `url` and parses its WAVE header. /// 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 { guard let h: FileHandle = try? FileHandle(forReadingFrom: url) else {
throw WavFileError.cannotOpen(url) throw WavFileError.cannotOpen(url)
} }
@@ -51,9 +51,9 @@ public final class WavFileReader {
// File length, for clamping a `data` size the file cannot back. Taken // 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 // by seeking to the end and back rather than stat-ing the path, so it
// describes the handle actually being read. // describes the handle actually being read.
let scanStart: UInt64 = try h.offset() let scanStart: UInt64 = try Self.fhOffset(h)
let fileByteCount: Int = Int(try h.seekToEnd()) let fileByteCount: Int = Int(try Self.fhSeekToEnd(h))
try h.seek(toOffset: scanStart) try Self.fhSeek(h, to: scanStart)
// Walk chunks until the data chunk is located (its body is left unread // Walk chunks until the data chunk is located (its body is left unread
// so reads stream from the current file offset). // 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 // and believing it yields a nonsense frame count and a
// `.truncated` throw partway through a render instead of a // `.truncated` throw partway through a render instead of a
// clean EOF. // 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) dataLength = min(size, remaining)
foundData = true foundData = true
break break
@@ -100,10 +100,10 @@ public final class WavFileReader {
// discard it, and a file with embedded artwork or a large // discard it, and a file with embedded artwork or a large
// "LIST" ahead of `data` makes that a real allocation. // "LIST" ahead of `data` makes that a real allocation.
let skip: Int = size + (size % 2) 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)) let target: UInt64 = current + UInt64(max(0, skip))
guard target <= UInt64(fileByteCount) else { break } 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 /// Reads up to `frames` frames, returning interleaved `Float` samples. The
/// returned array holds `framesRead * channels` values; `framesRead` may be /// returned array holds `framesRead * channels` values; `framesRead` may be
/// smaller than requested at end of file (and zero once exhausted). /// 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) let toRead: Int = min(frames, framesRemaining)
guard toRead > 0 else { return [] } guard toRead > 0 else { return [] }
let byteCount: Int = toRead * bytesPerFrame let byteCount: Int = toRead * bytesPerFrame
@@ -169,11 +169,11 @@ public final class WavFileReader {
/// end simply exhausts the reader. /// end simply exhausts the reader.
/// ///
/// - Parameter frames: Frames to advance by. Non-positive values do nothing. /// - 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) let toSkip: Int = min(frames, framesRemaining)
guard toSkip > 0 else { return } guard toSkip > 0 else { return }
let current: UInt64 = try handle.offset() let current: UInt64 = try Self.fhOffset(handle)
try handle.seek(toOffset: current + UInt64(toSkip * bytesPerFrame)) try Self.fhSeek(handle, to: current + UInt64(toSkip * bytesPerFrame))
framesRemaining -= toSkip 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 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 throw WavFileError.truncated
} }
return d return d
+51 -16
View File
@@ -62,7 +62,7 @@ public final class WavFileWriter {
channels: Int, channels: Int,
sampleRate: Double, sampleRate: Double,
encoding: WavEncoding = .float32 encoding: WavEncoding = .float32
) throws { ) throws(WavFileError) {
precondition(channels >= 1, "WavFileWriter requires at least one channel") precondition(channels >= 1, "WavFileWriter requires at least one channel")
self.channels = channels self.channels = channels
self.encoding = encoding self.encoding = encoding
@@ -80,8 +80,11 @@ public final class WavFileWriter {
guard fm.createFile(atPath: url.path, contents: header) else { guard fm.createFile(atPath: url.path, contents: header) else {
throw WavFileError.cannotCreate(url) throw WavFileError.cannotCreate(url)
} }
self.handle = try FileHandle(forWritingTo: url) let h: FileHandle
try handle.seekToEnd() 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. /// Appends one block of interleaved `Float` samples.
@@ -89,7 +92,7 @@ public final class WavFileWriter {
/// - Parameters: /// - Parameters:
/// - samples: Interleaved buffer, length ≥ `frames * channels`. /// - samples: Interleaved buffer, length ≥ `frames * channels`.
/// - frames: Number of frames (per-channel sample groups) to write. /// - 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 let needed: Int = frames * channels
precondition(samples.count >= needed, "interleaved buffer shorter than frames * channels") precondition(samples.count >= needed, "interleaved buffer shorter than frames * channels")
var out: Data = Data(capacity: needed * encoding.bytesPerSample) var out: Data = Data(capacity: needed * encoding.bytesPerSample)
@@ -121,7 +124,7 @@ public final class WavFileWriter {
out.append(UInt8(truncatingIfNeeded: v >> 16)) out.append(UInt8(truncatingIfNeeded: v >> 16))
} }
} }
try handle.write(contentsOf: out) try Self.fhWrite(handle, out)
dataBytesWritten += out.count dataBytesWritten += out.count
} }
@@ -133,7 +136,7 @@ public final class WavFileWriter {
} }
/// Patches the RIFF and `data` chunk sizes and closes the file. Idempotent. /// 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 } guard !finalized else { return }
// Chunks are word-aligned: an odd `data` payload (possible with int24) // Chunks are word-aligned: an odd `data` payload (possible with int24)
// needs a pad byte, which counts toward the RIFF size but not the // 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. // sizing the file for one.
let padByteCount: Int = dataBytesWritten % 2 let padByteCount: Int = dataBytesWritten % 2
if padByteCount > 0 && !padByteWritten { if padByteCount > 0 && !padByteWritten {
try handle.seekToEnd() try Self.fhSeekToEnd(handle)
try handle.write(contentsOf: [UInt8(0)]) try Self.fhWrite(handle, [UInt8(0)])
padByteWritten = true padByteWritten = true
} }
let riffChunkSize: UInt32 = try Self.riffChunkSize( let riffChunkSize: UInt32 = try Self.riffChunkSize(
@@ -153,8 +156,8 @@ public final class WavFileWriter {
) )
let dataChunkSize: UInt32 = UInt32(dataBytesWritten) let dataChunkSize: UInt32 = UInt32(dataBytesWritten)
try handle.seek(toOffset: Self.riffChunkSizeOffset) try Self.fhSeek(handle, to: Self.riffChunkSizeOffset)
try handle.write(contentsOf: Self.leBytes(riffChunkSize)) try Self.fhWrite(handle, Self.leBytes(riffChunkSize))
if !encoding.isPCM { if !encoding.isPCM {
// `fact` carries the per-channel sample count, which is only known // `fact` carries the per-channel sample count, which is only known
// now that writing has finished. // now that writing has finished.
@@ -162,12 +165,12 @@ public final class WavFileWriter {
let frames: UInt32 = bytesPerFrame > 0 let frames: UInt32 = bytesPerFrame > 0
? UInt32(dataBytesWritten / bytesPerFrame) ? UInt32(dataBytesWritten / bytesPerFrame)
: 0 : 0
try handle.seek(toOffset: Self.factSampleCountOffset) try Self.fhSeek(handle, to: Self.factSampleCountOffset)
try handle.write(contentsOf: Self.leBytes(frames)) try Self.fhWrite(handle, Self.leBytes(frames))
} }
try handle.seek(toOffset: dataChunkSizeOffset) try Self.fhSeek(handle, to: dataChunkSizeOffset)
try handle.write(contentsOf: Self.leBytes(dataChunkSize)) try Self.fhWrite(handle, Self.leBytes(dataChunkSize))
try handle.close() try Self.fhClose(handle)
// Set last: a throw above must leave the writer retryable rather than // Set last: a throw above must leave the writer retryable rather than
// latching "finalized" over a file whose sizes are still zero. // latching "finalized" over a file whose sizes are still zero.
finalized = true finalized = true
@@ -181,7 +184,7 @@ public final class WavFileWriter {
/// ///
/// - Throws: ``WavFileError/fileTooLarge(bytes:)`` past `UInt32.max`. /// - Throws: ``WavFileError/fileTooLarge(bytes:)`` past `UInt32.max`.
@_spi(LyrebirdExtensions) @_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 let payload: Int = headerBytes - 8 + dataBytes
guard payload <= Int(UInt32.max) else { guard payload <= Int(UInt32.max) else {
throw WavFileError.fileTooLarge(bytes: payload) throw WavFileError.fileTooLarge(bytes: payload)
@@ -189,6 +192,38 @@ public final class WavFileWriter {
return UInt32(payload) 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 // MARK: - Header
private static func makeHeader( 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. /// Allocates the first contiguous block of `channelCount` free audio buses.
/// Throws `BusAllocatorError.noFreeBus` if no block of that size is available. /// 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) let index: Int = try _allocate(in: &audioFreeList, channelCount: channelCount)
return AudioBus(index: index, 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. /// Allocates the first contiguous block of `channelCount` free control buses.
/// Throws `BusAllocatorError.noFreeBus` if no block of that size is available. /// 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) let index: Int = try _allocate(in: &controlFreeList, channelCount: channelCount)
return ControlBus(index: index, channelCount: channelCount) return ControlBus(index: index, channelCount: channelCount)
} }
@@ -113,13 +113,15 @@ public final class BusAllocator: @unchecked Sendable {
private func _allocate( private func _allocate(
in freeList: inout [Bool], in freeList: inout [Bool],
channelCount: Int channelCount: Int
) throws -> Int { ) throws(BusAllocatorError) -> Int {
precondition(channelCount >= 1, "BusAllocator: channelCount must be >= 1") 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 let n: Int = freeList.count
guard channelCount <= n else { guard channelCount <= n else { return nil }
throw BusAllocatorError.noFreeBus(channelCount: channelCount)
}
var start: Int = 0 var start: Int = 0
outer: while start <= n - channelCount { outer: while start <= n - channelCount {
for i: Int in start..<(start + channelCount) { for i: Int in start..<(start + channelCount) {
@@ -133,8 +135,12 @@ public final class BusAllocator: @unchecked Sendable {
} }
return start return start
} }
return nil
}
guard let index: Int = allocated else {
throw BusAllocatorError.noFreeBus(channelCount: channelCount) throw BusAllocatorError.noFreeBus(channelCount: channelCount)
} }
return index
} }
/// Marks `[startIndex, startIndex + channelCount)` slots back to free. When /// 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. /// - fftSize: FFT frame size. Must match the `SpectralChain.Audio` this capture is registered on.
/// Must be a power of two ≥ 4. Default: 2048. /// Must be a power of two ≥ 4. Default: 2048.
public init(fftSize: Int = 2048) { public init(fftSize: Int = 2048) {
precondition( lyrebirdRequireFFTSize(fftSize, typeName: "SpectrumCapture")
fftSize >= 4 && (fftSize & (fftSize - 1)) == 0,
"SpectrumCapture: fftSize must be a power of two >= 4, got \(fftSize)"
)
self.fftSize = fftSize self.fftSize = fftSize
let bc: Int = fftSize / 2 + 1 let bc: Int = fftSize / 2 + 1
self.binCount = bc 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 /// it is callable from any non-RT thread. From a `LyrebirdRoutine` / `LyrebirdTask` body, go
/// through the context (``LyrebirdRoutineContext/add(_:)``, which dispatches to main) rather /// through the context (``LyrebirdRoutineContext/add(_:)``, which dispatches to main) rather
/// than calling the engine directly. See `ARCHITECTURE.md` §1 and §9. /// 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 { public final class SynthesisEngine {
/// Process-unique identity. Used by the engine ownership-binding system /// 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 /// - Throws: ``SynthesisEngineConfigError/engineIsRunning`` if the engine is
/// currently running; ``SynthesisEngineConfigError/invalidValue(_:)`` if /// currently running; ``SynthesisEngineConfigError/invalidValue(_:)`` if
/// `rate` is non-finite or `<= 0`. /// `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 !isRunning else { throw SynthesisEngineConfigError.engineIsRunning }
guard rate.isFinite, rate > 0 else { guard rate.isFinite, rate > 0 else {
throw SynthesisEngineConfigError.invalidValue( throw SynthesisEngineConfigError.invalidValue(
@@ -982,7 +1006,7 @@ public final class SynthesisEngine {
/// `numAudioBuses`. /// `numAudioBuses`.
/// - Throws: ``SynthesisEngineConfigError/engineIsRunning`` / /// - Throws: ``SynthesisEngineConfigError/engineIsRunning`` /
/// ``SynthesisEngineConfigError/invalidValue(_:)``. /// ``SynthesisEngineConfigError/invalidValue(_:)``.
public func setNumOutputChannels(_ count: Int) throws { public func setNumOutputChannels(_ count: Int) throws(SynthesisEngineConfigError) {
guard !isRunning else { throw SynthesisEngineConfigError.engineIsRunning } guard !isRunning else { throw SynthesisEngineConfigError.engineIsRunning }
guard count >= 1 else { guard count >= 1 else {
throw SynthesisEngineConfigError.invalidValue( throw SynthesisEngineConfigError.invalidValue(
@@ -1013,7 +1037,7 @@ public final class SynthesisEngine {
/// `numAudioBuses` together with `numOutputChannels`. /// `numAudioBuses` together with `numOutputChannels`.
/// - Throws: ``SynthesisEngineConfigError/engineIsRunning`` / /// - Throws: ``SynthesisEngineConfigError/engineIsRunning`` /
/// ``SynthesisEngineConfigError/invalidValue(_:)``. /// ``SynthesisEngineConfigError/invalidValue(_:)``.
public func setNumInputChannels(_ count: Int) throws { public func setNumInputChannels(_ count: Int) throws(SynthesisEngineConfigError) {
guard !isRunning else { throw SynthesisEngineConfigError.engineIsRunning } guard !isRunning else { throw SynthesisEngineConfigError.engineIsRunning }
guard count >= 0 else { guard count >= 0 else {
throw SynthesisEngineConfigError.invalidValue( throw SynthesisEngineConfigError.invalidValue(
@@ -1410,7 +1434,7 @@ public final class SynthesisEngine {
@MainActor public func schedule( @MainActor public func schedule(
_ synth: any Synthesizer, _ synth: any Synthesizer,
at time: SampleTime at time: SampleTime
) throws { ) throws(EngineAddError) {
precondition( precondition(
synth !== rootGroup && synth !== mainGroup, synth !== rootGroup && synth !== mainGroup,
"Cannot add the engine's persistent rootGroup or mainGroup as a child Synthesizer" "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( @MainActor public func schedule(
_ synth: any Synthesizer, _ synth: any Synthesizer,
after seconds: Double after seconds: Double
) throws { ) throws(EngineAddError) {
precondition( precondition(
synth !== rootGroup && synth !== mainGroup, synth !== rootGroup && synth !== mainGroup,
"Cannot add the engine's persistent rootGroup or mainGroup as a child Synthesizer" "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 /// Equivalent to `schedule(_:at:currentTime)`. The synthesizer lands at the head of
/// `mainGroup` — newest-first order. Safe to call from the main thread. /// `mainGroup` — newest-first order. Safe to call from the main thread.
/// - Throws: `EngineAddError` — see `schedule(_:at:)` for cases. /// - 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) try schedule(synth, at: currentTime)
} }
@@ -1526,7 +1550,7 @@ public final class SynthesisEngine {
@MainActor public func add( @MainActor public func add(
_ synth: any Synthesizer, _ synth: any Synthesizer,
position: NodePosition position: NodePosition
) throws { ) throws(EngineAddError) {
precondition( precondition(
synth !== rootGroup && synth !== mainGroup, synth !== rootGroup && synth !== mainGroup,
"Cannot add the engine's persistent rootGroup or mainGroup as a child Synthesizer" "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 /// Used by `calculatedSamples` when `controlBlockSize < count` to accumulate
/// results from multiple `_computeSamples` calls without heap allocation. /// results from multiple `_computeSamples` calls without heap allocation.
/// Initialise to `[[]]` (via `GeneratorBase` default). Call `_setupSubBlockBuffer()` /// Initialise to `[[]]` (via `GeneratorBase` default). A sub-blocking `Control.init`
/// in the designated `Control.init` to resize for sub-block assembly. Never call on the RT thread. /// 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 } var _subBlockBuffer: [[Double]] { get set }
} }
@@ -205,18 +206,16 @@ extension Generator {
/// Bypass-sub-block fan-out cache helper. /// Bypass-sub-block fan-out cache helper.
/// ///
/// Used by generators that override `calculatedSamples` to force `_computeSamples` to /// The block-rate gateway: runs `_computeSamples` exactly once per audio block,
/// run exactly once per audio block, bypassing the `ControlGenerator` extension's /// bypassing the `ControlGenerator` extension's sub-block path. Required for any
/// sub-block path. Required for any generator whose state must advance once per audio /// generator whose state must advance once per audio block (IIR filters, bus writers,
/// block (IIR filters, bus writers, buffer-position advancers, gain smoothers, trigger /// buffer-position advancers, gain smoothers, trigger detectors, random drawers,
/// detectors, random drawers). See `docs/protocols/writing-generators.md` §15. /// analysers). See `docs/protocols/writing-generators.md` §15.
/// ///
/// Drop-in replacement for the canonical bypass block: /// The standard way to get this behaviour is to conform the control generator to
/// ```swift /// `BlockRateControlGenerator`, whose `calculatedSamples` default calls this method —
/// public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { /// prefer that over hand-writing a `calculatedSamples` forwarder. Call this directly
/// _calculatedSamplesBlockRate(graph: graph, count: count) /// only when the bypass is needed but the marker cannot apply.
/// }
/// ```
@inline(__always) @inline(__always)
public func _calculatedSamplesBlockRate( public func _calculatedSamplesBlockRate(
graph: SynthGraph, graph: SynthGraph,
@@ -22,8 +22,10 @@
/// post-super reassignment. `outputChannelCount` must be overridden to return the /// post-super reassignment. `outputChannelCount` must be overridden to return the
/// fixed channel count. /// fixed channel count.
/// ///
/// `Audio` conformers inherit `_subBlockBuffer` as `[[]]` (no allocation); `Control` conformers /// `Audio` conformers inherit `_subBlockBuffer` as `[[]]` (no allocation); sub-blocking
/// resize it to `lyrebirdDefaultResultBufferSize` via `_setupSubBlockBuffer()` in `init`. /// `Control` conformers resize it to `lyrebirdDefaultResultBufferSize` via
/// `_setupSubBlockBuffer()` in `init`. `BlockRateControlGenerator` conformers never
/// sub-block and leave it unallocated.
open class GeneratorBase { open class GeneratorBase {
public var _segmentSerial: UInt64 = 0 public var _segmentSerial: UInt64 = 0
public var _cachedResult: [[Double]] = [[]] public var _cachedResult: [[Double]] = [[]]
@@ -58,3 +58,63 @@ public func resolveGeneratorOrScalar(
} }
return (nil, source.floatValue(graph: graph)) 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 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 // MARK: - Scalar extraction
/// Returns the constant value for compile-time-known scalar inputs, nil for generators/strings. /// 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) /// _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
/// ``` /// ```
/// `applyIfNeeded` short-circuits internally on `isIdentity`, so the call site /// `applyIfNeeded` short-circuits internally on `isIdentity`, so the call site
/// never needs an `if !isIdentity` guard. `MathGenerators.Control` does not call /// never needs an `if !isIdentity` guard. `MathGenerators.Control` applies mul/add to
/// through this struct — it computes its scalar `target = input * mulFloat + addFloat` /// its scalar `target` before the ramp (not to the output buffer after) via `applyScalar`
/// before the ramp, documented in `docs/protocols/writing-generators.md` §13. /// below — documented in `docs/protocols/writing-generators.md` §13.
@_spi(LyrebirdExtensions) @_spi(LyrebirdExtensions)
public struct MulAddSpec { public struct MulAddSpec {
public let mulInput: any ValidGeneratorInput public let mulInput: any ValidGeneratorInput
@@ -115,6 +83,20 @@ public struct MulAddSpec {
if !isIdentity { apply(to: &channels, graph: graph, count: count) } 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`. /// Applies `(x × mul) + add` via vDSP to every channel in `channels`.
/// ///
/// **Channel-aware broadcast (matches `BinaryOpGenerator` policy).** When `mul` or /// **Channel-aware broadcast (matches `BinaryOpGenerator` policy).** When `mul` or
@@ -247,8 +229,7 @@ public func fillRampedResult(
/// Usage in a Math-style ControlGenerator._computeSamples: /// Usage in a Math-style ControlGenerator._computeSamples:
/// ```swift /// ```swift
/// var target = someScalarOp(input.floatValue(graph: graph)) /// var target = someScalarOp(input.floatValue(graph: graph))
/// if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) /// target = _mulAdd.applyScalar(target, graph: graph)
/// + _mulAdd.addInput.floatValue(graph: graph) }
/// fillScalarRampedResult( /// fillScalarRampedResult(
/// into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) /// into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
/// return _result /// 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 // MARK: - Per-channel vDSP dispatch
/// Pure-scalar `(x * mulScalar) + addScalar` for one channel. No `Optional` /// Pure-scalar `(x * mulScalar) + addScalar` for one channel. No `Optional`
@@ -42,7 +42,7 @@ public enum BeatTrack {
/// once at init. Defaults to ``beatTrackPreferredBPM``. /// once at init. Defaults to ``beatTrackPreferredBPM``.
/// - windowSeconds: ODF history length for autocorrelation. Read once at /// - windowSeconds: ODF history length for autocorrelation. Read once at
/// init. Defaults to ``beatTrackMaxWindowSeconds``. /// 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 /// Internal ODF source + the input refs each mode needs. Only one mode's
/// state is live; the spectral-flux state (`_prevMag`, `_isFirstFrame`) /// state is live; the spectral-flux state (`_prevMag`, `_isFirstFrame`)
@@ -197,19 +197,8 @@ public enum BeatTrack {
featureRateHz: beatTrackFeatureRateHz featureRateHz: beatTrackFeatureRateHz
) )
super.init(channels: beatTrackOutputRowCount) 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( public func _computeSamples(
graph: SynthGraph, graph: SynthGraph,
@@ -38,7 +38,7 @@ public enum Loudness {
/// - calibrationDB: dBFS→SPL offset. Defaults to ``loudnessDefaultCalibrationDB``. /// - calibrationDB: dBFS→SPL offset. Defaults to ``loudnessDefaultCalibrationDB``.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset (sones). Defaults to `0.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 _analysis: SpectralChain.Audio?
private let _spectral: SpectralBuffer private let _spectral: SpectralBuffer
@@ -127,17 +127,8 @@ public enum Loudness {
) )
self._mulAdd = MulAddSpec(mul: mul, add: add) self._mulAdd = MulAddSpec(mul: mul, add: add)
super.init() 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( public func _computeSamples(
graph: SynthGraph, graph: SynthGraph,
@@ -143,7 +143,7 @@ public enum RunningMax {
/// - trig: Reset trigger. ≤0 → >0 rising edges reset the running maximum. Defaults to `0.0`. /// - trig: Reset trigger. ≤0 → >0 rising edges reset the running maximum. Defaults to `0.0`.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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 public var previousOutputValue: Double = 0.0
/// - Parameters: /// - Parameters:
@@ -158,17 +158,8 @@ public enum RunningMax {
add: any ValidGeneratorInput = 0.0 add: any ValidGeneratorInput = 0.0
) { ) {
super.init(input: input, trig: trig, mul: mul, add: add) 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( public func _computeSamples(
graph: SynthGraph, graph: SynthGraph,
@@ -203,16 +194,7 @@ public enum RunningMax {
_prevTrig = prevTrig _prevTrig = prevTrig
_initialized = initialized _initialized = initialized
var fillValue: Double = extreme fillHeldResult(into: &_result, value: extreme, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
_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]
return _result return _result
} }
@@ -143,7 +143,7 @@ public enum RunningMin {
/// - trig: Reset trigger. ≤0 → >0 rising edges reset the running minimum. Defaults to `0.0`. /// - trig: Reset trigger. ≤0 → >0 rising edges reset the running minimum. Defaults to `0.0`.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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 public var previousOutputValue: Double = 0.0
/// - Parameters: /// - Parameters:
@@ -158,17 +158,8 @@ public enum RunningMin {
add: any ValidGeneratorInput = 0.0 add: any ValidGeneratorInput = 0.0
) { ) {
super.init(input: input, trig: trig, mul: mul, add: add) 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( public func _computeSamples(
graph: SynthGraph, graph: SynthGraph,
@@ -203,16 +194,7 @@ public enum RunningMin {
_prevTrig = prevTrig _prevTrig = prevTrig
_initialized = initialized _initialized = initialized
var fillValue: Double = extreme fillHeldResult(into: &_result, value: extreme, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
_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]
return _result return _result
} }
@@ -132,7 +132,7 @@ public enum Slope {
/// - input: Signal to differentiate. /// - input: Signal to differentiate.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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 public var previousOutputValue: Double = 0.0
/// - Parameters: /// - Parameters:
@@ -145,16 +145,8 @@ public enum Slope {
add: any ValidGeneratorInput = 0.0 add: any ValidGeneratorInput = 0.0
) { ) {
super.init(input: input, mul: mul, add: add) 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( public func _computeSamples(
graph: SynthGraph, graph: SynthGraph,
@@ -178,16 +170,7 @@ public enum Slope {
_prevSample = x _prevSample = x
} }
var fillValue: Double = slope fillHeldResult(into: &_result, value: slope, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
_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]
return _result return _result
} }
@@ -157,7 +157,7 @@ public enum ZeroCrossing {
/// - input: Signal to analyse. /// - input: Signal to analyse.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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 public var previousOutputValue: Double = 0.0
/// - Parameters: /// - Parameters:
@@ -170,17 +170,8 @@ public enum ZeroCrossing {
add: any ValidGeneratorInput = 0.0 add: any ValidGeneratorInput = 0.0
) { ) {
super.init(input: input, mul: mul, add: add) 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( public func _computeSamples(
graph: SynthGraph, graph: SynthGraph,
@@ -216,16 +207,7 @@ public enum ZeroCrossing {
_freq = freq _freq = freq
_initialized = initialized _initialized = initialized
var fillValue: Double = freq fillHeldResult(into: &_result, value: freq, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
_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]
return _result return _result
} }
@@ -166,7 +166,7 @@ public enum BufferRead {
/// - interpolation: Sample interpolation quality. Defaults to `.linear`. /// - interpolation: Sample interpolation quality. Defaults to `.linear`.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Offset added after multiplier. Defaults to `0.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 public var previousOutputValue: Double = 0.0
@@ -203,7 +203,6 @@ public enum BufferRead {
_mulAdd = MulAddSpec(mul: mul, add: add) _mulAdd = MulAddSpec(mul: mul, add: add)
_rampTargets = [Double](repeating: 0, count: buffer.channelCount) _rampTargets = [Double](repeating: 0, count: buffer.channelCount)
super.init(channels: buffer.channelCount) super.init(channels: buffer.channelCount)
_setupSubBlockBuffer(channels: buffer.channelCount)
} }
/// Replace the buffer being read. Pass `nil` to silence the reader. /// Replace the buffer being read. Pass `nil` to silence the reader.
@@ -226,14 +225,6 @@ public enum BufferRead {
_slot.swap(buffer, engine: engine) _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( public func _computeSamples(
graph: SynthGraph, graph: SynthGraph,
@@ -332,26 +332,10 @@ public enum PlayBuffer {
// Evaluate rate input — generator path reads a full per-sample buffer; // Evaluate rate input — generator path reads a full per-sample buffer;
// scalar path computes one constant value and skips array allocation. // scalar path computes one constant value and skips array allocation.
let rateSamples: [Double]? let (rateSamples, scalarRate) = resolveGeneratorOrScalar(_rateInput, isGenerator: _rateIsGenerator, graph: graph, count: count)
let scalarRate: Double
if _rateIsGenerator {
rateSamples = _rateInput.calculatedSamples(graph: graph, count: count).first
scalarRate = 0
} else {
rateSamples = nil
scalarRate = _rateInput.floatValue(graph: graph)
}
// Evaluate trigger input — same two-path pattern. // Evaluate trigger input — same two-path pattern.
let triggerSamples: [Double]? let (triggerSamples, scalarTrigger) = resolveGeneratorOrScalar(_triggerInput, isGenerator: _triggerIsGenerator, graph: graph, count: count)
let scalarTrigger: Double
if _triggerIsGenerator {
triggerSamples = _triggerInput.calculatedSamples(graph: graph, count: count).first
scalarTrigger = 0
} else {
triggerSamples = nil
scalarTrigger = _triggerInput.floatValue(graph: graph)
}
guard let buffer: LyrebirdBuffer = _slot.load(engine: graph.engine), buffer.isValid else { guard let buffer: LyrebirdBuffer = _slot.load(engine: graph.engine), buffer.isValid else {
for ch: Int in 0..<channelCount { for ch: Int in 0..<channelCount {
@@ -444,7 +428,7 @@ public enum PlayBuffer {
/// Defaults to `0.0` (no trigger). /// Defaults to `0.0` (no trigger).
/// - mul: Output multiplier applied after synthesis. Defaults to `1.0`. /// - mul: Output multiplier applied after synthesis. Defaults to `1.0`.
/// - add: Offset added after multiplier. Defaults to `0.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 public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 0.0 private var _rampTarget: Double = 0.0
@@ -490,19 +474,10 @@ public enum PlayBuffer {
startPos: startPos, rate: rate, trigger: trigger, startPos: startPos, rate: rate, trigger: trigger,
mul: mul, add: add mul: mul, add: add
) )
_setupSubBlockBuffer()
_registerAutoFreeIfNeeded(doneAction) _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( public func _computeSamples(
graph: SynthGraph, graph: SynthGraph,
@@ -538,7 +538,7 @@ public enum RecordBuffer {
/// `doneAction` and stops recording. Default `true`. /// `doneAction` and stops recording. Default `true`.
/// - doneAction: Behaviour when the write head reaches the end of the /// - doneAction: Behaviour when the write head reaches the end of the
/// buffer (`loop == false`). Default `.nothing`. /// 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 public var previousOutputValue: Double = 0.0
@@ -566,20 +566,11 @@ public enum RecordBuffer {
+ "For multi-channel recording use RecordBuffer.Audio." + "For multi-channel recording use RecordBuffer.Audio."
) )
super.init(input: input, buffer: buffer, loop: loop, doneAction: doneAction) super.init(input: input, buffer: buffer, loop: loop, doneAction: doneAction)
_setupSubBlockBuffer()
_registerAutoFreeIfNeeded(doneAction) _registerAutoFreeIfNeeded(doneAction)
_registerAsRootIfBuilding() _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( public func _computeSamples(
graph: SynthGraph, 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``. /// 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 /// - channels: Only available on the `Int`-index overload. Number of consecutive buses
/// to read. Defaults to `1`. Fixed at init — no RT allocation. /// 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. /// Per-channel ramp state. Updated by `_computeSamples` after each block.
private var _previousOutputValues: [Double] private var _previousOutputValues: [Double]
@@ -187,7 +187,6 @@ public enum In {
let ch: Int = _resolvedChannelCount(bus) let ch: Int = _resolvedChannelCount(bus)
_previousOutputValues = [Double](repeating: 0.0, count: ch) _previousOutputValues = [Double](repeating: 0.0, count: ch)
super.init(bus: bus.index, channels: ch) super.init(bus: bus.index, channels: ch)
_setupSubBlockBuffer(channels: ch)
} }
/// Reads from a raw bus index with an explicit channel count. /// 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) _previousOutputValues = [Double](repeating: 0.0, count: channels)
super.init(bus: bus, channels: channels) super.init(bus: bus, channels: channels)
_setupSubBlockBuffer(channels: channels)
} }
public func floatValue(graph: SynthGraph) -> Double { public func floatValue(graph: SynthGraph) -> Double {
@@ -209,15 +207,6 @@ public enum In {
return Double(graph.engine.controlBuses[bus]) 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 /// Produces a linearly-interpolated block for each channel, ramping from the previous
/// block's end value to the current control bus value. /// 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. /// to `channelCount`). An ``AudioBus`` traps; use ``Out/Audio`` instead.
/// - source: Signal to write. The last sample of each channel block is accumulated into /// - 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. /// 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 public var previousOutputValue: Double = 0.0
/// Number of channels to write. Governs `_result` row count. /// Number of channels to write. Governs `_result` row count.
@@ -159,18 +159,9 @@ public enum Out {
let ch: Int = _resolvedChannelCount(bus) let ch: Int = _resolvedChannelCount(bus)
self._channels = ch self._channels = ch
super.init(bus: bus.index, source: source, maxChannels: bus.channelCount, channels: ch) super.init(bus: bus.index, source: source, maxChannels: bus.channelCount, channels: ch)
_setupSubBlockBuffer(channels: ch)
_registerAsRootIfBuilding() _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( public func _computeSamples(
graph: SynthGraph, graph: SynthGraph,
@@ -169,9 +169,9 @@ public enum ReplaceOut {
/// ``ControlBus`` (clamped to `channelCount`). An ``AudioBus`` traps; use ``ReplaceOut/Audio``. /// ``ControlBus`` (clamped to `channelCount`). An ``AudioBus`` traps; use ``ReplaceOut/Audio``.
/// - source: Signal to write. The last sample of each channel block is /// - source: Signal to write. The last sample of each channel block is
/// written to the corresponding control bus. /// 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 public var previousOutputValue: Double = 0.0
/// Number of channels to write. Governs `_result` row count. /// Number of channels to write. Governs `_result` row count.
@@ -199,18 +199,9 @@ public enum ReplaceOut {
let ch: Int = _resolvedChannelCount(bus) let ch: Int = _resolvedChannelCount(bus)
self._channels = ch self._channels = ch
super.init(bus: bus.index, source: source, maxChannels: bus.channelCount, channels: ch) super.init(bus: bus.index, source: source, maxChannels: bus.channelCount, channels: ch)
_setupSubBlockBuffer(channels: ch)
_registerAsRootIfBuilding() _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( public func _computeSamples(
graph: SynthGraph, graph: SynthGraph,
@@ -102,4 +102,61 @@ public class ChaoticBase: GeneratorBase {
_h2 = iterate() _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. /// Snapshot the per-block parameters into the fields `iterate()` reads.
@inline(__always) override func readParams(graph: SynthGraph) {
func readParams(graph: SynthGraph) {
_a = aInput.floatValue(graph: graph) _a = aInput.floatValue(graph: graph)
_b = bInput.floatValue(graph: graph) _b = bInput.floatValue(graph: graph)
} }
@@ -100,20 +99,7 @@ public enum CuspStepped {
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } return renderAudioBlock(graph: graph, count: count)
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
} }
} }
@@ -130,10 +116,7 @@ public enum CuspStepped {
/// - interpolation: Bridging between iterations. Defaults to `.none`. /// - interpolation: Bridging between iterations. Defaults to `.none`.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue } public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
@@ -156,30 +139,12 @@ public enum CuspStepped {
) { ) {
super.init(freq: freq, a: a, b: b, xi: xi, super.init(freq: freq, a: a, b: b, xi: xi,
interpolation: interpolation, mul: mul, add: add) 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]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } return renderControlBlock(graph: graph, count: count)
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
} }
} }
} }
@@ -70,8 +70,7 @@ public enum FBSineStepped {
} }
/// Snapshot the per-block parameters into the fields `iterate()` reads. /// Snapshot the per-block parameters into the fields `iterate()` reads.
@inline(__always) override func readParams(graph: SynthGraph) {
func readParams(graph: SynthGraph) {
_im = imInput.floatValue(graph: graph) _im = imInput.floatValue(graph: graph)
_fb = fbInput.floatValue(graph: graph) _fb = fbInput.floatValue(graph: graph)
_a = aInput.floatValue(graph: graph) _a = aInput.floatValue(graph: graph)
@@ -125,20 +124,7 @@ public enum FBSineStepped {
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } return renderAudioBlock(graph: graph, count: count)
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
} }
} }
@@ -158,10 +144,7 @@ public enum FBSineStepped {
/// - interpolation: Bridging between iterations. Defaults to `.none`. /// - interpolation: Bridging between iterations. Defaults to `.none`.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue } 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, super.init(freq: freq, im: im, fb: fb, a: a, c: c, xi: xi, yi: yi,
interpolation: interpolation, mul: mul, add: add) 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]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } return renderControlBlock(graph: graph, count: count)
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
} }
} }
} }
@@ -83,19 +83,7 @@ public enum GbmanStepped {
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } return renderAudioBlock(graph: graph, count: count)
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
} }
} }
@@ -111,10 +99,7 @@ public enum GbmanStepped {
/// - interpolation: Bridging between iterations. Defaults to `.none`. /// - interpolation: Bridging between iterations. Defaults to `.none`.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue } public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
@@ -135,29 +120,12 @@ public enum GbmanStepped {
) { ) {
super.init(freq: freq, xi: xi, yi: yi, super.init(freq: freq, xi: xi, yi: yi,
interpolation: interpolation, mul: mul, add: add) 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]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } return renderControlBlock(graph: graph, count: count)
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
} }
} }
} }
@@ -58,8 +58,7 @@ public enum HenonStepped {
} }
/// Snapshot the per-block parameters into the fields `iterate()` reads. /// Snapshot the per-block parameters into the fields `iterate()` reads.
@inline(__always) override func readParams(graph: SynthGraph) {
func readParams(graph: SynthGraph) {
_a = aInput.floatValue(graph: graph) _a = aInput.floatValue(graph: graph)
_b = bInput.floatValue(graph: graph) _b = bInput.floatValue(graph: graph)
} }
@@ -105,20 +104,7 @@ public enum HenonStepped {
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } return renderAudioBlock(graph: graph, count: count)
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
} }
} }
@@ -136,10 +122,7 @@ public enum HenonStepped {
/// - interpolation: Bridging between iterations. Defaults to `.none`. /// - interpolation: Bridging between iterations. Defaults to `.none`.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue } 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, super.init(freq: freq, a: a, b: b, x0: x0, x1: x1,
interpolation: interpolation, mul: mul, add: add) 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]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } return renderControlBlock(graph: graph, count: count)
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
} }
} }
} }
@@ -71,8 +71,7 @@ public enum LatoocarfianStepped {
} }
/// Snapshot the per-block parameters into the fields `iterate()` reads. /// Snapshot the per-block parameters into the fields `iterate()` reads.
@inline(__always) override func readParams(graph: SynthGraph) {
func readParams(graph: SynthGraph) {
_a = aInput.floatValue(graph: graph) _a = aInput.floatValue(graph: graph)
_b = bInput.floatValue(graph: graph) _b = bInput.floatValue(graph: graph)
_c = cInput.floatValue(graph: graph) _c = cInput.floatValue(graph: graph)
@@ -126,20 +125,7 @@ public enum LatoocarfianStepped {
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } return renderAudioBlock(graph: graph, count: count)
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
} }
} }
@@ -159,10 +145,7 @@ public enum LatoocarfianStepped {
/// - interpolation: Bridging between iterations. Defaults to `.none`. /// - interpolation: Bridging between iterations. Defaults to `.none`.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue } 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, super.init(freq: freq, a: a, b: b, c: c, d: d, xi: xi, yi: yi,
interpolation: interpolation, mul: mul, add: add) 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]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } return renderControlBlock(graph: graph, count: count)
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
} }
} }
} }
@@ -61,8 +61,7 @@ public enum LinCongStepped {
} }
/// Snapshot the per-block parameters into the fields `iterate()` reads. /// Snapshot the per-block parameters into the fields `iterate()` reads.
@inline(__always) override func readParams(graph: SynthGraph) {
func readParams(graph: SynthGraph) {
_a = aInput.floatValue(graph: graph) _a = aInput.floatValue(graph: graph)
_c = cInput.floatValue(graph: graph) _c = cInput.floatValue(graph: graph)
_m = mInput.floatValue(graph: graph) _m = mInput.floatValue(graph: graph)
@@ -109,20 +108,7 @@ public enum LinCongStepped {
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } return renderAudioBlock(graph: graph, count: count)
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
} }
} }
@@ -140,10 +126,7 @@ public enum LinCongStepped {
/// - interpolation: Bridging between iterations. Defaults to `.none`. /// - interpolation: Bridging between iterations. Defaults to `.none`.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue } 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, super.init(freq: freq, a: a, c: c, m: m, xi: xi,
interpolation: interpolation, mul: mul, add: add) 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]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } return renderControlBlock(graph: graph, count: count)
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
} }
} }
} }
@@ -76,8 +76,7 @@ public enum LorenzLinear {
} }
/// Snapshot the per-block parameters into the fields `iterate()` reads. /// Snapshot the per-block parameters into the fields `iterate()` reads.
@inline(__always) override func readParams(graph: SynthGraph) {
func readParams(graph: SynthGraph) {
_s = sInput.floatValue(graph: graph) _s = sInput.floatValue(graph: graph)
_r = rInput.floatValue(graph: graph) _r = rInput.floatValue(graph: graph)
_b = bInput.floatValue(graph: graph) _b = bInput.floatValue(graph: graph)
@@ -134,20 +133,7 @@ public enum LorenzLinear {
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } return renderAudioBlock(graph: graph, count: count)
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
} }
} }
@@ -168,10 +154,7 @@ public enum LorenzLinear {
/// - interpolation: Bridging between iterations. Defaults to `.linear`. /// - interpolation: Bridging between iterations. Defaults to `.linear`.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue } 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, super.init(freq: freq, s: s, r: r, b: b, h: h, xi: xi, yi: yi, zi: zi,
interpolation: interpolation, mul: mul, add: add) 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]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } return renderControlBlock(graph: graph, count: count)
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
} }
} }
} }
@@ -59,8 +59,7 @@ public enum QuadStepped {
} }
/// Snapshot the per-block parameters into the fields `iterate()` reads. /// Snapshot the per-block parameters into the fields `iterate()` reads.
@inline(__always) override func readParams(graph: SynthGraph) {
func readParams(graph: SynthGraph) {
_a = aInput.floatValue(graph: graph) _a = aInput.floatValue(graph: graph)
_b = bInput.floatValue(graph: graph) _b = bInput.floatValue(graph: graph)
_c = cInput.floatValue(graph: graph) _c = cInput.floatValue(graph: graph)
@@ -107,20 +106,7 @@ public enum QuadStepped {
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } return renderAudioBlock(graph: graph, count: count)
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
} }
} }
@@ -138,10 +124,7 @@ public enum QuadStepped {
/// - interpolation: Bridging between iterations. Defaults to `.none`. /// - interpolation: Bridging between iterations. Defaults to `.none`.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue } 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, super.init(freq: freq, a: a, b: b, c: c, xi: xi,
interpolation: interpolation, mul: mul, add: add) 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]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } return renderControlBlock(graph: graph, count: count)
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 StandardStepped {
} }
/// Snapshot the per-block parameter into the field `iterate()` reads. /// Snapshot the per-block parameter into the field `iterate()` reads.
@inline(__always) override func readParams(graph: SynthGraph) {
func readParams(graph: SynthGraph) {
_k = kInput.floatValue(graph: graph) _k = kInput.floatValue(graph: graph)
} }
} }
@@ -99,20 +98,7 @@ public enum StandardStepped {
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } return renderAudioBlock(graph: graph, count: count)
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
} }
} }
@@ -129,10 +115,7 @@ public enum StandardStepped {
/// - interpolation: Bridging between iterations. Defaults to `.none`. /// - interpolation: Bridging between iterations. Defaults to `.none`.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue } public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
@@ -155,30 +138,12 @@ public enum StandardStepped {
) { ) {
super.init(freq: freq, k: k, xi: xi, yi: yi, super.init(freq: freq, k: k, xi: xi, yi: yi,
interpolation: interpolation, mul: mul, add: add) 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]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } return renderControlBlock(graph: graph, count: count)
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
} }
} }
} }
@@ -180,7 +180,13 @@ public final class DelayLine: GeneratorBase, AudioGenerator {
apPrev = out apPrev = out
dstP[i] = out dstP[i] = out
} else { } 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 dstP[i] = yn
} }
bufP[writePosLocal & maskLocal] = sampleOrZero(srcP, i, inputCount) bufP[writePosLocal & maskLocal] = sampleOrZero(srcP, i, inputCount)
@@ -270,9 +270,6 @@ public final class DelayLineFeedback: GeneratorBase, AudioGenerator {
let frac: Double = d - Double(intD) let frac: Double = d - Double(intD)
let yn: Double = bufP[(writePosLocal - intD) & maskLocal] let yn: Double = bufP[(writePosLocal - intD) & maskLocal]
let delayed: Double 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 { if frac > 0 {
let eta: Double = (1.0 - frac) / (1.0 + frac) let eta: Double = (1.0 - frac) / (1.0 + frac)
let ynm1: Double = bufP[(writePosLocal - intD - 1) & maskLocal] let ynm1: Double = bufP[(writePosLocal - intD - 1) & maskLocal]
@@ -280,6 +277,13 @@ public final class DelayLineFeedback: GeneratorBase, AudioGenerator {
apPrev = out apPrev = out
delayed = out delayed = out
} else { } 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 delayed = yn
} }
let x: Double = sampleOrZero(srcP, i, inputCount) let x: Double = sampleOrZero(srcP, i, inputCount)
@@ -125,7 +125,7 @@ public enum Demand {
/// ///
/// `floatValue(graph:)` returns `previousOutputValue` without advancing the sequence — /// `floatValue(graph:)` returns `previousOutputValue` without advancing the sequence —
/// use the full `calculatedSamples` path for demand evaluation. /// 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 public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 0.0 private var _rampTarget: Double = 0.0
@@ -136,18 +136,9 @@ public enum Demand {
demand: any DemandGenerator demand: any DemandGenerator
) { ) {
super.init(trig: trig, reset: reset, demand: demand) 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( public func _computeSamples(
graph: SynthGraph, graph: SynthGraph,
@@ -153,7 +153,7 @@ public enum AmplitudeFollower {
/// - input: Signal to track. /// - 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`. /// - 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`. /// - 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 public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 0.0 private var _rampTarget: Double = 0.0
@@ -167,17 +167,8 @@ public enum AmplitudeFollower {
releaseTime: any ValidGeneratorInput = 0.1 releaseTime: any ValidGeneratorInput = 0.1
) { ) {
super.init(in: input, attackTime: attackTime, releaseTime: releaseTime) 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( public func _computeSamples(
graph: SynthGraph, 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`. /// - 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`. /// - 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`. /// - 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 public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 1.0 // matches _prevGain initial value 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, super.init(in: input, threshold: threshold, ratio: ratio,
attack: attack, release: release, attack: attack, release: release,
kneeWidth: kneeWidth, makeupGain: makeupGain) 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( public func _computeSamples(
graph: SynthGraph, 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`. /// - 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`. /// - 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`. /// - 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 public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 1.0 // matches _prevGain initial value 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, super.init(in: input, threshold: threshold, ratio: ratio,
attack: attack, release: release, kneeWidth: kneeWidth) 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( public func _computeSamples(
graph: SynthGraph, graph: SynthGraph,
@@ -43,7 +43,7 @@ public enum ExponentialLine {
/// - doneAction: Action taken on completion. Defaults to `.nothing`. /// - doneAction: Action taken on completion. Defaults to `.nothing`.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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 start: Double
let end: Double let end: Double
let dur: Double let dur: Double
@@ -98,18 +98,10 @@ public enum ExponentialLine {
self._rampTarget = start self._rampTarget = start
self.previousOutputValue = start self.previousOutputValue = start
super.init() super.init()
_setupSubBlockBuffer()
_registerAutoFreeIfNeeded(doneAction) _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( public func _computeSamples(
graph: SynthGraph, graph: SynthGraph,
@@ -37,7 +37,7 @@ public enum Line {
/// - doneAction: Action taken on completion. Defaults to `.nothing`. /// - doneAction: Action taken on completion. Defaults to `.nothing`.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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 start: Double
let end: Double let end: Double
let dur: Double let dur: Double
@@ -80,18 +80,10 @@ public enum Line {
self._rampTarget = start self._rampTarget = start
self.previousOutputValue = start self.previousOutputValue = start
super.init() super.init()
_setupSubBlockBuffer()
_registerAutoFreeIfNeeded(doneAction) _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( public func _computeSamples(
graph: SynthGraph, graph: SynthGraph,
@@ -54,7 +54,7 @@ public enum RateRamp {
/// Defaults to `0.0`. /// Defaults to `0.0`.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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 trigInput: any ValidGeneratorInput
let rateInput: any ValidGeneratorInput let rateInput: any ValidGeneratorInput
let startInput: any ValidGeneratorInput let startInput: any ValidGeneratorInput
@@ -95,18 +95,9 @@ public enum RateRamp {
self._rateIsGenerator = resolvedRate is any Generator self._rateIsGenerator = resolvedRate is any Generator
self._mulAdd = MulAddSpec(mul: mul, add: add) self._mulAdd = MulAddSpec(mul: mul, add: add)
super.init() 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( public func _computeSamples(
graph: SynthGraph, graph: SynthGraph,
@@ -234,8 +234,14 @@ public final class AllpassFilter: GeneratorBase, AudioGenerator {
xD = xOut xD = xOut
yD = yOut yD = yOut
} else { } else {
apPrevIn = 0 // frac == 0: both reads are exactly the integer-delayed
apPrevOut = 0 // 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 xD = xn
yD = yn yD = yn
} }
@@ -213,7 +213,13 @@ public final class CombFilter: GeneratorBase, AudioGenerator {
apPrev = out apPrev = out
delayed = out delayed = out
} else { } 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 delayed = yn
} }
let y: Double = sampleOrZero(srcP, i, n) + g * delayed let y: Double = sampleOrZero(srcP, i, n) + g * delayed
@@ -123,15 +123,15 @@ public enum Decay {
/// Control-rate leaky integrator. /// Control-rate leaky integrator.
/// ///
/// Advances integrator state once per audio block. The sub-block loop is bypassed via /// Advances integrator state once per audio block. The sub-block loop is bypassed by conforming to
/// a `calculatedSamples` override (same pattern as `SVF.Control`). /// `BlockRateControlGenerator` (same pattern as `SVF.Control`).
/// ///
/// - Parameters: /// - Parameters:
/// - input: Excitation signal (typically impulses). Each non-zero block value adds to the integrator state. /// - 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. /// - decayTime: Time in seconds for the output to decay by 60 dB. `0` = no memory.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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 public var previousOutputValue: Double = 0.0
@@ -147,13 +147,9 @@ public enum Decay {
add: any ValidGeneratorInput = 0.0 add: any ValidGeneratorInput = 0.0
) { ) {
super.init(input: input, decayTime: decayTime, mul: mul, add: add) 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]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
@@ -162,13 +158,7 @@ public enum Decay {
let x: Double = inputSource.floatValue(graph: graph) let x: Double = inputSource.floatValue(graph: graph)
let y: Double = x + b1 * y1 let y: Double = x + b1 * y1
y1 = denormalsToZero(y) y1 = denormalsToZero(y)
var fillValue: Double = y fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
_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]
return _result return _result
} }
} }
@@ -143,8 +143,8 @@ public enum Decay2 {
/// Control-rate two-integrator decay with rounded attack. /// Control-rate two-integrator decay with rounded attack.
/// ///
/// Advances both integrator states once per audio block. The sub-block loop is bypassed via /// Advances both integrator states once per audio block. The sub-block loop is bypassed by conforming to
/// a `calculatedSamples` override (same pattern as `SVF.Control`). /// `BlockRateControlGenerator` (same pattern as `SVF.Control`).
/// ///
/// - Parameters: /// - Parameters:
/// - input: Excitation signal (typically impulses). /// - 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. /// - decayTime: 60 dB decay time of the main decay integrator in seconds. `0` = no decay memory.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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 public var previousOutputValue: Double = 0.0
@@ -170,13 +170,9 @@ public enum Decay2 {
add: any ValidGeneratorInput = 0.0 add: any ValidGeneratorInput = 0.0
) { ) {
super.init(input: input, attackTime: attackTime, decayTime: decayTime, mul: mul, add: add) 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]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
@@ -189,13 +185,7 @@ public enum Decay2 {
yA1 = denormalsToZero(newYA) yA1 = denormalsToZero(newYA)
yD1 = denormalsToZero(newYD) yD1 = denormalsToZero(newYD)
let y: Double = newYD - newYA let y: Double = newYD - newYA
var fillValue: Double = y fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
_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]
return _result return _result
} }
} }
@@ -197,8 +197,8 @@ public enum Formlet {
/// Control-rate FOF-like resonant filter. /// Control-rate FOF-like resonant filter.
/// ///
/// Advances both resonators once per audio block at the control rate /// Advances both resonators once per audio block at the control rate
/// (`sampleRate / blockSize`); the sub-block loop is bypassed via a /// (`sampleRate / blockSize`); the sub-block loop is bypassed by conforming to
/// `calculatedSamples` override (same pattern as `Lag.Control`). /// `BlockRateControlGenerator` (same pattern as `Lag.Control`).
/// ///
/// - Parameters: /// - Parameters:
/// - input: Signal to excite the resonators. /// - 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). /// - decayTime: Fall time in seconds (60 dB time of the long resonator).
/// - mul: Output multiplier applied after synthesis. Defaults to `1.0`. /// - mul: Output multiplier applied after synthesis. Defaults to `1.0`.
/// - add: Offset added after multiplier. Defaults to `0.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 public var previousOutputValue: Double = 0.0
@@ -228,13 +228,8 @@ public enum Formlet {
) { ) {
super.init(input: input, freq: freq, attackTime: attackTime, super.init(input: input, freq: freq, attackTime: attackTime,
decayTime: decayTime, mul: mul, add: add) 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]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
@@ -256,13 +251,7 @@ public enum Formlet {
yAttack2 = denormalsToZero(yAttack1) yAttack2 = denormalsToZero(yAttack1)
yAttack1 = denormalsToZero(yAttack) yAttack1 = denormalsToZero(yAttack)
var fillValue: Double = yDecay - yAttack fillHeldResult(into: &_result, value: yDecay - yAttack, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
_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]
return _result return _result
} }
} }
@@ -146,15 +146,7 @@ public enum Hilbert {
let (b0, b1, b2, b3): (Double, Double, Double, Double) = Hilbert.hilbertCoeffB let (b0, b1, b2, b3): (Double, Double, Double, Double) = Hilbert.hilbertCoeffB
// Fetch input block (audio-rate or scalar). // Fetch input block (audio-rate or scalar).
let inputSamples: [Double]? let (inputSamples, scalarInput) = resolveGeneratorOrScalar(_inputSource, isGenerator: _inputIsGenerator, graph: graph, count: count)
let scalarInput: Double
if _inputIsGenerator {
inputSamples = _inputSource.calculatedSamples(graph: graph, count: count).first
scalarInput = 0
} else {
inputSamples = nil
scalarInput = _inputSource.floatValue(graph: graph)
}
for i: Int in 0..<count { for i: Int in 0..<count {
let x: Double let x: Double
+4 -16
View File
@@ -128,8 +128,8 @@ public enum Lag {
/// Control-rate one-pole exponential smoother. /// Control-rate one-pole exponential smoother.
/// ///
/// Advances filter state once per audio block. The sub-block loop is bypassed via /// Advances filter state once per audio block. The sub-block loop is bypassed by conforming to
/// a `calculatedSamples` override (same pattern as `SVF.Control`). /// `BlockRateControlGenerator` (same pattern as `SVF.Control`).
/// ///
/// The coefficient is computed at the control rate (`sampleRate / blockSize`); `time` /// The coefficient is computed at the control rate (`sampleRate / blockSize`); `time`
/// stays in seconds and the filter converges in `time` wall-clock seconds regardless /// 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). /// - time: 60 dB lag time in seconds. `0` = transparent (no smoothing).
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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 public var previousOutputValue: Double = 0.0
@@ -156,12 +156,6 @@ public enum Lag {
add: any ValidGeneratorInput = 0.0 add: any ValidGeneratorInput = 0.0
) { ) {
super.init(input: input, time: time, mul: mul, add: add) 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]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
@@ -171,13 +165,7 @@ public enum Lag {
let x: Double = inputSource.floatValue(graph: graph) let x: Double = inputSource.floatValue(graph: graph)
let y: Double = b1 * y1 + (1.0 - b1) * x let y: Double = b1 * y1 + (1.0 - b1) * x
y1 = denormalsToZero(y) y1 = denormalsToZero(y)
var fillValue: Double = y fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
_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]
return _result return _result
} }
} }
+4 -14
View File
@@ -128,15 +128,15 @@ public enum Lag2 {
/// Control-rate two-cascaded one-pole smoother. /// Control-rate two-cascaded one-pole smoother.
/// ///
/// Advances both filter stages once per audio block. The sub-block loop is bypassed via /// Advances both filter stages once per audio block. The sub-block loop is bypassed by conforming to
/// a `calculatedSamples` override (same pattern as `SVF.Control`). /// `BlockRateControlGenerator` (same pattern as `SVF.Control`).
/// ///
/// - Parameters: /// - Parameters:
/// - input: Signal to smooth. /// - input: Signal to smooth.
/// - time: 60 dB lag time in seconds per stage. `0` = transparent. /// - time: 60 dB lag time in seconds per stage. `0` = transparent.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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 public var previousOutputValue: Double = 0.0
@@ -152,13 +152,9 @@ public enum Lag2 {
add: any ValidGeneratorInput = 0.0 add: any ValidGeneratorInput = 0.0
) { ) {
super.init(input: input, time: time, mul: mul, add: add) 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]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
@@ -170,13 +166,7 @@ public enum Lag2 {
let y: Double = b1 * y1b + oneMinusB1 * s1 let y: Double = b1 * y1b + oneMinusB1 * s1
y1a = denormalsToZero(s1) y1a = denormalsToZero(s1)
y1b = denormalsToZero(y) y1b = denormalsToZero(y)
var fillValue: Double = y fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
_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]
return _result return _result
} }
} }
@@ -141,8 +141,8 @@ public enum Lag2UpDown {
/// Control-rate two-cascaded asymmetric one-pole smoother. /// Control-rate two-cascaded asymmetric one-pole smoother.
/// ///
/// Advances both filter stages once per audio block. The sub-block loop is bypassed via /// Advances both filter stages once per audio block. The sub-block loop is bypassed by conforming to
/// a `calculatedSamples` override (same pattern as `SVF.Control`). /// `BlockRateControlGenerator` (same pattern as `SVF.Control`).
/// ///
/// - Parameters: /// - Parameters:
/// - input: Signal to smooth. /// - 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. /// - lagDown: 60 dB lag time in seconds for falling transitions per stage. `0` = instant.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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 public var previousOutputValue: Double = 0.0
@@ -168,13 +168,9 @@ public enum Lag2UpDown {
add: any ValidGeneratorInput = 0.0 add: any ValidGeneratorInput = 0.0
) { ) {
super.init(input: input, lagUp: lagUp, lagDown: lagDown, mul: mul, add: add) 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]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
@@ -188,13 +184,7 @@ public enum Lag2UpDown {
let y: Double = sel2 * y1b + (1.0 - sel2) * s1 let y: Double = sel2 * y1b + (1.0 - sel2) * s1
y1a = denormalsToZero(s1) y1a = denormalsToZero(s1)
y1b = denormalsToZero(y) y1b = denormalsToZero(y)
var fillValue: Double = y fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
_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]
return _result return _result
} }
} }
@@ -143,8 +143,8 @@ public enum LagUpDown {
/// Control-rate asymmetric one-pole smoother. /// Control-rate asymmetric one-pole smoother.
/// ///
/// Advances filter state once per audio block. The sub-block loop is bypassed via /// Advances filter state once per audio block. The sub-block loop is bypassed by conforming to
/// a `calculatedSamples` override (same pattern as `SVF.Control`). /// `BlockRateControlGenerator` (same pattern as `SVF.Control`).
/// ///
/// - Parameters: /// - Parameters:
/// - input: Signal to smooth. /// - input: Signal to smooth.
@@ -152,7 +152,7 @@ public enum LagUpDown {
/// - lagDown: 60 dB lag time in seconds for falling transitions. `0` = instant. /// - lagDown: 60 dB lag time in seconds for falling transitions. `0` = instant.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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 public var previousOutputValue: Double = 0.0
@@ -170,13 +170,9 @@ public enum LagUpDown {
add: any ValidGeneratorInput = 0.0 add: any ValidGeneratorInput = 0.0
) { ) {
super.init(input: input, lagUp: lagUp, lagDown: lagDown, mul: mul, add: add) 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]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
@@ -187,13 +183,7 @@ public enum LagUpDown {
let b1: Double = x >= y1 ? b1Up : b1Down let b1: Double = x >= y1 ? b1Up : b1Down
let y: Double = b1 * y1 + (1.0 - b1) * x let y: Double = b1 * y1 + (1.0 - b1) * x
y1 = denormalsToZero(y) y1 = denormalsToZero(y)
var fillValue: Double = y fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
_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]
return _result return _result
} }
} }
@@ -139,15 +139,15 @@ public enum LeakDC {
/// Control-rate one-pole DC blocker. /// Control-rate one-pole DC blocker.
/// ///
/// Advances filter state once per audio block. The sub-block loop is bypassed via /// Advances filter state once per audio block. The sub-block loop is bypassed by conforming to
/// a `calculatedSamples` override (same pattern as `SVF.Control`). /// `BlockRateControlGenerator` (same pattern as `SVF.Control`).
/// ///
/// - Parameters: /// - Parameters:
/// - input: Signal from which to remove DC bias. /// - 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). /// - coef: Pole coefficient in `[0, 1)`. Higher values lower the corner frequency. Defaults to `leakDCDefaultControlCoef` (0.9).
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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 public var previousOutputValue: Double = 0.0
@@ -163,13 +163,9 @@ public enum LeakDC {
add: any ValidGeneratorInput = 0.0 add: any ValidGeneratorInput = 0.0
) { ) {
super.init(input: input, coef: coef, mul: mul, add: add) 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]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
@@ -178,13 +174,7 @@ public enum LeakDC {
let y: Double = x - x1 + c * y1 let y: Double = x - x1 + c * y1
x1 = x x1 = x
y1 = denormalsToZero(y) y1 = denormalsToZero(y)
var fillValue: Double = y fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
_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]
return _result return _result
} }
} }
@@ -261,15 +261,7 @@ public enum MuTronIII {
// Read input — generator block or scalar fast path (avoids RT allocation in // Read input — generator block or scalar fast path (avoids RT allocation in
// `Double.calculatedSamples`). // `Double.calculatedSamples`).
let inputSamples: [Double]? let (inputSamples, scalarInput) = resolveGeneratorOrScalar(_inputSource, isGenerator: _inputIsGenerator, graph: graph, count: count)
let scalarInput: Double
if _inputIsGenerator {
inputSamples = _inputSource.calculatedSamples(graph: graph, count: count).first
scalarInput = 0.0
} else {
inputSamples = nil
scalarInput = _inputSource.floatValue(graph: graph)
}
for i: Int in 0..<count { for i: Int in 0..<count {
let x: Double let x: Double
@@ -326,7 +318,7 @@ public enum MuTronIII {
/// Control-rate Mu-Tron III auto-wah — block-rate envelope and filter evaluation. /// 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. /// 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 /// must advance exactly once per audio block, processing each input sample exactly
/// once. /// once.
/// ///
@@ -342,7 +334,7 @@ public enum MuTronIII {
/// - releaseTime: Envelope release time in seconds. Defaults to `0.15`. /// - releaseTime: Envelope release time in seconds. Defaults to `0.15`.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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 public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 0.0 private var _rampTarget: Double = 0.0
@@ -379,14 +371,8 @@ public enum MuTronIII {
attackTime: attackTime, releaseTime: releaseTime, attackTime: attackTime, releaseTime: releaseTime,
mul: mul, add: add 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]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
@@ -439,15 +425,7 @@ public enum MuTronIII {
// Bypass guarantees `_computeSamples` runs once per audio block, so `count` equals // Bypass guarantees `_computeSamples` runs once per audio block, so `count` equals
// the full audio block size for input generators. // the full audio block size for input generators.
let inputSamples: [Double]? let (inputSamples, scalarInput) = resolveGeneratorOrScalar(_inputSource, isGenerator: _inputIsGenerator, graph: graph, count: count)
let scalarInput: Double
if _inputIsGenerator {
inputSamples = _inputSource.calculatedSamples(graph: graph, count: count).first
scalarInput = 0.0
} else {
inputSamples = nil
scalarInput = _inputSource.floatValue(graph: graph)
}
// Process all `count` input samples to advance state fully. // Process all `count` input samples to advance state fully.
var lastOut: Double = previousOutputValue 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. /// 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 /// 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`). /// (same pattern as `AmplitudeFollower.Control`).
/// ///
/// - Parameters: /// - Parameters:
@@ -192,7 +192,7 @@ public enum SVF {
/// divide-by-zero. Defaults to `svfButterworthQ`. /// divide-by-zero. Defaults to `svfButterworthQ`.
/// - mul: Output multiplier applied to all four channels. Defaults to `1.0`. /// - mul: Output multiplier applied to all four channels. Defaults to `1.0`.
/// - add: Output offset applied to all four channels. Defaults to `0.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 public var previousOutputValue: Double = 0.0
@@ -216,24 +216,11 @@ public enum SVF {
add: any ValidGeneratorInput = 0.0 add: any ValidGeneratorInput = 0.0
) { ) {
super.init(input: input, freq: freq, q: q, mul: mul, add: add) super.init(input: input, freq: freq, q: q, mul: mul, add: add)
// _setupSubBlockBuffer retained defensively; calculatedSamples bypass prevents // No _setupSubBlockBuffer(): BlockRateControlGenerator conformance bypasses the
// sub-block engagement in practice. // sub-block loop, so _subBlockBuffer is never read.
_setupSubBlockBuffer(channels: svfChannelCount)
} }
// 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( public func _computeSamples(
graph: SynthGraph, 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. /// 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 /// 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 /// (`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`). /// 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`. /// - dn: Maximum falling slope in units per second. Defaults to `1.0`.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.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 public var previousOutputValue: Double = 0.0
@@ -186,16 +186,8 @@ public enum Slew {
add: any ValidGeneratorInput = 0.0 add: any ValidGeneratorInput = 0.0
) { ) {
super.init(input: input, up: up, dn: dn, mul: mul, add: add) 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( public func _computeSamples(
graph: SynthGraph, graph: SynthGraph,
@@ -222,14 +214,7 @@ public enum Slew {
} }
} }
var fillValue: Double = _state fillHeldResult(into: &_result, value: _state, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
_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]
return _result return _result
} }
} }
@@ -269,7 +269,7 @@ public enum Gendy1 {
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`. /// - add: Output offset. Defaults to `0.0`.
/// - seed: Optional PRNG seed for deterministic output. `nil` uses a time-based seed. /// - 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 public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 0.0 private var _rampTarget: Double = 0.0
@@ -313,14 +313,9 @@ public enum Gendy1 {
seed: seed, seed: seed,
seedMixConstant: 0xFEDC_BA98_1357_2468 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]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
@@ -273,7 +273,7 @@ public enum Gendy2 {
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`. /// - add: Output offset. Defaults to `0.0`.
/// - seed: Optional PRNG seed for deterministic output. `nil` uses a time-based seed. /// - 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 public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 0.0 private var _rampTarget: Double = 0.0
@@ -317,14 +317,9 @@ public enum Gendy2 {
seed: seed, seed: seed,
seedMixConstant: 0xABCD_EF01_2468_1357 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]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
@@ -222,7 +222,7 @@ public enum Gendy3 {
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`. /// - add: Output offset. Defaults to `0.0`.
/// - seed: Optional PRNG seed for deterministic output. `nil` uses a time-based seed. /// - 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 public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 0.0 private var _rampTarget: Double = 0.0
@@ -256,14 +256,9 @@ public enum Gendy3 {
seed: seed, seed: seed,
seedMixConstant: 0x0123_4567_FEDC_BA98 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]] { public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count) _checkCount(count)
@@ -178,59 +178,19 @@ public enum GatedKarplusStrong {
let doublingOffset: Int = delayLineCount * 2 let doublingOffset: Int = delayLineCount * 2
// Read exciter block unconditionally so upstream generator always advances state. // Read exciter block unconditionally so upstream generator always advances state.
let exciterSamples: [Double]? let (exciterSamples, scalarExciter) = resolveGeneratorOrScalar(_exciterSource, isGenerator: _exciterIsGenerator, graph: graph, count: count)
let scalarExciter: Double
if _exciterIsGenerator {
exciterSamples = _exciterSource.calculatedSamples(graph: graph, count: count).first
scalarExciter = 0
} else {
exciterSamples = nil
scalarExciter = _exciterSource.floatValue(graph: graph)
}
// Read gate block. // Read gate block.
let gateSamples: [Double]? let (gateSamples, scalarGate) = resolveGeneratorOrScalar(_gateSource, isGenerator: _gateIsGenerator, graph: graph, count: count)
let scalarGate: Double
if _gateIsGenerator {
gateSamples = _gateSource.calculatedSamples(graph: graph, count: count).first
scalarGate = 0
} else {
gateSamples = nil
scalarGate = _gateSource.floatValue(graph: graph)
}
// Read freq block. // Read freq block.
let freqSamples: [Double]? let (freqSamples, scalarFreq) = resolveGeneratorOrScalar(_freqSource, isGenerator: _freqIsGenerator, graph: graph, count: count)
let scalarFreq: Double
if _freqIsGenerator {
freqSamples = _freqSource.calculatedSamples(graph: graph, count: count).first
scalarFreq = 0
} else {
freqSamples = nil
scalarFreq = _freqSource.floatValue(graph: graph)
}
// Read feedback block. // Read feedback block.
let feedbackSamples: [Double]? let (feedbackSamples, scalarFeedback) = resolveGeneratorOrScalar(_feedbackSource, isGenerator: _feedbackIsGenerator, graph: graph, count: count)
let scalarFeedback: Double
if _feedbackIsGenerator {
feedbackSamples = _feedbackSource.calculatedSamples(graph: graph, count: count).first
scalarFeedback = 0
} else {
feedbackSamples = nil
scalarFeedback = _feedbackSource.floatValue(graph: graph)
}
// Read coef block. // Read coef block.
let coefSamples: [Double]? let (coefSamples, scalarCoef) = resolveGeneratorOrScalar(_coefSource, isGenerator: _coefIsGenerator, graph: graph, count: count)
let scalarCoef: Double
if _coefIsGenerator {
coefSamples = _coefSource.calculatedSamples(graph: graph, count: count).first
scalarCoef = 0
} else {
coefSamples = nil
scalarCoef = _coefSource.floatValue(graph: graph)
}
// Per-sample loop. // Per-sample loop.
for i: Int in 0..<count { for i: Int in 0..<count {
@@ -180,59 +180,19 @@ public enum KarplusStrong {
let doublingOffset: Int = delayLineCount * 2 let doublingOffset: Int = delayLineCount * 2
// Read exciter block (unconditionally so upstream generator always advances state). // Read exciter block (unconditionally so upstream generator always advances state).
let exciterSamples: [Double]? let (exciterSamples, scalarExciter) = resolveGeneratorOrScalar(_exciterSource, isGenerator: _exciterIsGenerator, graph: graph, count: count)
let scalarExciter: Double
if _exciterIsGenerator {
exciterSamples = _exciterSource.calculatedSamples(graph: graph, count: count).first
scalarExciter = 0
} else {
exciterSamples = nil
scalarExciter = _exciterSource.floatValue(graph: graph)
}
// Read trigger block. // Read trigger block.
let triggerSamples: [Double]? let (triggerSamples, scalarTrigger) = resolveGeneratorOrScalar(_triggerSource, isGenerator: _triggerIsGenerator, graph: graph, count: count)
let scalarTrigger: Double
if _triggerIsGenerator {
triggerSamples = _triggerSource.calculatedSamples(graph: graph, count: count).first
scalarTrigger = 0
} else {
triggerSamples = nil
scalarTrigger = _triggerSource.floatValue(graph: graph)
}
// Read freq block. // Read freq block.
let freqSamples: [Double]? let (freqSamples, scalarFreq) = resolveGeneratorOrScalar(_freqSource, isGenerator: _freqIsGenerator, graph: graph, count: count)
let scalarFreq: Double
if _freqIsGenerator {
freqSamples = _freqSource.calculatedSamples(graph: graph, count: count).first
scalarFreq = 0
} else {
freqSamples = nil
scalarFreq = _freqSource.floatValue(graph: graph)
}
// Read feedback block. // Read feedback block.
let feedbackSamples: [Double]? let (feedbackSamples, scalarFeedback) = resolveGeneratorOrScalar(_feedbackSource, isGenerator: _feedbackIsGenerator, graph: graph, count: count)
let scalarFeedback: Double
if _feedbackIsGenerator {
feedbackSamples = _feedbackSource.calculatedSamples(graph: graph, count: count).first
scalarFeedback = 0
} else {
feedbackSamples = nil
scalarFeedback = _feedbackSource.floatValue(graph: graph)
}
// Read coef block. // Read coef block.
let coefSamples: [Double]? let (coefSamples, scalarCoef) = resolveGeneratorOrScalar(_coefSource, isGenerator: _coefIsGenerator, graph: graph, count: count)
let scalarCoef: Double
if _coefIsGenerator {
coefSamples = _coefSource.calculatedSamples(graph: graph, count: count).first
scalarCoef = 0
} else {
coefSamples = nil
scalarCoef = _coefSource.floatValue(graph: graph)
}
// Per-sample loop. // Per-sample loop.
for i: Int in 0..<count { for i: Int in 0..<count {
+2 -15
View File
@@ -10,20 +10,7 @@
/// ///
/// - Parameter signal: Input signal. /// - Parameter signal: Input signal.
public enum Abs { public enum Abs {
public class _Base: GeneratorBase { public class _Base: UnaryMathBase {}
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)
}
}
/// - Parameters: /// - Parameters:
/// - signal: Input signal. /// - signal: Input signal.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
@@ -71,7 +58,7 @@ public enum Abs {
) -> [[Double]] { ) -> [[Double]] {
_checkCount(count) _checkCount(count)
var target: Double = Swift.abs(inputSource.floatValue(graph: graph)) 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) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
return _result return _result
} }
+2 -15
View File
@@ -12,20 +12,7 @@ import Foundation
/// ///
/// - Parameter signal: Input signal. /// - Parameter signal: Input signal.
public enum Ceil { public enum Ceil {
public class _Base: GeneratorBase { public class _Base: UnaryMathBase {}
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)
}
}
/// - Parameters: /// - Parameters:
/// - signal: Input signal. /// - signal: Input signal.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
@@ -73,7 +60,7 @@ public enum Ceil {
) -> [[Double]] { ) -> [[Double]] {
_checkCount(count) _checkCount(count)
var target: Double = Foundation.ceil(inputSource.floatValue(graph: graph)) 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) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
return _result return _result
} }
+1 -4
View File
@@ -116,10 +116,7 @@ public enum Clip {
let lo: Double = loInput.floatValue(graph: graph) let lo: Double = loInput.floatValue(graph: graph)
let hi: Double = hiInput.floatValue(graph: graph) let hi: Double = hiInput.floatValue(graph: graph)
var target: Double = Swift.max(lo, Swift.min(hi, inputSource.floatValue(graph: graph))) var target: Double = Swift.max(lo, Swift.min(hi, inputSource.floatValue(graph: graph)))
if !_mulAdd.isIdentity { target = _mulAdd.applyScalar(target, graph: graph)
target = target * _mulAdd.mulInput.floatValue(graph: graph)
+ _mulAdd.addInput.floatValue(graph: graph)
}
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
return _result return _result
} }
+2 -15
View File
@@ -13,20 +13,7 @@ import Foundation
/// ///
/// - Parameter signal: Input signal in radians. /// - Parameter signal: Input signal in radians.
public enum Cos { public enum Cos {
public class _Base: GeneratorBase { public class _Base: UnaryMathBase {}
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)
}
}
/// - Parameters: /// - Parameters:
/// - signal: Input signal in radians. /// - signal: Input signal in radians.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
@@ -74,7 +61,7 @@ public enum Cos {
) -> [[Double]] { ) -> [[Double]] {
_checkCount(count) _checkCount(count)
var target: Double = Foundation.cos(inputSource.floatValue(graph: graph)) 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) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
return _result return _result
} }
+2 -16
View File
@@ -15,19 +15,7 @@
/// ///
/// - Parameter signal: Input value in decibels. /// - Parameter signal: Input value in decibels.
public enum DbAmp { public enum DbAmp {
public class _Base: GeneratorBase { public class _Base: UnaryMathBase {}
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)
}
}
/// - Parameters: /// - Parameters:
/// - signal: Input value in decibels. /// - signal: Input value in decibels.
@@ -52,9 +40,7 @@ public enum DbAmp {
) -> [[Double]] { ) -> [[Double]] {
_checkCount(count) _checkCount(count)
var target: Double = dbToAmp(inputSource.floatValue(graph: graph)) var target: Double = dbToAmp(inputSource.floatValue(graph: graph))
if !_mulAdd.isIdentity { target = _mulAdd.applyScalar(target, graph: graph)
target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph)
}
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
return _result return _result
} }
+2 -15
View File
@@ -12,20 +12,7 @@ import Foundation
/// ///
/// - Parameter signal: Input signal. /// - Parameter signal: Input signal.
public enum Exp { public enum Exp {
public class _Base: GeneratorBase { public class _Base: UnaryMathBase {}
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)
}
}
/// - Parameters: /// - Parameters:
/// - signal: Input signal. /// - signal: Input signal.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
@@ -73,7 +60,7 @@ public enum Exp {
) -> [[Double]] { ) -> [[Double]] {
_checkCount(count) _checkCount(count)
var target: Double = Foundation.exp(inputSource.floatValue(graph: graph)) 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) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
return _result return _result
} }
@@ -139,7 +139,7 @@ public enum ExpExp {
let logOutRatio: Double = Foundation.log(outHi / outLo) let logOutRatio: Double = Foundation.log(outHi / outLo)
let t: Double = Foundation.log(inputSource.floatValue(graph: graph) / inLo) / logInRange let t: Double = Foundation.log(inputSource.floatValue(graph: graph) / inLo) / logInRange
var target: Double = outLo * Foundation.exp(t * logOutRatio) 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) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
return _result return _result
} }
@@ -138,7 +138,7 @@ public enum ExpLin {
let logInRange: Double = Foundation.log(inHi / inLo) let logInRange: Double = Foundation.log(inHi / inLo)
let t: Double = Foundation.log(inputSource.floatValue(graph: graph) / inLo) / logInRange let t: Double = Foundation.log(inputSource.floatValue(graph: graph) / inLo) / logInRange
var target: Double = outLo + t * (outHi - outLo) 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) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
return _result return _result
} }
+2 -15
View File
@@ -12,20 +12,7 @@ import Foundation
/// ///
/// - Parameter signal: Input signal. /// - Parameter signal: Input signal.
public enum Floor { public enum Floor {
public class _Base: GeneratorBase { public class _Base: UnaryMathBase {}
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)
}
}
/// - Parameters: /// - Parameters:
/// - signal: Input signal. /// - signal: Input signal.
/// - mul: Output multiplier. Defaults to `1.0`. /// - mul: Output multiplier. Defaults to `1.0`.
@@ -73,7 +60,7 @@ public enum Floor {
) -> [[Double]] { ) -> [[Double]] {
_checkCount(count) _checkCount(count)
var target: Double = Foundation.floor(inputSource.floatValue(graph: graph)) 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) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
return _result return _result
} }
+1 -4
View File
@@ -128,10 +128,7 @@ public enum Fold {
let lo: Double = loInput.floatValue(graph: graph) let lo: Double = loInput.floatValue(graph: graph)
let hi: Double = hiInput.floatValue(graph: graph) let hi: Double = hiInput.floatValue(graph: graph)
var target: Double = Fold._fold(inputSource.floatValue(graph: graph), lo: lo, hi: hi) var target: Double = Fold._fold(inputSource.floatValue(graph: graph), lo: lo, hi: hi)
if !_mulAdd.isIdentity { target = _mulAdd.applyScalar(target, graph: graph)
target = target * _mulAdd.mulInput.floatValue(graph: graph)
+ _mulAdd.addInput.floatValue(graph: graph)
}
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count) fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
return _result return _result
} }

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