v1.3.0 release: graceful-release fix, quickstart template + demo, documentation accuracy pass
- Fixed: SynthesizerBase subclasses' release/free now dispatch correctly (gated synths were hard-freed instead of released). - New: quickstart project template + LyrebirdQuickstartDemo. - Docs: every example typechecked or provably illustrative (426->542); ~20 wrong-API examples fixed; root docs brought under the compile guard. - Fixed: NRT/Score demo Package.swift build from terminal again. See RELEASES.md for details.
This commit is contained in:
+19
-228
@@ -2,18 +2,20 @@
|
||||
|
||||
Phases are ordered by dependency. Each phase should have tests before moving on.
|
||||
|
||||
Completed phases (1–34, 36–95, 96a, 97, 99, 101, 102a, 102b, 103, 104a, 104b, 104c, 104d, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 159, 160, 161, 162, 163, 170, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 196, 197, 198, 88b, MCE-A, MCE-B, 85.5, 86.75a, 86.75b, LyrebirdBufferUpdates, 77-review-cleanup, 71b, 49b, 46, iOS-1–iOS-4, Score Phases A–D, 204, 222, GC-1–GC-9B, GC-11, GC-12) are archived in `docs/01-completed-working-order.md`.
|
||||
Completed phases (1–34, 36–95, 96a, 97, 99, 101, 102a, 102b, 103, 104a, 104b, 104c, 104d, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 159, 160, 161, 162, 163, 170, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 196, 197, 198, 88b, MCE-A, MCE-B, 85.5, 86.75a, 86.75b, LyrebirdBufferUpdates, 77-review-cleanup, 71b, 49b, 46, iOS-1–iOS-4, Score Phases A–D, 204, 222, GC-1–GC-9B, GC-11, GC-12, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239) are archived in `docs/01-completed-working-order.md`.
|
||||
|
||||
## Phase Completion Checklist
|
||||
|
||||
Before merging any phase branch to `main`:
|
||||
|
||||
1. All tests pass (`swift test`)
|
||||
2. Run `/lyrebird_review` — no blocking findings
|
||||
3. Fix any blocking issues found; re-run `/lyrebird_review` until clean
|
||||
4. Merge to `main` with a `--no-ff` merge commit
|
||||
5. `/lyrebird_review` updates `MEMORY.md` automatically on a clean pass
|
||||
6. Move the completed phase section from this file into `docs/01-completed-working-order.md` (append at the bottom) and update the summary table below
|
||||
1. All tests pass (`swift test --no-parallel` — the parallel runner has a known SIGABRT teardown flake)
|
||||
2. If the phase touched a **public signature**, `.docc`, or doc comments: `bash scripts/check-docc.sh` (no new DocC warnings) **and** `bash scripts/check-doc-snippets.sh` (recorded doc examples still compile)
|
||||
3. If the phase touched **`SynthesizerBase` / `Synthesizer` actor isolation**: `bash scripts/check-swift6-consumer.sh` — the test suite cannot catch isolation regressions (it doesn't build under `-default-isolation MainActor`)
|
||||
4. Run `/lyrebird_review` — no blocking findings
|
||||
5. Fix any blocking issues found; re-run `/lyrebird_review` until clean
|
||||
6. Merge to `main` with a `--no-ff` merge commit
|
||||
7. `/lyrebird_review` updates `MEMORY.md` automatically on a clean pass
|
||||
8. Move the completed phase section from this file into `docs/01-completed-working-order.md` (append at the bottom) and update the summary table below
|
||||
|
||||
## Generator Authoring Rules
|
||||
|
||||
@@ -229,232 +231,21 @@ Full details in `docs/01-completed-working-order.md`.
|
||||
| 228b | Parser meter round-trip — reads all `<time>` → `MeterMap` segments (sort, bar-1 guarantee, dedupe); `annotateBeams` per-measure capacity. Constant-meter byte-identical. Grouping re-inferred (MusicXML carries no grouping). | 4600 |
|
||||
| 228c | Anacrusis (pickup) notation + round-trip — `<measure number="0" implicit="yes">` (capacity = `anacrusis`), full bars 1-based, both loops + `measureCount` + beam accounting; parser recovers `anacrusis`. No-anacrusis byte-identical. | 4611 |
|
||||
| 229 | Polymeter notation — per-part `MeterMap` renders each part against its own meter (independent bar groupings/counts). Tests + `Meter`/`Polymeter`/`Beat timelines` docc + ScoreDemo material samples. Closes the beat-timeline group (223–229). | 4615 |
|
||||
| 230 | Configurable `SynthesisEngine.maxEventsPerBlock` (was hard-coded 256) — the per-block firing + carry-over look-ahead budget; threaded through `SynthesisEngineConfig`/`EngineHost`. RT-safe drop telemetry (`perBlockEventDropCount`) + one-line console warning drained off-RT (`freeWorker`/`stop()`/NRT post-render). `docs/engine/scheduling.md`. | 5456 |
|
||||
| 231 | `LyrebirdRoutineContext.onMain(_:)` — construct `@MainActor` synths inside a `@Sendable` routine/task body (result carried out of the main hop via a box; the shared bridge is `Void`-returning). Threading/isolation documented in `ARCHITECTURE.md` §9.2 + linked from GettingStarted / RoutineTask docs; records why `SynthesizerBase.init` cannot be `nonisolated` (MainActorConsumer fixture). | 5460 |
|
||||
| 232 | Doc sweep + DocC warning ratchet — `scripts/check-docc.sh` gates new DocC warnings against a 62-entry baseline (links pin full signatures; nothing else checks them). Fixed actively-wrong docs (SPSCQueue "rounds up" → traps; nonexistent `schedule(.remove:)`; `Package.swift` docc target), 11 `engine.add` examples missing `try`, and SynthesisEngine init/threading/NRT drift. | 5460 |
|
||||
| 233 | DocC link repair — 62 → 5 warnings. Score API grew params (`spanners:`, `meterMap:`, `normalType:`, `tie:`, `measureBarlines:`…) and DocC links pin full signatures, so every older link broke. Updated links; converted permanently-ambiguous overloads (`Chord`, `fill`, `dbToAmp`) and `internal` symbols to plain code. 5 article/symbol collisions left (DocC bug, IA decision). | 5460 |
|
||||
| 234 | DocC catalog to zero warnings — converted 5 filename-colliding articles (`SendTrigger`, `SpectralChain`, `StepSequencer`, `ValueComputable`, `GeneratorInputProvider`) into documentation extensions, so each guide merges into its symbol's page instead of shadowing the API reference. Baseline now empty; the gate is effectively strict. | 5460 |
|
||||
| 235 | Killed the three hand-copied API mirrors (`SynthesizerProtocol`, `GeneratorProtocol`, `EngineSetup`) — all three had already drifted — replacing them with gate-verified symbol-link tables; removed 75 references to the deleted `LyrebirdFloat`/`LyrebirdInt` types from live docs. | 5460 |
|
||||
| 236 | Doc-example compile harness — `check-doc-snippets.sh` typechecks doc fences against the real API via `swiftc -typecheck` + `#sourceLocation` (failures point at the .md line). Checked set classified by the compiler, not by hand: 323 of 1457. | 5460 |
|
||||
| 237 | Doc-example fallout — fixed `GettingStarted`'s flagship example (`doneAction`/`.freeEnclosing` never existed), made entry examples self-contained (coverage 382/1458; the original `try` rot now fails), harness `throws` wrapper + narrowest-first preambles, and pinned `DistributionKind`'s golden values (3 of 4 had drifted). | 5465 |
|
||||
| 238 | Doc-rot gap pass — extended the DocC gate to `LyrebirdUI` (was entirely unguarded; 0 warnings), implemented the `member` preamble (396 → 426 fences), confirmed zero remaining dead API forms, and established that the residual 1032 fences are continuation fragments no preamble can fix. | 5477 |
|
||||
| 239 | Doc checks in the review process — `check-doc-impact.sh` reports which docs a diff's public-API changes may have invalidated (validated against the commit that caused the original `engine.add` rot). Reports, never fails; suppresses refs the compile guard already covers; wired into `/lyrebird_review` step 2b. | 5477 |
|
||||
|
||||
---
|
||||
|
||||
## Upcoming Phases
|
||||
|
||||
### Beat-Timeline / Time-Signature group (Phases 224–229)
|
||||
|
||||
Goal: let authors place notes at explicit beat positions on a part timeline and
|
||||
auto-fill the rests (the `VoiceGenerator.from((1.0, Note…), (5.0, Note…))`
|
||||
request), with a real time-signature model underneath (compound, complex/
|
||||
additive, anacrusis, mid-piece meter changes, eventual polymeter).
|
||||
|
||||
Design decisions (locked with Josh):
|
||||
|
||||
- **One internal truth** = 0-based quarter-note beats (matches `ScoreEvent.beat`,
|
||||
tuplet math, engine). All musician-friendly addressing resolves down to it.
|
||||
- **`beatGrouping` is the primitive.** A `TimeSignature` carries a partition of
|
||||
the numerator into beats in denominator-note units. Auto-inferred, but
|
||||
explicitly overridable: `6/8` defaults compound `[3,3]` but can be made simple
|
||||
`[1,1,1,1,1,1]` (slow 6/8); additive `8/8` as `[3,3,2]` gives a 3+3+2 pulse.
|
||||
`isCompound` = "any group > 1". No special-casing — compound math falls out of
|
||||
the grouping data.
|
||||
- **Meter scope:** `Score.meterMap` is the global default; `Part.meterMap?` is an
|
||||
all-or-nothing override (nil = inherit; non-nil = a *complete* replacement map).
|
||||
A part can NOT patch a segment of the score map. `MeterMap` itself is segmented
|
||||
`[(startBar, TimeSignature)]`.
|
||||
- **Anacrusis:** `anacrusis: Fraction` (pickup length in quarters). Quarter `0.0`
|
||||
= pickup start; first full barline at `anacrusis`; pickup = bar 0 (`implicit`);
|
||||
bar 1 = first complete measure. Existing 1-based `TempoChange`/`Ending` measure
|
||||
refs stay bar ≥ 1 (pickup excluded).
|
||||
- **Overlap policy:** default traps loud + signals — throws a descriptive
|
||||
`TimelineError.overlap(at:previousEndsAt:incoming:)` (catchable, also routable
|
||||
to `LyrebirdMessageCenter`). Not a silent fix.
|
||||
- **Polymeter:** allow in the model from Phase 224 (cheap — the placement/`flatten`
|
||||
path is meter-map-driven, gets polymeter free); defer the hard *notation*
|
||||
(per-part non-aligning barlines, per-part encoder measure loop) to Phase 229.
|
||||
No retrofit — staged fill-in, not a rewrite.
|
||||
|
||||
#### Phase 224 — `TimeSignature` + `MeterMap` model ✓ *(complete — see `01-completed-working-order.md`)*
|
||||
|
||||
#### Phase 225 — `ScoreTimeline.fill` (quarter-beat addressing) + shared rest-fill ✓ *(complete — see `01-completed-working-order.md`)*
|
||||
|
||||
#### Phase 226 — `BeatPosition` (musical addressing) + meter-aware resolver ✓ *(complete — see `01-completed-working-order.md`)*
|
||||
|
||||
#### Phase 227 — Overlap policies + multi-voice timelines ✓ *(complete — see `01-completed-working-order.md`)*
|
||||
|
||||
#### Phase 228 — Homometric mid-piece meter changes (encoder) ✓ *(complete — see `01-completed-working-order.md`)*
|
||||
|
||||
#### Phase 228b — Parser meter round-trip + per-measure beams ✓ *(complete — see `01-completed-working-order.md`)*
|
||||
|
||||
#### Phase 228c — Anacrusis notation + round-trip ✓ *(complete — see `01-completed-working-order.md`)*
|
||||
|
||||
#### Phase 228.5 — Drop phase-number references from code/docs ✓ *(complete)*
|
||||
|
||||
- Swept `Phase NNN` references from all source comments, doc-comments, `.docc`
|
||||
prose, `@Suite` strings, and test file/type/function names (59 files). Renamed
|
||||
`Phase60ScatterCollectionTests`/`Phase57NoiseTests`/`Phase201IsolationGuardTests`.
|
||||
- New CLAUDE.md hard rule **"No phase numbers in code or docs"** (under Swift
|
||||
Code Style Rules → review-flagged) enforces it for code-writing + review agents
|
||||
going forward. DSP term "phase" exempt.
|
||||
|
||||
#### Phase 229 — Polymeter notation ✓ *(complete — see `01-completed-working-order.md`)*
|
||||
|
||||
Per-part meter already rendered correctly once the encoder went per-part for
|
||||
mid-piece meter changes (`part.meterMap ?? score.meterMap`, parts encode
|
||||
independently) — so this was tests + docs + ScoreDemo material samples, not a
|
||||
structural lift. **The beat-timeline / time-signature group (223–229) is
|
||||
complete.**
|
||||
|
||||
New work beyond this group is scoped from the **Deferred / Future** and **Not
|
||||
planned** lists below as demand appears.
|
||||
|
||||
### Generator Consolidation + RT Performance group (GP-1 … GP-9)
|
||||
|
||||
Goal: collapse remaining duplicated per-sample / per-init Generator code into
|
||||
shared helpers, and land a set of benchmark-gated real-time performance wins on
|
||||
the audio render path (`_computeSamples` / `calculatedSamples`). Sourced from an
|
||||
architecture sweep of `Sources/Lyrebird/Generators/` + `GeneratorCore/`.
|
||||
|
||||
Splits into two work-streams: **dedup** (no behaviour change, gated on tests
|
||||
only) and **perf** (gated on before/after benchmark + tests + review). Each
|
||||
phase is its own branch off `main` per the standing phase-branch policy.
|
||||
|
||||
**Locked decisions (with Josh):**
|
||||
|
||||
- **vDSP/vForce strategy = split-path, keep scalar fallback.** Each vectorised
|
||||
generator branches on `n == count` (upstream block full-length — the normal
|
||||
case at *any* block size, including small control blocks like 64). Only the
|
||||
rare short-upstream-block case (`n < count`) falls to the existing scalar
|
||||
loop. The vDSP/vForce call fires for 64-sample control blocks too — the gate
|
||||
is upstream-fullness, not absolute block size. If benchmarks show vDSP call
|
||||
overhead losing at *tiny* counts (1/2/4), add a `count >= minVectorCount`
|
||||
threshold (strictly better than "vDSP everywhere"). Revisit a
|
||||
"vDSP-everywhere + zero-pad" variant only if the split-path data warrants it.
|
||||
- **Benchmark harness = existing `Sources/LyrebirdBenchmark/main.swift`.** Add
|
||||
one timed case per perf phase (`ContinuousClock`, warmup + N timed iters,
|
||||
reports ns/block + ns/sample; `OfflineDriver` for in-context `processBlock`).
|
||||
Run release only: `swift run -c release LyrebirdBenchmark`. The control-block
|
||||
sweep (512 → 1) already in the harness shows the win-curve across block sizes.
|
||||
- **Per-phase gate.** Dedup phases: `swift test --no-parallel` green +
|
||||
`/lyrebird_review` clean. Perf phases: same, *plus* a committed before/after
|
||||
benchmark delta; keep the change only if it shows a real win with no test
|
||||
regression. Capture baseline numbers in the phase branch's first commit.
|
||||
|
||||
#### Phase GP-0 — Benchmark baseline capture
|
||||
|
||||
Add timed cases to `LyrebirdBenchmark` for every perf target *before* touching
|
||||
code: `BinaryOpGenerator` (scalar-mul, vector-add), unary math (`Sin`/`Exp`/
|
||||
`Sqrt`/`Abs`), `LinLin.Audio`, SVF generator-driven `freq`, `Chorus.Audio`.
|
||||
Run the control-block sweep on each. Commit the baseline numbers as the
|
||||
reference all GP perf phases diff against. No production code change.
|
||||
|
||||
#### Phase GP-1 — Trivial / low-risk dedup (no perf risk) ✓ *(complete — merged to main)*
|
||||
|
||||
Pure consolidation, semantically identical, gated on tests + review only:
|
||||
|
||||
- **D1** — Merge byte-identical `normalizeLFPhase` / `normalizeBLPhase` into one
|
||||
`normalizeOscPhase(_:)` helper. 8 oscillator `.Control` callers
|
||||
(LF/Osc Sawtooth/Square/Triangle/DutyCycle).
|
||||
- **D7** — Add `lyrebirdTwoPi` to `Math/LyrebirdConstants.swift`; replace 5
|
||||
inline `let twoPi = 2.0 * .pi` locals (Chorus/Flanger/Phaser/Jitter/
|
||||
ScannedSynthesizer). Removes magic-number-rule smell on the hot path.
|
||||
- **D4** — Adopt existing `resolveGeneratorOrScalar(...)` in `Chorus`/`Flanger`/
|
||||
`Phaser._computeSamples` — replaces ~17 hand-rolled 8-line input-resolution
|
||||
blocks. Helper already proven in Flute/Clarinet/Pan*/PlateReverb.
|
||||
- **D2** — Extract `computeButterworthQs(order:) -> [Double]` (new
|
||||
`Filters/ButterworthHelpers.swift`); 4 Butterworth filters call it at init.
|
||||
|
||||
#### Phase GP-2 — SVF helper extraction + coefficient interpolation (D6 + P4) ✓ *(complete — merged to main; −5.9% on gen-driven-freq bench)*
|
||||
|
||||
Bundles a dedup and a perf win that touch the same code:
|
||||
|
||||
- **D6** — Extract `runSVFBlock(...)` (Chamberlin recurrence + denormal flush +
|
||||
zero-fill); `SVF.Audio` and `SVF.Control._computeSamples` collapse to setup +
|
||||
one call + `mulAdd`. Name `svfMinQDamping` / `svfFCoeffMax` constants.
|
||||
- **P4** — In the generator-driven-`freq` path, replace per-sample
|
||||
`Darwin.sin(piOverSr·freq)` with block-boundary `fFirst`/`fLast` + linear
|
||||
interpolation (same technique as `runRBJBiquadBlock`). Eliminates ~510 of 512
|
||||
`sin` calls/block on that path. Benchmark the gen-driven-freq case.
|
||||
|
||||
Gate: tests + review + benchmark (perf component).
|
||||
|
||||
#### Phase GP-3 — Butterworth LP/HP cascade engine extraction (D3) ✓ *(complete — merged to main; ~250 dup lines removed, behavior-identical)*
|
||||
|
||||
- **D3** — Extract shared background-thread vDSP cascade machinery
|
||||
(`runScalar`/`runVDSP`/`runAudioRate`/deinit drain + the `_vdsp*Queue` set)
|
||||
into a `ButterworthCascadeEngine` in `ButterworthHelpers.swift`. LP and HP
|
||||
inject two coefficient closures and become thin wrappers. Removes ~250 lines
|
||||
of duplicated thread lifecycle. Medium risk — match the thread teardown
|
||||
exactly. Gate: tests + review. Sets up GP-9.
|
||||
|
||||
#### Phase GP-4 — Unary math vForce/vDSP fast path (P3) ✓ *(complete — merged to main; −66.9% / ~3× on the 4-op unary chain)*
|
||||
|
||||
- **P3** — Split-path vectorisation for `Sin`/`Cos`/`Exp`/`Log`/`Sqrt`/`Floor`/
|
||||
`Ceil` (`vvsin`/`vvcos`/`vvexp`/`vvlog`/`vvsqrt`/`vvfloor`/`vvceil`) and
|
||||
`Abs` (`vDSP_vabsD`). `n == count` → vectorised; `n < count` → existing scalar
|
||||
loop. No allocation (write into pre-zeroed `_result`). Highest single-generator
|
||||
throughput win (~4–10×). Benchmark each across the control-block sweep; apply
|
||||
`minVectorCount` threshold if tiny blocks regress.
|
||||
|
||||
#### Phase GP-5 — `BinaryOpGenerator` enum dispatch + vDSP (P2) ✓ *(complete — merged to main; gen×gen −56%, gen×scalar −72%)*
|
||||
|
||||
- **P2** — Replace the stored `op: (Double,Double)->Double` closure with an
|
||||
operator enum (`.add`/`.subtract`/`.multiply`/`.divide`) classified at init;
|
||||
dispatch aligned gen-vs-gen / gen-vs-scalar paths to `vDSP_vaddD`/`vsubD`/
|
||||
`vmulD`/`vdivD`/`vsaddD`/`vsmulD`. Keep the per-sample closure fallback for
|
||||
non-arithmetic / unaligned-count cases. Highest *graph-wide* win — every
|
||||
`osc * 0.5 + env` chain. Preserve IEEE-754 divide-by-zero behaviour. Medium
|
||||
risk — enumerate all variants, keep closure escape hatch. Benchmark scalar-mul
|
||||
+ vector-add cases.
|
||||
|
||||
#### Phase GP-6 — `LinLin` vDSP fast path (P7) ✓ *(complete — merged to main; −26.9%. LinExp/ExpLin deferred)*
|
||||
|
||||
- **P7** — `LinLin.Audio` → single `vDSP_vsmsaD` (`a·x + b`, coefficients
|
||||
hoisted out of loop; range params are always block-scalar so unconditional).
|
||||
Short-block fallback keeps the exact per-sample formula.
|
||||
- *Deferred:* `LinExp`/`ExpLin` (build the linear stage via vDSP then `vvexp` —
|
||||
needs a pre-allocated scratch buffer at init; modest incremental win, revisit
|
||||
if a profile flags them).
|
||||
|
||||
#### Phase GP-7 — Power-of-two delay-line wrapping (P5) ✓ *(complete — merged to main; Chorus −3.3%)*
|
||||
|
||||
- **P5** — `Chorus`/`Flanger` circular delay lines: size up to next power of two
|
||||
at init, replace per-sample `% delayLineCount` (3–4 per sample) with
|
||||
`& (delayLineCount - 1)`. ~2× delay-buffer memory (≈64 KB at max delay) for
|
||||
~6–9 cycles/sample saved. Add init-time `roundUpToPowerOfTwo(_:)`. Benchmark
|
||||
`Chorus.Audio`.
|
||||
|
||||
#### Phase GP-8 — Butterworth band-pass / band-reject vDSP cascade (P6) ✓ *(complete — merged to main; shared ButterworthSectionEngine, BP/BR gain vDSP + dedup)*
|
||||
|
||||
- **P6** — Extend the GP-3 `ButterworthCascadeEngine` vDSP path to
|
||||
`ButterworthBandPass` (sequenced HP→LP) and `ButterworthBandReject` (parallel
|
||||
LP+HP summed via `vDSP_vaddD`). Matches the LP/HP acceleration. Depends on
|
||||
GP-3. Band-reject needs two vDSP setups + dual kill-queue drain. Benchmark a
|
||||
4th-order bandpass.
|
||||
|
||||
**Sequencing:** GP-0 (baseline) → GP-1 (safe dedup) → GP-2/GP-3 (helper
|
||||
extractions, GP-3 before GP-8) → GP-4/GP-5 (highest-value perf) → GP-6/GP-7 →
|
||||
GP-8. Each lands on `main` via `--no-ff` before the next starts, per policy.
|
||||
|
||||
**Not pursued:** D5 (`OscSin.Audio` inlined switch) — intentional audio-rate
|
||||
choice (three branchless loops vs per-sample function call); leave as-is, revisit
|
||||
only if `OscillatorTableReadHelpers` gains a bitmask-wrap variant.
|
||||
|
||||
### Generator Catalog Expansion — 1.2 (SuperCollider parity gaps) ✓ *(complete)*
|
||||
|
||||
Closed the most-noticed UGen gaps relative to SuperCollider (trigger/timing
|
||||
logic, control-signal conditioning, filters, waveshaping/routing, chaotic
|
||||
oscillators, analysis). **The whole 1.2 group is complete** — GC-1…GC-9B, GC-11,
|
||||
and GC-12 merged to main; GC-10 (`DFM1`) skipped on license grounds (GPL source +
|
||||
baked GPL LUT). All phase records are archived in
|
||||
`docs/01-completed-working-order.md` (§ Generator Catalog Expansion — 1.2).
|
||||
`TGrains` and `PingPongDelay` were explicitly excluded from this group (deferred
|
||||
separately).
|
||||
|
||||
### Longer-term — Not planned
|
||||
|
||||
#### Phase 96b — Ableton Link *(not planned)*
|
||||
|
||||
Ableton Link SDK integration for peer-to-peer beat sync over LAN/WiFi was
|
||||
scoped but will not be built. MIDI Clock follow (Phase 96a, complete on `main`)
|
||||
is the supported external-transport path. Revisit only if real demand appears;
|
||||
the SDK-vendoring cost (C++ SwiftPM target, abl_link FFI shim, Bonjour
|
||||
entitlements, 2-device test bench) is not justified otherwise.
|
||||
|
||||
---
|
||||
|
||||
## Deferred / Future
|
||||
|
||||
|
||||
@@ -10760,3 +10760,331 @@ parameter where more than one bridging mode is wanted.
|
||||
Validated against the **1 kHz @ 40 dB SPL = 1 sone** definition anchor (all
|
||||
models), +10 dB ≈ 2× (Stevens), monotonicity, silence→0, free≠diffuse. Design +
|
||||
algorithm + tables: `docs/stdlib/analysis.md`. This completes the GC 1.2 group.
|
||||
|
||||
---
|
||||
|
||||
## Phase 230 — Configurable `maxEventsPerBlock` + drop telemetry ✓ *(merged to main)*
|
||||
|
||||
- **`SynthesisEngine.maxEventsPerBlock`** — the per-block scheduling budget (events
|
||||
firing per block **and** future-event carry-over / look-ahead depth) was a hard-coded
|
||||
`private static let = 256`; now an `init` parameter (default
|
||||
`lyrebirdDefaultMaxEventsPerBlock = 256`, `> 0`, power-of-two **not** required) stored
|
||||
as a `public let` and read on the RT thread as a plain immutable. Threaded through
|
||||
`SynthesisEngineConfig` + `EngineHost`. Clarified that this cap — not
|
||||
`eventQueueCapacity` — is the ceiling that governs whether a large batch of
|
||||
pre-scheduled / carried-over events survives; the two are independent (carry-over
|
||||
accumulates across blocks, so `maxEventsPerBlock` may exceed `eventQueueCapacity`,
|
||||
e.g. under a JIT NRT feed).
|
||||
- **Drop telemetry + console warning** — when the RT drain discards an event for
|
||||
exceeding the cap it calls `_recordPerBlockEventDrop()`: a relaxed counter increment
|
||||
+ a `.releasing` latch store (no allocation / lock / `print` — RT-safe). A non-RT
|
||||
drain (`freeWorker` timer, `stop()`, and the end of `NRTDriver.start()` so a
|
||||
fast-exiting NRT process still reports) does an `.acquiring` CAS on the latch and
|
||||
prints a one-line `[Lyrebird] Warning: … exceeded maxEventsPerBlock …` at most once
|
||||
per drain. Public `perBlockEventDropCount` / `resetPerBlockEventDropCount()` mirror
|
||||
the existing `pendingQueueDroppedCount` surface. Docs: `docs/engine/scheduling.md`
|
||||
(new "Per-Block Event Budget" section).
|
||||
- Tests: `MaxEventsPerBlockTests` (6) — default-cap drops surplus look-ahead, raised
|
||||
cap keeps all, exact drop-count arithmetic, counter stays zero within cap, configured
|
||||
value exposed, default matches constant. Review fixes: latch store `.relaxed →
|
||||
.releasing` for a correct release/acquire pair with the drain; dropped an over-strict
|
||||
`maxEventsPerBlock <= eventQueueCapacity` precondition (staging arrays are independent
|
||||
of ring size — it broke small-queue engines).
|
||||
|
||||
---
|
||||
|
||||
## Phase 231 — `ctx.onMain` + threading/isolation docs ✓ *(merged to main)*
|
||||
|
||||
- **`LyrebirdRoutineContext.onMain(_:)`** — runs a `@MainActor` closure, blocks the
|
||||
routine/task body until it returns, and hands the (possibly non-`Sendable`) result back.
|
||||
Lets a `@Sendable` body construct `@MainActor` synthesizers inline, so the *number* and
|
||||
*parameters* of synths can depend on the body's own logic rather than being pre-allocated
|
||||
outside and captured (the `BufferDemos` idiom). Built on the existing
|
||||
`lyrebirdRunMainActorMutation` bridge — that helper returns `Void` because a non-`Sendable`
|
||||
result cannot cross back through `DispatchQueue.sync`, so a private `_OnMainResultBox`
|
||||
(`@unchecked Sendable`, safe by the sync hop's full barrier) carries the value out.
|
||||
Deadlock-free: a body always runs off-main, so the internal `DispatchQueue.main.sync` cannot
|
||||
re-enter its own thread. Synchronous cost is absorbed by `wait(seconds:)`'s existing drift
|
||||
compensation. `rethrows`.
|
||||
- **Threading documentation** — `ARCHITECTURE.md` §9.2 ("Working with the isolation from a
|
||||
routine or task"): a table of what is main-bound and *why* (load-bearing vs ergonomic),
|
||||
the pre-publication (`init`) vs post-publication (parameter write) distinction, `ctx.onMain`
|
||||
for construction, and `ctx.set` + a main-captured `$param` for mutation (a lock-free atomic
|
||||
write — *not* a main hop; the only cost is the capture). Linked from `GettingStarted.md`
|
||||
(new "Threading" section), `Lyrebird.docc/RoutineTask.md`, and
|
||||
`docs/tooling/routine-task.md` (§ Thread model → Actor isolation).
|
||||
- **Recorded why `SynthesizerBase.init` cannot be made `nonisolated`** — it looks free (empty
|
||||
base init, `build()` not called from it, fresh synth unshared) but under
|
||||
`-default-isolation MainActor` a consumer subclass's *implicit* `@MainActor init()` would
|
||||
override a `nonisolated` base init and fail isolation-mismatch, breaking every unannotated
|
||||
consumer — the guarantee §9.1 documents. The main suite cannot catch this (it does not build
|
||||
under that flag); only `RegressionFixtures/MainActorConsumer` does. `onMain` buys the same
|
||||
ergonomics additively with no isolation change. Dropped the stale `(Phase 201)` tag from the
|
||||
§9.1 heading per the no-phase-numbers-in-docs rule.
|
||||
- Tests: `RoutineContextOnMainTests` (4) — result built on the main thread, synthesizer
|
||||
constructed inside the body (3 dynamic synths all reach `build()`), thrown errors propagate,
|
||||
non-`Sendable` reference type returned. Suite is intentionally not `@MainActor`: `run`
|
||||
blocks the caller, so the body's hops need a free main thread.
|
||||
|
||||
---
|
||||
|
||||
## Phase 232 — Doc sweep + DocC warning ratchet ✓ *(merged to main)*
|
||||
|
||||
- **`scripts/check-docc.sh`** — guards against new DocC warnings (broken symbol links,
|
||||
ambiguous refs, article/symbol collisions). DocC symbol links pin a symbol's **full
|
||||
signature**, so adding one parameter silently breaks every link to it — and nothing in
|
||||
`swift build` / `swift test` checks this, which is why ~84 warnings had accumulated
|
||||
undetected (including one broken by the `maxEventsPerBlock` init parameter in the cycle it
|
||||
shipped). A **ratchet**, not a zero-gate: fails only on warnings absent from the committed
|
||||
`scripts/docc-warnings-baseline.txt` (62 entries), so it gates regressions today while the
|
||||
Score-signature backlog is cleared incrementally. Baseline identity is `message :: file` —
|
||||
line/col are dropped because they shift on unrelated edits. `--update-baseline` re-records
|
||||
(may only shrink); `--strict` requires zero (goal state). Verified both directions: an
|
||||
injected bogus link fails with exit 1; a removed baseline entry reports "now fixed" and
|
||||
suggests tightening. Manual/CI only (~60s) — deliberately not in `pre-commit`, which is fast
|
||||
by design. Documented in CLAUDE.md alongside the previously-undocumented
|
||||
`check-swift6-consumer.sh`, and both added to the phase-completion checklist.
|
||||
- **Doc corrections — actively wrong:** `SPSCQueue.init(capacity:)` was documented as
|
||||
"capacity rounded up to next power of 2" in two files; it **preconditions** — a
|
||||
non-power-of-two traps rather than rounding. `EnvelopeGen`'s usage example called
|
||||
`engine.schedule(.remove(synth), at:)`, an overload that does not exist (→ `engine.remove`).
|
||||
`Package.swift`'s own DocC command named `--target Lyrebird`; the target is `LyrebirdSynth`.
|
||||
- **Doc corrections — stale since add/schedule became throwing:** 11 doc-comment examples
|
||||
called `engine.add(...)` without `try` (SynthesisEngine, VoicePool, ParallelGroup,
|
||||
NodePosition, ParameterNode, DiskOut) — none would compile.
|
||||
- **SynthesisEngine:** `EngineSetup.md`'s init block was missing `controlBlockSize`,
|
||||
`eventQueueCapacity`, and `maxEventsPerBlock`; added with a table distinguishing the two
|
||||
scheduling ceilings. Class-doc thread-safety text claimed `add`/`remove`/`schedule` are all
|
||||
"safe to call from the main thread" — imprecise: `add`/`schedule` are `@MainActor`-isolated
|
||||
(SPSC single-producer), `remove` is `nonisolated`. `NRTGuide`'s "large scores" advice pinned
|
||||
the pre-`maxEventsPerBlock` init signature and only mentioned `eventQueueCapacity` — the
|
||||
carry-over cap is what actually drops a large pre-scheduled batch; now covers both knobs plus
|
||||
the `TriggerListener` just-in-time alternative. Added a Per-Block Event Budget section to
|
||||
docc `Scheduling.md`, and normalised ~15 MusicXML symbol links to the current full signature.
|
||||
- Remaining backlog (baselined, not blocking): ~62 DocC warnings, almost all Score-system
|
||||
signature links (`Note` / `Chord` / `Part` / `Score.init`), `fill(_:overlap:)` ambiguity, and
|
||||
5 article/symbol name collisions.
|
||||
|
||||
---
|
||||
|
||||
## Phase 233 — DocC link repair (62 → 5) ✓ *(merged to main)*
|
||||
|
||||
- **Cleared the DocC backlog the ratchet was holding**: 62 baselined warnings → 5. Baseline
|
||||
tightened accordingly (`scripts/docc-warnings-baseline.txt`); the gate stays green and now
|
||||
guards a much smaller floor.
|
||||
- **Root cause, uniformly**: DocC symbol links pin a symbol's **full** signature, and the Score
|
||||
API grew parameters over the beat-timeline group — `Note`/`Chord` gained
|
||||
`spanners:`/`display:`/`marks:`/`dynamicCurve:`, `Part` gained `meterMap:`/`offset:`/`id:`,
|
||||
`Score.init` gained `measureBarlines:`/`timeSignature:`, `ScoreElement.tuplet` gained
|
||||
`normalType:`, `ScoreElement.chord` gained `tie:`, `toMusicXMLString`/`Data` gained
|
||||
`rehearsalMarksAsStaffText:`. Every older link silently broke. Links updated to the current
|
||||
signatures.
|
||||
- **Converted to plain code where a symbol link cannot ever resolve** (rather than pinning a
|
||||
fragile signature): overloads that collapse to one DocC signature and are therefore
|
||||
permanently ambiguous — `Chord(_:dur:…)` (`[Pitch]` vs `[(NoteName, Int)]`),
|
||||
`ScoreTimeline.fill(_:overlap:)` (array-of-pairs vs dictionary), `dbToAmp(_:)` (scalar vs
|
||||
array); symbols DocC never emits a page for because they are `internal` — `BeatTrackerCore`,
|
||||
`Dynamic.midiMaxVelocity`, `Fraction.beatApproxDenominator`; and links to initializers that
|
||||
do not exist (`Score(parts:)`, `init(parts:)`). Bare `` ``Part`` `` / `` ``Tuplet`` `` /
|
||||
`` ``Voice`` `` prose mentions likewise became plain code — a DocC link to an overloaded DSL
|
||||
builder renders as the full ugly signature and re-breaks on the next parameter addition.
|
||||
- Fixed `` ``.rest(duration:)`` `` (a leading dot never resolves → `ScoreElement/rest(duration:)`)
|
||||
and pointed `Klank` / `Klang`'s `setBuffer(_:engine:)` links at the nested `Audio` class that
|
||||
actually declares them.
|
||||
- **Remaining 5 (baselined, deliberate):** article/symbol filename collisions
|
||||
(`SendTrigger`, `SpectralChain`, `StepSequencer`, `ValueComputable`,
|
||||
`GeneratorInputProvider`) — an acknowledged DocC bug where a curated article shadows the
|
||||
symbol's reference page. These are an information-architecture decision (rename the article
|
||||
vs. convert it to a symbol extension), not stale links, and both options change published doc
|
||||
URLs — deferred pending a maintainer call rather than restructured unilaterally.
|
||||
|
||||
---
|
||||
|
||||
## Phase 234 — DocC catalog to zero warnings ✓ *(merged to main)*
|
||||
|
||||
- **Converted the 5 colliding articles to documentation extensions** — `SendTrigger`,
|
||||
`SpectralChain`, `StepSequencer`, `ValueComputable`, `GeneratorInputProvider`. Each was an
|
||||
article whose *filename* matched a public symbol, so DocC (by its own acknowledged bug) let
|
||||
the article shadow the symbol's reference page — the API reference for five public types was
|
||||
unreachable. Changing each H1 from a plain title to a symbol link (`` # ``SendTrigger`` ``)
|
||||
makes the file an extension, so DocC merges the guide **into** the symbol's page instead:
|
||||
one canonical page carrying both the prose guide and the generated API reference.
|
||||
`@Metadata { @PageKind(article) }` removed (invalid on an extension).
|
||||
- Cost of the approach, accepted deliberately: the three custom titles are gone
|
||||
("RT-to-Language Triggers", "Step Sequencer", "Value Sources for Non-RT Loops") — an
|
||||
extension is titled by its symbol. Each page's abstract still carries the framing.
|
||||
- `<doc:X>` references across the catalog (Scheduling, ParameterInputs, ProcessSystem,
|
||||
RoutineTask, Generators/Triggers, Lyrebird.md) rewritten to the symbol-link form ``` ``X` ```.
|
||||
`Lyrebird.md` curated both `<doc:StepSequencer>` **and** ``StepSequencer`` as separate
|
||||
Topics bullets — the same page twice once merged — so the duplicates were removed
|
||||
(same for `ValueComputable`).
|
||||
- **The catalog is now at zero DocC warnings** (from ~84 at the start of the sweep). The
|
||||
ratchet's baseline is empty, so `check-docc.sh` now fails on *any* new warning —
|
||||
`--strict` passes and is equivalent while the baseline stays empty. CLAUDE.md and the
|
||||
script header updated to describe the cleared state rather than a backlog.
|
||||
|
||||
---
|
||||
|
||||
## Phase 236 — Doc-example compile harness ✓ *(merged to main)*
|
||||
|
||||
- **`scripts/check-doc-snippets.sh`** + **`scripts/doc_snippets.py`** — typechecks the
|
||||
```swift examples in the DocC catalog and the `///` doc comments against the real API.
|
||||
Nothing else could: `swift build` never sees a code fence and `check-docc.sh` only
|
||||
validates symbol links, which is why `engine.add` could become throwing while 11 examples
|
||||
kept calling it without `try`, and why 75 references to the deleted `LyrebirdFloat`
|
||||
survived. Both are type errors, so typechecking catches them.
|
||||
- **Mechanism.** Each fence is generated into a throwaway `.swift` under `mktemp -d`
|
||||
(nothing touches the working tree): imports hoisted to file scope — each replaced in
|
||||
place by a blank line so line numbers stay exact — and the body wrapped in
|
||||
`@MainActor func _fence_N()`. `@MainActor` because doc examples are language-side code
|
||||
and a nonisolated wrapper would false-positive on every `engine.add`; everything inside
|
||||
the function so two fences declaring the same helper can't collide at file scope.
|
||||
`#sourceLocation` makes a failure point at the **original markdown file and line**.
|
||||
Deliberately not a guard sub-package — that would re-resolve the dependency graph and
|
||||
full-link a module already built, for a check that only needs `swiftc -typecheck`.
|
||||
- **Classify, don't mark.** The checked set (`scripts/doc-snippets-manifest.txt`) is
|
||||
produced by asking the compiler which fences compile, never by annotating ~1450 fences.
|
||||
Fences that compile under no preamble self-exclude — iOS-only examples, `Package.swift`
|
||||
snippets and pseudo-code drop out with no skip list. Result: **323 of 1457 checkable**
|
||||
(304 under `none`, 19 more under `engine`); 1134 fragments unchecked. Classify ~35 s
|
||||
(parallel), check ~32 s.
|
||||
- **Soundness bug found and fixed during the build.** The first classify claimed 1455 of
|
||||
1457 compiled. Batching is unsound: a parse error in one file (an invalid
|
||||
`Package.swift` fence) aborts swiftc before later files are reached, so "no diagnostic"
|
||||
does not mean "compiles" — ~1450 unreached fences were silently recorded as passing.
|
||||
Classification is now one invocation per file, parallelised. Checks still batch, which
|
||||
*is* sound when clean (no diagnostics at all means the whole set was processed).
|
||||
- **Verified both directions, and an honest negative.** Renaming a parameter in a covered
|
||||
example fails with the true source line (`Envelopes/Envelope.swift:143`). But
|
||||
re-injecting the original historical rot — dropping `try` from
|
||||
`GettingStarted.md`'s `try engine.add(MySynth())` — **passes**, because that fence needs
|
||||
both an `engine` and a `MySynth` in scope and is therefore unclassifiable. The harness
|
||||
does not cover the exact incident that motivated it. The fix is to make that example
|
||||
self-contained (phase 237), not to grow the preamble table.
|
||||
|
||||
---
|
||||
|
||||
## Phase 237 — Doc-example fallout + golden values ✓ *(merged to main)*
|
||||
|
||||
- **Fixed the flagship example, which did not compile.** `GettingStarted.md`'s "Add a
|
||||
synthesizer" — the first code a new user copies — set `doneAction = .freeEnclosing` inside
|
||||
`build()`. `doneAction` is not a member of ``SynthesizerBase`` (it is a read-only
|
||||
*Generator* property), and **`.freeEnclosing` does not exist at all** (the cases are
|
||||
`.nothing` / `.freeNode` / `.loop`). Two errors in six lines. Replaced with a plain
|
||||
continuous synth, plus a second example showing the real self-freeing idiom —
|
||||
`EnvelopeGen(doneAction: .freeNode)`.
|
||||
- **Made the entry examples self-contained**, which is better documentation *and* pulls them
|
||||
into harness coverage: the wiring example is now a complete `main.swift` (engine + start +
|
||||
add) rather than the bare fragment `try engine.add(MySynth())`. `GettingStarted` went from
|
||||
**0 of 5** covered to 3.
|
||||
- **Closed the coverage gap phase 236 reported.** Re-injecting the original historical rot —
|
||||
dropping `try` from `GettingStarted`'s `engine.add` — now **fails** at the exact markdown
|
||||
line. In phase 236 that same injection passed.
|
||||
- **Two harness fixes found by chasing that gap:**
|
||||
- The generated wrapper was not `throws`, so **every fence using `try` failed to
|
||||
classify** — silently excluding the exact examples most worth checking. Making it
|
||||
`throws` unlocked +53 fences (a missing `try` still errors, which is the point).
|
||||
- Preambles are now tried narrowest-first (`none` → `synth` → `engine`), because a
|
||||
preamble that declares a name the fence also declares makes the fence fail. Coverage:
|
||||
**382 of 1458** (was 323).
|
||||
- **Golden values — the rot a typecheck cannot see.** `DistributionKind`'s four documented
|
||||
sequences passed `seed:` to ``TemporalTendency``, which has no such parameter (the seed
|
||||
belongs to ``TemporalStream``), so none of them compiled. Worse, once run against the real
|
||||
API, **three of the four documented sequences were wrong** — `.lpRand`, `.hpRand`,
|
||||
`.meanRand` had drifted, while their prose descriptions stayed correct (actual `.lpRand` is
|
||||
exactly `uniform²`, as described). Corrected the API and the values, and pinned them with
|
||||
`DistributionKindGoldenValueTests`, which also asserts the *characterisations*
|
||||
(`.lpRand == uniform²`, `.hpRand == 1 − uniform²`) so the prose is verified rather than
|
||||
merely asserted.
|
||||
- **Kept `_DocTheorySnippetCheckTests` rather than retiring it.** The plan assumed the
|
||||
extractor would subsume it; the harness does now typecheck **17 of theory.md's 21** fences,
|
||||
but that suite *is* value assertions (`#expect(Interval.majorThird.semitones == 4)`) —
|
||||
precisely what a typecheck cannot do. Deleting it would have lost coverage. Its header now
|
||||
states the division of labour, and CLAUDE.md records golden-value tests as the standing
|
||||
companion to the compile guard.
|
||||
|
||||
---
|
||||
|
||||
## Phase 238 — Doc-rot gap pass ✓ *(merged to main)*
|
||||
|
||||
Swept what the guards could not see. Each item below was measured, not assumed.
|
||||
|
||||
- **`LyrebirdUI.docc` was entirely unguarded** — `check-docc.sh` only built the
|
||||
`LyrebirdSynth` target, so a broken link in the public UI module's catalog produced no
|
||||
signal anywhere. The gate now builds every consumer-facing catalog
|
||||
(`TARGETS=("LyrebirdSynth" "LyrebirdUI")`). Its first-ever build came back at **0 warnings**,
|
||||
so nothing needed fixing — but the coverage was the point. Verified in both directions: an
|
||||
injected bogus link into `LyrebirdUI.docc` now fails with the correct file.
|
||||
- **The LiveCompile catalog stays a deliberate gap.** `LiveCompile/` has no
|
||||
`swift-docc-plugin` dependency, so `generate-documentation` cannot run there at all; its
|
||||
catalog is one 86-line file with 2 fences. Adding a plugin dependency and a second gate
|
||||
invocation to a dev-only sub-package is disproportionate. Recorded in `check-docc.sh`'s
|
||||
header so the omission is a decision rather than an oversight.
|
||||
- **Known-dead API forms: clean.** Grepped the whole corpus for every form this series
|
||||
retired — `.freeEnclosing`, `doneAction` assignment on a synth, `LyrebirdFloat`,
|
||||
`LyrebirdInt`, `seed:` on an algorithm — and found **zero** remaining outside the historical
|
||||
planning archives (which legitimately record what was true at the time).
|
||||
- **Implemented the fourth preamble, `member`.** Triage of the 1062 unchecked fences showed
|
||||
the single biggest blocker was `output` (118 occurrences) — `output(bus:source:)` is a
|
||||
`SynthesizerBase` member that exists in no other context, so those fences are `build()`
|
||||
bodies lifted out of their class. `member` is structurally a *wrapper*, not a text prefix:
|
||||
the body goes inside `final class DocSynth_N: SynthesizerBase { override func build() { … } }`.
|
||||
Gain: **+30** (396 → **426**). Less than hoped, because most `output` fences *also*
|
||||
reference a previous fence's locals — which brings us to:
|
||||
- **The remaining 1032 are dominated by continuation fences and are not preamble-fixable.**
|
||||
The undefined identifiers are `sig` (142), `osc` (62), `lfo` (32), `env` (18) — arbitrary
|
||||
locals defined in a *preceding* fence. No preamble can supply those; only rewriting the doc
|
||||
self-contained can, one example at a time (as phase 237 did for GettingStarted). All four
|
||||
planned preambles (`none`/`synth`/`engine`/`member`) are now implemented, and per the plan
|
||||
the table stops here.
|
||||
- **Golden values: `DistributionKind` was the only gap.** A corpus scan for docs asserting
|
||||
concrete numeric output found exactly two files. The other, `LyrebirdMusicMath`'s
|
||||
`interpolateAt` examples, turned out to be **already pinned** — including both documented
|
||||
clipping cases — by `MusicMathTests.interpolateAtFraction/ClipHigh/ClipLow`. Verified the
|
||||
values against the real API anyway (all three correct). No new test needed.
|
||||
- **Verified the guards compose.** Breaking a doc example fails the check via the content
|
||||
hash; following the advice to `--classify` is then **REFUSED** by the shrink guard
|
||||
("A doc example probably broke — fix it rather than un-recording it"). A broken example
|
||||
cannot be silently un-recorded without an explicit `--allow-shrink`.
|
||||
|
||||
---
|
||||
|
||||
## Phase 239 — Doc checks in the review process ✓ *(merged to main)*
|
||||
|
||||
- **`scripts/check-doc-impact.sh` + `scripts/doc_impact.py`** — reports which docs a diff's
|
||||
public-API changes may have invalidated. Doc rot is overwhelmingly *caused* by an API
|
||||
change, and a review that reads only the diff **structurally cannot find it**: the stale
|
||||
references live in files the diff never touches. Validated against the real commit that
|
||||
caused the original incident (`f4b5be6`, which converted `engine.add` to `throws`) — the
|
||||
tool names `SynthesisEngine.add` and lists the docs referencing it, which is exactly the
|
||||
set that then rotted for months.
|
||||
- **It reports and never fails.** It cannot distinguish "intentionally unaffected" from
|
||||
"forgotten", and a check that cannot judge must not block. Every other guard in the repo
|
||||
fails on violation; this one deliberately does not, which is why it is wired into
|
||||
`/lyrebird_review` (step 2b) and pasted into the review agent's prompt rather than run as a
|
||||
gate.
|
||||
- **It composes with the existing guards instead of duplicating them.** References inside
|
||||
fences that `check-doc-snippets.sh` already typechecks are **suppressed** — re-reporting
|
||||
them would bury the references nobody is checking. Everything it lists is unverified by any
|
||||
automation.
|
||||
- **Two precision problems, both fixed by measurement rather than assumption:**
|
||||
- Matching the bare declaration name returned **1329** hits for `add` — almost all English
|
||||
prose ("must *add* the same two-line extension"). That is the same signal-to-noise failure
|
||||
that sank phase 235b's corpus-wide identifier lint. References must be **code-shaped**
|
||||
(a call, a symbol link, or a code span): 1329 → 278.
|
||||
- The detector is name-based, so `add` also matched `group.add(` / `pool.add(`. Git's hunk
|
||||
headers carry the enclosing declaration, giving the owning type for free — the report now
|
||||
says `SynthesisEngine.add` vs `LyrebirdEventList.addPreMaster`, and states plainly that a
|
||||
member name is matched across types so the reviewer qualifies by owner.
|
||||
- Output is **grouped by file with counts**, not a flat sample: for a common member name a
|
||||
flat list is hundreds of lines and a reviewer checks none of them.
|
||||
- **New public API with no doc reference anywhere is called out explicitly** — the
|
||||
`maxEventsPerBlock` case, which reached zero `.docc` files in the cycle it shipped.
|
||||
- Wired into `/lyrebird_review` (new step 2b) and the review agent's documentation-accuracy
|
||||
section, which now says to *work the list* rather than to remember to grep. Correctly
|
||||
silent on docs-only diffs.
|
||||
|
||||
**Known limits, recorded honestly:** it is a text matcher, not a semantic one. It cannot see
|
||||
rot that no API change caused (`theory.md`'s `.freeEnclosing` was already dead — that needed
|
||||
the phase 238 sweep), and for short common member names the candidate list is long enough that
|
||||
the reviewer must qualify by owning type. It narrows where to look; it does not decide.
|
||||
|
||||
@@ -81,7 +81,7 @@ Mono sources are unaffected — they return one channel and write only `bus`.
|
||||
|
||||
## Multi-channel Expansion
|
||||
|
||||
`GeneratorArray` wraps N generators and returns an N-channel `[[LyrebirdFloat]]`.
|
||||
`GeneratorArray` wraps N generators and returns an N-channel `[[Double]]`.
|
||||
Create one with the `expand()` helper in `build()`:
|
||||
|
||||
```swift
|
||||
|
||||
@@ -47,7 +47,7 @@ final class SPSCQueue<T> {
|
||||
private let writeIdx = Atomic<Int>(0)
|
||||
private let readIdx = Atomic<Int>(0)
|
||||
|
||||
init(capacity: Int) { ... } // capacity rounded up to next power of 2
|
||||
init(capacity: Int) { ... } // capacity MUST be a power of two — precondition, not rounded
|
||||
|
||||
// Called from producer (main thread) only
|
||||
func enqueue(_ value: T) -> Bool
|
||||
@@ -117,13 +117,33 @@ currentBlockStart = engine.currentTime
|
||||
|
||||
Events scheduled before `currentBlockStart` (i.e., in the past) are applied immediately at `offset = 0`.
|
||||
|
||||
## Per-Block Event Budget — `maxEventsPerBlock`
|
||||
|
||||
Step 2's drain and the future-event **carry-over** are both hard-capped so the RT thread never reallocates its staging arrays mid-render. The cap is `maxEventsPerBlock`, a `SynthesisEngine.init` parameter (default `lyrebirdDefaultMaxEventsPerBlock = 256`, a power of two is *not* required — only `> 0`). Also settable via `SynthesisEngineConfig` / `EngineHost`.
|
||||
|
||||
It bounds **two** things per block:
|
||||
|
||||
- **Events firing this block** — how many `targetTime ∈ [blockStart, blockEnd)` events apply in one block.
|
||||
- **Look-ahead depth** — how many future-dated events the engine carries across a block boundary. Events scheduled further out than the current block sit in a `carryOverEvents` buffer capped at the same value; anything beyond it is **dropped**, not deferred.
|
||||
|
||||
This is the ceiling that governs whether a large batch of pre-scheduled events survives — **not** `eventQueueCapacity` (which only bounds the SPSC ring's in-flight occupancy). The two are independent: `maxEventsPerBlock` may legitimately exceed `eventQueueCapacity`, because carry-over accumulates across blocks (e.g. under a just-in-time NRT feed) while the ring only ever holds a per-drain burst.
|
||||
|
||||
### When events are dropped
|
||||
|
||||
Dropping is silent to the audio path but instrumented off the RT thread:
|
||||
|
||||
- **`engine.perBlockEventDropCount: UInt64`** — monotonic count of events dropped for exceeding the cap since start (or since `resetPerBlockEventDropCount()`). Distinct from `pendingQueueDroppedCount` (which counts main-thread *enqueue* failures against `eventQueueCapacity`).
|
||||
- **Console warning** — a one-line `[Lyrebird] Warning: … exceeded maxEventsPerBlock …` is printed at most once per drain interval. The RT thread only sets a relaxed counter + a `.releasing` latch (no allocation / lock / `print`); a non-RT drain (`freeWorker` timer, `stop()`, and the end of `NRTDriver.start()`) prints and clears the latch.
|
||||
|
||||
Raising the cap costs only pre-allocated staging memory (three arrays × `maxEventsPerBlock` `ScheduledEvent`s), reserved once in `start()` — no RT cost. Alternatively, keep the cap and **spread scheduling over time** (e.g. a JIT feed driven by a `TriggerListener` in NRT) so no single block's onset density or look-ahead exceeds the budget.
|
||||
|
||||
## Generator Interface — count Parameter
|
||||
|
||||
Because segments are variable length, generators produce `count` samples rather than always `blockSize`:
|
||||
|
||||
```swift
|
||||
protocol Generator {
|
||||
func calculatedSamples(graph: SynthGraph, count: Int) -> [[LyrebirdFloat]]
|
||||
func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]]
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
+24
-17
@@ -7,8 +7,8 @@ The base unit of signal production in Lyrebird.
|
||||
```swift
|
||||
protocol Generator: AnyObject {
|
||||
var rate: ProcessingRate { get }
|
||||
func calculatedSamples(graph: SynthGraph, count: Int) -> [[LyrebirdFloat]]
|
||||
func floatValue(graph: SynthGraph) -> LyrebirdFloat
|
||||
func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]]
|
||||
func floatValue(graph: SynthGraph) -> Double
|
||||
}
|
||||
|
||||
protocol AudioGenerator: Generator {} // rate == .audio
|
||||
@@ -112,32 +112,39 @@ describe(OscSin.self) // Audio: OscSin.Audio Control: OscSin.Control
|
||||
## Type Aliases
|
||||
|
||||
```swift
|
||||
typealias LyrebirdFloat = Double
|
||||
typealias LyrebirdInt = Int
|
||||
typealias LyrebirdFloatClosureBody = (SynthGraph, Int) -> LyrebirdFloat
|
||||
typealias ClosureBody = (SynthGraph, Int) -> Double // RT-safe closure signature
|
||||
```
|
||||
|
||||
Samples are plain `Double` and counts plain `Int` — Lyrebird does not wrap them in aliases.
|
||||
|
||||
## ValidGeneratorInput Protocol
|
||||
|
||||
Enables seamless mixing of constants, generators, parameter keys, and closures as generator inputs. All of the following are valid:
|
||||
Enables seamless mixing of constants, generators, and closures as generator inputs. All of the following are valid:
|
||||
|
||||
```swift
|
||||
OscSin.Audio(freq: 440.0) // Float literal
|
||||
OscSin.Audio(freq: someGenerator) // another Generator
|
||||
OscSin.Audio(freq: "FreqParam") // string parameter key — resolved at runtime
|
||||
OscSin.Audio(freq: { g, i in ... }) // closure
|
||||
let someGenerator: OscSin.Control = OscSin.Control(freq: 2.0, mul: 10.0, add: 440.0)
|
||||
|
||||
let a: OscSin.Audio = OscSin.Audio(freq: 440.0) // Double literal
|
||||
let b: OscSin.Audio = OscSin.Audio(freq: 60) // Int literal
|
||||
let c: OscSin.Audio = OscSin.Audio(freq: someGenerator) // another Generator
|
||||
let d: OscSin.Audio = OscSin.Audio(freq: Closure { graph, i in Double(i) }) // closure
|
||||
```
|
||||
|
||||
To drive an input from a live parameter, wire a `@LiveParam`'s projected value (`$freq`, a
|
||||
`ParameterNode`) into the generator. `String` is **not** a `ValidGeneratorInput` — the old
|
||||
string-parameter-key input was removed when `ParameterNode` / `UIParamNode` became
|
||||
`ControlGenerator`s.
|
||||
|
||||
```swift
|
||||
protocol ValidGeneratorInput {
|
||||
func calculatedSamples(graph: SynthGraph, count: Int) -> [[LyrebirdFloat]]
|
||||
func floatValue(graph: SynthGraph) -> LyrebirdFloat
|
||||
func intValue(graph: SynthGraph) -> LyrebirdInt
|
||||
func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]]
|
||||
func floatValue(graph: SynthGraph) -> Double
|
||||
func intValue(graph: SynthGraph) -> Int
|
||||
func needsInterpolation() -> Bool
|
||||
func sampleBlock(graph: SynthGraph, count: Int, previousValue: LyrebirdFloat) -> [LyrebirdFloat]
|
||||
func sampleBlock(graph: SynthGraph, count: Int, previousValue: Double) -> [Double]
|
||||
}
|
||||
|
||||
// Conforming types: Double, Int, String, any Generator, Closure
|
||||
// Conforming types: Double, Int, any Generator, Closure, GeneratorInputProvider
|
||||
// Contract: calculatedSamples must always return a non-empty outer array (at least one channel).
|
||||
```
|
||||
|
||||
@@ -199,7 +206,7 @@ mono-izes the generator under arithmetic.
|
||||
|
||||
When one or both operands are non-Generator literals (`Double` or `Int`), `BinaryOpGenerator`
|
||||
uses `floatValue` instead of `calculatedSamples` for that side. This avoids the per-block
|
||||
`[[LyrebirdFloat](repeating:count:)]` heap allocation that the `Double`/`Int` conformers would
|
||||
`[[Double](repeating:count:)]` heap allocation that the `Double`/`Int` conformers would
|
||||
otherwise produce. The classification is performed once in `init` and stored as `lhsIsLiteral`
|
||||
/ `rhsIsLiteral` — no type-metadata checks on the RT thread.
|
||||
|
||||
@@ -251,7 +258,7 @@ is never violated in engine-driven usage. New generators **must** follow this pa
|
||||
|
||||
```swift
|
||||
// Canonical new-generator calculatedSamples skeleton:
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[LyrebirdFloat]] {
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
precondition(count <= _result[0].count,
|
||||
"count \(count) exceeds pre-allocated buffer. "
|
||||
+ "Ensure blockSize <= lyrebirdDefaultResultBufferSize.")
|
||||
|
||||
@@ -31,8 +31,8 @@ Subclass `SynthesizerBase` and override `build()`. Declare mutable parameters wi
|
||||
```swift
|
||||
// Example — your synthesizer, defined by subclassing SynthesizerBase
|
||||
final class SineTone: SynthesizerBase {
|
||||
@LiveParam var freq: LyrebirdFloat = 440.0
|
||||
@LiveParam var amp: LyrebirdFloat = 0.5
|
||||
@LiveParam var freq: Double = 440.0
|
||||
@LiveParam var amp: Double = 0.5
|
||||
|
||||
override func build() {
|
||||
let osc = OscSin.Audio(freq: $freq, phase: 0.0)
|
||||
@@ -234,7 +234,7 @@ Override `release(engine:)` in synthesizers that have an envelope gate:
|
||||
|
||||
```swift
|
||||
final class GatedNote: SynthesizerBase {
|
||||
@LiveParam var gate: LyrebirdFloat = 1.0
|
||||
@LiveParam var gate: Double = 1.0
|
||||
|
||||
override func build() {
|
||||
// … gate drives EnvelopeGen …
|
||||
|
||||
@@ -31,6 +31,13 @@ public protocol Synthesizer: AnyObject {
|
||||
|
||||
Default `evaluate` and `free` are provided by a protocol extension. Default `release` throws `SynthesizerError.noGate` — override it in synthesizers that have a gate input.
|
||||
|
||||
`SynthesizerBase` re-declares `release(engine:)` and `free(engine:)` as `open` members mirroring
|
||||
those defaults. This is deliberate and load-bearing: a protocol-extension default binds
|
||||
statically at the conformance, so without the class members a subclass's implementation would
|
||||
be unreachable through an `any Synthesizer` — including `Group.release`'s cascade to its
|
||||
children, which would then see `.noGate` and hard-free every gated child. Subclass
|
||||
`SynthesizerBase` and `override`. See `ARCHITECTURE.md` §9.1.
|
||||
|
||||
---
|
||||
|
||||
## Synthesizer Lifecycle
|
||||
@@ -41,7 +48,7 @@ Signal the synthesizer to begin releasing (set gate → 0, trigger doneAction en
|
||||
|
||||
```swift
|
||||
final class GatedNote: SynthesizerBase {
|
||||
@LiveParam var gate: LyrebirdFloat = 1.0
|
||||
@LiveParam var gate: Double = 1.0
|
||||
|
||||
override func build() { /* … gate drives EnvelopeGen … */ }
|
||||
|
||||
@@ -102,8 +109,8 @@ Most Synthesizer implementations should subclass `SynthesizerBase` rather than c
|
||||
```swift
|
||||
// Example — your synthesizer, defined by subclassing SynthesizerBase
|
||||
final class SineTone: SynthesizerBase {
|
||||
@LiveParam var freq: LyrebirdFloat = 440.0
|
||||
@LiveParam var amp: LyrebirdFloat = 0.5
|
||||
@LiveParam var freq: Double = 440.0
|
||||
@LiveParam var amp: Double = 0.5
|
||||
|
||||
override func build() {
|
||||
let osc = OscSin.Audio(freq: $freq, phase: 0.0)
|
||||
@@ -192,6 +199,44 @@ producing a linearly-interpolated audio-rate buffer ramping to the new value. Th
|
||||
sized to the engine's control block: one ramp per audio block when `controlBlockSize ==
|
||||
blockSize` (default), or K ramps per audio block when `controlBlockSize < blockSize`.
|
||||
|
||||
### Changing a `@LiveParam` from a Routine / Task
|
||||
|
||||
`@LiveParam` values can be driven from a `LyrebirdRoutine` / `LyrebirdTask` body — algorithmic,
|
||||
sequential, timed control code that runs on a **background thread**. The `ParameterNode`'s value
|
||||
setter is a releasing atomic store, so a routine/task-body write is safe (a single control-side
|
||||
producer alongside the RT thread's acquiring load) — the same store as the main-thread setter.
|
||||
|
||||
Two facts shape how you access the parameter:
|
||||
|
||||
- The synth is `@MainActor`-isolated, so `tone.freq` and `tone.$freq` can't be reached from the
|
||||
`@Sendable` body (that's a main-actor access from a background thread).
|
||||
- The projected node `$freq` is a **`ParameterNode`, which is `Sendable`**.
|
||||
|
||||
So **capture the projected node on the main actor at setup, then drive it from the body** with
|
||||
`ctx.set` / `ctx.ramp` (see `docs/tooling/routine-task.md` § Live parameters):
|
||||
|
||||
```swift
|
||||
let tone = SineTone() // @MainActor setup
|
||||
let freq = tone.$freq // ParameterNode — Sendable, captured once
|
||||
|
||||
LyrebirdTask.run(engine: engine) { ctx in // @Sendable body — background thread
|
||||
ctx.add(tone)
|
||||
try ctx.wait(beats: 1)
|
||||
ctx.set(freq, to: 660) // step
|
||||
try ctx.ramp(freq, to: 220, beats: 2) // glide, blocks for the duration
|
||||
ctx.remove(tone)
|
||||
}
|
||||
```
|
||||
|
||||
`ctx.set` / `ctx.ramp` take a **`ParameterNode` only** — `@UIParam`'s `UIParamNode` is `@Observable`
|
||||
and main-thread-only, so it is not a valid target from a background body; update `@UIParam` from the
|
||||
main thread.
|
||||
|
||||
> No-capture alternative: a synth driven mostly from routines can declare the node directly as
|
||||
> `nonisolated let freq = ParameterNode(440)` instead of `@LiveParam` — reachable from the body with
|
||||
> no capture line (`ctx.set(tone.freq, to: 660)`), trading the plain-`Double` value sugar and the
|
||||
> `$`-projection.
|
||||
|
||||
### Auto-registration via Mirror
|
||||
|
||||
`SynthesizerBase.rebuildGraph()` walks `Mirror(reflecting: self)` plus the superclass chain
|
||||
|
||||
@@ -366,8 +366,8 @@ final class MyOsc: GeneratorBase, AudioGenerator {
|
||||
Key points:
|
||||
- `freqIsGenerator` is stored at init, not checked per block.
|
||||
- The `calculatedSamples` / `floatValue` call is **outside the inner loop** — only the index lookup happens per sample.
|
||||
- When `freqIsGenerator` is false (literal `Double`/`Int`, `String`, or `Closure`), the scalar path calls `floatValue` once — zero extra allocation. `ConstantGeneratorInput` conforms to `Generator` and therefore takes the audio-rate `calculatedSamples` path; its buffer is pre-allocated so the path is RT-safe.
|
||||
- String parameter key inputs are classified as non-generator (`String` does not conform to `Generator`), so they always use the block-rate scalar path. This is correct: parameter updates are control-rate by design.
|
||||
- When `freqIsGenerator` is false (literal `Double`/`Int` or `Closure`), the scalar path calls `floatValue` once — zero extra allocation. `ConstantGeneratorInput` conforms to `Generator` and therefore takes the audio-rate `calculatedSamples` path; its buffer is pre-allocated so the path is RT-safe.
|
||||
- To drive an input from a live parameter, wire a `@LiveParam`'s projected value (`$name`, a `ParameterNode`) — a `ControlGenerator` — into it. (`String` is not a `ValidGeneratorInput`; the old string-parameter-key input was removed when `ParameterNode` / `UIParamNode` became `ControlGenerator`s.)
|
||||
|
||||
### FM synthesis example
|
||||
|
||||
|
||||
@@ -43,9 +43,9 @@ Requires a **mono** buffer (`channelCount == 1`). Use `RecordBuffer.Audio` for m
|
||||
|
||||
```swift
|
||||
// Both variants inherit these from RecordBuffer._Base:
|
||||
@LiveParam public var run: LyrebirdFloat // > 0 = recording, ≤ 0 = paused (default 1.0)
|
||||
@LiveParam public var recLevel: LyrebirdFloat // scale on incoming signal (default 1.0)
|
||||
@LiveParam public var preLevel: LyrebirdFloat // scale on existing buffer (default 0.0 = overwrite)
|
||||
@LiveParam public var run: Double // > 0 = recording, ≤ 0 = paused (default 1.0)
|
||||
@LiveParam public var recLevel: Double // scale on incoming signal (default 1.0)
|
||||
@LiveParam public var preLevel: Double // scale on existing buffer (default 0.0 = overwrite)
|
||||
|
||||
public let buffer: LyrebirdBuffer
|
||||
public let doneAction: DoneAction
|
||||
@@ -288,10 +288,10 @@ Free function used by `PlayBuffer` (and available to future generators like `Gra
|
||||
internal func lyrebirdBufferRead(
|
||||
_ buffer: LyrebirdBuffer,
|
||||
channel: Int,
|
||||
phase: LyrebirdFloat,
|
||||
phase: Double,
|
||||
interpolation: TableInterpolation,
|
||||
loop: Bool
|
||||
) -> LyrebirdFloat
|
||||
) -> Double
|
||||
```
|
||||
|
||||
Frame boundaries are **clamped** when `loop == false`, **wrapped modulo** `buffer.count` when `loop == true`.
|
||||
|
||||
+28
-26
@@ -39,7 +39,7 @@ condition is never violated in engine-driven usage. No heap allocation occurs in
|
||||
Input literalness is classified once at `init` time (`lhsIsLiteral`/`rhsIsLiteral`) — no
|
||||
runtime type checks on the RT thread.
|
||||
- **`Out.Control`**: `_result` pre-allocated in `init`; fills in-place and returns the pre-allocated
|
||||
buffer rather than constructing `[[LyrebirdFloat](repeating:count:)]` on every block.
|
||||
buffer rather than constructing `[[Double](repeating:count:)]` on every block.
|
||||
- **`Out.Audio`**: returns the source's own `calculatedSamples` result directly — no additional
|
||||
wrapper allocation.
|
||||
|
||||
@@ -47,15 +47,15 @@ condition is never violated in engine-driven usage. No heap allocation occurs in
|
||||
|
||||
## `ParameterNode` — Live Parameter Node
|
||||
|
||||
`ParameterNode` is an `AudioGenerator` that carries a single `LyrebirdFloat` value from
|
||||
`ParameterNode` is an `AudioGenerator` that carries a single `Double` value from
|
||||
the main thread to the RT audio thread through a lock-free `Atomic<UInt64>`. It is
|
||||
typically created implicitly via the `@LiveParam` property wrapper.
|
||||
|
||||
```swift
|
||||
// Example — your synthesizer, defined by subclassing SynthesizerBase
|
||||
final class SineTone: SynthesizerBase {
|
||||
@LiveParam var freq: LyrebirdFloat = 440.0 // $freq is a ParameterNode
|
||||
@LiveParam var amp: LyrebirdFloat = 0.2
|
||||
@LiveParam var freq: Double = 440.0 // $freq is a ParameterNode
|
||||
@LiveParam var amp: Double = 0.2
|
||||
|
||||
override func build() {
|
||||
output(bus: 0, source: OscSin.Audio(freq: $freq) * $amp)
|
||||
@@ -104,7 +104,7 @@ OscSin.Audio(freq: 440.0, interpolation: .cubic) // Catmull-Ro
|
||||
OscSin.Audio(freq: 440.0, table: engine.sharedTables.sineTable) // use engine's shared copy
|
||||
```
|
||||
|
||||
- `freq` accepts any `ValidGeneratorInput`. **Scalar inputs** (literal, String) call `floatValue` once per block. **Generator inputs** are read at audio rate — one frequency value per sample — enabling true FM synthesis with no block-rate aliasing.
|
||||
- `freq` accepts any `ValidGeneratorInput`. **Scalar inputs** (a `Double`/`Int` literal) call `floatValue` once per block. **Generator inputs** are read at audio rate — one frequency value per sample — enabling true FM synthesis with no block-rate aliasing.
|
||||
- `phase` parameter is a fraction of a full cycle [0, 1).
|
||||
- `interpolation` — `TableInterpolation` enum: `.none` (nearest), `.linear` (default), `.cubic`
|
||||
(Catmull-Rom, ~4× arithmetic cost; only audibly better than `.linear` at table sizes < 256 or
|
||||
@@ -116,7 +116,7 @@ OscSin.Audio(freq: 440.0, table: engine.sharedTables.sineTable) // use engine
|
||||
- **Power-of-two required**: `OscSin.init` enforces this with a `precondition`. Use `OscTable`
|
||||
for non-power-of-two sizes.
|
||||
- The table reference is stored as a non-Optional `let` ivar — zero ARC traffic on the RT thread.
|
||||
- State: `LyrebirdFloat` phase accumulator, advanced per sample.
|
||||
- State: `Double` phase accumulator, advanced per sample.
|
||||
|
||||
#### OscTable
|
||||
Table-lookup oscillator reading from a user-supplied `LyrebirdBuffer`. Accepts any table content
|
||||
@@ -125,7 +125,7 @@ and any size (power-of-two or not), with selectable interpolation.
|
||||
```swift
|
||||
// Custom waveform (linear interpolation, default)
|
||||
let table = LyrebirdBuffer(count: lyrebirdDefaultTableSize)
|
||||
table.fill { i, n in LyrebirdFloat(i) / LyrebirdFloat(n) * 2.0 - 1.0 } // sawtooth
|
||||
table.fill { i, n in Double(i) / Double(n) * 2.0 - 1.0 } // sawtooth
|
||||
let osc = OscTable.Audio(table: table, freq: 440.0)
|
||||
|
||||
// Cubic interpolation for a small custom table
|
||||
@@ -146,7 +146,7 @@ let osc = OscTable.Audio(table: engine.sharedTables.sineTable, freq: 440.0, phas
|
||||
fast path for power-of-two tables.
|
||||
- Checks `table.isValid` (acquiring load) each block; outputs silence if the table has been
|
||||
invalidated. The freq input generator is always evaluated — its state advances even when silent.
|
||||
- State: `LyrebirdFloat` phase accumulator, advanced per sample.
|
||||
- State: `Double` phase accumulator, advanced per sample.
|
||||
|
||||
#### VectorOscillator
|
||||
Vector-synthesis (XY) wavetable oscillator. Audio + Control variants; `GeneratorEnum` conformance. Crossfades between four mono `LyrebirdBuffer` waveforms on a 2D plane: `x` blends A↔B and C↔D, `y` blends the resulting AB↔CD pair. Linear blend on both axes; per-buffer reads use `TableInterpolation` (`.none` / `.linear` / `.cubic`).
|
||||
@@ -161,8 +161,8 @@ let d = LyrebirdBuffer(count: size); d.fillHanning()
|
||||
VectorOscillator.Audio(
|
||||
bufferA: a, bufferB: b, bufferC: c, bufferD: d,
|
||||
freq: 220.0,
|
||||
x: LFNoise2.Audio(freq: 0.4) * 0.5 + 0.5, // animated X
|
||||
y: LFNoise2.Audio(freq: 0.3) * 0.5 + 0.5 // animated Y
|
||||
x: LFCurveNoise.Audio(freq: 0.4) * 0.5 + 0.5, // animated X
|
||||
y: LFCurveNoise.Audio(freq: 0.3) * 0.5 + 0.5 // animated Y
|
||||
)
|
||||
```
|
||||
|
||||
@@ -182,7 +182,7 @@ Impulse.Audio(freq: 1.0, initPhase: 0.5) // first fire at half-period offset
|
||||
|
||||
- `freq` accepts any `ValidGeneratorInput`. **Scalar inputs** compute a constant phase increment once per block. **Generator inputs** are read at audio rate — one frequency value per sample — so the impulse spacing can be modulated at full audio precision.
|
||||
- `initPhase` is a fraction [0, 1) — `0.0` fires at sample 0 of the first block.
|
||||
- State: `LyrebirdFloat` phase accumulator.
|
||||
- State: `Double` phase accumulator.
|
||||
|
||||
#### Phasor
|
||||
Linear phase accumulator (ramp generator). Equivalent to SuperCollider `Phasor`. Accumulates `rate` units per sample within the half-open range `[start, end)`. On a ≤0 → >0 rising edge of `trig`, phase resets to `resetPos`.
|
||||
@@ -339,7 +339,7 @@ State: `x1`, `x2`, `y1`, `y2` persist across block boundaries.
|
||||
#### RBJ Filter Overview
|
||||
|
||||
All RBJ filters share the same modulation model:
|
||||
- All parameter inputs accept any `ValidGeneratorInput` (literals, Strings, Generators).
|
||||
- All parameter inputs accept any `ValidGeneratorInput` (literals, Generators, closures).
|
||||
- **Scalar inputs**: coefficients recomputed only when a parameter or `sampleRate` changes between blocks.
|
||||
- **Generator inputs**: coefficients computed at block boundaries (first and last sample) and linearly interpolated across the block — at most 6 trig/pow calls per block regardless of block size.
|
||||
- Frequencies above 0.999 × Nyquist return `BiquadCoeffs.zero` (silence).
|
||||
@@ -465,7 +465,7 @@ Envelope(levels: [0, 1, 0], duration: 1.0, curves: [0, 0])
|
||||
- `levels`: N+1 values. `durations` and `curves`: N values each (one per segment).
|
||||
- Both `durations` and `curves` are padded/trimmed to `segmentCount` in `init` — a mismatched
|
||||
array never reaches the RT thread.
|
||||
- `totalDuration: LyrebirdFloat` is pre-computed in `init` (not a `reduce` computed property).
|
||||
- `totalDuration: Double` is pre-computed in `init` (not a `reduce` computed property).
|
||||
|
||||
**Curve values** (formula per segment: `(1 − exp(curve·t/N)) / (1 − exp(curve))`):
|
||||
|
||||
@@ -824,7 +824,7 @@ Read from one or more consecutive buses. Do not modify bus memory. Channel count
|
||||
In.Audio(bus: 2) // AudioGenerator — reads audioBuses[2]
|
||||
In.Control(bus: 10) // ControlGenerator — reads controlBuses[10], interpolated ramp
|
||||
|
||||
// Multi-channel — N consecutive buses, N-channel [[LyrebirdFloat]] output
|
||||
// Multi-channel — N consecutive buses, N-channel [[Double]] output
|
||||
In.Audio(bus: 4, channels: 3) // reads audioBuses[4], [5], [6]
|
||||
In.Control(bus: 10, channels: 2) // reads controlBuses[10] and [11]; independent ramps
|
||||
|
||||
@@ -1442,10 +1442,11 @@ Single Chamberlin SVF stage with four simultaneous outputs available through the
|
||||
|
||||
```swift
|
||||
SVF.Audio(input: sig, freq: 800.0, q: 0.707) // Butterworth Q
|
||||
SVF.Audio(input: sig, freq: env, q: 4.0, mode: .bandpass)
|
||||
SVF.Audio(input: sig, freq: env, q: 4.0).bandpass // select the bandpass output
|
||||
```
|
||||
|
||||
- Modes: `.lowpass` (default), `.highpass`, `.bandpass`, `.notch`. Init-only.
|
||||
- Outputs: `.lowpass`, `.highpass`, `.bandpass`, `.notch` accessors (all four are
|
||||
computed simultaneously; pick one, or read several from the same instance).
|
||||
- `q` defaults to `svfButterworthQ` (= 0.707).
|
||||
- Audio-rate `freq` modulation supported; Chamberlin clamping ensures stability at the Nyquist limit.
|
||||
|
||||
@@ -1686,7 +1687,7 @@ Continuous random walker with low-pass smoothing. Internal xorshift64 PRNG (seed
|
||||
|
||||
```swift
|
||||
Jitter.Control(center: 1.0, speed: 5.0, amount: 0.3) // 5 Hz wobble, ±30% around 1.0
|
||||
Jitter.Audio(center: 220.0, speed: 8.0, amount: 50.0, // 50 Hz random detune
|
||||
Jitter.Control(center: 220.0, speed: 8.0, amount: 50.0, // 50 Hz random detune
|
||||
seed: 12345)
|
||||
```
|
||||
|
||||
@@ -1711,7 +1712,7 @@ Buffer-driven, oscillator-driven, FM, and input-grain synthesis. All use the sha
|
||||
Reads grains from a `LyrebirdBuffer` at sample-accurate positions.
|
||||
|
||||
```swift
|
||||
BufferGrain.Audio(
|
||||
BufferGrain(
|
||||
buffer: bufferRef,
|
||||
position: 0.5, positionSpread: 0.1,
|
||||
duration: 0.08,
|
||||
@@ -1728,14 +1729,14 @@ BufferGrain.Audio(
|
||||
Sine-window grain cloud. `freq` is the grain pitch.
|
||||
|
||||
```swift
|
||||
SineGrain.Audio(freq: 440.0, amp: 0.4, duration: 0.05, density: 100.0)
|
||||
SineGrain(freq: 440.0, amp: 0.4, duration: 0.05, density: 100.0)
|
||||
```
|
||||
|
||||
### FMGrain
|
||||
Per-grain FM synthesis. `carrierFreq` × `modFreq` × `modIndex` defines the grain's spectrum.
|
||||
|
||||
```swift
|
||||
FMGrain.Audio(carrierFreq: 880.0, modFreq: 440.0, modIndex: 2.0,
|
||||
FMGrain(carrierFreq: 880.0, modFreq: 440.0, modIndex: 2.0,
|
||||
amp: 0.3, duration: 0.1)
|
||||
```
|
||||
|
||||
@@ -1743,7 +1744,7 @@ FMGrain.Audio(carrierFreq: 880.0, modFreq: 440.0, modIndex: 2.0,
|
||||
Records live audio into a circular capture buffer, then triggers grains from arbitrary read positions. Use for "freeze" effects, stutter, micro-looping live input.
|
||||
|
||||
```swift
|
||||
InputGrain.Audio(input: micIn, position: 0.1, positionSpread: 0.4,
|
||||
InputGrain(input: micIn, position: 0.1, positionSpread: 0.4,
|
||||
duration: 0.15, density: 30.0)
|
||||
```
|
||||
|
||||
@@ -1965,7 +1966,8 @@ ScannedSynthesizer.Audio(
|
||||
centeringForce: 1.0,
|
||||
excitationIndex: 0,
|
||||
initialDisplacement: .gaussian,
|
||||
sampleRate: engine.sampleRate
|
||||
sampleRate: engine.sampleRate,
|
||||
blockSize: engine.blockSize
|
||||
)
|
||||
```
|
||||
|
||||
@@ -2030,7 +2032,7 @@ let player = try DiskIn.Audio(
|
||||
sampleRate: engine.sampleRate,
|
||||
rate: 1.0, // 1.0 = native pitch, audio-rate Generator OK
|
||||
loop: true,
|
||||
doneAction: .freeSynth, // node-tree action when EOF hit (loop=false)
|
||||
doneAction: .freeNode, // node-tree action when EOF hit (loop=false)
|
||||
bufferFrames: 8192
|
||||
)
|
||||
output(bus: 0, source: player)
|
||||
@@ -2038,7 +2040,7 @@ output(bus: 0, source: player)
|
||||
|
||||
- Reads in a background thread; RT pulls from a lock-free SPSC queue. `bufferFrames` sizes the pre-read buffer.
|
||||
- `rate` accepts Generator inputs for varispeed playback.
|
||||
- `doneAction` mirrors SC node-tree actions: `.nothing` / `.freeSynth` / `.pause` / `.releaseNode(n)`. See `Sources/Lyrebird/Generators/BufferIO/DiskInError.swift` for error cases.
|
||||
- `doneAction` sets the node-tree action on EOF: `.nothing` / `.freeNode` / `.loop`. See `Sources/Lyrebird/Generators/BufferIO/DiskInError.swift` for error cases.
|
||||
|
||||
### DiskOut.Audio
|
||||
Streams `source` audio to a file URL. Throwing init.
|
||||
@@ -2345,7 +2347,7 @@ The minimal `AmbiEncoder1` / `AmbiDecoder1` panning generators above remain in c
|
||||
Plays a `SpectralFrameBuffer` as sinusoidal partials directly (additive resynthesis, no IFFT). Reads `position` ∈ `[0, frameCount)` and interpolates between consecutive frames.
|
||||
|
||||
```swift
|
||||
let frameBuffer = SpectralFrameBuffer(fftSize: 2048, frameCount: 1024)
|
||||
let frameBuffer = SpectralFrameBuffer(fftSize: 2048, hopSize: 512, frameCount: 1024, sampleRate: 44100.0)
|
||||
// ... fill from analysis or file ...
|
||||
AdditiveSynthesizer(
|
||||
frameBuffer: frameBuffer,
|
||||
@@ -2442,7 +2444,7 @@ freeze.unfreeze() // resume live analysis
|
||||
Record a chain into a `SpectralFrameBuffer` for offline playback, or play back from one. `SpectralPlayBuffer` and `SpectralBufferRead` conform to `SpectralBufferGenerator` and drive `SpectralChain.Audio`'s synthOnly mode directly.
|
||||
|
||||
```swift
|
||||
let frames = SpectralFrameBuffer(fftSize: 2048, frameCount: 256)
|
||||
let frames = SpectralFrameBuffer(fftSize: 2048, hopSize: 512, frameCount: 256, sampleRate: 44100.0)
|
||||
|
||||
// Record into frames
|
||||
let rec = SpectralRecordBuffer(frameBuffer: frames, loop: false)
|
||||
|
||||
+22
-22
@@ -20,20 +20,20 @@ silently dropped — no allocation, no error.
|
||||
struct GrainState {
|
||||
var isActive: Bool // true while grain is playing
|
||||
// Buffer-reading (BufferGrain, InputGrain)
|
||||
var phase: LyrebirdFloat // fractional buffer frame
|
||||
var phaseInc: LyrebirdFloat // playback rate (frames/sample)
|
||||
var phase: Double // fractional buffer frame
|
||||
var phaseInc: Double // playback rate (frames/sample)
|
||||
// Common
|
||||
var remaining: Int // samples left in grain
|
||||
var amp: LyrebirdFloat // amplitude at trigger time
|
||||
var pan: LyrebirdFloat // [-1, 1]; 0 = centre
|
||||
var windowPhase: LyrebirdFloat // window table position (index units)
|
||||
var windowInc: LyrebirdFloat // window advance per sample
|
||||
var amp: Double // amplitude at trigger time
|
||||
var pan: Double // [-1, 1]; 0 = centre
|
||||
var windowPhase: Double // window table position (index units)
|
||||
var windowInc: Double // window advance per sample
|
||||
// Synthesis (SineGrain, FMGrain)
|
||||
var synthPhase: LyrebirdFloat // carrier oscillator phase (index units)
|
||||
var synthPhaseInc: LyrebirdFloat // carrier phase increment
|
||||
var modPhase: LyrebirdFloat // FM modulator phase (index units)
|
||||
var modPhaseInc: LyrebirdFloat // FM modulator increment
|
||||
var modIndex: LyrebirdFloat // FM β (modulation depth)
|
||||
var synthPhase: Double // carrier oscillator phase (index units)
|
||||
var synthPhaseInc: Double // carrier phase increment
|
||||
var modPhase: Double // FM modulator phase (index units)
|
||||
var modPhaseInc: Double // FM modulator increment
|
||||
var modIndex: Double // FM β (modulation depth)
|
||||
}
|
||||
```
|
||||
|
||||
@@ -109,8 +109,8 @@ from their `ValidGeneratorInput` sources (block-constant via fan-out cache).
|
||||
|
||||
```swift
|
||||
public final class SineGrain: AudioGenerator {
|
||||
@LiveParam public var density: LyrebirdFloat = 10.0 // grains/sec
|
||||
@LiveParam public var duration: LyrebirdFloat = 0.1 // seconds
|
||||
@LiveParam public var density: Double = 10.0 // grains/sec
|
||||
@LiveParam public var duration: Double = 0.1 // seconds
|
||||
|
||||
public init(freq: any ValidGeneratorInput = 440.0, // Hz, polled at trigger
|
||||
amp: any ValidGeneratorInput = 0.5, // amplitude, polled at trigger
|
||||
@@ -146,8 +146,8 @@ Each grain generates a windowed two-operator FM tone. All four parameters are
|
||||
|
||||
```swift
|
||||
public final class FMGrain: AudioGenerator {
|
||||
@LiveParam public var density: LyrebirdFloat = 10.0
|
||||
@LiveParam public var duration: LyrebirdFloat = 0.1
|
||||
@LiveParam public var density: Double = 10.0
|
||||
@LiveParam public var duration: Double = 0.1
|
||||
|
||||
public init(carrierFreq: any ValidGeneratorInput = 440.0, // Hz
|
||||
modFreq: any ValidGeneratorInput = 440.0, // Hz
|
||||
@@ -194,13 +194,13 @@ grains from that history.
|
||||
|
||||
```swift
|
||||
public final class InputGrain: AudioGenerator {
|
||||
@LiveParam public var density: LyrebirdFloat = 10.0
|
||||
@LiveParam public var duration: LyrebirdFloat = 0.1
|
||||
@LiveParam public var position: LyrebirdFloat = 0.0 // 0=recent, 1=oldest
|
||||
@LiveParam public var positionSpread: LyrebirdFloat = 0.0
|
||||
@LiveParam public var rate: LyrebirdFloat = 1.0
|
||||
@LiveParam public var rateSpread: LyrebirdFloat = 0.0
|
||||
@LiveParam public var amp: LyrebirdFloat = 1.0 // output scaler
|
||||
@LiveParam public var density: Double = 10.0
|
||||
@LiveParam public var duration: Double = 0.1
|
||||
@LiveParam public var position: Double = 0.0 // 0=recent, 1=oldest
|
||||
@LiveParam public var positionSpread: Double = 0.0
|
||||
@LiveParam public var rate: Double = 1.0
|
||||
@LiveParam public var rateSpread: Double = 0.0
|
||||
@LiveParam public var amp: Double = 1.0 // output scaler
|
||||
|
||||
public init(input: any ValidGeneratorInput,
|
||||
window: LyrebirdBuffer? = nil,
|
||||
|
||||
@@ -83,7 +83,7 @@ matched-shape per-channel modulation that should ride alongside the generator's
|
||||
## GeneratorArray
|
||||
|
||||
`GeneratorArray` wraps N independent generators and produces an N-channel
|
||||
`[[LyrebirdFloat]]`. It conforms to `Generator`, so it participates in the fan-out cache
|
||||
`[[Double]]`. It conforms to `Generator`, so it participates in the fan-out cache
|
||||
and can be passed anywhere a `ValidGeneratorInput` is accepted.
|
||||
|
||||
```swift
|
||||
@@ -204,7 +204,7 @@ override func build() {
|
||||
```swift
|
||||
// Example — your synthesizer, defined by subclassing SynthesizerBase
|
||||
final class StereoPanner: SynthesizerBase {
|
||||
@LiveParam var pan: LyrebirdFloat = 0.0
|
||||
@LiveParam var pan: Double = 0.0
|
||||
|
||||
override func build() {
|
||||
let osc = OscSin.Audio(freq: 440.0)
|
||||
|
||||
@@ -292,11 +292,11 @@ final class Tone: SynthesizerBase {
|
||||
|
||||
override func build() {
|
||||
let env = EnvelopeGen.Control(
|
||||
envelope: Envelope(levels: [0, 1, 0], durations: [0.01, 0.4], curves: [2, -3])
|
||||
envelope: Envelope(levels: [0, 1, 0], durations: [0.01, 0.4], curves: [2, -3]),
|
||||
doneAction: .freeNode // engine removes this synth when the envelope ends
|
||||
)
|
||||
let sig = OscSin.Audio(freq: freq) * env * amp
|
||||
output(bus: 0, source: Pan2(input: sig, pan: 0))
|
||||
doneAction = .freeEnclosing
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -84,7 +84,7 @@ lyrebird new 1stPiece # error: not a valid Swift module name
|
||||
|
||||
**Templates** — `--template <name>`:
|
||||
|
||||
- SPM-only (open `Package.swift` in Xcode): `basic` (default), `demo`, `ui-demo`, `nrt`, `score`
|
||||
- SPM-only (open `Package.swift` in Xcode): `quickstart` (fastest sound), `basic` (default), `demo`, `ui-demo`, `nrt`, `score`
|
||||
- Xcode-project (ships `.xcodeproj` + `.xcworkspace`, builds to `.app` or `.appex`): `macos-ui-xcode`, `ios-ui`, `auv3`
|
||||
|
||||
```sh
|
||||
@@ -156,7 +156,7 @@ final class BassDrum: SynthesizerBase {
|
||||
// MARK: - Parameters
|
||||
|
||||
// Declare parameters here. Example:
|
||||
// let freq: LyrebirdFloat = 440.0
|
||||
// let freq: Double = 440.0
|
||||
|
||||
// MARK: - Build
|
||||
|
||||
@@ -233,7 +233,7 @@ try engine.start()
|
||||
|
||||
// Example — your synthesizer, defined by subclassing SynthesizerBase
|
||||
final class SineTone: SynthesizerBase {
|
||||
@LiveParam var freq: LyrebirdFloat = 440.0
|
||||
@LiveParam var freq: Double = 440.0
|
||||
|
||||
override func build() {
|
||||
let osc = OscSin.Audio(freq: $freq)
|
||||
|
||||
@@ -340,7 +340,7 @@ try buf.write(to: url, format: .wav, sampleRate: 44100) // WAV, Float32
|
||||
| `.aiff` | `.aiff` | big-endian | ≤ 2 recommended | Broad DAW compatibility |
|
||||
| `.wav` | `.wav` | little-endian | up to 8 | Cross-platform standard |
|
||||
|
||||
All formats write 32-bit float samples (Float32). The `LyrebirdFloat` (Double) values in the buffer are converted to Float32 on the way out.
|
||||
All formats write 32-bit float samples (Float32). The `Double` (Double) values in the buffer are converted to Float32 on the way out.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -38,7 +38,8 @@ Swift-Package-only templates (lightweight; open `Package.swift` in Xcode for Swi
|
||||
|
||||
| Template | Command | Description |
|
||||
|---|---|---|
|
||||
| `basic` (default) | `lyrebird new MyPiece` | Minimal engine + `RunLoop.main.run()` |
|
||||
| `quickstart` | `lyrebird new MyFirstSound --template quickstart` | Fastest sound — a one-oscillator `SineTone` that plays 440 Hz for 10 s and exits |
|
||||
| `basic` (default) | `lyrebird new MyPiece` | Minimal engine + `RunLoop.main.run()` (no synth wired yet) |
|
||||
| `demo` | `lyrebird new MyPiece --template demo` | `SineTone` with `@LiveParam` frequency and amplitude |
|
||||
| `ui-demo` | `lyrebird new MyApp --template ui-demo` | AppKit window with `@UIParam` controls and `LyrebirdWindow`; adds `LyrebirdUI` to package deps |
|
||||
| `nrt` | `lyrebird new MyRender --template nrt` | `NRTDriver` renders to `output.caf` and exits — no audio hardware needed |
|
||||
@@ -234,7 +235,7 @@ final class Tone: SynthesizerBase {
|
||||
// MARK: - Parameters
|
||||
|
||||
// Declare parameters here. Example:
|
||||
// let freq: LyrebirdFloat = 440.0
|
||||
// let freq: Double = 440.0
|
||||
|
||||
// MARK: - Build
|
||||
|
||||
|
||||
@@ -75,8 +75,8 @@ try engine.start()
|
||||
|
||||
// Example — your synthesizer, defined by subclassing SynthesizerBase
|
||||
final class SineTone: SynthesizerBase {
|
||||
@LiveParam var freq: LyrebirdFloat = 440.0
|
||||
@LiveParam var amp: LyrebirdFloat = 0.3
|
||||
@LiveParam var freq: Double = 440.0
|
||||
@LiveParam var amp: Double = 0.3
|
||||
|
||||
override func build() {
|
||||
let osc = OscSin.Audio(freq: $freq)
|
||||
|
||||
@@ -197,6 +197,49 @@ ctx.remove(synth)
|
||||
ctx.remove(synth, at: sampleTime)
|
||||
```
|
||||
|
||||
### Live parameters
|
||||
|
||||
Change a running synth's `@LiveParam` from the body. Unlike the engine calls above, a `ParameterNode` write goes straight to its lock-free atomic — no main-thread hop — so it runs inline on the routine's own thread; the RT thread picks it up at the next block.
|
||||
|
||||
> `@UIParam` (`UIParamNode`) is **not** a valid target: its value is `@Observable`-tracked and main-thread-only, so it can't be written from the routine's background thread. `ctx.set` / `ctx.ramp` take a `ParameterNode`; update `@UIParam` from the main thread.
|
||||
|
||||
```swift
|
||||
ctx.set(param, to: 8.0) // step: jump to a value
|
||||
try ctx.ramp(param, to: 0.5, seconds: 3) // glide: smooth sweep over 3 s, then continue
|
||||
try ctx.ramp(param, to: 0.5, beats: 2) // same, in beats at the current tempo
|
||||
```
|
||||
|
||||
`ctx.ramp` **blocks** the body for its duration — like `wait` — and lands exactly on the target. It steps the scalar at the 10 ms poll granularity; the `ParameterNode`'s own per-block linear interpolation blends the steps into a continuous glide on the RT thread (no node source is installed, so a later `ctx.set` still takes effect immediately).
|
||||
|
||||
**`param` is the projected node, captured on the main actor first.** The synth is `@MainActor`-isolated, so its `@LiveParam` property and `$`-projection can't be reached from the background body. Capture the (`Sendable`) node once at setup, then drive it from the body — this is the idiomatic Swift-6 shape:
|
||||
|
||||
```swift
|
||||
// runDemo() / setup — @MainActor context
|
||||
let reverbSynth = GVerbTest(sampleRate: sr)
|
||||
let reverbTime = reverbSynth.$reverbTime // ParameterNode — Sendable, captured once
|
||||
|
||||
LyrebirdTask.run(engine: engine) { ctx in // @Sendable body — background thread
|
||||
ctx.add(reverbSynth)
|
||||
try ctx.wait(beats: 2)
|
||||
ctx.set(reverbTime, to: 8.0) // long tail
|
||||
try ctx.ramp(reverbTime, to: 0.5, beats: 2) // then glide down
|
||||
ctx.remove(reverbSynth)
|
||||
}
|
||||
```
|
||||
|
||||
> The background thread is the point: the body is *sequential, blocking* code — `add → wait → set → ramp → remove` reads top-to-bottom like a score — while the audio and the main thread run undisturbed. `wait`/`ramp` sleep this thread, never the RT thread.
|
||||
|
||||
**No-capture alternative.** A synth that is driven mostly from routines can skip `@LiveParam` and expose the node directly as a `nonisolated let ParameterNode`, which *is* reachable from the background with no capture — trading the plain-`Double` value sugar and the `$`-projection:
|
||||
|
||||
```swift
|
||||
@MainActor final class GVerbTest: SynthesizerBase {
|
||||
nonisolated let reverbTime = ParameterNode(3.0)
|
||||
override func build() { output(bus: 0, source: GVerb.Audio(/* … */, reverbTime: reverbTime)) }
|
||||
}
|
||||
// then, straight from the body — no capture line:
|
||||
ctx.set(reverbSynth.reverbTime, to: 8.0)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Error handling
|
||||
@@ -226,6 +269,32 @@ Uncaught `LyrebirdRoutineError.stopped` is silently swallowed by the Routine/Tas
|
||||
- Do not call `reset()` from inside the body closure.
|
||||
- Multiple routines run concurrently and independently.
|
||||
|
||||
### Actor isolation
|
||||
|
||||
The body is `@Sendable` and runs off the main thread; `SynthesizerBase` is `@MainActor`. So:
|
||||
|
||||
| To do this from a body | Use | Cost |
|
||||
|---|---|---|
|
||||
| Construct a synth | `ctx.onMain { MySynth(...) }` | Synchronous main hop — absorbed by `wait`'s drift compensation. Keep it short; needs a serviced main thread (see below). |
|
||||
| Add / schedule / remove | `ctx.add` / `ctx.schedule` / `ctx.remove` | Async hop to main (`build()` runs there) |
|
||||
| Change a parameter | `ctx.set(node, to:)` with `$param` captured on main | **None** — lock-free atomic write, inline on the body's thread |
|
||||
|
||||
Direct property writes (`synth.freq = 880`) and projected-node access (`synth.$freq`) are
|
||||
main-isolated and unavailable from a body — capture the node on main first.
|
||||
|
||||
`ctx.onMain` is what lets the *number* and *parameters* of synths depend on the body's own
|
||||
logic, instead of pre-allocating every synth outside the body and capturing it.
|
||||
|
||||
**`ctx.onMain` requires a serviced main thread.** It hops synchronously with no timeout, so it
|
||||
blocks the body forever if nothing drains the main queue. A GUI run loop services it, as does a
|
||||
caller parked on `waitUntilComplete()` / `LyrebirdTask.run` (both pump the main run loop for
|
||||
exactly this reason). The trap: `task.start(engine:)` followed by blocking main on a bare
|
||||
`Thread.sleep` or semaphore — `ctx.add` would silently queue, but `onMain` hangs.
|
||||
|
||||
Full model — what is main-bound and why, pre- vs post-publication, and why
|
||||
`SynthesizerBase.init` cannot simply be made `nonisolated` (a committed regression fixture
|
||||
enforces it) — is in `ARCHITECTURE.md` §9.2.
|
||||
|
||||
---
|
||||
|
||||
## LyrebirdClock
|
||||
|
||||
@@ -43,8 +43,8 @@ try engine.start()
|
||||
|
||||
// Example — your synthesizer, defined by subclassing SynthesizerBase
|
||||
final class KickDrum: SynthesizerBase {
|
||||
@LiveParam var freq: LyrebirdFloat = 60.0
|
||||
@LiveParam var decay: LyrebirdFloat = 0.3
|
||||
@LiveParam var freq: Double = 60.0
|
||||
@LiveParam var decay: Double = 0.3
|
||||
|
||||
override func build() {
|
||||
let osc = OscSin.Audio(freq: $freq)
|
||||
@@ -115,8 +115,8 @@ final class KickDrum: SynthesizerBase {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
@LiveParam var freq: LyrebirdFloat = 60.0
|
||||
@LiveParam var decay: LyrebirdFloat = 0.3
|
||||
@LiveParam var freq: Double = 60.0
|
||||
@LiveParam var decay: Double = 0.3
|
||||
|
||||
// MARK: - Build
|
||||
|
||||
|
||||
Reference in New Issue
Block a user