bugfixes, better MusicXML support and 1.1.0

This commit is contained in:
2026-06-10 08:41:07 -07:00
parent 6d3a0930a1
commit f59fd3b55a
228 changed files with 32271 additions and 2586 deletions
+89 -495
View File
@@ -2,7 +2,7 @@
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) 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) are archived in `docs/01-completed-working-order.md`.
## Phase Completion Checklist
@@ -161,7 +161,7 @@ Full details in `docs/01-completed-working-order.md`.
| 92 | `MoogLadder.Audio` — Huovilainen-style 4-pole resonant lowpass with per-stage `tanh` saturation, internal 2× oversampling via Phase 91 `HalfbandUpsampler2x` + `HalfbandDownsampler2x`, and SC-style half-sample feedback compensation (`xfb = x − k·(y4 − 0.5·x)`). Self-oscillates near `resonance = 1.0`, clamped to `moogLadderMaxResonance = 1.4`; cutoff coefficient capped at `0.999`. Mono Audio-only (no GeneratorEnum, no `.Control`). `cutoff`/`resonance` `ValidGeneratorInput`. tanh count optimised: 5 per oversampled sample by caching `tanh(yN)` between stages. `denormalsToZero` on every stage. New "Saturating Ladder Filters" section in `Filters.md` DocC. | 2949 |
| 93 | `ConvolutionReverb.Audio` — uniformly partitioned FFT overlap-save convolution against an `LyrebirdBuffer` IR. `partitionSize` (power of two, default 256) sets FFT size `N = 2P` and inherent latency. IR is partitioned into `ceil(ir.count / P)` blocks at init; each partition's `vDSP_fft_zrip` forward FFT is precomputed once into per-channel split-complex storage. RT path: input accumulator fills P samples, runs forward FFT into a numPartitions-slot frequency-delay line, dispatches `vDSP_zvma` complex multiply-accumulate against every IR partition spectrum (with scalar fix-up for the packed bin-0 DC/Nyquist real values), inverse FFT, scales by `1/(4N)` (forward ×2 × forward ×2 × inverse ×N), copies last P samples (overlap-save) into a per-channel output stage. `outputChannelCount` matches `ir.channelCount`; mono input is convolved separately against each IR channel. `mix`, `mul`, `add` are `ValidGeneratorInput`. All FFT/FDL/IR storage uses `UnsafeMutablePointer<Float>` allocated in `init`, freed in `deinit`. `convolutionReverbMaxPartitionSize` = 8192, `convolutionReverbMaxPartitionCount` = 16384 cap total IR length. | 2962 |
| 94 | `MIDIFile` SMF parser (formats 0 + 1, PPQ division) + `MIDIFilePlayer` clock-driven playback. Pure language-side parser in `Sources/Lyrebird/MIDI/SMF/`: `MIDIFileError` enum, `MIDIFileEvent` (beat-stamped event with `Kind` covering `.midi(MIDIMessage)` channel events + `.tempo`/`.timeSignature`/`.keySignature`/`.trackName`/`.instrumentName`/`.text`/`.copyright`/`.lyric`/`.marker`/`.cuePoint`/`.endOfTrack` meta), `MIDIFileTrack`, `MIDIFile`. Internal `SMFParser` reads MThd/MTrk chunks, decodes VLQ delta times, honours running status, surfaces meta events through `decodeMetaEvent`, silently skips SysEx / unknown meta. Tick→beat conversion at parse time (`beat = tick / ticksPerQuarter`) so result is tempo-independent. `allEvents`/`allChannelEvents`/`tempoMap`/`totalBeats` convenience views; merge across tracks is stable on `(beat, trackIndex)`. `MIDIFilePlayer` owns a `LyrebirdRoutine`, walks `allEvents` calling `ctx.wait(beats:)` between events, dispatches `.midi` to `handler`, applies `.tempo` to `clock.bpm` when `applyTempoMap == true` (else forwards), routes everything else to optional `metaHandler`. `play`/`stop`/`reset`/`state` lifecycle. Rejects format 2 + SMPTE division at parse time. | 2983 |
| 96a | `MIDIClockFollower` language-side BPM follower (`Sources/Lyrebird/MIDI/Sync/MIDIClockFollower.swift`): rolling window of last *N* tick `SampleTime`s (default 24 = quarter-note window) → inter-tick avg → `60 / (avgSec * 24)` BPM, clamped to `[minBPM, maxBPM]`, epsilon-gated push to `clock.bpm` *outside* the follower's lock to avoid lock-ordering vs `LyrebirdClock._lock`. Default `_isRunning = true` so free-running clock sources without transport messages work; `.stop` gates `_handleClock` until `.start`/`.continue` re-enables. New `MIDIMessage.continue` (0xFB) added to enum (keyword-escaped), parser, and `bytes()`. Internal `init(timeProvider:)` allows synthetic-clock test injection. Phase 96b (Ableton Link) deferred — stub at `docs/roadmap/ableton-link.md`. | 3122 |
| 96a | `MIDIClockFollower` language-side BPM follower (`Sources/Lyrebird/MIDI/Sync/MIDIClockFollower.swift`): rolling window of last *N* tick `SampleTime`s (default 24 = quarter-note window) → inter-tick avg → `60 / (avgSec * 24)` BPM, clamped to `[minBPM, maxBPM]`, epsilon-gated push to `clock.bpm` *outside* the follower's lock to avoid lock-ordering vs `LyrebirdClock._lock`. Default `_isRunning = true` so free-running clock sources without transport messages work; `.stop` gates `_handleClock` until `.start`/`.continue` re-enables. New `MIDIMessage.continue` (0xFB) added to enum (keyword-escaped), parser, and `bytes()`. Internal `init(timeProvider:)` allows synthetic-clock test injection. Phase 96b (Ableton Link) not planned. | 3122 |
| 95 | `ScannedSynthesizer.Audio` — Mathews/Verplank 2000 1D mass-spring scanned synthesis. Power-of-two ring of N masses (default 64, max 1024). Per audio block: two-pass Jacobi explicit-Euler update — pass 1 fills `_accelerations[]` from old positions/velocities (avoiding in-place Gauss-Seidel asymmetry), pass 2 integrates `v += a·dt` and `x += v·dt`. Per-mass: discrete 1D Laplacian × stiffness − damping·v − centeringForce·x + excitationForce[i]. Excitation injected at single configurable mass index, sampled once per block via `lastGeneratorSampleOrFloat`. Per-sample audio-rate phasor scans `_positions[]` as a wavetable through `oscillatorTableRead` (none/linear/cubic). New `[Double]` overloads of `oscillatorTableRead*` helpers added in `OscillatorTableReadHelpers.swift`. New `ScannedSynthesizerShape` enum (`.gaussian`/`.sine`/`.impulse`/`.zeros`) for init-time displacement preset. Audio-only, no `.Control`, no `GeneratorEnum`. New DocC topic `Generators/ScannedSynthesis.md`. | 3138 |
| 97 | `MuTronIII` — envelope-controlled resonant filter (Audio + Control) modelling the Musitronics Mu-Tron III (1972) auto-wah. Topology: full-wave rectify × `sensitivity` → asymmetric one-pole envelope follower (inlined, not composed) → exponential cutoff sweep `freqLo·pow(freqHi/freqLo, env)` → inlined Chamberlin SVF (selectable `MuTronIIIMode` `.lowpass`/`.bandpass`/`.highpass` and `MuTronIIISweep` `.up`/`.down` — both `let` constants set at init). Mono output. Guards: `_inputIsGenerator` classification + scalar fast path (avoids `Double.calculatedSamples` heap alloc), sensitivity clamped ≥ 0, `freqLo`/`freqHi` clamped to `[0.001, Nyquist]` with monotone ratio, peak floor `1.0` (Chamberlin stability `q1 + f < 2` at `f → 1.0` from Nyquist sweep), denormals zeroed on `_prevAmp` + `_svfLow` + `_svfBand`. `Control` uses standard `calculatedSamples` bypass for once-per-block IIR state advancement; output `fillRampedResult` from previous to current target. New types: `MuTronIIIMode`, `MuTronIIISweep`. 24 tests including deterministic Chamberlin sample 0/1 verification at `1e-12`. | 3162 |
| 102a | Ambisonic Toolkit (FOA extra encoders) — `FoaEncodeOmni` (omni: W=input, X=Y=Z=0; full amplitude on W vs FoaPanB's plane-wave 1/√2 convention) + `FoaEncodeStereo` (left, right, angle) summing two opposing FoaPanB encodes at ±angle. Static `angle: Double` arg; coefficients (`foaRsqrt2`, `cos(angle)`, `sin(angle)`) pre-computed at init. Direct `GeneratorBase, AudioGenerator` finals with 4-row output. lyrebird_review clean on first pass. 28 new tests. | 3595 |
@@ -218,504 +218,98 @@ Full details in `docs/01-completed-working-order.md`.
| 196 | Engine Ownership + Lifecycle Safety — set-once atomic binding (`SynthesizerBase._engineBinding: Atomic<UInt>` storing engine pointer bit pattern, two-pass CAS-loop with stale-pointer recovery via `EngineLifecycleCoordinator` registry lookup), opt-in two-tier binding on `LyrebirdBuffer` (exclusive CAS + saturated-subtract read-only refcount); new `engine.identifier: UUID`; new internal `EngineLifecycleCoordinator` singleton holding weak refs keyed by UUID under `NSLock` (lifecycle-lock site around `start`/`stop` deferred to Phase 197 host scope); new public `EngineAddError` enum (`boundToOtherEngine(current:prior: UUID?)`, `doubleAdd`, `pendingQueueFull`, `rebuildFailed` reserved); new internal typed `RetainQueue<T>` centralising the 8 RT-side `Unmanaged.passRetained` enqueue sites in `applyEvent`. Breaking pre-ship: `engine.add(_:)` / `add(_:position:)` / `schedule(_:at:)` / `schedule(_:after:)` Bool → throws, mechanical sweep of ~357 call sites across `Sources/`, `Tests/`, `Demos/`; `LyrebirdEventList.addPreMaster` / `addPostMaster` also throws. Partial-state rollback in `LyrebirdEventList._firstEventSetup` and `VoicePool.init` (committed-array + reverse-`engine.remove` on throw; instance-state writes deferred until full success). New `Tests/LyrebirdTests/MultiEngineRegressionTests.swift` (8 tests) covers two-engines-two-threads-1000-segments, cross-engine + double-add throws, remove + re-add, stale-pointer recovery (with documented address-reuse known limit and skip path), buffer read-only share, buffer exclusive blocks cross-engine, buffer unbind saturation. Docs: `synthesis-engine.md` gains Engine Identity + Ownership Binding sections; `multi-core.md` gains Object Ownership Rules subsection with canonical cross-engine wavetable share pattern; `CLAUDE.md` Interface Conventions gains `engine.add` throws entry. Review skills updated to `swift test --no-parallel` (canonical command per memory). Four `/lyrebird_review` cycles (3 with substantive fixes, 4th clean). 15 commits on `phase-196`. | ~4180 |
| 197 | `EngineHost` Multi-Engine Facade — creation-owning `public final class EngineHost` (NSLock-protected role→engine + UUID→role maps); `public enum EngineHostRole` (`.nrtRender`, `.rtOutput(deviceID:)`, `.auxiliary`, `.custom`) — `.rtOutput` device-exclusivity enforced by role-Hashable identity, no separate `_claimedDevices` set; `public enum EngineHostError`; `public struct SynthesisEngineConfig` value carrier (not Sendable — driver field). APIs: `makeEngine(role:config:) throws`, `engine(for:)`/`role(for:)`/`engines`/`roles`/`engineCount` (lookup), `startAll() throws` / `stopAll()` (snapshot-and-iterate-unlocked with rollback on partial-start failure — failing engine captured inside loop's catch, no fragile re-iteration-by-elimination), `adopt(existing:role:) throws` (verifies engine in EngineLifecycleCoordinator). NRT batch render pool: `renderConcurrent(jobs:maxConcurrent:) -> AsyncThrowingStream<NRTResult, Error>` using `withThrowingTaskGroup` + `addTaskUnlessCancelled` seed-and-refill; pool engines inline (not host-registered); `defer { engine.stop() }` post-render; monotonic `DispatchTime` elapsed measurement. New `public struct NRTJob: Sendable` + `public struct NRTResult: Sendable`. **Lock-nesting safety**: host releases `_lock` before touching `EngineLifecycleCoordinator` (which has its own NSLock) — pre-validate under host lock, release, construct/query coordinator outside, re-acquire for commit with second validation. Closes the latent host→coordinator deadlock window. New 220-line `docs/engine/multi-engine-host.md`; `multi-core.md` "See also" updated; `CLAUDE.md` doc-map gains row. New `EngineHostTests.swift` (15 tests) + `MultiEngineRegressionTests.twoEnginesViaHostUniformityContract` proving host path produces identical observable behaviour to direct-ctor. **Five `/lyrebird_review` cycles** (passes 1-4 substantive fixes, pass 5 clean): lock-nesting, snapshot-and-iterate-unlocked, NRTJob numInputChannels silent-discard, magic 44100, false @MainActor doc, missing defer on pre-check (`.duplicateRole` would leak lock causing instance-wide deadlock), stale class-level + role + adopt + multi-engine-host.md docs on `.duplicateDevice` semantics, magic 1_000_000_000.0 literal, `addTaskUnlessCancelled` refill bug, cancellation doc accuracy, NRTJob.numInputChannels doc contradiction, doc-comment merging bug (class Quick Help mis-attributed to file-scope const). 9 commits on `phase-197`. | ~4204 |
| 198 | Host Footgun Cleanup — discharges the eleven non-blocking findings (F1–F11) captured in POST_197_FIXES.md after the five-cycle phase-197 review. **F1 code fix**: `EngineHost.renderConcurrent` outer catch distinguishes caller-initiated cancel from a user `build` closure deliberately throwing `CancellationError` via `Task.isCancelled` guard — caller break ends stream cleanly; build-thrown surfaces as stream throw. Two regression tests cover both paths. **F2–F7 docs**: new "Caveats and footguns" section in `docs/engine/multi-engine-host.md` covering NRT pool memory cost (per-engine working-set table, mobile cap recommendation), in-flight files written after cancel (caller-side `Set<URL>` cleanup pattern), cross-job synth-instance sharing (WRONG vs RIGHT examples), cooperative pool starvation (user-side cap; host-side `DispatchQueue` redesign deferred to Phase 199+), `adopt` TOCTOU benign via ARC takeover. **F6 role doc**: `EngineHostRole.swift` `.rtOutput(deviceID:)` rewrote for macOS/iOS asymmetry — iOS deviceID is host-bookkeeping only because RemoteIO doesn't address devices. **F8 source-break**: dropped `.duplicateDevice(UInt32)` case from `EngineHostError` — had no producer (`.rtOutput` Hashable role discriminates by deviceID directly) and forced consumer switches to handle dead code. **F11 code comment**: `// TODO(phase-future, F11)` at `SynthesisEngine.init` call in `makeEngine` documenting non-throwing-init dependency. **Cleanup**: deleted `POST_197_FIXES.md`. F9 + F10 skipped after evaluation. **Two `/lyrebird_review` cycles** — pass 1 found one blocking (CancellationError-from-`build`-vs-caller-cancel ambiguity), pass 2 clean (review-agent no blocking; caveman LGTM on arch + 3 nits applied: rethrow caught CancellationError instance, `>= 1` result count robustness, `onTermination` fires-on-finished comment). 5 commits on `phase-198`. | ~4205 |
| 204 | Score / MusicXML demo + CLI templates — `Demos/LyrebirdScoreDemo/` NRT-render demo + `ProjectTemplate.score` + `LyrebirdScore.xctemplate`, all driven by the existing Score DSL + MusicXML round-trip (no new core API). | 4214 |
| 222 | `LyrebirdPaths` filesystem conveniences — `projectRoot(from:marker:)` (source-anchored via default-arg `#filePath`, extension-marker match) + sandbox-standard dir accessors; score template writes output via it. | 4516 |
| 223 | `Generate` / `PatternNotes` algorithmic score generators — index-driven + `Pattern`-driven `[ScoreElement]` helpers (no new result-builder type); demo/template/docc examples. | 4526 |
| 224 | `TimeSignature` + `MeterMap` model — `beatGrouping` primitive (compound/simple/additive), segmented meter map + anacrusis; `Score.meterMap` + `Part.meterMap?` polymeter override. Model-only foundation for the beat-timeline group. | 4544 |
| 225 | `ScoreTimeline.fill` + shared `fillRests` — place elements at 0-based quarter beats, auto-fill rests, throw on overlap. Generic helper dedups all three gap-fill sites (Timeline/parser Fraction, MIDI Double); `Fraction: AdditiveArithmetic`. | 4558 |
| 226 | `BeatPosition` musical addressing — `.quarters`/`.beat`/`.bar(_:beat:)`/`.bar(_:division:)` resolved to absolute quarters via `MeterMap`; `beat` = felt/conducted pulse (consistent across 4/4, compound 6/8, additive 3+3+2). Anacrusis + mid-piece meter accumulation; meter-layer naming aligned (`pulse*`→`beat*`, `beatUnitQuarters`→`divisionQuarters`). | 4579 |
| 227 | `ScoreTimeline` overlap policies (`.trap`/`.truncatePrevious`) + multi-voice (`fillVoices` explicit, `fillAutoVoiced` greedy distribution). Double + BeatPosition overloads; `ScoreTimelineError.invalidVoice`. | 4586 |
| 228 | Mid-piece meter-change notation (encoder) — `Score+MusicXMLEncode` consumes `meterMap`: `<time>` on change, per-measure capacity in both loops, `measureCount(atoms:meterMap:)`. Constant-meter byte-identical. Encoder-only (round-trip/anacrusis → 228b). | 4595 |
| 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 |
---
## Upcoming Phases
Phases ordered by dependency and value/effort. Each phase needs tests before moving on.
### Phase 201 — Swift 6 main-actor isolation for `Synthesizer` (zero-annotation consumer subclassing)
**Goal.** A consumer building under Xcode 26's default
`SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor` must be able to subclass
`SynthesizerBase` with **no concurrency annotations**:
```swift
import LyrebirdSynth
final class ToneSynth: SynthesizerBase { // no nonisolated, no @preconcurrency
@UIParam var freq: Double = 440
override func build() {
output(bus: 0, source: OscSin.Audio(freq: $freq) * 0.2)
}
}
```
This must hold for the **core package, Quartet (local-path reference), and Test
(remote gitea reference)** simultaneously — those three are the acceptance gate.
**Problem (reproduced).** Core compiles in Swift 5 language mode, so
`SynthesizerBase.build()` / `init()` are *nonisolated*. A consumer whose project
defaults to `@MainActor` makes its subclass's `build()`/`init()` main-actor
isolated → **"main actor-isolated method has different actor isolation from
nonisolated overridden declaration."** Today's only workarounds live on the
consumer (`nonisolated override func build()`, `@preconcurrency`,
`nonisolated override init()`) — exactly what we will not ship. Verified: no
core annotation that keeps `build` nonisolated fixes it (the consumer's own
default-isolation governs its own override declaration). The fix is to make the
*language-side* surface of `Synthesizer` **main-actor isolated** so the
consumer's MainActor default *matches* instead of conflicts, while the single
RT entry point (`evaluate`) stays `nonisolated`.
**Isolation split — the core design.** `Synthesizer` has exactly one RT-thread
entry point; everything else is language-side (main thread):
| Member | Thread | Phase 201 isolation |
|---|---|---|
| `build()` | main (called once at add) | `@MainActor` |
| `release(engine:)` | main only (doc-stated) | `@MainActor` |
| `free(engine:)` | main only (doc-stated) | `@MainActor` |
| `evaluate(graph:count:)` | **RT render thread** | **`nonisolated`** |
| `@LiveParam` / `@UIParam` setters | main / atomic store | inherit main; atomic store is already cross-thread-safe |
`evaluate()` reads only two members: `parameterTable` (immutable `let`) and
`outputGenerators` (`var`, written in `build()` on main, read on RT after the
add-event barrier). Both are touched cross-thread **safely today** via the
engine's existing scheduling contract (the add event is applied on the RT thread
only after `build()` has fully returned on main — a happens-before edge through
the SPSC `pendingQueue`). Phase 201 makes that contract explicit to the compiler
with `nonisolated(unsafe)` on exactly those two stored properties, with a
comment citing the barrier. No new runtime synchronisation is added — the safety
argument is the one already in `ARCHITECTURE.md` §2/§9.
**Plan of work.**
1. **Protocol (`Synthesizer.swift`).** Annotate the protocol so language-side
requirements are `@MainActor` and `evaluate` is `nonisolated`. Options to
evaluate during implementation (pick whichever the compiler accepts most
cleanly): `@MainActor protocol Synthesizer` with `nonisolated func
evaluate(...)`, vs. per-requirement isolation. Update the default-extension
implementations (`evaluate` no-op, `release` throws, `free`) to match.
2. **`SynthesizerBase.swift`.** Mark the class `@MainActor`. Mark
`evaluate(graph:count:)` `nonisolated final`. Mark `parameterTable` and
`outputGenerators` `nonisolated(unsafe)` (the only state `evaluate` reads),
each with a `// RT-read after add-barrier; see ARCHITECTURE.md §9` comment.
Confirm `@LiveParam`/`@UIParam` wrapper-backed properties still compile (the
earlier whole-class-`nonisolated` experiment failed *because* wrappers reject
`nonisolated`; `@MainActor` does not have that problem — verify).
3. **`Group` / `ParallelGroup` (`NodeTree/`).** Both conform to `Synthesizer`
and call `evaluate` on the RT thread. Apply the same split: `build`/`release`/
`free` main-actor, `evaluate` `nonisolated`. `ParallelGroup.evaluate` uses
`concurrentPerform` over children — confirm the child `evaluate` calls remain
`nonisolated` end-to-end (no hop).
4. **Engine call sites.** `SynthesisEngine.processBlock` → `rootGroup.evaluate`
runs on the RT thread and must reach `evaluate` with no actor hop. Verify the
whole RT call chain (`processBlock` → `Group.evaluate` →
`synth.evaluate` → `Generator.calculatedSamples`) is `nonisolated`. The
engine itself is not an actor; ensure nothing forces a `MainActor.assumeIsolated`
or `await` onto the RT path (that would be a correctness/perf regression — a
hard fail for this phase).
5. **Other in-core conformers.** Audit the conformers that implement
`Synthesizer` directly rather than via `SynthesizerBase` (e.g. `VoicePool`,
AUv3 `LyrebirdAudioUnit` / `LyrebirdAUVoicePoolBinding`, any others surfaced
by `grep ": Synthesizer"`). Each needs the same `evaluate`-nonisolated split.
AUv3 is the riskiest (its render block is already a separate isolation
domain) — give it explicit attention.
6. **Language-mode decision.** Determine whether the core `LyrebirdSynth` target
should move to `.swiftLanguageMode(.v6)` (so the isolation is baked into the
module's binary interface and propagates to consumers regardless of their
mode) or stay `.v5` with explicit annotations. Prefer keeping `.v5` if
explicit `@MainActor`/`nonisolated` annotations suffice — a full v6 migration
of the whole module is a much larger lift and out of scope unless required to
make the consumer experience clean. **Spike this first** — it determines the
size of the rest of the phase.
7. **`LyrebirdUI`.** Currently `.v5` to dodge SwiftUI/AppKit actor diagnostics.
`@UIParam` lives here. Confirm the isolation split doesn't force a `.v6`
migration of `LyrebirdUI`; if `@UIParam`-bearing synths need anything, capture
it.
**Acceptance criteria (all three must pass with NO consumer-side concurrency
annotations):**
- **Core:** `swift test --no-parallel` green; `(cd LiveCompile && swift test
--no-parallel)` 34/34. RT path verified to have no actor hop (inspect, and
confirm no perf regression on the core synthesis benchmark).
- **Quartet** (local-path ref): builds + runs; its `SynthesizerBase` subclasses
carry no `nonisolated`/`@preconcurrency`. Remove any such annotations Quartet
currently has and confirm it still builds.
- **Test** (remote gitea ref, Xcode-26 `MainActor` default): the plain
`final class ToneSynth: SynthesizerBase { override func build() {…} }` builds
and runs with zero annotations. Revert the `@preconcurrency` /
`nonisolated override init` / `nonisolated override func build` that
Claude-in-Xcode added.
- A **regression fixture**: an SPM consumer target built with
`-default-isolation MainActor` + `.swiftLanguageMode(.v6)` (the repro from
the Phase-201 investigation) compiles an unannotated `SynthesizerBase`
subclass. Keep this as a committed smoke test so the guarantee doesn't silently
regress.
**Risks / watch-items.**
- `nonisolated(unsafe)` is a promise to the compiler — the `/lyrebird_review`
RT-safety pass must explicitly bless the two properties it lands on, citing the
add-barrier. Do not broaden it beyond `parameterTable` + `outputGenerators`
without re-justifying.
- If the protocol-level `@MainActor` forces awaits onto any existing internal
call site that currently runs sync on a background queue (routines, NRT batch),
that's in-scope to fix — those are language-side and can be `@MainActor` or
explicitly hopped, but must not touch the RT path.
- Docs: once landed, update `GettingStarted.md` / `INSTALLATION_AND_USAGE.md` to
show the clean zero-annotation subclass as *the* pattern, and drop the
interim "use `nonisolated final class`" guidance if it was added.
**Branch:** `phase-201-mainactor-isolation` off `main`. Standard phase
checklist + `/lyrebird_review` before merge. After merge, re-snapshot to gitea
and re-tag (the gitea 1.0.0 is unreleased, so it can absorb this).
**Investigation notes (from the session that wrote this plan — don't re-run these).**
*Exact failure (reproduced).* Consumer error under Xcode 26 MainActor default:
```
error: main actor-isolated instance method 'build()' has different actor isolation
from nonisolated overridden declaration
error: main actor-isolated initializer 'init()' has different actor isolation
from nonisolated overridden declaration
```
Source: `SynthesizerBase.build()` / `init()` are nonisolated (core is Swift 5
mode); consumer's project default makes the *subclass's* override `@MainActor`;
override-vs-base isolation mismatch.
*Reproduction recipe (use verbatim as the Phase 201 regression fixture).* A
throwaway SPM consumer at `/tmp`, depending on the package via local path:
```swift
// Package.swift target settings that reproduce Xcode 26's new-project default:
swiftSettings: [
.swiftLanguageMode(.v6),
.unsafeFlags(["-default-isolation", "MainActor"]),
]
```
```swift
// Sources/App/main.swift — the unannotated subclass that MUST compile post-201:
import LyrebirdSynth
final class ToneSynth: SynthesizerBase {
override func build() { output(bus: 0, source: OscSin.Audio(freq: 440) * 0.2) }
}
let s = ToneSynth(); print("ok \(s)")
```
Note: `.defaultIsolation(MainActor.self)` in the manifest is **unavailable** in
this SwiftPM toolchain (`error: 'defaultIsolation' is unavailable`) — must use
the raw `-default-isolation MainActor` unsafeFlag as above.
*Approaches already tried and RULED OUT (don't repeat):*
1. `nonisolated` on base `init()` + `build()` — **fails.** Consumer's override
still gets `@MainActor` from its own project default; mismatch persists. (The
error even confirms the base is "nonisolated" — proving the problem is the
consumer side, not the base.)
2. `nonisolated` on the **class** declaration (`open nonisolated class
SynthesizerBase`) — **fails to compile core**: `'nonisolated' is not
supported on properties with property wrappers` (the `@LiveParam`/`@UIParam`
stored properties). Whole-class `nonisolated` is a dead end.
3. `nonisolated` on the **protocol requirement** (`Synthesizer.build`) + base —
**fails the same way** as (1).
4. `@MainActor` on the class + `nonisolated final func evaluate(...)` — **right
direction, but surfaced the real work**: 9 errors, all from `evaluate()`
reading `parameterTable` and `outputGenerators` from a nonisolated context
while the class is MainActor (`#ConformanceIsolation` + "main actor-isolated
property can not be referenced from a nonisolated context"). This is exactly
why the plan lands `nonisolated(unsafe)` on those **two** properties — they
are the entire RT-read surface of `evaluate()`. Nothing else in the class is
read on the RT thread.
*Verified-working interim (NOT what we ship, but proves the seam):* the consumer
single-annotation form `nonisolated final class ToneSynth: SynthesizerBase { … }`
compiles cleanly (`Build complete`). Confirms one annotation on the *type* is
enough — Phase 201's job is to move that necessity into the core so the consumer
needs zero.
*RT-read surface (confirmed by reading `evaluate()`):* `evaluate(graph:count:)`
references exactly `parameterTable` (immutable `let`) and `outputGenerators`
(`var`, written in `build()` on main, read on RT). No other stored property is
touched on the RT thread. The `nonisolated(unsafe)` blast radius is precisely
these two.
### Phase 104 — AUv3 Plugin Export
Ship a `SynthesizerBase` subclass as an AudioUnit v3 (.appex) plugin loadable
by Logic, GarageBand, Ableton (AUv3-wrapped via Bridge), Loopy Pro, AUM,
and other AUv3 hosts on macOS and iOS. Closes a major distribution gap: today
Lyrebird synths can only run inside a Lyrebird app. After 104 they can ship
as drop-in instruments / effects in any DAW.
**Background.** AUv3 is Apple's modern Audio Unit format — sandboxed app-
extensions hosted in the DAW's process via a remote-audio-unit interface.
Required for iOS plugin distribution (AUv2 doesn't exist on iOS). Replaces
AUv2 on macOS (still allowed but discouraged for new development). Lyrebird
currently uses the AudioUnit *consumer* C API in `CoreAudioDriver` /
`iOSAudioDriver` to pull samples from hardware — Phase 104 inverts the
relationship: Lyrebird becomes an AudioUnit *producer* that hosts pull from.
**Phase split.** This is a large lift. Split into three sub-phases that can
ship independently:
| Sub-phase | Scope | Status |
|-----------|-------|--------|
| 104a | Wrapper infrastructure: `AUv3Driver`, `LyrebirdAudioUnit` (`AUAudioUnit` subclass), parameter-tree mapping, buffer adapter, ring-buffer block-size adapter. Pure Swift, in `Sources/Lyrebird/`. Headless — no Xcode artefact yet. | ✓ shipped — see `docs/01-completed-working-order.md` |
| 104b | Example Xcode AUv3 project under `Demos/LyrebirdAUv3Demo/` with host app shell + extension target; `auval` validation; ships one example synth ("LyrebirdFM") as a working AUv3 instrument. | ✓ shipped — see `docs/01-completed-working-order.md` |
| 104c | MIDI render block (kAudioUnitType_MusicDevice — note on/off → Lyrebird voice pool), advanced parameter ramping (AUAudioUnit's per-sample parameter automation), preset save/restore, view controller (minimal SwiftUI). | ✓ shipped — see `docs/01-completed-working-order.md` |
All three Phase 104 sub-phases are now shipped. See
`docs/01-completed-working-order.md` for the writeups.
---
### Phase 113 — Pan4 family refactor (`PanAz`, `PanAzDistance`, `PanXY`, `PanXYDistance`)
✓ shipped — see `docs/01-completed-working-order.md` for the full writeup.
Reshapes the 4-speaker panning family around an `open class Pan4` base that
holds the shared infrastructure (4-row output buffer, `_mulAdd`,
`outputChannelCount = 4`, named channel aliases). Four concrete subclasses
provide the user-facing generators with two coordinate systems (polar /
cartesian) crossed with two distance modes (none / full SpatialDistance-style
shaping).
**Why now.** The original Phase 113 work (planned as PanXY + PanXYDistance
only) duplicated the 4-corner equal-power gain math against the existing
`Pan4`. Mid-phase the scope expanded to:
1. Drop elevation from `Pan4` — the original "elevation" parameter was just
a second planar axis, not real elevation, and made the API ambiguous.
2. Give the family a polar interface (`PanAz` / `PanAzDistance`) alongside
the cartesian one for sound-positioning workflows that think in
`(angle, radius)` instead of `(x, y)`.
3. Single-source the equal-power gain math so all four subclasses share one
implementation.
**Design.**
| Subclass | Coordinates | Distance modelling |
|----------|-------------|--------------------|
| `PanAz` | polar — `@LiveParam azimuth: Double` (radians) | none (position fixed to unit-square boundary) |
| `PanAzDistance` | polar — `azimuth` + `distance` + `velocity` (all `any ValidGeneratorInput`) | 1/d amp + air-absorption LP + Doppler past `\|distance\| = 1` |
| `PanXY` | cartesian — `@LiveParam x`, `@LiveParam y` ∈ `[-1, 1]` | none |
| `PanXYDistance` | cartesian — `x`, `y` + `velocity` (all `any ValidGeneratorInput`) | Chebyshev metric: 1/d amp + air-absorption LP + Doppler past `max(\|x\|, \|y\|) = 1` |
Shared module-internal helpers (`Sources/Lyrebird/Generators/Panning/Pan4Helpers.swift`):
- `azimuthToSquareBoundary(_ az: Double) -> (x, y)` — projects azimuth
radians onto the unit-square boundary via `1 / max(|sin|, |cos|)` scaling
so the trajectory hits speaker corners at `±π/4` and `±3π/4` (rather than
the inscribed unit circle, which would leave corners unreachable from
azimuth alone).
- `writeEqualPowerSquarePanSample(into:sampleIndex:source:x:y:)` — clamps
`(x, y)` to `[-1, 1]²`, computes the standard four-corner equal-power
gains via `(±+1)·π/4` angles, and writes `source × gain` into the four
`_result` rows at the given index. Power invariant
`LF² + RF² + RR² + LR² = 1` for any clamped position.
Both helpers `@inline(__always) internal`; call cost vanishes after the
optimiser. NaN / subnormal-cancellation guards in
`azimuthToSquareBoundary` collapse degenerate inputs to `(0, 0)`.
Distance shaping (`PanAzDistance` + `PanXYDistance`) reuses the
`SpatialDistanceConstants.swift` module-internal constants
(`spatialDistanceMinReadRate`, `spatialDistanceMaxReadRate`,
`spatialDistanceInitialDelaySamples`, `spatialDistanceMinDelaySamples`,
`spatialDistanceMinCutoffHz`, `spatialDistanceMaxCutoffFraction`,
`spatialDistanceTwoPi`) — promoted out of `SpatialDistance.swift` so the
distance generators share one source of truth. The amplitude / LP /
Doppler pipeline applies to the mono signal **once** before panning
(single one-pole LP + single variable-rate delay line) to avoid
per-channel phase decorrelation artifacts; distance from the listener is
a single scalar.
**Migration / breaking changes.**
- Old `Pan4(input:).azimuth` / `.elevation` (each `@LiveParam` in
`[-1, 1]`) API is removed. The azimuth-only behaviour now lives in
`PanAz` with proper radian semantics (`0` = front centre,
`±π/4` / `±3π/4` for corners, wraps modulo `2π`).
- `Pan4` itself is no longer instantiable as a useful generator — it is
the open base class. Bare `Pan4(mul:add:)` produces a silent zero-fill
output. The doc comment warns against this.
- All existing tests using the old `Pan4` API (`PanningTests.swift` Pan4
suite, `Pan4ParameterRampingTests.swift`, the `Pan4` alias section of
`ChannelSelectTests.swift`) migrated to `PanAz` with corresponding
radian-based corner / edge expectations.
**Files changed.**
New:
- `Sources/Lyrebird/Generators/Panning/Pan4Helpers.swift`
- `Sources/Lyrebird/Generators/Panning/PanAz.swift`
- `Sources/Lyrebird/Generators/Panning/PanAzDistance.swift`
- `Sources/Lyrebird/Generators/Panning/PanXY.swift` (initial Phase 113 pass; refactored to subclass `Pan4`)
- `Sources/Lyrebird/Generators/Panning/PanXYDistance.swift` (initial Phase 113 pass; refactored to subclass `Pan4`)
- `Sources/Lyrebird/Generators/Modulation/SpatialDistanceConstants.swift`
- `Tests/LyrebirdTests/PanXYTests.swift`
- `Tests/LyrebirdTests/PanXYParameterRampingTests.swift`
- `Tests/LyrebirdTests/PanXYDistanceTests.swift`
- `Tests/LyrebirdTests/PanAzDistanceTests.swift`
Modified:
- `Sources/Lyrebird/Generators/Panning/Pan4.swift` (leaf class → `open` base)
- `Sources/Lyrebird/Generators/Modulation/SpatialDistance.swift` (constants extracted)
- `Tests/LyrebirdTests/PanningTests.swift` (Pan4 suite rewritten as PanAz)
- `Tests/LyrebirdTests/ChannelSelectTests.swift` (Pan4 alias → PanAz)
- `Tests/LyrebirdTests/PanAzParameterRampingTests.swift` (renamed from `Pan4ParameterRampingTests.swift` via `git mv`)
- `docs/stdlib/generators.md`, `docs/stdlib/multichannel.md`,
`Sources/Lyrebird/Lyrebird.docc/Generators/MultiChannel.md`
**Verification.**
- `swift build` clean.
- `swift test --filter PanAz --filter PanXY` — 58 tests across 6 suites.
- `swift test` — 3544 tests in 409 suites pass.
- `lyrebird_review_agent` two review cycles. First (initial PanXY /
PanXYDistance work with the old leaf Pan4 still on the elevation API)
caught four blocking findings: dead `_referenceDistance` stored property,
dead `_sampleRate` stored property, two `@Suite` in one file, and
`try? outsideEng.start()` swallowing a second-engine start failure. All
resolved before re-review. The Pan4-family refactor (this entry) passed
clean on the first sweep — vtable dispatch through the `AudioGenerator`
protocol witness verified correct for `_computeSamples` overrides;
`is any Generator` classification confined to `init`; helper inlining
clean; channel-alias inheritance through `extension Pan4` correctly
propagates to every subclass.
---
### Phases 142–147 — Live-compile scratch view (`LyrebirdScratchView` + `LyrebirdScratchDemo`)
Live-coding path for Lyrebird via dylib hot-swap. Replaces the dead
`swift package repl` (removed from current Swift toolchain). User writes a
Swift snippet in a `NSTextView`-backed editor, ⌘↩ shells out to `swiftc
-emit-library`, the resulting dylib is `dlopen`'d and its entry symbol
called with a pointer to the live `SynthesisEngine`. macOS-only v1 (iOS
can't shell out to swiftc).
**Why renumbered.** Originally scoped as phases 135–140 in
`memory/project_live_compile_phases.md` (planned 2026-05-12). Phases
135–141 got consumed by unrelated drive-by work (SC reference scrub,
DocC build instructions, Xcode-project scaffolder templates, denormal-
flush macro, NoteController template, Sendable-warning cleanup) before
the scratch-view work started. Renumbered here to 142–147 — same scope,
same naming, same split.
**Naming locked.**
- SwiftUI view: `LyrebirdScratchView` (lives in `Sources/LyrebirdUI/LiveCompile/`).
- Sample app: `LyrebirdScratchDemo` (under `Demos/LyrebirdScratchDemo/`).
- New SPM target: `LyrebirdLiveCompile` (`Sources/LyrebirdLiveCompile/`)
— keeps swiftc shell-out + `dlopen` surface out of the core RT
`Lyrebird` module.
- Snippet entry symbol: `lyrebird_snippet_entry` (`@_cdecl`).
**Why not the alternatives** (don't re-litigate):
- `swift package repl` — removed from current Swift toolchain.
- Xcode Playgrounds — user tested; audio did not work.
- Embedded Swift interpreter — no such thing; SwiftSyntax parses but
does not execute.
**Phase split** (each on its own branch off `main` per the standard
phase-branch workflow):
| Sub-phase | Scope |
|-----------|-------|
| 142 ✓ | `LiveCompiler` core: `swiftc -emit-library -module-name LBSnippet_<uuid> ...` shell-out, dylib write to a temp dir, `dlopen` + `dlsym(lyrebird_snippet_entry)`. No UI, no engine binding. Returns a callable function pointer + a `LoadedSnippet` handle (kept alive for the lifetime of the process — dylib unload is unsafe while live `Synth` instances reference dylib types). **Merged to main.** |
| 143 ✓ | `SnippetHarness` + `SnippetContext` + `LiveSession`: tiny Swift preamble wrapped around the user's snippet body that imports `Lyrebird`, declares `@_cdecl("lyrebird_snippet_entry")`, and exposes `engine: SynthesisEngine` (+ helpers TBD per open question 4). `LiveSession` owns the `SynthesisEngine` and tracks every `Synth` started by the current snippet so re-evaluation can `free` them. **Merged to main.** |
| 144 ✓ | Diagnostics: parse `swiftc` stderr → structured `Diagnostic` (file/line/column/severity/message). Offset the line numbers back from the harness preamble to the user's snippet coordinates so error reports point to the row the user actually typed. **Merged to main.** |
| 145 ✓ | `LyrebirdScratchView` SwiftUI (`#if os(macOS)`) in `LyrebirdUI` — `NSTextView`-backed editor, ⌘↩ compile-and-run, ⌘⇧↩ additive compile-and-run, scrollable diagnostics list, status row. **Merged to main.** Async compile + line-gutter / syntax highlighting deferred to Phase 147. |
| 146 ✓ | `LyrebirdScratchDemo` Xcode project under `Demos/`, registered in `Lyrebird.xcworkspace`. Demo `.app` cannot be sandboxed (App Sandbox blocks shell-out + `dlopen`); hardened-runtime likely needs `Disable Library Validation` entitlement for unsigned dylib loading. **Merged to main.** |
| 147 ✓ | Polish v1 — async compile (swiftc on background `Task.detached`, real `isCompiling` state, Run buttons disable while compiling), line-number gutter (`ScratchLineNumberRuler` NSRulerView subclass), snippet open/save (`NSOpenPanel`/`NSSavePanel`, ⌘O/⌘S/⌘⇧S). Syntax highlighting + multi-snippet tabs deferred to a later phase. **Merged to main.** |
**Open questions to resolve before Phase 142 starts.**
1. **Sandboxing.** Demo `.app` cannot be sandboxed. Confirm OK for
v1 (not for Mac App Store; fine for direct distribution).
2. **Hardened runtime.** `Disable Library Validation` entitlement
likely needed for `dlopen` on unsigned dylibs. Test early in 146.
3. **Re-evaluation semantics.** ⌘↩ removes the prior snippet's tracked
synths first; ⌘⇧↩ is additive. Confirm.
4. **Snippet body API surface.** Just `engine`, or also helpers like
`play(_:)` / `stop(_:)`? Lean minimal for v1.
**Non-goals (don't scope-creep).**
- Recreating the SuperCollider interpreter pattern.
- iOS support v1.
- AOT-style autocomplete / IDE-equivalent symbol resolution.
- Hot-**unload** of dylibs — types in a dylib are referenced by live
`Synth` instances. Unload = crash. Leak them by design; new snippet =
new dylib.
---
### Phases 182–190 — Pattern + Demand catalogue expansion
Expand the language-side `Pattern<T>` and RT-side `Demand*` catalogues with
SuperCollider-style data-generation and composition primitives (no event-binding
/ synth-spawning patterns — Lyrebird wires Generators directly). Plan covers
nine sequential phases. Full design + rationale: plan file
`/Users/josh/.claude/plans/let-s-plan-more-pattern-quirky-wilkinson.md`.
**Phase 182** — Pattern facade refactor + Demand* rename. ✓ shipped; see
`docs/01-completed-working-order.md` for the full writeup.
**Phase 183** — Atomic numeric Pattern sources (`series`, `geometric`,
`uniformRandom`, `brownian`, `gaussian`, `cauchy`, `beta`). ✓ shipped;
see `docs/01-completed-working-order.md` for the full writeup.
**Phase 184** — Discrete-pool Pattern sources + closure escape hatch
(`shuffle`, `nonRepeatingRandom`, `weightedRandom`, `closure`). ✓ shipped;
see `docs/01-completed-working-order.md` for the full writeup.
**Phase 185** — Length/range Pattern modifiers (`repeating`, `limit`,
`drop`, `stutter`). ✓ shipped; see `docs/01-completed-working-order.md`
for the full writeup.
**Phase 186** — Multi-pattern composition (`switching`, `concatenate`,
`roundRobin`, `tuple`, `interleave`). ✓ shipped; see
`docs/01-completed-working-order.md` for the full writeup.
**Phase 187** — Map/filter/transform Pattern catalogue (`map`, `filter`,
`reject`, and `where T == Double` numeric transforms — `accumulate`,
`difference`, `wrap`, `clip`, `round`, `smooth`). ✓ shipped; see
`docs/01-completed-working-order.md` for the full writeup. Closes the
Pattern-side of the 183-187 sweep.
**Phase 188** — Atomic numeric `Demand*` (`DemandSeries`,
`DemandGeometric`, `DemandUniformRandom`, `DemandBrownian`) built as
thin wrappers around the Phase 183 Pattern engines. ✓ shipped; see
`docs/01-completed-working-order.md` for the full writeup.
**Phase 189** — Discrete-pool `Demand*` (`DemandShuffle`,
`DemandNonRepeatingRandom`, `DemandWeightedRandom`) built as thin
wrappers around the Phase 184 Pattern engines parameterised over
`T=Double`. ✓ shipped; see `docs/01-completed-working-order.md` for
the full writeup.
**Phase 190** — Composition `Demand*` (`DemandStutter`, `DemandSwitch`,
`DemandConcatenate`) composing other `DemandGenerator` instances
directly (no Pattern-engine wrap). ✓ shipped; see
`docs/01-completed-working-order.md` for the full writeup.
**Closes the 182-190 Pattern + Demand catalogue expansion.**
---
### Longer-term — Deferred
| Phase | Title | Source ref | Complexity |
|-------|-------|-----------|-----------|
| 96b | Ableton Link Sync | 9.2 | High |
#### Phase 96b — Ableton Link *(deferred)*
Ableton Link SDK (open source, Apache 2.0) integration for peer-to-peer beat sync over
LAN/WiFi. `LyrebirdClock` follows Link session tempo and beat phase. Stub:
`docs/roadmap/ableton-link.md`. SDK vendoring effort estimate 5–8 days (asio +
Link headers, C++ SwiftPM target, abl_link FFI shim, Bonjour entitlements,
manual 2-device test bench). Phase 96a (MIDI Clock follow) and Phase 95
(Scanned Synthesis) are complete on `main`.
---
### 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.
### 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.
---
+662 -2
View File
@@ -4750,14 +4750,14 @@ needed no change — system-realtime status bytes still route through
the `(status & 0xF0) == 0xF0 ? 0x1 : 0x2` test.
**Docs.** `docs/tooling/midi-clock-sync.md` is the user-facing
guide; `docs/roadmap/ableton-link.md` stubs Phase 96b.
guide. Phase 96b (Ableton Link) is not planned.
**3122 tests at completion** (was 3108 on `main` after inter-phase
ramps; +13 follower tests + 1 `.continue` round-trip).
### Phase 96b — Ableton Link
Deferred. Stub at `docs/roadmap/ableton-link.md`.
Not planned. MIDI Clock follow (Phase 96a) is the supported external-transport path.
---
@@ -9928,3 +9928,663 @@ which the runtime check resolves.
**Branch:** `phase-203-livecompile-swift6` off `main`. Standard checklist +
`/lyrebird_review` before merge.
---
## Phase 201 — Swift 6 main-actor isolation for `Synthesizer` (zero-annotation consumer subclassing)
**Goal.** A consumer building under Xcode 26's default
`SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor` must be able to subclass
`SynthesizerBase` with **no concurrency annotations**:
```swift
import LyrebirdSynth
final class ToneSynth: SynthesizerBase { // no nonisolated, no @preconcurrency
@UIParam var freq: Double = 440
override func build() {
output(bus: 0, source: OscSin.Audio(freq: $freq) * 0.2)
}
}
```
This must hold for the **core package, Quartet (local-path reference), and Test
(remote gitea reference)** simultaneously — those three are the acceptance gate.
**Problem (reproduced).** Core compiles in Swift 5 language mode, so
`SynthesizerBase.build()` / `init()` are *nonisolated*. A consumer whose project
defaults to `@MainActor` makes its subclass's `build()`/`init()` main-actor
isolated → **"main actor-isolated method has different actor isolation from
nonisolated overridden declaration."** Today's only workarounds live on the
consumer (`nonisolated override func build()`, `@preconcurrency`,
`nonisolated override init()`) — exactly what we will not ship. Verified: no
core annotation that keeps `build` nonisolated fixes it (the consumer's own
default-isolation governs its own override declaration). The fix is to make the
*language-side* surface of `Synthesizer` **main-actor isolated** so the
consumer's MainActor default *matches* instead of conflicts, while the single
RT entry point (`evaluate`) stays `nonisolated`.
**Isolation split — the core design.** `Synthesizer` has exactly one RT-thread
entry point; everything else is language-side (main thread):
| Member | Thread | Phase 201 isolation |
|---|---|---|
| `build()` | main (called once at add) | `@MainActor` |
| `release(engine:)` | main only (doc-stated) | `@MainActor` |
| `free(engine:)` | main only (doc-stated) | `@MainActor` |
| `evaluate(graph:count:)` | **RT render thread** | **`nonisolated`** |
| `@LiveParam` / `@UIParam` setters | main / atomic store | inherit main; atomic store is already cross-thread-safe |
`evaluate()` reads only two members: `parameterTable` (immutable `let`) and
`outputGenerators` (`var`, written in `build()` on main, read on RT after the
add-event barrier). Both are touched cross-thread **safely today** via the
engine's existing scheduling contract (the add event is applied on the RT thread
only after `build()` has fully returned on main — a happens-before edge through
the SPSC `pendingQueue`). Phase 201 makes that contract explicit to the compiler
with `nonisolated(unsafe)` on exactly those two stored properties, with a
comment citing the barrier. No new runtime synchronisation is added — the safety
argument is the one already in `ARCHITECTURE.md` §2/§9.
**Plan of work.**
1. **Protocol (`Synthesizer.swift`).** Annotate the protocol so language-side
requirements are `@MainActor` and `evaluate` is `nonisolated`. Options to
evaluate during implementation (pick whichever the compiler accepts most
cleanly): `@MainActor protocol Synthesizer` with `nonisolated func
evaluate(...)`, vs. per-requirement isolation. Update the default-extension
implementations (`evaluate` no-op, `release` throws, `free`) to match.
2. **`SynthesizerBase.swift`.** Mark the class `@MainActor`. Mark
`evaluate(graph:count:)` `nonisolated final`. Mark `parameterTable` and
`outputGenerators` `nonisolated(unsafe)` (the only state `evaluate` reads),
each with a `// RT-read after add-barrier; see ARCHITECTURE.md §9` comment.
Confirm `@LiveParam`/`@UIParam` wrapper-backed properties still compile (the
earlier whole-class-`nonisolated` experiment failed *because* wrappers reject
`nonisolated`; `@MainActor` does not have that problem — verify).
3. **`Group` / `ParallelGroup` (`NodeTree/`).** Both conform to `Synthesizer`
and call `evaluate` on the RT thread. Apply the same split: `build`/`release`/
`free` main-actor, `evaluate` `nonisolated`. `ParallelGroup.evaluate` uses
`concurrentPerform` over children — confirm the child `evaluate` calls remain
`nonisolated` end-to-end (no hop).
4. **Engine call sites.** `SynthesisEngine.processBlock` → `rootGroup.evaluate`
runs on the RT thread and must reach `evaluate` with no actor hop. Verify the
whole RT call chain (`processBlock` → `Group.evaluate` →
`synth.evaluate` → `Generator.calculatedSamples`) is `nonisolated`. The
engine itself is not an actor; ensure nothing forces a `MainActor.assumeIsolated`
or `await` onto the RT path (that would be a correctness/perf regression — a
hard fail for this phase).
5. **Other in-core conformers.** Audit the conformers that implement
`Synthesizer` directly rather than via `SynthesizerBase` (e.g. `VoicePool`,
AUv3 `LyrebirdAudioUnit` / `LyrebirdAUVoicePoolBinding`, any others surfaced
by `grep ": Synthesizer"`). Each needs the same `evaluate`-nonisolated split.
AUv3 is the riskiest (its render block is already a separate isolation
domain) — give it explicit attention.
6. **Language-mode decision.** Determine whether the core `LyrebirdSynth` target
should move to `.swiftLanguageMode(.v6)` (so the isolation is baked into the
module's binary interface and propagates to consumers regardless of their
mode) or stay `.v5` with explicit annotations. Prefer keeping `.v5` if
explicit `@MainActor`/`nonisolated` annotations suffice — a full v6 migration
of the whole module is a much larger lift and out of scope unless required to
make the consumer experience clean. **Spike this first** — it determines the
size of the rest of the phase.
7. **`LyrebirdUI`.** Currently `.v5` to dodge SwiftUI/AppKit actor diagnostics.
`@UIParam` lives here. Confirm the isolation split doesn't force a `.v6`
migration of `LyrebirdUI`; if `@UIParam`-bearing synths need anything, capture
it.
**Acceptance criteria (all three must pass with NO consumer-side concurrency
annotations):**
- **Core:** `swift test --no-parallel` green; `(cd LiveCompile && swift test
--no-parallel)` 34/34. RT path verified to have no actor hop (inspect, and
confirm no perf regression on the core synthesis benchmark).
- **Quartet** (local-path ref): builds + runs; its `SynthesizerBase` subclasses
carry no `nonisolated`/`@preconcurrency`. Remove any such annotations Quartet
currently has and confirm it still builds.
- **Test** (remote gitea ref, Xcode-26 `MainActor` default): the plain
`final class ToneSynth: SynthesizerBase { override func build() {…} }` builds
and runs with zero annotations. Revert the `@preconcurrency` /
`nonisolated override init` / `nonisolated override func build` that
Claude-in-Xcode added.
- A **regression fixture**: an SPM consumer target built with
`-default-isolation MainActor` + `.swiftLanguageMode(.v6)` (the repro from
the Phase-201 investigation) compiles an unannotated `SynthesizerBase`
subclass. Keep this as a committed smoke test so the guarantee doesn't silently
regress.
**Risks / watch-items.**
- `nonisolated(unsafe)` is a promise to the compiler — the `/lyrebird_review`
RT-safety pass must explicitly bless the two properties it lands on, citing the
add-barrier. Do not broaden it beyond `parameterTable` + `outputGenerators`
without re-justifying.
- If the protocol-level `@MainActor` forces awaits onto any existing internal
call site that currently runs sync on a background queue (routines, NRT batch),
that's in-scope to fix — those are language-side and can be `@MainActor` or
explicitly hopped, but must not touch the RT path.
- Docs: once landed, update `GettingStarted.md` / `INSTALLATION_AND_USAGE.md` to
show the clean zero-annotation subclass as *the* pattern, and drop the
interim "use `nonisolated final class`" guidance if it was added.
**Branch:** `phase-201-mainactor-isolation` off `main`. Standard phase
checklist + `/lyrebird_review` before merge. After merge, re-snapshot to gitea
and re-tag (the gitea 1.0.0 is unreleased, so it can absorb this).
**Investigation notes (from the session that wrote this plan — don't re-run these).**
*Exact failure (reproduced).* Consumer error under Xcode 26 MainActor default:
```
error: main actor-isolated instance method 'build()' has different actor isolation
from nonisolated overridden declaration
error: main actor-isolated initializer 'init()' has different actor isolation
from nonisolated overridden declaration
```
Source: `SynthesizerBase.build()` / `init()` are nonisolated (core is Swift 5
mode); consumer's project default makes the *subclass's* override `@MainActor`;
override-vs-base isolation mismatch.
*Reproduction recipe (use verbatim as the Phase 201 regression fixture).* A
throwaway SPM consumer at `/tmp`, depending on the package via local path:
```swift
// Package.swift target settings that reproduce Xcode 26's new-project default:
swiftSettings: [
.swiftLanguageMode(.v6),
.unsafeFlags(["-default-isolation", "MainActor"]),
]
```
```swift
// Sources/App/main.swift — the unannotated subclass that MUST compile post-201:
import LyrebirdSynth
final class ToneSynth: SynthesizerBase {
override func build() { output(bus: 0, source: OscSin.Audio(freq: 440) * 0.2) }
}
let s = ToneSynth(); print("ok \(s)")
```
Note: `.defaultIsolation(MainActor.self)` in the manifest is **unavailable** in
this SwiftPM toolchain (`error: 'defaultIsolation' is unavailable`) — must use
the raw `-default-isolation MainActor` unsafeFlag as above.
*Approaches already tried and RULED OUT (don't repeat):*
1. `nonisolated` on base `init()` + `build()` — **fails.** Consumer's override
still gets `@MainActor` from its own project default; mismatch persists. (The
error even confirms the base is "nonisolated" — proving the problem is the
consumer side, not the base.)
2. `nonisolated` on the **class** declaration (`open nonisolated class
SynthesizerBase`) — **fails to compile core**: `'nonisolated' is not
supported on properties with property wrappers` (the `@LiveParam`/`@UIParam`
stored properties). Whole-class `nonisolated` is a dead end.
3. `nonisolated` on the **protocol requirement** (`Synthesizer.build`) + base —
**fails the same way** as (1).
4. `@MainActor` on the class + `nonisolated final func evaluate(...)` — **right
direction, but surfaced the real work**: 9 errors, all from `evaluate()`
reading `parameterTable` and `outputGenerators` from a nonisolated context
while the class is MainActor (`#ConformanceIsolation` + "main actor-isolated
property can not be referenced from a nonisolated context"). This is exactly
why the plan lands `nonisolated(unsafe)` on those **two** properties — they
are the entire RT-read surface of `evaluate()`. Nothing else in the class is
read on the RT thread.
*Verified-working interim (NOT what we ship, but proves the seam):* the consumer
single-annotation form `nonisolated final class ToneSynth: SynthesizerBase { … }`
compiles cleanly (`Build complete`). Confirms one annotation on the *type* is
enough — Phase 201's job is to move that necessity into the core so the consumer
needs zero.
*RT-read surface (confirmed by reading `evaluate()`):* `evaluate(graph:count:)`
references exactly `parameterTable` (immutable `let`) and `outputGenerators`
(`var`, written in `build()` on main, read on RT). No other stored property is
touched on the RT thread. The `nonisolated(unsafe)` blast radius is precisely
these two.
---
### Phase 204 — Score / MusicXML demo + templates
Code-first starting point for authoring notated scores and exporting MusicXML.
Three surfaces, all driven by the existing `Score` DSL + `Score+MusicXMLEncode`
round-trip (no new core API):
1. **`Demos/LyrebirdScoreDemo/`** — nested SwiftPM package + `.xcodeproj`, mirrors
`LyrebirdNRTDemo`'s offline-render model. `ScoreDemo` builds a two-part 8-bar
`Score` exercising every DSL node (Note/Rest/Chord/Tuplet, all dynamics, all
articulations), writes `~/Desktop/LyrebirdScoreDemo.musicxml`, round-trips it
(`Score.fromMusicXML`), then schedules one self-freeing `ScoreVoice`
(`OscSawtooth` + `EnvelopeGen.Control(doneAction: .freeNode)`) per `ScoreEvent`
against an `NRTDriver` and renders `~/Desktop/LyrebirdScoreDemo.caf`. Added to
`Lyrebird.xcworkspace`.
2. **CLI project template** `lyrebird new <name> --template score`
(`ProjectTemplate.score`, SPM-only) — emits a single-file NRT-render flavor of
the demo via `mainSwiftScore(name:)`.
3. **Xcode file template** `LyrebirdScore.xctemplate` — `func make<Name>() -> Score`
factory (Tier 2, SortOrder 26), auto-discovered by `TemplateInstaller`.
Key API used (all pre-existing): `Pitch.frequency: Double?`, `ScoreEvent.isRest`,
`Score.allEvents` / `.totalBeats`, `NoteDuration.dotted(_:)`,
`score.toMusicXMLString()` / `.toMusicXMLData()` / `Score.fromMusicXML(data:)`.
Note: `Score.allEvents` excludes rests (rests only advance the flatten cursor), so
scheduled voice count == sounding-note count.
Swift 6 isolation: emitted SPM `main.swift` top-level entry is main-actor-isolated
by default, so the scaffold template schedules `@MainActor` `SynthesizerBase` voices
and calls `@MainActor` `engine.schedule` directly from top-level with no
`MainActor.assumeIsolated` wrapper — verified to compile + run (sibling
`LyrebirdNRTDemo` does the same).
Verification: `swift test --no-parallel` 4214/4214; scaffolded `--template score`
project built + ran end-to-end (valid MusicXML 4.0, round-trip 12→12, 5.5 s `.caf`);
`LyrebirdScore.xctemplate` validates parse + build OK. One `/lyrebird_review` cycle:
architecture agent's `@MainActor` "won't compile" finding rejected as empirically
false; two magic-number findings fixed (ScoreDemo pan/amp constants). Pre-existing
unrelated `LyrebirdTask.xctemplate` validation failure flagged separately.
---
### Pitch / Scale Theory Toolkit (Phases T1–T6)
A spelling-aware music-theory layer: intervals, scales/modes, pitch collections
(cells / 12-tone rows), and diatonic vs chromatic transposition — all preserving
**correct enharmonic spelling** (transposing `A` up an augmented 2nd gives `B♯`,
NOT `C♮`).
**Foundation already in place** (do not re-implement): `Letter` (C–B,
`rootSemitone`, `CaseIterable`), `Accidental` (9-step grid double-flat…double-
sharp + quarter-tones, `semitones: Double`), `NoteName(Letter, Accidental)`
(spelling-preserving, `semitones`, full static-let factories `.cSharp`/`.eFlat`/…),
`Pitch` (`.midi`/`.freq`/`.named(NoteName, Int)`, `midiNote`, `frequency`). The
letter carries the octave; the accidental never changes the octave (`C♭4` is
octave 4). This is what makes correct spelling possible.
**Layout:** new `Sources/Lyrebird/Score/Theory/` subfolder, one public type per
file. All pure value types — `Sendable`, `Hashable`, explicit type annotations,
no force unwraps, no magic numbers (interval tables as named constants). Pure
language-side; no RT/engine involvement. Everything outputs `NoteName`/`Pitch`
so results drop straight into the Score DSL (`Note(.named(...))`). Tests: one
`@Suite` per type; encode every worked example below; add a MusicXML round-trip
test on a transposed phrase to confirm spellings survive export.
Dependency order: **T1 → T2 → T3 → (T4, T5, T6)**.
---
**Phase T1 — `Interval` + spelling-correct transposition** (the keystone; covers
items b and f). Everything else spells through this.
- `Theory/Interval.swift`: `struct Interval` = `number: Int` (diatonic interval
number ≥ 1; 1 = unison, 2 = second, … 8 = octave, 9 = ninth — compound allowed)
+ `quality: IntervalQuality`. Computed `diatonicSteps = number - 1` (letter
distance) and `semitones: Int` (derived from number+quality via the
perfect/major reference table). Validity rule: perfect qualities only on
unison/4th/5th/octave; major/minor only on 2nd/3rd/6th/7th; diminished/
augmented on any. Static conveniences: `.unison`, `.minorSecond`,
`.majorSecond`, `.augmentedSecond`, `.minorThird`, `.majorThird`,
`.perfectFourth`, `.augmentedFourth`, `.diminishedFifth`, `.perfectFifth`,
`.minorSixth`, `.majorSixth`, `.minorSeventh`, `.majorSeventh`, `.octave`, …
Plus `static func between(_ a: NoteName, _ b: NoteName) -> Interval` (analyze
the spelled interval between two names — needed by T6).
- `Theory/IntervalQuality.swift`: `.diminished(Int)` / `.minor` / `.perfect` /
`.major` / `.augmented(Int)` (the `Int` = degree, for doubly-dim/aug).
- `Theory/IntervalDirection.swift`: `.up` / `.down`.
- Transposition (`Theory/NoteName+Transpose.swift`, `Pitch+Transpose.swift`):
- `NoteName.transposed(by: Interval, _ dir: IntervalDirection = .up) -> NoteName`.
**Algorithm**: advance the letter by ±`diatonicSteps` (mod 7); compute the
natural semitone gap to the new letter; pick the accidental that makes the
actual semitone distance equal `interval.semitones`. Out-of-range result
(beyond double-sharp/flat) → decide: `throws` or return the best
representable enharmonic (document).
- `Pitch.transposed(by:_:) -> Pitch`: for `.named`, transpose the `NoteName`
and adjust the octave by the letter wrap (+ compound octaves); for
`.midi`/`.freq`, shift by `interval.semitones` numerically (spelling lost —
document).
- **Tests (worked examples — must pass):** A +aug2↑ = B♯ (not C); C +M3↑ = E,
E +M3↑ = G♯; C +m3↑ = E♭; B +P4↑ = E; F♯ +m3↓ = D♯; C♭ +M2↑ = D♭.
---
**Phase T2 — `Scale`** (items a, a1).
- `Theory/Scale.swift`: `struct Scale` = `tonic: NoteName` + `degrees: [NoteName]`
(spelled pitch-classes, `degrees[0] == tonic`, one entry per scale degree).
- `init(tonic:intervals: [Interval])` — degrees = `tonic.transposed(by:)` each
interval (designated; guarantees correct per-degree spelling).
- `init(tonic:degrees: [NoteName])` and `init(tonic:pitches: [Pitch])` — treat
an arbitrary pitch set as a scale (item a).
- Queries: `contains(_:) -> Bool`; `degree(of: NoteName) -> ScaleDegree?`
(`ScaleDegree = (index: Int, alteration: Int)` so chromatic non-scale pitches
map as nearest degree + chromatic alteration); `noteName(atDegree: Int)
-> NoteName` (wraps mod count); `pitch(atDegree:octave:) -> Pitch`.
- `Theory/ScaleDegree.swift`: `struct ScaleDegree { index: Int; alteration: Int }`.
- Convenience factories (item a1), each from a tonic + interval pattern:
modes `.major`/`.ionian`, `.dorian`, `.phrygian`, `.lydian`, `.mixolydian`,
`.aeolian`/`.naturalMinor`, `.locrian`; `.harmonicMinor`, `.melodicMinor`;
symmetric `.wholeTone`, `.chromatic`, `.octatonicHalfWhole`,
`.octatonicWholeHalf`, `.augmentedScale`; `.majorPentatonic`,
`.minorPentatonic`, `.blues`.
- **Spelling note:** 7-note diatonic scales use 7 distinct letters (one per
degree) — the interval pattern guarantees the letter progression (D major →
D E F♯ G A B C♯). Symmetric scales (6/8/12 notes) have no one-letter-per-degree
mapping; each factory must define a **canonical spelling** per tonic (e.g.
whole-tone C = C D E F♯ G♯ A♯; document the sharps-up / flats-down choice).
---
**Phase T3 — `PitchCollection`** (item c).
- `Theory/PitchCollection.swift`: `struct PitchCollection` = `pitches: [Pitch]`
(ordered — melodic cell, atonal cell, or 12-tone row), optional
`referenceScale: Scale?` (used by T6).
- Spelled ops: `retrograde`; `transposedChromatic(by: Interval, _ dir:)` (item f,
via T1 on every pitch); `inverted(around: Pitch)` (pitch inversion preserving
spelling); `octaveReduced` (to pitch-classes).
- 12-tone row ops (when 12 distinct pitch-classes): `prime`, `inversion (I)`,
`retrograde (R)`, `retrogradeInversion (RI)`, `transposed(_ n)` (Tn),
`transposedInversion(_ n)` (TnI), `matrix() -> [[NoteName]]` (12×12) — spelling
via T1.
- Optional atonal set-theory helpers (pitch-class integers, spelling-agnostic):
normal form, prime form, interval-class vector — keep separate from the spelled
ops (could be a T3b sub-phase).
---
**Phase T4 — Diatonic (modal) transposition** (item e). Transpose a collection by
SCALE DEGREES within a scale, staying in the scale, correct spelling.
- `Scale.transposeDiatonic(_ c: PitchCollection, byDegrees n: Int)
-> PitchCollection`: each pitch → `degree(of:)`, `index += n`, wrap octave,
re-spell via `noteName(atDegree:)`; carry chromatic alteration through for
non-scale pitches.
- **Test:** C-D-E up a third (n = +2) in C major → **E-F-G** (NOT E-F♯-G♯). Plus
down + octave-wrap cases.
---
**Phase T5 — Chromatic transposition of collections** (item f). Mostly falls out
of T1 + T3.
- `PitchCollection.transposedChromatic(by: Interval, _ dir:)` applies the
spelling-correct interval to every pitch.
- **Test:** C-D-E up a major third → **E-F♯-G♯**. Pair it with the T4 test on the
same input to lock the modal-vs-chromatic distinction. (May fold into T3; kept
explicit to pin the contrast.)
---
**Phase T6 — Scale-to-scale mapping** (item d). Map a collection from an original
scale to a target scale by degree, correct spelling.
- `PitchCollection.mapped(from original: Scale, to target: Scale)
-> PitchCollection`: each pitch → `original.degree(of:)` →
`target.noteName(atDegree:)`, carrying alteration + octave.
- **Test:** C-E-G assigned to C major → mapped to D major = **D-F♯-A**; mapped to
E♭ major = **E♭-G-B♭**.
- Decide + document degree-count-mismatch policy (e.g. pentatonic → heptatonic):
map-by-index with wrap, or error.
**Open decisions to settle during implementation:** out-of-range spelling
(beyond 𝄫/𝄪); compound-interval octave bookkeeping; quarter-tone interaction
(intervals are 12-TET — define or exclude quarter-tone accidentals in
transposition); degree-count mismatch in T6.
---
### Phase 222 — `LyrebirdPaths` filesystem conveniences
New `LyrebirdPaths` namespace (`Sources/Lyrebird/Utilities/`, new subfolder) of
filesystem-location helpers, motivated by the `score` template hardcoding
`URL(fileURLWithPath: "score.musicxml")` — which drops files in the launch
directory (DerivedData under Xcode), not the project.
- `projectRoot(from:marker:) -> URL?` — walks up from the **caller's** source
file (default-argument `#filePath` expands at the call site, not in the
library) to the directory containing `Package.swift`. `marker` matches by
exact filename, or — when dot-prefixed (`.xcodeproj`) — by path extension
against directory contents, so it finds `MyApp.xcodeproj` (private
`directory(_:contains:)` helper). Dev-time only — path reflects the build
machine; docs steer shipped apps to `documents` / `applicationSupport`.
- Sandbox-standard accessors: `documents` / `applicationSupport` / `caches`
(via private `searchPath`, fallback `temporary`), `temporary` / `home` /
`currentWorkingDirectory`, plus macOS-only `desktop -> URL?`.
- `score` template generator (`ProjectScaffolder.mainSwiftScore`) now writes
both outputs via `projectRoot() ?? currentWorkingDirectory`.
- Docs: new **File output locations** section in `INSTALLATION_AND_USAGE.md`
(same session also added the `score` template row, a Score-features section,
and `LyrebirdScoreDemo` to the demo table); `Utilities/` added to the
CLAUDE.md folder list.
- Tests: `LyrebirdPathsTests` (6 cases). Full suite `swift test --no-parallel`
4516/4516.
One `/lyrebird_review` cycle — clean, no blocking. The caveman sweep's one risk
(docs said pass `.xcodeproj` but matching was exact-name) fixed by adding the
extension-suffix match + a 6th test. Number bumped from 221 (taken by the
mid-voice clef-changes phase).
---
## Phase 224 — `TimeSignature` + `MeterMap` model
Foundation for the beat-timeline group (Phases 224–229). **Model-only — no
notation behavior change.** Full suite 4544/4544 (+18).
- New `TimeSignature` value type: `numerator`, `denominator`, `beatGrouping: [Int]`
(sum == numerator), derived `measureQuarters: Fraction`, `isCompound`,
`pulsesPerBar`, `tuple`. Constructors: `(n, d)` auto-grouping (compound default
when `d ∈ {8,16}`, `n % 3 == 0`, `n > 3`), `(n, d, grouping:)` explicit override
(slow-6/8-simple `[1,1,1,1,1,1]` and additive 3+3+2 `[3,3,2]`), `(_ tuple:)`
back-compat. Named statics (`.fourFour`, `.threeFour`, `.twoFour`, `.cutTime`,
`.sixEightCompound`, `.sixEightSimple`, `.nineEight`, `.twelveEight`).
- New `MeterMap` type: segmented `[Segment(startBar:_:)]` (sorted, first must be
bar 1, unique startBars) + `anacrusis: Fraction` (pickup quarters). `timeSignature(atBar:)`
lookup (last segment with `startBar <= bar`; pickup bar 0 → initial), `initial`,
`isConstant`, single-constant convenience init.
- Wired `Score.meterMap` (defaults to single-segment map from `timeSignature`;
explicit map drives the back-compat tuple from `initial`) + `Part.meterMap?`
(all-or-nothing polymeter override, nil = inherit). **Model only** — encoder
still renders against the bar-1 signature.
- Refactored the encoder's inline `Fraction(num: ts.0*4, den: ts.1)` to
`TimeSignature(ts).measureQuarters` (bit-identical output).
- Design decisions (locked with Josh): grouping is the primitive (compound NOT
auto-only — explicitly overridable; complex/additive expressible); meter scope
= score-global default + all-or-nothing part override; anacrusis = bar 0
implicit; polymeter allowed in the model now, notation deferred to Phase 229.
- One `/lyrebird_review` cycle: 3 blocking fixed (ScorePart.init `/// - Parameters:`
block; MeterMap `anacrusis >= .zero`; `timeSignature(atBar:)` early-return) + 1
non-blocking (Score tuple precondition guarded `if meterMap == nil`). Caveman LGTM.
- Tests: `TimeSignatureTests` (13), `MeterMapTests` (5).
---
## Phase 225 — `ScoreTimeline.fill` + shared rest-fill helper
The core beat-timeline feature: place `ScoreElement`s at explicit 0-based
quarter-note beats; auto-fill the rests. Full suite 4558/4558 (+14).
- `ScoreTimeline` (caseless `public enum`): `fill([(beat:Double, element:ScoreElement)])`,
variadic `from(...)`, dict `fill([Double: ScoreElement])` — all `throws`.
0-based quarter addressing (beat 0.0 = part start). Sorts (stable); leading rest
when the first element starts after 0. Usage: `let lead = try ScoreTimeline.from(...)`
then `Part("lead") { lead }` (builders are non-throwing).
- `ScoreTimelineError`: `.overlap(atBeat:previousEndsAtBeat:elementDescription:)`
thrown when an element starts before the running cursor (monophonic per call —
loud signal, not a silent fix) + `.negativeBeat`.
- Shared generic `fillRests<P: Comparable & AdditiveArithmetic>(sorted:duration:makeRest:onOverlap:transform:)`
(gap → rest, `< cursor` → onOverlap, `==` → no rest, cursor `= position + duration`).
`scoreElementBeatSpan` (Fraction; recursive tuplet `× normal/actual`, wedge
transparent, voice/grace/clefChange zero). `noteDurationFraction` / `fractionFromBeats`.
- **Dedup**: routed all THREE gap-fill sites through `fillRests` — `ScoreTimeline`
(Fraction, throwing overlap), `MusicXMLParser` voice reconstruction (Fraction,
no-op overlap, `zeroVoice` transform), `MIDIFile+Score` event→element (P=Double,
preserves `.beats` representation + lossy-monophonic SMF behavior). `Fraction`
gained `AdditiveArithmetic` (+ `-=`) so the generic spans both cursors with no
cross-conversion.
- Consolidated the triplicated `2^20` denominator into `Fraction.beatApproxDenominator`.
- One `/lyrebird_review` cycle: 2 blocking fixed (tuplet-advance test; constant
consolidation) + 2 non-blocking (DocC link; wedge/zero-span tests). Caveman LGTM.
Parser round-trip + SMF bridge 281/281 unchanged (refactor behavior-identical).
- Tests: `ScoreTimelineTests` (14).
---
## Phase 226 — `BeatPosition` musical addressing + meter-aware resolver
Musician-friendly positions resolved to absolute quarter beats via a `MeterMap`.
Addressing only — anacrusis *notation* deferred to Phase 228. Full suite 4579/4579.
- `BeatPosition` (`public struct` + private `Kind` enum + static factory funcs —
`.bar(_:beat:)` and `.bar(_:division:)` differ only by label, which enum cases
can't, so static funcs): `.quarters(Double)`/`.quarters(Fraction)` (0-based,
meter-free, Fraction exact), `.beat(Double)` (flat 1-based felt beat, continuous
across bars, constant-initial-meter + anacrusis-free), `.bar(Int, beat:)` (felt
beat, meter-aware), `.bar(Int, division:)` (denominator-note granular).
`resolve(in: MeterMap) -> Fraction` honors anacrusis (bar 0 = pickup) + mid-piece
meter accumulation. Out-of-range felt beat traps.
- **`beat` = the conducted/felt pulse** (Josh): 4/4 → quarter, compound 6/8 → dotted-
quarter, additive 3+3+2 → [dotted-q, dotted-q, q]. `beat 1` = downbeat in every
meter. The finer notated note-value (eighth in 6/8) is the granular `division`.
- **Naming alignment**: two layers of "beat" — absolute timeline = quarter
(`ScoreEvent.beat`, `bpm`, `NoteDuration`, untouched) vs meter/addressing = felt
beat. Aligned the meter layer: `pulsesPerBar`→`beatsPerBar`, `pulseOnsetsQuarters`
→`beatOnsetsQuarters`, `pulseLengthsQuarters`→`beatLengthsQuarters`,
`beatUnitQuarters`→`divisionQuarters` (the denominator-note unit). Cross-layer
overload accepted; bridge documented at `resolve()`.
- `MeterMap.barStartQuarters(_:)`; `TimeSignature.divisionQuarters` / `beatOnsetsQuarters`
/ `beatLengthsQuarters`. `ScoreTimeline` meter-aware overloads `fill([(BeatPosition,
element)], meter:)` + `from(..., meter: = .fourFour)` via shared `fillResolved` core.
- One `/lyrebird_review` cycle: one blocking — out-of-range felt beat silently
misplaced → `precondition` trap (consistent with Tuplet/Voice/MeterMap). Caveman LGTM.
- Tests: `BeatPositionTests` (19) + 4 `ScoreTimeline` meter overload tests.
---
## Phase 227 — `ScoreTimeline` overlap policies + multi-voice timelines
Extends `ScoreTimeline` beyond single-voice-trap. Full suite 4586/4586.
- `ScoreTimelineOverlap` (`public enum`): `.trap` (default — throw) / `.truncatePrevious`
(shorten the previous note/chord/rest to end at the overlapping element's start;
tuplet/voice/wedge/grace/clef and same-start throw). Added as `overlap:` to every
single-voice `fill`/`from`/dict overload (Double + BeatPosition).
- `fillVoices([(beat/BeatPosition, voice, element)])` — explicit voice numbers; each
voice filled independently (intra-voice overlap traps), wrapped in `.voice(v, …)`
ascending → multi-voice `Part`. `voice < 1` throws `ScoreTimelineError.invalidVoice`.
- `fillAutoVoiced([(beat/BeatPosition, element)])` — greedy first-fit overlap
distribution into voices 1…N (the `.toNewVoice` behavior); non-overlapping → one
`.voice(1, …)`.
- Private cores `fillCore(_:overlap:)` / `fillVoicesCore` / `autoVoiceCore` + shared
`stableSorted` / `absoluteItems` / `resolvedItems` / `truncateOverlaps` /
`withTruncatedDuration` (rebuilds note/chord/rest preserving all fields). Public
overloads resolve once to `[(Fraction, element)]` then funnel through the cores.
- One `/lyrebird_review` cycle: 2 blocking — `voice<1` precondition→throw
(`invalidVoice`); missing BeatPosition-overload tests added. Caveman LGTM (chained
truncation, field preservation, greedy auto-voice, strict-`<` consistency verified).
- Tests: +7 `ScoreTimelineTests` (28 total).
---
## Phase 228 — Homometric mid-piece meter changes (encoder)
MusicXML encoder consumes `score.meterMap` (per-part `part.meterMap ?? score.meterMap`)
instead of a single timeSignature tuple. **Constant-meter output byte-identical.**
ENCODER-ONLY — parser round-trip + anacrusis deferred to 228b. Full suite 4595/4595.
- `encodePart` / `encodeVoiceSequence` / `openMeasure`: `timeSignature` tuple param
replaced by `meterMap: MeterMap`.
- Per-measure capacity: `remaining` resets to `meterMap.timeSignature(atBar: N).measureQuarters`
in both the multi-voice loop (`thisMeasureCapacity`) and `encodeVoiceSequence`
(recompute after `measureIndex += 1`). Dependent computations (wholeMeasureRest,
pad-rest, `<backup>` divisions) use the per-bar value.
- `openMeasure` emits `<time>` at measure 1 and at any later bar where
`timeSignature(atBar:N) != timeSignature(atBar:N-1)` — a bare `<attributes><time>…</time></attributes>`.
- `measureCount(atoms:meterMap:)` walks bars subtracting variable capacities.
- Byte-identical guarantee for single-segment maps verified provably by both review agents.
- One `/lyrebird_review` cycle: NO BLOCKING (both LGTM). Implemented by `lyrebird_language_agent`,
verified by tests + review.
- Known limitations → 228b: parser still first-`<time>`-wins (lossy round-trip),
anacrusis ignored, `annotateBeams` uses bar-1 capacity for all bars.
- Tests: `MusicXMLMeterChangeTests` (6).
---
## Phase 228b — Parser meter round-trip + per-measure beams
Closes the Phase 228 lossy round-trip for mid-piece meter changes. Full suite 4600/4600.
- Parser (`MusicXMLParser`): reads EVERY `<time>` from the first part (per-block
`pendingTimeBeatCount`/`pendingTimeBeatType` accumulators, committed on `</time>`
to `parsedMeterByMeasure[measure]` first-wins, `isFirstPart`-gated). `parsedScore()`
builds a `MeterMap` (sort by bar, guarantee a bar-1 segment, dedupe consecutive
equal signatures), passed to both `Score` constructions. First `<time>` still sets
the back-compat tuple. Single `<time>` → single-segment map → byte-identical model.
- Encoder (`annotateBeams(atoms:meterMap:)`): bar counter resets `tempRemaining` to
`meterMap.timeSignature(atBar: bar).measureQuarters` at each barline. Constant-meter
beams byte-identical.
- Caveat (documented + tested): MusicXML standard `<time>` carries no beat grouping,
so round-trip preserves num/den but re-infers the default grouping (6/8-simple → [3,3]).
- One `/lyrebird_review` cycle: NO BLOCKING (both LGTM) — byte-identity, MeterMap-build
precondition safety, no off-by-one, grouping-caveat-documented all verified.
- Tests: `firstTimeSignatureWinsOnMultiTimeDocument` → `midPieceTimeSignatureParsesIntoMeterMap`;
new `MusicXMLMeterRoundTripTests` (5).
---
## Phase 228c — Anacrusis (pickup) notation + round-trip
Encoder emits the pickup as `<measure number="0" implicit="yes">` (capacity =
`meterMap.anacrusis`); full bars stay 1-based. No-anacrusis output byte-identical.
Full suite 4611/4611.
- `measureCapacity(forMeasure:meterMap:)` (measure 0 → anacrusis, n≥1 → per-bar);
`measureCount` subtracts anacrusis before the full-bar walk (pickup-only → 0).
- `openMeasure` gains `implicit: Bool`; else-branch `<time>`-on-change gains a
`prevBar >= 1` guard (bar 1 after a pickup doesn't re-emit the initial `<time>`).
- Both measure loops prepend measure 0; `annotateBeams` starts at bar 0 (pickup
window) when `anacrusis > 0` so the full bar after resets to beat 0.
- Parser reads `<measure implicit="yes">`, pre-decrements the counter so the pickup
is measure 0 (full bars 1..N, existing 1-based maps intact), and recovers
`anacrusis = Fraction(pickupCursorDivisions, divisions)`. The pickup `<time>`
maps to MeterMap key 1 (no bar-0 segment → no precondition trap).
- One `/lyrebird_review` cycle: 2 blocking (beam pickup-window accounting + a
missing pickup-beaming test) + 1 non-blocking (doc comment) all fixed. Both LGTM.
- Tests: `MusicXMLAnacrusisTests` (11).
The meter-notation layer (mid-piece changes + anacrusis) is complete except
polymeter; per-part barlines already work via `part.meterMap ?? score.meterMap`.
---
## Phase 229 — Polymeter notation
Per-part meter maps already rendered correctly (the encoder went per-part for
mid-piece meter changes: `part.meterMap ?? score.meterMap`, parts encode
independently in `score-partwise`), so this was tests + docs + demo, not a
structural lift. **Closes the beat-timeline / time-signature group (223–229).**
Full suite 4615/4615; ScoreDemo xcodebuild SUCCEEDED.
- `MusicXMLPolymeterTests` (4): each part uses its own meter + bar count; no
cross-part `<time>` leak; per-part mid-piece meter change; per-part anacrusis.
- ScoreSystem.docc: new "Meter and time signatures" + "Polymeter" + "Beat
timelines" section (the 224–229 group was previously undocumented there).
- Caveats documented: score-level repeats/tempo/key are measure-indexed (align by
measure number, not absolute beat under polymeter); round-trip reads meter
score-globally (first part), so per-part overrides are export-faithful but do
not survive `fromMusicXML`.
- Corrected stale "later phase" doc-comments on `Score`/`ScorePart`/`MeterMap`.
- ScoreDemo: `timeline` (ScoreTimeline + BeatPosition), `autovoice`
(fillAutoVoiced), `polymeter` (own 3/4 MeterMap) parts + a makeScore() menu of
all material-creation approaches.
- One `/lyrebird_review` cycle: 1 blocking (stale `MeterMap` doc-comment) + caveman
LGTM; all docc claims + caveats verified against code.
### Beat-timeline / time-signature group (223–229) — summary
223 `Generate`/`PatternNotes` algorithmic generators · 224 `TimeSignature`+`MeterMap`
model · 225 `ScoreTimeline.fill` + shared `fillRests` · 226 `BeatPosition` musical
addressing (`beat` = felt pulse) · 227 overlap policies + multi-voice · 228 mid-piece
meter-change encoder · 228b parser meter round-trip · 228c anacrusis · 228.5 phase-ref
cleanup + CLAUDE.md rule · 229 polymeter. The Score system now places notes at
explicit/musical beats with rest auto-fill, addresses beats across simple/compound/
additive meters, handles overlaps + multi-voice, and renders mid-piece meter changes,
anacrusis, and polymeter — all MusicXML-export-faithful.
-2
View File
@@ -212,5 +212,3 @@ is `$(TARGET_NAME)` by default, so the target name itself).
— `LyrebirdAudioUnit` API reference.
- [`Demos/LyrebirdAUv3Demo/README.md`](../Demos/LyrebirdAUv3Demo/README.md)
— reference demo walkthrough.
- [`docs/roadmap/auv3-extension-project.md`](roadmap/auv3-extension-project.md)
— the original project sketch that this guide grew out of.
-61
View File
@@ -1,61 +0,0 @@
# Phase 96b — Ableton Link (Deferred)
This phase is **deferred**. Phase 96a (MIDI Clock follow) is implemented and merged.
---
## Goal
Peer-to-peer beat and tempo synchronisation over a local network (LAN/WiFi) using the
Ableton Link open-source SDK. Multiple apps on the same network share a common timeline
and tempo without a designated leader — any participant can change tempo and all others
follow.
---
## Shape
The integration would follow the same pattern as `MIDIClockFollower` (Phase 96a):
```swift
public final class AbletonLinkFollower: @unchecked Sendable {
public init(engine: SynthesisEngine, clock: LyrebirdClock, quantum: Double = 4.0)
public func start() throws
public func stop()
public var sessionTempo: Double { get }
public var isConnected: Bool { get }
}
```
`AbletonLinkFollower.start()` connects to the Link session and begins pushing session
tempo changes to `clock.bpm`. The `quantum` (default 4 beats) defines the phase-sync
window. On `.start()`, the follower aligns the local `LyrebirdClock` beat phase to the
Link session timeline.
---
## Prerequisites
- **Ableton Link C++ SDK** (`ableton/link`, Apache 2.0) as a SwiftPM binary or source
dependency. The SDK's `ABLLink.h` C bridging header or Swift overlay must be added to
`Package.swift`.
- A thin C or C++ wrapper to call Link from Swift (the SDK is header-only C++; a minimal
shim is needed to expose an Objective-C or C-compatible interface).
- Network capability entitlements on macOS/iOS (Bonjour + peer-to-peer networking).
---
## Effort estimate
High. The main complexity is the C++/Swift FFI for the Link SDK and testing peer-to-peer
behaviour without dedicated hardware (requires at least two simulators or devices on the
same LAN).
---
## References
- [Ableton Link SDK](https://github.com/Ableton/link) — Apache 2.0 open source
- [Link API overview](https://ableton.github.io/link/)
- Phase 96a implementation: `Sources/Lyrebird/MIDI/Sync/MIDIClockFollower.swift`
- Related: `docs/tooling/midi-clock-sync.md`
-76
View File
@@ -1,76 +0,0 @@
# AUv3 Extension Project (Phase 104b sketch)
Phase 104a ships only the Swift API surface (``LyrebirdAudioUnit``,
``AUv3Driver``, parameter mapping, ring buffer, `fullState`). Wrapping that as
an actual `.appex` plugin is Phase 104b's job, which lives in a separate
Xcode-managed sub-directory because SwiftPM cannot build app extensions.
This file is the planning sketch for that work — kept as a roadmap entry so
contributors can pick it up after 104a lands.
## Demos/LyrebirdAUv3Demo layout (104b)
```
Demos/LyrebirdAUv3Demo/
LyrebirdAUv3Demo.xcodeproj
LyrebirdAUv3Demo/ container app target
LyrebirdAUv3DemoApp.swift minimal SwiftUI app entry
ContentView.swift "Install me so the AU registers"
Info.plist
LyrebirdFMExtension/ .appex AUv3 extension target
LyrebirdFM.swift example SynthesizerBase subclass
LyrebirdFMAudioUnit.swift LyrebirdAudioUnit subclass
LyrebirdFMAudioUnitViewController.swift empty AUViewController (104c populates)
Info.plist AudioComponents declaration
README.md "How to copy this template"
```
## Example AudioComponentDescription
```xml
<key>NSExtension</key>
<dict>
<key>NSExtensionAttributes</key>
<dict>
<key>AudioComponents</key>
<array>
<dict>
<key>type</key> <string>aumu</string>
<key>subtype</key> <string>LBFM</string>
<key>manufacturer</key><string>RLZS</string>
<key>name</key> <string>Realized Sound: LyrebirdFM</string>
<key>version</key> <integer>1</integer>
<key>factoryFunction</key><string>...</string>
<key>sandboxSafe</key><true/>
<key>tags</key> <array><string>Synth</string></array>
</dict>
</array>
</dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.AudioUnit-UI</string>
<key>NSExtensionPrincipalClass</key>
<string>$(PRODUCT_MODULE_NAME).LyrebirdFMAudioUnitViewController</string>
</dict>
```
## Validation pass
- `auval -v aumu LBFM RLZS` from terminal — must produce a `PASS` summary.
- Load in Logic Pro / GarageBand / AUM / Loopy Pro and verify the plugin
instantiates, exposes its parameters, and plays back via host MIDI.
## auval pitfalls 104a already handles
- `parameterTree` non-nil before `allocateRenderResources` ✓
- `latency` returns finite value (0 for instrument) ✓
- `tailTime` returns 0 for instrument ✓
- `internalRenderBlock` returns `noErr` and writes into the supplied ABL ✓
- `maximumFramesToRender` honoured by the driver's ring sizing ✓
## Open items handed off to 104b
- Code-signing scheme (Josh's team ID or placeholder for forks).
- iOS app-extension entitlements (`com.apple.security.app-sandbox` etc.).
- Embedding the SwiftPM `Lyrebird` package as a local dependency of the
Xcode project (vs. publishing the package to a registry).
- README walkthrough of "how to fork this template for your own synth".
-112
View File
@@ -1,112 +0,0 @@
# iOS Support — Roadmap ✓ COMPLETE
> All four phases shipped. See `docs/01-completed-working-order.md` (iOS phases section) for the authoritative implementation record. This file is preserved as the original plan with implementation notes appended.
Builds on prior analysis: `docs/support_for_iOS_findings.md`.
## What Stayed Untouched (as planned)
All Generators, SynthesisEngine, bus system, scheduling, patterns, MIDI, OSC, envelopes, spectral, granular — zero changes needed. ✓
`LyrebirdWindow.swift` was the only AppKit-only file expected. However, `ParameterKnob.swift` and `ParameterXY.swift` also used `Color(nsColor:)` / `NSColor` system colors — not caught during planning, discovered at iOS compile time. Fixed via `PlatformColors.swift` (see iOS-3 notes below).
---
## Phases
### Phase iOS-1 — iOSAudioDriver ✓
**Implemented as planned with one important correction:**
The original plan used `engine.sampleRate` for the AU stream format. In practice, `setPreferredSampleRate` is a hint — many devices (iPhone 6s+, most modern hardware) lock to 48 kHz regardless. Configuring the AU at 44100 when the session runs at 48000 causes a per-callback frame-count mismatch → choppy audio.
**Actual implementation:**
- AU stream formats use `session.sampleRate` (actual committed rate) after `setActive(true)`, not `engine.sampleRate`
- `setPreferredIOBufferDuration(blockSize / sampleRate)` added to align hardware buffer with `MaximumFramesPerSlice`
- Category: `.playback` for output-only (not `.playAndRecord` — avoids unnecessary mic permission); `.playAndRecord` + `.defaultToSpeaker` only when `numInputChannels > 0`
- `sessionSampleRate: Double?` property exposes actual committed rate
- Tests in `Tests/LyrebirdTests/iOSAudioDriverTests.swift` (`#if os(iOS)` guarded)
---
### Phase iOS-2 — Package.swift + LyrebirdC ARM64 ✓
`DenormalUtils.c` unchanged — `fesetenv(FE_DFL_DISABLE_DENORMS_ENV)` is a Darwin-wide extension available on iOS ARM64 without guards. `swift build` clean.
Added `.linkedFramework("AVFoundation", .when(platforms: [.iOS]))` to the `Lyrebird` target (not in original plan — needed because `iOSAudioDriver.swift` imports AVFoundation).
---
### Phase iOS-3 — LyrebirdUI AppKit Isolation ✓
`LyrebirdWindow.swift` guarded as planned. Additionally: `ParameterKnob.swift` and `ParameterXY.swift` used `Color(nsColor: .controlBackgroundColor/separatorColor)` — AppKit-only, not caught during planning.
**Fix:** New `Sources/LyrebirdUI/Controls/PlatformColors.swift` defines `Color.lyrebirdControlBackground` and `Color.lyrebirdSeparator` with `#if os(macOS)` / `#else` branches using `NSColor` / `UIColor` respectively. Both control files updated to use these instead.
---
### Phase iOS-4 — iOS Demo App
**Goal:** Runnable iOS demo proving the stack works end-to-end. Mirrors `LyrebirdMacOSDemo` layout and UI exactly.
**New:** `Demos/LyrebirdiOSDemo/LyrebirdiOSDemo.xcodeproj`
**Modified:** `Lyrebird.xcworkspace/contents.xcworkspacedata` — add new project ref
**Same source structure as macOS demo:**
```
LyrebirdiOSDemo/
LyrebirdiOSDemoApp.swift ← SwiftUI @main (replaces main.swift + AppDelegate)
Synthesizers/
SineToneUI.swift ← identical to macOS demo
UI/
NoteController.swift ← identical to macOS demo (no AppKit)
SineToneView.swift ← identical to macOS demo (pure SwiftUI)
```
### Phase iOS-4 — iOS Demo App ✓
**Key differences from original plan:**
AVAudioSession is pre-activated in `App.init` **before** `SynthesisEngine` is created, not just before `engine.start()`. This is required to read the hardware's actual sample rate and pass it into the engine at construction time. The original plan activated session inside `iOSAudioDriver.setup()`, which is called during `engine.start()` — too late for the engine's `sampleRate` property.
**Actual App.init pattern:**
```swift
let session = AVAudioSession.sharedInstance()
try? session.setCategory(.playback, mode: .default)
try? session.setActive(true)
let sampleRate = session.sampleRate // actual hardware rate
let driver = iOSAudioDriver()
let engine = SynthesisEngine(blockSize: 512, sampleRate: sampleRate, ...)
```
All other differences from macOS demo as planned:
- No `main.swift`, no `AppDelegate`, no `NSApplication`, no `LyrebirdWindow`
- SwiftUI `@main` App struct handles lifecycle
- `iOSAudioDriver()` instead of `CoreAudioDriver()`
- Engine `start()`/`stop()` tied to `.onAppear`/`.onDisappear` on root view
`SineToneView.swift` and `NoteController.swift` copy verbatim from the macOS demo — both are already pure SwiftUI/Swift with no AppKit.
---
## File Change Summary
| File | Change |
|------|--------|
| `Sources/Lyrebird/AudioDrivers/iOSAudioDriver.swift` | **New** — RemoteIO driver |
| `Sources/Lyrebird/AudioDrivers/CoreAudioDriver.swift` | Add `#if os(macOS)` guard |
| `Sources/LyrebirdUI/LyrebirdWindow.swift` | Add `#if os(macOS)` guard |
| `Package.swift` | Add `.iOS(.v18)` |
| `Sources/LyrebirdC/DenormalUtils.c` | Verify/guard ARM64 FTZ |
| `Demos/LyrebirdiOSDemo/` | **New** — iOS demo Xcode project (mirrors macOS demo) |
| `Lyrebird.xcworkspace/contents.xcworkspacedata` | Add iOS demo project ref |
Zero changes to all Generators, SynthesisEngine, bus system, all other LyrebirdUI files.
---
## Order of Operations
iOS-1 → iOS-2 → iOS-3 → iOS-4. Each phase is independently mergeable. iOS-2 and iOS-3 can be done in parallel. iOS-4 requires iOS-1 through iOS-3 complete.
-209
View File
@@ -1,209 +0,0 @@
# PitchShift A/B experiment — current pool model vs SC 4-head SOLA
Status: **resolved**. After A/B listening, the SC-faithful 4-head SOLA variant was
adopted as the primary granular pitch shifter and renamed to `PitchShift.Audio`. The
former dynamic grain-pool `PitchShift.Audio` was preserved (its tunable `overlap` and
selectable grain-read `interpolation` remain valuable) and renamed to
`TuneablePitchShift.Audio`. Tests, demos, benchmark, and `PitchShifting.md` were
updated end-to-end as part of the rename. The rest of this document is kept as the
historical experiment plan.
## Background
`Sources/Lyrebird/Generators/Granular/PitchShift.swift` currently uses a dynamic
grain pool: triggers fire every `windowSamples / overlap` ticks and allocate a
free `GrainState` slot. Default `overlap = 8`, pool size = 64.
The SuperCollider `PitchShift` UGen (`server/plugins/DelayUGens.cpp:4581–5044`)
uses a **fixed 4-read-head SOLA** model:
- Single power-of-two circular delay buffer, write head with `& mask` wrap.
- Always exactly four read heads. Each head re-triggered every `framesize / 4`
samples (cyclic stage 0→3).
- Window envelope is an inline accumulator: each head carries `ramp` and
`ramp_slope` floats; slope flips sign at quarter-window boundaries. Heads
1/3 form one inverted-slope pair, 2/4 another → 4-way constant-power
cross-fade.
- `samp_slope = 1 - pchratio`; read at `iwrphase - dsamp`. `startpos` is
set so the head trails the writer for any clamped pitchRatio.
- Output normalized by `value *= 0.5` to compensate triangle OLA gain of 2.0.
After the recent fixes ([PitchShift.swift:140](Sources/Lyrebird/Generators/Granular/PitchShift.swift)
lookback formula + inline triangle envelope) the Lyrebird implementation is
correct at all clamped pitchRatios but still spends per-grain bookkeeping time
the SC version doesn't.
## Goal
Determine whether replacing the current pool model with the SC 4-head SOLA
model is worth the migration cost. Decision based on three axes:
1. **Sound quality** — listening tests at typical and extreme settings.
2. **CPU cost** — measured at `overlap = 4` (matched comparison) and at
`overlap = 8` (Lyrebird's default).
3. **API surface** — what features (overlap parameter, pitchDispersion,
timeDispersion) survive in the 4-head model and which do not.
## Approach
### Side-by-side implementation
Add a second class `PitchShift.Audio4` (working name) implementing the SC
4-head SOLA model alongside the existing `PitchShift.Audio`. Both live in
`Sources/Lyrebird/Generators/Granular/PitchShift.swift` (or a new
`PitchShift4Head.swift`) and share `_Base`-like configuration where useful.
The 4-head class:
- Drops the `overlap` parameter (fixed at 4 by construction).
- Drops the dynamic `_grains: [GrainState]` pool and `lyrebirdGrainPoolSize`
dependency.
- Stores per-head fields directly on the class:
```swift
var dsamp1, dsamp2, dsamp3, dsamp4: Double
var dsampSlope1, dsampSlope2, dsampSlope3, dsampSlope4: Double
var ramp1, ramp2, ramp3, ramp4: Double
var rampSlope1, rampSlope2, rampSlope3, rampSlope4: Double
var stage: Int = 3
var counter: Int
let slope: Double // 2 / framesize
let framesize: Int
```
- Uses a power-of-two capture buffer (round `captureSize` up at init) and a
precomputed `_captureMask = captureSize - 1` for `& mask` wrap.
- Normalizes output by `* 0.5` to match SC's triangle OLA gain compensation.
- Keeps `pitchDispersion`: applied at each stage trigger, identical to SC.
- Keeps `timeDispersion`: applied to `startpos` via `+= timedisp * frand()`,
identical to SC.
### Surface decision
Two viable shapes:
**Option 1 — separate type**
- `PitchShift.Audio` keeps current grain-pool model, retains `overlap`.
- `PitchShift.Audio4` exposes the 4-head model, no `overlap` parameter.
- User picks. Both ship.
**Option 2 — switchable mode**
- `PitchShift.Audio` gains a `mode: PitchShiftMode` enum: `.pool` (current),
`.fourHead` (SC). Init dispatches to one or the other internally.
- Smaller API footprint; one type covers both.
Recommend **Option 1** for the experiment (cleanest diff, easiest to delete
the loser). Decision on long-term shape comes after measurement.
### Benchmark harness
Add a benchmark in `Sources/LyrebirdBenchmark/`:
- Single-instance stress: 1 PitchShift driven by a sine, 60 s render at 48 kHz,
blockSize 256. Measure wall-clock and per-block min/max/avg.
- Polyphonic stress: 32 instances in parallel groups, same render.
- Run for: pool model `overlap=4`, pool model `overlap=8`, 4-head model.
- Use Instruments (Time Profiler) for hot-path attribution if anything looks off.
### A/B listening test
Render six audio files via NRT (`docs/tooling/nrt-guide.md`) using a fixed
input (sine sweep + percussive sample + sustained voice):
| File | Model | pitchRatio | windowSize | overlap | Notes |
|------|-------|------------|------------|---------|-------|
| 1 | pool | 1.5 | 0.05 | 4 | matched comparison |
| 2 | 4-head | 1.5 | 0.05 | — | matched comparison |
| 3 | pool | 0.5 | 0.05 | 4 | octave down |
| 4 | 4-head | 0.5 | 0.05 | — | octave down |
| 5 | pool | 4.0 | 0.05 | 4 | extreme up — was the buggy region |
| 6 | 4-head | 4.0 | 0.05 | — | extreme up |
Save to a stable directory. Subjective listening + spectrogram inspection
(LyrebirdSpectrumView NRT capture, or external tool) for transient artifacts,
spectral leakage, periodic flutter.
### Test parity
Mirror the existing `PitchShiftTests` suite for `PitchShift.Audio4`:
- silence in → silence out
- pitchRatio clamp behavior
- deterministic output with fixed seed
- mul/add scaling
- high-pitchRatio read-head safety regression
Plus 4-head-specific:
- output gain compensation (`* 0.5`) verified against constant input
- `overlap` parameter not present (compile-time check or doc note)
## Decision criteria
After benchmarks + listening tests, switch architectures if **all three** hold:
1. 4-head CPU cost ≤ pool model at matched `overlap=4` (expected — fewer
indirections, fewer field loads, no slot scan).
2. 4-head sound quality is subjectively equal or better at the three
pitchRatio test points.
3. Loss of `overlap` parameter is acceptable. (The current docs already note
`overlap > 16` is a CPU-vs-quality knob with diminishing returns, so a
fixed 4 may be fine for most users.)
If any fail, keep both via Option 1 indefinitely or scrap the 4-head class.
## Files involved
| File | Role |
|---|---|
| `Sources/Lyrebird/Generators/Granular/PitchShift.swift` | current pool model, untouched until decision |
| `Sources/Lyrebird/Generators/Granular/PitchShift4Head.swift` | new 4-head class (Option 1) |
| `Tests/LyrebirdTests/PitchShift4HeadTests.swift` | parity test suite |
| `Sources/LyrebirdBenchmark/main.swift` | add PitchShift A/B benchmark |
| `docs/stdlib/generators.md` | document new type / mode if shipped |
## Estimated effort
- 4-head implementation + tests: ~half day.
- Benchmark harness + run: ~half day.
- A/B render + listening notes: ~half day.
- Decision + cleanup or merge: ~half day.
Total ~2 days when scheduled. Not blocking any current phase.
## Open questions — resolved at implementation time
1. **Param compatibility.** `windowSize > 0` precondition retained;
internal `framesize` clamps to ≥ 4 samples after rounding to a multiple
of 4. Audible difference at < ~3 samples is moot.
2. **`pitchRatio` clamp.** Kept at Lyrebird `[0.25, 4]` for cross-variant
consistency. SC's `[0, 4]` not adopted.
3. **MCE expansion.** Both mono; nothing to change.
## Implementation log
Landed:
- `Sources/Lyrebird/Generators/Granular/PitchShift4Head.swift` — `PitchShift.Audio4`
- `Tests/LyrebirdTests/PitchShift4HeadTests.swift` — 10 parity tests
- `Sources/LyrebirdBenchmark/main.swift` — A/B benchmark section
- `Sources/Lyrebird/Lyrebird.docc/Generators/PitchShifting.md` — variant section
Bench results (release build, 16 instances in parallel, 10 000 iterations):
```
PitchShift.Audio overlap=4 ×16 2968 ns/block
PitchShift.Audio overlap=8 ×16 2877 ns/block
PitchShift.Audio4 ×16 2864 ns/block
```
Single-instance numbers are dominated by `OscSin → Pan2 → Out` overhead, so the
inter-variant difference is small (≈ 2 % spread). At polyphony of 16, the 4-head
model is the fastest variant, edging the `overlap = 8` pool by ~0.5 % and the
matched `overlap = 4` pool by ~3.5 %. CPU criterion (1) is met.
## Pending — listening test + decision
Plan above (NRT renders at three pitchRatios, subjective listening + spectrogram
inspection) is unchanged. After listening:
- If `Audio4` is judged equal-or-better at all three pitchRatios: deprecate
`PitchShift.Audio` over a phase or two, keep `Audio4`.
- If both have niches: keep both indefinitely. Update DocC to nudge users toward
the right one (steady tonal material → Audio4; transient / textural material
with higher `overlap` → Audio).
- If `Audio4` is worse: revert the file, keep the bench as historical context.
+340
View File
@@ -0,0 +1,340 @@
# Pitch / Scale Theory Toolkit
A spelling-aware music-theory layer: intervals, scales and modes, pitch collections (melodic cells, atonal sets, 12-tone rows), and diatonic-vs-chromatic transposition — all preserving **correct enharmonic spelling**. Transposing `A` up an augmented second gives `B♯`, never `C♮`.
It is a pure, language-side value layer — no RT thread, no engine, no Generators. Everything is built on the existing `Letter` / `Accidental` / `NoteName` / `Pitch` foundation and outputs `NoteName` / `Pitch`, so results drop straight into the **Score DSL** for notation/MusicXML, or convert to **Hz and seconds** to drive synthesis parameters.
Files live under `Sources/Lyrebird/Score/Theory/`. All types are `Sendable` + `Hashable`.
```swift
import LyrebirdSynth
```
---
## Core types
| Type | Role |
|---|---|
| `Interval` | Spelled diatonic interval: `number` (1 = unison … 8 = octave, compounds allowed) + `IntervalQuality`. |
| `IntervalQuality` | `.diminished(n)` / `.minor` / `.perfect` / `.major` / `.augmented(n)`. |
| `IntervalDirection` | `.up` / `.down`. |
| `Scale` | A tonic + ordered spelled `degrees`. Modes, symmetric scales, pentatonics, or arbitrary pitch sets. |
| `ScaleDegree` | A located degree: `index` + chromatic `alteration` (semitones off the degree). |
| `PitchCollection` | An ordered list of `Pitch` (cell / set / row) + optional `referenceScale`. |
Most operations **throw** (`IntervalError`, `ScaleError`, `ToneRowError`). Intervals are 12-TET; quarter-tone accidentals are rejected (`IntervalError.quarterToneUnsupported`). A correct spelling that would need an accidental beyond double-flat / double-sharp throws `IntervalError.unrepresentableSpelling`.
---
## Intervals
A static catalogue covers the common simple intervals; build others with `init(number:quality:)`.
```swift
Interval.majorThird.semitones // 4
Interval.augmentedSecond.semitones // 3 (same SOUND as a minor third…)
Interval.minorThird.semitones // 3 (…but a different SPELLING)
Interval.majorThird.diatonicSteps // 2 (letter distance)
let majorNinth = try Interval(number: 9, quality: .major) // compound
majorNinth.semitones // 14
```
Validity is enforced: perfect-class numbers (unison / 4th / 5th / octave) reject `.major` / `.minor`; imperfect-class numbers (2nd / 3rd / 6th / 7th) reject `.perfect`.
```swift
try Interval(number: 5, quality: .major) // throws .qualityNumberMismatch
```
Analyse the spelled interval between two names or pitches:
```swift
try Interval.between(.c, .e) // major third
try Interval.between(.a, .bSharp) // augmented second (not minor third)
// Directed, possibly-compound, between two named pitches:
let (interval, dir) = try Interval.directed(from: .named(.c, 4), to: .named(.e, 5))
// interval = major tenth, dir = .up
```
### Transposition
`transposed(by:_:)` advances the letter by the interval's `diatonicSteps`, then picks the accidental that makes the chromatic distance equal `interval.semitones` — so the spelling is always correct.
```swift
try NoteName.a.transposed(by: .augmentedSecond) // B♯ (NOT C)
try NoteName.e.transposed(by: .majorThird) // G♯
try NoteName.fSharp.transposed(by: .minorThird, .down) // D♯
// Pitch keeps spelling AND tracks the octave:
try Pitch.named(.b, 4).transposed(by: .perfectFourth) // .named(.e, 5) (letter wraps past C)
try Pitch.named(.c, 4).transposed(by: majorNinth) // .named(.d, 5)
```
`.midi` / `.freq` pitches shift numerically (spelling is lost — documented on the method).
### Folding into a register
`Pitch.mapIntoRange(low:high:)` shifts a pitch into the inclusive register `[low, high]` by whole octaves, taking the fewest octaves. The pitch class is preserved, and for `.named` pitches **spelling survives** — a `B♭` maps to a `B♭`, never an enharmonic `A♯` (unlike the scalar `Double`/`Int` `mapIntoRange`, which only knows MIDI numbers). There is no `modulo:` parameter: the fold is octave-only by design, which is exactly what keeps the pitch class and spelling intact.
```swift
Pitch.named(.c, 3).mapIntoRange(low: .named(.a, 4), high: .named(.a, 5)) // .named(.c, 5)
Pitch.named(.bFlat, 2).mapIntoRange(low: .named(.c, 4), high: .named(.c, 5)) // .named(.bFlat, 4)
```
When the range is wider than an octave the fewest-octaves rule returns the first representative reached from `self`:
```swift
Pitch.named(.c, 3).mapIntoRange(low: .named(.a, 4), high: .named(.a, 6)) // .named(.c, 5) — folds up
Pitch.named(.c, 7).mapIntoRange(low: .named(.a, 4), high: .named(.a, 6)) // .named(.c, 6) — folds down
```
When no octave lands inside the range (the bounds span less than an octave and this pitch class has no member there), or when an endpoint / the pitch is a rest or out-of-MIDI-range, **the original pitch is returned unchanged**. `.midi` / `.freq` pitches fold numerically and keep their case (`.freq` keeps sub-semitone cents).
---
## Scales and modes
Factories build a scale from a tonic + interval pattern. Seven-note diatonic modes use seven distinct letters, so spelling is guaranteed.
```swift
let dMajor = try Scale.major(.d)
dMajor.degrees // [D, E, F♯, G, A, B, C♯] ← one letter per degree
try Scale.dorian(.eFlat).degrees // [E♭, F, G♭, A♭, B♭, C, D♭]
try Scale.harmonicMinor(.a).degrees // [A, B, C, D, E, F, G♯]
```
Symmetric scales have more notes than letters; each factory fixes a canonical spelling:
```swift
try Scale.wholeTone(.c).degrees // [C, D, E, F♯, G♯, A♯]
try Scale.octatonicHalfWhole(.c).degrees // [C, D♭, E♭, E, F♯, G, A, B♭]
try Scale.majorPentatonic(.c).degrees // [C, D, E, G, A]
try Scale.blues(.c).degrees // [C, E♭, F, G♭, G, B♭]
```
Available: `major`/`ionian`, `dorian`, `phrygian`, `lydian`, `mixolydian`, `aeolian`/`naturalMinor`, `locrian`, `harmonicMinor`, `melodicMinor`, `wholeTone`, `chromatic`, `octatonicHalfWhole`, `octatonicWholeHalf`, `augmentedScale`, `majorPentatonic`, `minorPentatonic`, `blues`. Or build from explicit degrees / intervals / named pitches:
```swift
let custom = try Scale(tonic: .c, intervals: [.unison, .majorSecond, .minorThird])
let set = try Scale(tonic: .c, pitches: [.named(.c, 4), .named(.e, 4), .named(.g, 4)])
```
### Queries
```swift
let cMajor = try Scale.major(.c)
cMajor.contains(.fSharp) // false (pitch-class membership)
cMajor.degree(of: .g) // ScaleDegree(index: 4, alteration: 0)
cMajor.degree(of: .fSharp) // ScaleDegree(index: 3, alteration: +1) ← raised 4th
cMajor.noteName(atDegree: 9) // E (wraps mod 7)
cMajor.pitch(atDegree: 2, octave: 4) // .named(.e, 4)
```
`degree(of:)` resolves exact spelling → enharmonic pitch-class → same letter → nearest pitch-class, carrying any chromatic `alteration` so non-scale pitches survive the round trip.
---
## Pitch collections
Order matters — a `PitchCollection` is a melodic cell, an atonal set, or a 12-tone row.
```swift
let cell = PitchCollection(pitches: [.named(.c, 4), .named(.e, 4), .named(.g, 4)])
cell.retrograde.pitches // G E C
try cell.transposedChromatic(by: .majorThird).pitches // E G♯ B (every pitch +M3)
try cell.inverted(around: .named(.c, 4)).pitches // C A♭3 F3 (mirror, spelled)
cell.octaveReduced.pitches // fold to one octave
```
### 12-tone rows
When a collection is twelve named pitches across all twelve pitch-classes, the row's own spelling defines a pitch-class → note-name map, so **every derived form stays spelling-consistent** with the prime row.
```swift
let row = PitchCollection(pitches: [
.named(.c, 4), .named(.dFlat, 4), .named(.d, 4), .named(.eFlat, 4),
.named(.e, 4), .named(.f, 4), .named(.gFlat, 4), .named(.g, 4),
.named(.aFlat, 4), .named(.a, 4), .named(.bFlat, 4), .named(.b, 4),
])
row.isToneRow // true
try row.toneRowInversion() // I0
try row.toneRowRetrograde() // R0
try row.toneRowTransposed(3) // T3 (pc + 3, spelled via the row's map → G♭ stays G♭)
try row.toneRowTransposedInversion(5) // T5I
let matrix = try row.toneRowMatrix() // [[NoteName]] 12×12 (top = prime, left = inversion)
```
---
## Diatonic vs. chromatic transposition
This is the distinction the toolkit exists to get right.
- **Chromatic** — `PitchCollection.transposedChromatic(by:_:)` moves every pitch by the *same spelled interval*.
- **Diatonic (modal)** — `Scale.transposeDiatonic(_:byDegrees:)` moves every pitch by the *same number of scale steps*, staying in the scale.
```swift
let cMajor = try Scale.major(.c)
let line = PitchCollection(pitches: [.named(.c, 4), .named(.d, 4), .named(.e, 4)])
try cMajor.transposeDiatonic(line, byDegrees: 2).pitches // E F G (in-scale thirds)
try line.transposedChromatic(by: .majorThird).pitches // E F♯ G♯ (three equal M3s)
```
### Scale-to-scale mapping
`PitchCollection.mapped(from:to:)` re-assigns each pitch by degree from one scale to another, carrying alteration and octave register.
```swift
let triad = PitchCollection(pitches: [.named(.c, 4), .named(.e, 4), .named(.g, 4)])
try triad.mapped(from: try Scale.major(.c), to: try Scale.major(.d)).pitches // D F♯ A
try triad.mapped(from: try Scale.major(.c), to: try Scale.major(.eFlat)).pitches // E♭ G B♭
try triad.mapped(from: try Scale.major(.c), to: try Scale.aeolian(.c)).pitches // C E♭ G (major→minor triad)
```
Degree-count mismatch (e.g. pentatonic → heptatonic) maps by index with wrap.
---
## Notation — feeding the Score / MusicXML pipeline
Theory output is `NoteName` / `Pitch`, which the **Score DSL** consumes directly. Build a transposed phrase, then export to MusicXML — the spellings survive the round trip (sharps stay sharp, `B♯` does not collapse to `C`).
```swift
// A phrase, transposed up a major third with correct spelling.
let phrase = PitchCollection(pitches: [.named(.c, 4), .named(.d, 4), .named(.a, 4)])
let up = try phrase.transposedChromatic(by: .majorThird) // E F♯ C♯
let score = Score(bpm: 120) {
Part("theory") {
for pitch in up.pitches {
Note(pitch, dur: .quarter) // Note(_ pitch: Pitch, dur:) takes .named directly
}
}
}
let xml = score.toMusicXMLString()
// E → <step>E</step>, F♯ → <step>F</step><alter>1</alter>, C♯ → <step>C</step><alter>1</alter>
// Round-trips losslessly:
let decoded = try Score.fromMusicXML(data: Data(xml.utf8))
```
Build a whole scale or a chord the same way:
```swift
let scale = try Scale.dorian(.d)
let part = Part("dorian") {
for i in 0..<scale.count {
Note(scale.pitch(atDegree: i, octave: 4), dur: .eighth)
}
}
let chordTriad = try Scale.major(.eFlat)
Chord([ // Chord(_ pitches: [Pitch], dur:)
chordTriad.pitch(atDegree: 0, octave: 4),
chordTriad.pitch(atDegree: 2, octave: 4),
chordTriad.pitch(atDegree: 4, octave: 4),
], dur: .half)
```
See `ScoreSystem` for the full notation DSL, and `docs/stdlib/` neighbours for generators.
---
## Synthesis — Hz and seconds from theory values
For audio, convert `Pitch` to frequency and `NoteDuration` to seconds, then feed Generator parameters.
**Pitch → frequency.** `Pitch.frequency` returns Hz (`Double?`, `nil` for rests / out-of-range). Quarter-tones and `.freq` pitches resolve to real Hz.
```swift
Pitch.named(.a, 4).frequency // 440.0
Pitch.named(.cQuarterSharp, 4).frequency // ≈ 269.29 Hz (C4 × 2^(0.5/12))
Pitch.midi(60).frequency // 261.63 Hz
// Map a whole scale to oscillator frequencies:
let freqs = try Scale.major(.a)
.degrees.enumerated()
.compactMap { Pitch.named($0.element, 4).frequency }
```
(`midiToHz(_:)` / `hzToMidi(_:)` in `LyrebirdMusicMath` cover the raw numeric conversions.)
**Duration → seconds.** `NoteDuration.beats` is in quarter-note beats (quarter = 1). Multiply by the seconds-per-beat for your tempo:
```swift
let bpm = 120.0
let secondsPerBeat = 60.0 / bpm
let eighthSeconds = NoteDuration.eighth.beats * secondsPerBeat // 0.5 × 0.5 = 0.25 s
let dottedQuarter = NoteDuration.quarter.dotted.beats * secondsPerBeat // 0.75 s
```
**Drive a Synthesizer.** Pass the frequency into a Generator graph:
```swift
final class Tone: SynthesizerBase {
let freq: Double
let amp: Double
init(freq: Double, amp: Double = 0.2) {
self.freq = freq
self.amp = amp
super.init()
}
override func build() {
let env = EnvelopeGen.Control(
envelope: Envelope(levels: [0, 1, 0], durations: [0.01, 0.4], curves: [2, -3])
)
let sig = OscSin.Audio(freq: freq) * env * amp
output(bus: 0, source: Pan2(input: sig, pan: 0))
doneAction = .freeEnclosing
}
}
let gSharp4 = try Pitch.named(.e, 4).transposed(by: .majorThird) // .named(.gSharp, 4)
if let hz = gSharp4.frequency {
try engine.add(Tone(freq: hz)) // G♯4 ≈ 415.30 Hz
}
```
**Sequence a collection over time** with a routine — convert each pitch to Hz, hold each for a duration:
```swift
let cell = try PitchCollection(pitches: [.named(.c, 4), .named(.e, 4), .named(.g, 4)])
.transposedChromatic(by: .perfectFifth) // G B D
let routine = LyrebirdRoutine { ctx in
ctx.tempo = 120.0
for pitch in cell.pitches {
guard let hz = pitch.frequency else { continue }
ctx.add(Tone(freq: hz))
try ctx.wait(beats: NoteDuration.quarter.beats) // 0.5 s at 120 BPM
}
}
routine.start(engine: engine)
```
Because the toolkit preserves spelling end-to-end, the **same theory objects** drive both the engraved score (correct accidentals in MusicXML) and the sounding synthesis (exact Hz) — no separate pitch model for notation vs. audio.
---
## Error handling
Operations throw rather than silently mis-spell:
| Error | When |
|---|---|
| `IntervalError.qualityNumberMismatch` | `.major` on a 5th, `.perfect` on a 3rd, etc. |
| `IntervalError.unrepresentableSpelling` | correct spelling needs an accidental beyond 𝄫 / 𝄪. |
| `IntervalError.quarterToneUnsupported` | transposing across a quarter-tone accidental (intervals are 12-TET). |
| `ScaleError.tonicMismatch` / `.nonNamedPitch` | bad `Scale` construction; diatonic / mapping on a `.midi` / `.freq` pitch. |
| `ToneRowError.notTwelveToneRow` | row operation on a collection that is not 12 distinct named pitch-classes. |
+1 -1
View File
@@ -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`
- SPM-only (open `Package.swift` in Xcode): `basic` (default), `demo`, `ui-demo`, `nrt`, `score`
- Xcode-project (ships `.xcodeproj` + `.xcworkspace`): `macos-ui-xcode`, `ios-ui`, `auv3`
```sh
+1 -1
View File
@@ -3,7 +3,7 @@
`MIDIClockFollower` estimates BPM from incoming MIDI Clock (0xF8) messages and drives a
`LyrebirdClock` to follow an external transport.
Ableton Link is deferred — see `docs/roadmap/ableton-link.md`.
Ableton Link sync is not planned; MIDI Clock follow is the supported external-transport path.
---
+1
View File
@@ -42,6 +42,7 @@ Swift-Package-only templates (lightweight; open `Package.swift` in Xcode for Swi
| `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 |
| `score` | `lyrebird new MyPiece --template score` | Builds a two-part `Score` with the DSL (Note/Rest/Chord/Tuplet/dynamics/articulations), exports `score.musicxml` (round-trip checked), and renders `score.caf` offline via `NRTDriver` |
Xcode-project templates (ship a real `.xcodeproj` for deliverables SwiftPM can't express — `.app` bundles, AUv3 extensions):
+1 -1
View File
@@ -30,7 +30,7 @@ All variants below are constructed by static factory methods on `Pattern<T>`. Ev
| Factory | Behaviour |
|---|---|
| `Pattern.sequence(_:repeats:)` | Cycle through array `repeats` times. `-1` infinite. |
| `Pattern.sequence(_:repeats:offset:)` | Cycle through array `repeats` times. `-1` infinite. `offset` shifts only the first pass — emission opens at `values[offset]` (wraps modulo count) and runs to the array end, then later cycles run full from index 0. |
| `Pattern.shuffle(_:repeats:seed:)` | Fisher-Yates permute once at init, then cycle. Same permutation replays on reset. (SC `Pshuf`) |
| `Pattern.nonRepeatingRandom(_:repeats:seed:)` | Random pick avoiding same *index* as previous. Documented index-vs-value caveat for duplicate-value pools. (SC `Pxrand`) |
| `Pattern.weightedRandom(_:weights:repeats:seed:)` | Pick proportional to weight. Init preconditions: equal count, finite non-negative weights, positive sum. (SC `Pwrand`) |
+1
View File
@@ -85,6 +85,7 @@ accumulator, PRNG state, biquad coefficients) inline.
| **Lyrebird UI View** | `public struct <Name>: View` with `@Observable` controller, `ScopeCapture` + `LyrebirdScopeView`, parameter knobs, play/stop button | Building a SwiftUI front-end for a `@UIParam`-annotated synth. Requires the LyrebirdUI module. |
| **Lyrebird Generator Test Suite** | `@Suite("…") struct <Name> { @Test … }` using `makeTestEngine` / `makeSynthGraph` / `advanceBlock` helpers | Adding a Swift Testing suite for a new Generator. Drop the file into `Tests/LyrebirdTests/` — the helpers are module-internal. |
| **Lyrebird NRT Render** | `main.swift` with a `SynthesizerBase` stub and an NRTDriver that renders the duration to disk | Building a standalone executable target that produces an offline audio file. Drop the file into the `Sources/<exec-target>/` directory of an `executableTarget`. |
| **Lyrebird Score** | `func make<Name>() -> Score` building a two-part Score with the DSL (Note/Rest/Chord/Tuplet/dynamics/articulations); doc comment shows `toMusicXMLString()` / `Score.fromMusicXML()` round-trip and `allEvents` iteration | Authoring a notated score in code and exporting it to MusicXML 4.0. Drop the file anywhere in a target that links `Lyrebird`. |
The UI templates (`Synthesizer (UI)` and `UI View`) add `import LyrebirdUI` and
compile cleanly in projects with both `Lyrebird` and `LyrebirdUI` as