Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 560724d116 | |||
| 63d6e0746f | |||
| c058493a98 | |||
| 8a2eb191a2 | |||
| 676e8d3278 | |||
| 032b7c39d3 | |||
| 73191c958f |
+45
-1
@@ -256,12 +256,14 @@ And `engine.remove(synth)`:
|
||||
|
||||
`remove` returns `Bool` (it unbinds synchronously on successful enqueue), but there is a documented one-`processBlock` window between `remove` and a re-`add` of the same instance — the RT thread needs a block to actually unlink it. If `freeQueue` overflows, the framework logs one warning and leaks that single reference rather than risk the RT thread; a leaked voice is preferable to an audio dropout or crash.
|
||||
|
||||
### 9.1 Actor isolation of the lifecycle (Phase 201)
|
||||
### 9.1 Actor isolation of the lifecycle
|
||||
|
||||
The Swift-concurrency isolation of `Synthesizer` is split along exactly the thread boundary above:
|
||||
|
||||
- **Language side is `@MainActor`.** `SynthesizerBase` is a `@MainActor` class, and the `Synthesizer` protocol declares `build()`, `release(engine:)`, `free(engine:)` as `@MainActor` requirements. Steps 1–4 of the add path (allocate → build → enqueue) and the `engine.add` / `schedule` / `add(position:)` entry points are therefore main-actor-isolated. This is what lets a consumer building under Xcode 26's `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor` default subclass `SynthesizerBase` and override `build()` with **no** concurrency annotations — the consumer's MainActor default now matches the base instead of conflicting with a nonisolated override. (`engine.remove` stays nonisolated — it unbinds via atomics and enqueues a pointer-only event; `_bind` / `_unbind` are nonisolated for the same reason.)
|
||||
|
||||
- **`SynthesizerBase` declares `release(engine:)` / `free(engine:)` as `open` members, not just protocol conformances.** The `Synthesizer` extension supplies defaults for both, but a protocol-extension default is bound **statically** at the conformance — `SynthesizerBase`'s. Were the base to declare no member of its own, a subclass could not `override` them at all, and a subclass method declared without `override` would be invisible to every caller holding an `any Synthesizer`: the call would reach the extension default and throw `.noGate`. That matters because the callers that drive the lifecycle are exactly those existential ones — `Group.release` cascades to children as `any Synthesizer`, freeing any child that throws `.noGate`, so a gated subclass would be hard-freed and its envelope release phase skipped. Declaring both as `open` class members makes the witness a class method, so the call dispatches through the vtable and subclass overrides run. Pinned by `SynthesizerReleaseDispatchTests`.
|
||||
|
||||
- **The RT entry point is `nonisolated`.** `evaluate(graph:count:)` is `nonisolated final` so the render callback (steps 5–6) reaches it with **no actor hop**. It reads exactly two stored properties cross-thread — `parameterTable` (immutable `let`) and `outputGenerators` (written in `build()` on main, read on RT) — both marked `nonisolated(unsafe)`. Their safety rests entirely on the happens-before edge established by the SPSC `pendingQueue` (§2.1): the RT thread cannot observe the node until it dequeues the `.add` event, which the producer enqueued *after* `build()` fully returned on main. No new runtime synchronisation is introduced by the isolation annotations.
|
||||
|
||||
- **`Group` / `ParallelGroup` stay nonisolated.** They satisfy the `@MainActor` `build`/`release`/`free` requirements with less-isolated (nonisolated) witnesses, keeping their RT-owned linked-list / snapshot state reachable from the render thread. `Group.release` installs its self-free poll timer through a `nonisolated` helper so the utility-queue handler does not inherit `@MainActor` (which would trap when it fires off-main).
|
||||
@@ -270,6 +272,48 @@ The Swift-concurrency isolation of `Synthesizer` is split along exactly the thre
|
||||
|
||||
The guarantee is locked by the committed `RegressionFixtures/MainActorConsumer` package, which compiles an unannotated `SynthesizerBase` subclass under `.swiftLanguageMode(.v6)` + `-default-isolation MainActor`.
|
||||
|
||||
### 9.2 Working with the isolation from a routine or task
|
||||
|
||||
A `LyrebirdRoutine` / `LyrebirdTask` body is `@Sendable` and runs on its own background thread. `SynthesizerBase` is `@MainActor`. Those two facts drive every ergonomic question below, so it is worth being precise about **what is actually main-bound, and why**:
|
||||
|
||||
| Step | Main-bound? | Why |
|
||||
|---|---|---|
|
||||
| `init` (allocate the synth) | **Yes** — but for an *ergonomic* reason, not an RT one | See "Why `init` is not `nonisolated`" below |
|
||||
| `build()` (construct the DAG) | **Yes — load-bearing** | Must complete-before the `.add` enqueue; that is the happens-before edge the RT thread relies on (§9.1) |
|
||||
| `engine.add` / `schedule` | **Yes — load-bearing** | `pendingQueue` is SPSC: exactly one producer |
|
||||
| `engine.remove` | No | Unbinds via atomics, enqueues a pointer-only event |
|
||||
| Writing a `@LiveParam` | No — but the *property* is main-isolated | The value itself crosses via a lock-free atomic (see "Mutating parameters") |
|
||||
| `evaluate()` (RT) | No — `nonisolated final` | The render callback must reach it with no actor hop |
|
||||
|
||||
**Constructing a synth inside a body — `ctx.onMain`.** Because a body cannot touch `@MainActor` state directly, the historical idiom was to pre-allocate every synth *outside* the body and capture it (the `BufferDemos` pattern). That forces the set of synths to be known in advance. ``LyrebirdRoutineContext/onMain(_:)`` removes the restriction — it runs a main-actor closure, blocks the body until it returns, and hands the (possibly non-`Sendable`) result back:
|
||||
|
||||
```swift
|
||||
LyrebirdTask.run(engine: engine) { ctx in
|
||||
while ctx.now < 10.0 {
|
||||
let grain: Grain = ctx.onMain { Grain(startPos: nextPos(), rate: nextRate()) }
|
||||
ctx.add(grain) // async hop; grain self-frees via its envelope
|
||||
try ctx.wait(seconds: 0.05) // drift-compensated as usual
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The hop is synchronous, so its cost counts as work between `wait` calls — which `wait(seconds:)` already compensates for by shortening the next sleep. Keep the closure short (build one synth, not a batch): it blocks both the body and the main thread. Note `build()` does **not** run inside `onMain` — it runs later, on main, inside `ctx.add`'s dispatched `engine.add`.
|
||||
|
||||
`onMain` **requires a serviced main thread**, and this is the one way to misuse it. `ctx.add` is fire-and-forget (`DispatchQueue.main.async`) and merely delays if main is busy; `onMain` hops synchronously with no timeout, so if main is never serviced it blocks the body forever with no diagnostic. A GUI run loop services it; so does a CLI parked on `waitUntilComplete()` / `LyrebirdTask.run`, which pump the main run loop for exactly this reason. The trap is `task.start(engine:)` followed by blocking main on something that is not a run loop (a bare `Thread.sleep`, a semaphore wait) — park on `waitUntilComplete()` instead. Re-entering the caller's own thread is *not* a hazard: `lyrebirdRunMainActorMutation` branches on `Thread.isMainThread` and runs the closure inline when already on main, so `onMain` is self-deadlock-free whichever thread calls it.
|
||||
|
||||
**Mutating parameters — `ctx.set`, not property writes.** Construction is *pre-publication*: the synth is thread-local, unshared, and the RT thread cannot reach it, which is what makes hopping to main for it a pure formality. A parameter write is *post-publication*: the synth is live in the tree and the RT thread reads it every block. Safety there comes from `ParameterNode`'s atomic — **not** from isolation. So capture the projected node on main once, then drive it from the body:
|
||||
|
||||
```swift
|
||||
let cutoff: ParameterNode = filter.$cutoff // captured on main
|
||||
LyrebirdTask.run(engine: engine) { ctx in
|
||||
ctx.set(cutoff, to: 1200) // releasing atomic store — no dispatch
|
||||
}
|
||||
```
|
||||
|
||||
`ctx.set` is **not** a main hop: unlike `ctx.add`, it writes the atomic inline on the body's own thread. The only cost is the one-line capture. (`synth.cutoff = 1200` and `synth.$cutoff` are both main-isolated — the property inherits the class's isolation even though `LiveParam` itself is a plain, atomic-backed struct.)
|
||||
|
||||
**Why `init` is not `nonisolated`.** It looks free — the base `init()` is empty, `build()` is not called from it, and a fresh synth is unshared. It is not free. Under `-default-isolation MainActor` a consumer subclass that declares no init gets an *implicit `@MainActor init()`*, which would then override a `nonisolated` base init and fail with `different actor isolation from nonisolated overridden declaration` — breaking every unannotated consumer, i.e. exactly the §9.1 guarantee. The main test suite cannot catch this (it does not build under that flag); `RegressionFixtures/MainActorConsumer` is the only thing that does. **If you are tempted to relax the isolation on `SynthesizerBase.init`, build that fixture first.** `ctx.onMain` exists precisely because it buys the same ergonomics additively, with no isolation change.
|
||||
|
||||
---
|
||||
|
||||
## Where to go deeper
|
||||
|
||||
@@ -31,6 +31,23 @@ git config core.hooksPath .githooks
|
||||
```
|
||||
The `.githooks/pre-commit` hook calls `--check`. Skips silently when `~/.claude/agents/` is absent (contributors without working copies are not blocked). Bypass for one commit with `git commit --no-verify`.
|
||||
|
||||
## Repo Guard Scripts
|
||||
|
||||
These guards catch classes of regression that **`swift build` / `swift test` structurally cannot**. Both are manual/CI (too slow for pre-commit). Run before a release or a merge that touches their surface.
|
||||
|
||||
| Script | Guards | Run when |
|
||||
|---|---|---|
|
||||
| `bash scripts/check-swift6-consumer.sh` | The zero-annotation consumer guarantee — builds `RegressionFixtures/MainActorConsumer` under `.swiftLanguageMode(.v6)` + `-default-isolation MainActor`. The main package **does not build under that flag**, so the test suite cannot catch an isolation regression. | Any change to `SynthesizerBase` / `Synthesizer` actor isolation. Non-negotiable: `swift test` passing is *not* evidence here. |
|
||||
| `bash scripts/check-docc.sh` | New DocC warnings — broken symbol links, ambiguous refs, article/symbol collisions. DocC links pin a symbol's **full signature**, so adding one parameter silently breaks every link to it. Nothing else checks this. | Any change to a public signature, or edits to `.docc` / doc comments. |
|
||||
| `bash scripts/check-doc-impact.sh [range]` | **Reports** (never fails) which docs a diff's public-API changes may have invalidated. Doc rot is usually *caused* by an API change, and a diff-only read cannot find the stale references — they live in files the diff never touches. Run by `/lyrebird_review` step 2b; suppresses refs the compile guard already covers. | Any change to a public signature. |
|
||||
| `bash scripts/check-doc-snippets.sh` | Doc **examples** that stop compiling. `swift build` never sees a code fence and `check-docc.sh` only validates links, so examples rot silently — `engine.add` became throwing and 11 examples kept calling it without `try`; `LyrebirdFloat` was deleted and 75 references outlived it. Both are type errors, so the fences are typechecked against the real API. | Any change to a public signature, or edits to `.docc` / doc comments. |
|
||||
|
||||
`check-docc.sh` is a **ratchet**: it fails on warnings absent from `scripts/docc-warnings-baseline.txt`. That baseline is now **empty** — the catalog is at zero warnings — so in practice any new warning fails the build. Keep it that way; the baseline may only shrink. (`--strict` asserts zero explicitly and is equivalent while the baseline is empty. `--update-baseline` exists for the rare deliberate exception — prefer fixing the link.)
|
||||
|
||||
**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.
|
||||
|
||||
## Task → Doc Map
|
||||
|
||||
**Engine / RT core**
|
||||
@@ -324,6 +341,7 @@ Module-level helpers exist to eliminate repeated boilerplate; inlining any of th
|
||||
- `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)`
|
||||
- `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`).
|
||||
|
||||
Full table, signatures, examples, and the per-generator exceptions (notably `MathGenerators.Control` and the non-standard ControlGenerator ramp paths) live in `docs/protocols/writing-generators.md` §13. That document is the single source of truth — when adding or removing a helper, update §13 and reference it from here.
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ final class BufferDemos: DemoProtocol {
|
||||
|
||||
func runDemo() {
|
||||
// BufferDemos.swift lives at .../Demos/LyrebirdDemo/LyrebirdDemo/Demos/BufferDemos.swift
|
||||
// — 4 components up to reach .../Demos/ where Perc.aiff lives.
|
||||
// — 4 components up to reach .../Demos/ where Mozart.aiff lives.
|
||||
let percURL: URL = URL(fileURLWithPath: #filePath)
|
||||
.deletingLastPathComponent() // .../Demos/
|
||||
.deletingLastPathComponent() // .../LyrebirdDemo/
|
||||
@@ -37,10 +37,6 @@ final class BufferDemos: DemoProtocol {
|
||||
|
||||
let sampleRate: Double = engine.sampleRate
|
||||
|
||||
// SynthesizerBase is @MainActor-isolated. LyrebirdTask.run's body is @Sendable and
|
||||
// non-async, so synth inits must happen BEFORE the closure on the main thread.
|
||||
// runDemo() is reached from main.swift on the main thread, so assumeIsolated is valid.
|
||||
|
||||
let pitchSteps: [(Double, String)] = [
|
||||
(0.5, "0.5 — octave down"),
|
||||
(0.75, "0.75 — minor third down"),
|
||||
@@ -70,27 +66,23 @@ final class BufferDemos: DemoProtocol {
|
||||
(0.33, "0.33 — 3× compression (triple speed, pitch preserved)"),
|
||||
]
|
||||
|
||||
// Pre-construct all synthesizers on the main actor before entering the @Sendable closure.
|
||||
let (demo1, demo2, demo3, pitchRatioNode, demo4Array, demo5Array, demo6Array):
|
||||
(PercPlayBuffer, PercBufferRead, PercPitchShift, ParameterNode,
|
||||
[PercSpectralPitchShift], [PercSpectralStereoDiffuse], [PercTimeStretch]) =
|
||||
MainActor.assumeIsolated {
|
||||
let d1: PercPlayBuffer = PercPlayBuffer(buffer: percBuffer, engineSampleRate: sampleRate)
|
||||
let d2: PercBufferRead = PercBufferRead(buffer: percBuffer)
|
||||
let d3: PercPitchShift = PercPitchShift(buffer: percBuffer, engineSampleRate: sampleRate)
|
||||
let prNode: ParameterNode = d3.$pitchRatio
|
||||
// `runDemo()` is @MainActor (see DemoProtocol), so the @MainActor synths are constructed
|
||||
// directly — no `MainActor.assumeIsolated` wrapping. Build them here, then hand the
|
||||
// resulting instances / live-param node to the @Sendable task body.
|
||||
let demo1: PercPlayBuffer = PercPlayBuffer(buffer: percBuffer, engineSampleRate: sampleRate)
|
||||
let demo2: PercBufferRead = PercBufferRead(buffer: percBuffer)
|
||||
let demo3: PercPitchShift = PercPitchShift(buffer: percBuffer, engineSampleRate: sampleRate)
|
||||
let pitchRatioNode: ParameterNode = demo3.$pitchRatio
|
||||
|
||||
let d4: [PercSpectralPitchShift] = spectralRatios.map { ratio, _ in
|
||||
PercSpectralPitchShift(buffer: percBuffer, pitchRatio: ratio, engineSampleRate: sampleRate)
|
||||
}
|
||||
let d5: [PercSpectralStereoDiffuse] = diffuseSteps.map { amount, _ in
|
||||
PercSpectralStereoDiffuse(buffer: percBuffer, amount: amount, engineSampleRate: sampleRate)
|
||||
}
|
||||
let d6: [PercTimeStretch] = stretchSteps.map { factor, _ in
|
||||
PercTimeStretch(buffer: percBuffer, stretchFactor: factor)
|
||||
}
|
||||
return (d1, d2, d3, prNode, d4, d5, d6)
|
||||
}
|
||||
let demo4Array: [PercSpectralPitchShift] = spectralRatios.map { ratio, _ in
|
||||
PercSpectralPitchShift(buffer: percBuffer, pitchRatio: ratio, engineSampleRate: sampleRate)
|
||||
}
|
||||
let demo5Array: [PercSpectralStereoDiffuse] = diffuseSteps.map { amount, _ in
|
||||
PercSpectralStereoDiffuse(buffer: percBuffer, amount: amount, engineSampleRate: sampleRate)
|
||||
}
|
||||
let demo6Array: [PercTimeStretch] = stretchSteps.map { factor, _ in
|
||||
PercTimeStretch(buffer: percBuffer, stretchFactor: factor)
|
||||
}
|
||||
|
||||
LyrebirdTask.run(engine: engine) { ctx in
|
||||
// Demo 1 — PlayBuffer (looping at native rate)
|
||||
@@ -112,8 +104,7 @@ final class BufferDemos: DemoProtocol {
|
||||
ctx.add(demo3)
|
||||
for (ratio, label) in pitchSteps {
|
||||
print(" pitchRatio \(label)")
|
||||
// Update via ParameterNode.value — nonisolated atomic setter, RT-safe.
|
||||
pitchRatioNode.value = ratio
|
||||
ctx.set(pitchRatioNode, to: ratio) // live-param write from the task body
|
||||
try ctx.wait(seconds: 3)
|
||||
}
|
||||
ctx.remove(demo3)
|
||||
|
||||
@@ -7,5 +7,10 @@
|
||||
import LyrebirdSynth
|
||||
|
||||
protocol DemoProtocol {
|
||||
func runDemo()
|
||||
/// Main-actor-isolated: demos construct `@MainActor` `SynthesizerBase` synths and are launched
|
||||
/// from `main.swift`'s top-level code (which runs on the main actor). Isolating the requirement
|
||||
/// lets conformances build synths and read their `$liveParam` nodes directly — no
|
||||
/// `MainActor.assumeIsolated { … }` wrapping — before handing Sendable references to a
|
||||
/// background `LyrebirdTask`/`LyrebirdRoutine` body.
|
||||
@MainActor func runDemo()
|
||||
}
|
||||
|
||||
@@ -19,19 +19,29 @@ final class ReverbDemo: DemoProtocol {
|
||||
|
||||
let sampleRate: Double = engine.sampleRate
|
||||
|
||||
// SynthesizerBase is @MainActor-isolated. Pre-construct the synth on the main actor
|
||||
// before entering the @Sendable LyrebirdTask closure. runDemo() is reached from
|
||||
// main.swift on the main thread, so assumeIsolated is valid.
|
||||
let reverbDemo: GVerbTest = MainActor.assumeIsolated {
|
||||
GVerbTest(sampleRate: sampleRate)
|
||||
}
|
||||
// `runDemo()` is @MainActor (see DemoProtocol), so the @MainActor synth is constructed and
|
||||
// its live-param node read directly
|
||||
let reverbDemo: GVerbTest = GVerbTest(sampleRate: sampleRate)
|
||||
|
||||
// `$reverbTime` is a Sendable `ParameterNode` — capture it here, then write it from inside
|
||||
// the @Sendable task body (GVerb picks up each change on the next block). The @MainActor
|
||||
// `reverbDemo.reverbTime` property itself is NOT reachable from the task body under Swift 6;
|
||||
// the node is. either grab it outside the task (uncomment below) ...
|
||||
// let reverbTimeParam: ParameterNode = reverbDemo.$reverbTime
|
||||
|
||||
LyrebirdTask.run(engine: engine) { ctx in
|
||||
ctx.tempo = 60.0
|
||||
ctx.add(reverbDemo)
|
||||
try ctx.wait(beats: 6) // could also use seconds
|
||||
// ... or use ctx.onMain inside the task
|
||||
let param: ParameterNode = ctx.onMain {
|
||||
reverbDemo.$reverbTime
|
||||
}
|
||||
try ctx.wait(beats: 2) // hold the starting reverbTime (3.0)
|
||||
ctx.set(param, to: 8.0) // step: jump to a long tail
|
||||
try ctx.wait(beats: 2)
|
||||
try ctx.ramp(param, to: 0.5, beats: 2) // glide: smooth swoosh down to a short tail
|
||||
ctx.remove(reverbDemo)
|
||||
print("\nAll buffer demos complete.")
|
||||
print("\nAll reverb demos complete.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,17 +14,21 @@
|
||||
import LyrebirdSynth
|
||||
|
||||
final class GVerbTest: SynthesizerBase {
|
||||
// A live parameter: `$reverbTime` is a `ParameterNode` (Sendable) that GVerb re-reads every
|
||||
// block, so writing `reverbTime`/`$reverbTime.value` retunes the running reverb. Change it from
|
||||
// the main thread or a `LyrebirdTask`/`LyrebirdRoutine` body — see `ReverbDemo`.
|
||||
@LiveParam var reverbTime: Double = 3.0
|
||||
private let sampleRate: Double
|
||||
|
||||
|
||||
init(sampleRate: Double) {
|
||||
self.sampleRate = sampleRate
|
||||
}
|
||||
|
||||
|
||||
override func build() {
|
||||
let impulse = Impulse.Audio(freq: 0.5)
|
||||
let reverb = GVerb.Audio(source: impulse,
|
||||
roomSize: 70.0,
|
||||
reverbTime: 3.0,
|
||||
reverbTime: $reverbTime, // live ParameterNode, not the baked scalar
|
||||
earlyLevel: 0.4,
|
||||
tailLevel: 0.9,
|
||||
dryLevel: 0.1,
|
||||
|
||||
@@ -9,7 +9,7 @@ import LyrebirdSynth
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
sampleRate: 48000,
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 2,
|
||||
driver: CoreAudioDriver()
|
||||
@@ -22,6 +22,7 @@ do {
|
||||
exit(1)
|
||||
}
|
||||
|
||||
BufferDemos(engine: engine).runDemo()
|
||||
//ReverbDemo(engine: engine).runDemo()
|
||||
// BufferDemos(engine: engine).runDemo()
|
||||
ReverbDemo(engine: engine).runDemo()
|
||||
|
||||
engine.stop()
|
||||
|
||||
@@ -17,7 +17,7 @@ let package = Package(
|
||||
.executableTarget(
|
||||
name: "LyrebirdDemo",
|
||||
dependencies: [
|
||||
.product(name: "Lyrebird", package: "LyrebirdII"),
|
||||
.product(name: "Lyrebird", package: "Lyrebird"),
|
||||
],
|
||||
path: "LyrebirdDemo"
|
||||
),
|
||||
|
||||
@@ -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 = .binDelay
|
||||
private let demo: Demo = .vector
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
|
||||
@@ -9,7 +9,7 @@ import LyrebirdSynth
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
sampleRate: 48000,
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
|
||||
@@ -17,7 +17,7 @@ let package = Package(
|
||||
.executableTarget(
|
||||
name: "LyrebirdNRTDemo",
|
||||
dependencies: [
|
||||
.product(name: "Lyrebird", package: "LyrebirdII"),
|
||||
.product(name: "Lyrebird", package: "Lyrebird"),
|
||||
],
|
||||
path: "LyrebirdNRTDemo"
|
||||
),
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 60;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
E3C000000000000000000007 /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3C000000000000000000006 /* main.swift */; };
|
||||
E3C000000000000000000013 /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = E3C000000000000000000012 /* Lyrebird */; };
|
||||
E3C000000000000000000015 /* SineTone.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3C000000000000000000014 /* SineTone.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
E3C000000000000000000004 /* LyrebirdQuickstartDemo */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = LyrebirdQuickstartDemo; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
E3C000000000000000000006 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
|
||||
E3C000000000000000000014 /* SineTone.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SineTone.swift; sourceTree = "<group>"; };
|
||||
E3C000000000000000000017 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
E3C000000000000000000018 /* LyrebirdQuickstartDemo.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdQuickstartDemo.entitlements; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
E3C000000000000000000009 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
E3C000000000000000000013 /* Lyrebird in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
E3C000000000000000000002 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
E3C000000000000000000005 /* LyrebirdQuickstartDemo */,
|
||||
E3C000000000000000000003 /* Products */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
E3C000000000000000000003 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
E3C000000000000000000004 /* LyrebirdQuickstartDemo */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
E3C000000000000000000005 /* LyrebirdQuickstartDemo */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
E3C000000000000000000006 /* main.swift */,
|
||||
E3C000000000000000000016 /* Synthesizers */,
|
||||
E3C000000000000000000017 /* Info.plist */,
|
||||
E3C000000000000000000018 /* LyrebirdQuickstartDemo.entitlements */,
|
||||
);
|
||||
path = LyrebirdQuickstartDemo;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
E3C000000000000000000016 /* Synthesizers */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
E3C000000000000000000014 /* SineTone.swift */,
|
||||
);
|
||||
path = Synthesizers;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
E3C00000000000000000000A /* LyrebirdQuickstartDemo */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = E3C00000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdQuickstartDemo" */;
|
||||
buildPhases = (
|
||||
E3C000000000000000000008 /* Sources */,
|
||||
E3C000000000000000000009 /* Frameworks */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = LyrebirdQuickstartDemo;
|
||||
packageProductDependencies = (
|
||||
E3C000000000000000000012 /* Lyrebird */,
|
||||
);
|
||||
productName = LyrebirdQuickstartDemo;
|
||||
productReference = E3C000000000000000000004 /* LyrebirdQuickstartDemo */;
|
||||
productType = "com.apple.product-type.tool";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
E3C000000000000000000001 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = 1;
|
||||
LastSwiftUpdateCheck = 1600;
|
||||
LastUpgradeCheck = 1600;
|
||||
TargetAttributes = {
|
||||
E3C00000000000000000000A = {
|
||||
CreatedOnToolsVersion = 16.0;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = E3C00000000000000000000E /* Build configuration list for PBXProject "LyrebirdQuickstartDemo" */;
|
||||
compatibilityVersion = "Xcode 14.0";
|
||||
developmentRegion = en;
|
||||
hasScannedForEncodings = 0;
|
||||
knownRegions = (
|
||||
en,
|
||||
Base,
|
||||
);
|
||||
mainGroup = E3C000000000000000000002;
|
||||
packageReferences = (
|
||||
E3C000000000000000000011 /* XCLocalSwiftPackageReference "../.." */,
|
||||
);
|
||||
productRefGroup = E3C000000000000000000003 /* Products */;
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
E3C00000000000000000000A /* LyrebirdQuickstartDemo */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
E3C000000000000000000008 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
E3C000000000000000000007 /* main.swift in Sources */,
|
||||
E3C000000000000000000015 /* SineTone.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
E3C00000000000000000000C /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdQuickstartDemo/LyrebirdQuickstartDemo.entitlements;
|
||||
CODE_SIGN_IDENTITY = "-";
|
||||
CODE_SIGN_STYLE = Manual;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
INFOPLIST_FILE = LyrebirdQuickstartDemo/Info.plist;
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdQuickstartDemo;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 6.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
E3C00000000000000000000D /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdQuickstartDemo/LyrebirdQuickstartDemo.entitlements;
|
||||
CODE_SIGN_IDENTITY = "-";
|
||||
CODE_SIGN_STYLE = Manual;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
INFOPLIST_FILE = LyrebirdQuickstartDemo/Info.plist;
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdQuickstartDemo;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 6.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
E3C00000000000000000000F /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
CLANG_ANALYZER_NONNULL = YES;
|
||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu17;
|
||||
GCC_DYNAMIC_NO_PIC = NO;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
GCC_PREPROCESSOR_DEFINITIONS = (
|
||||
"DEBUG=1",
|
||||
"$(inherited)",
|
||||
);
|
||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
||||
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
|
||||
MTL_FAST_MATH = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = macosx;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
E3C000000000000000000010 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
CLANG_ANALYZER_NONNULL = YES;
|
||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
ENABLE_NS_ASSERTIONS = NO;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu17;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
||||
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
MTL_FAST_MATH = YES;
|
||||
SDKROOT = macosx;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
E3C00000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdQuickstartDemo" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
E3C00000000000000000000C /* Debug */,
|
||||
E3C00000000000000000000D /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
E3C00000000000000000000E /* Build configuration list for PBXProject "LyrebirdQuickstartDemo" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
E3C00000000000000000000F /* Debug */,
|
||||
E3C000000000000000000010 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
|
||||
/* Begin XCLocalSwiftPackageReference section */
|
||||
E3C000000000000000000011 /* XCLocalSwiftPackageReference "../.." */ = {
|
||||
isa = XCLocalSwiftPackageReference;
|
||||
relativePath = ../..;
|
||||
};
|
||||
/* End XCLocalSwiftPackageReference section */
|
||||
|
||||
/* Begin XCSwiftPackageProductDependency section */
|
||||
E3C000000000000000000012 /* Lyrebird */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = E3C000000000000000000011 /* XCLocalSwiftPackageReference "../.." */;
|
||||
productName = Lyrebird;
|
||||
};
|
||||
/* End XCSwiftPackageProductDependency section */
|
||||
};
|
||||
rootObject = E3C000000000000000000001 /* Project object */;
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "2620"
|
||||
version = "1.7">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES"
|
||||
buildArchitectures = "Automatic">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "E3C00000000000000000000A"
|
||||
BuildableName = "LyrebirdQuickstartDemo"
|
||||
BlueprintName = "LyrebirdQuickstartDemo"
|
||||
ReferencedContainer = "container:LyrebirdQuickstartDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
shouldAutocreateTestPlan = "YES">
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Release"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "E3C00000000000000000000A"
|
||||
BuildableName = "LyrebirdQuickstartDemo"
|
||||
BlueprintName = "LyrebirdQuickstartDemo"
|
||||
ReferencedContainer = "container:LyrebirdQuickstartDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "E3C00000000000000000000A"
|
||||
BuildableName = "LyrebirdQuickstartDemo"
|
||||
BlueprintName = "LyrebirdQuickstartDemo"
|
||||
ReferencedContainer = "container:LyrebirdQuickstartDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>NSDesktopFolderUsageDescription</key>
|
||||
<string>LyrebirdQuickstartDemo writes rendered audio files to the Desktop.</string>
|
||||
<key>NSDocumentsFolderUsageDescription</key>
|
||||
<string>LyrebirdQuickstartDemo writes rendered audio files to Documents.</string>
|
||||
</dict>
|
||||
</plist>
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.app-sandbox</key>
|
||||
<false/>
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,21 @@
|
||||
// SineTone.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
// A Synthesizer is a graph built in `build()`. This one is a single sine
|
||||
// oscillator, scaled down so it isn't harsh, centred to both speakers with
|
||||
// Pan2 and written to output bus 0 (left) / bus 1 (right).
|
||||
//
|
||||
// This is the same synth the `quickstart` CLI template scaffolds:
|
||||
// lyrebird new MyFirstSound --template quickstart
|
||||
final class SineTone: SynthesizerBase {
|
||||
override func build() {
|
||||
let sin: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.2)
|
||||
let pan: Pan2 = Pan2(input: sin, pan: 0)
|
||||
output(bus: 0, source: pan)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// main.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdQuickstartDemo — the shortest path to sound.
|
||||
//
|
||||
// Mirrors the `quickstart` CLI template (`lyrebird new … --template quickstart`):
|
||||
// the engine, a one-oscillator SineTone (see Synthesizers/SineTone.swift), and a
|
||||
// main that starts it, plays a 440 Hz tone for 10 seconds, then stops and exits.
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// Seconds to play before exiting.
|
||||
let quickstartDuration: Double = 5.0
|
||||
|
||||
do {
|
||||
// The engine owns Core Audio and runs the graph on the RT thread.
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
sampleRate: 48000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
)
|
||||
|
||||
try engine.start()
|
||||
let sineTone: SineTone = SineTone()
|
||||
try engine.add(sineTone) // starts sounding immediately
|
||||
|
||||
print("LyrebirdQuickstartDemo: playing a 440 Hz sine for \(Int(quickstartDuration)) seconds…")
|
||||
Thread.sleep(forTimeInterval: quickstartDuration)
|
||||
|
||||
engine.remove(sineTone)
|
||||
|
||||
Thread.sleep(forTimeInterval: 0.1)
|
||||
engine.stop() // closes the device
|
||||
print("Done.")
|
||||
} catch {
|
||||
fputs("Lyrebird quickstart failed to start: \(error)\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"originHash" : "293673d962d3211d0b8d90755b3dd158ce14df67eed9e956cb4457dba015dc09",
|
||||
"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,25 @@
|
||||
// Package.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// swift-tools-version: 6.0
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "LyrebirdQuickstartDemo",
|
||||
platforms: [.macOS(.v15)],
|
||||
dependencies: [
|
||||
.package(path: "../.."),
|
||||
],
|
||||
targets: [
|
||||
.executableTarget(
|
||||
name: "LyrebirdQuickstartDemo",
|
||||
dependencies: [
|
||||
.product(name: "Lyrebird", package: "Lyrebird"),
|
||||
],
|
||||
path: "LyrebirdQuickstartDemo"
|
||||
),
|
||||
]
|
||||
)
|
||||
@@ -17,7 +17,7 @@ let package = Package(
|
||||
.executableTarget(
|
||||
name: "LyrebirdScoreDemo",
|
||||
dependencies: [
|
||||
.product(name: "Lyrebird", package: "LyrebirdII"),
|
||||
.product(name: "Lyrebird", package: "Lyrebird"),
|
||||
],
|
||||
path: "LyrebirdScoreDemo"
|
||||
),
|
||||
|
||||
@@ -100,11 +100,21 @@ Full reference: [`docs/tooling/cli-guide.md`](docs/tooling/cli-guide.md).
|
||||
|
||||
## Generating projects
|
||||
|
||||
**First sound in 30 seconds** — the `quickstart` template is the shortest path from an installed CLI to audio:
|
||||
|
||||
```bash
|
||||
lyrebird new MyFirstSound --template quickstart
|
||||
cd MyFirstSound && lyrebird run # plays a 440 Hz sine for 10 seconds, then exits
|
||||
```
|
||||
|
||||
That's a complete, self-contained Swift Package: a one-oscillator `SineTone`, the engine, and a `main` that starts it, sleeps 10 seconds, and stops. Read it, then reach for the richer templates below.
|
||||
|
||||
`lyrebird new <name> --template <template>` is the single entry point. The templates fall into two groups: **SPM-only** (a `Package.swift` + an `.xcworkspace` that references it — open and run with `swift`/Xcode, no `.xcodeproj`) and **Xcode-project** (ship a real `.xcodeproj`, needed for `.app`/`.appex` bundles, code signing, and iOS).
|
||||
|
||||
| Template | Group | What you get | Driver |
|
||||
|---|---|---|---|
|
||||
| `basic` *(default)* | SPM-only | Minimal engine + `RunLoop.main.run()`. | `CoreAudioDriver` |
|
||||
| `quickstart` | SPM-only | **Fastest sound.** A one-oscillator `SineTone` that plays a 440 Hz tone for 10 seconds and exits — the shortest path to hearing Lyrebird. | `CoreAudioDriver` |
|
||||
| `basic` *(default)* | SPM-only | Minimal engine + `RunLoop.main.run()` (no synth wired yet). | `CoreAudioDriver` |
|
||||
| `demo` | SPM-only | A `SineTone` synth with `@LiveParam` frequency/amplitude. | `CoreAudioDriver` |
|
||||
| `ui-demo` | SPM-only | AppKit window with `@UIParam` knobs + `LyrebirdWindow`. | `CoreAudioDriver` |
|
||||
| `nrt` | SPM-only | Renders to `output.caf`, no hardware needed. | `NRTDriver` |
|
||||
@@ -170,9 +180,9 @@ import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
struct ContentView: View {
|
||||
@StateObject var synth = ToneSynth() // ToneSynth: SynthesizerBase with @UIParam
|
||||
let synth: ToneSynth // ToneSynth: SynthesizerBase with @UIParam
|
||||
var body: some View {
|
||||
ParameterKnob(value: synth.$frequency, in: 50...2000, label: "Freq")
|
||||
ParameterKnob("Freq", node: synth.$frequency, range: 50...2000)
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -347,10 +357,11 @@ From a repo checkout you can equivalently run `bash scripts/install-xcode-templa
|
||||
|
||||
## Reference projects
|
||||
|
||||
The repo ships seven runnable demos in [`Demos/`](Demos/), opened via `Lyrebird.xcworkspace`, covering every template above — start there to see complete, working code:
|
||||
The repo ships eight runnable demos in [`Demos/`](Demos/), opened via `Lyrebird.xcworkspace`, covering every template above — start there to see complete, working code:
|
||||
|
||||
| Demo | Mirrors template |
|
||||
|---|---|
|
||||
| [`LyrebirdQuickstartDemo`](Demos/LyrebirdQuickstartDemo/) | `quickstart` |
|
||||
| [`LyrebirdDemo`](Demos/LyrebirdDemo/) | real-time CLI |
|
||||
| [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | `macos-ui-xcode` |
|
||||
| [`LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/) | `ios-ui` |
|
||||
|
||||
+17
-4
@@ -1,18 +1,29 @@
|
||||
# Lyrebird — Start Here
|
||||
|
||||
Seven demo projects live in this workspace. This guide covers how to open them, what each one does, where to add your own synthesizers, and the gotchas that will bite you if you don't know about them.
|
||||
Eight demo projects live in this workspace. This guide covers how to open them, what each one does, where to add your own synthesizers, and the gotchas that will bite you if you don't know about them.
|
||||
|
||||
---
|
||||
|
||||
## Opening the Workspace
|
||||
|
||||
Open **`Lyrebird.xcworkspace`** — not any individual `.xcodeproj` file. The workspace links all seven demo projects together so they share the local Lyrebird package.
|
||||
Open **`Lyrebird.xcworkspace`** — not any individual `.xcodeproj` file. The workspace links all eight demo projects together so they share the local Lyrebird package.
|
||||
|
||||
Once open, pick a scheme from the scheme picker at the top of the Xcode window and hit Run.
|
||||
|
||||
---
|
||||
|
||||
## The Seven Demos
|
||||
## The Eight Demos
|
||||
|
||||
### LyrebirdQuickstartDemo — Fastest Sound
|
||||
|
||||
The shortest path to hearing Lyrebird. A command-line tool that starts the engine, adds a one-oscillator `SineTone`, plays a 440 Hz tone for 10 seconds through `CoreAudioDriver`, then stops and exits. Start here.
|
||||
|
||||
- **Where the synth lives:** `Demos/LyrebirdQuickstartDemo/LyrebirdQuickstartDemo/Synthesizers/SineTone.swift` — one `build()` with a single `OscSin.Audio` through `Pan2`.
|
||||
- **Wire it up:** `main.swift` is `engine.start()` → `engine.add(SineTone())` → `Thread.sleep(10)` → `engine.stop()`. No `RunLoop` — it self-terminates.
|
||||
- **Run it:** pick the `LyrebirdQuickstartDemo` scheme and hit Run, or from the terminal `cd Demos/LyrebirdQuickstartDemo && swift run`.
|
||||
- **Same as the CLI template:** this mirrors `lyrebird new MyFirstSound --template quickstart`.
|
||||
|
||||
---
|
||||
|
||||
### LyrebirdDemo — Real-Time CLI
|
||||
|
||||
@@ -40,7 +51,9 @@ final class MySynth: SynthesizerBase {
|
||||
@UIParam var amp: Double = 0.5
|
||||
|
||||
override func build() {
|
||||
let sig = OscSin.Audio(freq: freq) * amp
|
||||
// Use the $-projected nodes ($freq / $amp), not the bare values —
|
||||
// the projection is what makes each knob update reach the audio graph live.
|
||||
let sig = OscSin.Audio(freq: $freq) * $amp
|
||||
output(bus: 0, source: Pan2(input: sig, pan: 0))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
# Live coding with `LyrebirdScratchView`
|
||||
|
||||
A SwiftUI scratchpad for hot-swapping snippets through `LyrebirdLiveCompile`.
|
||||
|
||||
## Overview
|
||||
|
||||
`LyrebirdScratchView` pairs an `NSTextView`-backed Swift editor with a `LiveSession`
|
||||
that owns the audio engine. Pressing **⌘↩** wraps the snippet body in the standard
|
||||
harness, shells out to `swiftc`, `dlopen`s the resulting dylib, and calls the
|
||||
snippet's `lyrebird_snippet_entry` with a `SnippetContext` bound to the session.
|
||||
Synthesizers played via `context.play(_:)` are tracked, so the next non-additive
|
||||
run replaces them. **⌘⇧↩** layers a new snippet on top of the prior ones.
|
||||
|
||||
Compile diagnostics from a failing snippet are parsed by `DiagnosticParser`
|
||||
and rendered beneath the editor with line numbers already remapped from the wrapped
|
||||
source back to the user's snippet coordinates.
|
||||
|
||||
The view is macOS-only — `LyrebirdLiveCompile` shells out to `swiftc`, which is
|
||||
unavailable on iOS. The nested `LiveCompile/` sub-package declares
|
||||
`platforms: [.macOS(.v15)]` and cannot be added to an iOS target.
|
||||
|
||||
## Hosting
|
||||
|
||||
```swift
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI // LyrebirdWindow
|
||||
import LyrebirdLiveCompile // LiveSession
|
||||
import LyrebirdLiveCompileUI // LyrebirdScratchView
|
||||
|
||||
let engine = SynthesisEngine(/* … */)
|
||||
try engine.start()
|
||||
|
||||
let session = LiveSession(engine: engine)
|
||||
let window = LyrebirdWindow(title: "Lyrebird Scratch", width: 640, height: 480)
|
||||
window.open {
|
||||
LyrebirdScratchView(session: session)
|
||||
}
|
||||
```
|
||||
|
||||
## Keyboard shortcuts
|
||||
|
||||
| Shortcut | Action |
|
||||
|----------|--------|
|
||||
| ⌘↩ | Compile + run. Removes synths from the previous run before executing. |
|
||||
| ⌘⇧↩ | Compile + run additively. Keeps previously played synths in the engine. |
|
||||
|
||||
The toolbar exposes both as buttons plus a `Clear Synths` button that calls
|
||||
`LiveSession.clearTracked()` directly.
|
||||
|
||||
## Snippet API surface
|
||||
|
||||
A snippet has one local in scope:
|
||||
|
||||
```swift
|
||||
context: SnippetContext
|
||||
```
|
||||
|
||||
`SnippetContext` is intentionally minimal in v1:
|
||||
|
||||
- `context.engine` — the host `SynthesisEngine`.
|
||||
- `context.play(_:)` — add a `Synthesizer` to the engine and register it for
|
||||
cleanup on the next non-additive run.
|
||||
- `context.reportMessage(_:)` — write back to the host (used by tests; handy for
|
||||
`print`-style probes during development).
|
||||
|
||||
## Threading
|
||||
|
||||
All UI is `@MainActor`-isolated. `LiveSession.compileAndRun` is invoked
|
||||
synchronously inside the button action, so the editor freezes for the duration
|
||||
of the `swiftc` invocation (≈ 1 second cold, much faster on warm cache). v1
|
||||
accepts that trade-off; an off-main compile path is on the polish list.
|
||||
|
||||
## Limitations
|
||||
|
||||
- macOS only.
|
||||
- No syntax highlighting, code completion, or line-number gutter (deferred).
|
||||
- Compiled dylibs are leaked by design — types in a loaded snippet may still be
|
||||
referenced by tracked synths; unloading is unsafe.
|
||||
- The host `.app` must not be sandboxed and must allow library validation to be
|
||||
disabled, since `swiftc` is invoked via `Process` and the resulting unsigned
|
||||
dylib is `dlopen`'d.
|
||||
|
||||
## Topics
|
||||
|
||||
- ``LyrebirdScratchView``
|
||||
- ``LyrebirdScratchModel``
|
||||
@@ -0,0 +1,288 @@
|
||||
// LyrebirdScratchMenuController.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
import UniformTypeIdentifiers
|
||||
import LyrebirdSynth
|
||||
import LyrebirdLiveCompile
|
||||
|
||||
/// Builds and installs the macOS application menu bar for a live-coding host
|
||||
/// driven by a `LyrebirdScratchModel`. Owns the action targets so menu items
|
||||
/// stay wired for the lifetime of the controller.
|
||||
@MainActor
|
||||
public final class LyrebirdScratchMenuController: NSObject {
|
||||
|
||||
public let model: LyrebirdScratchModel
|
||||
|
||||
public init(model: LyrebirdScratchModel) {
|
||||
self.model = model
|
||||
}
|
||||
|
||||
/// Construct the full menu bar (App / File / Edit / Run / View / Window /
|
||||
/// Help) and assign it to `NSApplication.shared.mainMenu`.
|
||||
public func installMainMenu(appName: String = "LyrebirdScratchDemo") {
|
||||
let mainMenu: NSMenu = NSMenu()
|
||||
|
||||
mainMenu.addItem(appMenuItem(appName: appName))
|
||||
mainMenu.addItem(fileMenuItem())
|
||||
mainMenu.addItem(editMenuItem())
|
||||
mainMenu.addItem(runMenuItem())
|
||||
mainMenu.addItem(viewMenuItem())
|
||||
mainMenu.addItem(windowMenuItem())
|
||||
|
||||
NSApplication.shared.mainMenu = mainMenu
|
||||
}
|
||||
|
||||
// MARK: App menu
|
||||
|
||||
private func appMenuItem(appName: String) -> NSMenuItem {
|
||||
let item: NSMenuItem = NSMenuItem()
|
||||
let menu: NSMenu = NSMenu(title: appName)
|
||||
menu.addItem(NSMenuItem(title: "About \(appName)",
|
||||
action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)),
|
||||
keyEquivalent: ""))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
let services: NSMenuItem = NSMenuItem(title: "Services", action: nil, keyEquivalent: "")
|
||||
let servicesMenu: NSMenu = NSMenu(title: "Services")
|
||||
services.submenu = servicesMenu
|
||||
NSApplication.shared.servicesMenu = servicesMenu
|
||||
menu.addItem(services)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(NSMenuItem(title: "Hide \(appName)",
|
||||
action: #selector(NSApplication.hide(_:)),
|
||||
keyEquivalent: "h"))
|
||||
let hideOthers: NSMenuItem = NSMenuItem(title: "Hide Others",
|
||||
action: #selector(NSApplication.hideOtherApplications(_:)),
|
||||
keyEquivalent: "h")
|
||||
hideOthers.keyEquivalentModifierMask = [.command, .option]
|
||||
menu.addItem(hideOthers)
|
||||
menu.addItem(NSMenuItem(title: "Show All",
|
||||
action: #selector(NSApplication.unhideAllApplications(_:)),
|
||||
keyEquivalent: ""))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(NSMenuItem(title: "Quit \(appName)",
|
||||
action: #selector(NSApplication.terminate(_:)),
|
||||
keyEquivalent: "q"))
|
||||
item.submenu = menu
|
||||
return item
|
||||
}
|
||||
|
||||
// MARK: File menu
|
||||
|
||||
private func fileMenuItem() -> NSMenuItem {
|
||||
let item: NSMenuItem = NSMenuItem()
|
||||
let menu: NSMenu = NSMenu(title: "File")
|
||||
menu.addItem(target(NSMenuItem(title: "New",
|
||||
action: #selector(newSnippet(_:)),
|
||||
keyEquivalent: "n")))
|
||||
menu.addItem(target(NSMenuItem(title: "Open…",
|
||||
action: #selector(openSnippet(_:)),
|
||||
keyEquivalent: "o")))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(target(NSMenuItem(title: "Save",
|
||||
action: #selector(saveSnippet(_:)),
|
||||
keyEquivalent: "s")))
|
||||
let saveAs: NSMenuItem = NSMenuItem(title: "Save As…",
|
||||
action: #selector(saveSnippetAs(_:)),
|
||||
keyEquivalent: "s")
|
||||
saveAs.keyEquivalentModifierMask = [.command, .shift]
|
||||
menu.addItem(target(saveAs))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(NSMenuItem(title: "Close",
|
||||
action: #selector(NSWindow.performClose(_:)),
|
||||
keyEquivalent: "w"))
|
||||
item.submenu = menu
|
||||
return item
|
||||
}
|
||||
|
||||
// MARK: Edit menu — wires to the first responder so NSTextView gets it
|
||||
|
||||
private func editMenuItem() -> NSMenuItem {
|
||||
let item: NSMenuItem = NSMenuItem()
|
||||
let menu: NSMenu = NSMenu(title: "Edit")
|
||||
menu.addItem(NSMenuItem(title: "Undo",
|
||||
action: Selector(("undo:")),
|
||||
keyEquivalent: "z"))
|
||||
let redo: NSMenuItem = NSMenuItem(title: "Redo",
|
||||
action: Selector(("redo:")),
|
||||
keyEquivalent: "z")
|
||||
redo.keyEquivalentModifierMask = [.command, .shift]
|
||||
menu.addItem(redo)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(NSMenuItem(title: "Cut",
|
||||
action: #selector(NSText.cut(_:)),
|
||||
keyEquivalent: "x"))
|
||||
menu.addItem(NSMenuItem(title: "Copy",
|
||||
action: #selector(NSText.copy(_:)),
|
||||
keyEquivalent: "c"))
|
||||
menu.addItem(NSMenuItem(title: "Paste",
|
||||
action: #selector(NSText.paste(_:)),
|
||||
keyEquivalent: "v"))
|
||||
menu.addItem(NSMenuItem(title: "Select All",
|
||||
action: #selector(NSText.selectAll(_:)),
|
||||
keyEquivalent: "a"))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
let find: NSMenuItem = NSMenuItem(title: "Find…",
|
||||
action: #selector(NSTextView.performFindPanelAction(_:)),
|
||||
keyEquivalent: "f")
|
||||
find.tag = Int(NSFindPanelAction.showFindPanel.rawValue)
|
||||
menu.addItem(find)
|
||||
item.submenu = menu
|
||||
return item
|
||||
}
|
||||
|
||||
// MARK: Run menu
|
||||
|
||||
private func runMenuItem() -> NSMenuItem {
|
||||
let item: NSMenuItem = NSMenuItem()
|
||||
let menu: NSMenu = NSMenu(title: "Run")
|
||||
menu.addItem(target(NSMenuItem(title: "Run",
|
||||
action: #selector(runSnippet(_:)),
|
||||
keyEquivalent: "\r")))
|
||||
let runAdd: NSMenuItem = NSMenuItem(title: "Run Additive",
|
||||
action: #selector(runSnippetAdditive(_:)),
|
||||
keyEquivalent: "\r")
|
||||
runAdd.keyEquivalentModifierMask = [.command, .shift]
|
||||
menu.addItem(target(runAdd))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(target(NSMenuItem(title: "Clear Tracked Synths",
|
||||
action: #selector(clearSynths(_:)),
|
||||
keyEquivalent: "k")))
|
||||
item.submenu = menu
|
||||
return item
|
||||
}
|
||||
|
||||
// MARK: View menu
|
||||
|
||||
private func viewMenuItem() -> NSMenuItem {
|
||||
let item: NSMenuItem = NSMenuItem()
|
||||
let menu: NSMenu = NSMenu(title: "View")
|
||||
let wrap: NSMenuItem = target(NSMenuItem(title: "Wrap Lines",
|
||||
action: #selector(toggleWrap(_:)),
|
||||
keyEquivalent: "l"))
|
||||
wrap.keyEquivalentModifierMask = [.command, .option]
|
||||
menu.addItem(wrap)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
let inc: NSMenuItem = target(NSMenuItem(title: "Increase Font Size",
|
||||
action: #selector(increaseFontSize(_:)),
|
||||
keyEquivalent: "+"))
|
||||
menu.addItem(inc)
|
||||
menu.addItem(target(NSMenuItem(title: "Decrease Font Size",
|
||||
action: #selector(decreaseFontSize(_:)),
|
||||
keyEquivalent: "-")))
|
||||
menu.addItem(target(NSMenuItem(title: "Reset Font Size",
|
||||
action: #selector(resetFontSize(_:)),
|
||||
keyEquivalent: "0")))
|
||||
item.submenu = menu
|
||||
return item
|
||||
}
|
||||
|
||||
// MARK: Window menu
|
||||
|
||||
private func windowMenuItem() -> NSMenuItem {
|
||||
let item: NSMenuItem = NSMenuItem()
|
||||
let menu: NSMenu = NSMenu(title: "Window")
|
||||
menu.addItem(NSMenuItem(title: "Minimize",
|
||||
action: #selector(NSWindow.performMiniaturize(_:)),
|
||||
keyEquivalent: "m"))
|
||||
menu.addItem(NSMenuItem(title: "Zoom",
|
||||
action: #selector(NSWindow.performZoom(_:)),
|
||||
keyEquivalent: ""))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(NSMenuItem(title: "Bring All to Front",
|
||||
action: #selector(NSApplication.arrangeInFront(_:)),
|
||||
keyEquivalent: ""))
|
||||
item.submenu = menu
|
||||
NSApplication.shared.windowsMenu = menu
|
||||
return item
|
||||
}
|
||||
|
||||
// MARK: - Action targets
|
||||
|
||||
private func target(_ item: NSMenuItem) -> NSMenuItem {
|
||||
item.target = self
|
||||
return item
|
||||
}
|
||||
|
||||
@objc private func newSnippet(_ sender: Any?) {
|
||||
model.text = LyrebirdScratchModel.defaultPlaceholder
|
||||
}
|
||||
|
||||
@objc private func openSnippet(_ sender: Any?) {
|
||||
let panel: NSOpenPanel = NSOpenPanel()
|
||||
panel.allowedContentTypes = [.swiftSource]
|
||||
panel.allowsMultipleSelection = false
|
||||
panel.canChooseDirectories = false
|
||||
panel.message = "Open a Lyrebird snippet"
|
||||
if panel.runModal() == .OK, let url: URL = panel.url {
|
||||
do {
|
||||
try model.load(from: url)
|
||||
} catch {
|
||||
model.reportLoadError(url: url, error: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func saveSnippet(_ sender: Any?) {
|
||||
if let url: URL = model.documentURL {
|
||||
do {
|
||||
try model.save(to: url)
|
||||
} catch {
|
||||
model.reportSaveError(url: url, error: error)
|
||||
}
|
||||
return
|
||||
}
|
||||
saveSnippetAs(sender)
|
||||
}
|
||||
|
||||
@objc private func saveSnippetAs(_ sender: Any?) {
|
||||
let panel: NSSavePanel = NSSavePanel()
|
||||
panel.allowedContentTypes = [.swiftSource]
|
||||
panel.nameFieldStringValue = model.documentURL?.lastPathComponent ?? "snippet.swift"
|
||||
panel.message = "Save Lyrebird snippet"
|
||||
if panel.runModal() == .OK, let url: URL = panel.url {
|
||||
do {
|
||||
try model.save(to: url)
|
||||
} catch {
|
||||
model.reportSaveError(url: url, error: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func runSnippet(_ sender: Any?) {
|
||||
Task { @MainActor in _ = await model.run(additive: false) }
|
||||
}
|
||||
|
||||
@objc private func runSnippetAdditive(_ sender: Any?) {
|
||||
Task { @MainActor in _ = await model.run(additive: true) }
|
||||
}
|
||||
|
||||
@objc private func clearSynths(_ sender: Any?) {
|
||||
model.clearTracked()
|
||||
}
|
||||
|
||||
@objc private func toggleWrap(_ sender: Any?) {
|
||||
model.toggleWrapsLines()
|
||||
if let item: NSMenuItem = sender as? NSMenuItem {
|
||||
item.state = model.wrapsLines ? .on : .off
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func increaseFontSize(_ sender: Any?) {
|
||||
model.bumpFontSize(by: 1)
|
||||
}
|
||||
|
||||
@objc private func decreaseFontSize(_ sender: Any?) {
|
||||
model.bumpFontSize(by: -1)
|
||||
}
|
||||
|
||||
@objc private func resetFontSize(_ sender: Any?) {
|
||||
model.resetFontSize()
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,231 @@
|
||||
// LyrebirdScratchModel.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// Backing model for `LyrebirdScratchView`. Owns the editable snippet text, the
|
||||
// most recent compile result, and the host `LiveSession`. Pulled out of the
|
||||
// view so logic can be exercised without instantiating SwiftUI.
|
||||
//
|
||||
// macOS only — wraps `LyrebirdLiveCompile`, which itself is macOS-only.
|
||||
|
||||
#if os(macOS)
|
||||
import Foundation
|
||||
import CoreGraphics
|
||||
import LyrebirdSynth
|
||||
// Re-exported so consumers that link only the `LyrebirdLiveCompileUI` product
|
||||
// (e.g. the LyrebirdScratchDemo app) get the `LyrebirdLiveCompile` API
|
||||
// (`LiveSession`, …) without separately linking the `LyrebirdLiveCompile`
|
||||
// dynamic product — which clashes in Xcode with the static target embed.
|
||||
@_exported import LyrebirdLiveCompile
|
||||
|
||||
/// Observable backing model for `LyrebirdScratchView`.
|
||||
///
|
||||
/// Drives one live-coding editor pane. `run(additive:)` awaits
|
||||
/// `LiveSession.compileAndRunAsync` so the swiftc invocation runs off the main
|
||||
/// actor and the editor stays responsive. ``isCompiling`` flips around the
|
||||
/// await so SwiftUI can disable the Run buttons and surface a "Compiling…"
|
||||
/// status while the dylib build is in flight.
|
||||
@MainActor
|
||||
public final class LyrebirdScratchModel: ObservableObject {
|
||||
|
||||
/// Default placeholder text loaded into a fresh model. Walks the user
|
||||
/// through the two keyboard shortcuts and the in-snippet API surface.
|
||||
/// `nonisolated` so callers in a non-main context (e.g. SwiftUI init's
|
||||
/// default-argument evaluation, which is not implicitly main-actor) can
|
||||
/// reference it without a Swift 6 isolation diagnostic.
|
||||
public nonisolated static let defaultPlaceholder: String = """
|
||||
// ⌘↩ — compile + run (removes synths from the previous run first).
|
||||
// ⌘⇧↩ — additive run (keep previously played synths around).
|
||||
//
|
||||
// The snippet body has `context: SnippetContext` in scope.
|
||||
// `context.engine` → the host `SynthesisEngine`.
|
||||
// `context.play(synth)` → adds a `Synthesizer` and tracks it for cleanup.
|
||||
// `context.reportMessage(_)`→ writes back to the host (useful for `print`-style probes).
|
||||
|
||||
class SineSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let sine = OscSin.Audio(freq: 440, mul: 0.15)
|
||||
let stereo = Pan2(input: sine, pan: 0)
|
||||
output(bus: 0, source: stereo)
|
||||
}
|
||||
}
|
||||
|
||||
let synth = SineSynth()
|
||||
_ = context.play(synth)
|
||||
context.reportMessage("playing 440 Hz sine — stereo, centered")
|
||||
|
||||
"""
|
||||
|
||||
/// Current editor text. View binds to this; user edits flow back here via
|
||||
/// the `NSTextView` delegate inside `LyrebirdScratchView`.
|
||||
@Published public var text: String
|
||||
|
||||
/// Parsed swiftc diagnostics from the last `run(additive:)` invocation.
|
||||
/// Empty when the last run compiled cleanly or has not yet been attempted.
|
||||
@Published public private(set) var diagnostics: [Diagnostic] = []
|
||||
|
||||
/// Single-line human-readable status line shown beneath the editor.
|
||||
/// Updated by `run(additive:)` and `clearTracked()`.
|
||||
@Published public private(set) var statusMessage: String = ""
|
||||
|
||||
/// Mirror of `session.trackedSynthCount`, refreshed after every `run` /
|
||||
/// `clearTracked` call so the toolbar can show the count without polling.
|
||||
@Published public private(set) var trackedSynthCount: Int
|
||||
|
||||
/// `true` while a `run(additive:)` invocation is awaiting the background
|
||||
/// swiftc compile. View code disables Run / Run Additive buttons against
|
||||
/// this so a second compile cannot stack on top of a still-running one.
|
||||
@Published public private(set) var isCompiling: Bool = false
|
||||
|
||||
/// URL of the file the editor text was last saved to or loaded from. `nil`
|
||||
/// when the editor holds unsaved scratch content. The view uses this to
|
||||
/// distinguish a silent overwrite (⌘S) from a Save As… prompt.
|
||||
@Published public private(set) var documentURL: URL?
|
||||
|
||||
/// Editor font size in points. Clamped to `[minFontSize, maxFontSize]`.
|
||||
@Published public var fontSize: CGFloat = 13
|
||||
|
||||
/// When `true`, lines wrap at the editor's right edge instead of scrolling
|
||||
/// horizontally.
|
||||
@Published public var wrapsLines: Bool = true
|
||||
|
||||
public let session: LiveSession
|
||||
|
||||
public nonisolated static let minFontSize: CGFloat = 9
|
||||
public nonisolated static let maxFontSize: CGFloat = 32
|
||||
public nonisolated static let defaultFontSize: CGFloat = 13
|
||||
|
||||
public func bumpFontSize(by delta: CGFloat) {
|
||||
fontSize = max(LyrebirdScratchModel.minFontSize,
|
||||
min(LyrebirdScratchModel.maxFontSize, fontSize + delta))
|
||||
}
|
||||
|
||||
public func resetFontSize() {
|
||||
fontSize = LyrebirdScratchModel.defaultFontSize
|
||||
}
|
||||
|
||||
public func toggleWrapsLines() {
|
||||
wrapsLines.toggle()
|
||||
}
|
||||
|
||||
/// - Parameters:
|
||||
/// - session: Host `LiveSession` the model forwards compile + cleanup
|
||||
/// calls to. Retained for the model's lifetime.
|
||||
/// - initialText: Seed text loaded into `text`. Defaults to
|
||||
/// ``defaultPlaceholder``.
|
||||
public init(
|
||||
session: LiveSession,
|
||||
initialText: String = LyrebirdScratchModel.defaultPlaceholder
|
||||
) {
|
||||
self.session = session
|
||||
self.text = initialText
|
||||
self.trackedSynthCount = session.trackedSynthCount
|
||||
}
|
||||
|
||||
/// Compile and execute the current `text`. Updates `diagnostics`,
|
||||
/// `statusMessage`, `trackedSynthCount`, and ``isCompiling``.
|
||||
///
|
||||
/// Awaits `LiveSession.compileAndRunAsync`, which runs swiftc on a
|
||||
/// `Task.detached`. The view's Run / Run Additive buttons bind to
|
||||
/// ``isCompiling`` and stay disabled until this method returns.
|
||||
///
|
||||
/// - Parameter additive: When `false`, the session removes every
|
||||
/// previously tracked synth before running. When `true`, prior synths
|
||||
/// stay in the engine (⌘⇧↩ in the view).
|
||||
/// - Returns: `true` when the snippet compiled and its entry returned
|
||||
/// without throwing; `false` otherwise.
|
||||
@discardableResult
|
||||
public func run(additive: Bool) async -> Bool {
|
||||
guard !isCompiling else { return false }
|
||||
let body: String = text
|
||||
diagnostics = []
|
||||
statusMessage = "Compiling…"
|
||||
isCompiling = true
|
||||
defer {
|
||||
isCompiling = false
|
||||
trackedSynthCount = session.trackedSynthCount
|
||||
}
|
||||
do {
|
||||
try await session.compileAndRunAsync(body, additive: additive)
|
||||
let mode: String = additive ? "additive" : "replaced"
|
||||
statusMessage = "Ran (\(mode)). Tracked synths: \(session.trackedSynthCount)."
|
||||
return true
|
||||
} catch let sessionError as LiveSessionError {
|
||||
switch sessionError {
|
||||
case .snippetCompileFailed(let diags, let underlying):
|
||||
if diags.isEmpty {
|
||||
diagnostics = [Diagnostic(
|
||||
line: nil,
|
||||
column: 0,
|
||||
severity: .error,
|
||||
message: "\(underlying)",
|
||||
rawLine: 0
|
||||
)]
|
||||
statusMessage = "Compile failed — see diagnostics below."
|
||||
} else {
|
||||
diagnostics = diags
|
||||
let plural: String = diags.count == 1 ? "" : "s"
|
||||
statusMessage = "Compile failed — \(diags.count) diagnostic\(plural)."
|
||||
}
|
||||
case .compilerError(let underlying):
|
||||
statusMessage = "Compiler error: \(underlying)"
|
||||
}
|
||||
return false
|
||||
} catch {
|
||||
statusMessage = "Error: \(error)"
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Forward to `LiveSession.clearTracked()` and refresh `trackedSynthCount`.
|
||||
public func clearTracked() {
|
||||
session.clearTracked()
|
||||
trackedSynthCount = session.trackedSynthCount
|
||||
statusMessage = "Cleared tracked synths."
|
||||
}
|
||||
|
||||
// MARK: - Snippet save / load
|
||||
|
||||
/// Replace `text` with the UTF-8 contents at `url`, set ``documentURL``
|
||||
/// for subsequent saves, and refresh the status line.
|
||||
///
|
||||
/// - Parameter url: File to read. Caller (view) is responsible for the
|
||||
/// `NSOpenPanel` UI; this method does the IO.
|
||||
public func load(from url: URL) throws {
|
||||
let loaded: String = try String(contentsOf: url, encoding: .utf8)
|
||||
text = loaded
|
||||
documentURL = url
|
||||
diagnostics = []
|
||||
statusMessage = "Loaded \(url.lastPathComponent)."
|
||||
}
|
||||
|
||||
/// Write `text` to `url` as UTF-8, set ``documentURL``, refresh status.
|
||||
///
|
||||
/// - Parameter url: Destination. Overwrites if present. Caller drives the
|
||||
/// `NSSavePanel` UI.
|
||||
public func save(to url: URL) throws {
|
||||
try text.write(to: url, atomically: true, encoding: .utf8)
|
||||
documentURL = url
|
||||
statusMessage = "Saved \(url.lastPathComponent)."
|
||||
}
|
||||
|
||||
/// Surface a load failure on the status line without throwing across the
|
||||
/// view layer. Called by the view after `NSOpenPanel` returned a URL that
|
||||
/// `load(from:)` rejected.
|
||||
public func reportLoadError(url: URL, error: Error) {
|
||||
statusMessage = "Load failed (\(url.lastPathComponent)): \(error.localizedDescription)"
|
||||
}
|
||||
|
||||
/// Surface a save failure on the status line without throwing across the
|
||||
/// view layer. Called by the view after `NSSavePanel` returned a URL that
|
||||
/// `save(to:)` rejected.
|
||||
public func reportSaveError(url: URL, error: Error) {
|
||||
statusMessage = "Save failed (\(url.lastPathComponent)): \(error.localizedDescription)"
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,409 @@
|
||||
// LyrebirdScratchView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// `LyrebirdScratchView` — SwiftUI scratchpad editor for live-coded snippets.
|
||||
// Wraps an `NSTextView` for the editor surface, drives a `LyrebirdScratchModel`
|
||||
// for compile state, and surfaces parsed `Diagnostic`s in a scrollable list
|
||||
// below the editor. macOS-only; iOS hosting is deferred (no swiftc on device).
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
import LyrebirdSynth
|
||||
import LyrebirdLiveCompile
|
||||
|
||||
/// SwiftUI scratchpad for live-compiled Lyrebird snippets.
|
||||
///
|
||||
/// Pair with a `LiveSession` that owns the audio engine, drop the view into a
|
||||
/// `LyrebirdWindow`, and ⌘↩ replaces the prior run while ⌘⇧↩ adds to it.
|
||||
/// Diagnostics from a failed compile are listed under the editor with the
|
||||
/// user's snippet-row coordinates already mapped by `DiagnosticParser`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - session: Host `LiveSession` owning the `SynthesisEngine`. Forwarded
|
||||
/// into the backing ``LyrebirdScratchModel``.
|
||||
/// - initialText: Seed text loaded into the editor. Defaults to
|
||||
/// ``LyrebirdScratchModel/defaultPlaceholder``.
|
||||
///
|
||||
/// ## Hosting
|
||||
///
|
||||
/// ```swift
|
||||
/// import LyrebirdUI // LyrebirdWindow
|
||||
/// import LyrebirdLiveCompile // LiveSession
|
||||
/// import LyrebirdLiveCompileUI // LyrebirdScratchView
|
||||
///
|
||||
/// let session = LiveSession(engine: engine)
|
||||
/// let win = LyrebirdWindow(title: "Lyrebird Scratch", width: 640, height: 480)
|
||||
/// win.open { LyrebirdScratchView(session: session) }
|
||||
/// ```
|
||||
///
|
||||
/// ## Threading
|
||||
///
|
||||
/// All UI work is `@MainActor`-isolated. The Run / Run Additive buttons
|
||||
/// dispatch a `Task` that awaits `LyrebirdScratchModel.run(additive:)`, which
|
||||
/// itself awaits `LiveSession.compileAndRunAsync`. The swiftc subprocess runs
|
||||
/// on a background `Task.detached`; the snippet entry then resumes on the
|
||||
/// main actor so it can touch UI-side state. Both Run buttons disable while
|
||||
/// ``LyrebirdScratchModel/isCompiling`` is `true`.
|
||||
@MainActor
|
||||
public struct LyrebirdScratchView: View {
|
||||
|
||||
@StateObject private var model: LyrebirdScratchModel
|
||||
@State private var engineTick: Int = 0
|
||||
private let engineRefresh = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()
|
||||
|
||||
/// Construct with a fresh `LyrebirdScratchModel` wrapping `session`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - session: Host live-coding session owning the audio engine. The view
|
||||
/// does not retain a reference of its own; the wrapped model does.
|
||||
/// - initialText: Seed text loaded into the editor. Defaults to the
|
||||
/// onboarding placeholder explaining the two keyboard shortcuts.
|
||||
public init(
|
||||
session: LiveSession,
|
||||
initialText: String = LyrebirdScratchModel.defaultPlaceholder
|
||||
) {
|
||||
_model = StateObject(wrappedValue: LyrebirdScratchModel(
|
||||
session: session,
|
||||
initialText: initialText
|
||||
))
|
||||
}
|
||||
|
||||
/// Construct against a pre-built model. Lets tests or alternate hosts
|
||||
/// inject a model with custom session, text, or pre-populated state.
|
||||
public init(model: LyrebirdScratchModel) {
|
||||
_model = StateObject(wrappedValue: model)
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
engineBar
|
||||
Divider()
|
||||
ScratchEditor(
|
||||
text: Binding(
|
||||
get: { model.text },
|
||||
set: { model.text = $0 }
|
||||
),
|
||||
fontSize: model.fontSize,
|
||||
wrapsLines: model.wrapsLines
|
||||
)
|
||||
.frame(minHeight: editorMinHeight)
|
||||
Divider()
|
||||
statusBar
|
||||
if !model.diagnostics.isEmpty {
|
||||
Divider()
|
||||
diagnosticsList
|
||||
}
|
||||
}
|
||||
.frame(minWidth: scratchMinWidth, minHeight: scratchMinHeight)
|
||||
.onReceive(engineRefresh) { _ in engineTick &+= 1 }
|
||||
}
|
||||
|
||||
private var engineBar: some View {
|
||||
let engine: SynthesisEngine = model.session.engine
|
||||
return HStack(spacing: toolbarSpacing) {
|
||||
Circle()
|
||||
.fill(engine.isRunning ? Color.green : Color.red)
|
||||
.frame(width: engineDotSize, height: engineDotSize)
|
||||
Text(engine.isRunning ? "engine running" : "engine stopped")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch · CPU \(formatCPU(engine.averageCPU))")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
Spacer().frame(width: 8)
|
||||
Text("synths: \(model.trackedSynthCount)")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.padding(.horizontal, toolbarPadding)
|
||||
.padding(.vertical, 6)
|
||||
.id(engineTick)
|
||||
}
|
||||
|
||||
private func formatCPU(_ value: Double) -> String {
|
||||
String(format: "%.0f%%", value * 100)
|
||||
}
|
||||
|
||||
public func runSnippet(additive: Bool) {
|
||||
Task { @MainActor in
|
||||
_ = await model.run(additive: additive)
|
||||
}
|
||||
}
|
||||
|
||||
public func presentOpenPanel() {
|
||||
let panel: NSOpenPanel = NSOpenPanel()
|
||||
panel.allowedContentTypes = [.swiftSource]
|
||||
panel.allowsMultipleSelection = false
|
||||
panel.canChooseDirectories = false
|
||||
panel.message = "Open a Lyrebird snippet"
|
||||
if panel.runModal() == .OK, let url: URL = panel.url {
|
||||
do {
|
||||
try model.load(from: url)
|
||||
} catch {
|
||||
model.reportLoadError(url: url, error: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func saveOrPromptForLocation() {
|
||||
if let url: URL = model.documentURL {
|
||||
do {
|
||||
try model.save(to: url)
|
||||
} catch {
|
||||
model.reportSaveError(url: url, error: error)
|
||||
}
|
||||
return
|
||||
}
|
||||
presentSavePanel()
|
||||
}
|
||||
|
||||
public func presentSavePanel() {
|
||||
let panel: NSSavePanel = NSSavePanel()
|
||||
panel.allowedContentTypes = [.swiftSource]
|
||||
panel.nameFieldStringValue = model.documentURL?.lastPathComponent ?? "snippet.swift"
|
||||
panel.message = "Save Lyrebird snippet"
|
||||
if panel.runModal() == .OK, let url: URL = panel.url {
|
||||
do {
|
||||
try model.save(to: url)
|
||||
} catch {
|
||||
model.reportSaveError(url: url, error: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var statusBar: some View {
|
||||
HStack {
|
||||
Text(model.statusMessage.isEmpty ? "Ready." : model.statusMessage)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.middle)
|
||||
Spacer()
|
||||
}
|
||||
.padding(.horizontal, statusHPad)
|
||||
.padding(.vertical, statusVPad)
|
||||
}
|
||||
|
||||
private var diagnosticsList: some View {
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: diagnosticRowSpacing) {
|
||||
ForEach(Array(model.diagnostics.enumerated()), id: \.offset) { _, diag in
|
||||
DiagnosticRow(diagnostic: diag)
|
||||
}
|
||||
}
|
||||
.padding(diagnosticListPadding)
|
||||
}
|
||||
.frame(minHeight: diagnosticsMinHeight, maxHeight: diagnosticsMaxHeight)
|
||||
}
|
||||
|
||||
// Layout constants — all in points. Kept private; tuned to match
|
||||
// LyrebirdEngineStatusView's visual density.
|
||||
private let scratchMinWidth: CGFloat = 520
|
||||
private let scratchMinHeight: CGFloat = 420
|
||||
private let editorMinHeight: CGFloat = 240
|
||||
private let toolbarSpacing: CGFloat = 8
|
||||
private let toolbarPadding: CGFloat = 8
|
||||
private let toolbarDividerHeight: CGFloat = 18
|
||||
private let statusHPad: CGFloat = 8
|
||||
private let statusVPad: CGFloat = 4
|
||||
private let diagnosticRowSpacing: CGFloat = 2
|
||||
private let diagnosticListPadding: CGFloat = 8
|
||||
private let diagnosticsMinHeight: CGFloat = 80
|
||||
private let diagnosticsMaxHeight: CGFloat = 200
|
||||
private let engineDotSize: CGFloat = 8
|
||||
}
|
||||
|
||||
/// One row in the diagnostics list. Renders `(line:col)`, severity, and
|
||||
/// message in a compact monospaced row.
|
||||
private struct DiagnosticRow: View {
|
||||
|
||||
let diagnostic: Diagnostic
|
||||
|
||||
var body: some View {
|
||||
HStack(alignment: .firstTextBaseline, spacing: rowGutter) {
|
||||
Text(locationString)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(minWidth: locationColumnWidth, alignment: .leading)
|
||||
Text(diagnostic.severity.rawValue)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(color(for: diagnostic.severity))
|
||||
.frame(minWidth: severityColumnWidth, alignment: .leading)
|
||||
Text(diagnostic.message)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.textSelection(.enabled)
|
||||
.multilineTextAlignment(.leading)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
}
|
||||
|
||||
private var locationString: String {
|
||||
if let line: Int = diagnostic.line {
|
||||
return "\(line):\(diagnostic.column)"
|
||||
}
|
||||
return "preamble:\(diagnostic.rawLine):\(diagnostic.column)"
|
||||
}
|
||||
|
||||
private func color(for severity: DiagnosticSeverity) -> Color {
|
||||
switch severity {
|
||||
case .error: return .red
|
||||
case .warning: return .orange
|
||||
case .note: return .secondary
|
||||
}
|
||||
}
|
||||
|
||||
private let rowGutter: CGFloat = 8
|
||||
private let locationColumnWidth: CGFloat = 80
|
||||
private let severityColumnWidth: CGFloat = 56
|
||||
}
|
||||
|
||||
/// `NSViewRepresentable` wrapping a vanilla `NSTextView` inside an
|
||||
/// `NSScrollView`. Monospaced 13 pt, plain text, no smart-quote / dash /
|
||||
/// auto-correct interference — matches the editor expectations of someone
|
||||
/// typing Swift code.
|
||||
private struct ScratchEditor: NSViewRepresentable {
|
||||
|
||||
@Binding var text: String
|
||||
let fontSize: CGFloat
|
||||
let wrapsLines: Bool
|
||||
|
||||
final class Coordinator: NSObject, NSTextViewDelegate {
|
||||
var parent: ScratchEditor
|
||||
init(_ parent: ScratchEditor) { self.parent = parent }
|
||||
|
||||
func textDidChange(_ notification: Notification) {
|
||||
guard let tv: NSTextView = notification.object as? NSTextView else { return }
|
||||
parent.text = tv.string
|
||||
}
|
||||
}
|
||||
|
||||
func makeCoordinator() -> Coordinator { Coordinator(self) }
|
||||
|
||||
func makeNSView(context: Context) -> NSScrollView {
|
||||
let scroll: NSScrollView = NSTextView.scrollableTextView()
|
||||
if let tv: NSTextView = scroll.documentView as? NSTextView {
|
||||
configure(tv, in: scroll, with: context.coordinator)
|
||||
}
|
||||
return scroll
|
||||
}
|
||||
|
||||
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
||||
context.coordinator.parent = self
|
||||
guard let tv: NSTextView = scroll.documentView as? NSTextView else { return }
|
||||
let font: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
|
||||
let fontChanged: Bool = (tv.font?.pointSize ?? -1) != fontSize
|
||||
if fontChanged {
|
||||
tv.font = font
|
||||
}
|
||||
let paragraphStyle: NSParagraphStyle = makeParagraphStyle(for: font)
|
||||
tv.defaultParagraphStyle = paragraphStyle
|
||||
tv.typingAttributes = makeAttrs(font: font, paragraph: paragraphStyle)
|
||||
applyWrap(to: tv, in: scroll)
|
||||
if tv.string != text {
|
||||
replaceText(in: tv, with: text, font: font, paragraph: paragraphStyle)
|
||||
} else if fontChanged {
|
||||
reapplyAttrs(to: tv, font: font, paragraph: paragraphStyle)
|
||||
}
|
||||
}
|
||||
|
||||
private func makeAttrs(font: NSFont, paragraph: NSParagraphStyle) -> [NSAttributedString.Key: Any] {
|
||||
[
|
||||
.font: font,
|
||||
.foregroundColor: NSColor.labelColor,
|
||||
.paragraphStyle: paragraph,
|
||||
]
|
||||
}
|
||||
|
||||
private func makeParagraphStyle(for font: NSFont) -> NSParagraphStyle {
|
||||
let style: NSMutableParagraphStyle = NSMutableParagraphStyle()
|
||||
let spaceAdvance: CGFloat = (" " as NSString).size(withAttributes: [.font: font]).width
|
||||
let tabWidth: CGFloat = spaceAdvance * tabSpaces
|
||||
style.tabStops = []
|
||||
style.defaultTabInterval = tabWidth
|
||||
return style
|
||||
}
|
||||
|
||||
private func replaceText(in tv: NSTextView,
|
||||
with newText: String,
|
||||
font: NSFont,
|
||||
paragraph: NSParagraphStyle) {
|
||||
let attrs: [NSAttributedString.Key : Any] = makeAttrs(font: font, paragraph: paragraph)
|
||||
let attributed: NSAttributedString = NSAttributedString(string: newText, attributes: attrs)
|
||||
tv.textStorage?.setAttributedString(attributed)
|
||||
tv.typingAttributes = attrs
|
||||
}
|
||||
|
||||
private func reapplyAttrs(to tv: NSTextView,
|
||||
font: NSFont,
|
||||
paragraph: NSParagraphStyle) {
|
||||
guard let storage: NSTextStorage = tv.textStorage else { return }
|
||||
let attrs: [NSAttributedString.Key : Any] = makeAttrs(font: font, paragraph: paragraph)
|
||||
let range: NSRange = NSRange(location: 0, length: storage.length)
|
||||
storage.setAttributes(attrs, range: range)
|
||||
tv.typingAttributes = attrs
|
||||
}
|
||||
|
||||
private func applyWrap(to tv: NSTextView, in scroll: NSScrollView) {
|
||||
guard let container: NSTextContainer = tv.textContainer else { return }
|
||||
if wrapsLines {
|
||||
scroll.hasHorizontalScroller = false
|
||||
tv.isHorizontallyResizable = false
|
||||
tv.autoresizingMask = [.width]
|
||||
container.widthTracksTextView = true
|
||||
container.containerSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
|
||||
height: CGFloat.greatestFiniteMagnitude)
|
||||
} else {
|
||||
scroll.hasHorizontalScroller = true
|
||||
tv.isHorizontallyResizable = true
|
||||
tv.autoresizingMask = []
|
||||
container.widthTracksTextView = false
|
||||
container.containerSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
|
||||
height: CGFloat.greatestFiniteMagnitude)
|
||||
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
|
||||
height: CGFloat.greatestFiniteMagnitude)
|
||||
}
|
||||
tv.needsDisplay = true
|
||||
}
|
||||
|
||||
private func configure(_ tv: NSTextView, in scroll: NSScrollView, with coordinator: Coordinator) {
|
||||
tv.delegate = coordinator
|
||||
let editorFont: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
|
||||
tv.font = editorFont
|
||||
tv.isRichText = false
|
||||
tv.isAutomaticQuoteSubstitutionEnabled = false
|
||||
tv.isAutomaticDashSubstitutionEnabled = false
|
||||
tv.isAutomaticTextReplacementEnabled = false
|
||||
tv.isAutomaticSpellingCorrectionEnabled = false
|
||||
tv.smartInsertDeleteEnabled = false
|
||||
tv.allowsUndo = true
|
||||
tv.usesFindBar = true
|
||||
tv.textContainerInset = NSSize(width: editorInset, height: editorInset)
|
||||
tv.drawsBackground = true
|
||||
tv.backgroundColor = .textBackgroundColor
|
||||
tv.textColor = .labelColor
|
||||
tv.insertionPointColor = .labelColor
|
||||
tv.selectedTextAttributes = [
|
||||
.backgroundColor: NSColor.selectedTextBackgroundColor,
|
||||
.foregroundColor: NSColor.selectedTextColor,
|
||||
]
|
||||
let paragraphStyle: NSParagraphStyle = makeParagraphStyle(for: editorFont)
|
||||
tv.defaultParagraphStyle = paragraphStyle
|
||||
tv.typingAttributes = makeAttrs(font: editorFont, paragraph: paragraphStyle)
|
||||
applyWrap(to: tv, in: scroll)
|
||||
replaceText(in: tv, with: text, font: editorFont, paragraph: paragraphStyle)
|
||||
}
|
||||
|
||||
private let editorInset: CGFloat = 6
|
||||
private let tabSpaces: CGFloat = 4
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,145 @@
|
||||
// ScratchLineNumberRuler.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// Vertical line-number gutter for `ScratchEditor`'s `NSTextView`. Installed as
|
||||
// the scroll view's `verticalRulerView` so it tracks scroll position for free.
|
||||
// Reads laid-out glyph rects from the text view's layout manager and writes one
|
||||
// 1-based line label per visible line into the ruler's bounds.
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
|
||||
/// `NSRulerView` subclass rendering one right-aligned line number per laid-out
|
||||
/// line of the host `NSTextView`. Tracks the text view's scroll origin via the
|
||||
/// `boundsDidChangeNotification` posted by the enclosing `NSClipView` and
|
||||
/// invalidates itself on every text edit and frame change.
|
||||
final class ScratchLineNumberRuler: NSRulerView {
|
||||
|
||||
/// Re-resolved on every `draw` so the ruler picks up font / layout-manager
|
||||
/// swaps the text view performs after attachment.
|
||||
private weak var textView: NSTextView?
|
||||
|
||||
init(scrollView: NSScrollView, textView: NSTextView) {
|
||||
self.textView = textView
|
||||
super.init(scrollView: scrollView, orientation: .verticalRuler)
|
||||
self.clientView = textView
|
||||
self.ruleThickness = gutterWidth
|
||||
let center: NotificationCenter = NotificationCenter.default
|
||||
center.addObserver(self,
|
||||
selector: #selector(invalidateForChange(_:)),
|
||||
name: NSText.didChangeNotification,
|
||||
object: textView)
|
||||
center.addObserver(self,
|
||||
selector: #selector(invalidateForChange(_:)),
|
||||
name: NSView.frameDidChangeNotification,
|
||||
object: textView)
|
||||
let clipView: NSClipView = scrollView.contentView
|
||||
clipView.postsBoundsChangedNotifications = true
|
||||
center.addObserver(self,
|
||||
selector: #selector(invalidateForChange(_:)),
|
||||
name: NSView.boundsDidChangeNotification,
|
||||
object: clipView)
|
||||
}
|
||||
|
||||
required init(coder: NSCoder) {
|
||||
fatalError("ScratchLineNumberRuler does not support NSCoder init")
|
||||
}
|
||||
|
||||
deinit {
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
|
||||
@objc private func invalidateForChange(_ note: Notification) {
|
||||
needsDisplay = true
|
||||
}
|
||||
|
||||
override func drawHashMarksAndLabels(in rect: NSRect) {
|
||||
guard let textView: NSTextView,
|
||||
let layoutManager: NSLayoutManager = textView.layoutManager,
|
||||
let textContainer: NSTextContainer = textView.textContainer else {
|
||||
return
|
||||
}
|
||||
|
||||
gutterFillColor.setFill()
|
||||
rect.fill()
|
||||
gutterDividerColor.setStroke()
|
||||
let dividerPath: NSBezierPath = NSBezierPath()
|
||||
let dividerX: CGFloat = bounds.maxX - dividerHalfPixel
|
||||
dividerPath.move(to: NSPoint(x: dividerX, y: rect.minY))
|
||||
dividerPath.line(to: NSPoint(x: dividerX, y: rect.maxY))
|
||||
dividerPath.lineWidth = 1
|
||||
dividerPath.stroke()
|
||||
|
||||
let nsText: NSString = textView.string as NSString
|
||||
let totalLength: Int = nsText.length
|
||||
let visibleRect: NSRect = scrollView?.contentView.bounds ?? .zero
|
||||
let glyphRange: NSRange = layoutManager.glyphRange(forBoundingRect: visibleRect, in: textContainer)
|
||||
let charRange: NSRange = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
|
||||
let inset: CGFloat = textView.textContainerInset.height
|
||||
let attrs: [NSAttributedString.Key: Any] = [
|
||||
.font: rulerFont,
|
||||
.foregroundColor: gutterTextColor,
|
||||
]
|
||||
|
||||
var lineIndex: Int = lineNumber(at: charRange.location, in: nsText)
|
||||
var cursor: Int = charRange.location
|
||||
let visibleEnd: Int = NSMaxRange(charRange)
|
||||
while cursor < visibleEnd && cursor <= totalLength {
|
||||
// `lineRange(for:)` advances cursor by the full line including its
|
||||
// terminator, so `\r`, `\n`, and `\r\n` line endings are all
|
||||
// handled by Foundation.
|
||||
let probeLength: Int = (cursor == totalLength) ? 0 : 0
|
||||
let lineRange: NSRange = nsText.lineRange(for: NSRange(location: cursor, length: probeLength))
|
||||
let lineGlyphRange: NSRange = layoutManager.glyphRange(forCharacterRange: lineRange,
|
||||
actualCharacterRange: nil)
|
||||
let usedRect: NSRect = layoutManager.boundingRect(forGlyphRange: lineGlyphRange,
|
||||
in: textContainer)
|
||||
let yInView: CGFloat = usedRect.minY + inset - visibleRect.minY
|
||||
let label: NSString = "\(lineIndex)" as NSString
|
||||
let size: CGSize = label.size(withAttributes: attrs)
|
||||
let drawPoint: NSPoint = NSPoint(
|
||||
x: bounds.maxX - size.width - rightInset,
|
||||
y: yInView + ((usedRect.height - size.height) * 0.5)
|
||||
)
|
||||
label.draw(at: drawPoint, withAttributes: attrs)
|
||||
|
||||
let advance: Int = NSMaxRange(lineRange)
|
||||
if advance <= cursor { break } // defensive — empty trailing line
|
||||
cursor = advance
|
||||
lineIndex += 1
|
||||
}
|
||||
}
|
||||
|
||||
// 1-based line number of the character at `loc`. Delegates to
|
||||
// `NSString.enumerateSubstrings(.byLines)` so CR, LF, and CRLF endings are
|
||||
// all counted correctly. Linear in `loc`, runs once per draw on the prefix
|
||||
// that precedes the first visible line.
|
||||
private func lineNumber(at loc: Int, in text: NSString) -> Int {
|
||||
if loc <= 0 { return 1 }
|
||||
var line: Int = 1
|
||||
let prefixRange: NSRange = NSRange(location: 0, length: loc)
|
||||
text.enumerateSubstrings(in: prefixRange,
|
||||
options: [.byLines, .substringNotRequired]) { _, _, _, _ in
|
||||
line += 1
|
||||
}
|
||||
return line
|
||||
}
|
||||
|
||||
private let gutterWidth: CGFloat = 40
|
||||
private let rightInset: CGFloat = 6
|
||||
private let dividerHalfPixel: CGFloat = 0.5 // crisp 1px divider on Retina
|
||||
private let rulerFontSize: CGFloat = 11
|
||||
private let gutterFillColor: NSColor = NSColor.controlBackgroundColor
|
||||
private let gutterDividerColor: NSColor = NSColor.separatorColor
|
||||
private let gutterTextColor: NSColor = NSColor.tertiaryLabelColor
|
||||
private var rulerFont: NSFont {
|
||||
NSFont.monospacedSystemFont(ofSize: rulerFontSize, weight: .regular)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
+3
@@ -1,6 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdQuickstartDemo/LyrebirdQuickstartDemo.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdDemo/LyrebirdDemo.xcodeproj">
|
||||
</FileRef>
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
# Lyrebird
|
||||
|
||||
Lyrebird is a native macOS audio synthesis framework written in Swift. Users write Swift code that implements the `Generator` and `Synthesizer` protocols against the Lyrebird engine — there is no separate scripting language. The framework handles Core Audio I/O, a pre-allocated bus memory system, and a node tree for ordering signal evaluation. The design is informed by 20+ years of SuperCollider practice, adapted to Swift idioms and a single-process architecture.
|
||||
|
||||
Development follows an interpret-then-compile workflow: sketch and perform in the Swift REPL with Lyrebird loaded, then graduate working code to a Swift Package project for compiled, optimized execution.
|
||||
|
||||
## Locked Decisions
|
||||
|
||||
| Decision | Choice |
|
||||
|---|---|
|
||||
| Implementation language | Swift |
|
||||
| Platform | macOS 15+ (requires `Synchronization.Atomic` for SPSCQueue) |
|
||||
| Swift tools version | 6.0 (required for macOS 15 platform target) |
|
||||
| Audio I/O | Direct Core Audio (`kAudioUnitSubType_HALOutput`) — no AVAudioEngine |
|
||||
| NRT rendering | `NRTDriver` — fixed-duration tight loop, `ExtAudioFile` AIFF/WAV output; event-driven stop is a stretch goal |
|
||||
| Execution model | Interpreted (REPL) → compiled (Swift Package) |
|
||||
| Bus system | Pre-allocated, SC convention (128 audio / 4096 control) |
|
||||
| Block size | Configurable at engine init |
|
||||
| Testing | Swift Testing framework — no Xcode Playgrounds |
|
||||
| REPL | Swift REPL + LineNoise |
|
||||
| Hot reload | Interpret-then-compile |
|
||||
| Inter-file modularity | Swift Package module system |
|
||||
| Package targets | `Lyrebird` (library), `LyrebirdDemo` (executable smoke test), `LyrebirdTests` (test) |
|
||||
|
||||
## SuperCollider Lineage
|
||||
|
||||
The designer has 20+ years of SC experience. SC concepts map to Lyrebird as follows:
|
||||
|
||||
| SuperCollider | Lyrebird |
|
||||
|---|---|
|
||||
| UGen | `Generator` protocol |
|
||||
| SynthDef / Synth | `Synthesizer` protocol |
|
||||
| Group | `Group` (node tree ordering) |
|
||||
| Audio/control bus | Pre-allocated bus memory |
|
||||
| `In` / `Out` UGen | `In` / `Out` generators |
|
||||
| sclang | Swift |
|
||||
| scsynth | `SynthesisEngine` |
|
||||
|
||||
## Document Index
|
||||
|
||||
| Doc | Topic |
|
||||
|---|---|
|
||||
| `docs/00-working-order.md` | Phased implementation sequence |
|
||||
| `docs/engine/synthesis-engine.md` | SynthesisEngine, Core Audio AUHAL |
|
||||
| `docs/engine/bus-system.md` | Bus memory model, In/Out |
|
||||
| `docs/engine/scheduling.md` | Sample-accurate scheduling, SPSCQueue, sub-block splitting |
|
||||
| `docs/protocols/generator.md` | Generator protocol hierarchy |
|
||||
| `docs/protocols/synthesizer.md` | Synthesizer protocol, node tree |
|
||||
| `docs/signal-flow/signal-flow.md` | DAG evaluation, block processing |
|
||||
| `docs/tooling/repl.md` | REPL, LineNoise, hot-swap |
|
||||
| `docs/tooling/project-system.md` | Swift Package model, CLI |
|
||||
| `docs/stdlib/generators.md` | Built-in generator library |
|
||||
| `docs/ui/gui-system.md` | Native SwiftUI GUI, parameter binding, control windows |
|
||||
|
||||
## Legacy Reference
|
||||
|
||||
`legacy/Lyrebird/LyrebirdSynth/Lyrebird/` — a working prototype from ~10 years ago. Good source for: `ValidGeneratorInput` protocol pattern, operator overloading approach, sine table oscillator, envelope curve math, delay interpolation. Do not copy verbatim — modernize to Swift concurrency, add Core Audio integration, expand test coverage.
|
||||
+2
-2
@@ -41,8 +41,8 @@ let package = Package(
|
||||
// swift-docc-plugin — command plugin that drives DocC documentation builds.
|
||||
// Registers two commands available to all targets in this package:
|
||||
// • In Xcode: Product ▸ Build Documentation (or scheme-level build action)
|
||||
// • From CLI: swift package generate-documentation --target Lyrebird
|
||||
// swift package preview-documentation --target Lyrebird
|
||||
// • From CLI: swift package generate-documentation --target LyrebirdSynth
|
||||
// swift package preview-documentation --target LyrebirdSynth
|
||||
// No target-level plugins: entry is needed — command plugins apply package-wide.
|
||||
.package(
|
||||
url: "https://github.com/apple/swift-docc-plugin",
|
||||
|
||||
@@ -120,7 +120,7 @@ The REPL is text-only and works from any project that depends on Lyrebird; the s
|
||||
|
||||
## New here?
|
||||
|
||||
**Read [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md)** — it covers the six demo projects, how to open the workspace, where to add synthesizers, and the gotchas that will bite you.
|
||||
**Read [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md)** — it covers the eight demo projects, how to open the workspace, where to add synthesizers, and the gotchas that will bite you.
|
||||
|
||||
---
|
||||
|
||||
@@ -151,7 +151,7 @@ Full walk-through (SPM manifest form, local-path dev dependency, per-template de
|
||||
|
||||
## Opening in Xcode
|
||||
|
||||
For the demo projects, open **`Lyrebird.xcworkspace`** — not any individual `.xcodeproj`. The workspace links all six demos to the local Lyrebird package.
|
||||
For the demo projects, open **`Lyrebird.xcworkspace`** — not any individual `.xcodeproj`. The workspace links all eight demos to the local Lyrebird package.
|
||||
|
||||
For the package itself:
|
||||
|
||||
@@ -161,16 +161,18 @@ xed . # opens Package.swift — Xcode auto-generates schemes for every target
|
||||
|
||||
### Schemes
|
||||
|
||||
Workspace scheme selector exposes eight entries:
|
||||
Workspace scheme selector exposes ten 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 |
|
||||
| `LyrebirdUI` | Builds the `LyrebirdUI` module only (SwiftUI parameter controls + visualisations) | macOS |
|
||||
| `LyrebirdDemo` | CLI — plays through default output via `CoreAudioDriver` | macOS |
|
||||
| `LyrebirdMacOSDemo` | SwiftUI app — live oscilloscope, `@UIParam` knobs | macOS |
|
||||
| `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 |
|
||||
| `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 |
|
||||
| `LyrebirdScratchDemo` | Live-coding scratchpad — type Swift snippets, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
||||
|
||||
@@ -192,7 +194,7 @@ Use `Lyrebird-Package` for day-to-day development of the engine and tests.
|
||||
|
||||
```bash
|
||||
swift build # build all targets
|
||||
swift test # run all 3544 tests
|
||||
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
|
||||
@@ -203,14 +205,16 @@ swift run LyrebirdDemo # run the hardware smoke-test demo
|
||||
|
||||
## Demo projects
|
||||
|
||||
All six live in [`Demos/`](Demos/). Open via `Lyrebird.xcworkspace`.
|
||||
All eight live in [`Demos/`](Demos/). Open via `Lyrebird.xcworkspace`.
|
||||
|
||||
| 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 |
|
||||
| [`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 |
|
||||
| [`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 |
|
||||
| [`LyrebirdScratchDemo`](Demos/LyrebirdScratchDemo/) | Live-coding scratchpad — type Swift, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
||||
|
||||
@@ -231,8 +235,10 @@ lyrebird --help # verify
|
||||
Then:
|
||||
|
||||
```bash
|
||||
lyrebird new MyPiece --template ui-demo # scaffold a standalone project
|
||||
open MyPiece/MyPiece.xcworkspace # open in Xcode (workspace refs Package.swift)
|
||||
lyrebird new MyFirstSound --template quickstart # fastest path to sound (plays 10 s, then exits)
|
||||
cd MyFirstSound && lyrebird run # hear it
|
||||
lyrebird new MyPiece --template ui-demo # a richer standalone project
|
||||
open MyPiece/MyPiece.xcworkspace # open in Xcode (workspace refs Package.swift)
|
||||
lyrebird # enter the lyrebird> interactive shell
|
||||
lyrebird repl # Swift REPL with Lyrebird importable
|
||||
lyrebird --version
|
||||
@@ -269,14 +275,16 @@ LyrebirdII/
|
||||
│ ├── LyrebirdCLI/ # lyrebird CLI binary
|
||||
│ └── LyrebirdDemo/ # macOS CLI hardware smoke-test
|
||||
├── Demos/
|
||||
│ ├── LyrebirdQuickstartDemo/ # fastest sound — SineTone plays 10 s then exits
|
||||
│ ├── LyrebirdDemo/ # (same as Sources/LyrebirdDemo — workspace target)
|
||||
│ ├── LyrebirdMacOSDemo/ # macOS SwiftUI app
|
||||
│ ├── LyrebirdiOSDemo/ # iOS SwiftUI app
|
||||
│ ├── LyrebirdNRTDemo/ # offline renderer
|
||||
│ ├── LyrebirdScoreDemo/ # notated Score → MusicXML + offline render
|
||||
│ ├── LyrebirdAUv3Demo/ # AUv3 `aumu` plugin reference (LyrebirdFM)
|
||||
│ └── LyrebirdScratchDemo/ # live-coding scratchpad (macOS, no sandbox)
|
||||
├── Tests/
|
||||
│ ├── LyrebirdTests/ # 3544 engine + generator tests
|
||||
│ ├── LyrebirdTests/ # 5253 engine + generator tests
|
||||
│ ├── LyrebirdUITests/ # SwiftUI component tests
|
||||
│ └── LyrebirdCLITests/ # CLI tests
|
||||
└── docs/
|
||||
|
||||
+184
@@ -7,6 +7,190 @@ functionality in a backward-compatible way.
|
||||
|
||||
---
|
||||
|
||||
## 1.3.0 — Graceful-release fix, quickstart template, documentation accuracy pass
|
||||
|
||||
A minor release. Backward-compatible: one real-time behavior fix, one new
|
||||
project template, and a large sweep that makes the documentation's code
|
||||
examples verifiably correct.
|
||||
|
||||
### Fixed — graceful release now works for `SynthesizerBase` subclasses
|
||||
|
||||
`release(engine:)` and `free(engine:)` were `Synthesizer` protocol requirements
|
||||
satisfied only by extension defaults; `SynthesizerBase` declared neither, so a
|
||||
subclass override was unreachable through an `any Synthesizer` reference. Because
|
||||
`Group.release(engine:)` cascades to its children through exactly that
|
||||
existential, **every gated `SynthesizerBase` subclass was hard-freed instead of
|
||||
released** — envelope release phases were skipped (audible as clicks and missing
|
||||
release tails). `SynthesizerBase` now declares both as `open` members, so
|
||||
overrides dispatch through the vtable. Pinned by `SynthesizerReleaseDispatchTests`.
|
||||
|
||||
### New — `quickstart` project template + demo
|
||||
|
||||
- `lyrebird new MyFirstSound --template quickstart` scaffolds the shortest path
|
||||
to sound: a one-oscillator `SineTone`, the engine, and a `main` that plays a
|
||||
440 Hz tone for ten seconds and exits. Featured as the fast option across the
|
||||
CLI help, README, and getting-started docs.
|
||||
- A matching bundled **`LyrebirdQuickstartDemo`** Xcode project ships in the
|
||||
workspace so the same starting point is runnable without the CLI.
|
||||
|
||||
### Documentation — every example now typechecked or provably illustrative
|
||||
|
||||
- Extended the doc-snippet compile guard to the published entry-point articles,
|
||||
the generator reference, and the root docs (`README` / `LYREBIRD_START_HERE` /
|
||||
`INSTALLATION_AND_USAGE`), which were previously checked by nothing. Recorded
|
||||
compilable examples rose from 426 to 542.
|
||||
- Fixed roughly twenty copy-paste examples that never compiled — wrong parameter
|
||||
labels and orders (`LinLin`, `SpringReverb`, `BufferGrain`), nonexistent APIs
|
||||
(`LFNoise2`, `DoneAction.freeSynth`, `buildGraph()`, `midiNoteToHz`,
|
||||
`LyrebirdBuffer(path:)`, a `>` operator on generators), missing required
|
||||
arguments (`CombFilter`/`AllpassFilter` `maxDelay`), a Swift 6 concurrency
|
||||
violation in the canonical routine example, and stale test counts. Removed an
|
||||
unsupported NRT-replay workflow that documented a fabricated driver API.
|
||||
|
||||
### Fixed — demo terminal builds
|
||||
|
||||
`LyrebirdNRTDemo` and `LyrebirdScoreDemo` pinned a stale `package: "LyrebirdII"`
|
||||
in their `Package.swift`, so standalone `swift build` / `swift run` from the demo
|
||||
directory failed. Corrected to `Lyrebird`.
|
||||
|
||||
---
|
||||
|
||||
## 1.2.0 — Generator catalog expansion *(planned)*
|
||||
|
||||
A minor release. Adds roughly forty SuperCollider-parity generators —
|
||||
triggers, time-domain analysis, chaotic oscillators, resonator banks, dynamics,
|
||||
waveshaping, routing/morph, and psychoacoustic metering — plus an iOS path fix.
|
||||
Fully backward-compatible; no changes to existing public API.
|
||||
|
||||
### New generators
|
||||
|
||||
**Trigger / timing.** `Trig` and `Trig1` (fixed-duration gate from a trigger),
|
||||
`Schmidt` (hysteresis threshold), `Stepper` (trigger-advanced counter),
|
||||
`PulseCount` (count triggers, reset on a second input), `TriggeredDelay` (hold
|
||||
then re-emit a trigger).
|
||||
|
||||
**Phasor / slew.** `Phasor` (sample-accurate sweeping ramp with wrap bounds and
|
||||
trigger-reset), `Slew` (asymmetric slew-rate limiter).
|
||||
|
||||
**Time-domain analysis.** `RunningMin`, `RunningMax` (running extrema, reset on
|
||||
trigger), `Slope` (per-sample first difference), `ZeroCrossing` (zero-crossing
|
||||
frequency estimator).
|
||||
|
||||
**Routing / morph.** `Select` (index-select one of N inputs), `CrossFade`
|
||||
(equal-power two-input mix), `LinearCrossFade` (linear two-input mix).
|
||||
|
||||
**Waveshaping / distortion.** `Waveshaper` (transfer-function table lookup with
|
||||
interpolation), `CrossoverDistortion` (dead-zone crossover), `Disintegrator`
|
||||
(probabilistic sample mangling).
|
||||
|
||||
**Resonant filter / LFO.** `Formlet` (FOF-style resonant formant filter),
|
||||
`LFGauss` (Gaussian-bell LFO).
|
||||
|
||||
**Chaotic oscillators.** `LorenzLinear`, `HenonStepped`, `QuadStepped`,
|
||||
`LinCongStepped`, `GbmanStepped`, `StandardStepped`, `FBSineStepped`,
|
||||
`LatoocarfianStepped`, `CuspStepped` — discrete chaotic maps, frequency-stepped
|
||||
where SuperCollider steps them.
|
||||
|
||||
**Resonator banks.** `Klank` (fixed bank of fixed-frequency resonators) and
|
||||
`Klang` (bank of sine partials), both runtime-respecifiable.
|
||||
|
||||
**Dynamics.** `Normalizer` (look-ahead peak normalizer) and `Balance` (RMS
|
||||
level matcher, with `logDomain` for dB-domain gain and `smooth` for decoupled
|
||||
gain lag).
|
||||
|
||||
**Metering.** `BeatTrack` (FFT-based tempo / beat tracker) and `Loudness`
|
||||
(Zwicker / ISO 532 B psychoacoustic loudness in sones).
|
||||
|
||||
> `DFM1` (the remaining catalog candidate) is intentionally omitted: its source
|
||||
> and lookup tables are GPL, incompatible with this project's MIT license.
|
||||
|
||||
### Tooling
|
||||
|
||||
- **ShoeGaze moved out of tree.** The guitar-pedalboard framework and its
|
||||
project/pedal scaffolding now live in a standalone ShoeGaze repository that
|
||||
depends on Lyrebird as a package. Lyrebird's CLI no longer ships the
|
||||
`shoegaze` / `shoegaze-ios` project templates or the "ShoeGaze Pedal" Xcode
|
||||
file template.
|
||||
|
||||
### Fixes
|
||||
|
||||
- **`LyrebirdPaths.home` on iOS** now returns the app's Documents directory
|
||||
instead of `homeDirectoryForCurrentUser` (the sandbox root, which is not
|
||||
writable on iOS). Unchanged on macOS.
|
||||
|
||||
### Internals (no API impact)
|
||||
|
||||
- The 4-point Catmull-Rom cubic interpolation duplicated across oscillator
|
||||
table reads, `PlayBuffer`, and the fractional-delay lines is now a single
|
||||
shared `catmullRomCubic` kernel.
|
||||
- Generator tests regrouped by family.
|
||||
|
||||
---
|
||||
|
||||
## 1.1.1 — Real-time performance + score-timing fixes *(planned)*
|
||||
|
||||
A patch release: real-time CPU improvements to the synthesis engine's hot path,
|
||||
internal generator consolidation, and two score-side timing fixes. Fully
|
||||
backward-compatible — no public API changes.
|
||||
|
||||
### Real-time performance
|
||||
|
||||
The generator render path (`_computeSamples`) is now Accelerate-accelerated
|
||||
where it was previously scalar. Wins are largest for the primitives that appear
|
||||
in nearly every patch:
|
||||
|
||||
- **Unary math waveshapers** (`Sin` / `Cos` / `Exp` / `Log` / `Sqrt` / `Floor`
|
||||
/ `Ceil` / `Abs`) — vectorized via vForce / vDSP (~3× faster on a typical
|
||||
chained-op voice).
|
||||
- **Arithmetic operators** (`+` `−` `×` `÷` on generators, via
|
||||
`BinaryOpGenerator`) — vDSP dispatch, **bit-identical** to the scalar result
|
||||
(divide uses true-division, never reciprocal-multiply). Roughly 2–3.5× faster;
|
||||
applies to every `osc * gain + offset`-style graph.
|
||||
- **`LinLin`** — single fused `vDSP_vsmsaD` affine map (~27% faster).
|
||||
- **State-variable filter (`SVF`)** — shared per-block kernel; generator-driven
|
||||
cutoff uses block-boundary coefficient interpolation instead of a per-sample
|
||||
`sin()`.
|
||||
- **`Chorus` / `Flanger`** — power-of-two delay lines (bitwise index wrap).
|
||||
- **Butterworth band-pass / band-reject** — now use the same background-thread
|
||||
vDSP biquad-cascade path the low-pass / high-pass filters already had.
|
||||
|
||||
All vectorized paths keep a scalar fallback for short upstream blocks, so output
|
||||
is unchanged on every code path (transcendentals within tolerance; arithmetic
|
||||
and filter sums bit-exact).
|
||||
|
||||
### Internals (no API impact)
|
||||
|
||||
- Generator consolidation: the duplicated Butterworth cascade machinery, SVF
|
||||
block body, unary-math and binary-op inner loops, and power-of-two buffer
|
||||
sizing are now shared helpers (`ButterworthSectionEngine`, `runSVFBlock`,
|
||||
`UnaryMathVectorHelpers`, `BinaryOpVectorHelpers`, `lyrebirdNextPowerOfTwo`,
|
||||
`computeButterworthQs`). Several hundred lines of duplication removed.
|
||||
- New `LyrebirdBenchmark` target with before/after reference numbers
|
||||
(`docs/benchmarks/gp-baseline.md`).
|
||||
- Language-side consolidation: shared `isCounterExhausted` / `resetAll` Pattern
|
||||
helpers, a `_RandomPatternBase` for the random pattern engines, a
|
||||
`TemporalAlgorithmBase` for the counter-driven temporal algorithms, a shared
|
||||
MusicXML `<direction>` / `<pitch>` emit helper, and a single
|
||||
engine-mutation-to-main-queue dispatch helper shared by the routine/process
|
||||
contexts.
|
||||
|
||||
### Score / MusicXML
|
||||
|
||||
- **`ScorePart` entrance offset** — a part can enter later than the start of its
|
||||
section via `offset:` (`ScoreOffset.measures(_:)` / `.beats(_:)` /
|
||||
`.fraction(_:)`). Resolved at build time into leading rests (the same way
|
||||
`FillMeasure()` is resolved), so it flows through section sizing, MusicXML bar
|
||||
splitting, and `flatten()` with no special handling.
|
||||
- **MusicXML barline-fill fix** — corrected two emit-side defects in sectioned
|
||||
scores with rest-padded short parts: a barline-crossing atom that exactly
|
||||
filled a bar left the measure open (shifting every later note by one division,
|
||||
rendering constant 4/4 as 5/4), and section auto-padding used meter-agnostic
|
||||
rests that straddled barlines. Padding is now bar-grid aligned (clean
|
||||
whole-measure rests; anacrusis-aware). Lowering/playback math was already
|
||||
correct — both fixes are export-only.
|
||||
|
||||
---
|
||||
|
||||
## 1.1 — Enhanced algorithmic composition tools
|
||||
|
||||
Release 1.1 turns Lyrebird's score side from a thin event list into a full
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
// main.swift
|
||||
// MainActorConsumer (Phase 201 regression fixture)
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
// PHASE 201 GUARANTEE: a consumer under the MainActor-default build mode subclasses
|
||||
// `SynthesizerBase` and overrides `build()` with NO `nonisolated`, NO `@preconcurrency`,
|
||||
// NO `@MainActor`, NO `nonisolated override init`. If this stops compiling, the
|
||||
// language-side actor-isolation guarantee has regressed.
|
||||
final class ToneSynth: SynthesizerBase {
|
||||
@LiveParam var freq: Double = 440
|
||||
override func build() {
|
||||
output(bus: 0, source: OscSin.Audio(freq: $freq) * 0.2)
|
||||
}
|
||||
}
|
||||
|
||||
let synth = ToneSynth()
|
||||
print("Phase 201 regression fixture OK: \(synth)")
|
||||
@@ -240,6 +240,11 @@ public final class NRTDriver: AudioDriver {
|
||||
throw NRTDriverError.writeFailed(writeStatus)
|
||||
}
|
||||
}
|
||||
|
||||
// Synchronous render is done and the freeWorker timer only starts after this
|
||||
// returns — emit any per-block event-drop warning here so it reaches the console
|
||||
// even if the process exits before that timer (or `stop()`) runs.
|
||||
engine.drainPerBlockEventDropWarning()
|
||||
}
|
||||
|
||||
public func stop() {
|
||||
|
||||
@@ -117,6 +117,9 @@ import Synchronization
|
||||
/// `invalidate()` uses a `.releasing` store; `isValid` uses an `.acquiring` load.
|
||||
/// `LyrebirdBuffer` is safe to share across threads:
|
||||
/// - The validity flag is protected by `Atomic<Bool>`.
|
||||
/// - `loopLength` is likewise an `Atomic<Int>` (`.acquiring` load / `.releasing` store
|
||||
/// via ``setLoopLength(_:)``) — read every sample by `PlayBuffer`-family generators,
|
||||
/// written once (non-RT) after e.g. a looper pedal finishes recording a take.
|
||||
/// - `channelCount` and `count` are `let` constants — freely readable on any thread.
|
||||
/// - Sample data can be written from the RT thread by `RecordBuffer` via the internal
|
||||
/// `write(_:frame:channel:)` method. The buffer is **not safe for concurrent non-RT
|
||||
@@ -240,6 +243,45 @@ public final class LyrebirdBuffer: @unchecked Sendable {
|
||||
return bufRate / engineSampleRate
|
||||
}
|
||||
|
||||
/// Number of frames that `PlayBuffer`-family generators should wrap (looping) or
|
||||
/// clamp (non-looping) against, distinct from `count` (the full allocated size).
|
||||
///
|
||||
/// Defaults to `count` at init, matching the historical full-buffer looping
|
||||
/// behaviour. Narrow this after recording a take that is shorter than the
|
||||
/// buffer's max-duration allocation — e.g. a looper pedal that pre-allocates
|
||||
/// 60 seconds but records a shorter take — so playback wraps only over the
|
||||
/// actually-recorded region without reallocating the buffer.
|
||||
///
|
||||
/// **RT contract.** Stored as an `Atomic<Int>` rather than behind `_writeLock`:
|
||||
/// this value is read on every sample inside `PlayBuffer`'s per-sample read loop
|
||||
/// (`lyrebirdBufferRead`), so a lock acquired every sample would be the wrong
|
||||
/// tool. An atomic load costs nothing close to a lock and gives torn-free reads
|
||||
/// of a single `Int`. Set from a non-RT thread via ``setLoopLength(_:)``, e.g.
|
||||
/// once after recording stops.
|
||||
private let _loopLength: Atomic<Int>
|
||||
|
||||
/// Current loop/clamp bound for `PlayBuffer`-family generators, in frames.
|
||||
///
|
||||
/// `1...count`, defaulting to `count`. Read with an `.acquiring` load — safe to
|
||||
/// call from the RT thread inside a per-sample read loop.
|
||||
public var loopLength: Int {
|
||||
_loopLength.load(ordering: .acquiring)
|
||||
}
|
||||
|
||||
/// Narrow (or restore) the frame count that `PlayBuffer`-family generators wrap
|
||||
/// or clamp against.
|
||||
///
|
||||
/// Call from a non-RT thread — typically once, right after recording stops
|
||||
/// (e.g. a looper pedal calling this with the frame count `RecordBuffer`
|
||||
/// actually wrote, so playback loops over just the recorded take instead of
|
||||
/// the full max-duration allocation).
|
||||
///
|
||||
/// - Parameter length: Desired loop length in frames. Clamped to `[1, count]`.
|
||||
public func setLoopLength(_ length: Int) {
|
||||
let clamped: Int = max(1, min(length, count))
|
||||
_loopLength.store(clamped, ordering: .releasing)
|
||||
}
|
||||
|
||||
/// Atomic validity flag. `true` after `init`, `false` after `invalidate()`.
|
||||
private let _isValid: Atomic<Bool>
|
||||
|
||||
@@ -460,6 +502,7 @@ public final class LyrebirdBuffer: @unchecked Sendable {
|
||||
_storage = UnsafeMutablePointer<Double>.allocate(capacity: total)
|
||||
_storage.initialize(repeating: 0, count: total)
|
||||
_isValid = Atomic<Bool>(true)
|
||||
_loopLength = Atomic<Int>(count)
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
@@ -44,3 +44,45 @@ func _resolvedChannelCount(_ bus: any ValidBus) -> Int {
|
||||
bus.channelCount == Int.max ? 1 : max(1, bus.channelCount)
|
||||
}
|
||||
|
||||
/// Traps at graph-build time when a ``ControlBus`` is handed to an **audio**-rate bus generator
|
||||
/// (`Out.Audio` / `ReplaceOut.Audio` / `In.Audio`).
|
||||
///
|
||||
/// Those generators address the **audio**-bus pool by index. A `ControlBus`'s `index` lives in the
|
||||
/// separate control-bus index space, so writing/reading it through an audio-rate generator hits
|
||||
/// audio memory at that number — silently colliding with unrelated audio buses (including the
|
||||
/// hardware output buses at low indices). There is no correct use for it: reach for the control-rate
|
||||
/// variant (`Out.Control` / `ReplaceOut.Control` / `In.Control`, or `SynthesizerBase`'s
|
||||
/// `controlOutput(bus:source:)` / `controlInput(bus:)`).
|
||||
///
|
||||
/// Runs only at `init` (graph construction, main thread) — never on the RT render path. A plain
|
||||
/// `Int` bus is the deliberate raw-index escape hatch and is intentionally not checked.
|
||||
@inline(__always)
|
||||
func _preconditionAudioRateBus(_ bus: any ValidBus) {
|
||||
precondition(
|
||||
!(bus is ControlBus),
|
||||
"A ControlBus was passed to an audio-rate bus generator (Out.Audio / ReplaceOut.Audio / "
|
||||
+ "In.Audio), which addresses the audio-bus pool at that index and collides with unrelated "
|
||||
+ "audio buses. Use the control-rate variant (Out.Control / ReplaceOut.Control / In.Control, "
|
||||
+ "or controlOutput(bus:source:) / controlInput(bus:))."
|
||||
)
|
||||
}
|
||||
|
||||
/// Traps at graph-build time when an ``AudioBus`` is handed to a **control**-rate bus generator
|
||||
/// (`Out.Control` / `ReplaceOut.Control` / `In.Control`).
|
||||
///
|
||||
/// The mirror of ``_preconditionAudioRateBus(_:)``: control-rate generators address the
|
||||
/// **control**-bus pool by index, so an `AudioBus`'s `index` reaches control memory at that number
|
||||
/// and collides with unrelated control buses. Use the audio-rate variant (`Out.Audio` /
|
||||
/// `ReplaceOut.Audio` / `In.Audio`, or `output(bus:source:)` / `input(bus:)`). `Int` buses are not
|
||||
/// checked. `init`-time only, never RT.
|
||||
@inline(__always)
|
||||
func _preconditionControlRateBus(_ bus: any ValidBus) {
|
||||
precondition(
|
||||
!(bus is AudioBus),
|
||||
"An AudioBus was passed to a control-rate bus generator (Out.Control / ReplaceOut.Control / "
|
||||
+ "In.Control), which addresses the control-bus pool at that index and collides with "
|
||||
+ "unrelated control buses. Use the audio-rate variant (Out.Audio / ReplaceOut.Audio / "
|
||||
+ "In.Audio, or output(bus:source:) / input(bus:))."
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -33,112 +33,138 @@
|
||||
///
|
||||
/// ## Per-distribution examples
|
||||
///
|
||||
/// All examples use `TemporalTendency` with fixed `.value(…)` parameters and
|
||||
/// `seed: 0xDEADCAFE12345678`. Actual outputs vary with seed.
|
||||
/// All examples build a ``TemporalStream`` over a ``TemporalTendency`` with fixed
|
||||
/// `.value(…)` parameters and `seed: 0xDEADCAFE12345678` — the seed lives on the stream,
|
||||
/// not on the algorithm. Actual outputs vary with seed. The values below are pinned by
|
||||
/// `DistributionKindGoldenValueTests`, since a typecheck cannot see them drift.
|
||||
///
|
||||
/// **`.uniform`** — flat probability across \[lo, hi\]
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .uniform, parX: .value(0), parY: .value(1), seed: s)
|
||||
/// TemporalStream(TemporalTendency(distribution: .uniform,
|
||||
/// parX: .value(0), parY: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.744, 0.046, 0.799, 0.681, 0.517
|
||||
/// ```
|
||||
///
|
||||
/// **`.lpRand`** — squared uniform, biases toward lo
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .lpRand, parX: .value(0), parY: .value(1), seed: s)
|
||||
/// // → 0.080, 0.337, 0.057, 0.830, 0.788
|
||||
/// TemporalStream(TemporalTendency(distribution: .lpRand,
|
||||
/// parX: .value(0), parY: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.553, 0.002, 0.638, 0.464, 0.267
|
||||
/// ```
|
||||
///
|
||||
/// **`.hpRand`** — squared uniform mirrored, biases toward hi
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .hpRand, parX: .value(0), parY: .value(1), seed: s)
|
||||
/// // → 0.878, 0.944, 0.939, 0.983, 0.899
|
||||
/// TemporalStream(TemporalTendency(distribution: .hpRand,
|
||||
/// parX: .value(0), parY: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.447, 0.998, 0.362, 0.536, 0.733
|
||||
/// ```
|
||||
///
|
||||
/// **`.meanRand`** — average of two uniforms (triangular), biases toward midpoint
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .meanRand, parX: .value(0), parY: .value(1), seed: s)
|
||||
/// // → 0.624, 0.559, 0.512, 0.586, 0.308
|
||||
/// TemporalStream(TemporalTendency(distribution: .meanRand,
|
||||
/// parX: .value(0), parY: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.395, 0.740, 0.400, 0.410, 0.899
|
||||
/// ```
|
||||
///
|
||||
/// **`.expRand`** — log-uniform, exponential density in \[lo, hi\]; lo and hi must be > 0
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .expRand, parX: .value(1), parY: .value(100), seed: s)
|
||||
/// // → 15.709, 4.710, 14.831, 26.119, 47.853
|
||||
/// TemporalStream(TemporalTendency(distribution: .expRand,
|
||||
/// parX: .value(1), parY: .value(100)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 30.743, 1.234, 39.596, 23.035, 10.818
|
||||
/// ```
|
||||
///
|
||||
/// **`.exponential`** — standard exponential; parX is the rate λ (higher = shorter tail)
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .exponential, parX: .value(1), seed: s)
|
||||
/// // → 0.023, 0.489, 0.126, 2.077, 0.354
|
||||
/// TemporalStream(TemporalTendency(distribution: .exponential, parX: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.296, 3.085, 0.225, 0.384, 0.660
|
||||
/// ```
|
||||
///
|
||||
/// **`.gamma`** — shape parameter k; k=1 → exponential, k>1 → bell shifted right
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .gamma, parX: .value(2), seed: s)
|
||||
/// // → 0.412, 2.998, 0.709, 1.409, 3.985
|
||||
/// TemporalStream(TemporalTendency(distribution: .gamma, parX: .value(2)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 2.812, 0.776, 1.756, 1.326, 3.649
|
||||
/// ```
|
||||
///
|
||||
/// **`.laplace`** — double-exponential, sharp central peak; parX is scale b
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .laplace, parX: .value(1), seed: s)
|
||||
/// // → 3.533, 0.530, -0.197, 0.195, -1.792
|
||||
/// TemporalStream(TemporalTendency(distribution: .laplace, parX: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.669, -2.392, 0.910, 0.450, 0.035
|
||||
/// ```
|
||||
///
|
||||
/// **`.alaplace`** — asymmetric Laplace (p=0.7), right tail heavier; parX is scale b
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .alaplace, parX: .value(1), seed: s)
|
||||
/// // → -0.706, 7.906, 1.867, -0.495, 1.675
|
||||
/// TemporalStream(TemporalTendency(distribution: .alaplace, parX: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.527, -3.898, 1.332, -0.039, -0.433
|
||||
/// ```
|
||||
///
|
||||
/// **`.hcos`** — half-cosine, smooth bell centred at 0; output ≈ \[−d/π, d/π\]
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .hcos, parX: .value(1), seed: s)
|
||||
/// // → -0.080, 0.021, 0.024, -0.366, 0.215
|
||||
/// TemporalStream(TemporalTendency(distribution: .hcos, parX: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.162, -0.363, 0.204, 0.118, 0.011
|
||||
/// ```
|
||||
///
|
||||
/// **`.logistic`** — logistic distribution, heavier tails than Gaussian; parX is scale s
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .logistic, parX: .value(1), seed: s)
|
||||
/// // → 0.299, 3.453, -1.994, 1.842, -0.640
|
||||
/// TemporalStream(TemporalTendency(distribution: .logistic, parX: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 1.066, -3.039, 1.379, 0.759, 0.068
|
||||
/// ```
|
||||
///
|
||||
/// **`.poisson`** — integer counts; parX is mean λ (clamped to \[0.001, 30\])
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .poisson, parX: .value(3), seed: s)
|
||||
/// // → 3.0, 3.0, 6.0, 5.0, 0.0
|
||||
/// TemporalStream(TemporalTendency(distribution: .poisson, parX: .value(3)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 1.000, 4.000, 4.000, 1.000, 4.000
|
||||
/// ```
|
||||
///
|
||||
/// **`.arcsin`** — U-shaped, concentrates near ±dispersion; output in \[−disp, disp\]
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .arcsin, parX: .value(1), seed: s)
|
||||
/// // → 0.616, -0.148, -0.986, -0.987, -0.417
|
||||
/// TemporalStream(TemporalTendency(distribution: .arcsin, parX: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.693, -0.990, 0.807, 0.539, 0.054
|
||||
/// ```
|
||||
///
|
||||
/// **`.betaRand`** — flexible shape in \[lo, hi\]; alpha/beta (parA/parB) control skew
|
||||
/// ```swift
|
||||
/// // alpha=2, beta=5 → left-skewed bell (peak near lo side)
|
||||
/// TemporalTendency(distribution: .betaRand,
|
||||
/// parX: .value(0), parY: .value(1),
|
||||
/// parA: .value(2), parB: .value(5), seed: s)
|
||||
/// // → 0.395, 0.539, 0.272, 0.386, 0.304
|
||||
/// TemporalStream(TemporalTendency(distribution: .betaRand,
|
||||
/// parX: .value(0), parY: .value(1),
|
||||
/// parA: .value(2), parB: .value(5)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.482, 0.301, 0.471, 0.415, 0.066
|
||||
///
|
||||
/// // alpha=1, beta=1 → uniform; alpha=beta → symmetric; alpha<1, beta<1 → bimodal
|
||||
/// ```
|
||||
///
|
||||
/// **`.cauchy`** — heavy-tailed, parX=mean, parY=spread; set parA>0 for positive-only
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .cauchy, parX: .value(0), parY: .value(1), seed: s)
|
||||
/// // → -1.457, 0.800, 10.047, 1.641, -1.570
|
||||
/// TemporalStream(TemporalTendency(distribution: .cauchy,
|
||||
/// parX: .value(0), parY: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.962, -6.916, 1.366, 0.640, 0.054
|
||||
/// // (occasional extreme outliers are characteristic of Cauchy)
|
||||
///
|
||||
/// // Positive-only (parA > 0):
|
||||
/// TemporalTendency(distribution: .cauchy, parX: .value(0), parY: .value(1), parA: .value(1))
|
||||
/// TemporalStream(TemporalTendency(distribution: .cauchy, parX: .value(0),
|
||||
/// parY: .value(1), parA: .value(1)))
|
||||
/// ```
|
||||
///
|
||||
/// **`.gauss`** — Gaussian; parX=standard deviation, parY=mean
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .gauss, parX: .value(1), parY: .value(0), seed: s)
|
||||
/// // → -0.554, 1.390, 0.086, -0.441, 2.156
|
||||
/// TemporalStream(TemporalTendency(distribution: .gauss,
|
||||
/// parX: .value(1), parY: .value(0)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.738, -0.281, -0.238, 0.068, 0.328
|
||||
/// ```
|
||||
public enum DistributionKind: Sendable {
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
// EngineDispatch.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Dispatch a throwing engine mutation to the main queue — preserving the
|
||||
/// `SynthesisEngine.pendingQueue` single-producer invariant — and log on failure.
|
||||
///
|
||||
/// Shared by the language-side context types (`LyrebirdRoutineContext`,
|
||||
/// `LyrebirdProcessContext`) whose `add` / `schedule` calls cross from a routine
|
||||
/// or process thread onto the main thread. `label` names the call site in the
|
||||
/// failure message only.
|
||||
func lyrebirdDispatchEngineOp(
|
||||
_ label: String,
|
||||
_ work: @escaping @MainActor () throws -> Void
|
||||
) {
|
||||
DispatchQueue.main.async {
|
||||
// The block runs on the main queue, so main-actor isolation holds.
|
||||
MainActor.assumeIsolated {
|
||||
do { try work() }
|
||||
catch { print("[Lyrebird] \(label) failed: \(error)") }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -165,6 +165,7 @@ public final class EngineHost: @unchecked Sendable {
|
||||
numAudioBuses: config.numAudioBuses,
|
||||
numControlBuses: config.numControlBuses,
|
||||
eventQueueCapacity: config.eventQueueCapacity,
|
||||
maxEventsPerBlock: config.maxEventsPerBlock,
|
||||
driver: config.driver
|
||||
)
|
||||
|
||||
|
||||
@@ -19,6 +19,9 @@ import Foundation
|
||||
/// would invoke the mutation off-main.
|
||||
/// - `LyrebirdAudioUnit.allocateRenderResources()` — overrides a nonisolated `AUAudioUnit`
|
||||
/// method; AU hosts *usually* call it on main, but the contract does not guarantee it.
|
||||
/// - `LyrebirdRoutineContext.onMain(_:)` — lets a `@Sendable` routine/task body construct
|
||||
/// `@MainActor` synthesizers. A body always runs on its own background thread, so this
|
||||
/// caller always takes the off-main `.sync` branch.
|
||||
///
|
||||
/// A bare `MainActor.assumeIsolated` would **trap** (`dispatch_assert_queue_fail`) on those
|
||||
/// off-main paths. This bridge instead:
|
||||
|
||||
@@ -29,14 +29,18 @@ import Synchronization
|
||||
/// driver: driver
|
||||
/// )
|
||||
/// try engine.start()
|
||||
/// engine.add(MySynth())
|
||||
/// try engine.add(MySynth())
|
||||
/// // … audio running …
|
||||
/// engine.stop()
|
||||
/// ```
|
||||
///
|
||||
/// **Thread safety** — `processBlock` runs on the Core Audio RT thread. All public
|
||||
/// scheduling methods (`add`, `remove`, `schedule`) are safe to call from the main thread.
|
||||
/// Never call `processBlock` directly from the main thread while the engine is running.
|
||||
/// **Thread safety** — `processBlock` runs on the Core Audio RT thread; never call it directly
|
||||
/// while the engine is running. `add(_:)` / `schedule(_:at:)` are `@MainActor`-isolated: the
|
||||
/// `pendingQueue` is single-producer, so every enqueue must come from the main thread.
|
||||
/// `remove(_:)` is `nonisolated` — it unbinds via atomics and enqueues a pointer-only event, so
|
||||
/// it is callable from any non-RT thread. From a `LyrebirdRoutine` / `LyrebirdTask` body, go
|
||||
/// through the context (``LyrebirdRoutineContext/add(_:)``, which dispatches to main) rather
|
||||
/// than calling the engine directly. See `ARCHITECTURE.md` §1 and §9.
|
||||
public final class SynthesisEngine {
|
||||
|
||||
/// Process-unique identity. Used by the engine ownership-binding system
|
||||
@@ -158,7 +162,12 @@ public final class SynthesisEngine {
|
||||
/// Hard cap on events processed per block. The staging arrays are reserved to this capacity
|
||||
/// in start(); if more events arrive, excess events are silently dropped rather than
|
||||
/// triggering a realloc on the RT thread.
|
||||
private static let maxEventsPerBlock: Int = 256
|
||||
///
|
||||
/// Bounds both the number of events firing within one block and the future-event
|
||||
/// look-ahead carried across block boundaries (`carryOverEvents`). Set at `init` from
|
||||
/// the `maxEventsPerBlock` parameter; immutable thereafter, so the RT thread reads it
|
||||
/// as a plain `let` with no synchronisation. Default `lyrebirdDefaultMaxEventsPerBlock`.
|
||||
public let maxEventsPerBlock: Int
|
||||
|
||||
/// Lock-free queue for events posted by the main thread, drained by the RT thread.
|
||||
/// Capacity is set at init time and must be a power of two.
|
||||
@@ -192,6 +201,64 @@ public final class SynthesisEngine {
|
||||
_droppedCount.wrappingAdd(1, ordering: .relaxed)
|
||||
}
|
||||
|
||||
/// Monotonic counter of scheduling events dropped by the RT thread because a single
|
||||
/// block's event budget (`maxEventsPerBlock`) was exceeded — either too many events
|
||||
/// fired in one block or the future-event look-ahead overflowed. Distinct from
|
||||
/// `pendingQueueDroppedCount`, which counts main-thread enqueue failures. Read from
|
||||
/// any thread; reset with `resetPerBlockEventDropCount()`.
|
||||
private let _perBlockEventDroppedCount: Atomic<UInt64> = Atomic<UInt64>(0)
|
||||
|
||||
/// Latch set by the RT thread when it drops at least one event for exceeding
|
||||
/// `maxEventsPerBlock`. A non-RT drain (`drainPerBlockEventDropWarning()`) checks,
|
||||
/// prints a one-line console warning, and clears it — so the warning is emitted at
|
||||
/// most once per drain interval regardless of how many events were dropped.
|
||||
private let _perBlockEventDropped: Atomic<Bool> = Atomic<Bool>(false)
|
||||
|
||||
/// Number of scheduling events the RT thread dropped because `maxEventsPerBlock` was
|
||||
/// exceeded since the engine started (or since the last `resetPerBlockEventDropCount()`).
|
||||
/// A non-zero value means a block's onset density or future look-ahead exceeded the cap —
|
||||
/// raise `maxEventsPerBlock` at engine init, or throttle scheduling on the caller side.
|
||||
public var perBlockEventDropCount: UInt64 {
|
||||
_perBlockEventDroppedCount.load(ordering: .acquiring)
|
||||
}
|
||||
|
||||
/// Resets the per-block event-drop counter to zero. Call from any non-RT thread.
|
||||
public func resetPerBlockEventDropCount() {
|
||||
_perBlockEventDroppedCount.store(0, ordering: .releasing)
|
||||
}
|
||||
|
||||
/// Records a per-block event-budget drop. RT-safe: two atomic ops, no allocation,
|
||||
/// no locking, no string construction. Called from `processBlock`'s event-drain loop
|
||||
/// when a staging array is already at `maxEventsPerBlock`.
|
||||
///
|
||||
/// The counter increment is `.relaxed`; the latch store is `.releasing` so it
|
||||
/// synchronizes-with the drain's `.acquiring` CAS in `drainPerBlockEventDropWarning()`.
|
||||
/// That release/acquire edge guarantees the drain thread, once it observes the latch
|
||||
/// set, also sees the counter increment that precedes it in program order — so the
|
||||
/// printed drop count is never stale.
|
||||
@inline(__always)
|
||||
private func _recordPerBlockEventDrop() {
|
||||
_perBlockEventDroppedCount.wrappingAdd(1, ordering: .relaxed)
|
||||
_perBlockEventDropped.store(true, ordering: .releasing)
|
||||
}
|
||||
|
||||
/// Checks the per-block event-drop latch and, if set, prints a one-line console
|
||||
/// warning naming `maxEventsPerBlock` and the cumulative drop count, then clears the
|
||||
/// latch. Non-RT only — shares the `freeWorker`/stop drain sites with the kill-queue
|
||||
/// overflow warning so no RT-thread `print` is ever attempted.
|
||||
internal func drainPerBlockEventDropWarning() {
|
||||
guard _perBlockEventDropped.compareExchange(
|
||||
expected: true,
|
||||
desired: false,
|
||||
successOrdering: .acquiring,
|
||||
failureOrdering: .relaxed
|
||||
).exchanged else { return }
|
||||
let dropped: UInt64 = _perBlockEventDroppedCount.load(ordering: .relaxed)
|
||||
print("[Lyrebird] Warning: scheduling events dropped — a block exceeded "
|
||||
+ "maxEventsPerBlock (\(maxEventsPerBlock)); \(dropped) event(s) dropped so far. "
|
||||
+ "Raise maxEventsPerBlock at engine init, or throttle/spread scheduling.")
|
||||
}
|
||||
|
||||
/// Update the synth/group counters by `delta` (typically `+1` or `-1`).
|
||||
/// Called from `applyEvent` on the RT thread — uses relaxed atomic adds (no allocation,
|
||||
/// no locks, no runtime type checks). The `isGroup` flag is read from `PreparedNode`,
|
||||
@@ -732,13 +799,13 @@ public final class SynthesisEngine {
|
||||
///
|
||||
/// ```swift
|
||||
/// // Pre-processing: runs before all instruments
|
||||
/// engine.add(InputLimiter(), position: .before(engine.mainGroup))
|
||||
/// try engine.add(InputLimiter(), position: .before(engine.mainGroup))
|
||||
///
|
||||
/// // Default instrument add — lands in mainGroup
|
||||
/// engine.add(MySynth())
|
||||
/// try engine.add(MySynth())
|
||||
///
|
||||
/// // Post-processing: runs after all instruments
|
||||
/// engine.add(MasterReverb(), position: .after(engine.mainGroup))
|
||||
/// try engine.add(MasterReverb(), position: .after(engine.mainGroup))
|
||||
/// ```
|
||||
public let mainGroup: Group = Group(persistent: true)
|
||||
|
||||
@@ -763,6 +830,7 @@ public final class SynthesisEngine {
|
||||
numAudioBuses: Int = lyrebirdDefaultNumAudioBuses,
|
||||
numControlBuses: Int = lyrebirdDefaultNumControlBuses,
|
||||
eventQueueCapacity: Int = lyrebirdDefaultEventQueueCapacity,
|
||||
maxEventsPerBlock: Int = lyrebirdDefaultMaxEventsPerBlock,
|
||||
driver: AudioDriver
|
||||
) {
|
||||
// Initialise RT-thread identity TLS key from this known non-RT call
|
||||
@@ -780,6 +848,10 @@ public final class SynthesisEngine {
|
||||
eventQueueCapacity > 0 && eventQueueCapacity & (eventQueueCapacity - 1) == 0,
|
||||
"eventQueueCapacity \(eventQueueCapacity) must be a power of two (e.g. 256, 512, 1024, 2048)."
|
||||
)
|
||||
precondition(
|
||||
maxEventsPerBlock > 0,
|
||||
"maxEventsPerBlock \(maxEventsPerBlock) must be positive."
|
||||
)
|
||||
// Resolution order: explicit caller value → driver suggestion → full block (no sub-blocking).
|
||||
// Explicit values are validated strictly. Driver suggestions that don't fit blockSize are
|
||||
// silently ignored (fall back to full-block mode) so small-blockSize test engines don't crash.
|
||||
@@ -811,6 +883,7 @@ public final class SynthesisEngine {
|
||||
self.numInputChannels = numInputChannels
|
||||
self.numAudioBuses = numAudioBuses
|
||||
self.numControlBuses = numControlBuses
|
||||
self.maxEventsPerBlock = maxEventsPerBlock
|
||||
self.busAllocator = BusAllocator(
|
||||
numAudioBuses: numAudioBuses,
|
||||
numControlBuses: numControlBuses,
|
||||
@@ -998,9 +1071,9 @@ public final class SynthesisEngine {
|
||||
|
||||
// Pre-allocate staging arrays to the hard cap — no RT realloc as long as
|
||||
// events-per-block stays within maxEventsPerBlock (excess are dropped).
|
||||
carryOverEvents.reserveCapacity(SynthesisEngine.maxEventsPerBlock)
|
||||
thisBlockEvents.reserveCapacity(SynthesisEngine.maxEventsPerBlock)
|
||||
nextCarryOver.reserveCapacity(SynthesisEngine.maxEventsPerBlock)
|
||||
carryOverEvents.reserveCapacity(maxEventsPerBlock)
|
||||
thisBlockEvents.reserveCapacity(maxEventsPerBlock)
|
||||
nextCarryOver.reserveCapacity(maxEventsPerBlock)
|
||||
|
||||
// Force eager initialization of module-level `let` constants used by RBJ filters.
|
||||
// Swift module-level lets are protected by swift_once on first access; touching them
|
||||
@@ -1076,6 +1149,7 @@ public final class SynthesisEngine {
|
||||
}
|
||||
self.drainParameterSourceKillQueue()
|
||||
self.drainBufferSwapKillQueue()
|
||||
self.drainPerBlockEventDropWarning()
|
||||
}
|
||||
_setState(.stopped)
|
||||
}
|
||||
@@ -1493,7 +1567,7 @@ public final class SynthesisEngine {
|
||||
// Read clock atomically; only processBlock writes it (RT thread single-writer).
|
||||
let blockStart: SampleTime = _currentTime.load(ordering: .relaxed)
|
||||
let blockEnd: SampleTime = blockStart + SampleTime(blockSize)
|
||||
let cap: Int = SynthesisEngine.maxEventsPerBlock
|
||||
let cap: Int = maxEventsPerBlock
|
||||
|
||||
thisBlockEvents.removeAll(keepingCapacity: true)
|
||||
nextCarryOver.removeAll(keepingCapacity: true)
|
||||
@@ -1502,8 +1576,10 @@ public final class SynthesisEngine {
|
||||
for event: ScheduledEvent in carryOverEvents {
|
||||
if event.targetTime < blockEnd {
|
||||
if thisBlockEvents.count < cap { thisBlockEvents.append(event) }
|
||||
else { _recordPerBlockEventDrop() }
|
||||
} else {
|
||||
if nextCarryOver.count < cap { nextCarryOver.append(event) }
|
||||
else { _recordPerBlockEventDrop() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1512,8 +1588,10 @@ public final class SynthesisEngine {
|
||||
let event: ScheduledEvent = pendingQueue.dequeue() {
|
||||
if event.targetTime < blockEnd {
|
||||
if thisBlockEvents.count < cap { thisBlockEvents.append(event) }
|
||||
else { _recordPerBlockEventDrop() }
|
||||
} else {
|
||||
if nextCarryOver.count < cap { nextCarryOver.append(event) }
|
||||
else { _recordPerBlockEventDrop() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1780,6 +1858,7 @@ public final class SynthesisEngine {
|
||||
}
|
||||
self.drainParameterSourceKillQueue()
|
||||
self.drainBufferSwapKillQueue()
|
||||
self.drainPerBlockEventDropWarning()
|
||||
}
|
||||
timer.resume()
|
||||
freeQueueTimer = timer
|
||||
|
||||
@@ -65,6 +65,10 @@ public struct SynthesisEngineConfig {
|
||||
/// `lyrebirdDefaultEventQueueCapacity`.
|
||||
public let eventQueueCapacity: Int
|
||||
|
||||
/// Per-block scheduling cap — events firing per block and future look-ahead
|
||||
/// depth. Must be positive. Defaults to `lyrebirdDefaultMaxEventsPerBlock`.
|
||||
public let maxEventsPerBlock: Int
|
||||
|
||||
/// Audio driver instance. Held by the engine via `let driver` after
|
||||
/// `init`. Caller transfers ownership at construction time.
|
||||
public let driver: AudioDriver
|
||||
@@ -78,6 +82,7 @@ public struct SynthesisEngineConfig {
|
||||
numAudioBuses: Int = lyrebirdDefaultNumAudioBuses,
|
||||
numControlBuses: Int = lyrebirdDefaultNumControlBuses,
|
||||
eventQueueCapacity: Int = lyrebirdDefaultEventQueueCapacity,
|
||||
maxEventsPerBlock: Int = lyrebirdDefaultMaxEventsPerBlock,
|
||||
driver: AudioDriver
|
||||
) {
|
||||
self.blockSize = blockSize
|
||||
@@ -88,6 +93,7 @@ public struct SynthesisEngineConfig {
|
||||
self.numAudioBuses = numAudioBuses
|
||||
self.numControlBuses = numControlBuses
|
||||
self.eventQueueCapacity = eventQueueCapacity
|
||||
self.maxEventsPerBlock = maxEventsPerBlock
|
||||
self.driver = driver
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
// BeatTrack.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Real-time beat / tempo tracker.
|
||||
///
|
||||
/// Estimates the period and phase of a musical pulse from an **onset detection
|
||||
/// function** (ODF) by autocorrelation with phase locking, emitting
|
||||
/// beat-synchronous triggers plus a continuous tempo estimate. The ODF source
|
||||
/// is selected by ``BeatTrackODF``:
|
||||
///
|
||||
/// - ``BeatTrackODF/spectralFlux(analysis:)`` — FFT-fed; the tracker computes
|
||||
/// its own ODF as the spectral flux of a paired ``SpectralChain/Audio``
|
||||
/// (drop-in; equivalent to SuperCollider's `BeatTrack`).
|
||||
/// - ``BeatTrackODF/feature(_:)`` — feature-fed; you supply the ODF as any
|
||||
/// signal (equivalent to SuperCollider's `BeatTrack2`).
|
||||
///
|
||||
/// Control-rate, 4-output: see ``BeatTrack/Control`` for the row layout.
|
||||
///
|
||||
/// > This is an independent implementation of standard autocorrelation tempo
|
||||
/// > induction with phase locking (see `BeatTrackerCore`), not a port of any
|
||||
/// > SuperCollider source.
|
||||
public enum BeatTrack {
|
||||
|
||||
/// Control-rate beat tracker. ODF source chosen at init via ``BeatTrackODF``.
|
||||
///
|
||||
/// Emits four output rows:
|
||||
/// - `0` — **beat** trigger (`1.0` for the block a beat fires on, else `0.0`)
|
||||
/// - `1` — **eighth** trigger (2× the beat rate)
|
||||
/// - `2` — **sixteenth** trigger (4× the beat rate)
|
||||
/// - `3` — **tempo** in BPM (continuous)
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - odf: Onset-detection-function source — FFT-fed or feature-fed.
|
||||
/// - minBPM: Slowest detectable tempo. Read once at init. Defaults to ``beatTrackMinBPM``.
|
||||
/// - maxBPM: Fastest detectable tempo. Read once at init. Defaults to ``beatTrackMaxBPM``.
|
||||
/// - preferredBPM: Preference-weight centre + pre-lock default tempo. Read
|
||||
/// 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 {
|
||||
|
||||
/// Internal ODF source + the input refs each mode needs. Only one mode's
|
||||
/// state is live; the spectral-flux state (`_prevMag`, `_isFirstFrame`)
|
||||
/// is dormant in feature mode.
|
||||
private enum Source {
|
||||
case spectralFlux(analysis: SpectralChain.Audio?, spectral: SpectralBuffer)
|
||||
case feature(input: any ValidGeneratorInput, isGenerator: Bool)
|
||||
}
|
||||
|
||||
private let _source: Source
|
||||
private var _prevMag: [Float]
|
||||
private var _isFirstFrame: Bool = true
|
||||
private let _core: BeatTrackerCore
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
public override var outputChannelCount: Int { beatTrackOutputRowCount }
|
||||
|
||||
// MARK: - Public inits
|
||||
|
||||
/// - Parameters:
|
||||
/// - odf: Onset-detection-function source — FFT-fed or feature-fed.
|
||||
/// - minBPM: Slowest detectable tempo. Read once at init. Defaults to ``beatTrackMinBPM``.
|
||||
/// - maxBPM: Fastest detectable tempo. Read once at init. Defaults to ``beatTrackMaxBPM``.
|
||||
/// - preferredBPM: Preference-weight centre + pre-lock default tempo.
|
||||
/// Read once at init. Defaults to ``beatTrackPreferredBPM``.
|
||||
/// - windowSeconds: ODF history length for autocorrelation. Read once
|
||||
/// at init. Defaults to ``beatTrackMaxWindowSeconds``.
|
||||
public convenience init(
|
||||
odf: BeatTrackODF,
|
||||
minBPM: Double = beatTrackMinBPM,
|
||||
maxBPM: Double = beatTrackMaxBPM,
|
||||
preferredBPM: Double = beatTrackPreferredBPM,
|
||||
windowSeconds: Double = beatTrackMaxWindowSeconds
|
||||
) {
|
||||
let source: Source
|
||||
switch odf {
|
||||
case .spectralFlux(let chain):
|
||||
source = .spectralFlux(analysis: chain, spectral: chain.spectralBuffer)
|
||||
case .feature(let signal):
|
||||
let resolved: any ValidGeneratorInput = signal._resolvedInput()
|
||||
source = .feature(input: resolved, isGenerator: resolved is any Generator)
|
||||
}
|
||||
self.init(
|
||||
source: source,
|
||||
minBPM: minBPM,
|
||||
maxBPM: maxBPM,
|
||||
preferredBPM: preferredBPM,
|
||||
windowSeconds: windowSeconds
|
||||
)
|
||||
}
|
||||
|
||||
/// FFT-fed convenience: track the spectral flux of `analysis`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - analysis: Paired ``SpectralChain/Audio`` (analyze-only). Its
|
||||
/// `spectralBuffer` is read once per audio block to compute spectral flux.
|
||||
/// - minBPM: Slowest detectable tempo. Defaults to ``beatTrackMinBPM``.
|
||||
/// - maxBPM: Fastest detectable tempo. Defaults to ``beatTrackMaxBPM``.
|
||||
/// - preferredBPM: Preference-weight centre + pre-lock default tempo.
|
||||
/// Defaults to ``beatTrackPreferredBPM``.
|
||||
/// - windowSeconds: ODF history length. Defaults to ``beatTrackMaxWindowSeconds``.
|
||||
public convenience init(
|
||||
analysis: SpectralChain.Audio,
|
||||
minBPM: Double = beatTrackMinBPM,
|
||||
maxBPM: Double = beatTrackMaxBPM,
|
||||
preferredBPM: Double = beatTrackPreferredBPM,
|
||||
windowSeconds: Double = beatTrackMaxWindowSeconds
|
||||
) {
|
||||
self.init(
|
||||
source: .spectralFlux(analysis: analysis, spectral: analysis.spectralBuffer),
|
||||
minBPM: minBPM,
|
||||
maxBPM: maxBPM,
|
||||
preferredBPM: preferredBPM,
|
||||
windowSeconds: windowSeconds
|
||||
)
|
||||
}
|
||||
|
||||
/// Feature-fed convenience: track an externally supplied ODF signal.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - feature: Onset detection function signal. Reduced to one ODF value
|
||||
/// per audio block (block max).
|
||||
/// - minBPM: Slowest detectable tempo. Defaults to ``beatTrackMinBPM``.
|
||||
/// - maxBPM: Fastest detectable tempo. Defaults to ``beatTrackMaxBPM``.
|
||||
/// - preferredBPM: Preference-weight centre + pre-lock default tempo.
|
||||
/// Defaults to ``beatTrackPreferredBPM``.
|
||||
/// - windowSeconds: ODF history length. Defaults to ``beatTrackMaxWindowSeconds``.
|
||||
public convenience init(
|
||||
feature: any ValidGeneratorInput,
|
||||
minBPM: Double = beatTrackMinBPM,
|
||||
maxBPM: Double = beatTrackMaxBPM,
|
||||
preferredBPM: Double = beatTrackPreferredBPM,
|
||||
windowSeconds: Double = beatTrackMaxWindowSeconds
|
||||
) {
|
||||
let resolved: any ValidGeneratorInput = feature._resolvedInput()
|
||||
self.init(
|
||||
source: .feature(input: resolved, isGenerator: resolved is any Generator),
|
||||
minBPM: minBPM,
|
||||
maxBPM: maxBPM,
|
||||
preferredBPM: preferredBPM,
|
||||
windowSeconds: windowSeconds
|
||||
)
|
||||
}
|
||||
|
||||
/// Buffer-only FFT-fed convenience. For tests / advanced use; no analysis
|
||||
/// auto-pull (the caller drives the chain populating `spectral`).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - spectral: Spectral frame buffer read each block for flux.
|
||||
/// - minBPM: Slowest detectable tempo. Defaults to ``beatTrackMinBPM``.
|
||||
/// - maxBPM: Fastest detectable tempo. Defaults to ``beatTrackMaxBPM``.
|
||||
/// - preferredBPM: Preference-weight centre + pre-lock default tempo.
|
||||
/// Defaults to ``beatTrackPreferredBPM``.
|
||||
/// - windowSeconds: ODF history length. Defaults to ``beatTrackMaxWindowSeconds``.
|
||||
public convenience init(
|
||||
spectral: SpectralBuffer,
|
||||
minBPM: Double = beatTrackMinBPM,
|
||||
maxBPM: Double = beatTrackMaxBPM,
|
||||
preferredBPM: Double = beatTrackPreferredBPM,
|
||||
windowSeconds: Double = beatTrackMaxWindowSeconds
|
||||
) {
|
||||
self.init(
|
||||
source: .spectralFlux(analysis: nil, spectral: spectral),
|
||||
minBPM: minBPM,
|
||||
maxBPM: maxBPM,
|
||||
preferredBPM: preferredBPM,
|
||||
windowSeconds: windowSeconds
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Designated init
|
||||
|
||||
private init(
|
||||
source: Source,
|
||||
minBPM: Double,
|
||||
maxBPM: Double,
|
||||
preferredBPM: Double,
|
||||
windowSeconds: Double
|
||||
) {
|
||||
self._source = source
|
||||
switch source {
|
||||
case .spectralFlux(_, let spectral):
|
||||
self._prevMag = [Float](repeating: 0, count: spectral.binCount)
|
||||
case .feature:
|
||||
self._prevMag = []
|
||||
}
|
||||
self._core = BeatTrackerCore(
|
||||
minBPM: minBPM,
|
||||
maxBPM: maxBPM,
|
||||
preferredBPM: preferredBPM,
|
||||
windowSeconds: windowSeconds,
|
||||
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,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let odf: Double = computeODF(graph: graph, count: count)
|
||||
|
||||
_core.processBlock(
|
||||
odf: odf,
|
||||
sampleCount: count,
|
||||
sampleRate: graph.engine.sampleRate
|
||||
)
|
||||
|
||||
previousOutputValue = fillBeatTrackerOutput(
|
||||
into: &_result, core: _core, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
/// Per-block onset-detection-function value for the active source.
|
||||
private func computeODF(graph: SynthGraph, count: Int) -> Double {
|
||||
switch _source {
|
||||
case .spectralFlux(let analysis, let spectral):
|
||||
_ = analysis?.calculatedSamples(graph: graph, count: count)
|
||||
return spectralFlux(spectral)
|
||||
case .feature(let input, let isGenerator):
|
||||
// Scalar feature → constant ODF (no per-block heap alloc);
|
||||
// generator feature → block-max of its output row.
|
||||
if isGenerator {
|
||||
let row: [Double] = input.calculatedSamples(
|
||||
graph: graph, count: count).first ?? []
|
||||
return blockMaxODF(row, count: count)
|
||||
}
|
||||
return max(0.0, input.floatValue(graph: graph))
|
||||
}
|
||||
}
|
||||
|
||||
/// Frame-to-frame magnitude-change flux (onset proxy). Identical measure
|
||||
/// to ``SpectralFlux``: RMS of per-bin magnitude differences. Returns `0`
|
||||
/// on the first block (no previous frame to compare).
|
||||
private func spectralFlux(_ spectral: SpectralBuffer) -> Double {
|
||||
let binCount: Int = spectral.binCount
|
||||
guard binCount > 0 else { return 0.0 }
|
||||
|
||||
if _isFirstFrame {
|
||||
for k: Int in 0..<binCount {
|
||||
_prevMag[k] = spectral.magnitude(at: k)
|
||||
}
|
||||
_isFirstFrame = false
|
||||
return 0.0
|
||||
}
|
||||
|
||||
var sumSquares: Double = 0.0
|
||||
for k: Int in 0..<binCount {
|
||||
let mag: Double = Double(spectral.magnitude(at: k))
|
||||
let prev: Double = Double(_prevMag[k])
|
||||
let diff: Double = mag - prev
|
||||
sumSquares += diff * diff
|
||||
_prevMag[k] = Float(mag)
|
||||
}
|
||||
return (sumSquares / Double(binCount)).squareRoot()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
// GeneratorEnum conformance omitted: BeatTrack is Control-rate only.
|
||||
@@ -0,0 +1,72 @@
|
||||
// BeatTrackConstants.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Number of ``BeatTrack`` output rows: beat, eighth, sixteenth, tempo.
|
||||
public let beatTrackOutputRowCount: Int = 4
|
||||
|
||||
/// Onset-detection-function (ODF) decimation target rate in Hz. The per-block
|
||||
/// ODF is reduced to one feature per `round(sampleRate / beatTrackFeatureRateHz)`
|
||||
/// samples so the autocorrelation window length is independent of block size.
|
||||
/// `≈ 86 Hz` matches the conventional 512-sample STFT hop at 44.1 kHz.
|
||||
public let beatTrackFeatureRateHz: Double = 86.0
|
||||
|
||||
/// Length of the ODF history (seconds) retained for autocorrelation. Six seconds
|
||||
/// at `beatTrackFeatureRateHz` is ≈ 516 features — long enough to resolve tempi
|
||||
/// down to ``beatTrackMinBPM`` with several beat periods in the window.
|
||||
public let beatTrackMaxWindowSeconds: Double = 6.0
|
||||
|
||||
/// Slowest detectable tempo (BPM). Sets the longest autocorrelation lag.
|
||||
public let beatTrackMinBPM: Double = 60.0
|
||||
|
||||
/// Fastest detectable tempo (BPM). Sets the shortest autocorrelation lag.
|
||||
public let beatTrackMaxBPM: Double = 200.0
|
||||
|
||||
/// Centre of the tempo-preference weight and the pre-lock default tempo (BPM).
|
||||
/// The weight biases the autocorrelation peak toward perceptually likely tempi,
|
||||
/// resolving the octave ambiguity between a pulse and its harmonics.
|
||||
public let beatTrackPreferredBPM: Double = 120.0
|
||||
|
||||
/// Width (in octaves) of the log-Gaussian tempo-preference weight.
|
||||
public let beatTrackPreferenceWidthOctaves: Double = 0.9
|
||||
|
||||
/// One-pole smoothing factor applied to the beat period across successive
|
||||
/// analyses. `0` = instant; `1` = frozen. Higher values steady the tempo output.
|
||||
public let beatTrackTempoSmoothing: Double = 0.9
|
||||
|
||||
/// Re-run tempo induction (autocorrelation + phase realignment) every N emitted
|
||||
/// ODF features. A small power of two amortises the analysis cost.
|
||||
public let beatTrackAnalysisHopFeatures: Int = 8
|
||||
|
||||
/// Time constant (seconds) of the running-mean subtraction used to whiten the
|
||||
/// ODF before autocorrelation. Removes DC offset / slow drift so a non-zero
|
||||
/// baseline does not bias the periodicity estimate.
|
||||
public let beatTrackMeanAdaptSeconds: Double = 1.0
|
||||
|
||||
/// Minimum normalised autocorrelation peak required to update the tempo estimate.
|
||||
/// Below this the input is treated as having no clear pulse (silence / noise);
|
||||
/// the previous period is held and the phase free-runs.
|
||||
public let beatTrackMinPeakStrength: Double = 1.0e-9
|
||||
|
||||
/// Seconds per minute — used in the BPM ↔ feature-lag conversions.
|
||||
internal let beatTrackSecondsPerMinute: Double = 60.0
|
||||
|
||||
/// Eighth-note subdivisions per beat (row 1 fires at this multiple of the beat rate).
|
||||
internal let beatTrackEighthsPerBeat: Double = 2.0
|
||||
|
||||
/// Sixteenth-note subdivisions per beat (row 2 fires at this multiple of the beat rate).
|
||||
internal let beatTrackSixteenthsPerBeat: Double = 4.0
|
||||
|
||||
/// Coefficient `½` in the log-Gaussian preference exponent `−½ · z²`.
|
||||
internal let beatTrackGaussianExponentCoeff: Double = 0.5
|
||||
|
||||
/// Coefficient `½` in the parabolic peak-interpolation offset `½ · (yₘ − yₚ) / denom`.
|
||||
internal let beatTrackParabolicCoeff: Double = 0.5
|
||||
|
||||
/// Minimum parabola curvature magnitude for peak refinement; below this the
|
||||
/// interpolation is degenerate and the integer lag is returned unchanged.
|
||||
internal let beatTrackParabolicEpsilon: Double = 1.0e-12
|
||||
@@ -0,0 +1,59 @@
|
||||
// BeatTrackHelpers.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import Foundation
|
||||
|
||||
/// Peak ODF value across one audio block. Onsets are impulsive, so the max
|
||||
/// preserves the peak regardless of where in the block it lands. Returns `0` for
|
||||
/// an empty row.
|
||||
@inline(__always)
|
||||
internal func blockMaxODF(_ row: [Double], count: Int) -> Double {
|
||||
guard !row.isEmpty else { return 0.0 }
|
||||
let n: Int = min(count, row.count)
|
||||
var peak: Double = 0.0
|
||||
for i: Int in 0..<n {
|
||||
let v: Double = row[i]
|
||||
if v > peak { peak = v }
|
||||
}
|
||||
return peak
|
||||
}
|
||||
|
||||
/// Fill the 4-row beat-tracker output buffer flat across the block from the
|
||||
/// core's per-block trigger / tempo state. Returns the row-0 (beat) value for
|
||||
/// `previousOutputValue`. No heap allocation — the four row values are filled
|
||||
/// directly (no intermediate array).
|
||||
@inline(__always)
|
||||
internal func fillBeatTrackerOutput(
|
||||
into result: inout [[Double]],
|
||||
core: BeatTrackerCore,
|
||||
count: Int
|
||||
) -> Double {
|
||||
let beat: Double = core.beatTriggered ? 1.0 : 0.0
|
||||
let eighth: Double = core.eighthTriggered ? 1.0 : 0.0
|
||||
let sixteenth: Double = core.sixteenthTriggered ? 1.0 : 0.0
|
||||
let tempo: Double = core.tempoBPM
|
||||
fillFlatRow(&result, row: 0, value: beat, count: count)
|
||||
fillFlatRow(&result, row: 1, value: eighth, count: count)
|
||||
fillFlatRow(&result, row: 2, value: sixteenth, count: count)
|
||||
fillFlatRow(&result, row: 3, value: tempo, count: count)
|
||||
return beat
|
||||
}
|
||||
|
||||
/// Fill one output row with a constant value over `count` samples.
|
||||
@inline(__always)
|
||||
private func fillFlatRow(
|
||||
_ result: inout [[Double]],
|
||||
row: Int,
|
||||
value: Double,
|
||||
count: Int
|
||||
) {
|
||||
var v: Double = value
|
||||
result[row].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
vDSP_vfillD(&v, base, 1, vDSP_Length(count))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// BeatTrackODF.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Selects where ``BeatTrack`` gets its onset detection function (ODF) — the
|
||||
/// one-dimensional signal whose peaks the tracker locks onto.
|
||||
///
|
||||
/// This is the implementation flag that folds the two SuperCollider beat-tracker
|
||||
/// flavours into a single ``BeatTrack`` generator. The cases carry different
|
||||
/// inputs (an FFT chain vs an arbitrary signal), so the selector is an enum
|
||||
/// rather than a `Bool`.
|
||||
public enum BeatTrackODF {
|
||||
|
||||
/// FFT-fed: compute the ODF internally as the spectral flux of `analysis`
|
||||
/// (the same frame-to-frame magnitude-change measure as ``SpectralFlux``).
|
||||
/// Drop-in — wire an analyze-only ``SpectralChain/Audio`` on the source you
|
||||
/// want to track. Equivalent to SuperCollider's `BeatTrack`.
|
||||
case spectralFlux(analysis: SpectralChain.Audio)
|
||||
|
||||
/// Feature-fed: take an externally supplied ODF — any signal whose peaks
|
||||
/// coincide with onsets (``SpectralFlux``, ``OnsetDetector``, an
|
||||
/// amplitude-difference feature, …). Reduced to one ODF value per audio
|
||||
/// block (block max). Equivalent to SuperCollider's `BeatTrack2`.
|
||||
case feature(any ValidGeneratorInput)
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
// BeatTrackerCore.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Shared autocorrelation tempo + beat-phase tracker backing ``BeatTrack`` (both
|
||||
/// the FFT-fed and feature-fed ODF sources). Independent of the `Generator`
|
||||
/// machinery: it consumes one per-audio-block onset-detection-function (ODF)
|
||||
/// value at a time and produces beat / eighth / sixteenth triggers plus a
|
||||
/// continuous tempo estimate.
|
||||
///
|
||||
/// All buffers are allocated once at `init`; ``processBlock(odf:sampleCount:)``
|
||||
/// performs no allocation and is safe to call from the render thread (the
|
||||
/// front-end generators call it from `_computeSamples`).
|
||||
///
|
||||
/// ## Pipeline
|
||||
/// 1. **Decimation** — per-block ODF values are combined by max over a feature
|
||||
/// hop of `round(sampleRate / featureRateHz)` samples; each completed hop
|
||||
/// emits one ODF feature.
|
||||
/// 2. **Whitening** — a running mean is subtracted and the result half-wave
|
||||
/// rectified, removing DC / drift bias.
|
||||
/// 3. **History** — features are pushed into a power-of-two ring buffer.
|
||||
/// 4. **Tempo induction** — every ``analysisHop`` features the windowed ODF is
|
||||
/// autocorrelated over the lag range for `[minBPM, maxBPM]`, weighted by a
|
||||
/// log-Gaussian preference curve; the peak lag is the smoothed beat period.
|
||||
/// 5. **Phase locking** — a phase accumulator advances at the current tempo;
|
||||
/// each analysis re-aligns it to the recent ODF peaks.
|
||||
///
|
||||
/// Algorithm is an independent implementation of standard autocorrelation tempo
|
||||
/// induction with phase locking — not a port of any SuperCollider source.
|
||||
final class BeatTrackerCore {
|
||||
|
||||
// MARK: - Configuration (fixed at init)
|
||||
|
||||
/// Samples per emitted feature. Sample-rate dependent, so resolved lazily on
|
||||
/// the first ``processBlock(odf:sampleCount:sampleRate:)`` (the only piece of
|
||||
/// state that needs the engine sample rate — ring size and lag range derive
|
||||
/// from the nominal feature rate alone). `0` until resolved.
|
||||
private var featureHop: Int = 0
|
||||
private let ringMask: Int
|
||||
private let windowLen: Int
|
||||
private let lagMin: Int
|
||||
private let lagMax: Int
|
||||
private let analysisHop: Int
|
||||
private let preferredLag: Double
|
||||
private let preferenceWidth: Double
|
||||
private let tempoSmoothing: Double
|
||||
private let meanAdaptCoeff: Double
|
||||
private let featureRate: Double
|
||||
private let minPeriod: Double
|
||||
private let maxPeriod: Double
|
||||
|
||||
// MARK: - Buffers (allocated once)
|
||||
|
||||
private var ring: [Double]
|
||||
|
||||
// MARK: - Decimation state
|
||||
|
||||
private var sampleAccum: Int = 0
|
||||
private var odfAccum: Double = 0.0
|
||||
|
||||
// MARK: - History state
|
||||
|
||||
private var writeIndex: Int = 0
|
||||
private var featureCount: Int = 0
|
||||
private var meanODF: Double = 0.0
|
||||
|
||||
// MARK: - Tempo / phase state
|
||||
|
||||
private var period: Double
|
||||
private var phase: Double = 0.0
|
||||
private var analysisCountdown: Int
|
||||
|
||||
// MARK: - Per-block outputs
|
||||
|
||||
/// `true` when a beat fired during the most recent ``processBlock(odf:sampleCount:)``.
|
||||
private(set) var beatTriggered: Bool = false
|
||||
/// `true` when an eighth-note subdivision fired (2× the beat rate).
|
||||
private(set) var eighthTriggered: Bool = false
|
||||
/// `true` when a sixteenth-note subdivision fired (4× the beat rate).
|
||||
private(set) var sixteenthTriggered: Bool = false
|
||||
/// Current tempo estimate in BPM.
|
||||
private(set) var tempoBPM: Double
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - minBPM: Slowest detectable tempo.
|
||||
/// - maxBPM: Fastest detectable tempo.
|
||||
/// - preferredBPM: Preference-weight centre + pre-lock default tempo.
|
||||
/// - windowSeconds: ODF history length for autocorrelation.
|
||||
/// - featureRateHz: ODF decimation target rate.
|
||||
init(
|
||||
minBPM: Double,
|
||||
maxBPM: Double,
|
||||
preferredBPM: Double,
|
||||
windowSeconds: Double,
|
||||
featureRateHz: Double
|
||||
) {
|
||||
let safeFeatureRate: Double = max(1.0, featureRateHz)
|
||||
let safeMinBPM: Double = max(1.0, min(minBPM, maxBPM))
|
||||
let safeMaxBPM: Double = max(safeMinBPM + 1.0, max(minBPM, maxBPM))
|
||||
|
||||
self.featureRate = safeFeatureRate
|
||||
|
||||
// Lag range from the tempo bounds: lag (features) = featureRate · 60 / BPM.
|
||||
let minLagD: Double = safeFeatureRate * beatTrackSecondsPerMinute / safeMaxBPM
|
||||
let maxLagD: Double = safeFeatureRate * beatTrackSecondsPerMinute / safeMinBPM
|
||||
self.lagMin = max(1, Int(minLagD.rounded(.down)))
|
||||
self.lagMax = max(self.lagMin + 1, Int(maxLagD.rounded(.up)))
|
||||
self.minPeriod = minLagD
|
||||
self.maxPeriod = maxLagD
|
||||
|
||||
// History window: at least a few of the longest periods.
|
||||
let requestedFeatures: Int = max(
|
||||
self.lagMax * 2,
|
||||
Int((max(0.1, windowSeconds) * safeFeatureRate).rounded(.up))
|
||||
)
|
||||
let ringSize: Int = lyrebirdNextPowerOfTwo(max(2, requestedFeatures))
|
||||
self.ring = [Double](repeating: 0.0, count: ringSize)
|
||||
self.ringMask = ringSize - 1
|
||||
// Cap the analysis window so the oldest (sample, lag) pair never wraps
|
||||
// past the ring onto just-written features: even when `requestedFeatures`
|
||||
// is an exact power of two (then `ringSize == requestedFeatures`), keep
|
||||
// `windowLen + lagMax ≤ ringSize`.
|
||||
self.windowLen = max(self.lagMin + 1, min(requestedFeatures, ringSize - self.lagMax))
|
||||
|
||||
self.analysisHop = max(1, beatTrackAnalysisHopFeatures)
|
||||
self.preferredLag = safeFeatureRate * beatTrackSecondsPerMinute / max(1.0, preferredBPM)
|
||||
self.preferenceWidth = max(0.05, beatTrackPreferenceWidthOctaves)
|
||||
self.tempoSmoothing = min(0.999, max(0.0, beatTrackTempoSmoothing))
|
||||
|
||||
// Per-feature one-pole coefficient for the running-mean subtraction.
|
||||
let meanTimeFeatures: Double = max(1.0, beatTrackMeanAdaptSeconds * safeFeatureRate)
|
||||
self.meanAdaptCoeff = 1.0 - Foundation.exp(-1.0 / meanTimeFeatures)
|
||||
|
||||
self.period = self.preferredLag
|
||||
self.tempoBPM = max(safeMinBPM, min(safeMaxBPM, preferredBPM))
|
||||
self.analysisCountdown = self.analysisHop
|
||||
}
|
||||
|
||||
// MARK: - Per-block entry point
|
||||
|
||||
/// Feed one audio block's ODF value. Updates the decimation accumulator and,
|
||||
/// for every completed feature hop, advances the tracker. The trigger /
|
||||
/// tempo outputs reflect the state after this block.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - odf: This block's onset-detection-function value (≥ 0).
|
||||
/// - sampleCount: Number of audio samples in this block.
|
||||
/// - sampleRate: Engine sample rate (Hz); resolves the feature hop on first call.
|
||||
func processBlock(odf: Double, sampleCount: Int, sampleRate: Double) {
|
||||
beatTriggered = false
|
||||
eighthTriggered = false
|
||||
sixteenthTriggered = false
|
||||
|
||||
if featureHop == 0 {
|
||||
let safeSampleRate: Double = max(1.0, sampleRate)
|
||||
featureHop = max(1, Int((safeSampleRate / featureRate).rounded()))
|
||||
}
|
||||
|
||||
let safeODF: Double = odf.isFinite ? max(0.0, odf) : 0.0
|
||||
odfAccum = max(odfAccum, safeODF)
|
||||
sampleAccum += max(0, sampleCount)
|
||||
|
||||
// Emit as many features as the accumulated sample count allows (handles
|
||||
// blocks longer than one feature hop). Triggers OR across features.
|
||||
while sampleAccum >= featureHop {
|
||||
sampleAccum -= featureHop
|
||||
emitFeature(odfAccum)
|
||||
odfAccum = 0.0
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Feature processing
|
||||
|
||||
private func emitFeature(_ raw: Double) {
|
||||
// Whiten: subtract a slow running mean, half-wave rectify.
|
||||
meanODF += (raw - meanODF) * meanAdaptCoeff
|
||||
var value: Double = raw - meanODF
|
||||
if value < 0.0 { value = 0.0 }
|
||||
value = denormalsToZero(value)
|
||||
|
||||
ring[writeIndex & ringMask] = value
|
||||
writeIndex += 1
|
||||
featureCount += 1
|
||||
|
||||
advancePhase()
|
||||
|
||||
analysisCountdown -= 1
|
||||
// Need at least the longest lag plus one beat of history before the ACF
|
||||
// is meaningful.
|
||||
if analysisCountdown <= 0 && featureCount >= lagMax + lagMin {
|
||||
analysisCountdown = analysisHop
|
||||
runAnalysis()
|
||||
}
|
||||
}
|
||||
|
||||
/// Advance the beat-phase accumulator by one feature at the current tempo,
|
||||
/// firing nested subdivision triggers on grid crossings.
|
||||
private func advancePhase() {
|
||||
let safePeriod: Double = max(1.0, period)
|
||||
let increment: Double = 1.0 / safePeriod
|
||||
let raw: Double = phase + increment
|
||||
|
||||
// Nested crossings: beat = integer, eighth = ½, sixteenth = ¼. A beat
|
||||
// boundary (raw ≥ 1) also crosses an eighth and sixteenth boundary, so
|
||||
// counts accumulate as beats:N, eighths:2N, sixteenths:4N.
|
||||
if raw >= 1.0 { beatTriggered = true }
|
||||
if Foundation.floor(raw * beatTrackEighthsPerBeat)
|
||||
> Foundation.floor(phase * beatTrackEighthsPerBeat) { eighthTriggered = true }
|
||||
if Foundation.floor(raw * beatTrackSixteenthsPerBeat)
|
||||
> Foundation.floor(phase * beatTrackSixteenthsPerBeat) { sixteenthTriggered = true }
|
||||
|
||||
var wrapped: Double = raw.truncatingRemainder(dividingBy: 1.0)
|
||||
if wrapped < 0.0 { wrapped += 1.0 }
|
||||
phase = wrapped
|
||||
}
|
||||
|
||||
// MARK: - Tempo induction
|
||||
|
||||
private func runAnalysis() {
|
||||
let available: Int = min(featureCount, windowLen)
|
||||
guard available > lagMax else { return }
|
||||
|
||||
var bestLag: Int = 0
|
||||
var bestScore: Double = 0.0
|
||||
var bestRawPeak: Double = 0.0
|
||||
|
||||
// Weighted, length-normalised autocorrelation over the candidate lags.
|
||||
for lag: Int in lagMin...lagMax {
|
||||
let terms: Int = available - lag
|
||||
if terms <= 0 { continue }
|
||||
var sum: Double = 0.0
|
||||
for j: Int in 0..<terms {
|
||||
let a: Double = ring[(writeIndex - 1 - j) & ringMask]
|
||||
let b: Double = ring[(writeIndex - 1 - j - lag) & ringMask]
|
||||
sum += a * b
|
||||
}
|
||||
let acf: Double = sum / Double(terms)
|
||||
let weight: Double = preferenceWeight(forLag: Double(lag))
|
||||
let score: Double = acf * weight
|
||||
if score > bestScore {
|
||||
bestScore = score
|
||||
bestLag = lag
|
||||
bestRawPeak = acf
|
||||
}
|
||||
}
|
||||
|
||||
// No clear pulse → hold the current period and let the phase free-run.
|
||||
guard bestLag > 0, bestRawPeak > beatTrackMinPeakStrength else { return }
|
||||
|
||||
let refinedLag: Double = parabolicPeak(around: bestLag, available: available)
|
||||
let clampedLag: Double = min(maxPeriod, max(minPeriod, refinedLag))
|
||||
|
||||
period = tempoSmoothing * period + (1.0 - tempoSmoothing) * clampedLag
|
||||
period = max(1.0, period)
|
||||
tempoBPM = beatTrackSecondsPerMinute * featureRate / period
|
||||
|
||||
realignPhase(periodLag: clampedLag)
|
||||
}
|
||||
|
||||
/// Log-Gaussian preference weight centred on ``preferredLag``.
|
||||
private func preferenceWeight(forLag lag: Double) -> Double {
|
||||
let octaves: Double = Foundation.log2(lag / preferredLag)
|
||||
let z: Double = octaves / preferenceWidth
|
||||
return Foundation.exp(-beatTrackGaussianExponentCoeff * z * z)
|
||||
}
|
||||
|
||||
/// Sub-feature peak location via parabolic interpolation of the
|
||||
/// length-normalised ACF at `lag-1, lag, lag+1`.
|
||||
private func parabolicPeak(around lag: Int, available: Int) -> Double {
|
||||
let lagD: Double = Double(lag)
|
||||
guard lag - 1 >= lagMin, lag + 1 <= lagMax else { return lagD }
|
||||
let ym: Double = normalisedACF(lag: lag - 1, available: available)
|
||||
let y0: Double = normalisedACF(lag: lag, available: available)
|
||||
let yp: Double = normalisedACF(lag: lag + 1, available: available)
|
||||
let denom: Double = ym - 2.0 * y0 + yp
|
||||
if abs(denom) < beatTrackParabolicEpsilon { return lagD }
|
||||
let delta: Double = beatTrackParabolicCoeff * (ym - yp) / denom
|
||||
if delta < -1.0 || delta > 1.0 { return lagD }
|
||||
return lagD + delta
|
||||
}
|
||||
|
||||
private func normalisedACF(lag: Int, available: Int) -> Double {
|
||||
let terms: Int = available - lag
|
||||
if terms <= 0 { return 0.0 }
|
||||
var sum: Double = 0.0
|
||||
for j: Int in 0..<terms {
|
||||
let a: Double = ring[(writeIndex - 1 - j) & ringMask]
|
||||
let b: Double = ring[(writeIndex - 1 - j - lag) & ringMask]
|
||||
sum += a * b
|
||||
}
|
||||
return sum / Double(terms)
|
||||
}
|
||||
|
||||
/// Re-align the phase accumulator so beat crossings coincide with the recent
|
||||
/// ODF peaks. Finds the grid offset (mod the integer period) whose comb of
|
||||
/// features carries the most onset energy.
|
||||
private func realignPhase(periodLag: Double) {
|
||||
let p: Int = max(1, Int(periodLag.rounded()))
|
||||
let available: Int = min(featureCount, windowLen)
|
||||
guard available >= p else { return }
|
||||
|
||||
var bestOffset: Int = 0
|
||||
var bestEnergy: Double = -1.0
|
||||
for offset: Int in 0..<p {
|
||||
var energy: Double = 0.0
|
||||
var j: Int = offset
|
||||
while j < available {
|
||||
energy += ring[(writeIndex - 1 - j) & ringMask]
|
||||
j += p
|
||||
}
|
||||
if energy > bestEnergy {
|
||||
bestEnergy = energy
|
||||
bestOffset = offset
|
||||
}
|
||||
}
|
||||
|
||||
// The most recent feature (offset 0) sits `bestOffset` features after the
|
||||
// last on-grid beat, so its beat fraction is bestOffset / period.
|
||||
var newPhase: Double = Double(bestOffset) / max(1.0, period)
|
||||
newPhase = newPhase.truncatingRemainder(dividingBy: 1.0)
|
||||
if newPhase < 0.0 { newPhase += 1.0 }
|
||||
phase = newPhase
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
// Loudness.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Psychoacoustic loudness meter — perceived loudness in **sones** from the
|
||||
/// magnitude spectrum of a paired analyze-only ``SpectralChain/Audio``.
|
||||
///
|
||||
/// Three fidelity models are folded into the one generator behind a
|
||||
/// ``LoudnessModel`` flag (mirroring the `Balance` `logDomain:` and `BeatTrack`
|
||||
/// `BeatTrackODF` folds):
|
||||
///
|
||||
/// - ``LoudnessModel/barkEstimate`` — cheap Stevens power-law band estimate.
|
||||
/// - ``LoudnessModel/realtimeZwicker(smask:tmask:)`` — SC `Loudness`-style
|
||||
/// critical-band Zwicker loudness with spectral + temporal masking.
|
||||
/// - ``LoudnessModel/iso532b(field:)`` — full ISO 532 B / DIN 45631 stationary
|
||||
/// Zwicker loudness.
|
||||
///
|
||||
/// Control-rate, single-row output (sones). See ``Loudness/Control``.
|
||||
///
|
||||
/// > **Clean-room note.** SuperCollider's `Loudness` (Nick Collins) is GPL. This
|
||||
/// > is an independent implementation from the published Zwicker model and the
|
||||
/// > ISO 532 B / DIN 45631 standard; output is in sones, not bit-exact with SC.
|
||||
public enum Loudness {
|
||||
|
||||
/// Control-rate loudness meter. Model selected at init via ``LoudnessModel``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - model: Loudness model + its parameters. Defaults to
|
||||
/// ``LoudnessModel/realtimeZwicker(smask:tmask:)`` with the standard
|
||||
/// `smask`/`tmask`.
|
||||
/// - analysis: Paired ``SpectralChain/Audio`` (analyze-only). Its
|
||||
/// `spectralBuffer` is read once per audio block.
|
||||
/// - sampleRate: Sample rate in Hz (bin→frequency mapping + block timing).
|
||||
/// - 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 {
|
||||
|
||||
private let _analysis: SpectralChain.Audio?
|
||||
private let _spectral: SpectralBuffer
|
||||
private let _model: LoudnessModel
|
||||
private let _core: LoudnessBandCore
|
||||
private let _sampleRate: Double
|
||||
private var _mulAdd: MulAddSpec
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 0.0
|
||||
|
||||
/// - Parameters:
|
||||
/// - model: Loudness model + parameters. Defaults to
|
||||
/// ``LoudnessModel/realtimeZwicker(smask:tmask:)``.
|
||||
/// - analysis: Paired ``SpectralChain/Audio`` (analyze-only).
|
||||
/// - sampleRate: Sample rate in Hz.
|
||||
/// - calibrationDB: dBFS→SPL offset. Defaults to ``loudnessDefaultCalibrationDB``.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset (sones). Defaults to `0.0`.
|
||||
public convenience init(
|
||||
model: LoudnessModel = .realtimeZwicker(
|
||||
smask: loudnessDefaultSMask, tmask: loudnessDefaultTMask),
|
||||
analysis: SpectralChain.Audio,
|
||||
sampleRate: Double,
|
||||
calibrationDB: Double = loudnessDefaultCalibrationDB,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
self.init(
|
||||
model: model,
|
||||
analysis: analysis,
|
||||
spectral: analysis.spectralBuffer,
|
||||
sampleRate: sampleRate,
|
||||
calibrationDB: calibrationDB,
|
||||
mul: mul,
|
||||
add: add
|
||||
)
|
||||
}
|
||||
|
||||
/// Buffer-only init. For tests / advanced use; no analysis auto-pull.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - model: Loudness model + parameters.
|
||||
/// - spectral: Spectral frame buffer read each block.
|
||||
/// - sampleRate: Sample rate in Hz.
|
||||
/// - calibrationDB: dBFS→SPL offset. Defaults to ``loudnessDefaultCalibrationDB``.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset (sones). Defaults to `0.0`.
|
||||
public convenience init(
|
||||
model: LoudnessModel = .realtimeZwicker(
|
||||
smask: loudnessDefaultSMask, tmask: loudnessDefaultTMask),
|
||||
spectral: SpectralBuffer,
|
||||
sampleRate: Double,
|
||||
calibrationDB: Double = loudnessDefaultCalibrationDB,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
self.init(
|
||||
model: model,
|
||||
analysis: nil,
|
||||
spectral: spectral,
|
||||
sampleRate: sampleRate,
|
||||
calibrationDB: calibrationDB,
|
||||
mul: mul,
|
||||
add: add
|
||||
)
|
||||
}
|
||||
|
||||
private init(
|
||||
model: LoudnessModel,
|
||||
analysis: SpectralChain.Audio?,
|
||||
spectral: SpectralBuffer,
|
||||
sampleRate: Double,
|
||||
calibrationDB: Double,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
self._analysis = analysis
|
||||
self._spectral = spectral
|
||||
self._model = model
|
||||
self._sampleRate = max(1.0, sampleRate)
|
||||
self._core = LoudnessBandCore(
|
||||
fftSize: spectral.fftSize,
|
||||
sampleRate: sampleRate,
|
||||
calibrationDB: calibrationDB,
|
||||
binCount: spectral.binCount
|
||||
)
|
||||
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,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
_ = _analysis?.calculatedSamples(graph: graph, count: count)
|
||||
|
||||
let blockSeconds: Double = Double(count) / _sampleRate
|
||||
let sones: Double = _core.loudness(
|
||||
spectral: _spectral, model: _model, blockSeconds: blockSeconds)
|
||||
|
||||
let target: Double = sones
|
||||
let rampStart: Double = _rampTarget
|
||||
_rampTarget = target
|
||||
guard count > 0 else { return _result }
|
||||
previousOutputValue = fillRampedResult(
|
||||
into: &_result,
|
||||
from: rampStart,
|
||||
to: target,
|
||||
mulAdd: _mulAdd,
|
||||
graph: graph,
|
||||
count: count
|
||||
)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
// GeneratorEnum conformance omitted: Loudness is Control-rate only.
|
||||
@@ -0,0 +1,315 @@
|
||||
// LoudnessBandCore.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Shared loudness back-end for ``Loudness``: bins a `SpectralBuffer` into
|
||||
/// third-octave band levels (dB SPL via the calibration offset), then computes
|
||||
/// total loudness in sones under one of the three ``LoudnessModel`` algorithms.
|
||||
///
|
||||
/// All buffers are allocated once at `init`; the per-block methods perform no
|
||||
/// allocation (RT-safe). The ISO 532 B path is an independent implementation of
|
||||
/// the published DIN 45631 / Zwicker stationary algorithm.
|
||||
final class LoudnessBandCore {
|
||||
|
||||
// MARK: - Fixed at init
|
||||
|
||||
private let calibrationDB: Double
|
||||
/// `binBand[k]` = third-octave band index for FFT bin `k`, or `-1` if the
|
||||
/// bin falls outside the 25 Hz … 12.5 kHz grid.
|
||||
private let binBand: [Int]
|
||||
private let binCount: Int
|
||||
|
||||
// MARK: - Scratch (allocated once)
|
||||
|
||||
private var bandPower: [Double] // 28 third-octave band powers (linear)
|
||||
private var bandLevel: [Double] // 28 third-octave band levels (dB SPL)
|
||||
private var coreLoudness: [Double] // 21 critical-band core loudnesses
|
||||
private var critLevel: [Double] // 20 critical-band levels (dB, ear-corrected)
|
||||
private var ti: [Double] // low-band intensities (ISO core path)
|
||||
private var logic: [Bool] // RAP-range comparison flags (ISO core path)
|
||||
|
||||
// MARK: - Temporal-mask state (realtimeZwicker only)
|
||||
|
||||
private var tmaskState: Double = 0.0
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - fftSize: FFT size of the paired analysis chain.
|
||||
/// - sampleRate: Engine sample rate (Hz), for bin→Hz mapping.
|
||||
/// - calibrationDB: dBFS→SPL offset added to each band power level.
|
||||
/// - binCount: Number of spectral bins (`fftSize/2 + 1`).
|
||||
init(fftSize: Int, sampleRate: Double, calibrationDB: Double, binCount: Int) {
|
||||
self.calibrationDB = calibrationDB
|
||||
self.binCount = max(0, binCount)
|
||||
|
||||
let safeSampleRate: Double = max(1.0, sampleRate)
|
||||
let binHz: Double = safeSampleRate / Double(max(1, fftSize))
|
||||
let ratio: Double = Foundation.pow(2.0, loudnessThirdOctaveHalfBandwidthExponent)
|
||||
|
||||
var map: [Int] = [Int](repeating: -1, count: self.binCount)
|
||||
for k: Int in 0..<self.binCount {
|
||||
let freq: Double = Double(k) * binHz
|
||||
var band: Int = -1
|
||||
for j: Int in 0..<loudnessISOThirdOctaveCount {
|
||||
let centre: Double = loudnessISOCenterFreqsHz[j]
|
||||
let lo: Double = centre / ratio
|
||||
let hi: Double = centre * ratio
|
||||
if freq >= lo && freq < hi {
|
||||
band = j
|
||||
break
|
||||
}
|
||||
}
|
||||
map[k] = band
|
||||
}
|
||||
self.binBand = map
|
||||
|
||||
self.bandPower = [Double](repeating: 0.0, count: loudnessISOThirdOctaveCount)
|
||||
self.bandLevel = [Double](repeating: 0.0, count: loudnessISOThirdOctaveCount)
|
||||
self.coreLoudness = [Double](repeating: 0.0, count: loudnessCriticalBandCount + 1)
|
||||
self.critLevel = [Double](repeating: 0.0, count: loudnessCriticalBandCount)
|
||||
self.ti = [Double](repeating: 0.0, count: loudnessISOLowBandCount)
|
||||
self.logic = [Bool](repeating: false, count: loudnessISORAP.count)
|
||||
}
|
||||
|
||||
// MARK: - Critical-band levels (shared by the Zwicker models)
|
||||
|
||||
/// Fill `critLevel[0..19]` with ear-corrected critical-band levels. The first
|
||||
/// three bands are the combined low third-octave bands (`computeLCB`); the
|
||||
/// rest map one-to-one onto third-octave bands 315 Hz … 12.5 kHz.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - lowFreqCorrected: apply the `RAP`/`DLL` equal-loudness correction to
|
||||
/// the low bands (ISO 532 B) vs a plain power sum (real-time).
|
||||
/// - field: free/diffuse field selector.
|
||||
private func fillCriticalLevels(lowFreqCorrected: Bool, field: LoudnessField) {
|
||||
let lcb: (Double, Double, Double) = computeLCB(corrected: lowFreqCorrected)
|
||||
let offset: Int = loudnessISOThirdOctaveCount - loudnessCriticalBandCount
|
||||
for z: Int in 0..<loudnessCriticalBandCount {
|
||||
var le: Double
|
||||
if z == 0 { le = lcb.0 } else if z == 1 { le = lcb.1 } else if z == 2 { le = lcb.2 }
|
||||
else { le = bandLevel[z + offset] }
|
||||
le -= loudnessISOA0[z]
|
||||
if field == .diffuse { le += loudnessISODDF[z] }
|
||||
critLevel[z] = le
|
||||
}
|
||||
}
|
||||
|
||||
/// Combine the lowest third-octave bands into the first three critical-band
|
||||
/// levels (dB). With `corrected`, the `RAP`/`DLL` equal-loudness correction is
|
||||
/// applied first (ISO 532 B); otherwise a plain power sum (real-time).
|
||||
private func computeLCB(corrected: Bool) -> (Double, Double, Double) {
|
||||
for i: Int in 0..<loudnessISOLowBandCount {
|
||||
let level: Double = bandLevel[i]
|
||||
var corr: Double = 0.0
|
||||
if corrected {
|
||||
for j: Int in 0..<loudnessISORAP.count {
|
||||
logic[j] = level > (loudnessISORAP[j] - loudnessISODLL[j][i])
|
||||
}
|
||||
corr = loudnessISODLL[0][i]
|
||||
if logic[0] { corr = 0.0 }
|
||||
for j: Int in 1..<(loudnessISORAP.count - 1) {
|
||||
if logic[j - 1] != logic[j] { corr = loudnessISODLL[j][i] }
|
||||
}
|
||||
}
|
||||
let xp: Double = level + corr
|
||||
ti[i] = Foundation.pow(loudnessDBDecadeFactor, xp / loudnessDBDecadeFactor)
|
||||
}
|
||||
let gi0: Double = ti[0] + ti[1] + ti[2] + ti[3] + ti[4] + ti[5]
|
||||
let gi1: Double = ti[6] + ti[7] + ti[8]
|
||||
let gi2: Double = ti[9] + ti[10]
|
||||
let lcb0: Double = gi0 > 0.0 ? loudnessDBDecadeFactor * Foundation.log10(gi0) : 0.0
|
||||
let lcb1: Double = gi1 > 0.0 ? loudnessDBDecadeFactor * Foundation.log10(gi1) : 0.0
|
||||
let lcb2: Double = gi2 > 0.0 ? loudnessDBDecadeFactor * Foundation.log10(gi2) : 0.0
|
||||
return (lcb0, lcb1, lcb2)
|
||||
}
|
||||
|
||||
// MARK: - Band binning
|
||||
|
||||
/// Fill `bandLevel` (dB SPL) from the spectral buffer's bin magnitudes.
|
||||
private func updateBandLevels(_ spectral: SpectralBuffer) {
|
||||
for j: Int in 0..<loudnessISOThirdOctaveCount {
|
||||
bandPower[j] = 0.0
|
||||
}
|
||||
let n: Int = min(binCount, spectral.binCount)
|
||||
for k: Int in 0..<n {
|
||||
let band: Int = binBand[k]
|
||||
if band < 0 { continue }
|
||||
let mag: Double = Double(spectral.magnitude(at: k))
|
||||
bandPower[band] += mag * mag
|
||||
}
|
||||
for j: Int in 0..<loudnessISOThirdOctaveCount {
|
||||
bandLevel[j] = loudnessDBDecadeFactor
|
||||
* Foundation.log10(bandPower[j] + loudnessTinyPower) + calibrationDB
|
||||
if bandLevel[j] > loudnessMaxBandLevelDB { bandLevel[j] = loudnessMaxBandLevelDB }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Model dispatch
|
||||
|
||||
/// Total loudness in sones for `model` from the current spectral frame.
|
||||
/// `blockSeconds` is the audio-block duration (for the temporal mask).
|
||||
func loudness(
|
||||
spectral: SpectralBuffer,
|
||||
model: LoudnessModel,
|
||||
blockSeconds: Double
|
||||
) -> Double {
|
||||
updateBandLevels(spectral)
|
||||
switch model {
|
||||
case .barkEstimate:
|
||||
return barkEstimateLoudness()
|
||||
case .realtimeZwicker(let smask, let tmask):
|
||||
return realtimeZwickerLoudness(smask: smask, tmask: tmask, blockSeconds: blockSeconds)
|
||||
case .iso532b(let field):
|
||||
return iso532bLoudness(field: field)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Model 1: Bark/third-octave Stevens estimate
|
||||
|
||||
private func barkEstimateLoudness() -> Double {
|
||||
var total: Double = 0.0
|
||||
let calibrationFactor: Double = Foundation.pow(
|
||||
loudnessDBDecadeFactor, calibrationDB / loudnessDBDecadeFactor)
|
||||
for j: Int in 0..<loudnessISOThirdOctaveCount {
|
||||
let intensity: Double = bandPower[j]
|
||||
if intensity <= 0.0 { continue }
|
||||
// Calibrated intensity ratio → Stevens power law.
|
||||
let ratio: Double = intensity * calibrationFactor
|
||||
total += Foundation.pow(ratio, loudnessStevensExponent)
|
||||
}
|
||||
let result: Double = total * loudnessBarkEstimateScale
|
||||
return result.isFinite ? max(0.0, result) : 0.0
|
||||
}
|
||||
|
||||
// MARK: - Model 2: real-time Zwicker (critical-band specific loudness + temporal mask)
|
||||
|
||||
private func realtimeZwickerLoudness(
|
||||
smask: Double,
|
||||
tmask: Double,
|
||||
blockSeconds: Double
|
||||
) -> Double {
|
||||
// Simplified core loudness: the same critical-band levels as ISO 532 B
|
||||
// (low bands combined into LCB, but without the RAP/DLL/DCB/korry
|
||||
// refinement), with the spectral-masking constant exposed as `smask`.
|
||||
// Then the shared upper-slope integration, followed by the temporal mask.
|
||||
let s: Double = min(1.0, max(0.0, smask))
|
||||
fillCriticalLevels(lowFreqCorrected: false, field: .free)
|
||||
for z: Int in 0..<loudnessCriticalBandCount {
|
||||
let le: Double = critLevel[z]
|
||||
let ltq: Double = loudnessISOLTQ[z]
|
||||
if le > ltq {
|
||||
let mp1: Double = loudnessZwickerConst
|
||||
* Foundation.pow(loudnessDBDecadeFactor, loudnessZwickerThresholdCoeff * ltq)
|
||||
let inner: Double = 1.0 - s
|
||||
+ s * Foundation.pow(loudnessDBDecadeFactor, loudnessLevelToPowerCoeff * (le - ltq))
|
||||
let mp2: Double = Foundation.pow(inner, loudnessZwickerExponent) - 1.0
|
||||
coreLoudness[z] = max(0.0, mp1 * mp2)
|
||||
} else {
|
||||
coreLoudness[z] = 0.0
|
||||
}
|
||||
}
|
||||
coreLoudness[loudnessCriticalBandCount] = 0.0
|
||||
|
||||
let base: Double = integrateUpperSlopes()
|
||||
|
||||
// Temporal mask: instant attack, exponential release toward 0.
|
||||
let safeTMask: Double = max(loudnessTinyPower, tmask)
|
||||
let coeff: Double = Foundation.exp(-max(0.0, blockSeconds) / safeTMask)
|
||||
let released: Double = tmaskState * coeff
|
||||
let out: Double = max(base, released)
|
||||
tmaskState = denormalsToZero(out)
|
||||
return out.isFinite ? max(0.0, out) : 0.0
|
||||
}
|
||||
|
||||
// MARK: - Model 3: ISO 532 B / DIN 45631 stationary Zwicker
|
||||
|
||||
private func iso532bLoudness(field: LoudnessField) -> Double {
|
||||
computeCoreLoudness(field: field)
|
||||
return integrateUpperSlopes()
|
||||
}
|
||||
|
||||
/// Fill `coreLoudness[0..20]` (main loudness per critical band) per DIN 45631.
|
||||
private func computeCoreLoudness(field: LoudnessField) {
|
||||
// Ear-corrected critical-band levels with the RAP/DLL low-frequency
|
||||
// correction (the full standard).
|
||||
fillCriticalLevels(lowFreqCorrected: true, field: field)
|
||||
|
||||
for z: Int in 0..<loudnessCriticalBandCount {
|
||||
var le: Double = critLevel[z]
|
||||
let ltq: Double = loudnessISOLTQ[z]
|
||||
if le > ltq { le -= loudnessISODCB[z] }
|
||||
|
||||
if le > ltq {
|
||||
let mp1: Double = loudnessZwickerConst
|
||||
* Foundation.pow(loudnessDBDecadeFactor, loudnessZwickerThresholdCoeff * ltq)
|
||||
let inner: Double = 1.0 - loudnessISOCoreS
|
||||
+ loudnessISOCoreS * Foundation.pow(
|
||||
loudnessDBDecadeFactor, loudnessLevelToPowerCoeff * (le - ltq))
|
||||
let mp2: Double = Foundation.pow(inner, loudnessZwickerExponent) - 1.0
|
||||
coreLoudness[z] = max(0.0, mp1 * mp2)
|
||||
} else {
|
||||
coreLoudness[z] = 0.0
|
||||
}
|
||||
}
|
||||
coreLoudness[loudnessCriticalBandCount] = 0.0 // appended sentinel band
|
||||
|
||||
// Lowest-band threshold-dependence correction.
|
||||
let korry: Double = loudnessKorryBase
|
||||
+ loudnessKorryScale * Foundation.pow(coreLoudness[0], loudnessKorryExponent)
|
||||
if korry <= 1.0 { coreLoudness[0] *= korry }
|
||||
}
|
||||
|
||||
/// Integrate the specific-loudness function with the Zwicker upper slopes →
|
||||
/// total loudness (sones). Walks each critical band's flat top plus the
|
||||
/// upper-slope tail spilling into higher bands.
|
||||
private func integrateUpperSlopes() -> Double {
|
||||
var total: Double = 0.0
|
||||
var z1: Double = 0.0
|
||||
var n1: Double = 0.0
|
||||
let maxColumn: Int = loudnessISOUSL[0].count - 1 // USL has 8 critical-band columns
|
||||
|
||||
for i: Int in 0..<(loudnessCriticalBandCount + 1) {
|
||||
let zupI: Double = loudnessISOZUP[i]
|
||||
var ig: Int = i - 1
|
||||
if ig > maxColumn { ig = maxColumn }
|
||||
if ig < 0 { ig = 0 }
|
||||
let nmI: Double = coreLoudness[i]
|
||||
|
||||
while true {
|
||||
if n1 <= nmI {
|
||||
// Rising / flat: plateau at nmI across the band.
|
||||
total += nmI * (zupI - z1)
|
||||
z1 = zupI
|
||||
n1 = nmI
|
||||
break
|
||||
}
|
||||
// Decreasing: upper slope from (z1, n1) down through rns ranges.
|
||||
var j: Int = 0
|
||||
while j < (loudnessISORNS.count - 1) && loudnessISORNS[j] >= n1 { j += 1 }
|
||||
let n2: Double = max(loudnessISORNS[j], nmI)
|
||||
let slope: Double = loudnessISOUSL[j][ig]
|
||||
let dz: Double = slope > 0.0 ? (n1 - n2) / slope : (zupI - z1)
|
||||
var z2: Double = z1 + dz
|
||||
|
||||
if z2 >= zupI {
|
||||
z2 = zupI
|
||||
let nEdge: Double = n1 - slope * (z2 - z1)
|
||||
total += loudnessTrapezoidalFactor * (n1 + nEdge) * (z2 - z1)
|
||||
z1 = zupI
|
||||
n1 = nEdge
|
||||
break
|
||||
}
|
||||
total += loudnessTrapezoidalFactor * (n1 + n2) * (z2 - z1)
|
||||
z1 = z2
|
||||
n1 = n2
|
||||
// Loop continues for the next rns range within the same band.
|
||||
}
|
||||
}
|
||||
return total.isFinite ? max(0.0, total) : 0.0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
// LoudnessConstants.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - General
|
||||
|
||||
/// Default dBFS→SPL calibration offset (dB) added to each bin's power level.
|
||||
/// Chosen so a full-scale sinusoid lands near the top of the musical SPL range.
|
||||
public let loudnessDefaultCalibrationDB: Double = 90.0
|
||||
|
||||
/// Floor added inside `log10` to guard the silence case (`log10(0)`).
|
||||
public let loudnessTinyPower: Double = 1.0e-30
|
||||
|
||||
/// Decade factor for dB ↔ power/intensity conversions (`L = 10·log10(P)`,
|
||||
/// `P = 10^(L/10)`).
|
||||
public let loudnessDBDecadeFactor: Double = 10.0
|
||||
|
||||
/// Trapezoidal-rule factor (`½`) for the upper-slope area integration.
|
||||
public let loudnessTrapezoidalFactor: Double = 0.5
|
||||
|
||||
/// Exponent for the third-octave half-bandwidth ratio `2^(1/6)`.
|
||||
public let loudnessThirdOctaveHalfBandwidthExponent: Double = 1.0 / 6.0
|
||||
|
||||
/// Stevens' power-law exponent on intensity for the `.barkEstimate` model
|
||||
/// (`N ∝ I^0.3` → +10 dB ≈ 2×).
|
||||
public let loudnessStevensExponent: Double = 0.3
|
||||
|
||||
/// Output scaling for `.barkEstimate` so a 1 kHz tone near 40 dB SPL lands near
|
||||
/// 1 sone (the model has no equal-loudness contour, so this is an anchor fit:
|
||||
/// `(10^(40/10))^0.3 ≈ 15.85`, so the scale is `≈ 1/15.85`).
|
||||
public let loudnessBarkEstimateScale: Double = 0.0631
|
||||
|
||||
/// Zwicker specific-loudness constant (`0.0635 = 0.0635`). Specific loudness
|
||||
/// `N' = const · 10^(0.025·LTQ) · ((1 − s + s·10^(0.1·(L−LTQ)))^0.25 − 1)`.
|
||||
public let loudnessZwickerConst: Double = 0.0635
|
||||
|
||||
/// Exponent in the Zwicker specific-loudness law (`^0.25`).
|
||||
public let loudnessZwickerExponent: Double = 0.25
|
||||
|
||||
/// `10^(0.025·LTQ)` coefficient exponent factor.
|
||||
public let loudnessZwickerThresholdCoeff: Double = 0.025
|
||||
|
||||
/// `10^(0.1·(L−LTQ))` level-to-power exponent factor (dB → power decade).
|
||||
public let loudnessLevelToPowerCoeff: Double = 0.1
|
||||
|
||||
/// Default Zwicker spectral-masking constant `s` for `.realtimeZwicker` (the
|
||||
/// standard's fixed value). SC `Loudness` `smask` default.
|
||||
public let loudnessDefaultSMask: Double = 0.25
|
||||
|
||||
/// Default temporal-mask release time (seconds) for `.realtimeZwicker`.
|
||||
public let loudnessDefaultTMask: Double = 1.0
|
||||
|
||||
// MARK: - Third-octave band layout (ISO 532 B input grid)
|
||||
|
||||
/// Number of third-octave bands (25 Hz … 12.5 kHz).
|
||||
public let loudnessISOThirdOctaveCount: Int = 28
|
||||
|
||||
/// Third-octave band centre frequencies (Hz).
|
||||
public let loudnessISOCenterFreqsHz: [Double] = [
|
||||
25, 31.5, 40, 50, 63, 80, 100, 125, 160, 200, 250, 315,
|
||||
400, 500, 630, 800, 1000, 1250, 1600, 2000, 2500, 3150,
|
||||
4000, 5000, 6300, 8000, 10000, 12500
|
||||
]
|
||||
|
||||
/// Number of Zwicker critical bands used by the core-loudness stage (the upper
|
||||
/// 20 third-octave bands, with the lowest three formed from sub-band sums).
|
||||
public let loudnessCriticalBandCount: Int = 20
|
||||
|
||||
/// Number of low third-octave bands (25 … 250 Hz) that get the `RAP`/`DLL`
|
||||
/// equal-loudness correction before being combined into the first three
|
||||
/// critical bands.
|
||||
public let loudnessISOLowBandCount: Int = 11
|
||||
|
||||
// MARK: - ISO 532 B core-loudness tables
|
||||
// Transcribed from the published DIN 45631 / Zwicker (1991) algorithm via the
|
||||
// Apache-2.0 MoSQITo implementation. Data only — facts of the standard.
|
||||
|
||||
/// Ranges of 1/3-octave band levels for low-frequency correction (dB).
|
||||
public let loudnessISORAP: [Double] = [45, 55, 65, 71, 80, 90, 100, 120]
|
||||
|
||||
/// Reduction of the lowest 11 1/3-octave band levels within the eight `RAP`
|
||||
/// ranges (8 rows × 11 columns), per the equal-loudness contours.
|
||||
public let loudnessISODLL: [[Double]] = [
|
||||
[-32, -24, -16, -10, -5, 0, -7, -3, 0, -2, 0],
|
||||
[-29, -22, -15, -10, -4, 0, -7, -2, 0, -2, 0],
|
||||
[-27, -19, -14, -9, -4, 0, -6, -2, 0, -2, 0],
|
||||
[-25, -17, -12, -9, -3, 0, -5, -2, 0, -2, 0],
|
||||
[-23, -16, -11, -7, -3, 0, -4, -1, 0, -1, 0],
|
||||
[-20, -14, -10, -6, -3, 0, -4, -1, 0, -1, 0],
|
||||
[-18, -12, -9, -6, -2, 0, -3, -1, 0, -1, 0],
|
||||
[-15, -10, -8, -4, -2, 0, -3, -1, 0, -1, 0]
|
||||
]
|
||||
|
||||
/// Critical-band level at absolute threshold without the ear transfer (dB), per
|
||||
/// the 20 critical bands.
|
||||
public let loudnessISOLTQ: [Double] = [
|
||||
30, 18, 12, 8, 7, 6, 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3
|
||||
]
|
||||
|
||||
/// Ear-transmission level correction (dB), per critical band.
|
||||
public let loudnessISOA0: [Double] = [
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.5, -1.6, -3.2, -5.4, -5.6, -4, -1.5, 2, 5, 12
|
||||
]
|
||||
|
||||
/// Free-field → diffuse-field level difference (dB), per critical band.
|
||||
public let loudnessISODDF: [Double] = [
|
||||
0, 0, 0.5, 0.9, 1.2, 1.6, 2.3, 2.8, 3, 2,
|
||||
0, -1.4, -2, -1.9, -1, 0.5, 3, 4, 4.3, 4
|
||||
]
|
||||
|
||||
/// Adaptation of 1/3-octave band levels to the critical-band level (dB).
|
||||
public let loudnessISODCB: [Double] = [
|
||||
-0.25, -0.6, -0.8, -0.8, -0.5, 0, 0.5, 1.1, 1.5, 1.7,
|
||||
1.8, 1.8, 1.7, 1.6, 1.4, 1.2, 0.8, 0.5, 0, -0.5
|
||||
]
|
||||
|
||||
/// Core-loudness correction `s` in the specific-loudness law.
|
||||
public let loudnessISOCoreS: Double = 0.25
|
||||
|
||||
// MARK: - ISO 532 B upper-slope / integration tables
|
||||
|
||||
/// Upper limits of the approximated critical bands in Bark (21 values).
|
||||
public let loudnessISOZUP: [Double] = [
|
||||
0.9, 1.8, 2.8, 3.5, 4.4, 5.4, 6.6, 7.9, 9.2, 10.6, 12.3,
|
||||
13.8, 15.2, 16.7, 18.1, 19.3, 20.6, 21.8, 22.7, 23.6, 24
|
||||
]
|
||||
|
||||
/// Specific-loudness range thresholds for upper-slope steepness selection (18,
|
||||
/// descending).
|
||||
public let loudnessISORNS: [Double] = [
|
||||
21.5, 18, 15.1, 11.5, 9, 6.1, 4.4, 3.1, 2.13, 1.36,
|
||||
0.82, 0.42, 0.30, 0.22, 0.15, 0.10, 0.035, 0
|
||||
]
|
||||
|
||||
/// Steepness of the upper slopes (18 ranges × 8 critical-band columns).
|
||||
public let loudnessISOUSL: [[Double]] = [
|
||||
[13, 8.2, 6.3, 5.5, 5.5, 5.5, 5.5, 5.5],
|
||||
[9, 7.5, 6, 5.1, 4.5, 4.5, 4.5, 4.5],
|
||||
[7.8, 6.7, 5.6, 4.9, 4.4, 3.9, 3.9, 3.9],
|
||||
[6.2, 5.4, 4.6, 4.0, 3.5, 3.2, 3.2, 3.2],
|
||||
[4.5, 3.8, 3.6, 3.2, 2.9, 2.7, 2.7, 2.7],
|
||||
[3.7, 3.0, 2.8, 2.35, 2.2, 2.2, 2.2, 2.2],
|
||||
[2.9, 2.3, 2.1, 1.9, 1.8, 1.7, 1.7, 1.7],
|
||||
[2.4, 1.7, 1.5, 1.35, 1.3, 1.3, 1.3, 1.3],
|
||||
[1.95, 1.45, 1.3, 1.15, 1.1, 1.1, 1.1, 1.1],
|
||||
[1.5, 1.2, 0.94, 0.86, 0.82, 0.82, 0.82, 0.82],
|
||||
[0.72, 0.67, 0.64, 0.63, 0.62, 0.62, 0.62, 0.62],
|
||||
[0.59, 0.53, 0.51, 0.50, 0.42, 0.42, 0.42, 0.42],
|
||||
[0.40, 0.33, 0.26, 0.24, 0.24, 0.22, 0.22, 0.22],
|
||||
[0.27, 0.21, 0.20, 0.18, 0.17, 0.17, 0.17, 0.17],
|
||||
[0.16, 0.15, 0.14, 0.12, 0.11, 0.11, 0.11, 0.11],
|
||||
[0.12, 0.11, 0.10, 0.08, 0.08, 0.08, 0.08, 0.08],
|
||||
[0.09, 0.08, 0.07, 0.06, 0.06, 0.06, 0.06, 0.05],
|
||||
[0.06, 0.05, 0.03, 0.02, 0.02, 0.02, 0.02, 0.02]
|
||||
]
|
||||
|
||||
/// `korry` low-band threshold-dependence correction constants
|
||||
/// (`0.4 + 0.32·N^0.2`).
|
||||
public let loudnessKorryBase: Double = 0.4
|
||||
public let loudnessKorryScale: Double = 0.32
|
||||
public let loudnessKorryExponent: Double = 0.2
|
||||
|
||||
/// Maximum third-octave band level (dB) above which the Zwicker method is
|
||||
/// undefined for the low bands; input is clamped to this.
|
||||
public let loudnessMaxBandLevelDB: Double = 120.0
|
||||
@@ -0,0 +1,16 @@
|
||||
// LoudnessField.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Sound-field assumption for the ISO 532 B loudness model
|
||||
/// (``LoudnessModel/iso532b(field:)``).
|
||||
public enum LoudnessField {
|
||||
/// Free field (frontal incidence). Default.
|
||||
case free
|
||||
/// Diffuse field (applies the `DDF` free→diffuse corrections).
|
||||
case diffuse
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// LoudnessModel.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Selects the loudness-estimation model for ``Loudness`` (the implementation
|
||||
/// flag, mirroring the `Balance` `logDomain:` and `BeatTrack` `BeatTrackODF`
|
||||
/// folds). The cases carry different parameters, so the selector is an enum.
|
||||
///
|
||||
/// All models output total loudness in **sones** from the same third-octave band
|
||||
/// powers; they differ in how specific loudness is derived.
|
||||
public enum LoudnessModel {
|
||||
|
||||
/// Cheapest: third-octave band intensity → Stevens power law
|
||||
/// (`N ∝ I^0.3`) → sum. No equal-loudness contour or masking. Rough but
|
||||
/// stable; no SC parity claim.
|
||||
case barkEstimate
|
||||
|
||||
/// SC `Loudness` ergonomics: critical-band specific loudness via the Zwicker
|
||||
/// law with a spectral-masking constant, summed, then temporally masked.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - smask: Spectral-masking constant `s` (`[0, 1]`); `0.25` is the
|
||||
/// standard value. Higher widens masking.
|
||||
/// - tmask: Temporal-mask release time (seconds); larger = slower decay,
|
||||
/// more masking of transients.
|
||||
case realtimeZwicker(smask: Double, tmask: Double)
|
||||
|
||||
/// Full ISO 532 B / DIN 45631 stationary Zwicker loudness: third-octave core
|
||||
/// loudness → upper-slope spreading → integrate the specific-loudness
|
||||
/// function.
|
||||
///
|
||||
/// - Parameter field: Sound-field assumption (`.free` default, `.diffuse`).
|
||||
case iso532b(field: LoudnessField)
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
// RunningMax.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
|
||||
/// File-scope zero-fill block for RunningMax — fallback when upstream returns no channel.
|
||||
private let runningMaxZeroBlock: [Double] = [Double](
|
||||
repeating: 0,
|
||||
count: lyrebirdDefaultResultBufferSize
|
||||
)
|
||||
|
||||
/// Running maximum with trigger reset. Equivalent to SuperCollider `RunningMax`.
|
||||
///
|
||||
/// Tracks the running maximum of `input` since the last trigger. On a ≤0 → >0 rising
|
||||
/// edge of `trig`, the extreme is reset to the current `input` value at that frame.
|
||||
/// On the very first sample/block, the extreme is initialised to the first input value.
|
||||
///
|
||||
/// ```swift
|
||||
/// let peak = RunningMax.Audio(input: signal)
|
||||
/// RunningMax.Audio(input: sig, trig: resetClock) // reset every clock pulse
|
||||
/// RunningMax.Control(input: $cv, trig: gate) // block-rate maximum tracking
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track. Any `ValidGeneratorInput`.
|
||||
/// - 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 enum RunningMax {
|
||||
|
||||
// MARK: - Shared base
|
||||
|
||||
/// Shared stored properties for `RunningMax.Audio` and `RunningMax.Control`.
|
||||
public class _Base: GeneratorBase {
|
||||
let _input: any ValidGeneratorInput
|
||||
let _trigInput: any ValidGeneratorInput
|
||||
let _mulAdd: MulAddSpec
|
||||
|
||||
/// Running maximum. Initialised to the first input sample (lazy init via `_initialized`).
|
||||
var _extreme: Double = 0.0
|
||||
/// Previous trigger value for edge detection.
|
||||
var _prevTrig: Double = 0.0
|
||||
/// `false` until the first sample is processed; prevents a false start at `0.0`.
|
||||
var _initialized: Bool = false
|
||||
|
||||
init(
|
||||
input: any ValidGeneratorInput,
|
||||
trig: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedTrig: any ValidGeneratorInput = trig._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_trigInput = resolvedTrig
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
super.init()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio rate
|
||||
|
||||
/// Audio-rate running maximum with trigger reset.
|
||||
///
|
||||
/// Evaluates per sample: lazy-initialises on the first sample; resets on rising trig
|
||||
/// edge; otherwise tracks `max(_extreme, x)`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track.
|
||||
/// - trig: Reset trigger. ≤0 → >0 rising edges reset to the current `input` value.
|
||||
/// Defaults to `0.0` (no reset).
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track.
|
||||
/// - trig: Reset trigger. ≤0 → >0 edges reset the running maximum. Defaults to `0.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
input: any ValidGeneratorInput,
|
||||
trig: any ValidGeneratorInput = 0.0,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, trig: trig, mul: mul, add: add)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let inputSamples: [Double] = _input.calculatedSamples(
|
||||
graph: graph, count: count).first ?? runningMaxZeroBlock
|
||||
let trigSamples: [Double] = _trigInput.calculatedSamples(
|
||||
graph: graph, count: count).first ?? runningMaxZeroBlock
|
||||
|
||||
var extreme: Double = _extreme
|
||||
var prevTrig: Double = _prevTrig
|
||||
var initialized: Bool = _initialized
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = inputSamples[i]
|
||||
let t: Double = trigSamples[i]
|
||||
if !initialized {
|
||||
extreme = x
|
||||
initialized = true
|
||||
} else if t > 0 && prevTrig <= 0 {
|
||||
extreme = x
|
||||
} else {
|
||||
extreme = Swift.max(extreme, x)
|
||||
}
|
||||
prevTrig = t
|
||||
_result[0][i] = extreme
|
||||
}
|
||||
|
||||
_extreme = extreme
|
||||
_prevTrig = prevTrig
|
||||
_initialized = initialized
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Control rate
|
||||
|
||||
/// Block-rate running maximum with trigger reset.
|
||||
///
|
||||
/// Scans the full audio-rate input block, applying the same state machine as `Audio`
|
||||
/// (lazy init; trig-edge reset; `max` tracking). Outputs the block-final extreme as
|
||||
/// a flat block (all samples equal). Bypasses the sub-block loop — the state machine
|
||||
/// must scan the full audio block exactly once per audio cycle.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track.
|
||||
/// - 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 var previousOutputValue: Double = 0.0
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track.
|
||||
/// - trig: Reset trigger. ≤0 → >0 edges reset the running maximum. Defaults to `0.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
input: any ValidGeneratorInput,
|
||||
trig: any ValidGeneratorInput = 0.0,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
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,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let inputSamples: [Double] = _input.calculatedSamples(
|
||||
graph: graph, count: count).first ?? runningMaxZeroBlock
|
||||
let trigSamples: [Double] = _trigInput.calculatedSamples(
|
||||
graph: graph, count: count).first ?? runningMaxZeroBlock
|
||||
|
||||
var extreme: Double = _extreme
|
||||
var prevTrig: Double = _prevTrig
|
||||
var initialized: Bool = _initialized
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = inputSamples[i]
|
||||
let t: Double = trigSamples[i]
|
||||
if !initialized {
|
||||
extreme = x
|
||||
initialized = true
|
||||
} else if t > 0 && prevTrig <= 0 {
|
||||
extreme = x
|
||||
} else {
|
||||
extreme = Swift.max(extreme, x)
|
||||
}
|
||||
prevTrig = t
|
||||
}
|
||||
|
||||
_extreme = extreme
|
||||
_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]
|
||||
return _result
|
||||
}
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
extension RunningMax: GeneratorEnum {
|
||||
public typealias AudioType = RunningMax.Audio
|
||||
public typealias ControlType = RunningMax.Control
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
// RunningMin.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
|
||||
/// File-scope zero-fill block for RunningMin — fallback when upstream returns no channel.
|
||||
private let runningMinZeroBlock: [Double] = [Double](
|
||||
repeating: 0,
|
||||
count: lyrebirdDefaultResultBufferSize
|
||||
)
|
||||
|
||||
/// Running minimum with trigger reset. Equivalent to SuperCollider `RunningMin`.
|
||||
///
|
||||
/// Tracks the running minimum of `input` since the last trigger. On a ≤0 → >0 rising
|
||||
/// edge of `trig`, the extreme is reset to the current `input` value at that frame.
|
||||
/// On the very first sample/block, the extreme is initialised to the first input value.
|
||||
///
|
||||
/// ```swift
|
||||
/// let peak = RunningMin.Audio(input: signal)
|
||||
/// RunningMin.Audio(input: sig, trig: resetClock) // reset every clock pulse
|
||||
/// RunningMin.Control(input: $cv, trig: gate) // block-rate minimum tracking
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track. Any `ValidGeneratorInput`.
|
||||
/// - 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 enum RunningMin {
|
||||
|
||||
// MARK: - Shared base
|
||||
|
||||
/// Shared stored properties for `RunningMin.Audio` and `RunningMin.Control`.
|
||||
public class _Base: GeneratorBase {
|
||||
let _input: any ValidGeneratorInput
|
||||
let _trigInput: any ValidGeneratorInput
|
||||
let _mulAdd: MulAddSpec
|
||||
|
||||
/// Running minimum. Initialised to the first input sample (lazy init via `_initialized`).
|
||||
var _extreme: Double = 0.0
|
||||
/// Previous trigger value for edge detection.
|
||||
var _prevTrig: Double = 0.0
|
||||
/// `false` until the first sample is processed; prevents a false start at `0.0`.
|
||||
var _initialized: Bool = false
|
||||
|
||||
init(
|
||||
input: any ValidGeneratorInput,
|
||||
trig: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedTrig: any ValidGeneratorInput = trig._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_trigInput = resolvedTrig
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
super.init()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio rate
|
||||
|
||||
/// Audio-rate running minimum with trigger reset.
|
||||
///
|
||||
/// Evaluates per sample: lazy-initialises on the first sample; resets on rising trig
|
||||
/// edge; otherwise tracks `min(_extreme, x)`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track.
|
||||
/// - trig: Reset trigger. ≤0 → >0 rising edges reset to the current `input` value.
|
||||
/// Defaults to `0.0` (no reset).
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track.
|
||||
/// - trig: Reset trigger. ≤0 → >0 edges reset the running minimum. Defaults to `0.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
input: any ValidGeneratorInput,
|
||||
trig: any ValidGeneratorInput = 0.0,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, trig: trig, mul: mul, add: add)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let inputSamples: [Double] = _input.calculatedSamples(
|
||||
graph: graph, count: count).first ?? runningMinZeroBlock
|
||||
let trigSamples: [Double] = _trigInput.calculatedSamples(
|
||||
graph: graph, count: count).first ?? runningMinZeroBlock
|
||||
|
||||
var extreme: Double = _extreme
|
||||
var prevTrig: Double = _prevTrig
|
||||
var initialized: Bool = _initialized
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = inputSamples[i]
|
||||
let t: Double = trigSamples[i]
|
||||
if !initialized {
|
||||
extreme = x
|
||||
initialized = true
|
||||
} else if t > 0 && prevTrig <= 0 {
|
||||
extreme = x
|
||||
} else {
|
||||
extreme = Swift.min(extreme, x)
|
||||
}
|
||||
prevTrig = t
|
||||
_result[0][i] = extreme
|
||||
}
|
||||
|
||||
_extreme = extreme
|
||||
_prevTrig = prevTrig
|
||||
_initialized = initialized
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Control rate
|
||||
|
||||
/// Block-rate running minimum with trigger reset.
|
||||
///
|
||||
/// Scans the full audio-rate input block, applying the same state machine as `Audio`
|
||||
/// (lazy init; trig-edge reset; `min` tracking). Outputs the block-final extreme as
|
||||
/// a flat block (all samples equal). Bypasses the sub-block loop — the state machine
|
||||
/// must scan the full audio block exactly once per audio cycle.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track.
|
||||
/// - 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 var previousOutputValue: Double = 0.0
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track.
|
||||
/// - trig: Reset trigger. ≤0 → >0 edges reset the running minimum. Defaults to `0.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
input: any ValidGeneratorInput,
|
||||
trig: any ValidGeneratorInput = 0.0,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
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,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let inputSamples: [Double] = _input.calculatedSamples(
|
||||
graph: graph, count: count).first ?? runningMinZeroBlock
|
||||
let trigSamples: [Double] = _trigInput.calculatedSamples(
|
||||
graph: graph, count: count).first ?? runningMinZeroBlock
|
||||
|
||||
var extreme: Double = _extreme
|
||||
var prevTrig: Double = _prevTrig
|
||||
var initialized: Bool = _initialized
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = inputSamples[i]
|
||||
let t: Double = trigSamples[i]
|
||||
if !initialized {
|
||||
extreme = x
|
||||
initialized = true
|
||||
} else if t > 0 && prevTrig <= 0 {
|
||||
extreme = x
|
||||
} else {
|
||||
extreme = Swift.min(extreme, x)
|
||||
}
|
||||
prevTrig = t
|
||||
}
|
||||
|
||||
_extreme = extreme
|
||||
_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]
|
||||
return _result
|
||||
}
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
extension RunningMin: GeneratorEnum {
|
||||
public typealias AudioType = RunningMin.Audio
|
||||
public typealias ControlType = RunningMin.Control
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
// Slope.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
|
||||
/// File-scope zero-fill block for Slope — fallback when upstream returns no channel.
|
||||
private let slopeZeroBlock: [Double] = [Double](
|
||||
repeating: 0,
|
||||
count: lyrebirdDefaultResultBufferSize
|
||||
)
|
||||
|
||||
/// Per-second rate-of-change estimator. Equivalent to SuperCollider `Slope`.
|
||||
///
|
||||
/// Computes `out[n] = (input[n] − input[n−1]) × sampleRate` (audio rate) or
|
||||
/// `out = (input − prevInput) × controlRate` (control rate). On the very first
|
||||
/// sample/block, the output is `0.0` and `prevInput` is initialised to the first input
|
||||
/// value — this prevents the startup spike that would occur if `prevInput` were `0`.
|
||||
///
|
||||
/// ```swift
|
||||
/// let rate = Slope.Audio(input: envelope) // audio-rate differentiation
|
||||
/// let rate = Slope.Control(input: $cv) // block-rate differentiation
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to differentiate.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public enum Slope {
|
||||
|
||||
// MARK: - Shared base
|
||||
|
||||
/// Shared stored properties for `Slope.Audio` and `Slope.Control`.
|
||||
public class _Base: GeneratorBase {
|
||||
let _input: any ValidGeneratorInput
|
||||
let _inputIsGenerator: Bool
|
||||
let _mulAdd: MulAddSpec
|
||||
|
||||
/// Previous sample value. Initialised on the first call (lazy init).
|
||||
var _prevSample: Double = 0.0
|
||||
/// `false` until the first sample/block is processed; avoids the startup spike.
|
||||
var _initialized: Bool = false
|
||||
|
||||
init(
|
||||
input: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_inputIsGenerator = resolvedInput is any Generator
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
super.init()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio rate
|
||||
|
||||
/// Audio-rate per-second rate-of-change estimator.
|
||||
///
|
||||
/// On the first sample, the output is `0.0` and `prevSample` is set to that sample's
|
||||
/// value. From the second sample onward, `out[n] = (x[n] − x[n−1]) × sampleRate`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to differentiate.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to differentiate.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
input: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, mul: mul, add: add)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let inputSamples: [Double] = _input.calculatedSamples(
|
||||
graph: graph, count: count).first ?? slopeZeroBlock
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
|
||||
var prev: Double = _prevSample
|
||||
var initialized: Bool = _initialized
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = inputSamples[i]
|
||||
if !initialized {
|
||||
prev = x
|
||||
initialized = true
|
||||
_result[0][i] = 0.0
|
||||
} else {
|
||||
_result[0][i] = (x - prev) * sr
|
||||
prev = x
|
||||
}
|
||||
}
|
||||
|
||||
_prevSample = prev
|
||||
_initialized = initialized
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Control rate
|
||||
|
||||
/// Control-rate per-second rate-of-change estimator.
|
||||
///
|
||||
/// Advances one differentiation step per audio block using the control rate
|
||||
/// (`sampleRate / blockSize`). On the first block, the output is `0.0` and
|
||||
/// `prevInput` is set to the block's input value. Subsequent blocks compute
|
||||
/// `slope = (x − prevInput) × controlRate`.
|
||||
///
|
||||
/// Bypasses the sub-block loop — state must advance exactly once per audio block.
|
||||
///
|
||||
/// The output block is flat (constant). For smoothly interpolated output, use
|
||||
/// `Slope.Audio`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - 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 var previousOutputValue: Double = 0.0
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to differentiate.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
input: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
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,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let controlRate: Double = graph.engine.sampleRate / Double(graph.engine.blockSize)
|
||||
// Sample the input at block end (captures ParameterNode ramp endpoints),
|
||||
// matching the block-constant-input convention of other control-rate generators.
|
||||
let x: Double = lastGeneratorSampleOrFloat(
|
||||
_input, isGenerator: _inputIsGenerator, graph: graph, count: count)
|
||||
|
||||
let slope: Double
|
||||
if !_initialized {
|
||||
_prevSample = x
|
||||
_initialized = true
|
||||
slope = 0.0
|
||||
} else {
|
||||
slope = (x - _prevSample) * controlRate
|
||||
_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]
|
||||
return _result
|
||||
}
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
extension Slope: GeneratorEnum {
|
||||
public typealias AudioType = Slope.Audio
|
||||
public typealias ControlType = Slope.Control
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
// ZeroCrossing.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
|
||||
/// File-scope zero-fill block for ZeroCrossing — fallback when upstream returns no channel.
|
||||
private let zeroCrossingZeroBlock: [Double] = [Double](
|
||||
repeating: 0,
|
||||
count: lyrebirdDefaultResultBufferSize
|
||||
)
|
||||
|
||||
/// Minimum sample count between crossings required before a zero crossing is recognised.
|
||||
/// Mirrors SuperCollider `ZeroCrossing_Ctor` guard (`counter > 4`) — rejects spurious
|
||||
/// high-frequency noise crossings. A crossing is only recorded when the inter-crossing
|
||||
/// sample count exceeds this threshold.
|
||||
private let zeroCrossingMinCount: Int = 4
|
||||
|
||||
/// Zero-crossing frequency estimator. Equivalent to SuperCollider `ZeroCrossing`.
|
||||
///
|
||||
/// Counts samples between successive rising zero crossings (≤0 → >0 edges) and computes a
|
||||
/// frequency estimate as `sampleRate / sampleCount`. The estimate is held between crossings
|
||||
/// and starts at `0.0` until the first full period is measured.
|
||||
///
|
||||
/// `_prevSample` is lazy-initialised to the first input sample on the very first call,
|
||||
/// matching SuperCollider's `ZeroCrossing_Ctor` (`m_previn = ZIN0(0)`). As a result,
|
||||
/// a constant positive (DC) input produces no crossing and the output remains `0.0`.
|
||||
/// Crossings require more than `zeroCrossingMinCount` (4) samples of inter-crossing
|
||||
/// spacing — spurious noise crossings are rejected.
|
||||
///
|
||||
/// ```swift
|
||||
/// // Estimate the frequency of an input signal.
|
||||
/// let freq = ZeroCrossing.Audio(input: OscSin.Audio(freq: 440.0))
|
||||
/// ZeroCrossing.Control(input: audioRateInput) // block-rate measurement
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to analyse. Can be any `ValidGeneratorInput`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public enum ZeroCrossing {
|
||||
|
||||
// MARK: - Shared base
|
||||
|
||||
/// Shared stored properties for `ZeroCrossing.Audio` and `ZeroCrossing.Control`.
|
||||
public class _Base: GeneratorBase {
|
||||
let _input: any ValidGeneratorInput
|
||||
let _mulAdd: MulAddSpec
|
||||
|
||||
/// Sample value from the previous `_computeSamples` call. Lazy-initialised to the
|
||||
/// first input sample on first use; not meaningful before that point.
|
||||
var _prevSample: Double = 0.0
|
||||
/// Samples elapsed since the last rising zero crossing.
|
||||
var _count: Int = 0
|
||||
/// Most recently measured frequency estimate, held until the next crossing.
|
||||
var _freq: Double = 0.0
|
||||
/// `false` until the very first sample is processed; guards lazy-init of `_prevSample`.
|
||||
var _initialized: Bool = false
|
||||
|
||||
init(
|
||||
input: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
super.init()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio rate
|
||||
|
||||
/// Audio-rate zero-crossing frequency estimator.
|
||||
///
|
||||
/// Computes a per-sample frequency estimate from rising zero-crossing spacing.
|
||||
/// The estimate is held between crossings. `_prevSample` is lazy-initialised to
|
||||
/// the first input sample; constant DC input yields `0.0`. Crossings require more
|
||||
/// than `zeroCrossingMinCount` (4) samples of spacing.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to analyse.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to analyse.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
input: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, mul: mul, add: add)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let inputSamples: [Double] = _input.calculatedSamples(
|
||||
graph: graph, count: count).first ?? zeroCrossingZeroBlock
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
|
||||
var prevSample: Double = _prevSample
|
||||
var xingCount: Int = _count
|
||||
var freq: Double = _freq
|
||||
var initialized: Bool = _initialized
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = inputSamples[i]
|
||||
if !initialized {
|
||||
prevSample = x
|
||||
initialized = true
|
||||
}
|
||||
xingCount += 1
|
||||
if xingCount > zeroCrossingMinCount && prevSample <= 0 && x > 0 {
|
||||
freq = sr / Double(xingCount)
|
||||
xingCount = 0
|
||||
}
|
||||
prevSample = x
|
||||
_result[0][i] = freq
|
||||
}
|
||||
|
||||
_prevSample = prevSample
|
||||
_count = xingCount
|
||||
_freq = freq
|
||||
_initialized = initialized
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Control rate
|
||||
|
||||
/// Block-rate zero-crossing frequency estimator.
|
||||
///
|
||||
/// Scans the full audio-rate input block running the same state machine as `Audio`;
|
||||
/// outputs the block-final frequency estimate as a flat block. The estimate is held
|
||||
/// between crossings and starts at `0.0` until the first period is measured.
|
||||
///
|
||||
/// `_prevSample` is lazy-initialised to the first input sample; constant DC input
|
||||
/// yields `0.0`. Crossings require more than `zeroCrossingMinCount` (4) samples of
|
||||
/// spacing, matching SuperCollider behaviour.
|
||||
///
|
||||
/// Bypasses the sub-block loop — the state machine must scan the full audio block
|
||||
/// exactly once per audio cycle to avoid double-advancing the crossing counter.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - 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 var previousOutputValue: Double = 0.0
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to analyse.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
input: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
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,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let inputSamples: [Double] = _input.calculatedSamples(
|
||||
graph: graph, count: count).first ?? zeroCrossingZeroBlock
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
|
||||
var prevSample: Double = _prevSample
|
||||
var xingCount: Int = _count
|
||||
var freq: Double = _freq
|
||||
var initialized: Bool = _initialized
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = inputSamples[i]
|
||||
if !initialized {
|
||||
prevSample = x
|
||||
initialized = true
|
||||
}
|
||||
xingCount += 1
|
||||
if xingCount > zeroCrossingMinCount && prevSample <= 0 && x > 0 {
|
||||
freq = sr / Double(xingCount)
|
||||
xingCount = 0
|
||||
}
|
||||
prevSample = x
|
||||
}
|
||||
|
||||
_prevSample = prevSample
|
||||
_count = xingCount
|
||||
_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]
|
||||
return _result
|
||||
}
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
extension ZeroCrossing: GeneratorEnum {
|
||||
public typealias AudioType = ZeroCrossing.Audio
|
||||
public typealias ControlType = ZeroCrossing.Control
|
||||
}
|
||||
@@ -51,7 +51,7 @@ public enum DiskOut {
|
||||
/// output(bus: 0, source: diskOut[0]) // pass-through to bus 0
|
||||
/// }
|
||||
/// }
|
||||
/// engine.add(Writer())
|
||||
/// try engine.add(Writer())
|
||||
/// try engine.start() // render / play
|
||||
/// diskOut.close() // flush remaining frames and close the file
|
||||
/// ```
|
||||
|
||||
@@ -10,10 +10,14 @@ import Synchronization
|
||||
|
||||
/// Interpolated read from `buffer` at a fractional frame `phase` for one `channel`.
|
||||
///
|
||||
/// - For `loop == true`: frames wrap modulo `buffer.count` (seamless looping). `wrappedFrame`
|
||||
/// handles negative frame indices via `r += frameCount`, so backward reads across the loop
|
||||
/// point are correct.
|
||||
/// - For `loop == false`: frames are clamped to `[0, buffer.count − 1]` (hold at ends).
|
||||
/// - For `loop == true`: frames wrap modulo `buffer.loopLength` (seamless looping).
|
||||
/// `wrappedFrame` handles negative frame indices via `r += frameCount`, so backward
|
||||
/// reads across the loop point are correct.
|
||||
/// - For `loop == false`: frames are clamped to `[0, buffer.loopLength − 1]` (hold at ends).
|
||||
///
|
||||
/// `buffer.loopLength` defaults to `buffer.count` (full-buffer looping) but may be
|
||||
/// narrowed at runtime — e.g. a looper pedal that recorded a take shorter than its
|
||||
/// max-duration buffer allocation — to bound wrap/clamp to just the recorded region.
|
||||
///
|
||||
/// Used by `PlayBuffer.Audio` and `PlayBuffer.Control`; exposed as `internal` for reuse by
|
||||
/// future buffer-reading generators (e.g. `BufferGrain`).
|
||||
@@ -25,7 +29,7 @@ internal func lyrebirdBufferRead(
|
||||
interpolation: TableInterpolation,
|
||||
loop: Bool
|
||||
) -> Double {
|
||||
let frameCount: Int = buffer.count
|
||||
let frameCount: Int = buffer.loopLength
|
||||
|
||||
@inline(__always)
|
||||
func clampedFrame(_ f: Int) -> Int {
|
||||
@@ -59,17 +63,11 @@ internal func lyrebirdBufferRead(
|
||||
case .cubic:
|
||||
let intPhase: Int = Int(phase.rounded(.down))
|
||||
let t: Double = phase - Double(intPhase)
|
||||
let t2: Double = t * t
|
||||
let t3: Double = t2 * t
|
||||
let pM1: Double = frame(intPhase - 1)
|
||||
let p0: Double = frame(intPhase)
|
||||
let p1: Double = frame(intPhase + 1)
|
||||
let p2: Double = frame(intPhase + 2)
|
||||
let catmullRomHalf: Double = 0.5
|
||||
return catmullRomHalf * ((2 * p0)
|
||||
+ (-pM1 + p1) * t
|
||||
+ (2 * pM1 - 5 * p0 + 4 * p1 - p2) * t2
|
||||
+ (-pM1 + 3 * p0 - 3 * p1 + p2) * t3)
|
||||
return catmullRomCubic(pM1, p0, p1, p2, t: t)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -362,7 +360,7 @@ public enum PlayBuffer {
|
||||
return _result
|
||||
}
|
||||
|
||||
let bufferFrames: Double = Double(buffer.count)
|
||||
let bufferFrames: Double = Double(buffer.loopLength)
|
||||
|
||||
@inline(__always)
|
||||
func rateAt(_ i: Int) -> Double {
|
||||
@@ -532,7 +530,7 @@ public enum PlayBuffer {
|
||||
// Read one output value for this block.
|
||||
let outputVal: Double
|
||||
if let buffer: LyrebirdBuffer = _slot.load(engine: graph.engine), buffer.isValid, !_isDone {
|
||||
let bufferFrames: Double = Double(buffer.count)
|
||||
let bufferFrames: Double = Double(buffer.loopLength)
|
||||
outputVal = lyrebirdBufferRead(
|
||||
buffer, channel: 0, phase: _phase,
|
||||
interpolation: interpolation, loop: loop
|
||||
|
||||
@@ -90,6 +90,27 @@ public enum RecordBuffer {
|
||||
var _isDone: Bool = false
|
||||
let _needsFree: Atomic<Bool> = Atomic(false)
|
||||
|
||||
/// Set by `requestReset()` on a non-RT thread, consumed once at the top of the
|
||||
/// next `_computeSamples` call on the RT thread.
|
||||
let _resetRequested: Atomic<Bool> = Atomic(false)
|
||||
|
||||
/// Block-rate snapshot of `writePos`, published once per audio block rather
|
||||
/// than per sample to avoid extra atomic-store overhead in the hot per-sample
|
||||
/// write loops. Updated at the end of every `_computeSamples` call.
|
||||
let _writePosSnapshot: Atomic<Int> = Atomic(0)
|
||||
|
||||
/// Number of frames written to `buffer` so far, safe to read from a non-RT
|
||||
/// thread.
|
||||
///
|
||||
/// `writePos` itself is a plain `var` mutated per-sample on the RT thread and
|
||||
/// is not safe for concurrent non-RT reads. This snapshot is published once
|
||||
/// per audio block (`.releasing` store at the end of `_computeSamples`) and
|
||||
/// read here with an `.acquiring` load, so a caller can safely read "how many
|
||||
/// frames were recorded" after stopping recording (e.g. setting `run = 0`) —
|
||||
/// for example a looper pedal narrowing `buffer.loopLength` to the actually
|
||||
/// recorded region once the take finishes.
|
||||
public var recordedFrameCount: Int { _writePosSnapshot.load(ordering: .acquiring) }
|
||||
|
||||
/// `true` when `doneAction == .freeNode` and recording has completed.
|
||||
///
|
||||
/// Read from a non-RT context after `processBlock` returns and schedule
|
||||
@@ -122,9 +143,42 @@ public enum RecordBuffer {
|
||||
|
||||
// MARK: - Shared
|
||||
|
||||
/// Requests that recording restart from frame 0 on the next processed block.
|
||||
///
|
||||
/// Safe to call from any non-RT thread at any time (e.g. a "reset" UI action on
|
||||
/// a looper pedal). Sets an `Atomic<Bool>` flag consumed once at the top of the
|
||||
/// next `_computeSamples` call — `writePos` is reset to `0`, `_isDone` cleared,
|
||||
/// and any pending `.freeNode` completion (`needsFree`) is cleared so the same
|
||||
/// instance can be reused for a fresh take. Because the flag is only checked at
|
||||
/// block boundaries, the reset takes effect at the start of the next block, not
|
||||
/// mid-block — acceptable for a user-triggered action.
|
||||
///
|
||||
/// Does **not** touch `buffer` contents or `buffer.loopLength`. Callers that want
|
||||
/// a fully blank take should also call `buffer.clear()` and
|
||||
/// `buffer.setLoopLength(buffer.count)` themselves before or after calling this.
|
||||
public func requestReset() {
|
||||
_resetRequested.store(true, ordering: .releasing)
|
||||
}
|
||||
|
||||
/// Consumes a pending reset request, if any. Call once at the top of
|
||||
/// `_computeSamples` before touching `writePos` / `_isDone`.
|
||||
@inline(__always)
|
||||
func _consumeResetIfRequested() {
|
||||
let (exchanged, _): (Bool, Bool) = _resetRequested.compareExchange(
|
||||
expected: true,
|
||||
desired: false,
|
||||
ordering: .acquiringAndReleasing
|
||||
)
|
||||
if exchanged {
|
||||
writePos = 0
|
||||
_isDone = false
|
||||
_needsFree.store(false, ordering: .releasing)
|
||||
}
|
||||
}
|
||||
|
||||
func handleEndOfBuffer() {
|
||||
_isDone = true
|
||||
writePos = buffer.count - 1
|
||||
writePos = buffer.loopLength - 1
|
||||
switch doneAction {
|
||||
case .nothing:
|
||||
break
|
||||
@@ -202,6 +256,10 @@ public enum RecordBuffer {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
_consumeResetIfRequested()
|
||||
// Publish `writePos` once per block (not per sample) for non-RT readers —
|
||||
// see `recordedFrameCount` doc-comment.
|
||||
defer { _writePosSnapshot.store(writePos, ordering: .releasing) }
|
||||
|
||||
let runSamples: [Double] = $run.calculatedSamples(graph: graph, count: count).first
|
||||
?? _zeroFallback
|
||||
@@ -212,7 +270,12 @@ public enum RecordBuffer {
|
||||
|
||||
let chCount: Int = channelCount
|
||||
let bufferIsLive: Bool = buffer.isValid
|
||||
let bufferCount: Int = buffer.count
|
||||
// Wrap/overrun bound is the caller-narrowed `loopLength` (defaults to `count`), for
|
||||
// both `loop == true` (a looping overdub recorder re-writes exactly the recorded
|
||||
// take instead of the full allocated buffer) and `loop == false` (the overrun pins
|
||||
// `writePos` to `loopLength - 1` via `handleEndOfBuffer()`, consistent with this bound
|
||||
// regardless of when the caller narrows `loopLength`).
|
||||
let bufferCount: Int = buffer.loopLength
|
||||
let canRecord: Bool = bufferIsLive && !_isDone
|
||||
let localLoop: Bool = loop
|
||||
|
||||
@@ -524,6 +587,10 @@ public enum RecordBuffer {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
_consumeResetIfRequested()
|
||||
// Publish `writePos` once per block (not per sample) for non-RT readers —
|
||||
// see `recordedFrameCount` doc-comment.
|
||||
defer { _writePosSnapshot.store(writePos, ordering: .releasing) }
|
||||
|
||||
// Evaluate params: advance ParameterNode state; use settled (last-sample) value.
|
||||
let runSamples: [Double] = $run.calculatedSamples(graph: graph, count: count).first
|
||||
@@ -551,7 +618,7 @@ public enum RecordBuffer {
|
||||
let existing: Double = buffer[writePos, 0]
|
||||
buffer.write(recVal * inputVal + preVal * existing, frame: writePos, channel: 0)
|
||||
writePos += 1
|
||||
if writePos >= buffer.count {
|
||||
if writePos >= buffer.loopLength {
|
||||
if loop { writePos = 0 }
|
||||
else { handleEndOfBuffer() }
|
||||
}
|
||||
|
||||
@@ -30,8 +30,9 @@ public enum In {
|
||||
|
||||
/// Reads from one or more consecutive audio buses.
|
||||
///
|
||||
/// The `bus` parameter accepts any ``ValidBus``: a plain `Int` index (1 channel),
|
||||
/// an ``AudioBus`` allocation (channel count taken from the bus), or a ``ControlBus``.
|
||||
/// The `bus` parameter takes a plain `Int` index (1 channel) or an ``AudioBus`` allocation
|
||||
/// (channel count taken from the bus). A ``ControlBus`` traps — `In.Audio` reads the audio-bus
|
||||
/// pool; use ``In/Control`` for a control bus.
|
||||
///
|
||||
/// ```swift
|
||||
/// In.Audio(bus: 5) // reads audioBuses[5], returns 1 channel
|
||||
@@ -42,8 +43,8 @@ public enum In {
|
||||
/// `floatValue` always returns the value of the first channel (bus).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bus: Source bus — `Int` index (1 channel), ``AudioBus`` (reads `channelCount`
|
||||
/// consecutive buses), or ``ControlBus``.
|
||||
/// - bus: Source bus — `Int` index (1 channel) or ``AudioBus`` (reads `channelCount`
|
||||
/// consecutive buses). A ``ControlBus`` traps; use ``In/Control``.
|
||||
/// - 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 Audio: _Base, AudioGenerator {
|
||||
@@ -51,9 +52,10 @@ public enum In {
|
||||
/// Reads from a ``ValidBus``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bus: Source bus — `Int` index (1 channel), ``AudioBus`` (uses `channelCount`),
|
||||
/// or ``ControlBus``.
|
||||
/// - bus: Source bus — `Int` index (1 channel) or ``AudioBus`` (uses `channelCount`).
|
||||
/// A ``ControlBus`` traps; use ``In/Control``.
|
||||
public init(bus: any ValidBus) {
|
||||
_preconditionAudioRateBus(bus)
|
||||
let ch: Int = _resolvedChannelCount(bus)
|
||||
super.init(bus: bus.index, channels: ch)
|
||||
}
|
||||
@@ -126,7 +128,12 @@ public enum In {
|
||||
|
||||
/// Creates a `GeneratorArray` of independent single-channel generators, one per channel of `bus`.
|
||||
/// Prefer `In.Audio(bus:)` when a single multi-output generator is sufficient.
|
||||
///
|
||||
/// Takes an `Int` index or an ``AudioBus``; a ``ControlBus`` traps (this reads the audio-bus
|
||||
/// pool). The `Int` delegate below can't see the original typed bus, so the guard is applied
|
||||
/// here before delegating.
|
||||
public static func multi(bus: any ValidBus) -> GeneratorArray {
|
||||
_preconditionAudioRateBus(bus)
|
||||
let ch: Int = _resolvedChannelCount(bus)
|
||||
return multi(bus: bus.index, channels: ch)
|
||||
}
|
||||
@@ -137,8 +144,9 @@ public enum In {
|
||||
/// Reads from one or more consecutive control buses and delivers interpolated audio-rate
|
||||
/// ramps to downstream generators.
|
||||
///
|
||||
/// The `bus` parameter accepts any ``ValidBus``: a plain `Int` index (1 channel),
|
||||
/// a ``ControlBus`` allocation (channel count taken from the bus), or an ``AudioBus``.
|
||||
/// The `bus` parameter takes a plain `Int` index (1 channel) or a ``ControlBus`` allocation
|
||||
/// (channel count taken from the bus). An ``AudioBus`` traps — `In.Control` reads the
|
||||
/// control-bus pool; use ``In/Audio`` for an audio bus.
|
||||
///
|
||||
/// ```swift
|
||||
/// In.Control(bus: 10) // reads controlBuses[10], interpolated ramp
|
||||
@@ -153,8 +161,8 @@ public enum In {
|
||||
/// in steady state.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bus: Source bus — `Int` index (1 channel), ``ControlBus`` (reads `channelCount`
|
||||
/// consecutive buses with independent ramp state per channel), or ``AudioBus``.
|
||||
/// - bus: Source bus — `Int` index (1 channel) or ``ControlBus`` (reads `channelCount`
|
||||
/// 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 {
|
||||
@@ -172,9 +180,10 @@ public enum In {
|
||||
/// Reads from a ``ValidBus``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bus: Source bus — `Int` index (1 channel), ``ControlBus`` (uses `channelCount`),
|
||||
/// or ``AudioBus``.
|
||||
/// - bus: Source bus — `Int` index (1 channel) or ``ControlBus`` (uses `channelCount`).
|
||||
/// An ``AudioBus`` traps; use ``In/Audio``.
|
||||
public init(bus: any ValidBus) {
|
||||
_preconditionControlRateBus(bus)
|
||||
let ch: Int = _resolvedChannelCount(bus)
|
||||
_previousOutputValues = [Double](repeating: 0.0, count: ch)
|
||||
super.init(bus: bus.index, channels: ch)
|
||||
|
||||
@@ -40,9 +40,9 @@ public enum Out {
|
||||
/// Accumulates into one or more consecutive audio buses using +=.
|
||||
/// Multiple ``Synthesizer`` instances writing to the same bus mix additively.
|
||||
///
|
||||
/// The `bus` parameter accepts any ``ValidBus``: a plain `Int` index, an ``AudioBus``
|
||||
/// allocation, or (unusually) a ``ControlBus``. When `bus` is an ``AudioBus``, writing
|
||||
/// is automatically clamped to `bus.channelCount` channels.
|
||||
/// The `bus` parameter takes a plain `Int` index or an ``AudioBus`` allocation (writes are
|
||||
/// clamped to `bus.channelCount` channels). Passing a ``ControlBus`` traps — an audio `Out`
|
||||
/// addresses the audio-bus pool, so use ``Out/Control`` for a control bus.
|
||||
///
|
||||
/// ## Multi-channel sources
|
||||
///
|
||||
@@ -57,9 +57,8 @@ public enum Out {
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bus: Destination bus — `Int` index (no channel clamping), ``AudioBus`` (clamped to
|
||||
/// `channelCount`), or ``ControlBus``. Passed to `In.Audio` or the `output(bus:source:)`
|
||||
/// helper.
|
||||
/// - bus: Destination bus — `Int` index (no channel clamping) or ``AudioBus`` (clamped to
|
||||
/// `channelCount`). A ``ControlBus`` traps; use ``Out/Control`` instead.
|
||||
/// - source: Signal to write. Multi-channel sources write to consecutive buses starting at
|
||||
/// `bus.index`.
|
||||
public final class Audio: _Base, AudioGenerator, RootRegistering {
|
||||
@@ -73,13 +72,14 @@ public enum Out {
|
||||
}
|
||||
|
||||
/// - Parameters:
|
||||
/// - bus: Destination bus — `Int` index, ``AudioBus``, or ``ControlBus``.
|
||||
/// When `bus` is an ``AudioBus``, writing is clamped to `bus.channelCount` channels.
|
||||
/// - bus: Destination bus — `Int` index or ``AudioBus`` (writing clamped to
|
||||
/// `bus.channelCount`). A ``ControlBus`` traps; use ``Out/Control`` instead.
|
||||
/// - source: Signal to write. Multi-channel sources write to consecutive buses.
|
||||
public init(
|
||||
bus: any ValidBus,
|
||||
source: any ValidGeneratorInput
|
||||
) {
|
||||
_preconditionAudioRateBus(bus)
|
||||
super.init(bus: bus.index, source: source, maxChannels: bus.channelCount)
|
||||
_registerAsRootIfBuilding()
|
||||
}
|
||||
@@ -115,9 +115,9 @@ public enum Out {
|
||||
/// a sink whose output is a control bus write). `previousOutputValue` is required by
|
||||
/// the ControlGenerator protocol but is not used.
|
||||
///
|
||||
/// The `bus` parameter accepts any ``ValidBus``: a plain `Int` index, a ``ControlBus``
|
||||
/// allocation, or an ``AudioBus``. When `bus` is a ``ControlBus``, writing is clamped to
|
||||
/// `bus.channelCount` channels.
|
||||
/// The `bus` parameter takes a plain `Int` index or a ``ControlBus`` allocation (writes are
|
||||
/// clamped to `bus.channelCount` channels). Passing an ``AudioBus`` traps — a control `Out`
|
||||
/// addresses the control-bus pool, so use ``Out/Audio`` for an audio bus.
|
||||
///
|
||||
/// ## Multi-channel sources
|
||||
///
|
||||
@@ -131,8 +131,8 @@ public enum Out {
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bus: Destination bus — `Int` index (1 channel, no clamping), ``ControlBus`` (clamped
|
||||
/// to `channelCount`), or ``AudioBus``.
|
||||
/// - bus: Destination bus — `Int` index (1 channel, no clamping) or ``ControlBus`` (clamped
|
||||
/// 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 {
|
||||
@@ -147,14 +147,15 @@ public enum Out {
|
||||
public override var outputChannelCount: Int { _channels }
|
||||
|
||||
/// - Parameters:
|
||||
/// - bus: Destination bus — `Int` index, ``ControlBus``, or ``AudioBus``.
|
||||
/// When `bus` is a ``ControlBus``, writing is clamped to `bus.channelCount` channels.
|
||||
/// - bus: Destination bus — `Int` index or ``ControlBus`` (writing clamped to
|
||||
/// `bus.channelCount`). An ``AudioBus`` traps; use ``Out/Audio`` instead.
|
||||
/// A plain `Int` writes a single channel.
|
||||
/// - source: Signal to write. Multi-channel sources write to consecutive buses.
|
||||
public init(
|
||||
bus: any ValidBus,
|
||||
source: any ValidGeneratorInput
|
||||
) {
|
||||
_preconditionControlRateBus(bus)
|
||||
let ch: Int = _resolvedChannelCount(bus)
|
||||
self._channels = ch
|
||||
super.init(bus: bus.index, source: source, maxChannels: bus.channelCount, channels: ch)
|
||||
|
||||
@@ -60,10 +60,10 @@ public enum ReplaceOut {
|
||||
/// Overwrites one or more consecutive audio buses with the source signal
|
||||
/// (wipes any prior writes to those buses in the current block).
|
||||
///
|
||||
/// The `bus` parameter accepts any ``ValidBus``: a plain `Int` index, an
|
||||
/// ``AudioBus`` allocation, or (unusually) a ``ControlBus``. When `bus` is
|
||||
/// an ``AudioBus``, writing is automatically clamped to `bus.channelCount`
|
||||
/// channels.
|
||||
/// The `bus` parameter takes a plain `Int` index or an ``AudioBus`` allocation
|
||||
/// (writing clamped to `bus.channelCount` channels). A ``ControlBus`` traps —
|
||||
/// an audio `ReplaceOut` addresses the audio-bus pool; use ``ReplaceOut/Control``
|
||||
/// for a control bus.
|
||||
///
|
||||
/// ## Multi-channel sources
|
||||
///
|
||||
@@ -81,8 +81,8 @@ public enum ReplaceOut {
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bus: Destination bus — `Int` index (no channel clamping), ``AudioBus``
|
||||
/// (clamped to `channelCount`), or ``ControlBus``.
|
||||
/// - bus: Destination bus — `Int` index (no channel clamping) or ``AudioBus``
|
||||
/// (clamped to `channelCount`). A ``ControlBus`` traps; use ``ReplaceOut/Control``.
|
||||
/// - source: Signal to write. Multi-channel sources overwrite consecutive
|
||||
/// buses starting at `bus.index`.
|
||||
public final class Audio: _Base, AudioGenerator, RootRegistering {
|
||||
@@ -102,13 +102,14 @@ public enum ReplaceOut {
|
||||
}
|
||||
|
||||
/// - Parameters:
|
||||
/// - bus: Destination bus — `Int` index, ``AudioBus``, or ``ControlBus``.
|
||||
/// When `bus` is an ``AudioBus``, writing is clamped to `bus.channelCount` channels.
|
||||
/// - bus: Destination bus — `Int` index or ``AudioBus`` (writing clamped to
|
||||
/// `bus.channelCount`). A ``ControlBus`` traps; use ``ReplaceOut/Control``.
|
||||
/// - source: Signal to write. Multi-channel sources overwrite consecutive buses.
|
||||
public init(
|
||||
bus: any ValidBus,
|
||||
source: any ValidGeneratorInput
|
||||
) {
|
||||
_preconditionAudioRateBus(bus)
|
||||
super.init(bus: bus.index, source: source, maxChannels: bus.channelCount)
|
||||
_registerAsRootIfBuilding()
|
||||
}
|
||||
@@ -151,9 +152,10 @@ public enum ReplaceOut {
|
||||
/// control bus write). `previousOutputValue` is required by the
|
||||
/// ControlGenerator protocol but is not used.
|
||||
///
|
||||
/// The `bus` parameter accepts any ``ValidBus``: a plain `Int` index, a
|
||||
/// ``ControlBus`` allocation, or an ``AudioBus``. When `bus` is a
|
||||
/// ``ControlBus``, writing is clamped to `bus.channelCount` channels.
|
||||
/// The `bus` parameter takes a plain `Int` index or a ``ControlBus`` allocation
|
||||
/// (writing clamped to `bus.channelCount` channels). An ``AudioBus`` traps —
|
||||
/// a control `ReplaceOut` addresses the control-bus pool; use ``ReplaceOut/Audio``
|
||||
/// for an audio bus.
|
||||
///
|
||||
/// ## Multi-channel sources
|
||||
///
|
||||
@@ -163,8 +165,8 @@ public enum ReplaceOut {
|
||||
/// usage.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bus: Destination bus — `Int` index (1 channel, no clamping),
|
||||
/// ``ControlBus`` (clamped to `channelCount`), or ``AudioBus``.
|
||||
/// - bus: Destination bus — `Int` index (1 channel, no clamping) or
|
||||
/// ``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 {
|
||||
@@ -176,8 +178,8 @@ public enum ReplaceOut {
|
||||
///
|
||||
/// - Note: Channel-count policy intentionally mirrors ``Out/Control``: a
|
||||
/// plain `Int` bus resolves to 1 channel (extra source channels are
|
||||
/// silently dropped); a ``ControlBus`` or ``AudioBus`` resolves to its
|
||||
/// explicit `channelCount`. ``ReplaceOut/Audio`` differs — a plain
|
||||
/// silently dropped); a ``ControlBus`` resolves to its explicit
|
||||
/// `channelCount`. ``ReplaceOut/Audio`` differs — a plain
|
||||
/// `Int` bus there writes all source channels via `_maxChannels =
|
||||
/// Int.max`. Use a typed bus allocation if you want explicit
|
||||
/// multi-channel writes from a plain index.
|
||||
@@ -186,13 +188,14 @@ public enum ReplaceOut {
|
||||
public override var outputChannelCount: Int { _channels }
|
||||
|
||||
/// - Parameters:
|
||||
/// - bus: Destination bus — `Int` index, ``ControlBus``, or ``AudioBus``.
|
||||
/// When `bus` is a ``ControlBus``, writing is clamped to `bus.channelCount` channels.
|
||||
/// - bus: Destination bus — `Int` index or ``ControlBus`` (writing clamped to
|
||||
/// `bus.channelCount`). An ``AudioBus`` traps; use ``ReplaceOut/Audio``.
|
||||
/// - source: Signal to write. Multi-channel sources overwrite consecutive buses.
|
||||
public init(
|
||||
bus: any ValidBus,
|
||||
source: any ValidGeneratorInput
|
||||
) {
|
||||
_preconditionControlRateBus(bus)
|
||||
let ch: Int = _resolvedChannelCount(bus)
|
||||
self._channels = ch
|
||||
super.init(bus: bus.index, source: source, maxChannels: bus.channelCount, channels: ch)
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
// ChaoticBase.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Shared base for strange-attractor / chaotic-map oscillators.
|
||||
///
|
||||
/// A chaotic oscillator iterates a discrete map (Lorenz, Hénon, …) at a chosen
|
||||
/// `freq` (iterations per second), **not** once per audio sample. Between
|
||||
/// successive iterations the audio output bridges the two map values according to
|
||||
/// `interpolation`:
|
||||
///
|
||||
/// - `.none` — hold the current iteration value until the next (hard, aliased).
|
||||
/// - `.linear` — straight-line ramp between successive iterations.
|
||||
/// - `.cubic` — 4-point cubic across the surrounding iterations (smoothest).
|
||||
///
|
||||
/// Same shape as `NoiseBase`: the base owns the cross-rate shared state
|
||||
/// (`_freqInput`, `_mulAdd`, `_interpolation`, the 4-value history ring, and the
|
||||
/// sub-iteration phase accumulator). Concrete per-map `_Base` subclasses add the
|
||||
/// map's own variables and the `iterate()` recurrence; `Audio` / `Control`
|
||||
/// variants inherit that subclass.
|
||||
///
|
||||
/// `freq` and the map parameters are read once per block (`floatValue`) — chaotic
|
||||
/// oscillators do not support per-sample audio-rate parameter modulation.
|
||||
public class ChaoticBase: GeneratorBase {
|
||||
let _freqInput: any ValidGeneratorInput
|
||||
var _mulAdd: MulAddSpec
|
||||
let _interpolation: TableInterpolation
|
||||
|
||||
/// History ring around the current `[_h0, _h1]` segment:
|
||||
/// `_hM1` = one iteration before the segment start, `_h2` = one after the end.
|
||||
/// `.none` reads `_h0`, `.linear` lerps `_h0…_h1`, `.cubic` uses all four.
|
||||
var _hM1: Double = 0.0
|
||||
var _h0: Double = 0.0
|
||||
var _h1: Double = 0.0
|
||||
var _h2: Double = 0.0
|
||||
|
||||
/// Fraction `[0, 1)` through the current iteration segment.
|
||||
var _phase: Double = 0.0
|
||||
|
||||
/// Lazy one-shot history priming guard (the concrete map seeds its variables
|
||||
/// at `init`, then the first `_computeSamples` fills the ring via `iterate()`).
|
||||
var _seeded: Bool = false
|
||||
|
||||
init(
|
||||
freq: any ValidGeneratorInput,
|
||||
interpolation: TableInterpolation,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
|
||||
self._freqInput = resolvedFreq
|
||||
self._interpolation = interpolation
|
||||
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
super.init()
|
||||
}
|
||||
|
||||
/// Advance the map one iteration and return its new output value.
|
||||
///
|
||||
/// Overridden by every concrete map `_Base`. The base implementation returns
|
||||
/// `0` — a missing override would silence the oscillator rather than trap on
|
||||
/// the RT thread.
|
||||
func iterate() -> Double { 0.0 }
|
||||
|
||||
/// Fill the history ring on first use: four warm-up iterations seed
|
||||
/// `_hM1, _h0, _h1, _h2` so the cubic kernel has real neighbours and the
|
||||
/// transient settles onto the attractor before audio is taken.
|
||||
@inline(__always)
|
||||
func primeIfNeeded() {
|
||||
if _seeded { return }
|
||||
_hM1 = iterate()
|
||||
_h0 = iterate()
|
||||
_h1 = iterate()
|
||||
_h2 = iterate()
|
||||
_phase = 0.0
|
||||
_seeded = true
|
||||
}
|
||||
|
||||
/// Per-sample phase increment for `freq`, clamped to `[0, chaoticMaxStepRate]`.
|
||||
///
|
||||
/// Negative `freq` holds (returns `0`) rather than driving `_phase` negative —
|
||||
/// the map has no backward iteration. The upper clamp bounds the `advancePhase`
|
||||
/// loop so an extreme `freq` cannot stall the RT thread.
|
||||
@inline(__always)
|
||||
func stepRate(freq: Double, sampleRate: Double) -> Double {
|
||||
let raw: Double = freq / sampleRate
|
||||
if raw <= 0 { return 0.0 }
|
||||
return min(raw, chaoticMaxStepRate)
|
||||
}
|
||||
|
||||
/// Advance the sub-iteration phase by `dphase`, performing as many `iterate()`
|
||||
/// steps as the phase crosses (shifting the history ring forward each time).
|
||||
@inline(__always)
|
||||
func advancePhase(by dphase: Double) {
|
||||
_phase += dphase
|
||||
while _phase >= 1.0 {
|
||||
_phase -= 1.0
|
||||
_hM1 = _h0
|
||||
_h0 = _h1
|
||||
_h1 = _h2
|
||||
_h2 = iterate()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// ChaoticHelpers.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Default iteration frequency (Hz) for the chaotic oscillators — one iteration
|
||||
/// every other sample at 44.1 kHz, matching the SuperCollider chaotic-UGen
|
||||
/// defaults. `@usableFromInline` so it can back the public `init` default args.
|
||||
@usableFromInline
|
||||
internal let chaoticDefaultFrequency: Double = 22050.0
|
||||
|
||||
/// Upper bound on map iterations per output sample. Caps the `advancePhase`
|
||||
/// `while` loop so a pathological caller-supplied `freq` (e.g. `freq ≫ sampleRate`)
|
||||
/// cannot do unbounded work on the RT thread.
|
||||
internal let chaoticMaxStepRate: Double = 64.0
|
||||
|
||||
/// Wrap a phase/angle into `[0, 2π)`. Used by the angle-state chaotic maps
|
||||
/// (`StandardN`, `FBSineN`) to keep their unbounded accumulators bounded.
|
||||
@inline(__always)
|
||||
internal func chaoticWrapTwoPi(_ v: Double) -> Double {
|
||||
v - lyrebirdTwoPi * (v / lyrebirdTwoPi).rounded(.down)
|
||||
}
|
||||
|
||||
// MARK: - Interpolation kernel
|
||||
|
||||
/// Bridge between successive chaotic-map iterations for the current segment.
|
||||
///
|
||||
/// `t ∈ [0, 1)` is the fraction through the `[h0, h1]` segment; `hM1` / `h2` are
|
||||
/// the surrounding iterations used only by the cubic kernel, which delegates to
|
||||
/// the shared `catmullRomCubic` spline.
|
||||
@inline(__always)
|
||||
internal func chaoticInterpolate(
|
||||
_ interpolation: TableInterpolation,
|
||||
phase t: Double,
|
||||
hM1: Double, h0: Double, h1: Double, h2: Double
|
||||
) -> Double {
|
||||
switch interpolation {
|
||||
case .none:
|
||||
return h0
|
||||
case .linear:
|
||||
return h0 + t * (h1 - h0)
|
||||
case .cubic:
|
||||
return catmullRomCubic(hM1, h0, h1, h2, t: t)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
// CuspStepped.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Cusp-map oscillator (non-interpolated by default).
|
||||
///
|
||||
/// Iterates the cusp map at `freq` Hz:
|
||||
/// ```
|
||||
/// x[n+1] = a − b · √|x[n]|
|
||||
/// ```
|
||||
/// and outputs `x`. With the canonical `a = 1`, `b = 1.9` the orbit is chaotic and
|
||||
/// bounded to roughly `[-0.9, 1.0]`. Iterations bridge per `interpolation`
|
||||
/// (default `.none`).
|
||||
///
|
||||
/// `freq`, `a`, and `b` are read once per block. See ``ChaoticBase`` for the
|
||||
/// iteration / interpolation model.
|
||||
public enum CuspStepped {
|
||||
|
||||
// MARK: - _Base
|
||||
|
||||
/// Shared cusp-map state + parameters for `Audio` and `Control`.
|
||||
public class _Base: ChaoticBase {
|
||||
let aInput: any ValidGeneratorInput
|
||||
let bInput: any ValidGeneratorInput
|
||||
|
||||
// Map state.
|
||||
var x: Double
|
||||
|
||||
// Per-block parameter snapshot read by `iterate()`.
|
||||
var _a: Double = 0.0
|
||||
var _b: Double = 0.0
|
||||
|
||||
init(
|
||||
freq: any ValidGeneratorInput,
|
||||
a: any ValidGeneratorInput,
|
||||
b: any ValidGeneratorInput,
|
||||
xi: Double,
|
||||
interpolation: TableInterpolation,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
self.aInput = a._resolvedInput()
|
||||
self.bInput = b._resolvedInput()
|
||||
self.x = xi
|
||||
super.init(freq: freq, interpolation: interpolation, mul: mul, add: add)
|
||||
}
|
||||
|
||||
override func iterate() -> Double {
|
||||
let xNew: Double = _a - _b * (abs(x)).squareRoot()
|
||||
x = xNew
|
||||
return xNew
|
||||
}
|
||||
|
||||
/// Snapshot the per-block parameters into the fields `iterate()` reads.
|
||||
@inline(__always)
|
||||
func readParams(graph: SynthGraph) {
|
||||
_a = aInput.floatValue(graph: graph)
|
||||
_b = bInput.floatValue(graph: graph)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio
|
||||
|
||||
/// Audio-rate cusp-map oscillator.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - a: Offset term. Defaults to `1`. No clamping; some `(a,b)` pairs diverge.
|
||||
/// - b: Square-root coefficient. Defaults to `1.9`.
|
||||
/// - xi: Initial `x`. Defaults to `0`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - a: Offset term. Defaults to `1`. No clamping; some `(a,b)` pairs diverge.
|
||||
/// - b: Square-root coefficient. Defaults to `1.9`.
|
||||
/// - xi: Initial `x`. Defaults to `0`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
freq: any ValidGeneratorInput = chaoticDefaultFrequency,
|
||||
a: any ValidGeneratorInput = 1.0,
|
||||
b: any ValidGeneratorInput = 1.9,
|
||||
xi: Double = 0.0,
|
||||
interpolation: TableInterpolation = .none,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(freq: freq, a: a, b: b, xi: xi,
|
||||
interpolation: interpolation, mul: mul, add: add)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Control
|
||||
|
||||
/// Control-rate cusp-map oscillator. Advances the map by one audio block per
|
||||
/// call and ramps from the previous block value to the new one.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - a: Offset term. Defaults to `1`. No clamping; some `(a,b)` pairs diverge.
|
||||
/// - b: Square-root coefficient. Defaults to `1.9`.
|
||||
/// - xi: Initial `x`. Defaults to `0`.
|
||||
/// - 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 func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - a: Offset term. Defaults to `1`. No clamping; some `(a,b)` pairs diverge.
|
||||
/// - b: Square-root coefficient. Defaults to `1.9`.
|
||||
/// - xi: Initial `x`. Defaults to `0`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
freq: any ValidGeneratorInput = chaoticDefaultFrequency,
|
||||
a: any ValidGeneratorInput = 1.0,
|
||||
b: any ValidGeneratorInput = 1.9,
|
||||
xi: Double = 0.0,
|
||||
interpolation: TableInterpolation = .none,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
extension CuspStepped: GeneratorEnum {
|
||||
public typealias AudioType = CuspStepped.Audio
|
||||
public typealias ControlType = CuspStepped.Control
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
// FBSineStepped.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Feedback-sine-map oscillator (non-interpolated by default).
|
||||
///
|
||||
/// Iterates a feedback sine map at `freq` Hz, with the phase accumulator `y`
|
||||
/// wrapped into `[0, 2π)`:
|
||||
/// ```
|
||||
/// x[n+1] = sin(im · y[n] + fb · x[n])
|
||||
/// y[n+1] = (a · y[n] + c) mod 2π
|
||||
/// ```
|
||||
/// and outputs `x` (range `[-1, 1]` — the output is a sine). With the canonical
|
||||
/// `im = 1`, `fb = 0.1`, `a = 1.1`, `c = 0.5` the orbit is chaotic. Iterations
|
||||
/// bridge per `interpolation` (default `.none`).
|
||||
///
|
||||
/// `freq`, `im`, `fb`, `a`, and `c` are read once per block. See ``ChaoticBase``
|
||||
/// for the iteration / interpolation model.
|
||||
public enum FBSineStepped {
|
||||
|
||||
// MARK: - _Base
|
||||
|
||||
/// Shared feedback-sine state + parameters for `Audio` and `Control`.
|
||||
public class _Base: ChaoticBase {
|
||||
let imInput: any ValidGeneratorInput
|
||||
let fbInput: any ValidGeneratorInput
|
||||
let aInput: any ValidGeneratorInput
|
||||
let cInput: any ValidGeneratorInput
|
||||
|
||||
// Map state.
|
||||
var x: Double
|
||||
var y: Double
|
||||
|
||||
// Per-block parameter snapshot read by `iterate()`.
|
||||
var _im: Double = 0.0
|
||||
var _fb: Double = 0.0
|
||||
var _a: Double = 0.0
|
||||
var _c: Double = 0.0
|
||||
|
||||
init(
|
||||
freq: any ValidGeneratorInput,
|
||||
im: any ValidGeneratorInput,
|
||||
fb: any ValidGeneratorInput,
|
||||
a: any ValidGeneratorInput,
|
||||
c: any ValidGeneratorInput,
|
||||
xi: Double,
|
||||
yi: Double,
|
||||
interpolation: TableInterpolation,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
self.imInput = im._resolvedInput()
|
||||
self.fbInput = fb._resolvedInput()
|
||||
self.aInput = a._resolvedInput()
|
||||
self.cInput = c._resolvedInput()
|
||||
self.x = xi
|
||||
self.y = yi
|
||||
super.init(freq: freq, interpolation: interpolation, mul: mul, add: add)
|
||||
}
|
||||
|
||||
override func iterate() -> Double {
|
||||
let xNew: Double = sin(_im * y + _fb * x)
|
||||
y = chaoticWrapTwoPi(_a * y + _c)
|
||||
x = xNew
|
||||
return xNew
|
||||
}
|
||||
|
||||
/// Snapshot the per-block parameters into the fields `iterate()` reads.
|
||||
@inline(__always)
|
||||
func readParams(graph: SynthGraph) {
|
||||
_im = imInput.floatValue(graph: graph)
|
||||
_fb = fbInput.floatValue(graph: graph)
|
||||
_a = aInput.floatValue(graph: graph)
|
||||
_c = cInput.floatValue(graph: graph)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio
|
||||
|
||||
/// Audio-rate feedback-sine oscillator.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - im: Phase index multiplier. Defaults to `1`.
|
||||
/// - fb: Feedback amount. Defaults to `0.1`.
|
||||
/// - a: Phase-accumulator multiplier. Defaults to `1.1`.
|
||||
/// - c: Phase-accumulator increment. Defaults to `0.5`.
|
||||
/// - xi: Initial `x`. Defaults to `0.1`.
|
||||
/// - yi: Initial `y` (phase). Defaults to `0.1`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - im: Phase index multiplier. Defaults to `1`.
|
||||
/// - fb: Feedback amount. Defaults to `0.1`.
|
||||
/// - a: Phase-accumulator multiplier. Defaults to `1.1`.
|
||||
/// - c: Phase-accumulator increment. Defaults to `0.5`.
|
||||
/// - xi: Initial `x`. Defaults to `0.1`.
|
||||
/// - yi: Initial `y` (phase). Defaults to `0.1`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
freq: any ValidGeneratorInput = chaoticDefaultFrequency,
|
||||
im: any ValidGeneratorInput = 1.0,
|
||||
fb: any ValidGeneratorInput = 0.1,
|
||||
a: any ValidGeneratorInput = 1.1,
|
||||
c: any ValidGeneratorInput = 0.5,
|
||||
xi: Double = 0.1,
|
||||
yi: Double = 0.1,
|
||||
interpolation: TableInterpolation = .none,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(freq: freq, im: im, fb: fb, a: a, c: c, xi: xi, yi: yi,
|
||||
interpolation: interpolation, mul: mul, add: add)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Control
|
||||
|
||||
/// Control-rate feedback-sine oscillator. Advances the map by one audio block
|
||||
/// per call and ramps from the previous block value to the new one.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - im: Phase index multiplier. Defaults to `1`.
|
||||
/// - fb: Feedback amount. Defaults to `0.1`.
|
||||
/// - a: Phase-accumulator multiplier. Defaults to `1.1`.
|
||||
/// - c: Phase-accumulator increment. Defaults to `0.5`.
|
||||
/// - xi: Initial `x`. Defaults to `0.1`.
|
||||
/// - yi: Initial `y` (phase). Defaults to `0.1`.
|
||||
/// - 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 func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - im: Phase index multiplier. Defaults to `1`.
|
||||
/// - fb: Feedback amount. Defaults to `0.1`.
|
||||
/// - a: Phase-accumulator multiplier. Defaults to `1.1`.
|
||||
/// - c: Phase-accumulator increment. Defaults to `0.5`.
|
||||
/// - xi: Initial `x`. Defaults to `0.1`.
|
||||
/// - yi: Initial `y` (phase). Defaults to `0.1`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
freq: any ValidGeneratorInput = chaoticDefaultFrequency,
|
||||
im: any ValidGeneratorInput = 1.0,
|
||||
fb: any ValidGeneratorInput = 0.1,
|
||||
a: any ValidGeneratorInput = 1.1,
|
||||
c: any ValidGeneratorInput = 0.5,
|
||||
xi: Double = 0.1,
|
||||
yi: Double = 0.1,
|
||||
interpolation: TableInterpolation = .none,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
extension FBSineStepped: GeneratorEnum {
|
||||
public typealias AudioType = FBSineStepped.Audio
|
||||
public typealias ControlType = FBSineStepped.Control
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
// GbmanStepped.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Gingerbreadman-map oscillator (non-interpolated / stepped by default).
|
||||
///
|
||||
/// Iterates the Gingerbreadman recurrence at `freq` Hz:
|
||||
/// ```
|
||||
/// x[n+1] = 1 − y[n] + |x[n]|
|
||||
/// y[n+1] = x[n]
|
||||
/// ```
|
||||
/// and outputs `x`. The orbit is chaotic and bounded (roughly `|x| < 8`). It has
|
||||
/// no shape parameters — only the initial conditions `xi` / `yi`. Iterations bridge
|
||||
/// per `interpolation` (default `.none` — held / stepped, the aliased SC `GbmanN`
|
||||
/// character).
|
||||
///
|
||||
/// `freq` is read once per block (no per-sample audio-rate modulation). See
|
||||
/// ``ChaoticBase`` for the iteration / interpolation model.
|
||||
public enum GbmanStepped {
|
||||
|
||||
// MARK: - _Base
|
||||
|
||||
/// Shared Gingerbreadman state for `Audio` and `Control`.
|
||||
public class _Base: ChaoticBase {
|
||||
// Map state: x[n] and y[n].
|
||||
var x: Double
|
||||
var y: Double
|
||||
|
||||
init(
|
||||
freq: any ValidGeneratorInput,
|
||||
xi: Double,
|
||||
yi: Double,
|
||||
interpolation: TableInterpolation,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
self.x = xi
|
||||
self.y = yi
|
||||
super.init(freq: freq, interpolation: interpolation, mul: mul, add: add)
|
||||
}
|
||||
|
||||
override func iterate() -> Double {
|
||||
let xNew: Double = 1.0 - y + abs(x)
|
||||
y = x
|
||||
x = xNew
|
||||
return xNew
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio
|
||||
|
||||
/// Audio-rate Gingerbreadman oscillator.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - xi: Initial `x`. Defaults to `1.2`.
|
||||
/// - yi: Initial `y`. Defaults to `2.1`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - xi: Initial `x`. Defaults to `1.2`.
|
||||
/// - yi: Initial `y`. Defaults to `2.1`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
freq: any ValidGeneratorInput = chaoticDefaultFrequency,
|
||||
xi: Double = 1.2,
|
||||
yi: Double = 2.1,
|
||||
interpolation: TableInterpolation = .none,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(freq: freq, xi: xi, yi: yi,
|
||||
interpolation: interpolation, mul: mul, add: add)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Control
|
||||
|
||||
/// Control-rate Gingerbreadman oscillator. Advances the map by one audio block
|
||||
/// per call and ramps from the previous block value to the new one.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - xi: Initial `x`. Defaults to `1.2`.
|
||||
/// - yi: Initial `y`. Defaults to `2.1`.
|
||||
/// - 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 func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - xi: Initial `x`. Defaults to `1.2`.
|
||||
/// - yi: Initial `y`. Defaults to `2.1`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
freq: any ValidGeneratorInput = chaoticDefaultFrequency,
|
||||
xi: Double = 1.2,
|
||||
yi: Double = 2.1,
|
||||
interpolation: TableInterpolation = .none,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
extension GbmanStepped: GeneratorEnum {
|
||||
public typealias AudioType = GbmanStepped.Audio
|
||||
public typealias ControlType = GbmanStepped.Control
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
// HenonStepped.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Hénon-map oscillator (non-interpolated / stepped by default).
|
||||
///
|
||||
/// Iterates the Hénon recurrence at `freq` Hz:
|
||||
/// ```
|
||||
/// x[n+1] = 1 − a · x[n]² + b · x[n−1]
|
||||
/// ```
|
||||
/// and outputs `x`. With the canonical `a = 1.4`, `b = 0.3` the orbit is chaotic
|
||||
/// and bounded to roughly `[-1.5, 1.5]`. Iterations bridge per `interpolation`
|
||||
/// (default `.none` — held / stepped, the aliased SC `HenonN` character).
|
||||
///
|
||||
/// `freq`, `a`, and `b` are read once per block (no per-sample audio-rate
|
||||
/// modulation). See ``ChaoticBase`` for the iteration / interpolation model.
|
||||
public enum HenonStepped {
|
||||
|
||||
// MARK: - _Base
|
||||
|
||||
/// Shared Hénon state + parameters for `Audio` and `Control`.
|
||||
public class _Base: ChaoticBase {
|
||||
let aInput: any ValidGeneratorInput
|
||||
let bInput: any ValidGeneratorInput
|
||||
|
||||
// Map state: x[n] and x[n-1].
|
||||
var xn: Double
|
||||
var xnm1: Double
|
||||
|
||||
// Per-block parameter snapshot read by `iterate()`.
|
||||
var _a: Double = 0.0
|
||||
var _b: Double = 0.0
|
||||
|
||||
init(
|
||||
freq: any ValidGeneratorInput,
|
||||
a: any ValidGeneratorInput,
|
||||
b: any ValidGeneratorInput,
|
||||
x0: Double,
|
||||
x1: Double,
|
||||
interpolation: TableInterpolation,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
self.aInput = a._resolvedInput()
|
||||
self.bInput = b._resolvedInput()
|
||||
self.xnm1 = x0
|
||||
self.xn = x1
|
||||
super.init(freq: freq, interpolation: interpolation, mul: mul, add: add)
|
||||
}
|
||||
|
||||
override func iterate() -> Double {
|
||||
let xNew: Double = 1.0 - _a * xn * xn + _b * xnm1
|
||||
xnm1 = xn
|
||||
xn = xNew
|
||||
return xNew
|
||||
}
|
||||
|
||||
/// Snapshot the per-block parameters into the fields `iterate()` reads.
|
||||
@inline(__always)
|
||||
func readParams(graph: SynthGraph) {
|
||||
_a = aInput.floatValue(graph: graph)
|
||||
_b = bInput.floatValue(graph: graph)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio
|
||||
|
||||
/// Audio-rate Hénon oscillator.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - a: Quadratic coefficient. Defaults to `1.4` (canonical chaotic value). No clamping; the orbit diverges for `a ≳ 1.42`.
|
||||
/// - b: Linear feedback coefficient. Defaults to `0.3`. No clamping; bounded near `|b| < 1`, classic value `0.3`.
|
||||
/// - x0: Initial `x[n−1]`. Defaults to `0`.
|
||||
/// - x1: Initial `x[n]`. Defaults to `0`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - a: Quadratic coefficient. Defaults to `1.4`. No clamping; the orbit diverges for `a ≳ 1.42`.
|
||||
/// - b: Linear feedback coefficient. Defaults to `0.3`. No clamping; bounded near `|b| < 1`, classic value `0.3`.
|
||||
/// - x0: Initial `x[n−1]`. Defaults to `0`.
|
||||
/// - x1: Initial `x[n]`. Defaults to `0`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
freq: any ValidGeneratorInput = chaoticDefaultFrequency,
|
||||
a: any ValidGeneratorInput = 1.4,
|
||||
b: any ValidGeneratorInput = 0.3,
|
||||
x0: Double = 0.0,
|
||||
x1: Double = 0.0,
|
||||
interpolation: TableInterpolation = .none,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(freq: freq, a: a, b: b, x0: x0, x1: x1,
|
||||
interpolation: interpolation, mul: mul, add: add)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Control
|
||||
|
||||
/// Control-rate Hénon oscillator. Advances the map by one audio block per call
|
||||
/// and ramps from the previous block value to the new one.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - a: Quadratic coefficient. Defaults to `1.4`. No clamping; the orbit diverges for `a ≳ 1.42`.
|
||||
/// - b: Linear feedback coefficient. Defaults to `0.3`. No clamping; bounded near `|b| < 1`, classic value `0.3`.
|
||||
/// - x0: Initial `x[n−1]`. Defaults to `0`.
|
||||
/// - x1: Initial `x[n]`. Defaults to `0`.
|
||||
/// - 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 func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - a: Quadratic coefficient. Defaults to `1.4`. No clamping; the orbit diverges for `a ≳ 1.42`.
|
||||
/// - b: Linear feedback coefficient. Defaults to `0.3`. No clamping; bounded near `|b| < 1`, classic value `0.3`.
|
||||
/// - x0: Initial `x[n−1]`. Defaults to `0`.
|
||||
/// - x1: Initial `x[n]`. Defaults to `0`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
freq: any ValidGeneratorInput = chaoticDefaultFrequency,
|
||||
a: any ValidGeneratorInput = 1.4,
|
||||
b: any ValidGeneratorInput = 0.3,
|
||||
x0: Double = 0.0,
|
||||
x1: Double = 0.0,
|
||||
interpolation: TableInterpolation = .none,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
extension HenonStepped: GeneratorEnum {
|
||||
public typealias AudioType = HenonStepped.Audio
|
||||
public typealias ControlType = HenonStepped.Control
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
// LatoocarfianStepped.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Latoocarfian-map (Pickover) oscillator (non-interpolated by default).
|
||||
///
|
||||
/// Iterates the Latoocarfian map at `freq` Hz:
|
||||
/// ```
|
||||
/// x[n+1] = sin(b · y[n]) + c · sin(b · x[n])
|
||||
/// y[n+1] = sin(a · x[n]) + d · sin(a · y[n])
|
||||
/// ```
|
||||
/// and outputs `x`. With the canonical `a = 1`, `b = 3`, `c = 0.5`, `d = 0.5` the
|
||||
/// orbit is chaotic and bounded to roughly `[-1.5, 1.5]`. Chaos generally requires
|
||||
/// `|a|, |b|` in about `[0.5, 3]`. Iterations bridge per `interpolation`
|
||||
/// (default `.none`).
|
||||
///
|
||||
/// `freq`, `a`, `b`, `c`, and `d` are read once per block. See ``ChaoticBase`` for
|
||||
/// the iteration / interpolation model.
|
||||
public enum LatoocarfianStepped {
|
||||
|
||||
// MARK: - _Base
|
||||
|
||||
/// Shared Latoocarfian state + parameters for `Audio` and `Control`.
|
||||
public class _Base: ChaoticBase {
|
||||
let aInput: any ValidGeneratorInput
|
||||
let bInput: any ValidGeneratorInput
|
||||
let cInput: any ValidGeneratorInput
|
||||
let dInput: any ValidGeneratorInput
|
||||
|
||||
// Map state.
|
||||
var x: Double
|
||||
var y: Double
|
||||
|
||||
// Per-block parameter snapshot read by `iterate()`.
|
||||
var _a: Double = 0.0
|
||||
var _b: Double = 0.0
|
||||
var _c: Double = 0.0
|
||||
var _d: Double = 0.0
|
||||
|
||||
init(
|
||||
freq: any ValidGeneratorInput,
|
||||
a: any ValidGeneratorInput,
|
||||
b: any ValidGeneratorInput,
|
||||
c: any ValidGeneratorInput,
|
||||
d: any ValidGeneratorInput,
|
||||
xi: Double,
|
||||
yi: Double,
|
||||
interpolation: TableInterpolation,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
self.aInput = a._resolvedInput()
|
||||
self.bInput = b._resolvedInput()
|
||||
self.cInput = c._resolvedInput()
|
||||
self.dInput = d._resolvedInput()
|
||||
self.x = xi
|
||||
self.y = yi
|
||||
super.init(freq: freq, interpolation: interpolation, mul: mul, add: add)
|
||||
}
|
||||
|
||||
override func iterate() -> Double {
|
||||
let xNew: Double = sin(_b * y) + _c * sin(_b * x)
|
||||
let yNew: Double = sin(_a * x) + _d * sin(_a * y)
|
||||
x = xNew
|
||||
y = yNew
|
||||
return xNew
|
||||
}
|
||||
|
||||
/// Snapshot the per-block parameters into the fields `iterate()` reads.
|
||||
@inline(__always)
|
||||
func readParams(graph: SynthGraph) {
|
||||
_a = aInput.floatValue(graph: graph)
|
||||
_b = bInput.floatValue(graph: graph)
|
||||
_c = cInput.floatValue(graph: graph)
|
||||
_d = dInput.floatValue(graph: graph)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio
|
||||
|
||||
/// Audio-rate Latoocarfian oscillator.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - a: First angular factor. Defaults to `1`. Chaos generally needs `|a| ≤ 3`.
|
||||
/// - b: Second angular factor. Defaults to `3`. Chaos generally needs `|b| ≤ 3`.
|
||||
/// - c: `x` self-coupling. Defaults to `0.5`.
|
||||
/// - d: `y` self-coupling. Defaults to `0.5`.
|
||||
/// - xi: Initial `x`. Defaults to `0.5`.
|
||||
/// - yi: Initial `y`. Defaults to `0.5`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - a: First angular factor. Defaults to `1`. Chaos generally needs `|a| ≤ 3`.
|
||||
/// - b: Second angular factor. Defaults to `3`. Chaos generally needs `|b| ≤ 3`.
|
||||
/// - c: `x` self-coupling. Defaults to `0.5`.
|
||||
/// - d: `y` self-coupling. Defaults to `0.5`.
|
||||
/// - xi: Initial `x`. Defaults to `0.5`.
|
||||
/// - yi: Initial `y`. Defaults to `0.5`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
freq: any ValidGeneratorInput = chaoticDefaultFrequency,
|
||||
a: any ValidGeneratorInput = 1.0,
|
||||
b: any ValidGeneratorInput = 3.0,
|
||||
c: any ValidGeneratorInput = 0.5,
|
||||
d: any ValidGeneratorInput = 0.5,
|
||||
xi: Double = 0.5,
|
||||
yi: Double = 0.5,
|
||||
interpolation: TableInterpolation = .none,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(freq: freq, a: a, b: b, c: c, d: d, xi: xi, yi: yi,
|
||||
interpolation: interpolation, mul: mul, add: add)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Control
|
||||
|
||||
/// Control-rate Latoocarfian oscillator. Advances the map by one audio block
|
||||
/// per call and ramps from the previous block value to the new one.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - a: First angular factor. Defaults to `1`. Chaos generally needs `|a| ≤ 3`.
|
||||
/// - b: Second angular factor. Defaults to `3`. Chaos generally needs `|b| ≤ 3`.
|
||||
/// - c: `x` self-coupling. Defaults to `0.5`.
|
||||
/// - d: `y` self-coupling. Defaults to `0.5`.
|
||||
/// - xi: Initial `x`. Defaults to `0.5`.
|
||||
/// - yi: Initial `y`. Defaults to `0.5`.
|
||||
/// - 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 func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - a: First angular factor. Defaults to `1`. Chaos generally needs `|a| ≤ 3`.
|
||||
/// - b: Second angular factor. Defaults to `3`. Chaos generally needs `|b| ≤ 3`.
|
||||
/// - c: `x` self-coupling. Defaults to `0.5`.
|
||||
/// - d: `y` self-coupling. Defaults to `0.5`.
|
||||
/// - xi: Initial `x`. Defaults to `0.5`.
|
||||
/// - yi: Initial `y`. Defaults to `0.5`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
freq: any ValidGeneratorInput = chaoticDefaultFrequency,
|
||||
a: any ValidGeneratorInput = 1.0,
|
||||
b: any ValidGeneratorInput = 3.0,
|
||||
c: any ValidGeneratorInput = 0.5,
|
||||
d: any ValidGeneratorInput = 0.5,
|
||||
xi: Double = 0.5,
|
||||
yi: Double = 0.5,
|
||||
interpolation: TableInterpolation = .none,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
extension LatoocarfianStepped: GeneratorEnum {
|
||||
public typealias AudioType = LatoocarfianStepped.Audio
|
||||
public typealias ControlType = LatoocarfianStepped.Control
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
// LinCongStepped.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Linear-congruential-map oscillator (non-interpolated / stepped by default).
|
||||
///
|
||||
/// Iterates the linear-congruential recurrence at `freq` Hz:
|
||||
/// ```
|
||||
/// x[n+1] = (a · x[n] + c) mod m
|
||||
/// ```
|
||||
/// and outputs `x`, which stays in `[0, m)` by construction. With the canonical
|
||||
/// `a = 1.1`, `c = 0.13`, `m = 1` the orbit fills `[0, 1)` chaotically. Iterations
|
||||
/// bridge per `interpolation` (default `.none` — held / stepped, the aliased SC
|
||||
/// `LinCongN` character).
|
||||
///
|
||||
/// `freq`, `a`, `c`, and `m` are read once per block (no per-sample audio-rate
|
||||
/// modulation). See ``ChaoticBase`` for the iteration / interpolation model.
|
||||
public enum LinCongStepped {
|
||||
|
||||
// MARK: - _Base
|
||||
|
||||
/// Shared LCG state + parameters for `Audio` and `Control`.
|
||||
public class _Base: ChaoticBase {
|
||||
let aInput: any ValidGeneratorInput
|
||||
let cInput: any ValidGeneratorInput
|
||||
let mInput: any ValidGeneratorInput
|
||||
|
||||
// Map state.
|
||||
var x: Double
|
||||
|
||||
// Per-block parameter snapshot read by `iterate()`.
|
||||
var _a: Double = 0.0
|
||||
var _c: Double = 0.0
|
||||
var _m: Double = 1.0
|
||||
|
||||
init(
|
||||
freq: any ValidGeneratorInput,
|
||||
a: any ValidGeneratorInput,
|
||||
c: any ValidGeneratorInput,
|
||||
m: any ValidGeneratorInput,
|
||||
xi: Double,
|
||||
interpolation: TableInterpolation,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
self.aInput = a._resolvedInput()
|
||||
self.cInput = c._resolvedInput()
|
||||
self.mInput = m._resolvedInput()
|
||||
self.x = xi
|
||||
super.init(freq: freq, interpolation: interpolation, mul: mul, add: add)
|
||||
}
|
||||
|
||||
override func iterate() -> Double {
|
||||
let raw: Double = _a * x + _c
|
||||
// Reduce modulo m into [0, m). Guard m <= 0 to avoid a divide-by-zero.
|
||||
let xNew: Double = _m > 0 ? raw - _m * (raw / _m).rounded(.down) : raw
|
||||
x = xNew
|
||||
return xNew
|
||||
}
|
||||
|
||||
/// Snapshot the per-block parameters into the fields `iterate()` reads.
|
||||
@inline(__always)
|
||||
func readParams(graph: SynthGraph) {
|
||||
_a = aInput.floatValue(graph: graph)
|
||||
_c = cInput.floatValue(graph: graph)
|
||||
_m = mInput.floatValue(graph: graph)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio
|
||||
|
||||
/// Audio-rate linear-congruential oscillator.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - a: Multiplier. Defaults to `1.1`.
|
||||
/// - c: Increment. Defaults to `0.13`.
|
||||
/// - m: Modulus; output stays in `[0, m)`. Defaults to `1`. `m <= 0` disables the reduction.
|
||||
/// - xi: Initial `x`. Defaults to `0`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - a: Multiplier. Defaults to `1.1`.
|
||||
/// - c: Increment. Defaults to `0.13`.
|
||||
/// - m: Modulus; output stays in `[0, m)`. Defaults to `1`. `m <= 0` disables the reduction.
|
||||
/// - xi: Initial `x`. Defaults to `0`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
freq: any ValidGeneratorInput = chaoticDefaultFrequency,
|
||||
a: any ValidGeneratorInput = 1.1,
|
||||
c: any ValidGeneratorInput = 0.13,
|
||||
m: any ValidGeneratorInput = 1.0,
|
||||
xi: Double = 0.0,
|
||||
interpolation: TableInterpolation = .none,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(freq: freq, a: a, c: c, m: m, xi: xi,
|
||||
interpolation: interpolation, mul: mul, add: add)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Control
|
||||
|
||||
/// Control-rate linear-congruential oscillator. Advances the map by one audio
|
||||
/// block per call and ramps from the previous block value to the new one.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - a: Multiplier. Defaults to `1.1`.
|
||||
/// - c: Increment. Defaults to `0.13`.
|
||||
/// - m: Modulus; output stays in `[0, m)`. Defaults to `1`. `m <= 0` disables the reduction.
|
||||
/// - xi: Initial `x`. Defaults to `0`.
|
||||
/// - 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 func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - a: Multiplier. Defaults to `1.1`.
|
||||
/// - c: Increment. Defaults to `0.13`.
|
||||
/// - m: Modulus; output stays in `[0, m)`. Defaults to `1`. `m <= 0` disables the reduction.
|
||||
/// - xi: Initial `x`. Defaults to `0`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
freq: any ValidGeneratorInput = chaoticDefaultFrequency,
|
||||
a: any ValidGeneratorInput = 1.1,
|
||||
c: any ValidGeneratorInput = 0.13,
|
||||
m: any ValidGeneratorInput = 1.0,
|
||||
xi: Double = 0.0,
|
||||
interpolation: TableInterpolation = .none,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
extension LinCongStepped: GeneratorEnum {
|
||||
public typealias AudioType = LinCongStepped.Audio
|
||||
public typealias ControlType = LinCongStepped.Control
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
// LorenzLinear.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Lorenz strange-attractor oscillator (linear-interpolated by default).
|
||||
///
|
||||
/// Integrates the Lorenz system by forward Euler at each iteration:
|
||||
/// ```
|
||||
/// x' = x + h · s · (y − x)
|
||||
/// y' = y + h · (x · (r − z) − y)
|
||||
/// z' = z + h · (x · y − b · z)
|
||||
/// ```
|
||||
/// and outputs the `x` coordinate. Iterations advance at `freq` Hz; the audio
|
||||
/// signal bridges successive `x` values per `interpolation` (default `.linear`).
|
||||
///
|
||||
/// Output is the **raw** `x` coordinate — on the canonical attractor `|x|` runs to
|
||||
/// roughly `20`. Scale with `mul` (e.g. `mul: 0.05`) for a `[-1, 1]`-ish signal.
|
||||
///
|
||||
/// `freq`, `s`, `r`, `b`, and `h` are read once per block (no per-sample audio-rate
|
||||
/// modulation). See ``ChaoticBase`` for the iteration / interpolation model.
|
||||
public enum LorenzLinear {
|
||||
|
||||
// MARK: - _Base
|
||||
|
||||
/// Shared Lorenz state + parameters for `Audio` and `Control`.
|
||||
public class _Base: ChaoticBase {
|
||||
let sInput: any ValidGeneratorInput
|
||||
let rInput: any ValidGeneratorInput
|
||||
let bInput: any ValidGeneratorInput
|
||||
let hInput: any ValidGeneratorInput
|
||||
|
||||
// Map state.
|
||||
var x: Double
|
||||
var y: Double
|
||||
var z: Double
|
||||
|
||||
// Per-block parameter snapshot read by `iterate()`.
|
||||
var _s: Double = 0.0
|
||||
var _r: Double = 0.0
|
||||
var _b: Double = 0.0
|
||||
var _h: Double = 0.0
|
||||
|
||||
init(
|
||||
freq: any ValidGeneratorInput,
|
||||
s: any ValidGeneratorInput,
|
||||
r: any ValidGeneratorInput,
|
||||
b: any ValidGeneratorInput,
|
||||
h: any ValidGeneratorInput,
|
||||
xi: Double,
|
||||
yi: Double,
|
||||
zi: Double,
|
||||
interpolation: TableInterpolation,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
self.sInput = s._resolvedInput()
|
||||
self.rInput = r._resolvedInput()
|
||||
self.bInput = b._resolvedInput()
|
||||
self.hInput = h._resolvedInput()
|
||||
self.x = xi
|
||||
self.y = yi
|
||||
self.z = zi
|
||||
super.init(freq: freq, interpolation: interpolation, mul: mul, add: add)
|
||||
}
|
||||
|
||||
override func iterate() -> Double {
|
||||
let x1: Double = x + _h * _s * (y - x)
|
||||
let y1: Double = y + _h * (x * (_r - z) - y)
|
||||
let z1: Double = z + _h * (x * y - _b * z)
|
||||
x = x1
|
||||
y = y1
|
||||
z = z1
|
||||
return x
|
||||
}
|
||||
|
||||
/// Snapshot the per-block parameters into the fields `iterate()` reads.
|
||||
@inline(__always)
|
||||
func readParams(graph: SynthGraph) {
|
||||
_s = sInput.floatValue(graph: graph)
|
||||
_r = rInput.floatValue(graph: graph)
|
||||
_b = bInput.floatValue(graph: graph)
|
||||
_h = hInput.floatValue(graph: graph)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio
|
||||
|
||||
/// Audio-rate Lorenz oscillator.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - s: Prandtl number (σ). Defaults to `10`. No clamping; the canonical chaotic regime is `s ≈ 10`.
|
||||
/// - r: Rayleigh number (ρ). Defaults to `28`. No clamping; chaos onsets near `r ≈ 24.74` — small/large values plus a big `h` can diverge.
|
||||
/// - b: Geometric factor (β). Defaults to `2.667`.
|
||||
/// - h: Euler integration step. Defaults to `0.02`. Above ~0.03 the forward-Euler orbit diverges (SC's nominal `0.05` is unstable here), so keep it small.
|
||||
/// - xi: Initial `x`. Defaults to `0.1`.
|
||||
/// - yi: Initial `y`. Defaults to `0`.
|
||||
/// - zi: Initial `z`. Defaults to `0`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.linear`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - s: Prandtl number (σ). Defaults to `10`. No clamping; the canonical chaotic regime is `s ≈ 10`.
|
||||
/// - r: Rayleigh number (ρ). Defaults to `28`. No clamping; chaos onsets near `r ≈ 24.74` — small/large values plus a big `h` can diverge.
|
||||
/// - b: Geometric factor (β). Defaults to `2.667`.
|
||||
/// - h: Euler integration step. Defaults to `0.02`. Keep below ~0.03 (forward Euler diverges above).
|
||||
/// - xi: Initial `x`. Defaults to `0.1`.
|
||||
/// - yi: Initial `y`. Defaults to `0`.
|
||||
/// - zi: Initial `z`. Defaults to `0`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.linear`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
freq: any ValidGeneratorInput = chaoticDefaultFrequency,
|
||||
s: any ValidGeneratorInput = 10.0,
|
||||
r: any ValidGeneratorInput = 28.0,
|
||||
b: any ValidGeneratorInput = 2.667,
|
||||
h: any ValidGeneratorInput = 0.02,
|
||||
xi: Double = 0.1,
|
||||
yi: Double = 0.0,
|
||||
zi: Double = 0.0,
|
||||
interpolation: TableInterpolation = .linear,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(freq: freq, s: s, r: r, b: b, h: h, xi: xi, yi: yi, zi: zi,
|
||||
interpolation: interpolation, mul: mul, add: add)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Control
|
||||
|
||||
/// Control-rate Lorenz oscillator. Advances the map by one audio block per call
|
||||
/// and ramps from the previous block value to the new one.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - s: Prandtl number (σ). Defaults to `10`. No clamping; the canonical chaotic regime is `s ≈ 10`.
|
||||
/// - r: Rayleigh number (ρ). Defaults to `28`. No clamping; chaos onsets near `r ≈ 24.74` — small/large values plus a big `h` can diverge.
|
||||
/// - b: Geometric factor (β). Defaults to `2.667`.
|
||||
/// - h: Euler integration step. Defaults to `0.02`. Keep below ~0.03 (forward Euler diverges above).
|
||||
/// - xi: Initial `x`. Defaults to `0.1`.
|
||||
/// - yi: Initial `y`. Defaults to `0`.
|
||||
/// - zi: Initial `z`. Defaults to `0`.
|
||||
/// - 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 func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - s: Prandtl number (σ). Defaults to `10`. No clamping; the canonical chaotic regime is `s ≈ 10`.
|
||||
/// - r: Rayleigh number (ρ). Defaults to `28`. No clamping; chaos onsets near `r ≈ 24.74` — small/large values plus a big `h` can diverge.
|
||||
/// - b: Geometric factor (β). Defaults to `2.667`.
|
||||
/// - h: Euler integration step. Defaults to `0.02`. Keep below ~0.03 (forward Euler diverges above).
|
||||
/// - xi: Initial `x`. Defaults to `0.1`.
|
||||
/// - yi: Initial `y`. Defaults to `0`.
|
||||
/// - zi: Initial `z`. Defaults to `0`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.linear`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
freq: any ValidGeneratorInput = chaoticDefaultFrequency,
|
||||
s: any ValidGeneratorInput = 10.0,
|
||||
r: any ValidGeneratorInput = 28.0,
|
||||
b: any ValidGeneratorInput = 2.667,
|
||||
h: any ValidGeneratorInput = 0.02,
|
||||
xi: Double = 0.1,
|
||||
yi: Double = 0.0,
|
||||
zi: Double = 0.0,
|
||||
interpolation: TableInterpolation = .linear,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
extension LorenzLinear: GeneratorEnum {
|
||||
public typealias AudioType = LorenzLinear.Audio
|
||||
public typealias ControlType = LorenzLinear.Control
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
// QuadStepped.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// General quadratic-map oscillator (non-interpolated / stepped by default).
|
||||
///
|
||||
/// Iterates the quadratic recurrence at `freq` Hz:
|
||||
/// ```
|
||||
/// x[n+1] = a · x[n]² + b · x[n] + c
|
||||
/// ```
|
||||
/// and outputs `x`. With the canonical `a = 1`, `b = −1`, `c = −0.75` the orbit is
|
||||
/// chaotic and bounded to roughly `[-1.25, 1.25]` (this family is conjugate to the
|
||||
/// logistic map). Iterations bridge per `interpolation` (default `.none` — held /
|
||||
/// stepped, the aliased SC `QuadN` character).
|
||||
///
|
||||
/// `freq`, `a`, `b`, and `c` are read once per block (no per-sample audio-rate
|
||||
/// modulation). See ``ChaoticBase`` for the iteration / interpolation model.
|
||||
public enum QuadStepped {
|
||||
|
||||
// MARK: - _Base
|
||||
|
||||
/// Shared quadratic-map state + parameters for `Audio` and `Control`.
|
||||
public class _Base: ChaoticBase {
|
||||
let aInput: any ValidGeneratorInput
|
||||
let bInput: any ValidGeneratorInput
|
||||
let cInput: any ValidGeneratorInput
|
||||
|
||||
// Map state.
|
||||
var x: Double
|
||||
|
||||
// Per-block parameter snapshot read by `iterate()`.
|
||||
var _a: Double = 0.0
|
||||
var _b: Double = 0.0
|
||||
var _c: Double = 0.0
|
||||
|
||||
init(
|
||||
freq: any ValidGeneratorInput,
|
||||
a: any ValidGeneratorInput,
|
||||
b: any ValidGeneratorInput,
|
||||
c: any ValidGeneratorInput,
|
||||
xi: Double,
|
||||
interpolation: TableInterpolation,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
self.aInput = a._resolvedInput()
|
||||
self.bInput = b._resolvedInput()
|
||||
self.cInput = c._resolvedInput()
|
||||
self.x = xi
|
||||
super.init(freq: freq, interpolation: interpolation, mul: mul, add: add)
|
||||
}
|
||||
|
||||
override func iterate() -> Double {
|
||||
let xNew: Double = _a * x * x + _b * x + _c
|
||||
x = xNew
|
||||
return xNew
|
||||
}
|
||||
|
||||
/// Snapshot the per-block parameters into the fields `iterate()` reads.
|
||||
@inline(__always)
|
||||
func readParams(graph: SynthGraph) {
|
||||
_a = aInput.floatValue(graph: graph)
|
||||
_b = bInput.floatValue(graph: graph)
|
||||
_c = cInput.floatValue(graph: graph)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio
|
||||
|
||||
/// Audio-rate quadratic-map oscillator.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - a: Quadratic coefficient. Defaults to `1`. No clamping; some `(a,b,c)` triples diverge.
|
||||
/// - b: Linear coefficient. Defaults to `-1`.
|
||||
/// - c: Constant term. Defaults to `-0.75`.
|
||||
/// - xi: Initial `x`. Defaults to `0`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - a: Quadratic coefficient. Defaults to `1`. No clamping; some `(a,b,c)` triples diverge.
|
||||
/// - b: Linear coefficient. Defaults to `-1`.
|
||||
/// - c: Constant term. Defaults to `-0.75`.
|
||||
/// - xi: Initial `x`. Defaults to `0`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
freq: any ValidGeneratorInput = chaoticDefaultFrequency,
|
||||
a: any ValidGeneratorInput = 1.0,
|
||||
b: any ValidGeneratorInput = -1.0,
|
||||
c: any ValidGeneratorInput = -0.75,
|
||||
xi: Double = 0.0,
|
||||
interpolation: TableInterpolation = .none,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(freq: freq, a: a, b: b, c: c, xi: xi,
|
||||
interpolation: interpolation, mul: mul, add: add)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Control
|
||||
|
||||
/// Control-rate quadratic-map oscillator. Advances the map by one audio block
|
||||
/// per call and ramps from the previous block value to the new one.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - a: Quadratic coefficient. Defaults to `1`. No clamping; some `(a,b,c)` triples diverge.
|
||||
/// - b: Linear coefficient. Defaults to `-1`.
|
||||
/// - c: Constant term. Defaults to `-0.75`.
|
||||
/// - xi: Initial `x`. Defaults to `0`.
|
||||
/// - 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 func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - a: Quadratic coefficient. Defaults to `1`. No clamping; some `(a,b,c)` triples diverge.
|
||||
/// - b: Linear coefficient. Defaults to `-1`.
|
||||
/// - c: Constant term. Defaults to `-0.75`.
|
||||
/// - xi: Initial `x`. Defaults to `0`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
freq: any ValidGeneratorInput = chaoticDefaultFrequency,
|
||||
a: any ValidGeneratorInput = 1.0,
|
||||
b: any ValidGeneratorInput = -1.0,
|
||||
c: any ValidGeneratorInput = -0.75,
|
||||
xi: Double = 0.0,
|
||||
interpolation: TableInterpolation = .none,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
extension QuadStepped: GeneratorEnum {
|
||||
public typealias AudioType = QuadStepped.Audio
|
||||
public typealias ControlType = QuadStepped.Control
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
// StandardStepped.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Standard-map (Chirikov kicked-rotor) oscillator (non-interpolated by default).
|
||||
///
|
||||
/// Iterates the standard map at `freq` Hz, both variables wrapped into `[0, 2π)`:
|
||||
/// ```
|
||||
/// y[n+1] = (y[n] + k · sin(x[n])) mod 2π
|
||||
/// x[n+1] = (x[n] + y[n+1]) mod 2π
|
||||
/// ```
|
||||
/// and outputs `x` (range `[0, 2π)` — scale with `mul`, e.g. `mul: 1/π, add: -1`
|
||||
/// for `[-1, 1)`). Larger `k` → stronger chaos. Iterations bridge per
|
||||
/// `interpolation` (default `.none`).
|
||||
///
|
||||
/// `freq` and `k` are read once per block. See ``ChaoticBase`` for the iteration /
|
||||
/// interpolation model.
|
||||
public enum StandardStepped {
|
||||
|
||||
// MARK: - _Base
|
||||
|
||||
/// Shared standard-map state + parameter for `Audio` and `Control`.
|
||||
public class _Base: ChaoticBase {
|
||||
let kInput: any ValidGeneratorInput
|
||||
|
||||
// Map state (angles in [0, 2π)).
|
||||
var x: Double
|
||||
var y: Double
|
||||
|
||||
// Per-block parameter snapshot read by `iterate()`.
|
||||
var _k: Double = 0.0
|
||||
|
||||
init(
|
||||
freq: any ValidGeneratorInput,
|
||||
k: any ValidGeneratorInput,
|
||||
xi: Double,
|
||||
yi: Double,
|
||||
interpolation: TableInterpolation,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
self.kInput = k._resolvedInput()
|
||||
self.x = xi
|
||||
self.y = yi
|
||||
super.init(freq: freq, interpolation: interpolation, mul: mul, add: add)
|
||||
}
|
||||
|
||||
override func iterate() -> Double {
|
||||
y = chaoticWrapTwoPi(y + _k * sin(x))
|
||||
x = chaoticWrapTwoPi(x + y)
|
||||
return x
|
||||
}
|
||||
|
||||
/// Snapshot the per-block parameter into the field `iterate()` reads.
|
||||
@inline(__always)
|
||||
func readParams(graph: SynthGraph) {
|
||||
_k = kInput.floatValue(graph: graph)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio
|
||||
|
||||
/// Audio-rate standard-map oscillator.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - k: Kick strength. Defaults to `1`. Larger → stronger chaos. No clamping.
|
||||
/// - xi: Initial `x` (angle). Defaults to `0.5`.
|
||||
/// - yi: Initial `y` (momentum). Defaults to `0`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - k: Kick strength. Defaults to `1`. Larger → stronger chaos. No clamping.
|
||||
/// - xi: Initial `x` (angle). Defaults to `0.5`.
|
||||
/// - yi: Initial `y` (momentum). Defaults to `0`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
freq: any ValidGeneratorInput = chaoticDefaultFrequency,
|
||||
k: any ValidGeneratorInput = 1.0,
|
||||
xi: Double = 0.5,
|
||||
yi: Double = 0.0,
|
||||
interpolation: TableInterpolation = .none,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(freq: freq, k: k, xi: xi, yi: yi,
|
||||
interpolation: interpolation, mul: mul, add: add)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Control
|
||||
|
||||
/// Control-rate standard-map oscillator. Advances the map by one audio block
|
||||
/// per call and ramps from the previous block value to the new one.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - k: Kick strength. Defaults to `1`. Larger → stronger chaos. No clamping.
|
||||
/// - xi: Initial `x` (angle). Defaults to `0.5`.
|
||||
/// - yi: Initial `y` (momentum). Defaults to `0`.
|
||||
/// - 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 func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
|
||||
/// - Parameters:
|
||||
/// - freq: Iteration frequency in Hz. Read per block. Defaults to `22050`.
|
||||
/// - k: Kick strength. Defaults to `1`. Larger → stronger chaos. No clamping.
|
||||
/// - xi: Initial `x` (angle). Defaults to `0.5`.
|
||||
/// - yi: Initial `y` (momentum). Defaults to `0`.
|
||||
/// - interpolation: Bridging between iterations. Defaults to `.none`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
freq: any ValidGeneratorInput = chaoticDefaultFrequency,
|
||||
k: any ValidGeneratorInput = 1.0,
|
||||
xi: Double = 0.5,
|
||||
yi: Double = 0.0,
|
||||
interpolation: TableInterpolation = .none,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
extension StandardStepped: GeneratorEnum {
|
||||
public typealias AudioType = StandardStepped.Audio
|
||||
public typealias ControlType = StandardStepped.Control
|
||||
}
|
||||
@@ -72,7 +72,7 @@ public final class DelayLine: GeneratorBase, AudioGenerator {
|
||||
self.delayIsGenerator = resolvedDelay is any Generator
|
||||
|
||||
let maxSamples: Int = Int(ceil(maxDelay * sampleRate)) + 1
|
||||
let bufSize: Int = Self.nextPowerOf2(max(maxSamples, 2))
|
||||
let bufSize: Int = lyrebirdNextPowerOfTwo(max(maxSamples, 2))
|
||||
self.buffer = [Double](repeating: 0, count: bufSize)
|
||||
self.bufferMask = bufSize - 1
|
||||
self.maxDelaySamples = maxSamples - 1
|
||||
@@ -199,33 +199,16 @@ public final class DelayLine: GeneratorBase, AudioGenerator {
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
/// Catmull-Rom cubic interpolation — static so the per-sample inner loop can call it
|
||||
/// without a method-dispatch frame on `self`.
|
||||
/// Catmull-Rom cubic interpolation (delegates to the shared `catmullRomCubic`)
|
||||
/// — static so the per-sample inner loop can call it without a method-dispatch
|
||||
/// frame on `self`.
|
||||
@inline(__always)
|
||||
fileprivate static func cubicInterpStatic(
|
||||
frac: Double,
|
||||
y0: Double, y1: Double,
|
||||
y2: Double, y3: Double
|
||||
) -> Double {
|
||||
// Catmull-Rom polynomial coefficients:
|
||||
// p(t) = ((-0.5y0 + 1.5y1 - 1.5y2 + 0.5y3)t³ + (y0 - 2.5y1 + 2y2 - 0.5y3)t²
|
||||
// + (-0.5y0 + 0.5y2)t + y1)
|
||||
let catmullHalf: Double = 0.5
|
||||
let catmullA3coeff: Double = 1.5
|
||||
let catmullB2coeff: Double = 2.5
|
||||
let catmullC2coeff: Double = 2.0
|
||||
let a: Double = -catmullHalf * y0 + catmullA3coeff * y1 - catmullA3coeff * y2 + catmullHalf * y3
|
||||
let b: Double = y0 - catmullB2coeff * y1 + catmullC2coeff * y2 - catmullHalf * y3
|
||||
let c: Double = -catmullHalf * y0 + catmullHalf * y2
|
||||
let d: Double = y1
|
||||
return ((a * frac + b) * frac + c) * frac + d
|
||||
}
|
||||
|
||||
private static func nextPowerOf2(_ n: Int) -> Int {
|
||||
guard n > 1 else { return 1 }
|
||||
var result: Int = 1
|
||||
while result < n { result <<= 1 }
|
||||
return result
|
||||
catmullRomCubic(y0, y1, y2, y3, t: frac)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -129,7 +129,7 @@ public final class DelayLineFeedback: GeneratorBase, AudioGenerator {
|
||||
self.targetAmpIsGenerator = resolvedTargetAmp is any Generator
|
||||
|
||||
let maxSamples: Int = Int(ceil(maxDelay * sampleRate)) + 1
|
||||
let bufSize: Int = Self.nextPowerOf2(max(maxSamples, 2))
|
||||
let bufSize: Int = lyrebirdNextPowerOfTwo(max(maxSamples, 2))
|
||||
self.buffer = [Double](repeating: 0, count: bufSize)
|
||||
self.bufferMask = bufSize - 1
|
||||
self.maxDelaySamples = maxSamples - 1
|
||||
@@ -300,31 +300,16 @@ public final class DelayLineFeedback: GeneratorBase, AudioGenerator {
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
/// Catmull-Rom cubic interpolation — static so the per-sample inner loop can call it
|
||||
/// without a method-dispatch frame on `self`.
|
||||
/// Catmull-Rom cubic interpolation (delegates to the shared `catmullRomCubic`)
|
||||
/// — static so the per-sample inner loop can call it without a method-dispatch
|
||||
/// frame on `self`.
|
||||
@inline(__always)
|
||||
fileprivate static func cubicInterpStatic(
|
||||
frac: Double,
|
||||
y0: Double, y1: Double,
|
||||
y2: Double, y3: Double
|
||||
) -> Double {
|
||||
// Catmull-Rom polynomial coefficients.
|
||||
let catmullHalf: Double = 0.5
|
||||
let catmullA3coeff: Double = 1.5
|
||||
let catmullB2coeff: Double = 2.5
|
||||
let catmullC2coeff: Double = 2.0
|
||||
let a: Double = -catmullHalf * y0 + catmullA3coeff * y1 - catmullA3coeff * y2 + catmullHalf * y3
|
||||
let b: Double = y0 - catmullB2coeff * y1 + catmullC2coeff * y2 - catmullHalf * y3
|
||||
let c: Double = -catmullHalf * y0 + catmullHalf * y2
|
||||
let d: Double = y1
|
||||
return ((a * frac + b) * frac + c) * frac + d
|
||||
}
|
||||
|
||||
private static func nextPowerOf2(_ n: Int) -> Int {
|
||||
guard n > 1 else { return 1 }
|
||||
var result: Int = 1
|
||||
while result < n { result <<= 1 }
|
||||
return result
|
||||
catmullRomCubic(y0, y1, y2, y3, t: frac)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
// Balance.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
|
||||
/// Smallest positive `hp` cutoff allowed. Below this the one-pole integrator coefficient
|
||||
/// would round to `1.0` (comp → 0), freezing the mean-square estimate. Clamps `hp` here.
|
||||
private let balanceMinHp: Double = 1.0e-3
|
||||
|
||||
/// Epsilon added to the input mean-square before the linear-domain divide, guarding
|
||||
/// `sqrt(ms_test / 0)` when `in` is silent. Small enough not to perturb the gain for any
|
||||
/// audible level.
|
||||
private let balanceTinyDenominator: Double = 1.0e-10
|
||||
|
||||
/// Power floor added to each mean-square before the log in `logDomain` mode, so `log10` never
|
||||
/// sees zero on silence and the log-ratio stays finite.
|
||||
private let balancePowerFloor: Double = 1.0e-20
|
||||
|
||||
/// `0.5 · ln(10)`. Converts a base-10 *power*-ratio log into a linear *amplitude* gain:
|
||||
/// `gain = exp(L · halfLn10)` is `10^(L/2) = (powerRatio)^(1/2)`.
|
||||
private let balanceHalfLn10: Double = 0.5 * log(10.0)
|
||||
|
||||
/// RMS level matcher. Scales `in` so its running RMS tracks the running RMS of a reference
|
||||
/// signal `test`. The canonical use is bringing a filtered signal back up to the level of the
|
||||
/// unfiltered source (SC sc3-plugins `Balance`, JoshUGens).
|
||||
///
|
||||
/// ## Algorithm
|
||||
/// The running mean-square of each signal is tracked with a one-pole lowpass on the squared
|
||||
/// samples, then the input is scaled by the square-root of their ratio:
|
||||
/// ```
|
||||
/// b1 = exp(-2π · hp / sr) // integrator pole from the hp cutoff (Hz)
|
||||
/// comp = 1 − b1
|
||||
/// msIn = b1·msIn + comp·in²
|
||||
/// msTest = b1·msTest + comp·test²
|
||||
/// rawGain = sqrt(msTest / (msIn + tiny))
|
||||
/// gain = lag(rawGain, smooth) // optional decoupled gain lag (see `smooth`)
|
||||
/// out = in · gain
|
||||
/// ```
|
||||
/// Because the gain is a *ratio* of two identically-normalised mean-squares, the `comp`
|
||||
/// normalisation cancels — only the `hp` window length affects the result. This matches SC's
|
||||
/// unnormalised running-sum form (`y = x² + b1·y`) while staying bounded and denormal-safe.
|
||||
///
|
||||
/// ## `hp` vs `smooth` — two decoupled time constants
|
||||
/// A single one-pole on `x²` ripples at twice the signal frequency, so a high `hp` (fast
|
||||
/// detection) lets that ripple modulate the gain — audible amplitude-modulation sidebands,
|
||||
/// worst on low-frequency material. `smooth` adds a **second** one-pole on the computed gain,
|
||||
/// letting you choose detection responsiveness (`hp`) and gain-change rate (`smooth`)
|
||||
/// independently: raise `hp` to track level changes quickly, then raise `smooth` to suppress
|
||||
/// the resulting ripple. `smooth == 0` (default) bypasses the lag, reproducing the classic
|
||||
/// single-pole behaviour exactly.
|
||||
///
|
||||
/// ## `logDomain` — linear vs decibel gain glide
|
||||
/// `logDomain == false` (default) smooths the **linear** gain. `logDomain == true` smooths the
|
||||
/// level difference in the **decibel (log) domain** instead — it lags `log10(ms_test / ms_in)`
|
||||
/// and exps back, so a `+6 dB` correction and a `−6 dB` correction glide with the same shape
|
||||
/// and time (symmetric, perceptually even — the way an analogue auto-leveller behaves), versus
|
||||
/// the linear lag which is faster on boosts than on cuts. Both modes converge to the same
|
||||
/// steady-state level. The log path costs one extra `log10` + `exp` per sample and floors the
|
||||
/// power before the log so silence yields a finite gain (`0 · gain = 0`, never `NaN`).
|
||||
///
|
||||
/// ## Edge behaviour
|
||||
/// - Silent `in` stays silent: `out = 0 · gain = 0` (a zero signal has no RMS to raise).
|
||||
/// - Silent `test` drives `in` toward zero: `msTest → 0`, so the gain collapses.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
/// let filtered = RBJLowPass.Audio(input: source, freq: 800.0, q: 0.707)
|
||||
/// let matched = Balance(in: filtered, test: source) // classic
|
||||
/// let matched = Balance(in: filtered, test: source, hp: 40.0, smooth: 0.05) // fast + de-rippled
|
||||
/// let matched = Balance(in: filtered, test: source, smooth: 0.1, logDomain: true) // dB glide
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal whose level is adjusted (scaled to match `test`).
|
||||
/// - test: Reference signal whose running RMS sets the target level.
|
||||
/// - hp: Integration cutoff in Hz. Sets the mean-square window length. Clamped to
|
||||
/// `≥ 0.001`. Snapshotted once per audio block. Default `10.0`.
|
||||
/// - smooth: Gain-lag time in seconds. A second one-pole applied to the gain, decoupled from
|
||||
/// `hp`. `0` bypasses it (classic behaviour). Default `0.0`.
|
||||
/// - logDomain: When `true`, smooth the gain in the decibel (log) domain for a symmetric,
|
||||
/// perceptually even glide. Default `false` (linear-gain smoothing).
|
||||
/// - mul: Output multiplier. Default `1.0`.
|
||||
/// - add: Output offset. Default `0.0`.
|
||||
public final class Balance: GeneratorBase, AudioGenerator {
|
||||
|
||||
// MARK: - Inputs
|
||||
|
||||
private let _input: any ValidGeneratorInput
|
||||
private let _testInput: any ValidGeneratorInput
|
||||
private let _hpInput: any ValidGeneratorInput
|
||||
private let _hpIsGenerator: Bool
|
||||
private let _smooth: Double
|
||||
private let _logDomain: Bool
|
||||
private let _mulAdd: MulAddSpec
|
||||
|
||||
// MARK: - State (running mean-square estimates + lagged gain)
|
||||
|
||||
private var _msIn: Double = 0.0
|
||||
private var _msTest: Double = 0.0
|
||||
/// Linear-domain lagged gain. Used when `logDomain == false`. Neutral start `1.0`.
|
||||
private var _gain: Double = 1.0
|
||||
/// Log-domain smoothed level difference (`log10` power ratio). Used when
|
||||
/// `logDomain == true`. Neutral start `0.0` (`exp(0) = 1` → unity gain).
|
||||
private var _logState: Double = 0.0
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal whose level is adjusted (scaled to match `test`).
|
||||
/// - test: Reference signal whose running RMS sets the target level.
|
||||
/// - hp: Integration cutoff in Hz. Sets the mean-square window length. Clamped to
|
||||
/// `≥ 0.001`. Snapshotted once per audio block. Default `10.0`.
|
||||
/// - smooth: Gain-lag time in seconds. A second one-pole applied to the gain, decoupled
|
||||
/// from `hp`. `0` bypasses it (classic behaviour). Default `0.0`.
|
||||
/// - logDomain: When `true`, smooth the gain in the decibel (log) domain for a symmetric,
|
||||
/// perceptually even glide. Default `false` (linear-gain smoothing).
|
||||
/// - mul: Output multiplier. Default `1.0`.
|
||||
/// - add: Output offset. Default `0.0`.
|
||||
public init(
|
||||
in input: any ValidGeneratorInput,
|
||||
test: any ValidGeneratorInput,
|
||||
hp: any ValidGeneratorInput = 10.0,
|
||||
smooth: Double = 0.0,
|
||||
logDomain: Bool = false,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
precondition(smooth >= 0, "Balance: smooth must be ≥ 0")
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedTest: any ValidGeneratorInput = test._resolvedInput()
|
||||
let resolvedHp: any ValidGeneratorInput = hp._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_testInput = resolvedTest
|
||||
_hpInput = resolvedHp
|
||||
_hpIsGenerator = resolvedHp is any Generator
|
||||
_smooth = smooth
|
||||
_logDomain = logDomain
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let inSamples: [Double] = _input.calculatedSamples(graph: graph, count: count).first ?? []
|
||||
let testSamples: [Double] = _testInput.calculatedSamples(graph: graph, count: count).first ?? []
|
||||
let hp: Double = max(balanceMinHp,
|
||||
lastGeneratorSampleOrFloat(_hpInput, isGenerator: _hpIsGenerator,
|
||||
graph: graph, count: count))
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
|
||||
// One-pole integrator pole + complement from the hp cutoff. Recomputed once per block.
|
||||
let b1: Double = exp(-lyrebirdTwoPi * hp / sr)
|
||||
let comp: Double = 1.0 - b1
|
||||
|
||||
// Decoupled gain-lag coefficients (shared by both domains). `smooth == 0` → lagB1 0,
|
||||
// lagComp 1 → pass-through (instant gain, classic behaviour).
|
||||
let lagB1: Double = _smooth > 0 ? exp(-1.0 / (_smooth * sr)) : 0.0
|
||||
let lagComp: Double = 1.0 - lagB1
|
||||
|
||||
var msIn: Double = _msIn
|
||||
var msTest: Double = _msTest
|
||||
let nIn: Int = inSamples.count
|
||||
let nTest: Int = testSamples.count
|
||||
|
||||
// Branch on the domain once (not per sample). Index form (not raw pointers) so an empty
|
||||
// `in`/`test` block — either input may independently return zero rows — pads with zeros
|
||||
// instead of leaving `_result` stale.
|
||||
if _logDomain {
|
||||
var logState: Double = _logState
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = i < nIn ? inSamples[i] : 0.0
|
||||
let t: Double = i < nTest ? testSamples[i] : 0.0
|
||||
_ = onePoleLowPassStep(state: &msIn, x: x * x, b1: b1, comp: comp)
|
||||
_ = onePoleLowPassStep(state: &msTest, x: t * t, b1: b1, comp: comp)
|
||||
// Level difference in the log (dB) domain, smoothed before exp-ing back.
|
||||
let logRatio: Double = log10((msTest + balancePowerFloor) / (msIn + balancePowerFloor))
|
||||
_ = onePoleLowPassStep(state: &logState, x: logRatio, b1: lagB1, comp: lagComp)
|
||||
_result[0][i] = x * exp(logState * balanceHalfLn10)
|
||||
}
|
||||
_logState = denormalsToZero(logState)
|
||||
} else {
|
||||
var gain: Double = _gain
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = i < nIn ? inSamples[i] : 0.0
|
||||
let t: Double = i < nTest ? testSamples[i] : 0.0
|
||||
_ = onePoleLowPassStep(state: &msIn, x: x * x, b1: b1, comp: comp)
|
||||
_ = onePoleLowPassStep(state: &msTest, x: t * t, b1: b1, comp: comp)
|
||||
let rawGain: Double = (msTest / (msIn + balanceTinyDenominator)).squareRoot()
|
||||
_ = onePoleLowPassStep(state: &gain, x: rawGain, b1: lagB1, comp: lagComp)
|
||||
_result[0][i] = x * gain
|
||||
}
|
||||
_gain = denormalsToZero(gain)
|
||||
}
|
||||
|
||||
_msIn = denormalsToZero(msIn)
|
||||
_msTest = denormalsToZero(msTest)
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
// `GeneratorEnum` conformance is intentionally omitted — this is an Audio-only generator
|
||||
// with no paired `Control` variant.
|
||||
@@ -10,7 +10,9 @@ import Darwin
|
||||
///
|
||||
/// Accumulates samples into a ring buffer and re-evaluates every `hopSize` samples.
|
||||
/// Between hops the output holds the previous result — frequency stabilises after
|
||||
/// one or two hops (~46 ms at the default settings and 44100 Hz sample rate).
|
||||
/// one or two hops (~46 ms at the default settings, `decimation: 1`, and 44100 Hz sample
|
||||
/// rate). Settle time scales with `decimation` (each hop spans `decimation×` more
|
||||
/// wall-clock time), so `decimation: 4` stabilises in ~184 ms.
|
||||
///
|
||||
/// ## Output
|
||||
/// Returns a two-channel buffer:
|
||||
@@ -19,10 +21,13 @@ import Darwin
|
||||
///
|
||||
/// ## Parameters
|
||||
/// - `in`: signal to analyse (Audio-rate input evaluated per sample)
|
||||
/// - `fftSize`: analysis window in samples (must be power of 2, set at init)
|
||||
/// - `hopSize`: samples between re-analyses (set at init; default `fftSize / 2`)
|
||||
/// - `fftSize`: analysis window in **decimated** samples (must be power of 2, set at init)
|
||||
/// - `hopSize`: decimated samples between re-analyses (set at init; default `fftSize / 2`)
|
||||
/// - `minFreq`: lower search bound in Hz (default 60.0)
|
||||
/// - `maxFreq`: upper search bound in Hz (default 3000.0)
|
||||
/// - `decimation`: keep only every Nth input sample before analysis (default `1`), lowering
|
||||
/// the effective rate to `sampleRate / decimation` to reach lower fundamentals. Caller must
|
||||
/// band-limit below the decimated Nyquist first. See the `init` doc for full detail.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
@@ -62,6 +67,7 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
|
||||
private let _hopSize: Int
|
||||
private let _minFreq: Double
|
||||
private let _maxFreq: Double
|
||||
private let _decimation: Int
|
||||
|
||||
// MARK: - Input
|
||||
|
||||
@@ -82,6 +88,11 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
|
||||
private var _lastFreq: Double = 0.0
|
||||
private var _lastConfidence: Double = 0.0
|
||||
|
||||
// Counts raw input samples toward the next decimated (stored) sample. Only every
|
||||
// `_decimation`-th input sample is written into the ring; the ring/hop machinery then
|
||||
// operates entirely in the decimated time base.
|
||||
private var _decimationCounter: Int = 0
|
||||
|
||||
// MARK: - Output
|
||||
|
||||
// MARK: - Fan-out cache
|
||||
@@ -89,18 +100,32 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track.
|
||||
/// - fftSize: Analysis window in samples. Power of 2 in [64, 512]. Default 512.
|
||||
/// Larger values increase latency and YIN cost (O(halfSize²) per hop);
|
||||
/// 512 gives ~5.8 ms at 44100 Hz and is the maximum RT-safe value.
|
||||
/// - hopSize: Samples between analysis updates. Default `fftSize / 2`.
|
||||
/// - fftSize: Analysis window in **decimated** samples. Power of 2 in [64, 512].
|
||||
/// Default 512. Larger values increase latency and YIN cost (O(halfSize²)
|
||||
/// per hop); 512 gives ~5.8 ms at 44100 Hz and is the maximum RT-safe value.
|
||||
/// - hopSize: Decimated samples between analysis updates. Default `fftSize / 2`.
|
||||
/// - minFreq: Minimum tracked frequency in Hz. Default 60.0.
|
||||
/// - maxFreq: Maximum tracked frequency in Hz. Default 3000.0.
|
||||
/// - decimation: Keep only every `decimation`-th input sample before analysis, lowering
|
||||
/// the effective sample rate to `sampleRate / decimation`. Default `1` (no
|
||||
/// decimation — original behaviour). A 512-sample window can then span
|
||||
/// `decimation ×` more time, extending the **minimum** detectable frequency
|
||||
/// down to roughly `sampleRate / (decimation × (fftSize/2 − 1))` while keeping
|
||||
/// YIN's O(halfSize²) cost fixed — ideal for low-pitched monophonic sources
|
||||
/// (bass, low guitar strings) where high-frequency resolution isn't needed.
|
||||
/// **The caller must band-limit the input below the decimated Nyquist
|
||||
/// (`sampleRate / (2 × decimation)`) first** — decimation does no anti-alias
|
||||
/// filtering of its own. The `maxFreq` search bound must also stay below that
|
||||
/// decimated Nyquist. Latency to a stable reading scales with `decimation`
|
||||
/// (each hop spans `decimation×` more wall-clock time), so `decimation: 4`
|
||||
/// settles in ~4× the undecimated hop-based time.
|
||||
public init(
|
||||
in input: any ValidGeneratorInput,
|
||||
fftSize: Int = 512,
|
||||
hopSize: Int? = nil,
|
||||
minFreq: Double = 60.0,
|
||||
maxFreq: Double = 3000.0
|
||||
maxFreq: Double = 3000.0,
|
||||
decimation: Int = 1
|
||||
) {
|
||||
precondition(fftSize >= 64 && fftSize <= 512 && (fftSize & (fftSize - 1)) == 0,
|
||||
"FreqTracker: fftSize must be a power of 2 in [64, 512]; got \(fftSize). "
|
||||
@@ -108,6 +133,8 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
|
||||
+ "Reduce fftSize or implement background-thread YIN in a future phase.")
|
||||
precondition(minFreq > 0 && maxFreq > minFreq,
|
||||
"FreqTracker: minFreq must be > 0 and < maxFreq")
|
||||
precondition(decimation >= 1,
|
||||
"FreqTracker: decimation must be >= 1; got \(decimation).")
|
||||
|
||||
_fftSize = fftSize
|
||||
_hopSize = hopSize ?? fftSize / 2
|
||||
@@ -119,6 +146,7 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
|
||||
+ "Larger values cause the YIN window to read stale data.")
|
||||
_minFreq = minFreq
|
||||
_maxFreq = maxFreq
|
||||
_decimation = decimation
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_inputRing = [Double](repeating: 0.0, count: fftSize)
|
||||
@@ -135,16 +163,23 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
|
||||
_checkCount(count)
|
||||
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
// Analysis runs in the decimated time base: the ring holds every `_decimation`-th
|
||||
// input sample, so lag→frequency conversion uses the decimated effective rate.
|
||||
let effectiveRate: Double = sr / Double(_decimation)
|
||||
let inputSamples: [[Double]] = _input.calculatedSamples(graph: graph, count: count)
|
||||
guard let ins: [Double] = inputSamples.first else {
|
||||
// No input — advance ring with zeros, still fire hops so state advances correctly.
|
||||
for _ in 0..<count {
|
||||
_inputRing[_ringPos % _fftSize] = 0.0
|
||||
_ringPos &+= 1
|
||||
_samplesUntilHop -= 1
|
||||
if _samplesUntilHop <= 0 {
|
||||
_samplesUntilHop = _hopSize
|
||||
_runYIN(sampleRate: sr)
|
||||
_decimationCounter &+= 1
|
||||
if _decimationCounter >= _decimation {
|
||||
_decimationCounter = 0
|
||||
_inputRing[_ringPos % _fftSize] = 0.0
|
||||
_ringPos &+= 1
|
||||
_samplesUntilHop -= 1
|
||||
if _samplesUntilHop <= 0 {
|
||||
_samplesUntilHop = _hopSize
|
||||
_runYIN(sampleRate: effectiveRate)
|
||||
}
|
||||
}
|
||||
}
|
||||
for i: Int in 0..<count {
|
||||
@@ -155,15 +190,21 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
|
||||
}
|
||||
|
||||
for i: Int in 0..<count {
|
||||
// Write incoming sample into ring buffer.
|
||||
let sample: Double = Double(ins[i])
|
||||
_inputRing[_ringPos % _fftSize] = sample
|
||||
_ringPos &+= 1
|
||||
// Write every `_decimation`-th incoming sample into the ring buffer. Naive
|
||||
// decimation (take-every-Nth) is correct because the caller band-limits below
|
||||
// the decimated Nyquist — see the `decimation` parameter docs.
|
||||
_decimationCounter &+= 1
|
||||
if _decimationCounter >= _decimation {
|
||||
_decimationCounter = 0
|
||||
let sample: Double = Double(ins[i])
|
||||
_inputRing[_ringPos % _fftSize] = sample
|
||||
_ringPos &+= 1
|
||||
|
||||
_samplesUntilHop -= 1
|
||||
if _samplesUntilHop <= 0 {
|
||||
_samplesUntilHop = _hopSize
|
||||
_runYIN(sampleRate: sr)
|
||||
_samplesUntilHop -= 1
|
||||
if _samplesUntilHop <= 0 {
|
||||
_samplesUntilHop = _hopSize
|
||||
_runYIN(sampleRate: effectiveRate)
|
||||
}
|
||||
}
|
||||
_result[0][i] = _lastFreq
|
||||
_result[1][i] = _lastConfidence
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
// Normalizer.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
|
||||
/// Look-ahead peak normalizer. Delays the output by `dur` seconds and uses the look-ahead
|
||||
/// window to scale the signal so its peak tracks `level` — scaling **up** quiet passages and
|
||||
/// **down** loud ones (vs ``LookAheadLimiter``, which only attenuates).
|
||||
///
|
||||
/// Because the gain is positioned from a look-ahead window, the normalized peak reaches
|
||||
/// `level` without overshoot: as a peak enters the window the gain drops instantly to
|
||||
/// `level / windowPeak`; as it leaves, the gain rises again under a one-pole release smoother
|
||||
/// (time constant `dur`) so the level-up is click-free.
|
||||
///
|
||||
/// ## Gain law
|
||||
/// ```
|
||||
/// windowPeak = max(|x|) over the look-ahead window
|
||||
/// requiredGain = windowPeak > 0 ? level / windowPeak : currentGain // hold gain when silent
|
||||
/// gain = requiredGain < gain ? requiredGain // instant attack
|
||||
/// : releaseCoeff·gain + attackComp·requiredGain // smoothed release
|
||||
/// y[n] = delayed(x)[n] · gain
|
||||
/// ```
|
||||
/// `windowPeak == 0` (true silence in the window) holds the current gain rather than dividing
|
||||
/// by zero. A near-silent (but non-zero) window amplifies its noise floor toward `level` — the
|
||||
/// defining behaviour of a normalizer; gate upstream if that is undesirable.
|
||||
///
|
||||
/// ## Latency
|
||||
/// Output is delayed by exactly `delaySamples = Int(dur × sampleRate)`. `dur` is fixed at init
|
||||
/// (it sizes the ring buffer and sets the release time constant).
|
||||
///
|
||||
/// ## RT-allocation model
|
||||
/// `_delayRing` is pre-allocated at `init` to `delaySamples + lyrebirdDefaultResultBufferSize
|
||||
/// + 1`. The monotonic sliding-window-max deque (payload `(peak, expireAtPos)`) is
|
||||
/// pre-allocated to `delaySamples + 2`. No heap allocation in `_computeSamples`.
|
||||
///
|
||||
/// ## Sliding-window max
|
||||
/// Window peak is O(1) amortised per sample via a monotonic deque of `(peakValue, expireAtPos)`
|
||||
/// entries kept in descending peak order; the front always holds the maximum in the current
|
||||
/// look-ahead window. Identical infrastructure to ``LookAheadLimiter``.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
/// let norm = Normalizer(in: signal, sampleRate: engine.sampleRate)
|
||||
/// let norm = Normalizer(in: signal, level: 0.8, dur: 0.01, sampleRate: engine.sampleRate)
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to normalize.
|
||||
/// - level: Target peak amplitude (absolute value). Output peak tracks this value once the
|
||||
/// look-ahead window has filled. Default `1.0`.
|
||||
/// - dur: Look-ahead and output delay in seconds. Fixed at init — sizes the ring buffer and
|
||||
/// sets the release time constant. Range `[0, ∞)`; values above ~50 ms waste memory.
|
||||
/// Default `0.01` (10 ms).
|
||||
/// - sampleRate: Engine sample rate in Hz. **Must match `SynthesisEngine.sampleRate`.**
|
||||
/// Required — no default. Ring buffer size and release coefficient are computed
|
||||
/// at init from this value and cannot be updated at runtime.
|
||||
public final class Normalizer: GeneratorBase, AudioGenerator {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
private let _input: any ValidGeneratorInput
|
||||
private let _levelInput: any ValidGeneratorInput
|
||||
private let _delaySamples: Int
|
||||
|
||||
// MARK: - Pre-allocated delay ring
|
||||
|
||||
private var _delayRing: [Double]
|
||||
private let _ringSize: Int
|
||||
private var _writeIdx: Int = 0
|
||||
private var _readIdx: Int
|
||||
|
||||
// MARK: - Sliding-window max (monotonic deque)
|
||||
// Front of deque always holds the maximum in the current look-ahead window.
|
||||
|
||||
private struct DequeEntry {
|
||||
var peak: Double
|
||||
var expireAtPos: Int
|
||||
}
|
||||
private var _deque: [DequeEntry]
|
||||
private let _dequeCapacity: Int
|
||||
private var _dequeHeadIdx: Int = 0
|
||||
private var _dequeTailIdx: Int = 0
|
||||
private var _dequeCount: Int = 0
|
||||
|
||||
// MARK: - State
|
||||
|
||||
private var _writePos: Int = 0
|
||||
private var _gain: Double = 1.0
|
||||
private let _releaseCoeff: Double
|
||||
private let _attackComp: Double
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to normalize.
|
||||
/// - level: Target peak amplitude (absolute value). Output peak tracks this value once the
|
||||
/// look-ahead window has filled. Default `1.0`.
|
||||
/// - dur: Look-ahead and output delay in seconds. Fixed at init — sizes the ring buffer and
|
||||
/// sets the release time constant. Range `[0, ∞)`. Default `0.01` (10 ms).
|
||||
/// - sampleRate: Engine sample rate in Hz. **Must match `SynthesisEngine.sampleRate`.**
|
||||
/// Required — no default. Ring buffer size and release coefficient are
|
||||
/// computed at init from this value and cannot be updated at runtime.
|
||||
public init(
|
||||
in input: any ValidGeneratorInput,
|
||||
level: any ValidGeneratorInput = 1.0,
|
||||
dur: Double = 0.01,
|
||||
sampleRate: Double
|
||||
) {
|
||||
precondition(dur >= 0, "Normalizer: dur must be ≥ 0")
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedLevel: any ValidGeneratorInput = level._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_levelInput = resolvedLevel
|
||||
_delaySamples = Int(dur * sampleRate)
|
||||
let bufferSize: Int = _delaySamples + lyrebirdDefaultResultBufferSize + 1
|
||||
_ringSize = bufferSize
|
||||
_delayRing = makeSampleBuffer(bufferSize)
|
||||
_releaseCoeff = dur > 0
|
||||
? exp(-1.0 / (sampleRate * dur))
|
||||
: 0.0
|
||||
_attackComp = 1.0 - _releaseCoeff
|
||||
// Deque capacity = max-live (_delaySamples + 1) + 1 slot of slack so a
|
||||
// push-before-front-pop on a wraparound step does not collide.
|
||||
_dequeCapacity = max(2, _delaySamples + 2)
|
||||
_deque = [DequeEntry](
|
||||
repeating: DequeEntry(peak: 0.0, expireAtPos: 0),
|
||||
count: _dequeCapacity
|
||||
)
|
||||
// Read trails write by _delaySamples. With writeIdx == 0:
|
||||
// readIdx = (0 - _delaySamples + _ringSize) % _ringSize
|
||||
// _delaySamples == 0 → readIdx == 0; otherwise == _ringSize - _delaySamples.
|
||||
_readIdx = _delaySamples == 0 ? 0 : _ringSize - _delaySamples
|
||||
}
|
||||
|
||||
/// Gain the upcoming sample requires to map `windowPeak` onto `level`. Holds the current
|
||||
/// gain when the window is exactly silent (avoids `level / 0`).
|
||||
@inline(__always)
|
||||
private func requiredGain(windowPeak: Double, level: Double, currentGain: Double) -> Double {
|
||||
windowPeak > 0.0 ? level / windowPeak : currentGain
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let level: Double = max(0.0, _levelInput.floatValue(graph: graph))
|
||||
let inputSamples: [[Double]] = _input.calculatedSamples(graph: graph, count: count)
|
||||
|
||||
let ringSize: Int = _ringSize
|
||||
let releaseCoeff: Double = _releaseCoeff
|
||||
let attackComp: Double = _attackComp
|
||||
|
||||
guard let ins: [Double] = inputSamples.first else {
|
||||
// Pathological branch: upstream returned a 0-row matrix. Advance ring + deque
|
||||
// maintenance per-sample so any peaks still inside the look-ahead window from a
|
||||
// prior block keep tracking the delay-line output.
|
||||
var gain: Double = _gain
|
||||
var writeIdx: Int = _writeIdx
|
||||
var readIdx: Int = _readIdx
|
||||
var writePos: Int = _writePos
|
||||
let dequeCap: Int = _dequeCapacity
|
||||
let lookAhead: Int = _delaySamples
|
||||
var headIdx: Int = _dequeHeadIdx
|
||||
var tailIdx: Int = _dequeTailIdx
|
||||
var dequeCount: Int = _dequeCount
|
||||
|
||||
for i: Int in 0..<count {
|
||||
_delayRing[writeIdx] = 0.0
|
||||
writeIdx += 1
|
||||
if writeIdx >= ringSize { writeIdx -= ringSize }
|
||||
|
||||
if lookAhead > 0 {
|
||||
while dequeCount > 0 {
|
||||
let backIdx: Int = tailIdx == 0 ? dequeCap - 1 : tailIdx - 1
|
||||
if _deque[backIdx].peak <= 0.0 {
|
||||
tailIdx = backIdx
|
||||
dequeCount -= 1
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
_deque[tailIdx] = DequeEntry(peak: 0.0, expireAtPos: writePos + lookAhead)
|
||||
tailIdx += 1
|
||||
if tailIdx >= dequeCap { tailIdx -= dequeCap }
|
||||
dequeCount += 1
|
||||
while dequeCount > 0 && _deque[headIdx].expireAtPos < writePos {
|
||||
headIdx += 1
|
||||
if headIdx >= dequeCap { headIdx -= dequeCap }
|
||||
dequeCount -= 1
|
||||
}
|
||||
let windowPeak: Double = _deque[headIdx].peak
|
||||
let needed: Double = requiredGain(windowPeak: windowPeak, level: level, currentGain: gain)
|
||||
gain = needed < gain ? needed : releaseCoeff * gain + attackComp * needed
|
||||
} else {
|
||||
gain = releaseCoeff * gain + attackComp
|
||||
}
|
||||
|
||||
_result[0][i] = _delayRing[readIdx] * gain
|
||||
readIdx += 1
|
||||
if readIdx >= ringSize { readIdx -= ringSize }
|
||||
writePos &+= 1
|
||||
}
|
||||
gain = denormalsToZero(gain)
|
||||
_gain = gain
|
||||
_writeIdx = writeIdx
|
||||
_readIdx = readIdx
|
||||
_writePos = writePos
|
||||
_dequeHeadIdx = headIdx
|
||||
_dequeTailIdx = tailIdx
|
||||
_dequeCount = dequeCount
|
||||
return _result
|
||||
}
|
||||
|
||||
var gain: Double = _gain
|
||||
var writeIdx: Int = _writeIdx
|
||||
var readIdx: Int = _readIdx
|
||||
|
||||
if _delaySamples == 0 {
|
||||
// Fast path: peak follower only — no ring, no deque. `_writePos` / `_writeIdx` /
|
||||
// `_readIdx` are intentionally not advanced; none are read while `_delaySamples == 0`.
|
||||
for i: Int in 0..<count {
|
||||
let sample: Double = ins[i]
|
||||
let absSample: Double = abs(sample)
|
||||
let needed: Double = requiredGain(windowPeak: absSample, level: level, currentGain: gain)
|
||||
gain = needed < gain ? needed : releaseCoeff * gain + attackComp * needed
|
||||
_result[0][i] = sample * gain
|
||||
}
|
||||
gain = denormalsToZero(gain)
|
||||
_gain = gain
|
||||
return _result
|
||||
}
|
||||
|
||||
// Look-ahead path with monotonic deque.
|
||||
let lookAhead: Int = _delaySamples
|
||||
let dequeCap: Int = _dequeCapacity
|
||||
var writePos: Int = _writePos
|
||||
var headIdx: Int = _dequeHeadIdx
|
||||
var tailIdx: Int = _dequeTailIdx
|
||||
var dequeCount: Int = _dequeCount
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let sample: Double = ins[i]
|
||||
let absSample: Double = abs(sample)
|
||||
|
||||
_delayRing[writeIdx] = sample
|
||||
writeIdx += 1
|
||||
if writeIdx >= ringSize { writeIdx -= ringSize }
|
||||
|
||||
// Pop from back while back peak ≤ new peak.
|
||||
while dequeCount > 0 {
|
||||
let backIdx: Int = tailIdx == 0 ? dequeCap - 1 : tailIdx - 1
|
||||
if _deque[backIdx].peak <= absSample {
|
||||
tailIdx = backIdx
|
||||
dequeCount -= 1
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
// Push new entry at back.
|
||||
_deque[tailIdx] = DequeEntry(peak: absSample, expireAtPos: writePos + lookAhead)
|
||||
tailIdx += 1
|
||||
if tailIdx >= dequeCap { tailIdx -= dequeCap }
|
||||
dequeCount += 1
|
||||
// Pop from front while expired (storedPos < writePos - lookAhead → expireAtPos < writePos).
|
||||
while dequeCount > 0 && _deque[headIdx].expireAtPos < writePos {
|
||||
headIdx += 1
|
||||
if headIdx >= dequeCap { headIdx -= dequeCap }
|
||||
dequeCount -= 1
|
||||
}
|
||||
let windowPeak: Double = _deque[headIdx].peak
|
||||
|
||||
// Normalize: scale up or down so the windowed peak maps to `level`.
|
||||
let needed: Double = requiredGain(windowPeak: windowPeak, level: level, currentGain: gain)
|
||||
|
||||
// Instantaneous attack (prevents overshoot above level), smoothed release.
|
||||
gain = needed < gain ? needed : releaseCoeff * gain + attackComp * needed
|
||||
|
||||
_result[0][i] = _delayRing[readIdx] * gain
|
||||
readIdx += 1
|
||||
if readIdx >= ringSize { readIdx -= ringSize }
|
||||
writePos &+= 1
|
||||
}
|
||||
|
||||
// Denormal flush once per block.
|
||||
gain = denormalsToZero(gain)
|
||||
|
||||
_gain = gain
|
||||
_writeIdx = writeIdx
|
||||
_readIdx = readIdx
|
||||
_writePos = writePos
|
||||
_dequeHeadIdx = headIdx
|
||||
_dequeTailIdx = tailIdx
|
||||
_dequeCount = dequeCount
|
||||
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
// `GeneratorEnum` conformance is intentionally omitted — this is an Audio-only generator
|
||||
// with no paired `Control` variant.
|
||||
@@ -376,7 +376,7 @@ public enum EnvelopeGen {
|
||||
/// ```swift
|
||||
/// let env = Envelope(levels: [0, 1, 0], durations: [0.01, 0.5], curves: [.sine, .exponential])
|
||||
/// let gen = EnvelopeGen.Audio(envelope: env, doneAction: .freeNode)
|
||||
/// // After processBlock: if gen.needsFree { engine.schedule(.remove(synth), at: now) }
|
||||
/// // After processBlock: if gen.needsFree { engine.remove(synth) }
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
|
||||
@@ -86,7 +86,7 @@ public final class AllpassFilter: GeneratorBase, AudioGenerator {
|
||||
self.interpolation = interpolation
|
||||
|
||||
let maxSamples: Int = Int(ceil(maxDelay * sampleRate)) + 1
|
||||
let bufSize: Int = Self.nextPowerOf2(max(maxSamples, 2))
|
||||
let bufSize: Int = lyrebirdNextPowerOfTwo(max(maxSamples, 2))
|
||||
self.inputBuf = [Double](repeating: 0, count: bufSize)
|
||||
self.outputBuf = [Double](repeating: 0, count: bufSize)
|
||||
self.bufferMask = bufSize - 1
|
||||
@@ -258,31 +258,16 @@ public final class AllpassFilter: GeneratorBase, AudioGenerator {
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
private static func nextPowerOf2(_ n: Int) -> Int {
|
||||
guard n > 1 else { return 1 }
|
||||
var r: Int = 1
|
||||
while r < n { r <<= 1 }
|
||||
return r
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Local cubic interpolation
|
||||
// MARK: - Catmull-Rom cubic interpolation (delegates to shared catmullRomCubic)
|
||||
|
||||
private func apCubicInterp(
|
||||
frac: Double,
|
||||
y0: Double, y1: Double,
|
||||
y2: Double, y3: Double
|
||||
) -> Double {
|
||||
let half: Double = 0.5
|
||||
let a3: Double = 1.5
|
||||
let b2: Double = 2.5
|
||||
let c2: Double = 2.0
|
||||
let a: Double = -half * y0 + a3 * y1 - a3 * y2 + half * y3
|
||||
let b: Double = y0 - b2 * y1 + c2 * y2 - half * y3
|
||||
let c: Double = -half * y0 + half * y2
|
||||
let d: Double = y1
|
||||
return ((a * frac + b) * frac + c) * frac + d
|
||||
catmullRomCubic(y0, y1, y2, y3, t: frac)
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
@@ -4,14 +4,19 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import Foundation
|
||||
|
||||
/// Cascaded Butterworth bandpass filter, orders 1–8 per section (2 × order total poles).
|
||||
///
|
||||
/// Implemented as an N-th order Butterworth HP section (cutoff = `lowFreq`) cascaded with
|
||||
/// an N-th order Butterworth LP section (cutoff = `highFreq`). Both sections share the same
|
||||
/// Butterworth Q values. The unified ping-pong cascade routes through a single `_scratch`
|
||||
/// buffer — no extra allocation on the RT thread.
|
||||
/// Implemented as two `ButterworthSectionEngine` instances in series: an N-th order
|
||||
/// Butterworth HP section (cutoff = `lowFreq`) cascaded with an N-th order Butterworth
|
||||
/// LP section (cutoff = `highFreq`). The HP engine writes into an intermediate buffer
|
||||
/// `_inter`; the LP engine reads `_inter` and writes to the final output. Both sections
|
||||
/// share the same per-stage Butterworth Q values.
|
||||
///
|
||||
/// Each engine manages its own scratch buffer and background-thread vDSP setup builder
|
||||
/// independently — no shared mutable state between the two sections on the RT thread.
|
||||
///
|
||||
/// Per-stage Q values follow the Butterworth pole formula:
|
||||
/// ```
|
||||
@@ -47,30 +52,11 @@ public enum ButterworthBandPass {
|
||||
/// Per-stage Butterworth Q values — `⌊order/2⌋` entries. Shared by both HP and LP sections.
|
||||
public let butterworthQs: [Double]
|
||||
|
||||
// HP section
|
||||
private var hpBiquadStages: [BiquadState]
|
||||
private var hpFirstOrder: FirstOrderState?
|
||||
private var cachedHPBiquadCoeffs: [BiquadCoeffs]
|
||||
private var cachedHPFO: (b0: Double, b1: Double, na1: Double) = (0, 0, 0)
|
||||
|
||||
// LP section
|
||||
private var lpBiquadStages: [BiquadState]
|
||||
private var lpFirstOrder: FirstOrderState?
|
||||
private var cachedLPBiquadCoeffs: [BiquadCoeffs]
|
||||
private var cachedLPFO: (b0: Double, b1: Double, na1: Double) = (0, 0, 0)
|
||||
|
||||
private var prevLowFreq: Double = -1.0
|
||||
private var prevHighFreq: Double = -1.0
|
||||
private var prevSampleRate: Double = -1.0
|
||||
|
||||
private var _scratch: [Double]
|
||||
private let hpEngine: ButterworthSectionEngine // HP section (lowFreq cutoff)
|
||||
private let lpEngine: ButterworthSectionEngine // LP section (highFreq cutoff)
|
||||
private var _inter: [Double] // HP output / LP input
|
||||
private let _mulAdd: MulAddSpec
|
||||
|
||||
/// Number of stages in each LP/HP section.
|
||||
private let sectionStageCount: Int
|
||||
/// Total stages = 2 × sectionStageCount.
|
||||
private let totalStageCount: Int
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to filter.
|
||||
/// - lowFreq: Lower edge of the passband in Hz (HP cutoff — content below this is attenuated). No internal clamping; stay below `highFreq` and Nyquist.
|
||||
@@ -86,7 +72,6 @@ public enum ButterworthBandPass {
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedLowFreq: any ValidGeneratorInput = lowFreq._resolvedInput()
|
||||
let resolvedHighFreq: any ValidGeneratorInput = highFreq._resolvedInput()
|
||||
@@ -98,35 +83,24 @@ public enum ButterworthBandPass {
|
||||
|
||||
let clampedOrder: Int = min(max(order, 1), maxButterworthOrder)
|
||||
self.order = clampedOrder
|
||||
self.butterworthQs = computeButterworthQs(order: clampedOrder)
|
||||
|
||||
let numBiquads: Int = clampedOrder / 2
|
||||
var qs: [Double] = [Double]()
|
||||
if numBiquads > 0 {
|
||||
for k: Int in 1...numBiquads {
|
||||
let angle: Double = Double.pi * Double(2 * k + clampedOrder - 1)
|
||||
/ Double(2 * clampedOrder)
|
||||
qs.append(-1.0 / (2.0 * cos(angle)))
|
||||
}
|
||||
}
|
||||
self.butterworthQs = qs
|
||||
|
||||
let hasFO: Bool = clampedOrder % 2 == 1
|
||||
let stagesPerSection: Int = numBiquads + (hasFO ? 1 : 0)
|
||||
let numFilterSections: Int = 2 // HP section + LP section
|
||||
self.sectionStageCount = stagesPerSection
|
||||
self.totalStageCount = stagesPerSection * numFilterSections
|
||||
|
||||
self.hpBiquadStages = [BiquadState](repeating: BiquadState(), count: numBiquads)
|
||||
self.hpFirstOrder = hasFO ? FirstOrderState() : nil
|
||||
self.cachedHPBiquadCoeffs = [BiquadCoeffs](repeating: .zero, count: numBiquads)
|
||||
|
||||
self.lpBiquadStages = [BiquadState](repeating: BiquadState(), count: numBiquads)
|
||||
self.lpFirstOrder = hasFO ? FirstOrderState() : nil
|
||||
self.cachedLPBiquadCoeffs = [BiquadCoeffs](repeating: .zero, count: numBiquads)
|
||||
|
||||
self._scratch = makeSampleBuffer()
|
||||
self.hpEngine = ButterworthSectionEngine(
|
||||
order: clampedOrder,
|
||||
foCoeffs: { foHPCoeffs(freq: $0, sr: $1) },
|
||||
biquadCoeffs: { rbjHighPassCoeffs(freq: $0, q: $1, sampleRate: $2) },
|
||||
threadName: "LyrebirdButterworthBP-HP.vDSP"
|
||||
)
|
||||
self.lpEngine = ButterworthSectionEngine(
|
||||
order: clampedOrder,
|
||||
foCoeffs: { foLPCoeffs(freq: $0, sr: $1) },
|
||||
biquadCoeffs: { rbjLowPassCoeffs(freq: $0, q: $1, sampleRate: $2) },
|
||||
threadName: "LyrebirdButterworthBP-LP.vDSP"
|
||||
)
|
||||
self._inter = makeSampleBuffer()
|
||||
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
@@ -138,234 +112,69 @@ public enum ButterworthBandPass {
|
||||
}
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
|
||||
if lowFreqIsGenerator || highFreqIsGenerator {
|
||||
let lowSamples: [Double]? = lowFreqIsGenerator
|
||||
? lowFreqInput.calculatedSamples(graph: graph, count: count).first
|
||||
: nil
|
||||
let highSamples: [Double]? = highFreqIsGenerator
|
||||
? highFreqInput.calculatedSamples(graph: graph, count: count).first
|
||||
: nil
|
||||
|
||||
let lastI: Int = count - 1
|
||||
let lf0: Double = lowSamples.map { $0.isEmpty ? lowFreqInput.floatValue(graph: graph) : $0[0] }
|
||||
?? lowFreqInput.floatValue(graph: graph)
|
||||
let lfN: Double = lowSamples.map { $0.isEmpty ? lf0 : $0[min($0.count - 1, lastI)] } ?? lf0
|
||||
let hf0: Double = highSamples.map { $0.isEmpty ? highFreqInput.floatValue(graph: graph) : $0[0] }
|
||||
?? highFreqInput.floatValue(graph: graph)
|
||||
let hfN: Double = highSamples.map { $0.isEmpty ? hf0 : $0[min($0.count - 1, lastI)] } ?? hf0
|
||||
|
||||
runAudioRate(input: inputBlock, lf0: lf0, lfN: lfN, hf0: hf0, hfN: hfN, sr: sr, count: count)
|
||||
} else {
|
||||
let lowFreq: Double = lowFreqInput.floatValue(graph: graph)
|
||||
let highFreq: Double = highFreqInput.floatValue(graph: graph)
|
||||
if lowFreq != prevLowFreq || highFreq != prevHighFreq || sr != prevSampleRate {
|
||||
recomputeScalarCoeffs(lowFreq: lowFreq, highFreq: highFreq, sr: sr)
|
||||
prevLowFreq = lowFreq; prevHighFreq = highFreq; prevSampleRate = sr
|
||||
// Resolve the HP-section cutoff (lowFreq — the lower passband edge).
|
||||
let hpScalarFreq: Double
|
||||
let hpF0: Double
|
||||
let hpFN: Double
|
||||
if lowFreqIsGenerator {
|
||||
let lowSamples: [[Double]] = lowFreqInput.calculatedSamples(graph: graph, count: count)
|
||||
if let s: [Double] = lowSamples.first, !s.isEmpty {
|
||||
hpF0 = s[0]
|
||||
hpFN = s[min(s.count - 1, count - 1)]
|
||||
} else {
|
||||
let fv: Double = lowFreqInput.floatValue(graph: graph)
|
||||
hpF0 = fv; hpFN = fv
|
||||
}
|
||||
runScalar(input: inputBlock, count: count)
|
||||
hpScalarFreq = 0.0
|
||||
} else {
|
||||
hpScalarFreq = lowFreqInput.floatValue(graph: graph)
|
||||
hpF0 = 0.0; hpFN = 0.0
|
||||
}
|
||||
|
||||
// Resolve the LP-section cutoff (highFreq — the upper passband edge).
|
||||
let lpScalarFreq: Double
|
||||
let lpF0: Double
|
||||
let lpFN: Double
|
||||
if highFreqIsGenerator {
|
||||
let highSamples: [[Double]] = highFreqInput.calculatedSamples(graph: graph, count: count)
|
||||
if let s: [Double] = highSamples.first, !s.isEmpty {
|
||||
lpF0 = s[0]
|
||||
lpFN = s[min(s.count - 1, count - 1)]
|
||||
} else {
|
||||
let fv: Double = highFreqInput.floatValue(graph: graph)
|
||||
lpF0 = fv; lpFN = fv
|
||||
}
|
||||
lpScalarFreq = 0.0
|
||||
} else {
|
||||
lpScalarFreq = highFreqInput.floatValue(graph: graph)
|
||||
lpF0 = 0.0; lpFN = 0.0
|
||||
}
|
||||
|
||||
// Series: HP section (lowFreq cutoff) → intermediate buffer → LP section (highFreq cutoff) → output.
|
||||
hpEngine.process(
|
||||
input: inputBlock,
|
||||
freqIsGenerator: lowFreqIsGenerator,
|
||||
scalarFreq: hpScalarFreq,
|
||||
f0: hpF0,
|
||||
fN: hpFN,
|
||||
sr: sr,
|
||||
count: count,
|
||||
into: &_inter
|
||||
)
|
||||
lpEngine.process(
|
||||
input: _inter,
|
||||
freqIsGenerator: highFreqIsGenerator,
|
||||
scalarFreq: lpScalarFreq,
|
||||
f0: lpF0,
|
||||
fN: lpFN,
|
||||
sr: sr,
|
||||
count: count,
|
||||
into: &_result[0]
|
||||
)
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
// MARK: - Coefficient computation
|
||||
|
||||
private func recomputeScalarCoeffs(
|
||||
lowFreq: Double,
|
||||
highFreq: Double,
|
||||
sr: Double
|
||||
) {
|
||||
if hpFirstOrder != nil { cachedHPFO = foHPCoeffs(freq: lowFreq, sr: sr) }
|
||||
for i: Int in 0..<hpBiquadStages.count {
|
||||
cachedHPBiquadCoeffs[i] = rbjHighPassCoeffs(freq: lowFreq, q: butterworthQs[i], sampleRate: sr)
|
||||
}
|
||||
if lpFirstOrder != nil { cachedLPFO = foLPCoeffs(freq: highFreq, sr: sr) }
|
||||
for i: Int in 0..<lpBiquadStages.count {
|
||||
cachedLPBiquadCoeffs[i] = rbjLowPassCoeffs(freq: highFreq, q: butterworthQs[i], sampleRate: sr)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Unified cascade
|
||||
|
||||
/// Buffer routing: stage `i` of `stageCount` total writes to `_result[0]` when `(stageCount+i)%2==1`,
|
||||
/// else to `_scratch`. LP stages (i ≥ sectionStageCount) always have i > 0.
|
||||
private func runScalar(
|
||||
input: [Double],
|
||||
count: Int
|
||||
) {
|
||||
let stageCount: Int = totalStageCount
|
||||
|
||||
// HP section (stages 0 ..< sectionStageCount)
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = hpFirstOrder {
|
||||
let writesResult: Bool = (stageCount + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input, b0: cachedHPFO.b0, b1: cachedHPFO.b1, na1: cachedHPFO.na1,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input, b0: cachedHPFO.b0, b1: cachedHPFO.b1, na1: cachedHPFO.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
hpFirstOrder = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<hpBiquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (stageCount + i) % 2 == 1
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
hpBiquadStages[bi].processBlock(input: input, coeffs: cachedHPBiquadCoeffs[bi],
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
hpBiquadStages[bi].processBlock(input: _scratch, coeffs: cachedHPBiquadCoeffs[bi],
|
||||
into: &_result[0], count: count)
|
||||
}
|
||||
} else {
|
||||
if i == 0 {
|
||||
hpBiquadStages[bi].processBlock(input: input, coeffs: cachedHPBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
} else {
|
||||
hpBiquadStages[bi].processBlock(input: _result[0], coeffs: cachedHPBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LP section (stages sectionStageCount ..< totalStageCount; i > 0 always)
|
||||
var lpi: Int = sectionStageCount
|
||||
if var fo: FirstOrderState = lpFirstOrder {
|
||||
let i: Int = lpi
|
||||
let writesResult: Bool = (stageCount + i) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: _scratch, b0: cachedLPFO.b0, b1: cachedLPFO.b1, na1: cachedLPFO.na1,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
fo.processBlock(input: _result[0], b0: cachedLPFO.b0, b1: cachedLPFO.b1, na1: cachedLPFO.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
lpFirstOrder = fo
|
||||
lpi += 1
|
||||
}
|
||||
for bi: Int in 0..<lpBiquadStages.count {
|
||||
let i: Int = lpi + bi
|
||||
let writesResult: Bool = (stageCount + i) % 2 == 1
|
||||
if writesResult {
|
||||
lpBiquadStages[bi].processBlock(input: _scratch, coeffs: cachedLPBiquadCoeffs[bi],
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
lpBiquadStages[bi].processBlock(input: _result[0], coeffs: cachedLPBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func runAudioRate(
|
||||
input: [Double],
|
||||
lf0: Double,
|
||||
lfN: Double,
|
||||
hf0: Double,
|
||||
hfN: Double,
|
||||
sr: Double,
|
||||
count: Int
|
||||
) {
|
||||
let stageCount: Int = totalStageCount
|
||||
|
||||
// Precompute HP boundary coefficients
|
||||
let hpFOS: (b0: Double, b1: Double, na1: Double)
|
||||
let hpFOE: (b0: Double, b1: Double, na1: Double)
|
||||
if hpFirstOrder != nil {
|
||||
hpFOS = foHPCoeffs(freq: lf0, sr: sr)
|
||||
hpFOE = foHPCoeffs(freq: lfN, sr: sr)
|
||||
} else {
|
||||
hpFOS = (0, 0, 0); hpFOE = (0, 0, 0)
|
||||
}
|
||||
|
||||
// Precompute LP boundary coefficients
|
||||
let lpFOS: (b0: Double, b1: Double, na1: Double)
|
||||
let lpFOE: (b0: Double, b1: Double, na1: Double)
|
||||
if lpFirstOrder != nil {
|
||||
lpFOS = foLPCoeffs(freq: hf0, sr: sr)
|
||||
lpFOE = foLPCoeffs(freq: hfN, sr: sr)
|
||||
} else {
|
||||
lpFOS = (0, 0, 0); lpFOE = (0, 0, 0)
|
||||
}
|
||||
|
||||
// HP section
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = hpFirstOrder {
|
||||
let writesResult: Bool = (stageCount + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input,
|
||||
startB0: hpFOS.b0, startB1: hpFOS.b1, startNa1: hpFOS.na1,
|
||||
endB0: hpFOE.b0, endB1: hpFOE.b1, endNa1: hpFOE.na1,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input,
|
||||
startB0: hpFOS.b0, startB1: hpFOS.b1, startNa1: hpFOS.na1,
|
||||
endB0: hpFOE.b0, endB1: hpFOE.b1, endNa1: hpFOE.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
hpFirstOrder = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<hpBiquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (stageCount + i) % 2 == 1
|
||||
let startC: BiquadCoeffs = rbjHighPassCoeffs(freq: lf0, q: butterworthQs[bi], sampleRate: sr)
|
||||
let endC: BiquadCoeffs = rbjHighPassCoeffs(freq: lfN, q: butterworthQs[bi], sampleRate: sr)
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
hpBiquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
hpBiquadStages[bi].processBlock(input: _scratch, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_result[0], count: count)
|
||||
}
|
||||
} else {
|
||||
if i == 0 {
|
||||
hpBiquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
} else {
|
||||
hpBiquadStages[bi].processBlock(input: _result[0], startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LP section (i > 0 always)
|
||||
var lpi: Int = sectionStageCount
|
||||
if var fo: FirstOrderState = lpFirstOrder {
|
||||
let i: Int = lpi
|
||||
let writesResult: Bool = (stageCount + i) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: _scratch,
|
||||
startB0: lpFOS.b0, startB1: lpFOS.b1, startNa1: lpFOS.na1,
|
||||
endB0: lpFOE.b0, endB1: lpFOE.b1, endNa1: lpFOE.na1,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
fo.processBlock(input: _result[0],
|
||||
startB0: lpFOS.b0, startB1: lpFOS.b1, startNa1: lpFOS.na1,
|
||||
endB0: lpFOE.b0, endB1: lpFOE.b1, endNa1: lpFOE.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
lpFirstOrder = fo
|
||||
lpi += 1
|
||||
}
|
||||
for bi: Int in 0..<lpBiquadStages.count {
|
||||
let i: Int = lpi + bi
|
||||
let writesResult: Bool = (stageCount + i) % 2 == 1
|
||||
let startC: BiquadCoeffs = rbjLowPassCoeffs(freq: hf0, q: butterworthQs[bi], sampleRate: sr)
|
||||
let endC: BiquadCoeffs = rbjLowPassCoeffs(freq: hfN, q: butterworthQs[bi], sampleRate: sr)
|
||||
if writesResult {
|
||||
lpBiquadStages[bi].processBlock(input: _scratch, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
lpBiquadStages[bi].processBlock(input: _result[0], startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,17 +4,20 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import Foundation
|
||||
|
||||
/// Cascaded Butterworth band-reject (notch) filter, orders 1–8 per section (2 × order total poles).
|
||||
///
|
||||
/// Implemented as two parallel paths summed: an N-th order Butterworth LP section
|
||||
/// (cutoff = `lowFreq`) plus an N-th order Butterworth HP section (cutoff = `highFreq`).
|
||||
/// Content between `lowFreq` and `highFreq` is attenuated; content outside that band passes.
|
||||
/// Implemented as two parallel `ButterworthSectionEngine` instances summed: an N-th order
|
||||
/// Butterworth LP section (cutoff = `lowFreq`) plus an N-th order Butterworth HP section
|
||||
/// (cutoff = `highFreq`). Content between `lowFreq` and `highFreq` is attenuated; content
|
||||
/// outside that band passes.
|
||||
///
|
||||
/// The LP cascade writes to a dedicated `_lpResult` buffer; the HP cascade writes to
|
||||
/// `_result[0]`. Both share a single `_scratch` buffer (used sequentially). Final output
|
||||
/// is the element-wise sum written back into `_result[0]`. No RT allocation.
|
||||
/// The LP engine writes to a dedicated `_lpOut` buffer; the HP engine writes to `_result[0]`.
|
||||
/// Both engines have independent scratch buffers and background-thread vDSP setup builders —
|
||||
/// no shared mutable state between the two sections on the RT thread. The final output is the
|
||||
/// element-wise sum (`vDSP_vaddD`) of `_lpOut` into `_result[0]`. No RT allocation.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
@@ -45,32 +48,15 @@ public enum ButterworthBandReject {
|
||||
/// Per-stage Butterworth Q values — `⌊order/2⌋` entries. Shared by both LP and HP sections.
|
||||
public let butterworthQs: [Double]
|
||||
|
||||
// LP section
|
||||
private var lpBiquadStages: [BiquadState]
|
||||
private var lpFirstOrder: FirstOrderState?
|
||||
private var cachedLPBiquadCoeffs: [BiquadCoeffs]
|
||||
private var cachedLPFO: (b0: Double, b1: Double, na1: Double) = (0, 0, 0)
|
||||
|
||||
// HP section
|
||||
private var hpBiquadStages: [BiquadState]
|
||||
private var hpFirstOrder: FirstOrderState?
|
||||
private var cachedHPBiquadCoeffs: [BiquadCoeffs]
|
||||
private var cachedHPFO: (b0: Double, b1: Double, na1: Double) = (0, 0, 0)
|
||||
|
||||
private var prevLowFreq: Double = -1.0
|
||||
private var prevHighFreq: Double = -1.0
|
||||
private var prevSampleRate: Double = -1.0
|
||||
|
||||
private var _lpResult: [Double] // LP cascade output
|
||||
private var _scratch: [Double] // shared intermediate buffer
|
||||
private let lpEngine: ButterworthSectionEngine // LP section (lowFreq cutoff)
|
||||
private let hpEngine: ButterworthSectionEngine // HP section (highFreq cutoff)
|
||||
private var _lpOut: [Double] // LP cascade output buffer
|
||||
private let _mulAdd: MulAddSpec
|
||||
|
||||
private let sectionStageCount: Int
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to filter.
|
||||
/// - lowFreq: Upper edge of the reject band in Hz (LP cutoff — content below this is passed by the LP path). No internal clamping; stay below `highFreq` and Nyquist.
|
||||
/// - highFreq: Lower edge of the reject band in Hz (HP cutoff — content above this is passed by the HP path). No internal clamping; stay above `lowFreq`.
|
||||
/// - lowFreq: Lower edge of the reject band in Hz (LP cutoff — content below this is passed by the LP path). No internal clamping; stay below `highFreq` and Nyquist.
|
||||
/// - highFreq: Upper edge of the reject band in Hz (HP cutoff — content above this is passed by the HP path). No internal clamping; stay above `lowFreq`.
|
||||
/// - order: Filter order per section 1–8 (clamped internally). Total poles = 2 × order. Higher order = deeper, narrower notch but higher CPU cost. Defaults to `2`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
@@ -82,7 +68,6 @@ public enum ButterworthBandReject {
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedLowFreq: any ValidGeneratorInput = lowFreq._resolvedInput()
|
||||
let resolvedHighFreq: any ValidGeneratorInput = highFreq._resolvedInput()
|
||||
@@ -94,33 +79,24 @@ public enum ButterworthBandReject {
|
||||
|
||||
let clampedOrder: Int = min(max(order, 1), maxButterworthOrder)
|
||||
self.order = clampedOrder
|
||||
self.butterworthQs = computeButterworthQs(order: clampedOrder)
|
||||
|
||||
let numBiquads: Int = clampedOrder / 2
|
||||
var qs: [Double] = [Double]()
|
||||
if numBiquads > 0 {
|
||||
for k: Int in 1...numBiquads {
|
||||
let angle: Double = Double.pi * Double(2 * k + clampedOrder - 1)
|
||||
/ Double(2 * clampedOrder)
|
||||
qs.append(-1.0 / (2.0 * cos(angle)))
|
||||
}
|
||||
}
|
||||
self.butterworthQs = qs
|
||||
|
||||
let hasFO: Bool = clampedOrder % 2 == 1
|
||||
self.sectionStageCount = numBiquads + (hasFO ? 1 : 0)
|
||||
|
||||
self.lpBiquadStages = [BiquadState](repeating: BiquadState(), count: numBiquads)
|
||||
self.lpFirstOrder = hasFO ? FirstOrderState() : nil
|
||||
self.cachedLPBiquadCoeffs = [BiquadCoeffs](repeating: .zero, count: numBiquads)
|
||||
|
||||
self.hpBiquadStages = [BiquadState](repeating: BiquadState(), count: numBiquads)
|
||||
self.hpFirstOrder = hasFO ? FirstOrderState() : nil
|
||||
self.cachedHPBiquadCoeffs = [BiquadCoeffs](repeating: .zero, count: numBiquads)
|
||||
|
||||
self._lpResult = makeSampleBuffer()
|
||||
self._scratch = makeSampleBuffer()
|
||||
self.lpEngine = ButterworthSectionEngine(
|
||||
order: clampedOrder,
|
||||
foCoeffs: { foLPCoeffs(freq: $0, sr: $1) },
|
||||
biquadCoeffs: { rbjLowPassCoeffs(freq: $0, q: $1, sampleRate: $2) },
|
||||
threadName: "LyrebirdButterworthBR-LP.vDSP"
|
||||
)
|
||||
self.hpEngine = ButterworthSectionEngine(
|
||||
order: clampedOrder,
|
||||
foCoeffs: { foHPCoeffs(freq: $0, sr: $1) },
|
||||
biquadCoeffs: { rbjHighPassCoeffs(freq: $0, q: $1, sampleRate: $2) },
|
||||
threadName: "LyrebirdButterworthBR-HP.vDSP"
|
||||
)
|
||||
self._lpOut = makeSampleBuffer()
|
||||
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
@@ -132,250 +108,78 @@ public enum ButterworthBandReject {
|
||||
}
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
|
||||
if lowFreqIsGenerator || highFreqIsGenerator {
|
||||
let lowSamples: [Double]? = lowFreqIsGenerator
|
||||
? lowFreqInput.calculatedSamples(graph: graph, count: count).first
|
||||
: nil
|
||||
let highSamples: [Double]? = highFreqIsGenerator
|
||||
? highFreqInput.calculatedSamples(graph: graph, count: count).first
|
||||
: nil
|
||||
|
||||
let lastI: Int = count - 1
|
||||
let lf0: Double = lowSamples.map { $0.isEmpty ? lowFreqInput.floatValue(graph: graph) : $0[0] }
|
||||
?? lowFreqInput.floatValue(graph: graph)
|
||||
let lfN: Double = lowSamples.map { $0.isEmpty ? lf0 : $0[min($0.count - 1, lastI)] } ?? lf0
|
||||
let hf0: Double = highSamples.map { $0.isEmpty ? highFreqInput.floatValue(graph: graph) : $0[0] }
|
||||
?? highFreqInput.floatValue(graph: graph)
|
||||
let hfN: Double = highSamples.map { $0.isEmpty ? hf0 : $0[min($0.count - 1, lastI)] } ?? hf0
|
||||
|
||||
runLPAudioRate(input: inputBlock, f0: lf0, fN: lfN, sr: sr, count: count)
|
||||
runHPAudioRate(input: inputBlock, f0: hf0, fN: hfN, sr: sr, count: count)
|
||||
} else {
|
||||
let lowFreq: Double = lowFreqInput.floatValue(graph: graph)
|
||||
let highFreq: Double = highFreqInput.floatValue(graph: graph)
|
||||
if lowFreq != prevLowFreq || highFreq != prevHighFreq || sr != prevSampleRate {
|
||||
recomputeScalarCoeffs(lowFreq: lowFreq, highFreq: highFreq, sr: sr)
|
||||
prevLowFreq = lowFreq; prevHighFreq = highFreq; prevSampleRate = sr
|
||||
// Resolve low-frequency (LP cutoff) inputs.
|
||||
let lpScalarFreq: Double
|
||||
let lpF0: Double
|
||||
let lpFN: Double
|
||||
if lowFreqIsGenerator {
|
||||
let lowSamples: [[Double]] = lowFreqInput.calculatedSamples(graph: graph, count: count)
|
||||
if let s: [Double] = lowSamples.first, !s.isEmpty {
|
||||
lpF0 = s[0]
|
||||
lpFN = s[min(s.count - 1, count - 1)]
|
||||
} else {
|
||||
let fv: Double = lowFreqInput.floatValue(graph: graph)
|
||||
lpF0 = fv; lpFN = fv
|
||||
}
|
||||
runLPScalar(input: inputBlock, count: count)
|
||||
runHPScalar(input: inputBlock, count: count)
|
||||
lpScalarFreq = 0.0
|
||||
} else {
|
||||
lpScalarFreq = lowFreqInput.floatValue(graph: graph)
|
||||
lpF0 = 0.0; lpFN = 0.0
|
||||
}
|
||||
|
||||
// Parallel sum: LP (in _lpResult) + HP (in _result[0]) → _result[0]
|
||||
for i: Int in 0..<count { _result[0][i] += _lpResult[i] }
|
||||
// Resolve high-frequency (HP cutoff) inputs.
|
||||
let hpScalarFreq: Double
|
||||
let hpF0: Double
|
||||
let hpFN: Double
|
||||
if highFreqIsGenerator {
|
||||
let highSamples: [[Double]] = highFreqInput.calculatedSamples(graph: graph, count: count)
|
||||
if let s: [Double] = highSamples.first, !s.isEmpty {
|
||||
hpF0 = s[0]
|
||||
hpFN = s[min(s.count - 1, count - 1)]
|
||||
} else {
|
||||
let fv: Double = highFreqInput.floatValue(graph: graph)
|
||||
hpF0 = fv; hpFN = fv
|
||||
}
|
||||
hpScalarFreq = 0.0
|
||||
} else {
|
||||
hpScalarFreq = highFreqInput.floatValue(graph: graph)
|
||||
hpF0 = 0.0; hpFN = 0.0
|
||||
}
|
||||
|
||||
// Parallel: LP section (lowFreq) and HP section (highFreq) each process the raw input.
|
||||
lpEngine.process(
|
||||
input: inputBlock,
|
||||
freqIsGenerator: lowFreqIsGenerator,
|
||||
scalarFreq: lpScalarFreq,
|
||||
f0: lpF0,
|
||||
fN: lpFN,
|
||||
sr: sr,
|
||||
count: count,
|
||||
into: &_lpOut
|
||||
)
|
||||
hpEngine.process(
|
||||
input: inputBlock,
|
||||
freqIsGenerator: highFreqIsGenerator,
|
||||
scalarFreq: hpScalarFreq,
|
||||
f0: hpF0,
|
||||
fN: hpFN,
|
||||
sr: sr,
|
||||
count: count,
|
||||
into: &_result[0]
|
||||
)
|
||||
|
||||
// Sum: LP (in _lpOut) + HP (in _result[0]) → _result[0]
|
||||
_lpOut.withUnsafeBufferPointer { lpBuf in
|
||||
_result[0].withUnsafeMutableBufferPointer { outBuf in
|
||||
guard let lpBase: UnsafePointer<Double> = lpBuf.baseAddress,
|
||||
let outBase: UnsafeMutablePointer<Double> = outBuf.baseAddress else { return }
|
||||
vDSP_vaddD(lpBase, 1, outBase, 1, outBase, 1, vDSP_Length(count))
|
||||
}
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
// MARK: - Coefficient computation
|
||||
|
||||
private func recomputeScalarCoeffs(
|
||||
lowFreq: Double,
|
||||
highFreq: Double,
|
||||
sr: Double
|
||||
) {
|
||||
if lpFirstOrder != nil { cachedLPFO = foLPCoeffs(freq: lowFreq, sr: sr) }
|
||||
for i: Int in 0..<lpBiquadStages.count {
|
||||
cachedLPBiquadCoeffs[i] = rbjLowPassCoeffs(freq: lowFreq, q: butterworthQs[i], sampleRate: sr)
|
||||
}
|
||||
if hpFirstOrder != nil { cachedHPFO = foHPCoeffs(freq: highFreq, sr: sr) }
|
||||
for i: Int in 0..<hpBiquadStages.count {
|
||||
cachedHPBiquadCoeffs[i] = rbjHighPassCoeffs(freq: highFreq, q: butterworthQs[i], sampleRate: sr)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - LP cascade (primary buffer = _lpResult)
|
||||
|
||||
private func runLPScalar(
|
||||
input: [Double],
|
||||
count: Int
|
||||
) {
|
||||
let stageCount: Int = sectionStageCount
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = lpFirstOrder {
|
||||
let writesResult: Bool = (stageCount + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input, b0: cachedLPFO.b0, b1: cachedLPFO.b1, na1: cachedLPFO.na1,
|
||||
into: &_lpResult, count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input, b0: cachedLPFO.b0, b1: cachedLPFO.b1, na1: cachedLPFO.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
lpFirstOrder = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<lpBiquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (stageCount + i) % 2 == 1
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
lpBiquadStages[bi].processBlock(input: input, coeffs: cachedLPBiquadCoeffs[bi],
|
||||
into: &_lpResult, count: count)
|
||||
} else {
|
||||
lpBiquadStages[bi].processBlock(input: _scratch, coeffs: cachedLPBiquadCoeffs[bi],
|
||||
into: &_lpResult, count: count)
|
||||
}
|
||||
} else {
|
||||
if i == 0 {
|
||||
lpBiquadStages[bi].processBlock(input: input, coeffs: cachedLPBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
} else {
|
||||
lpBiquadStages[bi].processBlock(input: _lpResult, coeffs: cachedLPBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - HP cascade (primary buffer = _result[0])
|
||||
|
||||
private func runHPScalar(
|
||||
input: [Double],
|
||||
count: Int
|
||||
) {
|
||||
let stageCount: Int = sectionStageCount
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = hpFirstOrder {
|
||||
let writesResult: Bool = (stageCount + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input, b0: cachedHPFO.b0, b1: cachedHPFO.b1, na1: cachedHPFO.na1,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input, b0: cachedHPFO.b0, b1: cachedHPFO.b1, na1: cachedHPFO.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
hpFirstOrder = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<hpBiquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (stageCount + i) % 2 == 1
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
hpBiquadStages[bi].processBlock(input: input, coeffs: cachedHPBiquadCoeffs[bi],
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
hpBiquadStages[bi].processBlock(input: _scratch, coeffs: cachedHPBiquadCoeffs[bi],
|
||||
into: &_result[0], count: count)
|
||||
}
|
||||
} else {
|
||||
if i == 0 {
|
||||
hpBiquadStages[bi].processBlock(input: input, coeffs: cachedHPBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
} else {
|
||||
hpBiquadStages[bi].processBlock(input: _result[0], coeffs: cachedHPBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio-rate paths
|
||||
|
||||
private func runLPAudioRate(
|
||||
input: [Double],
|
||||
f0: Double,
|
||||
fN: Double,
|
||||
sr: Double,
|
||||
count: Int
|
||||
) {
|
||||
let stageCount: Int = sectionStageCount
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = lpFirstOrder {
|
||||
let s: (b0: Double, b1: Double, na1: Double) = foLPCoeffs(freq: f0, sr: sr)
|
||||
let e: (b0: Double, b1: Double, na1: Double) = foLPCoeffs(freq: fN, sr: sr)
|
||||
let writesResult: Bool = (stageCount + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input,
|
||||
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
|
||||
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
|
||||
into: &_lpResult, count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input,
|
||||
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
|
||||
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
lpFirstOrder = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<lpBiquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (stageCount + i) % 2 == 1
|
||||
let startC: BiquadCoeffs = rbjLowPassCoeffs(freq: f0, q: butterworthQs[bi], sampleRate: sr)
|
||||
let endC: BiquadCoeffs = rbjLowPassCoeffs(freq: fN, q: butterworthQs[bi], sampleRate: sr)
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
lpBiquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_lpResult, count: count)
|
||||
} else {
|
||||
lpBiquadStages[bi].processBlock(input: _scratch, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_lpResult, count: count)
|
||||
}
|
||||
} else {
|
||||
if i == 0 {
|
||||
lpBiquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
} else {
|
||||
lpBiquadStages[bi].processBlock(input: _lpResult, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func runHPAudioRate(
|
||||
input: [Double],
|
||||
f0: Double,
|
||||
fN: Double,
|
||||
sr: Double,
|
||||
count: Int
|
||||
) {
|
||||
let stageCount: Int = sectionStageCount
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = hpFirstOrder {
|
||||
let s: (b0: Double, b1: Double, na1: Double) = foHPCoeffs(freq: f0, sr: sr)
|
||||
let e: (b0: Double, b1: Double, na1: Double) = foHPCoeffs(freq: fN, sr: sr)
|
||||
let writesResult: Bool = (stageCount + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input,
|
||||
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
|
||||
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input,
|
||||
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
|
||||
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
hpFirstOrder = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<hpBiquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (stageCount + i) % 2 == 1
|
||||
let startC: BiquadCoeffs = rbjHighPassCoeffs(freq: f0, q: butterworthQs[bi], sampleRate: sr)
|
||||
let endC: BiquadCoeffs = rbjHighPassCoeffs(freq: fN, q: butterworthQs[bi], sampleRate: sr)
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
hpBiquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
hpBiquadStages[bi].processBlock(input: _scratch, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_result[0], count: count)
|
||||
}
|
||||
} else {
|
||||
if i == 0 {
|
||||
hpBiquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
} else {
|
||||
hpBiquadStages[bi].processBlock(input: _result[0], startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
// ButterworthCascadeBase.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Thin Generator shell for the lowpass / highpass Butterworth filters.
|
||||
///
|
||||
/// All single-cascade machinery (biquad stages, optional first-order section, cached
|
||||
/// coefficients, scratch buffer, vDSP background-thread builder) lives in
|
||||
/// `ButterworthSectionEngine`. This class owns one engine, resolves its `input` and
|
||||
/// `freq` inputs, delegates the per-block computation, and applies `mul`/`add`.
|
||||
///
|
||||
/// Concrete filters subclass this and inject only their per-stage coefficient formulas
|
||||
/// and a thread name; all state and lifecycle live in the engine.
|
||||
///
|
||||
/// ## vDSP acceleration
|
||||
/// For constant or block-rate `freq` (non-generator), a background thread builds a
|
||||
/// `vDSP_biquad_SetupD` from the current coefficients and delivers it via a lock-free
|
||||
/// `SPSCQueue`. Once the setup arrives the biquad cascade uses `vDSP_biquadD`; the
|
||||
/// first-order section (odd orders) stays scalar. Audio-rate `freq` always uses the
|
||||
/// scalar interpolating path. All machinery lives inside `ButterworthSectionEngine`.
|
||||
public class _ButterworthCascadeBase: GeneratorBase, AudioGenerator {
|
||||
|
||||
private let inputSource: any ValidGeneratorInput
|
||||
private let freqInput: any ValidGeneratorInput
|
||||
private let freqIsGenerator: Bool
|
||||
private let _mulAdd: MulAddSpec
|
||||
|
||||
private let engine: ButterworthSectionEngine
|
||||
|
||||
/// Filter order, clamped to `[1, maxButterworthOrder]` at init.
|
||||
public var order: Int { engine.order }
|
||||
|
||||
/// Per-stage Butterworth Q values — `⌊order/2⌋` entries, computed once at init.
|
||||
public var butterworthQs: [Double] { engine.butterworthQs }
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to filter.
|
||||
/// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist (sampleRate / 2).
|
||||
/// - order: Filter order 1–8 (clamped internally).
|
||||
/// - mul: Output multiplier.
|
||||
/// - add: Output offset.
|
||||
/// - foCoeffs: First-order section coefficient formula `(freq, sr) -> (b0, b1, na1)`.
|
||||
/// - biquadCoeffs: Biquad-stage coefficient formula `(freq, q, sampleRate) -> BiquadCoeffs`.
|
||||
/// - threadName: Name for the background vDSP setup-builder thread.
|
||||
init(
|
||||
input: any ValidGeneratorInput,
|
||||
freq: any ValidGeneratorInput,
|
||||
order: Int,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput,
|
||||
foCoeffs: @escaping (Double, Double) -> (b0: Double, b1: Double, na1: Double),
|
||||
biquadCoeffs: @escaping (Double, Double, Double) -> BiquadCoeffs,
|
||||
threadName: String
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
|
||||
self.inputSource = resolvedInput
|
||||
self.freqInput = resolvedFreq
|
||||
self.freqIsGenerator = resolvedFreq is any Generator
|
||||
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
self.engine = ButterworthSectionEngine(
|
||||
order: order,
|
||||
foCoeffs: foCoeffs,
|
||||
biquadCoeffs: biquadCoeffs,
|
||||
threadName: threadName
|
||||
)
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - Compute
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
guard let inputBlock: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first else {
|
||||
return _result
|
||||
}
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
|
||||
let f0: Double
|
||||
let fN: Double
|
||||
let scalarFreq: Double
|
||||
if freqIsGenerator {
|
||||
let freqSamplesOuter: [[Double]] = freqInput.calculatedSamples(graph: graph, count: count)
|
||||
if let freqSamples: [Double] = freqSamplesOuter.first, !freqSamples.isEmpty {
|
||||
f0 = freqSamples[0]
|
||||
fN = freqSamples[min(freqSamples.count - 1, count - 1)]
|
||||
} else {
|
||||
let fv: Double = freqInput.floatValue(graph: graph)
|
||||
f0 = fv
|
||||
fN = fv
|
||||
}
|
||||
scalarFreq = 0.0
|
||||
} else {
|
||||
scalarFreq = freqInput.floatValue(graph: graph)
|
||||
f0 = 0.0
|
||||
fN = 0.0
|
||||
}
|
||||
|
||||
engine.process(
|
||||
input: inputBlock,
|
||||
freqIsGenerator: freqIsGenerator,
|
||||
scalarFreq: scalarFreq,
|
||||
f0: f0,
|
||||
fN: fN,
|
||||
sr: sr,
|
||||
count: count,
|
||||
into: &_result[0]
|
||||
)
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// ButterworthHelpers.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - Butterworth pole-Q helper
|
||||
|
||||
/// Computes per-stage Butterworth Q values for a filter of the given (already-clamped) order.
|
||||
///
|
||||
/// Returns `⌊order / 2⌋` Q values, one per biquad stage, using the pole formula:
|
||||
/// ```
|
||||
/// Q_k = −1 / (2 · cos(π · (2k + order − 1) / (2 · order))) k = 1 … ⌊order / 2⌋
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter order: Filter order, already clamped to `[1, maxButterworthOrder]`.
|
||||
/// - Returns: Array of Q values, empty when `order == 1` (first-order section only, no biquads).
|
||||
internal func computeButterworthQs(order: Int) -> [Double] {
|
||||
let numBiquads: Int = order / 2
|
||||
guard numBiquads > 0 else { return [] }
|
||||
var qs: [Double] = [Double]()
|
||||
qs.reserveCapacity(numBiquads)
|
||||
let twiceOrder: Double = Double(2 * order)
|
||||
for k: Int in 1...numBiquads {
|
||||
let numerator: Double = Double.pi * Double(2 * k + order - 1)
|
||||
let angle: Double = numerator / twiceOrder
|
||||
qs.append(-1.0 / (2.0 * cos(angle)))
|
||||
}
|
||||
return qs
|
||||
}
|
||||
@@ -4,17 +4,14 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import Foundation
|
||||
|
||||
/// Cascaded Butterworth highpass filter, orders 1–8.
|
||||
///
|
||||
/// Mirror of `ButterworthLowPass` — identical cascade logic; only the per-stage coefficient
|
||||
/// formula differs (RBJ HPF instead of LPF, and the bilinear first-order section is a HPF).
|
||||
///
|
||||
/// ## vDSP acceleration
|
||||
///
|
||||
/// Same Option-B background-thread strategy as `ButterworthLowPass`. See that class for details.
|
||||
/// Mirror of `ButterworthLowPass`: all cascade machinery lives in
|
||||
/// `_ButterworthCascadeBase`; this type injects the highpass coefficient
|
||||
/// formulas — RBJ highpass per biquad stage, and a bilinear first-order highpass
|
||||
/// for odd orders.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
@@ -30,369 +27,34 @@ import Foundation
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public enum ButterworthHighPass {
|
||||
|
||||
public final class Audio: GeneratorBase, AudioGenerator {
|
||||
public final class Audio: _ButterworthCascadeBase {
|
||||
|
||||
private static let bgPollInterval: TimeInterval = 0.001
|
||||
|
||||
private let inputSource: any ValidGeneratorInput
|
||||
private let freqInput: any ValidGeneratorInput
|
||||
private let freqIsGenerator: Bool
|
||||
|
||||
/// Filter order, clamped to `[1, maxButterworthOrder]` at init.
|
||||
public let order: Int
|
||||
|
||||
/// Per-stage Butterworth Q values — `⌊order/2⌋` entries, computed once at init.
|
||||
public let butterworthQs: [Double]
|
||||
|
||||
private var biquadStages: [BiquadState]
|
||||
private var firstOrderState: FirstOrderState?
|
||||
|
||||
private var _scratch: [Double]
|
||||
|
||||
private var cachedBiquadCoeffs: [BiquadCoeffs]
|
||||
private var cachedFO: (b0: Double, b1: Double, na1: Double) = (0, 0, 0)
|
||||
private var prevFreq: Double = -1.0
|
||||
private var prevSampleRate: Double = -1.0
|
||||
private let _mulAdd: MulAddSpec
|
||||
|
||||
// MARK: - vDSP cascade (background-thread Option B, RT-safe)
|
||||
|
||||
private var _vdspSetup: OpaquePointer?
|
||||
private var _vdspDelay: [Double]
|
||||
private let _vdspCoeffQueue: SPSCQueue<BiquadCoeffPacket>
|
||||
private let _vdspRespQueue: SPSCQueue<OpaquePointer>
|
||||
private let _vdspKillQueue: SPSCQueue<OpaquePointer>
|
||||
private let _bgDoneSema: DispatchSemaphore
|
||||
private let _bgSleepSema: DispatchSemaphore
|
||||
private var _vdspThread: Thread?
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to filter.
|
||||
/// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist (sampleRate / 2).
|
||||
/// - order: Filter order 1–8 (clamped internally). Each order adds −6 dB/oct slope. Higher order = steeper rolloff but higher CPU cost. Defaults to `4`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
freq: any ValidGeneratorInput,
|
||||
order: Int,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
|
||||
self.inputSource = resolvedInput
|
||||
self.freqInput = resolvedFreq
|
||||
self.freqIsGenerator = resolvedFreq is any Generator
|
||||
let clampedOrder: Int = min(max(order, 1), maxButterworthOrder)
|
||||
self.order = clampedOrder
|
||||
|
||||
let numBiquads: Int = clampedOrder / 2
|
||||
var qs: [Double] = [Double]()
|
||||
if numBiquads > 0 {
|
||||
for k: Int in 1...numBiquads {
|
||||
let angle: Double = Double.pi * Double(2 * k + clampedOrder - 1)
|
||||
/ Double(2 * clampedOrder)
|
||||
qs.append(-1.0 / (2.0 * cos(angle)))
|
||||
}
|
||||
}
|
||||
self.butterworthQs = qs
|
||||
self.biquadStages = [BiquadState](repeating: BiquadState(), count: numBiquads)
|
||||
self.firstOrderState = clampedOrder % 2 == 1 ? FirstOrderState() : nil
|
||||
self._scratch = makeSampleBuffer()
|
||||
self.cachedBiquadCoeffs = [BiquadCoeffs](repeating: .zero, count: numBiquads)
|
||||
|
||||
self._vdspSetup = nil
|
||||
let biquadDelayStateCount: Int = 2 * (numBiquads + 1)
|
||||
self._vdspDelay = numBiquads > 0
|
||||
? [Double](repeating: 0, count: biquadDelayStateCount)
|
||||
: []
|
||||
self._vdspCoeffQueue = SPSCQueue(capacity: butterworthCoeffQueueCapacity)
|
||||
self._vdspRespQueue = SPSCQueue(capacity: butterworthRespQueueCapacity)
|
||||
self._vdspKillQueue = SPSCQueue(capacity: butterworthKillQueueCapacity)
|
||||
self._bgDoneSema = DispatchSemaphore(value: 0)
|
||||
self._bgSleepSema = DispatchSemaphore(value: 0)
|
||||
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
|
||||
if numBiquads > 0 {
|
||||
let cq: SPSCQueue<BiquadCoeffPacket> = _vdspCoeffQueue
|
||||
let rq: SPSCQueue<OpaquePointer> = _vdspRespQueue
|
||||
let kq: SPSCQueue<OpaquePointer> = _vdspKillQueue
|
||||
let doneSema: DispatchSemaphore = _bgDoneSema
|
||||
let sleepSema: DispatchSemaphore = _bgSleepSema
|
||||
let t: Thread = Thread {
|
||||
var shouldStop: Bool = false
|
||||
while !shouldStop {
|
||||
while let ptr: OpaquePointer = kq.dequeue() {
|
||||
vDSP_biquad_DestroySetupD(ptr)
|
||||
}
|
||||
if let packet: BiquadCoeffPacket = cq.dequeue() {
|
||||
packet.withUnsafeCoeffPtr { ptr in
|
||||
if let setup: vDSP_biquad_SetupD = vDSP_biquad_CreateSetupD(
|
||||
ptr, vDSP_Length(packet.numSections)
|
||||
) {
|
||||
if !rq.enqueue(setup) {
|
||||
vDSP_biquad_DestroySetupD(setup)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if sleepSema.wait(timeout: .now() + Audio.bgPollInterval) == .success { shouldStop = true }
|
||||
}
|
||||
while let ptr: OpaquePointer = kq.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
while let ptr: OpaquePointer = rq.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
doneSema.signal()
|
||||
}
|
||||
t.name = "LyrebirdButterworthHP.vDSP"
|
||||
t.qualityOfService = .userInteractive
|
||||
_vdspThread = t
|
||||
t.start()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Deinit
|
||||
|
||||
deinit {
|
||||
if _vdspThread != nil {
|
||||
_bgSleepSema.signal()
|
||||
_bgDoneSema.wait()
|
||||
}
|
||||
if let setup: OpaquePointer = _vdspSetup {
|
||||
vDSP_biquad_DestroySetupD(setup)
|
||||
}
|
||||
while let ptr: OpaquePointer = _vdspRespQueue.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
while let ptr: OpaquePointer = _vdspKillQueue.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
}
|
||||
|
||||
// MARK: - Generator protocol
|
||||
// MARK: - Compute
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
guard let inputBlock: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first else {
|
||||
return _result
|
||||
}
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
let hasFO: Bool = firstOrderState != nil
|
||||
let totalStages: Int = biquadStages.count + (hasFO ? 1 : 0)
|
||||
|
||||
guard totalStages > 0 else {
|
||||
let n: Int = min(count, inputBlock.count)
|
||||
inputBlock.withUnsafeBufferPointer { srcBuf in
|
||||
_result[0].withUnsafeMutableBufferPointer { dstBuf in
|
||||
guard let srcBase: UnsafePointer<Double> = srcBuf.baseAddress,
|
||||
let dstBase: UnsafeMutablePointer<Double> = dstBuf.baseAddress else { return }
|
||||
if n > 0 { dstBase.update(from: srcBase, count: n) }
|
||||
if n < count {
|
||||
vDSP_vclrD(dstBase + n, 1, vDSP_Length(count - n))
|
||||
}
|
||||
}
|
||||
}
|
||||
return _result
|
||||
}
|
||||
|
||||
if freqIsGenerator {
|
||||
let freqSamplesOuter: [[Double]] = freqInput.calculatedSamples(graph: graph, count: count)
|
||||
let f0: Double
|
||||
let fN: Double
|
||||
if let freqSamples: [Double] = freqSamplesOuter.first, !freqSamples.isEmpty {
|
||||
f0 = freqSamples[0]
|
||||
fN = freqSamples[min(freqSamples.count - 1, count - 1)]
|
||||
} else {
|
||||
f0 = freqInput.floatValue(graph: graph)
|
||||
fN = f0
|
||||
}
|
||||
runAudioRate(input: inputBlock, f0: f0, fN: fN, sr: sr, N: totalStages, count: count)
|
||||
} else {
|
||||
let freq: Double = freqInput.floatValue(graph: graph)
|
||||
if freq != prevFreq || sr != prevSampleRate {
|
||||
recomputeScalarCoeffs(freq: freq, sr: sr)
|
||||
prevFreq = freq; prevSampleRate = sr
|
||||
if !biquadStages.isEmpty {
|
||||
let packet: BiquadCoeffPacket = BiquadCoeffPacket(from: cachedBiquadCoeffs)
|
||||
if !_vdspCoeffQueue.enqueue(packet) {
|
||||
// Queue full — reset sentinels so next block retries.
|
||||
prevFreq = -1.0; prevSampleRate = -1.0
|
||||
}
|
||||
}
|
||||
}
|
||||
if let newSetup: OpaquePointer = _vdspRespQueue.dequeue() {
|
||||
if let old: OpaquePointer = _vdspSetup {
|
||||
if !_vdspKillQueue.enqueue(old) {
|
||||
// Kill queue full (capacity 32, bg thread drains every 1ms).
|
||||
// Emergency same-thread destroy to prevent leak; violates RT-alloc rule
|
||||
// but is unreachable under normal operation.
|
||||
vDSP_biquad_DestroySetupD(old)
|
||||
}
|
||||
}
|
||||
_vdspSetup = newSetup
|
||||
}
|
||||
if let setup: OpaquePointer = _vdspSetup {
|
||||
runVDSP(input: inputBlock, count: count, setup: setup)
|
||||
} else {
|
||||
runScalar(input: inputBlock, N: totalStages, count: count)
|
||||
}
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
// MARK: - Coefficient computation
|
||||
|
||||
private func recomputeScalarCoeffs(
|
||||
freq: Double,
|
||||
sr: Double
|
||||
) {
|
||||
if firstOrderState != nil {
|
||||
cachedFO = foHPCoeffs(freq: freq, sr: sr)
|
||||
}
|
||||
for i: Int in 0..<biquadStages.count {
|
||||
cachedBiquadCoeffs[i] = rbjHighPassCoeffs(freq: freq, q: butterworthQs[i], sampleRate: sr)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - vDSP cascade path
|
||||
|
||||
private func runVDSP(
|
||||
input: [Double],
|
||||
count: Int,
|
||||
setup: OpaquePointer
|
||||
) {
|
||||
if var fo: FirstOrderState = firstOrderState {
|
||||
fo.processBlock(input: input,
|
||||
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
|
||||
into: &_scratch, count: count)
|
||||
firstOrderState = fo
|
||||
_scratch.withUnsafeBufferPointer { inBuf in
|
||||
_result[0].withUnsafeMutableBufferPointer { outBuf in
|
||||
_vdspDelay.withUnsafeMutableBufferPointer { delay in
|
||||
guard let d: UnsafeMutablePointer<Double> = delay.baseAddress, let i: UnsafePointer<Double> = inBuf.baseAddress,
|
||||
let o: UnsafeMutablePointer<Double> = outBuf.baseAddress else { return }
|
||||
vDSP_biquadD(setup, d, i, 1, o, 1, vDSP_Length(count))
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
input.withUnsafeBufferPointer { inBuf in
|
||||
_result[0].withUnsafeMutableBufferPointer { outBuf in
|
||||
_vdspDelay.withUnsafeMutableBufferPointer { delay in
|
||||
guard let d: UnsafeMutablePointer<Double> = delay.baseAddress, let i: UnsafePointer<Double> = inBuf.baseAddress,
|
||||
let o: UnsafeMutablePointer<Double> = outBuf.baseAddress else { return }
|
||||
vDSP_biquadD(setup, d, i, 1, o, 1, vDSP_Length(count))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Scalar cascade path
|
||||
|
||||
private func runScalar(
|
||||
input: [Double],
|
||||
N: Int,
|
||||
count: Int
|
||||
) {
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = firstOrderState {
|
||||
let writesResult: Bool = (N + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input,
|
||||
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input,
|
||||
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
firstOrderState = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<biquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (N + i) % 2 == 1
|
||||
let readsResult: Bool = i > 0 && (N + i) % 2 == 0
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
biquadStages[bi].processBlock(input: input, coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: _scratch, coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &_result[0], count: count)
|
||||
}
|
||||
} else {
|
||||
if readsResult {
|
||||
biquadStages[bi].processBlock(input: _result[0], coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: input, coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func runAudioRate(
|
||||
input: [Double],
|
||||
f0: Double,
|
||||
fN: Double,
|
||||
sr: Double,
|
||||
N: Int,
|
||||
count: Int
|
||||
) {
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = firstOrderState {
|
||||
let s: (b0: Double, b1: Double, na1: Double) = foHPCoeffs(freq: f0, sr: sr)
|
||||
let e: (b0: Double, b1: Double, na1: Double) = foHPCoeffs(freq: fN, sr: sr)
|
||||
let writesResult: Bool = (N + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input,
|
||||
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
|
||||
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input,
|
||||
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
|
||||
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
firstOrderState = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<biquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (N + i) % 2 == 1
|
||||
let readsResult: Bool = i > 0 && (N + i) % 2 == 0
|
||||
let startC: BiquadCoeffs = rbjHighPassCoeffs(freq: f0, q: butterworthQs[bi], sampleRate: sr)
|
||||
let endC: BiquadCoeffs = rbjHighPassCoeffs(freq: fN, q: butterworthQs[bi], sampleRate: sr)
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
biquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: _scratch, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_result[0], count: count)
|
||||
}
|
||||
} else {
|
||||
if readsResult {
|
||||
biquadStages[bi].processBlock(input: _result[0], startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
/// - Parameters:
|
||||
/// - input: Signal to filter.
|
||||
/// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist (sampleRate / 2).
|
||||
/// - order: Filter order 1–8 (clamped internally). Each order adds −6 dB/oct slope. Higher order = steeper rolloff but higher CPU cost. Defaults to `4`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
freq: any ValidGeneratorInput,
|
||||
order: Int,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(
|
||||
input: input,
|
||||
freq: freq,
|
||||
order: order,
|
||||
mul: mul,
|
||||
add: add,
|
||||
foCoeffs: { foHPCoeffs(freq: $0, sr: $1) },
|
||||
biquadCoeffs: { rbjHighPassCoeffs(freq: $0, q: $1, sampleRate: $2) },
|
||||
threadName: "LyrebirdButterworthHP.vDSP"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
} // close enum ButterworthHighPass
|
||||
|
||||
// MARK: - First-order HP coefficient helper
|
||||
|
||||
|
||||
@@ -4,29 +4,14 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import Foundation
|
||||
|
||||
/// Cascaded Butterworth lowpass filter, orders 1–8.
|
||||
///
|
||||
/// Order is fixed at `init`. For even orders the filter is all biquad stages; for odd
|
||||
/// orders a first-order section precedes the biquad cascade. All buffers are pre-allocated —
|
||||
/// no heap allocation occurs on the RT thread.
|
||||
///
|
||||
/// Per-stage Q values are derived at `init` from the Butterworth pole formula:
|
||||
/// ```
|
||||
/// Q_k = −1 / (2 · cos(π · (2k + N − 1) / (2N))) k = 1 … ⌊N/2⌋
|
||||
/// ```
|
||||
/// At block rate the shared `freq` input modulates all stage coefficients simultaneously.
|
||||
/// Audio-rate `freq` uses block-boundary coefficient interpolation independently per stage.
|
||||
///
|
||||
/// ## vDSP acceleration
|
||||
///
|
||||
/// For constant or block-rate `freq` (non-generator), a background thread builds a
|
||||
/// `vDSP_biquad_SetupD` from the current coefficients and delivers it via a lock-free
|
||||
/// `SPSCQueue`. Once the setup arrives the biquad cascade uses `vDSP_biquadD`; the
|
||||
/// first-order section (odd orders) stays scalar. Audio-rate `freq` always uses the
|
||||
/// scalar interpolating path.
|
||||
/// All cascade machinery (per-stage Butterworth Q, scalar / audio-rate-interpolated
|
||||
/// paths, and the background-thread `vDSP_biquad_SetupD` builder) lives in
|
||||
/// `_ButterworthCascadeBase`. This type injects the lowpass coefficient formulas:
|
||||
/// RBJ lowpass per biquad stage, and a bilinear first-order lowpass for odd orders.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
@@ -42,391 +27,34 @@ import Foundation
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public enum ButterworthLowPass {
|
||||
|
||||
public final class Audio: GeneratorBase, AudioGenerator {
|
||||
public final class Audio: _ButterworthCascadeBase {
|
||||
|
||||
private static let bgPollInterval: TimeInterval = 0.001
|
||||
|
||||
private let inputSource: any ValidGeneratorInput
|
||||
private let freqInput: any ValidGeneratorInput
|
||||
private let freqIsGenerator: Bool
|
||||
|
||||
/// Filter order, clamped to `[1, maxButterworthOrder]` at init.
|
||||
public let order: Int
|
||||
|
||||
/// Per-stage Butterworth Q values — `⌊order/2⌋` entries, computed once at init.
|
||||
public let butterworthQs: [Double]
|
||||
|
||||
private var biquadStages: [BiquadState]
|
||||
private var firstOrderState: FirstOrderState?
|
||||
|
||||
private var _scratch: [Double]
|
||||
|
||||
private var cachedBiquadCoeffs: [BiquadCoeffs]
|
||||
private var cachedFO: (b0: Double, b1: Double, na1: Double) = (0, 0, 0)
|
||||
private var prevFreq: Double = -1.0
|
||||
private var prevSampleRate: Double = -1.0
|
||||
private let _mulAdd: MulAddSpec
|
||||
|
||||
// MARK: - vDSP cascade (background-thread Option B, RT-safe)
|
||||
|
||||
// Current live Double biquad setup. nil until background thread delivers first setup.
|
||||
// Only accessed from _computeSamples (RT thread) — no concurrent access.
|
||||
private var _vdspSetup: OpaquePointer?
|
||||
// Delay buffer: 2*(numBiquads+1) Doubles. Pre-allocated; never resized.
|
||||
private var _vdspDelay: [Double]
|
||||
// RT → bg: new coefficient packets to build a setup from.
|
||||
private let _vdspCoeffQueue: SPSCQueue<BiquadCoeffPacket>
|
||||
// bg → RT: newly-built setups ready to swap in.
|
||||
private let _vdspRespQueue: SPSCQueue<OpaquePointer>
|
||||
// RT → bg: old setups to destroy (avoids dealloc on RT thread).
|
||||
private let _vdspKillQueue: SPSCQueue<OpaquePointer>
|
||||
// Signals deinit that the background thread has exited cleanly.
|
||||
private let _bgDoneSema: DispatchSemaphore
|
||||
// Doubles as sleep timer and stop signal: deinit signals it to wake the thread early.
|
||||
// Thread.cancel() / pthread_cancel is NOT used — pthread_cancel kills the thread at
|
||||
// nanosleep (a POSIX cancellation point), bypassing doneSema.signal() and deadlocking
|
||||
// _bgDoneSema.wait() in deinit.
|
||||
private let _bgSleepSema: DispatchSemaphore
|
||||
private var _vdspThread: Thread?
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to filter.
|
||||
/// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist (sampleRate / 2).
|
||||
/// - order: Filter order 1–8 (clamped internally). Each order adds −6 dB/oct slope. Higher order = steeper rolloff but higher CPU cost. Defaults to `4`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
freq: any ValidGeneratorInput,
|
||||
order: Int,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
|
||||
self.inputSource = resolvedInput
|
||||
self.freqInput = resolvedFreq
|
||||
self.freqIsGenerator = resolvedFreq is any Generator
|
||||
let clampedOrder: Int = min(max(order, 1), maxButterworthOrder)
|
||||
self.order = clampedOrder
|
||||
|
||||
let numBiquads: Int = clampedOrder / 2
|
||||
var qs: [Double] = [Double]()
|
||||
if numBiquads > 0 {
|
||||
for k: Int in 1...numBiquads {
|
||||
let angle: Double = Double.pi * Double(2 * k + clampedOrder - 1)
|
||||
/ Double(2 * clampedOrder)
|
||||
qs.append(-1.0 / (2.0 * cos(angle)))
|
||||
}
|
||||
}
|
||||
self.butterworthQs = qs
|
||||
self.biquadStages = [BiquadState](repeating: BiquadState(), count: numBiquads)
|
||||
self.firstOrderState = clampedOrder % 2 == 1 ? FirstOrderState() : nil
|
||||
self._scratch = makeSampleBuffer()
|
||||
self.cachedBiquadCoeffs = [BiquadCoeffs](repeating: .zero, count: numBiquads)
|
||||
|
||||
self._vdspSetup = nil
|
||||
let biquadDelayStateCount: Int = 2 * (numBiquads + 1)
|
||||
self._vdspDelay = numBiquads > 0
|
||||
? [Double](repeating: 0, count: biquadDelayStateCount)
|
||||
: []
|
||||
self._vdspCoeffQueue = SPSCQueue(capacity: butterworthCoeffQueueCapacity)
|
||||
self._vdspRespQueue = SPSCQueue(capacity: butterworthRespQueueCapacity)
|
||||
self._vdspKillQueue = SPSCQueue(capacity: butterworthKillQueueCapacity)
|
||||
self._bgDoneSema = DispatchSemaphore(value: 0)
|
||||
self._bgSleepSema = DispatchSemaphore(value: 0)
|
||||
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
|
||||
// Start background setup thread only when there are biquad sections (order >= 2).
|
||||
if numBiquads > 0 {
|
||||
let cq: SPSCQueue<BiquadCoeffPacket> = _vdspCoeffQueue
|
||||
let rq: SPSCQueue<OpaquePointer> = _vdspRespQueue
|
||||
let kq: SPSCQueue<OpaquePointer> = _vdspKillQueue
|
||||
let doneSema: DispatchSemaphore = _bgDoneSema
|
||||
let sleepSema: DispatchSemaphore = _bgSleepSema
|
||||
let t: Thread = Thread {
|
||||
var shouldStop: Bool = false
|
||||
while !shouldStop {
|
||||
while let ptr: OpaquePointer = kq.dequeue() {
|
||||
vDSP_biquad_DestroySetupD(ptr)
|
||||
}
|
||||
if let packet: BiquadCoeffPacket = cq.dequeue() {
|
||||
packet.withUnsafeCoeffPtr { ptr in
|
||||
if let setup: vDSP_biquad_SetupD = vDSP_biquad_CreateSetupD(
|
||||
ptr, vDSP_Length(packet.numSections)
|
||||
) {
|
||||
if !rq.enqueue(setup) {
|
||||
vDSP_biquad_DestroySetupD(setup)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// .success = woken early by deinit (stop signal); .timedOut = normal poll.
|
||||
if sleepSema.wait(timeout: .now() + Audio.bgPollInterval) == .success { shouldStop = true }
|
||||
}
|
||||
// Drain queues on exit so deinit can safely claim ownership.
|
||||
while let ptr: OpaquePointer = kq.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
while let ptr: OpaquePointer = rq.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
doneSema.signal()
|
||||
}
|
||||
t.name = "LyrebirdButterworthLP.vDSP"
|
||||
t.qualityOfService = .userInteractive
|
||||
_vdspThread = t
|
||||
t.start()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Deinit
|
||||
|
||||
deinit {
|
||||
if _vdspThread != nil {
|
||||
_bgSleepSema.signal() // wake thread from its 1ms sleep, stop signal
|
||||
_bgDoneSema.wait() // wait for thread to drain queues and exit
|
||||
}
|
||||
if let setup: OpaquePointer = _vdspSetup {
|
||||
vDSP_biquad_DestroySetupD(setup)
|
||||
}
|
||||
// Thread drained these on exit; drain again as safety (no-ops when already empty).
|
||||
while let ptr: OpaquePointer = _vdspRespQueue.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
while let ptr: OpaquePointer = _vdspKillQueue.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
}
|
||||
|
||||
// MARK: - Generator protocol
|
||||
// MARK: - Compute
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
guard let inputBlock: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first else {
|
||||
return _result
|
||||
}
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
let hasFO: Bool = firstOrderState != nil
|
||||
let totalStages: Int = biquadStages.count + (hasFO ? 1 : 0)
|
||||
|
||||
guard totalStages > 0 else {
|
||||
let n: Int = min(count, inputBlock.count)
|
||||
inputBlock.withUnsafeBufferPointer { srcBuf in
|
||||
_result[0].withUnsafeMutableBufferPointer { dstBuf in
|
||||
guard let srcBase: UnsafePointer<Double> = srcBuf.baseAddress,
|
||||
let dstBase: UnsafeMutablePointer<Double> = dstBuf.baseAddress else { return }
|
||||
if n > 0 { dstBase.update(from: srcBase, count: n) }
|
||||
if n < count {
|
||||
vDSP_vclrD(dstBase + n, 1, vDSP_Length(count - n))
|
||||
}
|
||||
}
|
||||
}
|
||||
return _result
|
||||
}
|
||||
|
||||
if freqIsGenerator {
|
||||
let freqSamplesOuter: [[Double]] = freqInput.calculatedSamples(graph: graph, count: count)
|
||||
let f0: Double
|
||||
let fN: Double
|
||||
if let freqSamples: [Double] = freqSamplesOuter.first, !freqSamples.isEmpty {
|
||||
f0 = freqSamples[0]
|
||||
fN = freqSamples[min(freqSamples.count - 1, count - 1)]
|
||||
} else {
|
||||
f0 = freqInput.floatValue(graph: graph)
|
||||
fN = f0
|
||||
}
|
||||
runAudioRate(input: inputBlock, f0: f0, fN: fN, sr: sr, N: totalStages, count: count)
|
||||
} else {
|
||||
let freq: Double = freqInput.floatValue(graph: graph)
|
||||
if freq != prevFreq || sr != prevSampleRate {
|
||||
recomputeScalarCoeffs(freq: freq, sr: sr)
|
||||
prevFreq = freq; prevSampleRate = sr
|
||||
if !biquadStages.isEmpty {
|
||||
let packet: BiquadCoeffPacket = BiquadCoeffPacket(from: cachedBiquadCoeffs)
|
||||
if !_vdspCoeffQueue.enqueue(packet) {
|
||||
// Queue full — reset sentinels so next block retries.
|
||||
prevFreq = -1.0; prevSampleRate = -1.0
|
||||
}
|
||||
}
|
||||
}
|
||||
// Swap in any new setup the background thread prepared.
|
||||
if let newSetup: OpaquePointer = _vdspRespQueue.dequeue() {
|
||||
if let old: OpaquePointer = _vdspSetup {
|
||||
if !_vdspKillQueue.enqueue(old) {
|
||||
// Kill queue full (capacity 32, bg thread drains every 1ms).
|
||||
// Emergency same-thread destroy to prevent leak; violates RT-alloc rule
|
||||
// but is unreachable under normal operation.
|
||||
vDSP_biquad_DestroySetupD(old)
|
||||
}
|
||||
}
|
||||
_vdspSetup = newSetup
|
||||
}
|
||||
if let setup: OpaquePointer = _vdspSetup {
|
||||
runVDSP(input: inputBlock, count: count, setup: setup)
|
||||
} else {
|
||||
runScalar(input: inputBlock, N: totalStages, count: count)
|
||||
}
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
// MARK: - Coefficient computation
|
||||
|
||||
private func recomputeScalarCoeffs(
|
||||
freq: Double,
|
||||
sr: Double
|
||||
) {
|
||||
if firstOrderState != nil {
|
||||
cachedFO = foLPCoeffs(freq: freq, sr: sr)
|
||||
}
|
||||
for i: Int in 0..<biquadStages.count {
|
||||
cachedBiquadCoeffs[i] = rbjLowPassCoeffs(freq: freq, q: butterworthQs[i], sampleRate: sr)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - vDSP cascade path
|
||||
|
||||
/// Runs the biquad cascade via `vDSP_biquadD`. For odd orders, the first-order section
|
||||
/// runs scalar first (into `_scratch`); the biquad cascade then reads from `_scratch`.
|
||||
private func runVDSP(
|
||||
input: [Double],
|
||||
count: Int,
|
||||
setup: OpaquePointer
|
||||
) {
|
||||
if var fo: FirstOrderState = firstOrderState {
|
||||
fo.processBlock(input: input,
|
||||
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
|
||||
into: &_scratch, count: count)
|
||||
firstOrderState = fo
|
||||
_scratch.withUnsafeBufferPointer { inBuf in
|
||||
_result[0].withUnsafeMutableBufferPointer { outBuf in
|
||||
_vdspDelay.withUnsafeMutableBufferPointer { delay in
|
||||
guard let d: UnsafeMutablePointer<Double> = delay.baseAddress, let i: UnsafePointer<Double> = inBuf.baseAddress,
|
||||
let o: UnsafeMutablePointer<Double> = outBuf.baseAddress else { return }
|
||||
vDSP_biquadD(setup, d, i, 1, o, 1, vDSP_Length(count))
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
input.withUnsafeBufferPointer { inBuf in
|
||||
_result[0].withUnsafeMutableBufferPointer { outBuf in
|
||||
_vdspDelay.withUnsafeMutableBufferPointer { delay in
|
||||
guard let d: UnsafeMutablePointer<Double> = delay.baseAddress, let i: UnsafePointer<Double> = inBuf.baseAddress,
|
||||
let o: UnsafeMutablePointer<Double> = outBuf.baseAddress else { return }
|
||||
vDSP_biquadD(setup, d, i, 1, o, 1, vDSP_Length(count))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Scalar cascade path
|
||||
|
||||
/// Buffer routing rule: stage `i` of `N` total writes to `_result[0]` when
|
||||
/// `(N + i) % 2 == 1`, otherwise writes to `_scratch`.
|
||||
/// When `i > 0` and writes to `_result[0]`, it reads from `_scratch` and vice versa.
|
||||
|
||||
private func runScalar(
|
||||
input: [Double],
|
||||
N: Int,
|
||||
count: Int
|
||||
) {
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = firstOrderState {
|
||||
let writesResult: Bool = (N + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input,
|
||||
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input,
|
||||
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
firstOrderState = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<biquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (N + i) % 2 == 1
|
||||
let readsResult: Bool = i > 0 && (N + i) % 2 == 0
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
biquadStages[bi].processBlock(input: input, coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: _scratch, coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &_result[0], count: count)
|
||||
}
|
||||
} else {
|
||||
if readsResult {
|
||||
biquadStages[bi].processBlock(input: _result[0], coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: input, coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func runAudioRate(
|
||||
input: [Double],
|
||||
f0: Double,
|
||||
fN: Double,
|
||||
sr: Double,
|
||||
N: Int,
|
||||
count: Int
|
||||
) {
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = firstOrderState {
|
||||
let s: (b0: Double, b1: Double, na1: Double) = foLPCoeffs(freq: f0, sr: sr)
|
||||
let e: (b0: Double, b1: Double, na1: Double) = foLPCoeffs(freq: fN, sr: sr)
|
||||
let writesResult: Bool = (N + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input,
|
||||
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
|
||||
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input,
|
||||
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
|
||||
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
firstOrderState = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<biquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (N + i) % 2 == 1
|
||||
let readsResult: Bool = i > 0 && (N + i) % 2 == 0
|
||||
let startC: BiquadCoeffs = rbjLowPassCoeffs(freq: f0, q: butterworthQs[bi], sampleRate: sr)
|
||||
let endC: BiquadCoeffs = rbjLowPassCoeffs(freq: fN, q: butterworthQs[bi], sampleRate: sr)
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
biquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: _scratch, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_result[0], count: count)
|
||||
}
|
||||
} else {
|
||||
if readsResult {
|
||||
biquadStages[bi].processBlock(input: _result[0], startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
/// - Parameters:
|
||||
/// - input: Signal to filter.
|
||||
/// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist (sampleRate / 2).
|
||||
/// - order: Filter order 1–8 (clamped internally). Each order adds −6 dB/oct slope. Higher order = steeper rolloff but higher CPU cost. Defaults to `4`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
freq: any ValidGeneratorInput,
|
||||
order: Int,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(
|
||||
input: input,
|
||||
freq: freq,
|
||||
order: order,
|
||||
mul: mul,
|
||||
add: add,
|
||||
foCoeffs: { foLPCoeffs(freq: $0, sr: $1) },
|
||||
biquadCoeffs: { rbjLowPassCoeffs(freq: $0, q: $1, sampleRate: $2) },
|
||||
threadName: "LyrebirdButterworthLP.vDSP"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
} // close enum ButterworthLowPass
|
||||
|
||||
// MARK: - First-order LP coefficient helper
|
||||
|
||||
|
||||
@@ -0,0 +1,409 @@
|
||||
// ButterworthSectionEngine.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import Foundation
|
||||
|
||||
/// Internal cascade engine for a single Butterworth LP or HP section.
|
||||
///
|
||||
/// Encapsulates all single-cascade machinery: biquad stages, optional first-order
|
||||
/// state, cached coefficients, scratch buffer, and the background-thread
|
||||
/// `vDSP_biquad_SetupD` builder (SPSC queues + semaphore deinit handshake).
|
||||
/// Coefficient formulas are injected via two stored closures and a thread name.
|
||||
///
|
||||
/// This class is NOT a `Generator`. It is a shared computation engine owned by
|
||||
/// `_ButterworthCascadeBase` (one engine, LP/HP), `ButterworthBandPass.Audio`
|
||||
/// (two engines in series), and `ButterworthBandReject.Audio` (two engines in
|
||||
/// parallel, summed). All buffer writes go into the caller-supplied `output`
|
||||
/// inout slice — no internal `_result` allocation.
|
||||
///
|
||||
/// Order is fixed at `init`. For even orders the filter is all biquad stages;
|
||||
/// for odd orders a first-order section precedes the biquad cascade. All buffers
|
||||
/// are pre-allocated — no heap allocation occurs on the RT thread.
|
||||
///
|
||||
/// ## vDSP acceleration
|
||||
/// For constant or block-rate `freq` (non-generator), a background thread builds
|
||||
/// a `vDSP_biquad_SetupD` from the current coefficients and delivers it via a
|
||||
/// lock-free `SPSCQueue`. Once the setup arrives the biquad cascade uses
|
||||
/// `vDSP_biquadD`; the first-order section (odd orders) stays scalar. Audio-rate
|
||||
/// `freq` always uses the scalar interpolating path.
|
||||
final class ButterworthSectionEngine {
|
||||
|
||||
private static let bgPollInterval: TimeInterval = 0.001
|
||||
|
||||
/// Filter order, clamped to `[1, maxButterworthOrder]` at init.
|
||||
let order: Int
|
||||
|
||||
/// Per-stage Butterworth Q values — `⌊order/2⌋` entries, computed once at init.
|
||||
let butterworthQs: [Double]
|
||||
|
||||
private var biquadStages: [BiquadState]
|
||||
private var firstOrderState: FirstOrderState?
|
||||
|
||||
private var scratch: [Double]
|
||||
|
||||
private var cachedBiquadCoeffs: [BiquadCoeffs]
|
||||
private var cachedFO: (b0: Double, b1: Double, na1: Double) = (0, 0, 0)
|
||||
private var prevFreq: Double = -1.0
|
||||
private var prevSampleRate: Double = -1.0
|
||||
|
||||
/// First-order section coefficients for a cutoff `freq` at sample rate `sr`.
|
||||
private let foCoeffs: (Double, Double) -> (b0: Double, b1: Double, na1: Double)
|
||||
/// Biquad-stage coefficients for `(freq, q, sampleRate)`.
|
||||
private let biquadCoeffsFunc: (Double, Double, Double) -> BiquadCoeffs
|
||||
|
||||
// MARK: - vDSP cascade (background-thread RT-safe)
|
||||
|
||||
// Current live Double biquad setup. nil until background thread delivers first setup.
|
||||
// Only accessed from process(...) (RT thread) — no concurrent access.
|
||||
private var vdspSetup: OpaquePointer?
|
||||
// Delay buffer: 2*(numBiquads+1) Doubles. Pre-allocated; never resized.
|
||||
private var vdspDelay: [Double]
|
||||
// RT → bg: new coefficient packets to build a setup from.
|
||||
private let vdspCoeffQueue: SPSCQueue<BiquadCoeffPacket>
|
||||
// bg → RT: newly-built setups ready to swap in.
|
||||
private let vdspRespQueue: SPSCQueue<OpaquePointer>
|
||||
// RT → bg: old setups to destroy (avoids dealloc on RT thread).
|
||||
private let vdspKillQueue: SPSCQueue<OpaquePointer>
|
||||
// Signals deinit that the background thread has exited cleanly.
|
||||
private let bgDoneSema: DispatchSemaphore
|
||||
// Doubles as sleep timer and stop signal: deinit signals it to wake the thread early.
|
||||
// Thread.cancel() / pthread_cancel is NOT used — pthread_cancel kills the thread at
|
||||
// nanosleep (a POSIX cancellation point), bypassing doneSema.signal() and deadlocking
|
||||
// bgDoneSema.wait() in deinit.
|
||||
private let bgSleepSema: DispatchSemaphore
|
||||
private var vdspThread: Thread?
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a single-cascade Butterworth section engine.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - order: Filter order 1–8 (clamped internally).
|
||||
/// - foCoeffs: First-order section coefficient formula `(freq, sr) -> (b0, b1, na1)`.
|
||||
/// - biquadCoeffs: Biquad-stage coefficient formula `(freq, q, sampleRate) -> BiquadCoeffs`.
|
||||
/// - threadName: Name for the background vDSP setup-builder thread.
|
||||
init(
|
||||
order: Int,
|
||||
foCoeffs: @escaping (Double, Double) -> (b0: Double, b1: Double, na1: Double),
|
||||
biquadCoeffs: @escaping (Double, Double, Double) -> BiquadCoeffs,
|
||||
threadName: String
|
||||
) {
|
||||
let clampedOrder: Int = min(max(order, 1), maxButterworthOrder)
|
||||
self.order = clampedOrder
|
||||
self.foCoeffs = foCoeffs
|
||||
self.biquadCoeffsFunc = biquadCoeffs
|
||||
|
||||
let numBiquads: Int = clampedOrder / 2
|
||||
self.butterworthQs = computeButterworthQs(order: clampedOrder)
|
||||
self.biquadStages = [BiquadState](repeating: BiquadState(), count: numBiquads)
|
||||
self.firstOrderState = clampedOrder % 2 == 1 ? FirstOrderState() : nil
|
||||
self.scratch = makeSampleBuffer()
|
||||
self.cachedBiquadCoeffs = [BiquadCoeffs](repeating: .zero, count: numBiquads)
|
||||
|
||||
self.vdspSetup = nil
|
||||
let biquadDelayStateCount: Int = 2 * (numBiquads + 1)
|
||||
self.vdspDelay = numBiquads > 0
|
||||
? [Double](repeating: 0, count: biquadDelayStateCount)
|
||||
: []
|
||||
self.vdspCoeffQueue = SPSCQueue(capacity: butterworthCoeffQueueCapacity)
|
||||
self.vdspRespQueue = SPSCQueue(capacity: butterworthRespQueueCapacity)
|
||||
self.vdspKillQueue = SPSCQueue(capacity: butterworthKillQueueCapacity)
|
||||
self.bgDoneSema = DispatchSemaphore(value: 0)
|
||||
self.bgSleepSema = DispatchSemaphore(value: 0)
|
||||
|
||||
// Start background setup thread only when there are biquad sections (order >= 2).
|
||||
if numBiquads > 0 {
|
||||
let cq: SPSCQueue<BiquadCoeffPacket> = vdspCoeffQueue
|
||||
let rq: SPSCQueue<OpaquePointer> = vdspRespQueue
|
||||
let kq: SPSCQueue<OpaquePointer> = vdspKillQueue
|
||||
let doneSema: DispatchSemaphore = bgDoneSema
|
||||
let sleepSema: DispatchSemaphore = bgSleepSema
|
||||
let pollInterval: TimeInterval = ButterworthSectionEngine.bgPollInterval
|
||||
let t: Thread = Thread {
|
||||
var shouldStop: Bool = false
|
||||
while !shouldStop {
|
||||
while let ptr: OpaquePointer = kq.dequeue() {
|
||||
vDSP_biquad_DestroySetupD(ptr)
|
||||
}
|
||||
if let packet: BiquadCoeffPacket = cq.dequeue() {
|
||||
packet.withUnsafeCoeffPtr { ptr in
|
||||
if let setup: vDSP_biquad_SetupD = vDSP_biquad_CreateSetupD(
|
||||
ptr, vDSP_Length(packet.numSections)
|
||||
) {
|
||||
if !rq.enqueue(setup) {
|
||||
vDSP_biquad_DestroySetupD(setup)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// .success = woken early by deinit (stop signal); .timedOut = normal poll.
|
||||
if sleepSema.wait(timeout: .now() + pollInterval) == .success { shouldStop = true }
|
||||
}
|
||||
// Drain queues on exit so deinit can safely claim ownership.
|
||||
while let ptr: OpaquePointer = kq.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
while let ptr: OpaquePointer = rq.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
doneSema.signal()
|
||||
}
|
||||
t.name = threadName
|
||||
t.qualityOfService = .userInteractive
|
||||
vdspThread = t
|
||||
t.start()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Deinit
|
||||
|
||||
deinit {
|
||||
if vdspThread != nil {
|
||||
bgSleepSema.signal() // wake thread from its 1ms sleep, stop signal
|
||||
bgDoneSema.wait() // wait for thread to drain queues and exit
|
||||
}
|
||||
if let setup: OpaquePointer = vdspSetup {
|
||||
vDSP_biquad_DestroySetupD(setup)
|
||||
}
|
||||
// Thread drained these on exit; drain again as safety (no-ops when already empty).
|
||||
while let ptr: OpaquePointer = vdspRespQueue.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
while let ptr: OpaquePointer = vdspKillQueue.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
}
|
||||
|
||||
// MARK: - Process
|
||||
|
||||
/// Runs one block of the cascade, writing results into `output`.
|
||||
///
|
||||
/// This method is the RT-safe per-block entry point. It selects the correct
|
||||
/// path (vDSP accelerated, scalar, or audio-rate interpolated) based on
|
||||
/// `freqIsGenerator` and the current coefficient cache state.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Input sample block. Must have at least `count` elements.
|
||||
/// - freqIsGenerator: `true` when `freq` was classified as a `Generator` at init time.
|
||||
/// - scalarFreq: Scalar frequency value (used when `freqIsGenerator == false`).
|
||||
/// - f0: Frequency at the start of this block (used when `freqIsGenerator == true`).
|
||||
/// - fN: Frequency at the end of this block (used when `freqIsGenerator == true`).
|
||||
/// - sr: Current sample rate in Hz.
|
||||
/// - count: Number of samples to process.
|
||||
/// - output: Destination buffer. Must have at least `count` writable elements.
|
||||
func process(
|
||||
input: [Double],
|
||||
freqIsGenerator: Bool,
|
||||
scalarFreq: Double,
|
||||
f0: Double,
|
||||
fN: Double,
|
||||
sr: Double,
|
||||
count: Int,
|
||||
into output: inout [Double]
|
||||
) {
|
||||
let hasFO: Bool = firstOrderState != nil
|
||||
let totalStages: Int = biquadStages.count + (hasFO ? 1 : 0)
|
||||
|
||||
guard totalStages > 0 else {
|
||||
let n: Int = min(count, input.count)
|
||||
input.withUnsafeBufferPointer { srcBuf in
|
||||
output.withUnsafeMutableBufferPointer { dstBuf in
|
||||
guard let srcBase: UnsafePointer<Double> = srcBuf.baseAddress,
|
||||
let dstBase: UnsafeMutablePointer<Double> = dstBuf.baseAddress else { return }
|
||||
if n > 0 { dstBase.update(from: srcBase, count: n) }
|
||||
if n < count {
|
||||
vDSP_vclrD(dstBase + n, 1, vDSP_Length(count - n))
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if freqIsGenerator {
|
||||
runAudioRate(input: input, f0: f0, fN: fN, sr: sr, N: totalStages,
|
||||
count: count, into: &output)
|
||||
} else {
|
||||
if scalarFreq != prevFreq || sr != prevSampleRate {
|
||||
recomputeScalarCoeffs(freq: scalarFreq, sr: sr)
|
||||
prevFreq = scalarFreq; prevSampleRate = sr
|
||||
if !biquadStages.isEmpty {
|
||||
let packet: BiquadCoeffPacket = BiquadCoeffPacket(from: cachedBiquadCoeffs)
|
||||
if !vdspCoeffQueue.enqueue(packet) {
|
||||
// Queue full — reset sentinels so next block retries.
|
||||
prevFreq = -1.0; prevSampleRate = -1.0
|
||||
}
|
||||
}
|
||||
}
|
||||
// Swap in any new setup the background thread prepared.
|
||||
if let newSetup: OpaquePointer = vdspRespQueue.dequeue() {
|
||||
if let old: OpaquePointer = vdspSetup {
|
||||
if !vdspKillQueue.enqueue(old) {
|
||||
// Kill queue full (capacity 32, bg thread drains every 1ms).
|
||||
// Emergency same-thread destroy to prevent leak; violates RT-alloc rule
|
||||
// but is unreachable under normal operation.
|
||||
vDSP_biquad_DestroySetupD(old)
|
||||
}
|
||||
}
|
||||
vdspSetup = newSetup
|
||||
}
|
||||
if let setup: OpaquePointer = vdspSetup {
|
||||
runVDSP(input: input, count: count, setup: setup, into: &output)
|
||||
} else {
|
||||
runScalar(input: input, N: totalStages, count: count, into: &output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Coefficient computation
|
||||
|
||||
private func recomputeScalarCoeffs(
|
||||
freq: Double,
|
||||
sr: Double
|
||||
) {
|
||||
if firstOrderState != nil {
|
||||
cachedFO = foCoeffs(freq, sr)
|
||||
}
|
||||
for i: Int in 0..<biquadStages.count {
|
||||
cachedBiquadCoeffs[i] = biquadCoeffsFunc(freq, butterworthQs[i], sr)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - vDSP cascade path
|
||||
|
||||
/// Runs the biquad cascade via `vDSP_biquadD`. For odd orders, the first-order section
|
||||
/// runs scalar first (into `scratch`); the biquad cascade then reads from `scratch`.
|
||||
private func runVDSP(
|
||||
input: [Double],
|
||||
count: Int,
|
||||
setup: OpaquePointer,
|
||||
into output: inout [Double]
|
||||
) {
|
||||
if var fo: FirstOrderState = firstOrderState {
|
||||
fo.processBlock(input: input,
|
||||
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
|
||||
into: &scratch, count: count)
|
||||
firstOrderState = fo
|
||||
scratch.withUnsafeBufferPointer { inBuf in
|
||||
output.withUnsafeMutableBufferPointer { outBuf in
|
||||
vdspDelay.withUnsafeMutableBufferPointer { delay in
|
||||
guard let d: UnsafeMutablePointer<Double> = delay.baseAddress,
|
||||
let i: UnsafePointer<Double> = inBuf.baseAddress,
|
||||
let o: UnsafeMutablePointer<Double> = outBuf.baseAddress else { return }
|
||||
vDSP_biquadD(setup, d, i, 1, o, 1, vDSP_Length(count))
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
input.withUnsafeBufferPointer { inBuf in
|
||||
output.withUnsafeMutableBufferPointer { outBuf in
|
||||
vdspDelay.withUnsafeMutableBufferPointer { delay in
|
||||
guard let d: UnsafeMutablePointer<Double> = delay.baseAddress,
|
||||
let i: UnsafePointer<Double> = inBuf.baseAddress,
|
||||
let o: UnsafeMutablePointer<Double> = outBuf.baseAddress else { return }
|
||||
vDSP_biquadD(setup, d, i, 1, o, 1, vDSP_Length(count))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Scalar cascade path
|
||||
|
||||
/// Buffer routing rule: stage `i` of `N` total writes to `output` when
|
||||
/// `(N + i) % 2 == 1`, otherwise writes to `scratch`.
|
||||
/// When `i > 0` and writes to `output`, it reads from `scratch` and vice versa.
|
||||
private func runScalar(
|
||||
input: [Double],
|
||||
N: Int,
|
||||
count: Int,
|
||||
into output: inout [Double]
|
||||
) {
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = firstOrderState {
|
||||
let writesResult: Bool = (N + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input,
|
||||
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
|
||||
into: &output, count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input,
|
||||
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
|
||||
into: &scratch, count: count)
|
||||
}
|
||||
firstOrderState = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<biquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (N + i) % 2 == 1
|
||||
let readsResult: Bool = i > 0 && (N + i) % 2 == 0
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
biquadStages[bi].processBlock(input: input, coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &output, count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: scratch, coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &output, count: count)
|
||||
}
|
||||
} else {
|
||||
if readsResult {
|
||||
biquadStages[bi].processBlock(input: output, coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &scratch, count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: input, coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func runAudioRate(
|
||||
input: [Double],
|
||||
f0: Double,
|
||||
fN: Double,
|
||||
sr: Double,
|
||||
N: Int,
|
||||
count: Int,
|
||||
into output: inout [Double]
|
||||
) {
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = firstOrderState {
|
||||
let s: (b0: Double, b1: Double, na1: Double) = foCoeffs(f0, sr)
|
||||
let e: (b0: Double, b1: Double, na1: Double) = foCoeffs(fN, sr)
|
||||
let writesResult: Bool = (N + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input,
|
||||
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
|
||||
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
|
||||
into: &output, count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input,
|
||||
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
|
||||
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
|
||||
into: &scratch, count: count)
|
||||
}
|
||||
firstOrderState = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<biquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (N + i) % 2 == 1
|
||||
let readsResult: Bool = i > 0 && (N + i) % 2 == 0
|
||||
let startC: BiquadCoeffs = biquadCoeffsFunc(f0, butterworthQs[bi], sr)
|
||||
let endC: BiquadCoeffs = biquadCoeffsFunc(fN, butterworthQs[bi], sr)
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
biquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &output, count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: scratch, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &output, count: count)
|
||||
}
|
||||
} else {
|
||||
if readsResult {
|
||||
biquadStages[bi].processBlock(input: output, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &scratch, count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -81,7 +81,7 @@ public final class CombFilter: GeneratorBase, AudioGenerator {
|
||||
self.interpolation = interpolation
|
||||
|
||||
let maxSamples: Int = Int(ceil(maxDelay * sampleRate)) + 1
|
||||
let bufSize: Int = Self.nextPowerOf2(max(maxSamples, 2))
|
||||
let bufSize: Int = lyrebirdNextPowerOfTwo(max(maxSamples, 2))
|
||||
self.buffer = [Double](repeating: 0, count: bufSize)
|
||||
self.bufferMask = bufSize - 1
|
||||
self.maxDelaySamples = maxSamples - 1
|
||||
@@ -231,31 +231,16 @@ public final class CombFilter: GeneratorBase, AudioGenerator {
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
private static func nextPowerOf2(_ n: Int) -> Int {
|
||||
guard n > 1 else { return 1 }
|
||||
var r: Int = 1
|
||||
while r < n { r <<= 1 }
|
||||
return r
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Catmull-Rom cubic interpolation (local copy, avoids cross-file dependency)
|
||||
// MARK: - Catmull-Rom cubic interpolation (delegates to shared catmullRomCubic)
|
||||
|
||||
private func cubicInterp(
|
||||
frac: Double,
|
||||
y0: Double, y1: Double,
|
||||
y2: Double, y3: Double
|
||||
) -> Double {
|
||||
let half: Double = 0.5
|
||||
let a3: Double = 1.5
|
||||
let b2: Double = 2.5
|
||||
let c2: Double = 2.0
|
||||
let a: Double = -half * y0 + a3 * y1 - a3 * y2 + half * y3
|
||||
let b: Double = y0 - b2 * y1 + c2 * y2 - half * y3
|
||||
let c: Double = -half * y0 + half * y2
|
||||
let d: Double = y1
|
||||
return ((a * frac + b) * frac + c) * frac + d
|
||||
catmullRomCubic(y0, y1, y2, y3, t: frac)
|
||||
}
|
||||
|
||||
// `combFeedbackCoeff` and the underlying `lyrebirdLog60dBLn` constant live in
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
// Formlet.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
|
||||
/// FOF-like resonant filter parameterised by attack and decay times.
|
||||
///
|
||||
/// The impulse response is a sine wave at `freq` enveloped by a rise-then-fall
|
||||
/// (Decay2-style) shape — short `attackTime` followed by longer `decayTime`.
|
||||
/// Equivalent to the difference of two `ResonatingFilter` (Ringz) outputs sharing
|
||||
/// the same `freq`:
|
||||
///
|
||||
/// ```
|
||||
/// Formlet(in, freq, attack, decay)
|
||||
/// == ResonatingFilter(in, freq, decay) − ResonatingFilter(in, freq, attack)
|
||||
/// ```
|
||||
///
|
||||
/// Each Ringz uses the frequency-independent decay coefficient
|
||||
/// `R = exp(log(0.001) / (time · sr))` (−60 dB after `time` seconds) and the
|
||||
/// Direct Form I recurrence `y[n] = (1 − R)·x[n] − na1·y[n−1] − na2·y[n−2]`.
|
||||
/// Subtracting the short-time (attack) response from the long-time (decay)
|
||||
/// response yields the characteristic formant grain. Classic vowel / formant
|
||||
/// synthesis when several Formlets at different `freq` excite a common source.
|
||||
///
|
||||
/// `freq`, `attackTime`, and `decayTime` all accept generator inputs. In `Audio`,
|
||||
/// when any is a generator, block-boundary coefficient interpolation is applied
|
||||
/// across both resonator coefficient sets (same scheme as `ResonatingFilter`);
|
||||
/// `Control` reads each input once per block (no interpolation).
|
||||
/// `denormalsToZero()` is applied to all four feedback state variables each block.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
/// Formlet.Audio(input: impulse, freq: 880.0, attackTime: 0.001, decayTime: 0.1)
|
||||
/// Formlet.Control(input: trig, freq: 220.0, attackTime: 0.01, decayTime: 0.5)
|
||||
/// ```
|
||||
public enum Formlet {
|
||||
|
||||
// MARK: - _Base
|
||||
|
||||
/// Shared stored state for `Formlet.Audio` and `Formlet.Control`.
|
||||
public class _Base: GeneratorBase {
|
||||
let inputSource: any ValidGeneratorInput
|
||||
let freqInput: any ValidGeneratorInput
|
||||
let attackTimeInput: any ValidGeneratorInput
|
||||
let decayTimeInput: any ValidGeneratorInput
|
||||
let freqIsGenerator: Bool
|
||||
let attackTimeIsGenerator: Bool
|
||||
let decayTimeIsGenerator: Bool
|
||||
let anyCoeffIsGenerator: Bool
|
||||
var _mulAdd: MulAddSpec
|
||||
|
||||
// Decay (long-time) resonator state.
|
||||
var yDecay1: Double = 0.0
|
||||
var yDecay2: Double = 0.0
|
||||
// Attack (short-time) resonator state.
|
||||
var yAttack1: Double = 0.0
|
||||
var yAttack2: Double = 0.0
|
||||
|
||||
init(
|
||||
input: any ValidGeneratorInput,
|
||||
freq: any ValidGeneratorInput,
|
||||
attackTime: any ValidGeneratorInput,
|
||||
decayTime: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
|
||||
let resolvedAttackTime: any ValidGeneratorInput = attackTime._resolvedInput()
|
||||
let resolvedDecayTime: any ValidGeneratorInput = decayTime._resolvedInput()
|
||||
self.inputSource = resolvedInput
|
||||
self.freqInput = resolvedFreq
|
||||
self.attackTimeInput = resolvedAttackTime
|
||||
self.decayTimeInput = resolvedDecayTime
|
||||
let freqGen: Bool = resolvedFreq is any Generator
|
||||
let attackGen: Bool = resolvedAttackTime is any Generator
|
||||
let decayGen: Bool = resolvedDecayTime is any Generator
|
||||
self.freqIsGenerator = freqGen
|
||||
self.attackTimeIsGenerator = attackGen
|
||||
self.decayTimeIsGenerator = decayGen
|
||||
self.anyCoeffIsGenerator = freqGen || attackGen || decayGen
|
||||
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio
|
||||
|
||||
/// Audio-rate FOF-like resonant filter.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to excite the resonators.
|
||||
/// - freq: Resonant (formant) frequency in Hz. A 0.1 Hz floor is applied internally.
|
||||
/// - attackTime: Rise time in seconds (60 dB time of the short resonator). Shorter than `decayTime`.
|
||||
/// - 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 Audio: _Base, AudioGenerator {
|
||||
|
||||
private var scratch: [Double] = makeSampleBuffer()
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to excite the resonators.
|
||||
/// - freq: Resonant (formant) frequency in Hz. A 0.1 Hz floor is applied internally.
|
||||
/// - attackTime: Rise time in seconds (60 dB time of the short resonator). Shorter than `decayTime`.
|
||||
/// - 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 override init(
|
||||
input: any ValidGeneratorInput,
|
||||
freq: any ValidGeneratorInput,
|
||||
attackTime: any ValidGeneratorInput,
|
||||
decayTime: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, freq: freq, attackTime: attackTime,
|
||||
decayTime: decayTime, mul: mul, add: add)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
let inputBlock: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
|
||||
if anyCoeffIsGenerator {
|
||||
let freqBlock: [Double]? = freqIsGenerator
|
||||
? freqInput.calculatedSamples(graph: graph, count: count).first : nil
|
||||
let attackBlock: [Double]? = attackTimeIsGenerator
|
||||
? attackTimeInput.calculatedSamples(graph: graph, count: count).first : nil
|
||||
let decayBlock: [Double]? = decayTimeIsGenerator
|
||||
? decayTimeInput.calculatedSamples(graph: graph, count: count).first : nil
|
||||
|
||||
let lastIdx: Int = count - 1
|
||||
let f0: Double = freqBlock.map { $0.isEmpty ? freqInput.floatValue(graph: graph) : $0[0] }
|
||||
?? freqInput.floatValue(graph: graph)
|
||||
let fN: Double = freqBlock.map { $0.isEmpty ? f0 : $0[min($0.count - 1, lastIdx)] } ?? f0
|
||||
let a0: Double = attackBlock.map { $0.isEmpty ? attackTimeInput.floatValue(graph: graph) : $0[0] }
|
||||
?? attackTimeInput.floatValue(graph: graph)
|
||||
let aN: Double = attackBlock.map { $0.isEmpty ? a0 : $0[min($0.count - 1, lastIdx)] } ?? a0
|
||||
let d0: Double = decayBlock.map { $0.isEmpty ? decayTimeInput.floatValue(graph: graph) : $0[0] }
|
||||
?? decayTimeInput.floatValue(graph: graph)
|
||||
let dN: Double = decayBlock.map { $0.isEmpty ? d0 : $0[min($0.count - 1, lastIdx)] } ?? d0
|
||||
|
||||
let decayStart: (b0: Double, na1: Double, na2: Double) = resonatingCoeffs(freq: f0, decayTime: d0, sr: sr)
|
||||
let decayEnd: (b0: Double, na1: Double, na2: Double) = resonatingCoeffs(freq: fN, decayTime: dN, sr: sr)
|
||||
let attackStart: (b0: Double, na1: Double, na2: Double) = resonatingCoeffs(freq: f0, decayTime: a0, sr: sr)
|
||||
let attackEnd: (b0: Double, na1: Double, na2: Double) = resonatingCoeffs(freq: fN, decayTime: aN, sr: sr)
|
||||
|
||||
runTwoPoleResonatorInterpolatedBlock(
|
||||
input: inputBlock, into: &_result[0],
|
||||
y1: &yDecay1, y2: &yDecay2,
|
||||
start: decayStart, end: decayEnd, count: count)
|
||||
runTwoPoleResonatorInterpolatedBlock(
|
||||
input: inputBlock, into: &scratch,
|
||||
y1: &yAttack1, y2: &yAttack2,
|
||||
start: attackStart, end: attackEnd, count: count)
|
||||
} else {
|
||||
let freq: Double = freqInput.floatValue(graph: graph)
|
||||
let attackTime: Double = attackTimeInput.floatValue(graph: graph)
|
||||
let decayTime: Double = decayTimeInput.floatValue(graph: graph)
|
||||
let decayC: (b0: Double, na1: Double, na2: Double) = resonatingCoeffs(freq: freq, decayTime: decayTime, sr: sr)
|
||||
let attackC: (b0: Double, na1: Double, na2: Double) = resonatingCoeffs(freq: freq, decayTime: attackTime, sr: sr)
|
||||
|
||||
runTwoPoleResonatorScalarBlock(
|
||||
input: inputBlock, into: &_result[0],
|
||||
y1: &yDecay1, y2: &yDecay2,
|
||||
b0: decayC.b0, na1: decayC.na1, na2: decayC.na2, count: count)
|
||||
runTwoPoleResonatorScalarBlock(
|
||||
input: inputBlock, into: &scratch,
|
||||
y1: &yAttack1, y2: &yAttack2,
|
||||
b0: attackC.b0, na1: attackC.na1, na2: attackC.na2, count: count)
|
||||
}
|
||||
|
||||
// Output = decay response − attack response (FOF grain).
|
||||
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
|
||||
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||||
scratch.withUnsafeBufferPointer { (atk: UnsafeBufferPointer<Double>) in
|
||||
guard let atkP: UnsafePointer<Double> = atk.baseAddress else { return }
|
||||
for i: Int in 0..<count {
|
||||
dstP[i] -= atkP[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Control
|
||||
|
||||
/// 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`).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to excite the resonators.
|
||||
/// - freq: Resonant (formant) frequency in Hz. A 0.1 Hz floor is applied internally.
|
||||
/// - attackTime: Rise time in seconds (60 dB time of the short resonator). Shorter than `decayTime`.
|
||||
/// - 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 var previousOutputValue: Double = 0.0
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to excite the resonators.
|
||||
/// - freq: Resonant (formant) frequency in Hz. A 0.1 Hz floor is applied internally.
|
||||
/// - attackTime: Rise time in seconds (60 dB time of the short resonator). Shorter than `decayTime`.
|
||||
/// - 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 override init(
|
||||
input: any ValidGeneratorInput,
|
||||
freq: any ValidGeneratorInput,
|
||||
attackTime: any ValidGeneratorInput,
|
||||
decayTime: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
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)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
let controlRate: Double = graph.engine.sampleRate / Double(graph.engine.blockSize)
|
||||
let freq: Double = freqInput.floatValue(graph: graph)
|
||||
let attackTime: Double = attackTimeInput.floatValue(graph: graph)
|
||||
let decayTime: Double = decayTimeInput.floatValue(graph: graph)
|
||||
let x: Double = inputSource.floatValue(graph: graph)
|
||||
|
||||
let decayC: (b0: Double, na1: Double, na2: Double) = resonatingCoeffs(freq: freq, decayTime: decayTime, sr: controlRate)
|
||||
let attackC: (b0: Double, na1: Double, na2: Double) = resonatingCoeffs(freq: freq, decayTime: attackTime, sr: controlRate)
|
||||
|
||||
let yDecay: Double = decayC.b0 * x - decayC.na1 * yDecay1 - decayC.na2 * yDecay2
|
||||
yDecay2 = denormalsToZero(yDecay1)
|
||||
yDecay1 = denormalsToZero(yDecay)
|
||||
let yAttack: Double = attackC.b0 * x - attackC.na1 * yAttack1 - attackC.na2 * yAttack2
|
||||
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]
|
||||
return _result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
extension Formlet: GeneratorEnum {
|
||||
public typealias AudioType = Formlet.Audio
|
||||
public typealias ControlType = Formlet.Control
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
// Klank.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
|
||||
/// Number of channels (= per-resonator parameters) required by ``Klank``: `freq`, `amp`,
|
||||
/// `decay`. Each ``LyrebirdBuffer`` frame supplies one resonator's parameters. The channel
|
||||
/// order (`freq, amp, decay`) matches the SuperCollider `Klank` specification triple.
|
||||
public let klankSpecChannelCount: Int = 3
|
||||
|
||||
/// Buffer channel index of the resonant frequency (Hz).
|
||||
public let klankFreqChannel: Int = 0
|
||||
|
||||
/// Buffer channel index of the per-resonator amplitude (linear gain).
|
||||
public let klankAmpChannel: Int = 1
|
||||
|
||||
/// Buffer channel index of the −60 dB ring decay time (seconds).
|
||||
public let klankDecayChannel: Int = 2
|
||||
|
||||
/// Floor applied to per-resonator effective frequency when computing coefficients.
|
||||
private let klankMinFreq: Double = 0.1
|
||||
|
||||
/// Floor applied to per-resonator effective decay time when computing coefficients.
|
||||
private let klankMinDecay: Double = 1.0e-6
|
||||
|
||||
/// Natural-log of the SC-conventional −60 dB target. `R = exp(klankLog0001 / (decay·sr))`.
|
||||
private let klankLog0001: Double = log(0.001)
|
||||
|
||||
/// Bank of N parallel two-pole (Ringz-style) resonators with **block-rate spec modulation**.
|
||||
///
|
||||
/// `Klank` is the modulatable counterpart of ``ResonatorBank``. Like `ResonatorBank` it reads
|
||||
/// a per-resonator `[freq, amp, decay]` table from a single ``LyrebirdBuffer`` (`channelCount
|
||||
/// == 3`, one resonator per frame) and drives every resonator in parallel from a shared input,
|
||||
/// summing to one mono channel. `Klank` additionally exposes the three SuperCollider `Klank`
|
||||
/// modulation parameters — `freqscale`, `freqoffset`, `decayscale` — which scale and shift the
|
||||
/// whole table without re-specifying it:
|
||||
///
|
||||
/// ```
|
||||
/// freq_k_effective = freq_k · freqscale + freqoffset
|
||||
/// decay_k_effective = decay_k · decayscale
|
||||
/// ```
|
||||
///
|
||||
/// Each is any `ValidGeneratorInput`, snapshotted once per audio block (block-rate / "control
|
||||
/// rate" respecification). Wire a control generator to glide the bank's tuning or ring time
|
||||
/// while it sounds. The full table can additionally be swapped at run time via
|
||||
/// ``Klank/Audio/setBuffer(_:engine:)`` (RT-safe ``RTBufferSlot`` handoff), so both per-mode editing and
|
||||
/// whole-table replacement are available.
|
||||
///
|
||||
/// ## Difference equation (per resonator k)
|
||||
///
|
||||
/// ```
|
||||
/// R_k = exp(log(0.001) / (decay_k_effective · sr)) // −60 dB after decay_k_effective seconds
|
||||
/// w0_k = 2π · freq_k_effective / sr
|
||||
/// b0_k = (1 − R_k) · amp_k
|
||||
/// na1_k = −2 · R_k · cos(w0_k)
|
||||
/// na2_k = R_k²
|
||||
/// y_k[n] = b0_k · x[n] − na1_k · y_k[n−1] − na2_k · y_k[n−2]
|
||||
/// ```
|
||||
///
|
||||
/// The output sample is `Σ_k y_k[n]`. Coefficients are recomputed once per block from the
|
||||
/// snapshotted spec and modulation values, then the per-sample inner loop is vectorised
|
||||
/// across the bank with vDSP (identical kernel to ``ResonatorBank``).
|
||||
///
|
||||
/// `freq_effective` is clamped to `>= 0.1` Hz; `decay_effective` is clamped to `>= 1e-6` s. No
|
||||
/// internal clamp is applied to `amp` (negative amplitudes invert phase).
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// ```swift
|
||||
/// let bank = LyrebirdBuffer(count: 3, channelCount: klankSpecChannelCount)
|
||||
/// // [freq, amp, decay] per mode
|
||||
/// for (i, t) in [
|
||||
/// (400.0, 1.0, 1.0),
|
||||
/// (1500.0, 0.5, 0.6),
|
||||
/// (3300.0, 0.25, 0.3),
|
||||
/// ].enumerated() {
|
||||
/// bank.setValue(t.0, frame: i, channel: klankFreqChannel)
|
||||
/// bank.setValue(t.1, frame: i, channel: klankAmpChannel)
|
||||
/// bank.setValue(t.2, frame: i, channel: klankDecayChannel)
|
||||
/// }
|
||||
///
|
||||
/// let exciter = Impulse.Audio(freq: 0.5, mul: 0.4)
|
||||
/// // Sweep the whole bank up an octave with an LFO.
|
||||
/// let voice = Klank.Audio(
|
||||
/// input: exciter, buffer: bank,
|
||||
/// freqscale: OscSin.Control(freq: 0.2) * 0.5 + 1.5
|
||||
/// )
|
||||
/// ```
|
||||
public enum Klank {
|
||||
|
||||
/// Audio-rate parallel resonator bank with block-rate `freqscale` / `freqoffset` /
|
||||
/// `decayscale` modulation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Mono signal driving every resonator in the bank. Any `ValidGeneratorInput`.
|
||||
/// - buffer: Mode table. Must have `channelCount == 3` and `count >= 1`. Frame `k`
|
||||
/// provides resonator `k`'s `[freq, amp, decay]`. Bank size = `buffer.count`. Live
|
||||
/// `setValue` writes are picked up once per audio block; whole-table swap via
|
||||
/// ``setBuffer(_:engine:)``.
|
||||
/// - freqscale: Multiplier applied to every resonator frequency. Snapshotted per block.
|
||||
/// Defaults to `1.0`.
|
||||
/// - freqoffset: Hz added to every resonator frequency after scaling. Snapshotted per
|
||||
/// block. Defaults to `0.0`.
|
||||
/// - decayscale: Multiplier applied to every resonator decay time. Snapshotted per block.
|
||||
/// Defaults to `1.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: GeneratorBase, AudioGenerator {
|
||||
|
||||
// MARK: Inputs
|
||||
|
||||
private let _inputSource: any ValidGeneratorInput
|
||||
/// Atomic slot — supports live whole-table swap via ``setBuffer(_:engine:)``.
|
||||
/// Loaded once per audio block.
|
||||
private let _slot: RTBufferSlot
|
||||
|
||||
private let _freqScaleInput: any ValidGeneratorInput
|
||||
private let _freqScaleIsGenerator: Bool
|
||||
private let _freqOffsetInput: any ValidGeneratorInput
|
||||
private let _freqOffsetIsGenerator: Bool
|
||||
private let _decayScaleInput: any ValidGeneratorInput
|
||||
private let _decayScaleIsGenerator: Bool
|
||||
|
||||
// MARK: State (one entry per resonator)
|
||||
|
||||
private let _bankSize: Int
|
||||
private var _b0: [Double]
|
||||
private var _na1: [Double]
|
||||
private var _na2: [Double]
|
||||
private var _y1: [Double]
|
||||
private var _y2: [Double]
|
||||
|
||||
// MARK: Per-sample scratch (size = _bankSize)
|
||||
|
||||
private var _newY: [Double]
|
||||
private var _tmp: [Double]
|
||||
|
||||
// MARK: Output
|
||||
private let _mulAdd: MulAddSpec
|
||||
|
||||
// MARK: Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Mono signal driving every resonator in the bank. Any `ValidGeneratorInput`.
|
||||
/// - buffer: Mode table. Must have `channelCount == 3` and `count >= 1`. Frame `k`
|
||||
/// provides resonator `k`'s `[freq, amp, decay]`. Bank size = `buffer.count`. Live
|
||||
/// `setValue` writes are picked up once per audio block; whole-table swap via
|
||||
/// ``setBuffer(_:engine:)``.
|
||||
/// - freqscale: Multiplier applied to every resonator frequency. Snapshotted per block.
|
||||
/// Defaults to `1.0`.
|
||||
/// - freqoffset: Hz added to every resonator frequency after scaling. Snapshotted per
|
||||
/// block. Defaults to `0.0`.
|
||||
/// - decayscale: Multiplier applied to every resonator decay time. Snapshotted per
|
||||
/// block. Defaults to `1.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
buffer: LyrebirdBuffer,
|
||||
freqscale: any ValidGeneratorInput = 1.0,
|
||||
freqoffset: any ValidGeneratorInput = 0.0,
|
||||
decayscale: any ValidGeneratorInput = 1.0,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
precondition(
|
||||
buffer.channelCount == klankSpecChannelCount,
|
||||
"Klank: buffer must have channelCount == \(klankSpecChannelCount) "
|
||||
+ "(freq, amp, decay); got channelCount=\(buffer.channelCount)"
|
||||
)
|
||||
precondition(
|
||||
buffer.count >= 1,
|
||||
"Klank: buffer must have count >= 1; got count=\(buffer.count)"
|
||||
)
|
||||
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
self._inputSource = resolvedInput
|
||||
self._slot = RTBufferSlot(initial: buffer)
|
||||
|
||||
let resolvedFreqScale: any ValidGeneratorInput = freqscale._resolvedInput()
|
||||
self._freqScaleInput = resolvedFreqScale
|
||||
self._freqScaleIsGenerator = resolvedFreqScale is any Generator
|
||||
let resolvedFreqOffset: any ValidGeneratorInput = freqoffset._resolvedInput()
|
||||
self._freqOffsetInput = resolvedFreqOffset
|
||||
self._freqOffsetIsGenerator = resolvedFreqOffset is any Generator
|
||||
let resolvedDecayScale: any ValidGeneratorInput = decayscale._resolvedInput()
|
||||
self._decayScaleInput = resolvedDecayScale
|
||||
self._decayScaleIsGenerator = resolvedDecayScale is any Generator
|
||||
|
||||
let n: Int = buffer.count
|
||||
self._bankSize = n
|
||||
self._b0 = makeSampleBuffer(n)
|
||||
self._na1 = makeSampleBuffer(n)
|
||||
self._na2 = makeSampleBuffer(n)
|
||||
self._y1 = makeSampleBuffer(n)
|
||||
self._y2 = makeSampleBuffer(n)
|
||||
self._newY = makeSampleBuffer(n)
|
||||
self._tmp = makeSampleBuffer(n)
|
||||
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
}
|
||||
|
||||
/// Replace the mode table driving the bank. Pass `nil` to silence the bank (filter
|
||||
/// state is preserved).
|
||||
///
|
||||
/// The new buffer must have `channelCount == klankSpecChannelCount` (3) and
|
||||
/// `count == bankSize` (the initial buffer's count) — internal state arrays are sized
|
||||
/// at init. The previously installed buffer's retain is routed through the engine's
|
||||
/// buffer-swap kill queue for off-RT release.
|
||||
public func setBuffer(_ buffer: LyrebirdBuffer?, engine: SynthesisEngine) {
|
||||
if let buffer: LyrebirdBuffer {
|
||||
precondition(
|
||||
buffer.channelCount == klankSpecChannelCount,
|
||||
"Klank.setBuffer: buffer must have channelCount == \(klankSpecChannelCount), got \(buffer.channelCount)"
|
||||
)
|
||||
precondition(
|
||||
buffer.count == _bankSize,
|
||||
"Klank.setBuffer: buffer count must equal initial bank size \(_bankSize), got \(buffer.count)"
|
||||
)
|
||||
}
|
||||
_slot.swap(buffer, engine: engine)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let n: Int = _bankSize
|
||||
let inputBlock: [Double] = _inputSource.calculatedSamples(graph: graph, count: count).first ?? []
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
|
||||
// Snapshot block-rate modulation. Evaluated unconditionally so any wired
|
||||
// modulation generator advances its state by `count` samples this block.
|
||||
let freqScale: Double = lastGeneratorSampleOrFloat(
|
||||
_freqScaleInput, isGenerator: _freqScaleIsGenerator, graph: graph, count: count)
|
||||
let freqOffset: Double = lastGeneratorSampleOrFloat(
|
||||
_freqOffsetInput, isGenerator: _freqOffsetIsGenerator, graph: graph, count: count)
|
||||
let decayScale: Double = lastGeneratorSampleOrFloat(
|
||||
_decayScaleInput, isGenerator: _decayScaleIsGenerator, graph: graph, count: count)
|
||||
|
||||
// Slot empty or buffer invalidated → emit silence and hold filter state.
|
||||
guard let buffer: LyrebirdBuffer = _slot.load(engine: graph.engine), buffer.isValid else {
|
||||
_result[0].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
vDSP_vclrD(base, 1, vDSP_Length(count))
|
||||
}
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
// Snapshot per-resonator (freq, amp, decay), apply modulation, recompute coeffs.
|
||||
let twoPiOverSr: Double = 2.0 * .pi / sr
|
||||
let recipSr: Double = 1.0 / sr
|
||||
for k: Int in 0..<n {
|
||||
let freq: Double = max(buffer[k, klankFreqChannel] * freqScale + freqOffset, klankMinFreq)
|
||||
let amp: Double = buffer[k, klankAmpChannel]
|
||||
let decay: Double = max(buffer[k, klankDecayChannel] * decayScale, klankMinDecay)
|
||||
let r: Double = exp(klankLog0001 * recipSr / decay)
|
||||
let w0: Double = twoPiOverSr * freq
|
||||
_b0[k] = (1.0 - r) * amp
|
||||
_na1[k] = -2.0 * r * cos(w0)
|
||||
_na2[k] = r * r
|
||||
}
|
||||
|
||||
// Per-sample inner loop, vectorised across the bank.
|
||||
let bankLength: vDSP_Length = vDSP_Length(n)
|
||||
let inputCount: Int = inputBlock.count
|
||||
|
||||
_b0.withUnsafeBufferPointer { b0p in
|
||||
_na1.withUnsafeBufferPointer { na1p in
|
||||
_na2.withUnsafeBufferPointer { na2p in
|
||||
_y1.withUnsafeMutableBufferPointer { y1p in
|
||||
_y2.withUnsafeMutableBufferPointer { y2p in
|
||||
_newY.withUnsafeMutableBufferPointer { newYp in
|
||||
_tmp.withUnsafeMutableBufferPointer { tmpp in
|
||||
_result[0].withUnsafeMutableBufferPointer { resBuf in
|
||||
guard
|
||||
let b0Base: UnsafePointer<Double> = b0p.baseAddress,
|
||||
let na1Base: UnsafePointer<Double> = na1p.baseAddress,
|
||||
let na2Base: UnsafePointer<Double> = na2p.baseAddress,
|
||||
let y1Base: UnsafeMutablePointer<Double> = y1p.baseAddress,
|
||||
let y2Base: UnsafeMutablePointer<Double> = y2p.baseAddress,
|
||||
let newYBase: UnsafeMutablePointer<Double> = newYp.baseAddress,
|
||||
let tmpBase: UnsafeMutablePointer<Double> = tmpp.baseAddress,
|
||||
let resBase: UnsafeMutablePointer<Double> = resBuf.baseAddress
|
||||
else { return }
|
||||
|
||||
for i: Int in 0..<count {
|
||||
var x: Double = i < inputCount ? inputBlock[i] : 0
|
||||
|
||||
// tmp = b0 * x (scalar input × per-row b0)
|
||||
vDSP_vsmulD(b0Base, 1, &x, tmpBase, 1, bankLength)
|
||||
|
||||
// newY = na1 * y1
|
||||
vDSP_vmulD(na1Base, 1, y1Base, 1, newYBase, 1, bankLength)
|
||||
// tmp -= newY → tmp = b0·x − na1·y1
|
||||
vDSP_vsubD(newYBase, 1, tmpBase, 1, tmpBase, 1, bankLength)
|
||||
|
||||
// newY = na2 * y2
|
||||
vDSP_vmulD(na2Base, 1, y2Base, 1, newYBase, 1, bankLength)
|
||||
// newY = tmp − newY → newY = b0·x − na1·y1 − na2·y2
|
||||
vDSP_vsubD(newYBase, 1, tmpBase, 1, newYBase, 1, bankLength)
|
||||
|
||||
// Output sample = Σ newY across the bank.
|
||||
var sum: Double = 0
|
||||
vDSP_sveD(newYBase, 1, &sum, bankLength)
|
||||
resBase[i] = sum
|
||||
|
||||
// Shift state: y2 ← y1, y1 ← denormal-cleaned newY.
|
||||
for k: Int in 0..<n {
|
||||
y2Base[k] = y1Base[k]
|
||||
y1Base[k] = denormalsToZero(newYBase[k])
|
||||
}
|
||||
}
|
||||
}}}}}}}}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
// GeneratorEnum conformance is intentionally omitted — Klank.Audio is Audio-only.
|
||||
// The IIR recurrence advances every sample, so a control-rate variant would need a
|
||||
// distinct architecture (per-sample state on a control-rate input is the same as audio rate).
|
||||
@@ -4,8 +4,6 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
|
||||
/// Butterworth Q (1/√2) — maximally flat magnitude response, no resonant peak. Default for SVF.
|
||||
public let svfButterworthQ: Double = 0.7071067811865475 // 1.0 / sqrt(2.0)
|
||||
|
||||
@@ -153,74 +151,21 @@ public enum SVF {
|
||||
let scalarQ: Double = qSamples == nil ? qInput.floatValue(graph: graph) : 0.0
|
||||
|
||||
let piOverSr: Double = Double.pi / sampleRate // π/sr; freq coeff = 2·sin(π·f/sr)
|
||||
let minQDamping: Double = 0.0001 // prevents 1/q divide-by-zero
|
||||
let fCoeffMax: Double = 1.0 // stability bound for Chamberlin SVF
|
||||
|
||||
// Pre-compute scalar coefficients when inputs are not generators.
|
||||
let scalarF: Double
|
||||
let scalarQ1: Double
|
||||
if !freqIsGenerator && !qIsGenerator {
|
||||
scalarF = min(fCoeffMax, max(0.0, 2.0 * Darwin.sin(piOverSr * scalarFreq)))
|
||||
scalarQ1 = 1.0 / max(minQDamping, scalarQ)
|
||||
} else {
|
||||
scalarF = 0.0
|
||||
scalarQ1 = 0.0
|
||||
}
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = ins[min(ins.count - 1, i)]
|
||||
|
||||
// Resolve per-sample freq/q when driven by generators.
|
||||
let f: Double
|
||||
let q1: Double
|
||||
if freqIsGenerator || qIsGenerator {
|
||||
let rawFreq: Double
|
||||
let rawQ: Double
|
||||
if let fs: [Double] = freqSamples {
|
||||
rawFreq = fs[min(fs.count - 1, i)]
|
||||
} else {
|
||||
rawFreq = scalarFreq
|
||||
}
|
||||
if let qs: [Double] = qSamples {
|
||||
rawQ = qs[min(qs.count - 1, i)]
|
||||
} else {
|
||||
rawQ = scalarQ
|
||||
}
|
||||
guard rawFreq > 0.0 else {
|
||||
_result[0][i] = 0.0
|
||||
_result[1][i] = 0.0
|
||||
_result[2][i] = 0.0
|
||||
_result[3][i] = 0.0
|
||||
continue
|
||||
}
|
||||
f = min(fCoeffMax, 2.0 * Darwin.sin(piOverSr * rawFreq))
|
||||
q1 = 1.0 / max(minQDamping, rawQ)
|
||||
} else {
|
||||
guard scalarFreq > 0.0 else {
|
||||
_result[0][i] = 0.0
|
||||
_result[1][i] = 0.0
|
||||
_result[2][i] = 0.0
|
||||
_result[3][i] = 0.0
|
||||
continue
|
||||
}
|
||||
f = scalarF
|
||||
q1 = scalarQ1
|
||||
}
|
||||
|
||||
// Chamberlin SVF recurrence.
|
||||
low = low + f * band
|
||||
let high: Double = x - low - q1 * band
|
||||
band = f * high + band
|
||||
let notch: Double = high + low
|
||||
|
||||
low = denormalsToZero(low)
|
||||
band = denormalsToZero(band)
|
||||
|
||||
_result[0][i] = low
|
||||
_result[1][i] = high
|
||||
_result[2][i] = band
|
||||
_result[3][i] = notch
|
||||
}
|
||||
runSVFBlock(
|
||||
ins: ins,
|
||||
freqSamples: freqSamples,
|
||||
qSamples: qSamples,
|
||||
scalarFreq: scalarFreq,
|
||||
scalarQ: scalarQ,
|
||||
freqIsGenerator: freqIsGenerator,
|
||||
qIsGenerator: qIsGenerator,
|
||||
piOverSr: piOverSr,
|
||||
low: &low,
|
||||
band: &band,
|
||||
result: &_result,
|
||||
count: count
|
||||
)
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
@@ -323,72 +268,21 @@ public enum SVF {
|
||||
let scalarQ: Double = qSamples == nil ? qInput.floatValue(graph: graph) : 0.0
|
||||
|
||||
let piOverSr: Double = Double.pi / sampleRate
|
||||
let minQDamping: Double = 0.0001
|
||||
let fCoeffMax: Double = 1.0
|
||||
|
||||
let scalarF: Double
|
||||
let scalarQ1: Double
|
||||
if !freqIsGenerator && !qIsGenerator {
|
||||
scalarF = min(fCoeffMax, max(0.0, 2.0 * Darwin.sin(piOverSr * scalarFreq)))
|
||||
scalarQ1 = 1.0 / max(minQDamping, scalarQ)
|
||||
} else {
|
||||
scalarF = 0.0
|
||||
scalarQ1 = 0.0
|
||||
}
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = ins[min(ins.count - 1, i)]
|
||||
|
||||
let f: Double
|
||||
let q1: Double
|
||||
if freqIsGenerator || qIsGenerator {
|
||||
let rawFreq: Double
|
||||
let rawQ: Double
|
||||
if let fs: [Double] = freqSamples {
|
||||
rawFreq = fs[min(fs.count - 1, i)]
|
||||
} else {
|
||||
rawFreq = scalarFreq
|
||||
}
|
||||
if let qs: [Double] = qSamples {
|
||||
rawQ = qs[min(qs.count - 1, i)]
|
||||
} else {
|
||||
rawQ = scalarQ
|
||||
}
|
||||
guard rawFreq > 0.0 else {
|
||||
_result[0][i] = 0.0
|
||||
_result[1][i] = 0.0
|
||||
_result[2][i] = 0.0
|
||||
_result[3][i] = 0.0
|
||||
continue
|
||||
}
|
||||
f = min(fCoeffMax, 2.0 * Darwin.sin(piOverSr * rawFreq))
|
||||
q1 = 1.0 / max(minQDamping, rawQ)
|
||||
} else {
|
||||
guard scalarFreq > 0.0 else {
|
||||
_result[0][i] = 0.0
|
||||
_result[1][i] = 0.0
|
||||
_result[2][i] = 0.0
|
||||
_result[3][i] = 0.0
|
||||
continue
|
||||
}
|
||||
f = scalarF
|
||||
q1 = scalarQ1
|
||||
}
|
||||
|
||||
// Chamberlin SVF recurrence.
|
||||
low = low + f * band
|
||||
let high: Double = x - low - q1 * band
|
||||
band = f * high + band
|
||||
let notch: Double = high + low
|
||||
|
||||
low = denormalsToZero(low)
|
||||
band = denormalsToZero(band)
|
||||
|
||||
_result[0][i] = low
|
||||
_result[1][i] = high
|
||||
_result[2][i] = band
|
||||
_result[3][i] = notch
|
||||
}
|
||||
runSVFBlock(
|
||||
ins: ins,
|
||||
freqSamples: freqSamples,
|
||||
qSamples: qSamples,
|
||||
scalarFreq: scalarFreq,
|
||||
scalarQ: scalarQ,
|
||||
freqIsGenerator: freqIsGenerator,
|
||||
qIsGenerator: qIsGenerator,
|
||||
piOverSr: piOverSr,
|
||||
low: &low,
|
||||
band: &band,
|
||||
result: &_result,
|
||||
count: count
|
||||
)
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
// SVFHelpers.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
|
||||
/// Minimum damping denominator — prevents the `1/q` divide-by-zero in the SVF.
|
||||
let svfMinQDamping: Double = 0.0001
|
||||
|
||||
/// Stability bound for the Chamberlin SVF frequency coefficient `f`.
|
||||
let svfFCoeffMax: Double = 1.0
|
||||
|
||||
/// Shared per-block body for `SVF.Audio` and `SVF.Control` — runs the Chamberlin
|
||||
/// state-variable recurrence over `count` samples, writing the four outputs
|
||||
/// (low / high / band / notch) into `result` rows 0…3.
|
||||
///
|
||||
/// `low` and `band` are the two IIR delay elements, advanced in place.
|
||||
///
|
||||
/// ## Frequency-coefficient interpolation
|
||||
/// When `freq` is generator-driven the cutoff coefficient `f = 2·sin(π·freq/sr)`
|
||||
/// is evaluated with `sin()` only at the first and last sample of the block and
|
||||
/// linearly interpolated for the samples in between — the same coefficient-ramp
|
||||
/// technique the RBJ biquads use. This replaces one transcendental call per
|
||||
/// sample with two per block. The per-sample `freq > 0 → silence` guard is still
|
||||
/// applied from the raw (un-interpolated) frequency so individual samples whose
|
||||
/// cutoff drops to zero are zeroed exactly as before.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - ins: Input signal block (last value repeats if shorter than `count`).
|
||||
/// - freqSamples: Per-sample cutoff in Hz when `freq` is generator-driven, else `nil`.
|
||||
/// - qSamples: Per-sample Q when `q` is generator-driven, else `nil`.
|
||||
/// - scalarFreq: Cutoff in Hz used when `freq` is not generator-driven.
|
||||
/// - scalarQ: Q used when `q` is not generator-driven.
|
||||
/// - freqIsGenerator: Whether `freq` is generator-driven (classified at init).
|
||||
/// - qIsGenerator: Whether `q` is generator-driven (classified at init).
|
||||
/// - piOverSr: `π / sampleRate`, precomputed by the caller.
|
||||
/// - low: Lowpass IIR accumulator, advanced in place.
|
||||
/// - band: Bandpass IIR accumulator, advanced in place.
|
||||
/// - result: Output buffer; rows 0…3 receive low / high / band / notch.
|
||||
/// - count: Number of samples to process.
|
||||
@inline(__always)
|
||||
func runSVFBlock(
|
||||
ins: [Double],
|
||||
freqSamples: [Double]?,
|
||||
qSamples: [Double]?,
|
||||
scalarFreq: Double,
|
||||
scalarQ: Double,
|
||||
freqIsGenerator: Bool,
|
||||
qIsGenerator: Bool,
|
||||
piOverSr: Double,
|
||||
low: inout Double,
|
||||
band: inout Double,
|
||||
result: inout [[Double]],
|
||||
count: Int
|
||||
) {
|
||||
let minQDamping: Double = svfMinQDamping
|
||||
let fCoeffMax: Double = svfFCoeffMax
|
||||
|
||||
// Scalar coefficients reused for whichever input is not generator-driven.
|
||||
// `scalarFCoeff` is computed whenever `freq` is scalar — even if `q` is a
|
||||
// generator — matching the original per-sample formula for that mixed case.
|
||||
let scalarFCoeff: Double = freqIsGenerator
|
||||
? 0.0
|
||||
: min(fCoeffMax, max(0.0, 2.0 * Darwin.sin(piOverSr * scalarFreq)))
|
||||
let scalarQ1: Double = qIsGenerator ? 0.0 : 1.0 / max(minQDamping, scalarQ)
|
||||
|
||||
// Block-boundary cutoff-coefficient ramp for the generator-driven case.
|
||||
var fFirst: Double = 0.0
|
||||
var fStep: Double = 0.0
|
||||
if freqIsGenerator, let fs: [Double] = freqSamples, count > 0, !fs.isEmpty {
|
||||
let firstRaw: Double = fs[0]
|
||||
let lastRaw: Double = fs[min(fs.count - 1, count - 1)]
|
||||
// `max(0.0, ...)` matches the scalar path: a freq above the sample rate makes
|
||||
// `sin(π·freq/sr)` negative, which would destabilise the Chamberlin recurrence.
|
||||
let cFirst: Double = firstRaw > 0.0 ? min(fCoeffMax, max(0.0, 2.0 * Darwin.sin(piOverSr * firstRaw))) : 0.0
|
||||
let cLast: Double = lastRaw > 0.0 ? min(fCoeffMax, max(0.0, 2.0 * Darwin.sin(piOverSr * lastRaw))) : 0.0
|
||||
fFirst = cFirst
|
||||
fStep = count > 1 ? (cLast - cFirst) / Double(count - 1) : 0.0
|
||||
}
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = ins[min(ins.count - 1, i)]
|
||||
|
||||
let f: Double
|
||||
let q1: Double
|
||||
if freqIsGenerator || qIsGenerator {
|
||||
let rawFreq: Double
|
||||
if freqIsGenerator, let fs: [Double] = freqSamples {
|
||||
rawFreq = fs[min(fs.count - 1, i)]
|
||||
} else {
|
||||
rawFreq = scalarFreq
|
||||
}
|
||||
guard rawFreq > 0.0 else {
|
||||
result[0][i] = 0.0
|
||||
result[1][i] = 0.0
|
||||
result[2][i] = 0.0
|
||||
result[3][i] = 0.0
|
||||
continue
|
||||
}
|
||||
f = freqIsGenerator ? (fFirst + fStep * Double(i)) : scalarFCoeff
|
||||
if qIsGenerator, let qs: [Double] = qSamples {
|
||||
q1 = 1.0 / max(minQDamping, qs[min(qs.count - 1, i)])
|
||||
} else {
|
||||
q1 = scalarQ1
|
||||
}
|
||||
} else {
|
||||
guard scalarFreq > 0.0 else {
|
||||
result[0][i] = 0.0
|
||||
result[1][i] = 0.0
|
||||
result[2][i] = 0.0
|
||||
result[3][i] = 0.0
|
||||
continue
|
||||
}
|
||||
f = scalarFCoeff
|
||||
q1 = scalarQ1
|
||||
}
|
||||
|
||||
// Chamberlin SVF recurrence.
|
||||
low = low + f * band
|
||||
let high: Double = x - low - q1 * band
|
||||
band = f * high + band
|
||||
let notch: Double = high + low
|
||||
|
||||
low = denormalsToZero(low)
|
||||
band = denormalsToZero(band)
|
||||
|
||||
result[0][i] = low
|
||||
result[1][i] = high
|
||||
result[2][i] = band
|
||||
result[3][i] = notch
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
// Slew.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
|
||||
/// Linear slew-rate limiter. Equivalent to SuperCollider `Slew`.
|
||||
///
|
||||
/// Moves the output toward `input` at a maximum rate of `up` units per second when the
|
||||
/// input is rising, and `dn` units per second when the input is falling. On the very
|
||||
/// first block, the output is initialised directly to the first input value with no slew
|
||||
/// applied — this matches SC's `Slew` initialisation behaviour.
|
||||
///
|
||||
/// This is **linear** rate-limiting, distinct from the exponential smoothing produced by
|
||||
/// the `Lag` family. Use `Lag` when you want an RC-filter-like curve; use `Slew` when you
|
||||
/// want a linear ramp at a controlled maximum slope.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
/// Slew.Audio(input: controlSignal, up: 500.0, dn: 200.0) // asymmetric slopes
|
||||
/// Slew.Control(input: $cv, up: 100.0, dn: 100.0) // smooth CV at control rate
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to slew-limit.
|
||||
/// - up: Maximum rising slope in units per second. Defaults to `1.0`.
|
||||
/// - dn: Maximum falling slope in units per second. Defaults to `1.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public enum Slew {
|
||||
|
||||
// MARK: - Shared base
|
||||
|
||||
/// Shared stored properties and initialiser for `Slew.Audio` and `Slew.Control`.
|
||||
public class _Base: GeneratorBase {
|
||||
let _input: any ValidGeneratorInput
|
||||
let _up: any ValidGeneratorInput
|
||||
let _dn: any ValidGeneratorInput
|
||||
let _mulAdd: MulAddSpec
|
||||
let _upIsGenerator: Bool
|
||||
let _dnIsGenerator: Bool
|
||||
|
||||
var _state: Double = 0.0
|
||||
var _initialized: Bool = false
|
||||
|
||||
init(
|
||||
input: any ValidGeneratorInput,
|
||||
up: any ValidGeneratorInput,
|
||||
dn: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedUp: any ValidGeneratorInput = up._resolvedInput()
|
||||
let resolvedDn: any ValidGeneratorInput = dn._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_up = resolvedUp
|
||||
_dn = resolvedDn
|
||||
_upIsGenerator = resolvedUp is any Generator
|
||||
_dnIsGenerator = resolvedDn is any Generator
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
super.init()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio
|
||||
|
||||
/// Audio-rate linear slew-rate limiter. Evaluates `up` and `dn` per sample.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to slew-limit.
|
||||
/// - up: Maximum rising slope in units per second. Defaults to `1.0`.
|
||||
/// - dn: Maximum falling slope in units per second. Defaults to `1.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to slew-limit.
|
||||
/// - up: Maximum rising slope in units per second. Defaults to `1.0`.
|
||||
/// - dn: Maximum falling slope in units per second. Defaults to `1.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
input: any ValidGeneratorInput,
|
||||
up: any ValidGeneratorInput = 1.0,
|
||||
dn: any ValidGeneratorInput = 1.0,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, up: up, dn: dn, mul: mul, add: add)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
|
||||
let inputBlock: [Double] = _input.calculatedSamples(graph: graph, count: count).first ?? []
|
||||
let inputCount: Int = inputBlock.count
|
||||
|
||||
let (upSamples, scalarUp) = resolveGeneratorOrScalar(
|
||||
_up, isGenerator: _upIsGenerator, graph: graph, count: count)
|
||||
let (dnSamples, scalarDn) = resolveGeneratorOrScalar(
|
||||
_dn, isGenerator: _dnIsGenerator, graph: graph, count: count)
|
||||
|
||||
// Scalar-path per-sample step is block-constant: precompute once.
|
||||
let scalarUpStep: Double = scalarUp / sr
|
||||
let scalarDnStep: Double = scalarDn / sr
|
||||
|
||||
var state: Double = _state
|
||||
var initialized: Bool = _initialized
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = i < inputCount ? inputBlock[i] : 0.0
|
||||
|
||||
if !initialized {
|
||||
state = x
|
||||
initialized = true
|
||||
_result[0][i] = state
|
||||
continue
|
||||
}
|
||||
|
||||
let upStep: Double = upSamples == nil
|
||||
? scalarUpStep
|
||||
: sampleOrFallback(upSamples, scalar: scalarUp, at: i) / sr
|
||||
let dnStep: Double = dnSamples == nil
|
||||
? scalarDnStep
|
||||
: sampleOrFallback(dnSamples, scalar: scalarDn, at: i) / sr
|
||||
|
||||
if x > state + upStep {
|
||||
state += upStep
|
||||
} else if x < state - dnStep {
|
||||
state -= dnStep
|
||||
} else {
|
||||
state = x
|
||||
}
|
||||
_result[0][i] = state
|
||||
}
|
||||
|
||||
_state = state
|
||||
_initialized = initialized
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Control
|
||||
|
||||
/// 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
|
||||
/// 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`).
|
||||
///
|
||||
/// The output block is flat (constant). For smoothly interpolated output, use `Slew.Audio`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to slew-limit.
|
||||
/// - up: Maximum rising slope in units per second. Defaults to `1.0`.
|
||||
/// - dn: Maximum falling slope in units per second. Defaults to `1.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to slew-limit.
|
||||
/// - up: Maximum rising slope in units per second. Defaults to `1.0`.
|
||||
/// - dn: Maximum falling slope in units per second. Defaults to `1.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
input: any ValidGeneratorInput,
|
||||
up: any ValidGeneratorInput = 1.0,
|
||||
dn: any ValidGeneratorInput = 1.0,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
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,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
let controlRate: Double = graph.engine.sampleRate / Double(graph.engine.blockSize)
|
||||
let x: Double = _input.floatValue(graph: graph)
|
||||
let upVal: Double = _up.floatValue(graph: graph)
|
||||
let dnVal: Double = _dn.floatValue(graph: graph)
|
||||
|
||||
if !_initialized {
|
||||
_state = x
|
||||
_initialized = true
|
||||
} else {
|
||||
let upStep: Double = upVal / controlRate
|
||||
let dnStep: Double = dnVal / controlRate
|
||||
if x > _state + upStep {
|
||||
_state += upStep
|
||||
} else if x < _state - dnStep {
|
||||
_state -= dnStep
|
||||
} else {
|
||||
_state = x
|
||||
}
|
||||
}
|
||||
|
||||
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]
|
||||
return _result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
extension Slew: GeneratorEnum {
|
||||
public typealias AudioType = Slew.Audio
|
||||
public typealias ControlType = Slew.Control
|
||||
}
|
||||
@@ -44,8 +44,7 @@ public enum Abs {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
let block: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
|
||||
let n: Int = block.count
|
||||
for i: Int in 0..<count { _result[0][i] = Swift.abs(i < n ? block[i] : 0.0) }
|
||||
unaryVectorAbs(block, into: &_result, count: count)
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -78,6 +78,9 @@ public final class BinaryOpGenerator: GeneratorBase, AudioGenerator {
|
||||
private let rhs: any ValidGeneratorInput
|
||||
private let op: (Double, Double) -> Double
|
||||
|
||||
/// Arithmetic operator kind for vDSP dispatch, or `nil` for an arbitrary
|
||||
/// closure (`.other`-style), which uses the per-sample `op` fallback.
|
||||
private let kind: BinaryOpKind?
|
||||
|
||||
/// Output channel count — `max(lhsChannels, rhsChannels)`. Read by downstream
|
||||
/// `BinaryOpGenerator` instances to compose multi-channel arithmetic.
|
||||
@@ -95,16 +98,18 @@ public final class BinaryOpGenerator: GeneratorBase, AudioGenerator {
|
||||
/// Channel count of `rhs` at init.
|
||||
private let rhsChannels: Int
|
||||
|
||||
public init(
|
||||
private init(
|
||||
lhs: any ValidGeneratorInput,
|
||||
rhs: any ValidGeneratorInput,
|
||||
op: @escaping (Double, Double) -> Double
|
||||
op: @escaping (Double, Double) -> Double,
|
||||
kind: BinaryOpKind?
|
||||
) {
|
||||
let resolvedLhs: any ValidGeneratorInput = lhs._resolvedInput()
|
||||
let resolvedRhs: any ValidGeneratorInput = rhs._resolvedInput()
|
||||
self.lhs = resolvedLhs
|
||||
self.rhs = resolvedRhs
|
||||
self.op = op
|
||||
self.kind = kind
|
||||
// Classify inputs at construction time — types are fixed after init, so we only
|
||||
// pay the is-any-Generator runtime cost once rather than once per RT block.
|
||||
self.lhsIsLiteral = !resolvedLhs.needsInterpolation() && !(resolvedLhs is any Generator)
|
||||
@@ -123,6 +128,34 @@ public final class BinaryOpGenerator: GeneratorBase, AudioGenerator {
|
||||
super.init(channels: max(lhsCh, rhsCh))
|
||||
}
|
||||
|
||||
/// Construct from an arbitrary closure. The per-sample closure path is used
|
||||
/// (no vDSP dispatch) since the operation is not one of the four arithmetic kinds.
|
||||
public convenience init(
|
||||
lhs: any ValidGeneratorInput,
|
||||
rhs: any ValidGeneratorInput,
|
||||
op: @escaping (Double, Double) -> Double
|
||||
) {
|
||||
self.init(lhs: lhs, rhs: rhs, op: op, kind: nil)
|
||||
}
|
||||
|
||||
/// Construct from one of the four arithmetic operator kinds — enables the
|
||||
/// vDSP dispatch path. The matching scalar closure backs the fallback loop
|
||||
/// (both-literals, short/unaligned rows).
|
||||
convenience init(
|
||||
lhs: any ValidGeneratorInput,
|
||||
rhs: any ValidGeneratorInput,
|
||||
kind: BinaryOpKind
|
||||
) {
|
||||
let opClosure: (Double, Double) -> Double
|
||||
switch kind {
|
||||
case .add: opClosure = (+)
|
||||
case .subtract: opClosure = (-)
|
||||
case .multiply: opClosure = (*)
|
||||
case .divide: opClosure = (/)
|
||||
}
|
||||
self.init(lhs: lhs, rhs: rhs, op: opClosure, kind: kind)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
@@ -161,7 +194,11 @@ public final class BinaryOpGenerator: GeneratorBase, AudioGenerator {
|
||||
continue
|
||||
}
|
||||
let ls: [Double] = lhsSamples[lhsRow]
|
||||
for i: Int in 0..<count { _result[ch][i] = op(ls[i], rhsScalar) }
|
||||
if let k: BinaryOpKind = kind, ls.count >= count {
|
||||
binaryOpVectorScalarRHS(ls, rhsScalar, k, into: &_result[ch], count: count)
|
||||
} else {
|
||||
for i: Int in 0..<count { _result[ch][i] = op(ls[i], rhsScalar) }
|
||||
}
|
||||
} else if lhsIsLiteral {
|
||||
// Scalar op generator (e.g. 0.5 * stereoGen)
|
||||
guard rhsRow < rhsSamples.count else {
|
||||
@@ -169,7 +206,11 @@ public final class BinaryOpGenerator: GeneratorBase, AudioGenerator {
|
||||
continue
|
||||
}
|
||||
let rs: [Double] = rhsSamples[rhsRow]
|
||||
for i: Int in 0..<count { _result[ch][i] = op(lhsScalar, rs[i]) }
|
||||
if let k: BinaryOpKind = kind, rs.count >= count {
|
||||
binaryOpScalarLHSVector(lhsScalar, rs, k, into: &_result[ch], count: count)
|
||||
} else {
|
||||
for i: Int in 0..<count { _result[ch][i] = op(lhsScalar, rs[i]) }
|
||||
}
|
||||
} else {
|
||||
// Both generators
|
||||
guard lhsRow < lhsSamples.count, rhsRow < rhsSamples.count else {
|
||||
@@ -178,7 +219,11 @@ public final class BinaryOpGenerator: GeneratorBase, AudioGenerator {
|
||||
}
|
||||
let ls: [Double] = lhsSamples[lhsRow]
|
||||
let rs: [Double] = rhsSamples[rhsRow]
|
||||
for i: Int in 0..<count { _result[ch][i] = op(ls[i], rs[i]) }
|
||||
if let k: BinaryOpKind = kind, ls.count >= count, rs.count >= count {
|
||||
binaryOpVectorVector(ls, rs, k, into: &_result[ch], count: count)
|
||||
} else {
|
||||
for i: Int in 0..<count { _result[ch][i] = op(ls[i], rs[i]) }
|
||||
}
|
||||
}
|
||||
}
|
||||
return _result
|
||||
@@ -202,44 +247,44 @@ public final class BinaryOpGenerator: GeneratorBase, AudioGenerator {
|
||||
|
||||
// Generator op Generator (tiebreaker — avoids ambiguity when both sides conform to Generator)
|
||||
public func + <L: Generator, R: Generator>(lhs: L, rhs: R) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: +)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .add)
|
||||
}
|
||||
public func - <L: Generator, R: Generator>(lhs: L, rhs: R) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: -)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .subtract)
|
||||
}
|
||||
public func * <L: Generator, R: Generator>(lhs: L, rhs: R) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: *)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .multiply)
|
||||
}
|
||||
public func / <L: Generator, R: Generator>(lhs: L, rhs: R) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: /)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .divide)
|
||||
}
|
||||
|
||||
// Generator op ValidGeneratorInput
|
||||
public func + <L: Generator>(lhs: L, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: +)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .add)
|
||||
}
|
||||
public func - <L: Generator>(lhs: L, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: -)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .subtract)
|
||||
}
|
||||
public func * <L: Generator>(lhs: L, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: *)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .multiply)
|
||||
}
|
||||
public func / <L: Generator>(lhs: L, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: /)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .divide)
|
||||
}
|
||||
|
||||
// ValidGeneratorInput op Generator
|
||||
public func + <R: Generator>(lhs: any ValidGeneratorInput, rhs: R) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: +)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .add)
|
||||
}
|
||||
public func - <R: Generator>(lhs: any ValidGeneratorInput, rhs: R) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: -)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .subtract)
|
||||
}
|
||||
public func * <R: Generator>(lhs: any ValidGeneratorInput, rhs: R) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: *)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .multiply)
|
||||
}
|
||||
public func / <R: Generator>(lhs: any ValidGeneratorInput, rhs: R) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: /)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .divide)
|
||||
}
|
||||
|
||||
// ValidGeneratorInput op ValidGeneratorInput — both existential.
|
||||
@@ -247,14 +292,14 @@ public func / <R: Generator>(lhs: any ValidGeneratorInput, rhs: R) -> BinaryOpGe
|
||||
// `freq: any ValidGeneratorInput`). Swift still picks the stdlib `Double op Double`
|
||||
// overload for concrete Double expressions, so pure scalar arithmetic is unaffected.
|
||||
public func + (lhs: any ValidGeneratorInput, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: +)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .add)
|
||||
}
|
||||
public func - (lhs: any ValidGeneratorInput, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: -)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .subtract)
|
||||
}
|
||||
public func * (lhs: any ValidGeneratorInput, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: *)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .multiply)
|
||||
}
|
||||
public func / (lhs: any ValidGeneratorInput, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: /)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .divide)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
// BinaryOpVectorHelpers.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
|
||||
/// The four arithmetic operators `BinaryOpGenerator` can dispatch to vDSP. A
|
||||
/// generator built from an arbitrary closure (not one of these four) carries no
|
||||
/// kind and falls back to the per-sample closure loop.
|
||||
enum BinaryOpKind {
|
||||
case add
|
||||
case subtract
|
||||
case multiply
|
||||
case divide
|
||||
}
|
||||
|
||||
// Vectorised `BinaryOpGenerator` inner loops. Each dispatches one output row.
|
||||
// All four operators map to correctly-rounded vDSP routines, so results are
|
||||
// bit-identical to the scalar `lhs op rhs` loop — divide uses true division
|
||||
// (vsdivD / svdivD / vdivD), never reciprocal-multiply, to preserve that.
|
||||
//
|
||||
// vDSP subtract/divide take operands in `C = A - B` / `C = A / B` order with the
|
||||
// "B" (subtrahend / divisor) pointer FIRST — the calls below pass them reversed
|
||||
// accordingly.
|
||||
|
||||
/// `out[i] = ls[i] <op> scalar`. Caller guarantees `ls.count >= count`.
|
||||
@inline(__always)
|
||||
func binaryOpVectorScalarRHS(
|
||||
_ ls: [Double],
|
||||
_ scalar: Double,
|
||||
_ kind: BinaryOpKind,
|
||||
into out: inout [Double],
|
||||
count: Int
|
||||
) {
|
||||
var s: Double = scalar
|
||||
ls.withUnsafeBufferPointer { lp in
|
||||
out.withUnsafeMutableBufferPointer { op in
|
||||
guard let a: UnsafePointer<Double> = lp.baseAddress,
|
||||
let c: UnsafeMutablePointer<Double> = op.baseAddress else { return }
|
||||
let n: vDSP_Length = vDSP_Length(count)
|
||||
switch kind {
|
||||
case .add:
|
||||
vDSP_vsaddD(a, 1, &s, c, 1, n)
|
||||
case .multiply:
|
||||
vDSP_vsmulD(a, 1, &s, c, 1, n)
|
||||
case .subtract:
|
||||
var neg: Double = -scalar // ls - s == ls + (-s), bit-exact
|
||||
vDSP_vsaddD(a, 1, &neg, c, 1, n)
|
||||
case .divide:
|
||||
vDSP_vsdivD(a, 1, &s, c, 1, n) // C[i] = ls[i] / s (true division)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `out[i] = scalar <op> rs[i]`. Caller guarantees `rs.count >= count`.
|
||||
@inline(__always)
|
||||
func binaryOpScalarLHSVector(
|
||||
_ scalar: Double,
|
||||
_ rs: [Double],
|
||||
_ kind: BinaryOpKind,
|
||||
into out: inout [Double],
|
||||
count: Int
|
||||
) {
|
||||
var s: Double = scalar
|
||||
rs.withUnsafeBufferPointer { rp in
|
||||
out.withUnsafeMutableBufferPointer { op in
|
||||
guard let b: UnsafePointer<Double> = rp.baseAddress,
|
||||
let c: UnsafeMutablePointer<Double> = op.baseAddress else { return }
|
||||
let n: vDSP_Length = vDSP_Length(count)
|
||||
switch kind {
|
||||
case .add:
|
||||
vDSP_vsaddD(b, 1, &s, c, 1, n) // s + rs == rs + s
|
||||
case .multiply:
|
||||
vDSP_vsmulD(b, 1, &s, c, 1, n) // commutative
|
||||
case .subtract:
|
||||
var negOne: Double = -1.0 // rs*(-1) + s == s - rs, bit-exact
|
||||
vDSP_vsmsaD(b, 1, &negOne, &s, c, 1, n)
|
||||
case .divide:
|
||||
vDSP_svdivD(&s, b, 1, c, 1, n) // C[i] = s / rs[i] (true division)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `out[i] = ls[i] <op> rs[i]`. Caller guarantees both counts `>= count`.
|
||||
@inline(__always)
|
||||
func binaryOpVectorVector(
|
||||
_ ls: [Double],
|
||||
_ rs: [Double],
|
||||
_ kind: BinaryOpKind,
|
||||
into out: inout [Double],
|
||||
count: Int
|
||||
) {
|
||||
ls.withUnsafeBufferPointer { lp in
|
||||
rs.withUnsafeBufferPointer { rp in
|
||||
out.withUnsafeMutableBufferPointer { op in
|
||||
guard let a: UnsafePointer<Double> = lp.baseAddress,
|
||||
let b: UnsafePointer<Double> = rp.baseAddress,
|
||||
let c: UnsafeMutablePointer<Double> = op.baseAddress else { return }
|
||||
let n: vDSP_Length = vDSP_Length(count)
|
||||
switch kind {
|
||||
case .add:
|
||||
vDSP_vaddD(a, 1, b, 1, c, 1, n)
|
||||
case .multiply:
|
||||
vDSP_vmulD(a, 1, b, 1, c, 1, n)
|
||||
case .subtract:
|
||||
vDSP_vsubD(b, 1, a, 1, c, 1, n) // C = A - B = ls - rs (B first)
|
||||
case .divide:
|
||||
vDSP_vdivD(b, 1, a, 1, c, 1, n) // C = A / B = ls / rs (B first)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,8 +46,7 @@ public enum Ceil {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
let block: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
|
||||
let n: Int = block.count
|
||||
for i: Int in 0..<count { _result[0][i] = Foundation.ceil(i < n ? block[i] : 0.0) }
|
||||
unaryVectorCeil(block, into: &_result, count: count)
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -47,8 +47,7 @@ public enum Cos {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
let block: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
|
||||
let n: Int = block.count
|
||||
for i: Int in 0..<count { _result[0][i] = Foundation.cos(i < n ? block[i] : 0.0) }
|
||||
unaryVectorCos(block, into: &_result, count: count)
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
// DbAmp.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// MARK: - DbAmp
|
||||
|
||||
/// Converts a decibel value to a linear amplitude multiplier: `10^(dB / 20)`.
|
||||
///
|
||||
/// Control-rate only — intended for live gain knobs authored in dB (e.g. a pedal's
|
||||
/// output-level control) that need to drive another generator's linear gain input
|
||||
/// every block. Wraps the scalar `dbToAmp(_:)` helper so the conversion formula
|
||||
/// lives in one place.
|
||||
///
|
||||
/// - 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)
|
||||
}
|
||||
}
|
||||
|
||||
/// - Parameters:
|
||||
/// - signal: Input value in decibels.
|
||||
/// - 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
|
||||
|
||||
/// - Parameters:
|
||||
/// - signal: Input value in decibels.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
_ signal: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) { super.init(signal, mul: mul, add: add); _setupSubBlockBuffer() }
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[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)
|
||||
}
|
||||
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,8 +46,7 @@ public enum Exp {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
let block: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
|
||||
let n: Int = block.count
|
||||
for i: Int in 0..<count { _result[0][i] = Foundation.exp(i < n ? block[i] : 0.0) }
|
||||
unaryVectorExp(block, into: &_result, count: count)
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, 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