1.0.0 release

This commit is contained in:
2026-06-01 18:27:40 -07:00
parent b1ab0f102c
commit 1f20fcab20
1151 changed files with 230703 additions and 14 deletions
+522
View File
@@ -0,0 +1,522 @@
# Working Order
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`.
## Phase Completion Checklist
Before merging any phase branch to `main`:
1. All tests pass (`swift test`)
2. Run `/lyrebird_review` — no blocking findings
3. Fix any blocking issues found; re-run `/lyrebird_review` until clean
4. Merge to `main` with a `--no-ff` merge commit
5. `/lyrebird_review` updates `MEMORY.md` automatically on a clean pass
6. Move the completed phase section from this file into `docs/01-completed-working-order.md` (append at the bottom) and update the summary table below
## Generator Authoring Rules
See `docs/protocols/writing-generators.md` for the full guide. Quick checklist:
- No RT allocation in `_computeSamples` — pre-allocate in `init`
- Open `_computeSamples` with `_checkCount(count)` (inherited from `GeneratorBase`)
- Inherit `GeneratorBase` — do NOT redeclare `_segmentSerial`/`_cachedResult`/`_subBlockBuffer`/`_result`
- `ControlGenerator.Control.init` must call `_setupSubBlockBuffer()` (or `_setupSubBlockBuffer(channels:N)` for multi-channel)
- Route `floatValue` through `calculatedSamples(blockSize)` for AudioGenerator; return scalar target directly for ControlGenerator
- Add `calculatedSamples` bypass override if the generator has per-audio-block state (phase accumulators, gain smoothers, buffer positions) — see Out.Control as the canonical pattern
- Apply `denormalsToZero()` to all IIR feedback state after each write
- Power-of-two table sizes enforced by `precondition`
---
## Completed Phases (summary)
Full details in `docs/01-completed-working-order.md`.
| Phase | Title | Tests at completion |
|-------|-------|---------------------|
| 1 | SynthesisEngine + Core Audio | 28 |
| 1b | Scheduling + NRT Rendering | — |
| 2 | Bus System | — |
| 3 | Generator Protocol | — |
| 4 | In / Out Generators | — |
| 5 | Synthesizer Protocol + Node Tree | — |
| 6 | Parameter System | 192 |
| 7 | REPL + LineNoise | — |
| 8 | Built-in Generator Stdlib | 319 |
| 8b | Buffer System + Shared Tables | 345 |
| 9 | lyrebird CLI + Project System | 416 |
| 10 | Swift Testing Suite | 447 |
| 11 | Interpret-then-Compile Polish | 447 |
| 12 | GUI System (LyrebirdUI) | 474 |
| 13 | Generator Fan-out / Shared Signal Semantics | 483 |
| 14 | Denormal Handling | 494 |
| 15 | AIFF / WAV File I/O for LyrebirdBuffer | 511 |
| 16 | Multichannel `LyrebirdBuffer` | 527 |
| 17 | Table-Lookup Generator Polish | 540 |
| 18 | Generator Authoring Guide | 540 |
| 19 | Bus / Output Ergonomics | 549 |
| 20 | LyrebirdBufferFileIO Channel-Count Validation | 556 |
| — | Operator overloads + ConstantGeneratorInput | 570 |
| 21 | Sample Rate Mismatch Detection | 671 |
| 22 | Audio-Rate Input Modulation (FM / AM / PM) | 593 |
| 23 | Full RBJ Cookbook Filters | 671 |
| 24 | Butterworth Filters | 692 |
| 25 | Resonating, Comb, and Allpass Filters | 752 |
| 26 | Multi-Channel Expansion (MCE) | 671 |
| 27 | Control-Rate Generator Variants | 805 |
| 28 | `ParameterNode` + `@LiveParam` | 826 |
| 29 | RecordBuf + PlayBuf (Audio + Control variants) | 872 | ← archived |
| 29b | PlayBuf Reverse Playback | 879 | ← archived |
| 30 | LyrebirdRoutine + LyrebirdTask + Pattern | 905 |
| 31 | FFT / IFFT Spectral Infrastructure | 930 |
| 32 | Granular Synthesis (BufferGrain, SineGrain, FMGrain, InputGrain) | 973 |
| 33 | Panning Suite (PanN, Pan4, AmbiEncoder1, AmbiDecoder1) | 1016 |
| 33b | Accelerate / vDSP Optimization | 1019 |
| 33b-fixes | RT safety + vDSP correctness fixes | 1038 |
| — | RoutineContext beat API | 1046 |
| — | EnvelopeGen.Control + _Base fixes | 1060 |
| 34 | Multi-Core Support (ParallelGroup) | 1078 |
| 36 | LyrebirdClock | 1092 |
| 37 | MIDI (Language-Side) | 1146 |
| 38 | OSC (Language-Side) | 1146 |
| 39 | Demand-Rate Generators | 1174 |
| 40 | Engine CPU Statistics + LyrebirdStatusView | 1180 |
| 41 | Stereo Scope + Pan (ScopeCapture / LyrebirdScopeView) | 1187 |
| 42 | TriggerListener (RT→Language Trigger Infrastructure) | — |
| 43 | SendTrigger Generators + NRT Support | 1238 |
| — | Envelope.releaseNode + EnvelopeGen.gate (gated ADSR hold) | 1264 |
| — | Envelope.loopNode (single-segment gate-controlled loop; _released flag) | 1271 |
| — | EnvelopeCurve renames (.sin→.sine/.exp→.exponential); digital osc for sine/welch | 1281 |
| — | EnvelopePoll.Audio/Control — stateless valueAtTime lookup; audio-rate time input | 1293 |
| 44 | Runtime Envelope Swap (EnvelopePacket + setEnvelope) | 1300 |
| 45 | LyrebirdEnvelopeView (SwiftUI envelope shape plotter) | 1320 |
| iOS-1 | iOSAudioDriver (RemoteIO); CoreAudioDriver `#if os(macOS)` guard | 1320 |
| iOS-2 | Package.swift `.iOS(.v18)`; AVFoundation linker; DenormalUtils verified | 1320 |
| iOS-3 | LyrebirdWindow `#if os(macOS)`; PlatformColors for ParameterKnob/XY | 1320 |
| iOS-4 | LyrebirdiOSDemo Xcode project; workspace entry; correct session rate init | 1320 |
| — | LyrebirdMusicMath: free functions, midiToHz/hzToMidi, dB/amp/power, linToExp, equalPowerFade | 1369 |
| 47 | Dynamics Generators (AmplitudeFollower, FreqTracker, LookAheadLimiter, Compressor, Expander) | 1404 |
| 48 | ChannelSelect — inline channel extraction ([n] subscript on all generators) | 1420 |
| 49 | Bus Allocator — AudioBus/ControlBus value types + BusAllocator on SynthesisEngine | 1434 |
| 49b | In.Audio / In.Control multi-channel — static channels param, AudioBus passthrough | 1444 |
| 50 | Group Semantics + Node Positioning — release/free lifecycle, NodePosition, addBefore/addAfter | 1472 |
| 51 | DiskIn.Audio + DiskOut.Audio — streaming soundfile I/O (double-buffer + ring-buffer) | 1472 |
| 46 | NRTDriver soundfile input — inputURL + inputStartOffset; ExtAudioFile SR conversion | 1472 |
| 52 | Math generators — Tanh/Pow/Clip/Fold/Wrap/SoftClip/LinLin/LinExp/ExpLin/ExpExp + unary/binary (Abs/Sign/Floor/Ceil/Round/Sqrt/Reciprocal/Log/Exp/Min/Max); Bipolar+UnipolarMappingGenerator | 1547 |
| 53 | FreeVerb — stereo reverb (Jezar Freeverb); 8 comb + 4 allpass per channel; .left/.right aliases; DocC Reverbs topic | 1555 |
| 54 | GVerb — Griesinger algorithmic stereo reverb (SC-faithful rewrite); FDN+Hadamard 4-line network; tap-delay early reflections; 3+3 post-sum allpass diffusers; dryLevel param; .left/.right aliases | 2507 |
| — | Control-rate sub-blocking (controlRateConsiderations): GeneratorBase, ControlGenerator.calculatedSamples sub-block loop, 11 .Control bypass overrides, phase-advancement uses count | 1618 |
| — | controlRateConsiderations fast-follow: _swapSerial gate prevents mid-block EnvelopePacket drain in sub-block mode; defensive channel zero-fill; fanOutCache + subBlockSwap tests; SynthesisEngine driverSuggestion capture; doc callouts | 1619 |
| 55 | Noise Family (Spectral-Colour + Event): xorshift64NextRaw split; PinkNoise/BrownNoise/GrayNoise/ClipNoise/Dust/Dust2 (Audio+Control each); bypass guards on all full-bandwidth Control variants | 1715 |
| 56 | Noise Family (Chaotic + Smooth): Crackle (2-pole chaotic map, bypass guard) + LFCurveNoise (SC LFNoise2 parabolic interp); floatValue fan-out cache fix; PinkNoise b5 sign fix; GrayNoise bitPattern fix | 1747 |
| 57 | Distribution Library + Standalone Distribution Noise Generators: DistributionKind enum; DistributionSampling math (Marsaglia-Tsang gamma, Box-Muller gauss, Knuth Poisson, etc.); UniformNoise/LpRandNoise/HpRandNoise/MeanRandNoise/GaussNoise/ExpRandNoise/ExponentialNoise/GammaNoise/LaplaceNoise/ALaplaceNoise/HcosNoise/LogisticNoise/PoissonNoise/ArcsinNoise/BetaRandNoise/CauchyNoise (Audio+Control each) | 1877 |
| 58 | TemporalStream language side: TemporalParameter (.value/.envelope/.closure); TemporalAlgorithm protocol; TemporalStream (wall-clock + beat-clock timing); TemporalSequence/TemporalRandomPick/TemporalTendency/TemporalBrownian/TemporalClosure algorithms; 163 tests | 1910 |
| — | DSeq→DSequence, DRand→DRandom rename for verbosity | 1910 |
| 59 | TimedDemand synthesis side: RTTemporalParameter (Sendable, no closure); TimedDemandGenerator protocol; TimedDemand.Audio/Control (sample-accurate currentTime+i elapsed); DTemporalTendency (16 distributions); DTemporalBrownian (RT walk, auto-centring) | 1950 |
| 60 | Distribution Preview: LyrebirdScatterView (Canvas scatter plot, degenerate-range guard); DemandGenerator.samples(count:); TimedDemandGenerator.samples(count:timespan:); TemporalStream.collect(_:); TemporalDemand.md Previewing Distributions section | 1959 |
| 61 | PitchShift.Audio — granular live-input pitch shifter; circular capture buffer; auto hop management; pitchRatio [0.25, 4.0]; mono out + MCE | 1978 |
| 62 | SpectralPitchShift — phase-vocoder SpectralProcessor; true-frequency bin tracking; magnitude remapping by ratio; synthesis phase accumulator; out-of-range bins zeroed | 1978 |
| 63 | Granular Modulation Upgrade + TimeStretch — BufferGrain/InputGrain/SineGrain/FMGrain ValidGeneratorInput promotion; rate→pitchRatio rename; TimeStretch.Audio fixed-hop granular time-stretcher | 1995 |
| — | SineBufferGrain→SineGrain, FMBufferGrain→FMGrain, InputBufferGrain→InputGrain rename (drop "Buf" suffix from non-buffer granular generators) | 1995 |
| 64 | Spectral Frame Buffer — SpectralFrameBuffer (framesWritten/interpolatePhases/trimmed) + SpectralRecordBuffer + SpectralPlayBuffer (startPos) + SpectralBufferRead (normalized position) + .lbsf file I/O | 2031 |
| 65 | PlayBuf→PlayBuffer + RecordBuf→RecordBuffer rename; @available deprecated typealiases; docs + agent file updated | 2031 |
| 66 | Buffer Metadata + Duration Helpers | 2040 |
| 67 | BufferRead — normalized-position random-access buffer reader; Audio+Control; multi-channel; lyrebirdBufferRead helper; GeneratorEnum | 2053 |
| 68 | TimeStretch Multi-Channel + Remove Pan — N-channel output matching buffer.channelCount; pan/panSpread removed | 2074 |
| 69 | LyrebirdBuffer Wavetable Generation Utilities — fill(partials:), fillChebyshev, fillWindow, fillWaveshaper, fillBandLimited, fillPartials, fillInharmonicPartials, WavetableSet | 2119 |
| 70 | Ring Modulator Variants — Ring1/Ring2/Ring3/Ring4 Audio+Control binary math generators; SC AM/RM family | 2127 |
| 71 | Band-Limited Oscillators (BLEP) — OscSawtooth / OscSquare / OscTriangle / OscDutyCycle Audio+Control; polyBLEP/BLAMP correction; audio-rate PWM | 2174 |
| 71b | Non-Band-Limited LFO Oscillators — LFSawtooth / LFSquare / LFTriangle / LFDutyCycle Audio+Control; raw piecewise math; audio-rate PWM on LFDutyCycle | 2232 |
| 72 | Euclidean Rhythm + Markov Chain Patterns — euclideanRhythm(pulses:steps:rotation:)->Pattern<Bool>; TemporalMarkov new TemporalAlgorithm | 2267 |
| 73 | Jitter / Triggered Random Generators — TriggeredRandom.Control + Jitter.Control | 2289 |
| 74 | Gendy Stochastic Synthesis — Gendy1/2/3 Audio+Control; linear/cubic/fixed-dur breakpoint state machines; all 16 DistributionKind variants | 2364 |
| 75 | Spectral Feature Extraction — SpectralCentroid/Flatness/Spread/Flux/Entropy/Rolloff (Control-only, bypass sub-block loop) | 2399 |
| 75b | Live Parameter Refactor — `@LiveParam` / `@UIParam` Mirror auto-registration; `ParameterNode` + `UIParamNode` → `ControlGenerator`; `updateParameter` direct atomic; deleted `declareParameter` × 3, `ControlParameter`, `ConstantParameter`, `String: ValidGeneratorInput`, SPSC param queue | 2377 |
| 76 | State Variable Filter (SVF) — Chamberlin recurrence, 4-channel output (LP/HP/BP/Notch) from one coefficient set; `freq` + `q` ValidGeneratorInput; SVF.Control bypasses sub-block loop (audio-input IIR must advance once per block) | 2403 |
| 77 | WavetableMorph Oscillator — Audio + Control; `[LyrebirdBuffer]` + `position: ValidGeneratorInput` [0, N-1] per-sample linear interp between adjacent tables; freq + phase as ValidGeneratorInput; TableInterpolation .none/.linear/.cubic for inner reads | 2426 |
| 77-review-cleanup | Scalar `ValidGeneratorInput` intra-block ramp fixes — `_xIsGenerator` guards + per-sample paths in pan family / dynamics / LF*Noise.Audio / DelayLineFeedback; new `lastGeneratorSampleOrFloat` helper; WavetableMorph dead `_tableCountFloat` removed; rmsValue test helper extracted | 2448 |
| 78 | Karplus-Strong / Waveguide String — `KarplusStrong.Audio` (trigger-based) + `GatedKarplusStrong.Audio` (continuous gate); `exciter` + `trigger`/`gate` + `freq` + `feedback` + `coef` (one-pole, SC formula) + `sampleRate` + `maxDelayTime`; fractional delay with linear interp; `_refillRemaining` gradual fill; Audio-only | 2471 |
| 79 | Flanger / Chorus / Phaser — `Flanger.Audio` (sine-LFO modulated delay + feedback), `Chorus.Audio` (2-tap stereo, LFOs 180° apart, `.left`/`.right`), `Phaser.Audio` (4/6/8 cascaded first-order AP stages, LFO sweeps coefficient); all Audio-only, ValidGeneratorInput for all mod params | 2506 |
| 80 | FrequencyShifter — `FrequencyShifter.Audio` SSB Weaver method; two 4-stage IIR all-pass chains (90° Hilbert approx); quadrature oscillator at `shiftHz`; inharmonic 2-ch output (`.upper`/`.lower`); `shiftHz: ValidGeneratorInput`; Audio-only | 2520 |
| 81 | Polyphonic Voice Allocator — `VoicePool<S: SynthesizerBase>`; noteOn/noteOff/allNotesOff; `.oldest`/`.roundRobin`/`.quietest`/`.lowestAmplitude` steal strategies; `.quietest` reads `@LiveParam` amp via Mirror, falls back to `.oldest` | 2541 |
| 82 | Step Sequencer — `StepSequencer` language-side beat sequencer driven by `LyrebirdClock`; `SequencerStep` with pitch/velocity/gate/probability/duration/parameterLocks; rests; NSLock-protected callbacks; `Atomic<Int>` currentStep; idle-burst-fire prevention | 2563 |
| 83 | AdditiveSynthesizer — `AdditiveSynthesizer.Audio` resynthesizes `SpectralFrameBuffer` as N sines via vDSP (vadd phases + vvsinf + dotpr); position `ValidGeneratorInput`; maxPartials cap; anti-aliasing; lazy phaseIncrement init | 2583 |
| 84 | FormantGrain (FOF) — `FormantGrain.Audio` IRCAM CHANT FOF formant-grain synthesizer; sine² rise + exponential decay; per-pulse octaviation sign-flip; pool-overflow steal-oldest policy; glottalFreq clamped to ≤ sampleRate; unconditional phase wrap via truncatingRemainder; new `Lyrebird.docc/Generators/GranularSynthesis.md` topic covering the family | 2597 |
| 85 | Spectrum / Spectrogram View — `SpectrumCapture` (SpectralProcessor, ping-pong double-buffer) + `LyrebirdSpectrumView` (Canvas log-frequency X / dB Y, optional waterfall spectrogram) | 2606 |
| 85.5 | Smoothing Filters — `Lag`/`LagUpDown`/`Lag2`/`Lag2UpDown`/`Decay`/`Decay2`/`LeakDC` (Audio+Control each); shared `lagCoeff()` helper; Control variants use control rate for coefficient | 2677 |
| 86.75a | Classic SC PV ports — `SpectralPartialFilter` / `SpectralNoiseFilter` (`ClassifierMode.frequency`/`.phase` multi-frame stability classifiers, ring history with warmup), `SpectralMagnitudeMap` (`LyrebirdBuffer` transfer function on normalized mags), `SpectralHarmonicEnhance` (1/i-falloff harmonic series, Double index arithmetic for large fftSize). Atomic<Float>/<Bool> params, no shared base class | 2694 |
| LyrebirdBufferUpdates | `LyrebirdBuffer.setValue(_:at:)` / `setValue(_:frame:channel:)` / `setRangeValues(_:startingAt:)` — live language-side parameter writes safe under concurrent block-rate RT reads. NSLock serialises lang writers; RT snapshots once per block, relies on hw-atomic 8-byte aligned `Double` stores. `invalidate()` takes the same lock | 2705 |
| 86.75b | Classic SC PV ports — `SpectralBinDelay` (per-bin delay + feedback ring; `LyrebirdBuffer` per-bin parameter snapshot per hop), `SpectralCrossMap` (dual-FFT magnitude masking via new `SpectralProcessor2` protocol; bandpass / bandreject continuous mode; freeze hold), `LyrebirdUI.MultiSlider` (N-column vertical slider row writing into a `LyrebirdBuffer`) | 2720 |
| 87 | `ResonatorBank.Audio` — Klank-style parallel two-pole (Ringz) resonator bank driven from a 3-channel `LyrebirdBuffer` of `[freq, decay, amp]` triplets. Coefficients recomputed once per audio block; per-sample inner loop vectorised across the bank via `vDSP_vsmulD`/`vmulD`/`vsubD` + `vDSP_sveD`. Audio-only; mono summed output | 2783 |
| MCE-A | Channel-aware `BinaryOpGenerator` + `outputChannelCount` on Generator protocol — `+ - * /` between any operands now respects channel shape: `1×N`/`N×1` mono-broadcast, `N×N` element-wise, `N×M` with both > 1 and N ≠ M traps at init. ~17 multi-row generators override `outputChannelCount`. `mul:`/`add:` channel-0-only asymmetry preserved and documented loudly | 2803 |
| MCE-B | `GeneratorArray op N-row-generator` precondition trap — element-wise GeneratorArray operators now refuse multi-row other operand (silent-drop fix); routed through `_generatorArrayCheckOtherOperandMono` helper. `GeneratorArray.init` left permissive (existing AmbiDecoder1 patterns rely on row-0-only silent-drop) | 2804 |
| 88 | `VectorOscillator.Audio` — 4-corner XY bilinear-blend wavetable oscillator; freq/x/y/phase all ValidGeneratorInput. Shared `OscillatorTableReadHelpers.swift` (per-mode `oscillatorTableReadNone/Linear/Cubic` + `oscillatorTableRead` dispatcher) replaces fileprivate copies in OscTable + WavetableMorph; FP-boundary-safe `% tableSize` on base index. Silence-path `_mulAdd.applyIfNeeded` propagated to OscTable.Audio + WavetableMorph.Audio + VectorOscillator.Audio. Audio-only; .Control + GeneratorEnum + UI demo deferred to Phase 88b | 2828 |
| 88b | `VectorOscillator.Control` (matches WavetableMorph.Control semantics — Generator inputs read first sample, ramped output via `fillRampedResult`, `_setupSubBlockBuffer()`) + `GeneratorEnum` conformance + `VectorOscillatorUI` demo (macOS + iOS): synthesizer with `@UIParam x/y/frequency/amplitude` and four built-in wavetables (sine, 16-partial saw, triangle, Hanning), `VectorOscillatorView` using existing `LyrebirdUI.ParameterXY` for X/Y, `AppDelegate` switched to `enum Demo { case vector, binDelay, sineTone }` selector defaulted to `.vector` | 2837 |
| 89 | `SpatialDistance.Audio` — physically-plausible source-distance model: `1/distance` amplitude (clamped at `referenceDistance`), one-pole air-absorption lowpass with cutoff ∝ `(referenceDistance/distance)²`, velocity-driven Doppler via fractional read-rate `(1 − velocity/speedOfSound)` clamped to `[0.25, 4.0]`. All params `ValidGeneratorInput`. Audio-only (no GeneratorEnum); circular delay buffer pre-allocated from `maxDelayTime`; one-entry cutoff cache skips `exp()` for scalar distance | 2849 |
| 89.5 | `SpringReverb.Audio` (Schroeder spring tank — 8 cascaded all-pass dispersion stages in feedback loop with one-pole HF damping; mono-out by default, optional 2-tank stereo via `stereo: Bool` flag with detuned right-tank all-pass lengths) + `PlateReverb.Audio` (Dattorro 1997 figure-of-eight EMT 140 model — pre-delay → bandwidth LP → 4 input diffusers → cross-coupled tank with modulated AP + delay + damping + decay + AP + delay; native stereo mono-in/2-row out, `.left`/`.right` aliases, 7 Dattorro Table 1 taps per channel scaled from 29761 Hz reference). Both Audio-only, no `.Control`, no GeneratorEnum. All Dattorro/Schroeder coefficients in file-private named constants. `denormalsToZero` on every IIR feedback state write | 2872 |
| 90 | STK Instrument Models — `BowedString.Audio` (Smith/Cook split-waveguide, two delay lines + bridge LP + Cook friction table), `Flute.Audio` (Cook slide flute, bore+jet delay lines + cubic jet nonlinearity + breath noise), `Clarinet.Audio` (Cook single-reed cylindrical bore, half-wavelength delay + sign-inverted reflection + reed table + breath noise). All Audio-only, no `.Control`, no GeneratorEnum (consistent with Phases 78–80 precedent). `xorshift64Next` shared PRNG for Flute/Clarinet. `denormalsToZero` on every delay write. `PhysicalModels.md` DocC topic. | 2902 |
| 91 | Oversampling primitives — `HalfbandUpsampler2x` / `HalfbandDownsampler2x` (polyphase 2×) + `HalfbandUpsampler4x` / `HalfbandDownsampler4x` (cascaded 4×) as RT-safe public value types in `Sources/Lyrebird/Oversampling/`. Shared 23-tap symmetric Type-1 linear-phase Hamming-windowed sinc halfband FIR (`HalfbandFIR.swift`); centre tap held at exactly `0.5`, six folded paired taps normalised so total filter DC gain = `1.0` exactly; group delay 11 samples at upsampled rate. All state pre-allocated in `init()`; `process(_:)` / `reset()` allocation-free. New `Oversampling.md` DocC topic. Replaces the original "wrapper Generator" framing — sub-rate child Generators would break bus / fan-out cache invariants and the helper-struct shape is what Phase 92 Moog ladder actually wants. | 2921 |
| 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 |
| 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 |
| 103 | Runtime Source-Swap for `@LiveParam` Slots — `synth.$freq.source = SineOsc.Control(...)` replaces the generator wired into a parameter slot without stopping the synth. RT-safe (no allocation, no locks, no ARC retain/release on the audio thread) via `SourcePacket` carrying `Unmanaged<AnyObject>` over per-parameter `ParameterSourceQueue` (SPSC, capacity 4). Engine-wide `parameterSourceKillQueue` (SPSC, capacity 256) holds old slots until the main-thread drain (hooked into the existing background timer) releases them; overflow degrades gracefully. Crossfade-N-blocks soft swap (mid-block-snapshot mix; scalar↔generator transitions handled; mid-crossfade swap kills in-progress old slot). UIParamNode parity via `calculatedSamples` forwarding. KeyPath approach rejected due to Swift 6 generic-on-open-class constraints; `synth.setSource(synth.$freq, to: lfo)` taking a `ParameterNode` directly is the secondary API. Two review passes — pass 1 caught `as?` on RT path (replaced with class-to-class-protocol `as!`) and `UIParamNode` missing `calculatedSamples` override (would have silently bypassed source-swap pipeline). 69 new tests across 5 files including end-to-end integration through a running engine. | 3703 |
| 104d | AUv3 aux output + sidechain input — Multi-bus extension on top of 104a/b/c. New `LyrebirdAUBusSpec` value type (name + channelCount). Two new `open class var` hooks on `LyrebirdAudioUnit`: `lyrebirdOutputBusses` + `lyrebirdInputBusses` returning `[LyrebirdAUBusSpec]`. Defaults derive from existing single-bus `lyrebirdOutputChannels` / `lyrebirdInputChannels` so single-bus subclasses (LyrebirdFM, every 104a-c demo) keep working unchanged. Init builds N `AUAudioUnitBus` per spec array, sums channels for engine init, builds AU-bus-to-engine-bus offset maps (`auOutputBusOffsets` / `auInputBusOffsets` now stored on `SynthesisEngine` as `public internal(set) var`). `internalRenderBlock` closure captures `outputBusNumber` and passes through to `AUv3Driver.render(outputBusNumber:...)`. Driver gains `configureBusMap(outputBusChannelCounts:inputBusChannelCounts:)` called by `allocateRenderResources` before engine.start; per-output-bus `AUv3RingBuffer`s replace single ring; per-input-bus host ABL + Float backing; `_fillInputStagingFromHost` iterates input busses and pulls each via `AURenderPullInputBlock(...,inputBusNumber:...)`. New `AUv3RingBuffer.write(fromAudioBuses:sourceBusOffset:channelCount:count:)` slices engine.audioBuses per bus. `AUInput.Audio` gains `init(busIndex:channel:)` designated init; existing `init(channel:)` is now a convenience for `busIndex: 0`; compute consults `engine.auInputBusOffsets[busIndex] + channel`. Saturation guard in `_distributeEngineOutputToRings` resets a ring when its `availableToWrite < blockSize` — handles asymmetric host bus pulls (RT crash otherwise). Named `auv3RingBufferHeadroomFactor: Int = 2` constant for ring sizing. Two review passes: pass 1 caught RT crash on asymmetric pulls (saturation guard added) + missing render-loop sidechain coverage (added) + magic number `2` (named) + AUInput.Audio class-level doc gap (busIndex entry added); pass 2 clean. 9 new tests across 1 file (single-bus backcompat + multi-output exposes + multi-output engine layout + multi-output rendering routes independently + asymmetric pulls don't crash + two input busses exposed + sidechain offset map populated + AU input busIndex resolves + render-loop dispatches per-input-bus pullInputBlock). | 3788 |
| 114 | Generator boilerplate reduction (`_result` on `GeneratorBase`, `_checkCount(_:)`, default `floatValue` on `AudioGenerator`, `makeSampleBuffer`/`makeResultBuffer` factories) — eliminates ~1000 lines of mechanical boilerplate. Mono `AudioGenerator` is six lines instead of ~18; multi-row generators call `super.init(channels: N)` and drop manual `_result = …` allocation. `FreqTracker`, `FreeVerb`, `GVerb` got `outputChannelCount` overrides en route (silently mono-ized under operator arithmetic before). `GranularBase.init(seed:channels:)` lets stereo grain subclasses thread channel count through. ~150 generator files + 17 test files swept; `docs/protocols/writing-generators.md`, `Sources/Lyrebird/Lyrebird.docc/Generators/WritingGenerators.md`, and `CLAUDE.md` rewritten around the new patterns. Three review passes: passes 1 + 2 each caught doc-only regressions (class-level + protocol-level `GeneratorBase`/`Generator` summaries that still described post-super reassignment instead of `super.init(channels: N)`, plus the DocC article's five pre-Phase-114 code blocks); pass 3 clean. 3544 tests — same count as Phase 113. | 3544 |
| 148 | Flaky timing tests — three `TestBlockDriver` fixtures (`LyrebirdProcess`/`LyrebirdEventList`/`LyrebirdEventListRecording`) drove the engine at ~1.45 ms audio per 1 ms wall sleep ≈ barely realtime, so 1.5 s wall-clock test timeouts expired before envelope releases / process completions could fire `onFinished` (10–18 failures/run). Burst 32 `processBlock` calls per `Thread.sleep` (≈ 46× realtime). `_running` flag tightened to `Atomic<Bool>` (`Synchronization`) since 32 reads/iter widened the prior plain-`var` race; `_thread` stored property added for parity; sleep duration named (`wallSleepSeconds`). 10 consecutive `swift test --filter` runs clean. Misdiagnosed `FLAKY_TIMING_TESTS.md` census deleted — `releaseElapsed ≈ 62.3 × 10⁹ s` is a `Date.distantFuture`-class sentinel delta, not a mach-timebase bug. | 3610 |
| 149 | `lyrebird repl` fix — `swift package repl` was removed from the Swift toolchain; the CLI's `repl` subcommand + the `lyrebird>` interactive-shell `repl` command had been silently broken. `REPLLauncher` rewritten as a two-step invocation: `swift build` stages `.build/debug/Modules/Lyrebird.swiftmodule` + `libLyrebird.dylib` + `LyrebirdC.build/module.modulemap`, then `swift repl -I .build/debug/Modules -I .build/debug/LyrebirdC.build -L .build/debug -lLyrebird` (same flags SPM was computing internally). New `CLIError.buildFailed(exitCode:)` surfaced in both `InteractiveShell` and `LyrebirdCLIMain.runREPL`; `build(in:)` checks `process.terminationReason == .exit` first so signal kills surface as `exitCode: 1` rather than the raw signal number. WIP recovered from an orphaned agent worktree (`claude/infallible-boyd-97598a`) during a branch-cleanup sweep; 3-way applied cleanly to current `main`. Two-pass review — pass 1 caught missing test coverage on the `buildFailed` path + missing `-I`/`-L` flag-token assertions + signal-kill exit-code leak; pass 2 clean. | 3611 |
| 151 | AppKit-in-core layering fix + `lyrebird_review_cycle` cleanup. Two batches landed together. (1) **AppKit extraction**: new `open class MouseInputBridge` in core (default no-op returns 0.5/0.5/0.0) + `enum MouseInput` registry (`Atomic<UnsafeMutableRawPointer?>` typed pointer with `nonisolated(unsafe)`; **scalar accessors** `currentX`/`currentY`/`currentButton: Double` to avoid returning a class reference on RT path with ARC retain/release; `.relaxed` ordering with documented "install before `engine.start()`" happens-before fence; identity-check fast path on `install(_:)`; `NSLock` serialises install/uninstall; `uninstall()` is `@_spi(LyrebirdExtensions)`). `Mouse.swift` made cross-platform, all three `Mouse.*.Control` get `_calculatedSamplesBlockRate` bypass override. `MouseTracker` deleted from core, recreated in `LyrebirdUI` as `MouseInputBridge` subclass; `installShared()` asserts main thread, idempotent via `Atomic<Bool>` CAS gating both registry install + main-queue NSEvent monitor install. CLAUDE.md module-layering rule extended to ban `AppKit`/`UIKit` in core alongside `SwiftUI`. (2) **Review-cycle cleanup**: RT ARC fixes — SynthesisEngine input-bus copy uses index-loop with `inputSamples[ch].withUnsafeBufferPointer` (no inner-`[Float]` `let` retain) + `Swift.max(0, …)` clamp + `min(src.count, dst.count)` element-wise update (step-1 zero-fill makes tail-clear unnecessary); ScopeCapture `borrowing [[Float]]` parameter + subscript-borrow access; In.swift / AUInput.swift subscript-borrow rewrites with `precondition(offset + count <= buf.count)` bounds restoration; In.floatValue uses `withUnsafeBufferPointer` + `preconditionFailure(...)`. `LyrebirdAUPresetCodable.makeGenerator` lock-during-callback fix (dequeue-then-invoke). 4 granular `outputChannelCount: Int { granularChannelCount }` overrides on `BufferGrain`/`SineGrain`/`FMGrain`/`InputGrain` (silent stereo→mono regression under `* 0.5`), pinned by 4 binary-op tests. New `fillScalarRampedResult(into:previousOutputValue:target:count:)` helper in `MulAdd.swift` with 28-site `Math.Control` sweep; registered in CLAUDE.md "Shared RT-Safe Helpers" + writing-generators.md §13. New `DynamicsBase: GeneratorBase` shared base (`public class`, `static let dbAmplitudeScale`/`logFloor`/`softKneeParabolaFactor`, dual-location `/// - Parameters:` docs at base + `Compressor._Base` + `Expander._Base`); Compressor + Expander `_Base` collapsed to subclasses. `GeneratorEnum`-omitted comments on `SpectralChain`/`AdditiveSynthesizer`/`FormantGrain`. Sendable invariant comments on `ScorePlayer`/`MIDIClockFollower`/`SpectralFrameBuffer`. `MouseTracker` `deinit` removed (singleton process-lifetime). 8 review-fix passes total before clean. | 3697 |
| 152 | Pre-run engine reconfig + master gain / mute. `SynthesisEngine.sampleRate` / `numOutputChannels` / `numInputChannels` promoted from `let` to `public private(set) var` with three new setters (`setSampleRate(_:)` / `setNumOutputChannels(_:)` / `setNumInputChannels(_:)`) gated by `engineIsRunning` + `invalidValue` errors from new `SynthesisEngineConfigError`; identity writes short-circuit so bus-allocator free list doesn't churn. `setSampleRate` recomputes `_blockDurationNs`. Master output gain (`masterGain: Double` via `Atomic<UInt64>` bit-packed pattern, NaN/Inf-rejecting setter) + `isMuted: Bool` (`Atomic<Bool>`) live on the engine; end-of-`processBlock` per-channel `vDSP_vrampmul` linear ramp from `_previousAppliedGain` to live target avoids slider/mute clicks. Per-channel `var start = from` reseed each iteration because `vDSP_vrampmul` mutates `*start` in place — first review pass caught a regression where channels 1–3 flat-multiplied at target instead of ramping. `_previousAppliedGain` reseeded from live state in `start()` so stop→start cycle that ended muted doesn't replay stale ramp. `BusAllocator.hardwareAudioEnd` becomes mutable; new internal `_reconfigureHardwareReservation(numOutputChannels:numInputChannels:)` invalidates audio buses + remarks reservation under existing `NSLock`; control buses untouched. `_release` refactored to `honoursHardwareReservation: Bool` + read live `hardwareAudioEnd` inside lock — closes TOCTOU race. `LyrebirdEngineStatusView` gets Configuration section (sample-rate `Picker` 44.1k / 48k / 88.2k / 96k / 176.4k / 192k dynamically augmented with engine's current rate when non-stock; output/input channel `Stepper`s 1…32 / 0…32) gated `.disabled(isRunning)`, Output section (`Toggle("Mute")` + `Slider` in `-90…+12` dB paired with `TextField` formatted `%+.1f`, shared `masterGainDb` state). View `init` seeds every `@State` from live engine values; private `linearToDb` finite-floors at slider lower bound; `pushConfigToEngine` guards setter `.onChange` against running-while-mirroring drift. Two new test suites — `SynthesisEngineConfigTests` (3 setters × happy / running-throws / invalid / overflow + post-resize bus allocation lands after reservation) + `MasterGainMuteTests` (get/set round-trip, NaN/Inf rejection, end-of-block ramp math `expectedLast = to + (from - to) / n`, 4-channel ramp regression catching the `*start`-leak, mute zeros output, master gain doesn't touch input buses, stop→start regression for `_previousAppliedGain` reseed). Two review passes — pass 1 caught the `vDSP_vrampmul` channel-leakage bug + unnecessary atomic surface area + missing reseed-on-start + reservation invalidation gap; pass 2 clean. | 3727 |
| 153 | `LyrebirdEventList` fire-time tracking + body-closure backref. Two new public methods on `LyrebirdEventList` — `fireTimes(forEvent:) -> [Double]` (every offset at which the index fired; empty if not yet / out-of-range, no trap) + `firstFireTime(forEvent:) -> Double?` — filter `_timeline` rather than maintain a parallel index (timelines are short). New `private let _timelineLock = NSLock()` protects `_timeline` across five mutation sites (`_appendTimelineEntry` / `clearTimeline` / `setTimeline` / `loadTimeline` / the `_timeline.removeAll()` in `reset`) and both cross-thread readers; bare `var timeline` getter + `saveTimeline` / `playTimeline` remain unsynchronized (main-thread only, same thread as mutators) with a new `- Important:` doc note. `@unchecked Sendable` rationale at top of class rewritten to spell out the new locking protocol vs. main-only state. `LyrebirdProcess` gains `internal weak var _owningEventList: LyrebirdEventList?` set in the ownership-claim loop alongside `_eventListStartProvider` / `_eventListStartSampleTimeProvider`; weak so the process doesn't retain the list (list already retains the process via `_allProcesses`). `LyrebirdProcessContext` gains matching `internal weak var _owningEventList` + public `var eventList: LyrebirdEventList?` computed accessor; populated by `LyrebirdProcess._play` next to existing `context._eventListStart = _eventListStartProvider?()`. Body / `onRelease` closures can now write `ctx.eventList?.firstFireTime(forEvent: 0)` to cross-reference earlier events. Six new tests appended to existing `LyrebirdEventList` suite — empty-before-play, monotonic first-fire-time (origin == 0.0, indices 1+2 strictly monotone-positive), out-of-range / negative indices return empty/nil without trapping, multi-fire capture (two `play(eventIndex: 1)` → two distinct entries), context.eventList identity for owned + standalone, body closure reads `ctx.eventList?.firstFireTime(forEvent: 0) == 0.0` after a 10 ms sleep (synchronous `_appendTimelineEntry` inside `play(eventIndex:)` runs before the background task wakes). Two-pass review — pass 1 caught stale `@unchecked Sendable` rationale comment claiming `_timeline` was main-thread only (contradicting the new cross-thread accessors) + two `t1!` / `t2!` force-unwraps in `#expect` (CLAUDE.md prohibits force-unwraps in test code too); fixes used `try #require(...)` bindings; pass 2 clean. | 3727 |
| 163 | `midiToRatio` / `ratioToMidi` SC-style musical-math additions — surfaces existing `semitonesToRatio` / `ratioToSemitones` under SC-flavored names that mirror the `midiToHz` / `hzToMidi` pair, plus dot-syntax on `Double` (`12.0.midiToRatio` → `2.0`, `2.0.ratioToMidi` → `12.0`) and `Int` (`12.midiToRatio` → `2.0`, `(-12).midiToRatio` → `0.5`). Free functions (Double + Int overloads + array overload), `extension Double` / `extension Int` computed-var dot syntax (module-qualified `Lyrebird.midiToRatio(self)` inside the extensions to disambiguate from the property name), `Collection<Double>` / `Collection<Int>` methods paired with the existing `semitonesToRatio()` / `midiToHz()` collection methods. Driven by the MyPiece pitch-shift use case where the composer reasons in semitones but the generator expects a ratio (`PitchShift.Audio(pitchRatio: 7.midiToRatio)`). 14 new tests (octave check, round-trip, equivalence with `semitonesToRatio`, dot syntax Double + Int, array overloads, non-positive edge → `-.infinity` / NaN inherited from `log2`, three collection-method forms). Docs updated end-to-end (`docs/stdlib/generators.md`, `Sources/Lyrebird/Lyrebird.docc/Generators/MusicalMath.md`) with the SC convention paragraph + PitchShift call-site example. Two review passes — pass 1 flagged absent Collection-method symmetry + missing non-positive edge test (both non-blocking but addressed); pass 2 clean. | 3876 |
| 162 | `Envelope.releaseNode` aligned with SuperCollider's level-index convention — fixes a sharp edge where `Envelope([0,1,0], [2,2], releaseNode: 1)` was silently holding at the post-decay zero instead of the audible peak. Pre-Phase-162 `releaseNode` was a SEGMENT INDEX (hold value `levels[releaseNode + 1]`); now a LEVEL INDEX (hold value `levels[releaseNode]`) — matches SuperCollider's `Env` convention and the user's mental model. Valid range `[1, levels.count - 1]`. `EnvelopePacket` converts the public level index → internal segment index `releaseNode - 1` at packet construction so RT-side `EnvelopeGen` arithmetic stays untouched. `LyrebirdProcess.release(reltime:)` reads `_envelope.levels[releaseNodeIdx]` directly. `loopNode` (still a segment index) cross-validation is now `loopNode < releaseNode - 1`. 45 in-tree `releaseNode: N` literals bumped to `N + 1` to preserve their existing hold-level behavior; three doc examples whose values had been incorrect under both old and new semantics were also fixed end-to-end. View helper `_regionForSegment` already treated `releaseNode` as a release-region-start boundary equivalent to a level index, so no view code change. Tests: 4-test `LyrebirdProcessReleaseNodeHoldTest` regression suite (level-index identity for the exact MyPiece envelope, peak-hold under gate, out-of-range clamps to nil, final-level edge case); `StdlibGeneratorTests` assertions `env.releaseNode == N` updated to match bumped public values. Two review passes — pass 1 caught 11 stale comments + a force-unwrap; pass 2 caught 4 remaining stale comments. | 3862 |
| 161 | Auto-free synths on envelope done — surfaces SC-style "envelope done → node freed" semantics. New `Sources/Lyrebird/Envelopes/DoneActionWatchable.swift` protocol (`var needsFree: Bool { get }`, AnyObject-constrained) conformed by `EnvelopeGen.Audio` + `EnvelopeGen.Control`. `SynthesizerBase.autoFreeOnDone(_:)` opt-in inside `build()` designates a lifecycle probe; engine `add`/`schedule`/`remove` hooks register/unregister via a new `_AutoFreeEntry` registry. Single shared `DispatchSourceTimer` on `lyrebird.autofree` utility queue, 10 ms cadence (matches LyrebirdProcess watcher). Tick: snapshot registry, read atomic `needsFree`, remove fired entries from registry BEFORE dispatching `engine.remove(synth)` on main — closes a double-fire race that would otherwise corrupt `NodeTreeMirror` via duplicate `didRemove`. Dead-entry sweep handles both `synth == nil` and `probe == nil` so orphaned slots can't pin the timer. `engine.stop()` cancels the timer, clears entries, and barriers via `_autoFreeWorker.sync {}`; late-arriving `DispatchQueue.main.async` blocks guard `args.engine.isRunning` so a tick that escapes the barrier exits cleanly instead of enqueuing a stranded `.remove` event into `pendingQueue`. Cross-thread carrier `_AutoFreeRemovalArgs: @unchecked Sendable` mirrors the existing `ContextAddArgs` / `GroupFreeArgs` idiom. Five new tests (`Tests/LyrebirdTests/Envelopes/AutoFreeOnDoneTests.swift`): Control + Audio envelope auto-free, manual-remove-before-fire unregister, multiple staggered synths, and a no-opt-in synth that stays in the tree. Three review passes — pass 1 caught the double-remove race + orphaned-probe gap + ARC leak via late-firing main.async after stop(); pass 2 caught a narrow remaining window where main.async could land post-stop; pass 3 clean. | 3855 |
| 160 | Node tree visualization — main-thread `NodeTreeMirror` (`@Observable public final class`) that tracks every language-side `engine.add` / `schedule` / `remove` / `Group.free` and publishes an immutable `NodeTreeSnapshot` for SwiftUI. New `Sources/Lyrebird/NodeTree/NodeTreeSnapshot.swift` (value-type `Node` with `Kind = .synth(className:) / .group / .parallelGroup`, `ObjectIdentifier id`, head→tail children) and `NodeTreeMirror.swift` (internal mutable tree keyed by `ObjectIdentifier`; updated **after** a successful `pendingQueue.enqueue` so the mirror's view stays consistent with the RT thread's view; skipped on overflow). `SynthesisEngine` gains a `public let nodeTreeMirror` seeded after `rootGroup`/`mainGroup` install; hooks added to `schedule(_:at:)`, `schedule(_:after:)`, `add(_:position:)`, `remove(_:at:)`. `Group.free(engine:)` records the update post-enqueue; `Group.release(engine:)`'s background timer hops to `DispatchQueue.main.async` via a new `GroupFreeArgs: @unchecked Sendable` carrier (same `LyrebirdRoutineContext.Args` idiom) before invoking `free` so the mirror is never mutated from `.global(qos: .utility)`. `ParallelGroup.head` promoted `private → internal` so the mirror can walk the main-thread-populated children at engine.add time. New `LyrebirdNodeTreeView` in `LyrebirdUI`: recursive disclosure rows, head→tail order, depth-indented; per-row glyph (chevron / dot), display name, child-count badge for groups, 4-hex identity suffix derived from `ObjectIdentifier.hashValue` (stable across processes; no parsing of stdlib internal `String(describing:)` format). Header has Expand All / Collapse All; macOS `presentInWindow(...)`. `LyrebirdEngineStatusView` gains a collapsible Node Tree section above the Messages section + macOS Open Window button (close-and-reopen toggle). Eleven new `NodeTreeMirrorTests` + one regression test for child-remove preserving the parent group: initial snapshot shape, head/tail/before/after insertion, remove, nested groups, ParallelGroup head→tail walk on add, Group.free dropping subtree, displayName matches runtime class, `.before` fallback on unknown anchor. Three review passes — pass 1 caught a thread-safety violation (`Group.release` timer mutating mirror on utility queue) + multi-param init style + magic-number `6` + dead-code `timestamp` + redundant `@Bindable`; pass 2 caught inaccurate "before"-vs-"after" doc wording and a brittle `String(describing: ObjectIdentifier)` parse; pass 3 clean. | 3839 |
| 159 | `LyrebirdMessage` + `LyrebirdMessageView` — user-visible diagnostic channel kept strictly off the RT thread. New `Sources/Lyrebird/Diagnostics/` subfolder with `LyrebirdMessageTier` (info / warning / error), `LyrebirdMessage` (Identifiable Sendable struct), and `LyrebirdMessageCenter` (`@Observable @MainActor` singleton with bounded FIFO ring, default capacity 200). `LyrebirdMessageView` in `LyrebirdUI` provides a scrollable list with per-tier filter chips, count badges, Clear button, auto-scroll to newest, and macOS `presentInWindow(...)`. `LyrebirdMessageBanner` is a compact 3-line embed surfaced inside `LyrebirdEngineStatusView` as a collapsible Messages section between CPU metrics and configuration; the engine status view also offers an "Open Window" button on macOS. Shared tier-colour / short-label helpers live in `LyrebirdMessageHelpers.swift` per the `*Helpers.swift` rule. `print()` is intentionally untouched — library authors opt into `post()` for user-visible messages while keeping the developer-console stream. Eight new `@MainActor` tests cover post / tier routing / capacity pruning / capacity-reduction prune / clear / identity / capacity-1 / `allCases` ordering. Two review passes — pass 1 caught two-public-types-in-one-file and a cross-file helper not in a `*Helpers.swift`; both fixed plus a missing subfolder rationale added to CLAUDE.md. | 3827 |
| 154 | Explicit `: Type` annotations on every inferred `let` / `var` binding across `Sources/` (351 files, 6177 sites) and `Tests/` (223 files, 14249 sites) — Xcode type-checker speedup + readability win. Motivation: Xcode's expression checker is markedly slower on long, generic-heavy synth-graph expressions when intermediate locals are inferred; annotating the binding short-circuits that work. New `Tools/AnnotateBindings/annotate_bindings.py` drives `/usr/bin/sourcekit-lsp` over LSP JSON-RPC: per file, sends `textDocument/didOpen` then requests `textDocument/inlayHint` for the full range and applies the LSP `textEdits` that come back. Applied set filtered by a strict guard that rejects every Swift position where `: T` would not parse: (a) line-suffix must match `(let\|var\|for)\s+<identifier>$` (no intervening `{`, `[`, `(`, `,`); (b) tuple-pattern destructures (`let (a, b) = …`); (c) closure-header / capture-list (`{ ptr in`, `{ [weak self] in`); (d) `case let .foo(x)` / `catch let err …` pattern positions. Iterated four times during initial bring-up: closure-param hints `{ ptr: T in` broke 16 files → `_has_binding_keyword_before` added; `[weak self: T]` capture-list hints broke 1 file → stricter `<identifier>$` suffix added; `catch let err: T as P` broke `LiveSession.swift` → `_PATTERN_CONTEXT_RE` added. One manual fix: `LyrebirdScratchView.swift` had `let engineRefresh = Timer.publish(...).autoconnect()` annotated as `Publishers.Autoconnect<…>` (Combine type not imported in that file) → reverted to inferred form. One stale untracked `Sources/Lyrebird/Generators/UI/MouseTracker.swift` discovered (Phase 151 deleted this exact path; canonical lives in `Sources/LyrebirdUI/`) → removed manually. Tool ships unit-free using only Python stdlib; idempotent (running twice produces no second round of edits because every binding now ends in `<identifier>$:`). `swift build` clean; `swift test --no-parallel` → 3725 tests in 422 suites pass. Two-agent review (lyrebird_review_agent + caveman line sweep) clean — only non-blocking tool nits flagged (hardcoded `/usr/bin/sourcekit-lsp` path, hardcoded `REPO_ROOT` default, regex doesn't strip `//` comments, file URI not percent-encoded). | 3725 |
| 170 | `GeneratorInputProvider` as first-class `ValidGeneratorInput`. New `_resolvedInput() -> any ValidGeneratorInput` protocol requirement (default returns `self`; provider overrides to call `make()`). Every Generator init resolves `any ValidGeneratorInput` slots once at the top before storing / classifying — provider becomes transparently substitutable for any input source at the call site with no `.make()` boundary call. Helper-boundary resolution at 5 sites (`MulAddSpec` / `OscillatorBase` / `LFNoiseBase` / `NoiseBase` / `DynamicsBase`) covers many Generators automatically; sweep touches 139 Generator inits across all 22 generator-folder families. Provider's other `ValidGeneratorInput` accessors are `preconditionFailure` traps with a shared `_unresolvedProviderTrapMessage` string — unreachable in correct code, fire at first audio block if a provider somehow survives unresolved. Init-time only, non-RT, zero render-path overhead. End-to-end validated by MyPiece `TimeStretchMoment.build()` passing the provider directly to `AmbiEncoder1.azimuth`. One review-fix pass closed 7 blocking findings (3 missed-sweep files, 5 raw-param `is any Generator` classification sites that shadowed correctly-resolved inherited flags, 9 distribution-noise `_Base` inits, 1 helper-boundary policy violation in `AmbiEncoder1`, 1 stale docc example, 1 plan-doc snippet contradicting the skip-list); re-review clean. | 3961 |
| 181 | sampleOrZero sweep — third + final sub-phase of the 179-181 code-dedup follow-on. New `Sources/Lyrebird/GeneratorCore/HotLoopHelpers.swift` with `@inline(__always) @_spi(LyrebirdExtensions) public func sampleOrZero(_ p: UnsafePointer<Double>, _ i: Int, _ n: Int) -> Double` returning `i < n ? p[i] : 0`. Replaces per-sample `(i < n) ? srcP[i] : 0` boilerplate across 16 files (Filter family + Delay primitives). 4 files (DelayLine / DelayLineFeedback / CombFilter / AllpassFilter) had pre-existing `sampleAt(_ i:)` inline closures — deleted; call sites use `sampleOrZero` directly. CLAUDE.md + writing-generators.md §13 registered. Output bit-equivalent across 358 affected tests. Closes the 179-181 follow-on to the 174-178 perf sweep. | 358+ |
| 180 | Smoother step helpers — second sub-phase of the 179-181 code-dedup follow-on. Two related abstractions: (A) `onePoleLowPassStep(state:x:b1:comp:)` (`y = b1·state + comp·x`) + `leakyIntegratorStep(state:x:b1:)` (`y = x + b1·state`) in `FilterHelpers.swift` — applied across Lag / Lag2 / LagUpDown / Lag2UpDown / Decay / Decay2 inner loops. (B) new `Sources/Lyrebird/Generators/Dynamics/DynamicsHelpers.swift` with `AttackReleaseDirection` enum (`.rising` / `.falling`) + `attackReleaseSmoother(state:target:attackCoeff:attackComp:releaseCoeff:releaseComp:direction:)` — applied across AmplitudeFollower (`.rising`) + Compressor / Expander (`.falling`). All `@inline(__always)` — generated code identical to inlined form. Review-fix pass registered new helpers in CLAUDE.md + writing-generators.md §13 (mandatory per convention) + `import Foundation` → `import Darwin` for Dynamics family consistency. Output bit-equivalent across 124 affected tests. | 124+ |
| 179 | Filter helper consolidation — first sub-phase of the 179-181 code-dedup follow-on to the 174-178 perf sweep. Two new `@inline(__always)` module-internal helpers in `Generators/Filters/FilterHelpers.swift`: (A) `runTwoPoleResonatorScalarBlock` + `runTwoPoleResonatorInterpolatedBlock` — `RingingFilter.processScalar` / `processInterpolated` and `ResonatingFilter.processScalar` / `processInterpolated` bodies were byte-identical post-Phase-178 except for the coefficient function; both consumers now shrink to a coefficient closure + one-line helper calls (~80 lines deleted across the two files). (B) `sampleOrFallback(_:scalar:at:)` — per-sample coefficient lookup with zero-fallback past block end. Replaces 8 verbose sites in SecondOrderSection (5) + FirstOrderSection (3). Review-fix pass added 4 missing class-level `/// - Parameters:` doc blocks on touched Generator types (pre-existing gaps). Output bit-equivalent across 358 filter-suite tests. | 358 |
| 178 | IIR filter library sweep — final sub-phase of the 174-178 generator perf sweep. State hoist + raw-pointer hoist + once-per-block denormal flush pattern applied to 12 IIR filter files. Largest win: the two shared `processBlock` overloads on `BiquadState` + `FirstOrderState` in `RBJBiquad.swift` — amortised across every RBJ filter (LP/HP/BP/BPSkirt/AP/Notch/PeakingEQ/LowShelf/HighShelf) and every Butterworth filter (cascade biquad + first-order stages). Direct sweep also touched Lag/Lag2/LagUpDown/Lag2UpDown/LeakDC/Decay/Decay2/SecondOrderSection/FirstOrderSection/RingingFilter/ResonatingFilter. Skipped (deferred): MoogLadder / SVF / MuTronIII (nonlinear oversampled, tanh dominates), ResonatorBank (needs vDSP rather than state-hoist), Hilbert (small site). Two review-fix passes — first eliminated RT-path per-sample Optional dispatch (`srcP?[i] ?? 0`) across all 12 newly-touched files + 4 Phase-176 delay primitives for consistency; second pass cosmetic. Output bit-equivalent across 358 affected tests. | 358 |
| 177 | `DiskOut.Audio` perf pass — fused ring-write + `_result` passthrough into one per-sample loop (was two passes). Mono fast path with raw-pointer hoist on `_ringBuffer[0]` (Float) / `_result[0]` (Double) / input row via nested `withUnsafe(Mutable)BufferPointer`. Four sub-branches `(canWrite, hasInput)`: fused write+passthrough / silence-fill both / passthrough only / silence result only. `wHead` hoisted to local + single `_framesWritten.store` at end. Multi-channel path kept on bounds-checked subscripts. BG-thread + producer-consumer atomics handshake unchanged. One review-fix pass eliminated an RT-path `[]` allocation in the zero-input-row degenerate branch. Output bit-equivalent across 11 DiskIn/DiskOut + EventList recording integration tests. | 11+ |
| 176 | Delay-line primitives perf pass — DelayLine / DelayLineFeedback / CombFilter / AllpassFilter all already used PoT ring + bitmask wrap; new wins from state hoist (`writePos`, `allpassPrevOut`/`InputOut`/`OutputOut`), raw-pointer hoist via nested `withUnsafe(Mutable)BufferPointer` on buffer(s) + input + `_result[0]`, interpolation `switch` lifted out of per-sample loop into 4 explicit per-mode branches (`.none` / `.linear` / `.cubic` / `.allpass`), `cubicInterp` converted from instance method to `@inline(__always) fileprivate static`. One new `ringWrapStressManyWrapsOfShortRing` test covers DelayLine across ~172 ring wraps. Review-fix pass addressed magic-number `64` × 3 in new test + stale `cubicInterp` doc reference. Output bit-equivalent across 124 affected tests. | 124+ |
| 175 | Reverb family modulo elimination — branchless ring-buffer wrap replaces every per-sample `% size` operation across SpringReverb (2 sites), PlateReverb (9 sites), GVerb (12 sites). Non-PoT sizes cannot fold to a bitmask so original code emitted real `idiv` on the RT path. `denormalsToZero` preserved per CLAUDE.md convention (NRTDriver no thread-level FTZ). FreeVerb deferred — already branchless wraps, structural flat-buffer refactor needed for further wins. Three new `denormalLongTailStaysFinite` tests exercise many ring wraps with real DSP (initial draft was vacuous via fan-out cache; review-fix pass hoisted shared engine + per-block `advanceBlock`). Output bit-equivalent across 43 reverb-suite tests. | 43+ |
| 174 | Dynamics family perf pass — `AmplitudeFollower.Audio`, `Compressor.Audio`, `Expander.Audio`. State hoisted to locals across block (`_prevAmp` / `_prevGain`), once-per-block denormal flush, precompute `attackComp = 1.0 - attackCoeff` + `releaseComp = 1.0 - releaseCoeff` once per block, explicit if/else over attack/release branches replaces shared coefficient ternary, raw-pointer hoist on input + `_result[0]`, drop redundant `Double(...)` casts. Control variants untouched (one smoother step per audio block, not per sample). 3 new denormal-cadence tests (`denormalCadenceAmplitudeFollower` / `denormalCadenceCompressor` / `denormalCadenceExpander`). Review-fix pass strengthened the AmplitudeFollower test (initial draft was vacuous — pure zero input never left state). Output bit-equivalent across 41 dynamics-suite tests. | 41+ |
| 173 | Input Conditioning Optimization (three sub-phases on independent branches): **173a** `LookAheadLimiter` perf pass — drop the parallel `_peakRing` (deque payload now carries `(peak, expireAtPos)` inline), branchless wrap on all ring/deque indices (kills every per-sample `%` on non-PoT capacities), precompute `_attackComp = 1.0 - _releaseCoeff`, denormal flush moved from per-sample to once-per-block, zero-look-ahead fast path (no ring, no deque), all state hoisted to locals with single writeback. **173b** `RecordBuffer.Audio._computeSamples` perf rewrite — `LyrebirdBuffer._rawStorageMutable` hoisted once per block, all param arrays + `_result[0]` lifted to raw pointers via nested `withUnsafe(Mutable)BufferPointer`, fill + buffer-write passes fused into one per-sample loop, block-constant fast-path detection on first + last sample of `run` / `recLevel` / `preLevel` (`runStable` / `preBlockZero` / `recBlockOne` flags), mono branch dispatches between four tightened loops with the hottest case collapsing to a single mul-free store per sample. Channel-count validation moved from RT-path `precondition` to `Audio.init`. **173c** new `MixIn.Audio(buses: [AudioBus], mul:, add:)` in `Generators/BusIO/` (sums N non-contiguous audio buses channel-wise into one output — replaces `signal + In.Audio(bus:)` chains) + new `SumChannels.Audio(input:, mul:, add:)` in `Generators/Routing/` (collapses any multi-channel input to mono via row summation; mono passthrough; `vDSP_vaddD` chain for multi-channel). Both Audio-only (no Control variant, `GeneratorEnum` conformance intentionally omitted). 27 new tests across `LookAheadLimiter` (2), `RecordBuffer` (5), `MixIn.Audio` (7), `SumChannels.Audio` (7). Touched-suite filter runs 241+/241+ pass deterministically; full `swift test --no-parallel` hits the intermittent pre-existing `RTThreadIdentity.markingIsThreadLocalNotProcessGlobal` TLS-leak / `LyrebirdBuffer` retain-race flakes only. Driven by MyPiece's `MixAndRecordInputs` / `ConditionAndRecordInputs` synthesizers running hot at session start (mix N input buses → optional `LookAheadLimiter` → `RecordBuffer`). Each sub-phase shipped on its own branch with full `/lyrebird_review` cycle (173a + 173b each had two review-fix passes; 173c one review-fix pass). | 3985+ |
| 172 | `LyrebirdEventList` master-amp routing redesign + `ReplaceOut.Audio` / `ReplaceOut.Control` primitives + pre/post-master sub-groups. Triggered by a real-world MyPiece bug: `LyrebirdProcess._play` accepted a `procOutOverride` parameter and `LyrebirdEventList` used it to silently override every contained process's declared `procOut` to point at an internally-allocated `_masterBus`, silently breaking any process designed to feed a downstream effect chain (e.g. ambisonic-routed B-format → global decoder). Coupled fix: (1) `LyrebirdEventList.init` takes caller-supplied `bus: AudioBus` (replaces `masterChannels: Int`), default `AudioBus(index: 0, channelCount: 2)`; (2) `procOutOverride` parameter removed from `LyrebirdProcess._play` — dead code that was the original-bug mechanism; (3) new `ReplaceOut.Audio` / `ReplaceOut.Control` first-class overwrite bus-write primitives parallel to `Out` (`vDSP_vdpsp` direct to bus slice; engine plumb `setAudioBus` / `setControlBus`; `ScratchBuses.replace` overwrites this child's scratch slot inside `ParallelGroup` — does NOT scrub other siblings or pre-parallel content; `SynthGraph.setSamplesOnAudioBus` routes; `SynthesizerBase.replaceOutput(bus:source:)` helper); (4) `EventListMasterSynth` rewritten as `In.Audio(bus) * smoothAmp -> replaceOutput(bus)` (multi-channel via `BinaryOpGenerator` mono-broadcast); supersedes an interim "delta-add" trick (`bus += bus * (amp - 1)`); (5) new `preMasterGroup` / `postMasterGroup` sub-groups inside `_masterGroup` for caller-owned FX synths around the master amp, with `addPreMaster(_:)` / `addPostMaster(_:)` convenience helpers — synth lifetime bounded by EventList session (freed via `_masterGroup.free()` on teardown; fresh empty groups re-allocated for next session). Unblocks ambisonic decoders / bus-level limiters / master tap recorders. Sweep migrates `Tests/LyrebirdTests/Process/LyrebirdEventList{,Recording,Timeline,BuildFromFile}Tests.swift`, `ProcessSystem.md`, and MyPiece's `QuartetEventManager.createEventList()`. 19 new tests across `ReplaceOutAudioGeneratorTests.swift` (9) + `ReplaceOutControlGeneratorTests.swift` (4) + `LyrebirdEventListPrePostGroupTests.swift` (6). One `/lyrebird_review` cycle — blocking finding (two `@Suite` per file) fixed by splitting Audio + Control suites; non-blocking nits addressed (`_lyrebirdAssertNotOnRTThread()` guard on `outputChannelCount`; duplicate-precondition removal; sink-only `floatValue=0` doc; Control vs Audio channel-count divergence doc; explicit row-count guard; `ScratchBuses.replace` dirty-mark inside the write block; stable-sort pending-queue ordering comment; pre/post group lifecycle comments; design doc reordered to lead with `ReplaceOut`, delta-add moved to "Historical Note"). New `docs/engine/eventlist-routing-design.md` captures the bug, fix, ReplaceOut refactor + trade-off table, pre/post group design, lifecycle / ordering, migration. MyPiece `xcodebuild` BUILD SUCCEEDED with `bus: dependencyContainer.ambisonicRoutingBus`; ambisonic-decode chain now hears all four quad-channel feeds. | 3980 |
| 113 | Pan4 family refactor (`PanAz`, `PanAzDistance`, `PanXY`, `PanXYDistance`) — reshapes the 4-speaker panning family around an `open class Pan4` base class holding the shared infrastructure (4-row output buffer pre-allocated to `lyrebirdDefaultResultBufferSize`, `_mulAdd`, `outputChannelCount = 4`, named channel aliases inherited via extension). Four concrete subclasses provide the actual generator behaviour. Old leaf `Pan4` (azimuth + elevation `@LiveParam` in `[-1, 1]`) retired — its azimuth-only behaviour now lives in `PanAz` with proper radian semantics. New shared `Pan4Helpers.swift` (module-internal, `@inline(__always)`): `azimuthToSquareBoundary(_ az: Double) -> (x, y)` projects azimuth radians onto the unit-square boundary via `1 / max(|sin|, |cos|)` so the trajectory hits speaker corners at `±π/4` and `±3π/4` (rather than the inscribed unit circle leaving corners unreachable); `writeEqualPowerSquarePanSample(into:sampleIndex:source:x:y:)` clamps `(x, y)` to `[-1, 1]²` and writes equal-power gains to the four `_result` rows. **`PanAz`** — `@LiveParam azimuth: Double` in radians (0 = front centre, wraps modulo 2π via `sin`/`cos`); position fixed to unit-square boundary. **`PanAzDistance`** — `azimuth` + `distance` (0 = listener, 1 = boundary, >1 = beyond) + `velocity`; same 1/d amp + air-absorption LP + Doppler pipeline as `PanXYDistance`, single mono LP + single delay line before panning; negative distance treated as `|distance|` (direction from azimuth). **`PanXY`** — `@LiveParam x`/`y` cartesian; refactored to inherit from `Pan4` and call the shared helper. **`PanXYDistance`** — cartesian + Chebyshev distance shaping; refactored to inherit from `Pan4` and use shared helper for the pan-write. `SpatialDistance` file-private constants promoted to module-internal `SpatialDistanceConstants.swift` for reuse across distance-model generators. Test migration: old `Pan4Tests` (in `PanningTests.swift`) rewritten as `PanAzTests` with corner positions at `±π/4` / `±3π/4` and cardinal-edge tests at `0` / `±π/2` / `π`; `Pan4ParameterRampingTests.swift` → `PanAzParameterRampingTests.swift` (git mv + rewrite); `ChannelSelectTests` Pan4-alias test updated to use `PanAz` at `az = -π/4`; new `PanAzDistanceTests.swift` (rate, channel count, boundary corner = PanAz, distance=0 equal-energy collapse, 1/d halving, negative-distance symmetry, Doppler down-shift, mul, fan-out cache); existing PanXY tests stay green via inheritance. Two review cycles total: first (initial PanXY/PanXYDistance with old Pan4 still elevation-based) caught dead `_referenceDistance` + `_sampleRate` + two-`@Suite`-per-file + `try?` swallow; second (this family refactor) clean on the first sweep — vtable dispatch through `AudioGenerator` protocol witness verified, no RT `is`/`as?`, helper inlining clean, channel-alias inheritance through extension on Pan4 correct. Docs swept: `docs/stdlib/generators.md` Panning Extensions section rewritten around the four-row family table; `docs/stdlib/multichannel.md` intro + named-aliases table; `Sources/Lyrebird/Lyrebird.docc/Generators/MultiChannel.md` intro list. | 3544 |
| 112 | Extension authors guide + README extensions section — new `docs/extension-authors-guide.md` walks end-to-end through building an out-of-tree Swift package adding Generator/Synthesizer implementations. Companion to `docs/protocols/extension-sdk.md` (SPI surface list). Covers wiring, versioned releases, and pitfalls (SPI imports in tests, `Bundle.module` per-package, package-name case-sensitivity in target deps, SSH vs HTTPS for private repos, SemVer + compatibility matrix). LyrebirdATK is the canonical worked example — authors clone its `Package.swift` / `Sources` / `Tests` / `README` / `LICENSE` as templates. README.md gets an "Extensions" section between "The lyrebird CLI" and "Project structure" listing known extension packages + pointers to the SDK doc and authors guide; documentation table picks up two new rows. Doc-only commit; no source code changed. | 3499 |
| 111 | Extract Ambisonic Toolkit (FOA) to LyrebirdATK external package — entire `Foa*` UGen set (37 generators in `Sources/Lyrebird/Generators/Ambisonic/`), bundled MIT KEMAR HRIR data (`Resources/HRTF/KEMAR/kemar-full.lbhr`, 1.47 MB), and `HRIRFile.bundledKemar{Full,FullURL}` static accessors removed from core. The exact same code (untouched algorithmically) now ships as the **LyrebirdATK** external Swift package — first worked example of the Extension SDK (Phase 110). Consumers add `LyrebirdATK` as a separate package dependency + `import LyrebirdATK` alongside `import Lyrebird`. Bundled-KEMAR `Bundle.module` lookup moved to `LyrebirdATK/Sources/LyrebirdATK/HRIRFile+BundledKEMAR.swift` where `Bundle.module` resolves to the LyrebirdATK package's resource bundle. Generic `HRIRFile.load(contentsOf:)` loader stays in core, unchanged. Six KEMAR-loading tests moved 1:1 to `LyrebirdATK/Tests/LyrebirdATKTests/HRIRFileBundledKEMARTests.swift`; 28 `Foa*` test suites moved out; synthetic / negative / round-trip loader tests stay in core. `docs/stdlib/ambisonic-toolkit.md` → `LyrebirdATK/docs/ATK-Guide.md`; `docs/stdlib/generators.md` ATK section rewritten as a pointer; `scripts/build-kemar-hrir.py` → `LyrebirdATK/scripts/`. `Package.swift` Lyrebird target — `resources: [.process("Resources")]` removed. Deliberate API-breaking change; recommended tag **Lyrebird 2.0.0** after merging (consumers on prior FOA-bundled Lyrebird stay pinned to `0.9.x`). Verification: core `swift test` 3499 / 405 suites; LyrebirdATK `swift test` (against this branch via local path dep) 322 / 36 suites; sum 3821 = pre-extraction total (no tests deleted, every removed test moved 1:1). | 3499 |
| 110 | Extension SDK foundation — promotes the shared RT-safe helper symbols required by external Generator packages to `@_spi(LyrebirdExtensions) public`. `MulAdd.swift`: `MulAddSpec` (struct + init + stored props), `applyIfNeeded`, `apply`, `identity` static, `extractScalar`, `fillRampedResult`, `lastGeneratorSampleOrFloat`. `WhiteNoise.swift`: `xorshift64Next` + `xorshift64NextRaw`. `@_spi(LyrebirdExtensions)` keeps the surface invisible to ordinary `import Lyrebird` consumers while letting extension authors opt in with `@_spi(LyrebirdExtensions) import Lyrebird`; SPI symbols documented as MINOR-version-mutable. New `docs/protocols/extension-sdk.md` (tier-1 stable public + tier-2 SPI table, versioning policy, namespacing guidance); `docs/protocols/writing-generators.md` §13 cross-link. `Tests/LyrebirdTests/MulAddTests.swift` switched to `@testable @_spi(LyrebirdExtensions) import Lyrebird` (the `@testable` import alone does not grant SPI access). **Phase 110 follow-up**: two additional SPI hooks for out-of-tree test code building its own `advanceBlock`-style helper — `SynthesisEngine.segmentSerial` (read-only acquiring load) + `SynthesisEngine.advanceSegmentSerial()`, documented in a new "Test-helper hooks" subsection of `extension-sdk.md`. Bulk import sweep across 231 test files (mechanical, no test logic changed). | 3821 |
| 109 | `SpectralPolarClosure` + `SpectralComplexClosure` — two closure-driven `SpectralProcessor` wrappers (same role `Closure` plays for time-domain DSP). Polar variant is zero-copy via existing buffer pointer accessors; DC/Nyquist round-tripped through pre-allocated single-element scratch (`_dcValue`/`_nyquistValue` are private). Complex variant uses `_readToRectangular`/`_writeFromRectangular` (vDSP packed split-complex: `real[0]=DC`, `imag[0]=Nyquist`) with two pre-allocated `UnsafeMutablePointer<Float>` scratch arrays freed in `deinit`. `Float` element type matches buffer storage. `hopSize` + `sampleRate` baked into closure class at init. `_frameIndex` mutable `Int` counter, RT single-threaded. New DocC topic `Generators/SpectralClosures.md`; new section in `docs/stdlib/spectral.md`. 12 tests for polar + 15 for complex including `complexFreezeLatchesSpectrum` (pre-allocated `memcpy` latch — canonical RT-safe freeze pattern). Two review passes — pass 1 caught dead `scratchReal`/`scratchImag` vars in freeze doc-example + typo `Latces`→`Latches`; pass 2 caught one non-blocking DocC terminology note (`inout`-like → captured reference box). | 3821 |
| 108 | `PlayBuffer` rate + trigger → `ValidGeneratorInput` — promoted `PlayBuffer.playRate` (renamed to `rate`) + `PlayBuffer.trigger` from `@LiveParam Double` to `any ValidGeneratorInput` init params on both Audio and Control variants. Generator path uses `lastGeneratorSampleOrFloat` (Control) / `Optional<[Double]>?? scalarFallback` (Audio) — no per-sample heap allocation; scalar fast path calls `floatValue(graph:)` once. `Control.calculatedSamples` bypass retained for per-block phase state. +5 tests (generator-driven rate, generator-driven trigger via `Impulse`, scalar trigger reset, Control trigger reset, Control reverse). 4 demos + buffer-io-generators.md swept. Two review passes — pass 1 caught helper-inlining + dead `_zeroFallback`; pass 2 clean. | 3794 |
| 107 | `LyrebirdBuffer.nativeRateScale` — sample-rate compensation helper moved off `PlayBuffer._Base` onto `LyrebirdBuffer` itself; any buffer-consuming generator now reuses it. Redundant `Double()` cast dropped (`sampleRate` already `Double?`). New 4-test `LyrebirdBufferRateScaleTests` @Suite covers nil/equal/up/downsampled; two prior cases in `PlayBufferTests` deleted. Six demos + `docs/stdlib/buffer-io-generators.md` swept. Single review pass clean — no findings. | 3790 |
| 106 | FFT chain consolidation (legacy removal + synthOnly) — delete `FFTAnalysis.swift` + `IFFTSynthesis.swift`; all public spectral surface routes through `SpectralChain.Audio`. New `SpectralBufferGenerator` protocol (`spectralBuffer` + `hopSize`); `SpectralBufferRead` + `SpectralPlayBuffer` conform. New init `SpectralChain.Audio(spectralSource:fftSize:hopSize:…)` for fourth mode — synthOnly: aliases source `spectralBuffer`, drives source once per block, skips windowing + forward FFT, runs processors + fan-out + IFFT bank on aliased buffer. `_fftAnalysisRealp`/`_fftAnalysisImagp` switched to `Optional<UnsafeMutablePointer<Float>>` (`nil` in synthOnly; guarded deinit + use sites). Runtime precondition `count <= hopSize` in synthOnly `_computeSamples` prevents frame-loss when engine blockSize > hopSize. Migrated 7 `.Control` feature extractors (Centroid/Flatness/Spread/Flux/Entropy/Rolloff/OnsetDetector): `analysis:` init type changes from `FFTAnalysis` to `SpectralChain.Audio`. `SpectralChain.Audio.processors` widened `private` → `internal` for OnsetDetector.Control precondition. Doc sweep: `docs/stdlib/spectral.md` rewritten around `SpectralChain.Audio`; `docs/stdlib/generators.md` spectral section rewritten; all `.docc` topics (`SpectralChain.md`, `SpectralFeatures.md`, `SignalAnalysis.md`, `BuiltInGenerators.md`, `PitchShifting.md`, `GranularSynthesis.md`) updated; `LyrebirdBuffer` window docs + `SpectralBuffer` + `SpectrumCapture` + `LyrebirdSpectrumView` updated. Demos: dropped duplicate root-level `PercSpectralPitchShift.swift`; rewrote `Synthesizers/Spectral/PercSpectralPitchShift.swift` to use `SpectralChain.Audio`. New `PercSpectralStereoDiffuse` demo (mono → 2-channel decorrelated stereo via `SpectralStereoDiffuse` fan-out), wired as Demo 5 in `BufferDemos.swift` (TimeStretch shifts to Demo 6). Stale `Synthesizers/Buffer/` + `Synthesizers/Granular/` subfolder duplicates folded — newer flat root copies moved into subfolders via `git mv` to match Xcode pbxproj groups; pbxproj updated for new fan-out demo. Tests rewritten across `FFTTests`, `SpectralAutoPullTests`, `SpectralProcessor2Tests`, `SpectralChainTests`, `OnsetDetectorTests`. Phase 105 golden-buffer parity test removed (no legacy to compare). New `SpectralChain.Audio — synthOnly mode` test suite: `synthOnlyResynthesisProducesNonZeroAudio` + `synthOnlyDispatchesProcessorsOnAliasedBuffer` (verifies counter callCount > 0, lastSeenDC == source DC, chain.spectralBuffer === source.spectralBuffer identity). Two review passes — pass 1 caught missing synthOnly test coverage + class-level `/// - Parameters:` doc gap + fragile capacity-0 allocate/deallocate; pass 2 clean. | 3789 |
| 105 | Spectral mono→N consolidation — `SpectralChain.Audio` Generator (`Sources/Lyrebird/Generators/Spectral/SpectralChain.swift`) collapses the legacy `FFTAnalysis` + `IFFTSynthesis` two-Generator pipeline into one. Three modes: mono resynthesis (default), mono→N fan-out (`fanOut` arg), analyze-only (`analyzeOnly: true` — no IFFT runs, audio output is silent, used by feature extractors). Internals: shared `vDSP_create_fftsetup` across N IFFTs; per-channel synthesis work buffers (`work realp/imagp`, `timeDomainBuf`, `overlapBuf`, `outputRing`) allocated in init; destinations[0] aliases `spectralBuffer` in the no-fanOut path (zero per-hop copy); analysis + synthesis hopCounters tick independently to match legacy `outputRingReadPos = ringSize - hopSize` one-hop latency. Golden-buffer test confirms sample-for-sample equivalence with `FFTAnalysis + IFFTSynthesis` for the mono path. New `SpectralFanOutProcessor` protocol (`process(source:into:channel:)` shape for mono→N decorrelation). First conformer `SpectralStereoDiffuse`: anti-correlated xorshift64 streams seeded from `seed` and `seed ^ spectralStereoDiffuseAntiSeedMask`; magnitudes memcpy-passthrough; phases blend toward independent uniform-random targets via shortest-angular-distance; `Atomic<Float>` amount [0, 1]; amount=0 is exact bypass. Legacy `FFTAnalysis` + `IFFTSynthesis` kept fully functional with class-level docstring "Note (Phase 105)" callouts pointing to `SpectralChain.Audio`; hard `@available(*, deprecated)` annotation deferred so internal feature extractors don't generate warnings — legacy-callsite migration is a future tightly-scoped phase. Two review passes — pass 1 caught a fan-out guard bug (`_destinations.count > 1` silently skipped fan-out for N=1 conformers, leaving uninitialised buffers fed to IFFT) + missing class-level `/// - Parameters:` block on `SpectralChain.Audio`; pass 2 clean. 17 new tests across 2 files. | 3779 |
| 104c | AUv3 MIDI / UI / Presets / Effect-AU — `LyrebirdAudioUnit.midiHandler: ((MIDIMessage, AUEventSampleTime) -> Void)?` dispatched from `internalRenderBlock` via `_MIDIHandlerStorage` `Atomic<UInt64>` pointer swap (acquire/release; ARC-free on RT). `LyrebirdAUVoicePoolBinding` main-thread adapter wraps a `VoicePool` for note-on/off with subclass-configurable per-voice setup + optional channel filter (RT bridging documented but not bundled — users wire via CoreMIDI or SPSC drain). Effect-AU mode via `open class var lyrebirdInputChannels: Int { 0 }` — when > 0 the AU declares an input bus, `AUv3Driver` pulls one engine block of host input per `engine.processBlock` via `AURenderPullInputBlock` into pre-allocated host-input `AudioBufferList` + contiguous Float backing, copies into engine input buses (`[numOutputChannels, numOutputChannels + numInputChannels)`). New `AUInput.Audio(channel:)` Generator reads from those buses lazily at compute time (defensive zero-fill on out-of-range). New `LyrebirdUI.LyrebirdSynthView` Mirror-driven SwiftUI parameter grid — `@UIParam` slots only (LiveParam skipped — no `@Observable` projected value), `LazyVGrid` of `ParameterKnob`, per-knob range/unit/display-name from optional `[String: LyrebirdAUParameterInfo]` metadata. Factory-preset system: `LyrebirdAUFactoryPreset` value type (`name` + `scalarValues` + `sourceSlots`) returned from `factoryPresetsForLyrebird()` override, bridged into `AUAudioUnit.factoryPresets` + `currentPreset` automatically. Source-slot save/restore: `LyrebirdAUPresetCodable` protocol (`presetTypeID` + `presetEncodedParameters` + `presetMake(from:)`) + `LyrebirdAUPresetSourceRegistry` (`NSLock`-protected) — generators wired into `ParameterNode.source` (Phase 103) round-trip through `fullState` when registered. `fullState` payload restructured: scalars + sources + sourceTypes nested under sub-keys (`lyrebirdAUFullStateScalarKey` / `SourcesKey` / `SourceTypesKey`); legacy flat 104a payload still readable. Three review passes — pass 1 caught `_MIDIHandlerStorage.handler` data race (replaced with atomic pointer swap) + `withUnsafePointer` escape in `_fillInputStagingFromHost` + VoicePoolBinding's "RT-callable" doc lie (rewritten main-thread-only with bridging patterns) + RT string interpolation in AUInput precondition + missing dual `/// - Parameters:` doc blocks; pass 2 caught a `!` force unwrap in `_MIDIHandlerStorage.deinit` + 3 unnamed layout constants in LyrebirdSynthView; pass 3 clean. 25 new tests across 7 files. | 3762 |
| 104b | AUv3 Reference Xcode Project — `Demos/LyrebirdAUv3Demo/` ships a working `aumu` AudioUnit v3 plugin (Realized Sound: LyrebirdFM, type/subtype/manufacturer `aumu`/`LBFM`/`RLZS`). Container app target embeds the `.appex` extension into `LyrebirdAUv3Demo.app/Contents/PlugIns/`. Hand-written `project.pbxproj` with both targets, Embed App Extensions copy phase (`dstSubfolderSpec = 13`), `PBXTargetDependency` wiring app → extension, shared `xcscheme` with `parallelizeBuildables="NO"` matching the Xcode 26 SPM convention. The extension target links only the `LyrebirdUI` SPM product — linking `Lyrebird` directly trips Xcode 26's "static library by both X and Y" conflict for the `type: .dynamic` package product. `LyrebirdFM.swift` example synth is a 2-op FM (`@LiveParam carrierFreq/modRatio/modIndex/amp`, mono fanned to stereo). `LyrebirdFMAudioUnit.swift` is 12 lines — `makeSynthesizer()` + `parameterMetadata()`. `LyrebirdFMAudioUnitViewController.swift` is the `AUAudioUnitFactory` (`createAudioUnit(with:)` builds the AU) + empty `AUViewController` stub (104c populates). `Info.plist` declares the `AudioComponents` array with `sandboxSafe = true`, `tags = [Synth]`, factory-via-principal-class. Both targets get `com.apple.security.app-sandbox`; container also gets `user-selected.read-only`. `xcodebuild` Debug + Release verified with `SWIFT_USE_INTEGRATED_DRIVER=NO` + ad-hoc signing; `.appex` correctly embedded. `auval -v aumu LBFM RLZS` + Logic / GarageBand / AUM smoke tests are manual Josh steps (autonomous `pluginkit` registration of an unsigned extension is sandbox-blocked, correctly). New top-level docs: `Demos/LyrebirdAUv3Demo/README.md` (template walkthrough), `docs/auv3-extension-guide.md` (step-by-step "ship your own plugin" guide). Single review pass — pass 1 caught one orphan `Lyrebird` SPM product dep + `BuildIndependentTargetsInParallel = 1` mismatch with scheme's `parallelizeBuildables=NO` + agent-internal memory path leak in the guide + Release launch action; pass 2 clean. No Lyrebird Swift sources changed — tests unchanged at 3737. | 3737 |
| 104a | AUv3 Wrapper Infrastructure — headless Swift API bridging `SynthesisEngine` + `SynthesizerBase` into the `AUAudioUnit` contract. `AUv3Driver` (passive `AudioDriver`; engine ref held via `Unmanaged`, no ARC on RT) drives an `AUv3RingBuffer` (per-channel power-of-two ring) to decouple fixed `blockSize` from host-variable `frameCount`. `open class LyrebirdAudioUnit: AUAudioUnit` exposes subclass hooks `makeSynthesizer()` + `parameterMetadata()` + `lyrebirdBlockSize` + `lyrebirdOutputChannels` + `lyrebirdMaxFramesToRender`; builds parameter tree in `init` via Mirror walk (matches `_autoRegisterLiveParams` order); creates a fresh engine in `allocateRenderResources` at host-negotiated sample rate; tears down in `deallocateRenderResources` (synth survives the cycle). `LyrebirdAUParameterMapping` Mirror-driven discovery emits stable `AUParameterAddress` per `@LiveParam` / `@UIParam` slot; `LyrebirdAUParameterInfo` carries per-parameter min/max/unit/displayName/flags overrides (since `@LiveParam` itself has no bounds). `fullState` round-trips scalar `@LiveParam` values under namespaced `lyrebirdAUFullStateKey` — Phase 103 source-slot generators explicitly out of scope (104c). `Package.swift` widens AVFoundation link from iOS-only to all platforms. Headless — no Xcode `.appex` artefact (104b's job). Two review passes — pass 1 caught two stored `AUAudioUnitBusArray!` IUOs (replaced with `?` + guard-fatalError in getters), two public types in one file (`LyrebirdAUParameterEntry` split out), and five `baseAddress!` force unwraps in tests (replaced with `guard let` + `Issue.record`); pass 2 clean. 32 new tests across 4 files. | 3737 |
| 102b | Ambisonic Toolkit (FOA binaural decoder) — `FoaDecodeBinaural`: 4-row B-format input → 2-row stereo headphone output via MIMO partitioned-FFT overlap-save convolution against 8 baked rendering filters (4 B-format channels × 2 ears). `FoaBinauralFilters.build(from:)` constructs filters at init by projection-decode summation over all HRIR positions (matching `FoaDecodeProjection` coefficients exactly). Bundled MIT KEMAR full set (710 positions, 512-sample IRs, 44.1 kHz) via `HRIRFile.bundledKemarFull`; user HRIR sets accepted via `HRIRFile.load(contentsOf:)`. Configurable `partitionSize` (power of two, default 256); inherent latency = one partition. `.left`/`.right` channel aliases. All buffers + FFT setups pre-allocated in `init`, freed in `deinit`; no RT allocation. 25 new tests. | 3634 |
| 101 | Ambisonic Toolkit (FOA core) — 27 `Foa*` generators in `Sources/Lyrebird/Generators/Ambisonic/`: 20 Group A angle transforms (Rotate/Tilt/Tumble, Focus/Push/Press/Zoom/Direct{X,Y,Z}, DirectO, Asymmetry) via `_FoaAngleBase`; 3 Group B (Dominate{X,Y,Z}) via `_FoaGainBase` (dB cached for skip-when-constant pow); 3 Group C IIR filters (NFC, Proximity, PsychoShelf) with `denormalsToZero` on every feedback var; `FoaPanB` encoder + 3 closed-form decoders (DecodeProjection N-speaker projection, DecodeStereo, DecodeQuad). `FoaMatrix4` 16-tuple `Double` value type + `@inline(__always) foaApply`. Math translated literally from SC3 `AtkUGens.cpp` FILL_*_MATRIX macros. Coexists with `AmbiEncoder1`/`AmbiDecoder1`. Two review passes: pass 1 flagged 5 redundant `calculatedSamples` overrides on `AudioGenerator` conformers (§5 violation — protocol extension already handles segment-serial fan-out caching; bypass concern is `ControlGenerator`-only). All deleted; pass 2 clean. 263 new tests. | 3567 |
| 100 | `SpectralFormantShift` — magnitude-envelope-preserving formant shift `SpectralProcessor`. Estimates the smooth envelope of the current frame via `.cepstral` (default, accurate; internal `CepstralEnvelopeEstimator` owns a second real `FFTSetup`, `vvlogf`/`vDSP_fft_zrip` inverse/lifter/forward/`vvexpf`, `2·N` round-trip rescale, `magnitudeFloor = 1e-12`) or `.magnitudeSmoothing(radiusBins:)` (two-pointer box blur), divides it out to whiten, resamples along the bin axis by `shiftRatio` with linear interpolation + one-bin fade past Nyquist, and reapplies. Phase untouched; DC/Nyquist signs preserved. `shiftRatio` `Atomic<Float>` clamped `[0.25, 4.0]`; `1.0` is bypass. Pairs with `SpectralPitchShift` to decouple pitch from formant motion. New public enum `FormantShiftMethod`. 10 new tests. | 3304 |
| 99 | Spectral Filtering + Phase Manipulation — seven new public `SpectralProcessor` types operating on polar `SpectralBuffer`: `SpectralBrickwall` (`.lp`/`.hp`/`.bp`/`.br` modes; `vDSP_vclr` outside passband), `SpectralPhaseShift` (`.deg90`/`.deg180`/`.deg270`/`.radians` Hilbert-style rotation; live `radians` retunable), `SpectralGate` (linear + `thresholdDB:` convenience init via shared `dbToAmp`; `floor` ∈ [0,1] hard-gate-to-bypass blend), `SpectralTilt` (pre-computed dB/oct gain table around pivot Hz; DC bin forced to unity), `SpectralBlur` (magnitude box-blur via two-pointer running sum; `_blurOut` allocated init-time; edge bins shrink window), `SpectralDiffuse` (continuous phase randomization 0→1 via `lyrebirdSeedXorshift64(from:mixConstant:)` + named `spectralDiffuseMixConstant`; shortest-angular-distance blend), `SpectralConvolve` (frequency-domain complex multiply with second buffer for cross-synthesis or static IR; either-buffer-invalid → live cleared). Two shared helpers extracted to `Sources/Lyrebird/Spectral/`: `wrapPhasesInPlace` (consumed by refactored `SpectralFreeze` + new processors) and `binFromHz`. All `process` methods open `guard spectral.fftSize == _fftSize else { return }` (no RT string interpolation). Pre-allocated scratch; `Atomic<Float>`/`Atomic<Int>` for live params. New "Spectral Filtering & Phase" section in `docs/stdlib/spectral.md`. 50 new tests. Required five review passes (RT precondition string interp; `dbToAmp` helper adoption; DC-bin proxy fix; shared seed helper adoption; multi-line init format + class-level `/// - Parameters:` blocks; unused `Foundation` imports). | 3294 |
| 182 | Pattern facade refactor + Demand* rename — `Pattern<T>` split into thin facade + module-internal `_PatternEngine<Element>` protocol; sequence behaviour moved into `SequencePatternEngine<T>`; exposed via `Pattern.sequence(_:repeats:)` static factory. Old `Pattern.init(values:repeats:)` removed. Four demand-rate sources renamed: `DSequence` → `DemandSequence`, `DRandom` → `DemandRandom`, `DTemporalBrownian` → `DemandTemporalBrownian`, `DTemporalTendency` → `DemandTemporalTendency`. `DemandGenerator` protocol name and `Demand.Audio`/`Demand.Control` puller names unchanged. No new types, no new RT behaviour — foundational phase for the 183-190 Pattern + Demand catalogue expansion. One review-fix pass (single-line init in `SequencePatternEngine` reformatted to multi-line). | 4010 |
| 183 | Atomic numeric Pattern sources — seven new `Pattern<Double>` factory methods via `public extension Pattern where T == Double`: `series` (arithmetic), `geometric`, `uniformRandom` (Box-Muller is `gaussian`'s job — `uniformRandom` is `[low, high]` uniform), `brownian` (clamped random walk; `start` defaults to midpoint), `gaussian` (Box-Muller), `cauchy` (inverse-CDF), `beta` (two-Gamma method on `[0, 1]`). Seven new engines in `Sources/Lyrebird/Patterns/Engines/` conform to `_PatternEngine<Double>` (Phase 182). Random engines reuse the file-internal helpers in `Sources/Lyrebird/Distributions/DistributionSampling.swift` (`_sampleUniform` / `_sampleGauss` / `_sampleCauchy` / `_sampleBetaRand`) — same code consumed by `DemandTemporalTendency`. Seeding via `lyrebirdSeedXorshift64(from:)`. `reset()` rewinds only the response counter / position — PRNG state NOT restored (mirrors `DemandRandom` precedent so rhythmic retriggering keeps audible variety). One review-fix pass (4 missing `reset()` tests across the random engines + stale `import Foundation` + missing `isExhausted` assertion + caveman shadowing nit in `Brownian.next()`). 33 new tests across 7 files. | 4042 |
| 184 | Discrete-pool Pattern sources + closure escape hatch — four new generic `Pattern<T>` factory methods on `public extension Pattern`: `shuffle` (Fisher-Yates permute once at init, then cycle; same permutation replays on `reset()` — SC `Pshuf` semantics), `nonRepeatingRandom` (random pick avoiding same *index* as previous; index-vs-value caveat documented for duplicate-value pools), `weightedRandom` (selection proportional to weight via cumulative distribution; init preconditions on equal count, finite non-negative weights, positive sum), `closure` (wraps `() -> T?`, latches once nil is returned). Four new engines in `Sources/Lyrebird/Patterns/Engines/` conform to `_PatternEngine<T>` (Phase 182). `reset()` rewinds counter / position / last-pick / latch state but NOT PRNG seed (mirrors `DemandRandom`). One review-fix pass (missing `!_values.isEmpty` guard in `WeightedRandomPatternEngine.next()`, plus caveman nits — `+Infinity` weights via `$0.isFinite` precondition, documented `u < cumulative[i]` strict-less-than fallthrough). 21 new tests across 4 files. | 4063 |
| 185 | Length/range Pattern modifiers — four new generic `Pattern<T>` factory methods wrapping any upstream pattern: `repeating` (SC `Pn`; replays `count` times with `reset()` between cycles; `-1` infinite; latches if upstream empty after fresh reset), `limit` (SC `Pfin`; emits at most `count` items returned, not calls made; latches if upstream exhausts first; `count >= 0` precondition), `drop` (SC `Pdrop`; lazy drop on first `next()` then pass through; `count >= 0` precondition), `stutter` (SC `Pstutter`; for each source value, emit it n times where n is the next value from a `Pattern<Int>`; `count <= 0` consumes source but emits nothing; latches when either upstream returns nil while pulling a new pair). Four new engines in `Sources/Lyrebird/Patterns/Engines/` conform to `_PatternEngine<T>` (Phase 182). All `reset()` propagate to wrapped upstream pattern(s). One review-fix pass (two blockers — `RepeatPatternEngine.init` missing `precondition(count >= -1)` allowed any negative to silently run forever; `StutterPatternEngine.next()` returned `_currentValue: T?` directly making invariant violations silently propagate as exhaustion — fixed with defensive guard; also added missing `negativeCountSkipsValue` test). 19 new tests across 4 files. | 4081 |
| 186 | Multi-pattern composition — five new factory methods on `public extension Pattern`: `switching` (SC `Pswitch1`; one value per index draw, out-of-range index latches), `concatenate` (sequential play; advances when active sub-pattern returns nil), `roundRobin` (SC `Ppatlace`; ragged patterns drop out individually with dead-slot tracking, latches when all dead), `tuple` (returns `Pattern<[T]>` — different element type from upstream; zips children into size-stable arrays, latches on any child nil), `interleave` (SC `Place`; outer-cycle semantic — each cycle emits one value per sub-list with `outerStep % sublist.count` wrap; empty sub-lists silently dropped; total emit = `lists.count × repeats`; precondition `repeats >= -1`). Five new engines in `Sources/Lyrebird/Patterns/Engines/`; `TuplePatternEngine` declares `Element = [T]` to make the differing return element type explicit. All `reset()` propagate to wrapped upstream pattern(s). Two review-fix passes (pass 1: `RoundRobin` defensive guard off-by-one + `Interleave` multiplication overflow path AND SC `Place` semantic divergence — rewrote engine to match SC exactly, eliminating both issues; pass 2: stale factory doc comment for `Pattern.interleave` still describing old `× maxLen` semantic — rewrote to `× repeats`). 24 new tests across 5 files. | 4105 |
| 187 | Map/filter/transform Pattern catalogue — nine new factory methods across two extension blocks. Generic (`public extension Pattern`): `map` (SC `Pcollect`; result element type can differ from upstream), `filter` (SC `Pselect`; documented spin caveat for infinite-source-never-matching-predicate), `reject` (SC `Preject`; routes `FilterPatternEngine` with negated predicate). Numeric (`public extension Pattern where T == Double`): `accumulate` (SC `Paccum` running sum), `difference` (SC `Pdiff`; first value verbatim, subsequent = deltas), `wrap` (SC `Pwrap`; floor-modulo into half-open `[low, high)` with FP-boundary post-clamp; precondition `high > low`), `clip` (SC `Pclip`; clamps to `[low, high]`; precondition `high >= low`), `round` (SC `Pround`; `.toNearestOrAwayFromZero` mode for SC parity; precondition `step > 0`), `smooth` (SC `Psmooth`; one-pole exponential smoother; coefficient clamped to `[0, 1]`; first sample passes through). Five new engines (Map / Filter / Accumulate / Difference / Smooth); stateless transforms (wrap / clip / round) reuse `MapPatternEngine` via closure. `PatternFactories.swift` gained `import Darwin` for `floor()` (matches existing Math/ convention). Closes the Pattern-side of the 183-187 sweep. One Lyrebird review cycle clean; two caveman fix passes (SC `Pround` parity via `.toNearestOrAwayFromZero` — banker's rounding default diverges at half-ties like `2.5 → 2` vs SC `3`; `Pattern.wrap` FP-boundary post-clamp; misleading `low == high` doc removed; stale rounding-mode comment in test aligned). 28 new tests across 9 files. | 4132 |
| 188 | Atomic numeric `Demand*` (Pattern-engine wrap consolidation) — four `public final class` `DemandGenerator` conformers built as ~30-line thin wrappers around the corresponding Phase 183 module-internal Pattern engines: `DemandSeries` ↔ `SeriesPatternEngine`, `DemandGeometric` ↔ `GeometricPatternEngine`, `DemandUniformRandom` ↔ `UniformRandomPatternEngine`, `DemandBrownian` ↔ `BrownianPatternEngine`. Each holds a `private let _engine: ConcreteEngineType` (Swift access permits private storage of internal types inside public classes) and forwards `nextValue()` / `reset()` / `isExhausted` in one line. Pattern engines were already RT-safe by construction (pure arithmetic, `xorshift64NextRaw`, no allocation / locks / String) so wrapping is bit-equivalent and saves ~120 lines of algorithm duplication. `DemandBrownian` is plain-parameter complement to `DemandTemporalBrownian`; `DemandUniformRandom` complements pool-based `DemandRandom` by drawing continuous values. `reset()` rewinds counter / position but NOT PRNG seed on random variants. Both Lyrebird + caveman reviews clean on first pass; no fixes. 13 new tests across 4 files. | 4145 |
| 189 | Discrete-pool `Demand*` (Pattern-engine wrap consolidation) — three `public final class` `DemandGenerator` conformers wrapping the corresponding Phase 184 module-internal Pattern engines parameterised over `T=Double`: `DemandShuffle` ↔ `ShufflePatternEngine<Double>` (SC `Dshuf`), `DemandNonRepeatingRandom` ↔ `NonRepeatingRandomPatternEngine<Double>` (SC `Dxrand`), `DemandWeightedRandom` ↔ `WeightedRandomPatternEngine<Double>` (SC `Dwrand`). Same thin-wrap pattern as Phase 188 (`private let _engine`, one-line forwards). RT-safety verified: Fisher-Yates at init only, `next()` bodies pure arithmetic + `xorshift64NextRaw` + `_uniform01`, NonRepeating retry-loop bounded for pools ≥ 2, WeightedRandom uses pre-built cumulative array. One review-fix pass (missing `resetClearsExhaustion` test in `DemandShuffleTests`; every Phase 188 peer carries one — added). 12 new tests across 3 files. | 4157 |
| 190 | Composition `Demand*` — closes the 182-190 Pattern + Demand catalogue expansion. Three new `public final class` `DemandGenerator` conformers composing other `DemandGenerator` instances directly (departure from the Phase 188-189 Pattern-engine-wrap strategy — Pattern engines take `Pattern<T>` upstream while the demand side composes other DemandGenerators, so direct impl is the cleaner fit): `DemandStutter` (scalar `Int` count, each upstream value emitted N times, `count >= 1` precondition; deliberately scalar count rather than `DemandGenerator`-driven for zero-allocation RT-path), `DemandSwitch` (SC `Dswitch1`; index source is itself a `DemandGenerator`, values floor-cast via `Int(idxRaw.rounded(.down))` so fractional negatives in `(-1.0, 0.0)` latch rather than silently picking `demands[0]`; latches on index/sub-source/out-of-range), `DemandConcatenate` (sequential play; advances on sub-source nil; while-loop correctly skips immediately-exhausted sub-sources). Each ~30 lines, RT-safe by construction. One review-fix pass (`Int(idxRaw)` truncate-toward-zero vs documented "floor-cast" — switched to `Int(idxRaw.rounded(.down))`, added `negativeFractionalIndexFloorsToLatch` test). 13 new tests across 3 files. **Pattern + Demand catalogue totals**: Pattern side = 30 factories on `Pattern<T>` (1 facade `sequence` + 29 new); Demand side = 14 public `DemandGenerator` types (10 new + 2 pre-existing renames + 2 pre-existing temporal). | 4170 |
| 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 |
---
## Upcoming Phases
Phases ordered by dependency and value/effort. Each phase needs tests before moving on.
### 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`.
---
---
## Deferred / Future
- **HOA (Higher-Order Ambisonics)**: Deferred until demand is clear. FOA covered by Phases 101 + 102. HOA decoder requires Accelerate `vDSP_mmulD` matrix multiply path; encoder requires real spherical harmonic basis up to chosen order.
- ~~AUv3 plugin export~~ → Phase 104 (split into 104a wrapper infrastructure, 104b Xcode example project + `auval`, 104c MIDI / UI / preset features).
- ~~Runtime source-swapping~~ → Phase 103 (planned; replaces obsolete `declareParameter`-era description with `@LiveParam` slot swap via `ParameterNode._sourceSlot` + `Unmanaged<AnyObject>` SPSC queue).
- **Single-sample feedback / History** (§7.2): `History.Audio` one-sample delay across blocks for zero-latency feedback. Engine-level change to permit designated feedback arcs in the DAG. Blocked on clear design.
- **Hot-reload / live coding** (§9.4): Unblocked by Phase 103 (runtime source-swap). Scope after 103 ships: file-watcher → recompile → swap.
- **CV/Gate Eurorack** (§9.3): Language-side only — `LinLin` scaling constants for ES-8/ES-9 ±5V range. Trivial; do inline when convenient.
- ~~`.demand` rate (pull-based on-demand generators)~~ → Phase 39 ✓
- ~~SIMD optimization pass~~ → Phase 33b ✓
- ~~iOS Support~~ → Phases iOS-1–iOS-4 ✓
File diff suppressed because it is too large Load Diff
+216
View File
@@ -0,0 +1,216 @@
# AUv3 Extension Guide
How to ship a `SynthesizerBase` subclass as an AudioUnit v3 (`.appex`)
plugin loadable by Logic, GarageBand, AUM, Loopy Pro, Ableton (via
Bridge), and any other AUv3 host.
`Demos/LyrebirdAUv3Demo/` is the working reference. Copy that template,
swap in your synth, change the bundle IDs / component codes, build.
## Prerequisites
- macOS 15+ with Xcode 16+ (project targets `MACOSX_DEPLOYMENT_TARGET = 15.0`).
- Apple Developer Team ID (any free or paid tier works for local
testing; distribution needs paid).
- Your synth is a `SynthesizerBase` subclass with one or more
`@LiveParam` properties.
- You understand the `LyrebirdAudioUnit` wrapper — see
[`Sources/Lyrebird/Lyrebird.docc/AUv3.md`](../Sources/Lyrebird/Lyrebird.docc/AUv3.md).
## Step-by-step
### 1. Duplicate the demo
```bash
cp -R Demos/LyrebirdAUv3Demo Demos/MyPluginDemo
```
Rename everything under `Demos/MyPluginDemo` to your plugin name. The
xcodeproj internally references by GUID, not by path, so the folder
rename is safe.
### 2. Replace the synth
In `Demos/MyPluginDemo/LyrebirdFMExtension/LyrebirdFM.swift`, replace
the `LyrebirdFM` class with your own `SynthesizerBase` subclass.
Stereo output is recommended (mirror the same source onto bus 0 and
bus 1) — most hosts expect stereo from `aumu` instruments.
### 3. Wire up the AU subclass
In `LyrebirdFMAudioUnit.swift`, change:
- The class name (matching the principal class reference in
`Info.plist`).
- The `makeSynthesizer()` body to return your new synth.
- The `parameterMetadata()` table to match your `@LiveParam`
properties' actual bounds and units. **Names must match the
property names exactly** — Mirror discovery is name-keyed.
### 4. Update the Info.plist
Change in `LyrebirdFMExtension/Info.plist`:
- `NSExtensionAttributes → AudioComponents`:
- `name`: `Manufacturer: PluginName` (this is what hosts display).
- `description`: short blurb shown in some hosts.
- `subtype`: 4-character code unique to *your* plugin
(e.g. `MFM1`). Must differ from `LBFM` / any other AU you ship.
- `manufacturer`: 4-character code unique to *your* organisation
(e.g. `ACME`). Reuse the same code for every AU you ship.
- `NSExtensionPrincipalClass`: must read
`<NewExtensionModuleName>.<NewViewControllerClassName>`.
### 5. Update bundle identifiers
In Xcode's build settings (or directly in `project.pbxproj`), change:
- Container app `PRODUCT_BUNDLE_IDENTIFIER`:
`com.yourorg.myplugindemo`
- Extension `PRODUCT_BUNDLE_IDENTIFIER`:
`com.yourorg.myplugindemo.MyExtension` — must be a strict prefix
match of the container.
The extension's `AudioComponentBundle` Info.plist entry is set to
`$(PRODUCT_BUNDLE_IDENTIFIER)` so it follows automatically.
### 6. Signing
Set `DEVELOPMENT_TEAM` to your Apple Developer Team ID on both
targets (Xcode → Target → Signing & Capabilities). Automatic signing
takes care of provisioning profiles.
For local-only testing you can build with `CODE_SIGNING_REQUIRED=NO
CODE_SIGNING_ALLOWED=NO` from `xcodebuild`, but App Store /
Notarization require real signing.
### 7. Build + run the container app once
Building the container app embeds the `.appex` into
`MyPluginDemo.app/Contents/PlugIns/`. **Running the app once** is what
registers the extension with the system AU registry (via
`LaunchServices` → `pluginkit`). Without that step no host will find
your AU.
### 8. Validate with `auval`
```bash
auval -v aumu <subType> <manufacturer>
```
For the demo: `auval -v aumu LBFM RLZS`.
Look for `* * PASS` in the output. If you see "didn't find the
component", the registration step (7) did not complete — re-run the
container app from Xcode, wait a moment, retry.
### 9. Host smoke test
Drop the plugin into Logic Pro / GarageBand:
1. Track → New Software Instrument.
2. Channel strip → Instrument slot → AU Instruments → your
manufacturer → your plugin name.
3. Open the plugin window. The host's generic UI shows the parameter
list (until you populate the SwiftUI view).
4. Move sliders, automate parameters, save / load presets — all
work through the `AUParameter` + `fullState` plumbing.
## Common pitfalls
### "Build settings: missing SWIFT_USE_INTEGRATED_DRIVER override"
On Xcode 26+ the explicit-module-build system breaks SPM dynamic
framework module resolution: Xcode scans every target's dependencies
before any module is built, and Lyrebird ships as a dynamic library
product (`type: .dynamic` in `Package.swift`) whose module map does
not yet exist at scan time. Set `SWIFT_USE_INTEGRATED_DRIVER = NO`
on every target to fall back to the classic sequential driver, which
resolves modules at compile time. The demo's `project.pbxproj` does
not bake this in — add it in your project's User-Defined build
settings or pass it on the command line. Revert when Apple fixes the
explicit-module scanner to generate C target module maps before
dependent Swift targets' dependency scans.
### "Swift package target 'Lyrebird' is linked as a static library"
Only link the `LyrebirdUI` SPM product, not `Lyrebird` directly.
LyrebirdUI declares Lyrebird as a transitive dependency, so the
binary surface area is identical, but the static-vs-dynamic conflict
disappears. The demo's `LyrebirdFMExtension` target links
`LyrebirdUI` only — and that is enough; the Lyrebird module is still
importable.
### "AU instantiated but no audio"
- Confirm the AU host is sending audio render calls (some hosts only
render when a MIDI event has fired). The base demo ships no MIDI input
handler — output is silent until you parameter-automate `amp` up
AND a way to gate notes exists (which you have to build, since
the demo's `LyrebirdFM` is a free-running oscillator that always sounds
at the carrier frequency × amp).
- Confirm `parameterMetadata()` names match your `@LiveParam`
property names exactly.
- Confirm both stereo channels receive output (`output(bus: 0, ...)
output(bus: 1, ...)`).
### "auval crashes / hangs"
Almost always the principal class is wrong. The `NSExtensionPrincipal
Class` Info.plist string must read `<ModuleName>.<ClassName>` where
the module name matches the extension target's `PRODUCT_NAME` (which
is `$(TARGET_NAME)` by default, so the target name itself).
## Aux output + sidechain input
- **Multi-output busses** — override
``LyrebirdAudioUnit/lyrebirdOutputBusses`` with an array of
``LyrebirdAUBusSpec``. Hosts (Logic, AUM, MainStage) expose each bus
separately in their routing UI.
- **Multi-input busses** — override
``LyrebirdAudioUnit/lyrebirdInputBusses`` for sidechain inputs.
`AUInput.Audio(busIndex: 0, channel: ch)` reads main, `busIndex: 1`
reads sidechain.
- **Engine bus layout** — outputs first, then inputs, each block
contiguous; `SynthesisEngine.auOutputBusOffsets` /
`auInputBusOffsets` maps AU bus index → engine bus index.
- Single-bus subclasses are **untouched** — defaults
derive from the existing `lyrebirdOutputChannels` /
`lyrebirdInputChannels` class vars.
## MIDI input, SwiftUI UI, presets, effect-type AU
- **MIDI input** — `au.midiHandler` closure receives parsed
``MIDIMessage`` from the host's `AURenderEvent` chain. For
polyphony use ``LyrebirdAUVoicePoolBinding`` with a
``VoicePool``.
- **SwiftUI parameter UI** — drop a ``LyrebirdSynthView`` into your
AU view controller; it walks the synth's `Mirror` for `@UIParam`
slots and renders one `ParameterKnob` per slot.
- **Source-slot preset serialisation** — conform your slot-source
generators to ``LyrebirdAUPresetCodable`` and register them with
``LyrebirdAUPresetSourceRegistry`` before instantiating the AU.
- **Effect-type AU (`aufx`)** — override
``LyrebirdAudioUnit/lyrebirdInputChannels`` to a positive value and
read host audio in `build()` via ``AUInput/Audio``.
## Out of scope
- Aux output / sidechain busses — see the dedicated section above.
- MIDI 2.0 UMP — AU base reports MIDI 1.0 protocol.
- Per-sample AU parameter automation ramps — host writes still apply
at the next sub-block boundary via the standard atomic ramp path.
- App Store distribution / notarization workflow — outside Lyrebird's
scope; follow Apple's standard
[Distributing your app on the App Store](https://developer.apple.com/app-store/)
guide.
## See also
- [`Sources/Lyrebird/Lyrebird.docc/AUv3.md`](../Sources/Lyrebird/Lyrebird.docc/AUv3.md)
— `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.
+371
View File
@@ -0,0 +1,371 @@
# Diagnostics Guide
Two complementary diagnostic surfaces live in `Sources/Lyrebird/Diagnostics/`
and `Sources/Lyrebird/NodeTree/`:
| Subsystem | Type | What it surfaces |
|---|---|---|
| Messages | `LyrebirdMessageCenter` | Curated user-visible text (info / warning / error) |
| Node tree mirror | `NodeTreeMirror` | Live snapshot of the engine's signal-graph node tree |
Both are **language-side, main-thread** facilities. The RT thread does
not call into either, and there is no SPSC bridge from RT to main. If
you need to react to RT events from the UI, the existing
`SynthesisEngineListener` lifecycle hook is the only fan-out the engine
exposes today.
---
## Part 1 — `LyrebirdMessage`
### What it is
A bounded ring of user-facing diagnostic messages, observed by SwiftUI
through the `@Observable` macro and rendered by `LyrebirdMessageView` /
`LyrebirdMessageBanner`.
```swift
public enum LyrebirdMessageTier: Sendable, Equatable, CaseIterable {
case info, warning, error
}
public struct LyrebirdMessage: Identifiable, Sendable, Equatable {
public let id: UUID
public let timestamp: Date
public let tier: LyrebirdMessageTier
public let text: String
public let source: String?
}
@Observable
@MainActor
public final class LyrebirdMessageCenter {
public static let shared: LyrebirdMessageCenter
public private(set) var messages: [LyrebirdMessage]
public var capacity: Int // default 200; prunes immediately when lowered
public func post(_ tier: LyrebirdMessageTier, _ text: String, source: String? = nil)
public func info(_ text: String, source: String? = nil)
public func warning(_ text: String, source: String? = nil)
public func error(_ text: String, source: String? = nil)
public func clear()
}
```
### `print()` vs `post()` — two channels, by design
Two distinct streams. Library authors choose which one each diagnostic
goes to:
| Channel | Audience | When to use |
|---|---|---|
| `print("[Lyrebird ...] ...")` | Developer / Xcode console | Engine internals, dev diagnostics, anything that should not surface to the end user. The existing engine / `LyrebirdEventList` / `LyrebirdProcess` / `OSCServer` sites all use this. |
| `LyrebirdMessageCenter.shared.post(...)` | End user / library consumer | Curated text the user is meant to see: "recording started", "buffer not found", "OSC port already in use", "voice pool full". |
Existing `print` sites stay as-is. New
diagnostic sites pick one channel — and one only — based on who needs
to see the line.
### Posting
```swift
import LyrebirdSynth
// At a save site:
LyrebirdMessageCenter.shared.info(
"Recording started at \(directory.path)",
source: "LyrebirdEventList '\(id)'"
)
// At a non-fatal anomaly:
LyrebirdMessageCenter.shared.warning(
"Sample rate changed mid-session — buffers may glitch.",
source: "SynthesisEngine"
)
// At a user-actionable failure:
LyrebirdMessageCenter.shared.error(
"OSC port \(port) is already in use; OSCServer not started.",
source: "OSCServer"
)
```
The `source` parameter is optional but encouraged — the UI shows it as
a small caption above the message body, and it's the only way the user
distinguishes two messages with identical text from different sources.
### Threading
The center is `@MainActor`. Callers off the main thread must hop:
```swift
Task { @MainActor in
LyrebirdMessageCenter.shared.warning("Bus pool nearly full.")
}
```
**No RT-thread access.** Generators (RT thread) have no API for
posting. If a future RT path genuinely needs to emit a message, the
intended bridge is a dedicated `SPSCQueue<MessageRecord>` drained at
10 Hz by the center — out of scope for now.
### Capacity
Default capacity is `200`. Exceeding it drops the oldest entries (FIFO
ring). Lowering `capacity` prunes immediately to the new bound.
```swift
LyrebirdMessageCenter.shared.capacity = 50 // keep only the most recent 50
```
### View hosting
Two SwiftUI surfaces:
```swift
import LyrebirdUI
// Full scrollable list with per-tier filter chips, count badges, Clear.
LyrebirdMessageView()
// Compact 3-line ticker. Tap → invokes the optional onOpenFull callback.
LyrebirdMessageBanner(onOpenFull: { /* open full view */ })
```
`LyrebirdEngineStatusView` already hosts a collapsible Messages section
between the CPU metrics divider and the configuration section.
Expanded, it inlines the full view; collapsed, it shows the banner.
macOS additionally offers an "Open Window" button.
Open standalone (macOS):
```swift
LyrebirdMessageView.presentInWindow() // shared center
LyrebirdMessageView.presentInWindow(center: myCenter) // custom center
```
### Custom centers
Most apps use the `shared` singleton. If you need an isolated channel
(e.g. a sub-component that wants its own message log), construct your
own:
```swift
let myCenter: LyrebirdMessageCenter = LyrebirdMessageCenter(capacity: 50)
myCenter.warning("Recording buffer almost full.")
LyrebirdMessageView(center: myCenter)
```
The shared center is unaffected by writes to a custom one.
---
## Part 2 — `NodeTreeMirror`
### What it is
A main-thread mirror of the engine's signal-graph node tree, kept up to
date by every language-side mutation and published as an immutable
`NodeTreeSnapshot` for SwiftUI to observe.
```swift
public struct NodeTreeSnapshot: Sendable, Equatable {
public struct Node: Identifiable, Sendable, Equatable {
public enum Kind: Sendable, Equatable {
case synth(className: String)
case group
case parallelGroup
}
public let id: ObjectIdentifier
public let kind: Kind
public let displayName: String
public let children: [Node]
}
public let root: Node
}
@Observable
public final class NodeTreeMirror {
public private(set) var snapshot: NodeTreeSnapshot
// didAdd / didRemove / didFreeGroup are internal — driven by the engine.
}
```
Access via the engine:
```swift
let mirror: NodeTreeMirror = engine.nodeTreeMirror
let root: NodeTreeSnapshot.Node = mirror.snapshot.root
```
### Why a mirror
The RT thread mutates `Group.head` / `PreparedNode.next` when it
drains `pendingQueue`. A direct main-thread walk during playback is a
data race. The mirror sidesteps the race by maintaining its own
value-type tree updated from the language-side mutation API — never
from the RT side.
### When the mirror updates
| Engine call | Mirror update |
|---|---|
| `engine.add(_:)` | head of `mainGroup` |
| `engine.add(_:position:)` | at the specified `NodePosition` |
| `engine.schedule(_:at:)` / `schedule(_:after:)` | head of `mainGroup` (immediately — UI shows the synth before its RT-side fire time) |
| `engine.remove(_:)` / `remove(_:at:)` | drops the synth |
| `Group.free(engine:)` | drops the group + entire subtree |
Updates fire **after** `pendingQueue.enqueue` returns `true`. If the
queue is full and the event is dropped, the mirror skips the update so
its view stays consistent with the RT thread's view ("synth never
appeared" — not "phantom node").
### What does NOT update the mirror
| Path | Why |
|---|---|
| Natural envelope completion drained via `freeQueue` | The RT thread frees the synth; there is no main-thread hook unless the owner (`LyrebirdProcess._teardown`, user code) calls `engine.remove(synth)`. Raw synths added via `engine.add` that self-terminate without an explicit remove will linger in the mirror. |
| `Group.release(engine:)` cascading to children | Release is envelope-driven; the actual removal only fires once each child completes its release tail and the owning code calls `engine.remove`. The mirror reflects the eventual removes, not the intermediate releasing state. |
| RT-side `Group.addToHead` / `addToTail` / `addBefore` / `addAfter` | These are RT-internal — the language side already drove the mirror update on the corresponding `engine.add` call. |
### Reading the snapshot
```swift
import LyrebirdSynth
let root: NodeTreeSnapshot.Node = engine.nodeTreeMirror.snapshot.root
// root.children[0] is mainGroup by construction.
for node: NodeTreeSnapshot.Node in root.children {
switch node.kind {
case .synth(let className):
print("synth: \(className)")
case .group:
print("group with \(node.children.count) children")
case .parallelGroup:
print("parallel group with \(node.children.count) children")
}
}
```
Identity is stable: `node.id == ObjectIdentifier(synthInstance)` from
the moment of add until the matching remove / free.
### View hosting
```swift
import LyrebirdUI
LyrebirdNodeTreeView(engine: engine)
```
Or bind directly to the mirror:
```swift
LyrebirdNodeTreeView(mirror: engine.nodeTreeMirror)
```
`LyrebirdEngineStatusView` already hosts a collapsible Node Tree
section above the Messages section. macOS adds an "Open Window" button
that opens a detached `LyrebirdWindow`:
```swift
LyrebirdNodeTreeView.presentInWindow(engine: engine)
```
### Persistent groups (`rootGroup` + `mainGroup`)
`rootGroup` and `mainGroup` are created at `SynthesisEngine.init`, are
flagged `_persistent = true`, and are never freed. They are visible in
the mirror snapshot from the moment the engine exists: the snapshot
root is `rootGroup`, and `mainGroup` is its sole initial child.
The engine's `engine.groupCount` excludes them by design — it tracks
user-added containers only, which makes per-test reasoning easier
(start at `0`, increment on every `engine.add(group, ...)`, decrement
on every `engine.remove` / `Group.free`). The `LyrebirdEngineStatusView`
"Groups" tile, however, displays `groupCount + 2` with an
`incl. rootGroup, mainGroup` caption so the UI surfaces the persistent
baseline. After `LyrebirdEventList.killAll()`, the tile reads `2`
(matching the tree view) rather than `0`.
The Node Tree section in `LyrebirdEngineStatusView` additionally
renders an always-visible "persistent-groups strip" — `rootGroup (N) ▸
mainGroup (N)` with live child counts pulled from the snapshot. The
strip stays on screen even when the full tree is collapsed, so the
user always has a confirmation that the two persistent containers are
alive.
### Reading order
Rows render top-to-bottom in head→tail order — the same order the RT
thread evaluates them in. This matters when reasoning about signal
flow:
- A pre-processing limiter installed via `.before(engine.mainGroup)`
appears above `mainGroup` (it runs first).
- A master reverb installed via `.after(engine.mainGroup)` appears
below `mainGroup` (it runs last).
- Inside `mainGroup`, the newest-added synth (from `engine.add(_:)`,
which inserts at head) appears at the top.
### Row affordances
Each row shows:
- Glyph: chevron for groups (clickable expand / collapse) or dot for
leaf synths.
- Display name: the Swift runtime class name (e.g. `MyVoice`) for
synths, or `Group` / `ParallelGroup` for containers.
- Child-count badge for containers: `(3)` etc.
- 4-hex identity suffix: `#a12c`. Derived deterministically from
`ObjectIdentifier.hashValue` so two `MyVoice` instances in the tree
can be told apart.
`ParallelGroup` children are populated by the main-thread `add(_:)`
calls **before** the engine adds the parent group. The mirror walks
that fixed list at parent-add time and never re-walks it; if you mutate
the children list after the parent is added, the mirror won't notice.
### Drift
The mirror drifts from the RT-thread tree only when:
- A self-terminating synth was added via `engine.add` and is never
explicitly removed (see "What does NOT update the mirror" above).
- The owning code keeps a reference to a freed group via something
other than the engine API.
Neither is fatal — drift surfaces as a stale node in the UI. Restarting
the view (or the engine) clears it.
---
## Choosing between the two
| Need | Use |
|---|---|
| Tell the user something happened | `LyrebirdMessageCenter.shared.{info,warning,error}` |
| Show the user what's running right now | Embed `LyrebirdNodeTreeView` or open via `presentInWindow` |
| Debug "is my synth actually in the graph?" | Read `engine.nodeTreeMirror.snapshot` programmatically |
| Surface engine startup / shutdown lifecycle | `SynthesisEngineListener` (pre-existing) |
The Messages + Node Tree pair gives composers a live read on both
**what the engine is doing** (node tree) and **what the engine wants
them to know** (messages). The engine status view bundles all three
(plus CPU metrics) into a single panel that drops cleanly into any
demo.
---
## See also
- `Sources/Lyrebird/Diagnostics/` — message model + center
- `Sources/Lyrebird/NodeTree/NodeTreeSnapshot.swift`, `NodeTreeMirror.swift` — tree mirror
- `Sources/LyrebirdUI/LyrebirdMessageView.swift`, `LyrebirdMessageBanner.swift`, `LyrebirdMessageHelpers.swift` — message UI
- `Sources/LyrebirdUI/LyrebirdNodeTreeView.swift` — tree UI
- `Sources/LyrebirdUI/LyrebirdEngineStatusView.swift` — bundled engine status panel hosting both
- `docs/ui/gui-system.md` — `@LiveParam` / `@UIParam` parameter binding
- `docs/01-completed-working-order.md` — diagnostics + message-center writeups
+140
View File
@@ -0,0 +1,140 @@
# Bus System
Pre-allocated at `SynthesisEngine.start()`. Never resized at runtime.
## Memory Layout
```swift
// Audio buses: 2D array, [busIndex][sampleIndex]
var audioBuses: [[Float]] // [numAudioBuses][blockSize]
// Control buses: 1D array, one value per bus
var controlBuses: [Float] // [numControlBuses]
```
## Reserved Bus Layout
```
Audio buses:
0 ..< numOutputChannels → hardware output
numOutputChannels ..< numOutputChannels + numInputChannels → hardware input
numOutputChannels + numInputChannels ..< numAudioBuses → user buses
Control buses:
0 ..< numControlBuses → all user-addressable (none reserved)
```
## Per-Cycle Semantics
At the top of each render callback:
1. **Zero all audio buses** — `audioBuses[i] = [Float](repeating: 0, count: blockSize)`
2. **Copy hardware input** — write input samples into the reserved input buses
3. **Retain control buses** — no zeroing; values persist until overwritten
At the bottom of each render callback:
4. **Copy output buses to hardware** — read buses 0..<numOutputChannels into the AudioBufferList
## `In` Generator
Reads from one or more consecutive buses. The channel count is fixed at init — no RT allocation.
```swift
// Single-channel (default)
In.Audio(bus: 5) // 1-channel generator
In.Control(bus: 10) // 1-channel, interpolated ramp
// Multi-channel — reads N consecutive buses, returns N channels
In.Audio(bus: 4, channels: 3) // reads audioBuses[4], [5], [6]
In.Control(bus: 10, channels: 2) // reads controlBuses[10] and [11]
// AudioBus object — channel count comes from the allocation
In.Audio(bus: myAudioBus) // channels == myAudioBus.channelCount
```
`floatValue` always returns the value of the first channel (bus index). Each `In.Control`
channel maintains its own ramp state (`previousOutputValue` exposes channel 0).
## `Out` Generator
Accumulates into a bus. Uses `+=` so multiple Synthesizers writing to the same bus mix.
```swift
// Audio rate — mono source writes one bus
for i in 0..<blockSize {
engine.audioBuses[busIndex][i] += inputBlock[i]
}
// Control rate
engine.controlBuses[busIndex] += inputValue
```
### Multi-channel `Out`
When the source returns N channels, `Out` writes channel `ch` to `bus + ch`:
```swift
// Stereo source (e.g. Pan2, GeneratorArray of 2) writes buses 0 and 1:
Out.Audio(bus: 0, source: Pan2(input: osc, pan: 0.0))
```
Mono sources are unaffected — they return one channel and write only `bus`.
## Multi-channel Expansion
`GeneratorArray` wraps N generators and returns an N-channel `[[LyrebirdFloat]]`.
Create one with the `expand()` helper in `build()`:
```swift
let oscs = expand([440.0, 880.0]) { OscSin.Audio(freq: $0) }
output(bus: 0, source: oscs) // bus 0 = 440 Hz, bus 1 = 880 Hz
```
Read N consecutive buses with `input(bus:channels:)`:
```swift
output(bus: 0, source: input(bus: 2, channels: 2) * 0.5)
```
See `docs/stdlib/multichannel.md` for the full MCE guide.
## Bus Allocator
`SynthesisEngine.busAllocator` manages user buses so you don't track raw integers manually.
Hardware output/input buses are pre-reserved at init; allocation starts from the first free
bus after them.
```swift
// Allocate a stereo user bus
let stereo = try engine.busAllocator.allocateAudioBus(channelCount: 2)
let ctrl = try engine.busAllocator.allocateControlBus()
// Use with convenience inits on In / Out
let reader = In.Audio(bus: stereo) // reads stereo.index (channel 0)
let multi = In.Audio.multi(bus: stereo) // GeneratorArray — both channels
let writer = Out.Audio(source: someSignal, bus: stereo) // clamped to stereo.channelCount
let ctrlIn = In.Control(bus: ctrl)
// Return when done
engine.busAllocator.releaseAudioBus(stereo)
engine.busAllocator.releaseControlBus(ctrl)
```
**Thread safety:** `BusAllocator` is protected by an internal `NSLock`; safe from any
language-side thread. Never call from the RT audio thread.
**`BusAllocatorError.noFreeBus(channelCount:)`** — thrown when no contiguous block of the
requested size is available.
### `AudioBus` and `ControlBus`
Plain value types. Pass directly to `In.Audio(bus:)`, `In.Audio.multi(bus:)`,
`Out.Audio(source:bus:)`, `In.Control(bus:)`, and `Out.Control(source:bus:)`. They are not
`ValidGeneratorInput` — for bus reading use the `In` generator wrappers.
## Defaults
| Parameter | Default |
|---|---|
| `numAudioBuses` | 128 |
| `numControlBuses` | 4096 |
| `blockSize` | Configurable at init (e.g. 512) |
+281
View File
@@ -0,0 +1,281 @@
# CoreAudioDriver — Pending Fixes
`Sources/Lyrebird/AudioDrivers/CoreAudioDriver.swift`
---
## Blocking Issues (must fix before next merge to `main`)
### 1. `print()` on the RT thread — lines 764–767
```swift
// CURRENT (broken)
if renderStatus != noErr && debugBlockCount < 3 {
print("ERROR: AudioUnitRender failed with status \(renderStatus)")
debugBlockCount += 1
}
```
**Fix:** Replace with an `Atomic<Int32>` that stores the last error code. The main thread can
inspect it later (e.g. in a debug accessor), but the RT thread never allocates or calls `print`.
```swift
// After the property declarations:
private let _lastInputRenderError = Atomic<Int32>(noErr)
// In render():
if renderStatus != noErr {
_lastInputRenderError.store(renderStatus, ordering: .relaxed)
}
```
Remove `debugBlockCount` entirely.
---
### 2. Non-atomic `isInitialized` — data race between `start()`/`stop()` and `render()`
```swift
// CURRENT (broken)
private var isInitialized: Bool = false // plain Bool — no ordering guarantee
```
`start()` and `stop()` run on the main thread; `render()` reads `isInitialized` on the RT thread.
This is an unsynchronised read/write pair — undefined behaviour under Swift's memory model.
**Fix:**
```swift
private let _isInitialized = Atomic<Bool>(false)
```
- `start()`: `_isInitialized.store(true, ordering: .releasing)` (after `AudioUnitInitialize`)
- `stop()`: `_isInitialized.store(false, ordering: .releasing)`
- `render()`: `_isInitialized.load(ordering: .acquiring)`
- `deinit`: `_isInitialized.store(false, ordering: .releasing)` before unit disposal
---
### 3. Per-sample input copy loop — unnecessary overhead
```swift
// CURRENT
for i in 0..<frameCount {
inputStagingBuffers[ch][i] = rawPtr[i]
}
```
**Fix:** Replace with `memcpy`. The raw pointer and staging buffer are already Float arrays of
the correct size.
```swift
inputStagingBuffers[ch].withUnsafeMutableBufferPointer { dst in
guard let base = dst.baseAddress else { return }
memcpy(base, rawPtr, frameCount * MemoryLayout<Float>.size)
}
```
---
## Non-Blocking Issues (clean-up, no correctness impact today)
### 4. Remove all `print()` / `DEBUG:` / `ERROR:` calls from `setup()`
There are approximately 30 `print()` calls throughout `setup()` that were scaffolding. They
allocate `String` instances and should be removed entirely. If diagnostics are needed in the
future, use `os_log` with `.debug` level (compile-time stripped in release builds).
---
### 5. Replace string-matching device selection with transport-type query
The current "last resort" device scan (lines 326–467) uses fragile string matching:
```swift
nameLower.contains("built-in")
nameLower.contains("macbook")
nameLower.contains("teams") // blocklist
nameLower.contains("zoom") // blocklist
```
This breaks under non-English locales and any device whose name doesn't match the expected
patterns.
**Fix:** Query `kAudioDevicePropertyTransportType` and compare against
`kAudioDeviceTransportTypeBuiltIn`. No string allocation, locale-independent.
```swift
private func deviceTransportType(_ deviceID: AudioDeviceID) -> UInt32 {
var transportType: UInt32 = 0
var size = UInt32(MemoryLayout<UInt32>.size)
var addr = AudioObjectPropertyAddress(
mSelector: kAudioDevicePropertyTransportType,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
AudioObjectGetPropertyData(deviceID, &addr, 0, nil, &size, &transportType)
return transportType
}
```
**Device selection order** (replaces the current chain of `if/else` blocks):
1. `defaultOutputID == defaultInputID` → use directly (ideal: USB headset, aggregate already set in system prefs)
2. `defaultOutputID` has ≥ `numInputChannels` input channels → use it
3. `defaultInputID` has ≥ `numOutputChannels` output channels → use it
4. Enumerate all devices; pick the first with `transportType == kAudioDeviceTransportTypeBuiltIn` that has both input and output → `findBuiltInDuplexDevice()`
5. Fall through to aggregate device creation (see §6)
---
### 6. Programmatic Aggregate Device creation
When no single device satisfies full-duplex requirements (step 5 above falls through), create a
private CoreAudio Aggregate Device rather than throwing an error.
**New error cases to add to `CoreAudioError`:**
```swift
case aggregateDeviceCreationFailed(OSStatus)
case microphoneAccessDenied
```
**New stored properties:**
```swift
private var aggregateDeviceID: AudioDeviceID = AudioDeviceID(kAudioObjectUnknown)
private var coreAudioPluginID: AudioObjectID = AudioObjectID(kAudioObjectUnknown)
```
**Step A — find the CoreAudio HAL plugin object:**
```swift
private func findCoreAudioPluginID() -> AudioObjectID {
// Uses AudioValueTranslation to resolve bundle ID → AudioObjectID
let bundleID = "com.apple.audio.CoreAudio" as CFString
var pluginID = AudioObjectID(kAudioObjectUnknown)
var translation = AudioValueTranslation(
mInputData: UnsafeMutableRawPointer(mutating: &bundleID as AnyObject as! UnsafeRawPointer),
mInputDataSize: UInt32(MemoryLayout<CFString>.size),
mOutputData: &pluginID,
mOutputDataSize: UInt32(MemoryLayout<AudioObjectID>.size)
)
var addr = AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyPlugInForBundleID,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
var size = UInt32(MemoryLayout<AudioValueTranslation>.size)
AudioObjectGetPropertyData(AudioObjectID(kAudioObjectSystemObject), &addr, 0, nil, &size, &translation)
return pluginID
}
```
**Step B — create the aggregate:**
```swift
private func makeAggregateDevice(
outputDeviceID: AudioDeviceID,
inputDeviceID: AudioDeviceID
) throws -> AudioDeviceID {
coreAudioPluginID = findCoreAudioPluginID()
guard coreAudioPluginID != kAudioObjectUnknown else {
throw CoreAudioError.aggregateDeviceCreationFailed(noErr)
}
// Get UIDs for both devices
let outputUID = try deviceUID(outputDeviceID)
let inputUID = try deviceUID(inputDeviceID)
// Build the composition dictionary
// Output device is master (drives the clock)
let subDeviceList: [CFDictionary] = [
[kAudioSubDeviceUIDKey: outputUID] as CFDictionary,
[kAudioSubDeviceUIDKey: inputUID] as CFDictionary,
]
let aggDesc: [String: Any] = [
kAudioAggregateDeviceNameKey: "LyrebirdAggregate",
kAudioAggregateDeviceUIDKey: "com.lyrebird.aggregate.\(UUID().uuidString)",
kAudioAggregateDeviceSubDeviceListKey: subDeviceList,
kAudioAggregateDeviceMasterSubDeviceKey: outputUID,
kAudioAggregateDeviceIsPrivateKey: 1, // auto-destroyed when plugin releases it
kAudioAggregateDeviceIsStackedKey: 0,
]
var newDeviceID = AudioDeviceID(kAudioObjectUnknown)
var addr = AudioObjectPropertyAddress(
mSelector: kAudioPlugInCreateAggregateDevice,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
let qualifier = aggDesc as CFDictionary
var size = UInt32(MemoryLayout<AudioDeviceID>.size)
let status = AudioObjectGetPropertyData(
coreAudioPluginID, &addr,
UInt32(MemoryLayout<CFDictionary>.size), [qualifier] as AnyObject,
&size, &newDeviceID
)
guard status == noErr else { throw CoreAudioError.aggregateDeviceCreationFailed(status) }
aggregateDeviceID = newDeviceID
return newDeviceID
}
```
**Step C — destroy on `stop()` and `deinit`:**
```swift
private func destroyAggregateDevice() {
guard aggregateDeviceID != AudioDeviceID(kAudioObjectUnknown),
coreAudioPluginID != AudioObjectID(kAudioObjectUnknown) else { return }
var addr = AudioObjectPropertyAddress(
mSelector: kAudioPlugInDestroyAggregateDevice,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
var deviceID = aggregateDeviceID
var size = UInt32(MemoryLayout<AudioDeviceID>.size)
AudioObjectSetPropertyData(coreAudioPluginID, &addr, 0, nil, size, &deviceID)
aggregateDeviceID = AudioDeviceID(kAudioObjectUnknown)
}
```
Call `destroyAggregateDevice()` at the top of `stop()` (before `AudioOutputUnitStop`) and in
`deinit`.
---
### 7. Named constant for bytes-per-sample
The literal `4` appears in six `AudioStreamBasicDescription` initialisers.
```swift
private let lyrebirdBytesPerSample: UInt32 = 4 // 32-bit float = 4 bytes
```
---
### 8. Microphone permission — throw instead of print
```swift
// CURRENT
} else if authStatus == .denied || authStatus == .restricted {
print("ERROR: Microphone access denied...")
}
```
**Fix:** Throw `CoreAudioError.microphoneAccessDenied` so the caller can surface it to the user.
---
## Implementation Order
1. Fix §1 (`_lastInputRenderError` + remove `debugBlockCount`) — blocking RT issue
2. Fix §2 (`_isInitialized` → `Atomic<Bool>`) — blocking data race
3. Fix §3 (`memcpy`) — trivial, same block
4. Fix §8 (throw on mic denied) — small change, clear error contract
5. Fix §7 (named constant) — cosmetic, do while touching ASBD initialisers
6. Fix §4 (remove all `print()` from `setup()`)
7. Fix §5 (transport-type device selection)
8. Fix §6 (aggregate device creation) — largest change; implement last
Run `/lyrebird_review` after all eight steps are complete.
+232
View File
@@ -0,0 +1,232 @@
# LyrebirdEventList Routing Design
## The Bug (pre-Phase X)
`LyrebirdEventList` allocated its own private `_masterBus` and, when starting any
contained `LyrebirdProcess`, passed `procOutOverride: masterBus` to
`LyrebirdProcess._play`. This **silently discarded** whatever `procOut` the
process factory had configured.
`EventListMasterSynth` then read from `_masterBus`, applied a lag-smoothed master
amplitude, and wrote to **hardcoded `outBusIndex: 0`** (hardware out).
### Symptom
A process configured with `procOut: ambisonicRoutingBus` (intending to feed an
`AmbisonicDecoder` placed `.after(engine.mainGroup)`) had its B-format output
re-routed to `_masterBus` instead of `ambisonicRoutingBus`. The downstream
decoder read silence. The master synth then wrote raw, un-decoded B-format
directly to hardware buses 0..N-1.
For a quad setup with `masterChannels: 4`, the user saw raw W/X/Y/Z components
on hardware outputs 0/1/2/3 — three "loud" channels and a flat Z (elevation = 0)
— with no spatialization at all. With the default `masterChannels: 2`, the W/X
components landed on hw 0/1 and the decoder again ran on silence.
### Why It Was Designed That Way
Early `LyrebirdEventList` used a single shared master bus to mix all owned
processes through one amplitude control, modelled after the trivial stereo
case where every process writes mono/stereo straight to hardware out and the
master synth applies a global volume. The override made wiring "just work" for
that case but is incompatible with any process that needs to feed an effect
chain (ambisonic decode, reverb send, sidechain, multi-bus stem, etc.).
## The Fix
Two coupled changes:
1. **Drop `procOutOverride`.** All three `_play` call sites in
`LyrebirdEventList` (`playEvent`, `initProcess` first-event setup,
`killProcess` teardown) pass `procOutOverride: nil`; the parameter itself
has been removed from `LyrebirdProcess._play`. The process writes to its
own declared `procOut`.
2. **Make the EventList's master bus user-supplied.** `LyrebirdEventList.init`
now takes a `bus: AudioBus` parameter (replacing `masterChannels: Int`).
Channel count is derived from `bus.channelCount`. No private bus is
allocated.
3. **Master synth applies amp in-place via `ReplaceOut`.**
`EventListMasterSynth.build()` reads N channels of `bus`, multiplies by
the lag-smoothed `amp` (mono-broadcast via `BinaryOpGenerator`'s
channel-aware policy), and overwrites the same N buses via a single
`ReplaceOut.Audio`:
let inSig = In.Audio(bus: bus) // reads bus.channelCount channels
let scaled = inSig * smoothAmp // N-channel × 1-channel → N
replaceOutput(bus: bus, source: scaled) // overwrites bus.channelCount buses
The master synth lives in `_masterGroup`, which is added as a sibling
immediately after the process group (`.after(group)`). Both groups sit
inside `engine.mainGroup` (at `.head`). The result is:
mainGroup
├── group (event-list process group, head)
│ └── processes write to their own procOut (e.g. ambisonicRoutingBus)
└── _masterGroup
├── _preMasterGroup (caller-FX, e.g. AmbisonicDecoder)
├── EventListMasterSynth (In * amp → ReplaceOut, in place)
└── _postMasterGroup (caller-FX, e.g. limiter, tap recorder)
[optional consumer placed `.after(engine.mainGroup)` reads scaled `bus`]
Order is sufficient because Lyrebird's signal-flow runs the head group
first, then `_masterGroup` (so master sees the fully-written `bus`), and
then any node placed `.after(mainGroup)`.
## Caller Responsibilities
- The caller is responsible for ensuring the `bus` passed to
`LyrebirdEventList` is the bus their `LyrebirdProcess` factories actually
write to (`procOut:` matches `bus:`). Otherwise the master amp control has
no effect on that process.
- If the caller wants no amp scaling, pass `amp: 1.0` (ReplaceOut multiplies
by 1 — effective passthrough).
- The hardware-out path is no longer hardcoded. The caller can place any
number of effects/decoders/recorders between the EventList's bus and the
hardware output, simply by adding synths at appropriate positions in the
node tree — or use ``LyrebirdEventList/addPreMaster(_:)`` /
``LyrebirdEventList/addPostMaster(_:)`` (see below).
## Historical Note — The Delta-Add Predecessor
The first cut of this refactor (before `ReplaceOut` existed) applied amp via
an additive trick on top of `Out.Audio`:
bus[ch] = bus[ch] + bus[ch] * (amp - 1)
= bus[ch] * amp
Cute but indirect — required a comment to be readable, and only generalised to
scalar amp scaling. `ReplaceOut.Audio` superseded it: same per-sample cost
(1 mul + 1 store vs 1 mul + 1 add), clearer semantics, and a primitive the
codebase can reuse for any read-transform-replace pattern (bus-level limiters,
master recorders, decoders that take ownership of hw-out buses).
## Why Not Pattern B (User Multiplies Amp In Their Chain)?
Considered: drop the master synth entirely, expose `amp` only as an
`@LiveParam` for the caller to wire into their own decoder/effect chain.
Rejected because the most common case (process writes to hardware out, single
event list) still benefits from a zero-config master amp. The current design
preserves drop-in convenience for the simple case while removing the override
that broke chained-effect cases.
## ReplaceOut Refactor
`ReplaceOut.Audio` / `ReplaceOut.Control` are first-class **overwrite** bus
write primitives parallel to `Out.Audio` / `Out.Control`. The master synth now
reads N channels of the EventList's `bus`, multiplies by the lag-smoothed
amp (mono-broadcast via the `BinaryOpGenerator` channel-aware policy), and
overwrites the same N buses via a single `ReplaceOut.Audio` call.
### ReplaceOut semantics
- Overwrites the target bus, wiping any prior writes in the current block's
`[offset, offset + count)` range.
- Multi-channel sources fan out to consecutive buses, just like `Out.Audio`.
- Inside a `ParallelGroup`, ReplaceOut routes through
`ScratchBuses.replace`, which only overwrites *this child's scratch
contribution*. Other siblings' parallel writes and any pre-existing
engine-bus content are unaffected. Outside a `ParallelGroup`, ReplaceOut
routes through `SynthesisEngine.setAudioBus`, which scrubs the engine bus
directly.
- Engine plumb: `engine.setAudioBus(_:offset:samples:count:)` writes the
bus slice via `vDSP_vdpsp` (Double → Float) directly into the bus
pointer; no accumulate scratch needed.
- `SynthesizerBase.replaceOutput(bus:source:)` mirrors
`SynthesizerBase.output(bus:source:)` — auto-registers via
`RootRegistering`.
### Trade-offs vs delta-add
| Aspect | Delta-add | ReplaceOut |
|--------|-----------|------------|
| Cost per sample | 1 mul + 1 add | 1 mul + 1 store |
| Per-channel passes | N (manual loop) | 1 (multi-channel source fans out) |
| Readability | Trick comment required | Direct read/scale/replace |
| Generalises | Specific to amp scaling | Any read-transform-replace pattern |
| Foot-guns | None | Wipes prior writes — node-tree order critical |
The cost is essentially equal at the per-sample level; ReplaceOut wins on
clarity and on enabling additional patterns (bus-level limiters, master
recorders, decoders that take ownership of hw-out buses).
## Pre/Post-Master Groups
EventList exposes two insertion groups inside `_masterGroup`:
```
mainGroup
├── group (process group, head)
│ └── processes write to their declared procOut
└── _masterGroup
├── _preMasterGroup ← caller adds decoders / pre-master FX
├── EventListMasterSynth ← reads bus, scales by amp, overwrites bus
└── _postMasterGroup ← caller adds limiters / mastering FX
```
Public API:
```swift
public var preMasterGroup: Group { _preMasterGroup }
public var postMasterGroup: Group { _postMasterGroup }
public func addPreMaster(_ synth: any Synthesizer)
public func addPostMaster(_ synth: any Synthesizer)
```
### Use cases
- **Ambisonic / multi-speaker decode**: factory writes B-format to a
routing bus; pre-master decoder reads the routing bus, decodes, writes
speaker feeds to the EventList's `bus`. Master synth then scales the
speaker feeds. Post-master synth can apply a limiter to the scaled feed.
- **Bus-level sidechain**: pre-master compressor reads control input,
reduces bus content before master amp.
- **Master recorder / tap**: post-master `DiskOut` records the final
scaled signal alongside per-process stems.
### Lifecycle
- `_preMasterGroup` and `_postMasterGroup` are constructed in
`LyrebirdEventList.init` and added to the engine in `_firstEventSetup`.
- Synths added via `addPreMaster` / `addPostMaster` are children of those
groups, so they are freed when `_masterGroup.free()` runs in
`_teardownMaster()` (which happens on `killAll`, on natural envelope
end-of-list, or on `reset()`).
- After teardown the EventList re-allocates fresh empty pre/post groups so
subsequent playback sessions start from a clean slate.
### Ordering guarantees
Group children evaluate in insertion order. `_firstEventSetup` adds, in
sequence:
1. `_preMasterGroup` at `.head(of: _masterGroup)`
2. `EventListMasterSynth` at `.tail(of: _masterGroup)` (now second)
3. `_postMasterGroup` at `.tail(of: _masterGroup)` (now third)
So evaluation order within `_masterGroup` is strictly pre → master → post.
Synths added later via `addPreMaster` / `addPostMaster` are appended to
their respective sub-group's tail; their relative order matches insertion
order.
## Migration
`LyrebirdEventList.init` signature change is breaking. Callers must replace
masterChannels: 2
with
bus: <theirAudioBus>
The `buildFromFile` static factory and recording-related code follow the same
substitution.
For callers that previously relied on the default master-to-hw-out routing
with `masterChannels: 2`: construct `let outBus = AudioBus(index: 0,
channelCount: 2)` and pass `bus: outBus`. Each process should also have its
`procOut` set to the same bus (most factories default to `procOut: 0`, which
matches). The `bus:` parameter retains a default of
`AudioBus(index: 0, channelCount: 2)` so call sites that omit it compile
unchanged.
+89
View File
@@ -0,0 +1,89 @@
# Multi-Core Audio
Two supported patterns for spreading synthesis work across CPU cores.
---
## ParallelGroup
`ParallelGroup` is a `Synthesizer` node that evaluates its children concurrently via `DispatchQueue.concurrentPerform`. Each child writes into a pre-allocated per-child scratch copy of `engine.audioBuses`. After the concurrent barrier, all scratch slots are summed into the real buses via `vDSP_vadd`.
### Architecture
- `segmentSerial` in `SynthesisEngine` is `Atomic<UInt64>`. Write is a single releasing `wrappingAdd` before concurrent evaluation; reads in concurrent workers use an acquiring load.
- `SynthGraph` carries an optional `ScratchBuses?` reference (`_scratchBuses`). Non-nil when evaluating inside a `ParallelGroup` child.
- `Out.Audio._computeSamples` calls `graph.addSamplesToAudioBus(...)` which routes to `ScratchBuses.accumulate(...)` (scratch path) or `engine.addToAudioBus(...)` (normal path).
- `SynthesizerBase.evaluate` forwards `_scratchBuses` when constructing `localGraph`, so the full downstream generator DAG writes to the same scratch slot.
- Each `ScratchBuses` instance owns a `conversionScratch: [Float]` for `vDSP_vdpsp` (Double→Float), avoiding races on the engine's `_busAccumulateScratch`.
### Clear and merge use busOffset
`ScratchBuses.clearDirtyBuses(offset:count:)` zeroes only the segment's sample range, and only for buses any child wrote since the last clear (tracked in a per-slot `dirty: [Bool]` mask updated inside `accumulate`). After clearing, the mask is reset; children's writes during this segment re-populate it; the merge pass then reads the mask and skips `vDSP_vadd` on buses left untouched. With the default 128 audio buses and a child that writes to two of them (a typical stereo voice), this drops both the clear and merge passes from 128 vDSP calls per child per segment down to 2. The merge pass still reads `srcBase.advanced(by: offset)` and writes to `dstBase.advanced(by: offset)`, correctly handling sub-block segments.
### Limitations
- **Cross-child generator fan-out:** sharing a `Generator` instance between two children races on `_segmentSerial`/`_cachedResult`. Each child must own its DAG exclusively.
- **Control bus writes:** `Out.Control` is not scratch-buffered. Same-index writes from concurrent children race.
- **Nested `ParallelGroup`s:** an inner group's merge pass writes directly to `engine.audioBuses`, bypassing the outer group's scratch.
- **Dynamic child mutation:** children are snapshotted into `childrenSnapshot` in `build()`. Mutating the child list while the group is active is a data race.
### Memory cost
`numChildren × numAudioBuses × blockSize × sizeof(Float)` per group, plus one `blockSize`-Float conversion scratch per child. Allocated in `build()` (off RT); never resized.
---
## Multiple Engine Instances
Each `SynthesisEngine` is fully independent: separate `audioBuses`, `controlBuses`, `sharedTables`, `segmentSerial`, root `Group`, scheduling queues, and `AudioDriver`. Two engines on separate threads use two cores with no shared state.
**Device constraint:** Core Audio grants exclusive AUHAL ownership per output device. Two engines cannot both drive the same hardware output simultaneously. This pattern is suited to NRT rendering (one engine per output file) or separate output devices.
No code changes are required — this works with the existing API. The `EngineHost` facade is the blessed entry point for multi-engine use (creation-owning, role-based, NRT pool, lifecycle serialisation). Single-engine code stays on the direct `SynthesisEngine()` constructor unchanged.
### Object ownership rules
Two engines do not magically share object graphs. Runtime binding checks enforce one-engine ownership at the points where a synth or buffer crosses the engine boundary.
**Synthesizer**
- One `SynthesizerBase` instance binds to exactly one `SynthesisEngine` for the period it lives in that engine's node tree.
- Bound on `engine.add(_:)` / `engine.add(_:position:)` / `engine.schedule(_:at:)` / `engine.schedule(_:after:)` via a single-shot atomic compare-exchange.
- Cleared on `engine.remove(_:)` after the matching `processBlock` cycle.
- Cross-engine sharing throws `EngineAddError.boundToOtherEngine(current:prior:)` — both UUIDs are reported.
- Same-engine re-add without an intervening `remove` throws `EngineAddError.doubleAdd(engine:)`.
- Pattern for "the same synth, on two engines": construct a fresh instance per engine. Synth construction is cheap; the build closure is the canonical place to express the graph.
**LyrebirdBuffer**
`LyrebirdBuffer` has an **opt-in** two-tier binding API. Single-engine code does not need to touch it — the default behaviour matches the legacy unbound state and the existing tear-free language-side write model is preserved.
| Tier | API | Semantics |
|------|-----|-----------|
| Exclusive | `try buffer.bindExclusive(to: engine)` + `buffer.unbindExclusive(from: engine)` | Single-engine ownership. Throws `EngineAddError.boundToOtherEngine` if any read-only holder or a different exclusive engine holds the buffer. |
| Read-only share | `try buffer.bindReadOnly(to: engine)` + `buffer.unbindReadOnly(from: engine)` | Any number of engines may hold read-only shares concurrently. Throws `EngineAddError.boundToOtherEngine` if an exclusive engine holds the buffer. Refcount-based — the refcount does not track per-engine identity. |
The tiers are mutually exclusive: `bindReadOnly` fails when an exclusive bind is in force, and `bindExclusive` fails when the read-only refcount is non-zero.
**Read-only invariant.** Callers holding a read-only share must not invoke `setValue`, `setRangeValues`, `clear`, `fill*`, or `invalidate`. This is documented but not runtime-enforced — existing mutation API stays unguarded to preserve the legacy tear-free single-engine write model. Audit at the binding site.
**Canonical cross-engine wavetable share pattern:**
```swift
let wavetable: LyrebirdBuffer = LyrebirdBuffer(count: 4096)
wavetable.fillSine() // mutate while unbound
try wavetable.bindReadOnly(to: engineA)
try wavetable.bindReadOnly(to: engineB)
// both engines read the same wavetable concurrently …
wavetable.unbindReadOnly(from: engineA)
wavetable.unbindReadOnly(from: engineB)
```
**Lifecycle coordination**
Process-wide `EngineLifecycleCoordinator` (internal singleton) tracks every live engine via `WeakEngineRef` keyed by `SynthesisEngine.identifier`. The coordinator's `withLifecycleLock(_:)` is the chokepoint intended to wrap `engine.start()` / `engine.stop()` calls so that concurrent start/stop across two engines cannot interleave on the `freeWorker.sync` teardown drain. The `EngineHost` uses this lock in `startAll` / `stopAll`; direct-ctor callers that drive their own multi-engine lifecycle should serialise start/stop on the caller side, or migrate to the host.
**See also:** [`docs/engine/multi-engine-host.md`](multi-engine-host.md) for the role-based, creation-owning `EngineHost` facade including the NRT pool API.
+317
View File
@@ -0,0 +1,317 @@
# EngineHost — Multi-Engine Facade
Creation-owning facade for processes that need **two or more** `SynthesisEngine` instances.
Single-engine code does **not** use the host. Direct `SynthesisEngine()` construction remains the supported path for N = 1. The host adds nothing for the single-engine case that the `EngineLifecycleCoordinator` registry does not already provide.
---
## When to use the host
- **NRT batch render** — render N audio files in parallel, one engine per file. Use `renderConcurrent(jobs:)`.
- **Multi-device RT output** — drive two separate audio devices (e.g. headphone + main + sub) from one process, one engine per AUHAL device.
- **Auxiliary engines** — analysis-only side engines, decoder side-chains, scope taps that should be lifecycle-managed with the rest of the process.
- **Test fixtures** — wrap a small set of engines for unified start/stop in integration tests.
If your process uses one engine throughout, do not introduce the host. The direct constructor + binding APIs cover the single-engine case.
---
## Role-based registration
Every engine the host manages carries a `EngineHostRole`:
```swift
public enum EngineHostRole: Hashable, Sendable {
case nrtRender(slot: Int)
case rtOutput(deviceID: UInt32)
case auxiliary(name: String)
case custom(String)
}
```
| Case | Purpose | Uniqueness enforcement |
|---|---|---|
| `.nrtRender(slot:)` | NRT batch render slot | Role-identity (slot index) |
| `.rtOutput(deviceID:)` | Realtime AUHAL output | Role-identity + per-device |
| `.auxiliary(name:)` | Non-output engine | Role-identity (name string) |
| `.custom(String)` | Escape hatch | Role-identity (string) |
The host throws `EngineHostError.duplicateRole(role)` on any second registration under the same role. For `.rtOutput(deviceID:)`, same deviceID implies the same role (deviceID is part of the role's `Hashable` key), so duplicate device registration surfaces as `.duplicateRole`. AUHAL grants exclusive ownership per output device on macOS — the host's role-keyed registry enforces this at the API. (There is no separate `.duplicateDevice` enum case — it would be unreachable given the role-keyed design; re-add one only if a future role shape ever cross-cuts deviceID under a different surrounding case.)
**`.rtOutput.deviceID` semantics.** On macOS the `UInt32` is the raw bit pattern of `CoreAudio.AudioDeviceID`. On iOS the type carries no native meaning (RemoteIO does not address individual hardware devices — `AVAudioSession` routes are chosen at the session layer). Pass `0` for the default iOS route, or any caller-defined unique value if you want host-level uniqueness checks against other RT engines.
---
## Creation: `makeEngine(role:config:)`
```swift
let host = EngineHost()
let cfg = SynthesisEngineConfig(
blockSize: 256,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
driver: CoreAudioDriver()
)
let engine = try host.makeEngine(role: .rtOutput(deviceID: 0), config: cfg)
```
`SynthesisEngineConfig` mirrors `SynthesisEngine.init` one-for-one with the same defaults. It is a value-typed carrier so callers don't thread eight parameters through every `makeEngine` call.
The returned engine is held strongly by the host. Caller may keep its own reference but the host's strong reference is the primary owner.
---
## Lookup
```swift
let engine: SynthesisEngine? = host.engine(for: .nrtRender(slot: 0))
let role: EngineHostRole? = host.role(for: someEngine)
let all: [SynthesisEngine] = host.engines // snapshot, unordered
let allRoles: [EngineHostRole] = host.roles
let n: Int = host.engineCount
```
All accessors hold the host's internal `NSLock` briefly; snapshots return arrays so callers can iterate without holding any lock.
---
## Lifecycle: `startAll()` / `stopAll()`
```swift
try host.startAll()
defer { host.stopAll() }
```
`startAll()` walks the registered engines from a snapshot taken under the host's lock, then calls `engine.start()` on each **outside the lock**. Concurrent host accessors (`engine(for:)`, `engineCount`, other `makeEngine` / `adopt` callers) are not blocked during the start sequence. Iteration order over the role dictionary is not stable; if your scenario requires a specific start ordering, register engines and start them explicitly via `engine(for:)`.
**Snapshot race window.** A `makeEngine` / `adopt` that commits between the snapshot and the loop end will leave its engine unstarted by this `startAll` call. Call `startAll()` once after all registrations complete, or serialise registration and startup on the caller side.
**Rollback on failure.** If one engine throws during start, every previously-started engine is rolled back with `engine.stop()` before the host throws `EngineHostError.startFailed(engine:underlying:)`. Partial start states are not exposed to the caller.
`stopAll()` is the reverse — `engine.stop()` is idempotent so calling `stopAll()` on a never-started or partially-started host is safe.
---
## Adoption: `adopt(existing:role:)`
Escape hatch for **migration** scenarios (existing direct-ctor code wanting to opt into host lifecycle without re-construction) and **test fixtures** (an engine constructed by a test helper that needs host registration after the fact):
```swift
let engine = SynthesisEngine(blockSize: 256, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 0,
driver: someDriver)
try host.adopt(existing: engine, role: .custom("imported"))
```
The host verifies the engine is visible in `EngineLifecycleCoordinator.shared.engines` before accepting — guards against passing a deinit-in-progress engine or one constructed via an unsupported path. Throws `EngineHostError.adoptRejected(engine:reason:)` if the verification fails.
After adoption the engine is indistinguishable from a `makeEngine`-constructed engine: same role-keyed lookup, same `startAll`/`stopAll` participation.
---
## NRT batch render: `renderConcurrent(jobs:maxConcurrent:)`
The blessed entry point for "render N audio files in parallel."
```swift
let host = EngineHost()
let jobs: [NRTJob] = mixes.enumerated().map { i, mix in
NRTJob(
outputURL: outDir.appendingPathComponent("mix_\(i).caf"),
duration: 4.0,
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2
) { engine in
try engine.add(mix.makeRouteSynth())
}
}
for try await result in host.renderConcurrent(jobs: jobs, maxConcurrent: 4) {
print("rendered \(result.outputURL.lastPathComponent) in \(result.elapsed) s")
}
```
### Job descriptors
`NRTJob` is a `Sendable` value carrying everything needed to spin up one engine and render one file:
| Field | Purpose |
|---|---|
| `outputURL: URL` | Destination CAF file |
| `duration: Double` | Render duration in seconds |
| `blockSize: Int` | Engine block size (defaults to `lyrebirdDefaultResultBufferSize = 512`) |
| `sampleRate: Double` | Engine sample rate |
| `numOutputChannels: Int` | 2 / 4 / 8 channel render |
| `inputURL: URL?` | Optional source file for processing jobs |
| `inputStartOffset: Double` | Seconds to skip into `inputURL` |
| `build: @Sendable (SynthesisEngine) throws -> Void` | Closure adding synths before render |
The `build` closure runs on the background `Task` executing the job — it must be `@Sendable` (no captures of non-Sendable state, no mutation of shared mutable references). Engine binding enforces that synthesizers added to one job's engine cannot leak into another job's engine.
### Completion records
`NRTResult` is yielded per successful render:
```swift
public struct NRTResult: Sendable {
public let outputURL: URL
public let jobIndex: Int // correlation back to input array
public let elapsed: Double // wall-clock seconds
}
```
**Results stream in completion order, not input order.** Use `jobIndex` to correlate results back to the original job list.
### Concurrency
`maxConcurrent` defaults to `ProcessInfo.processInfo.activeProcessorCount` and is clamped to `[1, jobs.count]`. The host drives a `withThrowingTaskGroup` with a seed-and-refill pattern: initial `maxConcurrent` jobs spawn; each completion triggers spawn of the next queued job until the input is exhausted.
### Failure semantics
If any job throws (from its `build` closure, from `engine.start()`, or from the `NRTDriver`), the throw propagates via the `AsyncThrowingStream`'s throw path. Iterate with `for try await`:
```swift
do {
for try await result in host.renderConcurrent(jobs: jobs) { … }
} catch let error as DeliberateBuildFailure {
// handle
}
```
Behaviour on throw:
- The throwing job's error propagates through the AsyncThrowingStream.
- `withThrowingTaskGroup` cancels the remaining child tasks when the body's `for try await` rethrows, and the refill loop's `addTaskUnlessCancelled` no longer spawns queued jobs.
- Cancellation propagates only as a flag — child tasks check `Task.isCancelled` cooperatively. `_executeJob` calls `engine.start()` which renders synchronously without cancellation checks, so any in-flight render runs to completion regardless of cancellation. Their results are discarded (the stream is finished by the time they return).
The stream is single-shot — once it finishes (clean end or throw), no further results arrive.
### Pool engines are not host-registered
NRT pool jobs spin up their engines **inline** — they are not registered in the host's role map. The engine lives for the duration of one render and deinits when the executing function returns. `EngineLifecycleCoordinator`'s auto register/unregister still applies.
This means:
- `host.engines` does **not** include pool jobs (the host's role map and the pool are independent facilities).
- Cancelling the stream cancels the underlying Task; in-flight engines stop naturally as their `engine.start()` returns.
---
## Drawbacks (acknowledged)
1. **New top-level public type.** API-stability commitment. If the role enum gains new cases (e.g. `.scope`, `.midiClock`) in a future phase, those additions are non-breaking — but renaming/removing cases is a major version bump.
2. **God-object risk.** The host is deliberately scoped to lifecycle + ownership registry + NRT pool. Routing stays in the bus system; scheduling stays per-engine; MIDI / OSC stay unchanged. Avoid expanding the host's responsibilities.
3. **Adoption optional.** Multi-engine bug reports without a host present require triage of "do you have an `EngineHost`?" as the first question.
---
## Drawbacks of NOT using the host
If you spin up two engines manually (direct `SynthesisEngine()` × 2) without a host, you lose:
- Role-keyed uniqueness check — nothing prevents two engines from binding to the same AUHAL device until the second one's `start()` fails at the driver layer.
- `startAll` / `stopAll` rollback semantics — you must hand-roll the partial-start cleanup.
- The `renderConcurrent` NRT pool API.
The `EngineLifecycleCoordinator` still tracks the engines, and binding errors still surface — but the convenience layer is missing.
---
## Caveats and footguns
Non-blocking findings that affect users of the host.
### NRT pool memory cost on high-core systems
`renderConcurrent`'s default `maxConcurrent: ProcessInfo.processInfo.activeProcessorCount` × per-engine working set can be large.
Per-engine memory at a glance (steady state):
| Component | Size |
|---|---|
| `audioBuses` | `numAudioBuses × blockSize × sizeof(Float)` |
| `controlBuses` | `numControlBuses × sizeof(Float)` |
| `_busAccumulateScratch` | `blockSize × sizeof(Float)` |
| `ScratchBuses` (per `ParallelGroup` child) | `numChildren × numAudioBuses × blockSize × sizeof(Float)` |
| Generator output buffers (per generator) | `lyrebirdDefaultResultBufferSize × numChannels × sizeof(Double)` |
On an M3 Max (16 cores) running stereo 48kHz with `numAudioBuses = 128`, `blockSize = 512`, the bus alone is ~2.5 MB × 16 ≈ 40 MB before any synth graph. iOS / memory-constrained Mac can OOM under the default cap.
**Mitigation.** Cap `maxConcurrent` to `min(4, activeProcessorCount)` on mobile / shared-memory targets, or size the cap to your render-time budget × per-render working set on desktop. Set explicitly:
```swift
let cap = max(1, ProcessInfo.processInfo.activeProcessorCount - 2)
for try await result in host.renderConcurrent(jobs: jobs, maxConcurrent: cap) { … }
```
### In-flight NRT jobs continue writing to disk after stream cancellation
`engine.start()` renders synchronously without cooperative-cancellation checks. Caller break → in-flight renders run to completion → CAF files land on disk → results are discarded by the closed `for try await` loop. Users expect "cancellation = no files left behind."
**Mitigation.** Track the expected output URLs on the caller side; on cancellation, walk the set and delete any URLs that did not receive a corresponding `NRTResult`:
```swift
var pending: Set<URL> = Set(jobs.map(\.outputURL))
do {
for try await result in host.renderConcurrent(jobs: jobs) {
pending.remove(result.outputURL)
if shouldCancel { break }
}
} catch { … }
// `pending` now contains URLs for jobs that either never ran, or ran
// and landed on disk after the loop broke. Either case is cleanup.
for url in pending {
try? FileManager.default.removeItem(at: url)
}
```
### Cross-job synth-instance sharing trips engine binding
If you share a `Synthesizer` instance across `NRTJob.build` closures (captured by a job-list-building loop without re-construction), the first job binds the synth to its engine via the `_engineBinding` CAS. Subsequent jobs then throw `EngineAddError.boundToOtherEngine` — surprising because the first engine is "gone" from the caller's perspective.
The binding atomic survives the first engine's `deinit`. Either:
- An explicit `engine.remove(synth)` on the bound engine clears the binding (but pool engines deinit when `_executeJob` returns — there is no opportunity for a caller-side `remove`).
- A subsequent `_bind` on a different engine triggers the stale-pointer recovery path. The recovery is bounded by a documented address-reuse known limit — if Swift's allocator places the new engine at the freed engine's exact address, the new bind misclassifies as `.doubleAdd`. See `Tests/LyrebirdTests/MultiEngineRegressionTests.swift::bindRecoversFromStaleEnginePointer` for the test that exercises this.
**Mitigation.** Construct fresh synth instances **inside** the `build` closure, not in the outer job-list-building scope:
```swift
// WRONG — synth is captured once and bound to job 0's engine.
let synth = MySynth()
let jobs = (0..<4).map { i in
NRTJob(...) { engine in try engine.add(synth) }
}
// RIGHT — each build closure constructs its own synth.
let jobs = (0..<4).map { i in
NRTJob(...) { engine in try engine.add(MySynth()) }
}
```
### Cooperative thread pool starvation on long renders
`_executeJob` runs a synchronous NRT render on a regular `Task` → occupies one cooperative-pool slot for the full render duration. With `maxConcurrent` = `activeProcessorCount`, the entire Swift global executor is parked for the render. Other async work in the same process stalls until at least one render completes and frees a slot.
**Mitigation (user-side).** Cap `maxConcurrent` below `activeProcessorCount` to leave headroom:
```swift
let cap = max(1, ProcessInfo.processInfo.activeProcessorCount - 2)
```
**Mitigation (future host change, deferred).** Dispatch `_executeJob` onto a dedicated `DispatchQueue.global(qos: .userInitiated)` and bridge to the `Task` via continuation. Decouples renders from the cooperative pool entirely. Tracked as a future change.
### `adopt(existing:role:)` TOCTOU is benign
`adopt` verifies the engine is live via `EngineLifecycleCoordinator.shared.engines` outside the host lock, then commits the registration under the host lock. The engine could deinit between the two — but Swift ARC guarantees the engine stays alive once the host's strong reference is acquired at commit time. The original strong-ref holder racing `deinit` either had a strong ref the whole time (no deinit) or already lost the ref by the time the coordinator's weak ref was non-nil at check time (engine cannot have started `deinit` while a strong ref existed).
**No user mitigation required** — the race is benign by ARC semantics. Surfaced here so users do not assume `adopt` needs external locking.
## See also
- `docs/engine/synthesis-engine.md` § Engine Identity, Ownership Binding
- `docs/engine/multi-core.md` § Multiple Engine Instances, Object ownership rules
- `Tests/LyrebirdTests/EngineHostTests.swift` — 14 host-coverage tests
- `Tests/LyrebirdTests/MultiEngineRegressionTests.swift::twoEnginesViaHostUniformityContract` — host-variant of the two-engine concurrent regression test, proves the host-driven path produces the same observable behaviour as direct-ctor
+223
View File
@@ -0,0 +1,223 @@
# Scheduling & Event Timing
## Design Goals
- Synthesizers are fully allocated **before** entering the signal tree — the RT thread never allocates
- Events are scheduled with a `SampleTime` target — sample-accurate start within a block
- Freed Synthesizers are deallocated **after** leaving the signal tree — the RT thread never frees
- Freeing is block-accurate (synth runs to end of block, then removed) — inaudible because envelopes decay to zero
## SampleTime
```swift
typealias SampleTime = Int64 // monotonic sample counter, updated each block
```
The engine exposes:
```swift
engine.currentTime // SampleTime at the start of the current (or most recent) block
engine.seconds(_ d: Double) -> SampleTime // convenience: d * sampleRate
```
## Three Lock-Free Queues
```
Main thread RT audio thread Background thread
─────────── ─────────────── ─────────────────
allocate Synthesizer
schedule(synth, at: T) → [pendingQueue] → insert at sample T
evaluate tree
done synths → [freeQueue] → ARC release (deinit)
update param at T → [paramQueue] → apply at sample T
```
All three are `SPSCQueue<T>` instances — single-producer/single-consumer ring buffers using `Synchronization.Atomic` (requires macOS 15+).
## SPSCQueue
Fixed-capacity ring buffer. Capacity set at engine init (default 1024 per queue). No allocation after init.
```swift
import Synchronization
final class SPSCQueue<T> {
private var buffer: [T?]
private let capacity: Int // must be power of 2
private let writeIdx = Atomic<Int>(0)
private let readIdx = Atomic<Int>(0)
init(capacity: Int) { ... } // capacity rounded up to next power of 2
// Called from producer (main thread) only
func enqueue(_ value: T) -> Bool
// Called from consumer (RT thread) only
func dequeue() -> T?
}
```
## ScheduledEvent
```swift
// Internal — the pointer-only payload handed to the RT thread. Synth/node
// allocation and retain happen on the main thread before enqueue.
internal enum ScheduledEvent {
case add(PreparedNode, at: SampleTime)
case remove(any Synthesizer, retainedRef: Unmanaged<AnyObject>, at: SampleTime)
case addNode(PreparedNode, NodePosition, at: SampleTime)
case groupFree(Group, parentGroup: Group?, at: SampleTime)
}
```
Parameter updates are **not** queue events — they are atomic stores on
`@LiveParam` / `@UIParam` properties, picked up by the RT thread on the next
(sub-)block. See below.
## Scheduling API (SynthesisEngine)
```swift
// Schedule a synth to start at an absolute sample time
try engine.schedule(synth, at: engine.currentTime + engine.seconds(2.0))
// Convenience: seconds from now
try engine.schedule(synth, after: 2.0)
// Immediately (next block boundary)
try engine.add(synth) // or: try engine.schedule(synth, at: engine.currentTime)
// Update a parameter — atomic store on a @LiveParam, no scheduling API
synth.freq = 880.0 // applied on the next (sub-)block
// Remove a synth at a future time (returns Bool — non-throwing)
engine.remove(synth, at: engine.currentTime + engine.seconds(4.0))
```
## processBlock — Sub-block Splitting
Each block, events whose `targetTime` falls within `[currentTime, currentTime + blockSize)` are applied mid-block at the correct sample offset. This gives sample-accurate start times.
```
currentBlockStart = engine.currentTime
1. Zero audio buses, copy hardware input to input buses
2. Drain pendingQueue → collect events in [currentBlockStart, currentBlockStart + blockSize)
Sort by targetTime
3. Evaluate in segments:
cursor = 0
for each event E at offset = E.targetTime - currentBlockStart:
if offset > cursor:
tree.evaluate(count: offset - cursor, busOffset: cursor)
applyEvent(E) ← pointer-only: add/remove node, update parameter
cursor = offset
tree.evaluate(count: blockSize - cursor, busOffset: cursor)
4. Collect synths with doneAction == .freeNode → post Unmanaged refs to freeQueue
5. currentTime += blockSize
```
Events scheduled before `currentBlockStart` (i.e., in the past) are applied immediately at `offset = 0`.
## Generator Interface — count Parameter
Because segments are variable length, generators produce `count` samples rather than always `blockSize`:
```swift
protocol Generator {
func calculatedSamples(graph: SynthGraph, count: Int) -> [[LyrebirdFloat]]
}
```
Stateful generators (phase accumulators, filter memory, delay write heads) advance by exactly `count` samples per call. This ensures correct timing even when a block is split.
## Out Generator — busOffset
The `Out` generator writes into the bus at the correct position:
```swift
// Audio rate Out — writes count samples starting at busOffset
for i in 0..<count {
engine.audioBuses[busIndex][busOffset + i] += inputBlock[i]
}
```
For segments before a new synth is inserted, the new synth's `Out` has not yet run — those bus positions remain zero (or whatever prior synths wrote).
## Block-Accurate Freeing
When a generator signals `doneAction: .freeNode`, the Synthesizer is flagged during the current block's evaluation. After the block is fully evaluated:
- The Synthesizer is removed from the signal tree (pointer update only)
- An `Unmanaged<any Synthesizer>` reference is posted to `freeQueue`
- A background `DispatchQueue` drains `freeQueue` and calls `.release()` — ARC deinit runs off RT
The synth runs to the natural end of the block. Since envelopes decay to zero before signalling done, there is no audible click.
## Memory Safety Invariants
| Thread | May do | Must not do |
|---|---|---|
| Main / REPL | Allocate Synthesizer, post to pendingQueue, read currentTime | Write directly to signal tree |
| RT callback | Read/write bus memory, evaluate generators, atomic index reads | Allocate, deallocate, lock, block |
| Background | Drain freeQueue, call ARC release, read/write non-RT state | Post to pendingQueue from multiple threads simultaneously |
## Non-Real-Time (NRT) Rendering
NRT rendering shares the entire scheduling stack — `SampleTime`, `SPSCQueue`, `ScheduledEvent`, sub-block splitting — with no engine changes. The only difference is the driver.
### NRTDriver
```swift
NRTDriver(outputURL: URL, duration: Double)
```
`start()` runs a tight synchronous loop:
```
while currentTime < totalSamples:
engine.processBlock(inputSamples: silence)
append audioBuses[0..<numOutputChannels] to output file
// currentTime advances inside processBlock
```
After the loop, the output file is finalised and `stop()` is called automatically. `start()` blocks until rendering is complete — appropriate for scripts and score workflows.
Output is written via `ExtAudioFile` (AudioToolbox) as AIFF or WAV. No additional framework dependencies beyond what `CoreAudioDriver` already uses.
### Score Pattern
Pre-schedule all events before calling `start()`. The pending queue holds them until the engine clock reaches each event's `SampleTime`:
```swift
let engine = SynthesisEngine(
blockSize: 512, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 0,
driver: NRTDriver(outputURL: url, duration: 10.0)
)
// Schedule the score
try engine.schedule(pad, at: 0)
try engine.schedule(kick, at: engine.seconds(0.0))
try engine.schedule(kick, at: engine.seconds(0.5))
try engine.schedule(kick, at: engine.seconds(1.0))
engine.remove(pad, at: engine.seconds(8.0)) // returns Bool — non-throwing
try engine.start() // renders synchronously, writes file, returns when done
```
### Termination
**Initial implementation: fixed duration.** The caller specifies total render length at `NRTDriver` init. The loop runs for exactly `ceil(duration * sampleRate / blockSize)` blocks.
**Stretch goal (future):** Event-driven termination — stop when the pending queue is empty *and* the node tree is empty (all synths have freed themselves). This enables rendering a score of unknown length without specifying duration upfront.
### NRT vs OfflineDriver
| Driver | Purpose |
|---|---|
| `OfflineDriver` | Tests — no-op, no output, `processBlock` called manually |
| `NRTDriver` | Score rendering — drives engine, writes audio file |
`OfflineDriver` remains the right choice for unit tests because it gives full control: call `processBlock` directly, inspect `audioBuses[]` immediately.
## macOS Version Note
`Synchronization.Atomic` requires macOS 15+. The package platform target is `.macOS(.v15)`.
+286
View File
@@ -0,0 +1,286 @@
# SynthesisEngine
The central object that owns Core Audio I/O and drives the signal graph.
## Initialization
```swift
SynthesisEngine(
blockSize: Int, // samples per render callback (e.g. 512)
sampleRate: Double, // e.g. 44100, 48000
numOutputChannels: Int, // hardware output channels (e.g. 2)
numInputChannels: Int, // hardware input channels (e.g. 2)
numAudioBuses: Int, // default 128
numControlBuses: Int // default 4096
)
```
`SynthesisEngine.init` also allocates and fills `sharedTables` (see below) on the calling
(non-RT) thread, so shared tables are ready before the first render callback.
## Shared Lookup Tables
```swift
engine.sharedTables.sineTable // LyrebirdBuffer — 32768-sample sine wave
engine.sharedTables.hanningTable // LyrebirdBuffer — 32768-sample Hanning window
```
`sharedTables` is a `public let SharedTables` instance created in `init`. All tables
use `lyrebirdDefaultTableSize` (32768) samples. Tables are never invalidated during the
engine's lifetime — generators that read from shared tables do not need to check `isValid`.
Access from generators via `graph.engine.sharedTables.sineTable` inside `calculatedSamples`.
The table reference should be cached as an ivar at `init` time (like `OscSin` does) to avoid
any per-block property traversal on the RT thread.
### User-allocated buffers (`LyrebirdBuffer`)
```swift
let buf = LyrebirdBuffer(count: lyrebirdDefaultTableSize) // allocate off RT thread
buf.fillSine() // fill before scheduling
let osc = OscTable.Audio(table: buf, freq: 440.0)
try engine.add(mySynth) // buf now in RT use — do not fill again
// Later, on the main thread:
buf.invalidate() // RT thread sees isValid == false, outputs silence
engine.remove(mySynth) // ARC releases buf when synth is freed via freeQueue
```
- Fill methods (`fill(with:)`, `fill(using:)`, `fillSine()`, `fillHanning()`) must be called
**before** the buffer enters RT use. Calling them while a generator holds the buffer in a
running engine is an unsynchronized data race.
- `invalidate()` is RT-safe (releasing atomic store). The RT thread reads `isValid` with an
acquiring load before accessing samples.
## Core Audio Setup (AUHAL)
Use `kAudioUnitSubType_HALOutput` — **not** `DefaultOutput`. Only `HALOutput` supports full-duplex I/O (both input and output on the same unit). `DefaultOutput` does not support input and will fail with `-10879` when `EnableIO` is requested on the input element.
```swift
var outputUnit: AudioComponentInstance
// 1. Find the HAL output audio component (supports full duplex)
var desc = AudioComponentDescription(
componentType: kAudioUnitType_Output,
componentSubType: kAudioUnitSubType_HALOutput, // NOT DefaultOutput
componentManufacturer: kAudioUnitManufacturer_Apple,
componentFlags: 0, componentFlagsMask: 0
)
let component = AudioComponentFindNext(nil, &desc)
AudioComponentInstanceNew(component, &outputUnit)
// 2. Enable output on element 0 (required for HALOutput — not automatic)
var enableOutput: UInt32 = 1
AudioUnitSetProperty(outputUnit,
kAudioOutputUnitProperty_EnableIO,
kAudioUnitScope_Output, 0,
&enableOutput, UInt32(MemoryLayout<UInt32>.size))
// 3. Enable input on element 1
var enableInput: UInt32 = 1
AudioUnitSetProperty(outputUnit,
kAudioOutputUnitProperty_EnableIO,
kAudioUnitScope_Input, 1,
&enableInput, UInt32(MemoryLayout<UInt32>.size))
// 4. Set stream format (match engine sampleRate, numOutputChannels)
// Apply to output scope element 0 and input scope element 1
// 5. Set max frames per slice
var maxFrames = UInt32(blockSize)
AudioUnitSetProperty(outputUnit,
kAudioUnitProperty_MaximumFramesPerSlice,
kAudioUnitScope_Global, 0,
&maxFrames, UInt32(MemoryLayout<UInt32>.size))
// 6. Install render callback
var callbackStruct = AURenderCallbackStruct(
inputProc: lyrebirdRenderCallback, // module-level @convention(c) free function
inputProcRefCon: Unmanaged.passUnretained(self).toOpaque()
)
AudioUnitSetProperty(outputUnit,
kAudioUnitProperty_SetRenderCallback,
kAudioUnitScope_Input, 0,
&callbackStruct, UInt32(MemoryLayout<AURenderCallbackStruct>.size))
// 7. Initialize and start
AudioUnitInitialize(outputUnit)
AudioOutputUnitStart(outputUnit)
```
Input staging buffers (one `AudioBufferList` per input channel) are pre-allocated during `setup()` — **never** in the render callback.
### Microphone Permission
When `numInputChannels > 0`, the host process needs explicit OS permission before AUHAL delivers non-zero input frames. System requirement, not Lyrebird-specific — applies to every Lyrebird host (CLI tool, SwiftUI app, scaffolded Xcode project, AUv3 host).
Templates do **not** pre-wire microphone capability because most pieces are output-only and would otherwise trigger a permission prompt on every first run for no reason. The project owner adds it when needed:
- **macOS** — add `NSMicrophoneUsageDescription` (string explaining the use) to the target's `Info.plist`. Sandboxed apps additionally need `com.apple.security.device.audio-input` in the `.entitlements`. A plain `swift run` CLI tool inherits Terminal's TCC grant: the user accepts the prompt for Terminal once and subsequent CLI runs from that shell get input.
- **iOS** — add `NSMicrophoneUsageDescription` to `Info.plist`, **and** set the `AVAudioSession` category to `.playAndRecord` (not `.playback`, which is output-only and returns zero-filled input regardless of `numInputChannels`).
Until the user grants permission the input buses stay zero-filled. Failure mode is silent: an `In` generator returns silence, a `ScopeCapture` tap on input buses draws a flat line, no error is thrown by the driver. (TODO #8 in [`core-audio-driver.md`](core-audio-driver.md) — surface `CoreAudioError.microphoneAccessDenied` instead of silently logging.) See [`project-system.md`](../tooling/project-system.md) for per-template specifics on where these fields live in scaffolded projects.
## Render Callback
Runs on the **real-time audio thread**. Must not allocate, lock, or block.
The callback is a module-level `@convention(c)` free function (`lyrebirdRenderCallback`). It recovers the engine via `Unmanaged.fromOpaque(inRefCon).takeUnretainedValue()`.
```swift
// Pseudocode — actual implementation in CoreAudioDriver.swift
func lyrebirdRenderCallback(...) -> OSStatus {
// 1. Read hardware input via AudioUnitRender on element 1
// (into pre-allocated staging buffers — no allocation here)
// 2. Build [[Float]] view over staging buffers
// 3. engine.processBlock(inputSamples:)
// → zeros audio buses, copies input, evaluates node tree
// 4. memcpy audioBuses[0..<numOutputChannels] → ioData AudioBufferList
return noErr
}
```
`processBlock` returns `Void` — callers read `engine.audioBuses[]` directly after the call. This avoids any allocation on the RT thread.
Each call to `processBlock` may invoke `evaluateSegment` one or more times (once per
sub-block when scheduled events split the block). `evaluateSegment` constructs a
`SynthGraph` value to pass into `rootGroup.evaluate`. The `SynthGraph` needs a
`_parameterTable` reference even at the root level (before any `SynthesizerBase.evaluate`
replaces it with the synth's own table). To avoid a `ParameterTable()` heap allocation on
every `evaluateSegment` call, `SynthesisEngine` pre-allocates a single empty
`_emptyParameterTable` in `init` and passes it via the internal
`SynthGraph(engine:busOffset:parameterTable:)` init. The empty table's `inputs` dictionary
is never written to after construction; `SynthesizerBase.evaluate` always overwrites
`_parameterTable` with the per-synthesizer table before any generator reads it.
## Lock-Free Graph Mutation
- Main thread builds a new node tree snapshot
- Posts it via a lock-free queue (e.g. single-producer single-consumer ring buffer) or `OSAtomicCompareAndSwap` on a pointer
- RT callback reads the current pointer atomically at the top of each block
- No locks, no `DispatchQueue` on the RT thread
## Lifecycle
```swift
try engine.start() // allocates bus memory, calls driver.setup() + driver.start()
engine.stop() // calls driver.stop(), sets isRunning = false
```
`start()` is idempotent — calling it when already running is a no-op. `stop()` is safe to call multiple times.
Bus memory (`audioBuses`, `controlBuses`) is allocated in `start()` and is empty before start. After `stop()`, the existing bus arrays remain in memory but are not updated further.
## Engine Identity
Every `SynthesisEngine` carries a process-unique `identifier: UUID`, assigned at `init` and immutable for the engine's lifetime. The identifier surfaces in:
- `EngineAddError.boundToOtherEngine(current: UUID, prior: UUID)` and `.doubleAdd(engine: UUID)` diagnostics.
- The internal `EngineLifecycleCoordinator` registry, which holds weak references to every live engine keyed by `identifier`. The coordinator is the registration target for the `EngineHost` facade and the lookup source for translating raw engine pointers back to UUIDs in binding error messages.
## Ownership Binding (`engine.add` throws)
`engine.add(_:)`, `engine.add(_:position:)`, `engine.schedule(_:at:)`, and `engine.schedule(_:after:)` are throwing methods:
```swift
public func add(_ synth: any Synthesizer) throws
public func add(_ synth: any Synthesizer, position: NodePosition) throws
public func schedule(_ synth: any Synthesizer, at time: SampleTime) throws
public func schedule(_ synth: any Synthesizer, after seconds: Double) throws
```
All four throw `EngineAddError`:
| Case | When |
|------|------|
| `.boundToOtherEngine(current:prior:)` | Synth is already bound to a different `SynthesisEngine`. Build a fresh instance per engine; one Synthesizer instance is bound to one engine for its lifetime. |
| `.doubleAdd(engine:)` | Synth is already active in this engine's node tree. Call `engine.remove(synth)` and allow at least one `processBlock` before re-adding the same instance. |
| `.pendingQueueFull` | The engine's `pendingQueue` SPSC queue was full when the add event was posted. Reduce add cadence or increase `eventQueueCapacity` at engine init. |
| `.rebuildFailed(underlying:)` | Reserved for future use — `rebuildGraph()` does not throw in the current implementation. Listed for forward compatibility. |
Internally, every add path calls `synth._bind(to: self)` before any RT-visible side effect. `_bind` is a single-shot acquire-release `compareExchange` on `SynthesizerBase._engineBinding: Atomic<UInt>` storing the raw bit pattern of an `UnsafeMutableRawPointer` to the bound engine. Zero RT cost — the binding atomic is read only on the main thread during add. `remove(_:)` synchronously calls `_unbind` on successful enqueue so a subsequent re-add (after one `processBlock`) does not collide with `.doubleAdd`.
`Group` instances are not bound — they are persistent node-tree fixtures and do not subclass `SynthesizerBase`.
`LyrebirdBuffer` has an opt-in two-tier binding API for cross-engine sharing — see [Multi-Core Audio § Multiple Engines](multi-core.md) and the `EngineHost` doc.
## CPU Statistics
`SynthesisEngine` tracks real-time CPU load and exposes two thread-safe read properties:
```swift
engine.averageCPU // Double — exponential moving average (α=0.1) of load per block
engine.peakCPU // Double — peak load since last reset (auto-resets every 5 s)
```
Both express load as a fraction of one nominal block duration: `0.0` = idle, `1.0` = full block
consumed, `> 1.0` = over budget (xruns likely). Manual reset:
```swift
engine.resetPeakCPU() // releases to 0.0 immediately; timer also fires every 5 s
```
**Threading:** both properties use `Atomic<UInt64>.load(ordering: .relaxed)` — safe to read from
any thread at any time. The RT callback writes via releasing atomic stores on every `processBlock`
call. The automatic reset fires on a background `DispatchQueue` (the same `lyrebird.free` worker
used for deallocation).
**LyrebirdStatusView** (in `LyrebirdUI`) wraps these properties in a compact embeddable SwiftUI
view that polls at 10 Hz and renders color-coded bars — see [GUI System](../ui/gui-system.md).
## Scope Tap (ScopeCapture)
`ScopeCapture` is an optional real-time audio bus tap that feeds a double-buffered
ring to the UI for oscilloscope display.
```swift
let scope = ScopeCapture(buses: [0, 1], bufferSize: 2048)
engine.scopeTap = scope // set before start()
try engine.start()
// In a SwiftUI view:
LyrebirdScopeView(capture: scope)
.frame(height: 120)
```
**How it works:**
- `ScopeCapture` holds two ping-pong `[[Float]]` buffers (each `bufferSize` samples
per channel). The RT thread writes into the "back" buffer; when it fills, it atomically
swaps front/back. The main thread calls `snapshot()` to get a deep copy of the most
recently completed front buffer.
- `SynthesisEngine` caches the tap as `Unmanaged<ScopeCapture>` at `start()` time
(in `_rtScopeTap`) to avoid ARC retain/release on the RT thread. Set `scopeTap` before
calling `start()` — changes after `start()` are not picked up.
- At the end of each `processBlock`, the engine calls `_rtScopeTap?.takeUnretainedValue().write(...)`.
No allocation occurs on the RT path: `write` uses `withUnsafeMutableBufferPointer` +
`assign(from:count:)` for raw pointer copies.
**RT safety invariants:**
- CoW sharing from `[Float](repeating:)` init is broken in `ScopeCapture.init`
via `withUnsafeMutableBufferPointer { _ in }` on every inner buffer before the RT thread starts.
- `snapshot()` copies via `Array($0)` from `UnsafeBufferPointer` — does not increase the
CoW refcount of the internal front buffer; RT writes to the back buffer never CoW-allocate.
- `bufferSize` must be ≥ the engine's `blockSize`. Enforced by `precondition` in `write()`.
```swift
// ScopeCapture init
public init(buses: [Int], bufferSize: Int = 2048)
// Called from processBlock (RT thread) — no allocation
public func write(audioBuses: [[Float]], count: Int)
// Called from main thread — returns a deep copy
public func snapshot() -> [[Float]] // [channelIndex][sampleIndex]
```
See `Sources/Lyrebird/Capture/ScopeCapture.swift` and `LyrebirdScopeView` in
`docs/ui/gui-system.md`.
## Threading Rules
| Thread | Allowed | Not Allowed |
|---|---|---|
| RT callback | Read bus memory, evaluate generators, atomic pointer reads, `Unmanaged.takeUnretainedValue()` | Allocate memory, take locks, call Swift runtime, print, ARC retain/release |
| Main thread | Allocate, lock, build graphs, post to lock-free queue, `scope.snapshot()` | Write directly to bus memory during a running callback |
+337
View File
@@ -0,0 +1,337 @@
# Authoring a Lyrebird Extension Package
End-to-end walk-through for building an out-of-tree Swift package that adds
`Generator` or `Synthesizer` implementations on top of Lyrebird.
The companion document is [`docs/protocols/extension-sdk.md`](protocols/extension-sdk.md),
which lists every public + SPI symbol your package may depend on. This guide
shows how to wire it together, ship a versioned release, and avoid the common
pitfalls.
`LyrebirdATK` (the FOA toolkit, extracted from Lyrebird core in v0.9.1) is the
canonical worked example. Repository layout, `Package.swift` shape, and test-helper
patterns below all match LyrebirdATK exactly — clone it as a starting template.
## Why a separate package?
- **Namespace isolation.** Your module's types live under your module name; no
collisions with core Lyrebird or other extension packages.
- **Independent release cadence.** Tag and publish on your own schedule. Users
pin the version range they want for your package, independently of Lyrebird.
- **Independent hosting.** Anywhere SwiftPM can fetch from — GitHub, GitLab,
Bitbucket, self-hosted git, or a local path during development.
## Naming conventions
These are conventions, not compiler rules. Reviewers may suggest changes if
they make your package harder to integrate.
| What | Convention | Example |
|---|---|---|
| Package / module name | `Lyrebird<Vendor>` | `LyrebirdATK`, `LyrebirdJoshFX` |
| Type prefix | Domain-meaningful | `Foa*`, `Hoa*`, `Pd*` |
| Parameter-key prefix | `<package>.<param>` | `"atk.azimuth"` |
| Source files | One public type per file | `FoaRotate.swift`, not `FoaTransforms.swift` |
| Test suite per type | `<TypeName>Tests.swift` | `FoaRotateTests.swift` |
## Repository layout
```
LyrebirdMyPackage/
├── Package.swift
├── README.md
├── LICENSE
├── .gitignore
├── docs/
│ └── MyPackage-Guide.md ← authoritative reference
├── scripts/
│ └── <any data-build scripts>
├── Sources/
│ └── LyrebirdMyPackage/
│ ├── MyGenerator.swift
│ ├── ...
│ └── Resources/ ← optional, processed by SwiftPM
└── Tests/
└── LyrebirdMyPackageTests/
├── Helpers/
│ └── TestHelpers.swift ← engine/graph fixtures
├── MyGeneratorTests.swift
└── ...
```
Same loose-file-at-root rule as core: every `.swift` lives in a subfolder. Use
`Sources/<Module>/<Group>/` to group large families.
## `Package.swift`
```swift
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "LyrebirdMyPackage",
platforms: [.macOS(.v15), .iOS(.v18)],
products: [
.library(name: "LyrebirdMyPackage", targets: ["LyrebirdMyPackage"]),
],
dependencies: [
// Pin tightly to the Lyrebird MINOR range — @_spi(LyrebirdExtensions)
// symbols are documented as MINOR-mutable.
.package(
url: "https://realizedsound.mooo.com/josh/Lyrebird.git",
"0.9.1" ..< "1.0.0"
),
],
targets: [
.target(
name: "LyrebirdMyPackage",
dependencies: [
.product(name: "Lyrebird", package: "Lyrebird"),
],
// Drop the next clause if you ship no resources.
resources: [.process("Resources")],
linkerSettings: [
.linkedFramework("Accelerate"), // only if you call vDSP
]
),
.testTarget(
name: "LyrebirdMyPackageTests",
dependencies: ["LyrebirdMyPackage"]
),
]
)
```
The `package: "Lyrebird"` argument matches the last path component of the
dependency URL (`Lyrebird.git` → `Lyrebird`), case-insensitive. SPM is strict
about this; mismatches produce an unhelpful "unknown package" error.
### Pre-publication / private-repo dependencies
If you are pulling Lyrebird from a private repository, use the SSH URL form:
```swift
.package(
url: "git@realizedsound.mooo.com:josh/Lyrebird.git",
"0.9.1" ..< "1.0.0"
)
```
SPM resolves SSH URLs through your existing SSH agent. Once Lyrebird is
publicly hosted, swap to the HTTPS URL.
### Local-path dependency during development
While iterating on both Lyrebird and your extension in parallel, prefer a
local path:
```swift
.package(path: "../Lyrebird")
```
The `package:` name in the target dependency is then the directory name
(`"Lyrebird"`). Switch back to the version dep before tagging.
## Importing Lyrebird
Every source file in your module that uses RT-safe helpers needs the SPI
import:
```swift
import Foundation
@_spi(LyrebirdExtensions) import LyrebirdSynth
```
The plain `import LyrebirdSynth` is enough for files that only touch the stable
public API. Pick one form per file; both is harmless but noisy.
Inside your test files, you generally want **both** access modes:
```swift
import Testing
import Foundation
import LyrebirdSynth
@_spi(LyrebirdExtensions) import LyrebirdSynth
@testable import LyrebirdMyPackage
```
`@testable` is what lets your tests reach `internal` types inside your own
module (e.g. helper structs and base classes that you keep `internal` because
they are implementation details). It does **not** grant SPI access on its own —
that is what the explicit `@_spi(LyrebirdExtensions)` import is for.
## Writing a Generator
Identical to the in-tree recipe in
[`docs/protocols/writing-generators.md`](protocols/writing-generators.md). Two
points to internalise:
1. Subclass `GeneratorBase`. Inherit `_segmentSerial` / `_cachedResult` /
`_subBlockBuffer` — do **not** redeclare them. `_setupSubBlockBuffer()` is
called from `ControlGenerator.Control.init` after `super.init()`.
2. Use the shared RT-safe helpers. Inlining them is a review violation. Full
table: writing-generators.md §13. SPI surface: extension-sdk.md.
Minimal example — an audio-rate gain stage:
```swift
@_spi(LyrebirdExtensions) import LyrebirdSynth
public final class MyGain: GeneratorBase, AudioGenerator {
private let _input: any ValidGeneratorInput
private var _result: [[Double]]
private let _mulAdd: MulAddSpec
public override var outputChannelCount: Int { 1 }
public init(
input: any ValidGeneratorInput,
gain: any ValidGeneratorInput = 1.0,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
_input = input
_result = [[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)]
_mulAdd = MulAddSpec(mul: gain * mul, add: add)
super.init()
}
public func floatValue(graph: SynthGraph) -> Double {
calculatedSamples(graph: graph, count: graph.engine.blockSize).first?.first ?? 0.0
}
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
precondition(count <= _result[0].count,
"MyGain: count \(count) exceeds buffer \(_result[0].count)")
let src = _input.calculatedSamples(graph: graph, count: count)
let row = src.first ?? []
for i in 0..<count { _result[0][i] = row.indices.contains(i) ? row[i] : 0 }
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
}
```
## Bundled resources
If your package needs to ship binary data (HRIR files, wavetables, IRs):
1. Place the file under `Sources/LyrebirdMyPackage/Resources/<subdir>/foo.bin`.
2. Declare `resources: [.process("Resources")]` on the target.
3. Look the file up at runtime via `Bundle.module` **from a file inside your
module** — `Bundle.module` resolves to your package's resource bundle, not
Lyrebird's.
```swift
public extension MyType {
static var bundledFoo: URL {
guard let url = Bundle.module.url(forResource: "foo", withExtension: "bin")
else { preconditionFailure("foo.bin missing from LyrebirdMyPackage bundle") }
return url
}
}
```
SwiftPM's `.process(...)` flattens subdirectories, so the lookup uses the file
name only (no subdir prefix).
LyrebirdATK's `HRIRFile+BundledKEMAR.swift` is the reference
implementation.
## Writing tests
Tests live in `Tests/LyrebirdMyPackageTests/`. Use Swift Testing
(`@Test`, `#expect`, `@Suite`), not XCTest.
You will need a small local `TestHelpers.swift` mirroring the core engine /
graph fixtures. Lyrebird's in-tree `TestHelpers.swift` is `internal` to the
core test target and not part of the published API; reproduce only the helpers
you need:
```swift
import Testing
import LyrebirdSynth
@_spi(LyrebirdExtensions) import LyrebirdSynth
func makeTestEngine(blockSize: Int = 512, sampleRate: Double = 44_100) -> SynthesisEngine {
SynthesisEngine(
blockSize: blockSize,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 2,
numAudioBuses: 128,
numControlBuses: 4_096,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
}
func makeSynthGraph(engine: SynthesisEngine, busOffset: Int = 0) -> SynthGraph {
SynthGraph(engine: engine, busOffset: busOffset)
}
/// Advance the fan-out cache serial — call between back-to-back
/// `calculatedSamples` invocations on the same generator within one test.
func advanceBlock(_ engine: SynthesisEngine) {
engine.advanceSegmentSerial()
}
```
`SynthesisEngine.advanceSegmentSerial()` is `@_spi(LyrebirdExtensions)` —
that is why the test helper file imports the SPI surface explicitly.
## Versioning your package
Follow SemVer:
- **MAJOR** — source-breaking changes (renamed types, removed APIs, changed
function signatures, behaviour changes that break existing user code).
- **MINOR** — additive (new generators, new init parameters with defaults,
new optional behaviour).
- **PATCH** — bug fixes, doc updates, internal refactors.
Document your Lyrebird-compatibility range in the README:
```markdown
## Compatibility matrix
| LyrebirdMyPackage | Lyrebird |
|---|---|
| 0.1.x | 0.9.x |
| 0.2.x | 0.10.x |
| 1.0.x | 1.0.x |
```
When Lyrebird's MINOR rolls over, audit the SPI diff before bumping your
support range — `@_spi(LyrebirdExtensions)` is the only API tier where
signatures may change in a Lyrebird MINOR.
Tag releases as `vMAJOR.MINOR.PATCH`:
```bash
git tag -a v0.1.0 -m "Initial release"
git push origin v0.1.0
```
## Reviewing your package
The Lyrebird review agents (`lyrebird_review_agent`, `pr_review_agent`) live
in core's `.claude/agents/`. To run them against your extension package, copy
or symlink the agent definitions into your own `.claude/agents/` directory.
Both agents are RT-safety focused and will flag the same kinds of issues they
catch in core (force unwraps, magic numbers, helper inlining, missing dual
doc comments).
You can also run `swift test` from CI against the lowest and highest pinned
Lyrebird versions in your compatibility range — this catches accidental SPI
breakage early.
## Reference
| Topic | Where |
|---|---|
| Stable public + SPI surface | [`docs/protocols/extension-sdk.md`](protocols/extension-sdk.md) |
| Generator implementation rules | [`docs/protocols/writing-generators.md`](protocols/writing-generators.md) |
| Shared RT-safe helpers (§13) | [`docs/protocols/writing-generators.md`](protocols/writing-generators.md) |
| Synthesizer protocol | [`docs/protocols/synthesizer.md`](protocols/synthesizer.md) |
| Worked example | `LyrebirdATK` — clone its `Package.swift`, `Sources/`, `Tests/`, README, LICENSE as templates |
+138
View File
@@ -0,0 +1,138 @@
# Lyrebird Extension SDK
This document lists the public surface available to **out-of-tree Swift packages** that add
`Generator` or `Synthesizer` implementations on top of the `Lyrebird` core module.
The surface is split into two stability tiers:
1. **Stable public API** — covered by Lyrebird's SemVer. Breaking changes only on a MAJOR
version bump.
2. **`@_spi(LyrebirdExtensions)` API** — low-level RT helpers that extension packages need
to implement generators correctly. Signatures may evolve in MINOR releases; pin tightly
if you depend on these (`.upToNextMinor(from:)`).
## Importing
```swift
import LyrebirdSynth // stable public API
@_spi(LyrebirdExtensions) import LyrebirdSynth // stable + SPI helpers
```
Only declare the SPI import in files that need it. Consumers of your extension package never
need the SPI import — they import your module and use its public types.
## Tier 1 — Stable public API
### Generator protocol & base
| Symbol | File |
|---|---|
| `protocol Generator` | `GeneratorCore/Generator.swift` |
| `protocol AudioGenerator` | `GeneratorCore/Generator.swift` |
| `protocol ControlGenerator` | `GeneratorCore/Generator.swift` |
| `class GeneratorBase` | `GeneratorCore/GeneratorBase.swift` |
| `protocol GeneratorEnum` | `GeneratorCore/GeneratorTypes.swift` |
| `enum ProcessingRate` | `GeneratorCore/GeneratorTypes.swift` |
| `class GeneratorArray` | `GeneratorCore/GeneratorArray.swift` |
| `+ - * /` operators on `GeneratorArray` | `GeneratorCore/GeneratorArray.swift` |
| `func expand<G: Generator>(...)` | `GeneratorCore/GeneratorArray.swift` |
### Generator input
| Symbol | File |
|---|---|
| `protocol ValidGeneratorInput` | `GeneratorCore/ValidGeneratorInput.swift` |
| `protocol ConstantGeneratorInput` | `GeneratorCore/ValidGeneratorInput.swift` |
| `struct Closure` | `GeneratorCore/ValidGeneratorInput.swift` |
| `typealias ClosureBody` | `GeneratorCore/ValidGeneratorInput.swift` |
### `GeneratorBase` storage (you read/write these in your subclass)
| Symbol | Visibility |
|---|---|
| `var _segmentSerial: UInt64` | `public` |
| `var _cachedResult: [[Double]]` | `public` |
| `var _subBlockBuffer: [[Double]]` | `public` |
| `func _setupSubBlockBuffer(channels: Int = 1)` | `public` |
### Synthesizer side (parameter & graph)
| Symbol | File |
|---|---|
| `struct SynthGraph` | `Synthesizer/SynthGraph.swift` |
| `class SynthesisEngine` | `Engine/SynthesisEngine.swift` |
| `@propertyWrapper struct LiveParam` | `Parameters/LiveParam.swift` |
| `protocol LiveParameterWrapper` | `Parameters/LiveParam.swift` |
| `protocol LiveParameterValue` | `Parameters/LiveParam.swift` |
| `final class ParameterNode` | `Parameters/ParameterNode.swift` |
### Resources / data types
| Symbol | File |
|---|---|
| `struct HRIRFile` | `Buffers/HRIRFile.swift` |
| `let lyrebirdDefaultResultBufferSize: Int` | `Math/LyrebirdConstants.swift` |
## Tier 2 — `@_spi(LyrebirdExtensions)` API
These RT-safe helpers are mandatory when implementing new generators. They are SPI to keep
the public Lyrebird API surface small for application code, but are stable enough to use
across MINOR versions; pin extension packages to a specific MINOR range and bump explicitly
when Lyrebird's MINOR rolls over.
### MulAdd helpers (`GeneratorCore/MulAdd.swift`)
| Symbol | Signature |
|---|---|
| `struct MulAddSpec` | stored `mul`/`add` inputs + precomputed identity flag |
| `MulAddSpec.init(mul:add:)` | call at `init` time |
| `MulAddSpec.applyIfNeeded(to:graph:count:)` | call at end of `_computeSamples` |
| `MulAddSpec.apply(to:graph:count:)` | unconditional apply (rare; prefer `applyIfNeeded`) |
| `MulAddSpec.identity` | static — for generators with no `mul`/`add` knobs |
| `func extractScalar(_:)` | init-time scalar detection |
| `func fillRampedResult(into:from:to:mulAdd:graph:count:)` | ControlGenerator ramp helper |
| `func lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` | block-constant capture from a generator input |
### PRNG (`Generators/Noise/WhiteNoise.swift`)
| Symbol | Signature |
|---|---|
| `func xorshift64NextRaw(_:)` | raw `UInt64` step |
| `func xorshift64Next(_:)` | step → `Double` in `[-1, 1]` |
### Test-helper hooks (`Engine/SynthesisEngine.swift`)
For out-of-tree extension packages building their own `advanceBlock`-style test helpers:
| Symbol | Signature |
|---|---|
| `SynthesisEngine.segmentSerial` | acquiring load (read-only) |
| `SynthesisEngine.advanceSegmentSerial()` | wrapping increment — call between back-to-back `calculatedSamples` calls in tests to simulate a block boundary |
## Versioning policy
Lyrebird 1.x:
- Stable public API: SemVer. Breaking change → 2.0.
- `@_spi(LyrebirdExtensions)` API: signatures may change in MINOR releases. Extension
packages should pin tightly:
```swift
.package(url: "...Lyrebird", "1.4.0"..<"1.5.0")
```
## Namespacing guidance
- **Module name**: prefer `Lyrebird<Vendor>` (e.g. `LyrebirdATK`). Swift module names already
prevent type collisions; the prefix makes the dependency obvious in `Package.swift`.
- **Type prefix**: match your domain (`Foa*`, `Hoa*`, `Pd*`, …). Keep it short and consistent
within the package.
- **Parameter-key prefix**: when your `Synthesizer` reads parameters by string key, prefix
them (`"atk.azimuth"`, not `"azimuth"`) to avoid collisions in user code that mixes
multiple extension packages.
## See also
- [Writing Generators](writing-generators.md) — full generator-author guide.
- `docs/extension-authors-guide.md` — end-to-end walkthrough of building and publishing an
extension package, using `LyrebirdATK` as a worked example.
+280
View File
@@ -0,0 +1,280 @@
# Generator Protocol
The base unit of signal production in Lyrebird.
## Protocol Hierarchy
```swift
protocol Generator: AnyObject {
var rate: ProcessingRate { get }
func calculatedSamples(graph: SynthGraph, count: Int) -> [[LyrebirdFloat]]
func floatValue(graph: SynthGraph) -> LyrebirdFloat
}
protocol AudioGenerator: Generator {} // rate == .audio
protocol ControlGenerator: Generator {} // rate == .control
enum ProcessingRate {
case audio // sample rate (e.g. 44100 Hz)
case control // block rate (e.g. 44100 / blockSize Hz)
case spectral // integer multiple of control rate
case demand // marks the DemandGenerator value-source tier; Demand.Audio/Control report .audio/.control
}
/// Marks a caseless namespace enum whose nested Audio and Control classes are a matched
/// generator pair. Conforming types declare AudioType and ControlType so documentation,
/// generic code, and tooling can discover the pair at compile time.
protocol GeneratorEnum {
associatedtype AudioType: AudioGenerator
associatedtype ControlType: ControlGenerator
}
```
## Control-Rate Variants
Paired generators use an `enum` namespace with nested `Audio` and `Control` classes (e.g. `OscSin.Audio`, `OscSin.Control`). The `Control` variant conforms to
`ControlGenerator` instead of `AudioGenerator`. The `Control` variant runs once per block rather
than once per sample, trading temporal resolution for CPU efficiency.
### When to create a Control variant
Create a `Control` variant when **all** of the following are true:
1. **The generator produces an independent signal** — it has its own internal state (phase
accumulator, PRNG, period counter) that advances over time without depending on an audio-rate
input buffer.
2. **It is commonly used as a modulator (LFO), not audio content** — the output is wired to a
parameter input of another generator rather than to an `Out` bus directly.
3. **Block-rate accuracy is sufficient** — oscillator frequencies below roughly
`sampleRate / (blockSize × 4)` are indistinguishable from audio-rate in practice; noise and
impulse generators are similarly well-served at block rate.
Current generators that meet all three criteria: `OscSin`, `OscTable`, `Impulse`, `WhiteNoise`,
`LFStepNoise`, `LFLineNoise`.
### When NOT to create a Control variant
| Generator type | Reason |
|---|---|
| Filters (`RBJLowPass`, `ButterworthLowPass`, etc.) | Input-driven; filters already accept control-rate input via the interpolated ramp mechanism — no separate class needed |
| Delay lines (`DelayLine`, `DelayLineFeedback`) | Require audio-rate state; a block-rate delay makes no acoustical sense |
| Math generators (`BinaryOpGenerator`, `BipolarMappingGenerator`, `UnipolarMappingGenerator`, etc.) | Rate follows their inputs; they have no independent state to run at a different rate |
| `EnvelopeGen.Audio` | Amplitude envelopes — per-sample shape accuracy is essential for click-free fade-outs and fast transients |
### How downstream consumers interact with Control-rate generators
A `ControlGenerator`'s `_computeSamples` override produces a full `blockSize`-sample
**interpolated ramp** from the previous block's output value to the current block's output value.
This means any `AudioGenerator` that calls `calculatedSamples(count: blockSize)` on a
`ControlGenerator` input receives a smooth audio-rate buffer — the filter or oscillator is
unaware of the source rate. No special handling is required in the downstream generator.
### Naming convention (enum namespace pattern)
Use an `enum` namespace with nested `_Base`, `Audio`, and `Control` classes. Both classes live in the same source file. Add a `GeneratorEnum` conformance extension at the bottom of the file to advertise the pair.
```
OscSin.Audio / OscSin.Control — OscSin.swift
OscTable.Audio / OscTable.Control — OscTable.swift
Impulse.Audio / Impulse.Control — Impulse.swift
WhiteNoise.Audio / WhiteNoise.Control — WhiteNoise.swift
LFStepNoise.Audio / LFStepNoise.Control — LFNoise.swift
LFLineNoise.Audio / LFLineNoise.Control — LFNoise.swift
EnvelopeGen.Audio / EnvelopeGen.Control — EnvelopeGen.swift
PlayBuffer.Audio / PlayBuffer.Control — PlayBuffer.swift
RecordBuffer.Audio / RecordBuffer.Control — RecordBuffer.swift
In.Audio / In.Control — In.swift
Out.Audio / Out.Control — Out.swift
SendTrigger.Audio / SendTrigger.Control — SendTrigger.swift
Demand.Audio / Demand.Control — Demand/Demand.swift
```
Every namespace enum adds a `GeneratorEnum` extension:
```swift
extension OscSin: GeneratorEnum {
public typealias AudioType = OscSin.Audio
public typealias ControlType = OscSin.Control
}
```
This lets generic code and DocC resolve the pair at compile time:
```swift
func describe<G: GeneratorEnum>(_ type: G.Type) {
print("Audio:", G.AudioType.self, "Control:", G.ControlType.self)
}
describe(OscSin.self) // Audio: OscSin.Audio Control: OscSin.Control
```
---
## Type Aliases
```swift
typealias LyrebirdFloat = Double
typealias LyrebirdInt = Int
typealias LyrebirdFloatClosureBody = (SynthGraph, Int) -> LyrebirdFloat
```
## ValidGeneratorInput Protocol
Enables seamless mixing of constants, generators, parameter keys, and closures as generator inputs. All of the following are valid:
```swift
OscSin.Audio(freq: 440.0) // Float literal
OscSin.Audio(freq: someGenerator) // another Generator
OscSin.Audio(freq: "FreqParam") // string parameter key — resolved at runtime
OscSin.Audio(freq: { g, i in ... }) // closure
```
```swift
protocol ValidGeneratorInput {
func calculatedSamples(graph: SynthGraph, count: Int) -> [[LyrebirdFloat]]
func floatValue(graph: SynthGraph) -> LyrebirdFloat
func intValue(graph: SynthGraph) -> LyrebirdInt
func needsInterpolation() -> Bool
func sampleBlock(graph: SynthGraph, count: Int, previousValue: LyrebirdFloat) -> [LyrebirdFloat]
}
// Conforming types: Double, Int, String, any Generator, Closure
// Contract: calculatedSamples must always return a non-empty outer array (at least one channel).
```
## Operator Overloading
Math operators on Generator inputs create `BinaryOpGenerator` instances:
```swift
let sig = OscSin.Audio(freq: 440) * 0.5 // BinaryOpGenerator (*)
let mix = sig1 + sig2 // BinaryOpGenerator (+)
```
Operators: `*`, `+`, `-`, `/`
### Operator Precedence
The overloads reuse Swift's standard operator symbols, so **standard Swift precedence applies**:
| Operators | Precedence group | Associativity |
|---|---|---|
| `*`, `/` | `MultiplicationPrecedence` | left |
| `+`, `-` | `AdditionPrecedence` | left |
`*` and `/` bind before `+` and `-`; equal-precedence operators are left-to-right:
```swift
osc * 0.5 + env // → (osc * 0.5) + env
osc + env * 0.5 // → osc + (env * 0.5)
osc - env - lfo // → (osc - env) - lfo (left-associative)
(osc + env) * 0.5 // parentheses work normally
```
Note: `Double op Double` always resolves to the Swift stdlib — not a `BinaryOpGenerator`. At
least one operand must be a `Generator` or `any ValidGeneratorInput`.
### BinaryOpGenerator — multi-channel broadcasting
`BinaryOpGenerator` reads each operand's `outputChannelCount` at construction time and
allocates `_result` to `max(lhs, rhs)` rows. Per-channel rules:
- `1 × 1` → 1-row output (classic mono).
- `1 × N` or `N × 1` → N-row output, mono operand broadcasts to every channel.
- `N × N` → N-row output, element-wise.
- `N × M` with both > 1 and N ≠ M → `precondition` traps at `init`. No implicit
wrap-extend, no truncation. Compose explicitly via `ChannelSelect` or `GeneratorArray`.
`outputChannelCount` is a `Generator` protocol requirement (default `1` from `GeneratorBase`).
Multi-row generators (`Pan2`, `Pan4`, `PanN`, `AmbiEncoder1/Decoder1`, `SVF`,
`FrequencyShifter.Audio`, `Chorus.Audio`, `GeneratorArray`, `TimeStretch.Audio`, multi-channel
`In` / `BufferRead` / `PlayBuffer`, etc.) must override it. A missing override silently
mono-izes the generator under arithmetic.
> **Channel-aware `mul:` / `add:`** — `MulAddSpec.apply` follows the same broadcast policy
> as `BinaryOpGenerator`: mono `mul`/`add` broadcasts across every output channel; `mul`/`add`
> matching the output channel count applies per-channel; mismatched multi-row inputs trap at
> the apply site. The `*` operator and `mul:` parameter now have parallel semantics.
### BinaryOpGenerator — scalar fast-path
When one or both operands are non-Generator literals (`Double` or `Int`), `BinaryOpGenerator`
uses `floatValue` instead of `calculatedSamples` for that side. This avoids the per-block
`[[LyrebirdFloat](repeating:count:)]` heap allocation that the `Double`/`Int` conformers would
otherwise produce. The classification is performed once in `init` and stored as `lhsIsLiteral`
/ `rhsIsLiteral` — no type-metadata checks on the RT thread.
```swift
// Fast path: rhs is a literal — only the generator side calls calculatedSamples.
let sig = OscSin.Audio(freq: 440) * 0.5 // 0.5 → floatValue; OscSin → calculatedSamples
// Both time-varying: both sides call calculatedSamples.
let am = OscSin.Audio(freq: 440) * OscSin.Audio(freq: 2.0)
```
### Fan-out caching
A single `Generator` instance can safely feed multiple downstream consumers. The segment-serial
fan-out cache ensures `_computeSamples` is called exactly once per `evaluateSegment`
call regardless of how many consumers evaluate the same generator. State advances by exactly
`count` samples per block — no double-advance artefacts.
```swift
// osc is shared between two signal paths — fan-out cache ensures one evaluation per block:
let osc = OscSin.Audio(freq: 440)
let fm = OscSin.Audio(freq: osc * 200 + 880) // osc as FM modulator
let mix = fm * 0.3 + osc * 0.05 // osc also in direct mix
output(bus: 0, source: Pan2(input: mix))
```
## count: Int Parameter
The `count` parameter in `calculatedSamples(graph:count:)` specifies exactly how many samples to
produce. This is normally `blockSize`, but during sub-block splitting (scheduling) it may be
smaller — a segment from event boundary to event boundary within a block.
Generators **must** advance their stateful accumulators by exactly `count` samples per call,
regardless of whether `count < blockSize`. This ensures correct timing across block boundaries.
## Pre-allocated output buffer pattern
Every stdlib generator pre-allocates `_result` to `lyrebirdDefaultResultBufferSize` (512) samples
in `init`, and opens `calculatedSamples` with:
```swift
precondition(count <= _result[0].count,
"count \(count) exceeds the pre-allocated buffer (\(_result[0].count) samples). ...")
```
This fires in both debug and release if the buffer is undersized — no grow path, no RT allocation.
`SynthesisEngine.init` enforces `blockSize <= lyrebirdDefaultResultBufferSize`, so the precondition
is never violated in engine-driven usage. New generators **must** follow this pattern exactly.
```swift
// Canonical new-generator calculatedSamples skeleton:
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[LyrebirdFloat]] {
precondition(count <= _result[0].count,
"count \(count) exceeds pre-allocated buffer. "
+ "Ensure blockSize <= lyrebirdDefaultResultBufferSize.")
// ... fill _result[0][0..<count] ...
return _result
}
```
## Statefulness
Each Generator instance owns its own state. Examples:
- `OscSin`: phase accumulator
- `EnvelopeGen.Audio` / `EnvelopeGen.Control`: current segment, elapsed time
- `DelayLine`: circular buffer, write head position
- `FirstOrderSection`: previous input and output sample
State is never shared between instances — graph-copy-per-Synthesizer ensures isolation.
## Legacy Reference
These files are in `legacy/Lyrebird/LyrebirdSynth/Lyrebird/` — the legacy prototype. They are **not** in the current codebase; they are design references only.
- `LyrebirdTypes.swift` — `ValidGeneratorInput` pattern, type aliases
- `LyrebirdUgen.swift` — base Generator class (legacy name: UGen)
- `MathUGens.swift` — `BinaryOpGenerator` pattern, operator overloading
- `OscUGens.swift` — sine table, phase accumulator pattern
+385
View File
@@ -0,0 +1,385 @@
# Node Tree and Group Actions
The Lyrebird signal graph is a tree of `Synthesizer` nodes owned by `SynthesisEngine`. Every node that produces or processes audio lives in this tree; nodes outside the tree are never evaluated.
---
## Tree Structure
```
SynthesisEngine
└── rootGroup (Group, persistent)
├── [pre-main nodes] ← .before(engine.mainGroup) — input limiters, gates, etc.
├── mainGroup (Group, persistent) ← default engine.add(_:) target
│ ├── Synthesizer ← newest-added evaluates first
│ └── Synthesizer
└── [post-main nodes] ← .after(engine.mainGroup) — decoders, master reverb
```
`rootGroup` is the engine's root `Group` — a doubly-linked list of child `Synthesizer` nodes evaluated in order. `mainGroup` is a persistent child of `rootGroup` and the default target for `engine.add(_:)`. Both groups are created at engine init and never freed.
**Evaluation order within mainGroup:** `engine.add(_:)` uses head-insertion — the most-recently-added node evaluates first. This means if synth B depends on bus output from synth A, add B first and then A.
`Group` itself conforms to `Synthesizer`, so groups can be nested to any depth.
---
## Defining a Synthesizer
Subclass `SynthesizerBase` and override `build()`. Declare mutable parameters with `@LiveParam`. Register `Out.Audio` (or `Out.Control`) generators with `addOutputGenerator` — or use the shorthand helpers `output(bus:source:)` and `controlOutput(bus:source:)`.
```swift
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class SineTone: SynthesizerBase {
@LiveParam var freq: LyrebirdFloat = 440.0
@LiveParam var amp: LyrebirdFloat = 0.5
override func build() {
let osc = OscSin.Audio(freq: $freq, phase: 0.0)
output(bus: 0, source: osc * $amp) // shorthand for addOutputGenerator(Out(...))
}
}
```
`build()` runs once on the **main thread** when the node is scheduled. All generator allocation happens here; the RT audio thread only calls `evaluate(graph:count:)`.
---
## Adding Nodes
### Immediately (at current sample time)
```swift
let tone = SineTone()
try engine.add(tone)
```
`add(_:)` is equivalent to `schedule(_:at: engine.currentTime)`. The engine reads `currentTime` via an atomic load — safe from the main thread.
### At an absolute sample time
```swift
// Start tone2 at exactly sample 44100 (1 second at 44.1 kHz)
let tone2 = SineTone()
try engine.schedule(tone2, at: 44100)
```
The `SampleTime` value is compared to `engine.currentTime` each block. When the scheduled sample falls within the current block window, the engine adds the node mid-block via sub-block splitting, so the onset is sample-accurate.
### After a relative duration in seconds
```swift
let tone3 = SineTone()
try engine.schedule(tone3, after: 2.0) // 2 seconds from now
```
`schedule(_:after:)` converts the duration to a `SampleTime` delta using `engine.seconds(_:)` and adds it to the current atomic clock. Internally identical to `schedule(_:at:)`.
### How the add path works
Before posting the `.add` event, the engine calls `rebuildGraph()` on `SynthesizerBase` instances (which clears then calls `build()`) on the **main thread**. The linked-list `PreparedNode` is also pre-allocated on the main thread. The RT thread in `applyEvent` only wires pointer references — no allocation on the RT thread.
---
## Removing Nodes
### Immediately
```swift
engine.remove(tone)
```
### At an absolute sample time
```swift
// Remove tone2 exactly 2 seconds after it was added
engine.remove(tone2, at: 44100 + engine.seconds(2.0))
```
Removed nodes are handed to `freeQueue`, where a background drain thread releases them via ARC — the RT thread never calls `release()` directly.
### Convenience: schedule paired add and remove
```swift
let note = SineTone()
let startTime = engine.currentTime + engine.seconds(0.5)
let stopTime = startTime + engine.seconds(1.0)
try engine.schedule(note, at: startTime)
engine.remove(note, at: stopTime)
```
Both events enqueue to the same `pendingQueue`. The engine processes them in target-time order within each block.
---
## Updating Parameters While Running
Assign `@LiveParam` properties from the main thread at any time after the node is added. Changes cross to the RT thread via an atomic write and produce a per-sample linear ramp on the next block.
```swift
tone.freq = 880.0 // no try, no string — RT-safe atomic write
tone.amp = 0.3
```
For external/REPL access by name (e.g. OSC handlers receiving the parameter name as a String), use `try synth.updateParameter("freq", value: 880.0)` — the by-name route writes the same atomic. See `docs/protocols/synthesizer.md`.
---
## Nested Groups
Nesting groups controls evaluation order without needing to track individual nodes. Add a `Group` to the engine the same way you add any `Synthesizer`.
```swift
let instruments = Group()
let effects = Group()
try engine.add(instruments) // evaluated before effects
try engine.add(effects)
```
> **Evaluation order is global.** Every `Synthesizer` in `instruments` is evaluated before any `Synthesizer` in `effects`. This matters for bus routing: a node writing to a bus must appear earlier in the tree than any node reading from the same bus.
---
## Node Positioning
By default `engine.add(_:)` inserts at the head of `mainGroup` (newest-first). Use the `position:` overload to control placement precisely.
### NodePosition cases
| Case | Meaning |
|------|---------|
| `.tail(of: group)` | Append to end of `group` |
| `.head(of: group)` | Prepend to front of `group` (evaluated first within that group) |
| `.before(target)` | Insert immediately before `target` in whatever group contains it |
| `.after(target)` | Insert immediately after `target` in whatever group contains it |
```swift
let instruments = Group()
try engine.add(instruments)
let bass = BassSynth()
try engine.add(bass, position: .tail(of: instruments)) // append
let lead = LeadSynth()
try engine.add(lead, position: .head(of: instruments)) // prepend — runs before bass
let pad = PadSynth()
try engine.add(pad, position: .after(bass)) // insert after bass
```
`.before` and `.after` search the entire node tree recursively (O(n)). If the target is not found, the node falls back to `mainGroup` head insertion.
### Global pre/post processing
Use `engine.mainGroup` as a position anchor to install global processing nodes that run before or after all default-added instruments:
```swift
// Evaluate before all instruments (e.g. input limiter on the live input bus)
try engine.add(InputLimiter(), position: .before(engine.mainGroup))
// Default instrument — lands in mainGroup
try engine.add(MySynth())
// Evaluate after all instruments (e.g. ambisonic decoder, master reverb)
try engine.add(MasterReverb(), position: .after(engine.mainGroup))
```
Multiple `.before(engine.mainGroup)` insertions are ordered so that each new pre-main node appears immediately before `mainGroup` (pushing earlier pre-main nodes further away). The same rule applies for `.after(engine.mainGroup)` insertions.
---
## Group Lifecycle — release and free
Every `Synthesizer` has two lifecycle methods:
```swift
try synth.release(engine: engine) // graceful: set gate → 0 (throws SynthesizerError.noGate if unsupported)
synth.free(engine: engine) // immediate: remove from tree now
```
`Group` provides cascade implementations of both.
### Group.release(engine:)
Releases all direct children, then self-frees when the group empties:
1. For each child: call `child.release(engine:)`. If it throws `.noGate`, call `child.free(engine:)` immediately.
2. Starts a 0.1 s repeating timer that reads `group.count` (atomically safe). When count reaches 0, calls `group.free(engine:)`.
**Persistent groups** (`rootGroup` and `mainGroup`) are exceptions: `release(engine:)` still cascades to all children, but the group itself never self-frees. The groups remain attached and ready to accept new children after the cascade drains to zero.
```swift
let instruments = Group()
// … populate instruments with gated synths …
try engine.add(instruments)
// Later: gracefully release all notes and remove the group when silent.
instruments.release(engine: engine)
```
### Group.free(engine:)
Immediately tears down the group and all its children — no envelope release:
```swift
instruments.free(engine: engine)
// On next block: all children enqueued to freeQueue, group removed from tree.
```
### Synthesizer.release — user implementation
Override `release(engine:)` in synthesizers that have an envelope gate:
```swift
final class GatedNote: SynthesizerBase {
@LiveParam var gate: LyrebirdFloat = 1.0
override func build() {
// … gate drives EnvelopeGen …
}
// Signal envelope to release (gate → 0).
override func release(engine: SynthesisEngine) throws {
gate = 0.0 // @LiveParam atomic write — no try needed
}
}
```
Or use the by-name route, which writes the same atomic on the auto-registered `@LiveParam`:
```swift
override func release(engine: SynthesisEngine) throws {
try updateParameter("gate", value: 0.0)
}
```
---
## Bus-Based Communication Between Nodes
Nodes communicate via audio buses (`Out.Audio` / `In.Audio`) or control buses (`Out.Control` / `In.Control`). Bus writes accumulate with `+=` — multiple nodes can write to the same bus and their outputs mix.
`In.Audio` and `In.Control` accept an optional `channels:` parameter to read N consecutive buses as a single N-channel generator (channel count fixed at init, no RT allocation):
```swift
In.Audio(bus: 4, channels: 2) // reads audioBuses[4] and [5]; returns 2-channel output
In.Control(bus: 10, channels: 2) // reads controlBuses[10] and [11]; independent ramps
```
With `BusAllocator`, pass an `AudioBus` directly and channel count is derived automatically:
```swift
let stereo = try engine.busAllocator.allocateAudioBus(channelCount: 2)
In.Audio(bus: stereo) // reads stereo.index and stereo.index+1
```
```swift
// Example — DrumSynth and ReverbEffect are user-defined SynthesizerBase subclasses
// Node A: writes to bus 4 (an intermediate "effects send" bus)
class DrumSynth: SynthesizerBase {
override func build() {
let drum = WhiteNoise.Audio() * 0.8
output(bus: 0, source: drum) // dry output on bus 0
output(bus: 4, source: drum) // parallel send to bus 4 for an effect
}
}
// Node B: reads from bus 4 and writes to the main output
// Must appear AFTER DrumSynth in the tree so bus 4 is populated first.
class ReverbEffect: SynthesizerBase {
override func build() {
let wet = input(bus: 4) // reads what DrumSynth wrote to bus 4
output(bus: 0, source: wet * 0.4)
}
}
let drums = DrumSynth()
let reverb = ReverbEffect()
try engine.add(drums) // added first → evaluated first → bus 4 populated
try engine.add(reverb) // added second → evaluated second → reads populated bus 4
```
Audio buses are zeroed at the start of every block. Control buses persist across blocks.
---
## Auto-Free with EnvelopeGen
When `EnvelopeGen.Audio` or `EnvelopeGen.Control` finishes and its `doneAction` is `.freeNode`,
it sets an atomic flag. Poll the flag from a non-RT context (main thread, scheduling loop, or
timer) and post the removal:
```swift
// Example — PianoNote is a user-defined SynthesizerBase subclass
class PianoNote: SynthesizerBase {
let env: EnvelopeGen.Audio
init() {
env = EnvelopeGen.Audio(
envelope: Envelope(levels: [0, 1, 0], durations: [0.01, 0.3], curves: [0, 0]),
doneAction: .freeNode
)
}
override func build() {
output(bus: 0, source: env)
}
}
let note = PianoNote()
try engine.add(note)
// Poll from main thread (e.g. in a display-link callback or timer):
if note.env.needsFree {
engine.remove(note)
}
```
Do not call `engine.remove` from within the RT audio callback — that would post to `pendingQueue` from the RT thread.
---
## Polyphonic Voice Management
For instruments that need multiple simultaneous notes, use `VoicePool` instead of managing individual synthesizer instances manually. The pool allocates N voices into a `Group` at init time and handles note-on/note-off assignment and steal arbitration on the main thread.
```swift
let group = Group()
try engine.add(group)
let pool = try VoicePool(
voiceCount: 8, group: group, engine: engine,
stealStrategy: .oldest
) { MySynth() }
let voice = pool.noteOn(note: 60) // allocates or steals
voice.freq = midiToHz(60)
voice.gate = 1.0
voice.gate = 0.0
pool.noteOff(note: 60) // marks voice free; gate down yourself
```
See `docs/protocols/synthesizer.md` — "Polyphonic Voice Pools" section for steal strategy reference and MIDI wiring.
---
## Thread Safety Summary
| Operation | Thread | Notes |
|---|---|---|
| `engine.add` / `engine.schedule` | Main | `build()` and `PreparedNode` allocation happen here before enqueueing |
| `engine.remove` | Main | Pre-retains the synth ref before enqueueing — no RT retain |
| `tone.freq = 880.0` (`@LiveParam`) | Main | Releasing `Atomic<UInt64>` store; RT reads with acquiring load |
| `updateParameter` (string-key) | Main | Enqueues to per-synth `SPSCQueue`; applied at next block boundary |
| `engine.add(_:position:)` | Main | Like `add(_:)` — builds graph, allocates node, posts `.addNode` event |
| `VoicePool` methods | Main | Language-side only; no RT involvement |
| `synth.release(engine:)` | Main | Language-side only; posts parameter or remove events |
| `synth.free(engine:)` | Main | Posts immediate remove / groupFree event |
| `Group.addToTail` / `remove` / `addBefore` / `addAfter` | RT (audio) | Called inside `applyEvent` — no allocation, pointer wiring only |
| `evaluate(graph:count:)` | RT (audio) | Never add, remove, or allocate here |
The key invariant: **every mutation that allocates or retains happens before the event enters `pendingQueue`**. The RT thread only wires pointers and reads atomic values.
+341
View File
@@ -0,0 +1,341 @@
# Synthesizer Protocol
The composable unit of instrument or effect in Lyrebird. Any type conforming to `Synthesizer` can be added to the signal graph tree.
## Current Implementation State
**Complete.** The protocol, node tree, `Group`, and `SynthesizerBase` are fully implemented and tested (152 tests passing).
---
## Protocol Definition
```swift
public protocol Synthesizer: AnyObject {
/// Configure the internal generator DAG. Called once on the scheduling thread.
func build()
/// Evaluate one segment of the signal graph. Called on the RT audio thread.
/// Default: no-op; SynthesizerBase provides the real one.
func evaluate(graph: SynthGraph, count: Int)
/// Begin a graceful release (e.g. set gate → 0).
/// Default throws `SynthesizerError.noGate`. Override in synthesizers with EnvelopeGen.
func release(engine: SynthesisEngine) throws
/// Immediately remove this node from the signal graph.
/// Default posts an engine remove event. Group overrides with full cascade teardown.
func free(engine: SynthesisEngine)
}
```
Default `evaluate` and `free` are provided by a protocol extension. Default `release` throws `SynthesizerError.noGate` — override it in synthesizers that have a gate input.
---
## Synthesizer Lifecycle
### release(engine:) — graceful shutdown
Signal the synthesizer to begin releasing (set gate → 0, trigger doneAction envelope, etc.). Synthesizers that don't support release throw `SynthesizerError.noGate`.
```swift
final class GatedNote: SynthesizerBase {
@LiveParam var gate: LyrebirdFloat = 1.0
override func build() { /* … gate drives EnvelopeGen … */ }
override func release(engine: SynthesisEngine) throws {
gate = 0.0 // atomic write — no try, no string
}
}
let note = GatedNote()
try engine.add(note)
// Later — begin release:
try? note.release(engine: engine)
```
For string-key gate parameters:
```swift
override func release(engine: SynthesisEngine) throws {
try updateParameter("gate", value: 0.0)
}
```
### free(engine:) — immediate removal
Removes the node from the signal graph at the current sample time, without waiting for an envelope to complete.
```swift
note.free(engine: engine)
```
### SynthesizerError
```swift
public enum SynthesizerError: Error {
case noGate // thrown by default release(engine:) when no gate is supported
}
```
Catch `.noGate` to distinguish synthesizers that don't support release from ones that throw real errors:
```swift
do {
try synth.release(engine: engine)
} catch SynthesizerError.noGate {
synth.free(engine: engine) // no gate — free immediately
}
```
### Group lifecycle cascade
`Group` provides cascade implementations of both lifecycle methods. See `docs/protocols/node-tree.md` — "Group Lifecycle" section.
---
## SynthesizerBase
Most Synthesizer implementations should subclass `SynthesizerBase` rather than conforming to `Synthesizer` directly.
```swift
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class SineTone: SynthesizerBase {
@LiveParam var freq: LyrebirdFloat = 440.0
@LiveParam var amp: LyrebirdFloat = 0.5
override func build() {
let osc = OscSin.Audio(freq: $freq, phase: 0.0)
output(bus: 0, source: osc * $amp)
}
}
```
- Override `build()` and call `addOutputGenerator(_:)` with each root generator (typically `Out.Audio` or `Out.Control`).
- `evaluate(graph:count:)` is `final` — the engine drives it automatically.
- Do not override `evaluate` in subclasses; override `build` instead.
## Adding to the Engine
```swift
let note1 = SineTone()
let note2 = SineTone() // independent instance — own phase, own envelope
try engine.add(note1)
try engine.add(note2)
```
`engine.add(_:)` posts an `.add` event to the pending queue. Before enqueueing, the engine:
1. Calls `rebuildGraph()` (clears then calls `build()`) on `SynthesizerBase` instances, or `build()` on plain `Synthesizer` conformers — on the **main thread**.
2. Pre-allocates the linked-list `PreparedNode` — on the **main thread**.
The RT audio thread in `applyEvent` only wires pointer references into `Group.addToTail` — no allocation occurs on the RT thread.
## Removing from the Engine
```swift
engine.remove(note1)
engine.remove(note2, at: someTime) // sample-accurate removal
```
Removed instances are handed off to `freeQueue` for ARC deallocation on the background drain thread — never on the RT audio thread.
## Node Tree
```
SynthesisEngine
└── rootGroup (Group)
├── Group (optional nesting)
│ ├── Synthesizer ← evaluated first
│ └── Synthesizer
└── Synthesizer ← evaluated last
```
- `Group` is itself a `Synthesizer` — groups can be nested arbitrarily.
- Children are evaluated in insertion order (tail-append by default).
- Evaluation order controls bus routing: if A writes to bus 2 and B reads from bus 2, A must precede B in the tree.
- `Group.addToTail` / `addToHead` / `remove` are `internal` — use `engine.add(_:)` and `engine.remove(_:)` from user code.
## `@LiveParam` and `@UIParam` — Live Parameters
`@LiveParam` (in `Lyrebird`) and `@UIParam` (in `LyrebirdUI`) are the only live-parameter
mechanisms. Both auto-register at `build()` time via `Mirror` reflection — no
`declareParameter` call is required.
```swift
final class SineTone: SynthesizerBase {
@LiveParam var freq: Double = 440.0
@LiveParam var amp: Double = 0.2
override func build() {
let osc = OscSin.Audio(freq: $freq)
output(bus: 0, source: osc * $amp)
}
}
let tone = SineTone()
try engine.add(tone)
tone.freq = 880.0 // typed direct write
try? tone.updateParameter("freq", value: 880.0) // by-name (e.g. from OSC)
```
### How it works
| Thread | Operation |
|--------|-----------|
| Main thread | `tone.freq = 880.0` → releasing `Atomic<UInt64>` store |
| RT thread | `_computeSamples` → acquiring load → linear ramp from previous to new target |
The projected value `$freq` is a `ParameterNode` — a `ControlGenerator`. When wired into
`OscSin.Audio(freq: $freq)`, OscSin detects it as a `Generator` and calls `calculatedSamples`,
producing a linearly-interpolated audio-rate buffer ramping to the new value. The ramp is
sized to the engine's control block: one ramp per audio block when `controlBlockSize ==
blockSize` (default), or K ramps per audio block when `controlBlockSize < blockSize`.
### Auto-registration via Mirror
`SynthesizerBase.rebuildGraph()` walks `Mirror(reflecting: self)` plus the superclass chain
at the end of `build()`, finding any `@LiveParam` / `@UIParam` properties (via the internal
`LiveParameterWrapper` protocol). The property name with the leading `_` of property-wrapper
backing storage stripped becomes the parameter key.
### Fan-out safety
`ParameterNode` has the standard segment-serial fan-out cache. Wiring `$freq` into multiple
downstream generators is safe — `_computeSamples` runs exactly once per segment regardless of
fan-out count.
### `updateParameter` (by-name path)
`updateParameter` is the by-name route. Use it for external integrations that arrive as
`String` (OSC, MIDI, REPL, JSON presets):
```swift
try tone.updateParameter("freq", value: 880.0) // throws on unknown key
try? tone.updateParameter("freq", value: 880.0) // silent ignore for fire-and-forget
```
Throws `ParameterUpdateError.keyNotFound(key)` if no live parameter exists for `key`. The
write is the same atomic store as the typed setter — both are equivalent.
### `@UIParam`
`@UIParam` is `@LiveParam` plus an `@Observable` `value` for SwiftUI binding. The projected
node (`UIParamNode`) delegates RT work to an internal `ParameterNode`, so audio-rate
delivery is identical. Use `@UIParam` whenever SwiftUI controls bind to the parameter — see
`docs/ui/gui-system.md`.
### Runtime source-swap
Beyond scalar writes, any `@LiveParam` (or `@UIParam`) slot supports replacing the wired
generator at runtime without stopping the synthesizer.
```swift
// Assign an LFO as the source for freq — takes effect at the next audio block boundary:
tone.$freq.source = LFSawtooth.Control(freq: 0.5, mul: 100, add: 440)
// Revert to scalar (the last value written via `tone.freq = ...`):
tone.$freq.source = nil
// Soft crossfade over 4 blocks (~23 ms at 44.1 kHz / 256-sample block):
tone.$freq.setSource(newLFO, crossfadeBlocks: 4)
// Equivalent SynthesizerBase convenience helper:
tone.setSource(tone.$freq, to: newLFO)
```
The two public API surfaces are:
- **`ParameterNode.source`** — get/set property on the projected value (`synth.$freq`).
Reading returns the last value assigned on the main thread (eventually consistent with the
audio thread within one block). The setter performs a hard swap (no crossfade).
- **`SynthesizerBase.setSource(_:to:crossfadeBlocks:)`** — convenience wrapper taking the
`ParameterNode` directly; useful in generic or programmatic contexts.
Crossfade semantics: `crossfadeBlocks = 0` (default) = hard swap at the next block boundary.
A value > 0 linearly blends old and new source outputs over that many blocks. A mid-crossfade
swap kills the in-progress old source immediately and starts a fresh crossfade.
For the complete contract — threading rules, queue limits, and the known limitation on
updating a source generator's own parameters — see `Sources/Lyrebird/Lyrebird.docc/ParameterInputs.md`
(the DocC-rendered material under "Live source-swap").
### Subclass parameters
Subclasses can declare additional `@LiveParam` / `@UIParam` properties — both subclass and
inherited parameters are registered. Note: Swift forbids re-declaring `@LiveParam var x` in
a subclass when the parent already has one (would require `override` on a property-wrapper
backing store, which is unsupported), so subclass parameters must use distinct names.
## Auto-Free
When `EnvelopeGen.Audio` or `EnvelopeGen.Control` signals completion with `doneAction: .freeNode`, it sets `needsFree = true`
(an `Atomic<Bool>` releasing store on the RT thread). The **caller** must read this flag from a
non-RT context (main thread or scheduling loop) after `processBlock` returns and post a `.remove`
event to the pending queue:
```swift
// After engine.processBlock — on main/scheduling thread:
if envelopeGen.needsFree {
engine.remove(synth)
}
```
Do not call `engine.remove` from within the RT callback — that would post to `pendingQueue` from
the RT thread, which violates the no-queue-posts-from-RT rule. The removed instance is routed
through `freeQueue` for off-RT deallocation.
## Polyphonic Voice Pools
`VoicePool<S: SynthesizerBase>` manages N pre-allocated synthesizer instances as polyphonic voices. All logic is language-side — no RT changes.
### Setup
```swift
let group = Group()
try engine.add(group)
let pool = try VoicePool(
voiceCount: 8,
group: group,
engine: engine,
stealStrategy: .oldest
) {
let s = MySynth()
s.gate = 0.0
return s
}
```
`VoicePoolError.invalidVoiceCount` is thrown when `voiceCount < 1`.
### Note-on / note-off
```swift
let voice = pool.noteOn(note: 60) // allocates or steals; returns S
voice.freq = midiToHz(60)
voice.gate = 1.0
voice.gate = 0.0
pool.noteOff(note: 60) // marks voice free; pool does not gate it down
pool.allNotesOff() // marks all voices free
```
### Steal strategies
| Case | Behavior |
|---|---|
| `.oldest` | Steals the voice playing longest (min trigger serial). Default. |
| `.roundRobin` | Cycles through voices in index order. |
| `.quietest` | Reads `@LiveParam` named `"amplitude"`, `"amp"`, or `"gain"` via `Mirror`; steals the lowest. Falls back to `.oldest` when no amp param found. |
| `.lowestAmplitude` | Alias for `.quietest`. |
All pool methods are main-thread only.
## Legacy Reference
These files are in `legacy/Lyrebird/LyrebirdSynth/Lyrebird/` — the legacy prototype. They are **not** in the current codebase; they are design references only.
- `LyrebirdNode.swift` — Group, linked list, head/tail
- `LyrebirdGraph.swift` — build closure, parameter dict, graph copy
- `AudioSampleGraphs.swift` — example Synthesizer definitions
File diff suppressed because it is too large Load Diff
+91
View File
@@ -0,0 +1,91 @@
# Review-Cycle Backlog
Findings from the 2026-05-10 `/lyrebird_review_cycle` sweep, plus follow-ons from later cycles. This file lives across phases — addressed bullets get deleted; new review cycles fold their findings in here.
---
## Deferred from 2026-05-27 `/lyrebird_review_cycle`
- **A-9 — Six early-phase audio-only filters lack namespace-enum wrapper.**
`CombFilter`, `AllpassFilter`, `RingingFilter`, `ResonatingFilter`,
`SecondOrderSection`, `FirstOrderSection` are bare
`public final class Foo: GeneratorBase, AudioGenerator` at the top
level of their files rather than the `enum Foo { class Audio: ... }`
namespace pattern used by all newer audio-only generators (`FreeVerb`,
`GVerb`, `Chorus`, `Flanger`, etc.). All six carry
`// GeneratorEnum conformance intentionally omitted` comments —
consistent with the audio-only contract, but the unwrapped public API
means call sites use `CombFilter(...)` while peers use
`FreeVerb.Audio(...)`. Refactoring would be a breaking change touching
all call sites; track for a future refactor phase that can land the
rename + deprecation alias in one commit.
- **Q-4 — Long `_computeSamples` reverb functions.**
- `Sources/Lyrebird/Generators/Reverb/PlateReverb.swift:425` —
`_computeSamples` is 224 lines.
- `Sources/Lyrebird/Generators/Reverb/GVerb.swift:324` —
`_computeSamples` is 172 lines.
- `Sources/Lyrebird/Generators/Panning/PanXYDistance.swift:188` /
`PanAzDistance.swift:190` — 167 lines each.
- `Sources/Lyrebird/Generators/PhysicalModels/Flute.swift:192` —
162 lines.
These are RT hot loops where the team has explicitly chosen inlining
over decomposition for performance. The reverb pair (Plate + GVerb)
might benefit from a `RuntimeReverbHelpers.swift` extraction
(similar to the existing `FilterHelpers.swift` /
`RBJBiquadHelpers.swift` pattern) when profiling justifies a perf
pass. The pan + flute cases are cohesive single-purpose state
machines and resist splitting.
---
## Architectural drift (kept — not blocking)
- `_Base` pattern vs flat `GeneratorBase` subclass split: early generators (`CombFilter`, `AllpassFilter`, `ResonatingFilter`, `RingingFilter`, all `RBJ*` types, `Pan2`/`Pan4`/`PanN`, `AmbiEncoder1`/`AmbiDecoder1`, `DelayLine`/`DelayLineFeedback`, `FreqTracker`, `LookAheadLimiter`, all granular generators) hand-allocate `_result: [[Double]]` and skip the `enum { _Base; Audio; Control }` pattern. Locking in either direction would break public API. Document in the generator authoring guide as "consider the namespace pattern even for Audio-only generators in case a Control variant becomes useful later," but leave existing public API alone.
- `RBJBiquad.swift` packs three internal types (`BiquadCoeffs`, `BiquadState`, `FirstOrderState`). All tightly coupled, all `internal`. Defensible — low priority split.
## Style retained for paper fidelity
- **PlateReverb snake_case constants**: `Sources/Lyrebird/Generators/Reverb/PlateReverb.swift:77-93` uses paper-cross-reference names (`plateLTap_LD1_A`, etc.). Acceptable for fidelity to the Dattorro paper.
## Future-visibility flags (no fix required)
- **Long inherently-linear functions**:
- `Sources/Lyrebird/AudioDrivers/CoreAudioDriver.swift:132-301` `setup(engine:)` — ~170 lines, 8 numbered steps. Splitting into `_findComponent`, `_enableIO`, `_installCallback` would ease maintenance.
- `Sources/Lyrebird/Process/LyrebirdEventList.swift:949-1052` `buildFromFile(…)` — already commented in 5 numbered steps; readable.
- `Sources/Lyrebird/Generators/Reverb/PlateReverb.swift:325-413` `Audio.init` buffer-sizing block — straight-line, self-evident.
## Skipped — needs `LyrebirdBuffer.isEmpty`
- `Sources/Lyrebird/Generators/Reverb/ConvolutionReverb.swift:206` uses `ir.count > 0`. Swap to `!ir.isEmpty` when `LyrebirdBuffer` grows that accessor; until then `count > 0` is acceptable.
---
## Resolved in step-6 maintenance pass (2026-05-10)
The following findings were addressed in the spectral formant-shift step-6 commit:
- **Shared `combFeedbackCoeff` / `lyrebirdLog60dBLn`**: extracted into `Sources/Lyrebird/Generators/Filters/FilterHelpers.swift`. `CombFilter`, `AllpassFilter`, `ResonatingFilter` now call the shared helper / constant.
- **GeneratorEnum-omitted comment** added at end of 20 Audio-only generators (filters, delays, panning, dynamics, granular families).
- **`SecondOrderSection` / `FirstOrderSection`**: confirmed user-facing low-level primitives; added init-level `/// - Parameters:` blocks.
- **Butterworth queue constant rename**: dropped `lyrebird` prefix on internal `butterworthCoeffQueueCapacity` / `butterworthRespQueueCapacity` / `butterworthKillQueueCapacity`.
- **LyrebirdUI formatter dedupe**: extracted `formattedParameterValue(_:)` into `Sources/LyrebirdUI/Controls/ParameterFormatting.swift` with named threshold constants. `ParameterKnob` and `ParameterXY` route through it.
- **Drag-start sentinel collision**: replaced the dual-zero check in `ParameterKnob.dragGesture` with an explicit `@State var dragInProgress: Bool` flag.
- **Lock without `defer`**: `LyrebirdRoutineContext._checkPause` now uses `lock(); defer { unlock() }` instead of explicit unlocks.
- **`.before/.after` arm collapse**: `LyrebirdProcess` cross-EventList validation uses a single `case .before(let other), .after(let other):` switch arm.
- **Close-error swallowing**: `SpectralFrameBufferFileIO.write(to:)` now closes the file handle explicitly on the success path so flush failures surface to the caller; the `defer` keeps the close on error bail-out only.
- **`ParameterNode` Sendable invariant**: added one-line comment summarising the `Atomic<UInt64>` cross-thread channel + RT-only mutable state.
## Resolved in steps 1–4 (earlier spectral formant-shift work)
- Foundation import sweep (~54 files), DemandRandom/TemporalStream seed-helper consolidation, DelayInterpolation/MouseTracker file splits, MoogLadder `cutoff:` → `freq:` rename + MuTronIII `peak:` documentation.
## Resolved in step 5
- `docs/stdlib/generators.md` catalog refresh — covered ~40 missing generator types across 15 categories.
---
## Maintenance discipline
Drain this file periodically. When new review cycles run, fold findings in here instead of dropping them.
+61
View File
@@ -0,0 +1,61 @@
# 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
@@ -0,0 +1,76 @@
# 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
@@ -0,0 +1,112 @@
# 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
@@ -0,0 +1,209 @@
# 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.
+71
View File
@@ -0,0 +1,71 @@
# Signal Flow
## Control Loop — Full Pass
Executed once per audio render callback:
```
1. Zero all audio bus memory
2. Copy hardware input samples → reserved input audio buses
3. (Control buses: no action — retain previous values)
4. Drain pendingQueue — collect all ScheduledEvents whose SampleTime falls in this block
5. Split block into segments at event boundaries:
For each segment [segmentStart, segmentEnd):
Apply any ScheduledEvents at segmentStart (add/remove nodes, parameter updates)
Evaluate node tree top-to-bottom, passing count = segmentEnd - segmentStart:
For each Group (in order):
For each Synthesizer (in order):
Evaluate its internal Generator DAG (leaves first, root last)
Out generators accumulate into bus at correct offset (busOffset = segmentStart)
Advance currentTime by count
6. Post freed Synthesizer instances to freeQueue (ARC deinit on background thread)
7. Copy reserved output audio buses → hardware AudioBufferList
```
**With no scheduled events**, there is exactly one segment spanning the full block — identical to non-scheduling behaviour with `count = blockSize` and `busOffset = 0`.
## DAG Evaluation (within a Synthesizer)
Generators form a directed acyclic graph. Evaluation is **pull-based**: the root generator (typically `Out`) requests its inputs, which recursively request their inputs.
```
Out.Audio(bus: 0)
└── BinaryOpGenerator (*)
├── OscSin (freq: 440) ← leaf: no inputs
└── EnvelopeGen.Audio ← leaf: no inputs
```
Evaluation order: leaves computed first, root last. Each generator's `calculatedSamples(graph:count:)` is called once per segment (which is once per block when no scheduling events split it).
## Audio Rate vs Control Rate
- **Audio generators** produce `[Float]` of length `blockSize`
- **Control generators** produce a single `Float` value
- When a control-rate value feeds an audio-rate generator, it is interpolated across the block (linear interpolation between previous and current value)
## In / Out Bus Interaction
```
Synthesizer A: Synthesizer B:
Out.Audio(bus: 2) ─writes─► [bus 2] ─reads─► In.Audio(bus: 2)
```
Because the node tree is evaluated in order, Synthesizer A must appear before Synthesizer B in the tree if B reads A's output. Group ordering controls this.
## Parallel Groups
Independent groups (no bus dependency between them) can evaluate concurrently using Swift structured concurrency (`async let` or `TaskGroup`). Groups that share bus data must be ordered sequentially.
```swift
// Safe to parallelize only if effectsGroup does NOT read from instrumentGroup's buses
// during the same cycle. If it does, they must be sequential.
async let groupA = evaluate(instrumentGroup)
async let groupB = evaluate(effectsGroup)
```
## Accumulation Model
`Out` uses `+=`. This means:
- Two Synthesizers writing to bus 0 → their signals sum (mixing)
- Three note instances of the same patch → polyphonic sum
- An effect `In`-ing from bus 2 and `Out`-ing to bus 0 → FX insert chain
+375
View File
@@ -0,0 +1,375 @@
# Buffer I/O Generators — RecordBuffer + PlayBuffer
Record signal into a `LyrebirdBuffer` and play it back at variable rate.
Both generators come in two rate variants following the `_Base`/`Audio`/`Control` enum pattern:
| Type | Rate | Use |
|---|---|---|
| `RecordBuffer.Audio` | Audio (per-sample) | Record audio signals, multi-channel |
| `RecordBuffer.Control` | Control (per-block) | Record automation curves (LFO, envelopes) |
| `PlayBuffer.Audio` | Audio (per-sample) | Playback at variable rate with interpolation |
| `PlayBuffer.Control` | Control (per-block) | Playback of control automation data |
---
## RecordBuffer
Writes its input signal into a `LyrebirdBuffer` and passes the signal through as output. Recording and monitoring happen simultaneously.
### RecordBuffer.Audio
Audio-rate recording — writes one buffer frame per sample.
```swift
let buf = LyrebirdBuffer(count: 44100, channelCount: 1)
let rec = RecordBuffer.Audio(input: someOsc, buffer: buf, loop: false, doneAction: .freeNode)
output(bus: 0, source: rec)
```
### RecordBuffer.Control
Control-rate recording — writes one buffer frame per block. Use for automation curves (LFO outputs, envelope followers).
```swift
let automationBuf = LyrebirdBuffer(count: 1000)
let lfo = OscSin.Control(freq: 0.5)
let rec = RecordBuffer.Control(input: lfo, buffer: automationBuf, loop: false)
```
Requires a **mono** buffer (`channelCount == 1`). Use `RecordBuffer.Audio` for multi-channel.
### Shared parameters
```swift
// Both variants inherit these from RecordBuffer._Base:
@LiveParam public var run: LyrebirdFloat // > 0 = recording, ≤ 0 = paused (default 1.0)
@LiveParam public var recLevel: LyrebirdFloat // scale on incoming signal (default 1.0)
@LiveParam public var preLevel: LyrebirdFloat // scale on existing buffer (default 0.0 = overwrite)
public let buffer: LyrebirdBuffer
public let doneAction: DoneAction
public var needsFree: Bool // acquiring Atomic<Bool> load
```
### Init
```swift
RecordBuffer.Audio(
input: any ValidGeneratorInput,
buffer: LyrebirdBuffer,
loop: Bool = true,
doneAction: DoneAction = .nothing
)
RecordBuffer.Control(
input: any ValidGeneratorInput,
buffer: LyrebirdBuffer, // must be mono (channelCount == 1)
loop: Bool = true,
doneAction: DoneAction = .nothing
)
```
### Write formula
Each frame:
```
buffer[frame, ch] = recLevel × input[ch] + preLevel × buffer[frame, ch]
```
`preLevel = 0.0` overwrites; `preLevel = 1.0` mixes new signal on top of existing content.
### Multi-channel (Audio variant)
Supply a `GeneratorArray` for stereo or N-channel buffers. Channel count must match `buffer.channelCount` — enforced by `precondition` in `_computeSamples`.
```swift
let buf = LyrebirdBuffer(count: 44100, channelCount: 2)
let stereoSrc = expand([leftSig, rightSig]) { $0 }
let rec = RecordBuffer.Audio(input: stereoSrc, buffer: buf)
output(bus: 0, source: rec) // stereo passthrough + stereo recording
```
### run param
Set `run = 0.0` to pause recording (write head holds position). Set `run = 1.0` to resume. The write head does not reset on resume.
### RT-safety note
Both variants write to `LyrebirdBuffer` storage from the RT thread. The buffer is **not safe for concurrent non-RT reads while recording is active**. Stop recording before reading from another thread.
### doneAction (loop == false)
| `DoneAction` | Behaviour |
|---|---|
| `.nothing` | Recording stops; generator stays in graph outputting passthrough |
| `.freeNode` | Sets `needsFree = true`; poll from main thread and call `engine.remove` |
| `.loop` | Resets write head to frame 0 (equivalent to `loop: true`) |
---
## PlayBuffer
Reads back a `LyrebirdBuffer` at a variable rate with interpolation.
### PlayBuffer.Audio
Audio-rate playback — reads one buffer frame per sample with interpolation. Output channel count equals `buffer.channelCount`.
```swift
let player = PlayBuffer.Audio(buffer: buf, loop: false, doneAction: .freeNode)
output(bus: 0, source: player)
```
### PlayBuffer.Control
Control-rate playback — advances phase once per block. Produces a linear-ramp output matching the `ControlGenerator` ramp convention. Use to play back automation curves recorded by `RecordBuffer.Control`.
```swift
let player = PlayBuffer.Control(buffer: automationBuf, loop: true)
```
Requires a **mono** buffer (`channelCount == 1`). Use `PlayBuffer.Audio` for multi-channel.
### Shared parameters
```swift
// Both variants inherit these from PlayBuffer._Base:
public let buffer: LyrebirdBuffer
public let doneAction: DoneAction
public var needsFree: Bool
```
### Init
```swift
PlayBuffer.Audio(
buffer: LyrebirdBuffer,
loop: Bool = true,
interpolation: TableInterpolation = .linear,
doneAction: DoneAction = .nothing,
startPos: Double = 0.0, // fractional frame index to begin playback
rate: any ValidGeneratorInput = 1.0, // playback rate multiplier
trigger: any ValidGeneratorInput = 0.0 // ≤0 → >0 edge resets play head
)
PlayBuffer.Control(
buffer: LyrebirdBuffer, // must be mono (channelCount == 1)
loop: Bool = true,
interpolation: TableInterpolation = .linear,
doneAction: DoneAction = .nothing,
startPos: Double = 0.0,
rate: any ValidGeneratorInput = 1.0,
trigger: any ValidGeneratorInput = 0.0
)
```
### Rate
| `rate` | Effect |
|---|---|
| `1.0` | Original speed (forward) |
| `2.0` | Double speed, pitch up one octave |
| `0.5` | Half speed, pitch down one octave |
| `-1.0` | Original speed, reversed |
| `-2.0` | Double speed, reversed, pitch up one octave |
`rate` accepts any `ValidGeneratorInput` — pass a generator for varispeed / vibrato:
```swift
// Constant rate (scalar at init):
let player = PlayBuffer.Audio(buffer: buf, rate: 2.0)
// Generator-driven rate (LFO vibrato):
let lfo = OscSin.Audio(freq: 5.0, mul: 0.05, add: 1.0)
let player = PlayBuffer.Audio(buffer: buf, rate: lfo)
```
### Reverse playback
Set `rate` negative to play the buffer in reverse. Use `startPos` to begin from the last frame:
```swift
let player = PlayBuffer.Audio(
buffer: buf,
loop: true,
startPos: Double(buf.count - 1),
rate: -1.0
)
```
With `loop: true` and a negative rate, `_phase` wraps from 0 back to the end of the buffer (seamless reverse loop). With `loop: false`, reaching `_phase < 0` fires `doneAction` and holds playback at frame 0.
### Trigger
`trigger` accepts any `ValidGeneratorInput`. Edge detection (≤0 → >0 transition) resets the play head to frame 0 and clears the `_isDone` flag.
```swift
// Scalar: always high — fires once on first sample (since _prevTrigger starts at 0).
let oneshot = PlayBuffer.Audio(buffer: buf, loop: false, trigger: 1.0)
// Generator: impulse-driven sample-accurate retrigger.
let imp = Impulse.Audio(freq: 2.0)
let player = PlayBuffer.Audio(buffer: buf, loop: false, trigger: imp)
// Mutable ParameterNode (when trigger must change over time):
let trigNode = ParameterNode(0.0)
let player = PlayBuffer.Audio(buffer: buf, trigger: trigNode)
// ... later, from non-RT thread:
trigNode.value = 1.0 // arm trigger
trigNode.value = 0.0 // lower, ready for next retrigger
```
### Multi-channel (Audio variant)
A stereo buffer produces two output channels. Wire through `output(bus:source:)`:
```swift
let stereoPlayer = PlayBuffer.Audio(buffer: stereoBuffer)
output(bus: 0, source: stereoPlayer) // bus 0 = left, bus 1 = right
```
### Interpolation
| Mode | Quality | Cost |
|---|---|---|
| `.none` | Truncate to nearest frame | Cheapest |
| `.linear` | Two-sample blend (default) | Low |
| `.cubic` | Catmull-Rom four-sample | Highest quality |
### doneAction (loop == false)
Same as `RecordBuffer` — `.freeNode` is the typical choice for one-shot samples.
```swift
let player = PlayBuffer.Audio(buffer: buf, loop: false, doneAction: .freeNode)
try engine.add(samplePlayer)
// Poll on main thread:
if player.needsFree { engine.remove(samplePlayer) }
```
---
## Sample-rate compensation
`LyrebirdBuffer` stores the native sample rate of its audio data:
```swift
public var sampleRate: Double? = nil
```
This is set automatically when loading from a file via `LyrebirdBuffer.load(url:)` or `loadAllChannels(url:)`. For manually-filled buffers, set `sampleRate` explicitly.
When playing a file recorded at a different sample rate than the engine, ask the buffer for the correcting `playRate` multiplier via `LyrebirdBuffer.nativeRateScale(engineSampleRate:)`. The helper is on the buffer itself so any buffer-consuming generator (`PlayBuffer`, granular, future warp/scrubbers) can reuse it:
```swift
let buf = try LyrebirdBuffer.loadAllChannels(url: url) // buf.sampleRate set automatically
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class SamplePlayer: SynthesizerBase {
override func build() {
let rateScale = buf.nativeRateScale(engineSampleRate: engine.sampleRate)
let player = PlayBuffer.Audio(buffer: buf, loop: false,
doneAction: .freeNode, rate: rateScale)
output(bus: 0, source: player)
}
}
```
Returns `1.0` when `buffer.sampleRate` is `nil` (rate unknown).
---
## lyrebirdBufferRead
Free function used by `PlayBuffer` (and available to future generators like `GrainBuf`):
```swift
internal func lyrebirdBufferRead(
_ buffer: LyrebirdBuffer,
channel: Int,
phase: LyrebirdFloat,
interpolation: TableInterpolation,
loop: Bool
) -> LyrebirdFloat
```
Frame boundaries are **clamped** when `loop == false`, **wrapped modulo** `buffer.count` when `loop == true`.
---
## Combined example: looper
```swift
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class Looper: SynthesizerBase {
let recordBuf = LyrebirdBuffer(count: 44100 * 4, channelCount: 2) // 4-second stereo buffer
lazy var recorder = RecordBuffer.Audio(input: micInput, buffer: recordBuf, loop: false, doneAction: .nothing)
lazy var player = PlayBuffer.Audio(buffer: recordBuf, loop: true)
override func build() {
output(bus: 0, source: recorder) // monitor mic while recording
// player is added separately after recording finishes
}
}
// Stop recording after 4 seconds, start playback:
looper.recorder.run = 0.0
try engine.add(playerSynth)
```
## Combined example: control automation round-trip
```swift
let automationBuf = LyrebirdBuffer(count: 1000)
// Record an LFO curve
let lfo = OscSin.Control(freq: 0.5)
let rec = RecordBuffer.Control(input: lfo, buffer: automationBuf, loop: false, doneAction: .nothing)
// Play it back later
let player = PlayBuffer.Control(buffer: automationBuf, loop: true)
// Wire player output to a parameter (e.g. oscillator frequency)
```
---
## Live buffer swap
`PlayBuffer.Audio`, `PlayBuffer.Control`, `BufferRead.Audio`, and
`BufferRead.Control` all expose a `setBuffer(_:engine:)` method that replaces
the source buffer on a running engine without rebuilding the synth graph.
```swift
let player = PlayBuffer.Audio(buffer: bufA, loop: true)
// later, while the engine is running:
player.setBuffer(bufB, engine: engine) // swap source
player.setBuffer(nil, engine: engine) // silence (slot empty)
```
Constraints (precondition-trapped):
- New buffer's `channelCount` must equal the initial buffer's `channelCount` —
the generator's output buffer shape is fixed at init.
- Frame `count` may differ; phase wrapping uses the loaded buffer's `count` on
each block. If `_phase` overshoots the new (smaller) buffer, the next sample
read is clamped (`loop == false`) or wrapped (`loop == true`) by
`lyrebirdBufferRead`, and the in-loop wrap normalises `_phase` afterwards.
- `PlayBuffer.Control` was preconditioned mono at init; the setter inherits
that — any swap-in buffer must satisfy `channelCount == 1`.
The previously installed buffer's retain is routed through
`engine.bufferSwapKillQueue` and released by the engine's background
`freeWorker`, never on the RT thread. See ``BufferGuide`` § "Live Buffer Swap"
for the full pattern.
---
## See also
- `Sources/Lyrebird/Generators/RecordBuffer.swift`
- `Sources/Lyrebird/Generators/PlayBuffer.swift`
- `Sources/Lyrebird/Buffers/LyrebirdBuffer.swift` — buffer allocation, fill, invalidation, sampleRate
- `Sources/Lyrebird/Buffers/RTBufferSlot.swift` — atomic slot powering live buffer swap
- `docs/stdlib/generators.md` — built-in generator index
- `docs/engine/bus-system.md` — bus layout
+236
View File
@@ -0,0 +1,236 @@
# Dynamics Generators
Five signal-processing generators for amplitude tracking, pitch tracking, limiting, compression, and expansion.
All generators are **single-channel in / single-channel out** (except `FreqTracker`, which outputs two channels). Multi-channel use relies on MCE — wiring a multi-channel source creates N independent instances. For linked-mode stereo compression, compute a shared side-chain level with `AmplitudeFollower` and pass it as the input to shared `threshold`/`ratio` controls.
---
## `AmplitudeFollower` — Envelope Follower
File: `Sources/Lyrebird/Generators/Dynamics/AmplitudeFollower.swift`
Tracks the instantaneous amplitude of an input signal using a one-pole smoother with independent attack and release time constants.
```swift
AmplitudeFollower.Audio(in:attackTime:releaseTime:)
AmplitudeFollower.Control(in:attackTime:releaseTime:)
```
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `in` | `ValidGeneratorInput` | — | Signal to track |
| `attackTime` | `ValidGeneratorInput` | `0.01` | Rise time in seconds |
| `releaseTime` | `ValidGeneratorInput` | `0.1` | Fall time in seconds |
**Output:** single channel, amplitude estimate ≥ 0.
**Algorithm:**
```
attackCoeff = exp(−1 / (sr × attackTime))
releaseCoeff = exp(−1 / (sr × releaseTime))
abs_x = |x[n]|
coeff = abs_x > prevAmp ? attackCoeff : releaseCoeff
out[n] = coeff × prevAmp + (1 − coeff) × abs_x
```
Setting `attackTime` or `releaseTime` to `0` makes that transition instantaneous (coefficient → 0).
`denormalsToZero()` applied to state after each sample.
**Control variant:** computes block-peak, applies one smoothing step, outputs linear ramp to downstream audio consumers.
**Usage:**
```swift
let mic = In.Audio(bus: 0)
let level = AmplitudeFollower.Audio(in: mic, attackTime: 0.005, releaseTime: 0.5)
// Use level as a modulation source:
let vca = mic * level
```
---
## `FreqTracker` — Monophonic Pitch Tracker
File: `Sources/Lyrebird/Generators/Dynamics/FreqTracker.swift`
Estimates the fundamental frequency of a monophonic signal using the **YIN algorithm** (de Cheveigné & Kawahara 2002). Produces a two-channel output: frequency in Hz and a confidence value.
```swift
FreqTracker(in:fftSize:hopSize:minFreq:maxFreq:)
```
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `in` | `ValidGeneratorInput` | — | Signal to analyse |
| `fftSize` | `Int` | `512` | Analysis window (power of 2, in [64, 512]). Set at init. |
| `hopSize` | `Int?` | `fftSize / 2` | Samples between analyses. Set at init. |
| `minFreq` | `Double` | `60.0` | Lower search bound in Hz |
| `maxFreq` | `Double` | `3000.0` | Upper search bound in Hz |
**Output:** two channels.
- `result[0]` — tracked frequency in Hz (`0.0` when no pitch detected)
- `result[1]` — confidence in `[0, 1]` (`1.0` = certain, `0.0` = no pitch)
Output holds the previous hop result between analyses. On init, both channels output `0.0` until the first hop completes (after `hopSize` samples).
**YIN Algorithm:**
1. Accumulate samples in a `fftSize`-sample ring buffer.
2. Every `hopSize` samples: compute squared difference function `d[τ]`.
3. Compute cumulative mean normalised difference function (CMNDF).
4. Find first `τ` where CMNDF `< 0.1` (adjustable threshold).
5. Parabolic interpolation for sub-sample period accuracy.
6. Confidence `= 1 − CMNDF[τ_peak]` (clamped to `[0, 1]`).
**Pre-allocated buffers (RT-safe):**
- `_inputRing: [Double]` of length `fftSize`
- `_yinBuffer: [Double]` of length `fftSize / 2`
**No Control variant** — pitch tracking is sample-accurate by design.
**Usage:**
```swift
let tracker = FreqTracker(in: In.Audio(bus: 0))
// Write freq to bus 2, confidence to bus 3:
output(bus: 2, source: tracker)
```
---
## `LookAheadLimiter` — True Look-Ahead Limiter
File: `Sources/Lyrebird/Generators/Dynamics/LookAheadLimiter.swift`
Delays the output by `lookAheadTime` seconds and uses the look-ahead window to detect peaks before they arrive, guaranteeing the output never exceeds `±maxAmplitude`. No overshoot.
```swift
LookAheadLimiter(in:maxAmplitude:lookAheadTime:sampleRate:)
```
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `in` | `ValidGeneratorInput` | — | Signal to limit |
| `maxAmplitude` | `ValidGeneratorInput` | `1.0` | Peak ceiling (absolute value) |
| `lookAheadTime` | `Double` | `0.005` | Delay in seconds. Set at init. |
| `sampleRate` | `Double` | `44100.0` | Used to size ring buffers at init. |
**Output:** single channel, delayed by `lookAheadSamples = Int(lookAheadTime × sampleRate)`.
**Algorithm:**
1. Write incoming sample into delay and peak ring buffers.
2. Scan the look-ahead window (`lookAheadSamples`) for peak.
3. Required gain = `min(1, maxAmplitude / peak)`.
4. Attack is **instantaneous** (gain can always be reduced within the window).
5. Release smoothed: `releaseCoeff = exp(−1 / (sr × lookAheadTime))`.
6. Output = delayed sample × current gain.
**Pre-allocated buffers:**
- `_delayRing`, `_peakRing`: length `lookAheadSamples + 513`.
> **Note:** Pass `sampleRate` at init if you know the engine's sample rate in advance (e.g. from `SynthesisEngine.sampleRate`). If not supplied, the default 44100 Hz is used to size the ring buffers. A mismatch causes the delay to differ from `lookAheadTime`, but will not crash.
**No Control variant** — latency management is meaningless at block rate.
**Usage:**
```swift
let mastered = LookAheadLimiter(in: mix, maxAmplitude: 0.99, lookAheadTime: 0.005)
```
---
## `Compressor` — Feed-Forward Compressor
File: `Sources/Lyrebird/Generators/Dynamics/Compressor.swift`
Reduces gain when the signal level exceeds `threshold`. Gain is smoothed with attack and release time constants — fast transients may briefly overshoot.
```swift
Compressor.Audio(in:threshold:ratio:attack:release:kneeWidth:makeupGain:)
Compressor.Control(in:threshold:ratio:attack:release:kneeWidth:makeupGain:)
```
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `in` | `ValidGeneratorInput` | — | Signal to compress |
| `threshold` | `ValidGeneratorInput` | `-6.0` | Level in dB above which compression engages |
| `ratio` | `ValidGeneratorInput` | `4.0` | Compression ratio (> 1; e.g. `4.0` = 4:1) |
| `attack` | `ValidGeneratorInput` | `0.01` | Attack time in seconds |
| `release` | `ValidGeneratorInput` | `0.1` | Release time in seconds |
| `kneeWidth` | `ValidGeneratorInput` | `0.0` | Soft-knee width in dB (`0` = hard knee) |
| `makeupGain` | `ValidGeneratorInput` | `0.0` | Output gain in dB added after compression |
**Output:** single-channel compressed signal.
**Gain computation:**
- Hard knee: `gain_dB = (level − threshold) × (1/ratio − 1)` when `level > threshold`.
- Soft knee (when `kneeWidth > 0`): parabolic interpolation within `±kneeWidth/2` of threshold.
- Makeup gain applied linearly after ratio.
- Gain smoothed per sample with attack/release one-pole filter.
**Control variant:** computes block-peak level, applies one smoothing step, ramps gain linearly across the block and applies it to the input.
**Usage:**
```swift
let comp = Compressor.Audio(in: bass,
threshold: -12.0, ratio: 4.0,
attack: 0.005, release: 0.08, makeupGain: 4.0)
```
---
## `Expander` — Downward Expander / Gate
File: `Sources/Lyrebird/Generators/Dynamics/Expander.swift`
Reduces gain when the signal level falls below `threshold`. Ratio of `0.0` is a hard gate; ratio of `1.0` is bypass.
```swift
Expander.Audio(in:threshold:ratio:attack:release:kneeWidth:)
Expander.Control(in:threshold:ratio:attack:release:kneeWidth:)
```
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `in` | `ValidGeneratorInput` | — | Signal to expand |
| `threshold` | `ValidGeneratorInput` | `-40.0` | Level in dB below which expansion engages |
| `ratio` | `ValidGeneratorInput` | `0.5` | `0` = gate, `1` = bypass, values between = expansion |
| `attack` | `ValidGeneratorInput` | `0.01` | Attack time in seconds |
| `release` | `ValidGeneratorInput` | `0.1` | Release time in seconds |
| `kneeWidth` | `ValidGeneratorInput` | `0.0` | Soft-knee width in dB |
**Output:** single-channel expanded signal.
**Gain computation:**
- Hard knee: `gain_dB = (threshold − level) × (1 − ratio)` when `level < threshold`.
- Soft knee: parabolic interpolation near threshold.
**Control variant:** same block-rate approach as `Compressor.Control`.
**Usage:**
```swift
let gated = Expander.Audio(in: drums, threshold: -35.0, ratio: 0.0,
attack: 0.001, release: 0.05)
```
---
## Multi-Channel Use and Side-Chain Compression
All generators are single-channel. Use MCE for parallel processing:
```swift
// Two independent mono compressors on a stereo signal
let left = Compressor.Audio(in: In.Audio(bus: 0), threshold: -12.0, ratio: 4.0)
let right = Compressor.Audio(in: In.Audio(bus: 1), threshold: -12.0, ratio: 4.0)
```
For linked stereo (preserve image), derive a shared level signal and gate both channels identically:
```swift
// Side-chain from a mono mix
let monoMix = (In.Audio(bus: 0) + In.Audio(bus: 1)) * 0.5
let level = AmplitudeFollower.Audio(in: monoMix)
// Use level to drive amplitude-based VCAs externally (not directly supported as
// a side-chain input to Compressor — compose manually with BinaryOpGenerator).
```
File diff suppressed because it is too large Load Diff
+270
View File
@@ -0,0 +1,270 @@
# Granular Synthesis
Four granular generators share a common grain pool model. All are stereo (`AudioGenerator`,
2-channel output), pre-allocate `lyrebirdGrainPoolSize = 64` grain slots at `init`, and
trigger the first grain immediately at sample 0 of the first block.
---
## Common design
### Grain pool
Each generator holds `[GrainState]` of length `lyrebirdGrainPoolSize = 64`. When a grain
triggers, the first inactive slot is claimed. When all 64 slots are active, new triggers are
silently dropped — no allocation, no error.
### `GrainState` fields
```swift
struct GrainState {
var isActive: Bool // true while grain is playing
// Buffer-reading (BufferGrain, InputGrain)
var phase: LyrebirdFloat // fractional buffer frame
var phaseInc: LyrebirdFloat // playback rate (frames/sample)
// Common
var remaining: Int // samples left in grain
var amp: LyrebirdFloat // amplitude at trigger time
var pan: LyrebirdFloat // [-1, 1]; 0 = centre
var windowPhase: LyrebirdFloat // window table position (index units)
var windowInc: LyrebirdFloat // window advance per sample
// Synthesis (SineGrain, FMGrain)
var synthPhase: LyrebirdFloat // carrier oscillator phase (index units)
var synthPhaseInc: LyrebirdFloat // carrier phase increment
var modPhase: LyrebirdFloat // FM modulator phase (index units)
var modPhaseInc: LyrebirdFloat // FM modulator increment
var modIndex: LyrebirdFloat // FM β (modulation depth)
}
```
### Scheduling (all generators)
```
hopSize = sampleRate / density (samples between grain triggers)
Per sample:
hopCounter += 1
if !hasTriggeredFirstGrain OR hopCounter >= hopSize:
reset hopCounter
find first inactive slot → activate it
(if pool full: skip)
```
### Window
All generators default to `graph.engine.sharedTables.hanningTable`. Pass a custom
`LyrebirdBuffer` to `window:` at `init` to override. The window table is looked up
per active grain per sample using linear interpolation.
### PRNG
All generators use an xorshift64 PRNG seeded at `init` (`seed: UInt64? = nil` for
time-derived, explicit value for reproducibility). Lock-free, allocation-free, RT-safe.
### Output
All generators produce 2 channels [left, right] with grains centred (equal-power pan,
`L = R ≈ sample × 0.707`). Wire through `output(bus: N, source: gen)` — `Out` fans
channel 0 to bus N and channel 1 to bus N+1.
---
## BufferGrain
Reads windowed segments from a pre-recorded `LyrebirdBuffer`.
```swift
public final class BufferGrain: AudioGenerator {
@LiveParam public var density: Double = 10.0 // grains/sec
@LiveParam public var rateSpread: Double = 0.0
@LiveParam public var panSpread: Double = 0.0
public init(buffer: LyrebirdBuffer,
position: any ValidGeneratorInput = 0.5,
positionSpread: any ValidGeneratorInput = 0.0,
duration: any ValidGeneratorInput = 0.1,
amp: any ValidGeneratorInput = 1.0,
pan: any ValidGeneratorInput = 0.0,
pitchRatio: any ValidGeneratorInput = 1.0,
pitchDispersion: any ValidGeneratorInput = 0.0,
density: (any ValidGeneratorInput)? = nil,
window: LyrebirdBuffer? = nil,
loop: Bool = true,
interpolation: TableInterpolation = .linear,
seed: UInt64? = nil,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0)
}
```
**At grain trigger:** `phase = position × bufferFrames ± positionSpread × random`,
`phaseInc = pitchRatio ± pitchDispersion × random ± rateSpread × random`.
---
## SineGrain
Each grain generates a windowed sine tone. Tone parameters are **polled per grain trigger**
from their `ValidGeneratorInput` sources (block-constant via fan-out cache).
```swift
public final class SineGrain: AudioGenerator {
@LiveParam public var density: LyrebirdFloat = 10.0 // grains/sec
@LiveParam public var duration: LyrebirdFloat = 0.1 // seconds
public init(freq: any ValidGeneratorInput = 440.0, // Hz, polled at trigger
amp: any ValidGeneratorInput = 0.5, // amplitude, polled at trigger
window: LyrebirdBuffer? = nil,
seed: UInt64? = nil)
}
```
**Per-grain synthesis (table-index domain):**
```
synthPhaseInc = freq × tableSize / sampleRate
per sample:
output = sineTable[synthPhase] (linear interpolation)
synthPhase += synthPhaseInc (wraps modulo tableSize)
```
### Example — frequency spread via generator
```swift
let freqLFO = OscSin.Control(freq: 0.3) * 200.0 + 440.0
let sineGrains = SineGrain(freq: freqLFO, amp: 0.4)
sineGrains.density = 25.0
sineGrains.duration = 0.06
```
---
## FMGrain
Each grain generates a windowed two-operator FM tone. All four parameters are
**polled per grain trigger** from their `ValidGeneratorInput` sources.
```swift
public final class FMGrain: AudioGenerator {
@LiveParam public var density: LyrebirdFloat = 10.0
@LiveParam public var duration: LyrebirdFloat = 0.1
public init(carrierFreq: any ValidGeneratorInput = 440.0, // Hz
modFreq: any ValidGeneratorInput = 440.0, // Hz
modIndex: any ValidGeneratorInput = 1.0, // β
amp: any ValidGeneratorInput = 0.5,
window: LyrebirdBuffer? = nil,
seed: UInt64? = nil)
}
```
**FM formula (table-index domain):**
```
modOut = sineTable[modPhase] // ∈ [-1, 1]
fmDisplace = β × modOut × tableSize / (2π)
output = sineTable[carrierPhase + fmDisplace] (linear interpolation)
per sample:
carrierPhase += carrierFreq × tableSize / sampleRate
modPhase += modFreq × tableSize / sampleRate
(both wrap modulo tableSize)
```
`fmGrainTableSizeDivTwoPi = lyrebirdDefaultTableSize / (2π)` is a module-level
constant computed once at load time (never on the RT thread).
### Example — modulation index swept by envelope
```swift
let env = EnvelopeGen.Audio(envelope: ...) * 8.0 // β: 0 → 8 over envelope
let fmGrains = FMGrain(carrierFreq: 330.0, modFreq: 330.0,
modIndex: env, amp: 0.3)
fmGrains.density = 20.0
fmGrains.duration = 0.1
```
---
## InputGrain
Records a live audio input into an internal circular buffer
(`lyrebirdInputGrainSize = 131072` frames, ~3 s at 44 100 Hz) and reads windowed
grains from that history.
```swift
public final class InputGrain: AudioGenerator {
@LiveParam public var density: LyrebirdFloat = 10.0
@LiveParam public var duration: LyrebirdFloat = 0.1
@LiveParam public var position: LyrebirdFloat = 0.0 // 0=recent, 1=oldest
@LiveParam public var positionSpread: LyrebirdFloat = 0.0
@LiveParam public var rate: LyrebirdFloat = 1.0
@LiveParam public var rateSpread: LyrebirdFloat = 0.0
@LiveParam public var amp: LyrebirdFloat = 1.0 // output scaler
public init(input: any ValidGeneratorInput,
window: LyrebirdBuffer? = nil,
captureSize: Int = lyrebirdInputGrainSize,
interpolation: TableInterpolation = .linear,
seed: UInt64? = nil)
}
```
### Position semantics
| `position` | Grain reads from |
|------------|-----------------|
| `0.0` | Most recent captured audio (minimum latency) |
| `0.5` | Middle of capture history |
| `1.0` | Oldest audio in circular buffer |
`positionSpread` adds ± random offset per grain (in capture-buffer fractions).
### Circular buffer
- Size: `lyrebirdInputGrainSize = 131072` frames by default (~3 s at 44 100 Hz,
~2.7 s at 48 000 Hz). Override via `captureSize:` init param.
- Pre-allocated as a `LyrebirdBuffer` at `init`; written via `buffer.write(_:frame:channel:)`.
- Only channel 0 is recorded (mono capture). Use `Out` + `In` routing if stereo capture
is required.
### Example — live microphone granulator
```swift
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class MicGranulator: SynthesizerBase {
override func build() {
let mic = input(bus: 0) // live mic on audio input bus 0
let grains = InputGrain(input: mic)
grains.density = 25.0
grains.duration = 0.07
grains.position = 0.05 // 50 ms in the past
grains.positionSpread = 0.02
grains.amp = 0.9
output(bus: 0, source: grains) // stereo out on buses 0 & 1
}
}
```
---
## RT safety summary
| Concern | Handled by |
|---------|-----------|
| No allocation in `_computeSamples` | Pool pre-allocated in `init`; pool-full = silent skip |
| No CoW on output buffer | `_result` is a `var` on a `class`; single owner |
| No CoW on circular buffer | `LyrebirdBuffer` wraps `UnsafeMutablePointer` |
| Randomness | xorshift64 — no syscall, no lock |
| Sine/FM table access | `sharedTables.sineTable` — never invalidated |
| Window table access | `sharedTables.hanningTable` or guarded user `LyrebirdBuffer` |
| Per-grain input polling | `.floatValue(graph:)` routes through fan-out cache — at most one evaluate per block |
---
## Constants (`LyrebirdConstants.swift`)
| Constant | Value | Description |
|----------|-------|-------------|
| `lyrebirdGrainPoolSize` | `64` | Max simultaneous grains per generator |
| `lyrebirdInputGrainSize` | `131072` | Circular capture buffer frames for `InputGrain` |
+367
View File
@@ -0,0 +1,367 @@
# Multi-Channel Expansion (MCE)
Lyrebird supports multi-channel signal flow through two complementary mechanisms:
1. **Multi-row single Generators** — one Generator instance whose internal `_result` has
multiple rows (`Pan2`, the `Pan4` family — `PanAz` / `PanAzDistance` / `PanXY` / `PanXYDistance`, `PanN`, `AmbiEncoder1`, `AmbiDecoder1`, `SVF`, multi-channel
`In` / `BufferRead` / `PlayBuffer`, `FrequencyShifter.Audio`, `Chorus.Audio`,
`TimeStretch.Audio`).
2. **`GeneratorArray`** — explicit wrapper around N independent generators, each
contributing one channel.
The `+ - * /` operators understand both forms — see [Multi-channel operators](#multi-channel-operators)
below.
---
## `outputChannelCount`
Every `Generator` advertises its fixed output channel count via `var outputChannelCount: Int`.
The default (provided by `GeneratorBase`) is `1`. Multi-row generators override to return their
actual channel count (set at `init`, never changes at runtime). The arithmetic operators read
this property to decide how to broadcast across operand pairs.
When writing a custom multi-row Generator, you **must** override `outputChannelCount` to match
the row count of your `_result`. A missing override causes the `+ - * /` operators to treat
your generator as mono, silently dropping channels 1..N-1.
---
## Multi-channel operators
The `+ - * /` operators on `Generator` (and `any ValidGeneratorInput`) produce a
`BinaryOpGenerator` that is channel-aware. The output channel count and per-channel
combination rule are decided at graph-construction time from each operand's
`outputChannelCount`:
| lhs × rhs | Output | Behaviour |
|-----------|--------|-----------|
| `1 × 1` | 1-row | Classic scalar / mono fast path. |
| `1 × N` | N-row | Mono `lhs` broadcasts: row[i] = lhs[0] op rhs[i]. |
| `N × 1` | N-row | Mono `rhs` broadcasts: row[i] = lhs[i] op rhs[0]. |
| `N × N` | N-row | Element-wise: row[i] = lhs[i] op rhs[i]. |
| `N × M`, both > 1, N ≠ M | — | `precondition` traps at `init`. No implicit wrap-extend, no truncation — Lyrebird requires explicit per-channel composition. |
```swift
// Stereo × scalar — both channels scale.
let pan = Pan2(input: osc, pan: -0.3)
output(bus: 0, source: pan * 0.5)
// Mono + stereo — mono broadcasts to both channels.
let dry = OscSin.Audio(freq: 220)
output(bus: 0, source: dry + pan)
// Stereo + stereo — element-wise.
let dry2ch = input(bus: 0, channels: 2)
let wet2ch = input(bus: 4, channels: 2)
output(bus: 0, source: dry2ch * 0.7 + wet2ch * 0.3)
// 2 × 3 — traps. Compose explicitly via channel selection or GeneratorArray.
// stereoGen * tripleGen // precondition fail at init
```
### Channel-aware `mul:` / `add:` parameters
The `mul:` and `add:` parameters on every Generator (`OscSin.Audio(..., mul: x)`,
`SVF.Audio(..., add: y)`, etc.) follow the same broadcast policy as the `*` / `+` operators
above:
- A mono (1-channel) `mul`/`add` broadcasts to every output channel — the historical
scalar-gain case. A scalar literal, a `ParameterNode`, a `Lag`, or any other single-channel
generator works unchanged.
- A multi-channel `mul`/`add` whose channel count matches the output applies element-wise
per channel — useful for per-side gain on a stereo source, per-component scaling on an
ambisonic encoder, etc.
- A multi-channel `mul`/`add` whose channel count does **not** match the output traps via
`precondition` at the apply site (same shape-mismatch policy as `BinaryOpGenerator`).
Use `*` for free composition with the broadcast rules; use `mul:` for scalar gain trims and
matched-shape per-channel modulation that should ride alongside the generator's main output.
---
## GeneratorArray
`GeneratorArray` wraps N independent generators and produces an N-channel
`[[LyrebirdFloat]]`. It conforms to `Generator`, so it participates in the fan-out cache
and can be passed anywhere a `ValidGeneratorInput` is accepted.
```swift
let arr = GeneratorArray([OscSin.Audio(freq: 440.0), OscSin.Audio(freq: 880.0)])
```
### expand()
The `expand(_:factory:)` free function is the idiomatic way to create a `GeneratorArray`
from an array of inputs:
```swift
let oscs = expand([440.0, 880.0]) { OscSin.Audio(freq: $0) }
output(bus: 0, source: oscs) // bus 0 = 440 Hz, bus 1 = 880 Hz
```
### Element-wise operators
All four arithmetic operators work element-wise and return a new `GeneratorArray`:
```swift
let quiet = oscs * 0.5 // each channel × 0.5
let louder = 2.0 * oscs // scalar op GeneratorArray
let sum = oscs + otherOscs // element-wise (counts must match)
let diff = oscs - 0.1 // subtract scalar from each channel
```
Mismatched-count `GeneratorArray op GeneratorArray` is caught by a `precondition` at
build time.
`GeneratorArray op multi-row-generator` (e.g. `oscs * Pan2(...)`) is also caught by a
`precondition`. `GeneratorArray._computeSamples` reads only row 0 of each inner generator,
so a multi-row operand would silently drop channels 1..N-1 inside each element-wise
product. The fix is to compose explicitly via `ChannelSelect` (`pan.left` / `pan.right`)
or by zipping per-channel into a `GeneratorArray`. For arithmetic on multi-row
generators directly, use the `+ - * /` operators on the generator itself (Pan2, SVF, etc.) —
those broadcast properly without needing a `GeneratorArray` wrapper.
---
## Multi-channel Out
`Out` writes each channel of its source to consecutive buses automatically:
| Source channels | Buses written |
|---|---|
| 1 (mono — current default) | `bus` |
| 2 (stereo) | `bus`, `bus + 1` |
| N | `bus` … `bus + N - 1` |
```swift
output(bus: 0, source: Pan2(input: osc, pan: 0.0)) // writes buses 0 and 1
output(bus: 0, source: expand([440.0, 880.0]) { OscSin.Audio(freq: $0) }) // same
```
Mono sources remain unaffected — they return one channel and write only `bus`.
---
## Pan2
Equal-power stereo panner. Maps mono input + pan position `[-1, 1]` to a two-channel
output `[left, right]` using the sine/cosine law:
```
angle = (pan + 1) / 2 × π/2
left = cos(angle) × input
right = sin(angle) × input
```
Power invariant: `left² + right² = input²` at all pan positions.
```swift
output(bus: 0, source: Pan2(input: OscSin.Audio(freq: 440.0), pan: -0.3))
// bus 0 = left (slightly louder), bus 1 = right
```
Pan position accepts any `ValidGeneratorInput` and may be modulated at audio rate.
---
## Multi-channel input
Read N consecutive buses with `input(bus:channels:)` inside `build()`, mirroring
`output(bus:source:)`:
```swift
// Read stereo from buses 2–3, apply gain, route to output buses 0–1
output(bus: 0, source: input(bus: 2, channels: 2) * 0.5)
```
To read hardware input, use the reserved bus offset:
```swift
// Assuming engine configured with numOutputChannels = 2
output(bus: 0, source: input(bus: engine.numOutputChannels, channels: 2))
```
`In.Audio(bus:channels:)` (or `In.Control(bus:channels:)`) is the underlying constructor
if you need it outside `SynthesizerBase`. The `bus:` parameter accepts any `ValidBus`:
plain `Int`, `AudioBus`, or `ControlBus`.
---
## Common patterns
### Stereo oscillator pair
```swift
override func build() {
let oscs = expand([440.0, 880.0]) { OscSin.Audio(freq: $0) }
output(bus: 0, source: oscs * 0.5)
}
```
### Stereo panner
```swift
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class StereoPanner: SynthesizerBase {
@LiveParam var pan: LyrebirdFloat = 0.0
override func build() {
let osc = OscSin.Audio(freq: 440.0)
output(bus: 0, source: Pan2(input: osc, pan: $pan))
}
}
```
### Stereo FX return
```swift
override func build() {
// Read wet signal from internal buses 4–5, mix back to output
let wet = input(bus: 4, channels: 2)
let dry = input(bus: 0, channels: 2)
output(bus: 0, source: dry * 0.7 + wet * 0.3)
}
```
---
---
## Inline Channel Selection
Multi-output generators can be decoupled into individual channels without bus routing.
All `AudioGenerator` and `ControlGenerator` instances support a `[n]` subscript and a
`.channel(n)` method that return a `ChannelSelect.Audio` (or `.Control`) wrapping the
source and extracting channel `n`. Out-of-range indices return silence — no crash.
Named semantic aliases are provided on specific generators as ergonomic sugar over `[n]`.
### Named aliases
| Generator | Property | Channel | Notes |
|---|---|---|---|
| `Pan2` | `.left` | 0 | |
| `Pan2` | `.right` | 1 | |
| `Pan4` subclasses (`PanAz`, `PanAzDistance`, `PanXY`, `PanXYDistance`) | `.frontLeft` | 0 | inherited from `Pan4` |
| `Pan4` subclasses | `.frontRight` | 1 | |
| `Pan4` subclasses | `.rearRight` | 2 | |
| `Pan4` subclasses | `.rearLeft` | 3 | |
| `FreqTracker` | `.freq` | 0 | Hz, 0.0 when no pitch |
| `FreqTracker` | `.confidence` | 1 | [0, 1] |
### Dynamic-channel generators
Generators whose channel count is determined at `init` also support `[n]`:
| Generator | Channel count | Index meaning |
|---|---|---|
| `PlayBuffer` | `buffer.channelCount` | one per audio file channel |
| `PanN` | `channels` (init param) | one per speaker in the ring |
| `AmbiEncoder1` | 4 | 0=W, 1=X, 2=Y, 3=Z |
| `AmbiDecoder1` | `speakers.count` (init param) | one per loudspeaker |
| `GeneratorArray` | `generators.count` | one per wrapped generator |
Out-of-range `[n]` always returns silence — no crash.
### Examples
```swift
// Pan2 — named or numeric
let pan = Pan2(input: src, pan: -0.3)
output(bus: 0, source: pan.left) // same as pan[0]
output(bus: 1, source: pan.right) // same as pan[1]
// Mono fold-down inline
output(bus: 0, source: pan[0] + pan[1])
// FreqTracker — no buses required
let tracker = FreqTracker(in: mic)
let osc = OscSin.Audio(freq: tracker.freq * 2.0)
output(bus: 0, source: osc * tracker.confidence)
// Generic subscript on any generator
output(bus: 0, source: PanXY(input: src)[2]) // rear-right channel
// PlayBuffer — route channels independently
let player = PlayBuffer.Audio(buffer: stereoBuffer)
let rev = SomeReverb(input: player[0])
output(bus: 0, source: player[0] * 0.7 + rev * 0.3)
output(bus: 1, source: player[1])
// AmbiEncoder1 — extract individual B-format components
let enc = AmbiEncoder1(input: src)
let W = enc[0] // omni
let X = enc[1] // front-back
// AmbiDecoder1 — per-speaker processing (encoder feeds decoder directly).
// Use AmbiSpeakerLayout for the common symmetric rigs (quad / hexagon /
// octagon / cube / doubleHexagon / doubleOctagon) or stackedRings(...).
let dec = AmbiDecoder1(input: enc, speakers: AmbiSpeakerLayout.quad())
output(bus: 0, source: dec[0] * frontGain)
output(bus: 1, source: dec[1] * frontGain)
output(bus: 2, source: dec[2])
output(bus: 3, source: dec[3])
// PanN — extract individual speakers
let ring = PanN(input: src, channels: 8, position: lfo)
output(bus: 0, source: ring[0]) // speaker 0 only
output(bus: 4, source: ring[4]) // speaker 4 only
// MCE decoupling — GeneratorArray subscript
let oscs = expand([440.0, 880.0, 1320.0]) { OscSin.Audio(freq: $0) }
output(bus: 0, source: oscs[0] + oscs[1]) // mix first two partials only
// Stereo signal → per-channel analysis → four signals inline (no buses)
let stereo = PlayBuffer.Audio(buffer: stereoBuffer) // 2-channel
let trackerL = FreqTracker(in: stereo[0]) // left → [freq, confidence]
let trackerR = FreqTracker(in: stereo[1]) // right → [freq, confidence]
output(bus: 0, source: OscSin.Audio(freq: trackerL.freq) * trackerL.confidence)
output(bus: 1, source: OscSin.Audio(freq: trackerR.freq) * trackerR.confidence)
```
### Fan-out guarantee
`pan.left` and `pan.right` both hold a reference to the same `Pan2` instance. When both
are evaluated in one segment, the segment-serial cache ensures `Pan2._computeSamples`
fires exactly once — both selectors see sample-consistent data at zero extra cost.
### GeneratorArray note
`GeneratorArray` also supports `[n]`, returning `ChannelSelect.Audio` that selects the
Nth channel of the entire array's output. For the raw generator instance, use `.generators[n]`.
---
## Angle convention
Every panning and ambisonic generator that accepts an azimuth, elevation, spread,
or rotation parameter takes the angle in **radians** — never degrees. Affected:
`AmbiEncoder1` (`azimuth`, `elevation`), `AmbiDecoder1` (`speakers: [(az, el)]`),
`AmbiDecoderMono` (`azimuth`, `elevation`), `AmbiEncoderStereo` (`spread`),
`AmbiSpeakerLayout` (`elevation`, `azimuthOffset`), `PanAz` / `PanAzDistance`
(`azimuth`).
Convert at the language-side boundary (UI knobs, OSC messages, score files
authored in degrees) with `degreesToRadians(_:)` / `radiansToDegrees(_:)` from
`LyrebirdMusicMath`. Array overloads and `Collection<Double>.degreesToRadians()` /
`.radiansToDegrees()` are also available for batched layout setup.
```swift
let enc = AmbiEncoder1(input: src, azimuth: degreesToRadians(45.0))
```
The `Pan2` / `PanN` / `PanXY` family is the exception — those take normalised
position in `[-1, 1]` and apply their own internal scaling.
---
## See Also
- `Sources/Lyrebird/Generators/ChannelSelect.swift` — `ChannelSelect.Audio/.Control`, `[n]` subscript
- `Sources/Lyrebird/GeneratorCore/GeneratorArray.swift` — `GeneratorArray` type, operators, `expand()`
- `Sources/Lyrebird/Generators/Pan2.swift` — stereo panner
- `Sources/Lyrebird/Generators/Out.swift` — multi-channel write logic
- `Sources/Lyrebird/Generators/In.swift` — `In.multi(bus:channels:)`
- `docs/engine/bus-system.md` — bus layout and reserved ranges
- `docs/protocols/writing-generators.md` — Pattern 4 (multi-output generators), Pattern 5 (MCE), Pattern 6 (channel selection)
+577
View File
@@ -0,0 +1,577 @@
# Spectral Processing
FFT / IFFT infrastructure using Accelerate/vDSP with a polar-primary buffer. The analysis + processor + IFFT pipeline is consolidated into one `SpectralChain.Audio` Generator. The legacy `FFTAnalysis` + `IFFTSynthesis` generators have been removed entirely; a synthOnly mode drives the IFFT bank from an external `SpectralBufferGenerator` (e.g. `SpectralBufferRead`, `SpectralPlayBuffer`).
## Overview
| Layer | Type | Role |
|---|---|---|
| `SpectralBuffer` | Data container | Polar (magnitude + phase) FFT frame |
| `SpectralChain.Audio` | `AudioGenerator` | Consolidated STFT pipeline: forward FFT → processor chain → optional sidechain → optional fan-out → N × IFFT. Four modes. |
| `SpectralProcessor` | Protocol | In-place polar transform called after each FFT hop |
| `SpectralProcessor2` | Protocol | Two-input processor (cross-synthesis / sidechain) |
| `SpectralFanOutProcessor` | Protocol | Mono → N decorrelation processor (writes per-channel destination buffers) |
| `SpectralBufferGenerator` | Protocol | A `Generator` that owns + populates its own `spectralBuffer` each hop; drives synthOnly mode of `SpectralChain.Audio` |
| `SpectralBufferRead` | `SpectralBufferGenerator` | Random-access frame playback via normalized position |
| `SpectralPlayBuffer` | `SpectralBufferGenerator` | Phase-vocoder playback with time-stretch |
### SpectralChain.Audio — four operating modes
```swift
// 1. Mono resynthesis — audio in, audio out:
let chain = SpectralChain.Audio(
input: signal,
fftSize: 2048,
hopSize: 512,
stages: [.mono(SpectralDiffuse(fftSize: 2048, amount: 0.5))]
)
output(bus: 0, source: chain)
// 2. Mono → N fan-out (stereo decorrelation example):
let diffuser = SpectralStereoDiffuse(amount: 0.8)
let stereoChain = SpectralChain.Audio(
input: monoIn,
fftSize: 2048,
fanOut: diffuser
)
output(bus: 0, source: stereoChain[0])
output(bus: 1, source: stereoChain[1])
// 3. Analyze-only for feature extraction or sidechain:
let analysisOnly = SpectralChain.Audio(
input: signal,
fftSize: 2048,
analyzeOnly: true
)
let centroid = SpectralCentroid.Control(analysis: analysisOnly,
sampleRate: engine.sampleRate)
// 4. SynthOnly — IFFT bank driven by a pre-analysed frame buffer:
let player = SpectralPlayBuffer(frameBuffer: frames, fftSize: 2048, hopSize: 512)
let synth = SpectralChain.Audio(spectralSource: player,
fftSize: 2048, hopSize: 512)
output(bus: 0, source: synth)
```
### Mono → N decorrelation
`SpectralFanOutProcessor` is a processor shape that reads the source spectral buffer (post-`SpectralProcessor` chain) and writes a full polar spectrum into each of N destination buffers. The host `SpectralChain.Audio` then runs N IFFTs to produce N audio output channels.
**`SpectralStereoDiffuse`** is the first conformer. Mono → stereo. Magnitudes pass through unchanged. Phases blend toward independent per-channel uniform random targets via shortest-angular-distance interpolation. Channels 0 and 1 draw from anti-correlated xorshift64 streams (seeded from `seed` and `seed ^ spectralStereoDiffuseAntiSeedMask`).
```swift
let diff = SpectralStereoDiffuse(amount: 0.8, seed: 0xDEADBEEF)
let chain = SpectralChain.Audio(input: monoIn, fftSize: 2048, fanOut: diff)
```
- `amount == 0` is exact bypass; both output channels equal the input.
- `amount == 1` is full per-channel randomisation, producing a wide decorrelated stereo image with magnitude conserved per bin.
- Magnitude conservation guarantees per-channel energy is preserved; summing L + R does **not** reconstruct the input (the random phase realisations interfere).
### Conversion flow per hop (non-synthOnly modes)
```
SpectralChain.Audio._runAnalysisHop()
vDSP_fft_zrip (forward) → private _fftAnalysisRealp/Imagp
_writeFromRectangular → spectralBuffer (polar: mag + phase)
[Processor chain — all in polar]
[Optional fan-out: SpectralFanOutProcessor → per-channel destinations]
SpectralChain.Audio._runIFFTBank() (one IFFT per output channel)
_readToRectangular → per-channel work arrays
vDSP_fft_zrip (inverse) + WOLA overlap-add → per-channel audio output
```
In synthOnly mode, `_runAnalysisHop` skips windowing + forward FFT + polar conversion; the source `SpectralBufferGenerator` has already populated `spectralBuffer` during its own `_computeSamples`. Registered processors and fan-out run as usual on the source's buffer, then the IFFT bank resynthesises.
### vDSP normalization
vDSP forward real FFT multiplies output by 2 (Apple convention). After rect→polar conversion, `dcValue` reflects this:
```
buf.dcValue ≈ 2 × Σ window[n] × input[n]
```
The synthesis-side WOLA normalisation factor `1 / (2N × Σ w²[n] / hopSize)` is pre-multiplied into the synthesis window at init, so a single `vDSP_vmul` in the IFFT path handles windowing + gain correction. Round-trip unity gain holds at any integer overlap ratio with the default sine window.
### Latency
Output is delayed by exactly `hopSize` samples (one hop). Block 0 outputs silence; block 1 outputs the first IFFT result.
### Precision note
Polar conversion uses `vDSP_zvmags + vvsqrtf + vvatan2f`; the inverse path uses `vvcosf + vvsinf + vDSP_vmul`. The round-trip introduces ~1e-7 float error per hop — inaudible in practice. Pass-through with no processors is not bit-exact with raw rectangular processing.
---
## SpectralBuffer
Holds one FFT frame in **polar form**: magnitudes and phases stored as `UnsafeMutablePointer<Float>` — addresses are stable for the object's lifetime, no Swift Array CoW.
DC and Nyquist are purely real (no meaningful phase); they are stored as signed scalars and accessed via properties, not subscripts.
```swift
let buf = SpectralBuffer(fftSize: 2048)
// DC and Nyquist — signed scalars
buf.dcValue // signed DC (may be negative)
buf.dcValue = -3.0 // set directly
buf.nyquistValue // signed Nyquist
buf.nyquistValue = 2.5
// Complex bins k = 1 ..< fftSize/2
buf[magnitude: k] // magnitude of bin k (≥ 0)
buf[magnitude: k] = 5.0 // set magnitude
buf[phase: k] // phase of bin k (radians, in (−π, π])
buf[phase: k] = Float.pi / 4
// Convenience — works for all bins including DC (0) and Nyquist (fftSize/2)
buf.magnitude(at: 0) // abs(dcValue)
buf.magnitude(at: 1024) // abs(nyquistValue) — Nyquist bin for fftSize=2048
buf.magnitude(at: k) // _mag[k] for complex bins
buf.phase(at: k)
buf.setMagnitude(1.0, at: k)
buf.invalidate() // non-RT — signals the chain to output silence
```
### Buffer layout
For `fftSize = N`:
| Accessor | Content |
|---|---|
| `dcValue` | Signed DC component |
| `[magnitude: k]`, `[phase: k]` for k=1..N/2-1 | Complex bin k |
| `nyquistValue` | Signed Nyquist component |
---
## SpectralProcessor protocol
```swift
public protocol SpectralProcessor: AnyObject {
func process(spectral: SpectralBuffer, engine: SynthesisEngine)
}
```
`process` is called on the RT thread from inside `SpectralChain.Audio._runAnalysisHop`. Implementations must not allocate memory or acquire locks. The buffer is in polar form — read magnitudes and phases directly, modify in-place.
`engine` is the host engine. Processors that hold ``RTBufferSlot``-backed parameter buffers (e.g. `SpectralBinDelay`, `SpectralMagnitudeMap`) use it to push displaced retains to `engine.bufferSwapKillQueue` from the RT thread. Processors with no swappable state can ignore the parameter.
For vDSP batch operations on complex bins, use the package-internal helpers:
```swift
// Inside a SpectralProcessor implementation:
spectral.withUnsafeMutableMagnitudePointer { mp in
// mp points to _mag[1] — valid for fftSize/2-1 elements (bins 1..halfSize-1)
vDSP_vsmul(mp, 1, &scale, mp, 1, vDSP_Length(spectral.fftSize / 2 - 1))
}
spectral.withUnsafeMutablePhasePointer { pp in
// pp points to _phase[1] — same element count
}
```
## SpectralFanOutProcessor protocol
```swift
public protocol SpectralFanOutProcessor: AnyObject {
var outputChannelCount: Int { get }
func process(source: SpectralBuffer,
into: SpectralBuffer,
channel: Int)
}
```
Called once per output channel by the host `SpectralChain.Audio` after the `SpectralProcessor` chain has run. The source buffer is read-only from the fan-out's perspective (any single-input processor that needed to mutate it has already done so); the destination buffer is per-channel scratch that the host's IFFT bank then reads.
## SpectralBufferGenerator protocol
```swift
public protocol SpectralBufferGenerator: Generator {
var spectralBuffer: SpectralBuffer { get }
var hopSize: Int { get }
}
```
A `Generator` that owns + populates its own `spectralBuffer` each hop. Built-in conformers: `SpectralBufferRead` (random-access frame playback by normalized position), `SpectralPlayBuffer` (phase-vocoder frame playback with time-stretch). Use as `spectralSource:` arg of `SpectralChain.Audio` to drive synthOnly mode.
Both source and host chain advance internal sample-by-sample hop counters from 0 at construction. Matching `hopSize` keeps them aligned within an audio block. A precondition in `SpectralChain.Audio.init` catches `hopSize` / `fftSize` mismatches at construction time.
---
## Built-in processors
### SpectralMagnitudeScale
Multiplies all bin magnitudes (including DC and Nyquist) by a constant factor.
```swift
let chain = SpectralChain.Audio(input: sig,
stages: [.mono(SpectralMagnitudeScale(scale: 0.5))])
output(bus: 0, source: chain)
```
### SpectralFreeze
Phase-vocoder freeze: captures magnitudes and phases, then advances each bin's phase by its locked instantaneous delta on every frozen hop.
```swift
let freeze = SpectralFreeze(fftSize: 2048)
let chain = SpectralChain.Audio(input: sig, stages: [.mono(freeze)])
output(bus: 0, source: chain)
// To freeze (call from non-RT thread):
freeze.freeze()
// To unfreeze:
freeze.unfreeze()
```
`freeze()` sets an `Atomic<Bool>` flag; the RT thread captures the polar frame (magnitude + phase) on the next hop — no rect→polar conversion needed since the buffer already stores polar data.
### OnsetDetector
Per-hop onset detector. Computes an onset-detection function (ODF) — either half-wave-rectified spectral flux or complex-domain prediction error — on every FFT hop, smooths the ODF with a rolling median to derive an adaptive threshold, and increments an atomic onset counter when the latest ODF exceeds `max(rollingMedian, floor) * threshold`. A configurable refractory window (`minHopsBetweenOnsets`) suppresses double-triggering on the tail of an attack.
`OnsetDetector` itself is a `SpectralProcessor`; pair it with an `OnsetDetector.Control` generator to surface the detected onsets as a trigger signal. `OnsetDetector.Control` emits a single-sample pulse at sample `0` of any audio block during which one or more onsets fired (zero otherwise) — guaranteeing a clean ≤0 → >0 edge for downstream `SendTrigger.Control` even on back-to-back onset blocks.
```swift
let detector = OnsetDetector(
fftSize: 2048,
hopSize: 512,
method: .spectralFlux, // .complexDomain for soft / pitched onsets
threshold: 1.5,
medianWindowFrames: 7,
minHopsBetweenOnsets: 3
)
let chain = SpectralChain.Audio(
input: micIn, fftSize: 2048, hopSize: 512,
stages: [.mono(detector)], analyzeOnly: true
)
let trig = OnsetDetector.Control(detector: detector, analysis: chain)
addOutputGenerator(SendTrigger.Control(trig: trig, id: 1))
```
`threshold` and `minHopsBetweenOnsets` are backed by `Atomic` storage and may be tuned from a non-RT thread at any time. `lastODF` and `lastMedian` expose the most recent RT-side telemetry for visualisation. Reference: Bello et al., "A Tutorial on Onset Detection in Music Signals", IEEE TSAP 2005.
---
## Spectral Filtering & Phase
A family of bin-domain processors for filtering, EQ, phase manipulation, and magnitude smearing. All operate directly on `SpectralBuffer` polar storage — no rectangular conversion — and are RT-safe. All scalar parameters that may be retuned at runtime are backed by `Atomic<…>`; updates take effect on the next FFT hop.
### SpectralBrickwall
Hard brick-wall filter with `.lp` / `.hp` / `.bp` / `.br` modes. Cutoffs in Hz are converted to nearest bin indices and magnitudes outside the pass band are zeroed via `vDSP_vclr`. Phase is untouched.
```swift
let lp = SpectralBrickwall(
fftSize: 2048, sampleRate: 48000, mode: .lp, highHz: 4000)
let bp = SpectralBrickwall(
fftSize: 2048, sampleRate: 48000, mode: .bp, lowHz: 200, highHz: 2000)
lp.lowHz = 100 // live retune
```
### SpectralPhaseShift
Adds a constant offset to every complex bin's phase, leaving magnitude untouched. `.deg90` is equivalent to a Hilbert transform (analytic-signal imaginary part); `.deg180` flips DC + Nyquist sign; `.radians(_:)` allows arbitrary fixed shifts. The `radians` property accepts live updates of the complex-bin offset; the DC/Nyquist sign-flip behaviour is fixed at init by the chosen `PhaseShiftAmount`.
```swift
let hilbert = SpectralPhaseShift(fftSize: 2048, shift: .deg90)
let custom = SpectralPhaseShift(fftSize: 2048, shift: .radians(0.3))
custom.radians = 1.0
```
### SpectralGate
Per-bin spectral gate. Bins whose magnitude is below `threshold` are scaled by `floor` (∈ `[0, 1]`); bins above pass through. `floor = 0` is a hard gate; `floor = 1` is bypass. DC and Nyquist gate on `abs(value)` and preserve sign. A `thresholdDB:` convenience initialiser converts dB to linear magnitude.
```swift
let gate = SpectralGate(fftSize: 2048, thresholdDB: -40, floor: 0.1)
gate.threshold = 0.05 // live retune (linear)
```
### SpectralTilt
Tilt EQ in the spectral domain: applies a constant dB/octave slope around a pivot frequency. The per-bin gain table is pre-computed at init from `slopeDBPerOctave` and `pivotHz`, so `process` is pure `vDSP_vmul`. `slope = 0` produces unity gain everywhere. `slope` and `pivot` are init-only.
```swift
let darken = SpectralTilt(
fftSize: 2048, sampleRate: 48000, slopeDBPerOctave: -3, pivotHz: 1000)
let sparkle = SpectralTilt(
fftSize: 2048, sampleRate: 48000, slopeDBPerOctave: +6, pivotHz: 1000)
```
### SpectralBlur
Magnitude moving-average ("box blur") across complex bins. Smears spectral peaks into plateaus of width `2 · radius + 1`. Edge bins shrink the window rather than wrap. Computation uses a running sum, so cost is O(halfSize) per hop regardless of `radius`. Phase is untouched.
```swift
let blur = SpectralBlur(fftSize: 2048, radius: 4)
blur.radius = 12 // wider smear
```
### SpectralDiffuse
Continuous phase-randomisation. Each hop, every complex bin's phase is blended by `amount ∈ [0, 1]` toward a freshly drawn uniform random target. `0` is bypass; `1` is full randomisation; intermediate values produce continuous spectral smearing — useful for transient softening, reverb-like washes, and "frozen cloud" effects when combined with `SpectralFreeze`.
```swift
let diffuse = SpectralDiffuse(fftSize: 2048, amount: 0.5)
diffuse.amount = 1.0 // full smear
```
### SpectralConvolve
Frequency-domain convolution: per-bin complex multiply between the live spectrum and a second `SpectralBuffer` (`other`). Equivalent to time-domain circular convolution of the two underlying signals. `other` is typically populated by either a parallel `SpectralChain.Audio` chain (cross-synthesis or matched filtering) or a static impulse response prepared once at startup. Either buffer being invalid causes the live buffer to be cleared.
```swift
let irBuf = SpectralBuffer(fftSize: 2048)
// ... populate irBuf from a precomputed impulse-response FFT frame ...
let conv = SpectralConvolve(spectralBuffer: liveBuf, other: irBuf)
let chain = SpectralChain.Audio(input: dryIn, fftSize: 2048, hopSize: 512,
stages: [.mono(conv)])
output(bus: 0, source: chain)
```
### SpectralFormantShift
Magnitude-envelope-preserving formant shifter. Estimates the smooth spectral envelope of the current frame, whitens the spectrum by dividing it out, resamples the envelope along the bin axis by `shiftRatio`, and reapplies the shifted envelope to the whitened residual. Phase is untouched. Pairs with `SpectralPitchShift` to decouple pitch from formant motion.
Two envelope-estimation methods:
- `.cepstral` (default) — real cepstrum with a low-quefrency lifter. Accurate; uses a second `FFTSetup` allocated at init.
- `.magnitudeSmoothing(radiusBins:)` — box moving-average of magnitudes. Cheaper; coarser envelope.
`shiftRatio` is `Atomic<Float>` and clamped to `[0.25, 4.0]`. `1.0` is bypass; `< 1.0` lowers formants; `> 1.0` raises them and fades bins whose source position falls above Nyquist to 0. DC and Nyquist participate in envelope estimation as unsigned magnitudes; their signs are preserved when the reshaped magnitude is written back.
```swift
// Pitch down an octave, keep formants in place:
let pitch = SpectralPitchShift(fftSize: 2048, hopSize: 512, pitchRatio: 0.5)
let formant = SpectralFormantShift(fftSize: 2048, shiftRatio: 2.0)
let chain = SpectralChain.Audio(input: voice, fftSize: 2048, hopSize: 512,
stages: [.mono(pitch), .mono(formant)])
output(bus: 0, source: chain)
formant.shiftRatio = 1.5 // live retune
```
---
## Complete example
```swift
final class SpectralPatch: SynthesizerBase {
let mic = In.Audio(bus: 0)
let freeze = SpectralFreeze(fftSize: 2048)
lazy var chain = SpectralChain.Audio(
input: mic, fftSize: 2048, hopSize: 512, stages: [.mono(freeze)]
)
override func build() {
output(bus: 0, source: chain)
}
}
// Freeze on button press (main thread):
freeze.freeze()
```
---
## Closure-driven spectral processors
`SpectralPolarClosure` and `SpectralComplexClosure` are `SpectralProcessor` conformers that
wrap an arbitrary user function. They provide the same role for spectral DSP that
`Closure` plays for time-domain DSP — rapid prototyping of spectral transforms
inline inside a `Synthesizer.build()` body, without writing a separate class.
### SpectralPolarClosure
Provides direct zero-copy access to the `SpectralBuffer`'s polar storage
(magnitudes and phases) on each FFT hop. No coordinate conversion — the buffer already
stores polar data. This is the cheapest spectral closure variant.
```swift
// 6 dB magnitude attenuation across all complex bins + DC + Nyquist:
let halver = SpectralPolarClosure(fftSize: 2048, hopSize: 512, sampleRate: sr) { ctx in
for i in 0..<ctx.binCount {
ctx.magnitudes[i] *= 0.5
}
ctx.dcValue.pointee *= 0.5
ctx.nyquistValue.pointee *= 0.5
}
let chain = SpectralChain.Audio(input: sig, fftSize: 2048, stages: [.mono(halver)])
output(bus: 0, source: chain)
```
**Context layout** (`SpectralPolarContext`):
| Property | Type | Content |
|---|---|---|
| `magnitudes` | `UnsafeMutableBufferPointer<Float>` | Complex bin magnitudes, length `fftSize/2 - 1` (bins 1 ..< `fftSize/2`) |
| `phases` | `UnsafeMutableBufferPointer<Float>` | Complex bin phases (radians), same length |
| `dcValue` | `UnsafeMutablePointer<Float>` | Signed DC component (bin 0) |
| `nyquistValue` | `UnsafeMutablePointer<Float>` | Signed Nyquist component (bin `fftSize/2`) |
| `binCount` | `Int` | Number of complex bins = `fftSize/2 - 1` |
| `sampleRate` | `Double` | Engine sample rate in Hz |
| `fftSize` | `Int` | FFT frame size |
| `hopSize` | `Int` | Samples between hops |
| `frameIndex` | `Int` | Zero-based hop counter since processor creation |
Addressing spectral bin `k` (where `k ≥ 1`): `ctx.magnitudes[k - 1]`, `ctx.phases[k - 1]`.
### SpectralComplexClosure
Provides Cartesian (split-complex real + imaginary) access to the spectral frame.
The framework performs a polar→Cartesian conversion before the closure and a
Cartesian→polar conversion after it, so the buffer is always up to date for downstream
processors. Use this when your transform is naturally expressed in rectangular form
(complex multiplication, comb filtering, phase rotation).
**Round-trip cost:** one vectorised `vvcosf + vvsinf + vDSP_vmul` pass (polar→Cartesian)
and one `vDSP_zvmags + vvsqrtf + vvatan2f` pass (Cartesian→polar) per hop. Negligible
at typical FFT sizes but non-zero. Prefer `SpectralPolarClosure` for magnitude-only
or phase-only transforms.
```swift
// Simple 6 dB magnitude scale in Cartesian space (less efficient than polar but illustrative):
let halver = SpectralComplexClosure(fftSize: 2048, hopSize: 512, sampleRate: sr) { ctx in
for i in 0..<ctx.binCount {
ctx.real[i] *= 0.5
ctx.imag[i] *= 0.5
}
}
```
**Context layout** (`SpectralComplexContext`):
| Property | Type | Content |
|---|---|---|
| `real` | `UnsafeMutableBufferPointer<Float>` | Split-complex real parts, length `fftSize/2` |
| `imag` | `UnsafeMutableBufferPointer<Float>` | Split-complex imaginary parts, length `fftSize/2` |
| `binCount` | `Int` | = `fftSize/2` (includes packed DC/Nyquist at index 0) |
| `sampleRate` | `Double` | Engine sample rate in Hz |
| `fftSize` | `Int` | FFT frame size |
| `hopSize` | `Int` | Samples between hops |
| `frameIndex` | `Int` | Zero-based hop counter since processor creation |
Split-complex packing convention (matches vDSP):
- `real[0]` = DC value; `imag[0]` = Nyquist value.
- `real[k]` = real part of complex bin `k`; `imag[k]` = imaginary part (for `k = 1..<binCount`).
### RT-safety contract
Both closure variants execute on the RT audio thread. The closure body must:
- Not allocate heap memory (no `Array(...)`, no `class` instantiation).
- Not acquire locks.
- Not call `print`, `NSLog`, or any `String`-constructing API.
- Not `throw`.
These constraints are identical to `Closure` and are architecturally
unenforceable. Violations cause audio dropouts. Pre-allocate any scratch storage
before audio starts (e.g. via `UnsafeMutablePointer.allocate` at `build()` time)
and capture the pointer in the closure's capture list.
---
## RT safety summary
| Component | RT-safe | How |
|---|---|---|
| `SpectralChain.Audio._runAnalysisHop` | ✓ | FFT into private work arrays; vectorized rect→polar into spectralBuffer raw pointers |
| `SpectralChain.Audio._runIFFTBank` | ✓ | Vectorized polar→rect into per-channel work arrays; raw pointer IFFT; OLA via `vDSP_vadd` |
| `SpectralMagnitudeScale.process` | ✓ | `vDSP_vsmul` in-place on `_mag` pointer; scalar DC/Nyquist multiply |
| `SpectralFreeze.process` | ✓ | Reads polar directly from buffer (no atan2f); writes polar back; no allocation |
| `SpectralFreeze.freeze()` | non-RT only | Sets `Atomic<Bool>` flag; RT thread captures polar on next hop |
| `OnsetDetector.process` | ✓ | Pre-allocated per-bin and ring buffers; `Atomic<Float>` params; manual selection-sort median (no Swift `sort`) |
| `SpectralBufferRead._runHop` | ✓ | Pre-allocated interpolation scratch; vDSP interpolation; `floatValue` for position read |
| `SpectralPlayBuffer._runHop` | ✓ | Pre-allocated phase-vocoder scratch; `Atomic<Double>` rate; no allocation |
| `SpectralPolarClosure.process` | ✓ (body is user's responsibility) | Zero-copy direct pointer into `_mag[1]`/`_phase[1]`; DC/Nyquist via pre-allocated single-element pointers |
| `SpectralComplexClosure.process` | ✓ (body is user's responsibility) | Polar→rect via `_readToRectangular`; user closure on pre-allocated scratch; rect→polar via `_writeFromRectangular` |
---
## Live parameter-buffer swap
Two built-in processors hold per-bin parameter buffers that can be replaced on a
running engine without rebuilding the synth graph. Both use ``RTBufferSlot``
internally — see ``BufferGuide`` § "Live Buffer Swap" for the full pattern.
### SpectralBinDelay
```swift
let delays = LyrebirdBuffer(count: halfSize)
let feedbacks = LyrebirdBuffer(count: halfSize)
delays.fill { i, n in Double(i) / Double(n) * 0.5 }
feedbacks.fill(with: 0.6)
let bd = SpectralBinDelay(fftSize: 2048, hopSize: 512,
maxDelaySeconds: 1.0, sampleRate: 44_100,
delayTimes: delays, feedbacks: feedbacks)
// Later, mid-piece:
let newDelays = LyrebirdBuffer(count: halfSize)
newDelays.fill { i, n in Double(i) / Double(n) * 0.25 } // halve the spread
bd.setDelayTimes(newDelays, engine: engine)
// Or silence the processor:
bd.setFeedbacks(nil, engine: engine)
```
Preconditions: both buffers must be mono and have `count >= fftSize/2`. When
either slot is empty or its loaded buffer is invalid, the hop is skipped
(no spectral mutation — output passes through unchanged).
### SpectralMagnitudeMap
```swift
let curve = LyrebirdBuffer(count: 256)
curve.fill { i, n in pow(Double(i) / Double(n - 1), 2.0) } // squared compression
let map = SpectralMagnitudeMap(buffer: curve)
// Swap to a steeper curve:
let steep = LyrebirdBuffer(count: 256)
steep.fill { i, n in pow(Double(i) / Double(n - 1), 4.0) }
map.setBuffer(steep, engine: engine)
// Or bypass (input magnitudes pass through unchanged):
map.setBuffer(nil, engine: engine)
```
Precondition: buffer must be mono with `count >= 2`.
### Authoring a swap-aware SpectralProcessor
The protocol's `engine: SynthesisEngine` argument is the host engine for the
chain — pass it to `RTBufferSlot.load(engine:)` inside your `process` body.
If your processor has no swappable state, ignore it.
```swift
public final class MyEnvelopeMask: SpectralProcessor {
private let _slot: RTBufferSlot
private let _halfSize: Int
public init(fftSize: Int, mask: LyrebirdBuffer) {
precondition(mask.count >= fftSize / 2 && mask.channelCount == 1)
self._slot = RTBufferSlot(initial: mask)
self._halfSize = fftSize / 2
}
public func setMask(_ buffer: LyrebirdBuffer?, engine: SynthesisEngine) {
if let buffer {
precondition(buffer.count >= _halfSize && buffer.channelCount == 1)
}
_slot.swap(buffer, engine: engine)
}
public func process(spectral: SpectralBuffer, engine: SynthesisEngine) {
guard let mask = _slot.load(engine: engine), mask.isValid else { return }
spectral.withUnsafeMutableMagnitudePointer { mp in
for i in 0..<(_halfSize - 1) {
mp[i] *= Float(mask[i + 1])
}
}
}
}
```
+369
View File
@@ -0,0 +1,369 @@
# Lyrebird CLI Guide
`lyrebird` is the command-line tool for creating, running, and exporting Lyrebird synthesis projects. This guide walks through a complete workflow from first install to a running audio patch.
---
## Installation
The `lyrebird` binary is built from the Lyrebird package itself. From the root of the Lyrebird repository:
```sh
swift build -c release --product LyrebirdCLI
```
Then copy the binary somewhere on your `PATH`, renaming to `lyrebird`:
```sh
cp .build/release/LyrebirdCLI /usr/local/bin/lyrebird
```
Verify:
```sh
lyrebird version
# lyrebird 0.1.0
```
**Requirement:** macOS 15+, Xcode or a Swift toolchain with `swift` on your `PATH`.
---
## Quick Start
Three commands to go from nothing to audio:
```sh
lyrebird new MyPiece # 1. scaffold a project
cd MyPiece
# edit Sources/MyPiece/main.swift
lyrebird run # 2. build and run
```
That's the complete loop. The rest of this guide explains each step in depth.
---
## Commands
### `lyrebird new <name>`
Scaffolds a new Lyrebird Swift Package in a subdirectory named `<name>`.
```sh
lyrebird new MyPiece
# Created MyPiece/
```
Generated layout:
```
MyPiece/
├── Package.swift
├── MyPiece.xcworkspace/
│ └── contents.xcworkspacedata ← open in Xcode (references Package.swift)
├── Sources/
│ └── MyPiece/
│ └── main.swift ← engine setup + entry point
└── Tests/
└── MyPieceTests/
└── MyPieceTests.swift
```
Open `MyPiece.xcworkspace` in Xcode for SwiftUI previews and debugging; or stay on the terminal with `lyrebird run`.
`main.swift` is pre-wired: engine is created, `engine.start()` is called, and `RunLoop.main.run()` keeps the process alive until Ctrl+C. Add your `Synthesizer` subclasses to the same `Sources/MyPiece/` directory — they share the module namespace so no imports are needed between files.
**Name rules:** valid Swift module identifiers only — ASCII letters, digits, underscores; no leading digit; no spaces or hyphens.
```sh
lyrebird new DrumMachine # OK
lyrebird new "my piece" # error: not a valid Swift module name
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`
- Xcode-project (ships `.xcodeproj` + `.xcworkspace`): `macos-ui-xcode`, `ios-ui`, `auv3`
```sh
lyrebird new MyApp --template macos-ui-xcode # macOS .app
lyrebird new MyApp --template ios-ui # iOS .app
lyrebird new MyPlugin --template auv3 # AUv3 host + .appex
```
**Local Lyrebird checkout** — `--lyrebird-path <abs-path>` makes the generated project depend on a local Lyrebird checkout (via `.package(name: "Lyrebird", path: ...)` in `Package.swift`, `XCLocalSwiftPackageReference` in `<name>.xcodeproj`). Use while the published repo URL isn't yet accessible:
```sh
lyrebird new MyApp --template macos-ui-xcode \
--lyrebird-path /Users/me/Documents/LyrebirdII
```
See `docs/tooling/project-system.md` for the layout each template emits.
If the directory already exists, the command fails cleanly and leaves the filesystem unchanged.
---
### `lyrebird run [--release]`
Builds and runs the current project. Must be called from the project's root directory (where `Package.swift` lives).
```sh
lyrebird run # debug build — fast compile, slower audio
lyrebird run --release # release build — full optimisation, use for performance
```
Under the hood this is `swift run` / `swift run -c release`. Exit code from `swift run` passes through, so CI can detect failures normally.
**Use `--release` for real audio work.** Debug builds run without optimisations; vDSP and tight DSP loops can be noticeably slower, and the RT thread may miss its deadline under heavy load.
```sh
cd MyPiece
lyrebird run --release
# Build complete!
# MyPiece running — press Ctrl+C to stop
```
---
### `lyrebird export <name> [--to <path>] [--overwrite]`
Generates a `SynthesizerBase` subclass template and writes it to a `.swift` file. Use this to stub out a new synth inside an existing project.
```sh
# Write BassDrum.swift to the current directory
lyrebird export BassDrum
# Write to a specific path
lyrebird export BassDrum --to Sources/MyPiece/BassDrum.swift
# Replace an existing file
lyrebird export BassDrum --to Sources/MyPiece/BassDrum.swift --overwrite
```
Generated file (`BassDrum.swift`):
```swift
import LyrebirdSynth
// MARK: - BassDrum
/// A Lyrebird synthesizer — generated by `lyrebird export BassDrum` (your subclass).
final class BassDrum: SynthesizerBase {
// MARK: - Parameters
// Declare parameters here. Example:
// let freq: LyrebirdFloat = 440.0
// MARK: - Build
override func build() {
// Wire your signal graph here. Example:
// let osc = OscSin.Audio(freq: freq)
// addOutputGenerator(osc * env)
}
}
```
Without `--overwrite`, the command fails if the destination already exists — safe to run repeatedly without clobbering work in progress.
---
### `lyrebird install-templates [--force]`
Installs Lyrebird's Xcode file templates (Generator, Synthesizer, Task, …) into
`~/Library/Developer/Xcode/Templates/File Templates/Lyrebird/`. After install,
Xcode's New File dialog (`⌘N`) shows a "Lyrebird" section listing every shipped
template.
```sh
lyrebird install-templates
# Installed 12 Lyrebird Xcode templates →
# /Users/you/Library/Developer/Xcode/Templates/File Templates/Lyrebird
```
Templates are bundled with the `lyrebird` binary as SPM resources — no repo
checkout needed once `lyrebird` is on your `PATH`.
Fails with `--force`-prompt error if the destination already exists. Pass
`--force` to replace it. See [xcode-templates.md](xcode-templates.md) for the
full template catalog and per-template usage notes.
### `lyrebird uninstall-templates`
Removes the entire `~/Library/Developer/Xcode/Templates/File Templates/Lyrebird/`
directory. Will not touch any other Xcode template you have installed.
```sh
lyrebird uninstall-templates
# Removed Lyrebird templates from
# /Users/you/Library/Developer/Xcode/Templates/File Templates/Lyrebird
```
---
### `lyrebird repl`
Runs `swift build` in the current directory, then launches `swift repl` with `-I` /
`-L` / `-l` flags pointing at the package's `.build/debug` artifacts so `import LyrebirdSynth`
works immediately. (`swift package repl` was removed from the toolchain; this is the
canonical replacement — see [repl.md](repl.md) for the raw command.)
```sh
cd MyPiece
lyrebird repl
# Lyrebird 0.1.0 — starting Swift REPL
# Run `import LyrebirdSynth` to access the framework.
```
Inside the REPL:
```swift
import LyrebirdSynth
let engine = SynthesisEngine(
blockSize: 512, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 0,
driver: CoreAudioDriver()
)
try engine.start()
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class SineTone: SynthesizerBase {
@LiveParam var freq: LyrebirdFloat = 440.0
override func build() {
let osc = OscSin.Audio(freq: $freq)
output(bus: 0, source: Pan2(input: osc * 0.2))
}
}
let tone = SineTone()
try engine.add(tone)
// While audio plays — parameter writes need no try (atomic store), RT-safe
tone.freq = 880.0
engine.remove(tone)
engine.stop()
```
`@LiveParam` assignments are atomic stores — safe to do from the REPL main thread while the audio thread runs. `engine.add` / `engine.remove` are lock-free and take effect at the next block boundary.
Exit the REPL with Ctrl+D.
See [repl.md](repl.md) for full REPL reference.
---
### `lyrebird help`
Prints the command summary.
```sh
lyrebird help
lyrebird --help
lyrebird -h
```
---
### `lyrebird version`
Prints the version string.
```sh
lyrebird version
lyrebird --version
# lyrebird 0.1.0
```
---
## Interactive Shell
Running `lyrebird` with no arguments enters the `lyrebird>` shell — a LineNoise-powered command loop with history and tab completion.
```sh
lyrebird
# Lyrebird 0.1.0 — Swift audio synthesis
# Type 'help' for available commands, or 'repl' to start a Swift REPL session.
#
# lyrebird>
```
All the same commands work inside the shell:
```
lyrebird> new FMSynth
Created FMSynth/
lyrebird> export Drone --to Sources/FMSynth/Drone.swift
Exported /Users/josh/FMSynth/Sources/FMSynth/Drone.swift
lyrebird> run --release
Build complete!
...
lyrebird> quit
```
**Shell features:**
| Feature | Details |
|---|---|
| Line editing | Arrow keys, Home/End, Ctrl+A/E (linenoise) |
| Tab completion | Prefix-match on all subcommand names |
| History | Up/down arrows; persisted to `~/.lyrebird_history` on exit |
| Case-insensitive verbs | `NEW`, `Run`, `EXPORT` all work |
| Preserved casing on names | `export MySynth` → file named `MySynth.swift`, not `mysynth.swift` |
| Exit | `quit`, `exit`, `:quit`, or Ctrl+D |
---
## A Complete Workflow
```sh
# 1. Scaffold
lyrebird new PadSynth
cd PadSynth
# 2. Stub out a synth
lyrebird export Pad --to Sources/PadSynth/Pad.swift
# 3. Edit Pad.swift — fill in build()
# (your editor here)
# 4. Add to main.swift:
# try engine.add(Pad())
# 5. Test with a debug build first
lyrebird run
# 6. Once stable, run optimised
lyrebird run --release
```
---
## Error Reference
| Error message | Cause | Fix |
|---|---|---|
| `error: directory 'X' already exists.` | `new` target dir present | Remove it or choose a different name |
| `error: 'X' is not a valid Swift module name.` | Name fails identifier rules | Use ASCII letters/digits/underscores only |
| `error: 'X' already exists. Pass --overwrite to replace it.` | `export` destination exists | Add `--overwrite` flag |
| `error: swift not found.` | No Swift toolchain on PATH | Install Xcode or a Swift toolchain |
| `Build failed (exit code N).` | `swift run` failed | Check compiler output above the error |
---
## Reference Docs
| Doc | Contents |
|---|---|
| [project-system.md](project-system.md) | Generated file contents, scaffolder/runner/exporter internals |
| [repl.md](repl.md) | Full REPL reference, threading model, live coding patterns |
| [targets.md](targets.md) | All package targets and when to use each |
+120
View File
@@ -0,0 +1,120 @@
# MIDI Clock Sync
`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`.
---
## Overview
MIDI System Real-Time sends 0xF8 bytes 24 times per quarter note. `MIDIClockFollower`
maintains a rolling window of the most recent N tick arrival times (default: 24 ticks =
one quarter-note), computes the average inter-tick interval, and derives a BPM estimate.
When the estimate changes by more than 0.01 BPM it writes `clock.bpm` — which correctly
accumulates beat-offset history inside `LyrebirdClock` so routines and tasks remain
phase-continuous across tempo changes.
Transport messages are handled as follows:
| Message | Effect |
|---------|--------|
| `.start` (0xFA) | `isRunning = true`, clears tick history |
| `.continue` (0xFB) | `isRunning = true`, clears tick history (beat alignment preserved) |
| `.stop` (0xFC) | `isRunning = false`, clears tick history. `clock.bpm` is **not** modified. |
| `.clock` (0xF8) | Updates rolling estimate, pushes to `clock.bpm` if change > epsilon |
All other messages are silently ignored.
---
## Wiring `MIDIClockFollower` to `MIDI`
```swift
import LyrebirdSynth
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
driver: CoreAudioDriver()
)
try engine.start()
// Create a clock. Initial BPM is a placeholder; the follower will override it quickly.
let clock = LyrebirdClock(engine: engine, bpm: 120.0)
// Create the follower.
let follower = MIDIClockFollower(
engine: engine,
clock: clock,
smoothingWindowTicks: 24, // one quarter-note window
minBPM: 40.0,
maxBPM: 250.0
)
// Create the MIDI integration.
let midi = MIDI(engine: engine)
try midi.start()
// Register a handler that passes every message to the follower.
midi.addHandler(name: "clockFollow") { message, _ in
follower.handle(message)
}
```
After this, any sequence clock running through MIDI will continuously update `clock.bpm`.
Routines and tasks that use `ctx.wait(beats:)` or `clock.nextBeat()` will automatically
track the external tempo.
---
## Parameters
| Parameter | Default | Meaning |
|-----------|---------|---------|
| `smoothingWindowTicks` | `24` | Rolling window size in ticks. 24 = one quarter-note. Smaller windows react faster but are more sensitive to jitter. |
| `minBPM` | `20.0` | Minimum accepted BPM. Estimates below this are clamped. |
| `maxBPM` | `999.0` | Maximum accepted BPM. Estimates above this are clamped. |
---
## Reading the estimate
```swift
print(follower.estimatedBPM) // current rolling BPM estimate
print(follower.isRunning) // true between .start/.continue and .stop
```
`estimatedBPM` returns `0.0` until at least 2 ticks have arrived since the last
`.start`, `.continue`, `reset()`, or initialisation.
---
## Manually resetting
```swift
follower.reset() // clears tick history; clock.bpm and isRunning are unchanged
```
---
## Beat alignment limitation
`LyrebirdClock` does not expose a public beat re-alignment API. When a `.start` message
arrives, `MIDIClockFollower` clears its tick history but cannot reset the clock's beat
phase to match the sender's Song Position Pointer. If beat-phase alignment is required,
snapshot `clock.currentBeat` at the moment `.start` arrives and offset all beat
calculations accordingly.
---
## Thread safety
`MIDIClockFollower` is `@unchecked Sendable`. All internal state is serialised under an
`NSLock`. `handle(_:)` is safe to call from any thread — in normal use it runs on the
`lyrebird.midi` background queue that `MIDI` uses for handler dispatch. The write
to `clock.bpm` is performed outside the follower's lock to prevent lock-ordering issues
with `LyrebirdClock`'s internal lock.
+437
View File
@@ -0,0 +1,437 @@
# Non-Real-Time Rendering Guide
Lyrebird supports offline rendering — running the synthesis engine faster than real time and writing the output directly to an audio file. No audio hardware is required. This is the correct approach for:
- Bouncing a finished piece to a file
- Batch-generating audio assets
- CI/automated testing with audio output verification
- Rendering samples or stems from a Lyrebird synthesizer
---
## Two Approaches
| Approach | What it does | Output format |
|---|---|---|
| `NRTDriver` | Renders the entire engine output to file | CAF (32-bit float) |
| `RecordBuffer` + `LyrebirdBuffer.write()` | Captures a signal path mid-graph, writes after render | AIFF, WAV, or CAF |
Use `NRTDriver` for most cases — it is a drop-in replacement for `CoreAudioDriver` and requires no signal graph changes. Use `RecordBuffer` when you need to capture a specific bus, a pre-effects signal, or multiple signal paths independently.
---
## Approach 1 — `NRTDriver`
### Basic usage
Replace `CoreAudioDriver()` with `NRTDriver(outputURL:duration:)`. Everything else stays the same.
```swift
import Foundation
import LyrebirdSynth
let outputURL = URL(fileURLWithPath: "output.caf")
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
numInputChannels: 0, // no hardware input needed
driver: NRTDriver(outputURL: outputURL, duration: 5.0)
)
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class SineTone: SynthesizerBase {
override func build() {
let osc = OscSin.Audio(freq: 440.0)
output(bus: 0, source: Pan2(input: osc * 0.3))
}
}
try engine.start() // blocks until 5 seconds are rendered, then returns
try engine.add(SineTone())
// engine.add is processed on next block — but start() renders all blocks first.
// For NRT, add synthesizers BEFORE start().
```
**Important:** `NRTDriver.start()` is synchronous. It renders all blocks, writes the file, and returns. There is no `RunLoop.main.run()` needed — the process exits naturally after `start()` returns.
### Correct ordering — add synthesizers before `start()`
With `CoreAudioDriver`, `engine.add()` works while audio runs because events are queued block-by-block. With `NRTDriver`, all rendering happens inside `start()`. Synthesizers added via `engine.add()` after `start()` are never rendered.
```swift
// CORRECT for NRT
try engine.add(SineTone())
try engine.add(BassLine())
try engine.start() // renders both
// WRONG for NRT — synthesizers added after start() are ignored
try engine.start()
try engine.add(SineTone()) // too late — rendering already complete
```
### Output file
`NRTDriver` always writes a **CAF** file: 32-bit float, interleaved, at the engine's sample rate. The file is created or overwritten at `outputURL`. The file is closed and flushed when `start()` returns.
```swift
// Absolute path
let url = URL(fileURLWithPath: "/Users/josh/renders/output.caf")
// Relative to working directory
let url = URL(fileURLWithPath: "output.caf")
// Documents folder
let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
.appendingPathComponent("render.caf")
```
### Duration
Duration is set at `NRTDriver` init time and cannot be changed. The engine renders exactly `ceil(duration × sampleRate / blockSize)` blocks.
```swift
NRTDriver(outputURL: url, duration: 10.0) // 10 seconds
NRTDriver(outputURL: url, duration: 0.5) // 500 ms — good for short samples
NRTDriver(outputURL: url, duration: 120.0) // 2 minutes
```
### Scheduling multiple timed events
`engine.schedule(_:after:)` and `engine.schedule(_:at:)` work before `start()` because `currentTime` is `0` at that point. The engine holds every event in its pending queue and applies each one at the exact sample offset as it renders blocks — full sample-accurate timing with no extra plumbing required.
The example below schedules 10 sine-tone voices at random start times between 1 and 5 seconds. Each voice runs for 5 seconds via an ASR envelope. In NRT mode the render terminates at `totalDur` and the envelope ends at level 0, so no removal is needed. Total render duration = max start (5 s) + event length (5 s) = **10 seconds**.
```swift
import Foundation
import LyrebirdSynth
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class Blip: SynthesizerBase {
let freq: Double
init(freq: Double) { self.freq = freq; super.init() }
override func build() {
let attackTime = 0.02
let sustainTime = 4.66
let releaseTime = 0.3
let env = EnvelopeGen.Audio(
envelope: Envelope(levels: [0, 1, 0.6, 0],
durations: [attackTime, sustainTime, releaseTime],
curves: [0, 0, 0])
)
let osc = OscSin.Audio(freq: freq) * env * 0.15
output(bus: 0, source: Pan2(input: osc))
}
}
let outputURL = URL(fileURLWithPath: "timed_events.caf")
let sampleRate: Double = 48000
let maxStart = 5.0
let eventLength = 5.0
let totalDur = maxStart + eventLength // 10.0 s
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 0,
driver: NRTDriver(outputURL: outputURL, duration: totalDur)
)
let pitches: [Double] = [220, 277.18, 329.63, 369.99, 440,
493.88, 554.37, 659.25, 739.99, 880]
var rng = SystemRandomNumberGenerator()
for freq in pitches {
let startSec = Double.random(in: 1.0...5.0, using: &rng)
try engine.schedule(Blip(freq: freq), after: startSec)
}
do {
try engine.start()
print("Rendered: \(outputURL.path)")
} catch {
fputs("Render failed: \(error)\n", stderr)
exit(1)
}
```
Key points:
- `after: startSec` is equivalent to `at: engine.seconds(startSec)` when called before `start()` — `currentTime` is `0` so both resolve to the same absolute sample offset.
- The envelope ends at level 0 and `doneAction` defaults to `.nothing` — synths stay in the graph but output silence. In NRT the render terminates at `totalDur` so no removal is needed. In RT, poll `env.needsFree` after each block and call `engine.remove()` when `true`.
- Set `NRTDriver(duration:)` to cover the latest possible start plus the full event length. Events whose scheduled start time falls beyond `duration` are never triggered.
- `pendingQueue` defaults to 1024 slots. For larger scores, pass `eventQueueCapacity:` (must be a power of two) to `SynthesisEngine.init` — a non-power-of-two value traps at startup. Events beyond capacity are silently dropped.
---
### Scheduling events during NRT render
`@LiveParam` and `ParameterNode` use atomic stores — they work correctly during NRT rendering because the render loop calls `calculatedSamples` on every block in sequence. You can set parameters on the main thread before `start()`, but not while rendering (since `start()` blocks the calling thread).
For score-based event sequencing in NRT, use `LyrebirdRoutine` / `LyrebirdTask` before `start()`, or wire parameters as generators driven by envelope/LFO shapes.
```swift
let synth = MySynth()
synth.freq = 880.0 // set before start() — applied from block 0
try engine.add(synth)
try engine.start()
```
---
### Soundfile input
Pass an audio file into the engine as simulated hardware input. Each block, the driver reads the next `blockSize` frames from the file and writes them to the engine's input buses exactly as `iOSAudioDriver` / `CoreAudioDriver` would from a microphone.
```swift
let inputURL = URL(fileURLWithPath: "source.wav")
let outputURL = URL(fileURLWithPath: "processed.caf")
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
numInputChannels: 2, // must be ≥ file channel count
driver: NRTDriver(outputURL: outputURL, duration: 5.0,
inputURL: inputURL,
inputStartOffset: 0.0) // seconds to skip
)
```
`In.Audio(bus: n)` uses a raw bus index. Input channels start at `numOutputChannels`, so input channel 0 is `In.Audio(bus: numOutputChannels + 0)`, input channel 1 is `In.Audio(bus: numOutputChannels + 1)`, and so on — identical to live hardware input behaviour.
```swift
final class SpectralProcessor: SynthesizerBase {
override func build() {
let inL = In.Audio(bus: 2) // input ch 0 (numOutputChannels = 2)
let inR = In.Audio(bus: 3) // input ch 1
// … process inL / inR …
output(bus: 0, source: Pan2(input: inL))
output(bus: 1, source: Pan2(input: inR))
}
}
try engine.add(SpectralProcessor())
try engine.start()
```
**Rules:**
- `numInputChannels` must be ≥ the file's channel count. Extra input buses stay zero.
- If the file has fewer channels than `numInputChannels`, only those buses are populated; the rest stay zero.
- If the file ends before `duration`, the remaining blocks receive silence — no crash.
- `inputStartOffset` skips that many seconds into the file before rendering begins. Negative values are clamped to 0.
- `ExtAudioFile` handles sample-rate conversion automatically if the file's sample rate differs from the engine's.
- Set `inputURL: nil` (the default) to restore the original behaviour — no file is opened.
---
## Approach 2 — `RecordBuffer` + `LyrebirdBuffer.write()`
Use this when you need to:
- Capture a specific signal path (not the final mix)
- Write AIFF or WAV instead of CAF
- Render with `CoreAudioDriver` while simultaneously saving to disk
### Step 1 — allocate a buffer
Size it to the number of frames you want to capture: `duration × sampleRate`.
```swift
let sampleRate = 44100.0
let duration = 4.0
let frameCount = Int(sampleRate * duration)
let captureBuf = LyrebirdBuffer(count: frameCount) // mono
let captureBuf = LyrebirdBuffer(count: frameCount, channelCount: 2) // stereo
```
### Step 2 — wire `RecordBuffer` into the signal graph
```swift
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class RecordingSynth: SynthesizerBase {
let captureBuf: LyrebirdBuffer
init(captureBuf: LyrebirdBuffer) {
self.captureBuf = captureBuf
super.init()
}
override func build() {
let osc = OscSin.Audio(freq: 220.0)
let sig = osc * 0.4
// RecordBuffer.Audio writes sig to captureBuf and passes sig through as output.
let recorder = RecordBuffer.Audio(input: sig, buffer: captureBuf, loop: false)
output(bus: 0, source: Pan2(input: recorder))
}
}
```
`RecordBuffer.Audio` passes the input signal through unchanged — it records and plays back simultaneously. Set `loop: false` so it stops at the end of the buffer instead of looping.
For stereo capture, supply a two-channel `GeneratorArray` and a buffer with `channelCount: 2`:
```swift
let stereoSig = expand([oscL, oscR]) { $0 }
let recorder = RecordBuffer.Audio(input: stereoSig, buffer: captureBuf, loop: false)
```
### Step 3 — render, then write
With `NRTDriver`:
```swift
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: Int(sampleRate),
numOutputChannels: 2,
numInputChannels: 0,
driver: NRTDriver(outputURL: URL(fileURLWithPath: "capture.caf"), duration: duration)
)
let synth = RecordingSynth(captureBuf: captureBuf)
try engine.add(synth)
try engine.start() // renders and writes the NRT output file
// After start() returns, captureBuf is fully populated — write it separately.
let aiffURL = URL(fileURLWithPath: "output.aiff")
try captureBuf.write(to: aiffURL, format: .aiff, sampleRate: sampleRate)
```
With `CoreAudioDriver` (real-time, write after recording finishes):
```swift
// Wait until recording is done (check doneAction or use a fixed delay)
Thread.sleep(forTimeInterval: duration + 0.1)
engine.stop()
try captureBuf.write(to: URL(fileURLWithPath: "output.wav"), format: .wav, sampleRate: sampleRate)
```
---
## Output Formats
### `NRTDriver` output — CAF only
`NRTDriver` writes CAF (Core Audio Format) unconditionally. CAF supports any sample rate, up to 8 channels, and 32-bit float samples. It is readable by all macOS/iOS audio tools.
To convert to AIFF or WAV after rendering, use `afconvert` (bundled with macOS):
```sh
afconvert -f AIFF -d BEF32 output.caf output.aiff
afconvert -f WAVE -d LEF32 output.caf output.wav
```
### `LyrebirdBuffer.write()` — AIFF, WAV, or CAF
```swift
try buf.write(to: url, format: .caf, sampleRate: 44100) // default
try buf.write(to: url, format: .aiff, sampleRate: 44100) // AIFF-C, Float32
try buf.write(to: url, format: .wav, sampleRate: 44100) // WAV, Float32
```
| Format | Extension | Endian | Channels | Notes |
|---|---|---|---|---|
| `.caf` | `.caf` | little-endian | up to 8 | Best for macOS; default |
| `.aiff` | `.aiff` | big-endian | ≤ 2 recommended | Broad DAW compatibility |
| `.wav` | `.wav` | little-endian | up to 8 | Cross-platform standard |
All formats write 32-bit float samples (Float32). The `LyrebirdFloat` (Double) values in the buffer are converted to Float32 on the way out.
---
## Complete Example — NRT Bounce to AIFF
```swift
import Foundation
import LyrebirdSynth
// --- Example: your synthesizer, defined by subclassing SynthesizerBase ---
final class FMTone: SynthesizerBase {
override func build() {
let mod = OscSin.Audio(freq: 220.0) * 150.0
let osc = OscSin.Audio(freq: 440.0 + mod)
let env = EnvelopeGen.Audio(
envelope: Envelope(levels: [0, 1, 0.6, 0],
durations: [0.01, 0.3, 0.5],
curves: [0, 0, 0])
)
let sig = osc * env * 0.4
output(bus: 0, source: Pan2(input: sig))
}
}
// --- Render ---
let cafURL = URL(fileURLWithPath: "fm_tone.caf")
let aiffURL = URL(fileURLWithPath: "fm_tone.aiff")
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
numInputChannels: 0,
driver: NRTDriver(outputURL: cafURL, duration: 2.0)
)
try engine.add(FMTone())
do {
try engine.start()
print("Rendered: \(cafURL.path)")
} catch {
fputs("Render failed: \(error)\n", stderr)
exit(1)
}
// Optional: convert to AIFF via afconvert (shell out)
let task = Process()
task.executableURL = URL(fileURLWithPath: "/usr/bin/afconvert")
task.arguments = ["-f", "AIFF", "-d", "BEF32", cafURL.path, aiffURL.path]
try? task.run()
task.waitUntilExit()
if task.terminationStatus == 0 {
print("Exported: \(aiffURL.path)")
}
```
---
## NRT vs RT — Key Differences
| | `CoreAudioDriver` | `NRTDriver` |
|---|---|---|
| `start()` blocks | No — audio runs on background thread | Yes — blocks until render complete |
| `engine.add()` timing | Works anytime audio is running | Must be called **before** `start()` |
| Speed | Real-time (1× wall clock) | Faster than real-time |
| Audio hardware | Required | Not required |
| Output | DAC / speakers | File on disk |
| `RunLoop.main.run()` | Required to keep process alive | Not needed — `start()` returns |
| CI/batch use | Not suitable | Yes |
---
## Error Reference
| Error | Cause | Fix |
|---|---|---|
| `NRTDriverError.cannotCreateFile` | Bad URL, permissions, or full disk | Check the path and disk space |
| `NRTDriverError.writeFailed` | Disk I/O error during render | Check disk space and path permissions |
| `LyrebirdBufferIOError.cannotCreateOutputFile` | Same as above for `write()` | |
| Silent output / all-zeros file | Synthesizers added after `start()` | Move all `engine.add()` calls before `start()` |
| File truncated short | `duration` too short for the patch | Increase `NRTDriver` duration |
---
## Reference Docs
| Doc | Contents |
|---|---|
| [cli-guide.md](cli-guide.md) | CLI commands, project workflow |
| [project-system.md](project-system.md) | Scaffolding and generated file contents |
| [targets.md](targets.md) | `LyrebirdDemo` as a starting point for NRT programs |
+311
View File
@@ -0,0 +1,311 @@
# Project System
A Lyrebird "piece" is a Swift Package that declares Lyrebird as a dependency.
The `lyrebird` CLI handles scaffolding, building, and exporting.
## Scaffold a New Project
```sh
lyrebird new MyPiece [--template <template>]
```
Creates:
```
MyPiece/
├── Package.swift
├── MyPiece.xcworkspace/
│ └── contents.xcworkspacedata (references Package.swift — open in Xcode)
├── Sources/
│ └── MyPiece/
│ └── main.swift (+ AppDelegate.swift, MyPieceSynth.swift for ui-demo)
└── Tests/
└── MyPieceTests/
└── MyPieceTests.swift
```
Open `MyPiece.xcworkspace` in Xcode for full project navigation, debugging, and SwiftUI previews — the workspace points at `Package.swift`, so SPM-resolved deps and targets show up as a normal project. Or run from the terminal with `lyrebird run`.
**Name rules** — the project name must be a valid Swift module identifier:
- ASCII letters, digits, and underscores only (`[A-Za-z0-9_]`)
- Must not start with a digit
- No spaces, hyphens, dots, or Unicode letters (Cyrillic, CJK, etc. are rejected
because SPM module names must be ASCII-safe on all toolchains)
### Templates
Swift-Package-only templates (lightweight; open `Package.swift` in Xcode for SwiftUI previews):
| Template | Command | Description |
|---|---|---|
| `basic` (default) | `lyrebird new MyPiece` | Minimal engine + `RunLoop.main.run()` |
| `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 |
Xcode-project templates (ship a real `.xcodeproj` for deliverables SwiftPM can't express — `.app` bundles, AUv3 extensions):
| Template | Command | Description |
|---|---|---|
| `macos-ui-xcode` | `lyrebird new MyApp --template macos-ui-xcode` | macOS `.app` (AppKit + SwiftUI), `@UIParam` synth, hardened runtime |
| `ios-ui` | `lyrebird new MyApp --template ios-ui` | iOS `.app` (SwiftUI + `iOSAudioDriver`), `AVAudioSession` activation, iPhone + iPad device family |
| `auv3` | `lyrebird new MyPlugin --template auv3` | AUv3 host `.app` + `aumu` `.appex` subclassing `LyrebirdAudioUnit`. Entitlements for both. Subtype + manufacturer pre-filled (manufacturer = `LYRB` placeholder — rewrite for distribution) |
Each Xcode-project template lays out:
```
<name>/
├── <name>.xcodeproj/
│ ├── project.pbxproj
│ └── xcshareddata/xcschemes/<name>.xcscheme
├── <name>.xcworkspace/
│ └── contents.xcworkspacedata (references <name>.xcodeproj)
├── <name>/ (app target sources + Info.plist [+ entitlements for auv3])
│ └── ...
└── <name>Extension/ (auv3 only — extension target + Info.plist + .entitlements)
└── ...
```
Lyrebird is pulled in via a remote SPM dependency on `https://realizedsound.mooo.com/josh/Lyrebird` (configurable via `ProjectScaffolder.lyrebirdPackageURL`). The scaffolded project lives anywhere on disk and does not need a local checkout.
### Microphone input — not pre-wired in any template
No template adds `NSMicrophoneUsageDescription` to the generated `Info.plist`, no template adds the hardened-runtime / sandbox audio-input capability, and the `ios-ui` template's `AVAudioSession` category is `.playback` (output only). Most pieces don't read live input, so the templates default to "no mic capability" rather than triggering a permission prompt on every first run.
If a piece needs live input (e.g. tapping the engine input bus into `ScopeCapture` or routing `In.Audio(bus: numOutputChannels)` through the graph), the project owner must add these themselves:
**Engine init** — set `numInputChannels > 0` and pass a non-nil `inputDeviceID` (macOS) when constructing `SynthesisEngine` / starting the driver.
**macOS** (`macos-ui-xcode`, `ui-demo` opened in Xcode, any AppKit/SwiftUI app):
- Add `NSMicrophoneUsageDescription` (string explaining the use) to the target's `Info.plist`. Required since macOS 10.14 — without it the OS silently denies input access and `CoreAudioDriver` reads zeros.
- If the app is sandboxed: add `com.apple.security.device.audio-input` to the `.entitlements` file. The `macos-ui-xcode` template ships unsandboxed; the `auv3` host app is sandboxed and will need the entitlement before the host can read mic in addition to hosting the plugin.
**iOS** (`ios-ui`):
- Add `NSMicrophoneUsageDescription` to the app `Info.plist`.
- Change the `AVAudioSession` category in the generated `AppDelegate` / `App` activation block from `.playback` to `.playAndRecord` (typically `mode: .default` or `.measurement`, options `[.defaultToSpeaker, .allowBluetooth]` depending on routing needs). `.playback` is output-only and will return zero-filled input buffers regardless of the engine's `numInputChannels`.
The first `start()` call after these are in place triggers the system permission prompt. Until the user grants, input frames remain zero — a scope tap on input buses will draw a flat line.
### `--lyrebird-path` — local checkout mode
While the Lyrebird repository is not yet publicly accessible, pass `--lyrebird-path <abs-path>` to point both `Package.swift` and (for Xcode templates) `<name>.xcodeproj` at a local Lyrebird checkout:
```sh
lyrebird new MyPiece --template macos-ui-xcode \
--lyrebird-path /Users/me/Documents/LyrebirdII
```
The generated `Package.swift` uses `.package(name: "Lyrebird", path: ...)` instead of `.package(url:from:)`; the `.xcodeproj` uses `XCLocalSwiftPackageReference` instead of `XCRemoteSwiftPackageReference`. The path must be absolute (relative paths are resolved against the current working directory).
Switch back to the remote URL by editing the `.package(...)` line in `Package.swift` and the `relativePath`/`repositoryURL` entry in `<name>.xcodeproj/project.pbxproj` once the public repo is available.
### Generated `Package.swift`
```swift
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "MyPiece",
platforms: [.macOS(.v15)],
dependencies: [
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.0.0"),
],
targets: [
.executableTarget(
name: "MyPiece",
dependencies: ["Lyrebird"]
),
.testTarget(
name: "MyPieceTests",
dependencies: ["MyPiece"]
),
]
)
```
The URL points to the Lyrebird repository on Bitbucket. Run `swift package resolve` to fetch it.
### Generated `Sources/MyPiece/main.swift`
```swift
// MyPiece — entry point
import Foundation
import LyrebirdSynth
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 2,
driver: CoreAudioDriver()
)
// Add your Synthesizers here.
// engine.add(MySynth())
do {
try engine.start()
} catch {
fatalError("Engine failed to start: \(error)")
}
print("MyPiece running — press Ctrl+C to stop")
RunLoop.main.run()
```
### Generated `Tests/MyPieceTests/MyPieceTests.swift`
```swift
import Testing
import LyrebirdSynth
@Suite("MyPiece")
struct MyPieceTests {
@Test func engineStartsClean() throws {
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 2,
driver: OfflineDriver()
)
try engine.start()
engine.processBlock(inputSamples: [])
engine.stop()
#expect(engine.audioBuses[0].allSatisfy { $0 == 0.0 })
}
}
```
## File Convention
- **`main.swift`** — configure engine, build node tree, call `engine.start()`
- **One Synthesizer per file** — `ReverbSynth.swift`, `BassDrum.swift`, etc.
- All files in the same target share a module namespace — no imports needed between them
## Run a Project
```sh
lyrebird run # debug build — wraps: swift run
lyrebird run --release # release build — wraps: swift run -c release
```
The `swift` binary is located by checking, in order:
1. `/usr/bin/swift` — Xcode Command Line Tools / Xcode toolchain
2. `/usr/local/bin/swift` — standalone toolchain (Intel Mac)
3. `/opt/homebrew/bin/swift` — Homebrew toolchain (Apple Silicon)
`lyrebird run` exits with the same exit code as `swift run`, so CI scripts can
detect build/runtime failures normally.
## Export a Synthesizer Template
```sh
lyrebird export Tone
lyrebird export Tone --to ./Sources/MyPiece/Tone.swift
lyrebird export Tone --to ./Sources/MyPiece/Tone.swift --overwrite
```
Writes a starter `SynthesizerBase` subclass to the given path (default:
`<Name>.swift` in the current directory). The generated file is ready to drop
into any Lyrebird project's `Sources/` directory and fill in with signal graph
code.
**Flags:**
- `--to <path>` — destination file path; defaults to `<Name>.swift` in CWD
- `--overwrite` — replace an existing file; without this flag the command fails
if the destination already exists
**Name rules** — same ASCII identifier rules as `lyrebird new`.
### Generated template
```swift
import LyrebirdSynth
// MARK: - Tone
/// A Lyrebird synthesizer — generated by `lyrebird export Tone` (your subclass).
final class Tone: SynthesizerBase {
// MARK: - Parameters
// Declare parameters here. Example:
// let freq: LyrebirdFloat = 440.0
// MARK: - Build
override func build() {
// Wire your signal graph here. Example:
// let osc = OscSin.Audio(freq: freq)
// addOutputGenerator(osc * env)
}
}
```
## Interactive Shell
All three commands are also available in the `lyrebird>` interactive shell:
```
lyrebird> new MyPiece
Created MyPiece/
lyrebird> run
Build complete!
...
lyrebird> export Tone --to ./Sources/Tone.swift
Exported /Users/josh/MyPiece/Sources/Tone.swift
```
Shell verbs are case-insensitive (`NEW`, `Run`, `EXPORT` all work); argument
values such as project names preserve the user's original casing.
## Sharing Synthesizers
A reusable effect or instrument library is just a Swift package:
```swift
// In Package.swift
.package(url: "https://github.com/artist/LyrebirdReverb", from: "1.0.0")
```
## Testing
```swift
// Tests/MyPieceTests/ReverbTests.swift
import Testing
import MyPiece
@Test func reverbOutputIsNotSilent() throws {
let engine = SynthesisEngine(
blockSize: 512, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 2,
driver: OfflineDriver()
)
try engine.start()
let reverb = ReverbSynth()
try engine.add(reverb)
engine.processBlock(inputSamples: [])
#expect(engine.audioBuses[0].contains { $0 != 0.0 })
engine.stop()
}
```
Run with `swift test`. No Xcode Playgrounds.
## Implementation
| Type | File | Purpose |
|---|---|---|
| `ProjectScaffolder` | `LyrebirdCLI/ProjectScaffolder.swift` | Creates directory tree and writes template files |
| `ProjectRunner` | `LyrebirdCLI/ProjectRunner.swift` | Locates `swift` binary, execs `swift run [--release]` |
| `SynthExporter` | `LyrebirdCLI/SynthExporter.swift` | Writes `SynthesizerBase` subclass template |
| `validateSwiftIdentifier` | `LyrebirdCLI/NameValidation.swift` | Shared ASCII identifier validation used by both scaffolder and exporter |
`ProjectScaffolder.scaffold(name:in:)` cleans up the partial directory tree on
any mid-scaffold failure, so a failed `lyrebird new` never leaves a broken
directory that blocks a retry with `.projectExists`.
+159
View File
@@ -0,0 +1,159 @@
# REPL & Live Coding
## Launch
```sh
lyrebird repl
```
Prints a banner, runs `swift build` in the current directory, then launches `swift repl`
with `-I` / `-L` / `-l` flags pointing at the package's `.build/debug` artifacts. `import
Lyrebird` works immediately in the REPL session.
The raw command that `lyrebird repl` runs (useful for debugging or scripting):
```sh
swift build
swift repl \
-I .build/debug/Modules \
-I .build/debug/LyrebirdC.build \
-L .build/debug \
-lLyrebird
```
Run from the Lyrebird package directory itself, or from any project whose `Package.swift`
declares Lyrebird as a dependency — SPM resolves transitive deps during `swift build`
and stages them under the same `.build/debug` layout.
```sh
lyrebird # enter the lyrebird> interactive shell (LineNoise-powered)
lyrebird --help # usage help
lyrebird --version
```
## Interactive Shell (`lyrebird>`)
Running `lyrebird` with no arguments enters a LineNoise-powered command shell:
```
Lyrebird 0.1.0 — Swift audio synthesis
Type 'help' for available commands, or 'repl' to start a Swift REPL session.
Commands:
new <name> Scaffold a new Lyrebird Swift Package
run [--release] Build and run the current project
export <name> [--to p] Export a Synthesizer template to a .swift file
repl Launch Swift REPL with Lyrebird available
version Print lyrebird version
help Show this help
quit Exit (also Ctrl+D)
lyrebird> repl
```
Features:
- Arrow-key line editing (linenoise C library, pure Swift wrapper)
- Tab completion for all subcommands
- Persistent command history — saved to `~/.lyrebird_history` on exit
- Shell verbs are case-insensitive (`NEW`, `Run`, `EXPORT` all work);
argument values such as project/synth names preserve the user's original casing
## Basic REPL Session
Once inside the Swift REPL:
```swift
import LyrebirdSynth
// Create and start the engine
let engine = SynthesisEngine(
blockSize: 512, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 2,
driver: CoreAudioDriver()
)
try engine.start()
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class SineTone: SynthesizerBase {
@LiveParam var freq: LyrebirdFloat = 440.0
@LiveParam var amp: LyrebirdFloat = 0.3
override func build() {
let osc = OscSin.Audio(freq: $freq)
output(bus: 0, source: osc * $amp)
}
}
// Add to engine — audio starts immediately
let tone = SineTone()
try engine.add(tone)
// Adjust while running — no try, no string
tone.freq = 880.0
// Remove
engine.remove(tone)
```
## Threading While Audio Runs
- REPL input and graph mutation: **main thread** (the `swift repl` process)
- Audio render callback: **RT thread** (Core Audio)
- `@LiveParam` assignments → `Atomic<UInt64>` store → RT acquiring load, per-sample ramp
- `engine.add` / `engine.remove` → `SPSCQueue` → applied at next block boundary
Audio never stops during node add/remove — the lock-free scheduling mechanism handles it.
## History
Command history for the `lyrebird>` interactive shell is persisted to `~/.lyrebird_history`
and shared across all shell sessions. The path is exposed as
`REPLLauncher.historyFilePath` and mirrored by `InteractiveShell.historyFilePath`.
## Implementation Notes
### `lyrebird repl` — `swift build` + `swift repl` with flags
Older versions of SPM shipped a `swift package repl` subcommand that resolved the whole
dependency graph and dropped you into an `import`-ready REPL with no flags. That
subcommand has been removed from the current Swift toolchain — running it now errors with
`error: Unknown subcommand or plugin name 'repl'`.
`REPLLauncher` replaces it with the canonical two-step invocation:
1. `swift build` — produces `.build/debug/Modules/LyrebirdSynth.swiftmodule`,
`.build/debug/libLyrebird.dylib`, and `.build/debug/LyrebirdC.build/module.modulemap`.
If the build fails, the REPL is not started and the user sees the compiler output
directly (stdout/stderr are inherited).
2. `swift repl -I .build/debug/Modules -I .build/debug/LyrebirdC.build -L .build/debug
-lLyrebird` — the same flags SPM used to compute internally. `-I` points the Swift
driver at the staged `.swiftmodule` and the LyrebirdC C-module modulemap; `-L` /
`-lLyrebird` links the dynamic library so `import LyrebirdSynth` succeeds and runtime
symbols resolve through the dylib's `@rpath` install name.
Run from the Lyrebird package directory itself, or from any project directory whose
`Package.swift` declares Lyrebird as a dependency — both produce the same `.build/debug`
layout after `swift build`.
### LineNoise
`LyrebirdCLI` depends on `andybest/linenoise-swift` (LineNoise 0.0.3). The interactive
shell (`InteractiveShell.run()`) owns the LineNoise instance and manages:
- History load/save (`~/.lyrebird_history`)
- Tab completion callback (prefix-matched subcommands)
The `swift repl` session that fires on `repl` has its own separate REPL history
managed by LLDB/Swift (typically in `~/.lldb/`).
### `CLICommand` parsing
`CLICommand.parse(_:)` is the canonical argument parser for the `lyrebird` binary.
`InteractiveShell.command(from:)` is its shell-line equivalent. Both apply the same
rules:
- Verb is lowercased before matching (case-insensitive commands)
- Positional name arguments are guarded against flag tokens (`hasPrefix("-")`)
- `--to` value is guarded against consuming a subsequent flag as a path
- `--overwrite` is parsed and threaded through to `SynthExporter.export`
See `docs/tooling/project-system.md` for the full `lyrebird new / run / export`
reference.
+319
View File
@@ -0,0 +1,319 @@
# LyrebirdRoutine, LyrebirdTask, and Pattern
Algorithmic event scheduling on background threads. Non-RT — drives high-level events (add/remove synths, change `@LiveParam` values) from sequential code with timed waits.
---
## Pattern\<T\>
Demand-rate value sequence. Not thread-safe; use within a single Routine/Task.
```swift
let freqs = Pattern.sequence([440.0, 550.0, 880.0], repeats: 2)
while let f = freqs.next() { ... } // iterates twice, then next() returns nil
freqs.reset() // restart from beginning
```
| Property/Method | Description |
|---|---|
| `next() -> T?` | Return current value and advance. `nil` when exhausted or values is empty. |
| `reset()` | Restart from first value; clear cycle count. |
| `isExhausted` | `true` after `repeats` full cycles. Always `false` when `repeats == -1`. |
`repeats: -1` (default) = infinite loop.
### Pattern Factory Reference
All variants below are constructed by static factory methods on `Pattern<T>`. Every variant returns a `Pattern<T>` (or `Pattern<[T]>` for `tuple`) backed by a module-internal engine. `next()` / `reset()` / `isExhausted` behave uniformly. Numeric factories require `T == Double` and live on `extension Pattern where T == Double`; the rest are generic.
**Atomic value sources — generic `T`**
| Factory | Behaviour |
|---|---|
| `Pattern.sequence(_:repeats:)` | Cycle through array `repeats` times. `-1` infinite. |
| `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`) |
| `Pattern.closure(_:)` | Wrap `() -> T?`. Latches once nil is returned. Reset clears latch but cannot reset closure-internal state. (SC `Pfunc`) |
**Atomic value sources — numeric `Pattern<Double>`**
| Factory | Behaviour |
|---|---|
| `Pattern.series(start:step:length:)` | Arithmetic series. `length == -1` infinite. (SC `Pseries`) |
| `Pattern.geometric(start:ratio:length:)` | Geometric series. (SC `Pgeom`) |
| `Pattern.uniformRandom(low:high:length:seed:)` | Uniform random in `[low, high]`. (SC `Pwhite`) |
| `Pattern.brownian(low:high:step:start:length:seed:)` | Clamped random walk. `start` defaults to midpoint. (SC `Pbrown`) |
| `Pattern.gaussian(mean:stdDev:length:seed:)` | Gaussian (Box-Muller). (SC `Pgauss`) |
| `Pattern.cauchy(location:scale:length:seed:)` | Cauchy (inverse-CDF). (SC `Pcauchy`) |
| `Pattern.beta(alpha:beta:length:seed:)` | Beta(α, β) in `[0, 1]` (two-Gamma). (SC `Pbeta`) |
**Length / range modifiers — generic `T`, wrap any `Pattern<T>`**
| Factory | Behaviour |
|---|---|
| `Pattern.repeating(_:count:)` | Replay upstream `count` times with `reset()` between cycles. `-1` infinite. (SC `Pn`) |
| `Pattern.limit(_:count:)` | Emit at most `count` items returned. `count >= 0` precondition. (SC `Pfin`) |
| `Pattern.drop(_:count:)` | Skip first `count` upstream values lazily. `count >= 0` precondition. (SC `Pdrop`) |
| `Pattern.stutter(_:count:)` | For each upstream value, emit n times where n is the next value from a `Pattern<Int>`. (SC `Pstutter`) |
**Multi-pattern composition — generic `T`**
| Factory | Behaviour |
|---|---|
| `Pattern.switching(_:index:)` | One value per index draw; out-of-range index latches. (SC `Pswitch1`) |
| `Pattern.concatenate(_:)` | Sequential play; advance when active sub-pattern returns nil. |
| `Pattern.roundRobin(_:)` | One value per pattern in rotation; dead slots skipped. (SC `Ppatlace`) |
| `Pattern.tuple(_:)` | Returns `Pattern<[T]>`. Zips children into size-stable arrays. Latches on any child nil. |
| `Pattern.interleave(_:repeats:)` | SC `Place`. Each outer cycle emits one value per sub-list; shorter sub-lists wrap modulo own length. Empty sub-lists silently dropped. `repeats == -1` infinite. |
**Map / filter / reject — generic `T`**
| Factory | Behaviour |
|---|---|
| `Pattern.map(_:_:)` | Wraps `Pattern<U>` with `(U) -> T` transform. Result element type can differ. (SC `Pcollect`) |
| `Pattern.filter(_:where:)` | Keep upstream values where predicate is true. Spin caveat for never-matching infinite source. (SC `Pselect`) |
| `Pattern.reject(_:where:)` | Inverse of `filter`. Routes the same engine with a negated predicate. (SC `Preject`) |
**Numeric transforms — `Pattern<Double>`**
| Factory | Behaviour |
|---|---|
| `Pattern.accumulate(_:initial:)` | Running sum from `initial`. (SC `Paccum`) |
| `Pattern.difference(_:)` | First value verbatim, subsequent = `x[n] - x[n-1]`. (SC `Pdiff`) |
| `Pattern.wrap(_:low:high:)` | Wrap into half-open `[low, high)` via floor-modulo with FP-boundary post-clamp. Precondition `high > low`. (SC `Pwrap`) |
| `Pattern.clip(_:low:high:)` | Clamp to `[low, high]`. Precondition `high >= low`. (SC `Pclip`) |
| `Pattern.round(_:step:)` | Round to nearest multiple of `step`, ties away from zero. Precondition `step > 0`. (SC `Pround`) |
| `Pattern.smooth(_:coefficient:)` | One-pole exponential smoother `y[n] = c·y[n-1] + (1-c)·x[n]`. Coefficient clamped to `[0, 1]`. First sample passes through. (SC `Psmooth`) |
**Composition example**
```swift
// Repeat (cycle through a switch of two sub-patterns picked by an index pattern) 4 times.
let composite: Pattern<Double> = Pattern.repeating(
Pattern.switching(
[Pattern.series(start: 0, step: 1, length: 4),
Pattern.uniformRandom(low: 0, high: 1, length: 4)],
index: Pattern.sequence([0, 1, 0, 1])
),
count: 4
)
```
The same factories on the demand side are implemented as separate `DemandGenerator` types (`DemandSeries`, `DemandShuffle`, `DemandSwitch`, etc.) wrapping the matching Pattern engines — see `docs/stdlib/generators.md` § Demand-rate.
---
## LyrebirdRoutine
Runs a closure **once** on a dedicated background thread (`Thread`, `.userInitiated` QoS).
```swift
let routine = LyrebirdRoutine { ctx in
let freqs = Pattern.sequence([440.0, 550.0, 660.0])
while let freq = freqs.next() {
let tone = SineTone(); tone.freq = freq
ctx.add(tone)
try ctx.wait(seconds: 0.5)
ctx.remove(tone)
try ctx.wait(seconds: 0.1)
}
}
routine.start(engine: engine)
// ... later:
routine.stop()
```
### States
```
idle → (start) → running → (body returns / stop) → stopped
stopped → (reset) → idle
```
### API
| Method | Description |
|---|---|
| `start(engine:)` | Launch background thread. No-op if not `.idle`. |
| `stop()` | Signal stop. Next `ctx.wait()` throws `LyrebirdRoutineError.stopped`. |
| `reset()` | Signal stop and block until thread finishes. Resets to `.idle` for restart. |
---
## LyrebirdTask
Like `LyrebirdRoutine` with `pause()` / `resume()`. Identical body signature.
```swift
let task = LyrebirdTask { ctx in
while true {
ctx.add(nextEvent())
try ctx.wait(seconds: 0.25)
}
}
task.start(engine: engine)
task.pause() // freeze; thread sleeps inside ctx.wait()
task.resume() // continue from where it left off
task.stop()
```
### States
```
idle → running → paused → running → stopped
```
| Method | Description |
|---|---|
| `pause()` | Suspend inside next `ctx.wait()`. Sets state `.paused`. |
| `resume()` | Broadcast on internal condition; resumes `ctx.wait()`. Sets state `.running`. |
| `stop()` / `reset()` | Same as `LyrebirdRoutine`. |
---
## LyrebirdRoutineContext
Passed to the body closure. Provides:
### Timed waits
```swift
try ctx.wait(seconds: 0.5) // sleep ~0.5s; polls stop/pause every 10ms
try ctx.waitUntil(sampleTime: t) // block until engine.currentTime >= t
```
Both throw `LyrebirdRoutineError.stopped` when `stop()` is called. Let the error propagate or catch and rethrow to unwind cleanly.
### Engine calls
All dispatched to the main thread via `DispatchQueue.main.async` to preserve the `pendingQueue` single-producer invariant.
```swift
ctx.add(synth)
ctx.schedule(synth, at: sampleTime)
ctx.schedule(synth, after: 2.0) // seconds
ctx.remove(synth)
ctx.remove(synth, at: sampleTime)
```
---
## Error handling
```swift
let routine = LyrebirdRoutine { ctx in
do {
while true {
try ctx.wait(seconds: 0.25)
// ... produce events ...
}
} catch LyrebirdRoutineError.stopped {
// cleanup if needed
}
// body returns → state = .stopped
}
```
Uncaught `LyrebirdRoutineError.stopped` is silently swallowed by the Routine/Task harness — it always signals a clean stop, not a crash.
---
## Thread model
- One `Thread` per Routine/Task. Thread is created on `start()`, destroyed when body returns.
- `stop()` is non-blocking. `reset()` blocks the calling thread until the body exits.
- Do not call `reset()` from inside the body closure.
- Multiple routines run concurrently and independently.
---
## LyrebirdClock
Named shared clock that multiple routines and tasks can align to without per-routine drift.
### The drift problem
Two routines calling `ctx.wait(beats: 1)` in independent loops accumulate OS scheduler jitter independently and drift apart within seconds. `ctx.waitUntil(sampleTime:)` on a shared sample-time grid never drifts.
```swift
// WRONG — drifts
let a = LyrebirdRoutine { ctx in
while true { ctx.add(Kick()); try ctx.wait(beats: 1) }
}
let b = LyrebirdRoutine { ctx in
while true { ctx.add(Bass()); try ctx.wait(beats: 1) }
}
// RIGHT — locked to same grid
let clock = LyrebirdClock(engine: engine, bpm: 120.0)
let a = LyrebirdRoutine { ctx in
while true {
try ctx.waitUntil(sampleTime: clock.nextBeat())
ctx.add(Kick())
}
}
let b = LyrebirdRoutine { ctx in
while true {
try ctx.waitUntil(sampleTime: clock.nextBeat())
ctx.add(Bass())
}
}
```
### API
```swift
let clock = LyrebirdClock(engine: engine, bpm: 120.0)
```
| Property / Method | Type | Description |
|---|---|---|
| `epoch` | `SampleTime` | Engine sample time at clock creation. |
| `bpm` | `Double` (get/set) | Tempo. Setter accumulates beats elapsed before the change — beat count is continuous. |
| `currentBeat` | `Double` | Beats elapsed since `epoch`, accumulated across tempo changes. |
| `sampleTime(beat:)` | `SampleTime` | Convert beat number → sample time. May return a past sample time. |
| `nextBeat(after:)` | `SampleTime` | Sample time of the next whole beat after `beat` (or `currentBeat` if nil). Exclusive: `nextBeat(after: 4.0)` returns beat 5. |
### Tempo changes
```swift
// Beat count is continuous across bpm changes
clock.bpm = 90.0 // _beatOffset accumulates beats since last change
```
`sampleTime(beat:)` is only accurate within the current tempo segment — beats since the last `bpm` change. Past-segment queries return mathematically extrapolated values, not a reconstruction of the prior tempo.
### Multi-voice example
```swift
let clock = LyrebirdClock(engine: engine, bpm: 120.0)
// Kick on every beat
let kick = LyrebirdRoutine { ctx in
while true {
try ctx.waitUntil(sampleTime: clock.nextBeat())
ctx.add(KickDrum())
}
}
// Bass on every other beat (offset by 0.5)
let bass = LyrebirdRoutine { ctx in
while true {
try ctx.waitUntil(sampleTime: clock.sampleTime(beat: floor(clock.currentBeat) + 1.5))
ctx.add(BassSynth())
}
}
kick.start(engine: engine)
bass.start(engine: engine)
```
### Thread safety
`LyrebirdClock` is `Sendable`. Multiple routines may call `currentBeat`, `sampleTime(beat:)`, and `nextBeat(after:)` concurrently. Only one thread should write `bpm`.
### Following an external MIDI clock
To drive `LyrebirdClock` from incoming MIDI Clock (0xF8) messages, use
`MIDIClockFollower`. See `docs/tooling/midi-clock-sync.md` for the full wiring guide.
+132
View File
@@ -0,0 +1,132 @@
# Package Targets
Lyrebird is structured as a multi-target Swift package. This document describes each target, its role, and when to use it.
---
## Core Targets
### `LyrebirdC`
Thin C shim. Exposes `fesetenv(FE_DFL_DISABLE_DENORMS_ENV)` to Swift — a C-only macro sentinel that Swift cannot reference directly. Linked into `Lyrebird` automatically; you never import this directly.
### `Lyrebird`
The core framework. Import this in any synthesis code.
```swift
import LyrebirdSynth
```
Provides: `SynthesisEngine`, `Generator`/`Synthesizer` protocols, all built-in generators, `LyrebirdBuffer`, `ParameterNode`, bus system, scheduling, and `CoreAudioDriver`. Links `CoreAudio`, `AudioToolbox`, and `Accelerate`.
Built as a `.dynamic` library — required by the Xcode 26 SPM regression (see `Package.swift` note). Reverts to `.static` when that regression is fixed.
### `LyrebirdUI`
Optional GUI module. Import alongside `Lyrebird` when you need parameter controls.
```swift
import LyrebirdUI
```
Provides: `LyrebirdWindow` (AppKit/SwiftUI host), `@SynthParam` property wrapper, and pre-built slider/knob views. Uses Swift 5 language mode to avoid actor-isolation diagnostics in SwiftUI/AppKit interop.
**Rule:** never import `LyrebirdUI` in `Lyrebird` — GUI code must stay in this module only.
---
## Executable Targets
### `LyrebirdCLI` — `lyrebird` command
Project scaffolding, running, and export from the command line.
```
lyrebird new MyProject # scaffold a new project
lyrebird run # compile and run
lyrebird export MySynth # generate a SynthesizerBase template
lyrebird repl # start Swift REPL with Lyrebird importable
```
Provides an interactive `lyrebird>` shell (via LineNoise) with history and tab completion. Uses Swift 5 language mode — LineNoise predates Swift 6 concurrency annotations.
See [cli-guide.md](cli-guide.md) for a full walkthrough.
### `LyrebirdDemo` — headless audio starting point
Command-line synthesis without a GUI. Best starting point for a new synthesis program.
```
swift run LyrebirdDemo
```
Demonstrates: `SynthesizerBase`, `@LiveParam`, `OscSin`, `DelayLine`, `engine.add`/`remove`, and RT-safe parameter updates from the main thread. Runs real-time audio via `CoreAudioDriver`, plays for a few seconds, then stops.
**Copy this target** when you want a headless synthesis starting point. Swap `CoreAudioDriver()` for `NRTDriver(outputURL:duration:)` to render offline to a file — see [nrt-guide.md](nrt-guide.md).
### `LyrebirdUIDemo` — GUI starting point
AppKit application with SwiftUI parameter controls. Best starting point for a windowed synthesis app.
```
swift run LyrebirdUIDemo
```
Demonstrates: `LyrebirdWindow`, `@SynthParam`-bound slider views, `AppDelegate` lifecycle (start/stop engine), and `NoteController` pattern for driving a `Synthesizer` from UI state.
**Copy this target** when you want a windowed synthesis app.
### `LyrebirdBenchmark`
Micro-benchmarks for DSP hot paths. Not a user starting point — run when profiling filter, vDSP, or block-processing performance.
```
swift run -c release LyrebirdBenchmark
```
Reports ns/block and ns/sample for scalar vs. vDSP biquad implementations at `blockSize = 512`. Always run with `-c release`; debug builds give meaningless numbers.
---
## Test Targets
| Target | What it covers |
|---|---|
| `LyrebirdTests` | Core engine: generators, bus system, scheduling, file I/O, all built-in DSP |
| `LyrebirdUITests` | `LyrebirdUI` module: parameter binding, `@SynthParam`, window lifecycle |
| `LyrebirdCLITests` | `LyrebirdCLI`: scaffolder, runner, exporter, REPL commands |
Run all tests:
```
swift test
```
---
## Dependency Map
```
LyrebirdC
└── Lyrebird (links CoreAudio, AudioToolbox, Accelerate)
├── LyrebirdUI (SwiftUI + AppKit, Swift 5 mode)
├── LyrebirdDemo
├── LyrebirdBenchmark
└── LyrebirdUIDemo (also links LyrebirdUI)
LyrebirdCLI (links LineNoise, Swift 5 mode)
```
---
## Choosing a Starting Point
| Goal | Use |
|---|---|
| Headless audio synthesis | `LyrebirdDemo` |
| Windowed app with GUI controls | `LyrebirdUIDemo` |
| CLI tooling / REPL | `lyrebird` (`LyrebirdCLI`) |
| Measure DSP performance | `LyrebirdBenchmark` (release build) |
| Framework import only | `import LyrebirdSynth` |
| GUI parameter controls | `import LyrebirdUI` |
+275
View File
@@ -0,0 +1,275 @@
# REPL → Compile Workflow
This guide walks from a live-coding sketch in the Lyrebird REPL to a fully
compiled, testable Swift Package. Every step uses the `lyrebird` CLI so no
manual project setup is required.
## Overview
```
lyrebird repl → prototype a patch in Swift
lyrebird new → scaffold a compiled project
lyrebird export → generate a Synthesizer source file
(edit) → fill in the signal graph
lyrebird run → compile and run
swift test → verify with tests
```
Because Lyrebird has no separate scripting language, code written in the REPL
(`swift build` + `swift repl` with `-I`/`-L`/`-l` flags) is already real Swift. The same `OscSin`, `Out`, and
`SynthesizerBase` APIs that work in the REPL compile identically in a project.
---
## Step 1 — Prototype in the REPL
Launch the REPL from the Lyrebird package directory:
```sh
lyrebird repl
```
Write your synthesizer inline and iterate until it sounds right:
```swift
import LyrebirdSynth
let engine = SynthesisEngine(
blockSize: 512, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 2,
driver: CoreAudioDriver()
)
try engine.start()
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class KickDrum: SynthesizerBase {
@LiveParam var freq: LyrebirdFloat = 60.0
@LiveParam var decay: LyrebirdFloat = 0.3
override func build() {
let osc = OscSin.Audio(freq: $freq)
let env = EnvelopeGen.Audio(envelope: Envelope(
segmentCount: 2,
levels: [1.0, 1.0, 0.0],
durations: [0.005, $decay]
))
output(bus: 0, source: osc * env)
}
}
let kick = KickDrum()
try engine.add(kick)
// Tune parameters while audio runs — no try, no string.
kick.freq = 80.0
kick.decay = 0.2
```
There is no REPL "state capture" step — you keep the code you wrote and copy
it into the compiled project directly.
---
## Step 2 — Scaffold a Compiled Project
When you are happy with the sketch, scaffold a new Swift Package in a directory
of your choice:
```sh
lyrebird new MyPiece
```
This creates:
```
MyPiece/
├── Package.swift ← swift-tools-version 6.0, macOS 15
├── Sources/
│ └── MyPiece/
│ └── main.swift ← engine setup + entry point
└── Tests/
└── MyPieceTests/
└── MyPieceTests.swift ← starter test suite
```
---
## Step 3 — Export a Synthesizer Template
Generate a starter source file for your synthesizer:
```sh
lyrebird export KickDrum --to MyPiece/Sources/MyPiece/KickDrum.swift
```
The generated file is ready to compile — it only needs the signal graph filled
in with the code you wrote in the REPL:
```swift
import LyrebirdSynth
// MARK: - KickDrum
/// A Lyrebird synthesizer — generated by `lyrebird export KickDrum` (your subclass).
final class KickDrum: SynthesizerBase {
// MARK: - Parameters
@LiveParam var freq: LyrebirdFloat = 60.0
@LiveParam var decay: LyrebirdFloat = 0.3
// MARK: - Build
override func build() {
// Paste the signal graph from your REPL session here.
let osc = OscSin.Audio(freq: $freq)
let env = EnvelopeGen.Audio(envelope: Envelope(
segmentCount: 2,
levels: [1.0, 1.0, 0.0],
durations: [0.005, $decay]
))
output(bus: 0, source: osc * env)
}
}
```
You can export multiple synthesizers; each goes in its own file. All files
in the same target share a module namespace so no imports are needed between
them.
---
## Step 4 — Wire the Synthesizer in main.swift
Open `MyPiece/Sources/MyPiece/main.swift` and instantiate your synthesizer:
```swift
// MyPiece — entry point
import Foundation
import LyrebirdSynth
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 2,
driver: CoreAudioDriver()
)
let kick = KickDrum()
try engine.add(kick)
do {
try engine.start()
} catch {
fatalError("Engine failed to start: \(error)")
}
print("MyPiece running — press Ctrl+C to stop")
RunLoop.main.run()
```
---
## Step 5 — Resolve the Lyrebird Dependency
Open `MyPiece/Package.swift` and update the placeholder URL to the published
Lyrebird repository:
```swift
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.0.0"),
```
Resolve the dependency graph:
```sh
cd MyPiece
swift package resolve
```
---
## Step 6 — Run
```sh
lyrebird run # debug build
lyrebird run --release # release build (recommended for real-time audio)
```
`lyrebird run` exits with the same code as `swift run`, so CI pipelines can
detect failures normally.
---
## Step 7 — Test
The scaffolded `MyPieceTests.swift` provides a starter test. Add
synthesizer-specific tests alongside it:
```swift
// Tests/MyPieceTests/KickDrumTests.swift
import Testing
import LyrebirdSynth
import MyPiece
@Suite("KickDrum")
struct KickDrumTests {
@Test func outputIsNonSilentAfterOneBlock() throws {
let engine = SynthesisEngine(
blockSize: 512, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 2,
driver: OfflineDriver()
)
try engine.start()
let kick = KickDrum()
try engine.add(kick)
engine.processBlock(inputSamples: [])
#expect(engine.audioBuses[0].contains { $0 != 0.0 })
engine.stop()
}
}
```
Run all tests with:
```sh
swift test
```
---
## Why Code Compiles Identically
There is no translation step between REPL and compiled code.
- `lyrebird repl` runs `swift build`, then launches `swift repl` with module/library
flags pointing at `.build/debug`, so the Lyrebird package is importable. The
`import LyrebirdSynth` in the REPL and in
a compiled project resolve to the same module.
- `SynthesizerBase` is declared `open`, so it can be subclassed from any
module — both in tests that use `@testable import LyrebirdSynth` and in
standalone projects that import it as a dependency.
- `@LiveParam`, generators (`OscSin`, `Out`, etc.), and the engine API are all `public` — no special REPL-only API exists.
The only difference is that REPL code is interpreted and compiled code is
optimised. For a release build of a real-time audio piece, `lyrebird run
--release` enables full optimisations.
---
## Command Reference
| Command | Description |
|---|---|
| `lyrebird repl` | Launch Swift REPL with Lyrebird pre-loaded |
| `lyrebird new <name>` | Scaffold a new Swift Package |
| `lyrebird export <name>` | Export a `SynthesizerBase` template to `<name>.swift` |
| `lyrebird export <name> --to <path>` | Export to an explicit path |
| `lyrebird export <name> --to <path> --overwrite` | Overwrite an existing file |
| `lyrebird run` | Build and run the current project (debug) |
| `lyrebird run --release` | Build and run in release mode |
| `swift test` | Run the project's test suite |
See `docs/tooling/repl.md` for REPL details and `docs/tooling/project-system.md`
for the full CLI reference.
+260
View File
@@ -0,0 +1,260 @@
# Xcode File Templates
Lyrebird ships a small set of Xcode file templates (`.xctemplate` bundles) for the
common code shapes — Generators, Synthesizers, and Tasks. After install, they appear
in Xcode's New File dialog (`⌘N`) under a **Lyrebird** section.
---
## Install
Two paths — both copy the same templates to
`~/Library/Developer/Xcode/Templates/File Templates/Lyrebird/`. No Xcode
restart required; Xcode rescans on next `⌘N`.
### Via the `lyrebird` CLI (preferred)
```sh
lyrebird install-templates # error if already installed
lyrebird install-templates --force # overwrite existing install
lyrebird uninstall-templates
```
The CLI bundles every `.xctemplate` as an SPM resource on the `LyrebirdCLI`
target, so the binary needs no access to the repo at install time — copy
`lyrebird` to `/usr/local/bin` and `install-templates` keeps working from
any working directory.
Both verbs are also available inside the interactive `lyrebird>` shell.
### Via shell script (repo-checkout install)
From the repo root, equivalent to the CLI:
```sh
bash scripts/install-xcode-templates.sh
bash scripts/install-xcode-templates.sh --dry-run # preview only
bash scripts/uninstall-xcode-templates.sh
```
Re-running `install-xcode-templates.sh` is idempotent (`rsync --delete`).
Both source paths read from `Sources/LyrebirdCLI/Resources/XcodeTemplates/`,
which lives there so SPM can bundle them as a target resource.
---
## Templates shipped
### Tier 1 — usable from any project that depends on Lyrebird
| Template | Generates | Use when |
|---|---|---|
| **Lyrebird Generator** | `public enum <Name>` with `_Base`, `Audio`, `Control` + `GeneratorEnum` conformance | Implementing a new signal-producing or signal-processing Generator family. |
| **Lyrebird Synthesizer** | `final class <Name>: SynthesizerBase` with `@LiveParam` slots and a stubbed `build()` body | Defining a new synth (oscillator + envelope + output) that you add to an engine via `engine.add(_:)`. |
| **Lyrebird Task** | `func make<Name>() -> LyrebirdTask` factory plus a private example Synthesizer | Scheduling a stream of events from a background thread with pause/resume/stop support. |
These templates start with `import LyrebirdSynth` (or `@_spi(LyrebirdExtensions) import
LyrebirdSynth` for the Generator template, which references the SPI-marked `MulAddSpec`)
and use only public + SPI API. They compile cleanly in any project that has Lyrebird
as a Swift Package dependency.
### Tier 1b — in-tree contributor templates
| Template | Generates | Use when |
|---|---|---|
| **Lyrebird Oscillator** | `public enum <Name>` whose `_Base` extends `OscillatorBase`; inherits `_phase` / `_freqInput` / `_freqIsGenerator` / `_mulAdd` | Adding a new oscillator family inside the Lyrebird module. Drop the file under `Sources/Lyrebird/Generators/Oscillators/`. |
| **Lyrebird Noise Generator** | `public enum <Name>` whose `_Base` extends `NoiseBase`; inherits `rngState` + `_mulAdd`; xorshift64 PRNG seeded via `lyrebirdSeedXorshift64(from:mixConstant:)` | Adding a new noise / random-source family. Drop the file under `Sources/Lyrebird/Generators/Noise/`. |
| **Lyrebird Filter** | Audio-only `final class Audio: GeneratorBase` using `runRBJBiquadBlock` with a `computeCoefficients` closure carrying the Audio EQ Cookbook formula | Adding a new RBJ biquad filter shape. Drop the file under `Sources/Lyrebird/Generators/Filters/`. |
These templates extend module-internal base classes (`OscillatorBase`, `NoiseBase`)
or call module-internal helpers (`runRBJBiquadBlock`, `lyrebirdSeedXorshift64`,
`normalizeLFPhase`, `fillRampedResult`) and are **only useful inside the Lyrebird
module**. Each generated file carries an in-tree-only banner comment at the top.
External users adding their own oscillators / noise / filters should start from
the basic **Lyrebird Generator** template and declare the relevant state (phase
accumulator, PRNG state, biquad coefficients) inline.
### Tier 2 — extended Generator + Synthesizer shapes
| Template | Generates | Use when |
|---|---|---|
| **Lyrebird Demand Generator** | `final class <Name>: DemandGenerator` with `nextValue()` / `reset()` / `isExhausted` | Defining a pure value source consumed by `Demand.Audio` / `Demand.Control` pullers — one value per trigger edge. |
| **Lyrebird Multi-Channel Generator** | `final class <Name>: GeneratorBase, AudioGenerator` with fixed `outputChannelCount`, multi-row `_result`, channel-aware mul/add | Adding a Generator whose output has 2+ channels (panners, spatial decoders, multi-bus mixers). Modeled on Pan2. |
| **Lyrebird Synthesizer (UI)** | `final class <Name>: SynthesizerBase` with `@UIParam` slots and a stubbed `build()` body | Defining a synth whose parameters bind to SwiftUI controls (`ParameterKnob`, `ParameterSlider`, `ParameterXY`). Requires the LyrebirdUI module. |
| **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`. |
The UI templates (`Synthesizer (UI)` and `UI View`) add `import LyrebirdUI` and
compile cleanly in projects with both `Lyrebird` and `LyrebirdUI` as
dependencies. The test-suite and NRT templates only compile in their respective
target kinds (`Test`, `executableTarget`) and are reported as `SKIP` in the
in-tree / external validation passes by design.
### Tier 3 — extended subsystems (MIDI / OSC / Spectral / Buffer / Process / AUv3)
| Template | Generates | Use when |
|---|---|---|
| **Lyrebird Spectral Processor** | `final class <Name>: SpectralProcessor` with a `process(spectral:engine:)` body that walks every bin in `SpectralBuffer` | Adding a custom FFT-domain transform (filter, pitch shift, cross-synthesis, freeze). Wire into `SpectralChain.Audio` as a `.mono` stage. |
| **Lyrebird MIDI Handler** | `func make<Name>(engine:clientName:) throws -> MIDI` factory with `noteOn` / `noteOff` / `controlChange` dispatch + a `midiNoteToHz` helper | Wiring CoreMIDI input to engine-level state. Handler closure runs on `lyrebird.midi` queue (not RT). |
| **Lyrebird OSC Handler** | `func make<Name>(engine:port:) throws -> OSCServer` factory with starter `/freq` / `/amp` / `/note/{on,off}` handlers + a `doubleValue(_:)` argument-coercion helper | Wiring an OSC UDP server to engine state. Handlers run on `lyrebird.osc.handlers` queue. |
| **Lyrebird Buffer Reader** | `final class <Name>: SynthesizerBase` that loads a multichannel `LyrebirdBuffer` at init and plays it via `PlayBuffer.Audio` with `nativeRateScale` SR compensation | Building a sample-playback Synthesizer (loop / one-shot / rate-modulated). |
| **Lyrebird Process** | `struct <Name>: LyrebirdProcessFactory` whose `createProcess()` returns a `LyrebirdProcess` with a 4-point envelope (attack / sustain / release / silence), `releaseNode`, async body closure, and `onRelease` / `onFinished` callbacks | Building an envelope-governed audio process (Lyrebird's equivalent of SuperCollider's `ProcMod`). |
| **Lyrebird AUv3 Source-Slot Synth** | A `SynthesizerBase` + `LyrebirdAudioUnit` pair (Synth class + `<Name>AudioUnit` AU wrapper) with `parameterMetadata()` exposing `@LiveParam` slots to the host. Includes step-by-step Info.plist + `AUViewController` integration notes. | Wrapping a Synthesizer as an Audio Unit App Extension (.appex) for Logic / GarageBand / AUM / Loopy Pro. Pair with the `Demos/LyrebirdAUv3Demo` reference project. |
All six Tier 3 templates compile in projects depending on Lyrebird as a Swift
Package and are reported as `OK (external)` by the validator. None require
LyrebirdUI.
Each template prompts for a name in Xcode's dialog. The name becomes both the file
name and the top-level identifier inside the file.
---
## Generated shapes
### Lyrebird Generator
The Generator template emits the canonical pattern matched by every built-in
Generator family in `Sources/Lyrebird/Generators/`:
```swift
public enum MyGenerator {
public class _Base: GeneratorBase {
let inputSource: any ValidGeneratorInput
let _mulAdd: MulAddSpec
public init(
_ signal: any ValidGeneratorInput,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) { ... }
}
public final class Audio: _Base, AudioGenerator {
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count)
// sample-rate processing
}
}
public final class Control: _Base, ControlGenerator {
public var previousOutputValue: Double = 0.0
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count)
// block-rate scalar + linear ramp to previousOutputValue
}
}
}
extension MyGenerator: GeneratorEnum {
public typealias AudioType = MyGenerator.Audio
public typealias ControlType = MyGenerator.Control
}
```
Fill in `_transform(_:)` (one line) and you have a working Audio + Control pair
with `mul` / `add` wiring and the sub-block ramp pattern already in place.
If you only need one rate, delete the other class plus its line in the
`GeneratorEnum` extension.
See [`writing-generators.md`](../protocols/writing-generators.md) for the full
Generator protocol contract, shared helpers, and decision rules.
### Lyrebird Synthesizer
```swift
public final class MySynth: SynthesizerBase {
@LiveParam public var frequency: Double = 440.0
@LiveParam public var amplitude: Double = 0.25
public override func build() {
let osc = OscSin.Audio(freq: $frequency)
output(bus: 0, source: osc * $amplitude)
}
}
```
Use `$paramName` (the projected value of `@LiveParam`) to pass a live-mutable
parameter as a generator input. Direct mutation (`synth.frequency = 880.0`) is
atomic and RT-safe.
See [`synthesizer.md`](../protocols/synthesizer.md) for the full Synthesizer
protocol and lifecycle.
### Lyrebird Task
```swift
public func makeMyTask() -> LyrebirdTask {
LyrebirdTask { ctx in
while true {
let note = ExampleNote()
ctx.add(note)
try ctx.wait(seconds: 0.25)
}
}
}
```
Call `task.start(engine:)` to begin, `task.pause()` / `task.resume()` to control,
`task.stop()` to exit cleanly (raises `LyrebirdRoutineError.stopped` inside the
next `wait`, which the closure handles internally).
See [`routine-task.md`](routine-task.md) for the full scheduling model.
---
## Validating templates
Templates are validated by `scripts/validate-xcode-templates.sh`. Three modes:
```sh
bash scripts/validate-xcode-templates.sh # --quick (default)
bash scripts/validate-xcode-templates.sh --full # + in-tree compile against Lyrebird
bash scripts/validate-xcode-templates.sh --external # + compile as an external SPM package
```
`--quick` runs `plutil -lint` on each `TemplateInfo.plist` and parses the
expanded `___FILEBASENAME___.swift` with `swift -frontend -parse` to confirm
the generated code is well-formed Swift.
`--full` adds an in-tree compile pass: it drops the expanded file into
`Sources/Lyrebird/Generators/Math/Probe.swift`, runs `swift build`, and removes
the file via `trap` so the working tree stays clean even on failure. This catches
template breakage from upstream API renames (e.g. `EnvGen` → `EnvelopeGen`).
`--external` adds a third pass: for every template whose body contains
`import LyrebirdSynth` (Tier 1 templates), the script creates a temporary SPM package
that depends on the local Lyrebird repo path, drops the expanded file into it,
and runs `swift build`. This proves the template works for users who consume
Lyrebird as a Swift Package dependency. In-tree-only templates (Tier 1b — no
`import LyrebirdSynth` line) are reported as `SKIP` here by design.
CI runs `--external` on every PR that touches `Xcode/Templates/` or
`Sources/Lyrebird/`.
---
## Adding a new template
1. Create `Xcode/Templates/Lyrebird/<Name>.xctemplate/` with two files:
- `TemplateInfo.plist` — kind, summary, options, allowed types
- `___FILEBASENAME___.swift` — source body with Xcode placeholders
2. Use the placeholders Xcode expands:
- `___FILEBASENAME___` — file name (preserves user's casing)
- `___FILEBASENAMEASIDENTIFIER___` — sanitized Swift identifier
- `___FILEHEADER___` — the project's standard file header comment block
- `___FULLUSERNAME___`, `___DATE___`, `___YEAR___` — author / date stamps
3. (Optional) Add a `TemplateIcon.png` (48×48) and `TemplateIcon@2x.png` (96×96)
for the Xcode dialog icon.
4. Add custom prompts in `TemplateInfo.plist > Options` if the template needs
user input beyond the file name (parameter types, channel count, etc.).
5. Run `bash scripts/validate-xcode-templates.sh --full` — must pass.
6. Add an entry to the "Templates shipped" table above.
The `TemplateInfo.plist` schema is described in Apple's Xcode docs under
"File Templates" — the same format is used by Xcode's built-in templates at
`/Applications/Xcode.app/Contents/Developer/Library/Xcode/Templates/File Templates/`.
Copy one of those as a starting point if you need an exotic option type.
+369
View File
@@ -0,0 +1,369 @@
# GUI System
Lyrebird provides native macOS UI via SwiftUI in the `LyrebirdUI` module. Controls bind
directly to Synthesizer parameters — the same parameter update path used by code is used
by the UI, so there is no special "GUI mode". Any parameter controllable from code is
automatically controllable from a GUI control, and vice versa.
The core `Lyrebird` module has **no UI dependency** — `LyrebirdUI` is imported only by
targets that need GUI windows.
```swift
import LyrebirdSynth // engine, protocols, generators — no UI
import LyrebirdUI // LyrebirdWindow, @UIParam, ParameterSlider, etc.
```
---
## @LiveParam vs @UIParam
Lyrebird provides two property wrappers for RT-safe parameters:
| | `@LiveParam` | `@UIParam` |
|---|---|---|
| Module | `Lyrebird` (no UI) | `LyrebirdUI` |
| Projected value | `ParameterNode` | `UIParamNode` |
| IS a `Generator`? | Yes (`AudioGenerator`) | No (`ValidGeneratorInput` only) |
| RT delivery to oscillators/filters | Per-sample linear ramp | Block-constant (atomic read) |
| SwiftUI binding | No | Yes — `@Observable`, all `Parameter*` controls |
| When to use | Code-only synths; any param needing smooth per-sample ramps | Synths with SwiftUI UI controls |
**Identical RT behavior:** both `@LiveParam` and `@UIParam` deliver a linearly-interpolated
ramp from the previous block's last value to the new atomic target via their projected
`ControlGenerator` node. `@UIParam` adds an `@Observable` `value` for SwiftUI binding on
top — there is no behavioral difference at the audio thread.
---
## Core Concept: @UIParam
A `struct` property wrapper that is simultaneously:
1. A `ValidGeneratorInput` (via its projected `UIParamNode`, a `ControlGenerator`) — wire
`$paramName` directly into the audio graph in `build()`.
2. An `@Observable` value — SwiftUI views bind to the node and redraw automatically
when the value changes.
3. RT-safe — the audio render callback reads via a lock-free `Atomic<UInt64>` load;
the main thread writes via a releasing atomic store. No locks, no queue drain.
```swift
import LyrebirdUI
final class MySynth: SynthesizerBase {
@UIParam var amplitude: Double = 0.5
@UIParam var frequency: Double = 440.0
override func build() {
let osc = OscSin.Audio(freq: $frequency)
output(bus: 0, source: osc * $amplitude)
}
}
```
`@UIParam` properties auto-register at `build()` time via `Mirror` reflection — no
`declareParameter` call is needed. The property name (with leading `_` of property-wrapper
backing storage stripped) is the parameter key for `updateParameter` / OSC handlers.
### Projected value
`$paramName` returns a `UIParamNode` — an `@Observable` class that conforms to
`ValidGeneratorInput`. This is the object you pass to UI controls:
```swift
ParameterSlider("Freq", node: synth.$frequency, range: 20...20000)
```
### Reading and writing from code
```swift
synth.amplitude = 0.2 // atomic store → RT thread picks up next block
synth.frequency = 880.0 // UI slider updates automatically via @Observable
```
---
## Opening a Control Window
`LyrebirdWindow` is a `@MainActor` class that wraps `NSWindow` + `NSHostingController`.
Create an instance, then call `open { ... }` with any SwiftUI content:
```swift
let window = LyrebirdWindow(title: "My Synth", width: 400, height: 300)
window.open {
VStack {
ParameterSlider("Amplitude", node: synth.$amplitude, range: 0...1)
ParameterSlider("Frequency", node: synth.$frequency, range: 20...20000)
ParameterButton("Free") { engine.rootGroup.remove(synth) }
}
.padding()
}
// Later
window.close()
```
`open` can be called again on the same instance to replace the content.
### LyrebirdWindow API
```swift
// Init — no window is shown yet
LyrebirdWindow(title: String = "Lyrebird", width: CGFloat = 400, height: CGFloat = 300)
// Show (or replace) the window with SwiftUI content
func open<Content: View>(@ViewBuilder content: () -> Content)
// Close and release the window
func close()
```
Full SwiftUI is available inside the `open` closure — mix Lyrebird controls with any
standard SwiftUI views.
---
## Built-in Controls
All controls accept a `UIParamNode` (the `$paramName` projected value).
Changes are bidirectional: UI → audio (atomic store) and code → UI (`@Observable`).
### ParameterSlider
Continuous value control with an optional exponential taper.
```swift
ParameterSlider("Amplitude", node: synth.$amplitude, range: 0.0...1.0)
ParameterSlider("Cutoff", node: synth.$cutoff, range: 20.0...20000.0, taper: .exponential)
```
**Taper options:** `.linear` (default), `.exponential` — exponential maps equal visual
steps to equal ratios, useful for frequency and time parameters.
### ParameterButton
Momentary action button or latching toggle.
```swift
// Momentary — runs action closure on press; no node binding
ParameterButton("Trigger") { synth.trigger() }
// Toggle — flips node between 0.0 (off) and 1.0 (on) on each press
ParameterButton("Mute", node: synth.$muted, style: .toggle)
```
The toggle button renders with an accent-colour highlight when the node value ≥ 0.5.
Custom off/on values:
```swift
var btn = ParameterButton("Bypass", node: synth.$bypass, style: .toggle)
btn.offValue = 0.0
btn.onValue = 1.0
```
### ParameterKnob
Rotary dial; drag vertically to change value. Equivalent in behaviour to `ParameterSlider`.
```swift
ParameterKnob("Resonance", node: synth.$resonance, range: 0...1)
```
### ParameterXY
Two-dimensional control pad for simultaneous X/Y parameter control. X increases
left-to-right; Y increases bottom-to-top.
```swift
ParameterXY(
xLabel: "Pan", xNode: synth.$pan, xRange: -1...1,
yLabel: "Amplitude", yNode: synth.$amplitude, yRange: 0...1
)
```
### ParameterLabel
Read-only display that updates automatically via `@Observable`.
```swift
ParameterLabel("Level", node: synth.$amplitude)
ParameterLabel("Freq (Hz)", node: synth.$frequency, decimalPlaces: 1)
```
### LyrebirdStatusView
Compact engine status display showing average and peak CPU load. Polls the engine at 10 Hz;
embed anywhere in a SwiftUI hierarchy.
```swift
LyrebirdStatusView(engine: engine)
```
Renders two labeled rows — **CPU Avg** and **CPU Peak** — each with a color-coded bar
(green < 50 %, yellow 50–80 %, red > 80 %) and a numeric percentage. Values above 100 % mean
the engine is running over budget. Peak resets automatically every 5 s (matches the engine's
built-in timer); `engine.resetPeakCPU()` triggers an immediate manual reset.
Takes a direct `SynthesisEngine` reference — does not require a `UIParamNode` or `@UIParam`:
```swift
// Embed alongside synth controls in any view
VStack {
ParameterSlider("Frequency", node: synth.$frequency, range: 20...20000)
ParameterKnob("Amplitude", node: synth.$amplitude, range: 0...1)
Divider()
LyrebirdStatusView(engine: engine)
}
```
### LyrebirdScopeView
Real-time dual-channel oscilloscope. Polls a `ScopeCapture` at ~30 Hz and renders
each channel's waveform using `Canvas`. Channels are stacked vertically: channel 0 (left bus)
in cyan, channel 1 (right bus) in orange. Each channel has a zero guide line and a hairline
separator between channels. Background is near-black.
```swift
// 1. Create and attach the capture tap before engine.start()
let scope = ScopeCapture(buses: [0, 1], bufferSize: 2048)
engine.scopeTap = scope
try engine.start()
// 2. Embed the view
LyrebirdScopeView(capture: scope)
.frame(height: 120)
```
The `bufferSize` determines how many samples are displayed per frame. At 44100 Hz / 512
blockSize, `bufferSize: 2048` ≈ 46 ms of history (≈ 4 blocks per frame flip). Use a larger
`bufferSize` for more temporal context; smaller for a tighter, faster-updating trace.
`LyrebirdScopeView` takes only the `ScopeCapture` reference — no engine reference
needed in the view itself:
```swift
LyrebirdScopeView(capture: scopeCapture)
.frame(height: 120)
.frame(maxWidth: .infinity)
```
See `Sources/LyrebirdUI/LyrebirdScopeView.swift` and the engine-side tap documentation in
`docs/engine/synthesis-engine.md`.
---
## Threading Model
```
UI gesture / code assignment (main thread)
→ synth.amplitude = 0.2
→ UIParamNode.update(0.2)
→ @Observable value = 0.2 (SwiftUI re-renders on next run loop)
→ Atomic<UInt64>.store(bitPattern, ordering: .releasing)
RT audio thread (render callback)
→ UIParamNode.calculatedSamples(graph:count:)
→ Atomic<UInt64>.load(ordering: .acquiring) (lock-free, no allocation)
→ linear ramp from previous value to new target
→ fills pre-allocated _result buffer in-place
```
**Key invariant:** the RT thread never accesses `UIParamNode.value` or the
`@Observable` registrar — it reads only `_atomicBits`. The main thread never touches
`_result` or `_previousValue`. These are disjoint fields; `@unchecked Sendable` is
correct and safe.
---
## Module Structure
```
Sources/
├── Lyrebird/ # engine, protocols, generators — no SwiftUI/AppKit imports
│ └── ScopeCapture.swift double-buffer RT bus tap; @unchecked Sendable
└── LyrebirdUI/ # LyrebirdWindow, @UIParam, controls — depends on Lyrebird
├── UIParamNode.swift @Observable backing; ValidGeneratorInput; Atomic RT reads
├── UIParam.swift @propertyWrapper; wrappedValue + $projectedValue
├── LyrebirdWindow.swift @MainActor NSWindow + NSHostingController
├── LyrebirdStatusView.swift CPU avg/peak display; polls engine at 10 Hz
├── LyrebirdScopeView.swift dual-channel oscilloscope; Canvas; polls capture at 30 Hz
└── Controls/
├── ParameterSlider.swift
├── ParameterButton.swift
├── ParameterKnob.swift
├── ParameterXY.swift
└── ParameterLabel.swift
```
`LyrebirdUI` uses `.swiftLanguageMode(.v5)` — the same rationale as `LyrebirdCLI` —
to avoid Swift 6 actor-isolation diagnostics in SwiftUI/AppKit interop until the
concurrency model for UI is fully audited.
---
## Full Example
```swift
import AppKit
import SwiftUI
import LyrebirdSynth
import LyrebirdUI
// Example — your synthesizer, defined by subclassing SynthesizerBase
// 1. Declare the synthesizer with @UIParam properties
final class DrumSynth: SynthesizerBase {
@UIParam var pitch: Double = 60.0
@UIParam var decay: Double = 0.3
@UIParam var amplitude: Double = 0.8
override func build() {
let osc = OscSin.Audio(freq: $pitch)
output(bus: 0, source: osc * $amplitude)
}
}
// 2. Track add/remove state in an @Observable controller
@Observable
final class DrumController {
private let engine: SynthesisEngine
let synth = DrumSynth()
private(set) var isPlaying = false
init(engine: SynthesisEngine) { self.engine = engine }
func toggle() {
if isPlaying {
engine.remove(synth)
} else {
do { try engine.add(synth) } catch { print("[Lyrebird] engine.add failed: \(error)") }
}
isPlaying.toggle()
}
}
// 3. Build the control view
struct DrumView: View {
let controller: DrumController
var body: some View {
VStack(spacing: 16) {
HStack {
Text("Drum Synth").font(.headline)
Spacer()
Button(controller.isPlaying ? "Stop" : "Start") { controller.toggle() }
.buttonStyle(.bordered)
.tint(controller.isPlaying ? .red : .green)
}
ParameterSlider("Pitch", node: controller.synth.$pitch, range: 30...90)
ParameterSlider("Decay", node: controller.synth.$decay, range: 0.05...2.0,
taper: .exponential)
ParameterKnob ("Amplitude", node: controller.synth.$amplitude, range: 0...1)
}
.padding()
}
}
// 4. Open the window
let controller = DrumController(engine: engine)
let window = LyrebirdWindow(title: "Drum", width: 360, height: 240)
window.open { DrumView(controller: controller) }
```