5 Commits

Author SHA1 Message Date
josh 560724d116 v1.3.0 release: graceful-release fix, quickstart template + demo, documentation accuracy pass
- Fixed: SynthesizerBase subclasses' release/free now dispatch correctly (gated
  synths were hard-freed instead of released).
- New: quickstart project template + LyrebirdQuickstartDemo.
- Docs: every example typechecked or provably illustrative (426->542); ~20
  wrong-API examples fixed; root docs brought under the compile guard.
- Fixed: NRT/Score demo Package.swift build from terminal again.

See RELEASES.md for details.
2026-07-17 14:05:01 -07:00
josh 63d6e0746f v1.2.4 release: bus-rate guard on Out/In/ReplaceOut constructors 2026-07-14 16:12:53 -07:00
josh c058493a98 v1.2.3 release: remove ShoeGaze CLI scaffolding (ShoeGaze now standalone) 2026-07-04 22:48:23 -07:00
josh 8a2eb191a2 improve freq trackers 2026-07-02 14:48:37 -07:00
josh 676e8d3278 1.2.1 release to support some ShoeGaze features 2026-07-02 10:20:40 -07:00
179 changed files with 6296 additions and 3283 deletions
+45 -1
View File
@@ -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. `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: 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.) - **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. - **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). - **`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`. 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 ## Where to go deeper
+17 -1
View File
@@ -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`. 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 ## Task → Doc Map
**Engine / RT core** **Engine / RT core**
@@ -71,7 +88,6 @@ The `.githooks/pre-commit` hook calls `--check`. Skips silently when `~/.claude/
- Dev workflow / phase branches / build → `docs/tooling/workflow.md` - Dev workflow / phase branches / build → `docs/tooling/workflow.md`
- Xcode project templates → `docs/tooling/xcode-templates.md` - Xcode project templates → `docs/tooling/xcode-templates.md`
- AUv3 plugin internals (`LyrebirdAudioUnit`, `LyrebirdAUVoicePoolBinding`, `AUInput`, preset codable, parameter slots) → `Sources/Lyrebird/Lyrebird.docc/AUv3.md` - AUv3 plugin internals (`LyrebirdAudioUnit`, `LyrebirdAUVoicePoolBinding`, `AUInput`, preset codable, parameter slots) → `Sources/Lyrebird/Lyrebird.docc/AUv3.md`
- ShoeGaze guitar-pedalboard sub-package (`Pedal`, `PedalBoard`, `ShoeGaze`, built-in pedals, `.testLoop` vs `.liveInput`, `lyrebird new --template shoegaze` workflow) → `docs/stdlib/shoegaze.md`
**UI** **UI**
- LyrebirdUI / parameter binding → `docs/ui/gui-system.md` - LyrebirdUI / parameter binding → `docs/ui/gui-system.md`
@@ -17,7 +17,7 @@ final class BufferDemos: DemoProtocol {
func runDemo() { func runDemo() {
// BufferDemos.swift lives at .../Demos/LyrebirdDemo/LyrebirdDemo/Demos/BufferDemos.swift // 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) let percURL: URL = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent() // .../Demos/ .deletingLastPathComponent() // .../Demos/
.deletingLastPathComponent() // .../LyrebirdDemo/ .deletingLastPathComponent() // .../LyrebirdDemo/
@@ -37,10 +37,6 @@ final class BufferDemos: DemoProtocol {
let sampleRate: Double = engine.sampleRate 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)] = [ let pitchSteps: [(Double, String)] = [
(0.5, "0.5 — octave down"), (0.5, "0.5 — octave down"),
(0.75, "0.75 — minor third 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)"), (0.33, "0.33 — 3× compression (triple speed, pitch preserved)"),
] ]
// Pre-construct all synthesizers on the main actor before entering the @Sendable closure. // `runDemo()` is @MainActor (see DemoProtocol), so the @MainActor synths are constructed
let (demo1, demo2, demo3, pitchRatioNode, demo4Array, demo5Array, demo6Array): // directly — no `MainActor.assumeIsolated` wrapping. Build them here, then hand the
(PercPlayBuffer, PercBufferRead, PercPitchShift, ParameterNode, // resulting instances / live-param node to the @Sendable task body.
[PercSpectralPitchShift], [PercSpectralStereoDiffuse], [PercTimeStretch]) = let demo1: PercPlayBuffer = PercPlayBuffer(buffer: percBuffer, engineSampleRate: sampleRate)
MainActor.assumeIsolated { let demo2: PercBufferRead = PercBufferRead(buffer: percBuffer)
let d1: PercPlayBuffer = PercPlayBuffer(buffer: percBuffer, engineSampleRate: sampleRate) let demo3: PercPitchShift = PercPitchShift(buffer: percBuffer, engineSampleRate: sampleRate)
let d2: PercBufferRead = PercBufferRead(buffer: percBuffer) let pitchRatioNode: ParameterNode = demo3.$pitchRatio
let d3: PercPitchShift = PercPitchShift(buffer: percBuffer, engineSampleRate: sampleRate)
let prNode: ParameterNode = d3.$pitchRatio
let d4: [PercSpectralPitchShift] = spectralRatios.map { ratio, _ in let demo4Array: [PercSpectralPitchShift] = spectralRatios.map { ratio, _ in
PercSpectralPitchShift(buffer: percBuffer, pitchRatio: ratio, engineSampleRate: sampleRate) PercSpectralPitchShift(buffer: percBuffer, pitchRatio: ratio, engineSampleRate: sampleRate)
} }
let d5: [PercSpectralStereoDiffuse] = diffuseSteps.map { amount, _ in let demo5Array: [PercSpectralStereoDiffuse] = diffuseSteps.map { amount, _ in
PercSpectralStereoDiffuse(buffer: percBuffer, amount: amount, engineSampleRate: sampleRate) PercSpectralStereoDiffuse(buffer: percBuffer, amount: amount, engineSampleRate: sampleRate)
} }
let d6: [PercTimeStretch] = stretchSteps.map { factor, _ in let demo6Array: [PercTimeStretch] = stretchSteps.map { factor, _ in
PercTimeStretch(buffer: percBuffer, stretchFactor: factor) PercTimeStretch(buffer: percBuffer, stretchFactor: factor)
} }
return (d1, d2, d3, prNode, d4, d5, d6)
}
LyrebirdTask.run(engine: engine) { ctx in LyrebirdTask.run(engine: engine) { ctx in
// Demo 1 — PlayBuffer (looping at native rate) // Demo 1 — PlayBuffer (looping at native rate)
@@ -112,8 +104,7 @@ final class BufferDemos: DemoProtocol {
ctx.add(demo3) ctx.add(demo3)
for (ratio, label) in pitchSteps { for (ratio, label) in pitchSteps {
print(" pitchRatio \(label)") print(" pitchRatio \(label)")
// Update via ParameterNode.value — nonisolated atomic setter, RT-safe. ctx.set(pitchRatioNode, to: ratio) // live-param write from the task body
pitchRatioNode.value = ratio
try ctx.wait(seconds: 3) try ctx.wait(seconds: 3)
} }
ctx.remove(demo3) ctx.remove(demo3)
@@ -7,5 +7,10 @@
import LyrebirdSynth import LyrebirdSynth
protocol DemoProtocol { 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 let sampleRate: Double = engine.sampleRate
// SynthesizerBase is @MainActor-isolated. Pre-construct the synth on the main actor // `runDemo()` is @MainActor (see DemoProtocol), so the @MainActor synth is constructed and
// before entering the @Sendable LyrebirdTask closure. runDemo() is reached from // its live-param node read directly
// main.swift on the main thread, so assumeIsolated is valid. let reverbDemo: GVerbTest = GVerbTest(sampleRate: sampleRate)
let reverbDemo: GVerbTest = MainActor.assumeIsolated {
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 LyrebirdTask.run(engine: engine) { ctx in
ctx.tempo = 60.0 ctx.tempo = 60.0
ctx.add(reverbDemo) 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) ctx.remove(reverbDemo)
print("\nAll buffer demos complete.") print("\nAll reverb demos complete.")
} }
} }
} }
@@ -14,17 +14,21 @@
import LyrebirdSynth import LyrebirdSynth
final class GVerbTest: SynthesizerBase { 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 private let sampleRate: Double
init(sampleRate: Double) { init(sampleRate: Double) {
self.sampleRate = sampleRate self.sampleRate = sampleRate
} }
override func build() { override func build() {
let impulse = Impulse.Audio(freq: 0.5) let impulse = Impulse.Audio(freq: 0.5)
let reverb = GVerb.Audio(source: impulse, let reverb = GVerb.Audio(source: impulse,
roomSize: 70.0, roomSize: 70.0,
reverbTime: 3.0, reverbTime: $reverbTime, // live ParameterNode, not the baked scalar
earlyLevel: 0.4, earlyLevel: 0.4,
tailLevel: 0.9, tailLevel: 0.9,
dryLevel: 0.1, dryLevel: 0.1,
+4 -3
View File
@@ -9,7 +9,7 @@ import LyrebirdSynth
let engine = SynthesisEngine( let engine = SynthesisEngine(
blockSize: 512, blockSize: 512,
sampleRate: 48000, sampleRate: 44100,
numOutputChannels: 2, numOutputChannels: 2,
numInputChannels: 2, numInputChannels: 2,
driver: CoreAudioDriver() driver: CoreAudioDriver()
@@ -22,6 +22,7 @@ do {
exit(1) exit(1)
} }
BufferDemos(engine: engine).runDemo() // BufferDemos(engine: engine).runDemo()
//ReverbDemo(engine: engine).runDemo() ReverbDemo(engine: engine).runDemo()
engine.stop() engine.stop()
+1 -1
View File
@@ -17,7 +17,7 @@ let package = Package(
.executableTarget( .executableTarget(
name: "LyrebirdDemo", name: "LyrebirdDemo",
dependencies: [ dependencies: [
.product(name: "Lyrebird", package: "LyrebirdII"), .product(name: "Lyrebird", package: "Lyrebird"),
], ],
path: "LyrebirdDemo" path: "LyrebirdDemo"
), ),
@@ -12,7 +12,7 @@ import LyrebirdUI
// ── Demo selector ───────────────────────────────────────────────────────────── // ── Demo selector ─────────────────────────────────────────────────────────────
// Change `demo` to `.sineTone` or `.binDelay` to switch demos. // Change `demo` to `.sineTone` or `.binDelay` to switch demos.
private enum Demo { case vector, binDelay, sineTone } private enum Demo { case vector, binDelay, sineTone }
private let demo: Demo = .binDelay private let demo: Demo = .vector
// ────────────────────────────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────────────────────────────
final class AppDelegate: NSObject, NSApplicationDelegate { final class AppDelegate: NSObject, NSApplicationDelegate {
@@ -9,7 +9,7 @@ import LyrebirdSynth
let engine = SynthesisEngine( let engine = SynthesisEngine(
blockSize: 512, blockSize: 512,
sampleRate: 48000, sampleRate: 44100,
numOutputChannels: 2, numOutputChannels: 2,
numInputChannels: 0, numInputChannels: 0,
driver: CoreAudioDriver() driver: CoreAudioDriver()
+1 -1
View File
@@ -17,7 +17,7 @@ let package = Package(
.executableTarget( .executableTarget(
name: "LyrebirdNRTDemo", name: "LyrebirdNRTDemo",
dependencies: [ dependencies: [
.product(name: "Lyrebird", package: "LyrebirdII"), .product(name: "Lyrebird", package: "Lyrebird"),
], ],
path: "LyrebirdNRTDemo" 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 */;
}
@@ -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>
@@ -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"
),
]
)
+1 -1
View File
@@ -17,7 +17,7 @@ let package = Package(
.executableTarget( .executableTarget(
name: "LyrebirdScoreDemo", name: "LyrebirdScoreDemo",
dependencies: [ dependencies: [
.product(name: "Lyrebird", package: "LyrebirdII"), .product(name: "Lyrebird", package: "Lyrebird"),
], ],
path: "LyrebirdScoreDemo" path: "LyrebirdScoreDemo"
), ),
+15 -4
View File
@@ -100,11 +100,21 @@ Full reference: [`docs/tooling/cli-guide.md`](docs/tooling/cli-guide.md).
## Generating projects ## 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). `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 | | 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` | | `demo` | SPM-only | A `SineTone` synth with `@LiveParam` frequency/amplitude. | `CoreAudioDriver` |
| `ui-demo` | SPM-only | AppKit window with `@UIParam` knobs + `LyrebirdWindow`. | `CoreAudioDriver` | | `ui-demo` | SPM-only | AppKit window with `@UIParam` knobs + `LyrebirdWindow`. | `CoreAudioDriver` |
| `nrt` | SPM-only | Renders to `output.caf`, no hardware needed. | `NRTDriver` | | `nrt` | SPM-only | Renders to `output.caf`, no hardware needed. | `NRTDriver` |
@@ -170,9 +180,9 @@ import LyrebirdSynth
import LyrebirdUI import LyrebirdUI
struct ContentView: View { struct ContentView: View {
@StateObject var synth = ToneSynth() // ToneSynth: SynthesizerBase with @UIParam let synth: ToneSynth // ToneSynth: SynthesizerBase with @UIParam
var body: some View { 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 ## 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 | | Demo | Mirrors template |
|---|---| |---|---|
| [`LyrebirdQuickstartDemo`](Demos/LyrebirdQuickstartDemo/) | `quickstart` |
| [`LyrebirdDemo`](Demos/LyrebirdDemo/) | real-time CLI | | [`LyrebirdDemo`](Demos/LyrebirdDemo/) | real-time CLI |
| [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | `macos-ui-xcode` | | [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | `macos-ui-xcode` |
| [`LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/) | `ios-ui` | | [`LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/) | `ios-ui` |
+17 -4
View File
@@ -1,18 +1,29 @@
# Lyrebird — Start Here # 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 ## 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. 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 ### LyrebirdDemo — Real-Time CLI
@@ -40,7 +51,9 @@ final class MySynth: SynthesizerBase {
@UIParam var amp: Double = 0.5 @UIParam var amp: Double = 0.5
override func build() { 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)) output(bus: 0, source: Pan2(input: sig, pan: 0))
} }
} }
+3
View File
@@ -1,6 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<Workspace <Workspace
version = "1.0"> version = "1.0">
<FileRef
location = "group:Demos/LyrebirdQuickstartDemo/LyrebirdQuickstartDemo.xcodeproj">
</FileRef>
<FileRef <FileRef
location = "group:Demos/LyrebirdDemo/LyrebirdDemo.xcodeproj"> location = "group:Demos/LyrebirdDemo/LyrebirdDemo.xcodeproj">
</FileRef> </FileRef>
+2 -2
View File
@@ -41,8 +41,8 @@ let package = Package(
// swift-docc-plugin — command plugin that drives DocC documentation builds. // swift-docc-plugin — command plugin that drives DocC documentation builds.
// Registers two commands available to all targets in this package: // Registers two commands available to all targets in this package:
// • In Xcode: Product ▸ Build Documentation (or scheme-level build action) // • In Xcode: Product ▸ Build Documentation (or scheme-level build action)
// • From CLI: swift package generate-documentation --target Lyrebird // • From CLI: swift package generate-documentation --target LyrebirdSynth
// swift package preview-documentation --target Lyrebird // swift package preview-documentation --target LyrebirdSynth
// No target-level plugins: entry is needed — command plugins apply package-wide. // No target-level plugins: entry is needed — command plugins apply package-wide.
.package( .package(
url: "https://github.com/apple/swift-docc-plugin", url: "https://github.com/apple/swift-docc-plugin",
+16 -8
View File
@@ -120,7 +120,7 @@ The REPL is text-only and works from any project that depends on Lyrebird; the s
## New here? ## 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 ## 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: For the package itself:
@@ -161,16 +161,18 @@ xed . # opens Package.swift — Xcode auto-generates schemes for every target
### Schemes ### Schemes
Workspace scheme selector exposes eight entries: Workspace scheme selector exposes ten entries:
| Scheme | Purpose | Platform | | Scheme | Purpose | Platform |
|---|---|---| |---|---|---|
| `Lyrebird-Package` | Umbrella — builds Lyrebird + LyrebirdUI + LyrebirdLiveCompile + LyrebirdC + LyrebirdBenchmark + LyrebirdCLI, runs the test suites, launches/profiles `LyrebirdCLI` | macOS | | `Lyrebird-Package` | Umbrella — builds Lyrebird + LyrebirdUI + LyrebirdLiveCompile + LyrebirdC + LyrebirdBenchmark + LyrebirdCLI, runs the test suites, launches/profiles `LyrebirdCLI` | macOS |
| `LyrebirdQuickstartDemo` | CLI — fastest sound: a one-oscillator `SineTone` that plays 440 Hz for 10 s and exits | macOS |
| `LyrebirdUI` | Builds the `LyrebirdUI` module only (SwiftUI parameter controls + visualisations) | macOS | | `LyrebirdUI` | Builds the `LyrebirdUI` module only (SwiftUI parameter controls + visualisations) | macOS |
| `LyrebirdDemo` | CLI — plays through default output via `CoreAudioDriver` | macOS | | `LyrebirdDemo` | CLI — plays through default output via `CoreAudioDriver` | macOS |
| `LyrebirdMacOSDemo` | SwiftUI app — live oscilloscope, `@UIParam` knobs | macOS | | `LyrebirdMacOSDemo` | SwiftUI app — live oscilloscope, `@UIParam` knobs | macOS |
| `LyrebirdiOSDemo` | SwiftUI app — same UI via `iOSAudioDriver` (RemoteIO) | iOS | | `LyrebirdiOSDemo` | SwiftUI app — same UI via `iOSAudioDriver` (RemoteIO) | iOS |
| `LyrebirdNRTDemo` | CLI — offline render to CAF via `NRTDriver` | macOS | | `LyrebirdNRTDemo` | CLI — offline render 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 | | `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 | | `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 ```bash
swift build # build all targets 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 test --filter LyrebirdTests # run one suite
swift run lyrebird # run the CLI swift run lyrebird # run the CLI
swift run lyrebird repl # Swift REPL with Lyrebird available swift run lyrebird repl # Swift REPL with Lyrebird available
@@ -203,14 +205,16 @@ swift run LyrebirdDemo # run the hardware smoke-test demo
## Demo projects ## 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 | | 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 | | [`LyrebirdDemo`](Demos/LyrebirdDemo/) | CLI — plays through default output via `CoreAudioDriver` | macOS |
| [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | SwiftUI app — live oscilloscope, `@UIParam` knobs | macOS | | [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | SwiftUI app — live oscilloscope, `@UIParam` knobs | macOS |
| [`LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/) | SwiftUI app — same UI system via `iOSAudioDriver` (RemoteIO) | iOS | | [`LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/) | SwiftUI app — same UI system via `iOSAudioDriver` (RemoteIO) | iOS |
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | CLI — offline render to CAF file via `NRTDriver` | macOS | | [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | CLI — offline render 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 | | [`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 | | [`LyrebirdScratchDemo`](Demos/LyrebirdScratchDemo/) | Live-coding scratchpad — type Swift, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
@@ -231,8 +235,10 @@ lyrebird --help # verify
Then: Then:
```bash ```bash
lyrebird new MyPiece --template ui-demo # scaffold a standalone project lyrebird new MyFirstSound --template quickstart # fastest path to sound (plays 10 s, then exits)
open MyPiece/MyPiece.xcworkspace # open in Xcode (workspace refs Package.swift) 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 # enter the lyrebird> interactive shell
lyrebird repl # Swift REPL with Lyrebird importable lyrebird repl # Swift REPL with Lyrebird importable
lyrebird --version lyrebird --version
@@ -269,14 +275,16 @@ LyrebirdII/
│ ├── LyrebirdCLI/ # lyrebird CLI binary │ ├── LyrebirdCLI/ # lyrebird CLI binary
│ └── LyrebirdDemo/ # macOS CLI hardware smoke-test │ └── LyrebirdDemo/ # macOS CLI hardware smoke-test
├── Demos/ ├── Demos/
│ ├── LyrebirdQuickstartDemo/ # fastest sound — SineTone plays 10 s then exits
│ ├── LyrebirdDemo/ # (same as Sources/LyrebirdDemo — workspace target) │ ├── LyrebirdDemo/ # (same as Sources/LyrebirdDemo — workspace target)
│ ├── LyrebirdMacOSDemo/ # macOS SwiftUI app │ ├── LyrebirdMacOSDemo/ # macOS SwiftUI app
│ ├── LyrebirdiOSDemo/ # iOS SwiftUI app │ ├── LyrebirdiOSDemo/ # iOS SwiftUI app
│ ├── LyrebirdNRTDemo/ # offline renderer │ ├── LyrebirdNRTDemo/ # offline renderer
│ ├── LyrebirdScoreDemo/ # notated Score → MusicXML + offline render
│ ├── LyrebirdAUv3Demo/ # AUv3 `aumu` plugin reference (LyrebirdFM) │ ├── LyrebirdAUv3Demo/ # AUv3 `aumu` plugin reference (LyrebirdFM)
│ └── LyrebirdScratchDemo/ # live-coding scratchpad (macOS, no sandbox) │ └── LyrebirdScratchDemo/ # live-coding scratchpad (macOS, no sandbox)
├── Tests/ ├── Tests/
│ ├── LyrebirdTests/ # 3544 engine + generator tests │ ├── LyrebirdTests/ # 5253 engine + generator tests
│ ├── LyrebirdUITests/ # SwiftUI component tests │ ├── LyrebirdUITests/ # SwiftUI component tests
│ └── LyrebirdCLITests/ # CLI tests │ └── LyrebirdCLITests/ # CLI tests
└── docs/ └── docs/
+55 -9
View File
@@ -7,13 +7,60 @@ 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)* ## 1.2.0 — Generator catalog expansion *(planned)*
A minor release. Adds roughly forty SuperCollider-parity generators — A minor release. Adds roughly forty SuperCollider-parity generators —
triggers, time-domain analysis, chaotic oscillators, resonator banks, dynamics, triggers, time-domain analysis, chaotic oscillators, resonator banks, dynamics,
waveshaping, routing/morph, and psychoacoustic metering — plus a `shoegaze` waveshaping, routing/morph, and psychoacoustic metering — plus an iOS path fix.
guitar-pedalboard project template and an iOS path fix. Fully Fully backward-compatible; no changes to existing public API.
backward-compatible; no changes to existing public API.
### New generators ### New generators
@@ -59,12 +106,11 @@ gain lag).
### Tooling ### Tooling
- **`shoegaze` project template.** `lyrebird new MyRig --template shoegaze` - **ShoeGaze moved out of tree.** The guitar-pedalboard framework and its
scaffolds a guitar-pedalboard app (macOS or iOS) that depends on the ShoeGaze project/pedal scaffolding now live in a standalone ShoeGaze repository that
package — a set of effect "pedals" chained into boards, with knobs, bypass, depends on Lyrebird as a package. Lyrebird's CLI no longer ships the
parallel routing, and recording. Ships with an Xcode "ShoeGaze Pedal" file `shoegaze` / `shoegaze-ios` project templates or the "ShoeGaze Pedal" Xcode
template for authoring custom pedals. ShoeGaze itself now lives in its own file template.
repository rather than in-tree.
### Fixes ### Fixes
@@ -240,6 +240,11 @@ public final class NRTDriver: AudioDriver {
throw NRTDriverError.writeFailed(writeStatus) 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() { public func stop() {
@@ -117,6 +117,9 @@ import Synchronization
/// `invalidate()` uses a `.releasing` store; `isValid` uses an `.acquiring` load. /// `invalidate()` uses a `.releasing` store; `isValid` uses an `.acquiring` load.
/// `LyrebirdBuffer` is safe to share across threads: /// `LyrebirdBuffer` is safe to share across threads:
/// - The validity flag is protected by `Atomic<Bool>`. /// - 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. /// - `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 /// - 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 /// `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 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()`. /// Atomic validity flag. `true` after `init`, `false` after `invalidate()`.
private let _isValid: Atomic<Bool> private let _isValid: Atomic<Bool>
@@ -460,6 +502,7 @@ public final class LyrebirdBuffer: @unchecked Sendable {
_storage = UnsafeMutablePointer<Double>.allocate(capacity: total) _storage = UnsafeMutablePointer<Double>.allocate(capacity: total)
_storage.initialize(repeating: 0, count: total) _storage.initialize(repeating: 0, count: total)
_isValid = Atomic<Bool>(true) _isValid = Atomic<Bool>(true)
_loopLength = Atomic<Int>(count)
} }
deinit { deinit {
+42
View File
@@ -44,3 +44,45 @@ func _resolvedChannelCount(_ bus: any ValidBus) -> Int {
bus.channelCount == Int.max ? 1 : max(1, bus.channelCount) 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 /// ## Per-distribution examples
/// ///
/// All examples use `TemporalTendency` with fixed `.value(…)` parameters and /// All examples build a ``TemporalStream`` over a ``TemporalTendency`` with fixed
/// `seed: 0xDEADCAFE12345678`. Actual outputs vary with seed. /// `.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\] /// **`.uniform`** — flat probability across \[lo, hi\]
/// ```swift /// ```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 /// // → 0.744, 0.046, 0.799, 0.681, 0.517
/// ``` /// ```
/// ///
/// **`.lpRand`** — squared uniform, biases toward lo /// **`.lpRand`** — squared uniform, biases toward lo
/// ```swift /// ```swift
/// TemporalTendency(distribution: .lpRand, parX: .value(0), parY: .value(1), seed: s) /// TemporalStream(TemporalTendency(distribution: .lpRand,
/// // → 0.080, 0.337, 0.057, 0.830, 0.788 /// 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 /// **`.hpRand`** — squared uniform mirrored, biases toward hi
/// ```swift /// ```swift
/// TemporalTendency(distribution: .hpRand, parX: .value(0), parY: .value(1), seed: s) /// TemporalStream(TemporalTendency(distribution: .hpRand,
/// // → 0.878, 0.944, 0.939, 0.983, 0.899 /// 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 /// **`.meanRand`** — average of two uniforms (triangular), biases toward midpoint
/// ```swift /// ```swift
/// TemporalTendency(distribution: .meanRand, parX: .value(0), parY: .value(1), seed: s) /// TemporalStream(TemporalTendency(distribution: .meanRand,
/// // → 0.624, 0.559, 0.512, 0.586, 0.308 /// 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 /// **`.expRand`** — log-uniform, exponential density in \[lo, hi\]; lo and hi must be > 0
/// ```swift /// ```swift
/// TemporalTendency(distribution: .expRand, parX: .value(1), parY: .value(100), seed: s) /// TemporalStream(TemporalTendency(distribution: .expRand,
/// // → 15.709, 4.710, 14.831, 26.119, 47.853 /// 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) /// **`.exponential`** — standard exponential; parX is the rate λ (higher = shorter tail)
/// ```swift /// ```swift
/// TemporalTendency(distribution: .exponential, parX: .value(1), seed: s) /// TemporalStream(TemporalTendency(distribution: .exponential, parX: .value(1)),
/// // → 0.023, 0.489, 0.126, 2.077, 0.354 /// 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 /// **`.gamma`** — shape parameter k; k=1 → exponential, k>1 → bell shifted right
/// ```swift /// ```swift
/// TemporalTendency(distribution: .gamma, parX: .value(2), seed: s) /// TemporalStream(TemporalTendency(distribution: .gamma, parX: .value(2)),
/// // → 0.412, 2.998, 0.709, 1.409, 3.985 /// seed: 0xDEADCAFE12345678).collect(5)
/// // → 2.812, 0.776, 1.756, 1.326, 3.649
/// ``` /// ```
/// ///
/// **`.laplace`** — double-exponential, sharp central peak; parX is scale b /// **`.laplace`** — double-exponential, sharp central peak; parX is scale b
/// ```swift /// ```swift
/// TemporalTendency(distribution: .laplace, parX: .value(1), seed: s) /// TemporalStream(TemporalTendency(distribution: .laplace, parX: .value(1)),
/// // → 3.533, 0.530, -0.197, 0.195, -1.792 /// 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 /// **`.alaplace`** — asymmetric Laplace (p=0.7), right tail heavier; parX is scale b
/// ```swift /// ```swift
/// TemporalTendency(distribution: .alaplace, parX: .value(1), seed: s) /// TemporalStream(TemporalTendency(distribution: .alaplace, parX: .value(1)),
/// // → -0.706, 7.906, 1.867, -0.495, 1.675 /// 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/π\] /// **`.hcos`** — half-cosine, smooth bell centred at 0; output ≈ \[−d/π, d/π\]
/// ```swift /// ```swift
/// TemporalTendency(distribution: .hcos, parX: .value(1), seed: s) /// TemporalStream(TemporalTendency(distribution: .hcos, parX: .value(1)),
/// // → -0.080, 0.021, 0.024, -0.366, 0.215 /// 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 /// **`.logistic`** — logistic distribution, heavier tails than Gaussian; parX is scale s
/// ```swift /// ```swift
/// TemporalTendency(distribution: .logistic, parX: .value(1), seed: s) /// TemporalStream(TemporalTendency(distribution: .logistic, parX: .value(1)),
/// // → 0.299, 3.453, -1.994, 1.842, -0.640 /// 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\]) /// **`.poisson`** — integer counts; parX is mean λ (clamped to \[0.001, 30\])
/// ```swift /// ```swift
/// TemporalTendency(distribution: .poisson, parX: .value(3), seed: s) /// TemporalStream(TemporalTendency(distribution: .poisson, parX: .value(3)),
/// // → 3.0, 3.0, 6.0, 5.0, 0.0 /// seed: 0xDEADCAFE12345678).collect(5)
/// // → 1.000, 4.000, 4.000, 1.000, 4.000
/// ``` /// ```
/// ///
/// **`.arcsin`** — U-shaped, concentrates near ±dispersion; output in \[−disp, disp\] /// **`.arcsin`** — U-shaped, concentrates near ±dispersion; output in \[−disp, disp\]
/// ```swift /// ```swift
/// TemporalTendency(distribution: .arcsin, parX: .value(1), seed: s) /// TemporalStream(TemporalTendency(distribution: .arcsin, parX: .value(1)),
/// // → 0.616, -0.148, -0.986, -0.987, -0.417 /// 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 /// **`.betaRand`** — flexible shape in \[lo, hi\]; alpha/beta (parA/parB) control skew
/// ```swift /// ```swift
/// // alpha=2, beta=5 → left-skewed bell (peak near lo side) /// // alpha=2, beta=5 → left-skewed bell (peak near lo side)
/// TemporalTendency(distribution: .betaRand, /// TemporalStream(TemporalTendency(distribution: .betaRand,
/// parX: .value(0), parY: .value(1), /// parX: .value(0), parY: .value(1),
/// parA: .value(2), parB: .value(5), seed: s) /// parA: .value(2), parB: .value(5)),
/// // → 0.395, 0.539, 0.272, 0.386, 0.304 /// 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 /// // 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 /// **`.cauchy`** — heavy-tailed, parX=mean, parY=spread; set parA>0 for positive-only
/// ```swift /// ```swift
/// TemporalTendency(distribution: .cauchy, parX: .value(0), parY: .value(1), seed: s) /// TemporalStream(TemporalTendency(distribution: .cauchy,
/// // → -1.457, 0.800, 10.047, 1.641, -1.570 /// 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) /// // (occasional extreme outliers are characteristic of Cauchy)
/// ///
/// // Positive-only (parA > 0): /// // 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 /// **`.gauss`** — Gaussian; parX=standard deviation, parY=mean
/// ```swift /// ```swift
/// TemporalTendency(distribution: .gauss, parX: .value(1), parY: .value(0), seed: s) /// TemporalStream(TemporalTendency(distribution: .gauss,
/// // → -0.554, 1.390, 0.086, -0.441, 2.156 /// parX: .value(1), parY: .value(0)),
/// seed: 0xDEADCAFE12345678).collect(5)
/// // → 0.738, -0.281, -0.238, 0.068, 0.328
/// ``` /// ```
public enum DistributionKind: Sendable { public enum DistributionKind: Sendable {
+1
View File
@@ -165,6 +165,7 @@ public final class EngineHost: @unchecked Sendable {
numAudioBuses: config.numAudioBuses, numAudioBuses: config.numAudioBuses,
numControlBuses: config.numControlBuses, numControlBuses: config.numControlBuses,
eventQueueCapacity: config.eventQueueCapacity, eventQueueCapacity: config.eventQueueCapacity,
maxEventsPerBlock: config.maxEventsPerBlock,
driver: config.driver driver: config.driver
) )
@@ -19,6 +19,9 @@ import Foundation
/// would invoke the mutation off-main. /// would invoke the mutation off-main.
/// - `LyrebirdAudioUnit.allocateRenderResources()` — overrides a nonisolated `AUAudioUnit` /// - `LyrebirdAudioUnit.allocateRenderResources()` — overrides a nonisolated `AUAudioUnit`
/// method; AU hosts *usually* call it on main, but the contract does not guarantee it. /// 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 /// A bare `MainActor.assumeIsolated` would **trap** (`dispatch_assert_queue_fail`) on those
/// off-main paths. This bridge instead: /// off-main paths. This bridge instead:
+91 -12
View File
@@ -29,14 +29,18 @@ import Synchronization
/// driver: driver /// driver: driver
/// ) /// )
/// try engine.start() /// try engine.start()
/// engine.add(MySynth()) /// try engine.add(MySynth())
/// // … audio running … /// // … audio running …
/// engine.stop() /// engine.stop()
/// ``` /// ```
/// ///
/// **Thread safety** — `processBlock` runs on the Core Audio RT thread. All public /// **Thread safety** — `processBlock` runs on the Core Audio RT thread; never call it directly
/// scheduling methods (`add`, `remove`, `schedule`) are safe to call from the main thread. /// while the engine is running. `add(_:)` / `schedule(_:at:)` are `@MainActor`-isolated: the
/// Never call `processBlock` directly from the main thread while the engine is running. /// `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 { public final class SynthesisEngine {
/// Process-unique identity. Used by the engine ownership-binding system /// 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 /// 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 /// in start(); if more events arrive, excess events are silently dropped rather than
/// triggering a realloc on the RT thread. /// 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. /// 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. /// 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) _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`). /// Update the synth/group counters by `delta` (typically `+1` or `-1`).
/// Called from `applyEvent` on the RT thread — uses relaxed atomic adds (no allocation, /// 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`, /// no locks, no runtime type checks). The `isGroup` flag is read from `PreparedNode`,
@@ -732,13 +799,13 @@ public final class SynthesisEngine {
/// ///
/// ```swift /// ```swift
/// // Pre-processing: runs before all instruments /// // 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 /// // Default instrument add — lands in mainGroup
/// engine.add(MySynth()) /// try engine.add(MySynth())
/// ///
/// // Post-processing: runs after all instruments /// // 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) public let mainGroup: Group = Group(persistent: true)
@@ -763,6 +830,7 @@ public final class SynthesisEngine {
numAudioBuses: Int = lyrebirdDefaultNumAudioBuses, numAudioBuses: Int = lyrebirdDefaultNumAudioBuses,
numControlBuses: Int = lyrebirdDefaultNumControlBuses, numControlBuses: Int = lyrebirdDefaultNumControlBuses,
eventQueueCapacity: Int = lyrebirdDefaultEventQueueCapacity, eventQueueCapacity: Int = lyrebirdDefaultEventQueueCapacity,
maxEventsPerBlock: Int = lyrebirdDefaultMaxEventsPerBlock,
driver: AudioDriver driver: AudioDriver
) { ) {
// Initialise RT-thread identity TLS key from this known non-RT call // 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 > 0 && eventQueueCapacity & (eventQueueCapacity - 1) == 0,
"eventQueueCapacity \(eventQueueCapacity) must be a power of two (e.g. 256, 512, 1024, 2048)." "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). // 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 // 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. // 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.numInputChannels = numInputChannels
self.numAudioBuses = numAudioBuses self.numAudioBuses = numAudioBuses
self.numControlBuses = numControlBuses self.numControlBuses = numControlBuses
self.maxEventsPerBlock = maxEventsPerBlock
self.busAllocator = BusAllocator( self.busAllocator = BusAllocator(
numAudioBuses: numAudioBuses, numAudioBuses: numAudioBuses,
numControlBuses: numControlBuses, numControlBuses: numControlBuses,
@@ -998,9 +1071,9 @@ public final class SynthesisEngine {
// Pre-allocate staging arrays to the hard cap — no RT realloc as long as // Pre-allocate staging arrays to the hard cap — no RT realloc as long as
// events-per-block stays within maxEventsPerBlock (excess are dropped). // events-per-block stays within maxEventsPerBlock (excess are dropped).
carryOverEvents.reserveCapacity(SynthesisEngine.maxEventsPerBlock) carryOverEvents.reserveCapacity(maxEventsPerBlock)
thisBlockEvents.reserveCapacity(SynthesisEngine.maxEventsPerBlock) thisBlockEvents.reserveCapacity(maxEventsPerBlock)
nextCarryOver.reserveCapacity(SynthesisEngine.maxEventsPerBlock) nextCarryOver.reserveCapacity(maxEventsPerBlock)
// Force eager initialization of module-level `let` constants used by RBJ filters. // 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 // 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.drainParameterSourceKillQueue()
self.drainBufferSwapKillQueue() self.drainBufferSwapKillQueue()
self.drainPerBlockEventDropWarning()
} }
_setState(.stopped) _setState(.stopped)
} }
@@ -1493,7 +1567,7 @@ public final class SynthesisEngine {
// Read clock atomically; only processBlock writes it (RT thread single-writer). // Read clock atomically; only processBlock writes it (RT thread single-writer).
let blockStart: SampleTime = _currentTime.load(ordering: .relaxed) let blockStart: SampleTime = _currentTime.load(ordering: .relaxed)
let blockEnd: SampleTime = blockStart + SampleTime(blockSize) let blockEnd: SampleTime = blockStart + SampleTime(blockSize)
let cap: Int = SynthesisEngine.maxEventsPerBlock let cap: Int = maxEventsPerBlock
thisBlockEvents.removeAll(keepingCapacity: true) thisBlockEvents.removeAll(keepingCapacity: true)
nextCarryOver.removeAll(keepingCapacity: true) nextCarryOver.removeAll(keepingCapacity: true)
@@ -1502,8 +1576,10 @@ public final class SynthesisEngine {
for event: ScheduledEvent in carryOverEvents { for event: ScheduledEvent in carryOverEvents {
if event.targetTime < blockEnd { if event.targetTime < blockEnd {
if thisBlockEvents.count < cap { thisBlockEvents.append(event) } if thisBlockEvents.count < cap { thisBlockEvents.append(event) }
else { _recordPerBlockEventDrop() }
} else { } else {
if nextCarryOver.count < cap { nextCarryOver.append(event) } if nextCarryOver.count < cap { nextCarryOver.append(event) }
else { _recordPerBlockEventDrop() }
} }
} }
@@ -1512,8 +1588,10 @@ public final class SynthesisEngine {
let event: ScheduledEvent = pendingQueue.dequeue() { let event: ScheduledEvent = pendingQueue.dequeue() {
if event.targetTime < blockEnd { if event.targetTime < blockEnd {
if thisBlockEvents.count < cap { thisBlockEvents.append(event) } if thisBlockEvents.count < cap { thisBlockEvents.append(event) }
else { _recordPerBlockEventDrop() }
} else { } else {
if nextCarryOver.count < cap { nextCarryOver.append(event) } if nextCarryOver.count < cap { nextCarryOver.append(event) }
else { _recordPerBlockEventDrop() }
} }
} }
@@ -1780,6 +1858,7 @@ public final class SynthesisEngine {
} }
self.drainParameterSourceKillQueue() self.drainParameterSourceKillQueue()
self.drainBufferSwapKillQueue() self.drainBufferSwapKillQueue()
self.drainPerBlockEventDropWarning()
} }
timer.resume() timer.resume()
freeQueueTimer = timer freeQueueTimer = timer
@@ -65,6 +65,10 @@ public struct SynthesisEngineConfig {
/// `lyrebirdDefaultEventQueueCapacity`. /// `lyrebirdDefaultEventQueueCapacity`.
public let eventQueueCapacity: Int 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 /// Audio driver instance. Held by the engine via `let driver` after
/// `init`. Caller transfers ownership at construction time. /// `init`. Caller transfers ownership at construction time.
public let driver: AudioDriver public let driver: AudioDriver
@@ -78,6 +82,7 @@ public struct SynthesisEngineConfig {
numAudioBuses: Int = lyrebirdDefaultNumAudioBuses, numAudioBuses: Int = lyrebirdDefaultNumAudioBuses,
numControlBuses: Int = lyrebirdDefaultNumControlBuses, numControlBuses: Int = lyrebirdDefaultNumControlBuses,
eventQueueCapacity: Int = lyrebirdDefaultEventQueueCapacity, eventQueueCapacity: Int = lyrebirdDefaultEventQueueCapacity,
maxEventsPerBlock: Int = lyrebirdDefaultMaxEventsPerBlock,
driver: AudioDriver driver: AudioDriver
) { ) {
self.blockSize = blockSize self.blockSize = blockSize
@@ -88,6 +93,7 @@ public struct SynthesisEngineConfig {
self.numAudioBuses = numAudioBuses self.numAudioBuses = numAudioBuses
self.numControlBuses = numControlBuses self.numControlBuses = numControlBuses
self.eventQueueCapacity = eventQueueCapacity self.eventQueueCapacity = eventQueueCapacity
self.maxEventsPerBlock = maxEventsPerBlock
self.driver = driver self.driver = driver
} }
} }
@@ -22,7 +22,7 @@ import Foundation
/// Control-rate, 4-output: see ``BeatTrack/Control`` for the row layout. /// Control-rate, 4-output: see ``BeatTrack/Control`` for the row layout.
/// ///
/// > This is an independent implementation of standard autocorrelation tempo /// > This is an independent implementation of standard autocorrelation tempo
/// > induction with phase locking (see ``BeatTrackerCore``), not a port of any /// > induction with phase locking (see `BeatTrackerCore`), not a port of any
/// > SuperCollider source. /// > SuperCollider source.
public enum BeatTrack { public enum BeatTrack {
@@ -51,7 +51,7 @@ public enum DiskOut {
/// output(bus: 0, source: diskOut[0]) // pass-through to bus 0 /// output(bus: 0, source: diskOut[0]) // pass-through to bus 0
/// } /// }
/// } /// }
/// engine.add(Writer()) /// try engine.add(Writer())
/// try engine.start() // render / play /// try engine.start() // render / play
/// diskOut.close() // flush remaining frames and close the file /// 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`. /// Interpolated read from `buffer` at a fractional frame `phase` for one `channel`.
/// ///
/// - For `loop == true`: frames wrap modulo `buffer.count` (seamless looping). `wrappedFrame` /// - For `loop == true`: frames wrap modulo `buffer.loopLength` (seamless looping).
/// handles negative frame indices via `r += frameCount`, so backward reads across the loop /// `wrappedFrame` handles negative frame indices via `r += frameCount`, so backward
/// point are correct. /// reads across the loop point are correct.
/// - For `loop == false`: frames are clamped to `[0, buffer.count − 1]` (hold at ends). /// - 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 /// Used by `PlayBuffer.Audio` and `PlayBuffer.Control`; exposed as `internal` for reuse by
/// future buffer-reading generators (e.g. `BufferGrain`). /// future buffer-reading generators (e.g. `BufferGrain`).
@@ -25,7 +29,7 @@ internal func lyrebirdBufferRead(
interpolation: TableInterpolation, interpolation: TableInterpolation,
loop: Bool loop: Bool
) -> Double { ) -> Double {
let frameCount: Int = buffer.count let frameCount: Int = buffer.loopLength
@inline(__always) @inline(__always)
func clampedFrame(_ f: Int) -> Int { func clampedFrame(_ f: Int) -> Int {
@@ -356,7 +360,7 @@ public enum PlayBuffer {
return _result return _result
} }
let bufferFrames: Double = Double(buffer.count) let bufferFrames: Double = Double(buffer.loopLength)
@inline(__always) @inline(__always)
func rateAt(_ i: Int) -> Double { func rateAt(_ i: Int) -> Double {
@@ -526,7 +530,7 @@ public enum PlayBuffer {
// Read one output value for this block. // Read one output value for this block.
let outputVal: Double let outputVal: Double
if let buffer: LyrebirdBuffer = _slot.load(engine: graph.engine), buffer.isValid, !_isDone { 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( outputVal = lyrebirdBufferRead(
buffer, channel: 0, phase: _phase, buffer, channel: 0, phase: _phase,
interpolation: interpolation, loop: loop interpolation: interpolation, loop: loop
@@ -90,6 +90,27 @@ public enum RecordBuffer {
var _isDone: Bool = false var _isDone: Bool = false
let _needsFree: Atomic<Bool> = Atomic(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. /// `true` when `doneAction == .freeNode` and recording has completed.
/// ///
/// Read from a non-RT context after `processBlock` returns and schedule /// Read from a non-RT context after `processBlock` returns and schedule
@@ -122,9 +143,42 @@ public enum RecordBuffer {
// MARK: - Shared // 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() { func handleEndOfBuffer() {
_isDone = true _isDone = true
writePos = buffer.count - 1 writePos = buffer.loopLength - 1
switch doneAction { switch doneAction {
case .nothing: case .nothing:
break break
@@ -202,6 +256,10 @@ public enum RecordBuffer {
) -> [[Double]] { ) -> [[Double]] {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } 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 let runSamples: [Double] = $run.calculatedSamples(graph: graph, count: count).first
?? _zeroFallback ?? _zeroFallback
@@ -212,7 +270,12 @@ public enum RecordBuffer {
let chCount: Int = channelCount let chCount: Int = channelCount
let bufferIsLive: Bool = buffer.isValid 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 canRecord: Bool = bufferIsLive && !_isDone
let localLoop: Bool = loop let localLoop: Bool = loop
@@ -524,6 +587,10 @@ public enum RecordBuffer {
) -> [[Double]] { ) -> [[Double]] {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } 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. // Evaluate params: advance ParameterNode state; use settled (last-sample) value.
let runSamples: [Double] = $run.calculatedSamples(graph: graph, count: count).first let runSamples: [Double] = $run.calculatedSamples(graph: graph, count: count).first
@@ -551,7 +618,7 @@ public enum RecordBuffer {
let existing: Double = buffer[writePos, 0] let existing: Double = buffer[writePos, 0]
buffer.write(recVal * inputVal + preVal * existing, frame: writePos, channel: 0) buffer.write(recVal * inputVal + preVal * existing, frame: writePos, channel: 0)
writePos += 1 writePos += 1
if writePos >= buffer.count { if writePos >= buffer.loopLength {
if loop { writePos = 0 } if loop { writePos = 0 }
else { handleEndOfBuffer() } else { handleEndOfBuffer() }
} }
+21 -12
View File
@@ -30,8 +30,9 @@ public enum In {
/// Reads from one or more consecutive audio buses. /// Reads from one or more consecutive audio buses.
/// ///
/// The `bus` parameter accepts any ``ValidBus``: a plain `Int` index (1 channel), /// The `bus` parameter takes a plain `Int` index (1 channel) or an ``AudioBus`` allocation
/// an ``AudioBus`` allocation (channel count taken from the bus), or a ``ControlBus``. /// (channel count taken from the bus). A ``ControlBus`` traps — `In.Audio` reads the audio-bus
/// pool; use ``In/Control`` for a control bus.
/// ///
/// ```swift /// ```swift
/// In.Audio(bus: 5) // reads audioBuses[5], returns 1 channel /// 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). /// `floatValue` always returns the value of the first channel (bus).
/// ///
/// - Parameters: /// - Parameters:
/// - bus: Source bus — `Int` index (1 channel), ``AudioBus`` (reads `channelCount` /// - bus: Source bus — `Int` index (1 channel) or ``AudioBus`` (reads `channelCount`
/// consecutive buses), or ``ControlBus``. /// consecutive buses). A ``ControlBus`` traps; use ``In/Control``.
/// - channels: Only available on the `Int`-index overload. Number of consecutive buses /// - channels: Only available on the `Int`-index overload. Number of consecutive buses
/// to read. Defaults to `1`. Fixed at init — no RT allocation. /// to read. Defaults to `1`. Fixed at init — no RT allocation.
public final class Audio: _Base, AudioGenerator { public final class Audio: _Base, AudioGenerator {
@@ -51,9 +52,10 @@ public enum In {
/// Reads from a ``ValidBus``. /// Reads from a ``ValidBus``.
/// ///
/// - Parameters: /// - Parameters:
/// - bus: Source bus — `Int` index (1 channel), ``AudioBus`` (uses `channelCount`), /// - bus: Source bus — `Int` index (1 channel) or ``AudioBus`` (uses `channelCount`).
/// or ``ControlBus``. /// A ``ControlBus`` traps; use ``In/Control``.
public init(bus: any ValidBus) { public init(bus: any ValidBus) {
_preconditionAudioRateBus(bus)
let ch: Int = _resolvedChannelCount(bus) let ch: Int = _resolvedChannelCount(bus)
super.init(bus: bus.index, channels: ch) 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`. /// 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. /// 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 { public static func multi(bus: any ValidBus) -> GeneratorArray {
_preconditionAudioRateBus(bus)
let ch: Int = _resolvedChannelCount(bus) let ch: Int = _resolvedChannelCount(bus)
return multi(bus: bus.index, channels: ch) 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 /// Reads from one or more consecutive control buses and delivers interpolated audio-rate
/// ramps to downstream generators. /// ramps to downstream generators.
/// ///
/// The `bus` parameter accepts any ``ValidBus``: a plain `Int` index (1 channel), /// The `bus` parameter takes a plain `Int` index (1 channel) or a ``ControlBus`` allocation
/// a ``ControlBus`` allocation (channel count taken from the bus), or an ``AudioBus``. /// (channel count taken from the bus). An ``AudioBus`` traps — `In.Control` reads the
/// control-bus pool; use ``In/Audio`` for an audio bus.
/// ///
/// ```swift /// ```swift
/// In.Control(bus: 10) // reads controlBuses[10], interpolated ramp /// In.Control(bus: 10) // reads controlBuses[10], interpolated ramp
@@ -153,8 +161,8 @@ public enum In {
/// in steady state. /// in steady state.
/// ///
/// - Parameters: /// - Parameters:
/// - bus: Source bus — `Int` index (1 channel), ``ControlBus`` (reads `channelCount` /// - bus: Source bus — `Int` index (1 channel) or ``ControlBus`` (reads `channelCount`
/// consecutive buses with independent ramp state per channel), or ``AudioBus``. /// consecutive buses with independent ramp state per channel). An ``AudioBus`` traps; use ``In/Audio``.
/// - channels: Only available on the `Int`-index overload. Number of consecutive buses /// - channels: Only available on the `Int`-index overload. Number of consecutive buses
/// to read. Defaults to `1`. Fixed at init — no RT allocation. /// to read. Defaults to `1`. Fixed at init — no RT allocation.
public final class Control: _Base, ControlGenerator { public final class Control: _Base, ControlGenerator {
@@ -172,9 +180,10 @@ public enum In {
/// Reads from a ``ValidBus``. /// Reads from a ``ValidBus``.
/// ///
/// - Parameters: /// - Parameters:
/// - bus: Source bus — `Int` index (1 channel), ``ControlBus`` (uses `channelCount`), /// - bus: Source bus — `Int` index (1 channel) or ``ControlBus`` (uses `channelCount`).
/// or ``AudioBus``. /// An ``AudioBus`` traps; use ``In/Audio``.
public init(bus: any ValidBus) { public init(bus: any ValidBus) {
_preconditionControlRateBus(bus)
let ch: Int = _resolvedChannelCount(bus) let ch: Int = _resolvedChannelCount(bus)
_previousOutputValues = [Double](repeating: 0.0, count: ch) _previousOutputValues = [Double](repeating: 0.0, count: ch)
super.init(bus: bus.index, channels: ch) super.init(bus: bus.index, channels: ch)
+16 -15
View File
@@ -40,9 +40,9 @@ public enum Out {
/// Accumulates into one or more consecutive audio buses using +=. /// Accumulates into one or more consecutive audio buses using +=.
/// Multiple ``Synthesizer`` instances writing to the same bus mix additively. /// Multiple ``Synthesizer`` instances writing to the same bus mix additively.
/// ///
/// The `bus` parameter accepts any ``ValidBus``: a plain `Int` index, an ``AudioBus`` /// The `bus` parameter takes a plain `Int` index or an ``AudioBus`` allocation (writes are
/// allocation, or (unusually) a ``ControlBus``. When `bus` is an ``AudioBus``, writing /// clamped to `bus.channelCount` channels). Passing a ``ControlBus`` traps — an audio `Out`
/// is automatically clamped to `bus.channelCount` channels. /// addresses the audio-bus pool, so use ``Out/Control`` for a control bus.
/// ///
/// ## Multi-channel sources /// ## Multi-channel sources
/// ///
@@ -57,9 +57,8 @@ public enum Out {
/// ``` /// ```
/// ///
/// - Parameters: /// - Parameters:
/// - bus: Destination bus — `Int` index (no channel clamping), ``AudioBus`` (clamped to /// - bus: Destination bus — `Int` index (no channel clamping) or ``AudioBus`` (clamped to
/// `channelCount`), or ``ControlBus``. Passed to `In.Audio` or the `output(bus:source:)` /// `channelCount`). A ``ControlBus`` traps; use ``Out/Control`` instead.
/// helper.
/// - source: Signal to write. Multi-channel sources write to consecutive buses starting at /// - source: Signal to write. Multi-channel sources write to consecutive buses starting at
/// `bus.index`. /// `bus.index`.
public final class Audio: _Base, AudioGenerator, RootRegistering { public final class Audio: _Base, AudioGenerator, RootRegistering {
@@ -73,13 +72,14 @@ public enum Out {
} }
/// - Parameters: /// - Parameters:
/// - bus: Destination bus — `Int` index, ``AudioBus``, or ``ControlBus``. /// - bus: Destination bus — `Int` index or ``AudioBus`` (writing clamped to
/// When `bus` is an ``AudioBus``, writing is clamped to `bus.channelCount` channels. /// `bus.channelCount`). A ``ControlBus`` traps; use ``Out/Control`` instead.
/// - source: Signal to write. Multi-channel sources write to consecutive buses. /// - source: Signal to write. Multi-channel sources write to consecutive buses.
public init( public init(
bus: any ValidBus, bus: any ValidBus,
source: any ValidGeneratorInput source: any ValidGeneratorInput
) { ) {
_preconditionAudioRateBus(bus)
super.init(bus: bus.index, source: source, maxChannels: bus.channelCount) super.init(bus: bus.index, source: source, maxChannels: bus.channelCount)
_registerAsRootIfBuilding() _registerAsRootIfBuilding()
} }
@@ -115,9 +115,9 @@ public enum Out {
/// a sink whose output is a control bus write). `previousOutputValue` is required by /// a sink whose output is a control bus write). `previousOutputValue` is required by
/// the ControlGenerator protocol but is not used. /// the ControlGenerator protocol but is not used.
/// ///
/// The `bus` parameter accepts any ``ValidBus``: a plain `Int` index, a ``ControlBus`` /// The `bus` parameter takes a plain `Int` index or a ``ControlBus`` allocation (writes are
/// allocation, or an ``AudioBus``. When `bus` is a ``ControlBus``, writing is clamped to /// clamped to `bus.channelCount` channels). Passing an ``AudioBus`` traps — a control `Out`
/// `bus.channelCount` channels. /// addresses the control-bus pool, so use ``Out/Audio`` for an audio bus.
/// ///
/// ## Multi-channel sources /// ## Multi-channel sources
/// ///
@@ -131,8 +131,8 @@ public enum Out {
/// ``` /// ```
/// ///
/// - Parameters: /// - Parameters:
/// - bus: Destination bus — `Int` index (1 channel, no clamping), ``ControlBus`` (clamped /// - bus: Destination bus — `Int` index (1 channel, no clamping) or ``ControlBus`` (clamped
/// to `channelCount`), or ``AudioBus``. /// to `channelCount`). An ``AudioBus`` traps; use ``Out/Audio`` instead.
/// - source: Signal to write. The last sample of each channel block is accumulated into /// - source: Signal to write. The last sample of each channel block is accumulated into
/// the corresponding control bus. Multi-channel sources write to consecutive buses. /// the corresponding control bus. Multi-channel sources write to consecutive buses.
public final class Control: _Base, ControlGenerator, RootRegistering { public final class Control: _Base, ControlGenerator, RootRegistering {
@@ -147,14 +147,15 @@ public enum Out {
public override var outputChannelCount: Int { _channels } public override var outputChannelCount: Int { _channels }
/// - Parameters: /// - Parameters:
/// - bus: Destination bus — `Int` index, ``ControlBus``, or ``AudioBus``. /// - bus: Destination bus — `Int` index or ``ControlBus`` (writing clamped to
/// When `bus` is a ``ControlBus``, writing is clamped to `bus.channelCount` channels. /// `bus.channelCount`). An ``AudioBus`` traps; use ``Out/Audio`` instead.
/// A plain `Int` writes a single channel. /// A plain `Int` writes a single channel.
/// - source: Signal to write. Multi-channel sources write to consecutive buses. /// - source: Signal to write. Multi-channel sources write to consecutive buses.
public init( public init(
bus: any ValidBus, bus: any ValidBus,
source: any ValidGeneratorInput source: any ValidGeneratorInput
) { ) {
_preconditionControlRateBus(bus)
let ch: Int = _resolvedChannelCount(bus) let ch: Int = _resolvedChannelCount(bus)
self._channels = ch self._channels = ch
super.init(bus: bus.index, source: source, maxChannels: bus.channelCount, channels: ch) super.init(bus: bus.index, source: source, maxChannels: bus.channelCount, channels: ch)
@@ -60,10 +60,10 @@ public enum ReplaceOut {
/// Overwrites one or more consecutive audio buses with the source signal /// Overwrites one or more consecutive audio buses with the source signal
/// (wipes any prior writes to those buses in the current block). /// (wipes any prior writes to those buses in the current block).
/// ///
/// The `bus` parameter accepts any ``ValidBus``: a plain `Int` index, an /// The `bus` parameter takes a plain `Int` index or an ``AudioBus`` allocation
/// ``AudioBus`` allocation, or (unusually) a ``ControlBus``. When `bus` is /// (writing clamped to `bus.channelCount` channels). A ``ControlBus`` traps —
/// an ``AudioBus``, writing is automatically clamped to `bus.channelCount` /// an audio `ReplaceOut` addresses the audio-bus pool; use ``ReplaceOut/Control``
/// channels. /// for a control bus.
/// ///
/// ## Multi-channel sources /// ## Multi-channel sources
/// ///
@@ -81,8 +81,8 @@ public enum ReplaceOut {
/// ``` /// ```
/// ///
/// - Parameters: /// - Parameters:
/// - bus: Destination bus — `Int` index (no channel clamping), ``AudioBus`` /// - bus: Destination bus — `Int` index (no channel clamping) or ``AudioBus``
/// (clamped to `channelCount`), or ``ControlBus``. /// (clamped to `channelCount`). A ``ControlBus`` traps; use ``ReplaceOut/Control``.
/// - source: Signal to write. Multi-channel sources overwrite consecutive /// - source: Signal to write. Multi-channel sources overwrite consecutive
/// buses starting at `bus.index`. /// buses starting at `bus.index`.
public final class Audio: _Base, AudioGenerator, RootRegistering { public final class Audio: _Base, AudioGenerator, RootRegistering {
@@ -102,13 +102,14 @@ public enum ReplaceOut {
} }
/// - Parameters: /// - Parameters:
/// - bus: Destination bus — `Int` index, ``AudioBus``, or ``ControlBus``. /// - bus: Destination bus — `Int` index or ``AudioBus`` (writing clamped to
/// When `bus` is an ``AudioBus``, writing is clamped to `bus.channelCount` channels. /// `bus.channelCount`). A ``ControlBus`` traps; use ``ReplaceOut/Control``.
/// - source: Signal to write. Multi-channel sources overwrite consecutive buses. /// - source: Signal to write. Multi-channel sources overwrite consecutive buses.
public init( public init(
bus: any ValidBus, bus: any ValidBus,
source: any ValidGeneratorInput source: any ValidGeneratorInput
) { ) {
_preconditionAudioRateBus(bus)
super.init(bus: bus.index, source: source, maxChannels: bus.channelCount) super.init(bus: bus.index, source: source, maxChannels: bus.channelCount)
_registerAsRootIfBuilding() _registerAsRootIfBuilding()
} }
@@ -151,9 +152,10 @@ public enum ReplaceOut {
/// control bus write). `previousOutputValue` is required by the /// control bus write). `previousOutputValue` is required by the
/// ControlGenerator protocol but is not used. /// ControlGenerator protocol but is not used.
/// ///
/// The `bus` parameter accepts any ``ValidBus``: a plain `Int` index, a /// The `bus` parameter takes a plain `Int` index or a ``ControlBus`` allocation
/// ``ControlBus`` allocation, or an ``AudioBus``. When `bus` is a /// (writing clamped to `bus.channelCount` channels). An ``AudioBus`` traps —
/// ``ControlBus``, writing is clamped to `bus.channelCount` channels. /// a control `ReplaceOut` addresses the control-bus pool; use ``ReplaceOut/Audio``
/// for an audio bus.
/// ///
/// ## Multi-channel sources /// ## Multi-channel sources
/// ///
@@ -163,8 +165,8 @@ public enum ReplaceOut {
/// usage. /// usage.
/// ///
/// - Parameters: /// - Parameters:
/// - bus: Destination bus — `Int` index (1 channel, no clamping), /// - bus: Destination bus — `Int` index (1 channel, no clamping) or
/// ``ControlBus`` (clamped to `channelCount`), or ``AudioBus``. /// ``ControlBus`` (clamped to `channelCount`). An ``AudioBus`` traps; use ``ReplaceOut/Audio``.
/// - source: Signal to write. The last sample of each channel block is /// - source: Signal to write. The last sample of each channel block is
/// written to the corresponding control bus. /// written to the corresponding control bus.
public final class Control: _Base, ControlGenerator, RootRegistering { public final class Control: _Base, ControlGenerator, RootRegistering {
@@ -176,8 +178,8 @@ public enum ReplaceOut {
/// ///
/// - Note: Channel-count policy intentionally mirrors ``Out/Control``: a /// - Note: Channel-count policy intentionally mirrors ``Out/Control``: a
/// plain `Int` bus resolves to 1 channel (extra source channels are /// plain `Int` bus resolves to 1 channel (extra source channels are
/// silently dropped); a ``ControlBus`` or ``AudioBus`` resolves to its /// silently dropped); a ``ControlBus`` resolves to its explicit
/// explicit `channelCount`. ``ReplaceOut/Audio`` differs — a plain /// `channelCount`. ``ReplaceOut/Audio`` differs — a plain
/// `Int` bus there writes all source channels via `_maxChannels = /// `Int` bus there writes all source channels via `_maxChannels =
/// Int.max`. Use a typed bus allocation if you want explicit /// Int.max`. Use a typed bus allocation if you want explicit
/// multi-channel writes from a plain index. /// multi-channel writes from a plain index.
@@ -186,13 +188,14 @@ public enum ReplaceOut {
public override var outputChannelCount: Int { _channels } public override var outputChannelCount: Int { _channels }
/// - Parameters: /// - Parameters:
/// - bus: Destination bus — `Int` index, ``ControlBus``, or ``AudioBus``. /// - bus: Destination bus — `Int` index or ``ControlBus`` (writing clamped to
/// When `bus` is a ``ControlBus``, writing is clamped to `bus.channelCount` channels. /// `bus.channelCount`). An ``AudioBus`` traps; use ``ReplaceOut/Audio``.
/// - source: Signal to write. Multi-channel sources overwrite consecutive buses. /// - source: Signal to write. Multi-channel sources overwrite consecutive buses.
public init( public init(
bus: any ValidBus, bus: any ValidBus,
source: any ValidGeneratorInput source: any ValidGeneratorInput
) { ) {
_preconditionControlRateBus(bus)
let ch: Int = _resolvedChannelCount(bus) let ch: Int = _resolvedChannelCount(bus)
self._channels = ch self._channels = ch
super.init(bus: bus.index, source: source, maxChannels: bus.channelCount, channels: ch) super.init(bus: bus.index, source: source, maxChannels: bus.channelCount, channels: ch)
@@ -10,7 +10,9 @@ import Darwin
/// ///
/// Accumulates samples into a ring buffer and re-evaluates every `hopSize` samples. /// Accumulates samples into a ring buffer and re-evaluates every `hopSize` samples.
/// Between hops the output holds the previous result — frequency stabilises after /// 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 /// ## Output
/// Returns a two-channel buffer: /// Returns a two-channel buffer:
@@ -19,10 +21,13 @@ import Darwin
/// ///
/// ## Parameters /// ## Parameters
/// - `in`: signal to analyse (Audio-rate input evaluated per sample) /// - `in`: signal to analyse (Audio-rate input evaluated per sample)
/// - `fftSize`: analysis window in samples (must be power of 2, set at init) /// - `fftSize`: analysis window in **decimated** samples (must be power of 2, set at init)
/// - `hopSize`: samples between re-analyses (set at init; default `fftSize / 2`) /// - `hopSize`: decimated samples between re-analyses (set at init; default `fftSize / 2`)
/// - `minFreq`: lower search bound in Hz (default 60.0) /// - `minFreq`: lower search bound in Hz (default 60.0)
/// - `maxFreq`: upper search bound in Hz (default 3000.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 /// ## Usage
/// ```swift /// ```swift
@@ -62,6 +67,7 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
private let _hopSize: Int private let _hopSize: Int
private let _minFreq: Double private let _minFreq: Double
private let _maxFreq: Double private let _maxFreq: Double
private let _decimation: Int
// MARK: - Input // MARK: - Input
@@ -82,6 +88,11 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
private var _lastFreq: Double = 0.0 private var _lastFreq: Double = 0.0
private var _lastConfidence: 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: - Output
// MARK: - Fan-out cache // MARK: - Fan-out cache
@@ -89,18 +100,32 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
/// - Parameters: /// - Parameters:
/// - input: Signal to track. /// - input: Signal to track.
/// - fftSize: Analysis window in samples. Power of 2 in [64, 512]. Default 512. /// - fftSize: Analysis window in **decimated** samples. Power of 2 in [64, 512].
/// Larger values increase latency and YIN cost (O(halfSize²) per hop); /// Default 512. Larger values increase latency and YIN cost (O(halfSize²)
/// 512 gives ~5.8 ms at 44100 Hz and is the maximum RT-safe value. /// 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`. /// - hopSize: Decimated samples between analysis updates. Default `fftSize / 2`.
/// - minFreq: Minimum tracked frequency in Hz. Default 60.0. /// - minFreq: Minimum tracked frequency in Hz. Default 60.0.
/// - maxFreq: Maximum tracked frequency in Hz. Default 3000.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( public init(
in input: any ValidGeneratorInput, in input: any ValidGeneratorInput,
fftSize: Int = 512, fftSize: Int = 512,
hopSize: Int? = nil, hopSize: Int? = nil,
minFreq: Double = 60.0, minFreq: Double = 60.0,
maxFreq: Double = 3000.0 maxFreq: Double = 3000.0,
decimation: Int = 1
) { ) {
precondition(fftSize >= 64 && fftSize <= 512 && (fftSize & (fftSize - 1)) == 0, precondition(fftSize >= 64 && fftSize <= 512 && (fftSize & (fftSize - 1)) == 0,
"FreqTracker: fftSize must be a power of 2 in [64, 512]; got \(fftSize). " "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.") + "Reduce fftSize or implement background-thread YIN in a future phase.")
precondition(minFreq > 0 && maxFreq > minFreq, precondition(minFreq > 0 && maxFreq > minFreq,
"FreqTracker: minFreq must be > 0 and < maxFreq") "FreqTracker: minFreq must be > 0 and < maxFreq")
precondition(decimation >= 1,
"FreqTracker: decimation must be >= 1; got \(decimation).")
_fftSize = fftSize _fftSize = fftSize
_hopSize = hopSize ?? fftSize / 2 _hopSize = hopSize ?? fftSize / 2
@@ -119,6 +146,7 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
+ "Larger values cause the YIN window to read stale data.") + "Larger values cause the YIN window to read stale data.")
_minFreq = minFreq _minFreq = minFreq
_maxFreq = maxFreq _maxFreq = maxFreq
_decimation = decimation
let resolvedInput: any ValidGeneratorInput = input._resolvedInput() let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
_input = resolvedInput _input = resolvedInput
_inputRing = [Double](repeating: 0.0, count: fftSize) _inputRing = [Double](repeating: 0.0, count: fftSize)
@@ -135,16 +163,23 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
_checkCount(count) _checkCount(count)
let sr: Double = graph.engine.sampleRate 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) let inputSamples: [[Double]] = _input.calculatedSamples(graph: graph, count: count)
guard let ins: [Double] = inputSamples.first else { guard let ins: [Double] = inputSamples.first else {
// No input — advance ring with zeros, still fire hops so state advances correctly. // No input — advance ring with zeros, still fire hops so state advances correctly.
for _ in 0..<count { for _ in 0..<count {
_inputRing[_ringPos % _fftSize] = 0.0 _decimationCounter &+= 1
_ringPos &+= 1 if _decimationCounter >= _decimation {
_samplesUntilHop -= 1 _decimationCounter = 0
if _samplesUntilHop <= 0 { _inputRing[_ringPos % _fftSize] = 0.0
_samplesUntilHop = _hopSize _ringPos &+= 1
_runYIN(sampleRate: sr) _samplesUntilHop -= 1
if _samplesUntilHop <= 0 {
_samplesUntilHop = _hopSize
_runYIN(sampleRate: effectiveRate)
}
} }
} }
for i: Int in 0..<count { for i: Int in 0..<count {
@@ -155,15 +190,21 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
} }
for i: Int in 0..<count { for i: Int in 0..<count {
// Write incoming sample into ring buffer. // Write every `_decimation`-th incoming sample into the ring buffer. Naive
let sample: Double = Double(ins[i]) // decimation (take-every-Nth) is correct because the caller band-limits below
_inputRing[_ringPos % _fftSize] = sample // the decimated Nyquist — see the `decimation` parameter docs.
_ringPos &+= 1 _decimationCounter &+= 1
if _decimationCounter >= _decimation {
_decimationCounter = 0
let sample: Double = Double(ins[i])
_inputRing[_ringPos % _fftSize] = sample
_ringPos &+= 1
_samplesUntilHop -= 1 _samplesUntilHop -= 1
if _samplesUntilHop <= 0 { if _samplesUntilHop <= 0 {
_samplesUntilHop = _hopSize _samplesUntilHop = _hopSize
_runYIN(sampleRate: sr) _runYIN(sampleRate: effectiveRate)
}
} }
_result[0][i] = _lastFreq _result[0][i] = _lastFreq
_result[1][i] = _lastConfidence _result[1][i] = _lastConfidence
@@ -376,7 +376,7 @@ public enum EnvelopeGen {
/// ```swift /// ```swift
/// let env = Envelope(levels: [0, 1, 0], durations: [0.01, 0.5], curves: [.sine, .exponential]) /// let env = Envelope(levels: [0, 1, 0], durations: [0.01, 0.5], curves: [.sine, .exponential])
/// let gen = EnvelopeGen.Audio(envelope: env, doneAction: .freeNode) /// 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: /// - Parameters:
@@ -46,7 +46,7 @@ private let klankLog0001: Double = log(0.001)
/// Each is any `ValidGeneratorInput`, snapshotted once per audio block (block-rate / "control /// 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 /// 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 /// while it sounds. The full table can additionally be swapped at run time via
/// ``setBuffer(_:engine:)`` (RT-safe ``RTBufferSlot`` handoff), so both per-mode editing and /// ``Klank/Audio/setBuffer(_:engine:)`` (RT-safe ``RTBufferSlot`` handoff), so both per-mode editing and
/// whole-table replacement are available. /// whole-table replacement are available.
/// ///
/// ## Difference equation (per resonator k) /// ## Difference equation (per resonator k)
@@ -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
}
}
}
@@ -27,7 +27,7 @@ public let klangFreqChannel: Int = 0
public let klangAmpChannel: Int = 1 public let klangAmpChannel: Int = 1
/// Buffer channel index of the per-partial initial phase (cycles, `[0, 1)`). Read once at /// Buffer channel index of the per-partial initial phase (cycles, `[0, 1)`). Read once at
/// `init` to seed the phase accumulator; ignored on later ``setBuffer(_:engine:)`` swaps. /// `init` to seed the phase accumulator; ignored on later ``Klang/Audio/setBuffer(_:engine:)`` swaps.
public let klangPhaseChannel: Int = 2 public let klangPhaseChannel: Int = 2
/// Bank of N summed sine partials — the additive-synthesis counterpart of ``Klank``. /// Bank of N summed sine partials — the additive-synthesis counterpart of ``Klank``.
@@ -44,7 +44,7 @@ public let klangPhaseChannel: Int = 2
/// ///
/// Both are any `ValidGeneratorInput`, snapshotted once per audio block (block-rate / "control /// Both are any `ValidGeneratorInput`, snapshotted once per audio block (block-rate / "control
/// rate"). `freq` and `amp` are re-read from the table each block, so live `setValue` edits and /// rate"). `freq` and `amp` are re-read from the table each block, so live `setValue` edits and
/// whole-table ``setBuffer(_:engine:)`` swaps retune the bank while it sounds. The `phase` /// whole-table ``Klang/Audio/setBuffer(_:engine:)`` swaps retune the bank while it sounds. The `phase`
/// channel is **only** read at `init` to seed each partial's running phase accumulator — phases /// channel is **only** read at `init` to seed each partial's running phase accumulator — phases
/// free-run thereafter and are unaffected by later table swaps (so the bank never clicks on a /// free-run thereafter and are unaffected by later table swaps (so the bank never clicks on a
/// respecification). /// respecification).
@@ -24,7 +24,7 @@ private let schmidtZeroBlock: [Double] = [Double](
/// ///
/// ```swift /// ```swift
/// // Gate signal on amplitude with 0.1/0.3 hysteresis band. /// // Gate signal on amplitude with 0.1/0.3 hysteresis band.
/// let amp = AmplitudeFollower.Audio(input: In.Audio(bus: 0)) /// let amp = AmplitudeFollower.Audio(in: In.Audio(bus: 0))
/// let gate = Schmidt.Audio(input: amp, lo: 0.1, hi: 0.3) /// let gate = Schmidt.Audio(input: amp, lo: 0.1, hi: 0.3)
/// ``` /// ```
/// ///
@@ -26,7 +26,7 @@ private let signalChangedZeroBlock: [Double] = [Double](
/// ///
/// ```swift /// ```swift
/// // Cheap onset proxy — fires whenever amplitude jumps > 0.05. /// // Cheap onset proxy — fires whenever amplitude jumps > 0.05.
/// let amp = AmplitudeFollower.Audio(input: In.Audio(bus: 0)) /// let amp = AmplitudeFollower.Audio(in: In.Audio(bus: 0))
/// let edge = SignalChanged.Audio(input: amp, threshold: 0.05) /// let edge = SignalChanged.Audio(input: amp, threshold: 0.05)
/// addOutputGenerator(SendTrigger.Audio(trig: edge, id: 1)) /// addOutputGenerator(SendTrigger.Audio(trig: edge, id: 1))
/// ``` /// ```
@@ -22,7 +22,7 @@ private let trigZeroBlock: [Double] = [Double](
/// ///
/// ```swift /// ```swift
/// // Capture amplitude and hold it for 0.1 s every time a trigger fires. /// // Capture amplitude and hold it for 0.1 s every time a trigger fires.
/// let amp = AmplitudeFollower.Audio(input: In.Audio(bus: 0)) /// let amp = AmplitudeFollower.Audio(in: In.Audio(bus: 0))
/// let clock = Impulse.Audio(freq: 4.0) /// let clock = Impulse.Audio(freq: 4.0)
/// let pulse = Trig.Audio(input: amp, dur: 0.1) /// let pulse = Trig.Audio(input: amp, dur: 0.1)
/// ``` /// ```
+61 -27
View File
@@ -53,6 +53,10 @@ All bus parameters in `In`, `Out`, and the ``SynthesizerBase`` helpers accept an
This means you can store and pass bus allocations directly without extracting `.index`: This means you can store and pass bus allocations directly without extracting `.index`:
```swift ```swift
// In real code myAudioBus comes from engine.busAllocator — see "Allocating User Buses" below.
let myAudioBus: AudioBus = AudioBus(index: 4, channelCount: 2)
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
// Before: extract .index manually // Before: extract .index manually
output(bus: myAudioBus.index, source: sig) output(bus: myAudioBus.index, source: sig)
@@ -69,17 +73,20 @@ consecutive control buses and delivers an interpolated audio-rate ramp per chann
The channel count is an init-time constant — no RT allocation. The channel count is an init-time constant — no RT allocation.
```swift ```swift
let myAudioBus: AudioBus = AudioBus(index: 4, channelCount: 2)
let myCtrlBus: ControlBus = ControlBus(index: 10, channelCount: 2)
// Single-channel (plain Int) // Single-channel (plain Int)
In.Audio(bus: 2) // AudioGenerator — reads audioBuses[2], 1 channel let a: In.Audio = In.Audio(bus: 2) // reads audioBuses[2], 1 channel
In.Control(bus: 10) // ControlGenerator — reads controlBuses[10], interpolated ramp let b: In.Control = In.Control(bus: 10) // reads controlBuses[10], interpolated ramp
// AudioBus / ControlBus — channel count inferred from allocation // AudioBus / ControlBus — channel count inferred from allocation
In.Audio(bus: myAudioBus) // reads myAudioBus.channelCount consecutive audio buses let c: In.Audio = In.Audio(bus: myAudioBus) // reads myAudioBus.channelCount audio buses
In.Control(bus: myCtrlBus) // reads myCtrlBus.channelCount consecutive control buses let d: In.Control = In.Control(bus: myCtrlBus) // reads myCtrlBus.channelCount control buses
// Explicit multi-channel override // Explicit multi-channel override
In.Audio(bus: 4, channels: 3) // reads audioBuses[4], [5], [6] let e: In.Audio = In.Audio(bus: 4, channels: 3) // reads audioBuses[4], [5], [6]
In.Control(bus: 10, channels: 2) // reads controlBuses[10] and [11]; independent ramps let f: In.Control = In.Control(bus: 10, channels: 2) // controlBuses[10] and [11]; independent ramps
``` ```
Use `input(bus:channels:)` inside `SynthesizerBase.build()` for a ``GeneratorArray`` of Use `input(bus:channels:)` inside `SynthesizerBase.build()` for a ``GeneratorArray`` of
@@ -95,11 +102,16 @@ input(bus: 2, channels: 2) // → GeneratorArray reading buses 2 and 3
same bus mix additively (polyphony, send-return routing). same bus mix additively (polyphony, send-return routing).
```swift ```swift
Out.Audio(bus: 0, source: sig) // plain Int bus let myAudioBus: AudioBus = AudioBus(index: 4, channelCount: 2)
Out.Audio(bus: myAudioBus, source: sig) // clamped to myAudioBus.channelCount let myCtrlBus: ControlBus = ControlBus(index: 10, channelCount: 2)
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
let lfo: OscSin.Control = OscSin.Control(freq: 2.0)
Out.Control(bus: 10, source: lfo) // plain Int bus let a: Out.Audio = Out.Audio(bus: 0, source: sig) // plain Int bus
Out.Control(bus: myCtrlBus, source: lfo) // clamped to myCtrlBus.channelCount let b: Out.Audio = Out.Audio(bus: myAudioBus, source: sig) // clamped to channelCount
let c: Out.Control = Out.Control(bus: 10, source: lfo) // plain Int bus
let d: Out.Control = Out.Control(bus: myCtrlBus, source: lfo) // clamped to channelCount
``` ```
### Multi-Channel Out ### Multi-Channel Out
@@ -108,11 +120,14 @@ When the source returns N channels, ``Out`` writes channel `ch` to `bus.index +
to both audio and control buses: to both audio and control buses:
```swift ```swift
let osc: OscSin.Audio = OscSin.Audio(freq: 440.0)
let stereoControlSrc: GeneratorArray = expand([2.0, 3.0]) { OscSin.Control(freq: $0) }
// Stereo audio source writes buses 0 and 1: // Stereo audio source writes buses 0 and 1:
Out.Audio(bus: 0, source: Pan2(input: osc, pan: 0.0)) let a: Out.Audio = Out.Audio(bus: 0, source: Pan2(input: osc, pan: 0.0))
// Multi-channel control source writes controlBuses[10] and [11]: // Multi-channel control source writes controlBuses[10] and [11]:
Out.Control(bus: 10, source: stereoControlSrc) let b: Out.Control = Out.Control(bus: 10, source: stereoControlSrc)
``` ```
Mono sources return one channel and write only `bus.index`. Mono sources return one channel and write only `bus.index`.
@@ -122,13 +137,29 @@ Mono sources return one channel and write only `bus.index`.
Inside `build()`, the helpers accept any ``ValidBus``: Inside `build()`, the helpers accept any ``ValidBus``:
```swift ```swift
override func build() { final class BusRoutingSynth: SynthesizerBase {
let osc = OscSin.Audio(freq: freq) @LiveParam var freq: Double = 440.0
output(bus: outbus, source: Pan2(input: osc * amp)) // AudioBus or Int @LiveParam var amp: Double = 0.5
controlOutput(bus: ctrlBus, source: lfo) // ControlBus or Int
let sig = input(bus: inbus) // AudioBus or Int // Hardcoded indices here for illustration. In real code, obtain user buses from
let ctrl = controlInput(bus: ctrlInBus) // ControlBus or Int // engine.busAllocator (see "Allocating User Buses" below) rather than hand-picking
// indices, which risks colliding with hardware buses or other synths.
let outbus: AudioBus = AudioBus(index: 0, channelCount: 2)
let inbus: AudioBus = AudioBus(index: 4, channelCount: 1)
let ctrlBus: ControlBus = ControlBus(index: 10)
let ctrlInBus: ControlBus = ControlBus(index: 11)
override func build() {
let osc: OscSin.Audio = OscSin.Audio(freq: $freq)
let lfo: OscSin.Control = OscSin.Control(freq: 2.0)
output(bus: outbus, source: Pan2(input: osc * $amp)) // AudioBus or Int
controlOutput(bus: ctrlBus, source: lfo) // ControlBus or Int
let sig: In.Audio = input(bus: inbus) // AudioBus or Int
let ctrl: In.Control = controlInput(bus: ctrlInBus) // ControlBus or Int
output(bus: 2, source: sig * ctrl)
}
} }
``` ```
@@ -157,18 +188,21 @@ don't track raw indices manually. Hardware output and input buses are pre-reserv
allocation starts from the first free bus after them. allocation starts from the first free bus after them.
```swift ```swift
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
let lfo: OscSin.Control = OscSin.Control(freq: 2.0)
// Allocate buses // Allocate buses
let stereo = try engine.busAllocator.allocateAudioBus(channelCount: 2) let stereo: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 2)
let ctrl = try engine.busAllocator.allocateControlBus() // single channel let ctrl: ControlBus = try engine.busAllocator.allocateControlBus() // single channel
let ctrl2ch = try engine.busAllocator.allocateControlBus(channelCount: 2) let ctrl2ch: ControlBus = try engine.busAllocator.allocateControlBus(channelCount: 2)
// Pass directly to In / Out / SynthesizerBase helpers — no .index needed // Pass directly to In / Out / SynthesizerBase helpers — no .index needed
let reader = In.Audio(bus: stereo) // reads stereo.channelCount buses let reader: In.Audio = In.Audio(bus: stereo) // reads stereo.channelCount buses
let multi = In.Audio.multi(bus: stereo) // GeneratorArray — one gen per channel let multi: GeneratorArray = In.Audio.multi(bus: stereo) // one gen per channel
let writer = Out.Audio(bus: stereo, source: sig) // clamped to stereo.channelCount let writer: Out.Audio = Out.Audio(bus: stereo, source: sig) // clamped to channelCount
let ctrlIn = In.Control(bus: ctrl) // single-channel ramp let ctrlIn: In.Control = In.Control(bus: ctrl) // single-channel ramp
let ctrl2In = In.Control(bus: ctrl2ch) // 2-channel, buses ctrl2ch.index and +1 let ctrl2In: In.Control = In.Control(bus: ctrl2ch) // 2-channel, ctrl2ch.index and +1
let ctrlOut = Out.Control(bus: ctrl2ch, source: lfo) // clamped to ctrl2ch.channelCount let ctrlOut: Out.Control = Out.Control(bus: ctrl2ch, source: lfo) // clamped to channelCount
// Release when the synthesizer is done // Release when the synthesizer is done
engine.busAllocator.releaseAudioBus(stereo) engine.busAllocator.releaseAudioBus(stereo)
+1 -1
View File
@@ -59,7 +59,7 @@ MyPiece/
**Templates** — `--template <name>`: **Templates** — `--template <name>`:
- SPM-only: `basic` (default), `demo`, `ui-demo`, `nrt` — open `Package.swift` in Xcode - SPM-only: `quickstart` (fastest sound), `basic` (default), `demo`, `ui-demo`, `nrt`, `score` — open `Package.swift` in Xcode
- Xcode-project: `macos-ui-xcode`, `ios-ui`, `auv3` — emit a full `<name>.xcodeproj` for `.app` / `.appex` deliverables. See <doc:ProjectSystem> for full layout per template. - Xcode-project: `macos-ui-xcode`, `ios-ui`, `auv3` — emit a full `<name>.xcodeproj` for `.app` / `.appex` deliverables. See <doc:ProjectSystem> for full layout per template.
### `lyrebird run [--release]` ### `lyrebird run [--release]`
+74 -24
View File
@@ -8,21 +8,52 @@ Configure and start a ``SynthesisEngine`` with hardware I/O or offline rendering
## Initialization ## Initialization
Five parameters are required; every other one defaults.
```swift ```swift
SynthesisEngine( import LyrebirdSynth
blockSize: Int, // samples per render callback (e.g. 512)
sampleRate: Double, // e.g. 44100, 48000 let engine = SynthesisEngine(
numOutputChannels: Int, // hardware output channels (e.g. 2) blockSize: 512,
numInputChannels: Int, // hardware input channels (e.g. 0 or 2) sampleRate: 48000,
numAudioBuses: Int, // default 128 numOutputChannels: 2,
numControlBuses: Int, // default 4096 numInputChannels: 0,
driver: AudioDriver // CoreAudioDriver, NRTDriver, or OfflineDriver driver: CoreAudioDriver()
) )
``` ```
`SynthesisEngine.init` enforces `blockSize ≤ lyrebirdDefaultResultBufferSize` (512) — this is the The full parameter list is ``SynthesisEngine/init(blockSize:controlBlockSize:sampleRate:numOutputChannels:numInputChannels:numAudioBuses:numControlBuses:eventQueueCapacity:maxEventsPerBlock:driver:)``:
maximum block size supported by all built-in generators. It also allocates and fills `sharedTables`
on the calling (non-RT) thread, so lookup tables are ready before the first render callback. | Parameter | Meaning | Default |
|---|---|---|
| `blockSize` | Samples per render callback (e.g. 512). | *required* |
| `controlBlockSize` | Control-rate sub-block size. `nil` asks the driver for its preference; if the driver has none, the engine runs at full-block control rate. | `nil` |
| `sampleRate` | Sample rate in Hz (e.g. 44100, 48000). | *required* |
| `numOutputChannels` | Hardware output channels reserved at bus indices `0..<n`. | *required* |
| `numInputChannels` | Hardware input channels, reserved directly above the outputs. | *required* |
| `numAudioBuses` | Total audio bus count. | ``lyrebirdDefaultNumAudioBuses`` |
| `numControlBuses` | Total control bus count. | ``lyrebirdDefaultNumControlBuses`` |
| `eventQueueCapacity` | `pendingQueue` ring occupancy. Must be a power of two. | ``lyrebirdDefaultEventQueueCapacity`` |
| `maxEventsPerBlock` | Per-block event budget — see below. | ``lyrebirdDefaultMaxEventsPerBlock`` |
| `driver` | ``CoreAudioDriver``, ``NRTDriver``, or ``OfflineDriver``. | *required* |
``SynthesisEngine/init(blockSize:controlBlockSize:sampleRate:numOutputChannels:numInputChannels:numAudioBuses:numControlBuses:eventQueueCapacity:maxEventsPerBlock:driver:)`` enforces `blockSize <= ` ``lyrebirdDefaultResultBufferSize`` — the maximum block size supported by all built-in generators. It also allocates and fills ``SynthesisEngine/sharedTables`` on the calling (non-RT) thread, so lookup tables are ready before the first render callback.
### Scheduling capacity
Two independent knobs bound scheduling. They are often confused:
| Parameter | Bounds | On overflow |
|---|---|---|
| `eventQueueCapacity` | `pendingQueue` ring occupancy — events enqueued but not yet drained *at one instant*. **Must be a power of two** (precondition, not rounded). | `add` / `schedule` throw `EngineAddError.pendingQueueFull`; `engine.pendingQueueDroppedCount` counts them |
| `maxEventsPerBlock` | Per-block budget: events *firing* in one block, **and** the future-event look-ahead carried across block boundaries. Must be `> 0`; power of two not required. | Surplus events are dropped by the RT thread; `engine.perBlockEventDropCount` counts them and a one-line console warning is printed off-RT |
`maxEventsPerBlock` — not `eventQueueCapacity` — is the ceiling that decides whether a large
batch of pre-scheduled events survives. The two are independent: `maxEventsPerBlock` may exceed
`eventQueueCapacity`, because carry-over accumulates across blocks while the ring only ever holds
a per-drain burst. Raising either costs pre-allocated memory only, never RT time.
Full model: <doc:Scheduling> and `docs/engine/scheduling.md`.
## Lifecycle ## Lifecycle
@@ -49,14 +80,25 @@ shared tables do not need to check `isValid`. Cache the reference in your genera
### User-Allocated Buffers ### User-Allocated Buffers
```swift ```swift
let buf = LyrebirdBuffer(count: lyrebirdDefaultTableSize) final class TableSynth: SynthesizerBase {
buf.fill { i, n in Double(i) / Double(n) * 2.0 - 1.0 } // sawtooth // Filled at init — before the buffer ever reaches the RT thread.
let osc = OscTable.Audio(table: buf, freq: 440.0) let table: LyrebirdBuffer = {
try engine.add(mySynth) // buf now in RT use — do not fill again let b: LyrebirdBuffer = LyrebirdBuffer(count: lyrebirdDefaultTableSize)
b.fill { i, n in Double(i) / Double(n) * 2.0 - 1.0 } // sawtooth
return b
}()
override func build() {
output(bus: 0, source: OscTable.Audio(table: table, freq: 440.0) * 0.2)
}
}
let mySynth: TableSynth = TableSynth()
try engine.add(mySynth) // table now in RT use — do not fill again
// Later, on the main thread: // Later, on the main thread:
buf.invalidate() // RT thread sees isValid == false and outputs silence mySynth.table.invalidate() // RT thread sees isValid == false and outputs silence
engine.remove(mySynth) // ARC releases buf when synth is freed via freeQueue engine.remove(mySynth) // ARC releases the table when the synth is freed via freeQueue
``` ```
Fill methods must be called **before** the buffer enters RT use. `invalidate()` is RT-safe Fill methods must be called **before** the buffer enters RT use. `invalidate()` is RT-safe
@@ -101,18 +143,26 @@ where these fields live in scaffolded projects.
### Offline Rendering (NRTDriver) ### Offline Rendering (NRTDriver)
```swift ```swift
let driver = NRTDriver(outputURL: url, duration: 10.0) import Foundation
let engine = SynthesisEngine(
let url: URL = URL(fileURLWithPath: "/tmp/render.caf")
let driver: NRTDriver = NRTDriver(outputURL: url, duration: 10.0)
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 512, sampleRate: 44100, blockSize: 512, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 0, numOutputChannels: 2, numInputChannels: 0,
driver: driver driver: driver
) )
// Pre-schedule the score // Pre-schedule the score. Each onset needs its OWN instance — scheduling one
try engine.schedule(pad, at: 0) // instance twice throws `EngineAddError.doubleAdd`.
try engine.schedule(kick, at: engine.seconds(0.5)) let pad: MySynth = MySynth()
try engine.schedule(kick, at: engine.seconds(1.0)) let kick1: MySynth = MySynth()
engine.remove(pad, at: engine.seconds(8.0)) let kick2: MySynth = MySynth()
try engine.schedule(pad, at: 0)
try engine.schedule(kick1, at: engine.seconds(0.5))
try engine.schedule(kick2, at: engine.seconds(1.0))
_ = engine.remove(pad, at: engine.seconds(8.0))
try engine.start() // renders synchronously, writes file, returns when done try engine.start() // renders synchronously, writes file, returns when done
``` ```
@@ -54,7 +54,7 @@ midi.addHandler(name: "notes") { message, ctx in
switch message { switch message {
case .noteOn(_, let note, let vel) where vel > 0: case .noteOn(_, let note, let vel) where vel > 0:
let synth = SineTone() let synth = SineTone()
synth.$freq.value = midiNoteToHz(Double(note)) synth.$freq.value = midiToHz(Double(note))
synth.$amp.value = Double(vel) / 127.0 synth.$amp.value = Double(vel) / 127.0
ctx.add(synth) ctx.add(synth)
case .noteOff, .noteOn(_, _, 0): case .noteOff, .noteOn(_, _, 0):
@@ -86,7 +86,7 @@ midi.addHandler(name: "cc74") { message, ctx in
guard case .controlChange(_, 74, let value) = message, guard case .controlChange(_, 74, let value) = message,
let synth = activeSynth else { return } let synth = activeSynth else { return }
let normalized = Double(value) / 127.0 let normalized = Double(value) / 127.0
try? ctx.set("cutoff", to: normalized * 8000.0, on: synth) ctx.set("cutoff", to: normalized * 8000.0, on: synth)
} }
``` ```
@@ -160,7 +160,7 @@ let server = OSCServer(port: 57120, engine: engine)
server.addHandler(address: "/note") { msg, ctx in server.addHandler(address: "/note") { msg, ctx in
guard let note = msg[0]?.intValue else { return } guard let note = msg[0]?.intValue else { return }
let synth = SineTone() let synth = SineTone()
synth.$freq.value = midiNoteToHz(Double(note)) synth.$freq.value = midiToHz(Double(note))
ctx.add(synth) ctx.add(synth)
} }
@@ -242,7 +242,7 @@ server.addHandler(address: "/synth/set") { msg, ctx in
guard let key = msg[0]?.stringValue, guard let key = msg[0]?.stringValue,
let value = msg[1]?.floatValue, let value = msg[1]?.floatValue,
let synth = activeSynth else { return } let synth = activeSynth else { return }
try? ctx.set(key, to: Double(value), on: synth) ctx.set(key, to: Double(value), on: synth)
} }
``` ```
@@ -272,7 +272,7 @@ let server = OSCServer(port: 57120, engine: engine)
// MIDI plays notes // MIDI plays notes
midi.addHandler(name: "notes") { msg, ctx in midi.addHandler(name: "notes") { msg, ctx in
if case .noteOn(_, let note, let vel) = msg, vel > 0 { if case .noteOn(_, let note, let vel) = msg, vel > 0 {
let s = SineTone(); s.$freq.value = midiNoteToHz(Double(note)); ctx.add(s) let s = SineTone(); s.$freq.value = midiToHz(Double(note)); ctx.add(s)
} }
} }
@@ -1,8 +1,4 @@
# GeneratorInputProvider # ``GeneratorInputProvider``
@Metadata {
@PageKind(article)
}
Pass a fresh generator subgraph (or a scalar) per process spawn through any Generator slot that accepts `any ValidGeneratorInput`, without sharing RT state across Synthesizer instances. Pass a fresh generator subgraph (or a scalar) per process spawn through any Generator slot that accepts `any ValidGeneratorInput`, without sharing RT state across Synthesizer instances.
@@ -9,16 +9,19 @@ Generators for reading from and writing to the Lyrebird bus system.
## Raw index form ## Raw index form
```swift ```swift
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
let lfo: OscSin.Control = OscSin.Control(freq: 2.0)
// Single-channel (default) // Single-channel (default)
In.Audio(bus: 2) // AudioGenerator — reads audioBuses[2] _ = In.Audio(bus: 2) // AudioGenerator — reads audioBuses[2]
In.Control(bus: 10) // ControlGenerator — reads controlBuses[10], interpolated ramp _ = In.Control(bus: 10) // ControlGenerator — reads controlBuses[10], interpolated ramp
// Multi-channel — reads N consecutive buses, returns N channels (static at init) // Multi-channel — reads N consecutive buses, returns N channels (static at init)
In.Audio(bus: 4, channels: 3) // reads audioBuses[4], [5], [6] _ = In.Audio(bus: 4, channels: 3) // reads audioBuses[4], [5], [6]
In.Control(bus: 10, channels: 2) // reads controlBuses[10] and [11], independent ramps _ = In.Control(bus: 10, channels: 2) // reads controlBuses[10] and [11], independent ramps
Out.Audio(bus: 0, source: sig) // accumulates into audioBuses[0] _ = Out.Audio(bus: 0, source: sig) // accumulates into audioBuses[0]
Out.Control(bus: 10, source: lfo) // accumulates into controlBuses[10] _ = Out.Control(bus: 10, source: lfo) // accumulates into controlBuses[10]
``` ```
## AudioBus / ControlBus form (preferred) ## AudioBus / ControlBus form (preferred)
@@ -27,21 +30,24 @@ Use ``BusAllocator`` to obtain typed bus handles instead of raw integers, then p
to the convenience initialisers: to the convenience initialisers:
```swift ```swift
let osc: OscSin.Audio = OscSin.Audio(freq: 440.0)
let lfo: OscSin.Control = OscSin.Control(freq: 2.0)
let stereo = try engine.busAllocator.allocateAudioBus(channelCount: 2) let stereo = try engine.busAllocator.allocateAudioBus(channelCount: 2)
let ctrl = try engine.busAllocator.allocateControlBus() let ctrl = try engine.busAllocator.allocateControlBus()
// Multi-channel read — single generator, N-channel output (preferred) // Multi-channel read — single generator, N-channel output (preferred)
In.Audio(bus: stereo) // channels == stereo.channelCount _ = In.Audio(bus: stereo) // channels == stereo.channelCount
// Independent generators per channel — GeneratorArray // Independent generators per channel — GeneratorArray
In.Audio.multi(bus: stereo) _ = In.Audio.multi(bus: stereo)
// Write — clamped to stereo.channelCount channels // Write — clamped to stereo.channelCount channels
Out.Audio(bus: stereo, source: Pan2(input: osc, pan: 0.0)) _ = Out.Audio(bus: stereo, source: Pan2(input: osc, pan: 0.0))
// Control read / write // Control read / write
In.Control(bus: ctrl) _ = In.Control(bus: ctrl)
Out.Control(bus: ctrl, source: lfo) _ = Out.Control(bus: ctrl, source: lfo)
``` ```
See <doc:BusSystem> for bus layout, reserved ranges, and allocator details. See <doc:BusSystem> for bus layout, reserved ranges, and allocator details.
@@ -13,15 +13,18 @@ Delay line generators shipped with the `Lyrebird` module.
Variable delay with no feedback. Power-of-2 circular buffer. Variable delay with no feedback. Power-of-2 circular buffer.
```swift ```swift
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
let lfoGen: OscSin.Control = OscSin.Control(freq: 5.0, mul: 0.005, add: 0.02)
// Basic usage — sampleRate required to size the buffer correctly // Basic usage — sampleRate required to size the buffer correctly
DelayLine(input: sig, maxDelay: 1.0, delay: 0.25, sampleRate: 44100) _ = DelayLine(input: sig, maxDelay: 1.0, delay: 0.25, sampleRate: 44100)
// Audio-rate modulation (vibrato, chorus, pitch effects) // Audio-rate modulation (vibrato, chorus, pitch effects)
DelayLine(input: sig, maxDelay: 0.05, delay: lfoGen, sampleRate: 44100, _ = DelayLine(input: sig, maxDelay: 0.05, delay: lfoGen, sampleRate: 44100,
interpolation: .cubic) interpolation: .cubic)
// 48 kHz engine // 48 kHz engine
DelayLine(input: sig, maxDelay: 1.0, delay: 0.25, sampleRate: 48000) _ = DelayLine(input: sig, maxDelay: 1.0, delay: 0.25, sampleRate: 48000)
``` ```
### Parameters ### Parameters
@@ -52,17 +55,20 @@ Delay with exponential feedback decay. `decayTime` sets the time for the tail to
`targetAmp` (default −60 dB / 0.001). Supports audio-rate `delay` and `decayTime` modulation. `targetAmp` (default −60 dB / 0.001). Supports audio-rate `delay` and `decayTime` modulation.
```swift ```swift
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
let lfoGen: OscSin.Control = OscSin.Control(freq: 5.0, mul: 0.005, add: 0.02)
// Basic usage // Basic usage
DelayLineFeedback(input: sig, maxDelay: 1.0, delay: 0.25, _ = DelayLineFeedback(input: sig, maxDelay: 1.0, delay: 0.25,
decayTime: 2.0, sampleRate: 44100) decayTime: 2.0, sampleRate: 44100)
// Custom target amplitude (e.g. −40 dB) // Custom target amplitude (e.g. −40 dB)
DelayLineFeedback(input: sig, maxDelay: 0.5, delay: 0.25, _ = DelayLineFeedback(input: sig, maxDelay: 0.5, delay: 0.25,
decayTime: 1.5, targetAmp: 0.01, sampleRate: 44100) decayTime: 1.5, targetAmp: 0.01, sampleRate: 44100)
// Audio-rate delay modulation // Audio-rate delay modulation
DelayLineFeedback(input: sig, maxDelay: 0.5, delay: lfoGen, _ = DelayLineFeedback(input: sig, maxDelay: 0.5, delay: lfoGen,
decayTime: 2.0, sampleRate: 44100, interpolation: .linear) decayTime: 2.0, sampleRate: 44100, interpolation: .linear)
``` ```
### Parameters ### Parameters
@@ -116,6 +116,7 @@ identical to ``EnvelopeGen/Audio``) and fills the output buffer with a linear ra
the block's target level. Intra-block shape detail is lost; use Audio-rate when that matters. the block's target level. Intra-block shape detail is lost; use Audio-rate when that matters.
```swift ```swift
let osc: OscSin.Audio = OscSin.Audio(freq: 440.0)
let env = Envelope(levels: [0, 1, 0.001], durations: [0.01, 0.5], curves: [.sine, .exponential]) let env = Envelope(levels: [0, 1, 0.001], durations: [0.01, 0.5], curves: [.sine, .exponential])
// Audio-rate amplitude envelope. Constructed inside Synthesizer.build() with // Audio-rate amplitude envelope. Constructed inside Synthesizer.build() with
@@ -135,6 +136,7 @@ let scaledEnv = EnvelopeGen.Audio(envelope: env,
// timeScale: stretches each segment's duration. Same shape, twice as long. // timeScale: stretches each segment's duration. Same shape, twice as long.
let slowEnv = EnvelopeGen.Audio(envelope: env, timeScale: 2.0 as Double) let slowEnv = EnvelopeGen.Audio(envelope: env, timeScale: 2.0 as Double)
_ = (ampEnv, filter, scaledEnv, slowEnv)
``` ```
**Parameters:** **Parameters:**
@@ -16,7 +16,8 @@ Butterworth cascades, and resonating/comb/allpass designs.
Single-pole IIR: `y[n] = a0·x[n] + a1·x[n-1] + b1·y[n-1]` Single-pole IIR: `y[n] = a0·x[n] + a1·x[n-1] + b1·y[n-1]`
```swift ```swift
FirstOrderSection(input: sig, a0: 1.0, a1: 0.0, b1: 0.5) let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
_ = FirstOrderSection(input: sig, a0: 1.0, a1: 0.0, b1: 0.5)
``` ```
All coefficient inputs accept any ``ValidGeneratorInput``. Generator inputs are read at audio All coefficient inputs accept any ``ValidGeneratorInput``. Generator inputs are read at audio
@@ -27,7 +28,8 @@ rate, enabling audio-rate coefficient modulation.
Two-pole biquad (Direct Form I): `y[n] = a0·x + a1·x[n-1] + a2·x[n-2] − b1·y[n-1] − b2·y[n-2]` Two-pole biquad (Direct Form I): `y[n] = a0·x + a1·x[n-1] + a2·x[n-2] − b1·y[n-1] − b2·y[n-2]`
```swift ```swift
SecondOrderSection(input: sig, a0: 1.0, a1: 0.0, a2: 0.0, b1: 0.5, b2: 0.25) let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
_ = SecondOrderSection(input: sig, a0: 1.0, a1: 0.0, a2: 0.0, b1: 0.5, b2: 0.25)
``` ```
Pass `b1` and `b2` as positive magnitudes — the subtraction is applied internally. Pass `b1` and `b2` as positive magnitudes — the subtraction is applied internally.
@@ -56,14 +58,17 @@ Frequencies above `0.999 × Nyquist` return silence. Shared infrastructure: `Biq
| ``RBJHighShelf`` | High-shelf boost/cut; `gain` in dB, `slope` controls transition steepness | | ``RBJHighShelf`` | High-shelf boost/cut; `gain` in dB, `slope` controls transition steepness |
```swift ```swift
RBJLowPass.Audio(input: sig, freq: 800.0, q: 0.707) // Butterworth LPF let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
RBJHighPass.Audio(input: sig, freq: 400.0, q: 0.707) let lfoGen: OscSin.Control = OscSin.Control(freq: 0.5, mul: 400.0, add: 800.0)
RBJBandPass.Audio(input: sig, freq: 1000.0, bandwidth: 1.0) // 1-octave BPF
RBJNotch.Audio(input: sig, freq: 60.0, q: 10.0) // hum removal _ = RBJLowPass.Audio(input: sig, freq: 800.0, q: 0.707) // Butterworth LPF
RBJAllPass.Audio(input: sig, freq: lfoGen, q: 1.0) // phaser stage _ = RBJHighPass.Audio(input: sig, freq: 400.0, q: 0.707)
RBJPeakingEQ.Audio(input: sig, freq: 1000.0, gain: 6.0, q: 1.0) // +6 dB at 1 kHz _ = RBJBandPass.Audio(input: sig, freq: 1000.0, bandwidth: 1.0) // 1-octave BPF
RBJLowShelf.Audio(input: sig, freq: 200.0, gain: 6.0, slope: 1.0) _ = RBJNotch.Audio(input: sig, freq: 60.0, q: 10.0) // hum removal
RBJHighShelf.Audio(input: sig, freq: 8000.0, gain: 3.0, slope: 1.0) _ = RBJAllPass.Audio(input: sig, freq: lfoGen, q: 1.0) // phaser stage
_ = RBJPeakingEQ.Audio(input: sig, freq: 1000.0, gain: 6.0, q: 1.0) // +6 dB at 1 kHz
_ = RBJLowShelf.Audio(input: sig, freq: 200.0, gain: 6.0, slope: 1.0)
_ = RBJHighShelf.Audio(input: sig, freq: 8000.0, gain: 3.0, slope: 1.0)
``` ```
--- ---
@@ -80,10 +85,11 @@ Cascaded biquad + first-order sections (bilinear transform, Butterworth Q formul
| ``ButterworthBandReject`` | N-th order band-reject (parallel LP + HP) | | ``ButterworthBandReject`` | N-th order band-reject (parallel LP + HP) |
```swift ```swift
ButterworthLowPass.Audio(input: sig, freq: 800.0, order: 4) let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
ButterworthHighPass.Audio(input: sig, freq: 400.0, order: 2) _ = ButterworthLowPass.Audio(input: sig, freq: 800.0, order: 4)
ButterworthBandPass.Audio(input: sig, lowFreq: 400.0, highFreq: 1200.0, order: 4) _ = ButterworthHighPass.Audio(input: sig, freq: 400.0, order: 2)
ButterworthBandReject.Audio(input: sig, lowFreq: 400.0, highFreq: 1200.0, order: 4) _ = ButterworthBandPass.Audio(input: sig, lowFreq: 400.0, highFreq: 1200.0, order: 4)
_ = ButterworthBandReject.Audio(input: sig, lowFreq: 400.0, highFreq: 1200.0, order: 4)
``` ```
--- ---
@@ -99,24 +105,26 @@ ButterworthBandReject.Audio(input: sig, lowFreq: 400.0, highFreq: 1200.0, order:
| ``ResonatorBank`` | Klank-style parallel bank of N two-pole resonators driven from a `[freq, decay, amp]` ``LyrebirdBuffer``; vDSP-accelerated per-sample inner loop. Modal synthesis (marimba, vibraphone, bell, bowl). | | ``ResonatorBank`` | Klank-style parallel bank of N two-pole resonators driven from a `[freq, decay, amp]` ``LyrebirdBuffer``; vDSP-accelerated per-sample inner loop. Modal synthesis (marimba, vibraphone, bell, bowl). |
```swift ```swift
ResonatingFilter(input: sig, freq: 440.0, decayTime: 1.0) let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
RingingFilter(input: sig, freq: 440.0, bandwidth: 20.0) _ = ResonatingFilter(input: sig, freq: 440.0, decayTime: 1.0)
CombFilter(input: sig, delay: 0.01, decayTime: 0.5) _ = RingingFilter(input: sig, freq: 440.0, bandwidth: 20.0)
AllpassFilter(input: sig, delay: 0.005, decayTime: 0.3) // maxDelay bounds the pre-allocated delay line; delay must stay <= maxDelay.
_ = CombFilter(input: sig, maxDelay: 0.05, delay: 0.01, decayTime: 0.5)
_ = AllpassFilter(input: sig, maxDelay: 0.05, delay: 0.005, decayTime: 0.3)
// Three-mode marimba-like bank: frame k = [freq, decay, amp] // Three-mode marimba-like bank: frame k = [freq, decay, amp]
let modes = LyrebirdBuffer(count: 3, channelCount: resonatorBankChannelCount) let modes: LyrebirdBuffer = LyrebirdBuffer(count: 3, channelCount: resonatorBankChannelCount)
let triplets: [(Double, Double, Double)] = [ let triplets: [(Double, Double, Double)] = [
(300.0, 0.40, 1.00), (300.0, 0.40, 1.00),
(1200.0, 0.25, 0.40), (1200.0, 0.25, 0.40),
(2700.0, 0.18, 0.20), (2700.0, 0.18, 0.20),
] ]
for (i, t) in triplets.enumerated() { for (i, t): (Int, (Double, Double, Double)) in triplets.enumerated() {
modes.setValue(t.0, frame: i, channel: resonatorBankFreqChannel) modes.setValue(t.0, frame: i, channel: resonatorBankFreqChannel)
modes.setValue(t.1, frame: i, channel: resonatorBankDecayChannel) modes.setValue(t.1, frame: i, channel: resonatorBankDecayChannel)
modes.setValue(t.2, frame: i, channel: resonatorBankAmpChannel) modes.setValue(t.2, frame: i, channel: resonatorBankAmpChannel)
} }
ResonatorBank.Audio(input: Impulse.Audio(freq: 0.5), buffer: modes) _ = ResonatorBank.Audio(input: Impulse.Audio(freq: 0.5), buffer: modes)
``` ```
--- ---
@@ -128,8 +136,11 @@ ResonatorBank.Audio(input: Impulse.Audio(freq: 0.5), buffer: modes)
| ``MoogLadder`` | Huovilainen-style 4-pole resonant lowpass with per-stage `tanh` saturation, internal 2× oversampling, and SC-style half-sample feedback compensation. Self-oscillates near `resonance = 1.0`. | | ``MoogLadder`` | Huovilainen-style 4-pole resonant lowpass with per-stage `tanh` saturation, internal 2× oversampling, and SC-style half-sample feedback compensation. Self-oscillates near `resonance = 1.0`. |
```swift ```swift
MoogLadder.Audio(input: noise, freq: 1200.0, resonance: 0.7) // classic resonant LP let noise: WhiteNoise.Audio = WhiteNoise.Audio()
MoogLadder.Audio(input: noise, freq: lfo, resonance: 1.1) // ringing self-osc with cutoff sweep let lfo: OscSin.Control = OscSin.Control(freq: 0.5, mul: 400.0, add: 800.0)
_ = MoogLadder.Audio(input: noise, freq: 1200.0, resonance: 0.7) // classic resonant LP
_ = MoogLadder.Audio(input: noise, freq: lfo, resonance: 1.1) // ringing self-osc with cutoff sweep
``` ```
--- ---
@@ -150,14 +161,18 @@ control signals, building envelopes from impulses, and removing DC bias.
| ``LeakDC`` | One-pole DC blocker: `y[n] = x[n] − x[n−1] + coef · y[n−1]` | | ``LeakDC`` | One-pole DC blocker: `y[n] = x[n] − x[n−1] + coef · y[n−1]` |
```swift ```swift
Lag.Audio(input: env, time: 0.05) // 50 ms lag let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
LagUpDown.Audio(input: env, lagUp: 0.1, lagDown: 0.01) // slow attack, fast release let env: OscSin.Audio = OscSin.Audio(freq: 1.0)
Lag2.Audio(input: sig, time: 0.05) // extra-smooth 50 ms let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0)
Lag2UpDown.Audio(input: env, lagUp: 0.1, lagDown: 0.01)
Decay.Audio(input: impulse, decayTime: 0.5) // 500 ms impulse tail _ = Lag.Audio(input: env, time: 0.05) // 50 ms lag
Decay2.Audio(input: impulse, attackTime: 0.01, decayTime: 0.5) // rounded attack _ = LagUpDown.Audio(input: env, lagUp: 0.1, lagDown: 0.01) // slow attack, fast release
LeakDC.Audio(input: sig) // default coef 0.995 _ = Lag2.Audio(input: sig, time: 0.05) // extra-smooth 50 ms
LeakDC.Control(input: sig) // default coef 0.9 _ = Lag2UpDown.Audio(input: env, lagUp: 0.1, lagDown: 0.01)
_ = Decay.Audio(input: impulse, decayTime: 0.5) // 500 ms impulse tail
_ = Decay2.Audio(input: impulse, attackTime: 0.01, decayTime: 0.5) // rounded attack
_ = LeakDC.Audio(input: sig) // default coef 0.995
_ = LeakDC.Control(input: sig) // default coef 0.9
``` ```
### Slew Limiting ### Slew Limiting
@@ -169,9 +184,13 @@ de-zippering, and taming abrupt control jumps. The state initialises to the firs
sample (no startup transient). sample (no startup transient).
```swift ```swift
Slew.Audio(input: sig, up: 100.0, dn: 100.0) // ≤ 100 units/sec slope in either direction let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
Slew.Audio(input: pitch, up: 50.0, dn: 200.0) // slow glide up, fast fall let pitch: OscSin.Control = OscSin.Control(freq: 1.0, mul: 100.0, add: 440.0)
Slew.Control(input: cv, up: 10.0, dn: 10.0) // block-rate slew let cv: OscSin.Control = OscSin.Control(freq: 1.0)
_ = Slew.Audio(input: sig, up: 100.0, dn: 100.0) // ≤ 100 units/sec slope in either direction
_ = Slew.Audio(input: pitch, up: 50.0, dn: 200.0) // slow glide up, fast fall
_ = Slew.Control(input: cv, up: 10.0, dn: 10.0) // block-rate slew
``` ```
- `up` / `dn` — maximum rising / falling slope in units per second. Default `1.0` each. - `up` / `dn` — maximum rising / falling slope in units per second. Default `1.0` each.
@@ -8,33 +8,30 @@ The base unit of signal production in Lyrebird.
## Protocol Hierarchy ## Protocol Hierarchy
```swift ``Generator`` refines `AnyObject` and ``ValidGeneratorInput``:
protocol Generator: AnyObject, ValidGeneratorInput {
var rate: ProcessingRate { get }
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]]
func floatValue(graph: SynthGraph) -> Double
var _segmentSerial: UInt64 { get set }
var _cachedResult: [[Double]] { get set }
}
protocol AudioGenerator: Generator {} // rate == .audio (provided by extension) | Requirement | Role |
protocol ControlGenerator: Generator {} // rate == .control (provided by extension) |---|---|
| ``Generator/rate`` | ``ProcessingRate`` — supplied by the ``AudioGenerator`` / ``ControlGenerator`` extensions. |
| ``Generator/outputChannelCount`` | Channel count of `_result`. Defaults to `1`; **multi-row generators must override it** or they silently mono-ize under `+ - * /`. See <doc:MultiChannel>. |
| `_computeSamples(graph:count:)` | Produce `count` samples. The one method every generator implements. |
| ``Generator/floatValue(graph:)`` | Scalar value. Provided by the ``AudioGenerator`` extension; ``ControlGenerator`` conformers supply their own. |
| `_segmentSerial` / `_cachedResult` | Fan-out cache. Inherited from ``GeneratorBase`` — never redeclare. |
enum ProcessingRate { Two refinements select the rate:
case audio // one output sample per engine sample tick (e.g. 44100 Hz)
case control // one output value per block, interpolated to audio rate downstream
case spectral // reserved
case demand // reserved
}
/// Marks a caseless namespace enum whose nested Audio and Control classes form a matched | Protocol | Adds |
/// generator pair. Conforming types declare AudioType and ControlType so DocC, generic |---|---|
/// code, and tooling can discover the pair at compile time. | ``AudioGenerator`` | Nothing — `rate == .audio` and `floatValue` come from its extension. |
protocol GeneratorEnum { | ``ControlGenerator`` | ``ControlGenerator/previousOutputValue`` and `_subBlockBuffer`, backing the block-rate ramp and the sub-block loop. |
associatedtype AudioType: AudioGenerator
associatedtype ControlType: ControlGenerator ``ProcessingRate`` has four cases: ``ProcessingRate/audio`` (one sample per engine tick),
} ``ProcessingRate/control`` (one value per block, interpolated downstream), and
``` ``ProcessingRate/spectral`` / ``ProcessingRate/demand`` (reserved).
``GeneratorEnum`` marks a caseless namespace enum whose nested `Audio` and `Control` classes form a
matched pair, declaring ``GeneratorEnum/AudioType`` and ``GeneratorEnum/ControlType`` so DocC,
generic code, and tooling can discover the pair at compile time.
All built-in paired generators (`OscSin`, `OscTable`, `Impulse`, `WhiteNoise`, `LFStepNoise`, All built-in paired generators (`OscSin`, `OscTable`, `Impulse`, `WhiteNoise`, `LFStepNoise`,
`LFLineNoise`, `EnvelopeGen`, `PlayBuffer`, `RecordBuffer`, `In`, `Out`, `SendTrigger`, `Demand`) `LFLineNoise`, `EnvelopeGen`, `PlayBuffer`, `RecordBuffer`, `In`, `Out`, `SendTrigger`, `Demand`)
@@ -75,15 +72,24 @@ typealias ClosureBody = (SynthGraph, Int) -> Double // RT-safe closure signatur
## ValidGeneratorInput Protocol ## ValidGeneratorInput Protocol
Enables seamless mixing of constants, generators, parameter keys, and closures as generator inputs. Enables seamless mixing of constants, generators, and closures as generator inputs.
```swift ```swift
OscSin.Audio(freq: 440.0) // Float literal let someGenerator: OscSin.Control = OscSin.Control(freq: 2.0, mul: 10.0, add: 440.0)
OscSin.Audio(freq: someGenerator) // another Generator
OscSin.Audio(freq: "FreqParam") // string key — resolved from ParameterTable at RT let a: OscSin.Audio = OscSin.Audio(freq: 440.0) // Double literal
OscSin.Audio(freq: Closure { g, i in ... }) // closure (allocates — offline only) let b: OscSin.Audio = OscSin.Audio(freq: 60) // Int literal
let c: OscSin.Audio = OscSin.Audio(freq: someGenerator) // another Generator
// Closure — allocates per block, so offline / non-RT use only.
let d: OscSin.Audio = OscSin.Audio(freq: Closure { graph, i in
440.0 + Double(i)
})
``` ```
To drive an input from a live parameter, wire the projected value of a `@LiveParam`
(`$freq`, a ``ParameterNode``) straight into the generator — see <doc:ParameterInputs>.
```swift ```swift
protocol ValidGeneratorInput { protocol ValidGeneratorInput {
func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]]
@@ -92,7 +98,7 @@ protocol ValidGeneratorInput {
func needsInterpolation() -> Bool func needsInterpolation() -> Bool
func sampleBlock(graph: SynthGraph, count: Int, previousValue: Double) -> [Double] func sampleBlock(graph: SynthGraph, count: Int, previousValue: Double) -> [Double]
} }
// Conforming types: Double, Int, String, any Generator, Closure // Conforming types: Double, Int, any Generator, Closure, GeneratorInputProvider
// Contract: calculatedSamples must always return a non-empty outer array. // Contract: calculatedSamples must always return a non-empty outer array.
``` ```
@@ -101,8 +107,11 @@ protocol ValidGeneratorInput {
Math operators on ``Generator`` inputs create ``BinaryOpGenerator`` instances: Math operators on ``Generator`` inputs create ``BinaryOpGenerator`` instances:
```swift ```swift
let sig = OscSin.Audio(freq: 440) * 0.5 // BinaryOpGenerator (*) let sig1: OscSin.Audio = OscSin.Audio(freq: 440)
let mix = sig1 + sig2 // BinaryOpGenerator (+) let sig2: OscSin.Audio = OscSin.Audio(freq: 660)
let scaled: any Generator = sig1 * 0.5 // BinaryOpGenerator (*)
let mix: any Generator = sig1 + sig2 // BinaryOpGenerator (+)
``` ```
Operators: `*`, `+`, `-`, `/` Operators: `*`, `+`, `-`, `/`
@@ -120,10 +129,14 @@ precedence applies** — no special rules to learn:
`*` and `/` bind before `+` and `-`; equal-precedence operators are left-to-right: `*` and `/` bind before `+` and `-`; equal-precedence operators are left-to-right:
```swift ```swift
osc * 0.5 + env // → (osc * 0.5) + env let osc: OscSin.Audio = OscSin.Audio(freq: 440)
osc + env * 0.5 // → osc + (env * 0.5) let env: OscSin.Audio = OscSin.Audio(freq: 1.0)
osc - env - lfo // → (osc - env) - lfo (left-associative) let lfo: OscSin.Audio = OscSin.Audio(freq: 2.0)
(osc + env) * 0.5 // parentheses override as expected
let a: any Generator = osc * 0.5 + env // → (osc * 0.5) + env
let b: any Generator = osc + env * 0.5 // → osc + (env * 0.5)
let c: any Generator = osc - env - lfo // → (osc - env) - lfo (left-associative)
let d: any Generator = (osc + env) * 0.5 // parentheses override as expected
``` ```
> Note: `Double op Double` always resolves to the Swift stdlib, not a ``BinaryOpGenerator``. > Note: `Double op Double` always resolves to the Swift stdlib, not a ``BinaryOpGenerator``.
@@ -169,21 +182,22 @@ automatically. See <doc:WritingGenerators> for the full pattern.
## Pre-Allocated Output Buffer Pattern ## Pre-Allocated Output Buffer Pattern
Every generator pre-allocates `_result` to `lyrebirdDefaultResultBufferSize` (512) samples in Every generator pre-allocates `_result` to `lyrebirdDefaultResultBufferSize` (512) samples in
`init`, and opens `_computeSamples` with a `precondition` that fires in both debug and release `init`, and opens `_computeSamples` with `_checkCount(count)` — a ``GeneratorBase`` helper that
if the engine is misconfigured: traps in both debug and release if the engine is misconfigured:
```swift ```swift
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
precondition(count <= _result[0].count, _checkCount(count)
"count \(count) exceeds pre-allocated buffer. "
+ "Ensure blockSize ≤ lyrebirdDefaultResultBufferSize.")
// … fill _result[0][0..<count] … // … fill _result[0][0..<count] …
return _result return _result
} }
``` ```
Use `_checkCount(count)` rather than writing the `precondition` out by hand — it is the
canonical form, and inlining the long version in a new generator is a review violation.
`SynthesisEngine.init` enforces `blockSize ≤ lyrebirdDefaultResultBufferSize`, so the `SynthesisEngine.init` enforces `blockSize ≤ lyrebirdDefaultResultBufferSize`, so the
precondition is never triggered in normal use. check is never triggered in normal use.
## count: Int Parameter ## count: Int Parameter
@@ -77,17 +77,17 @@ position.
### Quick start ### Quick start
```swift ```swift
let buf = try LyrebirdBuffer(path: someAudioFileURL) let buf = try LyrebirdBuffer.load(url: someAudioFileURL)
let g = BufferGrain( let g = BufferGrain(
buffer: buf, buffer: buf,
position: 0.5, // normalized buffer position [0, 1] position: 0.5, // normalized buffer position [0, 1]
positionSpread: 0.05, // ±5% random offset per grain positionSpread: 0.05, // ±5% random offset per grain
duration: 0.1, // grain length in seconds duration: 0.1, // grain length in seconds
amp: 0.4,
pan: 0.0, // centre, ±0 spread
pitchRatio: 1.0, // playback rate (×) pitchRatio: 1.0, // playback rate (×)
pitchDispersion: 0.05, // ±5% random pitch per grain pitchDispersion: 0.05, // ±5% random pitch per grain
density: 30.0, // grains/sec density: 30.0 // grains/sec
pan: 0.0, // centre, ±0 spread
amp: 0.4
) )
output(bus: 0, source: g) // 2-channel; Out fans to bus 0 + bus 1 output(bus: 0, source: g) // 2-channel; Out fans to bus 0 + bus 1
``` ```
@@ -208,13 +208,13 @@ Hop-driven grain reader over a static buffer with a generator-driven read positi
without affecting pitch. without affecting pitch.
```swift ```swift
let buf = try LyrebirdBuffer(path: someAudioFileURL) let buf = try LyrebirdBuffer.load(url: someAudioFileURL)
// Half-speed playback (no pitch change) — stream pos at 0.5× normal rate // Half-speed playback (no pitch change) — stream pos at 0.5× normal rate
let posLfo = LinLin.Audio( let posLfo = LinLin.Audio(
input: OscSin.Control(freq: 0.5), OscSin.Control(freq: 0.5),
inLow: -1.0, inHigh: 1.0, inLo: -1.0, inHi: 1.0,
outLow: 0.0, outHigh: 1.0 outLo: 0.0, outHi: 1.0
) )
let ts = TimeStretch.Audio( let ts = TimeStretch.Audio(
buffer: buf, buffer: buf,
@@ -11,8 +11,8 @@ Math utility generators and arithmetic operator overloads shipped with the `Lyre
## Math Generators ## Math Generators
```swift ```swift
LinLin.Audio(input: lfo, inLow: -1.0, inHigh: 1.0, outLow: 200.0, outHigh: 800.0) // maps [-1,1] → [200,800] LinLin.Audio(lfo, inLo: -1.0, inHi: 1.0, outLo: 200.0, outHi: 800.0) // maps [-1,1] → [200,800]
LinLin.Audio(input: env, inLow: 0.0, inHigh: 1.0, outLow: 200.0, outHigh: 800.0) // maps [ 0,1] → [200,800] LinLin.Audio(env, inLo: 0.0, inHi: 1.0, outLo: 200.0, outHi: 800.0) // maps [ 0,1] → [200,800]
Pow.Audio(osc, exp: 2.0) // input ^ 2 Pow.Audio(osc, exp: 2.0) // input ^ 2
(-1.0 as Double) * osc // −input (phase inversion) (-1.0 as Double) * osc // −input (phase inversion)
Cos.Audio(phasor) // cosine waveshaper, input in radians Cos.Audio(phasor) // cosine waveshaper, input in radians
@@ -37,6 +37,11 @@ rule are decided at graph-construction time from each operand's `outputChannelCo
| `N × M`, both > 1, N ≠ M | — | `precondition` traps at `init` — no implicit wrap-extend, no truncation. | | `N × M`, both > 1, N ≠ M | — | `precondition` traps at `init` — no implicit wrap-extend, no truncation. |
```swift ```swift
let osc: OscSin.Audio = OscSin.Audio(freq: 440.0)
let dry: OscSin.Audio = OscSin.Audio(freq: 220.0)
let dry2ch: Pan2 = Pan2(input: OscSin.Audio(freq: 220.0), pan: -0.5)
let wet2ch: Pan2 = Pan2(input: OscSin.Audio(freq: 440.0), pan: 0.5)
// Stereo × scalar — both channels scale. // Stereo × scalar — both channels scale.
let pan = Pan2(input: osc, pan: -0.3) let pan = Pan2(input: osc, pan: -0.3)
output(bus: 0, source: pan * 0.5) output(bus: 0, source: pan * 0.5)
@@ -80,10 +85,14 @@ output(bus: 0, source: oscs) // bus 0 = 440 Hz, bus 1 = 880 Hz
All four arithmetic operators work element-wise and return a new ``GeneratorArray``: All four arithmetic operators work element-wise and return a new ``GeneratorArray``:
```swift ```swift
let oscs: GeneratorArray = expand([440.0, 880.0]) { OscSin.Audio(freq: $0) }
let otherOscs: GeneratorArray = expand([550.0, 660.0]) { OscSin.Audio(freq: $0) }
let quiet = oscs * 0.5 // each channel × 0.5 let quiet = oscs * 0.5 // each channel × 0.5
let louder = 2.0 * oscs // scalar op GeneratorArray let louder = 2.0 * oscs // scalar op GeneratorArray
let sum = oscs + otherOscs // element-wise (counts must match) let sum = oscs + otherOscs // element-wise (counts must match)
let diff = oscs - 0.1 // subtract scalar from each channel let diff = oscs - 0.1 // subtract scalar from each channel
_ = (quiet, louder, sum, diff)
``` ```
Mismatched-count `GeneratorArray op GeneratorArray` is caught by a `precondition` at build time. Mismatched-count `GeneratorArray op GeneratorArray` is caught by a `precondition` at build time.
@@ -101,6 +110,7 @@ Mismatched-count `GeneratorArray op GeneratorArray` is caught by a `precondition
| N | `bus` … `bus + N - 1` | | N | `bus` … `bus + N - 1` |
```swift ```swift
let osc: OscSin.Audio = OscSin.Audio(freq: 440.0)
output(bus: 0, source: Pan2(input: osc, pan: 0.0)) // writes buses 0 and 1 output(bus: 0, source: Pan2(input: osc, pan: 0.0)) // writes buses 0 and 1
output(bus: 0, source: expand([440.0, 880.0]) { OscSin.Audio(freq: $0) }) // same output(bus: 0, source: expand([440.0, 880.0]) { OscSin.Audio(freq: $0) }) // same
``` ```
@@ -135,8 +145,9 @@ Read N consecutive buses with `input(bus:channels:)` inside ``SynthesizerBase/bu
// Read stereo from buses 2–3, apply gain, write to output buses 0–1 // Read stereo from buses 2–3, apply gain, write to output buses 0–1
output(bus: 0, source: input(bus: 2, channels: 2) * 0.5) output(bus: 0, source: input(bus: 2, channels: 2) * 0.5)
// Read hardware input (assuming numOutputChannels = 2) // Read hardware input (the first input bus sits just above the output buses;
output(bus: 0, source: input(bus: engine.numOutputChannels, channels: 2)) // here numOutputChannels = 2, so input buses start at 2)
output(bus: 0, source: input(bus: 2, channels: 2))
``` ```
`In.multi(bus:channels:)` is the underlying static helper if you need it outside `In.multi(bus:channels:)` is the underlying static helper if you need it outside
@@ -65,16 +65,18 @@ Two scales:
| Power / energy | `powToDb` / `dbToPow` | 10 × log₁₀ | FFT magnitudes, RMS | | Power / energy | `powToDb` / `dbToPow` | 10 × log₁₀ | FFT magnitudes, RMS |
```swift ```swift
ampToDb(1.0) // 0.0 dB — full scale _ = ampToDb(1.0) // 0.0 dB — full scale
ampToDb(0.5) // −6.02 dB _ = ampToDb(0.5) // −6.02 dB
dbToAmp(0.0) // 1.0 _ = dbToAmp(0.0) // 1.0
dbToAmp(-6.0) // ~0.501 _ = dbToAmp(-6.0) // ~0.501
// Set a @LiveParam in dB // Convert a dB gain to a linear amplitude (e.g. to set a @LiveParam gain)
synth.$gain.value = dbToAmp(-12.0) let gain: Double = dbToAmp(-12.0)
// Convert FFT bin magnitude // Convert an FFT bin magnitude
let dB = powToDb(magnitude) let magnitude: Double = 0.5
let dB: Double = powToDb(magnitude)
_ = (gain, dB)
``` ```
`ampToDb` and `powToDb` return `-.infinity` for zero input and `NaN` for negative input. `ampToDb` and `powToDb` return `-.infinity` for zero input and `NaN` for negative input.
@@ -105,17 +107,18 @@ driving a pitch-shift or playback-rate generator from semitone
intervals: intervals:
```swift ```swift
midiToRatio(12) // 2.0 — one octave up _ = midiToRatio(12) // 2.0 — one octave up
midiToRatio(-12) // 0.5 — one octave down _ = midiToRatio(-12) // 0.5 — one octave down
ratioToMidi(2.0) // 12.0 _ = ratioToMidi(2.0) // 12.0
// Dot syntax (SC-style `.midiratio` / `.ratiomidi`): // Dot syntax (SC-style `.midiratio` / `.ratiomidi`):
12.midiToRatio // 2.0 _ = 12.midiToRatio // 2.0
(-12).midiToRatio // 0.5 _ = (-12).midiToRatio // 0.5
2.0.ratioToMidi // 12.0 _ = 2.0.ratioToMidi // 12.0
// In context — PitchShift driven from semitone intervals: // In context — PitchShift driven from semitone intervals:
PitchShift.Audio(input: src, pitchRatio: 7.midiToRatio) // perfect fifth up let src: OscSin.Audio = OscSin.Audio(freq: 440.0)
_ = PitchShift.Audio(input: src, pitchRatio: 7.midiToRatio) // perfect fifth up
``` ```
--- ---
@@ -175,7 +178,9 @@ Maps a normalized value in [0, 1] onto an exponential range. Useful for filter s
```swift ```swift
// Frequency sweep from 200 Hz to 2000 Hz driven by a [0, 1] knob // Frequency sweep from 200 Hz to 2000 Hz driven by a [0, 1] knob
let knobValue: Double = 0.5
let freq = linToExp(knobValue, low: 200.0, high: 2000.0) let freq = linToExp(knobValue, low: 200.0, high: 2000.0)
_ = freq
``` ```
### equalPowerFade ### equalPowerFade
@@ -183,8 +188,12 @@ let freq = linToExp(knobValue, low: 200.0, high: 2000.0)
Returns `(gainA, gainB)` for a constant-power crossfade at `position` in [0, 1]. Both channels are −3 dB at the midpoint; combined power stays constant. Returns `(gainA, gainB)` for a constant-power crossfade at `position` in [0, 1]. Both channels are −3 dB at the midpoint; combined power stays constant.
```swift ```swift
let mixPosition: Double = 0.5
let dry: OscSin.Audio = OscSin.Audio(freq: 220.0)
let wet: OscSin.Audio = OscSin.Audio(freq: 440.0)
let (dryGain, wetGain) = equalPowerFade(mixPosition) let (dryGain, wetGain) = equalPowerFade(mixPosition)
Out.Audio(bus: 0, source: dry * dryGain + wet * wetGain) _ = Out.Audio(bus: 0, source: dry * dryGain + wet * wetGain)
``` ```
--- ---
@@ -215,8 +215,9 @@ Gamma distribution parameterised by `mode`. Shape is derived from the mode so th
PDF falls at `mode`. Uses the Marsaglia-Tsang acceptance-rejection algorithm — expected ≈1.7 iterations. PDF falls at `mode`. Uses the Marsaglia-Tsang acceptance-rejection algorithm — expected ≈1.7 iterations.
```swift ```swift
GammaNoise.Audio(mode: 0.5) let modulatorGen: OscSin.Control = OscSin.Control(freq: 0.5, mul: 0.3, add: 0.5)
GammaNoise.Control(mode: modulatorGen) _ = GammaNoise.Audio(mode: 0.5)
_ = GammaNoise.Control(mode: modulatorGen)
``` ```
### LaplaceNoise ### LaplaceNoise
@@ -262,8 +263,9 @@ Poisson distribution with mean `mean`. Outputs non-negative integer values as `D
`PoissonNoise.Control` is the most common usage — one Poisson draw per audio block. `PoissonNoise.Control` is the most common usage — one Poisson draw per audio block.
```swift ```swift
PoissonNoise.Control(mean: 4.0) // integer values ≈ 0–10 let modulatorGen: OscSin.Control = OscSin.Control(freq: 0.5, mul: 2.0, add: 4.0)
PoissonNoise.Control(mean: modulatorGen) // audio-rate mean modulation _ = PoissonNoise.Control(mean: 4.0) // integer values ≈ 0–10
_ = PoissonNoise.Control(mean: modulatorGen) // audio-rate mean modulation
``` ```
### ArcsinNoise ### ArcsinNoise
@@ -282,7 +284,7 @@ Beta distribution mapped to `[lo, hi]` with shape parameters `lowProb` and `high
both equal 2 = triangular. both equal 2 = triangular.
```swift ```swift
BetaRandNoise.Audio(lo: 0.0, hi: 1.0, lowProb: 2.0, highProb: 5.0) _ = BetaRandNoise.Audio(lo: 0.0, hi: 1.0, lowProb: 2.0, highProb: 5.0)
``` ```
### CauchyNoise ### CauchyNoise
@@ -301,7 +303,8 @@ Gaussian (normal) distribution with standard deviation `dev` and `mean`.
Uses the Box-Muller transform — two uniform samples per output value. Uses the Box-Muller transform — two uniform samples per output value.
```swift ```swift
GaussNoise.Audio(dev: 0.1, mean: 0.0) // zero-mean Gaussian noise let lfoGen: OscSin.Control = OscSin.Control(freq: 0.5, mul: 10.0, add: 30.0)
GaussNoise.Control(dev: 30.0, mean: 440.0) // random pitch per block ≈ 440±30 Hz _ = GaussNoise.Audio(dev: 0.1, mean: 0.0) // zero-mean Gaussian noise
GaussNoise.Control(dev: lfoGen, mean: 440.0) // audio-rate stddev modulation _ = GaussNoise.Control(dev: 30.0, mean: 440.0) // random pitch per block ≈ 440±30 Hz
_ = GaussNoise.Control(dev: lfoGen, mean: 440.0) // audio-rate stddev modulation
``` ```
@@ -22,10 +22,12 @@ steady state.
Table-lookup sine oscillator with a 32 768-sample single-cycle table and selectable interpolation. Table-lookup sine oscillator with a 32 768-sample single-cycle table and selectable interpolation.
```swift ```swift
OscSin.Audio(freq: 440.0) // constant freq, linear interp let lfo: OscSin.Control = OscSin.Control(freq: 5.0, mul: 10.0, add: 440.0)
OscSin.Audio(freq: lfo, phase: 0.25) // generator input, quarter-phase offset
OscSin.Audio(freq: 440.0, interpolation: .cubic) // Catmull-Rom cubic _ = OscSin.Audio(freq: 440.0) // constant freq, linear interp
OscSin.Audio(freq: 440.0, table: engine.sharedTables.sineTable) // share engine's pre-computed table _ = OscSin.Audio(freq: lfo, phase: 0.25) // generator input, quarter-phase offset
_ = OscSin.Audio(freq: 440.0, interpolation: .cubic) // Catmull-Rom cubic
_ = OscSin.Audio(freq: 440.0, table: engine.sharedTables.sineTable) // share engine's pre-computed table
``` ```
- `freq` — any ``ValidGeneratorInput``. Scalar inputs call `floatValue` once per block. Generator inputs are read at audio rate, enabling true FM synthesis. - `freq` — any ``ValidGeneratorInput``. Scalar inputs call `floatValue` once per block. Generator inputs are read at audio rate, enabling true FM synthesis.
@@ -97,9 +99,10 @@ enum namespace. All support `mul`/`add` and a `phase` offset.
Linear ascending ramp reset to −1 at each period. PolyBLEP step correction at the reset point. Linear ascending ramp reset to −1 at each period. PolyBLEP step correction at the reset point.
```swift ```swift
OscSawtooth.Audio(freq: 440.0) let lfo: OscSin.Audio = OscSin.Audio(freq: 5.0)
OscSawtooth.Audio(freq: lfo * 200 + 440, phase: 0.5) // phase offset, audio-rate FM _ = OscSawtooth.Audio(freq: 440.0)
OscSawtooth.Control(freq: 2.0) // LFO use at control rate _ = OscSawtooth.Audio(freq: lfo * 200 + 440, phase: 0.5) // phase offset, audio-rate FM
_ = OscSawtooth.Control(freq: 2.0) // LFO use at control rate
``` ```
- `freq` — any ``ValidGeneratorInput``. Generator inputs enable audio-rate FM. - `freq` — any ``ValidGeneratorInput``. Generator inputs enable audio-rate FM.
@@ -134,10 +137,11 @@ Variable duty-cycle pulse wave. PolyBLEP correction applied at both the rising e
when `dutyCycle` is a `Generator`. when `dutyCycle` is a `Generator`.
```swift ```swift
OscDutyCycle.Audio(freq: 440.0) // 0.5 = square let lfo: OscSin.Audio = OscSin.Audio(freq: 5.0)
OscDutyCycle.Audio(freq: 440.0, dutyCycle: 0.25) // 25% duty cycle _ = OscDutyCycle.Audio(freq: 440.0) // 0.5 = square
OscDutyCycle.Audio(freq: 440.0, dutyCycle: lfo * 0.4 + 0.5) // audio-rate PWM _ = OscDutyCycle.Audio(freq: 440.0, dutyCycle: 0.25) // 25% duty cycle
OscDutyCycle.Control(freq: 1.0, dutyCycle: 0.3) _ = OscDutyCycle.Audio(freq: 440.0, dutyCycle: lfo * 0.4 + 0.5) // audio-rate PWM
_ = OscDutyCycle.Control(freq: 1.0, dutyCycle: 0.3)
``` ```
- `dutyCycle` — normalized `[0, 1]`. Clamped internally. `0.5` = square wave. Defaults to `0.5`. - `dutyCycle` — normalized `[0, 1]`. Clamped internally. `0.5` = square wave. Defaults to `0.5`.
@@ -163,9 +167,10 @@ enum namespace.
Linear ascending ramp. Formula: `2 × phase − 1`. Range `[−1, 1]`. Linear ascending ramp. Formula: `2 × phase − 1`. Range `[−1, 1]`.
```swift ```swift
LFSawtooth.Audio(freq: 0.5) // slow ascending ramp, 0.5 Hz let lfo: OscSin.Audio = OscSin.Audio(freq: 0.5)
LFSawtooth.Audio(freq: lfo, phase: 0.5) // phase offset _ = LFSawtooth.Audio(freq: 0.5) // slow ascending ramp, 0.5 Hz
LFSawtooth.Control(freq: 2.0) // one new ramp value per audio block _ = LFSawtooth.Audio(freq: lfo, phase: 0.5) // phase offset
_ = LFSawtooth.Control(freq: 2.0) // one new ramp value per audio block
``` ```
### LFSquare ### LFSquare
@@ -194,9 +199,10 @@ Variable duty-cycle pulse with no BLEP correction. Same formula as ``OscDutyCycl
unfiltered. Supports audio-rate PWM via a Generator `dutyCycle` input. unfiltered. Supports audio-rate PWM via a Generator `dutyCycle` input.
```swift ```swift
LFDutyCycle.Audio(freq: 1.0, dutyCycle: 0.3) // 30% duty, 1 Hz let envGen: OscSin.Audio = OscSin.Audio(freq: 0.5, mul: 0.3, add: 0.5)
LFDutyCycle.Audio(freq: 2.0, dutyCycle: envGen) // envelope-driven PWM _ = LFDutyCycle.Audio(freq: 1.0, dutyCycle: 0.3) // 30% duty, 1 Hz
LFDutyCycle.Control(freq: 0.5, dutyCycle: 0.75) _ = LFDutyCycle.Audio(freq: 2.0, dutyCycle: envGen) // envelope-driven PWM
_ = LFDutyCycle.Control(freq: 0.5, dutyCycle: 0.75)
``` ```
- `dutyCycle` — normalized `[0, 1]`. Clamped internally. Defaults to `0.5`. - `dutyCycle` — normalized `[0, 1]`. Clamped internally. Defaults to `0.5`.
@@ -56,6 +56,9 @@ behave the same as in `TuneablePitchShift.Audio`.
### Quick start ### Quick start
```swift ```swift
let hardwareInputBus: Int = 4
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
let mic = In.Audio(bus: hardwareInputBus) let mic = In.Audio(bus: hardwareInputBus)
let shifted = PitchShift.Audio(input: mic, pitchRatio: 0.75, windowSize: 0.05) let shifted = PitchShift.Audio(input: mic, pitchRatio: 0.75, windowSize: 0.05)
output(bus: 0, source: shifted) output(bus: 0, source: shifted)
@@ -63,6 +66,7 @@ output(bus: 0, source: shifted)
// Modulated ratio from another generator // Modulated ratio from another generator
let lfo = OscSin.Control(freq: 0.5) * 0.1 + 1.0 // ±10% vibrato let lfo = OscSin.Control(freq: 0.5) * 0.1 + 1.0 // ±10% vibrato
let shifted2 = PitchShift.Audio(input: sig, pitchRatio: lfo) let shifted2 = PitchShift.Audio(input: sig, pitchRatio: lfo)
output(bus: 1, source: shifted2)
``` ```
### Parameters ### Parameters
@@ -136,6 +140,10 @@ hop timing is fixed by `windowSize / overlap`, new grains trigger at the origina
### Quick start ### Quick start
```swift ```swift
let leftSig: OscSin.Audio = OscSin.Audio(freq: 220.0)
let rightSig: OscSin.Audio = OscSin.Audio(freq: 221.0)
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
// Mono pitch shift, one octave up // Mono pitch shift, one octave up
let shifted = TuneablePitchShift.Audio(input: OscSin.Audio(freq: 220.0), pitchRatio: 2.0) let shifted = TuneablePitchShift.Audio(input: OscSin.Audio(freq: 220.0), pitchRatio: 2.0)
output(bus: 0, source: shifted) output(bus: 0, source: shifted)
@@ -155,6 +163,7 @@ let shimmer = TuneablePitchShift.Audio(
pitchDispersion: 0.05, // ±5% random per grain pitchDispersion: 0.05, // ±5% random per grain
timeDispersion: 0.005 // ±5 ms jitter timeDispersion: 0.005 // ±5 ms jitter
) )
output(bus: 0, source: shimmer)
``` ```
### Parameters ### Parameters
@@ -332,11 +341,13 @@ inharmonicity is the defining sonic character of the effect, and is intentional.
### Quick start ### Quick start
```swift ```swift
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
// Shift all frequencies up by 50 Hz // Shift all frequencies up by 50 Hz
let shifter = FrequencyShifter.Audio( let shifter = FrequencyShifter.Audio(
input: OscSin.Audio(freq: 440.0), input: OscSin.Audio(freq: 440.0),
shiftHz: 50.0, shiftHz: 50.0,
sampleRate: graph.engine.sampleRate sampleRate: 44100.0
) )
output(bus: 0, source: shifter.upper) // 490 Hz output(bus: 0, source: shifter.upper) // 490 Hz
output(bus: 1, source: shifter.lower) // 390 Hz output(bus: 1, source: shifter.lower) // 390 Hz
@@ -344,10 +355,12 @@ output(bus: 1, source: shifter.lower) // 390 Hz
// Audio-rate shiftHz modulation (Bode-style vibrato) // Audio-rate shiftHz modulation (Bode-style vibrato)
let lfo = OscSin.Audio(freq: 2.0) * 20.0 // ±20 Hz let lfo = OscSin.Audio(freq: 2.0) * 20.0 // ±20 Hz
let bode = FrequencyShifter.Audio(input: sig, shiftHz: lfo) let bode = FrequencyShifter.Audio(input: sig, shiftHz: lfo)
output(bus: 0, source: bode.upper)
// Thickening: mix shifted and dry signals // Thickening: mix shifted and dry signals
let shifted = FrequencyShifter.Audio(input: sig, shiftHz: 15.0) let shifted = FrequencyShifter.Audio(input: sig, shiftHz: 15.0)
let thickened = sig + shifted.upper * 0.5 let thickened = sig + shifted.upper * 0.5
output(bus: 1, source: thickened)
``` ```
### Parameters ### Parameters
@@ -101,6 +101,9 @@ edge, then holds that value until the next trigger. The held value is delivered
control-rate ramp to downstream audio-rate generators. control-rate ramp to downstream audio-rate generators.
```swift ```swift
let signal: WhiteNoise.Audio = WhiteNoise.Audio()
let trig: Impulse.Control = Impulse.Control(freq: 1.0)
// Change filter cutoff on each kick drum trigger // Change filter cutoff on each kick drum trigger
let kick = Impulse.Control(freq: 2.0) let kick = Impulse.Control(freq: 2.0)
let cutoff = TriggeredRandom.Control(trigger: kick, lo: 200.0, hi: 4000.0) let cutoff = TriggeredRandom.Control(trigger: kick, lo: 200.0, hi: 4000.0)
@@ -108,6 +111,7 @@ let filt = RBJLowPass.Audio(input: signal, freq: cutoff, q: 0.707)
// Deterministic output for testing — supply a fixed seed // Deterministic output for testing — supply a fixed seed
let det = TriggeredRandom.Control(trigger: trig, lo: 0.0, hi: 1.0, seed: 42) let det = TriggeredRandom.Control(trigger: trig, lo: 0.0, hi: 1.0, seed: 42)
_ = (filt, det)
``` ```
**Parameters:** **Parameters:**
@@ -188,8 +188,8 @@ let verb = SpringReverb.Audio(
let stereoVerb = SpringReverb.Audio( let stereoVerb = SpringReverb.Audio(
input: sig, input: sig,
decay: 2.5, decay: 2.5,
stereo: true, sampleRate: 44100,
sampleRate: 44100 stereo: true
) )
output(bus: 0, source: stereoVerb[0]) output(bus: 0, source: stereoVerb[0])
output(bus: 1, source: stereoVerb[1]) output(bus: 1, source: stereoVerb[1])
@@ -22,8 +22,16 @@ which is currently selected — matching SuperCollider's `Select`. `which` may b
for per-sample source switching. for per-sample source switching.
```swift ```swift
Select.Audio(which: index, inputs: [oscA, oscB, noise]) // pick one of three sources let index: OscSin.Control = OscSin.Control(freq: 1.0)
Select.Control(which: 1.0, inputs: [a, b, c]) // block-rate selection let oscA: OscSin.Audio = OscSin.Audio(freq: 220.0)
let oscB: OscSin.Audio = OscSin.Audio(freq: 440.0)
let noise: WhiteNoise.Audio = WhiteNoise.Audio()
let a: OscSin.Control = OscSin.Control(freq: 1.0)
let b: OscSin.Control = OscSin.Control(freq: 2.0)
let c: OscSin.Control = OscSin.Control(freq: 3.0)
_ = Select.Audio(which: index, inputs: [oscA, oscB, noise]) // pick one of three sources
_ = Select.Control(which: 1.0, inputs: [a, b, c]) // block-rate selection
``` ```
- `which` — any ``ValidGeneratorInput``; truncated + clamped to a valid index. - `which` — any ``ValidGeneratorInput``; truncated + clamped to a valid index.
@@ -37,8 +45,14 @@ Select.Control(which: 1.0, inputs: [a, b, c]) // block-rate selectio
overall output gain (SuperCollider's `level`). overall output gain (SuperCollider's `level`).
```swift ```swift
CrossFade.Audio(inA: dry, inB: wet, pan: mix) // equal-power morph let dry: OscSin.Audio = OscSin.Audio(freq: 220.0)
LinearCrossFade.Audio(inA: a, inB: b, pan: 0.0) // linear 50/50 let wet: OscSin.Audio = OscSin.Audio(freq: 440.0)
let mix: OscSin.Control = OscSin.Control(freq: 0.2)
let a: OscSin.Audio = OscSin.Audio(freq: 330.0)
let b: OscSin.Audio = OscSin.Audio(freq: 550.0)
_ = CrossFade.Audio(inA: dry, inB: wet, pan: mix) // equal-power morph
_ = LinearCrossFade.Audio(inA: a, inB: b, pan: 0.0) // linear 50/50
``` ```
- `pan` — any ``ValidGeneratorInput`` in `[-1, 1]`. Defaults to `0.0`. - `pan` — any ``ValidGeneratorInput`` in `[-1, 1]`. Defaults to `0.0`.
@@ -31,7 +31,7 @@ input → analyzer → threshold / latch → consumer
```swift ```swift
let mic = In.Audio(bus: 0) let mic = In.Audio(bus: 0)
let amp = AmplitudeFollower.Audio(input: mic, attackTime: 0.005, releaseTime: 0.05) let amp = AmplitudeFollower.Audio(in: mic, attackTime: 0.005, releaseTime: 0.05)
let edge = SignalChanged.Audio(input: amp, threshold: 0.05) let edge = SignalChanged.Audio(input: amp, threshold: 0.05)
addOutputGenerator(SendTrigger.Audio(trig: edge, id: 1)) addOutputGenerator(SendTrigger.Audio(trig: edge, id: 1))
@@ -55,7 +55,7 @@ output(bus: 0, source: osc)
```swift ```swift
let lfo = OscSin.Audio(freq: 0.5) let lfo = OscSin.Audio(freq: 0.5)
let gate = Impulse.Audio(freq: 1.0) > 0.0 // 1-sample-wide hi pulse per beat let gate = Impulse.Audio(freq: 1.0) // 1-sample-wide hi pulse per beat (already a trigger)
let held = Gate.Audio(input: lfo, trig: gate) let held = Gate.Audio(input: lfo, trig: gate)
``` ```
@@ -50,6 +50,9 @@ closure returns (copied via the pre-allocated single-element pointers).
### Example — 6 dB magnitude attenuation ### Example — 6 dB magnitude attenuation
```swift ```swift
let sr: Double = 44100.0
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
let halver = SpectralPolarClosure(fftSize: 2048, hopSize: 512, sampleRate: sr) { ctx in let halver = SpectralPolarClosure(fftSize: 2048, hopSize: 512, sampleRate: sr) { ctx in
for i in 0..<ctx.binCount { for i in 0..<ctx.binCount {
ctx.magnitudes[i] *= 0.5 ctx.magnitudes[i] *= 0.5
@@ -64,6 +67,7 @@ output(bus: 0, source: chain)
### Example — spectral brightness tilt using frame index ### Example — spectral brightness tilt using frame index
```swift ```swift
let sr: Double = 44100.0
let tilt = SpectralPolarClosure(fftSize: 2048, hopSize: 512, sampleRate: sr) { ctx in let tilt = SpectralPolarClosure(fftSize: 2048, hopSize: 512, sampleRate: sr) { ctx in
let factor = Float(ctx.frameIndex % 64) / 64.0 // slowly modulate let factor = Float(ctx.frameIndex % 64) / 64.0 // slowly modulate
for i in 0..<ctx.binCount { for i in 0..<ctx.binCount {
@@ -72,6 +76,7 @@ let tilt = SpectralPolarClosure(fftSize: 2048, hopSize: 512, sampleRate: sr) { c
ctx.magnitudes[i] *= binWeight ctx.magnitudes[i] *= binWeight
} }
} }
_ = tilt
``` ```
--- ---
@@ -78,14 +78,16 @@ low-frequency tones have centroid values close to their fundamental.
### Quick start ### Quick start
```swift ```swift
let sig: WhiteNoise.Audio = WhiteNoise.Audio()
let analysis = SpectralChain.Audio(input: sig, fftSize: 2048, hopSize: 512) let analysis = SpectralChain.Audio(input: sig, fftSize: 2048, hopSize: 512)
let centroid = SpectralCentroid.Control(analysis: analysis, let centroid = SpectralCentroid.Control(analysis: analysis,
sampleRate: 44100.0) sampleRate: 44100.0)
// Route centroid to filter cutoff (clamp to sensible range with LinLin) // Route centroid to filter cutoff (clamp to sensible range with LinLin)
let cutoff = LinLin.Control(input: centroid, inLow: 0, inHigh: 8000, let cutoff = LinLin.Control(centroid, inLo: 0, inHi: 8000,
outLow: 200, outHigh: 6000) outLo: 200, outHi: 6000)
let filter = RBJLowPass.Audio(input: sig, freq: cutoff, q: 0.707) let filter = RBJLowPass.Audio(input: sig, freq: cutoff, q: 0.707)
_ = filter
``` ```
### Parameters ### Parameters
@@ -122,6 +124,8 @@ No epsilon floor or zero-skipping is needed — IEEE 754 arithmetic handles it n
### Quick start ### Quick start
```swift ```swift
let sig: WhiteNoise.Audio = WhiteNoise.Audio()
let analysis = SpectralChain.Audio(input: sig, fftSize: 2048, hopSize: 512)
let flatness = SpectralFlatness.Control(analysis: analysis) let flatness = SpectralFlatness.Control(analysis: analysis)
// Gate processing: apply heavy compression when signal is noisy (high flatness), // Gate processing: apply heavy compression when signal is noisy (high flatness),
@@ -163,12 +167,15 @@ scan), so it does not need a separate ``SpectralCentroid/Control`` instance.
### Quick start ### Quick start
```swift ```swift
let sig: WhiteNoise.Audio = WhiteNoise.Audio()
let analysis = SpectralChain.Audio(input: sig, fftSize: 2048, hopSize: 512)
let spread = SpectralSpread.Control(analysis: analysis, let spread = SpectralSpread.Control(analysis: analysis,
sampleRate: 44100.0) sampleRate: 44100.0)
// Use spread to modulate filter bandwidth: wider spectrum → wider band. // Use spread to modulate filter bandwidth: wider spectrum → wider band.
let q = LinLin.Control(input: spread, inLow: 0, inHigh: 4000, outLow: 8.0, outHigh: 0.5) let q = LinLin.Control(spread, inLo: 0, inHi: 4000, outLo: 8.0, outHi: 0.5)
let bandpass = RBJBandPass.Audio(input: sig, freq: 1000.0, q: q) let bandpass = RBJBandPass.Audio(input: sig, freq: 1000.0, q: q)
_ = bandpass
``` ```
### Parameters ### Parameters
@@ -248,6 +255,8 @@ frequency location, making it complementary to centroid and spread.
### Quick start ### Quick start
```swift ```swift
let sig: WhiteNoise.Audio = WhiteNoise.Audio()
let analysis = SpectralChain.Audio(input: sig, fftSize: 2048, hopSize: 512)
let entropy = SpectralEntropy.Control(analysis: analysis) let entropy = SpectralEntropy.Control(analysis: analysis)
// Use entropy to crossfade between "noise" and "tone" processing paths. // Use entropy to crossfade between "noise" and "tone" processing paths.
@@ -285,6 +294,9 @@ are more sensitive to where energy first concentrates.
### Quick start ### Quick start
```swift ```swift
let sig: WhiteNoise.Audio = WhiteNoise.Audio()
let analysis = SpectralChain.Audio(input: sig, fftSize: 2048, hopSize: 512)
// Default — frequency below which 85% of energy falls // Default — frequency below which 85% of energy falls
let rolloff = SpectralRolloff.Control(analysis: analysis, let rolloff = SpectralRolloff.Control(analysis: analysis,
sampleRate: 44100.0) sampleRate: 44100.0)
@@ -12,8 +12,8 @@ Each generator provides an `.Audio` (sample-accurate) and a `.Control` (block-ra
variant. The Control variants run the same state machine across the block but emit a flat variant. The Control variants run the same state machine across the block but emit a flat
block-final value — trigger and counter outputs are discrete and are never smoothed/ramped. block-final value — trigger and counter outputs are discrete and are never smoothed/ramped.
For sending a trigger from the audio graph back to the language side, see ``SendTrigger`` For sending a trigger from the audio graph back to the language side, see ``SendTrigger``.
(<doc:SendTrigger>). For latching and gating an arbitrary signal on a trigger, see For latching and gating an arbitrary signal on a trigger, see
``Gate`` / ``SampleAndHold`` in <doc:SignalAnalysis>. ``Gate`` / ``SampleAndHold`` in <doc:SignalAnalysis>.
--- ---
@@ -25,8 +25,9 @@ For sending a trigger from the audio graph back to the language side, see ``Send
A new edge during the hold restarts the timer. A new edge during the hold restarts the timer.
```swift ```swift
Trig.Audio(input: impulse, dur: 0.1) // hold the trigger level for 100 ms let impulse: Impulse.Audio = Impulse.Audio(freq: 2.0)
Trig1.Audio(input: impulse, dur: 0.05) // 50 ms unity gate on each edge _ = Trig.Audio(input: impulse, dur: 0.1) // hold the trigger level for 100 ms
_ = Trig1.Audio(input: impulse, dur: 0.05) // 50 ms unity gate on each edge
``` ```
- `dur` — hold time in seconds (init-time scalar). Defaults to `0.1`. - `dur` — hold time in seconds (init-time scalar). Defaults to `0.1`.
@@ -37,8 +38,12 @@ Trig1.Audio(input: impulse, dur: 0.05) // 50 ms unity gate on each edge
``PulseCount`` accumulates a running count of rising edges with an optional reset. ``PulseCount`` accumulates a running count of rising edges with an optional reset.
```swift ```swift
TriggeredDelay.Audio(input: impulse, dur: 0.25) // echo the trigger 250 ms later let impulse: Impulse.Audio = Impulse.Audio(freq: 2.0)
PulseCount.Audio(trig: clock, reset: bar) // count clocks, reset each bar let clock: Impulse.Audio = Impulse.Audio(freq: 4.0)
let bar: Impulse.Audio = Impulse.Audio(freq: 1.0)
_ = TriggeredDelay.Audio(input: impulse, dur: 0.25) // echo the trigger 250 ms later
_ = PulseCount.Audio(trig: clock, reset: bar) // count clocks, reset each bar
``` ```
- `dur` — delay in seconds (init-time scalar). Defaults to `0.1`. - `dur` — delay in seconds (init-time scalar). Defaults to `0.1`.
@@ -50,7 +55,8 @@ PulseCount.Audio(trig: clock, reset: bar) // count clocks, reset each ba
`[min, max]`, with an optional reset to `resetval`. Ideal as a step-sequencer index. `[min, max]`, with an optional reset to `resetval`. Ideal as a step-sequencer index.
```swift ```swift
Stepper.Audio(trig: clock, reset: 0.0, min: 0, max: 7, step: 1) // 0,1,…,7,0,… let clock: Impulse.Audio = Impulse.Audio(freq: 4.0)
_ = Stepper.Audio(trig: clock, reset: 0.0, min: 0, max: 7, step: 1) // 0,1,…,7,0,…
``` ```
- `min` / `max` / `step` / `resetval` — init-time `Int` scalars. `max >= min` required. - `min` / `max` / `step` / `resetval` — init-time `Int` scalars. `max >= min` required.
@@ -61,7 +67,8 @@ Stepper.Audio(trig: clock, reset: 0.0, min: 0, max: 7, step: 1) // 0,1,…,7,0
above `hi`, back to `0` when it falls below `lo`, and holds in between. above `hi`, back to `0` when it falls below `lo`, and holds in between.
```swift ```swift
Schmidt.Audio(input: sig, lo: -0.2, hi: 0.2) // hysteresis band [-0.2, 0.2] let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
_ = Schmidt.Audio(input: sig, lo: -0.2, hi: 0.2) // hysteresis band [-0.2, 0.2]
``` ```
- `lo` / `hi` — any ``ValidGeneratorInput``; switch-off and switch-on thresholds. - `lo` / `hi` — any ``ValidGeneratorInput``; switch-off and switch-on thresholds.
@@ -22,9 +22,11 @@ harmonic waveshaping or ``LyrebirdBuffer/fillWaveshaper(_:)`` for preset distort
The table is held via an RT-safe slot and can be swapped live with `setTable(_:engine:)`. The table is held via an RT-safe slot and can be swapped live with `setTable(_:engine:)`.
```swift ```swift
let curve = LyrebirdBuffer(count: 1024) let osc: OscSin.Audio = OscSin.Audio(freq: 440.0)
let curve: LyrebirdBuffer = LyrebirdBuffer(count: 1024)
curve.fillChebyshev(coefficients: [0, 1, 0, 0.3]) // add a 3rd harmonic curve.fillChebyshev(coefficients: [0, 1, 0, 0.3]) // add a 3rd harmonic
let shaped = Waveshaper.Audio(table: curve, input: osc) let shaped: Waveshaper.Audio = Waveshaper.Audio(table: curve, input: osc)
_ = shaped
``` ```
- `table` — mono ``LyrebirdBuffer`` transfer curve (≥ 2 frames). - `table` — mono ``LyrebirdBuffer`` transfer curve (≥ 2 frames).
@@ -38,8 +40,9 @@ C1-continuous quadratic knee of width `amp · smooth`. Models transistor crossov
useful for grit and gating-style distortion. useful for grit and gating-style distortion.
```swift ```swift
CrossoverDistortion.Audio(input: sig, amp: 0.1, smooth: 0.0) // hard dead zone let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
CrossoverDistortion.Audio(input: sig, amp: 0.1, smooth: 0.5) // softened knee _ = CrossoverDistortion.Audio(input: sig, amp: 0.1, smooth: 0.0) // hard dead zone
_ = CrossoverDistortion.Audio(input: sig, amp: 0.1, smooth: 0.5) // softened knee
``` ```
- `amp` — dead-zone half-width (≥ 0, SuperCollider's crossover threshold). Defaults to `0.5`. - `amp` — dead-zone half-width (≥ 0, SuperCollider's crossover threshold). Defaults to `0.5`.
@@ -53,8 +56,9 @@ Produces glitch / dropout / bit-erosion textures. Audio-only — the stochastic
per sample and has no block-rate form. per sample and has no block-rate form.
```swift ```swift
Disintegrator.Audio(input: sig, probability: 0.3, multiplier: 0.0) // drop ~30% to silence let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
Disintegrator.Audio(input: sig, probability: 0.5, seed: 42) // deterministic _ = Disintegrator.Audio(input: sig, probability: 0.3, multiplier: 0.0) // drop ~30% to silence
_ = Disintegrator.Audio(input: sig, probability: 0.5, seed: 42) // deterministic
``` ```
- `probability` — `[0, 1]` chance a sample is disintegrated. Defaults to `0.5`. - `probability` — `[0, 1]` chance a sample is disintegrated. Defaults to `0.5`.
@@ -53,7 +53,25 @@ final class MySynth: SynthesizerBase {
override func build() { override func build() {
let osc = OscSin.Audio(freq: 440.0) * 0.3 let osc = OscSin.Audio(freq: 440.0) * 0.3
output(bus: 0, source: Pan2(input: osc, pan: 0)) output(bus: 0, source: Pan2(input: osc, pan: 0))
doneAction = .freeEnclosing }
}
```
This plays until you remove it. To have a synth free itself when its envelope
finishes, give the envelope a `doneAction` — see <doc:NodeTree>:
```swift
import LyrebirdSynth
final class MyPluckedNote: SynthesizerBase {
override func build() {
let env = EnvelopeGen.Audio(
envelope: Envelope(levels: [0, 1, 0], durations: [0.01, 0.6],
curves: [.sine, .exponential]),
doneAction: .freeNode // engine removes this synth when the envelope ends
)
let osc = OscSin.Audio(freq: 440.0) * env * 0.3
output(bus: 0, source: Pan2(input: osc, pan: 0))
} }
} }
``` ```
@@ -61,6 +79,16 @@ final class MySynth: SynthesizerBase {
Then in the demo's `main.swift` (or app entry point): Then in the demo's `main.swift` (or app entry point):
```swift ```swift
import LyrebirdSynth
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
numInputChannels: 0,
driver: CoreAudioDriver()
)
try engine.start()
try engine.add(MySynth()) try engine.add(MySynth())
``` ```
@@ -101,14 +129,16 @@ Every scaffolded project ships an `<Name>.xcworkspace` that references the gener
**Available templates:** **Available templates:**
Four lightweight Swift-Package-only templates (open with `Package.swift` in Xcode): Six lightweight Swift-Package-only templates (open with `Package.swift` in Xcode):
| Template | Command | Starting point | | Template | Command | Starting point |
|---|---|---| |---|---|---|
| `basic` (default) | `lyrebird new MyPiece` | Minimal engine + `RunLoop.main.run()` | | `quickstart` | `lyrebird new MyFirstSound --template quickstart` | **Fastest sound** — a one-oscillator `SineTone` that plays 440 Hz for 10 s and exits |
| `basic` (default) | `lyrebird new MyPiece` | Minimal engine + `RunLoop.main.run()` (no synth wired yet) |
| `demo` | `lyrebird new MyPiece --template demo` | `SineTone` with `@LiveParam` freq and amp | | `demo` | `lyrebird new MyPiece --template demo` | `SineTone` with `@LiveParam` freq and amp |
| `ui-demo` | `lyrebird new MyApp --template ui-demo` | AppKit window, `@UIParam` controls, `LyrebirdWindow` | | `ui-demo` | `lyrebird new MyApp --template ui-demo` | AppKit window, `@UIParam` controls, `LyrebirdWindow` |
| `nrt` | `lyrebird new MyRender --template nrt` | `NRTDriver` renders to `output.caf` then exits | | `nrt` | `lyrebird new MyRender --template nrt` | `NRTDriver` renders to `output.caf` then exits |
| `score` | `lyrebird new MyScore --template score` | Builds a `Score` with the notation DSL, exports MusicXML, renders offline |
Three full `.xcodeproj`-bearing templates for `.app` / `.appex` deliverables that SwiftPM can't express: Three full `.xcodeproj`-bearing templates for `.app` / `.appex` deliverables that SwiftPM can't express:
@@ -271,6 +301,28 @@ Xcode compiles the `.docc` catalog and opens it in the Documentation window. Sym
--- ---
## Threading — read this before you write a Routine or Task
Lyrebird runs your code on three kinds of thread, and the boundaries are not interchangeable:
- **Main thread** — where you construct synthesizers and call `engine.add` / `schedule`.
`SynthesizerBase` is `@MainActor`.
- **The RT audio thread** — runs the render callback. Never allocates, locks, or blocks.
You do not call into it; it calls your generators.
- **Routine / Task threads** — one background thread per `LyrebirdRoutine` / `LyrebirdTask`
body, for timed sequencing.
That last boundary is the one that surprises people: a task body is `@Sendable` and runs
off-main, so it **cannot construct a synthesizer directly**. Use `ctx.onMain { MySynth(...) }`
to build one inside the body, and `ctx.set` (with a `$param` node captured on main) to change
parameters — that one is a lock-free atomic write with no hop at all.
- <doc:RoutineTask> — the practical rules, with examples
- `ARCHITECTURE.md` §1 (thread model) and §9.2 (isolation from a routine or task) — the full
model and the reasoning behind it
---
## Next Steps ## Next Steps
- <doc:EngineSetup> — engine parameters, lifecycle, driver options, threading rules - <doc:EngineSetup> — engine parameters, lifecycle, driver options, threading rules
+2 -4
View File
@@ -65,7 +65,7 @@ try engine.add(MySynth()) // MySynth — your SynthesizerBase subclass
### Spectral ### Spectral
- <doc:SpectralChain> - ``SpectralChain``
### Signal Analysis ### Signal Analysis
@@ -120,7 +120,6 @@ try engine.add(MySynth()) // MySynth — your SynthesizerBase subclass
### Step Sequencer ### Step Sequencer
- <doc:StepSequencer>
- ``StepSequencer`` - ``StepSequencer``
- ``SequencerStep`` - ``SequencerStep``
@@ -135,7 +134,7 @@ try engine.add(MySynth()) // MySynth — your SynthesizerBase subclass
### Advanced ### Advanced
- <doc:MultiCore> - <doc:MultiCore>
- <doc:SendTrigger> - ``SendTrigger``
- <doc:AUv3> - <doc:AUv3>
### External Integrations ### External Integrations
@@ -160,7 +159,6 @@ try engine.add(MySynth()) // MySynth — your SynthesizerBase subclass
### Parameter Sources for Non-RT Loops ### Parameter Sources for Non-RT Loops
- <doc:ValueComputable>
- ``ValueComputable`` - ``ValueComputable``
- ``ValueComputableClosure`` - ``ValueComputableClosure``
- ``ValueComputableBody`` - ``ValueComputableBody``
+5 -1
View File
@@ -143,7 +143,11 @@ Key points:
- `after: startSec` is equivalent to `at: engine.seconds(startSec)` when called before `start()` — `currentTime` is `0` so both resolve to the same absolute sample offset. - `after: startSec` is equivalent to `at: engine.seconds(startSec)` when called before `start()` — `currentTime` is `0` so both resolve to the same absolute sample offset.
- The envelope ends at level 0 and `doneAction` defaults to `.nothing` — synths stay in the graph but output silence. In NRT the render terminates at `totalDur` so no removal is needed. In RT, poll `env.needsFree` after each block and call `engine.remove()` when `true`. - The envelope ends at level 0 and `doneAction` defaults to `.nothing` — synths stay in the graph but output silence. In NRT the render terminates at `totalDur` so no removal is needed. In RT, poll `env.needsFree` after each block and call `engine.remove()` when `true`.
- Set `NRTDriver(duration:)` to cover the latest possible start plus the full event length. Events whose scheduled start time falls beyond `duration` are never triggered. - Set `NRTDriver(duration:)` to cover the latest possible start plus the full event length. Events whose scheduled start time falls beyond `duration` are never triggered.
- ``SynthesisEngine`` defaults to a pending event queue capacity of 1024. For large scores pass `eventQueueCapacity:` (must be a power of two) to ``SynthesisEngine/init(blockSize:controlBlockSize:sampleRate:numOutputChannels:numInputChannels:numAudioBuses:numControlBuses:eventQueueCapacity:driver:)`` — a non-power-of-two value traps at startup. - **Large scores need two knobs raised, not one.** ``SynthesisEngine`` defaults to a pending event queue capacity of 1024 and a per-block event budget of 256. Pass both to ``SynthesisEngine/init(blockSize:controlBlockSize:sampleRate:numOutputChannels:numInputChannels:numAudioBuses:numControlBuses:eventQueueCapacity:maxEventsPerBlock:driver:)``:
- `eventQueueCapacity:` must hold every event you enqueue before `start()`, since NRT renders synchronously and nothing can refill the queue mid-render. Must be a power of two — a non-power-of-two value traps at startup.
- `maxEventsPerBlock:` bounds the future-event **look-ahead** carried across block boundaries. This is the one that silently bites: pre-schedule 5,000 events and the first block keeps only `maxEventsPerBlock` of them in carry-over and **drops the rest**. Check ``SynthesisEngine/perBlockEventDropCount`` (a console warning is also printed after the render).
Either raise both, or feed events just-in-time from a ``TriggerListener`` — `NRTDriver` drains its handlers after every block, so a handler can schedule the next few events as the render advances, keeping the in-flight count small. See <doc:Scheduling>.
### Soundfile input ### Soundfile input
+57 -21
View File
@@ -32,12 +32,12 @@ and `controlOutput(bus:source:)`.
```swift ```swift
// Example — your synthesizer, defined by subclassing SynthesizerBase // Example — your synthesizer, defined by subclassing SynthesizerBase
final class SineTone: SynthesizerBase { final class MySynth: SynthesizerBase {
@LiveParam var freq: Double = 440.0 @LiveParam var freq: Double = 440.0
@LiveParam var amp: Double = 0.5 @LiveParam var amp: Double = 0.5
override func build() { override func build() {
let osc = OscSin.Audio(freq: $freq, phase: 0.0, amp: 1.0) let osc: OscSin.Audio = OscSin.Audio(freq: $freq, phase: 0.0)
output(bus: 0, source: osc * $amp) output(bus: 0, source: osc * $amp)
} }
} }
@@ -51,7 +51,7 @@ happens here; the RT audio thread only calls `evaluate(graph:count:)`.
### Immediately (at current sample time) ### Immediately (at current sample time)
```swift ```swift
let tone = SineTone() let tone: MySynth = MySynth()
try engine.add(tone) try engine.add(tone)
``` ```
@@ -62,7 +62,7 @@ via an atomic load — safe from the main thread.
```swift ```swift
// Start tone2 at exactly sample 44100 (1 second at 44.1 kHz) // Start tone2 at exactly sample 44100 (1 second at 44.1 kHz)
let tone2 = SineTone() let tone2: MySynth = MySynth()
try engine.schedule(tone2, at: 44100) try engine.schedule(tone2, at: 44100)
``` ```
@@ -72,7 +72,7 @@ via sub-block splitting, giving a sample-accurate onset.
### After a relative duration in seconds ### After a relative duration in seconds
```swift ```swift
let tone3 = SineTone() let tone3: MySynth = MySynth()
try engine.schedule(tone3, after: 2.0) // 2 seconds from now try engine.schedule(tone3, after: 2.0) // 2 seconds from now
``` ```
@@ -91,12 +91,18 @@ no allocation on the RT thread.
### Immediately ### Immediately
```swift ```swift
let tone: MySynth = MySynth()
try engine.add(tone)
engine.remove(tone) engine.remove(tone)
``` ```
### At an absolute sample time ### At an absolute sample time
```swift ```swift
let tone2: MySynth = MySynth()
try engine.schedule(tone2, at: 44100)
engine.remove(tone2, at: 44100 + engine.seconds(2.0)) engine.remove(tone2, at: 44100 + engine.seconds(2.0))
``` ```
@@ -106,9 +112,9 @@ The RT thread never calls `release()` directly.
### Schedule paired add and remove ### Schedule paired add and remove
```swift ```swift
let note = SineTone() let note: MySynth = MySynth()
let startTime = engine.currentTime + engine.seconds(0.5) let startTime: SampleTime = engine.currentTime + engine.seconds(0.5)
let stopTime = startTime + engine.seconds(1.0) let stopTime: SampleTime = startTime + engine.seconds(1.0)
try engine.schedule(note, at: startTime) try engine.schedule(note, at: startTime)
engine.remove(note, at: stopTime) engine.remove(note, at: stopTime)
@@ -121,6 +127,20 @@ Both events enqueue to the same `pendingQueue` and are sorted by target time wit
Update from the main thread at any time after the node is added. Two equivalent routes: Update from the main thread at any time after the node is added. Two equivalent routes:
```swift ```swift
final class ParamSynth: SynthesizerBase {
@LiveParam var freq: Double = 440.0
@LiveParam var amp: Double = 0.5
override func build() {
output(bus: 0, source: OscSin.Audio(freq: $freq) * $amp)
}
}
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 512, sampleRate: 44100, numOutputChannels: 2,
numInputChannels: 0, driver: OfflineDriver())
let tone: ParamSynth = ParamSynth()
try engine.add(tone)
tone.freq = 880.0 // typed direct write tone.freq = 880.0 // typed direct write
try? tone.updateParameter("amp", value: 0.3) // by-name (e.g. from OSC) try? tone.updateParameter("amp", value: 0.3) // by-name (e.g. from OSC)
``` ```
@@ -152,16 +172,16 @@ By default `engine.add(_:)` inserts at the head of `mainGroup` (newest-first). U
`position:` overload to control placement precisely. `position:` overload to control placement precisely.
```swift ```swift
let instruments = Group() let instruments: Group = Group()
try engine.add(instruments) try engine.add(instruments)
let bass = BassSynth() let bass: MySynth = MySynth()
try engine.add(bass, position: .tail(of: instruments)) // append try engine.add(bass, position: .tail(of: instruments)) // append
let lead = LeadSynth() let lead: MySynth = MySynth()
try engine.add(lead, position: .head(of: instruments)) // prepend — runs before bass try engine.add(lead, position: .head(of: instruments)) // prepend — runs before bass
let pad = PadSynth() let pad: MySynth = MySynth()
try engine.add(pad, position: .after(bass)) // insert after bass in its group try engine.add(pad, position: .after(bass)) // insert after bass in its group
``` ```
@@ -180,13 +200,13 @@ Use `engine.mainGroup` as a position anchor for global processing nodes:
```swift ```swift
// Run before all instruments (e.g. input limiter on live input bus) // Run before all instruments (e.g. input limiter on live input bus)
try engine.add(InputLimiter(), position: .before(engine.mainGroup)) try engine.add(MySynth(), position: .before(engine.mainGroup))
// Default instrument add — lands in mainGroup // Default instrument add — lands in mainGroup
try engine.add(MySynth()) try engine.add(MySynth())
// Run after all instruments (e.g. ambisonic decoder, master reverb) // Run after all instruments (e.g. ambisonic decoder, master reverb)
try engine.add(MasterReverb(), position: .after(engine.mainGroup)) try engine.add(MySynth(), position: .after(engine.mainGroup))
``` ```
## Group Lifecycle ## Group Lifecycle
@@ -208,6 +228,10 @@ Releases all direct children, then self-frees when the group empties:
2. Starts a 0.1 s polling timer that watches `group.count` (atomically). When count reaches 0, calls `group.free(engine:)`. 2. Starts a 0.1 s polling timer that watches `group.count` (atomically). When count reaches 0, calls `group.free(engine:)`.
```swift ```swift
let instruments: Group = Group()
try engine.add(instruments)
try engine.add(MySynth(), position: .tail(of: instruments))
instruments.release(engine: engine) instruments.release(engine: engine)
// All gated children begin release phase. // All gated children begin release phase.
// When the last one finishes and is removed, instruments self-frees. // When the last one finishes and is removed, instruments self-frees.
@@ -218,6 +242,10 @@ instruments.release(engine: engine)
Immediately tears down the group and all its children — no envelope release: Immediately tears down the group and all its children — no envelope release:
```swift ```swift
let instruments: Group = Group()
try engine.add(instruments)
try engine.add(MySynth(), position: .tail(of: instruments))
instruments.free(engine: engine) instruments.free(engine: engine)
// On next block: all children enqueued to freeQueue, group removed from tree. // On next block: all children enqueued to freeQueue, group removed from tree.
``` ```
@@ -266,10 +294,10 @@ it sets an atomic flag. Poll the flag from a non-RT context and post the removal
```swift ```swift
// Example — PianoNote is a user-defined SynthesizerBase subclass // Example — PianoNote is a user-defined SynthesizerBase subclass
class PianoNote: SynthesizerBase { final class PianoNote: SynthesizerBase {
let env: EnvelopeGen.Audio let env: EnvelopeGen.Audio
init() { override init() {
env = EnvelopeGen.Audio( env = EnvelopeGen.Audio(
envelope: Envelope(levels: [0, 1, 0], durations: [0.01, 0.3], curves: [0, 0]), envelope: Envelope(levels: [0, 1, 0], durations: [0.01, 0.3], curves: [0, 0]),
doneAction: .freeNode doneAction: .freeNode
@@ -281,7 +309,7 @@ class PianoNote: SynthesizerBase {
} }
} }
let note = PianoNote() let note: PianoNote = PianoNote()
try engine.add(note) try engine.add(note)
// Poll from main thread (e.g. timer or display-link callback): // Poll from main thread (e.g. timer or display-link callback):
@@ -297,15 +325,23 @@ Do not call `engine.remove` from within the RT audio callback.
For instruments that need multiple simultaneous notes, use ``VoicePool`` instead of managing individual synthesizer instances manually. The pool allocates N voices into a ``Group`` at init time and handles note-on/note-off assignment and steal arbitration on the main thread. For instruments that need multiple simultaneous notes, use ``VoicePool`` instead of managing individual synthesizer instances manually. The pool allocates N voices into a ``Group`` at init time and handles note-on/note-off assignment and steal arbitration on the main thread.
```swift ```swift
let group = Group() final class Voice: SynthesizerBase {
@LiveParam var freq: Double = 440.0
@LiveParam var gate: Double = 0.0
override func build() {
output(bus: 0, source: OscSin.Audio(freq: $freq) * $gate * 0.2)
}
}
let group: Group = Group()
try engine.add(group) try engine.add(group)
let pool = try VoicePool( let pool: VoicePool = try VoicePool(
voiceCount: 8, group: group, engine: engine, voiceCount: 8, group: group, engine: engine,
stealStrategy: .oldest stealStrategy: .oldest
) { MySynth() } ) { Voice() }
let voice = pool.noteOn(note: 60) // allocate or steal let voice: Voice = pool.noteOn(note: 60) // allocate or steal
voice.freq = midiToHz(60) voice.freq = midiToHz(60)
voice.gate = 1.0 voice.gate = 1.0
@@ -208,7 +208,7 @@ issues an atomic store.
These cases are not handled by `@LiveParam`: These cases are not handled by `@LiveParam`:
- **Edge triggers / gates** — use ``SendTrigger`` to detect ≤0→>0 crossings on the RT - **Edge triggers / gates** — use ``SendTrigger`` to detect ≤0→>0 crossings on the RT
thread and post events to a ``TriggerListener`` handler. See <doc:SendTrigger>. thread and post events to a ``TriggerListener`` handler. See ``SendTrigger``.
- **Envelope swap** — ``EnvelopeGen`` exposes a hot-swap path via an SPSC queue of - **Envelope swap** — ``EnvelopeGen`` exposes a hot-swap path via an SPSC queue of
`EnvelopePacket` value types. Useful for live shape changes without rebuilding the synth. `EnvelopePacket` value types. Useful for live shape changes without rebuilding the synth.
- **Buffer / wavetable swap** — generators that hold a ``LyrebirdBuffer`` provide a - **Buffer / wavetable swap** — generators that hold a ``LyrebirdBuffer`` provide a
@@ -325,6 +325,6 @@ generator.
### See also ### See also
- <doc:SynthesizerProtocol> - <doc:SynthesizerProtocol>
- <doc:SendTrigger> - ``SendTrigger``
- <doc:Envelopes> - <doc:Envelopes>
- <doc:BusSystem> - <doc:BusSystem>
+17 -125
View File
@@ -4,7 +4,7 @@
@PageKind(article) @PageKind(article)
} }
Envelope-driven audio processes with a performance-paced event list, timeline capture, stem recording, and NRT offline replay. Envelope-driven audio processes with a performance-paced event list, timeline capture, and stem recording.
## Overview ## Overview
@@ -14,7 +14,7 @@ Envelope-driven audio processes with a performance-paced event list, timeline ca
- **Live performance**: step through events in real time, recording stems and capturing a performance timeline as you go. - **Live performance**: step through events in real time, recording stems and capturing a performance timeline as you go.
- **Rehearsal and jump**: set ``LyrebirdEventList/index`` directly to revisit any event without releasing prior runners. - **Rehearsal and jump**: set ``LyrebirdEventList/index`` directly to revisit any event without releasing prior runners.
- **NRT offline replay**: load a saved timeline, wire the EventList to an `NRTDriver`-backed engine, and render all stems offline at faster-than-real-time speed. - **Timeline replay**: capture a performance timeline as you play, save it to JSON, and replay it against a ``LyrebirdClock`` (see <doc:RoutineTask>).
- **Multi-take editing**: aggregate several performance log files via ``LyrebirdEventList/buildFromFile(id:engine:processFactories:tolerance:paths:amp:ampLag:bus:initProcess:killProcess:)`` to create a composite rehearsal EventList from the best moments of multiple takes. - **Multi-take editing**: aggregate several performance log files via ``LyrebirdEventList/buildFromFile(id:engine:processFactories:tolerance:paths:amp:ampLag:bus:initProcess:killProcess:)`` to create a composite rehearsal EventList from the best moments of multiple takes.
--- ---
@@ -29,7 +29,7 @@ let bell = LyrebirdProcess(
envelope: Envelope( envelope: Envelope(
levels: [0.0, 1.0, 0.5, 0.0], levels: [0.0, 1.0, 0.5, 0.0],
durations: [0.05, 2.0, 1.5], durations: [0.05, 2.0, 1.5],
curves: [.sin, .exp, .exp], curves: [.sine, .exponential, .exponential],
releaseNode: 2 // level index — holds at levels[2] = 0.5 until release() is called releaseNode: 2 // level index — holds at levels[2] = 0.5 until release() is called
), ),
amp: 0.8, amp: 0.8,
@@ -61,8 +61,8 @@ let bell = LyrebirdProcess(
| `amp` | `Double` | `1.0` | Initial output amplitude `[0.0, 1.0]`. Live — writable after `play()`. | | `amp` | `Double` | `1.0` | Initial output amplitude `[0.0, 1.0]`. Live — writable after `play()`. |
| `ampLag` | `Double` | `0.01` | Lag time in seconds applied to `amp` changes. | | `ampLag` | `Double` | `0.01` | Lag time in seconds applied to `amp` changes. |
| `numChannels` | `Int` | required | Channel count of the private route bus. Must be `≥ 1`. | | `numChannels` | `Int` | required | Channel count of the private route bus. Must be `≥ 1`. |
| `procOut` | `Int` | `0` | Destination audio bus. Overridden by a parent ``LyrebirdEventList``. | | `procOut` | `any ValidBus` | `0` | Destination audio bus. Overridden by a parent ``LyrebirdEventList``. |
| `target` | ``LyrebirdProcessTarget`` | `.tail` | Node-tree insertion point for the process group (see below). | | `target` | ``LyrebirdProcessTarget`` | `.head` | Node-tree insertion point for the process group (see below). |
| `body` | `async` closure | required | Main process logic. Receives a ``LyrebirdProcessContext``. | | `body` | `async` closure | required | Main process logic. Receives a ``LyrebirdProcessContext``. |
| `onRelease` | closure | `nil` | Invoked on the main thread when ``LyrebirdProcess/release(reltime:)`` is called, before the envelope tail begins. | | `onRelease` | closure | `nil` | Invoked on the main thread when ``LyrebirdProcess/release(reltime:)`` is called, before the envelope tail begins. |
| `onFinished` | closure | `nil` | Invoked on the main thread after the group and bus are freed. | | `onFinished` | closure | `nil` | Invoked on the main thread after the group and bus are freed. |
@@ -246,8 +246,8 @@ ctx.numChannels // Int — channel count of the route bus
```swift ```swift
// Insert at head or tail of parent group (or engine root for standalone): // Insert at head or tail of parent group (or engine root for standalone):
let p = LyrebirdProcess(id: "p", ..., target: .head, ...) let p = LyrebirdProcess(id: "p", ..., target: .head, ...) // default
let p = LyrebirdProcess(id: "p", ..., target: .tail, ...) // default let p = LyrebirdProcess(id: "p", ..., target: .tail, ...)
// Insert adjacent to a sibling process (must share the same EventList): // Insert adjacent to a sibling process (must share the same EventList):
let p2 = LyrebirdProcess(id: "p2", ..., target: .before(p), ...) let p2 = LyrebirdProcess(id: "p2", ..., target: .before(p), ...)
@@ -266,7 +266,7 @@ let drone = LyrebirdProcess(
envelope: Envelope( envelope: Envelope(
levels: [0.0, 0.8, 0.0], levels: [0.0, 0.8, 0.0],
durations: [0.5, 3.0], durations: [0.5, 3.0],
curves: [.lin, .exp], curves: [.lin, .exponential],
releaseNode: 1 // level index — holds at levels[1] = 0.8 (drone sustain) releaseNode: 1 // level index — holds at levels[1] = 0.8 (drone sustain)
), ),
numChannels: 2, numChannels: 2,
@@ -328,8 +328,8 @@ The caller advances the EventList manually by calling ``LyrebirdEventList/next()
Convenience inserters: Convenience inserters:
```swift ```swift
eventList.addPreMaster(decoder) // appended at .tail(of: preMasterGroup) try eventList.addPreMaster(decoder) // appended at .tail(of: preMasterGroup)
eventList.addPostMaster(limiter) // appended at .tail(of: postMasterGroup) try eventList.addPostMaster(limiter) // appended at .tail(of: postMasterGroup)
``` ```
Synths added via these helpers are children of the master sub-group and are freed together with the EventList session (on ``LyrebirdEventList/killAll()``, ``LyrebirdEventList/releaseAll()``-driven envelope end, or ``LyrebirdEventList/reset()``). The sub-groups are re-allocated empty after teardown so subsequent playback starts clean. Synths added via these helpers are children of the master sub-group and are freed together with the EventList session (on ``LyrebirdEventList/killAll()``, ``LyrebirdEventList/releaseAll()``-driven envelope end, or ``LyrebirdEventList/reset()``). The sub-groups are re-allocated empty after teardown so subsequent playback starts clean.
@@ -349,7 +349,7 @@ let events: [LyrebirdEvent] = [
LyrebirdEvent(releases: [drone, wash]) // event 3: release remaining LyrebirdEvent(releases: [drone, wash]) // event 3: release remaining
] ]
let list = LyrebirdEventList( let list = try LyrebirdEventList(
id: "my-performance", id: "my-performance",
events: events, events: events,
engine: engine, engine: engine,
@@ -645,7 +645,7 @@ The MyPiece project under `Lyrebird-Pieces/MyPiece` uses this exact shape for it
## Timeline ## Timeline
As the EventList runs, it silently captures a ``LyrebirdTimelineEntry`` for every event that fires. This timeline can be saved, loaded, and replayed — including offline against an NRT engine. As the EventList runs, it silently captures a ``LyrebirdTimelineEntry`` for every event that fires. This timeline can be saved, loaded, and replayed against a ``LyrebirdClock``.
### Live Capture ### Live Capture
@@ -701,71 +701,6 @@ list.isPlayingTimeline // Bool
``LyrebirdEventList/playTimeline(clock:)`` sorts entries by offset defensively before scheduling, converts each offset to a sample-accurate ``SampleTime``, and fires ``LyrebirdEventList/play(eventIndex:)`` on the main thread at the correct moment via a ``LyrebirdRoutine`` background thread. The `_isReplaying` flag is set for the duration to suppress re-capture, so the timeline array is not modified during replay. ``LyrebirdEventList/playTimeline(clock:)`` sorts entries by offset defensively before scheduling, converts each offset to a sample-accurate ``SampleTime``, and fires ``LyrebirdEventList/play(eventIndex:)`` on the main thread at the correct moment via a ``LyrebirdRoutine`` background thread. The `_isReplaying` flag is set for the duration to suppress re-capture, so the timeline array is not modified during replay.
### NRT Offline Replay Walkthrough
This is the primary use case for the timeline system: render a live performance as individual stems offline, at faster-than-real-time speed.
```swift
import LyrebirdSynth
// 1. Build the NRT engine.
let nrtDriver = NRTDriver(sampleRate: 44100, blockSize: 64)
let engine = try SynthesisEngine(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 128,
numControlBuses: 64,
driver: nrtDriver
)
try engine.start()
// 2. Reconstruct the EventList with the same process definitions.
// (Processes must be rebuilt — they are single-use instances.)
let bell0 = LyrebirdProcess(id: "bell", envelope: bellEnvelope(), numChannels: 2,
body: { ctx in /* ... */ })
let drone0 = LyrebirdProcess(id: "drone", envelope: droneEnvelope(), numChannels: 2,
body: { ctx in /* ... */ })
let events: [LyrebirdEvent] = [
LyrebirdEvent(starts: [bell0]),
LyrebirdEvent(starts: [drone0], releases: [bell0])
]
let stemDir = URL(fileURLWithPath: "/tmp/nrt-render/stems")
let list = LyrebirdEventList(
id: "my-performance",
events: events,
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
// 3. Load the saved timeline.
let timelineURL = URL(fileURLWithPath: "/tmp/my-session/timeline.json")
try list.loadTimeline(from: timelineURL)
// 4. Enable stem recording before replay begins.
list.record(directory: stemDir, format: .wavFloat32)
// 5. Build a clock to drive replay timing.
let clock = LyrebirdClock(engine: engine, bpm: 120.0)
// 6. Start timeline playback — fires events at their recorded offsets.
list.playTimeline(clock: clock)
// 7. Drive the NRT engine forward in time until all events have fired
// and all processes have finished.
let totalDuration = (list.timeline.last?.offset ?? 0.0) + 10.0 // add tail margin
try nrtDriver.renderDuration(totalDuration)
// 8. Stems are now on disk in stemDir. Load them into your DAW aligned at 0.0.
engine.stop()
```
The offset embedded in each stem filename is the time origin for that stem within the session. In your DAW, set each clip's start position to the filename's offset and all stems will lock to the performance grid automatically.
--- ---
## buildFromFile ## buildFromFile
@@ -859,7 +794,7 @@ try composite.saveTimeline(to: URL(fileURLWithPath: "/tmp/composite/timeline.jso
## End-to-End Example ## End-to-End Example
The following example walks through a complete live-performance-to-NRT-render workflow. The following example walks through a complete live-performance workflow — define process bodies, build an EventList, record stems, and drive events by hand.
```swift ```swift
import LyrebirdSynth import LyrebirdSynth
@@ -890,7 +825,7 @@ func bellEnvelope() -> Envelope {
Envelope( Envelope(
levels: [0.0, 1.0, 0.6, 0.0], levels: [0.0, 1.0, 0.6, 0.0],
durations: [0.05, 1.5, 2.0], durations: [0.05, 1.5, 2.0],
curves: [.sin, .exp, .exp], curves: [.sine, .exponential, .exponential],
releaseNode: 2 // level index — sustain at levels[2] = 0.6 releaseNode: 2 // level index — sustain at levels[2] = 0.6
) )
} }
@@ -899,7 +834,7 @@ func droneEnvelope() -> Envelope {
Envelope( Envelope(
levels: [0.0, 0.8, 0.0], levels: [0.0, 0.8, 0.0],
durations: [0.5, 3.0], durations: [0.5, 3.0],
curves: [.lin, .exp], curves: [.lin, .exponential],
releaseNode: 1 // level index — sustain at levels[1] = 0.8 releaseNode: 1 // level index — sustain at levels[1] = 0.8
) )
} }
@@ -951,7 +886,7 @@ try engine.start()
let stemDir = URL(fileURLWithPath: "/tmp/my-session/stems") let stemDir = URL(fileURLWithPath: "/tmp/my-session/stems")
let timelineURL = URL(fileURLWithPath: "/tmp/my-session/timeline.json") let timelineURL = URL(fileURLWithPath: "/tmp/my-session/timeline.json")
let list = LyrebirdEventList( let list = try LyrebirdEventList(
id: "demo", id: "demo",
events: events, events: events,
engine: engine, engine: engine,
@@ -971,49 +906,6 @@ list.next() // fires event 2 — both released
// Save the performance timeline. // Save the performance timeline.
try list.saveTimeline(to: timelineURL) try list.saveTimeline(to: timelineURL)
engine.stop() engine.stop()
// MARK: - NRT replay
let nrtDriver = NRTDriver(sampleRate: 44100, blockSize: 64)
let nrtEngine = SynthesisEngine(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 128,
numControlBuses: 64,
driver: nrtDriver
)
try nrtEngine.start()
// Rebuild events with fresh process instances.
let bell2 = LyrebirdProcess(id: "bell", envelope: bellEnvelope(), numChannels: 2,
body: { ctx in let s = BellSynth(); ctx.add(s) })
let drone2 = LyrebirdProcess(id: "drone", envelope: droneEnvelope(), numChannels: 2,
body: { ctx in let s = DroneSynth(); ctx.add(s) })
let nrtList = LyrebirdEventList(
id: "demo",
events: [
LyrebirdEvent(starts: [bell2]),
LyrebirdEvent(starts: [drone2]),
LyrebirdEvent(releases: [bell2, drone2])
],
engine: nrtEngine,
bus: AudioBus(index: 0, channelCount: 2)
)
try nrtList.loadTimeline(from: timelineURL)
nrtList.record(directory: stemDir, format: .wavFloat32)
let clock = LyrebirdClock(engine: nrtEngine, bpm: 120.0)
nrtList.playTimeline(clock: clock)
let lastOffset = nrtList.timeline.last?.offset ?? 0.0
try nrtDriver.renderDuration(lastOffset + 10.0)
nrtEngine.stop()
// Stems are in /tmp/my-session/stems — load into DAW aligned at 0.0.
``` ```
--- ---
@@ -1090,7 +982,7 @@ win.close()
- ``LyrebirdProcessError`` - ``LyrebirdProcessError``
- ``LyrebirdTimelineEntry`` - ``LyrebirdTimelineEntry``
- ``LyrebirdTimelineError`` - ``LyrebirdTimelineError``
- <doc:ValueComputable> - ``ValueComputable``
- <doc:ScoreSystem> - <doc:ScoreSystem>
- <doc:SynthesizerProtocol> - <doc:SynthesizerProtocol>
- <doc:RoutineTask> - <doc:RoutineTask>
@@ -44,10 +44,12 @@ Swift-Package-only templates (lightweight; `Package.swift` opens in Xcode for Sw
| Template | Command | Description | | Template | Command | Description |
|---|---|---| |---|---|---|
| `basic` (default) | `lyrebird new MyPiece` | Minimal engine + `RunLoop.main.run()` | | `quickstart` | `lyrebird new MyFirstSound --template quickstart` | Fastest sound — a one-oscillator `SineTone` that plays 440 Hz for 10 s and exits |
| `basic` (default) | `lyrebird new MyPiece` | Minimal engine + `RunLoop.main.run()` (no synth wired yet) |
| `demo` | `lyrebird new MyPiece --template demo` | `SineTone` with `@LiveParam` frequency and amplitude | | `demo` | `lyrebird new MyPiece --template demo` | `SineTone` with `@LiveParam` frequency and amplitude |
| `ui-demo` | `lyrebird new MyApp --template ui-demo` | AppKit window with `@UIParam` controls and `LyrebirdWindow` | | `ui-demo` | `lyrebird new MyApp --template ui-demo` | AppKit window with `@UIParam` controls and `LyrebirdWindow` |
| `nrt` | `lyrebird new MyRender --template nrt` | `NRTDriver` renders to `output.caf` then exits | | `nrt` | `lyrebird new MyRender --template nrt` | `NRTDriver` renders to `output.caf` then exits |
| `score` | `lyrebird new MyScore --template score` | Builds a `Score` with the notation DSL, exports MusicXML (round-trip checked), renders offline via `NRTDriver` |
Xcode-project templates (ship a full `.xcodeproj` for deliverables SwiftPM can't express — `.app` bundles, AUv3 extensions): Xcode-project templates (ship a full `.xcodeproj` for deliverables SwiftPM can't express — `.app` bundles, AUv3 extensions):
+78 -4
View File
@@ -16,8 +16,8 @@ A demand-rate value sequence. Not thread-safe; use within a single Routine/Task.
```swift ```swift
let freqs = Pattern.sequence([440.0, 550.0, 880.0], repeats: 2) let freqs = Pattern.sequence([440.0, 550.0, 880.0], repeats: 2)
while let f = freqs.next() { ... } // iterates twice, then next() returns nil while let f = freqs.next() { _ = f } // iterates twice, then next() returns nil
freqs.reset() // restart from beginning freqs.reset() // restart from beginning
``` ```
| Property/Method | Description | | Property/Method | Description |
@@ -132,11 +132,23 @@ The returned `Pattern` has `repeats: -1` (infinite). Call `reset()` to restart f
Runs a closure **once** on a dedicated background thread (`.userInitiated` QoS). Runs a closure **once** on a dedicated background thread (`.userInitiated` QoS).
```swift ```swift
final class SineTone: SynthesizerBase {
@LiveParam var freq: Double = 440.0
override func build() {
output(bus: 0, source: OscSin.Audio(freq: $freq) * 0.2)
}
}
let routine = LyrebirdRoutine { ctx in let routine = LyrebirdRoutine { ctx in
ctx.tempo = 120.0 ctx.tempo = 120.0
let freqs = Pattern.sequence([440.0, 550.0, 660.0]) let freqs = Pattern.sequence([440.0, 550.0, 660.0])
while let freq = freqs.next() { while let freq = freqs.next() {
let tone = SineTone(); tone.freq = freq // SynthesizerBase is @MainActor — construct and configure it on main.
let tone: SineTone = ctx.onMain {
let t: SineTone = SineTone()
t.freq = freq
return t
}
ctx.add(tone) ctx.add(tone)
try ctx.wait(beats: 1.0) // 0.5 s at 120 BPM; compensates for work above try ctx.wait(beats: 1.0) // 0.5 s at 120 BPM; compensates for work above
ctx.remove(tone) ctx.remove(tone)
@@ -196,6 +208,38 @@ idle → running → paused → running → stopped
Passed to the body closure. Provides a routine clock, timed waits, and engine calls. Passed to the body closure. Provides a routine clock, timed waits, and engine calls.
### Threading and actor isolation
A body is `@Sendable` and runs on its own background thread, while `SynthesizerBase` is
`@MainActor`. Two consequences shape every body you write:
- **To construct a synth inside the body, use `ctx.onMain`.** It runs a main-actor closure,
blocks the body until it returns, and hands the result back — so the number and parameters
of the synths can depend on the body's own logic instead of being pre-allocated outside and
captured. Keep the closure short; it blocks the body *and* main. `ctx.add` then dispatches
the (main-bound) `build()` for you. Note `onMain` hops **synchronously with no timeout**, so
it needs a main thread that is actually being serviced — a GUI run loop, or a caller parked
on `waitUntilComplete()` / `LyrebirdTask.run`. Don't `start()` a task and then block main on
a bare sleep or semaphore: `ctx.add` would merely queue, but `onMain` would hang.
- **To change a parameter, use `ctx.set` with a `$param` node captured on main.** Unlike
`ctx.add`, `ctx.set` is *not* a main hop — it is a lock-free atomic write that runs inline on
the body's own thread. Direct property writes (`synth.freq = 880`) are main-isolated and
unavailable from a body.
```swift
let cutoff: ParameterNode = filter.$cutoff // capture on main, once
LyrebirdTask.run(engine: engine) { ctx in
let grain: Grain = ctx.onMain { Grain(rate: nextRate()) } // construct in-body
ctx.add(grain)
ctx.set(cutoff, to: 1200) // atomic, no dispatch
try ctx.wait(seconds: 0.05)
}
```
The full model — what is main-bound and why, the pre- vs post-publication distinction, and why
`SynthesizerBase.init` cannot simply be made `nonisolated` — is documented in `ARCHITECTURE.md`
§9.2 ("Working with the isolation from a routine or task").
### Routine clock ### Routine clock
The context exposes two parallel timelines: a **wall-clock** clock (driven by `Date()`) and a **sample-accurate** clock (driven by `engine.currentTime`). The context exposes two parallel timelines: a **wall-clock** clock (driven by `Date()`) and a **sample-accurate** clock (driven by `engine.currentTime`).
@@ -298,6 +342,36 @@ ctx.remove(synth, at: sampleTime)
ctx.remove(synth, afterBeats: 4.0) // 4 beats at current tempo ctx.remove(synth, afterBeats: 4.0) // 4 beats at current tempo
``` ```
### Live parameters
Change a running synth's `@LiveParam` from the body. Unlike the engine calls above, a `ParameterNode` write goes straight to its lock-free atomic — no main-thread hop — so it runs inline on the routine's own thread; the RT thread reads it at the next block.
> `@UIParam` (`UIParamNode`) is **not** a valid target — its `@Observable` value is main-thread-only. `ctx.set` / `ctx.ramp` take a `ParameterNode`; update `@UIParam` from the main thread.
```swift
ctx.set(param, to: 8.0) // step
try ctx.ramp(param, to: 0.5, seconds: 3) // glide over 3 s, then continue
try ctx.ramp(param, to: 0.5, beats: 2) // glide in beats at the current tempo
```
``LyrebirdRoutineContext/ramp(_:to:seconds:)`` **blocks** the body for its duration (like `wait`) and lands exactly on the target. It steps the scalar at the poll granularity; the `ParameterNode`'s own per-block interpolation blends the steps into a continuous glide, and no node source is installed — so a later ``LyrebirdRoutineContext/set(_:to:)`` still applies immediately.
`param` is the synth's **projected node, captured on the main actor first** — the `@MainActor` synth's `@LiveParam` property/`$`-projection isn't reachable from the background body:
```swift
let reverbSynth = GVerbTest(sampleRate: sr) // @MainActor setup
let reverbTime = reverbSynth.$reverbTime // ParameterNode — Sendable
LyrebirdTask.run(engine: engine) { ctx in // @Sendable body — background thread
ctx.add(reverbSynth)
try ctx.wait(beats: 2)
ctx.set(reverbTime, to: 8.0)
try ctx.ramp(reverbTime, to: 0.5, beats: 2)
}
```
For a synth driven mostly from routines, expose the node as a `nonisolated let ParameterNode` instead of `@LiveParam` — reachable from the body with no capture, at the cost of the plain-`Double` value sugar.
## Error Handling ## Error Handling
```swift ```swift
@@ -407,6 +481,6 @@ bass.start(engine: engine)
## See Also ## See Also
- ``LyrebirdClock`` - ``LyrebirdClock``
- <doc:ValueComputable> - ``ValueComputable``
- <doc:Scheduling> - <doc:Scheduling>
- <doc:NodeTree> - <doc:NodeTree>
+28 -2
View File
@@ -80,7 +80,7 @@ Fixed-capacity ring buffer with no allocation after `init`.
```swift ```swift
final class SPSCQueue<T> { final class SPSCQueue<T> {
init(capacity: Int) // capacity rounded up to next power of 2 init(capacity: Int) // capacity MUST be a power of two — precondition, not rounded
func enqueue(_ value: T) -> Bool // producer (main thread) only func enqueue(_ value: T) -> Bool // producer (main thread) only
func dequeue() -> T? // consumer (RT thread) only func dequeue() -> T? // consumer (RT thread) only
@@ -111,6 +111,32 @@ currentBlockStart = engine.currentTime
Events scheduled in the past (before `currentBlockStart`) are applied at offset 0. Events scheduled in the past (before `currentBlockStart`) are applied at offset 0.
## Per-Block Event Budget
Step 2's drain and the future-event **carry-over** are both capped at `maxEventsPerBlock`
(`SynthesisEngine.init` parameter, default 256) so the RT thread never reallocates its staging
arrays mid-render. The cap bounds two things per block:
- **Events firing this block** — the per-block onset density.
- **Look-ahead depth** — future-dated events are held in a carry-over buffer capped at the same
value. Anything beyond it is **dropped, not deferred**.
This — not `eventQueueCapacity` — is what decides whether a large batch of pre-scheduled events
survives. Dropping is silent on the audio path but instrumented off-RT:
```swift
engine.perBlockEventDropCount // events dropped for exceeding maxEventsPerBlock
engine.resetPerBlockEventDropCount()
engine.pendingQueueDroppedCount // separate: main-thread enqueue failures (queue full)
```
A one-line `[Lyrebird] Warning: … exceeded maxEventsPerBlock …` is printed at most once per
drain. The RT thread only bumps an atomic and sets a latch; a non-RT drain prints.
Either raise the cap (costs pre-allocated memory only, never RT time) or spread scheduling over
time — e.g. a just-in-time feed driven by a ``TriggerListener``, whose handlers `NRTDriver` runs
after every block — so no single block's onset density or look-ahead exceeds the budget.
## Generator count Parameter ## Generator count Parameter
Because segments are variable length, generators produce `count` samples rather than always Because segments are variable length, generators produce `count` samples rather than always
@@ -187,7 +213,7 @@ seq.onNoteOff = { _, step, _ in pool.noteOff(note: step.pitch) }
seq.start(engine: engine) // quantizes to clock.nextBeat() by default seq.start(engine: engine) // quantizes to clock.nextBeat() by default
``` ```
Internally ``StepSequencer`` uses `waitUntil(sampleTime:)` at each step boundary, keeping it phase-locked to other routines and tasks sharing the same ``LyrebirdClock``. See <doc:StepSequencer> for the full API. Internally ``StepSequencer`` uses `waitUntil(sampleTime:)` at each step boundary, keeping it phase-locked to other routines and tasks sharing the same ``LyrebirdClock``. See ``StepSequencer`` for the full API.
## Routine Elapsed Time ## Routine Elapsed Time
+50 -37
View File
@@ -133,7 +133,7 @@ let score = Score(
TempoChange(measure: 9, bpm: 72) // adagio at bar 9 TempoChange(measure: 9, bpm: 72) // adagio at bar 9
] ]
) { ) {
Part("melody") { … } Part("melody") { Note(.c, 4, dur: .quarter) }
} }
``` ```
@@ -156,7 +156,7 @@ When two `TempoChange` values target the same measure, **first-in-array order wi
### MusicXML encoding ### MusicXML encoding
``Score/toMusicXMLString(divisions:)`` emits a tempo `<direction placement="above">` block at the start of each matching measure, in **every** part. The format is identical to the measure-1 base-tempo direction: ``Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)`` emits a tempo `<direction placement="above">` block at the start of each matching measure, in **every** part. The format is identical to the measure-1 base-tempo direction:
```xml ```xml
<direction placement="above"> <direction placement="above">
@@ -201,7 +201,7 @@ let score = Score(
] ]
) )
) { ) {
Part("melody") { … } Part("melody") { Note(.c, 4, dur: .quarter) }
} }
``` ```
@@ -226,7 +226,7 @@ The `repeats:` parameter defaults to ``RepeatStructure/none`` (empty — zero `<
### MusicXML barline encoding ### MusicXML barline encoding
``Score/toMusicXMLString(divisions:)`` emits `<barline>` elements inside each matching `<measure>` block, in **every** part. Child element order follows the MusicXML 4.0 DTD (`<bar-style>`, `<ending>`, `<repeat>`): ``Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)`` emits `<barline>` elements inside each matching `<measure>` block, in **every** part. Child element order follows the MusicXML 4.0 DTD (`<bar-style>`, `<ending>`, `<repeat>`):
**Left barline** (forward repeat and/or ending start) — emitted after `<attributes>` and the tempo direction, before the first note/rest: **Left barline** (forward repeat and/or ending start) — emitted after `<attributes>` and the tempo direction, before the first note/rest:
@@ -300,7 +300,7 @@ let score = Score(
MeterMap.Segment(startBar: 5, .threeFour), // mid-piece change at bar 5 MeterMap.Segment(startBar: 5, .threeFour), // mid-piece change at bar 5
], anacrusis: Fraction(1, 1)) // one-quarter pickup ], anacrusis: Fraction(1, 1)) // one-quarter pickup
) { ) {
Part("lead") { … } Part("lead") { Note(.c, 4, dur: .quarter) }
} }
``` ```
@@ -358,8 +358,8 @@ distribution). See ``ScoreTimeline`` for the full surface.
```swift ```swift
let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4), keySignature: .gMajor) { let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4), keySignature: .gMajor) {
Part("melody") { … } Part("melody") { Note(.g, 4, dur: .quarter) }
Part("bass", channel: 1, clef: .bass) { … } Part("bass", channel: 1, clef: .bass) { Note(.g, 2, dur: .whole) }
} }
``` ```
@@ -394,7 +394,7 @@ Named static-let constants cover every key in the table:
### MusicXML round-trip ### MusicXML round-trip
``Score/toMusicXMLString(divisions:)`` emits `<key>` inside `<attributes>` after `<divisions>` and before `<time>`, in every part's measure 1: ``Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)`` emits `<key>` inside `<attributes>` after `<divisions>` and before `<time>`, in every part's measure 1:
```xml ```xml
<attributes> <attributes>
@@ -445,7 +445,7 @@ Named conveniences for common instruments:
### Per-part key override ### Per-part key override
Pass `keySignature:` to the ``Part(_:channel:clef:keySignature:transpose:elements:)`` DSL constructor: Pass `keySignature:` to the ``Part(_:channel:clef:keySignature:transpose:meterMap:offset:id:elements:)`` DSL constructor:
```swift ```swift
// Concert key G major. B♭ clarinet: written key A major (a major 2nd up). // Concert key G major. B♭ clarinet: written key A major (a major 2nd up).
@@ -463,7 +463,7 @@ let score = Score(bpm: 120, keySignature: .gMajor) {
### MusicXML encoding ### MusicXML encoding
``Score/toMusicXMLString(divisions:)`` emits each part's **effective key** in its `<key>` block: ``Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)`` emits each part's **effective key** in its `<key>` block:
- Parts with a `keySignature` override → emit the override's fifths/mode. - Parts with a `keySignature` override → emit the override's fifths/mode.
- Parts with `keySignature == nil` → emit the score-level key (unchanged behaviour). - Parts with `keySignature == nil` → emit the score-level key (unchanged behaviour).
@@ -506,14 +506,14 @@ Resolution rules:
## Clef ## Clef
Each ``ScorePart`` carries a ``Clef`` used when encoding to MusicXML. Set it via the Each ``ScorePart`` carries a ``Clef`` used when encoding to MusicXML. Set it via the
`clef:` parameter of the ``Part(_:channel:clef:elements:)`` DSL constructor: `clef:` parameter of the ``Part(_:channel:clef:keySignature:transpose:meterMap:offset:id:elements:)`` DSL constructor:
```swift ```swift
Part("Violin", clef: .treble) { … } let violin: ScorePart = Part("Violin", clef: .treble) { Note(.c, 4, dur: .quarter) }
Part("Viola", clef: .alto) { … } let viola: ScorePart = Part("Viola", clef: .alto) { Note(.c, 4, dur: .quarter) }
Part("Cello", clef: .bass) { … } let cello: ScorePart = Part("Cello", clef: .bass) { Note(.c, 3, dur: .quarter) }
Part("Guitar", clef: .treble8vb) { … } // sounds an octave lower let guitar: ScorePart = Part("Guitar", clef: .treble8vb) { Note(.c, 4, dur: .quarter) } // sounds an octave lower
Part("Drums", clef: .percussion) { … } let drums: ScorePart = Part("Drums", clef: .percussion) { Note(.c, 4, dur: .quarter) }
``` ```
The default is ``Clef/auto``, which infers the clef at encode time from the The default is ``Clef/auto``, which infers the clef at encode time from the
@@ -609,7 +609,7 @@ The flattened total span is exactly 2 beats (5 outer eighth slots × 2/5 each),
### MusicXML bracket engraving for nested tuplets ### MusicXML bracket engraving for nested tuplets
When you export nested tuplets via ``Score/toMusicXMLString(divisions:)``, each When you export nested tuplets via ``Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)``, each
bracket level receives the correct displayed number. The encoder applies a bracket level receives the correct displayed number. The encoder applies a
**per-part** rule: **per-part** rule:
@@ -715,11 +715,14 @@ staff of a grand staff keeps its own dynamic line and genuinely different voice
dynamics (one voice `f`, another `p`) are always preserved. dynamics (one voice `f`, another `p`) are always preserved.
This is controlled by the `collapseRedundantDynamics` parameter on This is controlled by the `collapseRedundantDynamics` parameter on
``Score/toMusicXMLString(divisions:collapseRedundantDynamics:)`` (and ``Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)`` (and
``Score/toMusicXMLData(divisions:collapseRedundantDynamics:)``), which defaults ``Score/toMusicXMLData(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)``), which defaults
to `true`. Pass `false` to restore the raw one-direction-per-voice output: to `true`. Pass `false` to restore the raw one-direction-per-voice output:
```swift ```swift
let score = Score(bpm: 120) {
Part("melody") { Note(.c, 4, dur: .quarter) }
}
let clean: String = score.toMusicXMLString() // collapsed (default) let clean: String = score.toMusicXMLString() // collapsed (default)
let raw: String = score.toMusicXMLString(collapseRedundantDynamics: false) // one per voice let raw: String = score.toMusicXMLString(collapseRedundantDynamics: false) // one per voice
``` ```
@@ -872,7 +875,7 @@ composes freely with `Crescendo`, `Diminuendo`, `Tuplet`, and `Voice` wrappers.
When a note must simultaneously carry boundaries from *different* overlapping When a note must simultaneously carry boundaries from *different* overlapping
spans — for example, a slur that starts on the same note where a crescendo ends spans — for example, a slur that starts on the same note where a crescendo ends
— use the `spanners:` parameter on ``Note`` or ``Chord``: — use the `spanners:` parameter on `Note` or `Chord`:
```swift ```swift
Part("lead") { Part("lead") {
@@ -1481,6 +1484,12 @@ Pitch.named(.cQuarterSharp, 4).frequency // C4 × 2^(0.5/12) ≈ 268.
on a ``LyrebirdRoutine`` thread. Two modes: on a ``LyrebirdRoutine`` thread. Two modes:
```swift ```swift
// Your own note renderer and sampler — anything that consumes a ScoreEvent / MIDIMessage.
struct NoteRenderer: Sendable { func handle(_ event: ScoreEvent) {} }
struct DrumSampler: Sendable { func handle(_ message: MIDIMessage) {} }
let mySynth: NoteRenderer = NoteRenderer()
let mySampler: DrumSampler = DrumSampler()
let score = Score(bpm: 120) { let score = Score(bpm: 120) {
Part("lead", channel: 0) { Part("lead", channel: 0) {
Note(.c, 4, dur: .quarter) Note(.c, 4, dur: .quarter)
@@ -1488,8 +1497,8 @@ let score = Score(bpm: 120) {
Note(.g, 4, dur: .half) Note(.g, 4, dur: .half)
} }
} }
let clock = LyrebirdClock(engine: engine, bpm: 120) let clock: LyrebirdClock = LyrebirdClock(engine: engine, bpm: 120)
let player = ScorePlayer(score: score, engine: engine, clock: clock) let player: ScorePlayer = ScorePlayer(score: score, engine: engine, clock: clock)
// Mode 1: emit one ScoreEvent per notated event. Caller drives note-off / // Mode 1: emit one ScoreEvent per notated event. Caller drives note-off /
// sustain via event.performedDuration (sounding length) as needed. // sustain via event.performedDuration (sounding length) as needed.
@@ -1525,6 +1534,8 @@ no external dependency.
### Score → SMF bytes ### Score → SMF bytes
```swift ```swift
import Foundation
let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) { let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("lead", channel: 0) { Part("lead", channel: 0) {
Note(.c, 4, dur: .quarter) Note(.c, 4, dur: .quarter)
@@ -1535,7 +1546,7 @@ let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Note(.c, 2, dur: .whole) Note(.c, 2, dur: .whole)
} }
} }
let data = score.toMIDIFileBytes(ticksPerQuarter: 480) let data: Data = score.toMIDIFileBytes(ticksPerQuarter: 480)
try data.write(to: URL(fileURLWithPath: "/tmp/score.mid")) try data.write(to: URL(fileURLWithPath: "/tmp/score.mid"))
``` ```
@@ -1586,6 +1597,8 @@ format.
### Score → MusicXML ### Score → MusicXML
```swift ```swift
import Foundation
let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) { let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("Melody") { Part("Melody") {
Note(.cFlat, 4, dur: .quarter) // distinct from B3 Note(.cFlat, 4, dur: .quarter) // distinct from B3
@@ -1594,8 +1607,8 @@ let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Chord([(.c, 4), (.e, 4), (.g, 4)], dur: .half) Chord([(.c, 4), (.e, 4), (.g, 4)], dur: .half)
} }
} }
let xml = score.toMusicXMLString() // String let xml: String = score.toMusicXMLString() // String
let data = score.toMusicXMLData() // UTF-8 Data let data: Data = score.toMusicXMLData() // UTF-8 Data
try data.write(to: URL(fileURLWithPath: "/tmp/score.musicxml")) try data.write(to: URL(fileURLWithPath: "/tmp/score.musicxml"))
``` ```
@@ -1614,7 +1627,7 @@ print("\(score.bpm) BPM, \(score.parts.count) parts")
Parses `<part-list>` for part names + IDs, walks each `<part>` `<measure>` Parses `<part-list>` for part names + IDs, walks each `<part>` `<measure>`
collecting `<note>` blocks. `<pitch>` (`<step>`, `<alter>`, `<octave>`) collecting `<note>` blocks. `<pitch>` (`<step>`, `<alter>`, `<octave>`)
maps directly back to ``Pitch/named(_:_:)`` preserving spelling. maps directly back to ``Pitch/named(_:_:)`` preserving spelling.
`<chord/>` flag groups simultaneous notes into ``ScoreElement/chord(_:duration:dynamic:articulation:voice:)``. `<chord/>` flag groups simultaneous notes into ``ScoreElement/chord(_:duration:dynamic:articulation:voice:tie:)``.
`<rest/>` advances cursor without emitting a note. `<rest/>` advances cursor without emitting a note.
First `<sound tempo="...">` or `<metronome><per-minute>` becomes First `<sound tempo="...">` or `<metronome><per-minute>` becomes
``Score/bpm``. First `<time>` becomes ``Score/timeSignature``. ``Score/bpm``. First `<time>` becomes ``Score/timeSignature``.
@@ -1630,7 +1643,7 @@ Articulations (`<staccato/>`, `<accent/>`, `<strong-accent/>`,
- Beat positions and durations (via configurable `<divisions>`, - Beat positions and durations (via configurable `<divisions>`,
default 480). default 480).
- Chord groupings (consecutive `<note>` elements with `<chord/>` ↔ - Chord groupings (consecutive `<note>` elements with `<chord/>` ↔
``ScoreElement/chord(_:duration:dynamic:articulation:voice:)``). ``ScoreElement/chord(_:duration:dynamic:articulation:voice:tie:)``).
- Tempo + time signature. - Tempo + time signature.
- Track / part names. - Track / part names.
- Voice numbers. - Voice numbers.
@@ -1719,11 +1732,11 @@ For example, a section starting at global bar 5 with a local `TempoChange(measur
Parts are matched across sections by ``ScorePart/id``, not by ``ScorePart/name``. This lets a section rename an instrument (e.g. `"Solo Lead"` in one section, `"Rhythm Lead"` in another) while still stitching their content together into the same flat part: Parts are matched across sections by ``ScorePart/id``, not by ``ScorePart/name``. This lets a section rename an instrument (e.g. `"Solo Lead"` in one section, `"Rhythm Lead"` in another) while still stitching their content together into the same flat part:
```swift ```swift
Section("A") { let a: ScoreSection = Section("A") {
Part("Solo Lead", id: "lead") { … } Part("Solo Lead", id: "lead") { Note(.c, 4, dur: .quarter) }
} }
Section("B") { let b: ScoreSection = Section("B") {
Part("Rhythm Lead", id: "lead") { … } // same flat part as "Solo Lead" Part("Rhythm Lead", id: "lead") { Note(.e, 4, dur: .quarter) } // same flat part as "Solo Lead"
} }
``` ```
@@ -1764,12 +1777,12 @@ No authoring action is required — this happens during section lowering. The fi
```swift ```swift
// Simple: letter paper, portrait, default margins and scaling. // Simple: letter paper, portrait, default margins and scaling.
let score = Score(bpm: 120, pageLayout: PageLayout()) { let letterScore = Score(bpm: 120, pageLayout: PageLayout()) {
Part("Piano") { … } Part("Piano") { Note(.c, 4, dur: .quarter) }
} }
// A4 landscape with custom margins. // A4 landscape with custom margins.
let score = Score( let a4Score = Score(
bpm: 120, bpm: 120,
pageLayout: PageLayout( pageLayout: PageLayout(
size: .a4, size: .a4,
@@ -1777,12 +1790,12 @@ let score = Score(
margins: PageLayout.Margins(uniformMillimeters: 20.0) margins: PageLayout.Margins(uniformMillimeters: 20.0)
) )
) { ) {
Part("Piano") { … } Part("Piano") { Note(.c, 4, dur: .quarter) }
} }
// Section-based score with page layout. // Section-based score with page layout.
let score = Score(bpm: 120, pageLayout: PageLayout(size: .a4)) { let sectionScore = Score(bpm: 120, pageLayout: PageLayout(size: .a4)) {
Section("Intro") { Part("lead") { … } } Section("Intro") { Part("lead") { Note(.c, 4, dur: .quarter) } }
} }
``` ```
@@ -1,8 +1,4 @@
# RT-to-Language Triggers # ``SendTrigger``
@Metadata {
@PageKind(article)
}
Detect signal edges on the audio thread and react in Swift — add synths, update state, sequence events. Detect signal edges on the audio thread and react in Swift — add synths, update state, sequence events.
@@ -68,7 +64,7 @@ addOutputGenerator(Out.Audio(bus: 0, source: osc))
### Value payload ### Value payload
The optional `value` argument captures a signal sample at the moment of each crossing. Pass any `ValidGeneratorInput` — a constant, a generator, or a parameter string. The optional `value` argument captures a signal sample at the moment of each crossing. Pass any `ValidGeneratorInput` — a constant, a generator, or a closure.
```swift ```swift
let lfo = OscSin.Control(freq: 0.5) // 0.5 Hz LFO let lfo = OscSin.Control(freq: 0.5) // 0.5 Hz LFO
@@ -1,4 +1,4 @@
# SpectralChain # ``SpectralChain``
Consolidated STFT pipeline. One ``SpectralChain/Audio`` Generator owns Consolidated STFT pipeline. One ``SpectralChain/Audio`` Generator owns
the forward FFT, the polar-domain processor chain, optional sidechain the forward FFT, the polar-domain processor chain, optional sidechain
@@ -1,8 +1,4 @@
# Step Sequencer # ``StepSequencer``
@Metadata {
@PageKind(article)
}
Iterate a fixed step array on a `LyrebirdClock`-synchronized background thread with per-step pitch, velocity, gate, probability, and parameter locks. Iterate a fixed step array on a `LyrebirdClock`-synchronized background thread with per-step pitch, velocity, gate, probability, and parameter locks.
@@ -8,16 +8,23 @@ The composable unit of instrument or effect in Lyrebird.
## Protocol Definition ## Protocol Definition
```swift ``Synthesizer`` is four requirements, split along the thread boundary — `build` / `release` / `free`
public protocol Synthesizer: AnyObject { are the language side, `evaluate` is the RT side:
func build() // allocate generators; main thread only
func evaluate(graph: SynthGraph, count: Int) // RT thread; default is no-op
func release(engine: SynthesisEngine) throws // graceful gate→0; default throws .noGate
func free(engine: SynthesisEngine) // immediate removal; default posts remove event
}
```
Default `evaluate` is a no-op (``SynthesizerBase`` provides the real one). Default `release` throws `SynthesizerError.noGate` — override it in synthesizers with a gate input. Default `free` posts an immediate engine remove event. | Requirement | Isolation | Contract |
|---|---|---|
| ``Synthesizer/build()`` | `@MainActor` | Configure the generator DAG. Called once, when the synth is added. Allocate every generator here — never during `evaluate`. |
| ``Synthesizer/evaluate(graph:count:)`` | `nonisolated` | Evaluate one block segment. The RT render thread's **only** entry point into a Synthesizer; must not hop actors. Called once per segment — more than once per block when a scheduled event splits it. Default is a no-op; ``SynthesizerBase`` provides the real one. |
| ``Synthesizer/release(engine:)`` | `@MainActor` | Begin a graceful release (typically post `gate = 0`). Default throws ``SynthesizerError/noGate`` — override it in any synthesizer with a gate input. |
| ``Synthesizer/free(engine:)`` | `@MainActor` | Immediate removal. Posts a remove event at the current sample time; the synth stops evaluating once the RT thread applies it. |
The isolation split is the load-bearing part: see `ARCHITECTURE.md` §9.1. Language-side requirements
must never be called from the RT audio thread.
``SynthesizerBase`` declares `release(engine:)` and `free(engine:)` as `open` members mirroring
the protocol defaults, so a subclass `override` dispatches correctly when a caller holds an
`any Synthesizer` — which is how ``Group`` reaches its children. Subclass ``SynthesizerBase``
and `override`; do not rely on the protocol extension default to pick up your implementation.
## Synthesizer Lifecycle ## Synthesizer Lifecycle
@@ -38,6 +45,9 @@ final class GatedNote: SynthesizerBase {
Call `free(engine:)` for an immediate hard kill: Call `free(engine:)` for an immediate hard kill:
```swift ```swift
let note: MySynth = MySynth()
try engine.add(note)
note.free(engine: engine) // removed on next block boundary note.free(engine: engine) // removed on next block boundary
``` ```
@@ -74,35 +84,64 @@ final class SineTone: SynthesizerBase {
@LiveParam var amp: Double = 0.5 @LiveParam var amp: Double = 0.5
override func build() { override func build() {
let osc = OscSin.Audio(freq: $freq, phase: 0.0) let osc: OscSin.Audio = OscSin.Audio(freq: $freq, phase: 0.0)
output(bus: 0, source: osc * $amp) output(bus: 0, source: osc * $amp)
} }
} }
// Update from the main thread. Both routes write the same atomic.
let note: SineTone = SineTone()
note.freq = 880.0 // typed direct write
try? note.updateParameter("freq", value: 880.0) // by-name (e.g. OSC handler)
``` ```
`@LiveParam` / `@UIParam` properties are auto-registered via `Mirror` reflection at the end `@LiveParam` / `@UIParam` properties are auto-registered via `Mirror` reflection at the end
of `build()`. The property name (with the leading `_` of property-wrapper backing storage of `build()`. The property name (with the leading `_` of property-wrapper backing storage
stripped) becomes the parameter key. stripped) becomes the parameter key.
Update parameters from the main thread: The RT audio thread picks up the new value at the start of the next (sub-)block — never
mid-block.
```swift
note.freq = 880.0 // typed direct write
try? note.updateParameter("freq", value: 880.0) // by-name (e.g. OSC handler)
```
Both routes write the same atomic. The RT audio thread picks up the new value at the start
of the next (sub-)block — never mid-block.
`updateParameter` throws `ParameterUpdateError.keyNotFound` if no live parameter exists for `updateParameter` throws `ParameterUpdateError.keyNotFound` if no live parameter exists for
the supplied key. the supplied key.
Or drive a `@LiveParam` from a `LyrebirdRoutine` / `LyrebirdTask` body — timed, sequential
control code on a background thread. The synth is `@MainActor`, so capture the projected node
(`$freq`, a `Sendable` `ParameterNode`) on the main actor, then use `ctx.set` / `ctx.ramp`:
```swift
final class SineTone: SynthesizerBase {
@LiveParam var freq: Double = 440.0
override func build() {
output(bus: 0, source: OscSin.Audio(freq: $freq) * 0.2)
}
}
let note: SineTone = SineTone()
let freq: ParameterNode = note.$freq // captured on the main actor
LyrebirdTask.run(engine: engine) { ctx in
ctx.add(note)
ctx.set(freq, to: 660) // step
try ctx.ramp(freq, to: 220, beats: 2) // timed glide
}
```
`ctx.set` / `ctx.ramp` take a `ParameterNode` only — `@UIParam`'s `UIParamNode` is `@Observable`
and main-thread-only. See <doc:RoutineTask> § Live parameters.
For the full decision matrix (when to use `@LiveParam` vs direct generator wiring vs For the full decision matrix (when to use `@LiveParam` vs direct generator wiring vs
`SendTrigger` vs envelope/buffer swap), see <doc:ParameterInputs>. `SendTrigger` vs envelope/buffer swap), see <doc:ParameterInputs>.
## Convenience Helpers (SynthesizerBase) ## Convenience Helpers (SynthesizerBase)
These are all called from inside `build()`:
```swift ```swift
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0)
let lfo: OscSin.Control = OscSin.Control(freq: 2.0)
// Audio output // Audio output
output(bus: 0, source: signal) // one bus output(bus: 0, source: signal) // one bus
output(buses: 0..<2, source: signal) // same source to multiple buses (fan-out cached) output(buses: 0..<2, source: signal) // same source to multiple buses (fan-out cached)
@@ -111,20 +150,20 @@ output(buses: 0..<2, source: signal) // same source to multiple buses (f
controlOutput(bus: 5, source: lfo) controlOutput(bus: 5, source: lfo)
// Audio input (returns In.Audio generator) // Audio input (returns In.Audio generator)
let sig = input(bus: 2) let sig: In.Audio = input(bus: 2)
// Control input (returns In.Control generator, interpolated) // Control input (returns In.Control generator, interpolated)
let ctrl = controlInput(bus: 10) let ctrl: In.Control = controlInput(bus: 10)
// Multi-channel audio input (returns GeneratorArray) // Multi-channel audio input (returns GeneratorArray)
let stereo = input(bus: 2, channels: 2) let stereo: GeneratorArray = input(bus: 2, channels: 2)
``` ```
## Adding to the Engine ## Adding to the Engine
```swift ```swift
let note1 = SineTone() let note1: MySynth = MySynth()
let note2 = SineTone() // independent instance — own phase, own envelope let note2: MySynth = MySynth() // independent instance — own phase, own envelope
try engine.add(note1) try engine.add(note1)
try engine.add(note2) try engine.add(note2)
``` ```
@@ -138,6 +177,13 @@ The RT audio thread in `applyEvent` only wires pointer references — no allocat
## Removing from the Engine ## Removing from the Engine
```swift ```swift
let note1: MySynth = MySynth()
let note2: MySynth = MySynth()
try engine.add(note1)
try engine.add(note2)
let someTime: SampleTime = engine.currentTime + engine.seconds(2.0)
engine.remove(note1) engine.remove(note1)
engine.remove(note2, at: someTime) // sample-accurate removal engine.remove(note2, at: someTime) // sample-accurate removal
``` ```
@@ -154,11 +200,21 @@ constructed inside ``SynthesizerBase/build()`` with `doneAction: .freeNode` self
with the synth's auto-free watcher — no explicit call needed: with the synth's auto-free watcher — no explicit call needed:
```swift ```swift
public override func build() { final class PluckedNote: SynthesizerBase {
let env = EnvelopeGen.Control(envelope: myEnv, override func build() {
timeScale: 8.0, let myEnv: Envelope = Envelope(
doneAction: .freeNode) // self-registers levels: [0, 1, 0],
output(bus: 0, source: someSignal * env) durations: [0.01, 0.3],
curves: [.sine, .exponential]
)
let someSignal: OscSin.Audio = OscSin.Audio(freq: 440.0)
let env: EnvelopeGen.Control = EnvelopeGen.Control(
envelope: myEnv,
timeScale: 8.0,
doneAction: .freeNode // self-registers
)
output(bus: 0, source: someSignal * env)
}
} }
``` ```
@@ -170,6 +226,10 @@ For probes constructed outside `build()`, or for custom ``DoneActionWatchable``
register explicitly: register explicitly:
```swift ```swift
let myProbe: EnvelopeGen.Control = EnvelopeGen.Control(
envelope: Envelope(levels: [0, 1, 0], durations: [0.01, 0.3], curves: [.sine, .exponential]),
doneAction: .freeNode
)
autoFreeOnDone(myProbe) autoFreeOnDone(myProbe)
``` ```
@@ -185,6 +245,8 @@ Do not call `engine.remove` from within the RT callback.
- `updateParameter` issues a releasing atomic store on the projected `ParameterNode` / - `updateParameter` issues a releasing atomic store on the projected `ParameterNode` /
`UIParamNode`; the RT thread picks up the new value via an acquiring atomic load at the `UIParamNode`; the RT thread picks up the new value via an acquiring atomic load at the
start of the next (sub-)block — no queue, no dictionary mutation on the RT thread. start of the next (sub-)block — no queue, no dictionary mutation on the RT thread.
- **Double-add precondition:** adding the same instance while it is still active in the tree is - **Double-add is an error, not undefined behaviour:** adding the same instance while it is
undefined behaviour. Always `engine.remove(synth)` and allow at least one `processBlock` to still active in the tree throws ``EngineAddError/doubleAdd(engine:)``; adding an instance
complete before re-adding the same instance. already bound to a different engine throws ``EngineAddError/boundToOtherEngine(current:prior:)``.
Both are backed by a single-shot atomic CAS. To re-add an instance, `engine.remove(synth)` and
allow at least one `processBlock` to complete first.
@@ -395,7 +395,7 @@ let tendency = DemandTemporalTendency(
// Two voices with different seeds and rates — both share one DemandTemporalTendency each // Two voices with different seeds and rates — both share one DemandTemporalTendency each
class MelodyVoice: SynthesizerBase { class MelodyVoice: SynthesizerBase {
override func buildGraph() { override func build() {
let trig = Impulse.Control(freq: 3.0) let trig = Impulse.Control(freq: 3.0)
let pitch = TimedDemand.Control(trig: trig, demand: tendency) let pitch = TimedDemand.Control(trig: trig, demand: tendency)
let env = EnvelopeGen.Audio( let env = EnvelopeGen.Audio(
@@ -1,8 +1,4 @@
# Value Sources for Non-RT Loops # ``ValueComputable``
@Metadata {
@PageKind(article)
}
A uniform `(index, timestamp) -> Double` parameter source — constants, closures, envelopes, patterns — readable from any non-RT loop. A uniform `(index, timestamp) -> Double` parameter source — constants, closures, envelopes, patterns — readable from any non-RT loop.
@@ -163,6 +163,15 @@ public let lyrebirdDefaultNumControlBuses: Int = 4096
/// `SynthesisEngine.init`. Must be a power of two. /// `SynthesisEngine.init`. Must be a power of two.
public let lyrebirdDefaultEventQueueCapacity: Int = 1024 public let lyrebirdDefaultEventQueueCapacity: Int = 1024
/// Default per-block scheduling cap when none is supplied to `SynthesisEngine.init`.
///
/// Bounds two things per audio block: the number of events that may *fire* within the
/// block, and the number of future-dated events the engine carries across a block
/// boundary (the look-ahead depth). Events beyond this cap are dropped rather than
/// triggering an RT-thread realloc. Raise it for dense granular / batch-scheduled work
/// where either the per-block onset density or the pre-scheduled look-ahead exceeds 256.
public let lyrebirdDefaultMaxEventsPerBlock: Int = 256
/// Default sample rate in Hz when none is supplied (used by `NRTJob` /// Default sample rate in Hz when none is supplied (used by `NRTJob`
/// default and convenience constructors). 44100 matches the standard /// default and convenience constructors). 44100 matches the standard
/// CD-quality rate; callers that require a specific rate should pass /// CD-quality rate; callers that require a specific rate should pass
+3 -3
View File
@@ -8,13 +8,13 @@
/// ///
/// ```swift /// ```swift
/// let group = Group() /// let group = Group()
/// engine.add(group) /// try engine.add(group)
/// ///
/// let tone = SineTone() /// let tone = SineTone()
/// engine.add(tone, position: .head(of: group)) // insert at front of group /// try engine.add(tone, position: .head(of: group)) // insert at front of group
/// ///
/// let lead = LeadSynth() /// let lead = LeadSynth()
/// engine.add(lead, position: .after(tone)) // insert immediately after tone /// try engine.add(lead, position: .after(tone)) // insert immediately after tone
/// ``` /// ```
public enum NodePosition { public enum NodePosition {
/// Insert at the front of the specified group (evaluated first within that group). /// Insert at the front of the specified group (evaluated first within that group).
@@ -21,7 +21,7 @@ import Foundation
/// for _ in 0..<32 { /// for _ in 0..<32 {
/// group.add(GrainVoice()) // any Synthesizer subclass /// group.add(GrainVoice()) // any Synthesizer subclass
/// } /// }
/// engine.add(group) /// try engine.add(group)
/// ``` /// ```
/// ///
/// All 32 voices run concurrently. Each voice writes to its own scratch copy of the /// All 32 voices run concurrently. Each voice writes to its own scratch copy of the
+9 -5
View File
@@ -21,9 +21,12 @@ public protocol LiveParameterWrapper {
/// ///
/// `ParameterNode` (in `Lyrebird`) and `UIParamNode` (in `LyrebirdUI`) both conform. /// `ParameterNode` (in `Lyrebird`) and `UIParamNode` (in `LyrebirdUI`) both conform.
public protocol LiveParameterValue: AnyObject { public protocol LiveParameterValue: AnyObject {
/// Atomically writes `newValue`. Main-thread-only — the `@Observable` registrar in /// Writes `newValue`; the RT audio thread picks it up at the next (sub-)block boundary. The
/// `UIParamNode.update(_:)` is not thread-safe. The RT audio thread picks up the new /// threading contract depends on the conformer — see each override: `ParameterNode` is a
/// value at the next (sub-)block boundary. /// releasing atomic store (callable from any single control-side producer — main thread or a
/// `LyrebirdRoutine`/`LyrebirdTask` body), while `UIParamNode` is **main-thread-only** because
/// its value is `@Observable`-tracked, not atomic. Callers holding only `any LiveParameterValue`
/// must assume the stricter main-thread-only contract.
func _writeAtomicValue(_ newValue: Double) func _writeAtomicValue(_ newValue: Double)
/// The current parameter value. Read main-thread-side by `VoicePool` for /// The current parameter value. Read main-thread-side by `VoicePool` for
@@ -149,8 +152,9 @@ public struct LiveParam: LiveParameterWrapper {
/// The current parameter value. /// The current parameter value.
/// ///
/// - Getter: acquiring atomic load via `ParameterNode.value`. /// - Getter: acquiring atomic load via `ParameterNode.value`.
/// - Setter: releasing atomic store via `ParameterNode.value` — safe to call from /// - Setter: releasing atomic store via `ParameterNode.value` — call from the control side
/// the main thread; the RT thread picks up the change at the next block boundary. /// (the main thread, or a `LyrebirdRoutine` / `LyrebirdTask` body); the RT thread picks up
/// the change at the next block boundary.
public var wrappedValue: Double { public var wrappedValue: Double {
get { projectedValue.value } get { projectedValue.value }
nonmutating set { projectedValue.value = newValue } nonmutating set { projectedValue.value = newValue }
@@ -92,9 +92,10 @@ public final class ParameterNode: GeneratorBase, ControlGenerator, LiveParameter
/// ///
/// - Getter: acquiring atomic load (`_atomicBits.load(ordering: .acquiring)`) — safe to /// - Getter: acquiring atomic load (`_atomicBits.load(ordering: .acquiring)`) — safe to
/// call from any thread. /// call from any thread.
/// - Setter: releasing atomic store (`_atomicBits.store(…, ordering: .releasing)`) — call /// - Setter: releasing atomic store (`_atomicBits.store(…, ordering: .releasing)`) — call from
/// only from the main thread. The RT audio thread picks up the new value at the start of /// the **control side**: the main thread, or a `LyrebirdRoutine` / `LyrebirdTask` body (which
/// the next block. /// runs on its own thread). Keep it to a single control-side producer. The RT audio thread
/// picks up the new value at the start of the next block. Do not write from the RT thread.
public var value: Double { public var value: Double {
get { Double(bitPattern: _atomicBits.load(ordering: .acquiring)) } get { Double(bitPattern: _atomicBits.load(ordering: .acquiring)) }
set { _atomicBits.store(newValue.bitPattern, ordering: .releasing) } set { _atomicBits.store(newValue.bitPattern, ordering: .releasing) }
@@ -217,7 +218,7 @@ public final class ParameterNode: GeneratorBase, ControlGenerator, LiveParameter
/// } /// }
/// ///
/// let synth = MySynth() /// let synth = MySynth()
/// engine.add(synth) /// try engine.add(synth)
/// synth.$freq.source = LFOGen.Control(freq: 0.5, mul: 100, add: 440) // LFO /// synth.$freq.source = LFOGen.Control(freq: 0.5, mul: 100, add: 440) // LFO
/// // ... later ... /// // ... later ...
/// synth.$freq.source = nil // revert to scalar /// synth.$freq.source = nil // revert to scalar
@@ -310,7 +311,11 @@ public final class ParameterNode: GeneratorBase, ControlGenerator, LiveParameter
/// Atomically writes `newValue`. Used by `SynthesizerBase.updateParameter(_:value:)` /// Atomically writes `newValue`. Used by `SynthesizerBase.updateParameter(_:value:)`
/// to dispatch by-name writes without knowing the concrete projected-node type. /// to dispatch by-name writes without knowing the concrete projected-node type.
/// Main-thread-only. ///
/// Delegates to the ``value`` setter — a releasing atomic store — so it inherits that setter's
/// contract: callable from the control side (main thread, or a `LyrebirdRoutine`/`LyrebirdTask`
/// body), never the RT thread. (The `UIParamNode` conformer of `LiveParameterValue` is stricter
/// — main-thread-only — because its `value` is `@Observable`, not atomic.)
public func _writeAtomicValue(_ newValue: Double) { public func _writeAtomicValue(_ newValue: Double) {
value = newValue value = newValue
} }
@@ -338,14 +338,10 @@ public final class LyrebirdProcess: @unchecked Sendable {
onRelease: ((LyrebirdProcessContext) -> Void)? = nil, onRelease: ((LyrebirdProcessContext) -> Void)? = nil,
onFinished: (() -> Void)? = nil, onFinished: (() -> Void)? = nil,
) { ) {
// `procOut` is `any ValidBus` so callers may pass `Int` or `AudioBus`. // `procOut` addresses the audio-bus pool, so an accidental `ControlBus` here would route
// A `ControlBus` is also a `ValidBus` but routing audio samples into // audio into control-bus memory. Share the same audio-rate bus guard the BusIO generators
// the control bus address space is semantically invalid — trap at init // use (trap at init, off-RT, so the `is`-check is allowed).
// (off-RT, so `is`-check is allowed). _preconditionAudioRateBus(procOut)
precondition(
!(procOut is ControlBus),
"[LyrebirdProcess '\(id)'] procOut must be an Int or AudioBus — ControlBus routes audio samples into control bus memory."
)
self.id = id self.id = id
_envelope = envelope _envelope = envelope
@@ -183,6 +183,72 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
_nextWakeTime = Date() _nextWakeTime = Date()
} }
// MARK: - Main-thread construction
/// Runs `work` on the main thread and returns its result, **blocking** the routine/task
/// body until it completes.
///
/// `SynthesizerBase` is `@MainActor`-isolated, but a routine/task body is `@Sendable` and
/// runs on its own background thread — so a body cannot construct a synthesizer directly.
/// Without this, every synth a body might add has to be pre-allocated outside the body and
/// captured (the `BufferDemos` idiom). `onMain` lifts that restriction: construct inside the
/// loop, so the *count* and *parameters* of the synths can depend on the body's own logic.
///
/// ```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
/// }
/// }
/// ```
///
/// ## Cost and drift compensation
///
/// The main hop is synchronous, so the time `work` takes counts as work done between
/// `wait` calls — which ``wait(seconds:)`` already compensates for by shortening the next
/// sleep. As long as construction is shorter than the wait interval the schedule stays on
/// time; if it overruns, the sleep is skipped and the deficit is not carried forward.
///
/// Keep `work` short — it blocks both this body *and* the main thread. Build one synth, not
/// a batch. Note that `build()` (the DAG construction) does **not** run here: it runs later,
/// on main, inside `ctx.add`'s dispatched `engine.add`.
///
/// ## Requires a serviced main thread
///
/// - Important: Unlike ``add(_:)`` / ``schedule(_:at:)`` — which are fire-and-forget
/// `DispatchQueue.main.async` and merely *delay* if main is busy — `onMain` hops
/// **synchronously and without a timeout**. If the host process's main thread is never
/// serviced, this call blocks the body forever with no diagnostic.
///
/// Main is serviced in the normal cases: a GUI app's run loop, or a CLI caller parked on
/// ``LyrebirdTask/waitUntilComplete()`` / ``LyrebirdTask/run(engine:body:)``, which pump the
/// main run loop precisely so dispatched work lands. The hazard is a process that calls
/// ``LyrebirdTask/start(engine:)`` and then blocks main on something that is *not* a run loop
/// (a bare `Thread.sleep`, a semaphore wait): `ctx.add` would silently queue up, but `onMain`
/// will hang. Park on `waitUntilComplete()` instead.
///
/// Re-entering the calling thread is not a hazard: `lyrebirdRunMainActorMutation` branches on
/// `Thread.isMainThread` and runs `work` inline (no dispatch) when already on main, so `onMain`
/// is self-deadlock-free regardless of which thread calls it.
///
/// - Parameter work: Main-actor-isolated closure — typically a synthesizer initializer.
/// - Returns: Whatever `work` returns. The result need not be `Sendable`; the synchronous
/// hop is a full barrier, so the value is carried back without a data race.
public func onMain<T>(_ work: @MainActor () throws -> T) rethrows -> T {
let box: _OnMainResultBox<T> = _OnMainResultBox<T>()
// The shared bridge returns Void (a non-Sendable T cannot cross back through
// `DispatchQueue.sync` directly), so the result travels out via the box instead.
try lyrebirdRunMainActorMutation { box.value = try work() }
guard let result: T = box.value else {
// Unreachable: the bridge runs `work` synchronously before returning, so the box
// is always populated unless `work` threw (in which case `try` already exited).
preconditionFailure("onMain: main-actor work did not produce a result")
}
return result
}
// MARK: - Engine calls (dispatched to main thread) // MARK: - Engine calls (dispatched to main thread)
public func add(_ synth: any Synthesizer) { public func add(_ synth: any Synthesizer) {
@@ -247,6 +313,86 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
} }
} }
// MARK: - Live parameters
/// Sets a live parameter to `value` — the `ParameterNode` projected by a synth's `@LiveParam`
/// (`synth.$someLiveParam`). The RT thread picks the value up at the next block.
///
/// Unlike ``add(_:)`` / ``remove(_:)`` (engine graph edits, which hop to the main thread), a
/// `ParameterNode` write goes straight to its lock-free atomic — so it runs inline on the
/// routine/task body's own thread with no dispatch. Capture the projected node on the main actor
/// first (`let time = synth.$reverbTime`), then drive it from the body:
///
/// ```swift
/// let time = reverbSynth.$reverbTime // ParameterNode, captured on the main actor
/// LyrebirdTask.run(engine: engine) { ctx in
/// ctx.add(reverbSynth)
/// try ctx.wait(beats: 2)
/// ctx.set(time, to: 8.0) // long tail
/// try ctx.wait(beats: 2)
/// ctx.set(time, to: 0.5) // short tail
/// }
/// ```
///
/// > `@UIParam` (`UIParamNode`) is **not** accepted: its value is `@Observable`-tracked and
/// > main-thread-only, so it can't be written from the routine/task's background thread. Update
/// > `@UIParam` from the main thread instead.
///
/// - Parameters:
/// - param: The `@LiveParam` node — `synth.$someLiveParam`.
/// - value: The new value; applied at the next audio block.
public func set(_ param: ParameterNode, to value: Double) {
param.value = value
}
/// Glides a live parameter from its current value to `target` over `seconds`, then lands exactly
/// on `target`. **Blocks** the routine/task body for the duration — like ``wait(seconds:)``, so it
/// sequences naturally with the body's other timed events.
///
/// The glide is produced by stepping the scalar at the body's poll granularity; the parameter
/// node's own per-block linear interpolation blends the steps into a continuous ramp on the RT
/// thread. No node source is installed, so a later ``set(_:to:)`` still takes effect immediately.
/// A non-positive `seconds` jumps straight to `target`.
///
/// ```swift
/// let cutoff = filter.$cutoff
/// LyrebirdTask.run(engine: engine) { ctx in
/// ctx.add(filter)
/// try ctx.ramp(cutoff, to: 8000, seconds: 3) // 3 s sweep, then continue
/// try ctx.wait(seconds: 1)
/// }
/// ```
///
/// - Parameters:
/// - param: The `@LiveParam` node — `synth.$someLiveParam`. Its current value is read once
/// (an atomic load) to seed the glide. (`@UIParam` is not accepted — see ``set(_:to:)``.)
/// - target: The value to arrive at.
/// - seconds: Glide duration in seconds.
/// - Throws: Rethrows if the body is stopped/cancelled mid-glide (via the internal ``wait(seconds:)``).
public func ramp(_ param: ParameterNode, to target: Double, seconds: Double) throws {
guard seconds > 0 else {
param.value = target
return
}
let start: Double = param.value
let stepSeconds: Double = LyrebirdRoutineContext.pollIntervalSeconds
let steps: Int = max(1, Int((seconds / stepSeconds).rounded()))
for i: Int in 1...steps {
let fraction: Double = Double(i) / Double(steps)
param.value = start + (target - start) * fraction
try wait(seconds: seconds / Double(steps))
}
// The final step (i == steps) already wrote `start + (target - start)`, which is `target`
// to within a rounding ULP; this makes the landing exact.
param.value = target
}
/// Glides a `@LiveParam` node to `target` over `beats` beats at the current ``tempo``.
/// See ``ramp(_:to:seconds:)``.
public func ramp(_ param: ParameterNode, to target: Double, beats: Double) throws {
try ramp(param, to: target, seconds: beats * 60.0 / tempo)
}
// MARK: - Private // MARK: - Private
/// Sleep until `target` wall-clock time, polling every ~10 ms. /// Sleep until `target` wall-clock time, polling every ~10 ms.
@@ -292,6 +438,17 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
} }
} }
/// One-shot carrier that returns a (possibly non-`Sendable`) value from a synchronous
/// main-thread hop in ``LyrebirdRoutineContext/onMain(_:)``.
///
/// `@unchecked Sendable`: the value is written on the main thread and read on the calling
/// thread, but `lyrebirdRunMainActorMutation` performs the write inside a synchronous
/// `DispatchQueue.main.sync` (or inline when already on main). That hop is a full barrier —
/// the write happens-before the read, and the two threads never touch the box concurrently.
private final class _OnMainResultBox<T>: @unchecked Sendable {
var value: T?
}
/// Cross-thread argument carrier. `@unchecked Sendable` because engine calls are serialized /// Cross-thread argument carrier. `@unchecked Sendable` because engine calls are serialized
/// through the main-thread dispatch, which is the sole producer for `pendingQueue`. /// through the main-thread dispatch, which is the sole producer for `pendingQueue`.
private struct Args: @unchecked Sendable { private struct Args: @unchecked Sendable {
+1 -1
View File
@@ -50,7 +50,7 @@ public struct BeatPosition: Sendable, Hashable {
// MARK: - Factories // MARK: - Factories
/// Absolute 0-based quarter beats (meter-free). Quantized to /// Absolute 0-based quarter beats (meter-free). Quantized to
/// ``Fraction/beatApproxDenominator``. /// `Fraction.beatApproxDenominator`.
public static func quarters(_ q: Double) -> BeatPosition { public static func quarters(_ q: Double) -> BeatPosition {
BeatPosition(kind: .quarters(fractionFromBeats(q))) BeatPosition(kind: .quarters(fractionFromBeats(q)))
} }
+2 -2
View File
@@ -23,7 +23,7 @@ import Foundation
/// - ``auto`` — Infer the appropriate clef from the part's pitch content at encode time. /// - ``auto`` — Infer the appropriate clef from the part's pitch content at encode time.
/// Resolves to `.treble` or `.bass` based on the median MIDI pitch of the part's /// Resolves to `.treble` or `.bass` based on the median MIDI pitch of the part's
/// pitched events (median < ``autoBassThresholdMidi`` → `.bass`, else → `.treble`). /// pitched events (median < ``autoBassThresholdMidi`` → `.bass`, else → `.treble`).
/// `.auto` is the default for the ``Part(_:channel:clef:elements:)`` DSL constructor. /// `.auto` is the default for the ``Part(_:channel:clef:keySignature:transpose:meterMap:offset:id:elements:)`` DSL constructor.
public enum Clef: Sendable, Hashable { public enum Clef: Sendable, Hashable {
/// G clef, line 2. /// G clef, line 2.
@@ -46,7 +46,7 @@ public enum Clef: Sendable, Hashable {
/// Infer treble or bass from the part's pitch range at encode time. /// Infer treble or bass from the part's pitch range at encode time.
/// ///
/// At ``Score/toMusicXMLString(divisions:)`` time the median MIDI pitch of the /// At ``Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)`` time the median MIDI pitch of the
/// part's non-rest pitched notes is computed. If the median is below /// part's non-rest pitched notes is computed. If the median is below
/// ``autoBassThresholdMidi`` (57 — A3), `.bass` is chosen; otherwise `.treble`. /// ``autoBassThresholdMidi`` (57 — A3), `.bass` is chosen; otherwise `.treble`.
/// If the part has no pitched notes, `.treble` is chosen. /// If the part has no pitched notes, `.treble` is chosen.
+2 -2
View File
@@ -24,7 +24,7 @@ public enum Dynamic: Hashable, Sendable {
/// No sound — velocity zero, printed as `n` in MusicXML. /// No sound — velocity zero, printed as `n` in MusicXML.
/// ///
/// Use `.niente` at the start or end of a crescendo/diminuendo (al niente / /// Use `.niente` at the start or end of a crescendo/diminuendo (al niente /
/// dal niente) or as the initial/final point of a ``dynamicCurve:`` to indicate /// dal niente) or as the initial/final point of a `dynamicCurve:` to indicate
/// silence at that position. The `<n/>` MusicXML child element is the /// silence at that position. The `<n/>` MusicXML child element is the
/// standard MusicXML 4.0 representation. /// standard MusicXML 4.0 representation.
case niente case niente
@@ -66,7 +66,7 @@ public enum Dynamic: Hashable, Sendable {
} }
} }
/// MIDI velocity `[0, 127]` derived from ``velocity`` × ``midiMaxVelocity``, /// MIDI velocity `[0, 127]` derived from ``velocity`` × `midiMaxVelocity`,
/// rounded. /// rounded.
public var midiVelocity: UInt8 { public var midiVelocity: UInt8 {
UInt8(min(Dynamic.midiMaxVelocity, UInt8(min(Dynamic.midiMaxVelocity,

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