Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 560724d116 | |||
| 63d6e0746f | |||
| c058493a98 | |||
| 8a2eb191a2 | |||
| 676e8d3278 | |||
| 032b7c39d3 | |||
| 73191c958f | |||
| ca1ee503cc | |||
| 1c03e39eac | |||
| f59fd3b55a |
+45
-1
@@ -256,12 +256,14 @@ And `engine.remove(synth)`:
|
||||
|
||||
`remove` returns `Bool` (it unbinds synchronously on successful enqueue), but there is a documented one-`processBlock` window between `remove` and a re-`add` of the same instance — the RT thread needs a block to actually unlink it. If `freeQueue` overflows, the framework logs one warning and leaks that single reference rather than risk the RT thread; a leaked voice is preferable to an audio dropout or crash.
|
||||
|
||||
### 9.1 Actor isolation of the lifecycle (Phase 201)
|
||||
### 9.1 Actor isolation of the lifecycle
|
||||
|
||||
The Swift-concurrency isolation of `Synthesizer` is split along exactly the thread boundary above:
|
||||
|
||||
- **Language side is `@MainActor`.** `SynthesizerBase` is a `@MainActor` class, and the `Synthesizer` protocol declares `build()`, `release(engine:)`, `free(engine:)` as `@MainActor` requirements. Steps 1–4 of the add path (allocate → build → enqueue) and the `engine.add` / `schedule` / `add(position:)` entry points are therefore main-actor-isolated. This is what lets a consumer building under Xcode 26's `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor` default subclass `SynthesizerBase` and override `build()` with **no** concurrency annotations — the consumer's MainActor default now matches the base instead of conflicting with a nonisolated override. (`engine.remove` stays nonisolated — it unbinds via atomics and enqueues a pointer-only event; `_bind` / `_unbind` are nonisolated for the same reason.)
|
||||
|
||||
- **`SynthesizerBase` declares `release(engine:)` / `free(engine:)` as `open` members, not just protocol conformances.** The `Synthesizer` extension supplies defaults for both, but a protocol-extension default is bound **statically** at the conformance — `SynthesizerBase`'s. Were the base to declare no member of its own, a subclass could not `override` them at all, and a subclass method declared without `override` would be invisible to every caller holding an `any Synthesizer`: the call would reach the extension default and throw `.noGate`. That matters because the callers that drive the lifecycle are exactly those existential ones — `Group.release` cascades to children as `any Synthesizer`, freeing any child that throws `.noGate`, so a gated subclass would be hard-freed and its envelope release phase skipped. Declaring both as `open` class members makes the witness a class method, so the call dispatches through the vtable and subclass overrides run. Pinned by `SynthesizerReleaseDispatchTests`.
|
||||
|
||||
- **The RT entry point is `nonisolated`.** `evaluate(graph:count:)` is `nonisolated final` so the render callback (steps 5–6) reaches it with **no actor hop**. It reads exactly two stored properties cross-thread — `parameterTable` (immutable `let`) and `outputGenerators` (written in `build()` on main, read on RT) — both marked `nonisolated(unsafe)`. Their safety rests entirely on the happens-before edge established by the SPSC `pendingQueue` (§2.1): the RT thread cannot observe the node until it dequeues the `.add` event, which the producer enqueued *after* `build()` fully returned on main. No new runtime synchronisation is introduced by the isolation annotations.
|
||||
|
||||
- **`Group` / `ParallelGroup` stay nonisolated.** They satisfy the `@MainActor` `build`/`release`/`free` requirements with less-isolated (nonisolated) witnesses, keeping their RT-owned linked-list / snapshot state reachable from the render thread. `Group.release` installs its self-free poll timer through a `nonisolated` helper so the utility-queue handler does not inherit `@MainActor` (which would trap when it fires off-main).
|
||||
@@ -270,6 +272,48 @@ The Swift-concurrency isolation of `Synthesizer` is split along exactly the thre
|
||||
|
||||
The guarantee is locked by the committed `RegressionFixtures/MainActorConsumer` package, which compiles an unannotated `SynthesizerBase` subclass under `.swiftLanguageMode(.v6)` + `-default-isolation MainActor`.
|
||||
|
||||
### 9.2 Working with the isolation from a routine or task
|
||||
|
||||
A `LyrebirdRoutine` / `LyrebirdTask` body is `@Sendable` and runs on its own background thread. `SynthesizerBase` is `@MainActor`. Those two facts drive every ergonomic question below, so it is worth being precise about **what is actually main-bound, and why**:
|
||||
|
||||
| Step | Main-bound? | Why |
|
||||
|---|---|---|
|
||||
| `init` (allocate the synth) | **Yes** — but for an *ergonomic* reason, not an RT one | See "Why `init` is not `nonisolated`" below |
|
||||
| `build()` (construct the DAG) | **Yes — load-bearing** | Must complete-before the `.add` enqueue; that is the happens-before edge the RT thread relies on (§9.1) |
|
||||
| `engine.add` / `schedule` | **Yes — load-bearing** | `pendingQueue` is SPSC: exactly one producer |
|
||||
| `engine.remove` | No | Unbinds via atomics, enqueues a pointer-only event |
|
||||
| Writing a `@LiveParam` | No — but the *property* is main-isolated | The value itself crosses via a lock-free atomic (see "Mutating parameters") |
|
||||
| `evaluate()` (RT) | No — `nonisolated final` | The render callback must reach it with no actor hop |
|
||||
|
||||
**Constructing a synth inside a body — `ctx.onMain`.** Because a body cannot touch `@MainActor` state directly, the historical idiom was to pre-allocate every synth *outside* the body and capture it (the `BufferDemos` pattern). That forces the set of synths to be known in advance. ``LyrebirdRoutineContext/onMain(_:)`` removes the restriction — it runs a main-actor closure, blocks the body until it returns, and hands the (possibly non-`Sendable`) result back:
|
||||
|
||||
```swift
|
||||
LyrebirdTask.run(engine: engine) { ctx in
|
||||
while ctx.now < 10.0 {
|
||||
let grain: Grain = ctx.onMain { Grain(startPos: nextPos(), rate: nextRate()) }
|
||||
ctx.add(grain) // async hop; grain self-frees via its envelope
|
||||
try ctx.wait(seconds: 0.05) // drift-compensated as usual
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The hop is synchronous, so its cost counts as work between `wait` calls — which `wait(seconds:)` already compensates for by shortening the next sleep. Keep the closure short (build one synth, not a batch): it blocks both the body and the main thread. Note `build()` does **not** run inside `onMain` — it runs later, on main, inside `ctx.add`'s dispatched `engine.add`.
|
||||
|
||||
`onMain` **requires a serviced main thread**, and this is the one way to misuse it. `ctx.add` is fire-and-forget (`DispatchQueue.main.async`) and merely delays if main is busy; `onMain` hops synchronously with no timeout, so if main is never serviced it blocks the body forever with no diagnostic. A GUI run loop services it; so does a CLI parked on `waitUntilComplete()` / `LyrebirdTask.run`, which pump the main run loop for exactly this reason. The trap is `task.start(engine:)` followed by blocking main on something that is not a run loop (a bare `Thread.sleep`, a semaphore wait) — park on `waitUntilComplete()` instead. Re-entering the caller's own thread is *not* a hazard: `lyrebirdRunMainActorMutation` branches on `Thread.isMainThread` and runs the closure inline when already on main, so `onMain` is self-deadlock-free whichever thread calls it.
|
||||
|
||||
**Mutating parameters — `ctx.set`, not property writes.** Construction is *pre-publication*: the synth is thread-local, unshared, and the RT thread cannot reach it, which is what makes hopping to main for it a pure formality. A parameter write is *post-publication*: the synth is live in the tree and the RT thread reads it every block. Safety there comes from `ParameterNode`'s atomic — **not** from isolation. So capture the projected node on main once, then drive it from the body:
|
||||
|
||||
```swift
|
||||
let cutoff: ParameterNode = filter.$cutoff // captured on main
|
||||
LyrebirdTask.run(engine: engine) { ctx in
|
||||
ctx.set(cutoff, to: 1200) // releasing atomic store — no dispatch
|
||||
}
|
||||
```
|
||||
|
||||
`ctx.set` is **not** a main hop: unlike `ctx.add`, it writes the atomic inline on the body's own thread. The only cost is the one-line capture. (`synth.cutoff = 1200` and `synth.$cutoff` are both main-isolated — the property inherits the class's isolation even though `LiveParam` itself is a plain, atomic-backed struct.)
|
||||
|
||||
**Why `init` is not `nonisolated`.** It looks free — the base `init()` is empty, `build()` is not called from it, and a fresh synth is unshared. It is not free. Under `-default-isolation MainActor` a consumer subclass that declares no init gets an *implicit `@MainActor init()`*, which would then override a `nonisolated` base init and fail with `different actor isolation from nonisolated overridden declaration` — breaking every unannotated consumer, i.e. exactly the §9.1 guarantee. The main test suite cannot catch this (it does not build under that flag); `RegressionFixtures/MainActorConsumer` is the only thing that does. **If you are tempted to relax the isolation on `SynthesizerBase.init`, build that fixture first.** `ctx.onMain` exists precisely because it buys the same ergonomics additively, with no isolation change.
|
||||
|
||||
---
|
||||
|
||||
## Where to go deeper
|
||||
|
||||
@@ -31,6 +31,23 @@ git config core.hooksPath .githooks
|
||||
```
|
||||
The `.githooks/pre-commit` hook calls `--check`. Skips silently when `~/.claude/agents/` is absent (contributors without working copies are not blocked). Bypass for one commit with `git commit --no-verify`.
|
||||
|
||||
## Repo Guard Scripts
|
||||
|
||||
These guards catch classes of regression that **`swift build` / `swift test` structurally cannot**. Both are manual/CI (too slow for pre-commit). Run before a release or a merge that touches their surface.
|
||||
|
||||
| Script | Guards | Run when |
|
||||
|---|---|---|
|
||||
| `bash scripts/check-swift6-consumer.sh` | The zero-annotation consumer guarantee — builds `RegressionFixtures/MainActorConsumer` under `.swiftLanguageMode(.v6)` + `-default-isolation MainActor`. The main package **does not build under that flag**, so the test suite cannot catch an isolation regression. | Any change to `SynthesizerBase` / `Synthesizer` actor isolation. Non-negotiable: `swift test` passing is *not* evidence here. |
|
||||
| `bash scripts/check-docc.sh` | New DocC warnings — broken symbol links, ambiguous refs, article/symbol collisions. DocC links pin a symbol's **full signature**, so adding one parameter silently breaks every link to it. Nothing else checks this. | Any change to a public signature, or edits to `.docc` / doc comments. |
|
||||
| `bash scripts/check-doc-impact.sh [range]` | **Reports** (never fails) which docs a diff's public-API changes may have invalidated. Doc rot is usually *caused* by an API change, and a diff-only read cannot find the stale references — they live in files the diff never touches. Run by `/lyrebird_review` step 2b; suppresses refs the compile guard already covers. | Any change to a public signature. |
|
||||
| `bash scripts/check-doc-snippets.sh` | Doc **examples** that stop compiling. `swift build` never sees a code fence and `check-docc.sh` only validates links, so examples rot silently — `engine.add` became throwing and 11 examples kept calling it without `try`; `LyrebirdFloat` was deleted and 75 references outlived it. Both are type errors, so the fences are typechecked against the real API. | Any change to a public signature, or edits to `.docc` / doc comments. |
|
||||
|
||||
`check-docc.sh` is a **ratchet**: it fails on warnings absent from `scripts/docc-warnings-baseline.txt`. That baseline is now **empty** — the catalog is at zero warnings — so in practice any new warning fails the build. Keep it that way; the baseline may only shrink. (`--strict` asserts zero explicitly and is equivalent while the baseline is empty. `--update-baseline` exists for the rare deliberate exception — prefer fixing the link.)
|
||||
|
||||
**Golden values need a test, not a guard.** A typecheck proves an example still *compiles*; it cannot see a documented result drift. Where a doc asserts concrete output (`// → 0.744, 0.046, …`), pin it with a test — `DistributionKindGoldenValueTests` and `_DocTheorySnippetCheckTests` are the two instances. This is not optional pedantry: three of the four `DistributionKind` sequences had silently drifted, and their fences also passed a `seed:` argument to a type that has no such parameter.
|
||||
|
||||
`check-doc-snippets.sh` checks the fences recorded in `scripts/doc-snippets-manifest.txt` (currently **426** of 1458). That set is produced by asking the **compiler** which fences compile — `--classify` — never by hand-annotating fences. A fence that compiles under no preamble self-excludes, which is how iOS-only examples, `Package.swift` snippets and pseudo-code drop out with no skip list. **Coverage is therefore partial by construction**: a fragment like `try engine.add(MySynth())`, which needs both an `engine` and a `MySynth` in scope, is *not* checked. The fix for an important uncovered example is to make it self-contained in the doc — which is better documentation anyway — not to grow the preamble table. Re-run `--classify` after adding examples or deliberately changing what is checkable.
|
||||
|
||||
## Task → Doc Map
|
||||
|
||||
**Engine / RT core**
|
||||
@@ -61,6 +78,7 @@ The `.githooks/pre-commit` hook calls `--check`. Skips silently when `~/.claude/
|
||||
- TemporalStream / language-side value generation → `Sources/Lyrebird/Lyrebird.docc/TemporalDemand.md`
|
||||
- Polyphonic voice pool / step sequencer → `docs/tooling/routine-task.md`
|
||||
- Score / ScorePlayer / SMF / MusicXML → `Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md`
|
||||
- Pitch / scale theory toolkit (spelling-aware `Interval` / `Scale` / `PitchCollection` / 12-tone rows, diatonic-vs-chromatic transposition, scale mapping; → notation + Hz/seconds for synthesis) → `docs/stdlib/theory.md` (types under `Sources/Lyrebird/Score/Theory/`)
|
||||
- Performance event sequencing / `LyrebirdProcess` / `LyrebirdEventList` → `Sources/Lyrebird/Lyrebird.docc/ProcessSystem.md`
|
||||
- NRT / offline render → `docs/tooling/nrt-guide.md`
|
||||
|
||||
@@ -138,7 +156,7 @@ One-liners. Detail and rationale lives in linked docs.
|
||||
|
||||
**Never drop new files at `Sources/Lyrebird/` root.** Every new `.swift` file goes into a subfolder grouped by function. Existing top-level subfolders (alphabetical):
|
||||
|
||||
`AUv3/` `AudioDrivers/` `Buffers/` `Buses/` `Capture/` `Diagnostics/` `Distributions/` `Engine/` `Envelopes/` `External/` `GeneratorCore/` `Generators/` `Kinds/` `MIDI/` `Math/` `NodeTree/` `OSC/` `Oversampling/` `Parameters/` `Patterns/` `Process/` `Scheduling/` `Score/` `Spectral/` `Synthesizer/` `TemporalStream/` `Trigger/` `ValueCompute/` `Voices/`
|
||||
`AUv3/` `AudioDrivers/` `Buffers/` `Buses/` `Capture/` `Diagnostics/` `Distributions/` `Engine/` `Envelopes/` `External/` `GeneratorCore/` `Generators/` `Kinds/` `MIDI/` `Math/` `NodeTree/` `OSC/` `Oversampling/` `Parameters/` `Patterns/` `Process/` `Scheduling/` `Score/` `Spectral/` `Synthesizer/` `TemporalStream/` `Trigger/` `Utilities/` `ValueCompute/` `Voices/`
|
||||
|
||||
Rule:
|
||||
|
||||
@@ -178,6 +196,23 @@ Call-site pattern: every `engine.add` invocation needs `try`. In non-throwing co
|
||||
|
||||
Hard rules. Review agents flag violations.
|
||||
|
||||
### No phase numbers in code or docs
|
||||
Never write phase numbers (`Phase 228`, `Phase 228c`, `phase-224`, `pre-Phase-209c`, `// Phase 216:`, `(Phase 201)`, `— Phase 214`) in source comments, doc-comments (`///`), `.docc` markdown, `@Suite`/`@Test` display strings, or test function / type / file names. Phase numbers are meaningless to external readers — they belong **only** in planning docs (`docs/00-working-order.md`, `docs/01-completed-working-order.md`), commit messages, and `MEMORY.md`/phase history. Describe the **behavior or reason** instead:
|
||||
```swift
|
||||
// WRONG
|
||||
// Phase 216: emit a tempo direction for this measure when a TempoChange targets it.
|
||||
let cap = ... // Phase 228c
|
||||
/// > Note: Phase 224 wires this as model state.
|
||||
@Suite("EngineHost (Phase 197)")
|
||||
|
||||
// RIGHT
|
||||
// Emit a tempo direction for this measure when a TempoChange targets it.
|
||||
let cap = ...
|
||||
/// > Note: this is model state.
|
||||
@Suite("EngineHost")
|
||||
```
|
||||
Exception: the DSP term **"phase"** that is NOT a planning reference — oscillator `phase`, `phase accumulator`, `phase offset`, `_phase`, `initPhase`, `phase modulation`, "Phase 0.25 in an 8-sample table" — is a real audio term, never touch it. The rule targets `Phase <number>` planning tags only.
|
||||
|
||||
### No force unwraps
|
||||
Never `!` on optionals or `try!`. Hotspots: `UnsafeBufferPointer.baseAddress` in Accelerate calls, `Array.first!`/`last!` on output channels, `try!` in test helpers, `dict[key]!`.
|
||||
```swift
|
||||
@@ -306,6 +341,7 @@ Module-level helpers exist to eliminate repeated boilerplate; inlining any of th
|
||||
- `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)`
|
||||
- `xorshift64Next(_:)`
|
||||
- `lyrebirdSeedXorshift64(from:mixConstant:)` / `lyrebirdSeedXorshift64(from:)` — `Math/LyrebirdConstants.swift`; init-time xorshift64 seed helper. Two-arg form decorrelates Audio/Control pairs via `mixConstant`; one-arg form is the convenience for stand-alone single-state owners (e.g. `DemandTemporalTendency` / `DemandTemporalBrownian`)
|
||||
- `catmullRomCubic(_:_:_:_:t:)` — `Math/CubicInterpolation.swift`; the single shared 4-point Catmull-Rom cubic kernel. Pass `(pM1, p0, p1, p2, t:)` — the sample before the segment, the two bracketing it, the one after, and `t ∈ [0, 1]`. Use instead of inlining the `t²`/`t³` expanded form. `@inline(__always) @_spi(LyrebirdExtensions) public`. Consumers: oscillator table reads (`OscSin` / `oscillatorTableReadCubic`), `PlayBuffer`, `chaoticInterpolate`, and the fractional-delay lines (`DelayLine` / `DelayLineFeedback` / `CombFilter` / `AllpassFilter`).
|
||||
|
||||
Full table, signatures, examples, and the per-generator exceptions (notably `MathGenerators.Control` and the non-standard ControlGenerator ramp paths) live in `docs/protocols/writing-generators.md` §13. That document is the single source of truth — when adding or removing a helper, update §13 and reference it from here.
|
||||
|
||||
|
||||
@@ -17,8 +17,8 @@ final class BufferDemos: DemoProtocol {
|
||||
|
||||
func runDemo() {
|
||||
// BufferDemos.swift lives at .../Demos/LyrebirdDemo/LyrebirdDemo/Demos/BufferDemos.swift
|
||||
// — 4 components up to reach .../Demos/ where Perc.aiff lives.
|
||||
let percURL = URL(fileURLWithPath: #filePath)
|
||||
// — 4 components up to reach .../Demos/ where Mozart.aiff lives.
|
||||
let percURL: URL = URL(fileURLWithPath: #filePath)
|
||||
.deletingLastPathComponent() // .../Demos/
|
||||
.deletingLastPathComponent() // .../LyrebirdDemo/
|
||||
.deletingLastPathComponent() // .../LyrebirdDemo (package)/
|
||||
@@ -35,13 +35,58 @@ final class BufferDemos: DemoProtocol {
|
||||
exit(1)
|
||||
}
|
||||
|
||||
let sampleRate = engine.sampleRate
|
||||
let sampleRate: Double = engine.sampleRate
|
||||
|
||||
let pitchSteps: [(Double, String)] = [
|
||||
(0.5, "0.5 — octave down"),
|
||||
(0.75, "0.75 — minor third down"),
|
||||
(1.0, "1.0 — original pitch"),
|
||||
(1.5, "1.5 — perfect fifth up"),
|
||||
(2.0, "2.0 — octave up"),
|
||||
]
|
||||
|
||||
let spectralRatios: [(Double, String)] = [
|
||||
(0.5, "0.5 — octave down (phase vocoder)"),
|
||||
(1.0, "1.0 — no shift (phase vocoder passthrough)"),
|
||||
(1.5, "1.5 — perfect fifth up (phase vocoder)"),
|
||||
(2.0, "2.0 — octave up (phase vocoder)"),
|
||||
]
|
||||
|
||||
let diffuseSteps: [(Double, String)] = [
|
||||
(0.0, "0.0 — bypass (mono passthrough on both channels)"),
|
||||
(0.5, "0.5 — half decorrelation"),
|
||||
(1.0, "1.0 — full per-channel phase randomisation"),
|
||||
]
|
||||
|
||||
let stretchSteps: [(Double, String)] = [
|
||||
(3.0, "3.0 — 3× stretch (one-third speed, pitch preserved)"),
|
||||
(1.5, "1.5 — 1.5× stretch (three-quarter speed, pitch preserved)"),
|
||||
(1.0, "1.0 — native speed (no stretch)"),
|
||||
(0.5, "0.5 — 2× compression (double speed, pitch preserved)"),
|
||||
(0.33, "0.33 — 3× compression (triple speed, pitch preserved)"),
|
||||
]
|
||||
|
||||
// `runDemo()` is @MainActor (see DemoProtocol), so the @MainActor synths are constructed
|
||||
// directly — no `MainActor.assumeIsolated` wrapping. Build them here, then hand the
|
||||
// resulting instances / live-param node to the @Sendable task body.
|
||||
let demo1: PercPlayBuffer = PercPlayBuffer(buffer: percBuffer, engineSampleRate: sampleRate)
|
||||
let demo2: PercBufferRead = PercBufferRead(buffer: percBuffer)
|
||||
let demo3: PercPitchShift = PercPitchShift(buffer: percBuffer, engineSampleRate: sampleRate)
|
||||
let pitchRatioNode: ParameterNode = demo3.$pitchRatio
|
||||
|
||||
let demo4Array: [PercSpectralPitchShift] = spectralRatios.map { ratio, _ in
|
||||
PercSpectralPitchShift(buffer: percBuffer, pitchRatio: ratio, engineSampleRate: sampleRate)
|
||||
}
|
||||
let demo5Array: [PercSpectralStereoDiffuse] = diffuseSteps.map { amount, _ in
|
||||
PercSpectralStereoDiffuse(buffer: percBuffer, amount: amount, engineSampleRate: sampleRate)
|
||||
}
|
||||
let demo6Array: [PercTimeStretch] = stretchSteps.map { factor, _ in
|
||||
PercTimeStretch(buffer: percBuffer, stretchFactor: factor)
|
||||
}
|
||||
|
||||
LyrebirdTask.run(engine: engine) { ctx in
|
||||
// Demo 1 — PlayBuffer (looping at native rate)
|
||||
|
||||
print("\n── Demo 1: PlayBuffer (looping) ──")
|
||||
let demo1 = PercPlayBuffer(buffer: percBuffer, engineSampleRate: sampleRate)
|
||||
ctx.add(demo1)
|
||||
try ctx.wait(seconds: 6)
|
||||
ctx.remove(demo1)
|
||||
@@ -49,7 +94,6 @@ final class BufferDemos: DemoProtocol {
|
||||
|
||||
// Demo 2 — BufferRead (sine-wave position scan)
|
||||
print("\n── Demo 2: BufferRead (sine-wave position scan) ──")
|
||||
let demo2 = PercBufferRead(buffer: percBuffer)
|
||||
ctx.add(demo2)
|
||||
try ctx.wait(seconds: 6)
|
||||
ctx.remove(demo2)
|
||||
@@ -57,19 +101,10 @@ final class BufferDemos: DemoProtocol {
|
||||
|
||||
// Demo 3 — PlayBuffer → PitchShift (cycling through pitch ratios)
|
||||
print("\n── Demo 3: PlayBuffer → PitchShift ──")
|
||||
let demo3 = PercPitchShift(buffer: percBuffer, engineSampleRate: sampleRate)
|
||||
ctx.add(demo3)
|
||||
|
||||
let pitchSteps: [(Double, String)] = [
|
||||
(0.5, "0.5 — octave down"),
|
||||
(0.75, "0.75 — minor third down"),
|
||||
(1.0, "1.0 — original pitch"),
|
||||
(1.5, "1.5 — perfect fifth up"),
|
||||
(2.0, "2.0 — octave up"),
|
||||
]
|
||||
for (ratio, label) in pitchSteps {
|
||||
print(" pitchRatio \(label)")
|
||||
demo3.pitchRatio = ratio
|
||||
ctx.set(pitchRatioNode, to: ratio) // live-param write from the task body
|
||||
try ctx.wait(seconds: 3)
|
||||
}
|
||||
ctx.remove(demo3)
|
||||
@@ -77,16 +112,9 @@ final class BufferDemos: DemoProtocol {
|
||||
|
||||
// Demo 4 — PlayBuffer → SpectralChain.Audio (with SpectralPitchShift)
|
||||
print("\n── Demo 4: PlayBuffer → SpectralChain.Audio (SpectralPitchShift) ──")
|
||||
|
||||
let spectralRatios: [(Double, String)] = [
|
||||
(0.5, "0.5 — octave down (phase vocoder)"),
|
||||
(1.0, "1.0 — no shift (phase vocoder passthrough)"),
|
||||
(1.5, "1.5 — perfect fifth up (phase vocoder)"),
|
||||
(2.0, "2.0 — octave up (phase vocoder)"),
|
||||
]
|
||||
for (ratio, label) in spectralRatios {
|
||||
for (index, (_, label)) in spectralRatios.enumerated() {
|
||||
print(" pitchRatio \(label)")
|
||||
let demo4 = PercSpectralPitchShift(buffer: percBuffer, pitchRatio: ratio, engineSampleRate: sampleRate)
|
||||
let demo4: PercSpectralPitchShift = demo4Array[index]
|
||||
ctx.add(demo4)
|
||||
try ctx.wait(seconds: 5)
|
||||
ctx.remove(demo4)
|
||||
@@ -95,16 +123,9 @@ final class BufferDemos: DemoProtocol {
|
||||
|
||||
// Demo 5 — SpectralChain.Audio fan-out (mono → 2-channel decorrelated stereo)
|
||||
print("\n── Demo 5: SpectralChain.Audio fan-out (SpectralStereoDiffuse) ──")
|
||||
|
||||
let diffuseSteps: [(Double, String)] = [
|
||||
(0.0, "0.0 — bypass (mono passthrough on both channels)"),
|
||||
(0.5, "0.5 — half decorrelation"),
|
||||
(1.0, "1.0 — full per-channel phase randomisation"),
|
||||
]
|
||||
for (amount, label) in diffuseSteps {
|
||||
for (index, (_, label)) in diffuseSteps.enumerated() {
|
||||
print(" amount \(label)")
|
||||
let demo5 = PercSpectralStereoDiffuse(
|
||||
buffer: percBuffer, amount: amount, engineSampleRate: sampleRate)
|
||||
let demo5: PercSpectralStereoDiffuse = demo5Array[index]
|
||||
ctx.add(demo5)
|
||||
try ctx.wait(seconds: 5)
|
||||
ctx.remove(demo5)
|
||||
@@ -113,17 +134,9 @@ final class BufferDemos: DemoProtocol {
|
||||
|
||||
// Demo 6 — TimeStretch (granular, pitch-preserved time stretching + compression)
|
||||
print("\n── Demo 6: TimeStretch (granular time-stretch / compression) ──")
|
||||
|
||||
let stretchSteps: [(Double, String)] = [
|
||||
(3.0, "3.0 — 3× stretch (one-third speed, pitch preserved)"),
|
||||
(1.5, "1.5 — 1.5× stretch (three-quarter speed, pitch preserved)"),
|
||||
(1.0, "1.0 — native speed (no stretch)"),
|
||||
(0.5, "0.5 — 2× compression (double speed, pitch preserved)"),
|
||||
(0.33, "0.33 — 3× compression (triple speed, pitch preserved)"),
|
||||
]
|
||||
for (factor, label) in stretchSteps {
|
||||
for (index, (_, label)) in stretchSteps.enumerated() {
|
||||
print(" stretchFactor \(label)")
|
||||
let demo6 = PercTimeStretch(buffer: percBuffer, stretchFactor: factor)
|
||||
let demo6: PercTimeStretch = demo6Array[index]
|
||||
ctx.add(demo6)
|
||||
try ctx.wait(seconds: 6)
|
||||
ctx.remove(demo6)
|
||||
|
||||
@@ -7,5 +7,10 @@
|
||||
import LyrebirdSynth
|
||||
|
||||
protocol DemoProtocol {
|
||||
func runDemo()
|
||||
/// Main-actor-isolated: demos construct `@MainActor` `SynthesizerBase` synths and are launched
|
||||
/// from `main.swift`'s top-level code (which runs on the main actor). Isolating the requirement
|
||||
/// lets conformances build synths and read their `$liveParam` nodes directly — no
|
||||
/// `MainActor.assumeIsolated { … }` wrapping — before handing Sendable references to a
|
||||
/// background `LyrebirdTask`/`LyrebirdRoutine` body.
|
||||
@MainActor func runDemo()
|
||||
}
|
||||
|
||||
@@ -4,14 +4,6 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//
|
||||
// BufferDemos 2.swift
|
||||
// LyrebirdDemo
|
||||
//
|
||||
// Created by Joshua Parmenter on 5/6/26.
|
||||
//
|
||||
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -25,18 +17,31 @@ final class ReverbDemo: DemoProtocol {
|
||||
|
||||
func runDemo() {
|
||||
|
||||
let sampleRate = engine.sampleRate
|
||||
// sets up its own thread / timing, etc
|
||||
LyrebirdTask.run(engine: engine) { [sampleRate] ctx in
|
||||
let sampleRate: Double = engine.sampleRate
|
||||
|
||||
// `runDemo()` is @MainActor (see DemoProtocol), so the @MainActor synth is constructed and
|
||||
// its live-param node read directly
|
||||
let reverbDemo: GVerbTest = GVerbTest(sampleRate: sampleRate)
|
||||
|
||||
// `$reverbTime` is a Sendable `ParameterNode` — capture it here, then write it from inside
|
||||
// the @Sendable task body (GVerb picks up each change on the next block). The @MainActor
|
||||
// `reverbDemo.reverbTime` property itself is NOT reachable from the task body under Swift 6;
|
||||
// the node is. either grab it outside the task (uncomment below) ...
|
||||
// let reverbTimeParam: ParameterNode = reverbDemo.$reverbTime
|
||||
|
||||
LyrebirdTask.run(engine: engine) { ctx in
|
||||
ctx.tempo = 60.0
|
||||
let reverbDemo = GVerbTest(
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
ctx.add(reverbDemo)
|
||||
try ctx.wait(beats: 6) // could also use seconds
|
||||
// ... or use ctx.onMain inside the task
|
||||
let param: ParameterNode = ctx.onMain {
|
||||
reverbDemo.$reverbTime
|
||||
}
|
||||
try ctx.wait(beats: 2) // hold the starting reverbTime (3.0)
|
||||
ctx.set(param, to: 8.0) // step: jump to a long tail
|
||||
try ctx.wait(beats: 2)
|
||||
try ctx.ramp(param, to: 0.5, beats: 2) // glide: smooth swoosh down to a short tail
|
||||
ctx.remove(reverbDemo)
|
||||
print("\nAll buffer demos complete.")
|
||||
print("\nAll reverb demos complete.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,17 +14,21 @@
|
||||
import LyrebirdSynth
|
||||
|
||||
final class GVerbTest: SynthesizerBase {
|
||||
// A live parameter: `$reverbTime` is a `ParameterNode` (Sendable) that GVerb re-reads every
|
||||
// block, so writing `reverbTime`/`$reverbTime.value` retunes the running reverb. Change it from
|
||||
// the main thread or a `LyrebirdTask`/`LyrebirdRoutine` body — see `ReverbDemo`.
|
||||
@LiveParam var reverbTime: Double = 3.0
|
||||
private let sampleRate: Double
|
||||
|
||||
|
||||
init(sampleRate: Double) {
|
||||
self.sampleRate = sampleRate
|
||||
}
|
||||
|
||||
|
||||
override func build() {
|
||||
let impulse = Impulse.Audio(freq: 0.5)
|
||||
let reverb = GVerb.Audio(source: impulse,
|
||||
roomSize: 70.0,
|
||||
reverbTime: 3.0,
|
||||
reverbTime: $reverbTime, // live ParameterNode, not the baked scalar
|
||||
earlyLevel: 0.4,
|
||||
tailLevel: 0.9,
|
||||
dryLevel: 0.1,
|
||||
|
||||
@@ -9,7 +9,7 @@ import LyrebirdSynth
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
sampleRate: 48000,
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 2,
|
||||
driver: CoreAudioDriver()
|
||||
@@ -22,6 +22,7 @@ do {
|
||||
exit(1)
|
||||
}
|
||||
|
||||
BufferDemos(engine: engine).runDemo()
|
||||
//ReverbDemo(engine: engine).runDemo()
|
||||
// BufferDemos(engine: engine).runDemo()
|
||||
ReverbDemo(engine: engine).runDemo()
|
||||
|
||||
engine.stop()
|
||||
|
||||
@@ -17,7 +17,7 @@ let package = Package(
|
||||
.executableTarget(
|
||||
name: "LyrebirdDemo",
|
||||
dependencies: [
|
||||
.product(name: "Lyrebird", package: "LyrebirdII"),
|
||||
.product(name: "Lyrebird", package: "Lyrebird"),
|
||||
],
|
||||
path: "LyrebirdDemo"
|
||||
),
|
||||
|
||||
@@ -12,7 +12,7 @@ import LyrebirdUI
|
||||
// ── Demo selector ─────────────────────────────────────────────────────────────
|
||||
// Change `demo` to `.sineTone` or `.binDelay` to switch demos.
|
||||
private enum Demo { case vector, binDelay, sineTone }
|
||||
private let demo: Demo = .binDelay
|
||||
private let demo: Demo = .vector
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
@@ -26,6 +26,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
let binDelayController: BinDelayController
|
||||
var window: LyrebirdWindow?
|
||||
|
||||
@MainActor
|
||||
init(engine: SynthesisEngine) {
|
||||
let scopeCapture = ScopeCapture(buses: [0, 1], bufferSize: 2048)
|
||||
engine.scopeTap = scopeCapture
|
||||
|
||||
@@ -13,6 +13,7 @@ import LyrebirdSynth
|
||||
/// first taps "Start Synthesizer" — this is necessary because
|
||||
/// `SpectralBinDelayUI.init(sampleRate:)` requires the engine's committed
|
||||
/// sample rate, which is only valid after `engine.start()` returns.
|
||||
@MainActor
|
||||
@Observable
|
||||
final class BinDelayController {
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import Observation
|
||||
import LyrebirdSynth
|
||||
|
||||
@MainActor
|
||||
@Observable
|
||||
final class NoteController {
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import Observation
|
||||
import LyrebirdSynth
|
||||
|
||||
@MainActor
|
||||
@Observable
|
||||
final class VectorOscillatorController {
|
||||
|
||||
|
||||
@@ -9,14 +9,19 @@ import LyrebirdSynth
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
sampleRate: 48000,
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
)
|
||||
|
||||
let delegate = AppDelegate(engine: engine)
|
||||
let app = NSApplication.shared
|
||||
app.setActivationPolicy(.regular)
|
||||
app.delegate = delegate
|
||||
app.run()
|
||||
// AppDelegate.init is @MainActor (it builds @MainActor SynthesizerBase synths
|
||||
// and UI controllers). Program entry runs on the main thread, so assert main-
|
||||
// actor isolation for the AppKit bootstrap rather than hopping asynchronously.
|
||||
MainActor.assumeIsolated {
|
||||
let delegate: AppDelegate = AppDelegate(engine: engine)
|
||||
let app: NSApplication = NSApplication.shared
|
||||
app.setActivationPolicy(.regular)
|
||||
app.delegate = delegate
|
||||
app.run()
|
||||
}
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"originHash" : "2c98cd4172bcfb3eff9cb6e34a538f80f5e424aa73fbd5bea2b20cf0c8b539b7",
|
||||
"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
|
||||
}
|
||||
@@ -17,7 +17,7 @@ let package = Package(
|
||||
.executableTarget(
|
||||
name: "LyrebirdNRTDemo",
|
||||
dependencies: [
|
||||
.product(name: "Lyrebird", package: "LyrebirdII"),
|
||||
.product(name: "Lyrebird", package: "Lyrebird"),
|
||||
],
|
||||
path: "LyrebirdNRTDemo"
|
||||
),
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 60;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
E3C000000000000000000007 /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3C000000000000000000006 /* main.swift */; };
|
||||
E3C000000000000000000013 /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = E3C000000000000000000012 /* Lyrebird */; };
|
||||
E3C000000000000000000015 /* SineTone.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3C000000000000000000014 /* SineTone.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
E3C000000000000000000004 /* LyrebirdQuickstartDemo */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = LyrebirdQuickstartDemo; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
E3C000000000000000000006 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
|
||||
E3C000000000000000000014 /* SineTone.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SineTone.swift; sourceTree = "<group>"; };
|
||||
E3C000000000000000000017 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
E3C000000000000000000018 /* LyrebirdQuickstartDemo.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdQuickstartDemo.entitlements; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
E3C000000000000000000009 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
E3C000000000000000000013 /* Lyrebird in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
E3C000000000000000000002 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
E3C000000000000000000005 /* LyrebirdQuickstartDemo */,
|
||||
E3C000000000000000000003 /* Products */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
E3C000000000000000000003 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
E3C000000000000000000004 /* LyrebirdQuickstartDemo */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
E3C000000000000000000005 /* LyrebirdQuickstartDemo */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
E3C000000000000000000006 /* main.swift */,
|
||||
E3C000000000000000000016 /* Synthesizers */,
|
||||
E3C000000000000000000017 /* Info.plist */,
|
||||
E3C000000000000000000018 /* LyrebirdQuickstartDemo.entitlements */,
|
||||
);
|
||||
path = LyrebirdQuickstartDemo;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
E3C000000000000000000016 /* Synthesizers */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
E3C000000000000000000014 /* SineTone.swift */,
|
||||
);
|
||||
path = Synthesizers;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
E3C00000000000000000000A /* LyrebirdQuickstartDemo */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = E3C00000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdQuickstartDemo" */;
|
||||
buildPhases = (
|
||||
E3C000000000000000000008 /* Sources */,
|
||||
E3C000000000000000000009 /* Frameworks */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = LyrebirdQuickstartDemo;
|
||||
packageProductDependencies = (
|
||||
E3C000000000000000000012 /* Lyrebird */,
|
||||
);
|
||||
productName = LyrebirdQuickstartDemo;
|
||||
productReference = E3C000000000000000000004 /* LyrebirdQuickstartDemo */;
|
||||
productType = "com.apple.product-type.tool";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
E3C000000000000000000001 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = 1;
|
||||
LastSwiftUpdateCheck = 1600;
|
||||
LastUpgradeCheck = 1600;
|
||||
TargetAttributes = {
|
||||
E3C00000000000000000000A = {
|
||||
CreatedOnToolsVersion = 16.0;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = E3C00000000000000000000E /* Build configuration list for PBXProject "LyrebirdQuickstartDemo" */;
|
||||
compatibilityVersion = "Xcode 14.0";
|
||||
developmentRegion = en;
|
||||
hasScannedForEncodings = 0;
|
||||
knownRegions = (
|
||||
en,
|
||||
Base,
|
||||
);
|
||||
mainGroup = E3C000000000000000000002;
|
||||
packageReferences = (
|
||||
E3C000000000000000000011 /* XCLocalSwiftPackageReference "../.." */,
|
||||
);
|
||||
productRefGroup = E3C000000000000000000003 /* Products */;
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
E3C00000000000000000000A /* LyrebirdQuickstartDemo */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
E3C000000000000000000008 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
E3C000000000000000000007 /* main.swift in Sources */,
|
||||
E3C000000000000000000015 /* SineTone.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
E3C00000000000000000000C /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdQuickstartDemo/LyrebirdQuickstartDemo.entitlements;
|
||||
CODE_SIGN_IDENTITY = "-";
|
||||
CODE_SIGN_STYLE = Manual;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
INFOPLIST_FILE = LyrebirdQuickstartDemo/Info.plist;
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdQuickstartDemo;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 6.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
E3C00000000000000000000D /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdQuickstartDemo/LyrebirdQuickstartDemo.entitlements;
|
||||
CODE_SIGN_IDENTITY = "-";
|
||||
CODE_SIGN_STYLE = Manual;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
INFOPLIST_FILE = LyrebirdQuickstartDemo/Info.plist;
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdQuickstartDemo;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 6.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
E3C00000000000000000000F /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
CLANG_ANALYZER_NONNULL = YES;
|
||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu17;
|
||||
GCC_DYNAMIC_NO_PIC = NO;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
GCC_PREPROCESSOR_DEFINITIONS = (
|
||||
"DEBUG=1",
|
||||
"$(inherited)",
|
||||
);
|
||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
||||
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
|
||||
MTL_FAST_MATH = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = macosx;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
E3C000000000000000000010 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
CLANG_ANALYZER_NONNULL = YES;
|
||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
ENABLE_NS_ASSERTIONS = NO;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu17;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
||||
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
MTL_FAST_MATH = YES;
|
||||
SDKROOT = macosx;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
E3C00000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdQuickstartDemo" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
E3C00000000000000000000C /* Debug */,
|
||||
E3C00000000000000000000D /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
E3C00000000000000000000E /* Build configuration list for PBXProject "LyrebirdQuickstartDemo" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
E3C00000000000000000000F /* Debug */,
|
||||
E3C000000000000000000010 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
|
||||
/* Begin XCLocalSwiftPackageReference section */
|
||||
E3C000000000000000000011 /* XCLocalSwiftPackageReference "../.." */ = {
|
||||
isa = XCLocalSwiftPackageReference;
|
||||
relativePath = ../..;
|
||||
};
|
||||
/* End XCLocalSwiftPackageReference section */
|
||||
|
||||
/* Begin XCSwiftPackageProductDependency section */
|
||||
E3C000000000000000000012 /* Lyrebird */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = E3C000000000000000000011 /* XCLocalSwiftPackageReference "../.." */;
|
||||
productName = Lyrebird;
|
||||
};
|
||||
/* End XCSwiftPackageProductDependency section */
|
||||
};
|
||||
rootObject = E3C000000000000000000001 /* Project object */;
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "2620"
|
||||
version = "1.7">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES"
|
||||
buildArchitectures = "Automatic">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "E3C00000000000000000000A"
|
||||
BuildableName = "LyrebirdQuickstartDemo"
|
||||
BlueprintName = "LyrebirdQuickstartDemo"
|
||||
ReferencedContainer = "container:LyrebirdQuickstartDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
shouldAutocreateTestPlan = "YES">
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Release"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "E3C00000000000000000000A"
|
||||
BuildableName = "LyrebirdQuickstartDemo"
|
||||
BlueprintName = "LyrebirdQuickstartDemo"
|
||||
ReferencedContainer = "container:LyrebirdQuickstartDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "E3C00000000000000000000A"
|
||||
BuildableName = "LyrebirdQuickstartDemo"
|
||||
BlueprintName = "LyrebirdQuickstartDemo"
|
||||
ReferencedContainer = "container:LyrebirdQuickstartDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>NSDesktopFolderUsageDescription</key>
|
||||
<string>LyrebirdQuickstartDemo writes rendered audio files to the Desktop.</string>
|
||||
<key>NSDocumentsFolderUsageDescription</key>
|
||||
<string>LyrebirdQuickstartDemo writes rendered audio files to Documents.</string>
|
||||
</dict>
|
||||
</plist>
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.app-sandbox</key>
|
||||
<false/>
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,21 @@
|
||||
// SineTone.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
// A Synthesizer is a graph built in `build()`. This one is a single sine
|
||||
// oscillator, scaled down so it isn't harsh, centred to both speakers with
|
||||
// Pan2 and written to output bus 0 (left) / bus 1 (right).
|
||||
//
|
||||
// This is the same synth the `quickstart` CLI template scaffolds:
|
||||
// lyrebird new MyFirstSound --template quickstart
|
||||
final class SineTone: SynthesizerBase {
|
||||
override func build() {
|
||||
let sin: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.2)
|
||||
let pan: Pan2 = Pan2(input: sin, pan: 0)
|
||||
output(bus: 0, source: pan)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// main.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdQuickstartDemo — the shortest path to sound.
|
||||
//
|
||||
// Mirrors the `quickstart` CLI template (`lyrebird new … --template quickstart`):
|
||||
// the engine, a one-oscillator SineTone (see Synthesizers/SineTone.swift), and a
|
||||
// main that starts it, plays a 440 Hz tone for 10 seconds, then stops and exits.
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// Seconds to play before exiting.
|
||||
let quickstartDuration: Double = 5.0
|
||||
|
||||
do {
|
||||
// The engine owns Core Audio and runs the graph on the RT thread.
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
sampleRate: 48000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
)
|
||||
|
||||
try engine.start()
|
||||
let sineTone: SineTone = SineTone()
|
||||
try engine.add(sineTone) // starts sounding immediately
|
||||
|
||||
print("LyrebirdQuickstartDemo: playing a 440 Hz sine for \(Int(quickstartDuration)) seconds…")
|
||||
Thread.sleep(forTimeInterval: quickstartDuration)
|
||||
|
||||
engine.remove(sineTone)
|
||||
|
||||
Thread.sleep(forTimeInterval: 0.1)
|
||||
engine.stop() // closes the device
|
||||
print("Done.")
|
||||
} catch {
|
||||
fputs("Lyrebird quickstart failed to start: \(error)\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"originHash" : "293673d962d3211d0b8d90755b3dd158ce14df67eed9e956cb4457dba015dc09",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "linenoise-swift",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/andybest/linenoise-swift",
|
||||
"state" : {
|
||||
"revision" : "afc897c02b030af7333105c4fedcd843a8339238",
|
||||
"version" : "0.0.3"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "nimble",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/Quick/Nimble.git",
|
||||
"state" : {
|
||||
"revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0",
|
||||
"version" : "7.3.4"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 3
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// Package.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// swift-tools-version: 6.0
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "LyrebirdQuickstartDemo",
|
||||
platforms: [.macOS(.v15)],
|
||||
dependencies: [
|
||||
.package(path: "../.."),
|
||||
],
|
||||
targets: [
|
||||
.executableTarget(
|
||||
name: "LyrebirdQuickstartDemo",
|
||||
dependencies: [
|
||||
.product(name: "Lyrebird", package: "Lyrebird"),
|
||||
],
|
||||
path: "LyrebirdQuickstartDemo"
|
||||
),
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,344 @@
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 60;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
A5D100000000000000000007 /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D100000000000000000006 /* main.swift */; };
|
||||
A5D100000000000000000013 /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = A5D100000000000000000012 /* Lyrebird */; };
|
||||
A5D100000000000000000015 /* ScoreVoice.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D100000000000000000014 /* ScoreVoice.swift */; };
|
||||
A5D100000000000000000019 /* DemoProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D100000000000000000018 /* DemoProtocol.swift */; };
|
||||
A5D10000000000000000001B /* ScoreDemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D10000000000000000001A /* ScoreDemo.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
A5D100000000000000000004 /* LyrebirdScoreDemo */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = LyrebirdScoreDemo; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
A5D100000000000000000006 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
|
||||
A5D100000000000000000014 /* ScoreVoice.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScoreVoice.swift; sourceTree = "<group>"; };
|
||||
A5D100000000000000000017 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
A5D100000000000000000020 /* LyrebirdScoreDemo.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdScoreDemo.entitlements; sourceTree = "<group>"; };
|
||||
A5D100000000000000000018 /* DemoProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoProtocol.swift; sourceTree = "<group>"; };
|
||||
A5D10000000000000000001A /* ScoreDemo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScoreDemo.swift; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
A5D100000000000000000009 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
A5D100000000000000000013 /* Lyrebird in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
A5D100000000000000000002 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A5D100000000000000000005 /* LyrebirdScoreDemo */,
|
||||
A5D100000000000000000003 /* Products */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A5D100000000000000000003 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A5D100000000000000000004 /* LyrebirdScoreDemo */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A5D100000000000000000005 /* LyrebirdScoreDemo */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A5D100000000000000000006 /* main.swift */,
|
||||
A5D100000000000000000016 /* Synthesizers */,
|
||||
A5D10000000000000000001C /* Demos */,
|
||||
A5D100000000000000000017 /* Info.plist */,
|
||||
A5D100000000000000000020 /* LyrebirdScoreDemo.entitlements */,
|
||||
);
|
||||
path = LyrebirdScoreDemo;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A5D100000000000000000016 /* Synthesizers */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A5D100000000000000000014 /* ScoreVoice.swift */,
|
||||
);
|
||||
path = Synthesizers;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A5D10000000000000000001C /* Demos */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A5D100000000000000000018 /* DemoProtocol.swift */,
|
||||
A5D10000000000000000001A /* ScoreDemo.swift */,
|
||||
);
|
||||
path = Demos;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
A5D10000000000000000000A /* LyrebirdScoreDemo */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = A5D10000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdScoreDemo" */;
|
||||
buildPhases = (
|
||||
A5D100000000000000000008 /* Sources */,
|
||||
A5D100000000000000000009 /* Frameworks */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = LyrebirdScoreDemo;
|
||||
packageProductDependencies = (
|
||||
A5D100000000000000000012 /* Lyrebird */,
|
||||
);
|
||||
productName = LyrebirdScoreDemo;
|
||||
productReference = A5D100000000000000000004 /* LyrebirdScoreDemo */;
|
||||
productType = "com.apple.product-type.tool";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
A5D100000000000000000001 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = 1;
|
||||
LastSwiftUpdateCheck = 1600;
|
||||
LastUpgradeCheck = 1600;
|
||||
TargetAttributes = {
|
||||
A5D10000000000000000000A = {
|
||||
CreatedOnToolsVersion = 16.0;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = A5D10000000000000000000E /* Build configuration list for PBXProject "LyrebirdScoreDemo" */;
|
||||
compatibilityVersion = "Xcode 14.0";
|
||||
developmentRegion = en;
|
||||
hasScannedForEncodings = 0;
|
||||
knownRegions = (
|
||||
en,
|
||||
Base,
|
||||
);
|
||||
mainGroup = A5D100000000000000000002;
|
||||
packageReferences = (
|
||||
A5D100000000000000000011 /* XCLocalSwiftPackageReference "../.." */,
|
||||
);
|
||||
productRefGroup = A5D100000000000000000003 /* Products */;
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
A5D10000000000000000000A /* LyrebirdScoreDemo */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
A5D100000000000000000008 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
A5D100000000000000000007 /* main.swift in Sources */,
|
||||
A5D100000000000000000015 /* ScoreVoice.swift in Sources */,
|
||||
A5D100000000000000000019 /* DemoProtocol.swift in Sources */,
|
||||
A5D10000000000000000001B /* ScoreDemo.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
A5D10000000000000000000C /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScoreDemo/LyrebirdScoreDemo.entitlements;
|
||||
CODE_SIGN_IDENTITY = "-";
|
||||
CODE_SIGN_STYLE = Manual;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
INFOPLIST_FILE = LyrebirdScoreDemo/Info.plist;
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScoreDemo;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 6.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
A5D10000000000000000000D /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScoreDemo/LyrebirdScoreDemo.entitlements;
|
||||
CODE_SIGN_IDENTITY = "-";
|
||||
CODE_SIGN_STYLE = Manual;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
INFOPLIST_FILE = LyrebirdScoreDemo/Info.plist;
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScoreDemo;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 6.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
A5D10000000000000000000F /* 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;
|
||||
};
|
||||
A5D100000000000000000010 /* 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 */
|
||||
A5D10000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdScoreDemo" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
A5D10000000000000000000C /* Debug */,
|
||||
A5D10000000000000000000D /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
A5D10000000000000000000E /* Build configuration list for PBXProject "LyrebirdScoreDemo" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
A5D10000000000000000000F /* Debug */,
|
||||
A5D100000000000000000010 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
|
||||
/* Begin XCLocalSwiftPackageReference section */
|
||||
A5D100000000000000000011 /* XCLocalSwiftPackageReference "../.." */ = {
|
||||
isa = XCLocalSwiftPackageReference;
|
||||
relativePath = ../..;
|
||||
};
|
||||
/* End XCLocalSwiftPackageReference section */
|
||||
|
||||
/* Begin XCSwiftPackageProductDependency section */
|
||||
A5D100000000000000000012 /* Lyrebird */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = A5D100000000000000000011 /* XCLocalSwiftPackageReference "../.." */;
|
||||
productName = Lyrebird;
|
||||
};
|
||||
/* End XCSwiftPackageProductDependency section */
|
||||
};
|
||||
rootObject = A5D100000000000000000001 /* Project object */;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"originHash" : "2c98cd4172bcfb3eff9cb6e34a538f80f5e424aa73fbd5bea2b20cf0c8b539b7",
|
||||
"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
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "2620"
|
||||
version = "1.7">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES"
|
||||
buildArchitectures = "Automatic">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "A5D10000000000000000000A"
|
||||
BuildableName = "LyrebirdScoreDemo"
|
||||
BlueprintName = "LyrebirdScoreDemo"
|
||||
ReferencedContainer = "container:LyrebirdScoreDemo.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 = "A5D10000000000000000000A"
|
||||
BuildableName = "LyrebirdScoreDemo"
|
||||
BlueprintName = "LyrebirdScoreDemo"
|
||||
ReferencedContainer = "container:LyrebirdScoreDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "A5D10000000000000000000A"
|
||||
BuildableName = "LyrebirdScoreDemo"
|
||||
BlueprintName = "LyrebirdScoreDemo"
|
||||
ReferencedContainer = "container:LyrebirdScoreDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -0,0 +1,11 @@
|
||||
// DemoProtocol.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
protocol DemoProtocol {
|
||||
func runDemo()
|
||||
}
|
||||
@@ -0,0 +1,693 @@
|
||||
// ScoreDemo.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Builds a multi-part Score using every DSL node type, exports MusicXML, round-trips
|
||||
/// the document, and reports render statistics.
|
||||
///
|
||||
/// Call ``buildAndReport()`` after construction to export MusicXML and print the
|
||||
/// round-trip summary. ``scheduleVoices(engine:)`` is marked ``@MainActor`` because
|
||||
/// ``ScoreVoice`` (a ``SynthesizerBase`` subclass) is ``@MainActor``-isolated; call it
|
||||
/// on the main thread before ``engine.start()``.
|
||||
final class ScoreDemo: DemoProtocol {
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Beats per minute for the demo score.
|
||||
static let bpm: Double = 108.0
|
||||
|
||||
/// Seconds per beat at the demo tempo.
|
||||
static let secondsPerBeat: Double = 60.0 / ScoreDemo.bpm
|
||||
|
||||
/// Extra render tail (seconds) to let the final release decay.
|
||||
static let tailSeconds: Double = 1.2
|
||||
|
||||
/// Pan position for lead-part voices (MIDI channel 0): slightly left.
|
||||
static let leadPan: Double = -0.4
|
||||
|
||||
/// Pan position for bass-part voices (other channels): slightly right.
|
||||
static let bassPan: Double = 0.5
|
||||
|
||||
/// Scale applied to a `ScoreEvent`'s normalized velocity to set voice amplitude.
|
||||
static let velocityToAmpScale: Double = 0.35
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
/// The score built at init time.
|
||||
let score: Score
|
||||
|
||||
/// Total render duration in seconds, including tail.
|
||||
let totalDuration: Double
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
init() {
|
||||
let builtScore: Score = ScoreDemo.makeScore()
|
||||
self.score = builtScore
|
||||
self.totalDuration = builtScore.totalBeats * ScoreDemo.secondsPerBeat
|
||||
+ ScoreDemo.tailSeconds
|
||||
}
|
||||
|
||||
// MARK: - DemoProtocol
|
||||
|
||||
/// Export MusicXML and print the round-trip event count. Does not interact with
|
||||
/// the engine or schedule any voices.
|
||||
func runDemo() {
|
||||
// Step 1 — write MusicXML to Desktop.
|
||||
let xmlURL: URL = FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent("Desktop/LyrebirdScoreDemo.musicxml")
|
||||
let xmlString: String = score.toMusicXMLString()
|
||||
do {
|
||||
try xmlString.write(to: xmlURL, atomically: true, encoding: .utf8)
|
||||
print("MusicXML written → \(xmlURL.path)")
|
||||
} catch {
|
||||
fputs("Failed to write MusicXML: \(error)\n", stderr)
|
||||
}
|
||||
|
||||
// Step 2 — round-trip sanity check.
|
||||
let xmlData: Data = score.toMusicXMLData()
|
||||
do {
|
||||
let rt: Score = try Score.fromMusicXML(data: xmlData)
|
||||
let originalCount: Int = score.allEvents.count
|
||||
let roundTripCount: Int = rt.allEvents.count
|
||||
print("Round-trip events: \(originalCount) → \(roundTripCount)")
|
||||
// Verify notation-only elements do not affect event count. Grace
|
||||
// notes (lead), clef changes (bass), staff grouping + sustain-pedal
|
||||
// marks (piano) are all skipped by flatten(), so the score's event
|
||||
// count must equal the round-tripped count.
|
||||
let selfConsistent: String = (originalCount == roundTripCount) ? "self-consistent" : "MISMATCH"
|
||||
print("Notation-only event count: \(selfConsistent)")
|
||||
// Verify tempo changes round-trip.
|
||||
let originalChanges: Int = score.tempoChanges.count
|
||||
let rtChanges: Int = rt.tempoChanges.count
|
||||
print("Round-trip tempo changes: \(originalChanges) → \(rtChanges)")
|
||||
if originalChanges == rtChanges {
|
||||
for (orig, recovered): (TempoChange, TempoChange) in zip(score.tempoChanges, rt.tempoChanges) {
|
||||
let measMatch: String = orig.measure == recovered.measure ? "OK" : "MISMATCH"
|
||||
let bpmMatch: String = abs(orig.bpm - recovered.bpm) < 0.001 ? "OK" : "MISMATCH"
|
||||
print(" TempoChange measure=\(orig.measure) \(measMatch) bpm=\(orig.bpm) \(bpmMatch)")
|
||||
}
|
||||
}
|
||||
// Verify per-part key override + transpose round-trip on the clarinet part.
|
||||
// Part order: 0=lead, 1=bass, 2=clarinet, 3=piano, 4=texture,
|
||||
// 5=timeline, 6=autovoice, 7=polymeter — so the clarinet is index 2.
|
||||
if rt.parts.count > 2 {
|
||||
let clarinet: ScorePart = rt.parts[2]
|
||||
let keyOK: String = (clarinet.keySignature == .aMajor) ? "OK" : "MISMATCH(\(String(describing: clarinet.keySignature)))"
|
||||
let transposeOK: String = (clarinet.transpose == .bFlat) ? "OK" : "MISMATCH(\(String(describing: clarinet.transpose)))"
|
||||
print("Clarinet part key override: \(keyOK)")
|
||||
print("Clarinet part transpose (bFlat): \(transposeOK)")
|
||||
print("Score key (G major): \(rt.keySignature == .gMajor ? "OK" : "MISMATCH(\(rt.keySignature))")")
|
||||
}
|
||||
} catch {
|
||||
fputs("MusicXML round-trip failed: \(error)\n", stderr)
|
||||
}
|
||||
|
||||
// Step 2b — sectioned showcase: multiple Sections assembled into one
|
||||
// score (continuous measure numbers + per-section rehearsal marks),
|
||||
// glissandi, slurs/hairpins, per-note display overrides, tacet fill,
|
||||
// and a landscape page layout. Section labels export as standard
|
||||
// <rehearsal> marks — system objects placed once above the top staff (tied
|
||||
// to the section, not an instrument line, and collision-free). Some editors
|
||||
// (e.g. Dorico) auto-sequence imported rehearsal marks as A, B, C and hide
|
||||
// the authored text; that is an editor display setting. The
|
||||
// `rehearsalMarksAsStaffText: true` option emits boxed <words> staff text
|
||||
// instead, but that attaches to a staff and can collide with notation.
|
||||
let showcase: Score = ScoreDemo.makeSectionedShowcase()
|
||||
let showcaseURL: URL = FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent("Desktop/LyrebirdScoreSections.musicxml")
|
||||
do {
|
||||
try showcase.toMusicXMLString().write(to: showcaseURL, atomically: true, encoding: .utf8)
|
||||
print("Sectioned showcase written → \(showcaseURL.path)")
|
||||
// Report the assembled measure span + rehearsal marks.
|
||||
let marks: [(measure: Int, label: String)] = showcase.rehearsalMarks
|
||||
.sorted { $0.key < $1.key }
|
||||
.map { (measure: $0.key, label: $0.value) }
|
||||
let markList: String = marks.map { "\($0.label)@m\($0.measure)" }.joined(separator: ", ")
|
||||
print("Sections → rehearsal marks: \(markList)")
|
||||
print("Sectioned showcase parts: \(showcase.parts.map { $0.name }.joined(separator: ", "))")
|
||||
} catch {
|
||||
fputs("Failed to write sectioned showcase: \(error)\n", stderr)
|
||||
}
|
||||
|
||||
// Step 3 — report render parameters.
|
||||
let displayBeats: Double = score.totalBeats
|
||||
let displayDur: Double = totalDuration
|
||||
print(
|
||||
String(
|
||||
format: "Score: %.1f beats at %.0f BPM → %.2f s render (+ %.2f s tail)",
|
||||
displayBeats,
|
||||
ScoreDemo.bpm,
|
||||
displayBeats * ScoreDemo.secondsPerBeat,
|
||||
ScoreDemo.tailSeconds
|
||||
)
|
||||
)
|
||||
print(String(format: "Total render: %.2f s", displayDur))
|
||||
}
|
||||
|
||||
// MARK: - Voice scheduling
|
||||
|
||||
/// Schedule one ``ScoreVoice`` per non-rest event against the engine.
|
||||
///
|
||||
/// Must be called on the main actor because ``ScoreVoice`` (a ``SynthesizerBase``
|
||||
/// subclass) is ``@MainActor``-isolated. Call this after constructing the engine
|
||||
/// but before ``engine.start()``.
|
||||
@MainActor
|
||||
func scheduleVoices(engine: SynthesisEngine) {
|
||||
let secondsPerBeat: Double = ScoreDemo.secondsPerBeat
|
||||
let allEvents: [ScoreEvent] = score.allEvents
|
||||
var scheduledCount: Int = 0
|
||||
var failedCount: Int = 0
|
||||
|
||||
for event: ScoreEvent in allEvents {
|
||||
guard !event.isRest else { continue }
|
||||
guard let freqHz: Double = event.pitch.frequency else { continue }
|
||||
|
||||
let startSeconds: Double = event.beat * secondsPerBeat
|
||||
let durSeconds: Double = event.performedDuration * secondsPerBeat
|
||||
|
||||
// Separate lead (slight left) from bass (slight right) by MIDI channel.
|
||||
let pan: Double = event.channel == 0 ? ScoreDemo.leadPan : ScoreDemo.bassPan
|
||||
|
||||
let voice: ScoreVoice = ScoreVoice(
|
||||
freqHz: freqHz,
|
||||
amp: event.velocity * ScoreDemo.velocityToAmpScale,
|
||||
durSeconds: durSeconds,
|
||||
pan: pan
|
||||
)
|
||||
|
||||
do {
|
||||
try engine.schedule(voice, after: startSeconds)
|
||||
scheduledCount += 1
|
||||
} catch {
|
||||
fputs("engine.schedule failed for beat \(event.beat): \(error)\n", stderr)
|
||||
failedCount += 1
|
||||
}
|
||||
}
|
||||
|
||||
print("Scheduled \(scheduledCount) voices\(failedCount > 0 ? ", \(failedCount) failed" : "").")
|
||||
}
|
||||
|
||||
// MARK: - Material-creation helpers
|
||||
//
|
||||
// Beyond hand-authoring notes, Lyrebird offers several ways to GENERATE score
|
||||
// material. These helpers feed the `timeline` and `autovoice` parts.
|
||||
// `ScoreTimeline` is throwing, so the `[ScoreElement]` is built here (outside
|
||||
// the non-throwing score result-builder) and dropped into a `Part { … }` body.
|
||||
|
||||
/// Place notes at explicit musical beats and let the timeline fill the rests.
|
||||
/// `BeatPosition.beat(_:)` is the felt-beat reading (4/4: beat 1 = downbeat,
|
||||
/// beat 5 = bar-2 downbeat). See ``ScoreTimeline`` / ``BeatPosition``.
|
||||
private static func makeTimelineMaterial() -> [ScoreElement] {
|
||||
do {
|
||||
return try ScoreTimeline.from(
|
||||
(.beat(1.0), Note(.named(.d, 5), dur: .quarter, dyn: .mp)),
|
||||
(.beat(5.0), Note(.named(.f, 5), dur: .quarter, dyn: .mp)),
|
||||
(.bar(2, beat: 3.0), Note(.named(.a, 5), dur: .half, dyn: .mf, art: .tenuto)),
|
||||
meter: MeterMap(.fourFour)
|
||||
)
|
||||
} catch {
|
||||
print("[ScoreDemo] timeline material failed: \(error)")
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/// Overlapping placements distributed across voices automatically — a held
|
||||
/// whole note under a moving line becomes two voices. See
|
||||
/// ``ScoreTimeline/fillAutoVoiced(_:)``.
|
||||
private static func makeAutoVoicedMaterial() -> [ScoreElement] {
|
||||
do {
|
||||
return try ScoreTimeline.fillAutoVoiced([
|
||||
(beat: 0.0, element: Note(.named(.c, 4), dur: .whole, dyn: .p)),
|
||||
(beat: 0.0, element: Note(.named(.e, 5), dur: .quarter, dyn: .mp)),
|
||||
(beat: 1.0, element: Note(.named(.f, 5), dur: .quarter, dyn: .mp)),
|
||||
(beat: 2.0, element: Note(.named(.g, 5), dur: .quarter, dyn: .mp)),
|
||||
(beat: 3.0, element: Note(.named(.e, 5), dur: .quarter, dyn: .mp)),
|
||||
])
|
||||
} catch {
|
||||
print("[ScoreDemo] auto-voiced material failed: \(error)")
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Score construction
|
||||
|
||||
/// Builds the demo score: eight parts, each chosen to exercise a different
|
||||
/// authoring path.
|
||||
///
|
||||
/// The hand-authored `lead` part is written **inline** below to show direct
|
||||
/// result-builder entry; every other part is built by its own `make…Part()`
|
||||
/// helper for clearer encapsulation. The parts, in document order:
|
||||
///
|
||||
/// - **`lead`** *(inline)* — 8-bar melody: crescendo/diminuendo hairpins, a
|
||||
/// triplet run, tied sixteenths, chords, a grace note (acciaccatura F♯5),
|
||||
/// and a nested 5:4 ⊃ 3:2 tuplet.
|
||||
/// - **`bass`** — sustained low line with double-stops, a mid-voice clef
|
||||
/// change (bass → tenor → bass), a walking eighth-note run, and a triplet
|
||||
/// fill. Hand-authored.
|
||||
/// - **`clarinet`** — transposing-instrument demo (B♭): per-part key
|
||||
/// override (A major) + `<transpose>`. Hand-authored.
|
||||
/// - **`piano`** — grand staff. Staff 1 (treble) carries two voices (an
|
||||
/// upper melody and a tied C-major triad); staff 2 (bass) carries a
|
||||
/// sustained whole-note C under a sustain-pedal marking.
|
||||
/// - **`texture`** — algorithmic generation via `Generate` (index-driven)
|
||||
/// and `PatternNotes` (a seeded Brownian MIDI walk).
|
||||
/// - **`timeline`** — notes placed at explicit `BeatPosition`s with rests
|
||||
/// auto-filled (`ScoreTimeline`).
|
||||
/// - **`autovoice`** — overlapping placements distributed across voices
|
||||
/// automatically (`ScoreTimeline.fillAutoVoiced`).
|
||||
/// - **`polymeter`** — runs in its OWN 3/4 meter while the score is 4/4
|
||||
/// (per-part `MeterMap`).
|
||||
///
|
||||
/// Score-level features layered over all parts: a forward/backward repeat
|
||||
/// with 1st/2nd endings (bars 1–4) and tempo changes at bar 3 (132 BPM) and
|
||||
/// bar 7 (80 BPM). Both are notation-only — playback uses the base tempo.
|
||||
private static func makeScore() -> Score {
|
||||
return Score(
|
||||
bpm: ScoreDemo.bpm,
|
||||
timeSignature: TimeSignature(4, 4),
|
||||
keySignature: .gMajor,
|
||||
// Repeat of bars 1–3 with first/second endings. The backward repeat
|
||||
// sits at the END of the first ending (bar 3) — the jump-back point.
|
||||
// On the repeat, the first ending (bar 3) is skipped and the second
|
||||
// ending (bar 4) plays straight through, so bar 4 has no repeat.
|
||||
repeats: RepeatStructure(
|
||||
forwardRepeatMeasures: [1],
|
||||
backwardRepeatMeasures: [3],
|
||||
endings: [
|
||||
Ending(number: 1, startMeasure: 3, stopMeasure: 3),
|
||||
Ending(number: 2, startMeasure: 4, stopMeasure: 4)
|
||||
]
|
||||
),
|
||||
// Tempo changes. Bar 3 accelerates to 132 BPM; bar 7 relaxes to 80
|
||||
// BPM. These are notation-only — playback still uses the base bpm
|
||||
// (108). A tempo change is emitted in every part that reaches that
|
||||
// measure: bar 3 exists in all parts (incl. the 4-bar piano), bar 7
|
||||
// only in the 8-bar lead/bass.
|
||||
tempoChanges: [
|
||||
TempoChange(measure: 3, bpm: 132.0),
|
||||
TempoChange(measure: 7, bpm: 80.0)
|
||||
],
|
||||
// Page layout — emitted as a MusicXML <defaults> block (US Letter,
|
||||
// portrait). Engravers honour the page size, orientation, margins,
|
||||
// and staff scaling on import.
|
||||
pageLayout: PageLayout(size: .letter, orientation: .portrait)
|
||||
) {
|
||||
// Lead melody — kept INLINE to demonstrate direct result-builder
|
||||
// entry. Every other part is built by a make…Part() helper below.
|
||||
// 8 bars covering dynamics, articulations, a grace note, and a
|
||||
// nested tuplet. Bars 1–2 include a Crescendo and Diminuendo hairpin.
|
||||
Part("lead") {
|
||||
// Bar 1 — arpeggiated C major with staccato, under a crescendo.
|
||||
// The high C6 also starts a slur that overlaps into bar 2 —
|
||||
// demonstrating a shared boundary where a slur-start and a
|
||||
// hairpin coexist on the same note via the spanners: parameter.
|
||||
Slur {
|
||||
Crescendo {
|
||||
Note(.named(.c, 5), dur: .quarter, dyn: .mf, art: .staccato)
|
||||
Note(.named(.e, 5), dur: .quarter, dyn: .mf, art: .staccato)
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .mf, art: .staccato)
|
||||
// spanners: [.beginSlur] opens a slur here while the Crescendo
|
||||
// block simultaneously marks this note with the wedge-start.
|
||||
// The two annotations are independent fields on the atom and
|
||||
// compose without conflict in MusicXML.
|
||||
Note(.named(.c, 6), dur: .quarter, dyn: .f, art: .accent)
|
||||
}
|
||||
}
|
||||
|
||||
// Bar 2 — triplet run followed by legato half note, under a diminuendo.
|
||||
// The slur started on the C6 above ends on the last triplet note (G5),
|
||||
// which lies inside the Diminuendo block — the slur overlaps the hairpin.
|
||||
Diminuendo {
|
||||
Tuplet(3, inTimeOf: 2) {
|
||||
Note(.named(.b, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.a, 5), dur: .quarter, dyn: .mp, spanners: [.beginSlur])
|
||||
// spanners: [.endSlur] closes the slur here. The Diminuendo
|
||||
// block's wedge-start is on the B5 triplet note; the slur-stop
|
||||
// lands on this G5 — overlapping spans, cleanly expressed.
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .mp,
|
||||
spanners: [.endSlur])
|
||||
}
|
||||
Note(.named(.f, 5), dur: .half, dyn: .p, art: .legato)
|
||||
}
|
||||
// Bar 3 — staccatissimo sixteenth notes, then tenuto half; the
|
||||
// first two sixteenths are tied (authored tie: sounds
|
||||
// as one eighth note but is notated as two tied sixteenths).
|
||||
Note(.named(.e, 5), dur: .sixteenth, dyn: .ff, art: .staccatissimo, tie: true)
|
||||
Note(.named(.e, 5), dur: .sixteenth, dyn: .ff)
|
||||
Note(.named(.g, 5), dur: .sixteenth, dyn: .ff, art: .staccatissimo)
|
||||
Note(.named(.a, 5), dur: .sixteenth, dyn: .ff, art: .staccatissimo)
|
||||
Note(.named(.b, 5), dur: .half, dyn: .f, art: .tenuto)
|
||||
Rest(dur: .quarter)
|
||||
|
||||
// Bar 4 — chord, rest, single note
|
||||
Chord([.named(.c, 5), .named(.e, 5), .named(.g, 5)], dur: .half, dyn: .f, art: .accent)
|
||||
Rest(dur: .quarter)
|
||||
// Note-display override: a diamond notehead (e.g. a harmonic).
|
||||
// Notation-only — the flattened event is unchanged.
|
||||
Note(.named(.d, 5), dur: .quarter, dyn: .mf,
|
||||
display: NoteDisplay(notehead: .diamond))
|
||||
// Bar 5 — grace note (acciaccatura F#5) before a nested tuplet.
|
||||
// Grace is notation-only; flatten() skips it and the
|
||||
// event count is identical to a score without the grace note.
|
||||
// The nested 5:4 ⊃ 3:2 tuplet demonstrates per-level
|
||||
// <tuplet-actual>/<tuplet-normal> bracket engraving.
|
||||
// Outer children: 3 quarters + inner(3 quarters × 2/3 = 2 quarter-slots)
|
||||
// = 5 quarter-slots × 4/5 outer scale = 4 beats. Fits the 4/4 bar.
|
||||
Grace(.named(.fSharp, 5))
|
||||
Tuplet(5, inTimeOf: 4) {
|
||||
Note(.named(.c, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.d, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.e, 5), dur: .quarter, dyn: .mp)
|
||||
Tuplet(3, inTimeOf: 2) {
|
||||
Note(.named(.f, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.gSharp, 5), dur: .quarter, dyn: .mp)
|
||||
}
|
||||
}
|
||||
|
||||
// Bar 6 — dotted quarter glissando down to the eighth, then a
|
||||
// legato half. The glissando is a two-note span authored via the
|
||||
// spanners: parameter (begin on A5, end on G5).
|
||||
Note(.named(.a, 5), dur: .quarter.dotted, dyn: .mf,
|
||||
spanners: [.beginGlissando(Glissando())])
|
||||
Note(.named(.g, 5), dur: .eighth, dyn: .mp, spanners: [.endGlissando])
|
||||
Note(.named(.fSharp, 5), dur: .half, dyn: .p, art: .legato)
|
||||
|
||||
// Bar 7 — marcato descent ppp
|
||||
Note(.named(.e, 5), dur: .quarter, dyn: .fff, art: .marcato)
|
||||
Note(.named(.d, 5), dur: .quarter, dyn: .ff)
|
||||
Note(.named(.c, 5), dur: .quarter, dyn: .f)
|
||||
Note(.named(.b, 4), dur: .quarter, dyn: .mf)
|
||||
|
||||
// Bar 8 — closing chord
|
||||
Chord([.named(.c, 5), .named(.e, 5), .named(.g, 5), .named(.c, 6)], dur: .whole, dyn: .pp, art: .tenuto)
|
||||
}
|
||||
|
||||
ScoreDemo.makeBassPart()
|
||||
ScoreDemo.makeClarinetPart()
|
||||
ScoreDemo.makePianoPart()
|
||||
ScoreDemo.makeTexturePart()
|
||||
ScoreDemo.makeTimelinePart()
|
||||
ScoreDemo.makeAutoVoicePart()
|
||||
ScoreDemo.makePolymeterPart()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Sectioned showcase
|
||||
|
||||
/// A second, self-contained score that demonstrates the section-based
|
||||
/// authoring stack: multiple ``ScoreSection`` blocks assembled into one
|
||||
/// score with continuous global measure numbers, per-section rehearsal
|
||||
/// marks, a tacet instrument auto-filled with rests, glissandi/slides,
|
||||
/// slurs and hairpins, an intra-note dynamic curve (messa di voce / niente
|
||||
/// swell), per-note display overrides, and a landscape page layout.
|
||||
///
|
||||
/// Two instruments — `flute` (id `fl`) and `cello` (id `vc`) — are matched
|
||||
/// across sections by `id`. Section labels are single letters (`A`, `B`, `C`):
|
||||
/// rehearsal marks are system objects that editors typically render as a
|
||||
/// sequence of letters, so single letters round-trip reliably while custom
|
||||
/// words may be re-sequenced or hidden. Three sections run sequentially:
|
||||
/// - **A** (4/4, 2 bars): flute states the theme under a slurred crescendo,
|
||||
/// then a niente messa-di-voce swell (`dynamicCurve`) over the bar-2 whole
|
||||
/// note; cello is TACET (auto-filled, stays bar-aligned).
|
||||
/// - **B** (3/4, 2 bars): flute plays a wavy glissando and an x-notehead /
|
||||
/// stemless note; cello enters with a straight `slide` glissando.
|
||||
/// - **C** (4/4, 2 bars): a diminuendo close, a large-notehead final note,
|
||||
/// sustained cello.
|
||||
private static func makeSectionedShowcase() -> Score {
|
||||
return Score(
|
||||
bpm: 96.0,
|
||||
keySignature: .cMajor,
|
||||
// Landscape A4 — emitted as a MusicXML <defaults> block.
|
||||
pageLayout: PageLayout(size: .a4, orientation: .landscape)
|
||||
) {
|
||||
Section("A") {
|
||||
Part("flute", clef: .treble, id: "fl") {
|
||||
Crescendo {
|
||||
Slur {
|
||||
Note(.named(.c, 5), dur: .quarter, dyn: .p)
|
||||
Note(.named(.d, 5), dur: .quarter)
|
||||
Note(.named(.e, 5), dur: .quarter)
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .mf)
|
||||
}
|
||||
}
|
||||
// Messa di voce on a single sustained note: a niente swell
|
||||
// ◦< f >◦ authored via `dynamicCurve`. The dynamics and the
|
||||
// crescendo/diminuendo hairpins (each closing on a niente
|
||||
// circle) ride inside this one whole note — no tied split. The
|
||||
// note's `dyn:` still drives playback velocity.
|
||||
Note(.named(.c, 5), dur: .whole, dyn: .mf,
|
||||
dynamicCurve: [(0.0, .niente), (0.5, .f), (1.0, .niente)])
|
||||
}
|
||||
// cello is tacet in section A — the lowering fills it with rests.
|
||||
}
|
||||
|
||||
Section("B", meterMap: MeterMap(.threeFour)) {
|
||||
Part("flute", clef: .treble, id: "fl") {
|
||||
// Wavy glissando E5 → B5 (two-note span via spanners:).
|
||||
Note(.named(.e, 5), dur: .quarter, dyn: .mf,
|
||||
spanners: [.beginGlissando(Glissando())])
|
||||
Note(.named(.b, 5), dur: .quarter, spanners: [.endGlissando])
|
||||
// x-notehead (ghost / percussive) — notation-only.
|
||||
Note(.named(.a, 5), dur: .quarter, display: NoteDisplay(notehead: .x))
|
||||
// Bar 2: legato half + a stemless note.
|
||||
Note(.named(.g, 5), dur: .half, dyn: .p, art: .legato)
|
||||
Note(.named(.fSharp, 5), dur: .quarter,
|
||||
display: NoteDisplay(hideStem: true))
|
||||
}
|
||||
Part("cello", clef: .bass, id: "vc") {
|
||||
// Straight slide glissando C3 → G3, dashed line.
|
||||
Note(.named(.c, 3), dur: .half.dotted, dyn: .mp,
|
||||
spanners: [.beginGlissando(Glissando(kind: .slide, lineType: .dashed))])
|
||||
Note(.named(.g, 3), dur: .half.dotted, spanners: [.endGlissando])
|
||||
}
|
||||
}
|
||||
|
||||
Section("C") {
|
||||
Part("flute", clef: .treble, id: "fl") {
|
||||
Diminuendo {
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .f)
|
||||
Note(.named(.e, 5), dur: .quarter)
|
||||
Note(.named(.c, 5), dur: .half, dyn: .pp, art: .legato)
|
||||
}
|
||||
// Final note with a large notehead (single pitch, not a chord).
|
||||
Note(.named(.c, 6), dur: .whole, dyn: .pp, art: .tenuto,
|
||||
display: NoteDisplay(size: .large))
|
||||
}
|
||||
Part("cello", clef: .bass, id: "vc") {
|
||||
Note(.named(.c, 3), dur: .whole, dyn: .mp)
|
||||
Note(.named(.c, 3), dur: .whole, dyn: .pp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Part-creation helpers
|
||||
|
||||
/// Bass line — sustained low harmonies with occasional double-stops, a
|
||||
/// mid-voice clef change (bass → tenor → bass), a walking eighth-note run,
|
||||
/// and a triplet fill. Single voice; carries Crescendo/Diminuendo-free
|
||||
/// material at the low end of the texture.
|
||||
private static func makeBassPart() -> ScorePart {
|
||||
Part("bass", channel: 1, clef: .bass) {
|
||||
// Bar 1 — low C whole note
|
||||
Note(.named(.c, 2), dur: .whole, dyn: .mp)
|
||||
|
||||
// Bar 2 — G pedal
|
||||
Note(.named(.g, 2), dur: .whole, dyn: .p)
|
||||
|
||||
// Bar 3 — half plus quarter, then quarter rest (sums to 4 beats)
|
||||
Note(.named(.a, 2), dur: .half, dyn: .mf)
|
||||
Note(.named(.e, 2), dur: .quarter, dyn: .p)
|
||||
Rest(dur: .quarter)
|
||||
|
||||
// Bar 4 — double-stop chords
|
||||
Chord([.named(.f, 2), .named(.c, 3)], dur: .half, dyn: .mp)
|
||||
Chord([.named(.d, 2), .named(.a, 2)], dur: .half, dyn: .mp)
|
||||
|
||||
// Mid-voice clef change: switch to tenor clef for the
|
||||
// walking line so it reads with fewer ledger lines, then switch
|
||||
// back to bass for the low pedal in bar 6. Display-only — sounding
|
||||
// pitches are unchanged.
|
||||
ClefChange(.tenor)
|
||||
// Bar 5 — walking eighth-note bass line
|
||||
Note(.named(.c, 3), dur: .eighth, dyn: .mf)
|
||||
Note(.named(.d, 3), dur: .eighth, dyn: .mp)
|
||||
Note(.named(.e, 3), dur: .eighth, dyn: .mp)
|
||||
Note(.named(.f, 3), dur: .eighth, dyn: .mp)
|
||||
Note(.named(.g, 3), dur: .eighth, dyn: .mf)
|
||||
Note(.named(.a, 3), dur: .eighth, dyn: .mp)
|
||||
Note(.named(.b, 3), dur: .eighth, dyn: .mp)
|
||||
Note(.named(.c, 4), dur: .eighth, dyn: .mf)
|
||||
|
||||
ClefChange(.bass)
|
||||
// Bar 6 — pedal half + triplet fill
|
||||
Note(.named(.g, 2), dur: .half, dyn: .mp, art: .tenuto)
|
||||
Tuplet(3, inTimeOf: 2) {
|
||||
Note(.named(.f, 2), dur: .quarter, dyn: .p)
|
||||
Note(.named(.e, 2), dur: .quarter, dyn: .p)
|
||||
Note(.named(.d, 2), dur: .quarter, dyn: .p)
|
||||
}
|
||||
|
||||
// Bar 7 — marcato accent descent
|
||||
Note(.named(.e, 2), dur: .quarter, dyn: .ff, art: .marcato)
|
||||
Note(.named(.d, 2), dur: .quarter, dyn: .f, art: .staccato)
|
||||
Note(.named(.c, 2), dur: .half, dyn: .mf)
|
||||
|
||||
// Bar 8 — final bass chord (ppp close)
|
||||
Chord([.named(.c, 2), .named(.g, 2), .named(.c, 3)], dur: .whole, dyn: .ppp)
|
||||
}
|
||||
}
|
||||
|
||||
/// B♭ clarinet — transposing-instrument demonstration.
|
||||
/// Score key: G major. Clarinet written key: A major (a major 2nd up,
|
||||
/// because a B♭ instrument reads a major 2nd higher than concert pitch).
|
||||
/// transpose: .bFlat → <transpose><diatonic>-1</diatonic><chromatic>-2</chromatic></transpose>.
|
||||
/// Flatten returns these AS WRITTEN pitches; concert-pitch playback is future work.
|
||||
/// Single voice.
|
||||
private static func makeClarinetPart() -> ScorePart {
|
||||
Part("clarinet", channel: 3, clef: .treble, keySignature: .aMajor, transpose: .bFlat) {
|
||||
// Bar 1 — ascending A major scale fragment (written; sounds G major)
|
||||
Note(.named(.a, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.b, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.cSharp, 6), dur: .quarter, dyn: .mf)
|
||||
Note(.named(.d, 6), dur: .quarter, dyn: .mf)
|
||||
|
||||
// Bar 2 — descending to tonic (written A5, sounds G5)
|
||||
Note(.named(.e, 6), dur: .quarter, dyn: .mf)
|
||||
Note(.named(.d, 6), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.cSharp, 6), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.a, 5), dur: .quarter, dyn: .p)
|
||||
}
|
||||
}
|
||||
|
||||
/// Piano — a grand staff demonstrating multi-staff notation.
|
||||
///
|
||||
/// Staff 1 (treble) holds two independent voices:
|
||||
/// - **Voice 1** — a 4-bar melodic fragment.
|
||||
/// - **Voice 2** — sustained chord tones that overlay from beat 0; bars 1–2
|
||||
/// tie a C-major triad (C4–E4–G4) across the barline so all three pitches
|
||||
/// sustain.
|
||||
/// Staff 2 (bass) holds **Voice 3** — a sustained whole-note C under a
|
||||
/// sustain-pedal marking (pedal down before the note, released after it).
|
||||
///
|
||||
/// In MusicXML this encodes as one part with `<staves>2</staves>`, a
|
||||
/// `<clef number="1">` (treble) / `<clef number="2">` (bass) pair, a
|
||||
/// `<staff>` element on every note, `<backup>` between the three voices,
|
||||
/// and `<pedal>` start/stop directions attached to staff 2.
|
||||
private static func makePianoPart() -> ScorePart {
|
||||
Part("piano", channel: 2, clef: .treble) {
|
||||
Staff(1) {
|
||||
Voice(1) {
|
||||
// Bar 1 — stepwise ascent
|
||||
Note(.named(.c, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.d, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.e, 5), dur: .quarter, dyn: .mf)
|
||||
Note(.named(.f, 5), dur: .quarter, dyn: .mf)
|
||||
|
||||
// Bar 2 — triplet decoration with a half note landing
|
||||
Tuplet(3, inTimeOf: 2) {
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .mf)
|
||||
Note(.named(.a, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .mp)
|
||||
}
|
||||
Note(.named(.f, 5), dur: .half, dyn: .p, art: .legato)
|
||||
|
||||
// Bar 3 — eighth-note run with staccato
|
||||
Note(.named(.e, 5), dur: .eighth, dyn: .f, art: .staccato)
|
||||
Note(.named(.d, 5), dur: .eighth, dyn: .f, art: .staccato)
|
||||
Note(.named(.c, 5), dur: .eighth, dyn: .mf, art: .staccato)
|
||||
Note(.named(.d, 5), dur: .eighth, dyn: .mf, art: .staccato)
|
||||
Note(.named(.e, 5), dur: .half, dyn: .p, art: .tenuto)
|
||||
|
||||
// Bar 4 — closing whole note
|
||||
Note(.named(.c, 5), dur: .whole, dyn: .pp)
|
||||
}
|
||||
Voice(2) {
|
||||
// Bar 1 — sustained C major triad tied to bar 2 (chord tie).
|
||||
// The two identical chords sustain as one across the barline.
|
||||
Chord([.named(.c, 4), .named(.e, 4), .named(.g, 4)], dur: .whole, dyn: .mp, tie: true)
|
||||
|
||||
// Bar 2 — same C major triad (tie target: merges with bar 1 above)
|
||||
Chord([.named(.c, 4), .named(.e, 4), .named(.g, 4)], dur: .whole, dyn: .mp)
|
||||
|
||||
// Bar 3 — A minor
|
||||
Chord([.named(.a, 3), .named(.c, 4), .named(.e, 4)], dur: .whole, dyn: .mp)
|
||||
|
||||
// Bar 4 — close on C major
|
||||
Chord([.named(.c, 4), .named(.e, 4), .named(.g, 4)], dur: .whole, dyn: .pp)
|
||||
}
|
||||
}
|
||||
Staff(2, clef: .bass) {
|
||||
Voice(3) {
|
||||
// Bar 1 — sustained bass C under the sustain pedal. Pedal
|
||||
// down before the note, released after; both pedal marks are
|
||||
// notation-only (skipped by flatten(), no ScoreEvent).
|
||||
Pedal(.start)
|
||||
Note(.named(.c, 3), dur: .whole, dyn: .mp)
|
||||
Pedal(.stop)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Texture — algorithmic note generation. Demonstrates the two generative
|
||||
/// helpers, both returning `[ScoreElement]` that drops straight into the Part
|
||||
/// body via the result builder.
|
||||
private static func makeTexturePart() -> ScorePart {
|
||||
Part("texture", channel: 4, clef: .treble) {
|
||||
// `Generate` maps each index 0..<8 through the builder closure —
|
||||
// here a sixteenth-note whole-tone fragment driven by the index.
|
||||
Generate(8) { i in
|
||||
Note(midi: 72 + (i % 6) * 2, dur: .sixteenth, dyn: .pp, art: .staccato)
|
||||
}
|
||||
// `PatternNotes` pulls pitches and rhythms from `Pattern` value
|
||||
// sources: a seeded Brownian MIDI walk for pitch, a repeating
|
||||
// eighth/eighth/quarter cell for rhythm. Stops early if the pitch
|
||||
// pattern exhausts before `count`.
|
||||
PatternNotes(
|
||||
count: 12,
|
||||
midi: Pattern.brownian(low: 60.0, high: 84.0, step: 4.0, length: 12, seed: 42),
|
||||
durations: Pattern.sequence([.eighth, .eighth, .quarter]),
|
||||
dyn: .p
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Timeline — notes placed at explicit musical beats (`BeatPosition`), with
|
||||
/// rests auto-filled by `ScoreTimeline`. Material built in
|
||||
/// ``makeTimelineMaterial()`` (`ScoreTimeline` is throwing). Single voice.
|
||||
private static func makeTimelinePart() -> ScorePart {
|
||||
let material: [ScoreElement] = ScoreDemo.makeTimelineMaterial()
|
||||
return Part("timeline", channel: 5, clef: .treble) {
|
||||
material
|
||||
}
|
||||
}
|
||||
|
||||
/// Auto-voiced — overlapping placements distributed across voices
|
||||
/// automatically (a held whole note + a moving line → two voices). Material
|
||||
/// built in ``makeAutoVoicedMaterial()``.
|
||||
private static func makeAutoVoicePart() -> ScorePart {
|
||||
let material: [ScoreElement] = ScoreDemo.makeAutoVoicedMaterial()
|
||||
return Part("autovoice", channel: 6, clef: .treble) {
|
||||
material
|
||||
}
|
||||
}
|
||||
|
||||
/// Polymeter — this part runs in its OWN 3/4 meter while the rest of the
|
||||
/// score is 4/4. Per-part `meterMap` → independent barlines; the encoder
|
||||
/// renders each part against its own meter. Single voice.
|
||||
private static func makePolymeterPart() -> ScorePart {
|
||||
Part("polymeter", channel: 7, clef: .bass, meterMap: MeterMap(.threeFour)) {
|
||||
for _: Int in 0..<6 {
|
||||
Note(.named(.g, 2), dur: .quarter, dyn: .mp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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>LyrebirdScoreDemo writes rendered audio and MusicXML files to the Desktop.</string>
|
||||
<key>NSDocumentsFolderUsageDescription</key>
|
||||
<string>LyrebirdScoreDemo 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,76 @@
|
||||
// ScoreVoice.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A self-terminating NRT voice driven by a ``ScoreEvent``.
|
||||
///
|
||||
/// Plays a sawtooth oscillator through a percussive amplitude envelope. The
|
||||
/// envelope runs to completion and frees the synthesizer node automatically
|
||||
/// via ``DoneAction/freeNode``, so voices do not pile up during NRT render.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freqHz: Fundamental frequency in Hz. Stays within audible range; no internal clamping.
|
||||
/// - amp: Linear amplitude in `[0, 1]` — maps directly from ``ScoreEvent/velocity``.
|
||||
/// - durSeconds: Played duration in seconds. The sustain stage occupies the bulk of this
|
||||
/// duration; a fixed 10 ms attack and 60 ms release are subtracted first. If
|
||||
/// `durSeconds` is very short (< 70 ms), the sustain collapses to zero and the voice
|
||||
/// becomes purely percussive.
|
||||
/// - pan: Stereo position in `[-1, 1]`. Default `0.0` (centre).
|
||||
final class ScoreVoice: SynthesizerBase {
|
||||
|
||||
/// Fundamental frequency in Hz. No internal clamping; stay within audible range.
|
||||
let freqHz: Double
|
||||
|
||||
/// Linear amplitude in `[0, 1]`, from the score event's normalized velocity.
|
||||
let amp: Double
|
||||
|
||||
/// Played duration in seconds — determines sustain stage length.
|
||||
let durSeconds: Double
|
||||
|
||||
/// Stereo pan position in `[-1, 1]`.
|
||||
let pan: Double
|
||||
|
||||
/// Fixed attack duration in seconds.
|
||||
private static let attackSeconds: Double = 0.01
|
||||
|
||||
/// Fixed release duration in seconds.
|
||||
private static let releaseSeconds: Double = 0.06
|
||||
|
||||
init(
|
||||
freqHz: Double,
|
||||
amp: Double,
|
||||
durSeconds: Double,
|
||||
pan: Double = 0.0
|
||||
) {
|
||||
self.freqHz = freqHz
|
||||
self.amp = amp
|
||||
self.durSeconds = durSeconds
|
||||
self.pan = pan
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
let attack: Double = ScoreVoice.attackSeconds
|
||||
let release: Double = ScoreVoice.releaseSeconds
|
||||
let sustainSeconds: Double = max(0.0, durSeconds - attack - release)
|
||||
|
||||
let envelope: Envelope = Envelope(
|
||||
levels: [0.0, 1.0, 0.8, 0.0],
|
||||
durations: [attack, sustainSeconds, release],
|
||||
curves: [-4.0, 0.0, -6.0]
|
||||
)
|
||||
|
||||
// Sawtooth oscillator scaled by envelope and amplitude.
|
||||
let osc: OscSawtooth.Audio = OscSawtooth.Audio(freq: freqHz)
|
||||
let env: EnvelopeGen.Control = EnvelopeGen.Control(
|
||||
envelope: envelope,
|
||||
doneAction: .freeNode
|
||||
)
|
||||
let sig: any ValidGeneratorInput = osc * env * amp
|
||||
output(bus: 0, source: Pan2(input: sig, pan: pan))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// main.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// Output paths — both land on the Desktop.
|
||||
let cafURL: URL = FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent("Desktop/LyrebirdScoreDemo.caf")
|
||||
|
||||
// Render parameters.
|
||||
let sampleRate: Double = 48000
|
||||
let blockSize: Int = 512
|
||||
|
||||
// Build the score first — totalDuration must be known before NRTDriver is created.
|
||||
let demo: ScoreDemo = ScoreDemo()
|
||||
let totalDuration: Double = demo.totalDuration
|
||||
|
||||
// MusicXML export and round-trip before audio engine creation.
|
||||
demo.runDemo()
|
||||
|
||||
// Create NRTDriver and engine.
|
||||
let driver: NRTDriver = NRTDriver(outputURL: cafURL, duration: totalDuration)
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: blockSize,
|
||||
sampleRate: sampleRate,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: driver
|
||||
)
|
||||
|
||||
// Schedule all score voices. SynthesizerBase (and thus scheduleVoices) is
|
||||
// @MainActor-isolated; SwiftPM's top-level entry point is itself main-actor
|
||||
// isolated, so this is a plain direct call — no MainActor hop needed.
|
||||
demo.scheduleVoices(engine: engine)
|
||||
|
||||
print(String(format: "Rendering %.2f s → %@", totalDuration, cafURL.path))
|
||||
|
||||
do {
|
||||
try engine.start()
|
||||
print("Done.")
|
||||
} catch {
|
||||
fputs("Render failed: \(error)\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"originHash" : "4acd68de25440f1fcc60a86a69d66a0516f6e9d4f2d769aaab597e24b64fd245",
|
||||
"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: "LyrebirdScoreDemo",
|
||||
platforms: [.macOS(.v15)],
|
||||
dependencies: [
|
||||
.package(path: "../.."),
|
||||
],
|
||||
targets: [
|
||||
.executableTarget(
|
||||
name: "LyrebirdScoreDemo",
|
||||
dependencies: [
|
||||
.product(name: "Lyrebird", package: "Lyrebird"),
|
||||
],
|
||||
path: "LyrebirdScoreDemo"
|
||||
),
|
||||
]
|
||||
)
|
||||
@@ -9,9 +9,10 @@
|
||||
/* Begin PBXBuildFile section */
|
||||
C8D0000000000000000000C /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000007 /* main.swift */; };
|
||||
C8D0000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000008 /* AppDelegate.swift */; };
|
||||
C8D0000000000000000000F /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdUI */; };
|
||||
C8D00000000000000000021 /* LyrebirdLiveCompile in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001F /* LyrebirdLiveCompile */; };
|
||||
C8D00000000000000000022 /* LyrebirdLiveCompileUI in Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUI */; };
|
||||
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; };
|
||||
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; };
|
||||
C8D00000000000000000036 /* LyrebirdDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
|
||||
C8D00000000000000000034 /* LyrebirdLiveCompileUIDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
@@ -27,14 +28,28 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
C8D0000000000000000000F /* LyrebirdUI in Frameworks */,
|
||||
C8D00000000000000000021 /* LyrebirdLiveCompile in Frameworks */,
|
||||
C8D00000000000000000022 /* LyrebirdLiveCompileUI in Frameworks */,
|
||||
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */,
|
||||
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
C8D00000000000000000035 /* Embed Frameworks */ = {
|
||||
isa = PBXCopyFilesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
dstPath = "";
|
||||
dstSubfolderSpec = 10;
|
||||
files = (
|
||||
C8D00000000000000000036 /* LyrebirdDynamic in Embed Frameworks */,
|
||||
C8D00000000000000000034 /* LyrebirdLiveCompileUIDynamic in Embed Frameworks */,
|
||||
);
|
||||
name = "Embed Frameworks";
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
C8D00000000000000000002 = {
|
||||
isa = PBXGroup;
|
||||
@@ -73,6 +88,7 @@
|
||||
C8D00000000000000000011 /* Sources */,
|
||||
C8D00000000000000000012 /* Frameworks */,
|
||||
C8D00000000000000000013 /* Resources */,
|
||||
C8D00000000000000000035 /* Embed Frameworks */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
@@ -80,9 +96,8 @@
|
||||
);
|
||||
name = LyrebirdScratchDemo;
|
||||
packageProductDependencies = (
|
||||
C8D0000000000000000001D /* LyrebirdUI */,
|
||||
C8D0000000000000000001F /* LyrebirdLiveCompile */,
|
||||
C8D00000000000000000020 /* LyrebirdLiveCompileUI */,
|
||||
C8D0000000000000000001D /* LyrebirdDynamic */,
|
||||
C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */,
|
||||
);
|
||||
productName = LyrebirdScratchDemo;
|
||||
productReference = C8D00000000000000000004 /* LyrebirdScratchDemo.app */;
|
||||
@@ -248,6 +263,10 @@
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
// Xcode 26 explicit-module-build regression: SPM dynamic-library
|
||||
// framework binaries (LyrebirdDynamic / LyrebirdLiveCompileUIDynamic)
|
||||
// are not emitted under the integrated driver. Classic driver fixes it.
|
||||
SWIFT_USE_INTEGRATED_DRIVER = NO;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -303,6 +322,8 @@
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
// Xcode 26 explicit-module-build regression — see Debug config.
|
||||
SWIFT_USE_INTEGRATED_DRIVER = NO;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
@@ -341,20 +362,15 @@
|
||||
/* End XCLocalSwiftPackageReference section */
|
||||
|
||||
/* Begin XCSwiftPackageProductDependency section */
|
||||
C8D0000000000000000001D /* LyrebirdUI */ = {
|
||||
C8D0000000000000000001D /* LyrebirdDynamic */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = C8D0000000000000000001B /* XCLocalSwiftPackageReference "../.." */;
|
||||
productName = LyrebirdUI;
|
||||
productName = LyrebirdDynamic;
|
||||
};
|
||||
C8D0000000000000000001F /* LyrebirdLiveCompile */ = {
|
||||
C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = C8D0000000000000000001E /* XCLocalSwiftPackageReference "../../LiveCompile" */;
|
||||
productName = LyrebirdLiveCompile;
|
||||
};
|
||||
C8D00000000000000000020 /* LyrebirdLiveCompileUI */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = C8D0000000000000000001E /* XCLocalSwiftPackageReference "../../LiveCompile" */;
|
||||
productName = LyrebirdLiveCompileUI;
|
||||
productName = LyrebirdLiveCompileUIDynamic;
|
||||
};
|
||||
/* End XCSwiftPackageProductDependency section */
|
||||
};
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"originHash" : "52fa7c84ca46dcb1ce0f4374a4fb0a5d2c97be57f306d91b8e9efb54af7c3c9e",
|
||||
"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
|
||||
}
|
||||
@@ -7,18 +7,28 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
import LyrebirdLiveCompile
|
||||
// LyrebirdLiveCompile (LiveSession, …) is re-exported by LyrebirdLiveCompileUI.
|
||||
import LyrebirdLiveCompileUI
|
||||
|
||||
// This demo deliberately does NOT link `LyrebirdUI`. The live-compile stack
|
||||
// (`LyrebirdLiveCompileUIDynamic`) dynamic-links the single shared
|
||||
// `LyrebirdDynamic.framework` copy of `LyrebirdSynth`; linking the static
|
||||
// `LyrebirdUI` product would static-fold a SECOND copy of every `LyrebirdSynth`
|
||||
// ObjC class into the app binary (intra-package `LyrebirdUI → LyrebirdSynth` is
|
||||
// always a static edge), producing duplicate-class registration and the
|
||||
// "mysterious crashes" the runtime warns about. The only `LyrebirdUI` symbol
|
||||
// this demo used was `LyrebirdWindow`, an `NSWindow`/`NSHostingController`
|
||||
// wrapper with no `LyrebirdSynth` dependency — inlined below instead.
|
||||
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
let session: LiveSession
|
||||
var model: LyrebirdScratchModel?
|
||||
var menuController: LyrebirdScratchMenuController?
|
||||
var window: LyrebirdWindow?
|
||||
var window: NSWindow?
|
||||
|
||||
@MainActor
|
||||
init(engine: SynthesisEngine) {
|
||||
self.engine = engine
|
||||
self.session = LiveSession(engine: engine)
|
||||
@@ -32,20 +42,30 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
print("[LyrebirdScratchDemo] Engine failed to start: \(error)")
|
||||
}
|
||||
|
||||
let model = LyrebirdScratchModel(session: session)
|
||||
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session)
|
||||
self.model = model
|
||||
let menuController = LyrebirdScratchMenuController(model: model)
|
||||
let menuController: LyrebirdScratchMenuController = LyrebirdScratchMenuController(model: model)
|
||||
menuController.installMainMenu()
|
||||
self.menuController = menuController
|
||||
|
||||
window = LyrebirdWindow(
|
||||
title: "Lyrebird — Live Scratch",
|
||||
width: 720,
|
||||
height: 560
|
||||
let windowWidth: CGFloat = 720
|
||||
let windowHeight: CGFloat = 560
|
||||
let hosting: NSHostingController<LyrebirdScratchView> =
|
||||
NSHostingController(rootView: LyrebirdScratchView(model: model))
|
||||
let initialSize: CGSize = CGSize(width: windowWidth, height: windowHeight)
|
||||
let win: NSWindow = NSWindow(
|
||||
contentRect: NSRect(origin: .zero, size: initialSize),
|
||||
styleMask: [.titled, .closable, .resizable, .miniaturizable],
|
||||
backing: .buffered,
|
||||
defer: false
|
||||
)
|
||||
window?.open {
|
||||
LyrebirdScratchView(model: model)
|
||||
}
|
||||
// Keep ownership in Swift — NSWindow defaults to releasing on close.
|
||||
win.isReleasedWhenClosed = false
|
||||
win.title = "Lyrebird — Live Scratch"
|
||||
win.contentViewController = hosting
|
||||
win.center()
|
||||
win.makeKeyAndOrderFront(nil)
|
||||
self.window = win
|
||||
}
|
||||
|
||||
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
|
||||
This app is a direct-distribution developer tool, not a Mac App Store
|
||||
submission. Sandbox OFF is the only viable configuration for v1.
|
||||
Phase 147 polish can revisit if an XPC-worker approach is adopted.
|
||||
This could be revisited if an XPC-worker approach is adopted.
|
||||
|
||||
com.apple.security.app-sandbox key is absent (defaults false).
|
||||
-->
|
||||
|
||||
@@ -6,9 +6,8 @@
|
||||
|
||||
import AppKit
|
||||
import LyrebirdSynth
|
||||
import LyrebirdLiveCompile
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
sampleRate: 48000,
|
||||
numOutputChannels: 2,
|
||||
@@ -16,8 +15,14 @@ let engine = SynthesisEngine(
|
||||
driver: CoreAudioDriver()
|
||||
)
|
||||
|
||||
let delegate = AppDelegate(engine: engine)
|
||||
let app = NSApplication.shared
|
||||
app.setActivationPolicy(.regular)
|
||||
app.delegate = delegate
|
||||
app.run()
|
||||
// AppDelegate.init is `@MainActor` (mirrors the other demos' bootstrap — since
|
||||
// `SynthesizerBase` is `@MainActor`, AppKit-side construction is main-actor
|
||||
// isolated). Program entry runs on the main thread, so assert main-actor
|
||||
// isolation for the AppKit bootstrap rather than hopping asynchronously.
|
||||
MainActor.assumeIsolated {
|
||||
let delegate: AppDelegate = AppDelegate(engine: engine)
|
||||
let app: NSApplication = NSApplication.shared
|
||||
app.setActivationPolicy(.regular)
|
||||
app.delegate = delegate
|
||||
app.run()
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ private let demo: Demo = .vector
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
@main
|
||||
@MainActor
|
||||
struct LyrebirdiOSDemoApp: App {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
|
||||
@@ -13,6 +13,7 @@ import LyrebirdSynth
|
||||
/// first taps "Start Synthesizer" — this is necessary because
|
||||
/// `SpectralBinDelayUI.init(sampleRate:)` requires the engine's committed
|
||||
/// sample rate, which is only valid after `engine.start()` returns.
|
||||
@MainActor
|
||||
@Observable
|
||||
final class BinDelayController {
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import Observation
|
||||
import LyrebirdSynth
|
||||
|
||||
@MainActor
|
||||
@Observable
|
||||
final class NoteController {
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import Observation
|
||||
import LyrebirdSynth
|
||||
|
||||
@MainActor
|
||||
@Observable
|
||||
final class VectorOscillatorController {
|
||||
|
||||
|
||||
+102
-6
@@ -100,14 +100,25 @@ Full reference: [`docs/tooling/cli-guide.md`](docs/tooling/cli-guide.md).
|
||||
|
||||
## Generating projects
|
||||
|
||||
**First sound in 30 seconds** — the `quickstart` template is the shortest path from an installed CLI to audio:
|
||||
|
||||
```bash
|
||||
lyrebird new MyFirstSound --template quickstart
|
||||
cd MyFirstSound && lyrebird run # plays a 440 Hz sine for 10 seconds, then exits
|
||||
```
|
||||
|
||||
That's a complete, self-contained Swift Package: a one-oscillator `SineTone`, the engine, and a `main` that starts it, sleeps 10 seconds, and stops. Read it, then reach for the richer templates below.
|
||||
|
||||
`lyrebird new <name> --template <template>` is the single entry point. The templates fall into two groups: **SPM-only** (a `Package.swift` + an `.xcworkspace` that references it — open and run with `swift`/Xcode, no `.xcodeproj`) and **Xcode-project** (ship a real `.xcodeproj`, needed for `.app`/`.appex` bundles, code signing, and iOS).
|
||||
|
||||
| Template | Group | What you get | Driver |
|
||||
|---|---|---|---|
|
||||
| `basic` *(default)* | SPM-only | Minimal engine + `RunLoop.main.run()`. | `CoreAudioDriver` |
|
||||
| `quickstart` | SPM-only | **Fastest sound.** A one-oscillator `SineTone` that plays a 440 Hz tone for 10 seconds and exits — the shortest path to hearing Lyrebird. | `CoreAudioDriver` |
|
||||
| `basic` *(default)* | SPM-only | Minimal engine + `RunLoop.main.run()` (no synth wired yet). | `CoreAudioDriver` |
|
||||
| `demo` | SPM-only | A `SineTone` synth with `@LiveParam` frequency/amplitude. | `CoreAudioDriver` |
|
||||
| `ui-demo` | SPM-only | AppKit window with `@UIParam` knobs + `LyrebirdWindow`. | `CoreAudioDriver` |
|
||||
| `nrt` | SPM-only | Renders to `output.caf`, no hardware needed. | `NRTDriver` |
|
||||
| `score` | SPM-only | Authors a `Score` with the notation DSL, exports `score.musicxml` (round-trips it), then renders the events offline to `.caf`. | `NRTDriver` |
|
||||
| `macos-ui-xcode` | Xcode-project | macOS `.app` bundle (AppKit + SwiftUI), hardened runtime. | `CoreAudioDriver` |
|
||||
| `ios-ui` | Xcode-project | iOS `.app` (SwiftUI), with `AVAudioSession` activation. | `iOSAudioDriver` (RemoteIO) |
|
||||
| `auv3` | Xcode-project | AUv3 host `.app` + `aumu` `.appex` subclassing `LyrebirdAudioUnit`. | `AUv3Driver` |
|
||||
@@ -120,7 +131,9 @@ open <name>/<name>.xcworkspace # SPM-only & Xcode-project templates both shi
|
||||
cd <name> && lyrebird run
|
||||
```
|
||||
|
||||
To develop against a local Lyrebird checkout instead of the remote URL (path dependency + an `XCLocalSwiftPackageReference` in the generated project):
|
||||
**Lyrebird dependency, default behaviour.** When run from a Lyrebird source checkout (e.g. `swift run LyrebirdCLI new …`), the scaffolder pins the generated project to *that same checkout* as a `path:` dependency (and an `XCLocalSwiftPackageReference` in Xcode-bearing templates). This keeps the emitted template source and the Lyrebird it builds against in lockstep — pre-1.0-stable, the published tag lags unreleased Score/Generator API. The CLI prints the chosen dependency, e.g. `Lyrebird dependency: local checkout at /Users/me/Documents/LyrebirdII`. If no local checkout is derivable (an installed binary with no source tree), it falls back to the published remote package and warns.
|
||||
|
||||
Override the checkout explicitly with `--lyrebird-path`:
|
||||
|
||||
```bash
|
||||
lyrebird new <name> --template <t> --lyrebird-path /Users/me/Documents/LyrebirdII
|
||||
@@ -167,9 +180,9 @@ import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
struct ContentView: View {
|
||||
@StateObject var synth = ToneSynth() // ToneSynth: SynthesizerBase with @UIParam
|
||||
let synth: ToneSynth // ToneSynth: SynthesizerBase with @UIParam
|
||||
var body: some View {
|
||||
ParameterKnob(value: synth.$frequency, in: 50...2000, label: "Freq")
|
||||
ParameterKnob("Freq", node: synth.$frequency, range: 50...2000)
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -246,11 +259,92 @@ open MyApp/MyApp.xcworkspace # set your signing team, then run on device/si
|
||||
|
||||
The iOS template uses `iOSAudioDriver` (RemoteIO) and activates an `AVAudioSession` at launch; the synth/UI code is otherwise identical to the macOS UI template. The reference app is [`Demos/LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/).
|
||||
|
||||
### 6. Score / notation (MusicXML + offline render)
|
||||
|
||||
```bash
|
||||
lyrebird new MyScore --template score # aliases: score-musicxml, musicxml
|
||||
cd MyScore && lyrebird run # writes score.musicxml, round-trips it, renders .caf
|
||||
```
|
||||
|
||||
The `score` template authors music in the language-side **Score DSL** — a result-builder of `Note` / `Rest` / `Chord` / `Tuplet` with exact rational tuplet math (no float drift across nested ratios), spelling-aware pitches (`Note(.named(.c, 5))`), dynamics, and articulations. It exports MusicXML, parses it back for a round-trip sanity check, then schedules one self-freeing voice per `ScoreEvent` against an `NRTDriver`:
|
||||
|
||||
```swift
|
||||
import LyrebirdSynth
|
||||
|
||||
let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
|
||||
Part("lead") {
|
||||
Note(.named(.c, 5), dur: .quarter, dyn: .mf, art: .staccato)
|
||||
Note(.named(.e, 5), dur: .eighth.dotted, dyn: .mf)
|
||||
Rest(dur: .eighth)
|
||||
Tuplet(3, inTimeOf: 2) {
|
||||
Note(.named(.g, 5), dur: .quarter)
|
||||
Note(.named(.a, 5), dur: .quarter)
|
||||
Note(.named(.b, 5), dur: .quarter)
|
||||
}
|
||||
Chord([.named(.c, 5), .named(.e, 5), .named(.g, 5)], dur: .half, dyn: .f, art: .tenuto)
|
||||
}
|
||||
Part("bass", channel: 1, clef: .bass) {
|
||||
Note(.named(.c, 3), dur: .whole, dyn: .mp)
|
||||
}
|
||||
}
|
||||
|
||||
let xml = score.toMusicXMLString() // export
|
||||
let restored = try Score.fromMusicXML(data: score.toMusicXMLData()) // round-trip
|
||||
for event in score.allEvents { // flat, absolute-beat events (rests excluded)
|
||||
let hz = event.pitch.frequency ?? 0
|
||||
// schedule a voice at event.beat * secondsPerBeat for event.performedDuration …
|
||||
}
|
||||
```
|
||||
|
||||
Notable score features:
|
||||
|
||||
- **Notation model** — per-part `Clef` (`.auto` infers from pitch range), `KeySignature` (score-level + per-part override), `TempoChange` (measure-indexed), `RepeatStructure` / volta `Ending`, transposing-instrument `Transpose`, grace notes, chord ties, and nested tuplet brackets. These are notation-only — `flatten()` / playback use the base `bpm`.
|
||||
- **MusicXML round-trip** — `score.toMusicXMLString()` / `.toMusicXMLData()` out, `Score.fromMusicXML(data:)` back. Spelling (letter + accidental, microtonal nine-step grid) is preserved.
|
||||
- **Sounding vs. notated duration** — `ScoreEvent.duration` is notated; `event.performedDuration` applies `articulation.durationScale` for audio / MIDI note-off.
|
||||
- **Playback** — `ScorePlayer` walks the flat event list against a `LyrebirdClock` on a `LyrebirdRoutine` (mirrors `MIDIFilePlayer`); SMF bridges via `Score+MIDIFile`.
|
||||
- **Pitch / scale theory toolkit** — spelling-aware `Interval` / `Scale` / `PitchCollection` / 12-tone rows, diatonic-vs-chromatic transposition, scale-to-scale mapping; results drop straight into the DSL (`Note(.named(...))`). See [`docs/stdlib/theory.md`](docs/stdlib/theory.md).
|
||||
|
||||
The template writes both files into the **project root** (next to `Package.swift`) via `LyrebirdPaths.projectRoot()` — see [File output locations](#file-output-locations) — so output lands in the same place whether you run with `lyrebird run`, `swift run`, or Xcode.
|
||||
|
||||
Full guide: `Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md`. Reference project: [`Demos/LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/).
|
||||
|
||||
---
|
||||
|
||||
## File output locations
|
||||
|
||||
When a project writes files (an NRT `.caf`, a MusicXML export, a recording), *where* they land depends on how the binary is launched: `lyrebird run` / `swift run` set the working directory to the package root, but **Xcode sets it to `DerivedData`** and a bare binary inherits whatever shell launched it. Hardcoding `URL(fileURLWithPath: "out.caf")` therefore drops files in surprising places.
|
||||
|
||||
`LyrebirdPaths` (core `Lyrebird` module) resolves the common locations for you:
|
||||
|
||||
| Member | Resolves to | Use for |
|
||||
|---|---|---|
|
||||
| `LyrebirdPaths.projectRoot()` | Folder containing `Package.swift`, found by walking up from the **calling source file** at compile time. Returns `URL?`. | Dev-time render/export output you want beside your project, independent of launch method. |
|
||||
| `LyrebirdPaths.documents` | `.documentDirectory` (`~/Documents` on macOS; the app sandbox Documents on iOS). | **Shipped apps** writing user-visible data. The right choice on iOS. |
|
||||
| `LyrebirdPaths.applicationSupport` | `.applicationSupportDirectory` | App-managed data (presets, state) not meant to be user-visible. |
|
||||
| `LyrebirdPaths.caches` | `.cachesDirectory` | Regenerable data the system may purge. |
|
||||
| `LyrebirdPaths.temporary` | Per-process temp dir | Scratch files. |
|
||||
| `LyrebirdPaths.home` | User home | — |
|
||||
| `LyrebirdPaths.currentWorkingDirectory` | Process cwd | Equals project root under `lyrebird run`; a sensible `??` fallback for `projectRoot()`. |
|
||||
| `LyrebirdPaths.desktop` *(macOS only)* | `.desktopDirectory`. Returns `URL?`. | Quick dev dumps. Needs an entitlement in a sandboxed app. |
|
||||
|
||||
```swift
|
||||
import LyrebirdSynth
|
||||
|
||||
// Dev-time: write beside the project, regardless of launch method.
|
||||
let dir = LyrebirdPaths.projectRoot() ?? LyrebirdPaths.currentWorkingDirectory
|
||||
let cafURL = dir.appendingPathComponent("render.caf")
|
||||
|
||||
// Shipped app (iOS/macOS): write where the sandbox allows.
|
||||
let userOut = LyrebirdPaths.documents.appendingPathComponent("render.caf")
|
||||
```
|
||||
|
||||
`projectRoot()` is a compile-time, source-anchored path — it reflects where the binary was **built**, so it does not exist on another user's machine. Use it for development output only; use `documents` / `applicationSupport` in anything you distribute. It walks up to `Package.swift` by default; pass a dot-prefixed `marker: ".xcodeproj"` (or `.xcworkspace`) — matched by extension, so it finds `MyApp.xcodeproj` — for an Xcode-project layout with no manifest.
|
||||
|
||||
---
|
||||
|
||||
## Xcode file templates
|
||||
|
||||
Beyond whole projects, the CLI installs **New File…** templates so you can add a Generator, Synthesizer, Task, Oscillator, Filter, Spectral Processor, AUv3 source-slot synth, test suite, and more without boilerplate:
|
||||
Beyond whole projects, the CLI installs **New File…** templates so you can add a Generator, Synthesizer, Task, Oscillator, Filter, Spectral Processor, Score, AUv3 source-slot synth, test suite, and more without boilerplate:
|
||||
|
||||
```bash
|
||||
lyrebird install-templates # New File… ▸ Lyrebird section appears in Xcode
|
||||
@@ -263,14 +357,16 @@ From a repo checkout you can equivalently run `bash scripts/install-xcode-templa
|
||||
|
||||
## Reference projects
|
||||
|
||||
The repo ships six runnable demos in [`Demos/`](Demos/), opened via `Lyrebird.xcworkspace`, covering every template above — start there to see complete, working code:
|
||||
The repo ships eight runnable demos in [`Demos/`](Demos/), opened via `Lyrebird.xcworkspace`, covering every template above — start there to see complete, working code:
|
||||
|
||||
| Demo | Mirrors template |
|
||||
|---|---|
|
||||
| [`LyrebirdQuickstartDemo`](Demos/LyrebirdQuickstartDemo/) | `quickstart` |
|
||||
| [`LyrebirdDemo`](Demos/LyrebirdDemo/) | real-time CLI |
|
||||
| [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | `macos-ui-xcode` |
|
||||
| [`LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/) | `ios-ui` |
|
||||
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | `nrt` |
|
||||
| [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | `score` |
|
||||
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | `auv3` |
|
||||
| [`LyrebirdScratchDemo`](Demos/LyrebirdScratchDemo/) | live-coding scratchpad |
|
||||
|
||||
|
||||
+36
-10
@@ -1,26 +1,37 @@
|
||||
# Lyrebird — Start Here
|
||||
|
||||
Six demo projects live in this workspace. This guide covers how to open them, what each one does, where to add your own synthesizers, and the gotchas that will bite you if you don't know about them.
|
||||
Eight demo projects live in this workspace. This guide covers how to open them, what each one does, where to add your own synthesizers, and the gotchas that will bite you if you don't know about them.
|
||||
|
||||
---
|
||||
|
||||
## Opening the Workspace
|
||||
|
||||
Open **`Lyrebird.xcworkspace`** — not any individual `.xcodeproj` file. The workspace links all six demo projects together so they share the local Lyrebird package.
|
||||
Open **`Lyrebird.xcworkspace`** — not any individual `.xcodeproj` file. The workspace links all eight demo projects together so they share the local Lyrebird package.
|
||||
|
||||
Once open, pick a scheme from the scheme picker at the top of the Xcode window and hit Run.
|
||||
|
||||
---
|
||||
|
||||
## The Six 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
|
||||
|
||||
A command-line tool that plays audio through your default output device using `CoreAudioDriver`.
|
||||
|
||||
- **Where to add synthesizers:** `Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/` — `SineTone.swift` and `DelaySample.swift` are the starting examples
|
||||
- **Wire it up:** in `main.swift`, call `engine.schedule(MySynth(), after: 0.0)`
|
||||
- **To stop:** Ctrl-C in the Xcode console, or just let the synthesizer's done action free it
|
||||
- **Where to add synthesizers:** `Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/` — `General/SineTone.swift` and `General/DelaySample.swift` are the starting examples (the folder is grouped into `General/`, `Buffer/`, `Granular/`, `Spectral/`)
|
||||
- **Wire it up:** `main.swift` adds a synth and plays it — `try engine.add(mySynth)`, or `try engine.schedule(mySynth, after: seconds)` for sample-accurate start. (As shipped, `main.swift` runs a demo harness — `BufferDemos(engine: engine).runDemo()`; swap in your own.)
|
||||
- **To stop:** Ctrl-C in the Xcode console, or give a voice an envelope/line that frees itself (see below)
|
||||
|
||||
You can also run this from the terminal: `cd Demos/LyrebirdDemo && swift run`
|
||||
|
||||
@@ -36,11 +47,13 @@ A SwiftUI app with a live oscilloscope, parameter knobs, and real-time audio.
|
||||
|
||||
```swift
|
||||
final class MySynth: SynthesizerBase {
|
||||
@UIParam var freq: LyrebirdFloat = 440.0
|
||||
@UIParam var amp: LyrebirdFloat = 0.5
|
||||
@UIParam var freq: Double = 440.0
|
||||
@UIParam var amp: Double = 0.5
|
||||
|
||||
override func build() {
|
||||
let sig = OscSin.Audio(freq: freq) * amp
|
||||
// Use the $-projected nodes ($freq / $amp), not the bare values —
|
||||
// the projection is what makes each knob update reach the audio graph live.
|
||||
let sig = OscSin.Audio(freq: $freq) * $amp
|
||||
output(bus: 0, source: Pan2(input: sig, pan: 0))
|
||||
}
|
||||
}
|
||||
@@ -105,6 +118,17 @@ let right = In.Audio(bus: 3) // numOutputChannels + 1
|
||||
|
||||
---
|
||||
|
||||
### LyrebirdScoreDemo — Score / MusicXML + Offline Render
|
||||
|
||||
A command-line tool that builds notated `Score`s with the result-builder DSL, exports them to MusicXML on the Desktop, round-trips them through the parser as a sanity check, then renders the audio to a CAF file via `NRTDriver`.
|
||||
|
||||
- **Output files:** `~/Desktop/LyrebirdScoreDemo.musicxml` (a multi-part demo score), `~/Desktop/LyrebirdScoreSections.musicxml` (a sectioned showcase), and `~/Desktop/LyrebirdScoreDemo.caf` (rendered audio). Open the `.musicxml` in Dorico / MuseScore / Finale; open the `.caf` in any DAW.
|
||||
- **Where the score is built:** `Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/Demos/ScoreDemo.swift` — `makeScore()` (eight parts) and `makeSectionedShowcase()`.
|
||||
- **Notation coverage:** clefs, keys, dynamics/hairpins, ties, tuplets, grace notes, multi-staff `Staff`/`Voice`, sustain `Pedal`, repeats with 1st/2nd endings, `Section`s + rehearsal marks, glissandi, per-note display overrides, and page layout. Reference: [`Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md`](Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md).
|
||||
- **Rehearsal-mark tip:** use single-letter `Section` labels (`"A"`, `"B"`, `"C"`) — notation editors auto-sequence rehearsal marks and hide custom words.
|
||||
|
||||
---
|
||||
|
||||
### LyrebirdAUv3Demo — AUv3 Plugin Reference
|
||||
|
||||
A container app + `.appex` extension target shipping **Realized Sound: LyrebirdFM** — a two-operator FM synthesizer wrapped as an `aumu` Audio Unit v3. Loadable in Logic, GarageBand, AUM, Loopy Pro, and any other AUv3 host on macOS.
|
||||
@@ -152,11 +176,12 @@ final class MySynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let sig = OscSin.Audio(freq: 440) * 0.3
|
||||
output(bus: 0, source: Pan2(input: sig, pan: 0))
|
||||
doneAction = .freeEnclosing
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Self-freeing voices:** there is no `doneAction` property to set on the synthesizer. Instead, build a `DoneActionWatchable` generator — `EnvelopeGen`, `Line`, `ExponentialLine`, etc. — **inside `build()`** with `doneAction: .freeNode`; it self-registers, and the engine frees the node when that generator finishes. (`DoneAction` cases are `.nothing`, `.freeNode`, `.loop`.)
|
||||
|
||||
---
|
||||
|
||||
## Common Gotchas
|
||||
@@ -182,6 +207,7 @@ final class MySynth: SynthesizerBase {
|
||||
| Synthesizer and node tree | `docs/protocols/synthesizer.md` |
|
||||
| All built-in generators | `docs/stdlib/generators.md` |
|
||||
| NRT / offline rendering | `docs/tooling/nrt-guide.md` |
|
||||
| Score / MusicXML authoring | `Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md` |
|
||||
| REPL / hot-swap | `docs/tooling/repl.md` |
|
||||
| Xcode file templates | `docs/tooling/xcode-templates.md` |
|
||||
| GUI / parameter binding | `docs/ui/gui-system.md` |
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
// swift-tools-version: 6.0
|
||||
import PackageDescription
|
||||
|
||||
// Phase 167 — `LyrebirdLiveCompile` and `LyrebirdLiveCompileUI` live in this
|
||||
// `LyrebirdLiveCompile` and `LyrebirdLiveCompileUI` live in this
|
||||
// sub-package so that cross-package `.product(name:, package:)` dependency
|
||||
// resolution forces SwiftPM to dynamic-link `libLyrebirdLiveCompile.dylib`
|
||||
// against `libLyrebird.dylib` instead of statically embedding `Lyrebird`'s
|
||||
@@ -20,13 +20,25 @@ let package = Package(
|
||||
name: "LyrebirdLiveCompile",
|
||||
platforms: [.macOS(.v15)],
|
||||
products: [
|
||||
// Product name ≠ target name (mirrors the main package's
|
||||
// `Lyrebird`/`LyrebirdDynamic` pairing). A `.dynamic` product whose name
|
||||
// EQUALS its target name collides in Xcode when that target is also
|
||||
// referenced as a static link elsewhere in the same build graph:
|
||||
// "Swift package target 'X' is linked as a static library by … but
|
||||
// cannot be built dynamically because there is a package product with
|
||||
// the same name." Naming the dynamic products `…Dynamic` removes the
|
||||
// collision so each target builds as a single shared dylib that every
|
||||
// consumer links dynamically. Target/module names are unchanged, so
|
||||
// `import LyrebirdLiveCompile` / `import LyrebirdLiveCompileUI` and the
|
||||
// test targets (which reference targets by name) are unaffected.
|
||||
.library(
|
||||
name: "LyrebirdLiveCompile",
|
||||
name: "LyrebirdLiveCompileDynamic",
|
||||
type: .dynamic,
|
||||
targets: ["LyrebirdLiveCompile"]
|
||||
),
|
||||
.library(
|
||||
name: "LyrebirdLiveCompileUI",
|
||||
name: "LyrebirdLiveCompileUIDynamic",
|
||||
type: .dynamic,
|
||||
targets: ["LyrebirdLiveCompileUI"]
|
||||
),
|
||||
],
|
||||
@@ -48,7 +60,7 @@ let package = Package(
|
||||
.product(name: "LyrebirdDynamic", package: "Lyrebird"),
|
||||
],
|
||||
path: "Sources/LyrebirdLiveCompileUI"
|
||||
// Swift 6 language mode (Phase 203): inherits the swift-tools 6.0 default.
|
||||
// Swift 6 language mode: inherits the swift-tools 6.0 default.
|
||||
),
|
||||
.testTarget(
|
||||
name: "LyrebirdLiveCompileTests",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 142 core
|
||||
// LyrebirdLiveCompile — core
|
||||
//
|
||||
// `CompiledSnippet` owns the `dlopen` handle and the resolved entry function
|
||||
// pointer for one snippet's dylib. Held by the live session for the lifetime of
|
||||
@@ -35,7 +35,7 @@ public final class CompiledSnippet: @unchecked Sendable {
|
||||
/// Path to the dylib that was `dlopen`'d.
|
||||
public let dylibPath: String
|
||||
|
||||
/// Resolved entry function pointer. Calling this is Phase 143's job.
|
||||
/// Resolved entry function pointer. The snippet harness calls this.
|
||||
public let entry: SnippetEntry
|
||||
|
||||
/// Raw `dlopen` handle. Kept so the OS keeps the dylib mapped.
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 144
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// One parsed `swiftc` diagnostic, with `line` already mapped from the wrapped-
|
||||
// snippet coordinate space back to the user's snippet coordinate space (via the
|
||||
// `userBodyLineOffset` from `SnippetHarness.wrap(userBody:)`).
|
||||
//
|
||||
// The editor in Phase 145 (`LyrebirdScratchView`) renders diagnostics in its
|
||||
// The editor (`LyrebirdScratchView`) renders diagnostics in its
|
||||
// margin gutter using `(line, column)` directly.
|
||||
|
||||
#if os(macOS)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 144
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// `DiagnosticParser.parse(stderr:userBodyLineOffset:)` walks the swiftc stderr
|
||||
// stream line by line, extracts diagnostics matching the standard
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 144
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// Severity classifier for a parsed swiftc diagnostic line.
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 142 core
|
||||
// LyrebirdLiveCompile — core
|
||||
//
|
||||
// Errors raised by `LiveCompiler.compile(source:)`. RT path never sees these:
|
||||
// compilation is a main-thread (or background-queue) operation that runs long
|
||||
|
||||
@@ -4,12 +4,12 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 142 core
|
||||
// LyrebirdLiveCompile — core
|
||||
//
|
||||
// `LiveCompiler.compile(source:)` shells out to `swiftc -emit-library`, then
|
||||
// `dlopen`s the resulting dylib and resolves the snippet entry symbol. No UI,
|
||||
// no `SynthesisEngine` binding (those land in phases 143–146). macOS only —
|
||||
// iOS cannot exec swiftc.
|
||||
// no `SynthesisEngine` binding (those are handled by the harness and session
|
||||
// layers). macOS only — iOS cannot exec swiftc.
|
||||
|
||||
import Foundation
|
||||
#if os(macOS)
|
||||
@@ -34,8 +34,8 @@ public enum LiveCompiler {
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - source: Full Swift source, including the `@_cdecl("lyrebird_snippet_entry")`
|
||||
/// entry. Phase 143's `SnippetHarness` will wrap user input in a preamble that
|
||||
/// provides this; Phase 142 callers (incl. tests) write the full file.
|
||||
/// entry. `SnippetHarness` wraps user input in a preamble that provides
|
||||
/// this; direct callers (incl. tests) write the full file.
|
||||
/// - extraSwiftcArgs: Extra args appended to the `swiftc` invocation. Tests use
|
||||
/// this for `-suppress-warnings` etc. Production callers leave empty.
|
||||
/// - Returns: `CompiledSnippet` holding the dlopen handle and entry pointer.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 143
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// `LiveSession` owns the `SynthesisEngine` and tracks every `Synthesizer` that
|
||||
// each snippet `play(_:)`s, so the next non-additive re-evaluation can
|
||||
@@ -23,7 +23,7 @@ import LyrebirdSynth
|
||||
/// Snippets receive a `SnippetContext` bound to this session through
|
||||
/// `compileAndRun(_:additive:)`.
|
||||
///
|
||||
/// `@unchecked Sendable` (Phase 203): a `LiveSession` is shared between its `@MainActor`
|
||||
/// `@unchecked Sendable`: a `LiveSession` is shared between its `@MainActor`
|
||||
/// owner (`LyrebirdScratchModel`) and the `nonisolated` `compileAndRunAsync` it calls, so
|
||||
/// Swift 6 requires it to be `Sendable`. The conformance is sound by construction:
|
||||
///
|
||||
@@ -70,7 +70,7 @@ public final class LiveSession: @unchecked Sendable {
|
||||
engine: SynthesisEngine,
|
||||
importPaths: [URL] = LiveSession.defaultImportPaths(),
|
||||
librarySearchPaths: [URL] = LiveSession.defaultLibrarySearchPaths(),
|
||||
libraries: [String] = ["LyrebirdDynamic", "LyrebirdLiveCompile"],
|
||||
libraries: [String] = ["LyrebirdDynamic", "LyrebirdLiveCompileDynamic"],
|
||||
rpaths: [URL] = LiveSession.defaultRpaths()
|
||||
) {
|
||||
self.engine = engine
|
||||
@@ -91,7 +91,7 @@ public final class LiveSession: @unchecked Sendable {
|
||||
/// (⌘⇧↩ semantics in the future `LyrebirdScratchView` editor).
|
||||
/// - Returns: The compiled snippet handle. Retained internally so the dylib
|
||||
/// stays mapped; callers can ignore it.
|
||||
/// `@MainActor` (Phase 203): runs the snippet entry — and thus the user body's
|
||||
/// `@MainActor`: runs the snippet entry — and thus the user body's
|
||||
/// `MainActor.assumeIsolated { … }` and any `context.play(_:)` → `engine.add` — on the
|
||||
/// main thread, synchronously (swiftc compile included). The async variant
|
||||
/// ``compileAndRunAsync(_:additive:)`` keeps the compile off-main.
|
||||
@@ -112,8 +112,8 @@ public final class LiveSession: @unchecked Sendable {
|
||||
/// engine-touching steps (`clearTracked()` and the snippet entry via `runEntry`) then run
|
||||
/// on the **main actor**.
|
||||
///
|
||||
/// Running the entry on the main actor matters (Phase 203): the snippet's
|
||||
/// `context.play(_:)` calls `engine.add(_:)`, which is `@MainActor` (Phase 201) and
|
||||
/// Running the entry on the main actor matters: the snippet's
|
||||
/// `context.play(_:)` calls `engine.add(_:)`, which is `@MainActor` and
|
||||
/// mutates `engine.nodeTreeMirror` — state observed by SwiftUI on the main thread. A
|
||||
/// `nonisolated async` method resumes on the generic executor, NOT the caller's actor, so
|
||||
/// the hop is explicit here rather than assumed.
|
||||
@@ -288,7 +288,7 @@ public final class LiveSession: @unchecked Sendable {
|
||||
///
|
||||
/// Searches, in order:
|
||||
/// 1. Walks up from `Bundle(for: LiveSession.self).bundleURL` — this resolves
|
||||
/// to the directory holding `libLyrebirdLiveCompile.dylib` at runtime,
|
||||
/// to the directory holding `libLyrebirdLiveCompileDynamic.dylib` at runtime,
|
||||
/// which is the SPM debug/release dir.
|
||||
/// 2. Walks up from `Bundle.main.executableURL` — fallback for the case
|
||||
/// where the host bundles the dylibs into an `.app`.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 144
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// `LiveSession.compileAndRun(_:additive:)` throws this richer error so callers
|
||||
// see diagnostics pre-mapped to user-snippet coordinates. Other `LiveCompileError`
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 143
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// `SnippetContext` is the public API surface the user's snippet talks to. The
|
||||
// host (via `LiveSession.compileAndRun`) constructs one of these, passes the
|
||||
|
||||
@@ -4,16 +4,15 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 142 core
|
||||
// LyrebirdLiveCompile — core
|
||||
//
|
||||
// C ABI signature of the snippet's exported entry point.
|
||||
|
||||
#if os(macOS)
|
||||
|
||||
/// Snippets export this symbol via `@_cdecl("lyrebird_snippet_entry")`. Phase
|
||||
/// 143 will pass a pointer to a `LiveSession` (or harness context) here;
|
||||
/// Phase 142 only requires that snippets can declare a function matching this
|
||||
/// signature.
|
||||
/// Snippets export this symbol via `@_cdecl("lyrebird_snippet_entry")`. The host
|
||||
/// passes a pointer to a `LiveSession` (or harness context) here; snippets need
|
||||
/// only declare a function matching this signature.
|
||||
public typealias SnippetEntry = @convention(c) (UnsafeMutableRawPointer?) -> Void
|
||||
|
||||
#endif
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 143
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// `SnippetHarness.wrap(userBody:)` produces the full Swift source that
|
||||
// `LiveCompiler.compile(source:)` feeds to swiftc. The preamble imports the
|
||||
@@ -18,9 +18,9 @@ public enum SnippetHarness {
|
||||
|
||||
/// Wraps `userBody` in the standard preamble.
|
||||
///
|
||||
/// The user body runs inside `MainActor.assumeIsolated { … }` (Phase 203): snippets call
|
||||
/// The user body runs inside `MainActor.assumeIsolated { … }`: snippets call
|
||||
/// `@MainActor` API — `context.play(_:)` and `SynthesizerBase` subclass construction
|
||||
/// (both `@MainActor` since Phase 201) — which would not compile from the nonisolated
|
||||
/// (both `@MainActor`) — which would not compile from the nonisolated
|
||||
/// `@_cdecl` entry under Swift 6. The `assumeIsolated` closure gives the body main-actor
|
||||
/// isolation at compile time; it is safe at runtime because `LiveSession` always invokes
|
||||
/// the entry on the main actor (`compileAndRunAsync` hops via `MainActor.run`;
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 143
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// Output of `SnippetHarness.wrap(userBody:)`. Carries the full Swift source
|
||||
// that `swiftc` will compile, plus the 1-based line number on which the user's
|
||||
// body begins. Phase 144's diagnostic parser subtracts `userBodyLineOffset - 1`
|
||||
// body begins. The diagnostic parser subtracts `userBodyLineOffset - 1`
|
||||
// from each swiftc-reported line so error rows point back at the row the user
|
||||
// typed.
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile — Phase 145
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// Backing model for `LyrebirdScratchView`. Owns the editable snippet text, the
|
||||
// most recent compile result, and the host `LiveSession`. Pulled out of the
|
||||
@@ -16,7 +16,11 @@
|
||||
import Foundation
|
||||
import CoreGraphics
|
||||
import LyrebirdSynth
|
||||
import LyrebirdLiveCompile
|
||||
// Re-exported so consumers that link only the `LyrebirdLiveCompileUI` product
|
||||
// (e.g. the LyrebirdScratchDemo app) get the `LyrebirdLiveCompile` API
|
||||
// (`LiveSession`, …) without separately linking the `LyrebirdLiveCompile`
|
||||
// dynamic product — which clashes in Xcode with the static target embed.
|
||||
@_exported import LyrebirdLiveCompile
|
||||
|
||||
/// Observable backing model for `LyrebirdScratchView`.
|
||||
///
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile — Phase 145
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// `LyrebirdScratchView` — SwiftUI scratchpad editor for live-coded snippets.
|
||||
// Wraps an `NSTextView` for the editor surface, drives a `LyrebirdScratchModel`
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile — Phase 147
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// Vertical line-number gutter for `ScratchEditor`'s `NSTextView`. Installed as
|
||||
// the scroll view's `verticalRulerView` so it tracks scroll position for free.
|
||||
|
||||
@@ -52,7 +52,7 @@ struct LiveSessionDiagnosticsTests {
|
||||
@Test
|
||||
func compilerErrorWrapsUnderlyingForNonCompileFailures() {
|
||||
// Force a non-compile error by pointing at a build dir that doesn't exist.
|
||||
// The Phase 142 compile path still succeeds (a swiftc invocation with -I
|
||||
// The compile path still succeeds (a swiftc invocation with -I
|
||||
// pointing at a missing dir surfaces as `compileFailed` via swiftc's own
|
||||
// "no such module" — not `compilerError`). Instead, drive a real
|
||||
// compilerError case by routing through a LiveCompileError that isn't
|
||||
@@ -60,7 +60,7 @@ struct LiveSessionDiagnosticsTests {
|
||||
// entrySymbolMissing — but a real run with full build dir succeeds.
|
||||
// We just verify the type LiveSessionError.compilerError exists and is
|
||||
// representable; behavioural coverage of non-compileFailed cases is
|
||||
// exercised at the LiveCompiler layer (Phase 142 tests).
|
||||
// exercised at the LiveCompiler layer.
|
||||
let err: LiveSessionError = LiveSessionError.compilerError(.swiftcNotFound)
|
||||
#expect(String(describing: err).contains("swiftc"))
|
||||
}
|
||||
|
||||
@@ -74,9 +74,9 @@ struct LiveSessionTests {
|
||||
#expect(session.lastSnippetMessage == "async hello")
|
||||
}
|
||||
|
||||
/// Phase 203 runtime guard: a snippet driven through `compileAndRunAsync` that calls
|
||||
/// Runtime guard: a snippet driven through `compileAndRunAsync` that calls
|
||||
/// `context.play(_:)` actually adds and tracks a synth. `context.play` → `engine.add` is
|
||||
/// `@MainActor` (Phase 201); `compileAndRunAsync` resumes the snippet entry on the main
|
||||
/// `@MainActor`; `compileAndRunAsync` resumes the snippet entry on the main
|
||||
/// actor (not the nonisolated executor it suspends on), so this exercises that hop.
|
||||
@Test
|
||||
func asyncCompileAndRunPlaysAndTracksSynth() async throws {
|
||||
|
||||
@@ -72,8 +72,8 @@ struct LyrebirdScratchModelTests {
|
||||
func runInvalidSnippetSurfacesUserCoordinateDiagnostics() async throws {
|
||||
let session: LiveSession = makeSession()
|
||||
// `let x: Int = "nope"` — guaranteed type-check error on the first row
|
||||
// of the user body. Phase 144 maps the wrapped-source line back to
|
||||
// user line 1.
|
||||
// of the user body. The diagnostic parser maps the wrapped-source line
|
||||
// back to user line 1.
|
||||
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
||||
session: session,
|
||||
initialText: "let x: Int = \"nope\"\n"
|
||||
|
||||
+6
@@ -1,6 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdQuickstartDemo/LyrebirdQuickstartDemo.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdDemo/LyrebirdDemo.xcodeproj">
|
||||
</FileRef>
|
||||
@@ -19,4 +22,7 @@
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdScratchDemo/LyrebirdScratchDemo.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdScoreDemo/LyrebirdScoreDemo.xcodeproj">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
|
||||
+2
-2
@@ -41,8 +41,8 @@ let package = Package(
|
||||
// swift-docc-plugin — command plugin that drives DocC documentation builds.
|
||||
// Registers two commands available to all targets in this package:
|
||||
// • In Xcode: Product ▸ Build Documentation (or scheme-level build action)
|
||||
// • From CLI: swift package generate-documentation --target Lyrebird
|
||||
// swift package preview-documentation --target Lyrebird
|
||||
// • From CLI: swift package generate-documentation --target LyrebirdSynth
|
||||
// swift package preview-documentation --target LyrebirdSynth
|
||||
// No target-level plugins: entry is needed — command plugins apply package-wide.
|
||||
.package(
|
||||
url: "https://github.com/apple/swift-docc-plugin",
|
||||
|
||||
@@ -120,7 +120,7 @@ The REPL is text-only and works from any project that depends on Lyrebird; the s
|
||||
|
||||
## New here?
|
||||
|
||||
**Read [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md)** — it covers the six demo projects, how to open the workspace, where to add synthesizers, and the gotchas that will bite you.
|
||||
**Read [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md)** — it covers the eight demo projects, how to open the workspace, where to add synthesizers, and the gotchas that will bite you.
|
||||
|
||||
---
|
||||
|
||||
@@ -151,7 +151,7 @@ Full walk-through (SPM manifest form, local-path dev dependency, per-template de
|
||||
|
||||
## Opening in Xcode
|
||||
|
||||
For the demo projects, open **`Lyrebird.xcworkspace`** — not any individual `.xcodeproj`. The workspace links all six demos to the local Lyrebird package.
|
||||
For the demo projects, open **`Lyrebird.xcworkspace`** — not any individual `.xcodeproj`. The workspace links all eight demos to the local Lyrebird package.
|
||||
|
||||
For the package itself:
|
||||
|
||||
@@ -161,16 +161,18 @@ xed . # opens Package.swift — Xcode auto-generates schemes for every target
|
||||
|
||||
### Schemes
|
||||
|
||||
Workspace scheme selector exposes eight entries:
|
||||
Workspace scheme selector exposes ten entries:
|
||||
|
||||
| Scheme | Purpose | Platform |
|
||||
|---|---|---|
|
||||
| `Lyrebird-Package` | Umbrella — builds Lyrebird + LyrebirdUI + LyrebirdLiveCompile + LyrebirdC + LyrebirdBenchmark + LyrebirdCLI, runs the test suites, launches/profiles `LyrebirdCLI` | macOS |
|
||||
| `LyrebirdQuickstartDemo` | CLI — fastest sound: a one-oscillator `SineTone` that plays 440 Hz for 10 s and exits | macOS |
|
||||
| `LyrebirdUI` | Builds the `LyrebirdUI` module only (SwiftUI parameter controls + visualisations) | macOS |
|
||||
| `LyrebirdDemo` | CLI — plays through default output via `CoreAudioDriver` | macOS |
|
||||
| `LyrebirdMacOSDemo` | SwiftUI app — live oscilloscope, `@UIParam` knobs | macOS |
|
||||
| `LyrebirdiOSDemo` | SwiftUI app — same UI via `iOSAudioDriver` (RemoteIO) | iOS |
|
||||
| `LyrebirdNRTDemo` | CLI — offline render to CAF via `NRTDriver` | macOS |
|
||||
| `LyrebirdScoreDemo` | CLI — builds notated `Score`s (result-builder DSL), exports MusicXML, renders to CAF via `NRTDriver` | macOS |
|
||||
| `LyrebirdAUv3Demo` | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro, etc. Run the host app once to register the extension. | macOS |
|
||||
| `LyrebirdScratchDemo` | Live-coding scratchpad — type Swift snippets, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
||||
|
||||
@@ -192,7 +194,7 @@ Use `Lyrebird-Package` for day-to-day development of the engine and tests.
|
||||
|
||||
```bash
|
||||
swift build # build all targets
|
||||
swift test # run all 3544 tests
|
||||
swift test # run all 5481 tests
|
||||
swift test --filter LyrebirdTests # run one suite
|
||||
swift run lyrebird # run the CLI
|
||||
swift run lyrebird repl # Swift REPL with Lyrebird available
|
||||
@@ -203,14 +205,16 @@ swift run LyrebirdDemo # run the hardware smoke-test demo
|
||||
|
||||
## Demo projects
|
||||
|
||||
All six live in [`Demos/`](Demos/). Open via `Lyrebird.xcworkspace`.
|
||||
All eight live in [`Demos/`](Demos/). Open via `Lyrebird.xcworkspace`.
|
||||
|
||||
| Demo | What it does | Platform |
|
||||
|---|---|---|
|
||||
| [`LyrebirdQuickstartDemo`](Demos/LyrebirdQuickstartDemo/) | CLI — fastest sound: a one-oscillator `SineTone` plays 440 Hz for 10 s, then exits (mirrors the `quickstart` template) | macOS |
|
||||
| [`LyrebirdDemo`](Demos/LyrebirdDemo/) | CLI — plays through default output via `CoreAudioDriver` | macOS |
|
||||
| [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | SwiftUI app — live oscilloscope, `@UIParam` knobs | macOS |
|
||||
| [`LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/) | SwiftUI app — same UI system via `iOSAudioDriver` (RemoteIO) | iOS |
|
||||
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | CLI — offline render to CAF file via `NRTDriver` | macOS |
|
||||
| [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | CLI — notated `Score` → MusicXML export + offline render to CAF via `NRTDriver` | macOS |
|
||||
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro | macOS |
|
||||
| [`LyrebirdScratchDemo`](Demos/LyrebirdScratchDemo/) | Live-coding scratchpad — type Swift, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
||||
|
||||
@@ -231,8 +235,10 @@ lyrebird --help # verify
|
||||
Then:
|
||||
|
||||
```bash
|
||||
lyrebird new MyPiece --template ui-demo # scaffold a standalone project
|
||||
open MyPiece/MyPiece.xcworkspace # open in Xcode (workspace refs Package.swift)
|
||||
lyrebird new MyFirstSound --template quickstart # fastest path to sound (plays 10 s, then exits)
|
||||
cd MyFirstSound && lyrebird run # hear it
|
||||
lyrebird new MyPiece --template ui-demo # a richer standalone project
|
||||
open MyPiece/MyPiece.xcworkspace # open in Xcode (workspace refs Package.swift)
|
||||
lyrebird # enter the lyrebird> interactive shell
|
||||
lyrebird repl # Swift REPL with Lyrebird importable
|
||||
lyrebird --version
|
||||
@@ -269,14 +275,16 @@ LyrebirdII/
|
||||
│ ├── LyrebirdCLI/ # lyrebird CLI binary
|
||||
│ └── LyrebirdDemo/ # macOS CLI hardware smoke-test
|
||||
├── Demos/
|
||||
│ ├── LyrebirdQuickstartDemo/ # fastest sound — SineTone plays 10 s then exits
|
||||
│ ├── LyrebirdDemo/ # (same as Sources/LyrebirdDemo — workspace target)
|
||||
│ ├── LyrebirdMacOSDemo/ # macOS SwiftUI app
|
||||
│ ├── LyrebirdiOSDemo/ # iOS SwiftUI app
|
||||
│ ├── LyrebirdNRTDemo/ # offline renderer
|
||||
│ ├── LyrebirdScoreDemo/ # notated Score → MusicXML + offline render
|
||||
│ ├── LyrebirdAUv3Demo/ # AUv3 `aumu` plugin reference (LyrebirdFM)
|
||||
│ └── LyrebirdScratchDemo/ # live-coding scratchpad (macOS, no sandbox)
|
||||
├── Tests/
|
||||
│ ├── LyrebirdTests/ # 3544 engine + generator tests
|
||||
│ ├── LyrebirdTests/ # 5253 engine + generator tests
|
||||
│ ├── LyrebirdUITests/ # SwiftUI component tests
|
||||
│ └── LyrebirdCLITests/ # CLI tests
|
||||
└── docs/
|
||||
@@ -329,6 +337,7 @@ swift package --disable-sandbox preview-documentation --target Lyrebird
|
||||
| Topic | Doc |
|
||||
|---|---|
|
||||
| **Start here / demo projects** | [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) |
|
||||
| **What's new / release notes** | [`RELEASES.md`](RELEASES.md) |
|
||||
| Engine setup and Core Audio | `docs/engine/synthesis-engine.md` |
|
||||
| Bus memory / In / Out | `docs/engine/bus-system.md` |
|
||||
| Sample-accurate scheduling | `docs/engine/scheduling.md` |
|
||||
@@ -359,6 +368,12 @@ swift package --disable-sandbox preview-documentation --target Lyrebird
|
||||
|
||||
---
|
||||
|
||||
## Release notes
|
||||
|
||||
Per-version changes are in [`RELEASES.md`](RELEASES.md). The current release
|
||||
(1.1) adds the algorithmic-composition stack: a music-theory toolkit, pattern
|
||||
library, score DSL, and MusicXML / MIDI round-trips.
|
||||
|
||||
## Contributing
|
||||
|
||||
New Generators (in-tree) and out-of-tree extension packages are both welcome — see [`CONTRIBUTING.md`](CONTRIBUTING.md).
|
||||
|
||||
+288
@@ -0,0 +1,288 @@
|
||||
# Releases
|
||||
|
||||
Notable changes per release. Newest first.
|
||||
|
||||
This project follows semantic versioning: a minor bump (1.0 → 1.1) adds
|
||||
functionality in a backward-compatible way.
|
||||
|
||||
---
|
||||
|
||||
## 1.3.0 — Graceful-release fix, quickstart template, documentation accuracy pass
|
||||
|
||||
A minor release. Backward-compatible: one real-time behavior fix, one new
|
||||
project template, and a large sweep that makes the documentation's code
|
||||
examples verifiably correct.
|
||||
|
||||
### Fixed — graceful release now works for `SynthesizerBase` subclasses
|
||||
|
||||
`release(engine:)` and `free(engine:)` were `Synthesizer` protocol requirements
|
||||
satisfied only by extension defaults; `SynthesizerBase` declared neither, so a
|
||||
subclass override was unreachable through an `any Synthesizer` reference. Because
|
||||
`Group.release(engine:)` cascades to its children through exactly that
|
||||
existential, **every gated `SynthesizerBase` subclass was hard-freed instead of
|
||||
released** — envelope release phases were skipped (audible as clicks and missing
|
||||
release tails). `SynthesizerBase` now declares both as `open` members, so
|
||||
overrides dispatch through the vtable. Pinned by `SynthesizerReleaseDispatchTests`.
|
||||
|
||||
### New — `quickstart` project template + demo
|
||||
|
||||
- `lyrebird new MyFirstSound --template quickstart` scaffolds the shortest path
|
||||
to sound: a one-oscillator `SineTone`, the engine, and a `main` that plays a
|
||||
440 Hz tone for ten seconds and exits. Featured as the fast option across the
|
||||
CLI help, README, and getting-started docs.
|
||||
- A matching bundled **`LyrebirdQuickstartDemo`** Xcode project ships in the
|
||||
workspace so the same starting point is runnable without the CLI.
|
||||
|
||||
### Documentation — every example now typechecked or provably illustrative
|
||||
|
||||
- Extended the doc-snippet compile guard to the published entry-point articles,
|
||||
the generator reference, and the root docs (`README` / `LYREBIRD_START_HERE` /
|
||||
`INSTALLATION_AND_USAGE`), which were previously checked by nothing. Recorded
|
||||
compilable examples rose from 426 to 542.
|
||||
- Fixed roughly twenty copy-paste examples that never compiled — wrong parameter
|
||||
labels and orders (`LinLin`, `SpringReverb`, `BufferGrain`), nonexistent APIs
|
||||
(`LFNoise2`, `DoneAction.freeSynth`, `buildGraph()`, `midiNoteToHz`,
|
||||
`LyrebirdBuffer(path:)`, a `>` operator on generators), missing required
|
||||
arguments (`CombFilter`/`AllpassFilter` `maxDelay`), a Swift 6 concurrency
|
||||
violation in the canonical routine example, and stale test counts. Removed an
|
||||
unsupported NRT-replay workflow that documented a fabricated driver API.
|
||||
|
||||
### Fixed — demo terminal builds
|
||||
|
||||
`LyrebirdNRTDemo` and `LyrebirdScoreDemo` pinned a stale `package: "LyrebirdII"`
|
||||
in their `Package.swift`, so standalone `swift build` / `swift run` from the demo
|
||||
directory failed. Corrected to `Lyrebird`.
|
||||
|
||||
---
|
||||
|
||||
## 1.2.0 — Generator catalog expansion *(planned)*
|
||||
|
||||
A minor release. Adds roughly forty SuperCollider-parity generators —
|
||||
triggers, time-domain analysis, chaotic oscillators, resonator banks, dynamics,
|
||||
waveshaping, routing/morph, and psychoacoustic metering — plus an iOS path fix.
|
||||
Fully backward-compatible; no changes to existing public API.
|
||||
|
||||
### New generators
|
||||
|
||||
**Trigger / timing.** `Trig` and `Trig1` (fixed-duration gate from a trigger),
|
||||
`Schmidt` (hysteresis threshold), `Stepper` (trigger-advanced counter),
|
||||
`PulseCount` (count triggers, reset on a second input), `TriggeredDelay` (hold
|
||||
then re-emit a trigger).
|
||||
|
||||
**Phasor / slew.** `Phasor` (sample-accurate sweeping ramp with wrap bounds and
|
||||
trigger-reset), `Slew` (asymmetric slew-rate limiter).
|
||||
|
||||
**Time-domain analysis.** `RunningMin`, `RunningMax` (running extrema, reset on
|
||||
trigger), `Slope` (per-sample first difference), `ZeroCrossing` (zero-crossing
|
||||
frequency estimator).
|
||||
|
||||
**Routing / morph.** `Select` (index-select one of N inputs), `CrossFade`
|
||||
(equal-power two-input mix), `LinearCrossFade` (linear two-input mix).
|
||||
|
||||
**Waveshaping / distortion.** `Waveshaper` (transfer-function table lookup with
|
||||
interpolation), `CrossoverDistortion` (dead-zone crossover), `Disintegrator`
|
||||
(probabilistic sample mangling).
|
||||
|
||||
**Resonant filter / LFO.** `Formlet` (FOF-style resonant formant filter),
|
||||
`LFGauss` (Gaussian-bell LFO).
|
||||
|
||||
**Chaotic oscillators.** `LorenzLinear`, `HenonStepped`, `QuadStepped`,
|
||||
`LinCongStepped`, `GbmanStepped`, `StandardStepped`, `FBSineStepped`,
|
||||
`LatoocarfianStepped`, `CuspStepped` — discrete chaotic maps, frequency-stepped
|
||||
where SuperCollider steps them.
|
||||
|
||||
**Resonator banks.** `Klank` (fixed bank of fixed-frequency resonators) and
|
||||
`Klang` (bank of sine partials), both runtime-respecifiable.
|
||||
|
||||
**Dynamics.** `Normalizer` (look-ahead peak normalizer) and `Balance` (RMS
|
||||
level matcher, with `logDomain` for dB-domain gain and `smooth` for decoupled
|
||||
gain lag).
|
||||
|
||||
**Metering.** `BeatTrack` (FFT-based tempo / beat tracker) and `Loudness`
|
||||
(Zwicker / ISO 532 B psychoacoustic loudness in sones).
|
||||
|
||||
> `DFM1` (the remaining catalog candidate) is intentionally omitted: its source
|
||||
> and lookup tables are GPL, incompatible with this project's MIT license.
|
||||
|
||||
### Tooling
|
||||
|
||||
- **ShoeGaze moved out of tree.** The guitar-pedalboard framework and its
|
||||
project/pedal scaffolding now live in a standalone ShoeGaze repository that
|
||||
depends on Lyrebird as a package. Lyrebird's CLI no longer ships the
|
||||
`shoegaze` / `shoegaze-ios` project templates or the "ShoeGaze Pedal" Xcode
|
||||
file template.
|
||||
|
||||
### Fixes
|
||||
|
||||
- **`LyrebirdPaths.home` on iOS** now returns the app's Documents directory
|
||||
instead of `homeDirectoryForCurrentUser` (the sandbox root, which is not
|
||||
writable on iOS). Unchanged on macOS.
|
||||
|
||||
### Internals (no API impact)
|
||||
|
||||
- The 4-point Catmull-Rom cubic interpolation duplicated across oscillator
|
||||
table reads, `PlayBuffer`, and the fractional-delay lines is now a single
|
||||
shared `catmullRomCubic` kernel.
|
||||
- Generator tests regrouped by family.
|
||||
|
||||
---
|
||||
|
||||
## 1.1.1 — Real-time performance + score-timing fixes *(planned)*
|
||||
|
||||
A patch release: real-time CPU improvements to the synthesis engine's hot path,
|
||||
internal generator consolidation, and two score-side timing fixes. Fully
|
||||
backward-compatible — no public API changes.
|
||||
|
||||
### Real-time performance
|
||||
|
||||
The generator render path (`_computeSamples`) is now Accelerate-accelerated
|
||||
where it was previously scalar. Wins are largest for the primitives that appear
|
||||
in nearly every patch:
|
||||
|
||||
- **Unary math waveshapers** (`Sin` / `Cos` / `Exp` / `Log` / `Sqrt` / `Floor`
|
||||
/ `Ceil` / `Abs`) — vectorized via vForce / vDSP (~3× faster on a typical
|
||||
chained-op voice).
|
||||
- **Arithmetic operators** (`+` `−` `×` `÷` on generators, via
|
||||
`BinaryOpGenerator`) — vDSP dispatch, **bit-identical** to the scalar result
|
||||
(divide uses true-division, never reciprocal-multiply). Roughly 2–3.5× faster;
|
||||
applies to every `osc * gain + offset`-style graph.
|
||||
- **`LinLin`** — single fused `vDSP_vsmsaD` affine map (~27% faster).
|
||||
- **State-variable filter (`SVF`)** — shared per-block kernel; generator-driven
|
||||
cutoff uses block-boundary coefficient interpolation instead of a per-sample
|
||||
`sin()`.
|
||||
- **`Chorus` / `Flanger`** — power-of-two delay lines (bitwise index wrap).
|
||||
- **Butterworth band-pass / band-reject** — now use the same background-thread
|
||||
vDSP biquad-cascade path the low-pass / high-pass filters already had.
|
||||
|
||||
All vectorized paths keep a scalar fallback for short upstream blocks, so output
|
||||
is unchanged on every code path (transcendentals within tolerance; arithmetic
|
||||
and filter sums bit-exact).
|
||||
|
||||
### Internals (no API impact)
|
||||
|
||||
- Generator consolidation: the duplicated Butterworth cascade machinery, SVF
|
||||
block body, unary-math and binary-op inner loops, and power-of-two buffer
|
||||
sizing are now shared helpers (`ButterworthSectionEngine`, `runSVFBlock`,
|
||||
`UnaryMathVectorHelpers`, `BinaryOpVectorHelpers`, `lyrebirdNextPowerOfTwo`,
|
||||
`computeButterworthQs`). Several hundred lines of duplication removed.
|
||||
- New `LyrebirdBenchmark` target with before/after reference numbers
|
||||
(`docs/benchmarks/gp-baseline.md`).
|
||||
- Language-side consolidation: shared `isCounterExhausted` / `resetAll` Pattern
|
||||
helpers, a `_RandomPatternBase` for the random pattern engines, a
|
||||
`TemporalAlgorithmBase` for the counter-driven temporal algorithms, a shared
|
||||
MusicXML `<direction>` / `<pitch>` emit helper, and a single
|
||||
engine-mutation-to-main-queue dispatch helper shared by the routine/process
|
||||
contexts.
|
||||
|
||||
### Score / MusicXML
|
||||
|
||||
- **`ScorePart` entrance offset** — a part can enter later than the start of its
|
||||
section via `offset:` (`ScoreOffset.measures(_:)` / `.beats(_:)` /
|
||||
`.fraction(_:)`). Resolved at build time into leading rests (the same way
|
||||
`FillMeasure()` is resolved), so it flows through section sizing, MusicXML bar
|
||||
splitting, and `flatten()` with no special handling.
|
||||
- **MusicXML barline-fill fix** — corrected two emit-side defects in sectioned
|
||||
scores with rest-padded short parts: a barline-crossing atom that exactly
|
||||
filled a bar left the measure open (shifting every later note by one division,
|
||||
rendering constant 4/4 as 5/4), and section auto-padding used meter-agnostic
|
||||
rests that straddled barlines. Padding is now bar-grid aligned (clean
|
||||
whole-measure rests; anacrusis-aware). Lowering/playback math was already
|
||||
correct — both fixes are export-only.
|
||||
|
||||
---
|
||||
|
||||
## 1.1 — Enhanced algorithmic composition tools
|
||||
|
||||
Release 1.1 turns Lyrebird's score side from a thin event list into a full
|
||||
**algorithmic composition and notation toolkit**: a spelling-aware music-theory
|
||||
layer, a pattern/sequence library, a composable score DSL, and lossless MusicXML
|
||||
and Standard MIDI File round-trips. The real-time synthesis engine is unchanged —
|
||||
this release is additive and language-side.
|
||||
|
||||
### Music theory toolkit
|
||||
|
||||
- Spelling-aware **`Interval`**, **`Scale`**, and **`PitchCollection`** types
|
||||
(cells, sets, 12-tone rows) built on the existing `Letter` / `Accidental` /
|
||||
`NoteName` / `Pitch` foundation.
|
||||
- Diatonic-vs-chromatic transposition that preserves enharmonic spelling
|
||||
(`B♯` stays `B♯`, never collapses to `C`), scale-degree mapping between scales,
|
||||
and conversion straight to Hz / seconds for synthesis.
|
||||
- **`Pitch.mapIntoRange(low:high:)`** — fold a pitch into a register by whole
|
||||
octaves while preserving pitch class and spelling.
|
||||
- See [`docs/stdlib/theory.md`](docs/stdlib/theory.md).
|
||||
|
||||
### Patterns
|
||||
|
||||
- `Pattern<T>` factory catalog for sequences, series, random and stochastic
|
||||
distributions (uniform, brownian, gaussian, cauchy, beta, weighted, shuffle…),
|
||||
and combinators (map, filter, stutter, switching, interleave, round-robin…).
|
||||
- **`Pattern.sequence(_:repeats:offset:)`** — start a sequence partway through
|
||||
its list via `offset`.
|
||||
- Euclidean rhythm generator.
|
||||
- See [`Sources/Lyrebird/Lyrebird.docc/RoutineTask.md`](Sources/Lyrebird/Lyrebird.docc/RoutineTask.md).
|
||||
|
||||
### Score DSL and notation
|
||||
|
||||
- A result-builder score DSL — `Score`, `Part`, `Note`, `Rest`, `Chord`,
|
||||
`Tuplet`, `Voice`, `Staff` — that flattens to sample-accurate `ScoreEvent`s and
|
||||
plays back through `ScorePlayer`.
|
||||
- Notation features: dynamics, articulations, **crescendo / diminuendo hairpins**,
|
||||
**slurs** (a `Slur { }` block plus per-note `spanners:` for shared-boundary and
|
||||
overlapping spans), authored ties, grace notes, repeats and volta endings,
|
||||
mid-piece tempo changes, key signatures and transposing parts, mid-voice clef
|
||||
changes, grand-staff `Staff` grouping, and sustain `Pedal` marks.
|
||||
- Meter: `TimeSignature` + segmented `MeterMap`, mid-piece meter changes,
|
||||
anacrusis (pickup) bars, and polymeter (per-part meter overrides).
|
||||
- `ScoreTimeline` musical addressing (`BeatPosition`) with overlap policies and
|
||||
multi-voice fills.
|
||||
- See [`Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md`](Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md).
|
||||
|
||||
### Score structure and page layout
|
||||
|
||||
- **`Section { }`** blocks group parts into sequential sections, each with its
|
||||
own local bar/beat numbering. Assembled into a `Score`, sections render
|
||||
sequentially with continuous global measure numbers and a rehearsal mark per
|
||||
section; tacet instruments are auto-filled so every staff stays bar-aligned.
|
||||
`ScorePart` gains an `id` (defaults to `name`) to match the same instrument
|
||||
across sections.
|
||||
- **`PageLayout`** sets MusicXML page defaults: page size
|
||||
(`letter` / `legal` / `tabloid` / `a4` / `a3` / custom mm), `portrait` /
|
||||
`landscape` orientation, per-side odd/even margins, and `<scaling>`. Authored
|
||||
in millimeters and converted to MusicXML tenths on export.
|
||||
- **`NoteDisplay`** per-note display overrides via a `display:` parameter on
|
||||
`Note` / `Chord`: custom notehead shape (`x`, `diamond`, `slash`, `.hidden`,
|
||||
raw `.other(_)`, …), note size (`cue` / `large`), hidden stem, and hidden
|
||||
beam.
|
||||
- **Glissandos / slides** between two notes via the spanner API
|
||||
(`.beginGlissando(_:)` / `.endGlissando`): glissando (wavy/curved) or slide
|
||||
(straight) `kind`, a line type (`solid` / `dashed` / `dotted` / `wavy`), and an
|
||||
optional text label.
|
||||
|
||||
### Import / export
|
||||
|
||||
- **MusicXML** export and import (`score-partwise` 4.0) with a spelling- and
|
||||
event-faithful round trip across the notation features above.
|
||||
- **Standard MIDI File** round-trip (`Score` ↔ SMF).
|
||||
|
||||
### API and internals
|
||||
|
||||
- `Score.timeSignature` and the `Score` initializers take a typed
|
||||
`TimeSignature` (a `(numerator, denominator)` pair converts via
|
||||
`TimeSignature(_:)`) instead of a raw tuple.
|
||||
- Internal cleanups with no API impact: the MusicXML encoder and parser were
|
||||
split from two monoliths into focused, grouped extension files, and the
|
||||
parser's per-`<note>` state was extracted into a dedicated value type.
|
||||
|
||||
> **Namespace note:** the score DSL exposes capitalized free functions
|
||||
> (`Note`, `Chord`, `Voice`, `Slur`, `Crescendo`, …). `Voice` in particular can
|
||||
> collide with same-named types from other frameworks — qualify or alias if you
|
||||
> hit an ambiguity.
|
||||
|
||||
---
|
||||
|
||||
## 1.0 — Initial release
|
||||
|
||||
First public release: the real-time synthesis engine, the `Generator` /
|
||||
`Synthesizer` protocols and standard-library generators, the Core Audio and
|
||||
non-real-time drivers, `LyrebirdUI`, the `lyrebird` CLI and project scaffolding,
|
||||
and the AUv3 plug-in support.
|
||||
@@ -82,7 +82,7 @@ open class LyrebirdAudioUnit: AUAudioUnit {
|
||||
/// Required override. Construct and return the synthesizer instance that this
|
||||
/// AU should host.
|
||||
///
|
||||
/// `@MainActor` (Phase 201): the override constructs a `@MainActor` `SynthesizerBase`
|
||||
/// `@MainActor`: the override constructs a `@MainActor` `SynthesizerBase`
|
||||
/// subclass, so the factory must be main-actor-isolated for a consumer building under
|
||||
/// the MainActor-default mode to override it with no concurrency annotations — the same
|
||||
/// rationale as `SynthesizerBase.build()`. Invoked from `init` on the host's main thread.
|
||||
@@ -443,7 +443,7 @@ open class LyrebirdAudioUnit: AUAudioUnit {
|
||||
newEngine.auOutputBusOffsets = _outputBusOffsets
|
||||
newEngine.auInputBusOffsets = _inputBusOffsets
|
||||
try newEngine.start()
|
||||
// `engine.add` is `@MainActor` (Phase 201). `allocateRenderResources()` overrides
|
||||
// `engine.add` is `@MainActor`. `allocateRenderResources()` overrides
|
||||
// `AUAudioUnit`'s nonisolated declaration, so this method cannot itself be
|
||||
// `@MainActor`. AU hosts usually call render-resource allocation on the main thread,
|
||||
// but the contract does not guarantee it — the bridge runs the add inline when on
|
||||
|
||||
@@ -240,6 +240,11 @@ public final class NRTDriver: AudioDriver {
|
||||
throw NRTDriverError.writeFailed(writeStatus)
|
||||
}
|
||||
}
|
||||
|
||||
// Synchronous render is done and the freeWorker timer only starts after this
|
||||
// returns — emit any per-block event-drop warning here so it reaches the console
|
||||
// even if the process exits before that timer (or `stop()`) runs.
|
||||
engine.drainPerBlockEventDropWarning()
|
||||
}
|
||||
|
||||
public func stop() {
|
||||
|
||||
@@ -117,6 +117,9 @@ import Synchronization
|
||||
/// `invalidate()` uses a `.releasing` store; `isValid` uses an `.acquiring` load.
|
||||
/// `LyrebirdBuffer` is safe to share across threads:
|
||||
/// - The validity flag is protected by `Atomic<Bool>`.
|
||||
/// - `loopLength` is likewise an `Atomic<Int>` (`.acquiring` load / `.releasing` store
|
||||
/// via ``setLoopLength(_:)``) — read every sample by `PlayBuffer`-family generators,
|
||||
/// written once (non-RT) after e.g. a looper pedal finishes recording a take.
|
||||
/// - `channelCount` and `count` are `let` constants — freely readable on any thread.
|
||||
/// - Sample data can be written from the RT thread by `RecordBuffer` via the internal
|
||||
/// `write(_:frame:channel:)` method. The buffer is **not safe for concurrent non-RT
|
||||
@@ -240,6 +243,45 @@ public final class LyrebirdBuffer: @unchecked Sendable {
|
||||
return bufRate / engineSampleRate
|
||||
}
|
||||
|
||||
/// Number of frames that `PlayBuffer`-family generators should wrap (looping) or
|
||||
/// clamp (non-looping) against, distinct from `count` (the full allocated size).
|
||||
///
|
||||
/// Defaults to `count` at init, matching the historical full-buffer looping
|
||||
/// behaviour. Narrow this after recording a take that is shorter than the
|
||||
/// buffer's max-duration allocation — e.g. a looper pedal that pre-allocates
|
||||
/// 60 seconds but records a shorter take — so playback wraps only over the
|
||||
/// actually-recorded region without reallocating the buffer.
|
||||
///
|
||||
/// **RT contract.** Stored as an `Atomic<Int>` rather than behind `_writeLock`:
|
||||
/// this value is read on every sample inside `PlayBuffer`'s per-sample read loop
|
||||
/// (`lyrebirdBufferRead`), so a lock acquired every sample would be the wrong
|
||||
/// tool. An atomic load costs nothing close to a lock and gives torn-free reads
|
||||
/// of a single `Int`. Set from a non-RT thread via ``setLoopLength(_:)``, e.g.
|
||||
/// once after recording stops.
|
||||
private let _loopLength: Atomic<Int>
|
||||
|
||||
/// Current loop/clamp bound for `PlayBuffer`-family generators, in frames.
|
||||
///
|
||||
/// `1...count`, defaulting to `count`. Read with an `.acquiring` load — safe to
|
||||
/// call from the RT thread inside a per-sample read loop.
|
||||
public var loopLength: Int {
|
||||
_loopLength.load(ordering: .acquiring)
|
||||
}
|
||||
|
||||
/// Narrow (or restore) the frame count that `PlayBuffer`-family generators wrap
|
||||
/// or clamp against.
|
||||
///
|
||||
/// Call from a non-RT thread — typically once, right after recording stops
|
||||
/// (e.g. a looper pedal calling this with the frame count `RecordBuffer`
|
||||
/// actually wrote, so playback loops over just the recorded take instead of
|
||||
/// the full max-duration allocation).
|
||||
///
|
||||
/// - Parameter length: Desired loop length in frames. Clamped to `[1, count]`.
|
||||
public func setLoopLength(_ length: Int) {
|
||||
let clamped: Int = max(1, min(length, count))
|
||||
_loopLength.store(clamped, ordering: .releasing)
|
||||
}
|
||||
|
||||
/// Atomic validity flag. `true` after `init`, `false` after `invalidate()`.
|
||||
private let _isValid: Atomic<Bool>
|
||||
|
||||
@@ -460,6 +502,7 @@ public final class LyrebirdBuffer: @unchecked Sendable {
|
||||
_storage = UnsafeMutablePointer<Double>.allocate(capacity: total)
|
||||
_storage.initialize(repeating: 0, count: total)
|
||||
_isValid = Atomic<Bool>(true)
|
||||
_loopLength = Atomic<Int>(count)
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
@@ -44,3 +44,45 @@ func _resolvedChannelCount(_ bus: any ValidBus) -> Int {
|
||||
bus.channelCount == Int.max ? 1 : max(1, bus.channelCount)
|
||||
}
|
||||
|
||||
/// Traps at graph-build time when a ``ControlBus`` is handed to an **audio**-rate bus generator
|
||||
/// (`Out.Audio` / `ReplaceOut.Audio` / `In.Audio`).
|
||||
///
|
||||
/// Those generators address the **audio**-bus pool by index. A `ControlBus`'s `index` lives in the
|
||||
/// separate control-bus index space, so writing/reading it through an audio-rate generator hits
|
||||
/// audio memory at that number — silently colliding with unrelated audio buses (including the
|
||||
/// hardware output buses at low indices). There is no correct use for it: reach for the control-rate
|
||||
/// variant (`Out.Control` / `ReplaceOut.Control` / `In.Control`, or `SynthesizerBase`'s
|
||||
/// `controlOutput(bus:source:)` / `controlInput(bus:)`).
|
||||
///
|
||||
/// Runs only at `init` (graph construction, main thread) — never on the RT render path. A plain
|
||||
/// `Int` bus is the deliberate raw-index escape hatch and is intentionally not checked.
|
||||
@inline(__always)
|
||||
func _preconditionAudioRateBus(_ bus: any ValidBus) {
|
||||
precondition(
|
||||
!(bus is ControlBus),
|
||||
"A ControlBus was passed to an audio-rate bus generator (Out.Audio / ReplaceOut.Audio / "
|
||||
+ "In.Audio), which addresses the audio-bus pool at that index and collides with unrelated "
|
||||
+ "audio buses. Use the control-rate variant (Out.Control / ReplaceOut.Control / In.Control, "
|
||||
+ "or controlOutput(bus:source:) / controlInput(bus:))."
|
||||
)
|
||||
}
|
||||
|
||||
/// Traps at graph-build time when an ``AudioBus`` is handed to a **control**-rate bus generator
|
||||
/// (`Out.Control` / `ReplaceOut.Control` / `In.Control`).
|
||||
///
|
||||
/// The mirror of ``_preconditionAudioRateBus(_:)``: control-rate generators address the
|
||||
/// **control**-bus pool by index, so an `AudioBus`'s `index` reaches control memory at that number
|
||||
/// and collides with unrelated control buses. Use the audio-rate variant (`Out.Audio` /
|
||||
/// `ReplaceOut.Audio` / `In.Audio`, or `output(bus:source:)` / `input(bus:)`). `Int` buses are not
|
||||
/// checked. `init`-time only, never RT.
|
||||
@inline(__always)
|
||||
func _preconditionControlRateBus(_ bus: any ValidBus) {
|
||||
precondition(
|
||||
!(bus is AudioBus),
|
||||
"An AudioBus was passed to a control-rate bus generator (Out.Control / ReplaceOut.Control / "
|
||||
+ "In.Control), which addresses the control-bus pool at that index and collides with "
|
||||
+ "unrelated control buses. Use the audio-rate variant (Out.Audio / ReplaceOut.Audio / "
|
||||
+ "In.Audio, or output(bus:source:) / input(bus:))."
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -33,112 +33,138 @@
|
||||
///
|
||||
/// ## Per-distribution examples
|
||||
///
|
||||
/// All examples use `TemporalTendency` with fixed `.value(…)` parameters and
|
||||
/// `seed: 0xDEADCAFE12345678`. Actual outputs vary with seed.
|
||||
/// All examples build a ``TemporalStream`` over a ``TemporalTendency`` with fixed
|
||||
/// `.value(…)` parameters and `seed: 0xDEADCAFE12345678` — the seed lives on the stream,
|
||||
/// not on the algorithm. Actual outputs vary with seed. The values below are pinned by
|
||||
/// `DistributionKindGoldenValueTests`, since a typecheck cannot see them drift.
|
||||
///
|
||||
/// **`.uniform`** — flat probability across \[lo, hi\]
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .uniform, parX: .value(0), parY: .value(1), seed: s)
|
||||
/// TemporalStream(TemporalTendency(distribution: .uniform,
|
||||
/// parX: .value(0), parY: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.744, 0.046, 0.799, 0.681, 0.517
|
||||
/// ```
|
||||
///
|
||||
/// **`.lpRand`** — squared uniform, biases toward lo
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .lpRand, parX: .value(0), parY: .value(1), seed: s)
|
||||
/// // → 0.080, 0.337, 0.057, 0.830, 0.788
|
||||
/// TemporalStream(TemporalTendency(distribution: .lpRand,
|
||||
/// parX: .value(0), parY: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.553, 0.002, 0.638, 0.464, 0.267
|
||||
/// ```
|
||||
///
|
||||
/// **`.hpRand`** — squared uniform mirrored, biases toward hi
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .hpRand, parX: .value(0), parY: .value(1), seed: s)
|
||||
/// // → 0.878, 0.944, 0.939, 0.983, 0.899
|
||||
/// TemporalStream(TemporalTendency(distribution: .hpRand,
|
||||
/// parX: .value(0), parY: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.447, 0.998, 0.362, 0.536, 0.733
|
||||
/// ```
|
||||
///
|
||||
/// **`.meanRand`** — average of two uniforms (triangular), biases toward midpoint
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .meanRand, parX: .value(0), parY: .value(1), seed: s)
|
||||
/// // → 0.624, 0.559, 0.512, 0.586, 0.308
|
||||
/// TemporalStream(TemporalTendency(distribution: .meanRand,
|
||||
/// parX: .value(0), parY: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.395, 0.740, 0.400, 0.410, 0.899
|
||||
/// ```
|
||||
///
|
||||
/// **`.expRand`** — log-uniform, exponential density in \[lo, hi\]; lo and hi must be > 0
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .expRand, parX: .value(1), parY: .value(100), seed: s)
|
||||
/// // → 15.709, 4.710, 14.831, 26.119, 47.853
|
||||
/// TemporalStream(TemporalTendency(distribution: .expRand,
|
||||
/// parX: .value(1), parY: .value(100)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 30.743, 1.234, 39.596, 23.035, 10.818
|
||||
/// ```
|
||||
///
|
||||
/// **`.exponential`** — standard exponential; parX is the rate λ (higher = shorter tail)
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .exponential, parX: .value(1), seed: s)
|
||||
/// // → 0.023, 0.489, 0.126, 2.077, 0.354
|
||||
/// TemporalStream(TemporalTendency(distribution: .exponential, parX: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.296, 3.085, 0.225, 0.384, 0.660
|
||||
/// ```
|
||||
///
|
||||
/// **`.gamma`** — shape parameter k; k=1 → exponential, k>1 → bell shifted right
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .gamma, parX: .value(2), seed: s)
|
||||
/// // → 0.412, 2.998, 0.709, 1.409, 3.985
|
||||
/// TemporalStream(TemporalTendency(distribution: .gamma, parX: .value(2)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 2.812, 0.776, 1.756, 1.326, 3.649
|
||||
/// ```
|
||||
///
|
||||
/// **`.laplace`** — double-exponential, sharp central peak; parX is scale b
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .laplace, parX: .value(1), seed: s)
|
||||
/// // → 3.533, 0.530, -0.197, 0.195, -1.792
|
||||
/// TemporalStream(TemporalTendency(distribution: .laplace, parX: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.669, -2.392, 0.910, 0.450, 0.035
|
||||
/// ```
|
||||
///
|
||||
/// **`.alaplace`** — asymmetric Laplace (p=0.7), right tail heavier; parX is scale b
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .alaplace, parX: .value(1), seed: s)
|
||||
/// // → -0.706, 7.906, 1.867, -0.495, 1.675
|
||||
/// TemporalStream(TemporalTendency(distribution: .alaplace, parX: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.527, -3.898, 1.332, -0.039, -0.433
|
||||
/// ```
|
||||
///
|
||||
/// **`.hcos`** — half-cosine, smooth bell centred at 0; output ≈ \[−d/π, d/π\]
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .hcos, parX: .value(1), seed: s)
|
||||
/// // → -0.080, 0.021, 0.024, -0.366, 0.215
|
||||
/// TemporalStream(TemporalTendency(distribution: .hcos, parX: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.162, -0.363, 0.204, 0.118, 0.011
|
||||
/// ```
|
||||
///
|
||||
/// **`.logistic`** — logistic distribution, heavier tails than Gaussian; parX is scale s
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .logistic, parX: .value(1), seed: s)
|
||||
/// // → 0.299, 3.453, -1.994, 1.842, -0.640
|
||||
/// TemporalStream(TemporalTendency(distribution: .logistic, parX: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 1.066, -3.039, 1.379, 0.759, 0.068
|
||||
/// ```
|
||||
///
|
||||
/// **`.poisson`** — integer counts; parX is mean λ (clamped to \[0.001, 30\])
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .poisson, parX: .value(3), seed: s)
|
||||
/// // → 3.0, 3.0, 6.0, 5.0, 0.0
|
||||
/// TemporalStream(TemporalTendency(distribution: .poisson, parX: .value(3)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 1.000, 4.000, 4.000, 1.000, 4.000
|
||||
/// ```
|
||||
///
|
||||
/// **`.arcsin`** — U-shaped, concentrates near ±dispersion; output in \[−disp, disp\]
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .arcsin, parX: .value(1), seed: s)
|
||||
/// // → 0.616, -0.148, -0.986, -0.987, -0.417
|
||||
/// TemporalStream(TemporalTendency(distribution: .arcsin, parX: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.693, -0.990, 0.807, 0.539, 0.054
|
||||
/// ```
|
||||
///
|
||||
/// **`.betaRand`** — flexible shape in \[lo, hi\]; alpha/beta (parA/parB) control skew
|
||||
/// ```swift
|
||||
/// // alpha=2, beta=5 → left-skewed bell (peak near lo side)
|
||||
/// TemporalTendency(distribution: .betaRand,
|
||||
/// parX: .value(0), parY: .value(1),
|
||||
/// parA: .value(2), parB: .value(5), seed: s)
|
||||
/// // → 0.395, 0.539, 0.272, 0.386, 0.304
|
||||
/// TemporalStream(TemporalTendency(distribution: .betaRand,
|
||||
/// parX: .value(0), parY: .value(1),
|
||||
/// parA: .value(2), parB: .value(5)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.482, 0.301, 0.471, 0.415, 0.066
|
||||
///
|
||||
/// // alpha=1, beta=1 → uniform; alpha=beta → symmetric; alpha<1, beta<1 → bimodal
|
||||
/// ```
|
||||
///
|
||||
/// **`.cauchy`** — heavy-tailed, parX=mean, parY=spread; set parA>0 for positive-only
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .cauchy, parX: .value(0), parY: .value(1), seed: s)
|
||||
/// // → -1.457, 0.800, 10.047, 1.641, -1.570
|
||||
/// TemporalStream(TemporalTendency(distribution: .cauchy,
|
||||
/// parX: .value(0), parY: .value(1)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.962, -6.916, 1.366, 0.640, 0.054
|
||||
/// // (occasional extreme outliers are characteristic of Cauchy)
|
||||
///
|
||||
/// // Positive-only (parA > 0):
|
||||
/// TemporalTendency(distribution: .cauchy, parX: .value(0), parY: .value(1), parA: .value(1))
|
||||
/// TemporalStream(TemporalTendency(distribution: .cauchy, parX: .value(0),
|
||||
/// parY: .value(1), parA: .value(1)))
|
||||
/// ```
|
||||
///
|
||||
/// **`.gauss`** — Gaussian; parX=standard deviation, parY=mean
|
||||
/// ```swift
|
||||
/// TemporalTendency(distribution: .gauss, parX: .value(1), parY: .value(0), seed: s)
|
||||
/// // → -0.554, 1.390, 0.086, -0.441, 2.156
|
||||
/// TemporalStream(TemporalTendency(distribution: .gauss,
|
||||
/// parX: .value(1), parY: .value(0)),
|
||||
/// seed: 0xDEADCAFE12345678).collect(5)
|
||||
/// // → 0.738, -0.281, -0.238, 0.068, 0.328
|
||||
/// ```
|
||||
public enum DistributionKind: Sendable {
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
// EngineDispatch.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Dispatch a throwing engine mutation to the main queue — preserving the
|
||||
/// `SynthesisEngine.pendingQueue` single-producer invariant — and log on failure.
|
||||
///
|
||||
/// Shared by the language-side context types (`LyrebirdRoutineContext`,
|
||||
/// `LyrebirdProcessContext`) whose `add` / `schedule` calls cross from a routine
|
||||
/// or process thread onto the main thread. `label` names the call site in the
|
||||
/// failure message only.
|
||||
func lyrebirdDispatchEngineOp(
|
||||
_ label: String,
|
||||
_ work: @escaping @MainActor () throws -> Void
|
||||
) {
|
||||
DispatchQueue.main.async {
|
||||
// The block runs on the main queue, so main-actor isolation holds.
|
||||
MainActor.assumeIsolated {
|
||||
do { try work() }
|
||||
catch { print("[Lyrebird] \(label) failed: \(error)") }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -165,6 +165,7 @@ public final class EngineHost: @unchecked Sendable {
|
||||
numAudioBuses: config.numAudioBuses,
|
||||
numControlBuses: config.numControlBuses,
|
||||
eventQueueCapacity: config.eventQueueCapacity,
|
||||
maxEventsPerBlock: config.maxEventsPerBlock,
|
||||
driver: config.driver
|
||||
)
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import Foundation
|
||||
/// Run a `@MainActor` node-tree mutation from a language-side dispatch adapter that may
|
||||
/// execute either on the main thread or inline on a background NRT driver thread.
|
||||
///
|
||||
/// Phase 201 made the engine's add / schedule path and `Synthesizer.build`/`release`/`free`
|
||||
/// The engine's add / schedule path and `Synthesizer.build`/`release`/`free` are
|
||||
/// `@MainActor`. Most language-side adapters dispatch those mutations through
|
||||
/// `DispatchQueue.main.async`, so they already run on main. Two adapters can run a mutation
|
||||
/// **inline on the calling thread**:
|
||||
@@ -19,6 +19,9 @@ import Foundation
|
||||
/// would invoke the mutation off-main.
|
||||
/// - `LyrebirdAudioUnit.allocateRenderResources()` — overrides a nonisolated `AUAudioUnit`
|
||||
/// method; AU hosts *usually* call it on main, but the contract does not guarantee it.
|
||||
/// - `LyrebirdRoutineContext.onMain(_:)` — lets a `@Sendable` routine/task body construct
|
||||
/// `@MainActor` synthesizers. A body always runs on its own background thread, so this
|
||||
/// caller always takes the off-main `.sync` branch.
|
||||
///
|
||||
/// A bare `MainActor.assumeIsolated` would **trap** (`dispatch_assert_queue_fail`) on those
|
||||
/// off-main paths. This bridge instead:
|
||||
|
||||
@@ -29,14 +29,18 @@ import Synchronization
|
||||
/// driver: driver
|
||||
/// )
|
||||
/// try engine.start()
|
||||
/// engine.add(MySynth())
|
||||
/// try engine.add(MySynth())
|
||||
/// // … audio running …
|
||||
/// engine.stop()
|
||||
/// ```
|
||||
///
|
||||
/// **Thread safety** — `processBlock` runs on the Core Audio RT thread. All public
|
||||
/// scheduling methods (`add`, `remove`, `schedule`) are safe to call from the main thread.
|
||||
/// Never call `processBlock` directly from the main thread while the engine is running.
|
||||
/// **Thread safety** — `processBlock` runs on the Core Audio RT thread; never call it directly
|
||||
/// while the engine is running. `add(_:)` / `schedule(_:at:)` are `@MainActor`-isolated: the
|
||||
/// `pendingQueue` is single-producer, so every enqueue must come from the main thread.
|
||||
/// `remove(_:)` is `nonisolated` — it unbinds via atomics and enqueues a pointer-only event, so
|
||||
/// it is callable from any non-RT thread. From a `LyrebirdRoutine` / `LyrebirdTask` body, go
|
||||
/// through the context (``LyrebirdRoutineContext/add(_:)``, which dispatches to main) rather
|
||||
/// than calling the engine directly. See `ARCHITECTURE.md` §1 and §9.
|
||||
public final class SynthesisEngine {
|
||||
|
||||
/// Process-unique identity. Used by the engine ownership-binding system
|
||||
@@ -158,7 +162,12 @@ public final class SynthesisEngine {
|
||||
/// Hard cap on events processed per block. The staging arrays are reserved to this capacity
|
||||
/// in start(); if more events arrive, excess events are silently dropped rather than
|
||||
/// triggering a realloc on the RT thread.
|
||||
private static let maxEventsPerBlock: Int = 256
|
||||
///
|
||||
/// Bounds both the number of events firing within one block and the future-event
|
||||
/// look-ahead carried across block boundaries (`carryOverEvents`). Set at `init` from
|
||||
/// the `maxEventsPerBlock` parameter; immutable thereafter, so the RT thread reads it
|
||||
/// as a plain `let` with no synchronisation. Default `lyrebirdDefaultMaxEventsPerBlock`.
|
||||
public let maxEventsPerBlock: Int
|
||||
|
||||
/// Lock-free queue for events posted by the main thread, drained by the RT thread.
|
||||
/// Capacity is set at init time and must be a power of two.
|
||||
@@ -192,6 +201,64 @@ public final class SynthesisEngine {
|
||||
_droppedCount.wrappingAdd(1, ordering: .relaxed)
|
||||
}
|
||||
|
||||
/// Monotonic counter of scheduling events dropped by the RT thread because a single
|
||||
/// block's event budget (`maxEventsPerBlock`) was exceeded — either too many events
|
||||
/// fired in one block or the future-event look-ahead overflowed. Distinct from
|
||||
/// `pendingQueueDroppedCount`, which counts main-thread enqueue failures. Read from
|
||||
/// any thread; reset with `resetPerBlockEventDropCount()`.
|
||||
private let _perBlockEventDroppedCount: Atomic<UInt64> = Atomic<UInt64>(0)
|
||||
|
||||
/// Latch set by the RT thread when it drops at least one event for exceeding
|
||||
/// `maxEventsPerBlock`. A non-RT drain (`drainPerBlockEventDropWarning()`) checks,
|
||||
/// prints a one-line console warning, and clears it — so the warning is emitted at
|
||||
/// most once per drain interval regardless of how many events were dropped.
|
||||
private let _perBlockEventDropped: Atomic<Bool> = Atomic<Bool>(false)
|
||||
|
||||
/// Number of scheduling events the RT thread dropped because `maxEventsPerBlock` was
|
||||
/// exceeded since the engine started (or since the last `resetPerBlockEventDropCount()`).
|
||||
/// A non-zero value means a block's onset density or future look-ahead exceeded the cap —
|
||||
/// raise `maxEventsPerBlock` at engine init, or throttle scheduling on the caller side.
|
||||
public var perBlockEventDropCount: UInt64 {
|
||||
_perBlockEventDroppedCount.load(ordering: .acquiring)
|
||||
}
|
||||
|
||||
/// Resets the per-block event-drop counter to zero. Call from any non-RT thread.
|
||||
public func resetPerBlockEventDropCount() {
|
||||
_perBlockEventDroppedCount.store(0, ordering: .releasing)
|
||||
}
|
||||
|
||||
/// Records a per-block event-budget drop. RT-safe: two atomic ops, no allocation,
|
||||
/// no locking, no string construction. Called from `processBlock`'s event-drain loop
|
||||
/// when a staging array is already at `maxEventsPerBlock`.
|
||||
///
|
||||
/// The counter increment is `.relaxed`; the latch store is `.releasing` so it
|
||||
/// synchronizes-with the drain's `.acquiring` CAS in `drainPerBlockEventDropWarning()`.
|
||||
/// That release/acquire edge guarantees the drain thread, once it observes the latch
|
||||
/// set, also sees the counter increment that precedes it in program order — so the
|
||||
/// printed drop count is never stale.
|
||||
@inline(__always)
|
||||
private func _recordPerBlockEventDrop() {
|
||||
_perBlockEventDroppedCount.wrappingAdd(1, ordering: .relaxed)
|
||||
_perBlockEventDropped.store(true, ordering: .releasing)
|
||||
}
|
||||
|
||||
/// Checks the per-block event-drop latch and, if set, prints a one-line console
|
||||
/// warning naming `maxEventsPerBlock` and the cumulative drop count, then clears the
|
||||
/// latch. Non-RT only — shares the `freeWorker`/stop drain sites with the kill-queue
|
||||
/// overflow warning so no RT-thread `print` is ever attempted.
|
||||
internal func drainPerBlockEventDropWarning() {
|
||||
guard _perBlockEventDropped.compareExchange(
|
||||
expected: true,
|
||||
desired: false,
|
||||
successOrdering: .acquiring,
|
||||
failureOrdering: .relaxed
|
||||
).exchanged else { return }
|
||||
let dropped: UInt64 = _perBlockEventDroppedCount.load(ordering: .relaxed)
|
||||
print("[Lyrebird] Warning: scheduling events dropped — a block exceeded "
|
||||
+ "maxEventsPerBlock (\(maxEventsPerBlock)); \(dropped) event(s) dropped so far. "
|
||||
+ "Raise maxEventsPerBlock at engine init, or throttle/spread scheduling.")
|
||||
}
|
||||
|
||||
/// Update the synth/group counters by `delta` (typically `+1` or `-1`).
|
||||
/// Called from `applyEvent` on the RT thread — uses relaxed atomic adds (no allocation,
|
||||
/// no locks, no runtime type checks). The `isGroup` flag is read from `PreparedNode`,
|
||||
@@ -732,13 +799,13 @@ public final class SynthesisEngine {
|
||||
///
|
||||
/// ```swift
|
||||
/// // Pre-processing: runs before all instruments
|
||||
/// engine.add(InputLimiter(), position: .before(engine.mainGroup))
|
||||
/// try engine.add(InputLimiter(), position: .before(engine.mainGroup))
|
||||
///
|
||||
/// // Default instrument add — lands in mainGroup
|
||||
/// engine.add(MySynth())
|
||||
/// try engine.add(MySynth())
|
||||
///
|
||||
/// // Post-processing: runs after all instruments
|
||||
/// engine.add(MasterReverb(), position: .after(engine.mainGroup))
|
||||
/// try engine.add(MasterReverb(), position: .after(engine.mainGroup))
|
||||
/// ```
|
||||
public let mainGroup: Group = Group(persistent: true)
|
||||
|
||||
@@ -763,6 +830,7 @@ public final class SynthesisEngine {
|
||||
numAudioBuses: Int = lyrebirdDefaultNumAudioBuses,
|
||||
numControlBuses: Int = lyrebirdDefaultNumControlBuses,
|
||||
eventQueueCapacity: Int = lyrebirdDefaultEventQueueCapacity,
|
||||
maxEventsPerBlock: Int = lyrebirdDefaultMaxEventsPerBlock,
|
||||
driver: AudioDriver
|
||||
) {
|
||||
// Initialise RT-thread identity TLS key from this known non-RT call
|
||||
@@ -780,6 +848,10 @@ public final class SynthesisEngine {
|
||||
eventQueueCapacity > 0 && eventQueueCapacity & (eventQueueCapacity - 1) == 0,
|
||||
"eventQueueCapacity \(eventQueueCapacity) must be a power of two (e.g. 256, 512, 1024, 2048)."
|
||||
)
|
||||
precondition(
|
||||
maxEventsPerBlock > 0,
|
||||
"maxEventsPerBlock \(maxEventsPerBlock) must be positive."
|
||||
)
|
||||
// Resolution order: explicit caller value → driver suggestion → full block (no sub-blocking).
|
||||
// Explicit values are validated strictly. Driver suggestions that don't fit blockSize are
|
||||
// silently ignored (fall back to full-block mode) so small-blockSize test engines don't crash.
|
||||
@@ -811,6 +883,7 @@ public final class SynthesisEngine {
|
||||
self.numInputChannels = numInputChannels
|
||||
self.numAudioBuses = numAudioBuses
|
||||
self.numControlBuses = numControlBuses
|
||||
self.maxEventsPerBlock = maxEventsPerBlock
|
||||
self.busAllocator = BusAllocator(
|
||||
numAudioBuses: numAudioBuses,
|
||||
numControlBuses: numControlBuses,
|
||||
@@ -998,9 +1071,9 @@ public final class SynthesisEngine {
|
||||
|
||||
// Pre-allocate staging arrays to the hard cap — no RT realloc as long as
|
||||
// events-per-block stays within maxEventsPerBlock (excess are dropped).
|
||||
carryOverEvents.reserveCapacity(SynthesisEngine.maxEventsPerBlock)
|
||||
thisBlockEvents.reserveCapacity(SynthesisEngine.maxEventsPerBlock)
|
||||
nextCarryOver.reserveCapacity(SynthesisEngine.maxEventsPerBlock)
|
||||
carryOverEvents.reserveCapacity(maxEventsPerBlock)
|
||||
thisBlockEvents.reserveCapacity(maxEventsPerBlock)
|
||||
nextCarryOver.reserveCapacity(maxEventsPerBlock)
|
||||
|
||||
// Force eager initialization of module-level `let` constants used by RBJ filters.
|
||||
// Swift module-level lets are protected by swift_once on first access; touching them
|
||||
@@ -1076,6 +1149,7 @@ public final class SynthesisEngine {
|
||||
}
|
||||
self.drainParameterSourceKillQueue()
|
||||
self.drainBufferSwapKillQueue()
|
||||
self.drainPerBlockEventDropWarning()
|
||||
}
|
||||
_setState(.stopped)
|
||||
}
|
||||
@@ -1493,7 +1567,7 @@ public final class SynthesisEngine {
|
||||
// Read clock atomically; only processBlock writes it (RT thread single-writer).
|
||||
let blockStart: SampleTime = _currentTime.load(ordering: .relaxed)
|
||||
let blockEnd: SampleTime = blockStart + SampleTime(blockSize)
|
||||
let cap: Int = SynthesisEngine.maxEventsPerBlock
|
||||
let cap: Int = maxEventsPerBlock
|
||||
|
||||
thisBlockEvents.removeAll(keepingCapacity: true)
|
||||
nextCarryOver.removeAll(keepingCapacity: true)
|
||||
@@ -1502,8 +1576,10 @@ public final class SynthesisEngine {
|
||||
for event: ScheduledEvent in carryOverEvents {
|
||||
if event.targetTime < blockEnd {
|
||||
if thisBlockEvents.count < cap { thisBlockEvents.append(event) }
|
||||
else { _recordPerBlockEventDrop() }
|
||||
} else {
|
||||
if nextCarryOver.count < cap { nextCarryOver.append(event) }
|
||||
else { _recordPerBlockEventDrop() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1512,8 +1588,10 @@ public final class SynthesisEngine {
|
||||
let event: ScheduledEvent = pendingQueue.dequeue() {
|
||||
if event.targetTime < blockEnd {
|
||||
if thisBlockEvents.count < cap { thisBlockEvents.append(event) }
|
||||
else { _recordPerBlockEventDrop() }
|
||||
} else {
|
||||
if nextCarryOver.count < cap { nextCarryOver.append(event) }
|
||||
else { _recordPerBlockEventDrop() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1745,7 +1823,7 @@ public final class SynthesisEngine {
|
||||
/// All allocation and `build()`/`rebuildGraph()` happen here on the calling thread;
|
||||
/// the RT thread never allocates in `applyEvent`.
|
||||
/// `@MainActor`: invokes `build()` / `rebuildGraph()` (the `@MainActor` language-side
|
||||
/// add surface — Phase 201). The node-tree add path runs on the main thread by
|
||||
/// add surface). The node-tree add path runs on the main thread by
|
||||
/// contract (it also touches `nodeTreeMirror`, observed by SwiftUI).
|
||||
@MainActor private func prepareNode(_ synth: any Synthesizer) -> PreparedNode {
|
||||
if let base: SynthesizerBase = synth as? SynthesizerBase {
|
||||
@@ -1780,6 +1858,7 @@ public final class SynthesisEngine {
|
||||
}
|
||||
self.drainParameterSourceKillQueue()
|
||||
self.drainBufferSwapKillQueue()
|
||||
self.drainPerBlockEventDropWarning()
|
||||
}
|
||||
timer.resume()
|
||||
freeQueueTimer = timer
|
||||
|
||||
@@ -65,6 +65,10 @@ public struct SynthesisEngineConfig {
|
||||
/// `lyrebirdDefaultEventQueueCapacity`.
|
||||
public let eventQueueCapacity: Int
|
||||
|
||||
/// Per-block scheduling cap — events firing per block and future look-ahead
|
||||
/// depth. Must be positive. Defaults to `lyrebirdDefaultMaxEventsPerBlock`.
|
||||
public let maxEventsPerBlock: Int
|
||||
|
||||
/// Audio driver instance. Held by the engine via `let driver` after
|
||||
/// `init`. Caller transfers ownership at construction time.
|
||||
public let driver: AudioDriver
|
||||
@@ -78,6 +82,7 @@ public struct SynthesisEngineConfig {
|
||||
numAudioBuses: Int = lyrebirdDefaultNumAudioBuses,
|
||||
numControlBuses: Int = lyrebirdDefaultNumControlBuses,
|
||||
eventQueueCapacity: Int = lyrebirdDefaultEventQueueCapacity,
|
||||
maxEventsPerBlock: Int = lyrebirdDefaultMaxEventsPerBlock,
|
||||
driver: AudioDriver
|
||||
) {
|
||||
self.blockSize = blockSize
|
||||
@@ -88,6 +93,7 @@ public struct SynthesisEngineConfig {
|
||||
self.numAudioBuses = numAudioBuses
|
||||
self.numControlBuses = numControlBuses
|
||||
self.eventQueueCapacity = eventQueueCapacity
|
||||
self.maxEventsPerBlock = maxEventsPerBlock
|
||||
self.driver = driver
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -57,7 +57,7 @@ public struct LyrebirdMessageContext: @unchecked Sendable {
|
||||
let args: SynthArgs = SynthArgs(engine, synth)
|
||||
_dispatch {
|
||||
// `_dispatch` runs this on main (default `DispatchQueue.main.async`) or inline on
|
||||
// the NRT driver thread. `engine.add` is `@MainActor` (Phase 201); the bridge runs
|
||||
// the NRT driver thread. `engine.add` is `@MainActor`; the bridge runs
|
||||
// it inline when already on main and hops synchronously otherwise — never traps.
|
||||
lyrebirdRunMainActorMutation {
|
||||
do { try args.engine.add(args.synth) }
|
||||
@@ -133,7 +133,7 @@ public struct LyrebirdMessageContext: @unchecked Sendable {
|
||||
// but a warning posts to LyrebirdMessageCenter so debug builds get
|
||||
// visibility into typo'd OSC / MIDI param names that would
|
||||
// otherwise route silently to nowhere.
|
||||
// `updateParameter` is `@MainActor` (Phase 201). `_dispatch` runs this on main
|
||||
// `updateParameter` is `@MainActor`. `_dispatch` runs this on main
|
||||
// (default) or inline on the NRT driver — the bridge runs inline on main and hops
|
||||
// synchronously off-main, never trapping.
|
||||
lyrebirdRunMainActorMutation {
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
// BeatTrack.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Real-time beat / tempo tracker.
|
||||
///
|
||||
/// Estimates the period and phase of a musical pulse from an **onset detection
|
||||
/// function** (ODF) by autocorrelation with phase locking, emitting
|
||||
/// beat-synchronous triggers plus a continuous tempo estimate. The ODF source
|
||||
/// is selected by ``BeatTrackODF``:
|
||||
///
|
||||
/// - ``BeatTrackODF/spectralFlux(analysis:)`` — FFT-fed; the tracker computes
|
||||
/// its own ODF as the spectral flux of a paired ``SpectralChain/Audio``
|
||||
/// (drop-in; equivalent to SuperCollider's `BeatTrack`).
|
||||
/// - ``BeatTrackODF/feature(_:)`` — feature-fed; you supply the ODF as any
|
||||
/// signal (equivalent to SuperCollider's `BeatTrack2`).
|
||||
///
|
||||
/// Control-rate, 4-output: see ``BeatTrack/Control`` for the row layout.
|
||||
///
|
||||
/// > This is an independent implementation of standard autocorrelation tempo
|
||||
/// > induction with phase locking (see `BeatTrackerCore`), not a port of any
|
||||
/// > SuperCollider source.
|
||||
public enum BeatTrack {
|
||||
|
||||
/// Control-rate beat tracker. ODF source chosen at init via ``BeatTrackODF``.
|
||||
///
|
||||
/// Emits four output rows:
|
||||
/// - `0` — **beat** trigger (`1.0` for the block a beat fires on, else `0.0`)
|
||||
/// - `1` — **eighth** trigger (2× the beat rate)
|
||||
/// - `2` — **sixteenth** trigger (4× the beat rate)
|
||||
/// - `3` — **tempo** in BPM (continuous)
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - odf: Onset-detection-function source — FFT-fed or feature-fed.
|
||||
/// - minBPM: Slowest detectable tempo. Read once at init. Defaults to ``beatTrackMinBPM``.
|
||||
/// - maxBPM: Fastest detectable tempo. Read once at init. Defaults to ``beatTrackMaxBPM``.
|
||||
/// - preferredBPM: Preference-weight centre + pre-lock default tempo. Read
|
||||
/// once at init. Defaults to ``beatTrackPreferredBPM``.
|
||||
/// - windowSeconds: ODF history length for autocorrelation. Read once at
|
||||
/// init. Defaults to ``beatTrackMaxWindowSeconds``.
|
||||
public final class Control: GeneratorBase, ControlGenerator {
|
||||
|
||||
/// Internal ODF source + the input refs each mode needs. Only one mode's
|
||||
/// state is live; the spectral-flux state (`_prevMag`, `_isFirstFrame`)
|
||||
/// is dormant in feature mode.
|
||||
private enum Source {
|
||||
case spectralFlux(analysis: SpectralChain.Audio?, spectral: SpectralBuffer)
|
||||
case feature(input: any ValidGeneratorInput, isGenerator: Bool)
|
||||
}
|
||||
|
||||
private let _source: Source
|
||||
private var _prevMag: [Float]
|
||||
private var _isFirstFrame: Bool = true
|
||||
private let _core: BeatTrackerCore
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
public override var outputChannelCount: Int { beatTrackOutputRowCount }
|
||||
|
||||
// MARK: - Public inits
|
||||
|
||||
/// - Parameters:
|
||||
/// - odf: Onset-detection-function source — FFT-fed or feature-fed.
|
||||
/// - minBPM: Slowest detectable tempo. Read once at init. Defaults to ``beatTrackMinBPM``.
|
||||
/// - maxBPM: Fastest detectable tempo. Read once at init. Defaults to ``beatTrackMaxBPM``.
|
||||
/// - preferredBPM: Preference-weight centre + pre-lock default tempo.
|
||||
/// Read once at init. Defaults to ``beatTrackPreferredBPM``.
|
||||
/// - windowSeconds: ODF history length for autocorrelation. Read once
|
||||
/// at init. Defaults to ``beatTrackMaxWindowSeconds``.
|
||||
public convenience init(
|
||||
odf: BeatTrackODF,
|
||||
minBPM: Double = beatTrackMinBPM,
|
||||
maxBPM: Double = beatTrackMaxBPM,
|
||||
preferredBPM: Double = beatTrackPreferredBPM,
|
||||
windowSeconds: Double = beatTrackMaxWindowSeconds
|
||||
) {
|
||||
let source: Source
|
||||
switch odf {
|
||||
case .spectralFlux(let chain):
|
||||
source = .spectralFlux(analysis: chain, spectral: chain.spectralBuffer)
|
||||
case .feature(let signal):
|
||||
let resolved: any ValidGeneratorInput = signal._resolvedInput()
|
||||
source = .feature(input: resolved, isGenerator: resolved is any Generator)
|
||||
}
|
||||
self.init(
|
||||
source: source,
|
||||
minBPM: minBPM,
|
||||
maxBPM: maxBPM,
|
||||
preferredBPM: preferredBPM,
|
||||
windowSeconds: windowSeconds
|
||||
)
|
||||
}
|
||||
|
||||
/// FFT-fed convenience: track the spectral flux of `analysis`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - analysis: Paired ``SpectralChain/Audio`` (analyze-only). Its
|
||||
/// `spectralBuffer` is read once per audio block to compute spectral flux.
|
||||
/// - minBPM: Slowest detectable tempo. Defaults to ``beatTrackMinBPM``.
|
||||
/// - maxBPM: Fastest detectable tempo. Defaults to ``beatTrackMaxBPM``.
|
||||
/// - preferredBPM: Preference-weight centre + pre-lock default tempo.
|
||||
/// Defaults to ``beatTrackPreferredBPM``.
|
||||
/// - windowSeconds: ODF history length. Defaults to ``beatTrackMaxWindowSeconds``.
|
||||
public convenience init(
|
||||
analysis: SpectralChain.Audio,
|
||||
minBPM: Double = beatTrackMinBPM,
|
||||
maxBPM: Double = beatTrackMaxBPM,
|
||||
preferredBPM: Double = beatTrackPreferredBPM,
|
||||
windowSeconds: Double = beatTrackMaxWindowSeconds
|
||||
) {
|
||||
self.init(
|
||||
source: .spectralFlux(analysis: analysis, spectral: analysis.spectralBuffer),
|
||||
minBPM: minBPM,
|
||||
maxBPM: maxBPM,
|
||||
preferredBPM: preferredBPM,
|
||||
windowSeconds: windowSeconds
|
||||
)
|
||||
}
|
||||
|
||||
/// Feature-fed convenience: track an externally supplied ODF signal.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - feature: Onset detection function signal. Reduced to one ODF value
|
||||
/// per audio block (block max).
|
||||
/// - minBPM: Slowest detectable tempo. Defaults to ``beatTrackMinBPM``.
|
||||
/// - maxBPM: Fastest detectable tempo. Defaults to ``beatTrackMaxBPM``.
|
||||
/// - preferredBPM: Preference-weight centre + pre-lock default tempo.
|
||||
/// Defaults to ``beatTrackPreferredBPM``.
|
||||
/// - windowSeconds: ODF history length. Defaults to ``beatTrackMaxWindowSeconds``.
|
||||
public convenience init(
|
||||
feature: any ValidGeneratorInput,
|
||||
minBPM: Double = beatTrackMinBPM,
|
||||
maxBPM: Double = beatTrackMaxBPM,
|
||||
preferredBPM: Double = beatTrackPreferredBPM,
|
||||
windowSeconds: Double = beatTrackMaxWindowSeconds
|
||||
) {
|
||||
let resolved: any ValidGeneratorInput = feature._resolvedInput()
|
||||
self.init(
|
||||
source: .feature(input: resolved, isGenerator: resolved is any Generator),
|
||||
minBPM: minBPM,
|
||||
maxBPM: maxBPM,
|
||||
preferredBPM: preferredBPM,
|
||||
windowSeconds: windowSeconds
|
||||
)
|
||||
}
|
||||
|
||||
/// Buffer-only FFT-fed convenience. For tests / advanced use; no analysis
|
||||
/// auto-pull (the caller drives the chain populating `spectral`).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - spectral: Spectral frame buffer read each block for flux.
|
||||
/// - minBPM: Slowest detectable tempo. Defaults to ``beatTrackMinBPM``.
|
||||
/// - maxBPM: Fastest detectable tempo. Defaults to ``beatTrackMaxBPM``.
|
||||
/// - preferredBPM: Preference-weight centre + pre-lock default tempo.
|
||||
/// Defaults to ``beatTrackPreferredBPM``.
|
||||
/// - windowSeconds: ODF history length. Defaults to ``beatTrackMaxWindowSeconds``.
|
||||
public convenience init(
|
||||
spectral: SpectralBuffer,
|
||||
minBPM: Double = beatTrackMinBPM,
|
||||
maxBPM: Double = beatTrackMaxBPM,
|
||||
preferredBPM: Double = beatTrackPreferredBPM,
|
||||
windowSeconds: Double = beatTrackMaxWindowSeconds
|
||||
) {
|
||||
self.init(
|
||||
source: .spectralFlux(analysis: nil, spectral: spectral),
|
||||
minBPM: minBPM,
|
||||
maxBPM: maxBPM,
|
||||
preferredBPM: preferredBPM,
|
||||
windowSeconds: windowSeconds
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Designated init
|
||||
|
||||
private init(
|
||||
source: Source,
|
||||
minBPM: Double,
|
||||
maxBPM: Double,
|
||||
preferredBPM: Double,
|
||||
windowSeconds: Double
|
||||
) {
|
||||
self._source = source
|
||||
switch source {
|
||||
case .spectralFlux(_, let spectral):
|
||||
self._prevMag = [Float](repeating: 0, count: spectral.binCount)
|
||||
case .feature:
|
||||
self._prevMag = []
|
||||
}
|
||||
self._core = BeatTrackerCore(
|
||||
minBPM: minBPM,
|
||||
maxBPM: maxBPM,
|
||||
preferredBPM: preferredBPM,
|
||||
windowSeconds: windowSeconds,
|
||||
featureRateHz: beatTrackFeatureRateHz
|
||||
)
|
||||
super.init(channels: beatTrackOutputRowCount)
|
||||
_setupSubBlockBuffer(channels: beatTrackOutputRowCount)
|
||||
}
|
||||
|
||||
// MARK: - Compute
|
||||
|
||||
// Bypass the sub-block loop: the ODF advances once per audio block (the
|
||||
// spectral buffer once per FFT hop) and the tracker state must too.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let odf: Double = computeODF(graph: graph, count: count)
|
||||
|
||||
_core.processBlock(
|
||||
odf: odf,
|
||||
sampleCount: count,
|
||||
sampleRate: graph.engine.sampleRate
|
||||
)
|
||||
|
||||
previousOutputValue = fillBeatTrackerOutput(
|
||||
into: &_result, core: _core, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
/// Per-block onset-detection-function value for the active source.
|
||||
private func computeODF(graph: SynthGraph, count: Int) -> Double {
|
||||
switch _source {
|
||||
case .spectralFlux(let analysis, let spectral):
|
||||
_ = analysis?.calculatedSamples(graph: graph, count: count)
|
||||
return spectralFlux(spectral)
|
||||
case .feature(let input, let isGenerator):
|
||||
// Scalar feature → constant ODF (no per-block heap alloc);
|
||||
// generator feature → block-max of its output row.
|
||||
if isGenerator {
|
||||
let row: [Double] = input.calculatedSamples(
|
||||
graph: graph, count: count).first ?? []
|
||||
return blockMaxODF(row, count: count)
|
||||
}
|
||||
return max(0.0, input.floatValue(graph: graph))
|
||||
}
|
||||
}
|
||||
|
||||
/// Frame-to-frame magnitude-change flux (onset proxy). Identical measure
|
||||
/// to ``SpectralFlux``: RMS of per-bin magnitude differences. Returns `0`
|
||||
/// on the first block (no previous frame to compare).
|
||||
private func spectralFlux(_ spectral: SpectralBuffer) -> Double {
|
||||
let binCount: Int = spectral.binCount
|
||||
guard binCount > 0 else { return 0.0 }
|
||||
|
||||
if _isFirstFrame {
|
||||
for k: Int in 0..<binCount {
|
||||
_prevMag[k] = spectral.magnitude(at: k)
|
||||
}
|
||||
_isFirstFrame = false
|
||||
return 0.0
|
||||
}
|
||||
|
||||
var sumSquares: Double = 0.0
|
||||
for k: Int in 0..<binCount {
|
||||
let mag: Double = Double(spectral.magnitude(at: k))
|
||||
let prev: Double = Double(_prevMag[k])
|
||||
let diff: Double = mag - prev
|
||||
sumSquares += diff * diff
|
||||
_prevMag[k] = Float(mag)
|
||||
}
|
||||
return (sumSquares / Double(binCount)).squareRoot()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
// GeneratorEnum conformance omitted: BeatTrack is Control-rate only.
|
||||
@@ -0,0 +1,72 @@
|
||||
// BeatTrackConstants.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Number of ``BeatTrack`` output rows: beat, eighth, sixteenth, tempo.
|
||||
public let beatTrackOutputRowCount: Int = 4
|
||||
|
||||
/// Onset-detection-function (ODF) decimation target rate in Hz. The per-block
|
||||
/// ODF is reduced to one feature per `round(sampleRate / beatTrackFeatureRateHz)`
|
||||
/// samples so the autocorrelation window length is independent of block size.
|
||||
/// `≈ 86 Hz` matches the conventional 512-sample STFT hop at 44.1 kHz.
|
||||
public let beatTrackFeatureRateHz: Double = 86.0
|
||||
|
||||
/// Length of the ODF history (seconds) retained for autocorrelation. Six seconds
|
||||
/// at `beatTrackFeatureRateHz` is ≈ 516 features — long enough to resolve tempi
|
||||
/// down to ``beatTrackMinBPM`` with several beat periods in the window.
|
||||
public let beatTrackMaxWindowSeconds: Double = 6.0
|
||||
|
||||
/// Slowest detectable tempo (BPM). Sets the longest autocorrelation lag.
|
||||
public let beatTrackMinBPM: Double = 60.0
|
||||
|
||||
/// Fastest detectable tempo (BPM). Sets the shortest autocorrelation lag.
|
||||
public let beatTrackMaxBPM: Double = 200.0
|
||||
|
||||
/// Centre of the tempo-preference weight and the pre-lock default tempo (BPM).
|
||||
/// The weight biases the autocorrelation peak toward perceptually likely tempi,
|
||||
/// resolving the octave ambiguity between a pulse and its harmonics.
|
||||
public let beatTrackPreferredBPM: Double = 120.0
|
||||
|
||||
/// Width (in octaves) of the log-Gaussian tempo-preference weight.
|
||||
public let beatTrackPreferenceWidthOctaves: Double = 0.9
|
||||
|
||||
/// One-pole smoothing factor applied to the beat period across successive
|
||||
/// analyses. `0` = instant; `1` = frozen. Higher values steady the tempo output.
|
||||
public let beatTrackTempoSmoothing: Double = 0.9
|
||||
|
||||
/// Re-run tempo induction (autocorrelation + phase realignment) every N emitted
|
||||
/// ODF features. A small power of two amortises the analysis cost.
|
||||
public let beatTrackAnalysisHopFeatures: Int = 8
|
||||
|
||||
/// Time constant (seconds) of the running-mean subtraction used to whiten the
|
||||
/// ODF before autocorrelation. Removes DC offset / slow drift so a non-zero
|
||||
/// baseline does not bias the periodicity estimate.
|
||||
public let beatTrackMeanAdaptSeconds: Double = 1.0
|
||||
|
||||
/// Minimum normalised autocorrelation peak required to update the tempo estimate.
|
||||
/// Below this the input is treated as having no clear pulse (silence / noise);
|
||||
/// the previous period is held and the phase free-runs.
|
||||
public let beatTrackMinPeakStrength: Double = 1.0e-9
|
||||
|
||||
/// Seconds per minute — used in the BPM ↔ feature-lag conversions.
|
||||
internal let beatTrackSecondsPerMinute: Double = 60.0
|
||||
|
||||
/// Eighth-note subdivisions per beat (row 1 fires at this multiple of the beat rate).
|
||||
internal let beatTrackEighthsPerBeat: Double = 2.0
|
||||
|
||||
/// Sixteenth-note subdivisions per beat (row 2 fires at this multiple of the beat rate).
|
||||
internal let beatTrackSixteenthsPerBeat: Double = 4.0
|
||||
|
||||
/// Coefficient `½` in the log-Gaussian preference exponent `−½ · z²`.
|
||||
internal let beatTrackGaussianExponentCoeff: Double = 0.5
|
||||
|
||||
/// Coefficient `½` in the parabolic peak-interpolation offset `½ · (yₘ − yₚ) / denom`.
|
||||
internal let beatTrackParabolicCoeff: Double = 0.5
|
||||
|
||||
/// Minimum parabola curvature magnitude for peak refinement; below this the
|
||||
/// interpolation is degenerate and the integer lag is returned unchanged.
|
||||
internal let beatTrackParabolicEpsilon: Double = 1.0e-12
|
||||
@@ -0,0 +1,59 @@
|
||||
// BeatTrackHelpers.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import Foundation
|
||||
|
||||
/// Peak ODF value across one audio block. Onsets are impulsive, so the max
|
||||
/// preserves the peak regardless of where in the block it lands. Returns `0` for
|
||||
/// an empty row.
|
||||
@inline(__always)
|
||||
internal func blockMaxODF(_ row: [Double], count: Int) -> Double {
|
||||
guard !row.isEmpty else { return 0.0 }
|
||||
let n: Int = min(count, row.count)
|
||||
var peak: Double = 0.0
|
||||
for i: Int in 0..<n {
|
||||
let v: Double = row[i]
|
||||
if v > peak { peak = v }
|
||||
}
|
||||
return peak
|
||||
}
|
||||
|
||||
/// Fill the 4-row beat-tracker output buffer flat across the block from the
|
||||
/// core's per-block trigger / tempo state. Returns the row-0 (beat) value for
|
||||
/// `previousOutputValue`. No heap allocation — the four row values are filled
|
||||
/// directly (no intermediate array).
|
||||
@inline(__always)
|
||||
internal func fillBeatTrackerOutput(
|
||||
into result: inout [[Double]],
|
||||
core: BeatTrackerCore,
|
||||
count: Int
|
||||
) -> Double {
|
||||
let beat: Double = core.beatTriggered ? 1.0 : 0.0
|
||||
let eighth: Double = core.eighthTriggered ? 1.0 : 0.0
|
||||
let sixteenth: Double = core.sixteenthTriggered ? 1.0 : 0.0
|
||||
let tempo: Double = core.tempoBPM
|
||||
fillFlatRow(&result, row: 0, value: beat, count: count)
|
||||
fillFlatRow(&result, row: 1, value: eighth, count: count)
|
||||
fillFlatRow(&result, row: 2, value: sixteenth, count: count)
|
||||
fillFlatRow(&result, row: 3, value: tempo, count: count)
|
||||
return beat
|
||||
}
|
||||
|
||||
/// Fill one output row with a constant value over `count` samples.
|
||||
@inline(__always)
|
||||
private func fillFlatRow(
|
||||
_ result: inout [[Double]],
|
||||
row: Int,
|
||||
value: Double,
|
||||
count: Int
|
||||
) {
|
||||
var v: Double = value
|
||||
result[row].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
vDSP_vfillD(&v, base, 1, vDSP_Length(count))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// BeatTrackODF.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Selects where ``BeatTrack`` gets its onset detection function (ODF) — the
|
||||
/// one-dimensional signal whose peaks the tracker locks onto.
|
||||
///
|
||||
/// This is the implementation flag that folds the two SuperCollider beat-tracker
|
||||
/// flavours into a single ``BeatTrack`` generator. The cases carry different
|
||||
/// inputs (an FFT chain vs an arbitrary signal), so the selector is an enum
|
||||
/// rather than a `Bool`.
|
||||
public enum BeatTrackODF {
|
||||
|
||||
/// FFT-fed: compute the ODF internally as the spectral flux of `analysis`
|
||||
/// (the same frame-to-frame magnitude-change measure as ``SpectralFlux``).
|
||||
/// Drop-in — wire an analyze-only ``SpectralChain/Audio`` on the source you
|
||||
/// want to track. Equivalent to SuperCollider's `BeatTrack`.
|
||||
case spectralFlux(analysis: SpectralChain.Audio)
|
||||
|
||||
/// Feature-fed: take an externally supplied ODF — any signal whose peaks
|
||||
/// coincide with onsets (``SpectralFlux``, ``OnsetDetector``, an
|
||||
/// amplitude-difference feature, …). Reduced to one ODF value per audio
|
||||
/// block (block max). Equivalent to SuperCollider's `BeatTrack2`.
|
||||
case feature(any ValidGeneratorInput)
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
// BeatTrackerCore.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Shared autocorrelation tempo + beat-phase tracker backing ``BeatTrack`` (both
|
||||
/// the FFT-fed and feature-fed ODF sources). Independent of the `Generator`
|
||||
/// machinery: it consumes one per-audio-block onset-detection-function (ODF)
|
||||
/// value at a time and produces beat / eighth / sixteenth triggers plus a
|
||||
/// continuous tempo estimate.
|
||||
///
|
||||
/// All buffers are allocated once at `init`; ``processBlock(odf:sampleCount:)``
|
||||
/// performs no allocation and is safe to call from the render thread (the
|
||||
/// front-end generators call it from `_computeSamples`).
|
||||
///
|
||||
/// ## Pipeline
|
||||
/// 1. **Decimation** — per-block ODF values are combined by max over a feature
|
||||
/// hop of `round(sampleRate / featureRateHz)` samples; each completed hop
|
||||
/// emits one ODF feature.
|
||||
/// 2. **Whitening** — a running mean is subtracted and the result half-wave
|
||||
/// rectified, removing DC / drift bias.
|
||||
/// 3. **History** — features are pushed into a power-of-two ring buffer.
|
||||
/// 4. **Tempo induction** — every ``analysisHop`` features the windowed ODF is
|
||||
/// autocorrelated over the lag range for `[minBPM, maxBPM]`, weighted by a
|
||||
/// log-Gaussian preference curve; the peak lag is the smoothed beat period.
|
||||
/// 5. **Phase locking** — a phase accumulator advances at the current tempo;
|
||||
/// each analysis re-aligns it to the recent ODF peaks.
|
||||
///
|
||||
/// Algorithm is an independent implementation of standard autocorrelation tempo
|
||||
/// induction with phase locking — not a port of any SuperCollider source.
|
||||
final class BeatTrackerCore {
|
||||
|
||||
// MARK: - Configuration (fixed at init)
|
||||
|
||||
/// Samples per emitted feature. Sample-rate dependent, so resolved lazily on
|
||||
/// the first ``processBlock(odf:sampleCount:sampleRate:)`` (the only piece of
|
||||
/// state that needs the engine sample rate — ring size and lag range derive
|
||||
/// from the nominal feature rate alone). `0` until resolved.
|
||||
private var featureHop: Int = 0
|
||||
private let ringMask: Int
|
||||
private let windowLen: Int
|
||||
private let lagMin: Int
|
||||
private let lagMax: Int
|
||||
private let analysisHop: Int
|
||||
private let preferredLag: Double
|
||||
private let preferenceWidth: Double
|
||||
private let tempoSmoothing: Double
|
||||
private let meanAdaptCoeff: Double
|
||||
private let featureRate: Double
|
||||
private let minPeriod: Double
|
||||
private let maxPeriod: Double
|
||||
|
||||
// MARK: - Buffers (allocated once)
|
||||
|
||||
private var ring: [Double]
|
||||
|
||||
// MARK: - Decimation state
|
||||
|
||||
private var sampleAccum: Int = 0
|
||||
private var odfAccum: Double = 0.0
|
||||
|
||||
// MARK: - History state
|
||||
|
||||
private var writeIndex: Int = 0
|
||||
private var featureCount: Int = 0
|
||||
private var meanODF: Double = 0.0
|
||||
|
||||
// MARK: - Tempo / phase state
|
||||
|
||||
private var period: Double
|
||||
private var phase: Double = 0.0
|
||||
private var analysisCountdown: Int
|
||||
|
||||
// MARK: - Per-block outputs
|
||||
|
||||
/// `true` when a beat fired during the most recent ``processBlock(odf:sampleCount:)``.
|
||||
private(set) var beatTriggered: Bool = false
|
||||
/// `true` when an eighth-note subdivision fired (2× the beat rate).
|
||||
private(set) var eighthTriggered: Bool = false
|
||||
/// `true` when a sixteenth-note subdivision fired (4× the beat rate).
|
||||
private(set) var sixteenthTriggered: Bool = false
|
||||
/// Current tempo estimate in BPM.
|
||||
private(set) var tempoBPM: Double
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - minBPM: Slowest detectable tempo.
|
||||
/// - maxBPM: Fastest detectable tempo.
|
||||
/// - preferredBPM: Preference-weight centre + pre-lock default tempo.
|
||||
/// - windowSeconds: ODF history length for autocorrelation.
|
||||
/// - featureRateHz: ODF decimation target rate.
|
||||
init(
|
||||
minBPM: Double,
|
||||
maxBPM: Double,
|
||||
preferredBPM: Double,
|
||||
windowSeconds: Double,
|
||||
featureRateHz: Double
|
||||
) {
|
||||
let safeFeatureRate: Double = max(1.0, featureRateHz)
|
||||
let safeMinBPM: Double = max(1.0, min(minBPM, maxBPM))
|
||||
let safeMaxBPM: Double = max(safeMinBPM + 1.0, max(minBPM, maxBPM))
|
||||
|
||||
self.featureRate = safeFeatureRate
|
||||
|
||||
// Lag range from the tempo bounds: lag (features) = featureRate · 60 / BPM.
|
||||
let minLagD: Double = safeFeatureRate * beatTrackSecondsPerMinute / safeMaxBPM
|
||||
let maxLagD: Double = safeFeatureRate * beatTrackSecondsPerMinute / safeMinBPM
|
||||
self.lagMin = max(1, Int(minLagD.rounded(.down)))
|
||||
self.lagMax = max(self.lagMin + 1, Int(maxLagD.rounded(.up)))
|
||||
self.minPeriod = minLagD
|
||||
self.maxPeriod = maxLagD
|
||||
|
||||
// History window: at least a few of the longest periods.
|
||||
let requestedFeatures: Int = max(
|
||||
self.lagMax * 2,
|
||||
Int((max(0.1, windowSeconds) * safeFeatureRate).rounded(.up))
|
||||
)
|
||||
let ringSize: Int = lyrebirdNextPowerOfTwo(max(2, requestedFeatures))
|
||||
self.ring = [Double](repeating: 0.0, count: ringSize)
|
||||
self.ringMask = ringSize - 1
|
||||
// Cap the analysis window so the oldest (sample, lag) pair never wraps
|
||||
// past the ring onto just-written features: even when `requestedFeatures`
|
||||
// is an exact power of two (then `ringSize == requestedFeatures`), keep
|
||||
// `windowLen + lagMax ≤ ringSize`.
|
||||
self.windowLen = max(self.lagMin + 1, min(requestedFeatures, ringSize - self.lagMax))
|
||||
|
||||
self.analysisHop = max(1, beatTrackAnalysisHopFeatures)
|
||||
self.preferredLag = safeFeatureRate * beatTrackSecondsPerMinute / max(1.0, preferredBPM)
|
||||
self.preferenceWidth = max(0.05, beatTrackPreferenceWidthOctaves)
|
||||
self.tempoSmoothing = min(0.999, max(0.0, beatTrackTempoSmoothing))
|
||||
|
||||
// Per-feature one-pole coefficient for the running-mean subtraction.
|
||||
let meanTimeFeatures: Double = max(1.0, beatTrackMeanAdaptSeconds * safeFeatureRate)
|
||||
self.meanAdaptCoeff = 1.0 - Foundation.exp(-1.0 / meanTimeFeatures)
|
||||
|
||||
self.period = self.preferredLag
|
||||
self.tempoBPM = max(safeMinBPM, min(safeMaxBPM, preferredBPM))
|
||||
self.analysisCountdown = self.analysisHop
|
||||
}
|
||||
|
||||
// MARK: - Per-block entry point
|
||||
|
||||
/// Feed one audio block's ODF value. Updates the decimation accumulator and,
|
||||
/// for every completed feature hop, advances the tracker. The trigger /
|
||||
/// tempo outputs reflect the state after this block.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - odf: This block's onset-detection-function value (≥ 0).
|
||||
/// - sampleCount: Number of audio samples in this block.
|
||||
/// - sampleRate: Engine sample rate (Hz); resolves the feature hop on first call.
|
||||
func processBlock(odf: Double, sampleCount: Int, sampleRate: Double) {
|
||||
beatTriggered = false
|
||||
eighthTriggered = false
|
||||
sixteenthTriggered = false
|
||||
|
||||
if featureHop == 0 {
|
||||
let safeSampleRate: Double = max(1.0, sampleRate)
|
||||
featureHop = max(1, Int((safeSampleRate / featureRate).rounded()))
|
||||
}
|
||||
|
||||
let safeODF: Double = odf.isFinite ? max(0.0, odf) : 0.0
|
||||
odfAccum = max(odfAccum, safeODF)
|
||||
sampleAccum += max(0, sampleCount)
|
||||
|
||||
// Emit as many features as the accumulated sample count allows (handles
|
||||
// blocks longer than one feature hop). Triggers OR across features.
|
||||
while sampleAccum >= featureHop {
|
||||
sampleAccum -= featureHop
|
||||
emitFeature(odfAccum)
|
||||
odfAccum = 0.0
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Feature processing
|
||||
|
||||
private func emitFeature(_ raw: Double) {
|
||||
// Whiten: subtract a slow running mean, half-wave rectify.
|
||||
meanODF += (raw - meanODF) * meanAdaptCoeff
|
||||
var value: Double = raw - meanODF
|
||||
if value < 0.0 { value = 0.0 }
|
||||
value = denormalsToZero(value)
|
||||
|
||||
ring[writeIndex & ringMask] = value
|
||||
writeIndex += 1
|
||||
featureCount += 1
|
||||
|
||||
advancePhase()
|
||||
|
||||
analysisCountdown -= 1
|
||||
// Need at least the longest lag plus one beat of history before the ACF
|
||||
// is meaningful.
|
||||
if analysisCountdown <= 0 && featureCount >= lagMax + lagMin {
|
||||
analysisCountdown = analysisHop
|
||||
runAnalysis()
|
||||
}
|
||||
}
|
||||
|
||||
/// Advance the beat-phase accumulator by one feature at the current tempo,
|
||||
/// firing nested subdivision triggers on grid crossings.
|
||||
private func advancePhase() {
|
||||
let safePeriod: Double = max(1.0, period)
|
||||
let increment: Double = 1.0 / safePeriod
|
||||
let raw: Double = phase + increment
|
||||
|
||||
// Nested crossings: beat = integer, eighth = ½, sixteenth = ¼. A beat
|
||||
// boundary (raw ≥ 1) also crosses an eighth and sixteenth boundary, so
|
||||
// counts accumulate as beats:N, eighths:2N, sixteenths:4N.
|
||||
if raw >= 1.0 { beatTriggered = true }
|
||||
if Foundation.floor(raw * beatTrackEighthsPerBeat)
|
||||
> Foundation.floor(phase * beatTrackEighthsPerBeat) { eighthTriggered = true }
|
||||
if Foundation.floor(raw * beatTrackSixteenthsPerBeat)
|
||||
> Foundation.floor(phase * beatTrackSixteenthsPerBeat) { sixteenthTriggered = true }
|
||||
|
||||
var wrapped: Double = raw.truncatingRemainder(dividingBy: 1.0)
|
||||
if wrapped < 0.0 { wrapped += 1.0 }
|
||||
phase = wrapped
|
||||
}
|
||||
|
||||
// MARK: - Tempo induction
|
||||
|
||||
private func runAnalysis() {
|
||||
let available: Int = min(featureCount, windowLen)
|
||||
guard available > lagMax else { return }
|
||||
|
||||
var bestLag: Int = 0
|
||||
var bestScore: Double = 0.0
|
||||
var bestRawPeak: Double = 0.0
|
||||
|
||||
// Weighted, length-normalised autocorrelation over the candidate lags.
|
||||
for lag: Int in lagMin...lagMax {
|
||||
let terms: Int = available - lag
|
||||
if terms <= 0 { continue }
|
||||
var sum: Double = 0.0
|
||||
for j: Int in 0..<terms {
|
||||
let a: Double = ring[(writeIndex - 1 - j) & ringMask]
|
||||
let b: Double = ring[(writeIndex - 1 - j - lag) & ringMask]
|
||||
sum += a * b
|
||||
}
|
||||
let acf: Double = sum / Double(terms)
|
||||
let weight: Double = preferenceWeight(forLag: Double(lag))
|
||||
let score: Double = acf * weight
|
||||
if score > bestScore {
|
||||
bestScore = score
|
||||
bestLag = lag
|
||||
bestRawPeak = acf
|
||||
}
|
||||
}
|
||||
|
||||
// No clear pulse → hold the current period and let the phase free-run.
|
||||
guard bestLag > 0, bestRawPeak > beatTrackMinPeakStrength else { return }
|
||||
|
||||
let refinedLag: Double = parabolicPeak(around: bestLag, available: available)
|
||||
let clampedLag: Double = min(maxPeriod, max(minPeriod, refinedLag))
|
||||
|
||||
period = tempoSmoothing * period + (1.0 - tempoSmoothing) * clampedLag
|
||||
period = max(1.0, period)
|
||||
tempoBPM = beatTrackSecondsPerMinute * featureRate / period
|
||||
|
||||
realignPhase(periodLag: clampedLag)
|
||||
}
|
||||
|
||||
/// Log-Gaussian preference weight centred on ``preferredLag``.
|
||||
private func preferenceWeight(forLag lag: Double) -> Double {
|
||||
let octaves: Double = Foundation.log2(lag / preferredLag)
|
||||
let z: Double = octaves / preferenceWidth
|
||||
return Foundation.exp(-beatTrackGaussianExponentCoeff * z * z)
|
||||
}
|
||||
|
||||
/// Sub-feature peak location via parabolic interpolation of the
|
||||
/// length-normalised ACF at `lag-1, lag, lag+1`.
|
||||
private func parabolicPeak(around lag: Int, available: Int) -> Double {
|
||||
let lagD: Double = Double(lag)
|
||||
guard lag - 1 >= lagMin, lag + 1 <= lagMax else { return lagD }
|
||||
let ym: Double = normalisedACF(lag: lag - 1, available: available)
|
||||
let y0: Double = normalisedACF(lag: lag, available: available)
|
||||
let yp: Double = normalisedACF(lag: lag + 1, available: available)
|
||||
let denom: Double = ym - 2.0 * y0 + yp
|
||||
if abs(denom) < beatTrackParabolicEpsilon { return lagD }
|
||||
let delta: Double = beatTrackParabolicCoeff * (ym - yp) / denom
|
||||
if delta < -1.0 || delta > 1.0 { return lagD }
|
||||
return lagD + delta
|
||||
}
|
||||
|
||||
private func normalisedACF(lag: Int, available: Int) -> Double {
|
||||
let terms: Int = available - lag
|
||||
if terms <= 0 { return 0.0 }
|
||||
var sum: Double = 0.0
|
||||
for j: Int in 0..<terms {
|
||||
let a: Double = ring[(writeIndex - 1 - j) & ringMask]
|
||||
let b: Double = ring[(writeIndex - 1 - j - lag) & ringMask]
|
||||
sum += a * b
|
||||
}
|
||||
return sum / Double(terms)
|
||||
}
|
||||
|
||||
/// Re-align the phase accumulator so beat crossings coincide with the recent
|
||||
/// ODF peaks. Finds the grid offset (mod the integer period) whose comb of
|
||||
/// features carries the most onset energy.
|
||||
private func realignPhase(periodLag: Double) {
|
||||
let p: Int = max(1, Int(periodLag.rounded()))
|
||||
let available: Int = min(featureCount, windowLen)
|
||||
guard available >= p else { return }
|
||||
|
||||
var bestOffset: Int = 0
|
||||
var bestEnergy: Double = -1.0
|
||||
for offset: Int in 0..<p {
|
||||
var energy: Double = 0.0
|
||||
var j: Int = offset
|
||||
while j < available {
|
||||
energy += ring[(writeIndex - 1 - j) & ringMask]
|
||||
j += p
|
||||
}
|
||||
if energy > bestEnergy {
|
||||
bestEnergy = energy
|
||||
bestOffset = offset
|
||||
}
|
||||
}
|
||||
|
||||
// The most recent feature (offset 0) sits `bestOffset` features after the
|
||||
// last on-grid beat, so its beat fraction is bestOffset / period.
|
||||
var newPhase: Double = Double(bestOffset) / max(1.0, period)
|
||||
newPhase = newPhase.truncatingRemainder(dividingBy: 1.0)
|
||||
if newPhase < 0.0 { newPhase += 1.0 }
|
||||
phase = newPhase
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
// Loudness.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Psychoacoustic loudness meter — perceived loudness in **sones** from the
|
||||
/// magnitude spectrum of a paired analyze-only ``SpectralChain/Audio``.
|
||||
///
|
||||
/// Three fidelity models are folded into the one generator behind a
|
||||
/// ``LoudnessModel`` flag (mirroring the `Balance` `logDomain:` and `BeatTrack`
|
||||
/// `BeatTrackODF` folds):
|
||||
///
|
||||
/// - ``LoudnessModel/barkEstimate`` — cheap Stevens power-law band estimate.
|
||||
/// - ``LoudnessModel/realtimeZwicker(smask:tmask:)`` — SC `Loudness`-style
|
||||
/// critical-band Zwicker loudness with spectral + temporal masking.
|
||||
/// - ``LoudnessModel/iso532b(field:)`` — full ISO 532 B / DIN 45631 stationary
|
||||
/// Zwicker loudness.
|
||||
///
|
||||
/// Control-rate, single-row output (sones). See ``Loudness/Control``.
|
||||
///
|
||||
/// > **Clean-room note.** SuperCollider's `Loudness` (Nick Collins) is GPL. This
|
||||
/// > is an independent implementation from the published Zwicker model and the
|
||||
/// > ISO 532 B / DIN 45631 standard; output is in sones, not bit-exact with SC.
|
||||
public enum Loudness {
|
||||
|
||||
/// Control-rate loudness meter. Model selected at init via ``LoudnessModel``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - model: Loudness model + its parameters. Defaults to
|
||||
/// ``LoudnessModel/realtimeZwicker(smask:tmask:)`` with the standard
|
||||
/// `smask`/`tmask`.
|
||||
/// - analysis: Paired ``SpectralChain/Audio`` (analyze-only). Its
|
||||
/// `spectralBuffer` is read once per audio block.
|
||||
/// - sampleRate: Sample rate in Hz (bin→frequency mapping + block timing).
|
||||
/// - calibrationDB: dBFS→SPL offset. Defaults to ``loudnessDefaultCalibrationDB``.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset (sones). Defaults to `0.0`.
|
||||
public final class Control: GeneratorBase, ControlGenerator {
|
||||
|
||||
private let _analysis: SpectralChain.Audio?
|
||||
private let _spectral: SpectralBuffer
|
||||
private let _model: LoudnessModel
|
||||
private let _core: LoudnessBandCore
|
||||
private let _sampleRate: Double
|
||||
private var _mulAdd: MulAddSpec
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 0.0
|
||||
|
||||
/// - Parameters:
|
||||
/// - model: Loudness model + parameters. Defaults to
|
||||
/// ``LoudnessModel/realtimeZwicker(smask:tmask:)``.
|
||||
/// - analysis: Paired ``SpectralChain/Audio`` (analyze-only).
|
||||
/// - sampleRate: Sample rate in Hz.
|
||||
/// - calibrationDB: dBFS→SPL offset. Defaults to ``loudnessDefaultCalibrationDB``.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset (sones). Defaults to `0.0`.
|
||||
public convenience init(
|
||||
model: LoudnessModel = .realtimeZwicker(
|
||||
smask: loudnessDefaultSMask, tmask: loudnessDefaultTMask),
|
||||
analysis: SpectralChain.Audio,
|
||||
sampleRate: Double,
|
||||
calibrationDB: Double = loudnessDefaultCalibrationDB,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
self.init(
|
||||
model: model,
|
||||
analysis: analysis,
|
||||
spectral: analysis.spectralBuffer,
|
||||
sampleRate: sampleRate,
|
||||
calibrationDB: calibrationDB,
|
||||
mul: mul,
|
||||
add: add
|
||||
)
|
||||
}
|
||||
|
||||
/// Buffer-only init. For tests / advanced use; no analysis auto-pull.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - model: Loudness model + parameters.
|
||||
/// - spectral: Spectral frame buffer read each block.
|
||||
/// - sampleRate: Sample rate in Hz.
|
||||
/// - calibrationDB: dBFS→SPL offset. Defaults to ``loudnessDefaultCalibrationDB``.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset (sones). Defaults to `0.0`.
|
||||
public convenience init(
|
||||
model: LoudnessModel = .realtimeZwicker(
|
||||
smask: loudnessDefaultSMask, tmask: loudnessDefaultTMask),
|
||||
spectral: SpectralBuffer,
|
||||
sampleRate: Double,
|
||||
calibrationDB: Double = loudnessDefaultCalibrationDB,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
self.init(
|
||||
model: model,
|
||||
analysis: nil,
|
||||
spectral: spectral,
|
||||
sampleRate: sampleRate,
|
||||
calibrationDB: calibrationDB,
|
||||
mul: mul,
|
||||
add: add
|
||||
)
|
||||
}
|
||||
|
||||
private init(
|
||||
model: LoudnessModel,
|
||||
analysis: SpectralChain.Audio?,
|
||||
spectral: SpectralBuffer,
|
||||
sampleRate: Double,
|
||||
calibrationDB: Double,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
self._analysis = analysis
|
||||
self._spectral = spectral
|
||||
self._model = model
|
||||
self._sampleRate = max(1.0, sampleRate)
|
||||
self._core = LoudnessBandCore(
|
||||
fftSize: spectral.fftSize,
|
||||
sampleRate: sampleRate,
|
||||
calibrationDB: calibrationDB,
|
||||
binCount: spectral.binCount
|
||||
)
|
||||
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
super.init()
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
// Bypass the sub-block loop: the spectral buffer advances once per FFT
|
||||
// hop and the loudness state (temporal mask) advances once per block.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
_ = _analysis?.calculatedSamples(graph: graph, count: count)
|
||||
|
||||
let blockSeconds: Double = Double(count) / _sampleRate
|
||||
let sones: Double = _core.loudness(
|
||||
spectral: _spectral, model: _model, blockSeconds: blockSeconds)
|
||||
|
||||
let target: Double = sones
|
||||
let rampStart: Double = _rampTarget
|
||||
_rampTarget = target
|
||||
guard count > 0 else { return _result }
|
||||
previousOutputValue = fillRampedResult(
|
||||
into: &_result,
|
||||
from: rampStart,
|
||||
to: target,
|
||||
mulAdd: _mulAdd,
|
||||
graph: graph,
|
||||
count: count
|
||||
)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
// GeneratorEnum conformance omitted: Loudness is Control-rate only.
|
||||
@@ -0,0 +1,315 @@
|
||||
// LoudnessBandCore.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Shared loudness back-end for ``Loudness``: bins a `SpectralBuffer` into
|
||||
/// third-octave band levels (dB SPL via the calibration offset), then computes
|
||||
/// total loudness in sones under one of the three ``LoudnessModel`` algorithms.
|
||||
///
|
||||
/// All buffers are allocated once at `init`; the per-block methods perform no
|
||||
/// allocation (RT-safe). The ISO 532 B path is an independent implementation of
|
||||
/// the published DIN 45631 / Zwicker stationary algorithm.
|
||||
final class LoudnessBandCore {
|
||||
|
||||
// MARK: - Fixed at init
|
||||
|
||||
private let calibrationDB: Double
|
||||
/// `binBand[k]` = third-octave band index for FFT bin `k`, or `-1` if the
|
||||
/// bin falls outside the 25 Hz … 12.5 kHz grid.
|
||||
private let binBand: [Int]
|
||||
private let binCount: Int
|
||||
|
||||
// MARK: - Scratch (allocated once)
|
||||
|
||||
private var bandPower: [Double] // 28 third-octave band powers (linear)
|
||||
private var bandLevel: [Double] // 28 third-octave band levels (dB SPL)
|
||||
private var coreLoudness: [Double] // 21 critical-band core loudnesses
|
||||
private var critLevel: [Double] // 20 critical-band levels (dB, ear-corrected)
|
||||
private var ti: [Double] // low-band intensities (ISO core path)
|
||||
private var logic: [Bool] // RAP-range comparison flags (ISO core path)
|
||||
|
||||
// MARK: - Temporal-mask state (realtimeZwicker only)
|
||||
|
||||
private var tmaskState: Double = 0.0
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - fftSize: FFT size of the paired analysis chain.
|
||||
/// - sampleRate: Engine sample rate (Hz), for bin→Hz mapping.
|
||||
/// - calibrationDB: dBFS→SPL offset added to each band power level.
|
||||
/// - binCount: Number of spectral bins (`fftSize/2 + 1`).
|
||||
init(fftSize: Int, sampleRate: Double, calibrationDB: Double, binCount: Int) {
|
||||
self.calibrationDB = calibrationDB
|
||||
self.binCount = max(0, binCount)
|
||||
|
||||
let safeSampleRate: Double = max(1.0, sampleRate)
|
||||
let binHz: Double = safeSampleRate / Double(max(1, fftSize))
|
||||
let ratio: Double = Foundation.pow(2.0, loudnessThirdOctaveHalfBandwidthExponent)
|
||||
|
||||
var map: [Int] = [Int](repeating: -1, count: self.binCount)
|
||||
for k: Int in 0..<self.binCount {
|
||||
let freq: Double = Double(k) * binHz
|
||||
var band: Int = -1
|
||||
for j: Int in 0..<loudnessISOThirdOctaveCount {
|
||||
let centre: Double = loudnessISOCenterFreqsHz[j]
|
||||
let lo: Double = centre / ratio
|
||||
let hi: Double = centre * ratio
|
||||
if freq >= lo && freq < hi {
|
||||
band = j
|
||||
break
|
||||
}
|
||||
}
|
||||
map[k] = band
|
||||
}
|
||||
self.binBand = map
|
||||
|
||||
self.bandPower = [Double](repeating: 0.0, count: loudnessISOThirdOctaveCount)
|
||||
self.bandLevel = [Double](repeating: 0.0, count: loudnessISOThirdOctaveCount)
|
||||
self.coreLoudness = [Double](repeating: 0.0, count: loudnessCriticalBandCount + 1)
|
||||
self.critLevel = [Double](repeating: 0.0, count: loudnessCriticalBandCount)
|
||||
self.ti = [Double](repeating: 0.0, count: loudnessISOLowBandCount)
|
||||
self.logic = [Bool](repeating: false, count: loudnessISORAP.count)
|
||||
}
|
||||
|
||||
// MARK: - Critical-band levels (shared by the Zwicker models)
|
||||
|
||||
/// Fill `critLevel[0..19]` with ear-corrected critical-band levels. The first
|
||||
/// three bands are the combined low third-octave bands (`computeLCB`); the
|
||||
/// rest map one-to-one onto third-octave bands 315 Hz … 12.5 kHz.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - lowFreqCorrected: apply the `RAP`/`DLL` equal-loudness correction to
|
||||
/// the low bands (ISO 532 B) vs a plain power sum (real-time).
|
||||
/// - field: free/diffuse field selector.
|
||||
private func fillCriticalLevels(lowFreqCorrected: Bool, field: LoudnessField) {
|
||||
let lcb: (Double, Double, Double) = computeLCB(corrected: lowFreqCorrected)
|
||||
let offset: Int = loudnessISOThirdOctaveCount - loudnessCriticalBandCount
|
||||
for z: Int in 0..<loudnessCriticalBandCount {
|
||||
var le: Double
|
||||
if z == 0 { le = lcb.0 } else if z == 1 { le = lcb.1 } else if z == 2 { le = lcb.2 }
|
||||
else { le = bandLevel[z + offset] }
|
||||
le -= loudnessISOA0[z]
|
||||
if field == .diffuse { le += loudnessISODDF[z] }
|
||||
critLevel[z] = le
|
||||
}
|
||||
}
|
||||
|
||||
/// Combine the lowest third-octave bands into the first three critical-band
|
||||
/// levels (dB). With `corrected`, the `RAP`/`DLL` equal-loudness correction is
|
||||
/// applied first (ISO 532 B); otherwise a plain power sum (real-time).
|
||||
private func computeLCB(corrected: Bool) -> (Double, Double, Double) {
|
||||
for i: Int in 0..<loudnessISOLowBandCount {
|
||||
let level: Double = bandLevel[i]
|
||||
var corr: Double = 0.0
|
||||
if corrected {
|
||||
for j: Int in 0..<loudnessISORAP.count {
|
||||
logic[j] = level > (loudnessISORAP[j] - loudnessISODLL[j][i])
|
||||
}
|
||||
corr = loudnessISODLL[0][i]
|
||||
if logic[0] { corr = 0.0 }
|
||||
for j: Int in 1..<(loudnessISORAP.count - 1) {
|
||||
if logic[j - 1] != logic[j] { corr = loudnessISODLL[j][i] }
|
||||
}
|
||||
}
|
||||
let xp: Double = level + corr
|
||||
ti[i] = Foundation.pow(loudnessDBDecadeFactor, xp / loudnessDBDecadeFactor)
|
||||
}
|
||||
let gi0: Double = ti[0] + ti[1] + ti[2] + ti[3] + ti[4] + ti[5]
|
||||
let gi1: Double = ti[6] + ti[7] + ti[8]
|
||||
let gi2: Double = ti[9] + ti[10]
|
||||
let lcb0: Double = gi0 > 0.0 ? loudnessDBDecadeFactor * Foundation.log10(gi0) : 0.0
|
||||
let lcb1: Double = gi1 > 0.0 ? loudnessDBDecadeFactor * Foundation.log10(gi1) : 0.0
|
||||
let lcb2: Double = gi2 > 0.0 ? loudnessDBDecadeFactor * Foundation.log10(gi2) : 0.0
|
||||
return (lcb0, lcb1, lcb2)
|
||||
}
|
||||
|
||||
// MARK: - Band binning
|
||||
|
||||
/// Fill `bandLevel` (dB SPL) from the spectral buffer's bin magnitudes.
|
||||
private func updateBandLevels(_ spectral: SpectralBuffer) {
|
||||
for j: Int in 0..<loudnessISOThirdOctaveCount {
|
||||
bandPower[j] = 0.0
|
||||
}
|
||||
let n: Int = min(binCount, spectral.binCount)
|
||||
for k: Int in 0..<n {
|
||||
let band: Int = binBand[k]
|
||||
if band < 0 { continue }
|
||||
let mag: Double = Double(spectral.magnitude(at: k))
|
||||
bandPower[band] += mag * mag
|
||||
}
|
||||
for j: Int in 0..<loudnessISOThirdOctaveCount {
|
||||
bandLevel[j] = loudnessDBDecadeFactor
|
||||
* Foundation.log10(bandPower[j] + loudnessTinyPower) + calibrationDB
|
||||
if bandLevel[j] > loudnessMaxBandLevelDB { bandLevel[j] = loudnessMaxBandLevelDB }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Model dispatch
|
||||
|
||||
/// Total loudness in sones for `model` from the current spectral frame.
|
||||
/// `blockSeconds` is the audio-block duration (for the temporal mask).
|
||||
func loudness(
|
||||
spectral: SpectralBuffer,
|
||||
model: LoudnessModel,
|
||||
blockSeconds: Double
|
||||
) -> Double {
|
||||
updateBandLevels(spectral)
|
||||
switch model {
|
||||
case .barkEstimate:
|
||||
return barkEstimateLoudness()
|
||||
case .realtimeZwicker(let smask, let tmask):
|
||||
return realtimeZwickerLoudness(smask: smask, tmask: tmask, blockSeconds: blockSeconds)
|
||||
case .iso532b(let field):
|
||||
return iso532bLoudness(field: field)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Model 1: Bark/third-octave Stevens estimate
|
||||
|
||||
private func barkEstimateLoudness() -> Double {
|
||||
var total: Double = 0.0
|
||||
let calibrationFactor: Double = Foundation.pow(
|
||||
loudnessDBDecadeFactor, calibrationDB / loudnessDBDecadeFactor)
|
||||
for j: Int in 0..<loudnessISOThirdOctaveCount {
|
||||
let intensity: Double = bandPower[j]
|
||||
if intensity <= 0.0 { continue }
|
||||
// Calibrated intensity ratio → Stevens power law.
|
||||
let ratio: Double = intensity * calibrationFactor
|
||||
total += Foundation.pow(ratio, loudnessStevensExponent)
|
||||
}
|
||||
let result: Double = total * loudnessBarkEstimateScale
|
||||
return result.isFinite ? max(0.0, result) : 0.0
|
||||
}
|
||||
|
||||
// MARK: - Model 2: real-time Zwicker (critical-band specific loudness + temporal mask)
|
||||
|
||||
private func realtimeZwickerLoudness(
|
||||
smask: Double,
|
||||
tmask: Double,
|
||||
blockSeconds: Double
|
||||
) -> Double {
|
||||
// Simplified core loudness: the same critical-band levels as ISO 532 B
|
||||
// (low bands combined into LCB, but without the RAP/DLL/DCB/korry
|
||||
// refinement), with the spectral-masking constant exposed as `smask`.
|
||||
// Then the shared upper-slope integration, followed by the temporal mask.
|
||||
let s: Double = min(1.0, max(0.0, smask))
|
||||
fillCriticalLevels(lowFreqCorrected: false, field: .free)
|
||||
for z: Int in 0..<loudnessCriticalBandCount {
|
||||
let le: Double = critLevel[z]
|
||||
let ltq: Double = loudnessISOLTQ[z]
|
||||
if le > ltq {
|
||||
let mp1: Double = loudnessZwickerConst
|
||||
* Foundation.pow(loudnessDBDecadeFactor, loudnessZwickerThresholdCoeff * ltq)
|
||||
let inner: Double = 1.0 - s
|
||||
+ s * Foundation.pow(loudnessDBDecadeFactor, loudnessLevelToPowerCoeff * (le - ltq))
|
||||
let mp2: Double = Foundation.pow(inner, loudnessZwickerExponent) - 1.0
|
||||
coreLoudness[z] = max(0.0, mp1 * mp2)
|
||||
} else {
|
||||
coreLoudness[z] = 0.0
|
||||
}
|
||||
}
|
||||
coreLoudness[loudnessCriticalBandCount] = 0.0
|
||||
|
||||
let base: Double = integrateUpperSlopes()
|
||||
|
||||
// Temporal mask: instant attack, exponential release toward 0.
|
||||
let safeTMask: Double = max(loudnessTinyPower, tmask)
|
||||
let coeff: Double = Foundation.exp(-max(0.0, blockSeconds) / safeTMask)
|
||||
let released: Double = tmaskState * coeff
|
||||
let out: Double = max(base, released)
|
||||
tmaskState = denormalsToZero(out)
|
||||
return out.isFinite ? max(0.0, out) : 0.0
|
||||
}
|
||||
|
||||
// MARK: - Model 3: ISO 532 B / DIN 45631 stationary Zwicker
|
||||
|
||||
private func iso532bLoudness(field: LoudnessField) -> Double {
|
||||
computeCoreLoudness(field: field)
|
||||
return integrateUpperSlopes()
|
||||
}
|
||||
|
||||
/// Fill `coreLoudness[0..20]` (main loudness per critical band) per DIN 45631.
|
||||
private func computeCoreLoudness(field: LoudnessField) {
|
||||
// Ear-corrected critical-band levels with the RAP/DLL low-frequency
|
||||
// correction (the full standard).
|
||||
fillCriticalLevels(lowFreqCorrected: true, field: field)
|
||||
|
||||
for z: Int in 0..<loudnessCriticalBandCount {
|
||||
var le: Double = critLevel[z]
|
||||
let ltq: Double = loudnessISOLTQ[z]
|
||||
if le > ltq { le -= loudnessISODCB[z] }
|
||||
|
||||
if le > ltq {
|
||||
let mp1: Double = loudnessZwickerConst
|
||||
* Foundation.pow(loudnessDBDecadeFactor, loudnessZwickerThresholdCoeff * ltq)
|
||||
let inner: Double = 1.0 - loudnessISOCoreS
|
||||
+ loudnessISOCoreS * Foundation.pow(
|
||||
loudnessDBDecadeFactor, loudnessLevelToPowerCoeff * (le - ltq))
|
||||
let mp2: Double = Foundation.pow(inner, loudnessZwickerExponent) - 1.0
|
||||
coreLoudness[z] = max(0.0, mp1 * mp2)
|
||||
} else {
|
||||
coreLoudness[z] = 0.0
|
||||
}
|
||||
}
|
||||
coreLoudness[loudnessCriticalBandCount] = 0.0 // appended sentinel band
|
||||
|
||||
// Lowest-band threshold-dependence correction.
|
||||
let korry: Double = loudnessKorryBase
|
||||
+ loudnessKorryScale * Foundation.pow(coreLoudness[0], loudnessKorryExponent)
|
||||
if korry <= 1.0 { coreLoudness[0] *= korry }
|
||||
}
|
||||
|
||||
/// Integrate the specific-loudness function with the Zwicker upper slopes →
|
||||
/// total loudness (sones). Walks each critical band's flat top plus the
|
||||
/// upper-slope tail spilling into higher bands.
|
||||
private func integrateUpperSlopes() -> Double {
|
||||
var total: Double = 0.0
|
||||
var z1: Double = 0.0
|
||||
var n1: Double = 0.0
|
||||
let maxColumn: Int = loudnessISOUSL[0].count - 1 // USL has 8 critical-band columns
|
||||
|
||||
for i: Int in 0..<(loudnessCriticalBandCount + 1) {
|
||||
let zupI: Double = loudnessISOZUP[i]
|
||||
var ig: Int = i - 1
|
||||
if ig > maxColumn { ig = maxColumn }
|
||||
if ig < 0 { ig = 0 }
|
||||
let nmI: Double = coreLoudness[i]
|
||||
|
||||
while true {
|
||||
if n1 <= nmI {
|
||||
// Rising / flat: plateau at nmI across the band.
|
||||
total += nmI * (zupI - z1)
|
||||
z1 = zupI
|
||||
n1 = nmI
|
||||
break
|
||||
}
|
||||
// Decreasing: upper slope from (z1, n1) down through rns ranges.
|
||||
var j: Int = 0
|
||||
while j < (loudnessISORNS.count - 1) && loudnessISORNS[j] >= n1 { j += 1 }
|
||||
let n2: Double = max(loudnessISORNS[j], nmI)
|
||||
let slope: Double = loudnessISOUSL[j][ig]
|
||||
let dz: Double = slope > 0.0 ? (n1 - n2) / slope : (zupI - z1)
|
||||
var z2: Double = z1 + dz
|
||||
|
||||
if z2 >= zupI {
|
||||
z2 = zupI
|
||||
let nEdge: Double = n1 - slope * (z2 - z1)
|
||||
total += loudnessTrapezoidalFactor * (n1 + nEdge) * (z2 - z1)
|
||||
z1 = zupI
|
||||
n1 = nEdge
|
||||
break
|
||||
}
|
||||
total += loudnessTrapezoidalFactor * (n1 + n2) * (z2 - z1)
|
||||
z1 = z2
|
||||
n1 = n2
|
||||
// Loop continues for the next rns range within the same band.
|
||||
}
|
||||
}
|
||||
return total.isFinite ? max(0.0, total) : 0.0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
// LoudnessConstants.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - General
|
||||
|
||||
/// Default dBFS→SPL calibration offset (dB) added to each bin's power level.
|
||||
/// Chosen so a full-scale sinusoid lands near the top of the musical SPL range.
|
||||
public let loudnessDefaultCalibrationDB: Double = 90.0
|
||||
|
||||
/// Floor added inside `log10` to guard the silence case (`log10(0)`).
|
||||
public let loudnessTinyPower: Double = 1.0e-30
|
||||
|
||||
/// Decade factor for dB ↔ power/intensity conversions (`L = 10·log10(P)`,
|
||||
/// `P = 10^(L/10)`).
|
||||
public let loudnessDBDecadeFactor: Double = 10.0
|
||||
|
||||
/// Trapezoidal-rule factor (`½`) for the upper-slope area integration.
|
||||
public let loudnessTrapezoidalFactor: Double = 0.5
|
||||
|
||||
/// Exponent for the third-octave half-bandwidth ratio `2^(1/6)`.
|
||||
public let loudnessThirdOctaveHalfBandwidthExponent: Double = 1.0 / 6.0
|
||||
|
||||
/// Stevens' power-law exponent on intensity for the `.barkEstimate` model
|
||||
/// (`N ∝ I^0.3` → +10 dB ≈ 2×).
|
||||
public let loudnessStevensExponent: Double = 0.3
|
||||
|
||||
/// Output scaling for `.barkEstimate` so a 1 kHz tone near 40 dB SPL lands near
|
||||
/// 1 sone (the model has no equal-loudness contour, so this is an anchor fit:
|
||||
/// `(10^(40/10))^0.3 ≈ 15.85`, so the scale is `≈ 1/15.85`).
|
||||
public let loudnessBarkEstimateScale: Double = 0.0631
|
||||
|
||||
/// Zwicker specific-loudness constant (`0.0635 = 0.0635`). Specific loudness
|
||||
/// `N' = const · 10^(0.025·LTQ) · ((1 − s + s·10^(0.1·(L−LTQ)))^0.25 − 1)`.
|
||||
public let loudnessZwickerConst: Double = 0.0635
|
||||
|
||||
/// Exponent in the Zwicker specific-loudness law (`^0.25`).
|
||||
public let loudnessZwickerExponent: Double = 0.25
|
||||
|
||||
/// `10^(0.025·LTQ)` coefficient exponent factor.
|
||||
public let loudnessZwickerThresholdCoeff: Double = 0.025
|
||||
|
||||
/// `10^(0.1·(L−LTQ))` level-to-power exponent factor (dB → power decade).
|
||||
public let loudnessLevelToPowerCoeff: Double = 0.1
|
||||
|
||||
/// Default Zwicker spectral-masking constant `s` for `.realtimeZwicker` (the
|
||||
/// standard's fixed value). SC `Loudness` `smask` default.
|
||||
public let loudnessDefaultSMask: Double = 0.25
|
||||
|
||||
/// Default temporal-mask release time (seconds) for `.realtimeZwicker`.
|
||||
public let loudnessDefaultTMask: Double = 1.0
|
||||
|
||||
// MARK: - Third-octave band layout (ISO 532 B input grid)
|
||||
|
||||
/// Number of third-octave bands (25 Hz … 12.5 kHz).
|
||||
public let loudnessISOThirdOctaveCount: Int = 28
|
||||
|
||||
/// Third-octave band centre frequencies (Hz).
|
||||
public let loudnessISOCenterFreqsHz: [Double] = [
|
||||
25, 31.5, 40, 50, 63, 80, 100, 125, 160, 200, 250, 315,
|
||||
400, 500, 630, 800, 1000, 1250, 1600, 2000, 2500, 3150,
|
||||
4000, 5000, 6300, 8000, 10000, 12500
|
||||
]
|
||||
|
||||
/// Number of Zwicker critical bands used by the core-loudness stage (the upper
|
||||
/// 20 third-octave bands, with the lowest three formed from sub-band sums).
|
||||
public let loudnessCriticalBandCount: Int = 20
|
||||
|
||||
/// Number of low third-octave bands (25 … 250 Hz) that get the `RAP`/`DLL`
|
||||
/// equal-loudness correction before being combined into the first three
|
||||
/// critical bands.
|
||||
public let loudnessISOLowBandCount: Int = 11
|
||||
|
||||
// MARK: - ISO 532 B core-loudness tables
|
||||
// Transcribed from the published DIN 45631 / Zwicker (1991) algorithm via the
|
||||
// Apache-2.0 MoSQITo implementation. Data only — facts of the standard.
|
||||
|
||||
/// Ranges of 1/3-octave band levels for low-frequency correction (dB).
|
||||
public let loudnessISORAP: [Double] = [45, 55, 65, 71, 80, 90, 100, 120]
|
||||
|
||||
/// Reduction of the lowest 11 1/3-octave band levels within the eight `RAP`
|
||||
/// ranges (8 rows × 11 columns), per the equal-loudness contours.
|
||||
public let loudnessISODLL: [[Double]] = [
|
||||
[-32, -24, -16, -10, -5, 0, -7, -3, 0, -2, 0],
|
||||
[-29, -22, -15, -10, -4, 0, -7, -2, 0, -2, 0],
|
||||
[-27, -19, -14, -9, -4, 0, -6, -2, 0, -2, 0],
|
||||
[-25, -17, -12, -9, -3, 0, -5, -2, 0, -2, 0],
|
||||
[-23, -16, -11, -7, -3, 0, -4, -1, 0, -1, 0],
|
||||
[-20, -14, -10, -6, -3, 0, -4, -1, 0, -1, 0],
|
||||
[-18, -12, -9, -6, -2, 0, -3, -1, 0, -1, 0],
|
||||
[-15, -10, -8, -4, -2, 0, -3, -1, 0, -1, 0]
|
||||
]
|
||||
|
||||
/// Critical-band level at absolute threshold without the ear transfer (dB), per
|
||||
/// the 20 critical bands.
|
||||
public let loudnessISOLTQ: [Double] = [
|
||||
30, 18, 12, 8, 7, 6, 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3
|
||||
]
|
||||
|
||||
/// Ear-transmission level correction (dB), per critical band.
|
||||
public let loudnessISOA0: [Double] = [
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.5, -1.6, -3.2, -5.4, -5.6, -4, -1.5, 2, 5, 12
|
||||
]
|
||||
|
||||
/// Free-field → diffuse-field level difference (dB), per critical band.
|
||||
public let loudnessISODDF: [Double] = [
|
||||
0, 0, 0.5, 0.9, 1.2, 1.6, 2.3, 2.8, 3, 2,
|
||||
0, -1.4, -2, -1.9, -1, 0.5, 3, 4, 4.3, 4
|
||||
]
|
||||
|
||||
/// Adaptation of 1/3-octave band levels to the critical-band level (dB).
|
||||
public let loudnessISODCB: [Double] = [
|
||||
-0.25, -0.6, -0.8, -0.8, -0.5, 0, 0.5, 1.1, 1.5, 1.7,
|
||||
1.8, 1.8, 1.7, 1.6, 1.4, 1.2, 0.8, 0.5, 0, -0.5
|
||||
]
|
||||
|
||||
/// Core-loudness correction `s` in the specific-loudness law.
|
||||
public let loudnessISOCoreS: Double = 0.25
|
||||
|
||||
// MARK: - ISO 532 B upper-slope / integration tables
|
||||
|
||||
/// Upper limits of the approximated critical bands in Bark (21 values).
|
||||
public let loudnessISOZUP: [Double] = [
|
||||
0.9, 1.8, 2.8, 3.5, 4.4, 5.4, 6.6, 7.9, 9.2, 10.6, 12.3,
|
||||
13.8, 15.2, 16.7, 18.1, 19.3, 20.6, 21.8, 22.7, 23.6, 24
|
||||
]
|
||||
|
||||
/// Specific-loudness range thresholds for upper-slope steepness selection (18,
|
||||
/// descending).
|
||||
public let loudnessISORNS: [Double] = [
|
||||
21.5, 18, 15.1, 11.5, 9, 6.1, 4.4, 3.1, 2.13, 1.36,
|
||||
0.82, 0.42, 0.30, 0.22, 0.15, 0.10, 0.035, 0
|
||||
]
|
||||
|
||||
/// Steepness of the upper slopes (18 ranges × 8 critical-band columns).
|
||||
public let loudnessISOUSL: [[Double]] = [
|
||||
[13, 8.2, 6.3, 5.5, 5.5, 5.5, 5.5, 5.5],
|
||||
[9, 7.5, 6, 5.1, 4.5, 4.5, 4.5, 4.5],
|
||||
[7.8, 6.7, 5.6, 4.9, 4.4, 3.9, 3.9, 3.9],
|
||||
[6.2, 5.4, 4.6, 4.0, 3.5, 3.2, 3.2, 3.2],
|
||||
[4.5, 3.8, 3.6, 3.2, 2.9, 2.7, 2.7, 2.7],
|
||||
[3.7, 3.0, 2.8, 2.35, 2.2, 2.2, 2.2, 2.2],
|
||||
[2.9, 2.3, 2.1, 1.9, 1.8, 1.7, 1.7, 1.7],
|
||||
[2.4, 1.7, 1.5, 1.35, 1.3, 1.3, 1.3, 1.3],
|
||||
[1.95, 1.45, 1.3, 1.15, 1.1, 1.1, 1.1, 1.1],
|
||||
[1.5, 1.2, 0.94, 0.86, 0.82, 0.82, 0.82, 0.82],
|
||||
[0.72, 0.67, 0.64, 0.63, 0.62, 0.62, 0.62, 0.62],
|
||||
[0.59, 0.53, 0.51, 0.50, 0.42, 0.42, 0.42, 0.42],
|
||||
[0.40, 0.33, 0.26, 0.24, 0.24, 0.22, 0.22, 0.22],
|
||||
[0.27, 0.21, 0.20, 0.18, 0.17, 0.17, 0.17, 0.17],
|
||||
[0.16, 0.15, 0.14, 0.12, 0.11, 0.11, 0.11, 0.11],
|
||||
[0.12, 0.11, 0.10, 0.08, 0.08, 0.08, 0.08, 0.08],
|
||||
[0.09, 0.08, 0.07, 0.06, 0.06, 0.06, 0.06, 0.05],
|
||||
[0.06, 0.05, 0.03, 0.02, 0.02, 0.02, 0.02, 0.02]
|
||||
]
|
||||
|
||||
/// `korry` low-band threshold-dependence correction constants
|
||||
/// (`0.4 + 0.32·N^0.2`).
|
||||
public let loudnessKorryBase: Double = 0.4
|
||||
public let loudnessKorryScale: Double = 0.32
|
||||
public let loudnessKorryExponent: Double = 0.2
|
||||
|
||||
/// Maximum third-octave band level (dB) above which the Zwicker method is
|
||||
/// undefined for the low bands; input is clamped to this.
|
||||
public let loudnessMaxBandLevelDB: Double = 120.0
|
||||
@@ -0,0 +1,16 @@
|
||||
// LoudnessField.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Sound-field assumption for the ISO 532 B loudness model
|
||||
/// (``LoudnessModel/iso532b(field:)``).
|
||||
public enum LoudnessField {
|
||||
/// Free field (frontal incidence). Default.
|
||||
case free
|
||||
/// Diffuse field (applies the `DDF` free→diffuse corrections).
|
||||
case diffuse
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// LoudnessModel.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Selects the loudness-estimation model for ``Loudness`` (the implementation
|
||||
/// flag, mirroring the `Balance` `logDomain:` and `BeatTrack` `BeatTrackODF`
|
||||
/// folds). The cases carry different parameters, so the selector is an enum.
|
||||
///
|
||||
/// All models output total loudness in **sones** from the same third-octave band
|
||||
/// powers; they differ in how specific loudness is derived.
|
||||
public enum LoudnessModel {
|
||||
|
||||
/// Cheapest: third-octave band intensity → Stevens power law
|
||||
/// (`N ∝ I^0.3`) → sum. No equal-loudness contour or masking. Rough but
|
||||
/// stable; no SC parity claim.
|
||||
case barkEstimate
|
||||
|
||||
/// SC `Loudness` ergonomics: critical-band specific loudness via the Zwicker
|
||||
/// law with a spectral-masking constant, summed, then temporally masked.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - smask: Spectral-masking constant `s` (`[0, 1]`); `0.25` is the
|
||||
/// standard value. Higher widens masking.
|
||||
/// - tmask: Temporal-mask release time (seconds); larger = slower decay,
|
||||
/// more masking of transients.
|
||||
case realtimeZwicker(smask: Double, tmask: Double)
|
||||
|
||||
/// Full ISO 532 B / DIN 45631 stationary Zwicker loudness: third-octave core
|
||||
/// loudness → upper-slope spreading → integrate the specific-loudness
|
||||
/// function.
|
||||
///
|
||||
/// - Parameter field: Sound-field assumption (`.free` default, `.diffuse`).
|
||||
case iso532b(field: LoudnessField)
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
// RunningMax.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
|
||||
/// File-scope zero-fill block for RunningMax — fallback when upstream returns no channel.
|
||||
private let runningMaxZeroBlock: [Double] = [Double](
|
||||
repeating: 0,
|
||||
count: lyrebirdDefaultResultBufferSize
|
||||
)
|
||||
|
||||
/// Running maximum with trigger reset. Equivalent to SuperCollider `RunningMax`.
|
||||
///
|
||||
/// Tracks the running maximum of `input` since the last trigger. On a ≤0 → >0 rising
|
||||
/// edge of `trig`, the extreme is reset to the current `input` value at that frame.
|
||||
/// On the very first sample/block, the extreme is initialised to the first input value.
|
||||
///
|
||||
/// ```swift
|
||||
/// let peak = RunningMax.Audio(input: signal)
|
||||
/// RunningMax.Audio(input: sig, trig: resetClock) // reset every clock pulse
|
||||
/// RunningMax.Control(input: $cv, trig: gate) // block-rate maximum tracking
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track. Any `ValidGeneratorInput`.
|
||||
/// - trig: Reset trigger. ≤0 → >0 rising edges reset the running maximum. Defaults to `0.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public enum RunningMax {
|
||||
|
||||
// MARK: - Shared base
|
||||
|
||||
/// Shared stored properties for `RunningMax.Audio` and `RunningMax.Control`.
|
||||
public class _Base: GeneratorBase {
|
||||
let _input: any ValidGeneratorInput
|
||||
let _trigInput: any ValidGeneratorInput
|
||||
let _mulAdd: MulAddSpec
|
||||
|
||||
/// Running maximum. Initialised to the first input sample (lazy init via `_initialized`).
|
||||
var _extreme: Double = 0.0
|
||||
/// Previous trigger value for edge detection.
|
||||
var _prevTrig: Double = 0.0
|
||||
/// `false` until the first sample is processed; prevents a false start at `0.0`.
|
||||
var _initialized: Bool = false
|
||||
|
||||
init(
|
||||
input: any ValidGeneratorInput,
|
||||
trig: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedTrig: any ValidGeneratorInput = trig._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_trigInput = resolvedTrig
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
super.init()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio rate
|
||||
|
||||
/// Audio-rate running maximum with trigger reset.
|
||||
///
|
||||
/// Evaluates per sample: lazy-initialises on the first sample; resets on rising trig
|
||||
/// edge; otherwise tracks `max(_extreme, x)`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track.
|
||||
/// - trig: Reset trigger. ≤0 → >0 rising edges reset to the current `input` value.
|
||||
/// Defaults to `0.0` (no reset).
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track.
|
||||
/// - trig: Reset trigger. ≤0 → >0 edges reset the running maximum. Defaults to `0.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
input: any ValidGeneratorInput,
|
||||
trig: any ValidGeneratorInput = 0.0,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, trig: trig, mul: mul, add: add)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let inputSamples: [Double] = _input.calculatedSamples(
|
||||
graph: graph, count: count).first ?? runningMaxZeroBlock
|
||||
let trigSamples: [Double] = _trigInput.calculatedSamples(
|
||||
graph: graph, count: count).first ?? runningMaxZeroBlock
|
||||
|
||||
var extreme: Double = _extreme
|
||||
var prevTrig: Double = _prevTrig
|
||||
var initialized: Bool = _initialized
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = inputSamples[i]
|
||||
let t: Double = trigSamples[i]
|
||||
if !initialized {
|
||||
extreme = x
|
||||
initialized = true
|
||||
} else if t > 0 && prevTrig <= 0 {
|
||||
extreme = x
|
||||
} else {
|
||||
extreme = Swift.max(extreme, x)
|
||||
}
|
||||
prevTrig = t
|
||||
_result[0][i] = extreme
|
||||
}
|
||||
|
||||
_extreme = extreme
|
||||
_prevTrig = prevTrig
|
||||
_initialized = initialized
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Control rate
|
||||
|
||||
/// Block-rate running maximum with trigger reset.
|
||||
///
|
||||
/// Scans the full audio-rate input block, applying the same state machine as `Audio`
|
||||
/// (lazy init; trig-edge reset; `max` tracking). Outputs the block-final extreme as
|
||||
/// a flat block (all samples equal). Bypasses the sub-block loop — the state machine
|
||||
/// must scan the full audio block exactly once per audio cycle.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track.
|
||||
/// - trig: Reset trigger. ≤0 → >0 rising edges reset the running maximum. Defaults to `0.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track.
|
||||
/// - trig: Reset trigger. ≤0 → >0 edges reset the running maximum. Defaults to `0.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
input: any ValidGeneratorInput,
|
||||
trig: any ValidGeneratorInput = 0.0,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, trig: trig, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
/// Bypass sub-block loop: the running-maximum state machine must scan the full
|
||||
/// audio-rate input block exactly once per audio block.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let inputSamples: [Double] = _input.calculatedSamples(
|
||||
graph: graph, count: count).first ?? runningMaxZeroBlock
|
||||
let trigSamples: [Double] = _trigInput.calculatedSamples(
|
||||
graph: graph, count: count).first ?? runningMaxZeroBlock
|
||||
|
||||
var extreme: Double = _extreme
|
||||
var prevTrig: Double = _prevTrig
|
||||
var initialized: Bool = _initialized
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = inputSamples[i]
|
||||
let t: Double = trigSamples[i]
|
||||
if !initialized {
|
||||
extreme = x
|
||||
initialized = true
|
||||
} else if t > 0 && prevTrig <= 0 {
|
||||
extreme = x
|
||||
} else {
|
||||
extreme = Swift.max(extreme, x)
|
||||
}
|
||||
prevTrig = t
|
||||
}
|
||||
|
||||
_extreme = extreme
|
||||
_prevTrig = prevTrig
|
||||
_initialized = initialized
|
||||
|
||||
var fillValue: Double = extreme
|
||||
_result[0].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
|
||||
guard count > 0 else { return _result }
|
||||
previousOutputValue = _result[0][count - 1]
|
||||
return _result
|
||||
}
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
extension RunningMax: GeneratorEnum {
|
||||
public typealias AudioType = RunningMax.Audio
|
||||
public typealias ControlType = RunningMax.Control
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
// RunningMin.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
|
||||
/// File-scope zero-fill block for RunningMin — fallback when upstream returns no channel.
|
||||
private let runningMinZeroBlock: [Double] = [Double](
|
||||
repeating: 0,
|
||||
count: lyrebirdDefaultResultBufferSize
|
||||
)
|
||||
|
||||
/// Running minimum with trigger reset. Equivalent to SuperCollider `RunningMin`.
|
||||
///
|
||||
/// Tracks the running minimum of `input` since the last trigger. On a ≤0 → >0 rising
|
||||
/// edge of `trig`, the extreme is reset to the current `input` value at that frame.
|
||||
/// On the very first sample/block, the extreme is initialised to the first input value.
|
||||
///
|
||||
/// ```swift
|
||||
/// let peak = RunningMin.Audio(input: signal)
|
||||
/// RunningMin.Audio(input: sig, trig: resetClock) // reset every clock pulse
|
||||
/// RunningMin.Control(input: $cv, trig: gate) // block-rate minimum tracking
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track. Any `ValidGeneratorInput`.
|
||||
/// - trig: Reset trigger. ≤0 → >0 rising edges reset the running minimum. Defaults to `0.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public enum RunningMin {
|
||||
|
||||
// MARK: - Shared base
|
||||
|
||||
/// Shared stored properties for `RunningMin.Audio` and `RunningMin.Control`.
|
||||
public class _Base: GeneratorBase {
|
||||
let _input: any ValidGeneratorInput
|
||||
let _trigInput: any ValidGeneratorInput
|
||||
let _mulAdd: MulAddSpec
|
||||
|
||||
/// Running minimum. Initialised to the first input sample (lazy init via `_initialized`).
|
||||
var _extreme: Double = 0.0
|
||||
/// Previous trigger value for edge detection.
|
||||
var _prevTrig: Double = 0.0
|
||||
/// `false` until the first sample is processed; prevents a false start at `0.0`.
|
||||
var _initialized: Bool = false
|
||||
|
||||
init(
|
||||
input: any ValidGeneratorInput,
|
||||
trig: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedTrig: any ValidGeneratorInput = trig._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_trigInput = resolvedTrig
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
super.init()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio rate
|
||||
|
||||
/// Audio-rate running minimum with trigger reset.
|
||||
///
|
||||
/// Evaluates per sample: lazy-initialises on the first sample; resets on rising trig
|
||||
/// edge; otherwise tracks `min(_extreme, x)`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track.
|
||||
/// - trig: Reset trigger. ≤0 → >0 rising edges reset to the current `input` value.
|
||||
/// Defaults to `0.0` (no reset).
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track.
|
||||
/// - trig: Reset trigger. ≤0 → >0 edges reset the running minimum. Defaults to `0.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
input: any ValidGeneratorInput,
|
||||
trig: any ValidGeneratorInput = 0.0,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, trig: trig, mul: mul, add: add)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let inputSamples: [Double] = _input.calculatedSamples(
|
||||
graph: graph, count: count).first ?? runningMinZeroBlock
|
||||
let trigSamples: [Double] = _trigInput.calculatedSamples(
|
||||
graph: graph, count: count).first ?? runningMinZeroBlock
|
||||
|
||||
var extreme: Double = _extreme
|
||||
var prevTrig: Double = _prevTrig
|
||||
var initialized: Bool = _initialized
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = inputSamples[i]
|
||||
let t: Double = trigSamples[i]
|
||||
if !initialized {
|
||||
extreme = x
|
||||
initialized = true
|
||||
} else if t > 0 && prevTrig <= 0 {
|
||||
extreme = x
|
||||
} else {
|
||||
extreme = Swift.min(extreme, x)
|
||||
}
|
||||
prevTrig = t
|
||||
_result[0][i] = extreme
|
||||
}
|
||||
|
||||
_extreme = extreme
|
||||
_prevTrig = prevTrig
|
||||
_initialized = initialized
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Control rate
|
||||
|
||||
/// Block-rate running minimum with trigger reset.
|
||||
///
|
||||
/// Scans the full audio-rate input block, applying the same state machine as `Audio`
|
||||
/// (lazy init; trig-edge reset; `min` tracking). Outputs the block-final extreme as
|
||||
/// a flat block (all samples equal). Bypasses the sub-block loop — the state machine
|
||||
/// must scan the full audio block exactly once per audio cycle.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track.
|
||||
/// - trig: Reset trigger. ≤0 → >0 rising edges reset the running minimum. Defaults to `0.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track.
|
||||
/// - trig: Reset trigger. ≤0 → >0 edges reset the running minimum. Defaults to `0.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
input: any ValidGeneratorInput,
|
||||
trig: any ValidGeneratorInput = 0.0,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, trig: trig, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
/// Bypass sub-block loop: the running-minimum state machine must scan the full
|
||||
/// audio-rate input block exactly once per audio block.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let inputSamples: [Double] = _input.calculatedSamples(
|
||||
graph: graph, count: count).first ?? runningMinZeroBlock
|
||||
let trigSamples: [Double] = _trigInput.calculatedSamples(
|
||||
graph: graph, count: count).first ?? runningMinZeroBlock
|
||||
|
||||
var extreme: Double = _extreme
|
||||
var prevTrig: Double = _prevTrig
|
||||
var initialized: Bool = _initialized
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = inputSamples[i]
|
||||
let t: Double = trigSamples[i]
|
||||
if !initialized {
|
||||
extreme = x
|
||||
initialized = true
|
||||
} else if t > 0 && prevTrig <= 0 {
|
||||
extreme = x
|
||||
} else {
|
||||
extreme = Swift.min(extreme, x)
|
||||
}
|
||||
prevTrig = t
|
||||
}
|
||||
|
||||
_extreme = extreme
|
||||
_prevTrig = prevTrig
|
||||
_initialized = initialized
|
||||
|
||||
var fillValue: Double = extreme
|
||||
_result[0].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
|
||||
guard count > 0 else { return _result }
|
||||
previousOutputValue = _result[0][count - 1]
|
||||
return _result
|
||||
}
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
extension RunningMin: GeneratorEnum {
|
||||
public typealias AudioType = RunningMin.Audio
|
||||
public typealias ControlType = RunningMin.Control
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
// Slope.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
|
||||
/// File-scope zero-fill block for Slope — fallback when upstream returns no channel.
|
||||
private let slopeZeroBlock: [Double] = [Double](
|
||||
repeating: 0,
|
||||
count: lyrebirdDefaultResultBufferSize
|
||||
)
|
||||
|
||||
/// Per-second rate-of-change estimator. Equivalent to SuperCollider `Slope`.
|
||||
///
|
||||
/// Computes `out[n] = (input[n] − input[n−1]) × sampleRate` (audio rate) or
|
||||
/// `out = (input − prevInput) × controlRate` (control rate). On the very first
|
||||
/// sample/block, the output is `0.0` and `prevInput` is initialised to the first input
|
||||
/// value — this prevents the startup spike that would occur if `prevInput` were `0`.
|
||||
///
|
||||
/// ```swift
|
||||
/// let rate = Slope.Audio(input: envelope) // audio-rate differentiation
|
||||
/// let rate = Slope.Control(input: $cv) // block-rate differentiation
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to differentiate.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public enum Slope {
|
||||
|
||||
// MARK: - Shared base
|
||||
|
||||
/// Shared stored properties for `Slope.Audio` and `Slope.Control`.
|
||||
public class _Base: GeneratorBase {
|
||||
let _input: any ValidGeneratorInput
|
||||
let _inputIsGenerator: Bool
|
||||
let _mulAdd: MulAddSpec
|
||||
|
||||
/// Previous sample value. Initialised on the first call (lazy init).
|
||||
var _prevSample: Double = 0.0
|
||||
/// `false` until the first sample/block is processed; avoids the startup spike.
|
||||
var _initialized: Bool = false
|
||||
|
||||
init(
|
||||
input: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_inputIsGenerator = resolvedInput is any Generator
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
super.init()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio rate
|
||||
|
||||
/// Audio-rate per-second rate-of-change estimator.
|
||||
///
|
||||
/// On the first sample, the output is `0.0` and `prevSample` is set to that sample's
|
||||
/// value. From the second sample onward, `out[n] = (x[n] − x[n−1]) × sampleRate`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to differentiate.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to differentiate.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
input: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, mul: mul, add: add)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let inputSamples: [Double] = _input.calculatedSamples(
|
||||
graph: graph, count: count).first ?? slopeZeroBlock
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
|
||||
var prev: Double = _prevSample
|
||||
var initialized: Bool = _initialized
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = inputSamples[i]
|
||||
if !initialized {
|
||||
prev = x
|
||||
initialized = true
|
||||
_result[0][i] = 0.0
|
||||
} else {
|
||||
_result[0][i] = (x - prev) * sr
|
||||
prev = x
|
||||
}
|
||||
}
|
||||
|
||||
_prevSample = prev
|
||||
_initialized = initialized
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Control rate
|
||||
|
||||
/// Control-rate per-second rate-of-change estimator.
|
||||
///
|
||||
/// Advances one differentiation step per audio block using the control rate
|
||||
/// (`sampleRate / blockSize`). On the first block, the output is `0.0` and
|
||||
/// `prevInput` is set to the block's input value. Subsequent blocks compute
|
||||
/// `slope = (x − prevInput) × controlRate`.
|
||||
///
|
||||
/// Bypasses the sub-block loop — state must advance exactly once per audio block.
|
||||
///
|
||||
/// The output block is flat (constant). For smoothly interpolated output, use
|
||||
/// `Slope.Audio`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to differentiate.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to differentiate.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
input: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
/// Bypass sub-block loop: slope state must advance exactly once per audio block.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let controlRate: Double = graph.engine.sampleRate / Double(graph.engine.blockSize)
|
||||
// Sample the input at block end (captures ParameterNode ramp endpoints),
|
||||
// matching the block-constant-input convention of other control-rate generators.
|
||||
let x: Double = lastGeneratorSampleOrFloat(
|
||||
_input, isGenerator: _inputIsGenerator, graph: graph, count: count)
|
||||
|
||||
let slope: Double
|
||||
if !_initialized {
|
||||
_prevSample = x
|
||||
_initialized = true
|
||||
slope = 0.0
|
||||
} else {
|
||||
slope = (x - _prevSample) * controlRate
|
||||
_prevSample = x
|
||||
}
|
||||
|
||||
var fillValue: Double = slope
|
||||
_result[0].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
|
||||
guard count > 0 else { return _result }
|
||||
previousOutputValue = _result[0][count - 1]
|
||||
return _result
|
||||
}
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
extension Slope: GeneratorEnum {
|
||||
public typealias AudioType = Slope.Audio
|
||||
public typealias ControlType = Slope.Control
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
// ZeroCrossing.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
|
||||
/// File-scope zero-fill block for ZeroCrossing — fallback when upstream returns no channel.
|
||||
private let zeroCrossingZeroBlock: [Double] = [Double](
|
||||
repeating: 0,
|
||||
count: lyrebirdDefaultResultBufferSize
|
||||
)
|
||||
|
||||
/// Minimum sample count between crossings required before a zero crossing is recognised.
|
||||
/// Mirrors SuperCollider `ZeroCrossing_Ctor` guard (`counter > 4`) — rejects spurious
|
||||
/// high-frequency noise crossings. A crossing is only recorded when the inter-crossing
|
||||
/// sample count exceeds this threshold.
|
||||
private let zeroCrossingMinCount: Int = 4
|
||||
|
||||
/// Zero-crossing frequency estimator. Equivalent to SuperCollider `ZeroCrossing`.
|
||||
///
|
||||
/// Counts samples between successive rising zero crossings (≤0 → >0 edges) and computes a
|
||||
/// frequency estimate as `sampleRate / sampleCount`. The estimate is held between crossings
|
||||
/// and starts at `0.0` until the first full period is measured.
|
||||
///
|
||||
/// `_prevSample` is lazy-initialised to the first input sample on the very first call,
|
||||
/// matching SuperCollider's `ZeroCrossing_Ctor` (`m_previn = ZIN0(0)`). As a result,
|
||||
/// a constant positive (DC) input produces no crossing and the output remains `0.0`.
|
||||
/// Crossings require more than `zeroCrossingMinCount` (4) samples of inter-crossing
|
||||
/// spacing — spurious noise crossings are rejected.
|
||||
///
|
||||
/// ```swift
|
||||
/// // Estimate the frequency of an input signal.
|
||||
/// let freq = ZeroCrossing.Audio(input: OscSin.Audio(freq: 440.0))
|
||||
/// ZeroCrossing.Control(input: audioRateInput) // block-rate measurement
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to analyse. Can be any `ValidGeneratorInput`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public enum ZeroCrossing {
|
||||
|
||||
// MARK: - Shared base
|
||||
|
||||
/// Shared stored properties for `ZeroCrossing.Audio` and `ZeroCrossing.Control`.
|
||||
public class _Base: GeneratorBase {
|
||||
let _input: any ValidGeneratorInput
|
||||
let _mulAdd: MulAddSpec
|
||||
|
||||
/// Sample value from the previous `_computeSamples` call. Lazy-initialised to the
|
||||
/// first input sample on first use; not meaningful before that point.
|
||||
var _prevSample: Double = 0.0
|
||||
/// Samples elapsed since the last rising zero crossing.
|
||||
var _count: Int = 0
|
||||
/// Most recently measured frequency estimate, held until the next crossing.
|
||||
var _freq: Double = 0.0
|
||||
/// `false` until the very first sample is processed; guards lazy-init of `_prevSample`.
|
||||
var _initialized: Bool = false
|
||||
|
||||
init(
|
||||
input: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
super.init()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio rate
|
||||
|
||||
/// Audio-rate zero-crossing frequency estimator.
|
||||
///
|
||||
/// Computes a per-sample frequency estimate from rising zero-crossing spacing.
|
||||
/// The estimate is held between crossings. `_prevSample` is lazy-initialised to
|
||||
/// the first input sample; constant DC input yields `0.0`. Crossings require more
|
||||
/// than `zeroCrossingMinCount` (4) samples of spacing.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to analyse.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to analyse.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
input: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, mul: mul, add: add)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let inputSamples: [Double] = _input.calculatedSamples(
|
||||
graph: graph, count: count).first ?? zeroCrossingZeroBlock
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
|
||||
var prevSample: Double = _prevSample
|
||||
var xingCount: Int = _count
|
||||
var freq: Double = _freq
|
||||
var initialized: Bool = _initialized
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = inputSamples[i]
|
||||
if !initialized {
|
||||
prevSample = x
|
||||
initialized = true
|
||||
}
|
||||
xingCount += 1
|
||||
if xingCount > zeroCrossingMinCount && prevSample <= 0 && x > 0 {
|
||||
freq = sr / Double(xingCount)
|
||||
xingCount = 0
|
||||
}
|
||||
prevSample = x
|
||||
_result[0][i] = freq
|
||||
}
|
||||
|
||||
_prevSample = prevSample
|
||||
_count = xingCount
|
||||
_freq = freq
|
||||
_initialized = initialized
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Control rate
|
||||
|
||||
/// Block-rate zero-crossing frequency estimator.
|
||||
///
|
||||
/// Scans the full audio-rate input block running the same state machine as `Audio`;
|
||||
/// outputs the block-final frequency estimate as a flat block. The estimate is held
|
||||
/// between crossings and starts at `0.0` until the first period is measured.
|
||||
///
|
||||
/// `_prevSample` is lazy-initialised to the first input sample; constant DC input
|
||||
/// yields `0.0`. Crossings require more than `zeroCrossingMinCount` (4) samples of
|
||||
/// spacing, matching SuperCollider behaviour.
|
||||
///
|
||||
/// Bypasses the sub-block loop — the state machine must scan the full audio block
|
||||
/// exactly once per audio cycle to avoid double-advancing the crossing counter.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to analyse.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to analyse.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
input: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(input: input, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
/// Bypass sub-block loop: the zero-crossing state machine must scan the full
|
||||
/// audio-rate input block exactly once per audio block.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let inputSamples: [Double] = _input.calculatedSamples(
|
||||
graph: graph, count: count).first ?? zeroCrossingZeroBlock
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
|
||||
var prevSample: Double = _prevSample
|
||||
var xingCount: Int = _count
|
||||
var freq: Double = _freq
|
||||
var initialized: Bool = _initialized
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = inputSamples[i]
|
||||
if !initialized {
|
||||
prevSample = x
|
||||
initialized = true
|
||||
}
|
||||
xingCount += 1
|
||||
if xingCount > zeroCrossingMinCount && prevSample <= 0 && x > 0 {
|
||||
freq = sr / Double(xingCount)
|
||||
xingCount = 0
|
||||
}
|
||||
prevSample = x
|
||||
}
|
||||
|
||||
_prevSample = prevSample
|
||||
_count = xingCount
|
||||
_freq = freq
|
||||
_initialized = initialized
|
||||
|
||||
var fillValue: Double = freq
|
||||
_result[0].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
|
||||
guard count > 0 else { return _result }
|
||||
previousOutputValue = _result[0][count - 1]
|
||||
return _result
|
||||
}
|
||||
|
||||
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
extension ZeroCrossing: GeneratorEnum {
|
||||
public typealias AudioType = ZeroCrossing.Audio
|
||||
public typealias ControlType = ZeroCrossing.Control
|
||||
}
|
||||
@@ -51,7 +51,7 @@ public enum DiskOut {
|
||||
/// output(bus: 0, source: diskOut[0]) // pass-through to bus 0
|
||||
/// }
|
||||
/// }
|
||||
/// engine.add(Writer())
|
||||
/// try engine.add(Writer())
|
||||
/// try engine.start() // render / play
|
||||
/// diskOut.close() // flush remaining frames and close the file
|
||||
/// ```
|
||||
|
||||
@@ -10,10 +10,14 @@ import Synchronization
|
||||
|
||||
/// Interpolated read from `buffer` at a fractional frame `phase` for one `channel`.
|
||||
///
|
||||
/// - For `loop == true`: frames wrap modulo `buffer.count` (seamless looping). `wrappedFrame`
|
||||
/// handles negative frame indices via `r += frameCount`, so backward reads across the loop
|
||||
/// point are correct.
|
||||
/// - For `loop == false`: frames are clamped to `[0, buffer.count − 1]` (hold at ends).
|
||||
/// - For `loop == true`: frames wrap modulo `buffer.loopLength` (seamless looping).
|
||||
/// `wrappedFrame` handles negative frame indices via `r += frameCount`, so backward
|
||||
/// reads across the loop point are correct.
|
||||
/// - For `loop == false`: frames are clamped to `[0, buffer.loopLength − 1]` (hold at ends).
|
||||
///
|
||||
/// `buffer.loopLength` defaults to `buffer.count` (full-buffer looping) but may be
|
||||
/// narrowed at runtime — e.g. a looper pedal that recorded a take shorter than its
|
||||
/// max-duration buffer allocation — to bound wrap/clamp to just the recorded region.
|
||||
///
|
||||
/// Used by `PlayBuffer.Audio` and `PlayBuffer.Control`; exposed as `internal` for reuse by
|
||||
/// future buffer-reading generators (e.g. `BufferGrain`).
|
||||
@@ -25,7 +29,7 @@ internal func lyrebirdBufferRead(
|
||||
interpolation: TableInterpolation,
|
||||
loop: Bool
|
||||
) -> Double {
|
||||
let frameCount: Int = buffer.count
|
||||
let frameCount: Int = buffer.loopLength
|
||||
|
||||
@inline(__always)
|
||||
func clampedFrame(_ f: Int) -> Int {
|
||||
@@ -59,17 +63,11 @@ internal func lyrebirdBufferRead(
|
||||
case .cubic:
|
||||
let intPhase: Int = Int(phase.rounded(.down))
|
||||
let t: Double = phase - Double(intPhase)
|
||||
let t2: Double = t * t
|
||||
let t3: Double = t2 * t
|
||||
let pM1: Double = frame(intPhase - 1)
|
||||
let p0: Double = frame(intPhase)
|
||||
let p1: Double = frame(intPhase + 1)
|
||||
let p2: Double = frame(intPhase + 2)
|
||||
let catmullRomHalf: Double = 0.5
|
||||
return catmullRomHalf * ((2 * p0)
|
||||
+ (-pM1 + p1) * t
|
||||
+ (2 * pM1 - 5 * p0 + 4 * p1 - p2) * t2
|
||||
+ (-pM1 + 3 * p0 - 3 * p1 + p2) * t3)
|
||||
return catmullRomCubic(pM1, p0, p1, p2, t: t)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -362,7 +360,7 @@ public enum PlayBuffer {
|
||||
return _result
|
||||
}
|
||||
|
||||
let bufferFrames: Double = Double(buffer.count)
|
||||
let bufferFrames: Double = Double(buffer.loopLength)
|
||||
|
||||
@inline(__always)
|
||||
func rateAt(_ i: Int) -> Double {
|
||||
@@ -532,7 +530,7 @@ public enum PlayBuffer {
|
||||
// Read one output value for this block.
|
||||
let outputVal: Double
|
||||
if let buffer: LyrebirdBuffer = _slot.load(engine: graph.engine), buffer.isValid, !_isDone {
|
||||
let bufferFrames: Double = Double(buffer.count)
|
||||
let bufferFrames: Double = Double(buffer.loopLength)
|
||||
outputVal = lyrebirdBufferRead(
|
||||
buffer, channel: 0, phase: _phase,
|
||||
interpolation: interpolation, loop: loop
|
||||
|
||||
@@ -90,6 +90,27 @@ public enum RecordBuffer {
|
||||
var _isDone: Bool = false
|
||||
let _needsFree: Atomic<Bool> = Atomic(false)
|
||||
|
||||
/// Set by `requestReset()` on a non-RT thread, consumed once at the top of the
|
||||
/// next `_computeSamples` call on the RT thread.
|
||||
let _resetRequested: Atomic<Bool> = Atomic(false)
|
||||
|
||||
/// Block-rate snapshot of `writePos`, published once per audio block rather
|
||||
/// than per sample to avoid extra atomic-store overhead in the hot per-sample
|
||||
/// write loops. Updated at the end of every `_computeSamples` call.
|
||||
let _writePosSnapshot: Atomic<Int> = Atomic(0)
|
||||
|
||||
/// Number of frames written to `buffer` so far, safe to read from a non-RT
|
||||
/// thread.
|
||||
///
|
||||
/// `writePos` itself is a plain `var` mutated per-sample on the RT thread and
|
||||
/// is not safe for concurrent non-RT reads. This snapshot is published once
|
||||
/// per audio block (`.releasing` store at the end of `_computeSamples`) and
|
||||
/// read here with an `.acquiring` load, so a caller can safely read "how many
|
||||
/// frames were recorded" after stopping recording (e.g. setting `run = 0`) —
|
||||
/// for example a looper pedal narrowing `buffer.loopLength` to the actually
|
||||
/// recorded region once the take finishes.
|
||||
public var recordedFrameCount: Int { _writePosSnapshot.load(ordering: .acquiring) }
|
||||
|
||||
/// `true` when `doneAction == .freeNode` and recording has completed.
|
||||
///
|
||||
/// Read from a non-RT context after `processBlock` returns and schedule
|
||||
@@ -122,9 +143,42 @@ public enum RecordBuffer {
|
||||
|
||||
// MARK: - Shared
|
||||
|
||||
/// Requests that recording restart from frame 0 on the next processed block.
|
||||
///
|
||||
/// Safe to call from any non-RT thread at any time (e.g. a "reset" UI action on
|
||||
/// a looper pedal). Sets an `Atomic<Bool>` flag consumed once at the top of the
|
||||
/// next `_computeSamples` call — `writePos` is reset to `0`, `_isDone` cleared,
|
||||
/// and any pending `.freeNode` completion (`needsFree`) is cleared so the same
|
||||
/// instance can be reused for a fresh take. Because the flag is only checked at
|
||||
/// block boundaries, the reset takes effect at the start of the next block, not
|
||||
/// mid-block — acceptable for a user-triggered action.
|
||||
///
|
||||
/// Does **not** touch `buffer` contents or `buffer.loopLength`. Callers that want
|
||||
/// a fully blank take should also call `buffer.clear()` and
|
||||
/// `buffer.setLoopLength(buffer.count)` themselves before or after calling this.
|
||||
public func requestReset() {
|
||||
_resetRequested.store(true, ordering: .releasing)
|
||||
}
|
||||
|
||||
/// Consumes a pending reset request, if any. Call once at the top of
|
||||
/// `_computeSamples` before touching `writePos` / `_isDone`.
|
||||
@inline(__always)
|
||||
func _consumeResetIfRequested() {
|
||||
let (exchanged, _): (Bool, Bool) = _resetRequested.compareExchange(
|
||||
expected: true,
|
||||
desired: false,
|
||||
ordering: .acquiringAndReleasing
|
||||
)
|
||||
if exchanged {
|
||||
writePos = 0
|
||||
_isDone = false
|
||||
_needsFree.store(false, ordering: .releasing)
|
||||
}
|
||||
}
|
||||
|
||||
func handleEndOfBuffer() {
|
||||
_isDone = true
|
||||
writePos = buffer.count - 1
|
||||
writePos = buffer.loopLength - 1
|
||||
switch doneAction {
|
||||
case .nothing:
|
||||
break
|
||||
@@ -202,6 +256,10 @@ public enum RecordBuffer {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
_consumeResetIfRequested()
|
||||
// Publish `writePos` once per block (not per sample) for non-RT readers —
|
||||
// see `recordedFrameCount` doc-comment.
|
||||
defer { _writePosSnapshot.store(writePos, ordering: .releasing) }
|
||||
|
||||
let runSamples: [Double] = $run.calculatedSamples(graph: graph, count: count).first
|
||||
?? _zeroFallback
|
||||
@@ -212,7 +270,12 @@ public enum RecordBuffer {
|
||||
|
||||
let chCount: Int = channelCount
|
||||
let bufferIsLive: Bool = buffer.isValid
|
||||
let bufferCount: Int = buffer.count
|
||||
// Wrap/overrun bound is the caller-narrowed `loopLength` (defaults to `count`), for
|
||||
// both `loop == true` (a looping overdub recorder re-writes exactly the recorded
|
||||
// take instead of the full allocated buffer) and `loop == false` (the overrun pins
|
||||
// `writePos` to `loopLength - 1` via `handleEndOfBuffer()`, consistent with this bound
|
||||
// regardless of when the caller narrows `loopLength`).
|
||||
let bufferCount: Int = buffer.loopLength
|
||||
let canRecord: Bool = bufferIsLive && !_isDone
|
||||
let localLoop: Bool = loop
|
||||
|
||||
@@ -524,6 +587,10 @@ public enum RecordBuffer {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
_consumeResetIfRequested()
|
||||
// Publish `writePos` once per block (not per sample) for non-RT readers —
|
||||
// see `recordedFrameCount` doc-comment.
|
||||
defer { _writePosSnapshot.store(writePos, ordering: .releasing) }
|
||||
|
||||
// Evaluate params: advance ParameterNode state; use settled (last-sample) value.
|
||||
let runSamples: [Double] = $run.calculatedSamples(graph: graph, count: count).first
|
||||
@@ -551,7 +618,7 @@ public enum RecordBuffer {
|
||||
let existing: Double = buffer[writePos, 0]
|
||||
buffer.write(recVal * inputVal + preVal * existing, frame: writePos, channel: 0)
|
||||
writePos += 1
|
||||
if writePos >= buffer.count {
|
||||
if writePos >= buffer.loopLength {
|
||||
if loop { writePos = 0 }
|
||||
else { handleEndOfBuffer() }
|
||||
}
|
||||
|
||||
@@ -30,8 +30,9 @@ public enum In {
|
||||
|
||||
/// Reads from one or more consecutive audio buses.
|
||||
///
|
||||
/// The `bus` parameter accepts any ``ValidBus``: a plain `Int` index (1 channel),
|
||||
/// an ``AudioBus`` allocation (channel count taken from the bus), or a ``ControlBus``.
|
||||
/// The `bus` parameter takes a plain `Int` index (1 channel) or an ``AudioBus`` allocation
|
||||
/// (channel count taken from the bus). A ``ControlBus`` traps — `In.Audio` reads the audio-bus
|
||||
/// pool; use ``In/Control`` for a control bus.
|
||||
///
|
||||
/// ```swift
|
||||
/// In.Audio(bus: 5) // reads audioBuses[5], returns 1 channel
|
||||
@@ -42,8 +43,8 @@ public enum In {
|
||||
/// `floatValue` always returns the value of the first channel (bus).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bus: Source bus — `Int` index (1 channel), ``AudioBus`` (reads `channelCount`
|
||||
/// consecutive buses), or ``ControlBus``.
|
||||
/// - bus: Source bus — `Int` index (1 channel) or ``AudioBus`` (reads `channelCount`
|
||||
/// consecutive buses). A ``ControlBus`` traps; use ``In/Control``.
|
||||
/// - channels: Only available on the `Int`-index overload. Number of consecutive buses
|
||||
/// to read. Defaults to `1`. Fixed at init — no RT allocation.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
@@ -51,9 +52,10 @@ public enum In {
|
||||
/// Reads from a ``ValidBus``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bus: Source bus — `Int` index (1 channel), ``AudioBus`` (uses `channelCount`),
|
||||
/// or ``ControlBus``.
|
||||
/// - bus: Source bus — `Int` index (1 channel) or ``AudioBus`` (uses `channelCount`).
|
||||
/// A ``ControlBus`` traps; use ``In/Control``.
|
||||
public init(bus: any ValidBus) {
|
||||
_preconditionAudioRateBus(bus)
|
||||
let ch: Int = _resolvedChannelCount(bus)
|
||||
super.init(bus: bus.index, channels: ch)
|
||||
}
|
||||
@@ -126,7 +128,12 @@ public enum In {
|
||||
|
||||
/// Creates a `GeneratorArray` of independent single-channel generators, one per channel of `bus`.
|
||||
/// Prefer `In.Audio(bus:)` when a single multi-output generator is sufficient.
|
||||
///
|
||||
/// Takes an `Int` index or an ``AudioBus``; a ``ControlBus`` traps (this reads the audio-bus
|
||||
/// pool). The `Int` delegate below can't see the original typed bus, so the guard is applied
|
||||
/// here before delegating.
|
||||
public static func multi(bus: any ValidBus) -> GeneratorArray {
|
||||
_preconditionAudioRateBus(bus)
|
||||
let ch: Int = _resolvedChannelCount(bus)
|
||||
return multi(bus: bus.index, channels: ch)
|
||||
}
|
||||
@@ -137,8 +144,9 @@ public enum In {
|
||||
/// Reads from one or more consecutive control buses and delivers interpolated audio-rate
|
||||
/// ramps to downstream generators.
|
||||
///
|
||||
/// The `bus` parameter accepts any ``ValidBus``: a plain `Int` index (1 channel),
|
||||
/// a ``ControlBus`` allocation (channel count taken from the bus), or an ``AudioBus``.
|
||||
/// The `bus` parameter takes a plain `Int` index (1 channel) or a ``ControlBus`` allocation
|
||||
/// (channel count taken from the bus). An ``AudioBus`` traps — `In.Control` reads the
|
||||
/// control-bus pool; use ``In/Audio`` for an audio bus.
|
||||
///
|
||||
/// ```swift
|
||||
/// In.Control(bus: 10) // reads controlBuses[10], interpolated ramp
|
||||
@@ -153,8 +161,8 @@ public enum In {
|
||||
/// in steady state.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bus: Source bus — `Int` index (1 channel), ``ControlBus`` (reads `channelCount`
|
||||
/// consecutive buses with independent ramp state per channel), or ``AudioBus``.
|
||||
/// - bus: Source bus — `Int` index (1 channel) or ``ControlBus`` (reads `channelCount`
|
||||
/// consecutive buses with independent ramp state per channel). An ``AudioBus`` traps; use ``In/Audio``.
|
||||
/// - channels: Only available on the `Int`-index overload. Number of consecutive buses
|
||||
/// to read. Defaults to `1`. Fixed at init — no RT allocation.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
@@ -172,9 +180,10 @@ public enum In {
|
||||
/// Reads from a ``ValidBus``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bus: Source bus — `Int` index (1 channel), ``ControlBus`` (uses `channelCount`),
|
||||
/// or ``AudioBus``.
|
||||
/// - bus: Source bus — `Int` index (1 channel) or ``ControlBus`` (uses `channelCount`).
|
||||
/// An ``AudioBus`` traps; use ``In/Audio``.
|
||||
public init(bus: any ValidBus) {
|
||||
_preconditionControlRateBus(bus)
|
||||
let ch: Int = _resolvedChannelCount(bus)
|
||||
_previousOutputValues = [Double](repeating: 0.0, count: ch)
|
||||
super.init(bus: bus.index, channels: ch)
|
||||
|
||||
@@ -40,9 +40,9 @@ public enum Out {
|
||||
/// Accumulates into one or more consecutive audio buses using +=.
|
||||
/// Multiple ``Synthesizer`` instances writing to the same bus mix additively.
|
||||
///
|
||||
/// The `bus` parameter accepts any ``ValidBus``: a plain `Int` index, an ``AudioBus``
|
||||
/// allocation, or (unusually) a ``ControlBus``. When `bus` is an ``AudioBus``, writing
|
||||
/// is automatically clamped to `bus.channelCount` channels.
|
||||
/// The `bus` parameter takes a plain `Int` index or an ``AudioBus`` allocation (writes are
|
||||
/// clamped to `bus.channelCount` channels). Passing a ``ControlBus`` traps — an audio `Out`
|
||||
/// addresses the audio-bus pool, so use ``Out/Control`` for a control bus.
|
||||
///
|
||||
/// ## Multi-channel sources
|
||||
///
|
||||
@@ -57,9 +57,8 @@ public enum Out {
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bus: Destination bus — `Int` index (no channel clamping), ``AudioBus`` (clamped to
|
||||
/// `channelCount`), or ``ControlBus``. Passed to `In.Audio` or the `output(bus:source:)`
|
||||
/// helper.
|
||||
/// - bus: Destination bus — `Int` index (no channel clamping) or ``AudioBus`` (clamped to
|
||||
/// `channelCount`). A ``ControlBus`` traps; use ``Out/Control`` instead.
|
||||
/// - source: Signal to write. Multi-channel sources write to consecutive buses starting at
|
||||
/// `bus.index`.
|
||||
public final class Audio: _Base, AudioGenerator, RootRegistering {
|
||||
@@ -73,13 +72,14 @@ public enum Out {
|
||||
}
|
||||
|
||||
/// - Parameters:
|
||||
/// - bus: Destination bus — `Int` index, ``AudioBus``, or ``ControlBus``.
|
||||
/// When `bus` is an ``AudioBus``, writing is clamped to `bus.channelCount` channels.
|
||||
/// - bus: Destination bus — `Int` index or ``AudioBus`` (writing clamped to
|
||||
/// `bus.channelCount`). A ``ControlBus`` traps; use ``Out/Control`` instead.
|
||||
/// - source: Signal to write. Multi-channel sources write to consecutive buses.
|
||||
public init(
|
||||
bus: any ValidBus,
|
||||
source: any ValidGeneratorInput
|
||||
) {
|
||||
_preconditionAudioRateBus(bus)
|
||||
super.init(bus: bus.index, source: source, maxChannels: bus.channelCount)
|
||||
_registerAsRootIfBuilding()
|
||||
}
|
||||
@@ -115,9 +115,9 @@ public enum Out {
|
||||
/// a sink whose output is a control bus write). `previousOutputValue` is required by
|
||||
/// the ControlGenerator protocol but is not used.
|
||||
///
|
||||
/// The `bus` parameter accepts any ``ValidBus``: a plain `Int` index, a ``ControlBus``
|
||||
/// allocation, or an ``AudioBus``. When `bus` is a ``ControlBus``, writing is clamped to
|
||||
/// `bus.channelCount` channels.
|
||||
/// The `bus` parameter takes a plain `Int` index or a ``ControlBus`` allocation (writes are
|
||||
/// clamped to `bus.channelCount` channels). Passing an ``AudioBus`` traps — a control `Out`
|
||||
/// addresses the control-bus pool, so use ``Out/Audio`` for an audio bus.
|
||||
///
|
||||
/// ## Multi-channel sources
|
||||
///
|
||||
@@ -131,8 +131,8 @@ public enum Out {
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bus: Destination bus — `Int` index (1 channel, no clamping), ``ControlBus`` (clamped
|
||||
/// to `channelCount`), or ``AudioBus``.
|
||||
/// - bus: Destination bus — `Int` index (1 channel, no clamping) or ``ControlBus`` (clamped
|
||||
/// to `channelCount`). An ``AudioBus`` traps; use ``Out/Audio`` instead.
|
||||
/// - source: Signal to write. The last sample of each channel block is accumulated into
|
||||
/// the corresponding control bus. Multi-channel sources write to consecutive buses.
|
||||
public final class Control: _Base, ControlGenerator, RootRegistering {
|
||||
@@ -147,14 +147,15 @@ public enum Out {
|
||||
public override var outputChannelCount: Int { _channels }
|
||||
|
||||
/// - Parameters:
|
||||
/// - bus: Destination bus — `Int` index, ``ControlBus``, or ``AudioBus``.
|
||||
/// When `bus` is a ``ControlBus``, writing is clamped to `bus.channelCount` channels.
|
||||
/// - bus: Destination bus — `Int` index or ``ControlBus`` (writing clamped to
|
||||
/// `bus.channelCount`). An ``AudioBus`` traps; use ``Out/Audio`` instead.
|
||||
/// A plain `Int` writes a single channel.
|
||||
/// - source: Signal to write. Multi-channel sources write to consecutive buses.
|
||||
public init(
|
||||
bus: any ValidBus,
|
||||
source: any ValidGeneratorInput
|
||||
) {
|
||||
_preconditionControlRateBus(bus)
|
||||
let ch: Int = _resolvedChannelCount(bus)
|
||||
self._channels = ch
|
||||
super.init(bus: bus.index, source: source, maxChannels: bus.channelCount, channels: ch)
|
||||
|
||||
@@ -60,10 +60,10 @@ public enum ReplaceOut {
|
||||
/// Overwrites one or more consecutive audio buses with the source signal
|
||||
/// (wipes any prior writes to those buses in the current block).
|
||||
///
|
||||
/// The `bus` parameter accepts any ``ValidBus``: a plain `Int` index, an
|
||||
/// ``AudioBus`` allocation, or (unusually) a ``ControlBus``. When `bus` is
|
||||
/// an ``AudioBus``, writing is automatically clamped to `bus.channelCount`
|
||||
/// channels.
|
||||
/// The `bus` parameter takes a plain `Int` index or an ``AudioBus`` allocation
|
||||
/// (writing clamped to `bus.channelCount` channels). A ``ControlBus`` traps —
|
||||
/// an audio `ReplaceOut` addresses the audio-bus pool; use ``ReplaceOut/Control``
|
||||
/// for a control bus.
|
||||
///
|
||||
/// ## Multi-channel sources
|
||||
///
|
||||
@@ -81,8 +81,8 @@ public enum ReplaceOut {
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bus: Destination bus — `Int` index (no channel clamping), ``AudioBus``
|
||||
/// (clamped to `channelCount`), or ``ControlBus``.
|
||||
/// - bus: Destination bus — `Int` index (no channel clamping) or ``AudioBus``
|
||||
/// (clamped to `channelCount`). A ``ControlBus`` traps; use ``ReplaceOut/Control``.
|
||||
/// - source: Signal to write. Multi-channel sources overwrite consecutive
|
||||
/// buses starting at `bus.index`.
|
||||
public final class Audio: _Base, AudioGenerator, RootRegistering {
|
||||
@@ -102,13 +102,14 @@ public enum ReplaceOut {
|
||||
}
|
||||
|
||||
/// - Parameters:
|
||||
/// - bus: Destination bus — `Int` index, ``AudioBus``, or ``ControlBus``.
|
||||
/// When `bus` is an ``AudioBus``, writing is clamped to `bus.channelCount` channels.
|
||||
/// - bus: Destination bus — `Int` index or ``AudioBus`` (writing clamped to
|
||||
/// `bus.channelCount`). A ``ControlBus`` traps; use ``ReplaceOut/Control``.
|
||||
/// - source: Signal to write. Multi-channel sources overwrite consecutive buses.
|
||||
public init(
|
||||
bus: any ValidBus,
|
||||
source: any ValidGeneratorInput
|
||||
) {
|
||||
_preconditionAudioRateBus(bus)
|
||||
super.init(bus: bus.index, source: source, maxChannels: bus.channelCount)
|
||||
_registerAsRootIfBuilding()
|
||||
}
|
||||
@@ -151,9 +152,10 @@ public enum ReplaceOut {
|
||||
/// control bus write). `previousOutputValue` is required by the
|
||||
/// ControlGenerator protocol but is not used.
|
||||
///
|
||||
/// The `bus` parameter accepts any ``ValidBus``: a plain `Int` index, a
|
||||
/// ``ControlBus`` allocation, or an ``AudioBus``. When `bus` is a
|
||||
/// ``ControlBus``, writing is clamped to `bus.channelCount` channels.
|
||||
/// The `bus` parameter takes a plain `Int` index or a ``ControlBus`` allocation
|
||||
/// (writing clamped to `bus.channelCount` channels). An ``AudioBus`` traps —
|
||||
/// a control `ReplaceOut` addresses the control-bus pool; use ``ReplaceOut/Audio``
|
||||
/// for an audio bus.
|
||||
///
|
||||
/// ## Multi-channel sources
|
||||
///
|
||||
@@ -163,8 +165,8 @@ public enum ReplaceOut {
|
||||
/// usage.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bus: Destination bus — `Int` index (1 channel, no clamping),
|
||||
/// ``ControlBus`` (clamped to `channelCount`), or ``AudioBus``.
|
||||
/// - bus: Destination bus — `Int` index (1 channel, no clamping) or
|
||||
/// ``ControlBus`` (clamped to `channelCount`). An ``AudioBus`` traps; use ``ReplaceOut/Audio``.
|
||||
/// - source: Signal to write. The last sample of each channel block is
|
||||
/// written to the corresponding control bus.
|
||||
public final class Control: _Base, ControlGenerator, RootRegistering {
|
||||
@@ -176,8 +178,8 @@ public enum ReplaceOut {
|
||||
///
|
||||
/// - Note: Channel-count policy intentionally mirrors ``Out/Control``: a
|
||||
/// plain `Int` bus resolves to 1 channel (extra source channels are
|
||||
/// silently dropped); a ``ControlBus`` or ``AudioBus`` resolves to its
|
||||
/// explicit `channelCount`. ``ReplaceOut/Audio`` differs — a plain
|
||||
/// silently dropped); a ``ControlBus`` resolves to its explicit
|
||||
/// `channelCount`. ``ReplaceOut/Audio`` differs — a plain
|
||||
/// `Int` bus there writes all source channels via `_maxChannels =
|
||||
/// Int.max`. Use a typed bus allocation if you want explicit
|
||||
/// multi-channel writes from a plain index.
|
||||
@@ -186,13 +188,14 @@ public enum ReplaceOut {
|
||||
public override var outputChannelCount: Int { _channels }
|
||||
|
||||
/// - Parameters:
|
||||
/// - bus: Destination bus — `Int` index, ``ControlBus``, or ``AudioBus``.
|
||||
/// When `bus` is a ``ControlBus``, writing is clamped to `bus.channelCount` channels.
|
||||
/// - bus: Destination bus — `Int` index or ``ControlBus`` (writing clamped to
|
||||
/// `bus.channelCount`). An ``AudioBus`` traps; use ``ReplaceOut/Audio``.
|
||||
/// - source: Signal to write. Multi-channel sources overwrite consecutive buses.
|
||||
public init(
|
||||
bus: any ValidBus,
|
||||
source: any ValidGeneratorInput
|
||||
) {
|
||||
_preconditionControlRateBus(bus)
|
||||
let ch: Int = _resolvedChannelCount(bus)
|
||||
self._channels = ch
|
||||
super.init(bus: bus.index, source: source, maxChannels: bus.channelCount, channels: ch)
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
// ChaoticBase.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Shared base for strange-attractor / chaotic-map oscillators.
|
||||
///
|
||||
/// A chaotic oscillator iterates a discrete map (Lorenz, Hénon, …) at a chosen
|
||||
/// `freq` (iterations per second), **not** once per audio sample. Between
|
||||
/// successive iterations the audio output bridges the two map values according to
|
||||
/// `interpolation`:
|
||||
///
|
||||
/// - `.none` — hold the current iteration value until the next (hard, aliased).
|
||||
/// - `.linear` — straight-line ramp between successive iterations.
|
||||
/// - `.cubic` — 4-point cubic across the surrounding iterations (smoothest).
|
||||
///
|
||||
/// Same shape as `NoiseBase`: the base owns the cross-rate shared state
|
||||
/// (`_freqInput`, `_mulAdd`, `_interpolation`, the 4-value history ring, and the
|
||||
/// sub-iteration phase accumulator). Concrete per-map `_Base` subclasses add the
|
||||
/// map's own variables and the `iterate()` recurrence; `Audio` / `Control`
|
||||
/// variants inherit that subclass.
|
||||
///
|
||||
/// `freq` and the map parameters are read once per block (`floatValue`) — chaotic
|
||||
/// oscillators do not support per-sample audio-rate parameter modulation.
|
||||
public class ChaoticBase: GeneratorBase {
|
||||
let _freqInput: any ValidGeneratorInput
|
||||
var _mulAdd: MulAddSpec
|
||||
let _interpolation: TableInterpolation
|
||||
|
||||
/// History ring around the current `[_h0, _h1]` segment:
|
||||
/// `_hM1` = one iteration before the segment start, `_h2` = one after the end.
|
||||
/// `.none` reads `_h0`, `.linear` lerps `_h0…_h1`, `.cubic` uses all four.
|
||||
var _hM1: Double = 0.0
|
||||
var _h0: Double = 0.0
|
||||
var _h1: Double = 0.0
|
||||
var _h2: Double = 0.0
|
||||
|
||||
/// Fraction `[0, 1)` through the current iteration segment.
|
||||
var _phase: Double = 0.0
|
||||
|
||||
/// Lazy one-shot history priming guard (the concrete map seeds its variables
|
||||
/// at `init`, then the first `_computeSamples` fills the ring via `iterate()`).
|
||||
var _seeded: Bool = false
|
||||
|
||||
init(
|
||||
freq: any ValidGeneratorInput,
|
||||
interpolation: TableInterpolation,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput
|
||||
) {
|
||||
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
|
||||
self._freqInput = resolvedFreq
|
||||
self._interpolation = interpolation
|
||||
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
super.init()
|
||||
}
|
||||
|
||||
/// Advance the map one iteration and return its new output value.
|
||||
///
|
||||
/// Overridden by every concrete map `_Base`. The base implementation returns
|
||||
/// `0` — a missing override would silence the oscillator rather than trap on
|
||||
/// the RT thread.
|
||||
func iterate() -> Double { 0.0 }
|
||||
|
||||
/// Fill the history ring on first use: four warm-up iterations seed
|
||||
/// `_hM1, _h0, _h1, _h2` so the cubic kernel has real neighbours and the
|
||||
/// transient settles onto the attractor before audio is taken.
|
||||
@inline(__always)
|
||||
func primeIfNeeded() {
|
||||
if _seeded { return }
|
||||
_hM1 = iterate()
|
||||
_h0 = iterate()
|
||||
_h1 = iterate()
|
||||
_h2 = iterate()
|
||||
_phase = 0.0
|
||||
_seeded = true
|
||||
}
|
||||
|
||||
/// Per-sample phase increment for `freq`, clamped to `[0, chaoticMaxStepRate]`.
|
||||
///
|
||||
/// Negative `freq` holds (returns `0`) rather than driving `_phase` negative —
|
||||
/// the map has no backward iteration. The upper clamp bounds the `advancePhase`
|
||||
/// loop so an extreme `freq` cannot stall the RT thread.
|
||||
@inline(__always)
|
||||
func stepRate(freq: Double, sampleRate: Double) -> Double {
|
||||
let raw: Double = freq / sampleRate
|
||||
if raw <= 0 { return 0.0 }
|
||||
return min(raw, chaoticMaxStepRate)
|
||||
}
|
||||
|
||||
/// Advance the sub-iteration phase by `dphase`, performing as many `iterate()`
|
||||
/// steps as the phase crosses (shifting the history ring forward each time).
|
||||
@inline(__always)
|
||||
func advancePhase(by dphase: Double) {
|
||||
_phase += dphase
|
||||
while _phase >= 1.0 {
|
||||
_phase -= 1.0
|
||||
_hM1 = _h0
|
||||
_h0 = _h1
|
||||
_h1 = _h2
|
||||
_h2 = iterate()
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user