Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6da3615707 | |||
| a175c437de | |||
| 56726223f6 | |||
| 8e600f3a66 | |||
| 06bdcbbe92 | |||
| 162da89319 | |||
| 9f244b1939 | |||
| 24ea32e47c | |||
| c14efe998a | |||
| 63b630b317 | |||
| 3668739d20 | |||
| 6e7f4c0076 | |||
| f8878324fd |
@@ -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.
|
||||
|
||||
`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
|
||||
|
||||
@@ -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`
|
||||
- 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`
|
||||
- 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`
|
||||
- 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`
|
||||
@@ -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.
|
||||
- `floatValue` is provided by the `AudioGenerator` protocol extension (returns `calculatedSamples(...).first?.first ?? 0`). Do not redeclare in `AudioGenerator` conformers unless you need different scalar semantics (e.g. `ConstantGeneratorInput`). `ControlGenerator` conformers must provide their own `floatValue` returning the block target.
|
||||
- Buffer factories `makeResultBuffer(channels:)` / `makeSampleBuffer(_:)` (in `ResultBuffer.swift`) replace `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)` literals when a generator owns a separately-allocated scratch buffer.
|
||||
- Every `ControlGenerator.Control.init` calls `_setupSubBlockBuffer()` (or `_setupSubBlockBuffer(channels: N)`) after `super.init()`. Never call on the RT thread.
|
||||
- Every sub-blocking `ControlGenerator.Control.init` calls `_setupSubBlockBuffer()` (or `_setupSubBlockBuffer(channels: N)`) after `super.init()`. Never call on the RT thread. **Exception:** `BlockRateControlGenerator` conformers never sub-block and omit the call (see the bypass bullet below).
|
||||
- `Control._computeSamples` uses `count` (not `graph.engine.blockSize`) for phase/state advancement — `_computeSamples` may run N times per audio block in sub-block mode.
|
||||
- Generators with per-audio-block state (bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers) override `calculatedSamples` to bypass the sub-block loop. Canonical pattern: `Out.Control`. See `docs/protocols/writing-generators.md` §15 for the bypass list and decision rule.
|
||||
- Control generators with per-audio-block state (bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers, analysers) must advance once per audio block, bypassing the sub-block loop. Conform to `BlockRateControlGenerator` (marker protocol in `GeneratorCore/BlockRateControlGenerator.swift`) — its `calculatedSamples` default routes to the block-rate gateway and the conformer skips `_setupSubBlockBuffer()`. This replaced the old per-generator `calculatedSamples { _calculatedSamplesBlockRate(...) }` forwarder. A true sub-blocking Control must NOT conform. See `docs/protocols/writing-generators.md` §15 for the decision rule.
|
||||
- Multi-row generators (any with `_result.count > 1`) override `var outputChannelCount: Int { get }` to return the fixed channel count set at `init`. `GeneratorBase` defaults to `1`. Missing override silently mono-izes the generator under `+ - * /` operators. Channel count must be derivable from a `let` at init — never runtime-mutable. Detail + cases: `docs/stdlib/multichannel.md`.
|
||||
- `mul:` / `add:` parameters are channel-aware: mono input broadcasts; equal-N applies element-wise; mismatched multi-row precondition-traps. Same policy as `BinaryOpGenerator`. Detail: `docs/stdlib/multichannel.md`.
|
||||
|
||||
@@ -331,9 +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:
|
||||
|
||||
- `_checkCount(_:)` — `GeneratorBase` method; first line of every `_computeSamples`
|
||||
- `_calculatedSamplesBlockRate(graph:count:)` — `Generator` extension; canonical body of any `calculatedSamples` override that bypasses the `ControlGenerator` sub-block path (IIR filters, bus writers, buffer-position advancers, trigger detectors, random drawers)
|
||||
- `BlockRateControlGenerator` — `GeneratorCore/BlockRateControlGenerator.swift`; marker protocol a `ControlGenerator` conforms to when its state must advance once per audio block (IIR filters, bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers, analysers). Supplies the block-rate `calculatedSamples` gateway for free and lets the conformer skip `_setupSubBlockBuffer()`. The standard way to bypass sub-blocking — superseded the per-generator `_calculatedSamplesBlockRate` forwarder. A true sub-blocker must NOT conform.
|
||||
- `_calculatedSamplesBlockRate(graph:count:)` — `Generator` extension; the block-rate gateway the `BlockRateControlGenerator` default calls. Call it directly only in the rare case a generator needs the bypass but cannot conform to the marker
|
||||
- `OscillatorBase` — `Generators/Oscillators/OscillatorBase.swift`; extend instead of declaring `_freqInput` / `_freqIsGenerator` / `_phase` / `_mulAdd` inline. Designated `init(freq:phase:mul:add:)` performs canonical phase normalisation. Used by LF / band-limited oscillators (LFSawtooth, LFSquare, LFTriangle, LFDutyCycle, OscSawtooth, OscSquare, OscTriangle, OscDutyCycle) and `Impulse` (post-super-init writes `_phase = 1.0 - initPhase` so `initPhase == 0` fires at sample 0). Table-lookup oscillators (`OscSin`, `OscTable`) intentionally excluded — they store `_phase` in table-index units to avoid a per-sample multiply in the inner loop.
|
||||
- `NoiseBase` — `Generators/Noise/NoiseBase.swift`; extend instead of declaring `rngState: UInt64` + `_mulAdd: MulAddSpec` inline. Designated `init(initialRngState:mul:add:)`. Used by 23 noise generators across 3 tiers (parameterless, extra-state, distribution-parameterised). LF noise variants and Crackle intentionally excluded.
|
||||
- `UnaryMathBase` — `Generators/Math/UnaryMathBase.swift`; extend instead of declaring `inputSource` + `_mulAdd` inline. Designated `init(_:mul:add:)`. The shared `_Base` for the single-input math operators — each is `public class _Base: UnaryMathBase {}`, with `Audio`/`Control` supplying only the per-operator kernel. Used by 14 operators (Abs, Ceil, Floor, Round, Sign, Sqrt, Log, Exp, Sin, Cos, Tan, Tanh, Reciprocal, DbAmp). Multi-input math (Max, Min, Ring1–4, ExpExp, ExpLin, …) keeps its own `_Base`.
|
||||
- `SpectralFeatureControlBase` — `Generators/Spectral/SpectralFeatureControlBase.swift`; shared base for the control-rate spectral feature analysers (SpectralCentroid, SpectralSpread, SpectralFlatness, SpectralEntropy, SpectralFlux, SpectralRolloff). Owns the analysis handle, spectral buffer, MulAddSpec, ramp state, sub-block bypass, and the drive-analysis → `computeFeature` → ramp body; each `Control` subclass adds only its own params/state and overrides `computeFeature(graph:count:) -> Double`.
|
||||
- `runRBJBiquadBlock(...)` — `Generators/Filters/RBJBiquadHelpers.swift`; module-internal helper holding the shared `_computeSamples` body for `(freq, q)` RBJ biquad filters (LP / HP / AP / Notch). Concrete filters pass the coefficient formula as a closure.
|
||||
- `runTwoPoleResonatorScalarBlock(input:into:y1:y2:b0:na1:na2:count:)` / `runTwoPoleResonatorInterpolatedBlock(input:into:y1:y2:start:end:count:)` — `Generators/Filters/FilterHelpers.swift`; shared per-sample loop body for two-pole resonator filters (`y[n] = b0·x[n] − na1·y[n−1] − na2·y[n−2]`). Consumed by `RingingFilter` + `ResonatingFilter` — concrete filter passes its coefficient-computation function and one-line helper calls.
|
||||
- `sampleOrFallback(_:scalar:at:)` — `Generators/Filters/FilterHelpers.swift`; per-sample coefficient lookup with zero-fallback past block end. Replaces the `xxxSamples.map { i < $0.count ? $0[i] : 0 } ?? scalarX` pattern. Used by `SecondOrderSection` (5 coefficient slots) + `FirstOrderSection` (3 slots). `Lag`/`Decay` family use a different end-clamp + `lagCoeff` wrapping convention; helper doesn't apply there.
|
||||
@@ -341,7 +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).
|
||||
- `attackReleaseSmoother(state:target:attackCoeff:attackComp:releaseCoeff:releaseComp:direction:)` — `Generators/Dynamics/DynamicsHelpers.swift`; asymmetric attack/release smoother step with direction selector (`.rising` for envelope followers; `.falling` for compressor/expander gain-target smoothing). Used by `AmplitudeFollower.Audio` (`.rising`) + `Compressor.Audio` / `Expander.Audio` (`.falling`).
|
||||
- `sampleOrZero(_ p: UnsafePointer<Double>, _ i: Int, _ n: Int) -> Double` — `GeneratorCore/HotLoopHelpers.swift`; `i < n ? p[i] : 0`. Replaces the per-sample `(i < n) ? srcP[i] : 0` boilerplate inside hot loops that read an input row via raw pointer. Module-internal helper used across Filters (Lag / Lag2 / LagUpDown / Lag2UpDown / LeakDC / Decay / Decay2 / SecondOrderSection / FirstOrderSection / RBJBiquad / CombFilter / AllpassFilter) and Delays (DelayLine / DelayLineFeedback). `@_spi(LyrebirdExtensions) public` so out-of-tree generators can adopt the same helper.
|
||||
- `resolveGeneratorOrScalar(_:isGenerator:graph:count:) -> (samples: [Double]?, scalar: Double)` — `GeneratorCore/InputResolutionHelpers.swift`; block-rate input resolution. Replaces the 8-line `if _xxxIsGenerator { xxxSamples = ...; scalarXxx = 0 } else { xxxSamples = nil; scalarXxx = ... }` boilerplate at the top of any `_computeSamples` that pulls multiple `ValidGeneratorInput` parameters. Used by `Flute` (6 params), `Clarinet` (4 params), `PanXYDistance` (4 params), `PanAzDistance` (4 params). Tuple destructure at the call site is the CLAUDE.md-documented exception to the explicit-type-annotation rule. `@inline(__always) @_spi(LyrebirdExtensions) public`.
|
||||
- `resolveGeneratorOrScalar(_:isGenerator:graph:count:) -> (samples: [Double]?, scalar: Double)` — `GeneratorCore/InputResolutionHelpers.swift`; block-rate input resolution. Replaces the 8-line `if _xxxIsGenerator { xxxSamples = ...; scalarXxx = 0 } else { xxxSamples = nil; scalarXxx = ... }` boilerplate at the top of any `_computeSamples` that pulls multiple `ValidGeneratorInput` parameters. Used across many multi-input generators (`Flute`, `Clarinet`, `KarplusStrong`/`GatedKarplusStrong`, `BowedString`, `PlayBuffer`, `SpatialDistance`, `MuTronIII`, `Hilbert`, the spatial panners, and more). Tuple destructure at the call site is the CLAUDE.md-documented exception to the explicit-type-annotation rule. `@inline(__always) @_spi(LyrebirdExtensions) public`.
|
||||
- `applySpatialDistanceFiltering(...)` — `Generators/Panning/SpatialDistanceHelpers.swift`; module-internal shared per-sample pipeline for `PanXYDistance` (Cartesian) and `PanAzDistance` (polar). Both callers pre-compute `(panX, panY)` and the Chebyshev distance metric `posD` from their respective coordinate frames; the rest of the pipeline (amplitude attenuation, cutoff-coefficient caching, Doppler read-rate, delay-line write/read/wrap/clamp, one-pole lowpass, equal-power 4-corner pan) is identical and lives here. Mutates delay-line + one-pole state in place via `inout`. `@inline(__always) internal`.
|
||||
- `plateReverbInputDiffusion(...)` / `plateReverbTankHalf(...)` — `Generators/Reverb/PlateReverbHelpers.swift`; PlateReverb-specific per-sample sub-blocks. `plateReverbInputDiffusion` runs the 4-stage cascaded Schroeder allpass network on a single sample. `plateReverbTankHalf` runs one half of the figure-of-eight tank (modulated allpass → delay 1 → damping LP → decay scale → allpass 2 → delay 2 write). Consumed twice per sample by `PlateReverb._computeSamples` (left and right halves). All state mutated `inout`. `@inline(__always) internal`.
|
||||
- `gverbReadEarlyTaps(...)` / `gverbFDNDamperCascade(...)` — `Generators/Reverb/GVerbHelpers.swift`; GVerb-specific per-sample sub-blocks. `gverbReadEarlyTaps` reads four pre-FDN early-reflection taps with branchless wrap + per-tap gains and returns a 4-tuple. `gverbFDNDamperCascade` applies the FDN one-pole LP damper cascade `y = x*(1-damp) + prev*damp` to four raw FDN reads, mutates `fdnDampState[0..3]` with denormal flush, returns 4-tuple. Both `@inline(__always) internal`.
|
||||
@@ -349,7 +353,9 @@ Module-level helpers exist to eliminate repeated boilerplate; inlining any of th
|
||||
- `_mulAdd.applyIfNeeded(to:graph:count:)`
|
||||
- `fillRampedResult(into:from:to:mulAdd:graph:count:)`
|
||||
- `fillScalarRampedResult(into:previousOutputValue:target:count:)` — `MulAdd.swift`; canonical body of every `Math.Control` `_computeSamples` ramp (28 generators). Distinct from `fillRampedResult` because the caller has pre-folded `mul`/`add` into the scalar `target` — the helper writes the ramp without re-applying `MulAddSpec.apply`.
|
||||
- `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)`
|
||||
- `fillHeldResult(into:value:previousOutputValue:mulAdd:graph:count:)` — `MulAdd.swift`; held-constant counterpart of `fillScalarRampedResult` — fills a block with one value, applies mul/add, sets `previousOutputValue` to the last sample. For block-rate `Control` paths whose output holds one value (one-pole smoothers `Lag`/`Decay`/`LeakDC`/`Slew`/`Formlet`, block-constant analysis `ZeroCrossing`/`Slope`/`RunningMin`/`Max`, trigger/counter latches `Trig`/`Schmidt`/`PulseCount`/`Stepper`; 20 sites). No-op at `count == 0`. NOT for per-sample-varying output.
|
||||
- `MulAddSpec.applyScalar(_:graph:)` — `MulAdd.swift`; folds scalar `mul`/`add` into one block-constant `target` (returns it unchanged on identity). The scalar counterpart of `applyIfNeeded`; used by the 36 scalar-fold paths (Math.Control plus Routing/Waveshaping crossfades and shapers) before `fillScalarRampedResult`.
|
||||
- `firstGeneratorSampleOrFloat(_:isGenerator:graph:count:)` / `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` — `GeneratorCore/InputResolutionHelpers.swift`; block-rate read of a generator-or-scalar input. `first…` reads the block's first sample (`0` if empty) — oscillator/LF/noise `Control` paths; `last…` reads the final sample (ramp endpoint) — dynamics + delay-time paths. Both fall back to `floatValue` for non-generators
|
||||
- `xorshift64Next(_:)`
|
||||
- `lyrebirdSeedXorshift64(from:mixConstant:)` / `lyrebirdSeedXorshift64(from:)` — `Math/LyrebirdConstants.swift`; init-time xorshift64 seed helper. Two-arg form decorrelates Audio/Control pairs via `mixConstant`; one-arg form is the convenience for stand-alone single-state owners (e.g. `DemandTemporalTendency` / `DemandTemporalBrownian`)
|
||||
- `catmullRomCubic(_:_:_:_:t:)` — `Math/CubicInterpolation.swift`; the single shared 4-point Catmull-Rom cubic kernel. Pass `(pM1, p0, p1, p2, t:)` — the sample before the segment, the two bracketing it, the one after, and `t ∈ [0, 1]`. Use instead of inlining the `t²`/`t³` expanded form. `@inline(__always) @_spi(LyrebirdExtensions) public`. Consumers: oscillator table reads (`OscSin` / `oscillatorTableReadCubic`), `PlayBuffer`, `chaoticInterpolate`, and the fractional-delay lines (`DelayLine` / `DelayLineFeedback` / `CombFilter` / `AllpassFilter`).
|
||||
|
||||
+2
-2
@@ -50,7 +50,7 @@ If a unit is useful at both rates, implement both via the **enum namespace patte
|
||||
- **First line of every `_computeSamples` is `_checkCount(count)`.** It traps if `count` exceeds the pre-allocated buffer. No grow path exists.
|
||||
- **Pre-allocate everything in `init`.** Bus memory, scratch buffers, vDSP setup objects. `init` runs off the RT thread; `_computeSamples` must only read/write existing storage. Use `makeResultBuffer(channels:)` / `makeSampleBuffer(_:)` instead of `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)` literals.
|
||||
- **Use `count`, never `engine.blockSize`,** for phase/state advancement — a `Control._computeSamples` may run several times per audio block in sub-block mode.
|
||||
- **Generators with per-audio-block state** (bus writers, position advancers, gain smoothers, trigger detectors, random drawers) override `calculatedSamples` to bypass the sub-block loop via `_calculatedSamplesBlockRate(graph:count:)`. See §15 for the bypass list.
|
||||
- **Control generators with per-audio-block state** (bus writers, position advancers, gain smoothers, trigger detectors, random drawers, analysers) conform the `Control` to `BlockRateControlGenerator` to bypass the sub-block loop (no `calculatedSamples` override, no `_setupSubBlockBuffer()`). See writing-generators.md §15.
|
||||
- **Multi-row generators** (`_result.count > 1`) call `super.init(channels: N)` and override `outputChannelCount`. Missing the override silently mono-izes the generator under `+ - * /`. Channel count must be a `let` fixed at init.
|
||||
- **Extend the right base** where one exists: `OscillatorBase`, `NoiseBase`. Don't re-declare `_phase` / `_mulAdd` / `rngState` inline.
|
||||
- **Denormal hygiene** — flush denormals to zero in feedback paths (filters, delays, reverbs).
|
||||
@@ -127,7 +127,7 @@ let package = Package(
|
||||
.library(name: "LyrebirdMyExtension", targets: ["LyrebirdMyExtension"]),
|
||||
],
|
||||
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: [
|
||||
.target(
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
/* Begin PBXBuildFile section */
|
||||
0306C7C02FAC451300952EAF /* GVerbTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0306C7BF2FAC451300952EAF /* GVerbTest.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 */; };
|
||||
035A2F432FAA4F67007F6289 /* PercSpectralPitchShift.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F412FAA4F67007F6289 /* PercSpectralPitchShift.swift */; };
|
||||
035A2F482FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F492FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift */; };
|
||||
@@ -26,6 +27,7 @@
|
||||
/* Begin PBXFileReference section */
|
||||
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>"; };
|
||||
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>"; };
|
||||
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>"; };
|
||||
@@ -56,6 +58,7 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
0306C7C12FAC45F200952EAF /* ReverbDemo.swift */,
|
||||
99B83EC83F6C48D98441D7F7 /* EventPatternDemo.swift */,
|
||||
035B00032FAB0000007F0001 /* DemoProtocol.swift */,
|
||||
035B00042FAB0000007F0001 /* BufferDemos.swift */,
|
||||
);
|
||||
@@ -207,6 +210,7 @@
|
||||
035A2F482FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift in Sources */,
|
||||
035A2F442FAA4F67007F6289 /* PercBufferRead.swift in Sources */,
|
||||
0306C7C22FAC45F200952EAF /* ReverbDemo.swift in Sources */,
|
||||
631D4C5B1150427CB8D15210 /* EventPatternDemo.swift in Sources */,
|
||||
035A2F452FAA4F67007F6289 /* PercPlayBuffer.swift in Sources */,
|
||||
C1A000000000000000000007 /* main.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.")
|
||||
}
|
||||
}
|
||||
@@ -7,12 +7,21 @@
|
||||
import Foundation
|
||||
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(
|
||||
blockSize: 512,
|
||||
sampleRate: 44100,
|
||||
controlBlockSize: 64,
|
||||
sampleRate: 48000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 2,
|
||||
driver: CoreAudioDriver()
|
||||
driver: makeDefaultAudioDriver()
|
||||
)
|
||||
|
||||
do {
|
||||
@@ -22,7 +31,10 @@ do {
|
||||
exit(1)
|
||||
}
|
||||
|
||||
// BufferDemos(engine: engine).runDemo()
|
||||
ReverbDemo(engine: engine).runDemo()
|
||||
switch demo {
|
||||
case .buffer: BufferDemos(engine: engine).runDemo()
|
||||
case .reverb: ReverbDemo(engine: engine).runDemo()
|
||||
case .eventPattern: EventPatternDemo(engine: engine).runDemo()
|
||||
}
|
||||
|
||||
engine.stop()
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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"
|
||||
),
|
||||
]
|
||||
)
|
||||
@@ -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 ─────────────────────────────────────────────────────────────
|
||||
// Change `demo` to `.sineTone` or `.binDelay` to switch demos.
|
||||
private enum Demo { case vector, binDelay, sineTone }
|
||||
private let demo: Demo = .vector
|
||||
private let demo: Demo = .binDelay
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
|
||||
@@ -9,7 +9,7 @@ import LyrebirdSynth
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
sampleRate: 44100,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
|
||||
@@ -7,9 +7,21 @@
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// Output to the Desktop — triggers the NSDesktopFolderUsageDescription TCC prompt on first run.
|
||||
let outputURL = FileManager.default.homeDirectoryForCurrentUser
|
||||
// Offline render has no audio device, so this demo runs the same on macOS and Linux.
|
||||
// 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")
|
||||
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.
|
||||
let sampleRate: Double = 48000
|
||||
@@ -43,7 +55,7 @@ let tailDuration: Double = 0.1
|
||||
let lastStart = voices.map(\.start).max() ?? 0.0
|
||||
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(
|
||||
blockSize: blockSize,
|
||||
sampleRate: sampleRate,
|
||||
@@ -77,7 +89,7 @@ do {
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
fputs("engine.schedule failed: \(error)\n", stderr)
|
||||
FileHandle.standardError.write(Data("engine.schedule failed: \(error)\n".utf8))
|
||||
exit(1)
|
||||
}
|
||||
|
||||
@@ -87,7 +99,7 @@ do {
|
||||
try engine.start()
|
||||
print("Done.")
|
||||
} catch {
|
||||
fputs("Render failed: \(error)\n", stderr)
|
||||
FileHandle.standardError.write(Data("Render failed: \(error)\n".utf8))
|
||||
exit(1)
|
||||
}
|
||||
|
||||
|
||||
@@ -17,13 +17,15 @@ import LyrebirdSynth
|
||||
let quickstartDuration: Double = 5.0
|
||||
|
||||
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(
|
||||
blockSize: 512,
|
||||
sampleRate: 48000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
driver: makeDefaultAudioDriver()
|
||||
)
|
||||
|
||||
try engine.start()
|
||||
@@ -39,6 +41,6 @@ do {
|
||||
engine.stop() // closes the device
|
||||
print("Done.")
|
||||
} catch {
|
||||
fputs("Lyrebird quickstart failed to start: \(error)\n", stderr)
|
||||
FileHandle.standardError.write(Data("Lyrebird quickstart failed to start: \(error)\n".utf8))
|
||||
exit(1)
|
||||
}
|
||||
|
||||
@@ -7,6 +7,17 @@
|
||||
import Foundation
|
||||
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
|
||||
/// 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
|
||||
/// the engine or schedule any voices.
|
||||
func runDemo() {
|
||||
// Step 1 — write MusicXML to Desktop.
|
||||
let xmlURL: URL = FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent("Desktop/LyrebirdScoreDemo.musicxml")
|
||||
// Step 1 — write MusicXML to the demo output directory.
|
||||
let xmlURL: URL = demoOutputDirectory()
|
||||
.appendingPathComponent("LyrebirdScoreDemo.musicxml")
|
||||
let xmlString: String = score.toMusicXMLString()
|
||||
do {
|
||||
try xmlString.write(to: xmlURL, atomically: true, encoding: .utf8)
|
||||
print("MusicXML written → \(xmlURL.path)")
|
||||
} 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.
|
||||
@@ -105,7 +116,7 @@ final class ScoreDemo: DemoProtocol {
|
||||
print("Score key (G major): \(rt.keySignature == .gMajor ? "OK" : "MISMATCH(\(rt.keySignature))")")
|
||||
}
|
||||
} 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
|
||||
@@ -119,8 +130,8 @@ final class ScoreDemo: DemoProtocol {
|
||||
// `rehearsalMarksAsStaffText: true` option emits boxed <words> staff text
|
||||
// instead, but that attaches to a staff and can collide with notation.
|
||||
let showcase: Score = ScoreDemo.makeSectionedShowcase()
|
||||
let showcaseURL: URL = FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent("Desktop/LyrebirdScoreSections.musicxml")
|
||||
let showcaseURL: URL = demoOutputDirectory()
|
||||
.appendingPathComponent("LyrebirdScoreSections.musicxml")
|
||||
do {
|
||||
try showcase.toMusicXMLString().write(to: showcaseURL, atomically: true, encoding: .utf8)
|
||||
print("Sectioned showcase written → \(showcaseURL.path)")
|
||||
@@ -132,7 +143,7 @@ final class ScoreDemo: DemoProtocol {
|
||||
print("Sections → rehearsal marks: \(markList)")
|
||||
print("Sectioned showcase parts: \(showcase.parts.map { $0.name }.joined(separator: ", "))")
|
||||
} 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.
|
||||
@@ -185,7 +196,7 @@ final class ScoreDemo: DemoProtocol {
|
||||
try engine.schedule(voice, after: startSeconds)
|
||||
scheduledCount += 1
|
||||
} 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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,9 +7,16 @@
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// Output paths — both land on the Desktop.
|
||||
let cafURL: URL = FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent("Desktop/LyrebirdScoreDemo.caf")
|
||||
// Audio output. CAF is Apple-only (ExtAudioFile), so off Apple we render the
|
||||
// portable WAV codec; `demoOutputDirectory()` is the Desktop on Apple and the
|
||||
// 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.
|
||||
let sampleRate: Double = 48000
|
||||
@@ -23,7 +30,7 @@ let totalDuration: Double = demo.totalDuration
|
||||
demo.runDemo()
|
||||
|
||||
// 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(
|
||||
blockSize: blockSize,
|
||||
sampleRate: sampleRate,
|
||||
@@ -37,12 +44,12 @@ let engine: SynthesisEngine = SynthesisEngine(
|
||||
// isolated, so this is a plain direct call — no MainActor hop needed.
|
||||
demo.scheduleVoices(engine: engine)
|
||||
|
||||
print(String(format: "Rendering %.2f s → %@", totalDuration, cafURL.path))
|
||||
print(String(format: "Rendering %.2f s → %@", totalDuration, audioURL.path))
|
||||
|
||||
do {
|
||||
try engine.start()
|
||||
print("Done.")
|
||||
} catch {
|
||||
fputs("Render failed: \(error)\n", stderr)
|
||||
FileHandle.standardError.write(Data("Render failed: \(error)\n".utf8))
|
||||
exit(1)
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
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",
|
||||
platforms: [.macOS(.v15), .iOS(.v18)],
|
||||
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: [
|
||||
.executableTarget(
|
||||
@@ -156,7 +156,7 @@ let engine = SynthesisEngine(
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver())
|
||||
driver: makeDefaultAudioDriver())
|
||||
|
||||
try engine.start()
|
||||
try engine.add(SineTone())
|
||||
|
||||
+3
@@ -10,6 +10,9 @@
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdGUIDemo">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdiOSDemo/LyrebirdiOSDemo.xcodeproj">
|
||||
</FileRef>
|
||||
|
||||
@@ -1,14 +1,33 @@
|
||||
# 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.
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
|
||||
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
|
||||
|
||||
@@ -28,6 +47,42 @@ let env = EnvelopeGen.Control(envelope: Envelope(
|
||||
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
|
||||
|
||||
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,
|
||||
numOutputChannels: 2,
|
||||
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.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
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
@@ -81,7 +136,7 @@ import LyrebirdSynth
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: 512, sampleRate: 48_000,
|
||||
numOutputChannels: 2, numInputChannels: 0,
|
||||
driver: CoreAudioDriver())
|
||||
driver: makeDefaultAudioDriver())
|
||||
try engine.start()
|
||||
|
||||
// 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
|
||||
|
||||
| Platform | OS | Xcode | Swift |
|
||||
| Platform | OS | IDE | Swift |
|
||||
|---|---|---|---|
|
||||
| macOS | 15+ | 16+ | 6.0 |
|
||||
| iOS | 18+ | 16+ | 6.0 |
|
||||
| macOS | 15+ | Xcode 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:
|
||||
|
||||
```
|
||||
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`).
|
||||
@@ -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**.
|
||||
|
||||
**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
|
||||
|
||||
Workspace scheme selector exposes ten entries:
|
||||
Workspace scheme selector exposes eleven entries:
|
||||
|
||||
| Scheme | Purpose | Platform |
|
||||
|---|---|---|
|
||||
| `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 |
|
||||
| `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 |
|
||||
| `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 |
|
||||
| `LyrebirdNRTDemo` | CLI — offline render to CAF via `NRTDriver` | macOS |
|
||||
| `LyrebirdScoreDemo` | CLI — builds notated `Score`s (result-builder DSL), exports MusicXML, renders 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 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 |
|
||||
| `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. |
|
||||
| `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
|
||||
@@ -202,23 +309,24 @@ swift test # run all 5481 tests
|
||||
swift test --filter LyrebirdTests # run one suite
|
||||
swift run lyrebird # run the CLI
|
||||
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
|
||||
|
||||
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 |
|
||||
|---|---|---|
|
||||
| [`LyrebirdQuickstartDemo`](Demos/LyrebirdQuickstartDemo/) | CLI — fastest sound: a one-oscillator `SineTone` plays 440 Hz for 10 s, then exits (mirrors the `quickstart` template) | macOS |
|
||||
| [`LyrebirdDemo`](Demos/LyrebirdDemo/) | CLI — plays through default output via `CoreAudioDriver` | macOS |
|
||||
| [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | SwiftUI app — live oscilloscope, `@UIParam` knobs | 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 `makeDefaultAudioDriver()` (Core Audio on macOS, ALSA on Linux) | macOS · Linux |
|
||||
| [`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 |
|
||||
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | CLI — offline render to CAF file via `NRTDriver` | macOS |
|
||||
| [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | CLI — notated `Score` → MusicXML export + offline render to CAF 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 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 |
|
||||
| [`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.
|
||||
|
||||
| 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:
|
||||
|
||||
- **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/
|
||||
│ ├── LyrebirdQuickstartDemo/ # fastest sound — SineTone plays 10 s then exits
|
||||
│ ├── LyrebirdDemo/ # (same as Sources/LyrebirdDemo — workspace target)
|
||||
│ ├── LyrebirdGUIDemo/ # cross-platform GUI — SwiftUI (macOS) + GTK4 (Linux), one source
|
||||
│ ├── LyrebirdMacOSDemo/ # macOS SwiftUI app
|
||||
│ ├── LyrebirdiOSDemo/ # iOS SwiftUI app
|
||||
│ ├── LyrebirdNRTDemo/ # offline renderer
|
||||
|
||||
+144
@@ -7,6 +7,150 @@ 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
|
||||
|
||||
@@ -65,10 +65,7 @@ public final class SpectrumCapture: SpectralProcessor, @unchecked Sendable {
|
||||
/// - fftSize: FFT frame size. Must match the `SpectralChain.Audio` this capture is registered on.
|
||||
/// Must be a power of two ≥ 4. Default: 2048.
|
||||
public init(fftSize: Int = 2048) {
|
||||
precondition(
|
||||
fftSize >= 4 && (fftSize & (fftSize - 1)) == 0,
|
||||
"SpectrumCapture: fftSize must be a power of two >= 4, got \(fftSize)"
|
||||
)
|
||||
lyrebirdRequireFFTSize(fftSize, typeName: "SpectrumCapture")
|
||||
self.fftSize = fftSize
|
||||
let bc: Int = fftSize / 2 + 1
|
||||
self.binCount = bc
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -135,8 +135,9 @@ public protocol ControlGenerator: Generator {
|
||||
///
|
||||
/// Used by `calculatedSamples` when `controlBlockSize < count` to accumulate
|
||||
/// results from multiple `_computeSamples` calls without heap allocation.
|
||||
/// Initialise to `[[]]` (via `GeneratorBase` default). Call `_setupSubBlockBuffer()`
|
||||
/// in the designated `Control.init` to resize for sub-block assembly. Never call on the RT thread.
|
||||
/// Initialise to `[[]]` (via `GeneratorBase` default). A sub-blocking `Control.init`
|
||||
/// calls `_setupSubBlockBuffer()` to resize for sub-block assembly (never on the RT
|
||||
/// thread); `BlockRateControlGenerator` conformers never sub-block and skip it.
|
||||
var _subBlockBuffer: [[Double]] { get set }
|
||||
}
|
||||
|
||||
@@ -205,18 +206,16 @@ extension Generator {
|
||||
|
||||
/// Bypass-sub-block fan-out cache helper.
|
||||
///
|
||||
/// Used by generators that override `calculatedSamples` to force `_computeSamples` to
|
||||
/// run exactly once per audio block, bypassing the `ControlGenerator` extension's
|
||||
/// sub-block path. Required for any generator whose state must advance once per audio
|
||||
/// block (IIR filters, bus writers, buffer-position advancers, gain smoothers, trigger
|
||||
/// detectors, random drawers). See `docs/protocols/writing-generators.md` §15.
|
||||
/// The block-rate gateway: runs `_computeSamples` exactly once per audio block,
|
||||
/// bypassing the `ControlGenerator` extension's sub-block path. Required for any
|
||||
/// generator whose state must advance once per audio block (IIR filters, bus writers,
|
||||
/// buffer-position advancers, gain smoothers, trigger detectors, random drawers,
|
||||
/// analysers). See `docs/protocols/writing-generators.md` §15.
|
||||
///
|
||||
/// Drop-in replacement for the canonical bypass block:
|
||||
/// ```swift
|
||||
/// public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
/// _calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
/// }
|
||||
/// ```
|
||||
/// The standard way to get this behaviour is to conform the control generator to
|
||||
/// `BlockRateControlGenerator`, whose `calculatedSamples` default calls this method —
|
||||
/// prefer that over hand-writing a `calculatedSamples` forwarder. Call this directly
|
||||
/// only when the bypass is needed but the marker cannot apply.
|
||||
@inline(__always)
|
||||
public func _calculatedSamplesBlockRate(
|
||||
graph: SynthGraph,
|
||||
|
||||
@@ -22,8 +22,10 @@
|
||||
/// post-super reassignment. `outputChannelCount` must be overridden to return the
|
||||
/// fixed channel count.
|
||||
///
|
||||
/// `Audio` conformers inherit `_subBlockBuffer` as `[[]]` (no allocation); `Control` conformers
|
||||
/// resize it to `lyrebirdDefaultResultBufferSize` via `_setupSubBlockBuffer()` in `init`.
|
||||
/// `Audio` conformers inherit `_subBlockBuffer` as `[[]]` (no allocation); sub-blocking
|
||||
/// `Control` conformers resize it to `lyrebirdDefaultResultBufferSize` via
|
||||
/// `_setupSubBlockBuffer()` in `init`. `BlockRateControlGenerator` conformers never
|
||||
/// sub-block and leave it unallocated.
|
||||
open class GeneratorBase {
|
||||
public var _segmentSerial: UInt64 = 0
|
||||
public var _cachedResult: [[Double]] = [[]]
|
||||
|
||||
@@ -58,3 +58,63 @@ public func resolveGeneratorOrScalar(
|
||||
}
|
||||
return (nil, source.floatValue(graph: graph))
|
||||
}
|
||||
|
||||
// MARK: - Block-constant generator reads
|
||||
|
||||
/// Reads the **first** sample of a generator's block output, or returns the scalar
|
||||
/// `floatValue` when the input is not a Generator. RT-safe.
|
||||
///
|
||||
/// Use for block-constant parameters read once at the top of a `Control._computeSamples`:
|
||||
/// the first-sample read picks up the value at the block boundary while keeping the rest
|
||||
/// of the per-block math at block-rate. The companion `lastGeneratorSampleOrFloat` reads
|
||||
/// the block's final sample instead (ramp endpoint).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Any `ValidGeneratorInput` — scalar, `ParameterNode`, or generator.
|
||||
/// - isGenerator: Pre-computed at init (`input is any Generator`). Never use `is` on the RT thread.
|
||||
/// - graph: The current synthesis graph.
|
||||
/// - count: Number of samples in the current block.
|
||||
/// - Returns: the first sample of `input.calculatedSamples(...)` (or `0` if the block is
|
||||
/// empty) when `isGenerator` is true; `input.floatValue(graph:)` otherwise.
|
||||
@inline(__always)
|
||||
@_spi(LyrebirdExtensions)
|
||||
public func firstGeneratorSampleOrFloat(
|
||||
_ input: any ValidGeneratorInput,
|
||||
isGenerator: Bool,
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> Double {
|
||||
guard isGenerator else { return input.floatValue(graph: graph) }
|
||||
return input.calculatedSamples(graph: graph, count: count).first?.first ?? 0
|
||||
}
|
||||
|
||||
/// Reads the **last** sample of a generator's block output, or returns the scalar
|
||||
/// `floatValue` when the input is not a Generator. RT-safe.
|
||||
///
|
||||
/// Use for block-constant parameters that must still capture `ParameterNode` ramps:
|
||||
/// the last-sample read picks up the ramp endpoint while keeping coefficient math
|
||||
/// at block-rate. The companion `firstGeneratorSampleOrFloat` reads the block's first
|
||||
/// sample instead.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Any `ValidGeneratorInput` — scalar, `ParameterNode`, or generator.
|
||||
/// - isGenerator: Pre-computed at init (`input is any Generator`). Never use `is` on the RT thread.
|
||||
/// - graph: The current synthesis graph.
|
||||
/// - count: Number of samples in the current block.
|
||||
/// - Returns: `buf[count - 1]` when `isGenerator` is true and the block is non-empty;
|
||||
/// `input.floatValue(graph:)` otherwise.
|
||||
@inline(__always)
|
||||
@_spi(LyrebirdExtensions)
|
||||
public func lastGeneratorSampleOrFloat(
|
||||
_ input: any ValidGeneratorInput,
|
||||
isGenerator: Bool,
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> Double {
|
||||
guard isGenerator else { return input.floatValue(graph: graph) }
|
||||
guard let buf: [Double] = input.calculatedSamples(graph: graph, count: count).first,
|
||||
count > 0 else {
|
||||
return input.floatValue(graph: graph)
|
||||
}
|
||||
return buf[count - 1]
|
||||
}
|
||||
|
||||
@@ -6,38 +6,6 @@
|
||||
|
||||
import LyrebirdDSP
|
||||
|
||||
// MARK: - Block-constant generator read helper
|
||||
|
||||
/// Reads the last sample of a generator's block output, or returns the scalar
|
||||
/// `floatValue` when the input is not a Generator. RT-safe.
|
||||
///
|
||||
/// Use for block-constant parameters that must still capture `ParameterNode` ramps:
|
||||
/// the last-sample read picks up the ramp endpoint while keeping coefficient math
|
||||
/// at block-rate.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Any `ValidGeneratorInput` — scalar, `ParameterNode`, or generator.
|
||||
/// - isGenerator: Pre-computed at init (`input is any Generator`). Never use `is` on the RT thread.
|
||||
/// - graph: The current synthesis graph.
|
||||
/// - count: Number of samples in the current block.
|
||||
/// - Returns: `buf[count - 1]` when `isGenerator` is true and the block is non-empty;
|
||||
/// `input.floatValue(graph:)` otherwise.
|
||||
@_spi(LyrebirdExtensions)
|
||||
@inline(__always)
|
||||
public func lastGeneratorSampleOrFloat(
|
||||
_ input: any ValidGeneratorInput,
|
||||
isGenerator: Bool,
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> Double {
|
||||
guard isGenerator else { return input.floatValue(graph: graph) }
|
||||
guard let buf: [Double] = input.calculatedSamples(graph: graph, count: count).first,
|
||||
count > 0 else {
|
||||
return input.floatValue(graph: graph)
|
||||
}
|
||||
return buf[count - 1]
|
||||
}
|
||||
|
||||
// MARK: - Scalar extraction
|
||||
|
||||
/// Returns the constant value for compile-time-known scalar inputs, nil for generators/strings.
|
||||
@@ -63,9 +31,9 @@ public func extractScalar(_ input: any ValidGeneratorInput) -> Double? {
|
||||
/// _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
/// ```
|
||||
/// `applyIfNeeded` short-circuits internally on `isIdentity`, so the call site
|
||||
/// never needs an `if !isIdentity` guard. `MathGenerators.Control` does not call
|
||||
/// through this struct — it computes its scalar `target = input * mulFloat + addFloat`
|
||||
/// before the ramp, documented in `docs/protocols/writing-generators.md` §13.
|
||||
/// never needs an `if !isIdentity` guard. `MathGenerators.Control` applies mul/add to
|
||||
/// its scalar `target` before the ramp (not to the output buffer after) via `applyScalar`
|
||||
/// below — documented in `docs/protocols/writing-generators.md` §13.
|
||||
@_spi(LyrebirdExtensions)
|
||||
public struct MulAddSpec {
|
||||
public let mulInput: any ValidGeneratorInput
|
||||
@@ -115,6 +83,20 @@ public struct MulAddSpec {
|
||||
if !isIdentity { apply(to: &channels, graph: graph, count: count) }
|
||||
}
|
||||
|
||||
/// Applies the scalar `(target × mul) + add` to a single block-constant value,
|
||||
/// short-circuiting to `target` on identity. Reads `mul`/`add` at block rate via
|
||||
/// `floatValue`.
|
||||
///
|
||||
/// For `Math.Control` paths that compute one scalar target per block and hand it to
|
||||
/// `fillScalarRampedResult` — the documented exception to the buffer-based
|
||||
/// `apply`/`applyIfNeeded`. Replaces the inline
|
||||
/// `if !isIdentity { target = target * mulInput.floatValue + addInput.floatValue }`.
|
||||
@inline(__always)
|
||||
public func applyScalar(_ target: Double, graph: SynthGraph) -> Double {
|
||||
guard !isIdentity else { return target }
|
||||
return target * mulInput.floatValue(graph: graph) + addInput.floatValue(graph: graph)
|
||||
}
|
||||
|
||||
/// Applies `(x × mul) + add` via vDSP to every channel in `channels`.
|
||||
///
|
||||
/// **Channel-aware broadcast (matches `BinaryOpGenerator` policy).** When `mul` or
|
||||
@@ -247,8 +229,7 @@ public func fillRampedResult(
|
||||
/// Usage in a Math-style ControlGenerator._computeSamples:
|
||||
/// ```swift
|
||||
/// var target = someScalarOp(input.floatValue(graph: graph))
|
||||
/// if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph)
|
||||
/// + _mulAdd.addInput.floatValue(graph: graph) }
|
||||
/// target = _mulAdd.applyScalar(target, graph: graph)
|
||||
/// fillScalarRampedResult(
|
||||
/// into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
|
||||
/// return _result
|
||||
@@ -279,6 +260,40 @@ public func fillScalarRampedResult(
|
||||
}
|
||||
}
|
||||
|
||||
/// Fills `result[0]` with a single block-constant `value`, applies `mulAdd` if
|
||||
/// non-identity, and sets `previousOutputValue` to the (post-mulAdd) last sample.
|
||||
/// No-op when `count == 0` (leaving `previousOutputValue` unchanged).
|
||||
///
|
||||
/// The held counterpart of `fillScalarRampedResult`: block-rate `ControlGenerator`
|
||||
/// paths whose output holds one value for the whole block — one-pole/leaky
|
||||
/// smoothers (`Lag`, `Decay`, `LeakDC`, `Slew`, `Formlet`), block-constant analysis
|
||||
/// outputs (`ZeroCrossing`, `Slope`, `RunningMin`/`Max`), and trigger/counter latches
|
||||
/// (`Trig`, `Schmidt`, `PulseCount`, `Stepper`, …). Replaces the repeated
|
||||
/// `vDSP_vfillD` (or per-sample constant fill) + `applyIfNeeded` + last-sample tail.
|
||||
@_spi(LyrebirdExtensions)
|
||||
@inline(__always)
|
||||
public func fillHeldResult(
|
||||
into result: inout [[Double]],
|
||||
value: Double,
|
||||
previousOutputValue: inout Double,
|
||||
mulAdd: MulAddSpec,
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) {
|
||||
guard count > 0 else { return }
|
||||
precondition(!result.isEmpty,
|
||||
"fillHeldResult: result has no rows")
|
||||
precondition(count <= result[0].count,
|
||||
"fillHeldResult: count exceeds result buffer")
|
||||
var fillValue: Double = value
|
||||
result[0].withUnsafeMutableBufferPointer { (buf: inout UnsafeMutableBufferPointer<Double>) in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
|
||||
}
|
||||
mulAdd.applyIfNeeded(to: &result, graph: graph, count: count)
|
||||
previousOutputValue = result[0][count - 1]
|
||||
}
|
||||
|
||||
// MARK: - Per-channel vDSP dispatch
|
||||
|
||||
/// Pure-scalar `(x * mulScalar) + addScalar` for one channel. No `Optional`
|
||||
|
||||
@@ -42,7 +42,7 @@ public enum BeatTrack {
|
||||
/// once at init. Defaults to ``beatTrackPreferredBPM``.
|
||||
/// - windowSeconds: ODF history length for autocorrelation. Read once at
|
||||
/// init. Defaults to ``beatTrackMaxWindowSeconds``.
|
||||
public final class Control: GeneratorBase, ControlGenerator {
|
||||
public final class Control: GeneratorBase, BlockRateControlGenerator {
|
||||
|
||||
/// Internal ODF source + the input refs each mode needs. Only one mode's
|
||||
/// state is live; the spectral-flux state (`_prevMag`, `_isFirstFrame`)
|
||||
@@ -197,19 +197,8 @@ public enum BeatTrack {
|
||||
featureRateHz: beatTrackFeatureRateHz
|
||||
)
|
||||
super.init(channels: beatTrackOutputRowCount)
|
||||
_setupSubBlockBuffer(channels: beatTrackOutputRowCount)
|
||||
}
|
||||
|
||||
// MARK: - Compute
|
||||
|
||||
// Bypass the sub-block loop: the ODF advances once per audio block (the
|
||||
// spectral buffer once per FFT hop) and the tracker state must too.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
|
||||
@@ -38,7 +38,7 @@ public enum Loudness {
|
||||
/// - calibrationDB: dBFS→SPL offset. Defaults to ``loudnessDefaultCalibrationDB``.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset (sones). Defaults to `0.0`.
|
||||
public final class Control: GeneratorBase, ControlGenerator {
|
||||
public final class Control: GeneratorBase, BlockRateControlGenerator {
|
||||
|
||||
private let _analysis: SpectralChain.Audio?
|
||||
private let _spectral: SpectralBuffer
|
||||
@@ -127,17 +127,8 @@ public enum Loudness {
|
||||
)
|
||||
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
super.init()
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
// Bypass the sub-block loop: the spectral buffer advances once per FFT
|
||||
// hop and the loudness state (temporal mask) advances once per block.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
|
||||
@@ -143,7 +143,7 @@ public enum RunningMax {
|
||||
/// - trig: Reset trigger. ≤0 → >0 rising edges reset the running maximum. Defaults to `0.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
/// - Parameters:
|
||||
@@ -158,17 +158,8 @@ public enum RunningMax {
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, trig: trig, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
/// Bypass sub-block loop: the running-maximum state machine must scan the full
|
||||
/// audio-rate input block exactly once per audio block.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
@@ -203,16 +194,7 @@ public enum RunningMax {
|
||||
_prevTrig = prevTrig
|
||||
_initialized = initialized
|
||||
|
||||
var fillValue: Double = extreme
|
||||
_result[0].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
|
||||
guard count > 0 else { return _result }
|
||||
previousOutputValue = _result[0][count - 1]
|
||||
fillHeldResult(into: &_result, value: extreme, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
|
||||
@@ -143,7 +143,7 @@ public enum RunningMin {
|
||||
/// - trig: Reset trigger. ≤0 → >0 rising edges reset the running minimum. Defaults to `0.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
/// - Parameters:
|
||||
@@ -158,17 +158,8 @@ public enum RunningMin {
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, trig: trig, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
/// Bypass sub-block loop: the running-minimum state machine must scan the full
|
||||
/// audio-rate input block exactly once per audio block.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
@@ -203,16 +194,7 @@ public enum RunningMin {
|
||||
_prevTrig = prevTrig
|
||||
_initialized = initialized
|
||||
|
||||
var fillValue: Double = extreme
|
||||
_result[0].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
|
||||
guard count > 0 else { return _result }
|
||||
previousOutputValue = _result[0][count - 1]
|
||||
fillHeldResult(into: &_result, value: extreme, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
|
||||
@@ -132,7 +132,7 @@ public enum Slope {
|
||||
/// - input: Signal to differentiate.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
/// - Parameters:
|
||||
@@ -145,16 +145,8 @@ public enum Slope {
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
/// Bypass sub-block loop: slope state must advance exactly once per audio block.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
@@ -178,16 +170,7 @@ public enum Slope {
|
||||
_prevSample = x
|
||||
}
|
||||
|
||||
var fillValue: Double = slope
|
||||
_result[0].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
|
||||
guard count > 0 else { return _result }
|
||||
previousOutputValue = _result[0][count - 1]
|
||||
fillHeldResult(into: &_result, value: slope, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
|
||||
@@ -157,7 +157,7 @@ public enum ZeroCrossing {
|
||||
/// - input: Signal to analyse.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
/// - Parameters:
|
||||
@@ -170,17 +170,8 @@ public enum ZeroCrossing {
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
/// Bypass sub-block loop: the zero-crossing state machine must scan the full
|
||||
/// audio-rate input block exactly once per audio block.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
@@ -216,16 +207,7 @@ public enum ZeroCrossing {
|
||||
_freq = freq
|
||||
_initialized = initialized
|
||||
|
||||
var fillValue: Double = freq
|
||||
_result[0].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
|
||||
guard count > 0 else { return _result }
|
||||
previousOutputValue = _result[0][count - 1]
|
||||
fillHeldResult(into: &_result, value: freq, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
|
||||
@@ -166,7 +166,7 @@ public enum BufferRead {
|
||||
/// - interpolation: Sample interpolation quality. Defaults to `.linear`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Offset added after multiplier. Defaults to `0.0`.
|
||||
public final class Control: GeneratorBase, ControlGenerator {
|
||||
public final class Control: GeneratorBase, BlockRateControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
@@ -203,7 +203,6 @@ public enum BufferRead {
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
_rampTargets = [Double](repeating: 0, count: buffer.channelCount)
|
||||
super.init(channels: buffer.channelCount)
|
||||
_setupSubBlockBuffer(channels: buffer.channelCount)
|
||||
}
|
||||
|
||||
/// Replace the buffer being read. Pass `nil` to silence the reader.
|
||||
@@ -226,14 +225,6 @@ public enum BufferRead {
|
||||
_slot.swap(buffer, engine: engine)
|
||||
}
|
||||
|
||||
// Bypass sub-block loop: position is block-rate — re-evaluating per sub-block has
|
||||
// no benefit and would advance _rampTargets N times per audio block.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
|
||||
@@ -332,26 +332,10 @@ public enum PlayBuffer {
|
||||
|
||||
// Evaluate rate input — generator path reads a full per-sample buffer;
|
||||
// scalar path computes one constant value and skips array allocation.
|
||||
let rateSamples: [Double]?
|
||||
let scalarRate: Double
|
||||
if _rateIsGenerator {
|
||||
rateSamples = _rateInput.calculatedSamples(graph: graph, count: count).first
|
||||
scalarRate = 0
|
||||
} else {
|
||||
rateSamples = nil
|
||||
scalarRate = _rateInput.floatValue(graph: graph)
|
||||
}
|
||||
let (rateSamples, scalarRate) = resolveGeneratorOrScalar(_rateInput, isGenerator: _rateIsGenerator, graph: graph, count: count)
|
||||
|
||||
// Evaluate trigger input — same two-path pattern.
|
||||
let triggerSamples: [Double]?
|
||||
let scalarTrigger: Double
|
||||
if _triggerIsGenerator {
|
||||
triggerSamples = _triggerInput.calculatedSamples(graph: graph, count: count).first
|
||||
scalarTrigger = 0
|
||||
} else {
|
||||
triggerSamples = nil
|
||||
scalarTrigger = _triggerInput.floatValue(graph: graph)
|
||||
}
|
||||
let (triggerSamples, scalarTrigger) = resolveGeneratorOrScalar(_triggerInput, isGenerator: _triggerIsGenerator, graph: graph, count: count)
|
||||
|
||||
guard let buffer: LyrebirdBuffer = _slot.load(engine: graph.engine), buffer.isValid else {
|
||||
for ch: Int in 0..<channelCount {
|
||||
@@ -444,7 +428,7 @@ public enum PlayBuffer {
|
||||
/// Defaults to `0.0` (no trigger).
|
||||
/// - mul: Output multiplier applied after synthesis. Defaults to `1.0`.
|
||||
/// - add: Offset added after multiplier. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator, DoneActionWatchable {
|
||||
public final class Control: _Base, BlockRateControlGenerator, DoneActionWatchable {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 0.0
|
||||
@@ -490,19 +474,10 @@ public enum PlayBuffer {
|
||||
startPos: startPos, rate: rate, trigger: trigger,
|
||||
mul: mul, add: add
|
||||
)
|
||||
_setupSubBlockBuffer()
|
||||
_registerAutoFreeIfNeeded(doneAction)
|
||||
}
|
||||
|
||||
|
||||
// Bypass sub-block loop: PlayBuffer.Control advances _phase once per audio block.
|
||||
// Sub-blocking would advance it N times per block, running playback at N× speed.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
|
||||
@@ -538,7 +538,7 @@ public enum RecordBuffer {
|
||||
/// `doneAction` and stops recording. Default `true`.
|
||||
/// - doneAction: Behaviour when the write head reaches the end of the
|
||||
/// buffer (`loop == false`). Default `.nothing`.
|
||||
public final class Control: _Base, ControlGenerator, DoneActionWatchable, RootRegistering {
|
||||
public final class Control: _Base, BlockRateControlGenerator, DoneActionWatchable, RootRegistering {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
@@ -566,20 +566,11 @@ public enum RecordBuffer {
|
||||
+ "For multi-channel recording use RecordBuffer.Audio."
|
||||
)
|
||||
super.init(input: input, buffer: buffer, loop: loop, doneAction: doneAction)
|
||||
_setupSubBlockBuffer()
|
||||
_registerAutoFreeIfNeeded(doneAction)
|
||||
_registerAsRootIfBuilding()
|
||||
}
|
||||
|
||||
|
||||
// Bypass sub-block loop: RecordBuffer.Control writes one buffer frame per audio block.
|
||||
// Sub-blocking would write N frames per block, accelerating recording by N×.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
|
||||
@@ -165,7 +165,7 @@ public enum In {
|
||||
/// consecutive buses with independent ramp state per channel). An ``AudioBus`` traps; use ``In/Audio``.
|
||||
/// - channels: Only available on the `Int`-index overload. Number of consecutive buses
|
||||
/// to read. Defaults to `1`. Fixed at init — no RT allocation.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
/// Per-channel ramp state. Updated by `_computeSamples` after each block.
|
||||
private var _previousOutputValues: [Double]
|
||||
@@ -187,7 +187,6 @@ public enum In {
|
||||
let ch: Int = _resolvedChannelCount(bus)
|
||||
_previousOutputValues = [Double](repeating: 0.0, count: ch)
|
||||
super.init(bus: bus.index, channels: ch)
|
||||
_setupSubBlockBuffer(channels: ch)
|
||||
}
|
||||
|
||||
/// Reads from a raw bus index with an explicit channel count.
|
||||
@@ -201,7 +200,6 @@ public enum In {
|
||||
) {
|
||||
_previousOutputValues = [Double](repeating: 0.0, count: channels)
|
||||
super.init(bus: bus, channels: channels)
|
||||
_setupSubBlockBuffer(channels: channels)
|
||||
}
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double {
|
||||
@@ -209,15 +207,6 @@ public enum In {
|
||||
return Double(graph.engine.controlBuses[bus])
|
||||
}
|
||||
|
||||
// Bypass sub-block loop: control bus values are written once per audio block by Out.Control.
|
||||
// Sub-blocking would reset _previousOutputValues after each partial ramp, compressing
|
||||
// the interpolation into only the first controlBlockSize samples instead of the full block.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
/// Produces a linearly-interpolated block for each channel, ramping from the previous
|
||||
/// block's end value to the current control bus value.
|
||||
|
||||
@@ -135,9 +135,9 @@ public enum Out {
|
||||
/// to `channelCount`). An ``AudioBus`` traps; use ``Out/Audio`` instead.
|
||||
/// - source: Signal to write. The last sample of each channel block is accumulated into
|
||||
/// the corresponding control bus. Multi-channel sources write to consecutive buses.
|
||||
public final class Control: _Base, ControlGenerator, RootRegistering {
|
||||
public final class Control: _Base, BlockRateControlGenerator, RootRegistering {
|
||||
|
||||
/// Satisfies ControlGenerator protocol requirement — unused, Control overrides calculatedSamples.
|
||||
/// Satisfies ControlGenerator protocol requirement — unused; Control conforms to `BlockRateControlGenerator`.
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
/// Number of channels to write. Governs `_result` row count.
|
||||
@@ -159,18 +159,9 @@ public enum Out {
|
||||
let ch: Int = _resolvedChannelCount(bus)
|
||||
self._channels = ch
|
||||
super.init(bus: bus.index, source: source, maxChannels: bus.channelCount, channels: ch)
|
||||
_setupSubBlockBuffer(channels: ch)
|
||||
_registerAsRootIfBuilding()
|
||||
}
|
||||
|
||||
/// Bypasses the `ControlGenerator` sub-block loop so the bus write happens exactly
|
||||
/// once per audio block regardless of `controlBlockSize`.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
|
||||
@@ -169,9 +169,9 @@ public enum ReplaceOut {
|
||||
/// ``ControlBus`` (clamped to `channelCount`). An ``AudioBus`` traps; use ``ReplaceOut/Audio``.
|
||||
/// - source: Signal to write. The last sample of each channel block is
|
||||
/// written to the corresponding control bus.
|
||||
public final class Control: _Base, ControlGenerator, RootRegistering {
|
||||
public final class Control: _Base, BlockRateControlGenerator, RootRegistering {
|
||||
|
||||
/// Satisfies ControlGenerator protocol requirement — unused, Control overrides calculatedSamples.
|
||||
/// Satisfies ControlGenerator protocol requirement — unused; Control conforms to `BlockRateControlGenerator`.
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
/// Number of channels to write. Governs `_result` row count.
|
||||
@@ -199,18 +199,9 @@ public enum ReplaceOut {
|
||||
let ch: Int = _resolvedChannelCount(bus)
|
||||
self._channels = ch
|
||||
super.init(bus: bus.index, source: source, maxChannels: bus.channelCount, channels: ch)
|
||||
_setupSubBlockBuffer(channels: ch)
|
||||
_registerAsRootIfBuilding()
|
||||
}
|
||||
|
||||
/// Bypasses the `ControlGenerator` sub-block loop so the bus write happens
|
||||
/// exactly once per audio block regardless of `controlBlockSize`.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
|
||||
@@ -102,4 +102,61 @@ public class ChaoticBase: GeneratorBase {
|
||||
_h2 = iterate()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Shared render bodies
|
||||
|
||||
/// Ramp-target state for the `Control` render (the audio-block value the next
|
||||
/// block ramps from). Lives on the base so `renderControlBlock` can own the
|
||||
/// whole body; unused by `Audio`.
|
||||
var _rampTarget: Double = 0.0
|
||||
|
||||
/// `ControlGenerator`'s ramp origin. Declared here so `renderControlBlock` can
|
||||
/// update it; `Control` subclasses inherit it to satisfy the protocol, `Audio`
|
||||
/// leaves it unused.
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
/// Snapshot the map's per-block parameters into the fields `iterate()` reads.
|
||||
/// Overridden by maps that have parameters (Hénon's `a`/`b`, …); the default is
|
||||
/// a no-op for parameterless maps (e.g. Gbman).
|
||||
func readParams(graph: SynthGraph) {}
|
||||
|
||||
/// Canonical `Audio._computeSamples` body: read params, prime the ring, then
|
||||
/// bridge each sample between map iterations at `freq`. Shared by every concrete
|
||||
/// chaotic `Audio`.
|
||||
func renderAudioBlock(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
readParams(graph: graph)
|
||||
primeIfNeeded()
|
||||
let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate)
|
||||
|
||||
for i: Int in 0..<count {
|
||||
_result[0][i] = chaoticInterpolate(_interpolation, phase: _phase,
|
||||
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
|
||||
advancePhase(by: dphase)
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
/// Canonical `Control._computeSamples` body: advance the map by one audio block
|
||||
/// and ramp from the previous block value to the new one. Shared by every
|
||||
/// concrete chaotic `Control`.
|
||||
func renderControlBlock(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
readParams(graph: graph)
|
||||
primeIfNeeded()
|
||||
let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate)
|
||||
advancePhase(by: dphase * Double(count))
|
||||
let target: Double = chaoticInterpolate(_interpolation, phase: _phase,
|
||||
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
|
||||
|
||||
let rampStart: Double = _rampTarget
|
||||
_rampTarget = target
|
||||
previousOutputValue = fillRampedResult(
|
||||
into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,8 +56,7 @@ public enum CuspStepped {
|
||||
}
|
||||
|
||||
/// Snapshot the per-block parameters into the fields `iterate()` reads.
|
||||
@inline(__always)
|
||||
func readParams(graph: SynthGraph) {
|
||||
override func readParams(graph: SynthGraph) {
|
||||
_a = aInput.floatValue(graph: graph)
|
||||
_b = bInput.floatValue(graph: graph)
|
||||
}
|
||||
@@ -100,20 +99,7 @@ public enum CuspStepped {
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
readParams(graph: graph)
|
||||
primeIfNeeded()
|
||||
let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate)
|
||||
|
||||
for i: Int in 0..<count {
|
||||
_result[0][i] = chaoticInterpolate(_interpolation, phase: _phase,
|
||||
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
|
||||
advancePhase(by: dphase)
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
return renderAudioBlock(graph: graph, count: count)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,10 +116,7 @@ public enum CuspStepped {
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 0.0
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
|
||||
@@ -156,30 +139,12 @@ public enum CuspStepped {
|
||||
) {
|
||||
super.init(freq: freq, a: a, b: b, xi: xi,
|
||||
interpolation: interpolation, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
// Bypass sub-block loop: the map advances exactly one audio block per call.
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
readParams(graph: graph)
|
||||
primeIfNeeded()
|
||||
let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate)
|
||||
advancePhase(by: dphase * Double(count))
|
||||
let target: Double = chaoticInterpolate(_interpolation, phase: _phase,
|
||||
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
|
||||
|
||||
let rampStart: Double = _rampTarget
|
||||
_rampTarget = target
|
||||
previousOutputValue = fillRampedResult(
|
||||
into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
return renderControlBlock(graph: graph, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,8 +70,7 @@ public enum FBSineStepped {
|
||||
}
|
||||
|
||||
/// Snapshot the per-block parameters into the fields `iterate()` reads.
|
||||
@inline(__always)
|
||||
func readParams(graph: SynthGraph) {
|
||||
override func readParams(graph: SynthGraph) {
|
||||
_im = imInput.floatValue(graph: graph)
|
||||
_fb = fbInput.floatValue(graph: graph)
|
||||
_a = aInput.floatValue(graph: graph)
|
||||
@@ -125,20 +124,7 @@ public enum FBSineStepped {
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
readParams(graph: graph)
|
||||
primeIfNeeded()
|
||||
let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate)
|
||||
|
||||
for i: Int in 0..<count {
|
||||
_result[0][i] = chaoticInterpolate(_interpolation, phase: _phase,
|
||||
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
|
||||
advancePhase(by: dphase)
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
return renderAudioBlock(graph: graph, count: count)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,10 +144,7 @@ public enum FBSineStepped {
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 0.0
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
|
||||
@@ -190,30 +173,12 @@ public enum FBSineStepped {
|
||||
) {
|
||||
super.init(freq: freq, im: im, fb: fb, a: a, c: c, xi: xi, yi: yi,
|
||||
interpolation: interpolation, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
// Bypass sub-block loop: the map advances exactly one audio block per call.
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
readParams(graph: graph)
|
||||
primeIfNeeded()
|
||||
let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate)
|
||||
advancePhase(by: dphase * Double(count))
|
||||
let target: Double = chaoticInterpolate(_interpolation, phase: _phase,
|
||||
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
|
||||
|
||||
let rampStart: Double = _rampTarget
|
||||
_rampTarget = target
|
||||
previousOutputValue = fillRampedResult(
|
||||
into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
return renderControlBlock(graph: graph, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,19 +83,7 @@ public enum GbmanStepped {
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
primeIfNeeded()
|
||||
let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate)
|
||||
|
||||
for i: Int in 0..<count {
|
||||
_result[0][i] = chaoticInterpolate(_interpolation, phase: _phase,
|
||||
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
|
||||
advancePhase(by: dphase)
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
return renderAudioBlock(graph: graph, count: count)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,10 +99,7 @@ public enum GbmanStepped {
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 0.0
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
|
||||
@@ -135,29 +120,12 @@ public enum GbmanStepped {
|
||||
) {
|
||||
super.init(freq: freq, xi: xi, yi: yi,
|
||||
interpolation: interpolation, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
// Bypass sub-block loop: the map advances exactly one audio block per call.
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
primeIfNeeded()
|
||||
let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate)
|
||||
advancePhase(by: dphase * Double(count))
|
||||
let target: Double = chaoticInterpolate(_interpolation, phase: _phase,
|
||||
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
|
||||
|
||||
let rampStart: Double = _rampTarget
|
||||
_rampTarget = target
|
||||
previousOutputValue = fillRampedResult(
|
||||
into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
return renderControlBlock(graph: graph, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,8 +58,7 @@ public enum HenonStepped {
|
||||
}
|
||||
|
||||
/// Snapshot the per-block parameters into the fields `iterate()` reads.
|
||||
@inline(__always)
|
||||
func readParams(graph: SynthGraph) {
|
||||
override func readParams(graph: SynthGraph) {
|
||||
_a = aInput.floatValue(graph: graph)
|
||||
_b = bInput.floatValue(graph: graph)
|
||||
}
|
||||
@@ -105,20 +104,7 @@ public enum HenonStepped {
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
readParams(graph: graph)
|
||||
primeIfNeeded()
|
||||
let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate)
|
||||
|
||||
for i: Int in 0..<count {
|
||||
_result[0][i] = chaoticInterpolate(_interpolation, phase: _phase,
|
||||
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
|
||||
advancePhase(by: dphase)
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
return renderAudioBlock(graph: graph, count: count)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,10 +122,7 @@ public enum HenonStepped {
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 0.0
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
|
||||
@@ -164,30 +147,12 @@ public enum HenonStepped {
|
||||
) {
|
||||
super.init(freq: freq, a: a, b: b, x0: x0, x1: x1,
|
||||
interpolation: interpolation, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
// Bypass sub-block loop: the map advances exactly one audio block per call.
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
readParams(graph: graph)
|
||||
primeIfNeeded()
|
||||
let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate)
|
||||
advancePhase(by: dphase * Double(count))
|
||||
let target: Double = chaoticInterpolate(_interpolation, phase: _phase,
|
||||
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
|
||||
|
||||
let rampStart: Double = _rampTarget
|
||||
_rampTarget = target
|
||||
previousOutputValue = fillRampedResult(
|
||||
into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
return renderControlBlock(graph: graph, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,8 +71,7 @@ public enum LatoocarfianStepped {
|
||||
}
|
||||
|
||||
/// Snapshot the per-block parameters into the fields `iterate()` reads.
|
||||
@inline(__always)
|
||||
func readParams(graph: SynthGraph) {
|
||||
override func readParams(graph: SynthGraph) {
|
||||
_a = aInput.floatValue(graph: graph)
|
||||
_b = bInput.floatValue(graph: graph)
|
||||
_c = cInput.floatValue(graph: graph)
|
||||
@@ -126,20 +125,7 @@ public enum LatoocarfianStepped {
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
readParams(graph: graph)
|
||||
primeIfNeeded()
|
||||
let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate)
|
||||
|
||||
for i: Int in 0..<count {
|
||||
_result[0][i] = chaoticInterpolate(_interpolation, phase: _phase,
|
||||
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
|
||||
advancePhase(by: dphase)
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
return renderAudioBlock(graph: graph, count: count)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,10 +145,7 @@ public enum LatoocarfianStepped {
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 0.0
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
|
||||
@@ -191,30 +174,12 @@ public enum LatoocarfianStepped {
|
||||
) {
|
||||
super.init(freq: freq, a: a, b: b, c: c, d: d, xi: xi, yi: yi,
|
||||
interpolation: interpolation, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
// Bypass sub-block loop: the map advances exactly one audio block per call.
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
readParams(graph: graph)
|
||||
primeIfNeeded()
|
||||
let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate)
|
||||
advancePhase(by: dphase * Double(count))
|
||||
let target: Double = chaoticInterpolate(_interpolation, phase: _phase,
|
||||
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
|
||||
|
||||
let rampStart: Double = _rampTarget
|
||||
_rampTarget = target
|
||||
previousOutputValue = fillRampedResult(
|
||||
into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
return renderControlBlock(graph: graph, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,8 +61,7 @@ public enum LinCongStepped {
|
||||
}
|
||||
|
||||
/// Snapshot the per-block parameters into the fields `iterate()` reads.
|
||||
@inline(__always)
|
||||
func readParams(graph: SynthGraph) {
|
||||
override func readParams(graph: SynthGraph) {
|
||||
_a = aInput.floatValue(graph: graph)
|
||||
_c = cInput.floatValue(graph: graph)
|
||||
_m = mInput.floatValue(graph: graph)
|
||||
@@ -109,20 +108,7 @@ public enum LinCongStepped {
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
readParams(graph: graph)
|
||||
primeIfNeeded()
|
||||
let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate)
|
||||
|
||||
for i: Int in 0..<count {
|
||||
_result[0][i] = chaoticInterpolate(_interpolation, phase: _phase,
|
||||
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
|
||||
advancePhase(by: dphase)
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
return renderAudioBlock(graph: graph, count: count)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,10 +126,7 @@ public enum LinCongStepped {
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 0.0
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
|
||||
@@ -168,30 +151,12 @@ public enum LinCongStepped {
|
||||
) {
|
||||
super.init(freq: freq, a: a, c: c, m: m, xi: xi,
|
||||
interpolation: interpolation, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
// Bypass sub-block loop: the map advances exactly one audio block per call.
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
readParams(graph: graph)
|
||||
primeIfNeeded()
|
||||
let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate)
|
||||
advancePhase(by: dphase * Double(count))
|
||||
let target: Double = chaoticInterpolate(_interpolation, phase: _phase,
|
||||
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
|
||||
|
||||
let rampStart: Double = _rampTarget
|
||||
_rampTarget = target
|
||||
previousOutputValue = fillRampedResult(
|
||||
into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
return renderControlBlock(graph: graph, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,8 +76,7 @@ public enum LorenzLinear {
|
||||
}
|
||||
|
||||
/// Snapshot the per-block parameters into the fields `iterate()` reads.
|
||||
@inline(__always)
|
||||
func readParams(graph: SynthGraph) {
|
||||
override func readParams(graph: SynthGraph) {
|
||||
_s = sInput.floatValue(graph: graph)
|
||||
_r = rInput.floatValue(graph: graph)
|
||||
_b = bInput.floatValue(graph: graph)
|
||||
@@ -134,20 +133,7 @@ public enum LorenzLinear {
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
readParams(graph: graph)
|
||||
primeIfNeeded()
|
||||
let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate)
|
||||
|
||||
for i: Int in 0..<count {
|
||||
_result[0][i] = chaoticInterpolate(_interpolation, phase: _phase,
|
||||
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
|
||||
advancePhase(by: dphase)
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
return renderAudioBlock(graph: graph, count: count)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,10 +154,7 @@ public enum LorenzLinear {
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.linear`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 0.0
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
|
||||
@@ -202,30 +185,12 @@ public enum LorenzLinear {
|
||||
) {
|
||||
super.init(freq: freq, s: s, r: r, b: b, h: h, xi: xi, yi: yi, zi: zi,
|
||||
interpolation: interpolation, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
// Bypass sub-block loop: the map advances exactly one audio block per call.
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
readParams(graph: graph)
|
||||
primeIfNeeded()
|
||||
let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate)
|
||||
advancePhase(by: dphase * Double(count))
|
||||
let target: Double = chaoticInterpolate(_interpolation, phase: _phase,
|
||||
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
|
||||
|
||||
let rampStart: Double = _rampTarget
|
||||
_rampTarget = target
|
||||
previousOutputValue = fillRampedResult(
|
||||
into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
return renderControlBlock(graph: graph, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,8 +59,7 @@ public enum QuadStepped {
|
||||
}
|
||||
|
||||
/// Snapshot the per-block parameters into the fields `iterate()` reads.
|
||||
@inline(__always)
|
||||
func readParams(graph: SynthGraph) {
|
||||
override func readParams(graph: SynthGraph) {
|
||||
_a = aInput.floatValue(graph: graph)
|
||||
_b = bInput.floatValue(graph: graph)
|
||||
_c = cInput.floatValue(graph: graph)
|
||||
@@ -107,20 +106,7 @@ public enum QuadStepped {
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
readParams(graph: graph)
|
||||
primeIfNeeded()
|
||||
let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate)
|
||||
|
||||
for i: Int in 0..<count {
|
||||
_result[0][i] = chaoticInterpolate(_interpolation, phase: _phase,
|
||||
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
|
||||
advancePhase(by: dphase)
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
return renderAudioBlock(graph: graph, count: count)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,10 +124,7 @@ public enum QuadStepped {
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 0.0
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
|
||||
@@ -166,30 +149,12 @@ public enum QuadStepped {
|
||||
) {
|
||||
super.init(freq: freq, a: a, b: b, c: c, xi: xi,
|
||||
interpolation: interpolation, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
// Bypass sub-block loop: the map advances exactly one audio block per call.
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
readParams(graph: graph)
|
||||
primeIfNeeded()
|
||||
let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate)
|
||||
advancePhase(by: dphase * Double(count))
|
||||
let target: Double = chaoticInterpolate(_interpolation, phase: _phase,
|
||||
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
|
||||
|
||||
let rampStart: Double = _rampTarget
|
||||
_rampTarget = target
|
||||
previousOutputValue = fillRampedResult(
|
||||
into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
return renderControlBlock(graph: graph, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,8 +56,7 @@ public enum StandardStepped {
|
||||
}
|
||||
|
||||
/// Snapshot the per-block parameter into the field `iterate()` reads.
|
||||
@inline(__always)
|
||||
func readParams(graph: SynthGraph) {
|
||||
override func readParams(graph: SynthGraph) {
|
||||
_k = kInput.floatValue(graph: graph)
|
||||
}
|
||||
}
|
||||
@@ -99,20 +98,7 @@ public enum StandardStepped {
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
readParams(graph: graph)
|
||||
primeIfNeeded()
|
||||
let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate)
|
||||
|
||||
for i: Int in 0..<count {
|
||||
_result[0][i] = chaoticInterpolate(_interpolation, phase: _phase,
|
||||
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
|
||||
advancePhase(by: dphase)
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
return renderAudioBlock(graph: graph, count: count)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,10 +115,7 @@ public enum StandardStepped {
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 0.0
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
|
||||
@@ -155,30 +138,12 @@ public enum StandardStepped {
|
||||
) {
|
||||
super.init(freq: freq, k: k, xi: xi, yi: yi,
|
||||
interpolation: interpolation, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
// Bypass sub-block loop: the map advances exactly one audio block per call.
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
readParams(graph: graph)
|
||||
primeIfNeeded()
|
||||
let dphase: Double = stepRate(freq: _freqInput.floatValue(graph: graph), sampleRate: graph.engine.sampleRate)
|
||||
advancePhase(by: dphase * Double(count))
|
||||
let target: Double = chaoticInterpolate(_interpolation, phase: _phase,
|
||||
hM1: _hM1, h0: _h0, h1: _h1, h2: _h2)
|
||||
|
||||
let rampStart: Double = _rampTarget
|
||||
_rampTarget = target
|
||||
previousOutputValue = fillRampedResult(
|
||||
into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
return renderControlBlock(graph: graph, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,7 +180,13 @@ public final class DelayLine: GeneratorBase, AudioGenerator {
|
||||
apPrev = out
|
||||
dstP[i] = out
|
||||
} else {
|
||||
apPrev = 0
|
||||
// frac == 0: the output is exactly the integer-delayed sample,
|
||||
// so the allpass interpolator's output here IS yn. Record that
|
||||
// as its previous output. Zeroing apPrev clicks when a modulated
|
||||
// delay crosses an integer boundary; freezing the old value
|
||||
// clicks when the delay dwells on an integer and then moves off.
|
||||
// apPrev = yn tracks the true state and stays click-free in both.
|
||||
apPrev = yn
|
||||
dstP[i] = yn
|
||||
}
|
||||
bufP[writePosLocal & maskLocal] = sampleOrZero(srcP, i, inputCount)
|
||||
|
||||
@@ -270,9 +270,6 @@ public final class DelayLineFeedback: GeneratorBase, AudioGenerator {
|
||||
let frac: Double = d - Double(intD)
|
||||
let yn: Double = bufP[(writePosLocal - intD) & maskLocal]
|
||||
let delayed: Double
|
||||
// When frac == 0, output is exactly yn. Do NOT reset apPrev — that
|
||||
// would introduce a discontinuity (click) when modulated delay crosses an
|
||||
// integer boundary. Preserving state across zero crossings keeps output smooth.
|
||||
if frac > 0 {
|
||||
let eta: Double = (1.0 - frac) / (1.0 + frac)
|
||||
let ynm1: Double = bufP[(writePosLocal - intD - 1) & maskLocal]
|
||||
@@ -280,6 +277,13 @@ public final class DelayLineFeedback: GeneratorBase, AudioGenerator {
|
||||
apPrev = out
|
||||
delayed = out
|
||||
} else {
|
||||
// frac == 0: the output is exactly the integer-delayed sample,
|
||||
// so the allpass interpolator's output here IS yn. Record that
|
||||
// as its previous output. Zeroing apPrev clicks when a modulated
|
||||
// delay crosses an integer boundary; freezing the old value
|
||||
// clicks when the delay dwells on an integer and then moves off.
|
||||
// apPrev = yn tracks the true state and stays click-free in both.
|
||||
apPrev = yn
|
||||
delayed = yn
|
||||
}
|
||||
let x: Double = sampleOrZero(srcP, i, inputCount)
|
||||
|
||||
@@ -125,7 +125,7 @@ public enum Demand {
|
||||
///
|
||||
/// `floatValue(graph:)` returns `previousOutputValue` without advancing the sequence —
|
||||
/// use the full `calculatedSamples` path for demand evaluation.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
private var _rampTarget: Double = 0.0
|
||||
@@ -136,18 +136,9 @@ public enum Demand {
|
||||
demand: any DemandGenerator
|
||||
) {
|
||||
super.init(trig: trig, reset: reset, demand: demand)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
|
||||
/// Bypasses `ControlGenerator` sub-block loop — trigger detection requires scanning
|
||||
/// the full audio-rate trig input once per block, not per sub-block chunk.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
|
||||
@@ -153,7 +153,7 @@ public enum AmplitudeFollower {
|
||||
/// - input: Signal to track.
|
||||
/// - attackTime: Attack time constant in seconds. Formula: `exp(−1 / (sampleRate × t))`. Practical range 0.001–1.0. Defaults to `0.01`.
|
||||
/// - releaseTime: Release time constant in seconds. Practical range 0.01–5.0. Defaults to `0.1`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 0.0
|
||||
|
||||
@@ -167,17 +167,8 @@ public enum AmplitudeFollower {
|
||||
releaseTime: any ValidGeneratorInput = 0.1
|
||||
) {
|
||||
super.init(in: input, attackTime: attackTime, releaseTime: releaseTime)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
// Bypass sub-block loop: smoothing state must update once per audio block.
|
||||
// Sub-blocking would apply the coeff N times per block, making time constants N× shorter.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
|
||||
@@ -231,7 +231,7 @@ public enum Compressor {
|
||||
/// - release: Release time constant in seconds. Practical range 0.01–5.0. Defaults to `0.1`.
|
||||
/// - kneeWidth: Soft-knee width in dB (0 = hard knee). Must be ≥ 0. Defaults to `0.0`.
|
||||
/// - makeupGain: Output gain in dB applied after compression. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 1.0 // matches _prevGain initial value
|
||||
|
||||
@@ -255,17 +255,8 @@ public enum Compressor {
|
||||
super.init(in: input, threshold: threshold, ratio: ratio,
|
||||
attack: attack, release: release,
|
||||
kneeWidth: kneeWidth, makeupGain: makeupGain)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
// Bypass sub-block loop: _prevGain must advance once per audio block.
|
||||
// Sub-blocking would apply the gain smoother N times per block, shrinking time constants by N×.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
|
||||
@@ -226,7 +226,7 @@ public enum Expander {
|
||||
/// - attack: Attack time constant in seconds. Practical range 0.001–1.0. Defaults to `0.01`.
|
||||
/// - release: Release time constant in seconds. Practical range 0.01–5.0. Defaults to `0.1`.
|
||||
/// - kneeWidth: Soft-knee width in dB (0 = hard knee). Must be ≥ 0. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 1.0 // matches _prevGain initial value
|
||||
|
||||
@@ -247,17 +247,8 @@ public enum Expander {
|
||||
) {
|
||||
super.init(in: input, threshold: threshold, ratio: ratio,
|
||||
attack: attack, release: release, kneeWidth: kneeWidth)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
// Bypass sub-block loop: _prevGain must advance once per audio block.
|
||||
// Sub-blocking would apply the gain smoother N times per block, shrinking time constants by N×.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
|
||||
@@ -43,7 +43,7 @@ public enum ExponentialLine {
|
||||
/// - doneAction: Action taken on completion. Defaults to `.nothing`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: GeneratorBase, ControlGenerator, DoneActionWatchable {
|
||||
public final class Control: GeneratorBase, BlockRateControlGenerator, DoneActionWatchable {
|
||||
let start: Double
|
||||
let end: Double
|
||||
let dur: Double
|
||||
@@ -98,18 +98,10 @@ public enum ExponentialLine {
|
||||
self._rampTarget = start
|
||||
self.previousOutputValue = start
|
||||
super.init()
|
||||
_setupSubBlockBuffer()
|
||||
_registerAutoFreeIfNeeded(doneAction)
|
||||
}
|
||||
|
||||
|
||||
// Bypass sub-block loop: per-audio-block state advancement.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
|
||||
@@ -37,7 +37,7 @@ public enum Line {
|
||||
/// - doneAction: Action taken on completion. Defaults to `.nothing`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: GeneratorBase, ControlGenerator, DoneActionWatchable {
|
||||
public final class Control: GeneratorBase, BlockRateControlGenerator, DoneActionWatchable {
|
||||
let start: Double
|
||||
let end: Double
|
||||
let dur: Double
|
||||
@@ -80,18 +80,10 @@ public enum Line {
|
||||
self._rampTarget = start
|
||||
self.previousOutputValue = start
|
||||
super.init()
|
||||
_setupSubBlockBuffer()
|
||||
_registerAutoFreeIfNeeded(doneAction)
|
||||
}
|
||||
|
||||
|
||||
// Bypass sub-block loop: per-audio-block state advancement.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
|
||||
@@ -54,7 +54,7 @@ public enum RateRamp {
|
||||
/// Defaults to `0.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: GeneratorBase, ControlGenerator {
|
||||
public final class Control: GeneratorBase, BlockRateControlGenerator {
|
||||
let trigInput: any ValidGeneratorInput
|
||||
let rateInput: any ValidGeneratorInput
|
||||
let startInput: any ValidGeneratorInput
|
||||
@@ -95,18 +95,9 @@ public enum RateRamp {
|
||||
self._rateIsGenerator = resolvedRate is any Generator
|
||||
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
super.init()
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
|
||||
// Bypass sub-block loop: scans the full audio-rate trigger block for a ≤0→>0
|
||||
// edge — must run exactly once per audio block, not once per sub-block chunk.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
|
||||
@@ -234,8 +234,14 @@ public final class AllpassFilter: GeneratorBase, AudioGenerator {
|
||||
xD = xOut
|
||||
yD = yOut
|
||||
} else {
|
||||
apPrevIn = 0
|
||||
apPrevOut = 0
|
||||
// frac == 0: both reads are exactly the integer-delayed
|
||||
// samples, so each interpolator's output here IS xn / yn.
|
||||
// Record those as the previous outputs. Zeroing clicks when a
|
||||
// modulated delay crosses an integer boundary; freezing the
|
||||
// old values clicks when the delay dwells on an integer and
|
||||
// then moves off. Tracking the true state stays click-free.
|
||||
apPrevIn = xn
|
||||
apPrevOut = yn
|
||||
xD = xn
|
||||
yD = yn
|
||||
}
|
||||
|
||||
@@ -213,7 +213,13 @@ public final class CombFilter: GeneratorBase, AudioGenerator {
|
||||
apPrev = out
|
||||
delayed = out
|
||||
} else {
|
||||
apPrev = 0
|
||||
// frac == 0: the output is exactly the integer-delayed sample,
|
||||
// so the allpass interpolator's output here IS yn. Record that
|
||||
// as its previous output. Zeroing apPrev clicks when a modulated
|
||||
// delay crosses an integer boundary; freezing the old value
|
||||
// clicks when the delay dwells on an integer and then moves off.
|
||||
// apPrev = yn tracks the true state and stays click-free in both.
|
||||
apPrev = yn
|
||||
delayed = yn
|
||||
}
|
||||
let y: Double = sampleOrZero(srcP, i, n) + g * delayed
|
||||
|
||||
@@ -123,15 +123,15 @@ public enum Decay {
|
||||
|
||||
/// Control-rate leaky integrator.
|
||||
///
|
||||
/// Advances integrator state once per audio block. The sub-block loop is bypassed via
|
||||
/// a `calculatedSamples` override (same pattern as `SVF.Control`).
|
||||
/// Advances integrator state once per audio block. The sub-block loop is bypassed by conforming to
|
||||
/// `BlockRateControlGenerator` (same pattern as `SVF.Control`).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Excitation signal (typically impulses). Each non-zero block value adds to the integrator state.
|
||||
/// - decayTime: Time in seconds for the output to decay by 60 dB. `0` = no memory.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
@@ -147,13 +147,9 @@ public enum Decay {
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, decayTime: decayTime, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
@@ -162,13 +158,7 @@ public enum Decay {
|
||||
let x: Double = inputSource.floatValue(graph: graph)
|
||||
let y: Double = x + b1 * y1
|
||||
y1 = denormalsToZero(y)
|
||||
var fillValue: Double = y
|
||||
_result[0].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
|
||||
}
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
previousOutputValue = _result[0][count - 1]
|
||||
fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,8 +143,8 @@ public enum Decay2 {
|
||||
|
||||
/// Control-rate two-integrator decay with rounded attack.
|
||||
///
|
||||
/// Advances both integrator states once per audio block. The sub-block loop is bypassed via
|
||||
/// a `calculatedSamples` override (same pattern as `SVF.Control`).
|
||||
/// Advances both integrator states once per audio block. The sub-block loop is bypassed by conforming to
|
||||
/// `BlockRateControlGenerator` (same pattern as `SVF.Control`).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Excitation signal (typically impulses).
|
||||
@@ -152,7 +152,7 @@ public enum Decay2 {
|
||||
/// - decayTime: 60 dB decay time of the main decay integrator in seconds. `0` = no decay memory.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
@@ -170,13 +170,9 @@ public enum Decay2 {
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, attackTime: attackTime, decayTime: decayTime, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
@@ -189,13 +185,7 @@ public enum Decay2 {
|
||||
yA1 = denormalsToZero(newYA)
|
||||
yD1 = denormalsToZero(newYD)
|
||||
let y: Double = newYD - newYA
|
||||
var fillValue: Double = y
|
||||
_result[0].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
|
||||
}
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
previousOutputValue = _result[0][count - 1]
|
||||
fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,8 +197,8 @@ public enum Formlet {
|
||||
/// Control-rate FOF-like resonant filter.
|
||||
///
|
||||
/// Advances both resonators once per audio block at the control rate
|
||||
/// (`sampleRate / blockSize`); the sub-block loop is bypassed via a
|
||||
/// `calculatedSamples` override (same pattern as `Lag.Control`).
|
||||
/// (`sampleRate / blockSize`); the sub-block loop is bypassed by conforming to
|
||||
/// `BlockRateControlGenerator` (same pattern as `Lag.Control`).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to excite the resonators.
|
||||
@@ -207,7 +207,7 @@ public enum Formlet {
|
||||
/// - decayTime: Fall time in seconds (60 dB time of the long resonator).
|
||||
/// - mul: Output multiplier applied after synthesis. Defaults to `1.0`.
|
||||
/// - add: Offset added after multiplier. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
@@ -228,13 +228,8 @@ public enum Formlet {
|
||||
) {
|
||||
super.init(input: input, freq: freq, attackTime: attackTime,
|
||||
decayTime: decayTime, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
// Bypass sub-block loop: resonator state advances exactly once per audio block.
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
@@ -256,13 +251,7 @@ public enum Formlet {
|
||||
yAttack2 = denormalsToZero(yAttack1)
|
||||
yAttack1 = denormalsToZero(yAttack)
|
||||
|
||||
var fillValue: Double = yDecay - yAttack
|
||||
_result[0].withUnsafeMutableBufferPointer { (buf: inout UnsafeMutableBufferPointer<Double>) in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
|
||||
}
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
previousOutputValue = _result[0][count - 1]
|
||||
fillHeldResult(into: &_result, value: yDecay - yAttack, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,15 +146,7 @@ public enum Hilbert {
|
||||
let (b0, b1, b2, b3): (Double, Double, Double, Double) = Hilbert.hilbertCoeffB
|
||||
|
||||
// Fetch input block (audio-rate or scalar).
|
||||
let inputSamples: [Double]?
|
||||
let scalarInput: Double
|
||||
if _inputIsGenerator {
|
||||
inputSamples = _inputSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarInput = 0
|
||||
} else {
|
||||
inputSamples = nil
|
||||
scalarInput = _inputSource.floatValue(graph: graph)
|
||||
}
|
||||
let (inputSamples, scalarInput) = resolveGeneratorOrScalar(_inputSource, isGenerator: _inputIsGenerator, graph: graph, count: count)
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double
|
||||
|
||||
@@ -128,8 +128,8 @@ public enum Lag {
|
||||
|
||||
/// Control-rate one-pole exponential smoother.
|
||||
///
|
||||
/// Advances filter state once per audio block. The sub-block loop is bypassed via
|
||||
/// a `calculatedSamples` override (same pattern as `SVF.Control`).
|
||||
/// Advances filter state once per audio block. The sub-block loop is bypassed by conforming to
|
||||
/// `BlockRateControlGenerator` (same pattern as `SVF.Control`).
|
||||
///
|
||||
/// The coefficient is computed at the control rate (`sampleRate / blockSize`); `time`
|
||||
/// stays in seconds and the filter converges in `time` wall-clock seconds regardless
|
||||
@@ -140,7 +140,7 @@ public enum Lag {
|
||||
/// - time: 60 dB lag time in seconds. `0` = transparent (no smoothing).
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
@@ -156,12 +156,6 @@ public enum Lag {
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, time: time, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
@@ -171,13 +165,7 @@ public enum Lag {
|
||||
let x: Double = inputSource.floatValue(graph: graph)
|
||||
let y: Double = b1 * y1 + (1.0 - b1) * x
|
||||
y1 = denormalsToZero(y)
|
||||
var fillValue: Double = y
|
||||
_result[0].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
|
||||
}
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
previousOutputValue = _result[0][count - 1]
|
||||
fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,15 +128,15 @@ public enum Lag2 {
|
||||
|
||||
/// Control-rate two-cascaded one-pole smoother.
|
||||
///
|
||||
/// Advances both filter stages once per audio block. The sub-block loop is bypassed via
|
||||
/// a `calculatedSamples` override (same pattern as `SVF.Control`).
|
||||
/// Advances both filter stages once per audio block. The sub-block loop is bypassed by conforming to
|
||||
/// `BlockRateControlGenerator` (same pattern as `SVF.Control`).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to smooth.
|
||||
/// - time: 60 dB lag time in seconds per stage. `0` = transparent.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
@@ -152,13 +152,9 @@ public enum Lag2 {
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, time: time, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
@@ -170,13 +166,7 @@ public enum Lag2 {
|
||||
let y: Double = b1 * y1b + oneMinusB1 * s1
|
||||
y1a = denormalsToZero(s1)
|
||||
y1b = denormalsToZero(y)
|
||||
var fillValue: Double = y
|
||||
_result[0].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
|
||||
}
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
previousOutputValue = _result[0][count - 1]
|
||||
fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,8 +141,8 @@ public enum Lag2UpDown {
|
||||
|
||||
/// Control-rate two-cascaded asymmetric one-pole smoother.
|
||||
///
|
||||
/// Advances both filter stages once per audio block. The sub-block loop is bypassed via
|
||||
/// a `calculatedSamples` override (same pattern as `SVF.Control`).
|
||||
/// Advances both filter stages once per audio block. The sub-block loop is bypassed by conforming to
|
||||
/// `BlockRateControlGenerator` (same pattern as `SVF.Control`).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to smooth.
|
||||
@@ -150,7 +150,7 @@ public enum Lag2UpDown {
|
||||
/// - lagDown: 60 dB lag time in seconds for falling transitions per stage. `0` = instant.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
@@ -168,13 +168,9 @@ public enum Lag2UpDown {
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, lagUp: lagUp, lagDown: lagDown, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
@@ -188,13 +184,7 @@ public enum Lag2UpDown {
|
||||
let y: Double = sel2 * y1b + (1.0 - sel2) * s1
|
||||
y1a = denormalsToZero(s1)
|
||||
y1b = denormalsToZero(y)
|
||||
var fillValue: Double = y
|
||||
_result[0].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
|
||||
}
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
previousOutputValue = _result[0][count - 1]
|
||||
fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,8 +143,8 @@ public enum LagUpDown {
|
||||
|
||||
/// Control-rate asymmetric one-pole smoother.
|
||||
///
|
||||
/// Advances filter state once per audio block. The sub-block loop is bypassed via
|
||||
/// a `calculatedSamples` override (same pattern as `SVF.Control`).
|
||||
/// Advances filter state once per audio block. The sub-block loop is bypassed by conforming to
|
||||
/// `BlockRateControlGenerator` (same pattern as `SVF.Control`).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to smooth.
|
||||
@@ -152,7 +152,7 @@ public enum LagUpDown {
|
||||
/// - lagDown: 60 dB lag time in seconds for falling transitions. `0` = instant.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
@@ -170,13 +170,9 @@ public enum LagUpDown {
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, lagUp: lagUp, lagDown: lagDown, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
@@ -187,13 +183,7 @@ public enum LagUpDown {
|
||||
let b1: Double = x >= y1 ? b1Up : b1Down
|
||||
let y: Double = b1 * y1 + (1.0 - b1) * x
|
||||
y1 = denormalsToZero(y)
|
||||
var fillValue: Double = y
|
||||
_result[0].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
|
||||
}
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
previousOutputValue = _result[0][count - 1]
|
||||
fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,15 +139,15 @@ public enum LeakDC {
|
||||
|
||||
/// Control-rate one-pole DC blocker.
|
||||
///
|
||||
/// Advances filter state once per audio block. The sub-block loop is bypassed via
|
||||
/// a `calculatedSamples` override (same pattern as `SVF.Control`).
|
||||
/// Advances filter state once per audio block. The sub-block loop is bypassed by conforming to
|
||||
/// `BlockRateControlGenerator` (same pattern as `SVF.Control`).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal from which to remove DC bias.
|
||||
/// - coef: Pole coefficient in `[0, 1)`. Higher values lower the corner frequency. Defaults to `leakDCDefaultControlCoef` (0.9).
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
@@ -163,13 +163,9 @@ public enum LeakDC {
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, coef: coef, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
@@ -178,13 +174,7 @@ public enum LeakDC {
|
||||
let y: Double = x - x1 + c * y1
|
||||
x1 = x
|
||||
y1 = denormalsToZero(y)
|
||||
var fillValue: Double = y
|
||||
_result[0].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
|
||||
}
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
previousOutputValue = _result[0][count - 1]
|
||||
fillHeldResult(into: &_result, value: y, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -261,15 +261,7 @@ public enum MuTronIII {
|
||||
|
||||
// Read input — generator block or scalar fast path (avoids RT allocation in
|
||||
// `Double.calculatedSamples`).
|
||||
let inputSamples: [Double]?
|
||||
let scalarInput: Double
|
||||
if _inputIsGenerator {
|
||||
inputSamples = _inputSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarInput = 0.0
|
||||
} else {
|
||||
inputSamples = nil
|
||||
scalarInput = _inputSource.floatValue(graph: graph)
|
||||
}
|
||||
let (inputSamples, scalarInput) = resolveGeneratorOrScalar(_inputSource, isGenerator: _inputIsGenerator, graph: graph, count: count)
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double
|
||||
@@ -326,7 +318,7 @@ public enum MuTronIII {
|
||||
/// Control-rate Mu-Tron III auto-wah — block-rate envelope and filter evaluation.
|
||||
///
|
||||
/// Advances the envelope follower and Chamberlin SVF state once per audio block.
|
||||
/// The sub-block loop is bypassed via a `calculatedSamples` override — IIR state
|
||||
/// The sub-block loop is bypassed by conforming to `BlockRateControlGenerator` — IIR state
|
||||
/// must advance exactly once per audio block, processing each input sample exactly
|
||||
/// once.
|
||||
///
|
||||
@@ -342,7 +334,7 @@ public enum MuTronIII {
|
||||
/// - releaseTime: Envelope release time in seconds. Defaults to `0.15`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 0.0
|
||||
@@ -379,14 +371,8 @@ public enum MuTronIII {
|
||||
attackTime: attackTime, releaseTime: releaseTime,
|
||||
mul: mul, add: add
|
||||
)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
// Bypass sub-block loop: IIR state (envelope follower + SVF) must advance exactly
|
||||
// once per audio block, processing each input sample exactly once.
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
@@ -439,15 +425,7 @@ public enum MuTronIII {
|
||||
|
||||
// Bypass guarantees `_computeSamples` runs once per audio block, so `count` equals
|
||||
// the full audio block size for input generators.
|
||||
let inputSamples: [Double]?
|
||||
let scalarInput: Double
|
||||
if _inputIsGenerator {
|
||||
inputSamples = _inputSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarInput = 0.0
|
||||
} else {
|
||||
inputSamples = nil
|
||||
scalarInput = _inputSource.floatValue(graph: graph)
|
||||
}
|
||||
let (inputSamples, scalarInput) = resolveGeneratorOrScalar(_inputSource, isGenerator: _inputIsGenerator, graph: graph, count: count)
|
||||
|
||||
// Process all `count` input samples to advance state fully.
|
||||
var lastOut: Double = previousOutputValue
|
||||
|
||||
@@ -180,7 +180,7 @@ public enum SVF {
|
||||
/// Suitable for slow-moving filter sweeps or as a block-rate signal processor.
|
||||
///
|
||||
/// IIR state must advance exactly once per audio block, processing each input sample
|
||||
/// exactly once. The sub-block loop is bypassed via a `calculatedSamples` override
|
||||
/// exactly once. The sub-block loop is bypassed by conforming to `BlockRateControlGenerator`
|
||||
/// (same pattern as `AmplitudeFollower.Control`).
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -192,7 +192,7 @@ public enum SVF {
|
||||
/// divide-by-zero. Defaults to `svfButterworthQ`.
|
||||
/// - mul: Output multiplier applied to all four channels. Defaults to `1.0`.
|
||||
/// - add: Output offset applied to all four channels. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
@@ -216,24 +216,11 @@ public enum SVF {
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, freq: freq, q: q, mul: mul, add: add)
|
||||
// _setupSubBlockBuffer retained defensively; calculatedSamples bypass prevents
|
||||
// sub-block engagement in practice.
|
||||
_setupSubBlockBuffer(channels: svfChannelCount)
|
||||
// No _setupSubBlockBuffer(): BlockRateControlGenerator conformance bypasses the
|
||||
// sub-block loop, so _subBlockBuffer is never read.
|
||||
}
|
||||
|
||||
|
||||
// MARK: - AmplitudeFollower.Control pattern
|
||||
|
||||
// Bypass sub-block loop: IIR state must advance exactly once per audio block,
|
||||
// processing each input sample exactly once. The default sub-block path would
|
||||
// re-read the cached input prefix on every sub-block call, re-processing the
|
||||
// same audio samples N times instead of advancing through the block.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
|
||||
@@ -155,7 +155,7 @@ public enum Slew {
|
||||
|
||||
/// Control-rate linear slew-rate limiter. Advances one slew step per audio block.
|
||||
///
|
||||
/// Override of `calculatedSamples` bypasses the sub-block loop — the slew step must
|
||||
/// Conforming to `BlockRateControlGenerator` bypasses the sub-block loop — the slew step must
|
||||
/// advance exactly once per audio block. The coefficient is computed at the control rate
|
||||
/// (`sampleRate / blockSize`); `up` and `dn` remain in units per second and produce the
|
||||
/// same wall-clock slew time regardless of block size (matching `Lag.Control`).
|
||||
@@ -168,7 +168,7 @@ public enum Slew {
|
||||
/// - dn: Maximum falling slope in units per second. Defaults to `1.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
@@ -186,16 +186,8 @@ public enum Slew {
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, up: up, dn: dn, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
/// Bypass sub-block loop: slew state must advance exactly once per audio block.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
@@ -222,14 +214,7 @@ public enum Slew {
|
||||
}
|
||||
}
|
||||
|
||||
var fillValue: Double = _state
|
||||
_result[0].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
|
||||
}
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
guard count > 0 else { return _result }
|
||||
previousOutputValue = _result[0][count - 1]
|
||||
fillHeldResult(into: &_result, value: _state, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -269,7 +269,7 @@ public enum Gendy1 {
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
/// - seed: Optional PRNG seed for deterministic output. `nil` uses a time-based seed.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 0.0
|
||||
@@ -313,14 +313,9 @@ public enum Gendy1 {
|
||||
seed: seed,
|
||||
seedMixConstant: 0xFEDC_BA98_1357_2468
|
||||
)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
|
||||
// Bypass sub-block loop: phase position and PRNG must advance exactly once per audio block.
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
@@ -273,7 +273,7 @@ public enum Gendy2 {
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
/// - seed: Optional PRNG seed for deterministic output. `nil` uses a time-based seed.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 0.0
|
||||
@@ -317,14 +317,9 @@ public enum Gendy2 {
|
||||
seed: seed,
|
||||
seedMixConstant: 0xABCD_EF01_2468_1357
|
||||
)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
|
||||
// Bypass sub-block loop: phase position and PRNG must advance exactly once per audio block.
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
@@ -222,7 +222,7 @@ public enum Gendy3 {
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
/// - seed: Optional PRNG seed for deterministic output. `nil` uses a time-based seed.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public final class Control: _Base, BlockRateControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 0.0
|
||||
@@ -256,14 +256,9 @@ public enum Gendy3 {
|
||||
seed: seed,
|
||||
seedMixConstant: 0x0123_4567_FEDC_BA98
|
||||
)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
|
||||
// Bypass sub-block loop: phase position and PRNG must advance exactly once per audio block.
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
@@ -178,59 +178,19 @@ public enum GatedKarplusStrong {
|
||||
let doublingOffset: Int = delayLineCount * 2
|
||||
|
||||
// Read exciter block unconditionally so upstream generator always advances state.
|
||||
let exciterSamples: [Double]?
|
||||
let scalarExciter: Double
|
||||
if _exciterIsGenerator {
|
||||
exciterSamples = _exciterSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarExciter = 0
|
||||
} else {
|
||||
exciterSamples = nil
|
||||
scalarExciter = _exciterSource.floatValue(graph: graph)
|
||||
}
|
||||
let (exciterSamples, scalarExciter) = resolveGeneratorOrScalar(_exciterSource, isGenerator: _exciterIsGenerator, graph: graph, count: count)
|
||||
|
||||
// Read gate block.
|
||||
let gateSamples: [Double]?
|
||||
let scalarGate: Double
|
||||
if _gateIsGenerator {
|
||||
gateSamples = _gateSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarGate = 0
|
||||
} else {
|
||||
gateSamples = nil
|
||||
scalarGate = _gateSource.floatValue(graph: graph)
|
||||
}
|
||||
let (gateSamples, scalarGate) = resolveGeneratorOrScalar(_gateSource, isGenerator: _gateIsGenerator, graph: graph, count: count)
|
||||
|
||||
// Read freq block.
|
||||
let freqSamples: [Double]?
|
||||
let scalarFreq: Double
|
||||
if _freqIsGenerator {
|
||||
freqSamples = _freqSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarFreq = 0
|
||||
} else {
|
||||
freqSamples = nil
|
||||
scalarFreq = _freqSource.floatValue(graph: graph)
|
||||
}
|
||||
let (freqSamples, scalarFreq) = resolveGeneratorOrScalar(_freqSource, isGenerator: _freqIsGenerator, graph: graph, count: count)
|
||||
|
||||
// Read feedback block.
|
||||
let feedbackSamples: [Double]?
|
||||
let scalarFeedback: Double
|
||||
if _feedbackIsGenerator {
|
||||
feedbackSamples = _feedbackSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarFeedback = 0
|
||||
} else {
|
||||
feedbackSamples = nil
|
||||
scalarFeedback = _feedbackSource.floatValue(graph: graph)
|
||||
}
|
||||
let (feedbackSamples, scalarFeedback) = resolveGeneratorOrScalar(_feedbackSource, isGenerator: _feedbackIsGenerator, graph: graph, count: count)
|
||||
|
||||
// Read coef block.
|
||||
let coefSamples: [Double]?
|
||||
let scalarCoef: Double
|
||||
if _coefIsGenerator {
|
||||
coefSamples = _coefSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarCoef = 0
|
||||
} else {
|
||||
coefSamples = nil
|
||||
scalarCoef = _coefSource.floatValue(graph: graph)
|
||||
}
|
||||
let (coefSamples, scalarCoef) = resolveGeneratorOrScalar(_coefSource, isGenerator: _coefIsGenerator, graph: graph, count: count)
|
||||
|
||||
// Per-sample loop.
|
||||
for i: Int in 0..<count {
|
||||
|
||||
@@ -180,59 +180,19 @@ public enum KarplusStrong {
|
||||
let doublingOffset: Int = delayLineCount * 2
|
||||
|
||||
// Read exciter block (unconditionally so upstream generator always advances state).
|
||||
let exciterSamples: [Double]?
|
||||
let scalarExciter: Double
|
||||
if _exciterIsGenerator {
|
||||
exciterSamples = _exciterSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarExciter = 0
|
||||
} else {
|
||||
exciterSamples = nil
|
||||
scalarExciter = _exciterSource.floatValue(graph: graph)
|
||||
}
|
||||
let (exciterSamples, scalarExciter) = resolveGeneratorOrScalar(_exciterSource, isGenerator: _exciterIsGenerator, graph: graph, count: count)
|
||||
|
||||
// Read trigger block.
|
||||
let triggerSamples: [Double]?
|
||||
let scalarTrigger: Double
|
||||
if _triggerIsGenerator {
|
||||
triggerSamples = _triggerSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarTrigger = 0
|
||||
} else {
|
||||
triggerSamples = nil
|
||||
scalarTrigger = _triggerSource.floatValue(graph: graph)
|
||||
}
|
||||
let (triggerSamples, scalarTrigger) = resolveGeneratorOrScalar(_triggerSource, isGenerator: _triggerIsGenerator, graph: graph, count: count)
|
||||
|
||||
// Read freq block.
|
||||
let freqSamples: [Double]?
|
||||
let scalarFreq: Double
|
||||
if _freqIsGenerator {
|
||||
freqSamples = _freqSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarFreq = 0
|
||||
} else {
|
||||
freqSamples = nil
|
||||
scalarFreq = _freqSource.floatValue(graph: graph)
|
||||
}
|
||||
let (freqSamples, scalarFreq) = resolveGeneratorOrScalar(_freqSource, isGenerator: _freqIsGenerator, graph: graph, count: count)
|
||||
|
||||
// Read feedback block.
|
||||
let feedbackSamples: [Double]?
|
||||
let scalarFeedback: Double
|
||||
if _feedbackIsGenerator {
|
||||
feedbackSamples = _feedbackSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarFeedback = 0
|
||||
} else {
|
||||
feedbackSamples = nil
|
||||
scalarFeedback = _feedbackSource.floatValue(graph: graph)
|
||||
}
|
||||
let (feedbackSamples, scalarFeedback) = resolveGeneratorOrScalar(_feedbackSource, isGenerator: _feedbackIsGenerator, graph: graph, count: count)
|
||||
|
||||
// Read coef block.
|
||||
let coefSamples: [Double]?
|
||||
let scalarCoef: Double
|
||||
if _coefIsGenerator {
|
||||
coefSamples = _coefSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarCoef = 0
|
||||
} else {
|
||||
coefSamples = nil
|
||||
scalarCoef = _coefSource.floatValue(graph: graph)
|
||||
}
|
||||
let (coefSamples, scalarCoef) = resolveGeneratorOrScalar(_coefSource, isGenerator: _coefIsGenerator, graph: graph, count: count)
|
||||
|
||||
// Per-sample loop.
|
||||
for i: Int in 0..<count {
|
||||
|
||||
@@ -10,20 +10,7 @@
|
||||
///
|
||||
/// - Parameter signal: Input signal.
|
||||
public enum Abs {
|
||||
public class _Base: GeneratorBase {
|
||||
let inputSource: any ValidGeneratorInput
|
||||
let _mulAdd: MulAddSpec
|
||||
public init(
|
||||
_ signal: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
|
||||
let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput()
|
||||
inputSource = resolvedSignal
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
}
|
||||
}
|
||||
public class _Base: UnaryMathBase {}
|
||||
/// - Parameters:
|
||||
/// - signal: Input signal.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
@@ -71,7 +58,7 @@ public enum Abs {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
var target: Double = Swift.abs(inputSource.floatValue(graph: graph))
|
||||
if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) }
|
||||
target = _mulAdd.applyScalar(target, graph: graph)
|
||||
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -12,20 +12,7 @@ import Foundation
|
||||
///
|
||||
/// - Parameter signal: Input signal.
|
||||
public enum Ceil {
|
||||
public class _Base: GeneratorBase {
|
||||
let inputSource: any ValidGeneratorInput
|
||||
let _mulAdd: MulAddSpec
|
||||
public init(
|
||||
_ signal: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
|
||||
let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput()
|
||||
inputSource = resolvedSignal
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
}
|
||||
}
|
||||
public class _Base: UnaryMathBase {}
|
||||
/// - Parameters:
|
||||
/// - signal: Input signal.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
@@ -73,7 +60,7 @@ public enum Ceil {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
var target: Double = Foundation.ceil(inputSource.floatValue(graph: graph))
|
||||
if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) }
|
||||
target = _mulAdd.applyScalar(target, graph: graph)
|
||||
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -116,10 +116,7 @@ public enum Clip {
|
||||
let lo: Double = loInput.floatValue(graph: graph)
|
||||
let hi: Double = hiInput.floatValue(graph: graph)
|
||||
var target: Double = Swift.max(lo, Swift.min(hi, inputSource.floatValue(graph: graph)))
|
||||
if !_mulAdd.isIdentity {
|
||||
target = target * _mulAdd.mulInput.floatValue(graph: graph)
|
||||
+ _mulAdd.addInput.floatValue(graph: graph)
|
||||
}
|
||||
target = _mulAdd.applyScalar(target, graph: graph)
|
||||
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -13,20 +13,7 @@ import Foundation
|
||||
///
|
||||
/// - Parameter signal: Input signal in radians.
|
||||
public enum Cos {
|
||||
public class _Base: GeneratorBase {
|
||||
let inputSource: any ValidGeneratorInput
|
||||
let _mulAdd: MulAddSpec
|
||||
public init(
|
||||
_ signal: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
|
||||
let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput()
|
||||
inputSource = resolvedSignal
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
}
|
||||
}
|
||||
public class _Base: UnaryMathBase {}
|
||||
/// - Parameters:
|
||||
/// - signal: Input signal in radians.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
@@ -74,7 +61,7 @@ public enum Cos {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
var target: Double = Foundation.cos(inputSource.floatValue(graph: graph))
|
||||
if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) }
|
||||
target = _mulAdd.applyScalar(target, graph: graph)
|
||||
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -15,19 +15,7 @@
|
||||
///
|
||||
/// - Parameter signal: Input value in decibels.
|
||||
public enum DbAmp {
|
||||
public class _Base: GeneratorBase {
|
||||
let inputSource: any ValidGeneratorInput
|
||||
let _mulAdd: MulAddSpec
|
||||
public init(
|
||||
_ signal: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput()
|
||||
inputSource = resolvedSignal
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
}
|
||||
}
|
||||
public class _Base: UnaryMathBase {}
|
||||
|
||||
/// - Parameters:
|
||||
/// - signal: Input value in decibels.
|
||||
@@ -52,9 +40,7 @@ public enum DbAmp {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
var target: Double = dbToAmp(inputSource.floatValue(graph: graph))
|
||||
if !_mulAdd.isIdentity {
|
||||
target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph)
|
||||
}
|
||||
target = _mulAdd.applyScalar(target, graph: graph)
|
||||
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -12,20 +12,7 @@ import Foundation
|
||||
///
|
||||
/// - Parameter signal: Input signal.
|
||||
public enum Exp {
|
||||
public class _Base: GeneratorBase {
|
||||
let inputSource: any ValidGeneratorInput
|
||||
let _mulAdd: MulAddSpec
|
||||
public init(
|
||||
_ signal: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
|
||||
let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput()
|
||||
inputSource = resolvedSignal
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
}
|
||||
}
|
||||
public class _Base: UnaryMathBase {}
|
||||
/// - Parameters:
|
||||
/// - signal: Input signal.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
@@ -73,7 +60,7 @@ public enum Exp {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
var target: Double = Foundation.exp(inputSource.floatValue(graph: graph))
|
||||
if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) }
|
||||
target = _mulAdd.applyScalar(target, graph: graph)
|
||||
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -139,7 +139,7 @@ public enum ExpExp {
|
||||
let logOutRatio: Double = Foundation.log(outHi / outLo)
|
||||
let t: Double = Foundation.log(inputSource.floatValue(graph: graph) / inLo) / logInRange
|
||||
var target: Double = outLo * Foundation.exp(t * logOutRatio)
|
||||
if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) }
|
||||
target = _mulAdd.applyScalar(target, graph: graph)
|
||||
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -138,7 +138,7 @@ public enum ExpLin {
|
||||
let logInRange: Double = Foundation.log(inHi / inLo)
|
||||
let t: Double = Foundation.log(inputSource.floatValue(graph: graph) / inLo) / logInRange
|
||||
var target: Double = outLo + t * (outHi - outLo)
|
||||
if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) }
|
||||
target = _mulAdd.applyScalar(target, graph: graph)
|
||||
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -12,20 +12,7 @@ import Foundation
|
||||
///
|
||||
/// - Parameter signal: Input signal.
|
||||
public enum Floor {
|
||||
public class _Base: GeneratorBase {
|
||||
let inputSource: any ValidGeneratorInput
|
||||
let _mulAdd: MulAddSpec
|
||||
public init(
|
||||
_ signal: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
|
||||
let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput()
|
||||
inputSource = resolvedSignal
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
}
|
||||
}
|
||||
public class _Base: UnaryMathBase {}
|
||||
/// - Parameters:
|
||||
/// - signal: Input signal.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
@@ -73,7 +60,7 @@ public enum Floor {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
var target: Double = Foundation.floor(inputSource.floatValue(graph: graph))
|
||||
if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) }
|
||||
target = _mulAdd.applyScalar(target, graph: graph)
|
||||
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -128,10 +128,7 @@ public enum Fold {
|
||||
let lo: Double = loInput.floatValue(graph: graph)
|
||||
let hi: Double = hiInput.floatValue(graph: graph)
|
||||
var target: Double = Fold._fold(inputSource.floatValue(graph: graph), lo: lo, hi: hi)
|
||||
if !_mulAdd.isIdentity {
|
||||
target = target * _mulAdd.mulInput.floatValue(graph: graph)
|
||||
+ _mulAdd.addInput.floatValue(graph: graph)
|
||||
}
|
||||
target = _mulAdd.applyScalar(target, graph: graph)
|
||||
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -148,10 +148,7 @@ public enum LinExp {
|
||||
// outLo <= 0 produces NaN per IEEE 754.
|
||||
let t: Double = (inputSource.floatValue(graph: graph) - inLo) / inRange
|
||||
var target: Double = outLo * Foundation.exp(t * Foundation.log(outHi / outLo))
|
||||
if !_mulAdd.isIdentity {
|
||||
target = target * _mulAdd.mulInput.floatValue(graph: graph)
|
||||
+ _mulAdd.addInput.floatValue(graph: graph)
|
||||
}
|
||||
target = _mulAdd.applyScalar(target, graph: graph)
|
||||
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -159,10 +159,7 @@ public enum LinLin {
|
||||
let outRange: Double = outHiInput.floatValue(graph: graph) - outLo
|
||||
// inRange == 0 produces NaN/±Inf per IEEE 754 — intentional.
|
||||
var target: Double = outLo + (inputSource.floatValue(graph: graph) - inLo) / inRange * outRange
|
||||
if !_mulAdd.isIdentity {
|
||||
target = target * _mulAdd.mulInput.floatValue(graph: graph)
|
||||
+ _mulAdd.addInput.floatValue(graph: graph)
|
||||
}
|
||||
target = _mulAdd.applyScalar(target, graph: graph)
|
||||
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -12,20 +12,7 @@ import Foundation
|
||||
///
|
||||
/// - Parameter signal: Input signal. Non-positive input produces NaN or −Inf.
|
||||
public enum Log {
|
||||
public class _Base: GeneratorBase {
|
||||
let inputSource: any ValidGeneratorInput
|
||||
let _mulAdd: MulAddSpec
|
||||
public init(
|
||||
_ signal: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
|
||||
let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput()
|
||||
inputSource = resolvedSignal
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
}
|
||||
}
|
||||
public class _Base: UnaryMathBase {}
|
||||
/// - Parameters:
|
||||
/// - signal: Input signal. Non-positive input produces NaN or −Inf.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
@@ -73,7 +60,7 @@ public enum Log {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
var target: Double = Foundation.log(inputSource.floatValue(graph: graph))
|
||||
if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) }
|
||||
target = _mulAdd.applyScalar(target, graph: graph)
|
||||
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -88,7 +88,7 @@ public enum Max {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
var target: Double = Swift.max(inputA.floatValue(graph: graph), inputB.floatValue(graph: graph))
|
||||
if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) }
|
||||
target = _mulAdd.applyScalar(target, graph: graph)
|
||||
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -88,7 +88,7 @@ public enum Min {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
var target: Double = Swift.min(inputA.floatValue(graph: graph), inputB.floatValue(graph: graph))
|
||||
if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph) + _mulAdd.addInput.floatValue(graph: graph) }
|
||||
target = _mulAdd.applyScalar(target, graph: graph)
|
||||
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -105,10 +105,7 @@ public enum Pow {
|
||||
_checkCount(count)
|
||||
var target: Double = Foundation.pow(inputSource.floatValue(graph: graph),
|
||||
expInput.floatValue(graph: graph))
|
||||
if !_mulAdd.isIdentity {
|
||||
target = target * _mulAdd.mulInput.floatValue(graph: graph)
|
||||
+ _mulAdd.addInput.floatValue(graph: graph)
|
||||
}
|
||||
target = _mulAdd.applyScalar(target, graph: graph)
|
||||
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -184,10 +184,7 @@ public enum RangeMapper {
|
||||
let x: Double = inputSource.floatValue(graph: graph)
|
||||
let t: Double = (x + 1.0) * bipolarToUnipolarScale
|
||||
var target: Double = mapScalarRangeCurve(t: t, low: low, high: high, curve: curve)
|
||||
if !_mulAdd.isIdentity {
|
||||
target = target * _mulAdd.mulInput.floatValue(graph: graph)
|
||||
+ _mulAdd.addInput.floatValue(graph: graph)
|
||||
}
|
||||
target = _mulAdd.applyScalar(target, graph: graph)
|
||||
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user