# Completed Phases — Archive Phases moved here after merge to `main`. The phase completion checklist lives in `docs/00-working-order.md`. --- ## Phase 1 — SynthesisEngine + Core Audio ✓ COMPLETE **Goal:** silence that compiles and produces an audio stream. - `SynthesisEngine` class with init params: `blockSize`, `sampleRate`, `numOutputChannels`, `numInputChannels`, `numAudioBuses`, `numControlBuses` ✓ - Core Audio AUHAL setup (`kAudioUnitSubType_HALOutput`) — full duplex via explicit `EnableIO` on element 0 (output) and element 1 (input) ✓ - `AudioDriver` protocol + `OfflineDriver` (no-op) + `CoreAudioDriver` (AUHAL) — injected at init for testability ✓ - Install render callback (`lyrebirdRenderCallback` — module-level `@convention(c)` free function) ✓ - `start()` / `stop()` lifecycle (idempotent) ✓ - `processBlock(inputSamples:)` — returns `Void`; zeros audio buses, copies input samples ✓ - Pre-allocated input staging buffers in `CoreAudioDriver.setup()` — no RT allocation ✓ - 28 passing tests (`SynthesisEngineTests.swift`) ✓ - `LyrebirdDemo` executable target for hardware smoke test ✓ **Ref:** `docs/engine/synthesis-engine.md` --- ## Phase 1b — Scheduling + NRT Rendering ✓ COMPLETE **Goal:** sample-accurate event scheduling with RT-safe allocation/deallocation, plus non-real-time rendering to an audio file. - `SampleTime` typealias (`Int64`) ✓ - `SPSCQueue` — SPSC ring buffer using `Synchronization.Atomic` (macOS 15+) ✓ - `ScheduledEvent` enum — `.add`, `.remove` with `SampleTime` ✓ - `SynthesisEngine.pendingQueue`, `freeQueue` ✓ - `SynthesisEngine.currentTime` — monotonically incremented by `processBlock` ✓ - `engine.schedule(_:at:)` / `schedule(_:after:)` / `remove(_:at:)` API ✓ - `engine.seconds(_ d: Double) -> SampleTime` convenience ✓ - `processBlock` sub-block splitting: drain pending queue, sort by time, evaluate in variable-length segments ✓ - Background `DispatchQueue` drains `freeQueue` (ARC release off RT thread) ✓ - `NRTDriver(outputURL: URL, duration: Double)` — fixed-duration tight-loop, `ExtAudioFile` AIFF/WAV output ✓ **Ref:** `docs/engine/scheduling.md` --- ## Phase 2 — Bus System ✓ COMPLETE **Goal:** pre-allocated memory that the render callback can read/write safely. - Allocate audio bus buffer: `[numAudioBuses][blockSize]` Float ✓ - Allocate control bus buffer: `[numControlBuses]` Float ✓ - Implement cycle semantics: zero audio buses at top of each callback, retain control buses ✓ - Copy hardware input samples into reserved input buses ✓ - Read reserved output buses → write to hardware buffer (replacing zeros from Phase 1) ✓ **Ref:** `docs/engine/bus-system.md` --- ## Phase 3 — Generator Protocol ✓ COMPLETE **Goal:** typed, stateful, rate-aware signal generators. - Define `Generator` base protocol ✓ - `AudioGenerator` (sample-rate) and `ControlGenerator` (control-rate) ✓ - Processing rates enum: `.audio`, `.control`, `.spectral`, `.demand` ✓ - `ValidGeneratorInput` protocol: constants, Generators, string keys, closures all conform ✓ - Operator overloading: `*`, `+`, `-`, `/` produce `BinaryOpGenerator` ✓ - `SynthGraph` context struct (`engine` + `busOffset`) passed to all `calculatedSamples` calls ✓ - `Closure` wrapper conforming to `ValidGeneratorInput` ✓ - 55 new tests (generator protocol, ValidGeneratorInput, BinaryOpGenerator, In, Out) ✓ **Ref:** `docs/protocols/generator.md` --- ## Phase 4 — In / Out Generators ✓ COMPLETE **Goal:** connect the bus system to the Generator protocol. - `In` / `ControlIn` generators: read from numbered audio/control buses ✓ - `Out` / `ControlOut` generators: accumulate (`+=`) into numbered audio/control buses ✓ - `busOffset` support for correct write position during sub-block splitting ✓ - Wire the render callback: after graph evaluation, `Out` generators have populated the output buses ✓ **Ref:** `docs/engine/bus-system.md`, `docs/protocols/generator.md` --- ## Phase 5 — Synthesizer Protocol + Node Tree ✓ COMPLETE **Goal:** composable instruments that can be added to and removed from the running engine. - `Synthesizer` protocol with `build()` + `evaluate(graph:count:)` ✓ - `SynthesizerBase` — concrete base class; `addOutputGenerator(_:)` in `build()`, `evaluate` is `final` ✓ - `Group` type: linked-list ordered container, tail-append default ✓ - `engine.rootGroup` — node tree root; Groups can be nested ✓ - `engine.add(_:)` / `engine.remove(_:at:)` — `build()` + `PreparedNode` alloc on main thread; RT thread only wires pointers ✓ - `freeQueue` drains removed instances off-RT via background `DispatchQueue` ✓ **Ref:** `docs/protocols/synthesizer.md`, `docs/signal-flow/signal-flow.md` --- ## Phase 6 — Parameter System ✓ COMPLETE **Goal:** safe real-time parameter updates with three input types. - `ControlParameter` — interpolates to new values over one block (click-free); first block flat at declared default ✓ - `ConstantParameter` — sample-and-hold; instantaneous step ✓ - `ValidGeneratorInput` source — any generator, bus reader, LFO, or closure wired at `build()` time ✓ - `declareParameter(_:default:)` / `declareParameter(_:constant:)` / `declareParameter(_:source:)` — all no-op if key already exists ✓ - `try updateParameter(_:value:)` — throws `ParameterUpdateError.keyNotFound` or `.sourceNotUpdatable` ✓ - `ParameterTable` reference type — eliminates RT dict copy; shared by `SynthGraph` ✓ - `ParameterUpdate` SPSC queue — RT thread applies updates at block boundary, never mid-block ✓ - 192 tests at phase completion ✓ **Deferred:** runtime source-swapping (replace a slot's `ValidGeneratorInput` at runtime) — requires `Sendable`-conforming SPSC queue; deferred until stdlib generator types are stable. **Ref:** `docs/protocols/synthesizer.md` --- ## Phase 7 — REPL + LineNoise ✓ COMPLETE **Goal:** interactive Swift REPL with Lyrebird pre-loaded. - `lyrebird` CLI binary (`LyrebirdCLI` SPM executable target) ✓ - `lyrebird repl` — prints banner, launches `swift package repl` in current directory ✓ - `lyrebird` (no args) — LineNoise-powered `lyrebird>` interactive shell ✓ - LineNoise integration: arrow-key editing, persistent history (`~/.lyrebird_history`), tab completion for all subcommands ✓ - `lyrebird --help` / `lyrebird --version` ✓ - 20 tests (`LyrebirdCLITests`: CLICommand parsing, REPLLauncher, InteractiveShell) ✓ **Ref:** `docs/tooling/repl.md` --- ## Phase 8 — Built-in Generator Stdlib ✓ COMPLETE **Goal:** useful instruments and effects out of the box. - `OscSin` — 32768-sample table-lookup sine, linear interpolation; lazy global init on non-RT thread ✓ - `Impulse` — fires 1.0 once per period ✓ - `WhiteNoise`, `LFStepNoise`, `LFLineNoise` — xorshift64 PRNG, `clock_gettime_nsec_np` seeds ✓ - `FirstOrderSection`, `SecondOrderSection` — IIR filter sections ✓ - `RBJBandPass` — Bristow-Johnson cookbook BPF, change-detection coefficient caching, `rbjLn2Half` file-scope constant ✓ - `EnvelopeGen` — multi-segment, per-segment exp curve cache (1 multiply/sample in steady state), `Atomic needsFree` ✓ - `Envelope` struct — `init` pads both `durations` and `curves` to `segmentCount` (prevents RT out-of-bounds) ✓ - `DelayLine` — none/linear/cubic (Catmull-Rom) interpolation, read-before-write ordering ✓ - `DelayLineFeedback` — feedback coefficient cached; `exp()`/`log()` only on parameter change ✓ - `BipolarMappingGenerator` (was `RangeGenerator`), `UnipolarMappingGenerator`, `CosGenerator`, `SquaredGenerator`, `NegativeGenerator` ✓ - `LyrebirdConstants.swift` — `lyrebirdDefaultResultBufferSize = 512`; `SynthesisEngine.init` precondition enforces `blockSize ≤ 512`; all generators use `precondition(count <= _result[0].count, ...)` to eliminate any RT allocation path ✓ - 319 tests at phase completion ✓ **Ref:** `docs/stdlib/generators.md` --- ## Phase 8b — Buffer System + Shared Tables ✓ COMPLETE **Goal:** shared lookup tables on the engine, user-allocatable `LyrebirdBuffer`, and a generic table-reading oscillator. - `LyrebirdBuffer` — `UnsafeMutablePointer`-backed, `@unchecked Sendable`; `Atomic` validity flag; `fill(with:)` / `fill(using:)` / `fillSine()` / `fillHanning()` / `invalidate()` API; `precondition` guards fill-after-invalidate; fill methods must not be called after the buffer enters RT use ✓ - `SharedTables` — holds `sineTable` and `hanningTable` at `lyrebirdDefaultTableSize` (32768); allocated and filled at `SynthesisEngine.init` time; never invalidated ✓ - `SynthesisEngine.sharedTables` — `public let SharedTables`; accessible via `graph.engine.sharedTables` from any generator ✓ - `lyrebirdDefaultTableSize = 32768` added to `LyrebirdConstants.swift`; documented as must-be-power-of-two ✓ - `OscSin` migrated from private `[LyrebirdFloat]` global to `LyrebirdBuffer`; optional `table:` param lets callers share `engine.sharedTables.sineTable`; power-of-two enforced by `precondition` in `init` ✓ - `OscTable` — generic table-lookup oscillator accepting any `LyrebirdBuffer`; power-of-two tables use bitmask, non-power-of-two use modulo; `isValid` guarded ✓ - **System rule in GENERATORS.md (§3.6):** table-lookup oscillators must use power-of-two tables and enforce with `precondition`; buffer readers must handle non-power-of-two via modulo + negative-phase guard ✓ - 345 tests at phase completion ✓ **Ref:** `docs/stdlib/generators.md` --- ## Phase 9 — lyrebird CLI + Project System ✓ COMPLETE **Goal:** scaffold, run, and export Lyrebird projects. - `lyrebird new ` — scaffold swift-tools-version 6.0 / macOS 15 Swift Package with Lyrebird dependency ✓ - `lyrebird run [--release]` — wraps `swift run [-c release]`; checks Xcode, standalone, and Homebrew toolchain paths ✓ - `lyrebird export [--to ] [--overwrite]` — generates `SynthesizerBase` subclass template file ✓ - `ProjectScaffolder` — creates full directory tree; atomically cleans up partial scaffold on failure ✓ - `ProjectRunner` — locates `swift` binary; exits with SPM exit code for CI compatibility ✓ - `SynthExporter` — writes starter subclass template; `--overwrite` flag; display path via `defaultOutputPath(for:)` ✓ - `NameValidation.validateSwiftIdentifier` — shared ASCII-only `[A-Za-z0-9_]` validation ✓ - All parser sites guard flag-token-in-name-position (`hasPrefix("-")`) for both `new` and `export` ✓ - Interactive shell (`lyrebird>`) updated: new/run/export commands, case-insensitive verb matching ✓ - 416 tests at phase completion ✓ **Ref:** `docs/tooling/project-system.md`, `docs/tooling/repl.md` --- ## Phase 10 — Swift Testing Suite ✓ COMPLETE **Goal:** comprehensive, CI-friendly test coverage. - `SignalGraphIntegrationTests` — `OscSin`, filter chain (`RBJBandPass`), delay line, bus accumulation, and parameter modulation suites; full engine start/block/remove lifecycle tested ✓ - `ThreadSafetyTests` — SPSC queue producer/consumer concurrency, parameter queue block-boundary semantics, graph modification queue semantics, concurrent `updateParameter`+`processBlock` stability tests ✓ - No Xcode Playgrounds; all tests use `@Test`/`#expect`/`@Suite` (Swift Testing) ✓ - 447 tests at phase completion ✓ --- ## Phase 11 — Interpret-then-Compile Polish ✓ COMPLETE **Goal:** seamless transition from REPL sketch to compiled project. - `WorkflowIntegrationTests` — scaffold + export file tree test; `swiftc -parse` syntax checks on all generated templates ✓ - `SynthesisEngine._emptyParameterTable` — pre-allocated `ParameterTable` instance eliminates per-block heap allocation on RT thread ✓ - `docs/tooling/workflow.md` — end-to-end REPL → compile workflow guide ✓ - 447 tests at phase completion ✓ **Ref:** `docs/tooling/workflow.md`, `docs/tooling/project-system.md` --- ## Phase 12 — GUI System ✓ COMPLETE **Goal:** native SwiftUI control windows bound to Synthesizer parameters. - `LyrebirdUI` module — separate SPM library target; depends on `Lyrebird`; core `Lyrebird` module has zero UI imports ✓ - `SynthParamNode` — `@Observable` class, `ValidGeneratorInput`, `@unchecked Sendable`; main thread writes `value` + `Atomic` releasing store; RT thread reads via acquiring load → linear ramp in pre-allocated `_result` buffer ✓ - `@SynthParam` property wrapper — `$paramName` projected value is the `SynthParamNode`; wire directly into generator DAG or via `declareParameter(_:source:)` ✓ - `LyrebirdWindow` — `@MainActor` class; `NSWindow` + `NSHostingController`; `open(@ViewBuilder)` / `close()` API ✓ - Built-in controls: `ParameterSlider`, `ParameterButton`, `ParameterKnob`, `ParameterXY`, `ParameterLabel` ✓ - `CoreAudioDriver` fix: explicit `kAudioOutputUnitProperty_CurrentDevice` binding before IO configuration; explicit input-disable when `numInputChannels == 0` ✓ - `LyrebirdUIDemo` executable target — live freq/amp control with `@Observable` Start/Stop button ✓ - 474 tests at phase completion ✓ **Ref:** `docs/ui/gui-system.md` --- ## Phase 13 — Generator Fan-out / Shared Signal Semantics ✓ COMPLETE **Goal:** allow a single generator instance to feed multiple downstream consumers without re-evaluating, eliminating the per-block phase-skip bug. - Segment-serial fan-out cache in `Generator` protocol: `_computeSamples` + `calculatedSamples` gateway ✓ - All `floatValue` overrides route through `calculatedSamples(blockSize)` to prime the full-block cache ✓ - `_cachedResult = []` (empty-array singleton) before `_computeSamples` breaks CoW ✓ - `advanceBlock()` test helper for multi-block unit tests ✓ - `FanOutCachingTests.swift` proves single-evaluation invariant end-to-end ✓ - 483 tests at phase completion ✓ **Ref:** `docs/protocols/generator.md` --- ## Phase 14 — Denormal Handling ✓ COMPLETE **Goal:** eliminate CPU spikes caused by subnormal floating-point values in the RT audio path. - `LyrebirdC` SPM target — thin C shim wrapping `fesetenv(FE_DFL_DISABLE_DENORMS_ENV)`; necessary because `FE_DFL_DISABLE_DENORMS_ENV` is a C-only pointer sentinel `(fenv_t *)-2` not expressible in Swift ✓ - `enableFlushToZero()` — Swift wrapper calling the C shim; sets FPCR bit 24 (ARM64) or MXCSR bits 15+6 (x86-64); thread-local, called unconditionally at top of `CoreAudioDriver.render()` ✓ - `denormalsToZero(_ x: LyrebirdFloat) -> LyrebirdFloat` — `abs(x) < 1e-30 ? 0 : x`; applied to IIR state variables and delay-line buffer writes as the per-generator surgical guard ✓ - `FirstOrderSection`: `x1`, `y1` clamped via `denormalsToZero` after each sample ✓ - `SecondOrderSection`: same for `x1`, `y1` ✓ - `RBJBandPass`: same for `x1`, `y1` ✓ - `DelayLineFeedback`: buffer write clamped — prevents subnormal accumulation during long decay tails ✓ - `DenormalHandlingTests.swift` — 7 unit tests for `denormalsToZero`; 4 FTZ integration tests (one per guarded generator) feeding `Double.leastNonzeroMagnitude` across 500 blocks ✓ - 494 tests at phase completion ✓ --- ## Phase 15 — AIFF / WAV File I/O for LyrebirdBuffer ✓ COMPLETE **Goal:** load and save audio files into/from `LyrebirdBuffer` for use as wavetables, impulse responses, and sample playback sources. - `AudioFileFormat` enum — `.aiff` (AIFF-C, Float32 big-endian), `.wav` (Float32 little-endian), `.caf` (Apple CAF); maps to `kAudioFileAIFCType`, `kAudioFileWAVEType`, `kAudioFileCAFType` ✓ - `LyrebirdBufferIOError` enum — `cannotOpenFile`, `cannotQueryFileFormat`, `cannotQueryFrameCount`, `cannotSetClientFormat`, `readFailed`, `channelOutOfRange`, `cannotCreateOutputFile`, `cannotSetOutputFormat`, `writeFailed` ✓ - `LyrebirdBuffer.load(url:channel:normalise:)` — static factory; allocates a buffer sized exactly to the file's frame count; extracts the requested channel from mono or stereo (or N-channel) files; optional peak normalisation ✓ - `LyrebirdBuffer.fill(fromFile:channel:normalise:)` — fills an existing buffer (truncates longer files, zero-pads shorter files); `precondition` guards fill-after-invalidate ✓ - `LyrebirdBuffer.write(to:format:sampleRate:)` — writes mono Float32 to any `AudioFileFormat`; converts `LyrebirdFloat` (Double) → Float32 in `lyrebirdFileIOChunkFrames`-sized chunks (4096 frames) with no RT allocation; file format and client format are set independently so ExtAudioFile handles AIFF-C big-endian conversion transparently; default format is `.caf` ✓ - `withMutableStorage` / `withStorage` internal helpers on `LyrebirdBuffer` — give `LyrebirdBufferFileIO.swift` raw pointer access without exposing storage publicly ✓ - All file I/O uses `ExtAudioFileRef` (already in `AudioToolbox`); no new framework dependencies ✓ - `LyrebirdBufferFileIOTests.swift` — 17 tests covering: load sizing, mono round-trip, stereo channel extraction (L and R), normalisation, silent normalisation no-crash, channelOutOfRange error, missing-file error, fill truncation, fill zero-padding, write+load round-trips for AIFF/WAV/CAF, non-empty file size, bad-path error, chunk-boundary correctness ✓ - 511 tests at phase completion ✓ --- ## Phase 16 — Multichannel `LyrebirdBuffer` ✓ COMPLETE **Goal:** extend `LyrebirdBuffer` to carry a `channelCount` so a single buffer can hold N-channel interleaved audio. Add `loadAllChannels(url:normalise:)` to load all file channels into one buffer. Update `write(to:format:sampleRate:)` to write 2–8 channel files. Preserve complete backward compatibility for all wavetable and mono audio-file use. - `lyrebirdBufferMonoChannelCount = 1` and `lyrebirdMaxFileChannelCount = 8` added to `LyrebirdConstants.swift` ✓ - `LyrebirdBuffer.init(count:channelCount:)` — `channelCount` defaults to 1 for full backward compat; `precondition` guards channel range and `count × channelCount` overflow ✓ - `LyrebirdBuffer.channelCount: Int` — public `let`, freely readable on any thread ✓ - `LyrebirdBuffer.totalSampleCount: Int` — `count × channelCount` computed property ✓ - `LyrebirdBuffer.subscript(frame:channel:)` — named multichannel subscript with debug-build bounds assertions; `buffer[i]` linear subscript unchanged ✓ - `fillSine`, `fillHanning`, `fill(with:)`, `fill(using:)` — gain `precondition(channelCount == 1)` guards; mono-only by contract ✓ - `withMutableStorage` / `withStorage` updated to 3-argument closure `(ptr, frameCount, channelCount)` ✓ - `LyrebirdBuffer.write(to:format:sampleRate:)` — now multichannel-aware: `mChannelsPerFrame`, `mBytesPerFrame`, `mBytesPerPacket` use `channelCount`; iterates `totalSampleCount` samples ✓ - `LyrebirdBuffer.loadAllChannels(url:normalise:)` — static factory; opens file, queries frame/channel counts, allocates interleaved `LyrebirdBuffer(count:channelCount:)`, reads all channels; global-peak normalisation across all channels ✓ - `fill(fromFile:)` gains `precondition(channelCount == lyrebirdBufferMonoChannelCount)` ✓ - `OscSin.init` and `OscTable.init` gain `precondition(table.channelCount == lyrebirdBufferMonoChannelCount)` after existing power-of-two check ✓ - `LyrebirdBufferTests.swift` — new `@Suite("LyrebirdBuffer multichannel")` with 7 tests: init, `[frame:channel:]` subscript, mono equivalence, `totalSampleCount` formula, backwards-compat, and precondition guards for multichannel fill/OscSin/OscTable ✓ - `LyrebirdBufferFileIOTests.swift` — `writeTempMultichannelWAV` helper; new `@Suite("LyrebirdBuffer.loadAllChannels")` (mono, stereo, 4-channel, normalise, silent normalise); `@Suite("LyrebirdBuffer multichannel write")` (2-ch CAF, 3-ch CAF, mono regression guard) ✓ - 527 tests at phase completion ✓ --- ## Phase 17 — Table-Lookup Generator Polish **Goal:** unify interpolation modes across all table-lookup generators and resolve the modulo-vs-bitmask performance question. ### What was built **`TableInterpolation.swift`** — new shared `public enum TableInterpolation: Sendable` with `.none` (nearest), `.linear` (default), `.cubic` (Catmull-Rom). Doc comment includes per-mode cost table. **`OscSin`** — added `interpolation: TableInterpolation = .linear` parameter. Inner loop is now a `switch` with three branches. Added comment explaining that `-1 & mask` correctly wraps to `mask` on two's-complement in the cubic branch. **`OscTable`** — added `interpolation: TableInterpolation = .linear` parameter. Removed `_isPowerOfTwo` stored property and the two-path inner loop (power-of-two bitmask / non-power-of-two modulo). Collapsed to a single `%`-based `switch`. Precondition ordering corrected (channelCount check moved before stored property assignments). **Modulo vs bitmask benchmark result:** 4 000 000-iteration tight inner loop on Apple Silicon M-series at table sizes 256, 1024, 32 768: `%` and `& mask` are within measurement noise (< 1%). Decision: always use `%`. Benchmark numbers documented in `OscTable` class doc. **Denormal bug fix (FirstOrderSection / SecondOrderSection / RBJBandPass):** `denormalsToZero()` was incorrectly applied to feedforward input state (`x1`, `x2`). Only the recursive feedback state (`y1`, `y2`) can independently accumulate subnormals. Fixed to store raw `x` in feedforward state and apply `denormalsToZero` to `y` only. **LyrebirdBufferFileIO fix:** `ExtAudioFileGetProperty` return status was discarded in both `readSamples` and `readAllChannels`. Fixed to guard with `cannotQueryFileFormat` error. ### Checklist - `TableInterpolation` enum extracted to `Sources/Lyrebird/Generators/TableInterpolation.swift` ✓ - `OscSin` gains `interpolation:` parameter ✓ - `OscTable` gains `interpolation:` parameter; `_isPowerOfTwo` branch removed ✓ - Benchmark conducted; `%`-only decision documented in class doc ✓ - Feedforward denormal bug fixed in all three biquad generators ✓ - `LyrebirdBufferFileIO` format-query return status guarded ✓ - 13 new tests: bounds, deterministic sample values, all-modes-agree, modes-differ, cubic on non-power-of-two ✓ - `docs/stdlib/generators.md` updated with new `interpolation:` parameter docs ✓ - 540 tests at phase completion ✓ --- ## Phase 18 — Generator Authoring Guide ✓ COMPLETE **Goal:** a self-contained document that teaches users how to write correct, RT-safe generators, covering every rule enforced by the framework. **Deliverable:** `docs/protocols/writing-generators.md` **Sections:** 1. Protocol choice — `AudioGenerator` vs `ControlGenerator` (with table) 2. Buffer pre-allocation — `_result` sized to `lyrebirdDefaultResultBufferSize`; precondition pattern; `AudioGenerator` and `ControlGenerator` skeletons 3. State variables — declare all mutable DSP state as stored properties; initialize in `init` 4. Reading inputs — Pattern 1 (scalar/block-rate), Pattern 2 (block-interpolated ramp), Pattern 3 (audio-rate block); RT-allocation caution for `Double`/`Int`/`Closure` 5. Fan-out caching — implement `_computeSamples` only; `floatValue` must use `count: graph.engine.blockSize` to prime the full-block cache; `ControlGenerator.floatValue` must NOT route through `calculatedSamples` 6. RT-thread forbidden operations table 7. `needsFree` Atomic pattern — `EnvelopeGen`-style `.releasing`/`.acquiring` Atomic 8. Denormal hygiene — feedback vs feedforward distinction; split delay-buffer row (feedback YES / feedforward NO) 9. Complete `AudioGenerator` skeleton 10. Testing checklist — required tests + optional denormal/floatValue/modulation tests; test helper provenance documented **Tests at phase completion:** 540 (documentation-only phase; no new Swift source) ## Phase 19 — Bus / Output Ergonomics ✓ COMPLETE **Goal:** reduce `SynthesizerBase` subclass boilerplate for the common case of writing to output buses. **Helpers added to `SynthesizerBase`:** ```swift func output(bus: Int, source: any ValidGeneratorInput) func output(buses: Range, source: any ValidGeneratorInput) func controlOutput(bus: Int, source: any ValidGeneratorInput) func input(bus: Int) -> In func controlInput(bus: Int) -> ControlIn ``` `output(buses:source:)` creates one independent `Out` instance per bus — instances are not shared so each write is an independent bus accumulation. All instances reference the same `source`; the Phase 13 fan-out cache ensures single evaluation per block. **Tests:** `BusErgonomicsTests.swift` — 9 tests covering single-bus output, range output (boundary and independence checks), control output, audio bus input routing, and control bus input routing via `ControlIn` interpolation. **Tests at phase completion:** 549 --- ## Phase 20 — LyrebirdBufferFileIO Channel-Count Validation ✓ COMPLETE **Goal:** harden `LyrebirdBufferFileIO` against malformed files that report a pathologically large `mChannelsPerFrame`, which previously caused an out-of-memory abort before the channel clamp in `loadAllChannels` ever ran. **Changes:** 1. `queryFileProperties` validates `mChannelsPerFrame ∈ [1, lyrebirdMaxFileChannelCount]` immediately after reading the ASBD, throwing `LyrebirdBufferIOError.invalidChannelCount(Int)` before any allocation that uses the channel count. All three public entry points (`load`, `fill(fromFile:)`, `loadAllChannels`) are now protected. 2. `queryFileProperties` returns `sampleRate: Double` extracted from the ASBD it already reads, eliminating the redundant second `ExtAudioFileGetProperty` call in both `readSamples` and `readAllChannels`. `readSamples` and `readAllChannels` gain a `sampleRate:` parameter. 3. `LyrebirdBufferIOError` gains `Equatable` conformance to enable typed `#expect(throws:)` assertions in tests. 4. Dead-code `clampedChannelCount` binding removed from `loadAllChannels` (the guard makes it always equal to `fileChannelCount`). **Tests:** `LyrebirdBufferChannelCountValidationTests` — 7 tests: `load`, `fill(fromFile:)`, and `loadAllChannels` each tested for both zero-channel and over-limit channel counts; regression test confirming `lyrebirdMaxFileChannelCount` (8) channels still loads successfully. Raw WAV helper `writeTempRawWAV` writes minimal IEEE-float WAV headers from named constants. **Tests at phase completion:** 556 --- ## Operator Overloads + ConstantGeneratorInput ✓ COMPLETE **Goal:** allow `any ValidGeneratorInput`-typed operands to participate in arithmetic operator expressions without requiring at least one concrete `Generator` on each side. ### Operator overloads (`BinaryOpGenerator.swift`) Four new overloads added as the lowest-priority tier: ```swift public func + (lhs: any ValidGeneratorInput, rhs: any ValidGeneratorInput) -> BinaryOpGenerator public func - (lhs: any ValidGeneratorInput, rhs: any ValidGeneratorInput) -> BinaryOpGenerator public func * (lhs: any ValidGeneratorInput, rhs: any ValidGeneratorInput) -> BinaryOpGenerator public func / (lhs: any ValidGeneratorInput, rhs: any ValidGeneratorInput) -> BinaryOpGenerator ``` These fire when at least one operand is already typed as the existential (e.g. a Synthesizer property `let freq: any ValidGeneratorInput`). Swift's overload resolution picks the stdlib `Double op Double` overload for concrete scalar expressions — confirmed by a compile+runtime regression test `doubleOpDoubleRemainsDouble`. Overload priority order documented in the source: 1. `Generator op Generator` (tiebreaker) 2. `Generator op ValidGeneratorInput` 3. `ValidGeneratorInput op Generator` 4. `ValidGeneratorInput op ValidGeneratorInput` ← new ### `ConstantGeneratorInput` (`Sources/Lyrebird/Generators/ConstantGeneratorInput.swift`) A new `AudioGenerator`-conforming class that wraps a constant `LyrebirdFloat` value: - Pre-allocates `[[LyrebirdFloat]]` buffer once in `init` — zero RT allocation - `floatValue` returns the constant directly, bypassing the fan-out cache (safe: immutable) - Because it IS a `Generator`, it participates in the existing Category A/B operator overloads: `ConstantGeneratorInput(440.0) * 1.5` → `BinaryOpGenerator` via `Generator op ValidGeneratorInput` - `BinaryOpGenerator.init` classifies it as non-literal (`lhsIsLiteral = false`) since it IS a Generator, so `calculatedSamples` is called on it (returns the pre-allocated buffer) `Double` and `Int` `calculatedSamples` still allocate per call; `BinaryOpGenerator`'s `lhsIsLiteral`/`rhsIsLiteral` fast-path avoids calling them from the RT thread. For Phase 22 audio-rate input loops, generators must use the `inputIsGenerator` flag idiom (not call `Double.calculatedSamples` directly). **Tests:** `BinaryOpGeneratorExistentialTests` (7 tests) + `ConstantGeneratorInputTests` (6 tests). Covers all four operators via existential operands, the `doubleOpDoubleRemainsDouble` regression guard, rate/needsInterpolation properties, operator chaining, and fan-out cache hit behaviour. **Tests at phase completion:** 570 ## Phase 21 — Sample Rate Mismatch Detection ✓ COMPLETE **Goal:** fail fast with a clear error when the engine's configured sample rate does not match the hardware device's nominal rate. - `CoreAudioError.sampleRateMismatch(requested: Double, deviceRate: Double)` — thrown in `CoreAudioDriver.setup()` when rates differ and `matchDeviceSampleRate` is `false` ✓ - `CoreAudioDriverOptions` struct with `matchDeviceSampleRate: Bool = false` — when `true`, driver calls `AudioObjectSetPropertyData(kAudioDevicePropertyNominalSampleRate)` instead of throwing ✓ - `CoreAudioDriver.deviceSampleRate: Double?` — set after querying `kAudioDevicePropertyNominalSampleRate` in `setup()`; `nil` before setup ✓ - `CoreAudioDriver._validateSampleRates(requested:deviceRate:options:)` internal static helper — testable without hardware ✓ - 8 offline tests in `CoreAudioDriverTests.swift`: options defaults, throws on mismatch, error carries both rates, no throw with `matchDeviceSampleRate: true`, floating-point tolerance, `deviceSampleRate` nil before setup ✓ **Tests at phase completion:** 671 --- ## Phase 22 — Audio-Rate Input Modulation (FM / AM / PM) ✓ COMPLETE **Goal:** allow any generator input to be consumed at audio rate, enabling true FM synthesis, audio-rate AM, and accurate waveshaping. ### The Problem `OscSin.calculatedSamples` previously read its frequency input once per block via `floatValue` — block rate (~86 Hz at 44100/512). A 440 Hz FM carrier modulated at 440 Hz sounds completely wrong at block rate. Every generator calling `floatValue` on a potentially audio-rate input had this problem. ### The Three Input Consumption Patterns **Pattern 1 — Scalar (block-rate):** `source.floatValue(graph:)` - Use when the parameter changes at most once per block and interpolation is acceptable. **Pattern 2 — Block-interpolated:** `source.sampleBlock(graph:count:previousValue:)` - Use when a `ControlParameter` or `SynthParamNode` needs a smooth ramp within the block. **Pattern 3 — Audio-rate block:** `source.calculatedSamples(graph:count:).first` - Use when the input is an audio-rate generator and per-sample accuracy matters. - Use the `inputIsGenerator` flag at init to select this path; fall back to `floatValue` for scalars. ### Prerequisites (already done at phase start) `ConstantGeneratorInput` and the four `any ValidGeneratorInput op any ValidGeneratorInput` overloads shipped alongside the operator overload work. `Double` and `Int` `calculatedSamples` still allocate per call — generators that read inputs at audio rate use the `inputIsGenerator` flag idiom and must **not** call `calculatedSamples` on a raw `Double` input on the RT thread. ### What Was Done **Generators updated with audio-rate inner loops:** `OscSin`, `OscTable`, `Impulse`, `FirstOrderSection`, `SecondOrderSection`, `DelayLine`. Each stores a `Bool` flag (`freqIsGenerator`, `delayIsGenerator`, `a0IsGenerator`, etc.) set once at init. When the flag is true, `_computeSamples` calls `calculatedSamples` on the input and indexes per sample; when false it calls `floatValue` once — zero extra allocation. **`RBJBandPass` audio-rate path:** `freq` and `bandwidth` Generator inputs trigger block-boundary coefficient interpolation — `computeCoefficients` (pure, returns a 5-tuple) is called twice per block (first and last sample values), then the five normalised biquad coefficients are linearly interpolated across the block via delta-per-sample. 6 trig calls total per block regardless of block size, vs the previous 1536 per block. **Docs updated:** - `docs/protocols/writing-generators.md` — "Choosing the right input consumption pattern" section with Pattern 1/2/3 descriptions, `inputIsGenerator` idiom, and FM worked example. - `docs/stdlib/generators.md` — scalar vs audio-rate input behaviour documented for `OscSin`, `OscTable`, `Impulse`, `FirstOrderSection`, `SecondOrderSection`, `DelayLine`, and `RBJBandPass`. ### FM Synthesis Example ```swift class FMSynth: SynthesizerBase { override func build() { let modulatorFreq: LyrebirdFloat = 440.0 let carrierFreq: LyrebirdFloat = 440.0 let modDepth: LyrebirdFloat = 200.0 let modulator = OscSin.Audio(freq: modulatorFreq) let carrier = OscSin.Audio(freq: modulator * modDepth + carrierFreq) output(bus: 0, source: carrier * 0.3) output(bus: 1, source: carrier * 0.3) } } ``` ### Tests `AudioRateInputTests.swift` (23 tests across `AudioRateInput` and `FMSynthesis` suites): - Per-generator scalar/audio-rate divergence tests for `OscSin`, `OscTable`, `Impulse`, `FirstOrderSection`, `SecondOrderSection`, `RBJBandPass`, `DelayLine` - `FMSynthesisTests`: DFT-based sideband energy verification at `carrierFreq ± modulatorFreq` - `fmSynthExampleBuilds`: smoke test of the FM synth build closure **Tests at phase completion:** 593 --- ## Phase 23 — Full RBJ Cookbook Filters ✓ COMPLETE **Goal:** Add the 8 remaining Bristow-Johnson Audio EQ Cookbook filter types, extract shared biquad infrastructure, and migrate `RBJBandPass` onto it. ### Shared infrastructure — `RBJBiquad.swift` New file `Sources/Lyrebird/Generators/RBJBiquad.swift` provides: - **`BiquadCoeffs`** struct — `(nb0, nb1, nb2, na1, na2)` all normalised by dividing by `a0`. `BiquadCoeffs.zero` is returned on out-of-range input (freq ≥ Nyquist). - **`BiquadState`** struct — Direct Form I state `(x1, x2, y1, y2)` with two `mutating processBlock` overloads: - Block-rate: single `BiquadCoeffs`, simple inner loop - Audio-rate: `startCoeffs` + `endCoeffs`, linearly interpolated across block `denormalsToZero()` applied to y1/y2 on every sample inside both overloads. - **`rbjLn2Half`** — `log(2.0)/2.0` module-level constant (moved from `RBJBandPass.swift`) - **`rbjMaxFreqFraction`** — `0.999` guard constant ### Migration `RBJBandPass.swift`: replaced inline `x1/x2/y1/y2` state + inner loop with `BiquadState` and its `processBlock` methods. Removed private `rbjLn2Half` (now in `RBJBiquad.swift`). ### New filter classes | Class | File | Parameters | Notes | |---|---|---|---| | `RBJLowPass` | `RBJLowPass.swift` | `freq`, `q` | `b0=(1-c)/2, b1=1-c, b2=(1-c)/2` | | `RBJHighPass` | `RBJHighPass.swift` | `freq`, `q` | `b0=(1+c)/2, b1=-(1+c), b2=(1+c)/2` | | `RBJBandPassSkirt` | `RBJBandPassSkirt.swift` | `freq`, `q` | `alpha=sin(w0)/(2Q)`; `b0=sin/2, b1=0, b2=-sin/2`; peak gain = Q | | `RBJNotch` | `RBJNotch.swift` | `freq`, `q` | `b0=1, b1=-2c, b2=1` | | `RBJAllPass` | `RBJAllPass.swift` | `freq`, `q` | `b0=1-alpha, b1=-2c, b2=1+alpha` | | `RBJPeakingEQ` | `RBJPeakingEQ.swift` | `freq`, `gain` (dB), `q` | `A=10^(gain/40)`; `b0=1+α·A, b1=-2c, b2=1-α·A`; `a0=1+α/A, a2=1-α/A` | | `RBJLowShelf` | `RBJLowShelf.swift` | `freq`, `gain` (dB), `slope` | Full 6-term shelf formula; `A=10^(gain/40)` | | `RBJHighShelf` | `RBJHighShelf.swift` | `freq`, `gain` (dB), `slope` | Same as low shelf, sign-flipped cos terms | **3-parameter audio-rate modulation** (PeakingEQ/LowShelf/HighShelf): `BiquadCoeffs` computed at `i=0` and `i=count-1`; `state.processBlock(startCoeffs:endCoeffs:)` interpolates linearly. 2×N trig/pow calls per block regardless of block size. ### Tests — `RBJFilterTests.swift` (47 tests) - `BiquadState` unit tests: zero coeffs, identity passthrough, interpolated path - Frequency spot-checks for all 9 filter types (LPF/HPF/BPF-skirt/Notch/AllPass/PeakingEQ/LowShelf/HighShelf/BandPass regression) - Audio-rate modulation no-crash tests for all filter types - Denormal tests (FTZ + `!isSubnormal`) for all feedback-path filters - Deterministic output tests for all 7 new public generators - Nyquist guard: silence above Nyquist, negative freq **Tests at phase completion:** 671 --- ## Phase 24 — Butterworth Filters ✓ COMPLETE **Goal:** Cascaded Butterworth LPF and HPF (orders 1–8) via biquad stages with bilinear transform and pre-warped cutoff. Order fixed at `init`; all buffers pre-allocated. ### Key insight For order-N Butterworth the k-th second-order section has a Q that depends only on N: ``` Q_k = -1 / (2 · cos(π·(2k + N − 1) / (2N))) k = 1 … ⌊N/2⌋ ``` These are computed once at `init`. At block rate only `freq` changes, modulating coefficients of all stages using the standard RBJ LPF/HPF formula with the stored Q_k values. Odd orders add a first-order section (prepended): ``` Ωa = tan(π·freq/sr) b0 = b1 = Ωa/(Ωa+1), a1 = (Ωa−1)/(Ωa+1) ``` ### Classes **`ButterworthLowPass`** — `Sources/Lyrebird/Generators/Filters/ButterworthLowPass.swift` **`ButterworthHighPass`** — `Sources/Lyrebird/Generators/Filters/ButterworthHighPass.swift` ```swift ButterworthLowPass(input: any ValidGeneratorInput, freq: any ValidGeneratorInput, order: Int, // 1–8, fixed at init sampleRate: Double) ``` - `let butterworthQs: [LyrebirdFloat]` — `⌊order/2⌋` Q values, computed at init - `var biquadStages: [BiquadState]` — pre-allocated array, one entry per Q value - Optional `FirstOrderState` struct (`x1`, `y1`) for odd order - Inter-stage scratch buffer `[LyrebirdFloat]` pre-allocated to `lyrebirdDefaultResultBufferSize` - `let maxButterworthOrder: Int = 8` in `LyrebirdConstants.swift` - Coefficient computation per stage reuses `rbjLowPassCoeffs` / `rbjHighPassCoeffs` free functions extracted from `RBJLowPass` / `RBJHighPass` (Phase 23) - Audio-rate modulation: block-boundary interpolation applied independently per stage - Correct first-order HP bilinear numerator: `b0 = 1/(Ωa+1)` (not `Ωa/(Ωa+1)`) ### Pre-allocation - `[BiquadState](repeating: BiquadState(), count: numBiquadStages)` in `init` - Scratch `[LyrebirdFloat]` sized to `lyrebirdDefaultResultBufferSize` for inter-stage signal - `_result` standard pre-allocation ### Tests — `ButterworthFilterTests.swift` - 2nd-order LPF −3dB at cutoff (±1 dB, DFT of impulse response) ✓ - 4th-order LPF rolloff steeper than 2nd-order at 2× cutoff ✓ - HPF passes high freq, attenuates DC ✓ - Order 1 (first-order section only) ✓ - Order 7 (3 biquads + 1 first-order section) ✓ - Audio-rate freq modulation: no crash, output varies per block ✓ **Tests at phase completion:** 692 --- ## Phase 25 — Resonating, Comb, and Allpass Filters ✓ COMPLETE **Goal:** Two-pole resonating filters, delay-based comb and allpass filters with configurable fractional-delay interpolation (including a new `.allpass` interpolation mode), plus band-pass and band-reject Butterworth variants. ### ResonatingFilter (Ringz-style) ✓ `Sources/Lyrebird/Generators/Filters/ResonatingFilter.swift` Two-pole resonator parameterised by decay time: ``` R = exp(−π · freq / (decayTime · sr)) w0 = 2π · freq / sr b0 = 1 − R, na1 = −2R·cos(w0), na2 = R² y[n] = b0·x[n] − na1·y[n−1] − na2·y[n−2] ``` Uses only `y1`/`y2` feedback state. `denormalsToZero()` on both after each sample. `freq` and `decayTime` both support generator inputs; block-boundary coefficient interpolation on `(b0, na1, na2)`. ### RingingFilter (Resonz-style, amplitude-normalised) ✓ `Sources/Lyrebird/Generators/Filters/RingingFilter.swift` Two-pole resonator parameterised by bandwidth: ``` R = 1 − π · bandwidth / sr (clamped to [0, 1)) w0 = 2π · freq / sr b0 = (1 − R²) · sin(w0) / 2 (unity peak gain normalisation) na1 = −2R·cos(w0), na2 = R² ``` Same structure as `ResonatingFilter`; different `b0` formula and `bandwidth` parameter. ### CombFilter ✓ `Sources/Lyrebird/Generators/Filters/CombFilter.swift` Feedback comb filter: `y[n] = x[n] + g · y[n − D]` - `g = exp(−3·ln(10) · delay / decayTime)` (60 dB decay convention; sign preserved for ringing) - Pre-allocated circular power-of-2 buffer + `bufferMask` - `delay` and `decayTime` both support `isGenerator` flags - `denormalsToZero()` on the feedback sample after write ### AllpassFilter ✓ `Sources/Lyrebird/Generators/Filters/AllpassFilter.swift` Schroeder allpass: `y[n] = −g·x[n] + x[n−D] + g·y[n−D]` Same `g` formula as `CombFilter`. Requires both a feedforward and feedback read from the same circular buffer. Two circular buffers; `denormalsToZero()` on feedback state. ### `.allpass` interpolation mode ✓ `case allpass` added to `DelayInterpolation` in `DelayLine.swift`: ```swift /// First-order allpass fractional delay filter. /// Coefficient η = (1 − frac) / (1 + frac). frac == 0 guard added. case allpass ``` Used by `CombFilter`, `AllpassFilter`, `DelayLine`, and `DelayLineFeedback`. ### ButterworthBandPass / ButterworthBandReject ✓ `Sources/Lyrebird/Generators/Filters/ButterworthBandPass.swift` `Sources/Lyrebird/Generators/Filters/ButterworthBandReject.swift` - Band-pass: cascaded HP + LP Butterworth cascade, orders 1–8 each - Band-reject: parallel LP + HP Butterworth (summed outputs), orders 1–8 each - All buffers pre-allocated; audio-rate `freq` modulation via block-boundary coefficient interpolation ### RT performance improvements ✓ `BiquadState` and `FirstOrderState` `processBlock` signatures changed to `input: borrowing [LyrebirdFloat]` eliminating the ARC retain/release on the RT thread for every block processed. ### Tests — `ResonatingFilterTests.swift` ✓ - `ResonatingFilter`: impulse gives decaying sinusoid; longer `decayTime` → slower amplitude decay - `RingingFilter`: DFT peak at `freq`; −3 dB bandwidth matches `bandwidth` parameter (rough check) - `CombFilter`: output contains energy at multiples of `1/delay` Hz (spectral comb) - `AllpassFilter`: flat magnitude response; phase response non-trivial (DFT magnitude ≈ 1.0) - All four `DelayInterpolation` modes: `.none`, `.linear`, `.cubic`, `.allpass` — no crash, output varies - Audio-rate `delay` modulation: pitch-shifting effect (no crash) - `ButterworthBandPass` / `ButterworthBandReject`: passband energy and stopband attenuation checks **Tests at phase completion:** 752 --- ## Phase 26 — Multi-Channel Expansion (MCE) ✓ COMPLETE Added multi-channel signal flow inspired by SuperCollider's MCE system. ### Components - **`GeneratorArray`** (`Sources/Lyrebird/GeneratorCore/GeneratorArray.swift`) — wraps N generators, returns N-channel `[[LyrebirdFloat]]`; conforms to `Generator` for fan-out caching; element-wise `+`, `-`, `*`, `/` operators for both `GeneratorArray op scalar` and `GeneratorArray op GeneratorArray` (same-count precondition enforced). - **`expand(_:factory:)`** — free function for explicit MCE at build time. - **Multi-channel `Out`** — writes channel `ch` to `bus + ch`; backward-compatible with mono sources. - **`Pan2`** — equal-power stereo panner; two-channel `_result`; block-constant pan. - **`input(bus:channels:)`** in `SynthesizerBase` — mirrors `output(bus:source:)` for multi-channel reads. - **`In.multi(bus:channels:)`** — underlying static helper on `In`. Also fixed two Phase 23 review findings: `rbjLn2Half` precomputed literal + `SynthesisEngine.start()` warm-up prevents `swift_once` lock on first RT access; added `deterministicOutputBandPass` and `highShelfAudioRateSlopeNoCrash` tests. **Tests at phase completion:** 671 --- ## Phase 27 — Control-Rate Generator Variants ✓ COMPLETE **Goal:** Provide `ControlGenerator`-conforming versions of the six audio-rate oscillator and noise generators, enabling efficient LFO synthesis at block rate with smooth interpolated output for downstream audio-rate consumers (filters, oscillator FM inputs, etc.). ### Naming convention Control-rate variants append `Control` to the audio-rate class name: | Audio-rate | Control-rate | File | |---|---|---| | `OscSin` | `OscSinControl` | `OscSin.swift` | | `OscTable` | `OscTableControl` | `OscTable.swift` | | `Impulse` | `ImpulseControl` | `Impulse.swift` | | `WhiteNoise` | `WhiteNoiseControl` | `WhiteNoise.swift` | | `LFStepNoise` | `LFStepNoiseControl` | `LFNoise.swift` | | `LFLineNoise` | `LFLineNoiseControl` | `LFNoise.swift` | ### Implementation pattern Each `XControl` class conforms to `ControlGenerator` and: 1. Stores `var previousOutputValue: LyrebirdFloat = 0.0` (required by `ControlGenerator`). 2. Pre-allocates `_result: [[LyrebirdFloat]]` sized to `lyrebirdDefaultResultBufferSize`. 3. **Overrides `_computeSamples`** (mandatory): - Clamps `freq` via `max(0.0, freq)` before phase advance (prevents negative-freq drift) - Advances internal state (phase, PRNG) by one block's worth of time - Computes one output sample (table lookup or PRNG step) → `target` - Fills `_result[0][0..= 1.0 { phase -= 1.0; ... }` (not `if`) so multiple periods within a block all advance PRNG state correctly. ### Bug fixes applied during phase - `ImpulseControl` phase wrap: `phase -= 1.0` → `phase.truncatingRemainder(dividingBy: 1.0)` (single subtraction left `phase ≥ 1.0` when `freq * blockSize / sampleRate > 1.0`). - `LFStepNoiseControl` phase wrap: `if phase >= 1.0` → `while phase >= 1.0`, matching `LFLineNoiseControl`. - Both control-rate noise generators: `freq` clamped to `max(0.0, freq)` before phase advance; negative input previously caused unbounded phase drift and out-of-range output. - `OscSinControl` / `OscTableControl` freq-as-Generator doc: only sample 0 of the block is consumed (block-rate modulation); audio-rate FM requires `OscSin` / `OscTable`. ### Tests `Tests/LyrebirdTests/ControlGeneratorTests.swift` — 106 tests covering all six variants: - Rate, output count, ramp shape, `previousOutputValue` sync, fan-out cache - `floatValue` does not advance state - Deterministic output (same seed / same params → identical blocks) - High-freq phase-wrap stability (`freq * blockSize / sampleRate > 2.0`) - Negative-freq safety (`negativeFreqHoldsValue`, `negativeFreqOutputInRange`) - `ImpulseControl` fire-count contract (`firesOncePerBlockAtHighFreq`) **Tests at phase completion:** 805 --- ## Phase 28 — `ParameterNode` + `@LiveParam`: Typed, String-Free Parameters **Goal:** Eliminate string keys from synthesizer parameter declarations. ### What was implemented **`Sources/Lyrebird/Parameters/ParameterNode.swift`** (NEW) - `ParameterNode: AudioGenerator, @unchecked Sendable` - `Atomic` bit-cast backing for lock-free main→RT communication - `value` property: acquiring load getter, releasing store setter - `_computeSamples`: linear ramp from `_previousValue` to atomic target over the block; last sample equals target exactly - `floatValue`: direct acquiring atomic load (block-constant scalar; generators detect `ParameterNode` as a `Generator` and call `calculatedSamples` directly) - Segment-serial fan-out cache (`_segmentSerial`, `_cachedResult`) — `_computeSamples` runs exactly once per block regardless of consumer count - Pre-allocated `_result` to `lyrebirdDefaultResultBufferSize`; no RT allocation in steady state **`Sources/Lyrebird/Parameters/LiveParam.swift`** (NEW) - `@propertyWrapper struct LiveParam` - `projectedValue: ParameterNode` (let — identity stable across `rebuildGraph()` calls) - `wrappedValue`: acquiring load getter, releasing store setter via `projectedValue.value` - `nonmutating set` correct because mutation flows through the reference-type `ParameterNode` **`Sources/LyrebirdUI/SynthParamNode.swift`** (REFACTORED) - Delegation model (not subclassing) — holds `@ObservationIgnored private let _node: ParameterNode` - `@Observable var value` kept as main-thread tracked stored property for SwiftUI binding - `update(_:)` sets both `value` (observable) and `_node.value` (atomic) - All RT operations delegate to `_node`: `floatValue` → `_node.value` (direct atomic read), `intValue` → `LyrebirdInt(_node.value)`, `calculatedSamples` → `_node.calculatedSamples`, `sampleBlock` → `_node.sampleBlock` - Fan-out handled at `_node` level via its segment-serial cache **`Sources/LyrebirdUIDemo/SineToneUI.swift`** (SIMPLIFIED) - Removed `declareParameter("Freq", source: $frequency)` + `OscSin.Audio(freq: "Freq")` - Replaced with direct `OscSin.Audio(freq: $frequency)` wiring **`Sources/LyrebirdDemo/main.swift`** (UPDATED) - `SineTone` ported from `initialFreq`/`initialAmp` stored properties + `declareParameter` to `@LiveParam var freq` / `@LiveParam var amp` - `try tone.updateParameter("Freq", value: 880.0)` replaced with `tone.freq = 880.0` ### Key design decisions - `ParameterNode` conforms to `AudioGenerator` (not just `ValidGeneratorInput`) so that `inputIsGenerator` checks in OscSin etc. detect it as a generator and call `calculatedSamples` for per-sample linear ramp interpolation — smoother than the string-key `ControlParameter` path (block-constant via `floatValue`) - `floatValue` on `ParameterNode` is a direct atomic read (not routing through `calculatedSamples`) to avoid mixed-count fan-out cache complications; it is only reached by callers that explicitly want a block-constant scalar - `SynthParamNode` uses delegation (not inheritance) because `@Observable` macro only tracks stored properties on the annotated class; the `value` property must live on `SynthParamNode` itself - `SynthParamNode.needsInterpolation()` returns `true` so `BinaryOpGenerator` calls `calculatedSamples` (ramp path), even though `OscSin`-style generators using `is any Generator` get block-constant frequency via `floatValue` ### Tests added **`Tests/LyrebirdTests/ParameterNodeTests.swift`** (NEW — 21 tests) - `initialValueFlat`, `initialValueReturnedByFloatValue` - `rampsLinearlyToNewValue`, `lastSampleEqualsTarget`, `consecutiveBlocksRampContinuously`, `noRampWhenValueUnchanged` - `fanOutTwoConsumersSameSegment`, `fanOutDoesNotDoubleAdvancePreviousValue` - `atomicUpdateVisibleInNextBlock`, `valueGetterReadsAtomicBits` - `floatValueReturnsCurrentAtomicTarget`, `floatValueDoesNotConsumeComputeBudget` - `bufferIdentityPreservedAcrossBlocks`, `partialCountRampsCorrectly` - `@LiveParam`: `wrappedValueReadsAndWrites`, `projectedValueIsParameterNode`, `projectedValueAndWrappedValueShareSameNode`, `projectedNodeIdentityStable`, `liveParamWiresAsGenerator` **`Tests/LyrebirdUITests/SynthParamNodeTests.swift`** (EXTENDED) - `intValueAfterUpdate`, `intValueDoesNotPrimeFanOutCache` - `subsequentBlockIsFlatAtTarget` updated to advance segment serial between blocks **Tests at phase completion:** 826 --- ## Phase 29b — PlayBuf Reverse Playback **Goal:** Support `playRate < 0` in `PlayBuf.Audio` and `PlayBuf.Control` for reverse buffer playback. ### What was done - Removed `max(0, rateValue)` clamp in `PlayBuf.Audio._computeSamples` and `PlayBuf.Control._computeSamples`. - Added `_phase < 0` branch: loop mode wraps via `truncatingRemainder + _bufferFrames`; no-loop fires `handleEndOfBuffer`. - Added `wrapPhase: LyrebirdFloat` parameter to `handleEndOfBuffer` — the `doneAction: .loop` case now sets `_phase = wrapPhase` instead of hard-coded `0.0`, so reverse playback with `doneAction: .loop` resets to `_bufferFrames - 1` rather than re-triggering on every subsequent sample. - Updated `lyrebirdBufferRead` doc comment: `wrappedFrame` already handles negative `f` via `r += frameCount`. - Added `startPos: LyrebirdFloat = 0.0` init parameter to `PlayBuf.Audio` and `PlayBuf.Control` for convenience when starting reverse playback from the last frame. ### Files changed - `Sources/Lyrebird/Generators/PlayBuf.swift` - `Tests/LyrebirdTests/PlayBufTests.swift` - `docs/stdlib/buffer-io-generators.md` ### Tests added - `reverseNoLoopFiresDone` — Audio, loop:false, doneAction:.freeNode, rate:-1.0 → needsFree after one block - `reverseLoopWrapsPhaseToEnd` — Audio, loop:true, rate:-1.0 → block 2 output is monotonically decreasing - `reverseStartPosFirstSampleReadsLastFrame` — startPos=7 → first sample reads frame 7 - `reverseDoneActionLoopResetsPlayheadToEnd` — Audio, doneAction:.loop, rate:-1.0 → no re-trigger loop, _isDone cleared - `controlReverseAdvancesBackward` — Control settled values [2,1,0,0] with startPos:2, rate:-1.0 - `controlReverseLoopWrapsPhase` — Control loop alternates [1,0,1,0] with startPos:1, rate:-1.0 - `controlReverseDoneActionLoopResetsPlayheadToEnd` — Control doneAction:.loop → resets to frame 3 (end) **879 tests at completion.** --- ## Phase 30 — LyrebirdRoutine + LyrebirdTask + Pattern ✓ COMPLETE **Goal:** Algorithmic event scheduling on background threads + demand-rate value sequences. Non-RT — used for generating events (adding/removing synths, changing `@LiveParam` values), not for audio processing. ### Pattern\ Demand-rate value sequence. Not thread-safe — intended for single-thread use within a Routine/Task. ```swift public final class Pattern { public init(values: [T], repeats: Int = -1) // repeats: -1 = infinite public func next() -> T? // nil when exhausted public func reset() public var isExhausted: Bool } ``` `next()` returns `values[index]`, advances; wraps on end-of-list, increments `cycleCount`. Returns `nil` after `repeats` full cycles. ### LyrebirdRoutine Runs a closure **once** on a dedicated `Thread`. The closure is sequential — call `context.wait(seconds:)` to yield between events. Thread created on `start()`, destroyed when body returns or `stop()` is called. ```swift public final class LyrebirdRoutine { public enum State: Sendable { case idle, running, stopped } public init(_ body: @escaping @Sendable (LyrebirdRoutineContext) throws -> Void) public func start(engine: SynthesisEngine) // creates Thread; returns immediately public func stop() // signals stop; context.wait() throws, unwinds body public func reset() // stop + wait for thread + reset to .idle } ``` `start()` uses `compareExchange` on `_stateRaw` to prevent double-start races. `stop()` sets `_shouldStop: Atomic` and broadcasts on `pauseCondition`. `reset()` spin-polls `threadActive: Atomic` (5 ms ticks) until thread exits. ### LyrebirdRoutineContext ```swift public final class LyrebirdRoutineContext { public func wait(seconds: Double) throws // polling sleep, checks shouldStop + pause public func waitUntil(sampleTime: SampleTime) throws // Engine calls — DispatchQueue.main.async (DispatchQueue.main is serial → single-producer invariant) public func add(_ synth: any Synthesizer) public func schedule(_ synth: any Synthesizer, at: SampleTime) public func schedule(_ synth: any Synthesizer, after: Double) public func remove(_ synth: any Synthesizer) public func remove(_ synth: any Synthesizer, at: SampleTime) } ``` `wait(seconds:)` and `waitUntil(sampleTime:)` poll every 10 ms (`pollIntervalSeconds`), checking `shouldStop` before and inside the loop, and calling `_checkPause()` which blocks on `NSCondition` while paused. ### LyrebirdTask Like `LyrebirdRoutine` with added `pause()` / `resume()`. ```swift public final class LyrebirdTask { public enum State: Sendable { case idle, running, paused, stopped } public func pause() // sets isPaused; thread suspends inside _checkPause() public func resume() // clears isPaused + broadcasts on NSCondition } ``` ### RoutineControl (internal) Shared synchronization state between Routine/Task and its context: - `shouldStop: Atomic` - `isPaused: Atomic` - `threadActive: Atomic` - `pauseCondition: NSCondition` ### Bug fix included `lyrebirdBufferRead` (PlayBuf.swift): all three interpolation arms (`.none`, `.linear`, `.cubic`) updated to use `Int(phase.rounded(.down))` instead of `Int(phase)`. Swift's `Int(_:)` truncates toward zero; for negative fractional phases this read the wrong frame. Also added `startPos` precondition in `_Base.init`. ### New files - `Sources/Lyrebird/Scheduling/LyrebirdRoutine.swift` - `Sources/Lyrebird/Scheduling/LyrebirdTask.swift` - `Sources/Lyrebird/Scheduling/LyrebirdRoutineContext.swift` - `Sources/Lyrebird/Scheduling/RoutineControl.swift` - `Sources/Lyrebird/Patterns/Pattern.swift` - `Tests/LyrebirdTests/RoutineTests.swift` - `Tests/LyrebirdTests/PatternTests.swift` - `docs/tooling/routine-task.md` ### Tests added - `returnsValuesInOrder`, `wrapsAroundOnCycle`, `infiniteRepeatNeverExhausts` — Pattern basics - `exhaustsAfterOneRepeat`, `exhaustsAfterTwoRepeats`, `zeroRepeatsExhaustedImmediately` — finite cycles - `resetRestartsFromBeginning`, `resetClearsCycleCount` — Pattern reset - `emptyValuesAlwaysNil`, `singleValueCycles`, `worksWithStringValues` — Pattern edge cases - `bodyRunsOnNonMainThread` — thread identity - `stateTransitionsIdleRunningToStopped` — state machine - `stopCausesCleanExit`, `resetAllowsRestart` — lifecycle - `multipleRoutinesRunIndependently` — concurrency - `waitUntilStopsCleanlyOnStop`, `waitUntilBlocksUntilTargetSampleTime` — waitUntil coverage - `engineAddArrivesOnMainThread` — SPSC invariant verification - `taskPauseAndResume`, `taskStopWhilePaused`, `taskStateIsIdleBeforeStart`, `taskStateIsPausedWhileSuspended` — Task lifecycle - `linearInterpolationNegativeFractionalPhaseInterpolatesNotExtrapolates` — PlayBuf floor fix (.linear) - `cubicInterpolationNegativeFractionalPhaseInterpolatesNotExtrapolates` — PlayBuf floor fix (.cubic) - `reverseLinearInterpolationStaysInBufferRange` — PlayBuf integration **905 tests at completion.** --- ## Phase 31 — FFT / IFFT Spectral Infrastructure ✓ COMPLETE **Goal:** Spectral-domain processing using Accelerate/vDSP. Phase-vocoder SpectralFreeze for held spectral textures. ### SpectralBuffer `UnsafeMutablePointer` split-complex storage eliminates Swift Array CoW on the RT thread. Stable pointer addresses for lifetime of object. Labeled subscripts `[realp: k]` / `[imagp: k]` with `precondition`-guarded bounds. Internal pointer-access methods (`withDSPSplitComplex`, `withUnsafeMutableRealpPointer`, etc.) for zero-overhead RT hot paths. `Atomic isValid` for non-RT invalidation. `magnitude(at:)`, `phase(at:)`, `setMagnitude(_:at:)` documented as RT-thread-only; `setMagnitude` guards negative input with `precondition + abs`. ### FFTAnalysis `AudioGenerator` → silence. Accumulates audio into bitmask-indexed circular ring buffer (`fftMask = fftSize - 1`). Every `hopSize` samples: apply `vDSP_HANN_DENORM` Hanning window, pack with `vDSP_ctoz`, run `vDSP_fft_zrip` (forward) directly into `spectralBuffer` raw pointers via `withDSPSplitComplex` — no intermediate copy, no CoW. Calls registered `SpectralProcessor` chain in order after each hop. ### IFFTSynthesis `AudioGenerator` → resynthesised audio. Copies spectral buffer to `UnsafeMutablePointer` work arrays, runs `vDSP_fft_zrip` (inverse), `vDSP_ztoc` to interleaved, scales by `normScale = hopSize / fftSize²` (cancels vDSP 2N forward × N inverse scaling and Hanning OLA sum, giving unity gain at any integer overlap ratio). Overlap-adds into `overlapBuf`, writes `hopSize` samples to bitmask-indexed output ring. Read pointer initialized `hopSize` behind write → block 0 = silence, block 1 = first IFFT output. `isValid` guard outputs silence when spectral buffer invalidated. ### SpectralFreeze (phase vocoder) While live: `_updatePhaseTracking` computes `phaseDelta[k] = principalValue(atan2f(ip[k], rp[k]) − prevPhase[k])` per complex bin each hop. On `freeze()` from non-RT thread: sets `Atomic _freezeRequested` (`.releasing`). `process()` checks request BEFORE calling `_updatePhaseTracking` so `_phaseDelta` retains the previous-hop velocity. `_activateFreeze` runs on RT thread: captures `_frozenMag[k]` and seeds `_frozenPhase[k]` from current frame, stores `_prevPhase[k]` for clean unfreeze resume. Frozen hops: `vDSP_vadd` advances phase, scalar loop wraps to `(-π, π]` preventing branch-cut float precision loss, `vvcosf`/`vvsinf` reconstruct rectangular form, `vDSP_vmul` scales by `_frozenMag`. DC and Nyquist replayed verbatim. ### SpectralMagnitudeScale `vDSP_vsmul` in-place scale of all realp and imagp elements. No allocation. ### New files - `Sources/Lyrebird/Spectral/SpectralBuffer.swift` - `Sources/Lyrebird/Generators/Spectral/FFTAnalysis.swift` - `Sources/Lyrebird/Generators/Spectral/IFFTSynthesis.swift` - `Sources/Lyrebird/Generators/Spectral/SpectralMagnitudeScale.swift` - `Sources/Lyrebird/Generators/Spectral/SpectralFreeze.swift` - `Sources/Lyrebird/Generators/Spectral/SpectralProcessor.swift` - `Tests/LyrebirdTests/FFTTests.swift` - `docs/stdlib/spectral.md` ### Tests added - `spectralBufferBinCount` — bin count = fftSize/2 + 1 - `spectralBufferSubscriptRoundTrip` — realp/imagp read-write via labeled subscript - `spectralBufferSubscriptBoundsCheckRealp/Imagp` — precondition fires on OOB - `spectralBufferMagnitudeDC/Nyquist/GeneralBin` — magnitude API - `spectralBufferPhaseDCIsZero/PhaseNyquistIsZero/PhaseGeneralBin` — phase API - `spectralBufferSetMagnitudeOnZeroBin/OnNonZeroBin/PreservesPhase` — setMagnitude - `freezeHoldsDCMagnitude` — DC frozen verbatim - `freezeHoldsBinMagnitude` — complex bin magnitude constant over 4 frozen hops - `freezePhaseAdvancesByDelta` — each frozen hop advances phase by locked phaseDelta (circular angular distance comparison) - `freezeInactivePassesThrough` — unfrozen spectral buffer passes through unmodified - `freezePreservesAcrossSubsequentHops` — engine integration, DC stays frozen - `fftAnalysisRateIsAudio` — rate check - `fftAnalysisOutputIsSilence` — silence output - `fftAnalysisWritesSpectralBufferAfterHop` — DC non-zero after first hop - `fftDCBinDominatesForConstantInput` — DC dominates all other bins at steady state - `ifftSynthesisRateIsAudio` — rate check - `ifftSynthesisOutputsSilenceAfterInvalidation` — isValid guard - `ifftSynthesisFirstBlockIsSilence` — one-hop latency - `roundTripDCSignalReachesUnityGain` — OLA mean within ±0.05 of input - `ifftSynthesisDeterministicSampleOutput` — per-sample check within ±0.005 at steady state - `magnitudeScaleHalvesAllMagnitudes` — SpectralMagnitudeScale **930 tests at completion.** --- ## Phase 31b — Polar-Primary Spectral Buffer ✓ COMPLETE **Goal:** Refactor `SpectralBuffer` to store FFT frames as polar (magnitude + phase) rather than split-complex rectangular, so that rect→polar conversion happens once after the forward FFT and polar→rect once before the inverse FFT — eliminating redundant per-processor trig in `SpectralFreeze` and any future processor. ### SpectralBuffer (rewrite) Storage replaced: `_dcValue: Float` + `_nyquistValue: Float` (signed scalars) + `_mag: UnsafeMutablePointer` [halfSize] + `_phase: UnsafeMutablePointer` [halfSize]. Index 0 allocated but unused; complex bins occupy indices 1..halfSize-1, matching `SpectralFreeze`'s existing convention. Public API: - `dcValue: Float { get set }` / `nyquistValue: Float { get set }` — signed scalars; sign encodes phase (0 or π) - `subscript(magnitude bin: Int) -> Float { get set }` / `subscript(phase bin: Int) -> Float { get set }` — bins 1..= 4` (from `> 1`) across `SpectralBuffer`, `FFTAnalysis`, `IFFTSynthesis`, and `SpectralFreeze` — prevents forming a one-past-end pointer on a one-element `_mag`/`_phase` allocation when `fftSize == 2`. ### FFTAnalysis Added private `_fftRealp: UnsafeMutablePointer` and `_fftImagp: UnsafeMutablePointer` (each halfSize). `_runFFT` now runs `vDSP_ctoz + vDSP_fft_zrip` into these work arrays, then calls `spectralBuffer._writeFromRectangular(_fftRealp, imagp: _fftImagp)`. Removed `withDSPSplitComplex` usage. ### IFFTSynthesis `_runIFFT` now starts with `spectralBuffer._readToRectangular(realp: _fftWorkRealp, imagp: _fftWorkImagp)` instead of the old rect-copy. Rest of pipeline (IFFT, ztoc, normScale, OLA) unchanged. ### SpectralFreeze (simplified) All `atan2f`, `sqrt`, `vvcosf`, `vvsinf`, `vDSP_vmul` removed. `_updatePhaseTracking` reads phase directly from `spectralBuffer` via `withUnsafePhasePointer` — no trig needed. `_activateFreeze` reads mag/phase directly via pointer methods. `_runFrozenHop` writes polar data back to `spectralBuffer` (mag via `update(from:)`, phase after vDSP_vadd + scalar wrap) — `IFFTSynthesis._readToRectangular` handles the cos/sin/mul. Pointer loops fixed: `withUnsafePhasePointer` returns pointer advanced by 1, so loops use 0-indexed access (`pp[i]`, `mp[i]` for bin `i+1`). ### SpectralMagnitudeScale Updated to `withUnsafeMutableMagnitudePointer { vDSP_vsmul }` + scalar `dcValue *= scale` + `nyquistValue *= scale`. ### Precision note atan2f/cos/sin round-trip introduces ~1e-7 float error per hop — inaudible in practice. Pass-through with no processors is not bit-exact with Phase 31 rectangular design. ### New tests - `spectralBufferPolarRoundTrip` — `_writeFromRectangular` then `_readToRectangular` recovers within 1e-5 float tolerance - `spectralBufferDCNyquistPreservedThroughConversion` — signed DC/Nyquist pass through unchanged - `spectralBufferMagnitudeNegativeDC` — `magnitude(at: 0)` returns `abs(dcValue)` - `spectralBufferSetMagnitudePreservesSignDC` — `setMagnitude` on DC preserves sign - `spectralBufferSetMagnitudePreservesSignNyquist` — `setMagnitude` on Nyquist preserves sign **935 tests at completion.** --- ## Phase 29 — RecordBuf + PlayBuf ✓ COMPLETE **Goal:** Buffer recording and playback generators, mirroring SC RecordBuf / PlayBuf. ### RecordBuf `AudioGenerator` that writes input into a `LyrebirdBuffer`. Outputs silence. Uses the RT thread to write — buffer is not safe for concurrent non-RT reads during recording (same as SC convention). ```swift public final class RecordBuf: AudioGenerator { @LiveParam var run: LyrebirdFloat = 1.0 // 0.0 = paused @LiveParam var recLevel: LyrebirdFloat = 1.0 // new signal scale @LiveParam var preLevel: LyrebirdFloat = 0.0 // existing buffer scale (0 = overwrite, 1 = mix) public let buffer: LyrebirdBuffer // init(input:buffer:loop:doneAction:) public var needsFree: Bool // Atomic, set when no-loop recording completes } ``` - `inputSource` classified as generator or scalar at init (`inputIsGenerator` flag) - Multi-channel: `inputSource.calculatedSamples(...)` returns N channels; `precondition(N == buffer.channelCount)` - Write per sample: `buf[frame: writePos, ch] = recLevel * in[ch][i] + preLevel * buf[frame: writePos, ch]` - `run ≤ 0`: skip write, hold position - End-of-buffer: loop → `writePos = 0`; no-loop → `_isDone = true`, set `_needsFree` if `doneAction == .freeNode` ### PlayBuf `AudioGenerator` that reads from a `LyrebirdBuffer` at a variable rate with interpolation. Output channel count = `buffer.channelCount`. ```swift public final class PlayBuf: AudioGenerator { @LiveParam var rate: LyrebirdFloat = 1.0 // 1.0 = normal speed @LiveParam var trigger: LyrebirdFloat = 0.0 // edge 0→positive resets phase to 0 public let buffer: LyrebirdBuffer // init(buffer:loop:interpolation:doneAction:) public var needsFree: Bool } ``` - `_result` pre-allocated `[channelCount][lyrebirdDefaultResultBufferSize]` at init - Trigger edge-detect per sample: `if trig > 0 && _prevTrigger <= 0 { _phase = 0 }` - Read all channels at `_phase` using free function `lyrebirdBufferRead(_:channel:phase:interpolation:)` (parallel to `oscTableRead`) - Phase advance: `_phase += rateValue`; loop check wraps or signals done - Reuse `TableInterpolation` enum for `.none / .linear / .cubic` ### Files - `Sources/Lyrebird/Generators/RecordBuf.swift` - `Sources/Lyrebird/Generators/PlayBuf.swift` - `Tests/LyrebirdTests/RecordBufTests.swift` - `Tests/LyrebirdTests/PlayBufTests.swift` - `docs/stdlib/buffer-io-generators.md` **872 tests at completion (Phase 29). 879 tests after Phase 29b (reverse playback).** --- ## Phase 32 — Granular Synthesis ✓ COMPLETE **Goal:** Buffer-based granular synthesis with pre-allocated grain pool (no RT allocation). ### New types - `GranularBase` — xorshift64 PRNG superclass - `BufferGrain` — buffer-based granular (2-ch stereo output) - `SineGrain` — per-grain sine synthesis - `FMGrain` — per-grain FM synthesis - `InputGrain` — live circular-buffer granular `density` accepts `any ValidGeneratorInput` via `_resolvedDensitySource` (init-time two-phase to avoid pre-super.init `@LiveParam` access). `inputIsGenerator` flag in `InputGrain` eliminates RT alloc for scalar inputs. ### New files - `Sources/Lyrebird/Generators/Granular/GrainState.swift` - `Sources/Lyrebird/Generators/Granular/GranularBase.swift` - `Sources/Lyrebird/Generators/Granular/BufferGrain.swift` - `Sources/Lyrebird/Generators/Granular/SineGrain.swift` - `Sources/Lyrebird/Generators/Granular/FMGrain.swift` - `Sources/Lyrebird/Generators/Granular/InputGrain.swift` - `Tests/LyrebirdTests/GranularTests.swift` **973 tests at completion.** --- ## Phase 33 — Panning Suite ✓ COMPLETE **Goal:** PanN (circular N-channel), Pan4 (quad equal-power), AmbiEncoder1 + AmbiDecoder1 (1st-order B-format Ambisonics). Builds on Pan2. ### New types - `PanN` — circular N-channel equal-power panner; `position` is fractional speaker index [0, N) wrapping; `panNHalfPi` module-level constant warmed in `SynthesisEngine.start()`; `_positionIsGenerator` flag; `_gains[N]` pre-allocated scratch - `Pan4` — 4-ch quad equal-power panner; two-stage decomposition (azimuth L/R × elevation front/rear); reuses `pan2AngleScale`; `@LiveParam` azimuth/elevation - `AmbiEncoder1` — 1st-order B-format encoder; outputs [[W, X, Y, Z]] (4 channels); `ambi1WScale = 1/√2` warmed in `SynthesisEngine.start()`; `@LiveParam` azimuth/elevation in radians; block-constant coefficients - `AmbiDecoder1` — takes `GeneratorArray` (4-channel B-format); decode matrix flattened to `[LyrebirdFloat]` stride-4 (eliminates RT ARC on nested arrays); arbitrary speaker count ### Granular panning additions (review fixes) All four Phase 32 granular generators (`BufferGrain`, `SineGrain`, `FMGrain`, `InputGrain`) gained `@LiveParam pan` + `@LiveParam panSpread`. Equal-power L/R gains computed once at grain trigger via `cos`/`sin` of the pan angle, stored in `GrainState.panGainL`/`panGainR` — zero per-sample trig. `lyrebirdMaxFMModIndex = 1000` constant added to clamp `FMGrain` modulation index and prevent `Int(rawCarrier.rounded(.down))` trap on RT thread. ### New files - `Sources/Lyrebird/Generators/PanN.swift` - `Sources/Lyrebird/Generators/Pan4.swift` - `Sources/Lyrebird/Generators/AmbiEncoder1.swift` - `Sources/Lyrebird/Generators/AmbiDecoder1.swift` - `Tests/LyrebirdTests/PanNTests.swift` - `Tests/LyrebirdTests/PanningTests.swift` **1016 tests at completion.** --- ## Phase 33b — Accelerate / vDSP Optimization ✓ COMPLETE **Goal:** Eliminate per-sample scalar loops in hot generator paths; tier all inner loops through vDSP. ### Key changes - Tier 1: block-level scalar multiply/add replaced by `vDSP_vsmul`, `vDSP_vadd`, `vDSP_vsma` - Tier 2: biquad filters use `vDSP_biquad` / `vDSP_biquadm` with `BiquadCoeffPacket` - Tier 3: granular envelope apply via `vDSP_vmul` - `SPSCQueue` capacity raised from 4 → 32 (`_vdspKillQueue`); background thread drains on `DispatchQueue.global()` - Coefficient delivery via `SPSCQueue` retry-loop (non-blocking, RT-safe) - `MulAddSpec` protocol added to all generators supporting scalar mul/add - All `buf.baseAddress!` force-unwraps replaced with `guard let` pattern (CLAUDE.md compliance) **5.9× throughput improvement on 32-voice polyphonic benchmark.** **1019 tests at completion (Phase 33b). 1038 after RT-safety + vDSP correctness fixes.** --- ## Phase 34 — Multi-Core Support ✓ COMPLETE **Goal:** Enable parallel evaluation of independent voices with correct bus accumulation, supporting polyphonic patterns (many voices → same output bus). ### Architecture `segmentSerial` promoted from `UInt64` to `Atomic` in `SynthesisEngine`. Single `wrappingAdd(1, ordering: .releasing)` write before concurrent section; worker threads use `.acquiring` load. `advanceSegmentSerial()` replaces the previous direct increment. `ScratchBuses` — new `final class` owning per-child Float bus memory: - `buses: [[Float]]` — `[busIndex][sampleIndex]`, sized to `blockSize` - `conversionScratch: [Float]` — per-child Double→Float scratch, avoids race on `engine._busAccumulateScratch` - `clear(offset:count:)` — zeroes only the segment sample range (`base.advanced(by: offset)`) - `accumulate(_:bus:offset:count:)` — `vDSP_vdpsp` + `vDSP_vadd` at offset `SynthGraph` gains `internal let _scratchBuses: ScratchBuses?`. `addSamplesToAudioBus(_:offset:samples:count:)` routes to scratch when non-nil, or to `engine.addToAudioBus` otherwise. `SynthesizerBase.evaluate` forwards `graph._scratchBuses` when constructing `localGraph`. `Out.Audio._computeSamples` calls `graph.addSamplesToAudioBus(...)` instead of `graph.engine.addToAudioBus(...)` — the key routing change. `ParallelGroup` — new `Synthesizer` node: - `add(_ synth:)` — append child before activation (no RT mutation) - `build()` — snapshots `childrenSnapshot`, allocates one `ScratchBuses` per child (off RT, in `prepareAddEvent`) - `evaluate(graph:count:)` — clears scratch at offset, `DispatchQueue.concurrentPerform`, then merges all slots into `engine.audioBuses` via `vDSP_vadd` using `srcBase.advanced(by: offset)` ### Limitations documented - Cross-child generator fan-out is a data race — each child must own its DAG - Control bus writes not scratch-buffered — same-index writes from concurrent children race - Nested `ParallelGroup`s: inner merge bypasses outer scratch - Children snapshotted at `build()` — no mutation while active ### New files - `Sources/Lyrebird/NodeTree/ParallelGroup.swift` - `Sources/Lyrebird/Buses/ScratchBuses.swift` - `Sources/Lyrebird/Lyrebird.docc/MultiCore.md` - `Tests/LyrebirdTests/ParallelGroupTests.swift` - `docs/engine/multi-core.md` ### Modified files - `Sources/Lyrebird/Synthesizer/SynthGraph.swift` — `_scratchBuses`, `addSamplesToAudioBus` - `Sources/Lyrebird/Engine/SynthesisEngine.swift` — `Atomic` segmentSerial, `advanceSegmentSerial()` - `Sources/Lyrebird/Synthesizer/SynthesizerBase.swift` — forward `_scratchBuses` in `localGraph` - `Sources/Lyrebird/Generators/Out.swift` — route through `graph.addSamplesToAudioBus` - `Sources/Lyrebird/Lyrebird.docc/Lyrebird.md` — `### Advanced` topic group with `` - `Tests/LyrebirdTests/TestHelpers.swift` — `advanceBlock` uses `advanceSegmentSerial()` - `Tests/LyrebirdUITests/UIParamNodeTests.swift` — `advanceUIBlock` uses `advanceSegmentSerial()` **1078 tests at completion.** --- ## Phase 36 — LyrebirdClock Design notes: `docs/CONCURRENT_TASK_TIMING.md`. Named shared clock — SuperCollider `TempoClock` semantics — that multiple routines and tasks can align to without per-routine drift. ### What was built `LyrebirdClock` (`Sources/Lyrebird/Scheduling/LyrebirdClock.swift`): - `@unchecked Sendable` final class; `NSLock` protects `_bpm`, `_beatOffset`, `_tempoChangeSample` - All beat↔sample arithmetic goes through `engine.currentTime` (sample-accurate, no wall-clock) - `bpm` setter accumulates elapsed beats before switching tempo — same pattern as `LyrebirdRoutineContext.tempo` - `_sampleTime(beat:)` uses `.rounded()` on the Double→Int64 conversion to avoid truncation errors for past-beat queries - Magic number `60.0` (seconds-per-minute) extracted to `private static let secondsPerMinute` ### API ```swift let clock = LyrebirdClock(engine: engine, bpm: 120.0) // Convert beat ↔ SampleTime clock.sampleTime(beat: 4.0) // SampleTime at beat 4 clock.currentBeat // Double — beats elapsed since init clock.nextBeat() // SampleTime of next whole beat from now clock.nextBeat(after: 2.3) // SampleTime of beat 3.0 // Multi-routine sync — both fire on the same beat grid, never drift apart let a = LyrebirdRoutine { ctx in while true { try ctx.waitUntil(sampleTime: clock.nextBeat()) ctx.add(DrumHit()) } } let b = LyrebirdRoutine { ctx in while true { try ctx.waitUntil(sampleTime: clock.nextBeat(after: clock.currentBeat + 1)) ctx.add(BassNote()) } } // Tempo change mid-performance: beat count is continuous clock.bpm = 90.0 ``` ### Design notes - `sampleTime(beat:)` is only accurate within the current tempo segment (beats since the last `bpm` change). Multi-segment history reconstruction not implemented — consistent with SC TempoClock. - `nextBeat(after: N)` where N is exactly a whole number returns beat N+1 (exclusive semantics). - No RT path changes required. Depends only on Phase 30 (LyrebirdRoutine/Task/RoutineContext). ### Files | File | Change | |---|---| | `Sources/Lyrebird/Scheduling/LyrebirdClock.swift` | New | | `Tests/LyrebirdTests/LyrebirdClockTests.swift` | New (14 tests) | | `docs/tooling/routine-task.md` | Added LyrebirdClock section | **1092 tests at completion.** --- ## Phase 37 — MIDI (Language-Side) **Goal:** Receive and send CoreMIDI messages entirely on the language side. Zero RT-thread involvement. Handlers receive a `LyrebirdMessageContext` so they can schedule synths and update parameters without boilerplate. ### Shared prerequisite: LyrebirdMessageContext New file: `Sources/Lyrebird/External/LyrebirdMessageContext.swift` Thin `DispatchQueue.main.async` wrapper — same pattern as `LyrebirdRoutineContext`'s engine calls, but without the timing/wait primitives. Passed to every MIDI and OSC handler. ```swift public struct LyrebirdMessageContext: Sendable { public let engine: SynthesisEngine public func add(_ synth: any Synthesizer) public func remove(_ synth: any Synthesizer) public func schedule(_ synth: any Synthesizer, at: SampleTime) public func schedule(_ synth: any Synthesizer, after seconds: Double) public func set(_ key: String, to value: LyrebirdFloat, on synth: any SynthesizerBase) throws } ``` `@LiveParam` setters are atomic stores safe on any thread — no context needed for those. ### New files | File | Contents | |------|----------| | `Sources/Lyrebird/External/LyrebirdMessageContext.swift` | Shared context type (used by both phases) | | `Sources/Lyrebird/MIDI/MIDIMessage.swift` | `MIDIMessage` enum — all channel + system message cases | | `Sources/Lyrebird/MIDI/MIDI.swift` | `MIDI` class — CoreMIDI client, ports, handler dispatch | `Package.swift`: add `linkedFramework("CoreMIDI")` to the `Lyrebird` target's `linkerSettings`. ### MIDI API ```swift public final class MIDI: Sendable { public init(engine: SynthesisEngine, clientName: String = "Lyrebird") public var sources: [MIDISource] // name + MIDIEndpointRef public var destinations: [MIDIDestination] public func addHandler( name: String, onMessage: @Sendable @escaping (MIDIMessage, LyrebirdMessageContext) -> Void ) -> MIDIHandlerToken public func removeHandler(_ token: MIDIHandlerToken) public func createVirtualInput(name: String) throws public func createVirtualOutput(name: String) throws public func send(_ message: MIDIMessage, to destination: MIDIDestination) throws public func start() throws // opens input port, connects all current sources public func stop() } ``` ### MIDIMessage cases `noteOn`, `noteOff`, `controlChange`, `pitchBend`, `programChange`, `aftertouch`, `polyAftertouch`, `clock`, `start`, `stop`, `activeSensing`, `reset`, `sysex`, `other`. ### CoreMIDI notes - `MIDIClientCreate` + `MIDIInputPortCreate` using `MIDIEventList` API (macOS 15 required, no fallback needed) - Parse `MIDIEventPacket` bytes → `MIDIMessage`, dispatch handlers on `DispatchQueue(label: "lyrebird.midi", qos: .userInteractive)` - `MIDIOutputPort` + `MIDIEventList` builder for send - `MIDINotifyBlock` for hot-plug source/destination changes ### Tests (`MIDITests.swift`) - Raw byte → `MIDIMessage` parse for all message types - Round-trip encode → parse - Handler registration / removal - Context dispatch mock (verify mutations reach main thread) - `_receive` → handler integration tests via synthetic UMP buffers (NoteOn, CC, SysEx7) **1146 tests at completion.** --- ## Phase 38 — OSC (Language-Side) **Goal:** UDP OSC 1.0 server and client, in-house codec (Network.framework, no new package dep). Address-pattern handlers with OSC glob matching. Same `LyrebirdMessageContext` from Phase 37. ### New files | File | Contents | |------|----------| | `Sources/Lyrebird/OSC/OSCArgument.swift` | `OSCArgument` enum — `int32`, `float32`, `string`, `blob`, `bool`, `timetag`, `nil`, `impulse` | | `Sources/Lyrebird/OSC/OSCMessage.swift` | `OSCMessage` struct — address `String` + `[OSCArgument]` | | `Sources/Lyrebird/OSC/OSCCodec.swift` | OSC 1.0 encode/decode, bundle decode, glob pattern match | | `Sources/Lyrebird/OSC/OSCServer.swift` | `NWListener`-based UDP server, handler registry | | `Sources/Lyrebird/OSC/OSCClient.swift` | `NWConnection`-based UDP sender | `Package.swift`: no change — `Network` auto-linked. ### OSC 1.0 codec Big-endian, 4-byte aligned. Type tags: `i f s b T F N I t`. Bundle: `#bundle\0` header + timetag + size-prefixed inner messages, decoded recursively (depth limit 8). ### API ```swift public final class OSCServer: Sendable { public init(port: UInt16, engine: SynthesisEngine) public func addHandler( address: String, // OSC glob pattern: ?, *, [...], {a,b} handler: @Sendable @escaping (OSCMessage, LyrebirdMessageContext) -> Void ) -> OSCHandlerToken public func removeHandler(_ token: OSCHandlerToken) public func start() throws public func stop() public var port: UInt16 { get } } public final class OSCClient: Sendable { public init(host: String, port: UInt16) public func send(address: String, args: [OSCArgument]) public func send(_ message: OSCMessage) } ``` ### Tests (`OSCTests.swift`) - Codec round-trip for all argument types including timetag - Bundle decode (flat + nested) - Glob pattern matching (`?`, `*`, `[...]`, `{a,b}`) - Handler dispatch routing - Context dispatch mock - No live network needed — feed raw `Data` to codec in tests **1146 tests at completion.** --- ## Phase 39 — Demand-Rate Generators Pull-based on-demand generators triggered by ≤0→>0 crossings. RT-side analogue of `Pattern`. ### Two-layer architecture **Layer 1 — `DemandGenerator` protocol** (value source, not a `Generator`): - `func nextValue() -> LyrebirdFloat?` — nil = exhausted - `func reset()` - `var isExhausted: Bool` - `AnyObject`-constrained; owned by exactly one puller **Layer 2 — `Demand.Audio` / `Demand.Control` pullers** (actual `Generator` conformers): - `trig: any ValidGeneratorInput` — ≤0→>0 edge pulls next value - `reset: any ValidGeneratorInput` — ≤0→>0 edge calls `demand.reset()`, clears held value to 0 (default `0.0`) - `demand: any DemandGenerator` — value source - Hold `_heldValue`; hold last value forever on exhaustion (no wrap, no doneAction) - Reset fires before trigger within same sample (simultaneous edge: reset first, then pull first value of fresh sequence) ### Concrete demand generators **`DSeq`** — cycles through `values` in order. `repeats` = full cycles (-1 = infinite). Mirrors `Pattern` exactly. **`DRand`** — random pick per trigger. `repeats` = total trigger-responses (-1 = infinite). xorshift64 PRNG (same as granular). PRNG state NOT reset by `reset()` to avoid correlated repetition. ### Demand.Audio `_computeSamples` Per-sample loop — sample-accurate trigger detection: ``` reset[i] > 0 && _prevReset <= 0 → demand.reset(); _heldValue = 0 trig[i] > 0 && _prevTrig <= 0 → _heldValue = demand.nextValue() ?? _heldValue _result[0][i] = _heldValue ``` ### Demand.Control `_computeSamples` Full trig block scanned per-sample (catches mid-block rising edges from audio-rate sources). Single `_heldValue` update per block. Ramp output: `_rampTarget` (previous block's target) → `_heldValue`, reaching target at last sample. Matches `ControlParameter` convention. ### Files created ``` Sources/Lyrebird/Generators/Demand/DemandGenerator.swift Sources/Lyrebird/Generators/Demand/DSeq.swift Sources/Lyrebird/Generators/Demand/DRand.swift Sources/Lyrebird/Generators/Demand/Demand.swift Tests/LyrebirdTests/DemandGeneratorTests.swift ``` Updated `Sources/Lyrebird/GeneratorCore/GeneratorTypes.swift` — `.demand` doc comment: `Demand.Audio/Control` use `.audio`/`.control` rates; `.demand` case marks the value-source tier. Updated `docs/stdlib/generators.md` — Demand section added. ### Tests (28) **DSeq (7):** `returnsValuesInOrder`, `wrapsAfterFullCycle`, `infiniteRepeatsNeverExhausts`, `exhaustsAfterNRepeats`, `zeroRepeatsExhaustedImmediately`, `resetRestartsFromBeginning`, `emptyValuesAlwaysNil` **DRand (5):** `returnsValuesFromPool`, `infiniteRepeatsNeverExhausts`, `exhaustsAfterNResponses`, `resetRestartsResponseCount`, `deterministicWithSameSeed` **Demand.Audio (8):** `rateIsAudio`, `holdsZeroBeforeFirstTrigger`, `advancesOnRisingEdge`, `multipleTriggersInOneBlock`, `holdsLastValueAfterExhaustion`, `resetInputClearsHeldValue`, `resetThenTriggerSameSample`, `blockBoundaryTrigger` **Demand.Control (8):** `rateIsControl`, `holdsZeroBeforeFirstTrigger`, `advancesOnRisingEdgeMidBlock`, `outputIsRampToNewValue`, `holdsAfterExhaustion`, `resetClearsHeldValueAndRamps`, `floatValueDoesNotAdvanceSequence`, `resetThenTriggerSameBlock` **1174 tests at completion.** --- ## Phase 40 — Engine CPU Statistics + LyrebirdStatusView ✓ COMPLETE **Goal:** real-time CPU load monitoring accessible from any thread and displayable in SwiftUI. ### Engine-side (`SynthesisEngine`) - `averageCPU: Double` — exponential moving average (α = 0.1) of CPU load per block; published via `Atomic` bit-pattern store (releasing) on every `processBlock` call ✓ - `peakCPU: Double` — maximum load since last reset; same atomic pattern ✓ - `resetPeakCPU()` — releasing store of 0.0; safe to call from any thread ✓ - Both read via `.relaxed` load — safe from any thread with no synchronization cost ✓ - Timing uses `mach_absolute_time()` + one-time `mach_timebase_info` conversion factor (`_machTicksToNs`) computed at `init` — RT-safe, no allocation ✓ - `_blockDurationNs` precomputed at `init`: `(blockSize / sampleRate) * 1e9` ✓ - `_cpuEMA` / `_cpuEMAInitialized` are RT-private (`var`, no atomic needed); EMA initialized from first measurement, not from 0.0 ✓ - Automatic peak reset timer fires every 5 s on `freeWorker` (`DispatchSourceTimer`); started in `start()`, cancelled in `stop()` ✓ - Stats reset to 0.0 in `start()` for clean readings on engine restart ✓ ### UI-side (`LyrebirdUI`) - `LyrebirdStatusView(engine: SynthesisEngine)` — public SwiftUI `View`; embeds in any hierarchy ✓ - Two rows: **CPU Avg** and **CPU Peak**, each with color-coded bar + numeric percentage ✓ - Bar colors: green < 50 %, yellow 50–80 %, red ≥ 80 % ✓ - Polls engine at 10 Hz via `.task` async loop; cancels automatically on view disappear ✓ - `LyrebirdUIDemo` — `LyrebirdStatusView` embedded in `SineToneView` below a divider; `NoteController.engine` exposed (`private` → internal) ✓ ### Files created / modified ``` Sources/Lyrebird/Engine/SynthesisEngine.swift — averageCPU, peakCPU, resetPeakCPU(), timer Sources/LyrebirdUI/LyrebirdStatusView.swift — new public view (created) Sources/LyrebirdUIDemo/NoteController.swift — engine exposed Sources/LyrebirdUIDemo/SineToneView.swift — LyrebirdStatusView added Sources/LyrebirdUIDemo/AppDelegate.swift — window height 220→290 Tests/LyrebirdTests/CPUStatsTests.swift — new test file (created) docs/engine/synthesis-engine.md — CPU Statistics section added docs/ui/gui-system.md — LyrebirdStatusView section + module listing ``` ### Tests (6) `averageCPUNonNegativeAfterOneBlock`, `peakCPUAtLeastAverageCPU`, `peakNonDecreasingWithoutReset`, `resetPeakSetsZero`, `peakReseededAfterReset`, `averageCPUConverges` **1180 tests at completion.** --- ## Phase 41 — Stereo Scope + Pan ✓ COMPLETE **Goal:** real-time dual-channel oscilloscope in the UI demo; stereo panning knob wired to `Pan2`. ### Engine-side (`Lyrebird`) - `ScopeCapture` — `@unchecked Sendable` double-buffer RT bus tap ✓ - Two ping-pong `[[Float]]` buffers (`_bufs[0]` / `_bufs[1]`), each `bufferSize` samples per channel ✓ - RT thread writes into back buffer via `withUnsafeMutableBufferPointer` + `assign(from:count:)` — no per-sample CoW checks, no allocation ✓ - CoW sharing from `[Float](repeating:)` init broken in `init` via `withUnsafeMutableBufferPointer { _ in }` on every inner buffer before RT starts ✓ - When back buffer fills, `_flip()` atomically publishes new front index (`Atomic`, `.releasing`) ✓ - `snapshot()` deep-copies via `$0.withUnsafeBufferPointer { Array($0) }` — does not share CoW storage with internal buffers; RT retains exclusive ownership of back buffer ✓ - `precondition(count <= bufferSize)` in `write()` guards against buffer overrun ✓ - `SynthesisEngine.scopeTap: ScopeCapture?` — set before `start()`; cached as `_rtScopeTap: Unmanaged?` in `start()` so the RT thread reads via `takeUnretainedValue()` with no ARC retain/release ✓ - `processBlock` step 6: `_rtScopeTap?.takeUnretainedValue().write(audioBuses:count:)` — fires after CPU stats, before return ✓ ### UI-side (`LyrebirdUI`) - `LyrebirdScopeView(capture: ScopeCapture)` — public SwiftUI `View` ✓ - `Canvas`-based rendering; channels stacked vertically ✓ - Channel 0 (left) in cyan, channel 1 (right) in orange ✓ - Zero guide line (dim white) per channel; hairline separator between channels ✓ - Polls `capture.snapshot()` at ~30 Hz via `.task` async loop ✓ - Named constants for all non-trivial literals: `waveformHeightFraction`, `zeroLineOpacity`, `separatorOpacity`, `pollIntervalNs` ✓ ### Demo (`LyrebirdUIDemo`) - `SineToneUI` — added `@UIParam var pan: LyrebirdFloat = 0.0`; `build()` replaced two independent oscillators with single `OscSin.Audio` routed through `Pan2(input: osc * $amplitude, pan: $pan)` ✓ - `SineToneView` — added `ParameterKnob("Pan", node: synth.$pan, range: -1.0...1.0)` alongside Amplitude knob ✓ - `NoteController` — added `scopeCapture: ScopeCapture` property ✓ - `AppDelegate` — creates `ScopeCapture(buses: [0, 1], bufferSize: 2048)`, assigns to `engine.scopeTap`, passes to `NoteController`; window height 290→480 ✓ ### Files created / modified ``` Sources/Lyrebird/Capture/ScopeCapture.swift — new (created) Sources/Lyrebird/Engine/SynthesisEngine.swift — scopeTap, _rtScopeTap, processBlock step 6 Sources/LyrebirdUI/LyrebirdScopeView.swift — new (created) Sources/LyrebirdUIDemo/SineToneUI.swift — pan @UIParam + Pan2 Sources/LyrebirdUIDemo/SineToneView.swift — pan knob + LyrebirdScopeView Sources/LyrebirdUIDemo/NoteController.swift — scopeCapture property Sources/LyrebirdUIDemo/AppDelegate.swift — scope tap wiring, window resize Tests/LyrebirdTests/ScopeTests.swift — new test file (created) docs/engine/synthesis-engine.md — Scope Tap section + threading table docs/ui/gui-system.md — LyrebirdScopeView section + module listing ``` ### Tests (7) `snapshotInitiallyZero`, `snapshotBufferSizeMatchesInit`, `writeAndSnapshotRoundTrip`, `partialWriteNoFlipYet`, `multipleBlocksAccumulate`, `wraparoundProducesValidSnapshot`, `engineScopeTapReceivesData` **1187 tests at completion.** --- ## Phase 42 — TriggerListener (RT→Language Trigger Infrastructure) SuperCollider `SendTrig` pattern: RT thread detects signal edges and delivers notifications to the language layer. Phase 42 is the communication infrastructure; Phase 43 adds the generators. Follows the MIDI/OSC listener pattern exactly: standalone class, `addHandler`/`removeHandler` + opaque token, `LyrebirdMessageContext` for engine mutations in handlers. ### New Types **`TriggerEvent`** (`Sources/Lyrebird/Trigger/TriggerEvent.swift`) — value type, Sendable, no references. Enqueues into `SPSCQueue` with no ARC traffic. **`TriggerHandlerToken`** (`Sources/Lyrebird/Trigger/TriggerHandlerToken.swift`) — opaque, Equatable. Mirrors `MIDIHandlerToken`/`OSCHandlerToken`. **`TriggerListener`** (`Sources/Lyrebird/Trigger/TriggerListener.swift`) — class, parallel to `MIDI`. - `addHandler(id: Int32? = nil, _ handler:) -> TriggerHandlerToken` — `nil` id = wildcard - `removeHandler(_ token:)`, `start()`, `stop()` - `internal func _prepareRTSignal() -> () -> Void` — called by `SynthesisEngine.start()`; returns closure capturing `DispatchSourceUserDataAdd` directly so RT thread never reads mutable listener state - `internal func _drainSync()` — synchronous drain for NRT; preconditions `source == nil` to enforce SPSC single-consumer - Handler registry guarded by `NSLock`; snapshot-under-lock before dispatch ### Engine Changes (`SynthesisEngine.swift`) ```swift private static let triggerQueueCapacity = 1024 // headroom for multiple concurrent SendTrigger.Audio generators internal let triggerQueue: SPSCQueue internal weak var _triggerListener: TriggerListener? // main-thread only private var _rtTriggerSignalFn: (() -> Void)? // RT-cached closure; no ARC on render thread public func attachTriggerListener(_ listener: TriggerListener) internal func _postTrigger(_ event: TriggerEvent) // RT thread only; enqueue + signal (only on successful enqueue) ``` `_rtTriggerSignalFn` set in `start()` via `listener._prepareRTSignal()`, cleared in `stop()` after `driver.stop()`. The closure captures the dispatch source directly — eliminates ARC retain/release on the RT thread. ### `LyrebirdMessageContext` NRT Executor Added internal `_dispatch: @Sendable (@Sendable @escaping () -> Void) -> Void` closure. Public `init(engine:)` uses `DispatchQueue.main.async`; internal `init(nrtEngine:)` uses `{ $0() }` (inline execution). Enables `ctx.add(synth)` in NRT handlers to enqueue directly to `pendingQueue`; next `processBlock` renders it. ### Files | Action | Path | |--------|------| | New | `Sources/Lyrebird/Trigger/TriggerEvent.swift` | | New | `Sources/Lyrebird/Trigger/TriggerHandlerToken.swift` | | New | `Sources/Lyrebird/Trigger/TriggerListener.swift` | | Modify | `Sources/Lyrebird/Engine/SynthesisEngine.swift` | | Modify | `Sources/Lyrebird/External/LyrebirdMessageContext.swift` | | New | `Tests/LyrebirdTests/TriggerListenerTests.swift` | --- ## Phase 43 — SendTrigger Generators + NRT Support Adds `SendTrigger.Audio` and `SendTrigger.Control` generators using the Phase 42 infrastructure. Wires `NRTDriver` to drain triggers inline during offline renders. ### Generators (`Sources/Lyrebird/Generators/SendTrigger.swift`) ```swift public enum SendTrigger { public final class Audio: AudioGenerator // sample-accurate; all ≤0→>0 edges per block public final class Control: ControlGenerator // at most one edge per block (didTrigger gate) } ``` Both: `init(trig: any ValidGeneratorInput, id: Int32, value: any ValidGeneratorInput = 0.0)` - **Pass-through**: `_computeSamples` returns the `trig` input unchanged — zero signal impact - **Edge detection**: `t > 0 && _prevTrig <= 0` (from `Demand.Audio`/`Demand.Control`) - **Engine access**: via `graph.engine._postTrigger(...)` (same as `Out`/`In`) - **Generator authoring**: pre-allocated `_result`, `precondition(count <= ...)`, `count > 0` guard on `previousOutputValue` ### NRT Support `NRTDriver.triggerListener: TriggerListener?` — render loop calls `_drainSync()` after each `processBlock`. Inline NRT context enqueues synths directly; next block renders them. ### Files | Action | Path | |--------|------| | New | `Sources/Lyrebird/Generators/SendTrigger.swift` | | Modify | `Sources/Lyrebird/AudioDrivers/NRTDriver.swift` | | New | `Tests/LyrebirdTests/SendTriggerTests.swift` | **1238 tests at completion.** --- ## Envelope Enhancements — releaseNode, loopNode, EnvelopeCurve renames, EnvelopePoll > **Phase 162 update** — `Envelope.releaseNode` was originally a **segment > index** in the entries below (hold value = `levels[releaseNode + 1]`). > Phase 162 (May 2026) switched it to a **level index** matching > SuperCollider's `Env` convention (hold value = `levels[releaseNode]`). > Descriptions in this section are preserved as historical record of the > original design; the current API surface is documented at > `Sources/Lyrebird/Lyrebird.docc/Generators/Envelopes.md` and in the > Phase 162 entry appended near the end of this file. ### Envelope.releaseNode + EnvelopeGen.gate (gated ADSR hold) `Envelope.releaseNode: Int?` — segment index (0-based) at which `EnvelopeGen` holds after completing that segment, as long as `gate > 0`. When `gate` drops to `≤ 0`, playback resumes from `releaseNode + 1` through the remaining segments. Release is permanent: `_released` Bool latches on the first `gate ≤ 0` observation. `EnvelopeGen._Base.gateInput: any ValidGeneratorInput` — read once per block (block-constant). String key forbidden (`precondition`). `_heldAtRelease` / `_heldRawLevel` state fields track the hold point. **1264 tests at completion.** ### Envelope.loopNode (gate-controlled single-segment loop) `Envelope.loopNode: Int?` — segment index to loop while `gate > 0`. After completing the segment, the generator rewinds to its start and replays, as long as `gate > 0`. When `gate ≤ 0`, continues to `loopNode + 1` and runs to completion. `loopNode < releaseNode` enforced at `Envelope.init`. `_released` permanently disables loop/hold once latched. **1271 tests at completion.** ### EnvelopeCurve renames + digital oscillator for sine/welch `.sin` → `.sine`, `.exp` → `.exponential` (public API rename). Digital oscillator (rotation matrix, two mul + two add per sample) replaces per-sample `cos/sin` for `.sine` and `.welch` in `EnvelopeGen._Base.computeCurrentSample`. `initSegmentCache` calls trig once per segment entry. `_released` permanent-latch survives `doneAction:.loop` restart. `gateInput` String key assertion. **1281 tests at completion.** ### EnvelopePoll — stateless envelope value lookup generator `EnvelopePoll.Audio` and `EnvelopePoll.Control` — evaluate `Envelope.valueAtTime(t)` at an arbitrary time input without advancing playback state. `loopNode` and `releaseNode` are ignored. **Time input resolution:** - `Audio`: if `time` is an `AudioGenerator`, `valueAtTime` is called per sample using that generator's output buffer (audio-rate scrubbing). Scalar / `ControlGenerator` inputs are block-constant. - `Control`: time always read once per block via `floatValue`; output is a linear ramp to the new value. `levelScale` and `levelBias` applied after lookup. No playback state — safe to instantiate multiple pollers on the same `Envelope`. ```swift // Audio-rate time sweep (Phasor-driven scrub) let env = Envelope(levels: [0, 1, 0], durations: [0.5, 0.5], curves: [.sine, .sine]) let t = Phasor.Audio(freq: 1.0) * env.totalDuration let poll = EnvelopePoll.Audio(envelope: env, time: t) // Control-rate filter cutoff shaped by an envelope let cutoff = EnvelopePoll.Control(envelope: env, time: Line.Control(start: 0, end: 1.0, dur: 2.0)) ``` **RT note:** trig / `exp` called per sample only when `time` is audio-rate AND the curve kind requires it (`.sine`, `.welch`, `.exponential`, `.custom`). Block-constant time evaluates once per block regardless of curve. ### Files | Action | Path | |--------|------| | Modify | `Sources/Lyrebird/Generators/Envelope.swift` | | Modify | `Sources/Lyrebird/Generators/EnvelopeGen.swift` | | New | `Sources/Lyrebird/Generators/EnvelopePoll.swift` | | Modify | `Tests/LyrebirdTests/StdlibGeneratorTests.swift` | **1293 tests at completion.** --- ## Phase 44 — Runtime Envelope Swap **Goal:** Allow `EnvelopeGen.Audio`, `EnvelopeGen.Control`, `EnvelopePoll.Audio`, and `EnvelopePoll.Control` to accept a new `Envelope` at runtime via a `setEnvelope(_:)` method callable from the main thread. ### Motivation Envelope shape is currently baked at init. This prevents live re-shaping (morphing between articulations, tempo-sync updates, MIDI-driven envelope selection) without freeing and re-allocating the synthesizer node. ### Design **`EnvelopePacket`** — a fixed-size value type (modelled after `BiquadCoeffPacket`) encoding up to `maxSegments = 32` segments. No heap allocation, no ARC. Fields: - `_levels` — inline Buf33 (33 Doubles) - `_durations` — inline Buf32D (32 Doubles) - `_curveKinds` — inline Buf32U (32 × UInt8 curve tags) - `_curveParams` — inline Buf32D (32 Doubles for `.custom` associated value) - `segmentCount: Int`, `loopNode: Int` (-1 = none), `releaseNode: Int` (-1 = none), `totalDuration` Encoded from `Envelope` on the **main thread** via `EnvelopePacket(from:)`; decoded on the RT thread via `level(at:)`, `duration(at:)`, `curve(at:)` accessors using `withUnsafeBytes`. **`SPSCQueue`** (capacity 4) in both `EnvelopeGen._Base` and `EnvelopePoll._Base`. No kill queue needed — `EnvelopePacket` is a pure value type, so overwriting a queue slot triggers no ARC and no heap free. The `_packet = pkt` copy in `_checkEnvelopeSwap` is a plain ~832-byte memcopy on the RT thread. **In-place state semantics on swap:** `currentSegment` and `samplePos` are preserved; `currentSegment` is clamped to `max(0, newSegmentCount - 1)` if out-of-range; `_heldAtRelease` and `isDone` are reset to `false`; `_released` latch is unchanged. **`EnvelopePoll._valueAtTime`** — replaces `_envelope.valueAtTime(t)` with a packet-native implementation. Iterates `_packet` segments, constructs `EnvelopeSegmentCurve` on the stack per segment (no heap), delegates to `curve.value(startLevel:range:pos:)`. Called per-sample only when `time` is audio-rate; otherwise called once per block. ### Files | Action | File | |--------|------| | CREATE | `Sources/Lyrebird/Generators/EnvelopePacket.swift` | | MODIFY | `Sources/Lyrebird/Generators/EnvelopeGen.swift` — `_packet: EnvelopePacket`, single queue, no kill queue | | MODIFY | `Sources/Lyrebird/Generators/EnvelopePoll.swift` — `_packet`, `_valueAtTime`, `setEnvelope` | | MODIFY | `Sources/Lyrebird/Lyrebird.docc/Generators/Envelopes.md` — Runtime Envelope Swap section | | MODIFY | `Tests/LyrebirdTests/StdlibGeneratorTests.swift` — 7 swap tests | **1300 tests at completion.** --- ## Phase 45 — LyrebirdEnvelopeView: SwiftUI Envelope Shape Plotter **Goal:** Pure language-side SwiftUI view that plots any `Envelope` value as a color-coded Canvas path, with distinct colors for loop and release regions. ### What was implemented - **`LyrebirdEnvelopeView`** (`Sources/LyrebirdUI/LyrebirdEnvelopeView.swift`) — Canvas view accepting an `Envelope` value. No state, no polling, no RT interaction. Pure function of the `Envelope` passed in. - **`_EnvelopeRegion`** — internal enum (`preLoop`/`loop`/`release`) with associated `Color`; cyan, green, orange respectively. - **`_regionForSegment(index:loopNode:releaseNode:segmentCount:)`** — pure function classifying each segment. Loop-only semantics: only the segment *at* `loopNode` is green; segments after it are the gate-off release path (preLoop). Both `loopNode` and `releaseNode` set: `[loopNode, releaseNode)` = green, `[releaseNode, end)` = orange. - **`_segmentBoundaryTimes(durations:)`** — cumulative time array; drives X positions of vertical markers. - **`_envelopeYBounds(levels:)`** — min/max of levels with 10% headroom; uses `guard let` on `min()`/`max()`, named constants for `minimumLevelRange` (1e-6) and `headroomFactor` (0.1). - Dashed vertical "L"/"R" markers at `loopNode`/`releaseNode` boundary times. - Horizontal hairlines at each level value (opacity 0.2). - All non-trivial literals extracted to `private static let` constants (`backgroundBrightness`, `labelFontSize`, `markerLineWidth`, `cornerRadius`, etc.). - Demo sample added to `Sources/LyrebirdUIDemo/SineToneView.swift`. ### Key design decisions - Purely language-side — no `EnvelopePacket`, no SPSC queue, no RT access. The view takes `Envelope` directly and calls `Envelope.valueAtTime(_:)` for sampling. - One `Path` per segment (not per region) to preserve per-segment color fidelity at boundaries. - `0...nSamples` closed range: `nSamples` is a step count; the final point lands exactly at segment end, closing adjacent segments cleanly. - `boundaryTimes[ln/rn]` indexing is safe: `Envelope.init` validates `loopNode`/`releaseNode` into `[0, segmentCount)`, and `boundaryTimes` has `segmentCount + 1` entries. ### Files changed | Action | Path | |--------|------| | New | `Sources/LyrebirdUI/LyrebirdEnvelopeView.swift` | | New | `Tests/LyrebirdUITests/LyrebirdEnvelopeViewTests.swift` | | Modify | `Sources/LyrebirdUIDemo/SineToneView.swift` | ### Tests added - `RegionForSegmentTests` — 6 tests covering all loopNode/releaseNode combos - `SegmentBoundaryTimesTests` — 4 tests (empty, single, multi, zero-duration segment) - `EnvelopeYBoundsTests` — 5 tests (empty, single, normal, negative, flat levels) - `EnvelopeValueAtTimePlottingTests` — 4 tests (clamp below, clamp above, linear midpoint, loopNode/releaseNode ignored by valueAtTime) **1320 tests at completion.** --- ## iOS Support — Phases iOS-1 through iOS-4 **Goal:** Full iOS support with zero changes to Generators, SynthesisEngine, bus system, or existing LyrebirdUI views. ### Phase iOS-1 — iOSAudioDriver **New:** `Sources/Lyrebird/AudioDrivers/iOSAudioDriver.swift` **Modified:** `Sources/Lyrebird/AudioDrivers/CoreAudioDriver.swift` — entire file wrapped in `#if os(macOS)` / `#endif` Implements `AudioDriver` conformance using `kAudioUnitSubType_RemoteIO`. Render callback model identical to AUHAL: pre-allocate all buffers in `setup()`, no RT allocation. Key differences from `CoreAudioDriver`: - No device selection — `AVAudioSession` manages hardware routing - `AVAudioSession` category set in `setup()` before AU init (`.playback` for output-only, `.playAndRecord` with `.defaultToSpeaker` when input channels requested) - `setPreferredSampleRate` + `setPreferredIOBufferDuration(blockSize / sampleRate)` called before `setActive(true)` to request hardware alignment with engine block size - AU stream formats use `session.sampleRate` (actual committed rate) **not** `engine.sampleRate` — the preferred rate is a hint only; many devices lock to 48 kHz regardless. Using `engine.sampleRate` for AU format with a 48 kHz session causes per-callback frame-count mismatch → choppy audio - `sessionSampleRate: Double?` property exposes the actual committed rate for caller inspection - Entire file wrapped in `#if os(iOS)` / `#endif` **Tests:** `Tests/LyrebirdTests/iOSAudioDriverTests.swift` — `#if os(iOS)` guarded; tests instantiation, `AudioDriver` conformance, and `iOSAudioError` enum cases. Run on iOS simulator in Xcode. --- ### Phase iOS-2 — Package.swift + LyrebirdC ARM64 **Modified:** `Package.swift` - Added `.iOS(.v18)` to `platforms` (iOS 18 required for `Synchronization.Atomic` used by `SPSCQueue`) - Added `.linkedFramework("AVFoundation", .when(platforms: [.iOS]))` to `Lyrebird` target linker settings `Sources/LyrebirdC/DenormalUtils.c` unchanged — `fesetenv(FE_DFL_DISABLE_DENORMS_ENV)` is a Darwin-wide extension, available on iOS ARM64 without guards. --- ### Phase iOS-3 — LyrebirdUI AppKit Isolation **Modified:** `Sources/LyrebirdUI/LyrebirdWindow.swift` — wrapped in `#if os(macOS)` / `#endif` **Discovered:** `ParameterKnob.swift` and `ParameterXY.swift` used `Color(nsColor: .controlBackgroundColor)` and `Color(nsColor: .separatorColor)` — AppKit-only APIs not available on iOS. **Fix:** Added `Sources/LyrebirdUI/Controls/PlatformColors.swift` with a `Color` extension defining: ```swift extension Color { #if os(macOS) static let lyrebirdControlBackground = Color(NSColor.controlBackgroundColor) static let lyrebirdSeparator = Color(NSColor.separatorColor) #else static let lyrebirdControlBackground = Color(UIColor.secondarySystemBackground) static let lyrebirdSeparator = Color(UIColor.separator) #endif } ``` Both controls updated to use `Color.lyrebirdControlBackground` and `Color.lyrebirdSeparator`. Note: `LyrebirdWindow.swift` was the only file expected to need a guard, but the `ParameterKnob`/`ParameterXY` `Color(nsColor:)` usage was not caught during planning — iOS compile revealed it. --- ### Phase iOS-4 — iOS Demo App **New:** `Demos/LyrebirdiOSDemo/` — Xcode project mirroring `LyrebirdMacOSDemo` layout **Modified:** `Lyrebird.xcworkspace/contents.xcworkspacedata` — added iOS project ref Sources: | File | Notes | |------|-------| | `LyrebirdiOSDemo/LyrebirdiOSDemoApp.swift` | SwiftUI `@main` App struct; no AppDelegate/NSApplication/LyrebirdWindow | | `LyrebirdiOSDemo/Synthesizers/SineToneUI.swift` | Identical to macOS demo | | `LyrebirdiOSDemo/UI/NoteController.swift` | Identical to macOS demo | | `LyrebirdiOSDemo/UI/SineToneView.swift` | Identical to macOS demo | | `LyrebirdiOSDemo/Info.plist` | iOS plist; `NSMicrophoneUsageDescription`, `UILaunchScreen` | **Demo init pattern** (correct iOS audio startup sequence): ```swift // Pre-activate session to discover actual hardware rate before engine creation let session = AVAudioSession.sharedInstance() try? session.setCategory(.playback, mode: .default) try? session.setActive(true) let sampleRate = session.sampleRate // actual: 44100 or 48000 let driver = iOSAudioDriver() let engine = SynthesisEngine(blockSize: 512, sampleRate: sampleRate, ...) // engine.start() called in .onAppear; engine.stop() in .onDisappear ``` Pre-activating before engine creation ensures synthesis frequencies are computed at the hardware's actual rate. `iOSAudioDriver.setup()` re-activates harmlessly (no-op on already-active session) and reads `session.sampleRate` again for AU format configuration. ### Files changed (all iOS phases) | Action | File | |--------|------| | New | `Sources/Lyrebird/AudioDrivers/iOSAudioDriver.swift` | | New | `Sources/LyrebirdUI/Controls/PlatformColors.swift` | | New | `Tests/LyrebirdTests/iOSAudioDriverTests.swift` | | New | `Demos/LyrebirdiOSDemo/LyrebirdiOSDemo.xcodeproj/project.pbxproj` | | New | `Demos/LyrebirdiOSDemo/LyrebirdiOSDemo.xcodeproj/xcshareddata/xcschemes/LyrebirdiOSDemo.xcscheme` | | New | `Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/LyrebirdiOSDemoApp.swift` | | New | `Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/Synthesizers/SineToneUI.swift` | | New | `Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/NoteController.swift` | | New | `Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/SineToneView.swift` | | New | `Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/Info.plist` | | Modify | `Sources/Lyrebird/AudioDrivers/CoreAudioDriver.swift` — `#if os(macOS)` guard | | Modify | `Sources/LyrebirdUI/LyrebirdWindow.swift` — `#if os(macOS)` guard | | Modify | `Sources/LyrebirdUI/Controls/ParameterKnob.swift` — use `Color.lyrebirdControlBackground/Separator` | | Modify | `Sources/LyrebirdUI/Controls/ParameterXY.swift` — use `Color.lyrebirdControlBackground/Separator` | | Modify | `Package.swift` — `.iOS(.v18)`, AVFoundation linker setting | | Modify | `Lyrebird.xcworkspace/contents.xcworkspacedata` — iOS project ref | **1320 tests at completion** (macOS; iOS driver tests require Xcode + iOS simulator). --- ## LyrebirdMusicMath — Musical Conversion Utilities **Goal:** Free functions covering all common musical numeric conversions (MIDI↔Hz, amplitude↔dB, intervals, tempo, mapping) with array overloads for batch use and clear RT-safety documentation. ### What was implemented - **`Sources/Lyrebird/Math/LyrebirdMusicMath.swift`** — `import Darwin` (not Foundation); all conversions as plain free functions; scalar forms RT-safe, array overloads language-side only. - **Tuning constants** — `lyrebirdA4TuningHz: Double = 440.0`, `lyrebirdA4MidiNote: Double = 69.0`; typed `Double` (not `LyrebirdFloat`) to match call sites. - **Private domain constants** — `semitonesPerOctave`, `centsPerOctave`, `dbAmplitudeScale`, `dbPowerScale`, `secondsPerMinute`, `quarterTurn`; no magic numbers. **Scalar functions (RT-safe — pure Darwin math):** | Function(s) | Conversion | |-------------|-----------| | `midiToHz(_:)` / `hzToMidi(_:)` | MIDI note ↔ Hz, equal temperament, fractional MIDI supported | | `midiToHz(_:tuning:)` | MIDI → Hz with custom A4 reference | | `ampToDb(_:)` / `dbToAmp(_:)` | Linear amplitude ↔ dBFS (20 × log₁₀) | | `powToDb(_:)` / `dbToPow(_:)` | Power ↔ dB (10 × log₁₀) | | `semitonesToRatio(_:)` / `ratioToSemitones(_:)` | Semitone count ↔ frequency ratio | | `centsToRatio(_:)` / `ratioToCents(_:)` | Cents ↔ frequency ratio | | `bpmToSeconds(_:)` / `secondsToBpm(_:)` | BPM ↔ seconds per beat | | `hzToPeriod(_:)` / `periodToHz(_:)` | Hz ↔ period in seconds | | `linToExp(_:low:high:)` | Normalized [0,1] → exponential range; `precondition(low > 0)` | | `equalPowerFade(_:)` | Position [0,1] → `(gainA, gainB)` constant-power crossfade | **Array overloads (language-side only — allocate):** `midiToHz`, `hzToMidi`, `ampToDb`, `dbToAmp`, `powToDb`, `dbToPow`, `semitonesToRatio`, `ratioToSemitones`, `centsToRatio`, `ratioToCents`, `bpmToSeconds`, `secondsToBpm`, `hzToPeriod`, `periodToHz`. ### Key design decisions - **Free functions only** — no `extension Double` or `extension Array`. Cleaner call sites (`midiToHz(69.0)`, `midiToHz([60.0, 69.0])`); scalar and array forms resolved by Swift overloading. - **`import Darwin` not `Foundation`** — math functions (`pow`, `log2`, `log10`, `sin`, `cos`) resolve from Darwin. Avoids Objective-C bridging layer in a file that is otherwise pure Swift math. - **RT-safe scalar / non-RT array split** — documented in file header and docc article. Scalar functions safe in `build()`, `_computeSamples`, or any RT context. Array overloads must not cross the RT boundary. - **`hzToMidi` guards ≤ 0 → `-.infinity`**; `ampToDb`/`powToDb` do not guard negative input — `NaN` propagation is the correct signal for an invalid amplitude in a pipeline. - **`linToExp` uses `precondition`** — `low ≤ 0` silently produces wrong output; a hard precondition catches misuse at development time without adding a throwing signature. - Free functions `midiToHz`/`hzToMidi` fix existing doc-comment references in `MIDI.swift` and `LyrebirdMessageContext.swift`. ### Files changed | Action | Path | |--------|------| | New | `Sources/Lyrebird/Math/LyrebirdMusicMath.swift` | | New | `Tests/LyrebirdTests/MusicMathTests.swift` | | New | `Sources/Lyrebird/Lyrebird.docc/Generators/MusicalMath.md` | | Modify | `Sources/Lyrebird/Lyrebird.docc/Lyrebird.md` — added MusicalMath to "Math and Bus I/O" topic group | | Modify | `docs/stdlib/generators.md` — LyrebirdMusicMath section | | Modify | `CLAUDE.md` — musical math row in "Load These Docs" table | | Modify | `README.md` — current project state, iOS, demos, test count | | Modify | `LYREBIRD_START_HERE.md` — (existing; no change) | | Modify | `Sources/Lyrebird/Lyrebird.docc/GettingStarted.md` — workspace-first path, iOS notes, CLI scaffold path | | Modify | `Sources/Lyrebird/Lyrebird.docc/ProjectSystem.md` — Bitbucket URL, local path override note | | Modify | `Sources/LyrebirdCLI/ProjectScaffolder.swift` — Bitbucket repo URL in generated Package.swift | | Modify | `docs/tooling/project-system.md` — same URL update | | Modify | `docs/tooling/workflow.md` — same URL update | ### Tests added - `MusicMathTests` suite — 44 tests: known-value checks, round-trips for all conversion pairs, domain-error assertions (`hzToMidi(0)` → `-.infinity`, `ampToDb(-1)` → `NaN`, `powToDb(-1)` → `NaN`), boundary tests for `linToExp` and `equalPowerFade`, array overload smoke tests. **1369 tests at completion.** --- ## Phase 47 — Dynamics Generators Five dynamics processors: amplitude follower, pitch tracker, look-ahead limiter, compressor, expander. **New generators:** - `AmplitudeFollower.Audio / .Control` — envelope follower; asymmetric attack/release one-pole smoother - `FreqTracker.Audio` — YIN-based monophonic pitch tracker; 2-channel output (freq Hz + confidence 0..1) - `LookAheadLimiter.Audio` — true look-ahead limiter; no overshoot; introduces `lookAheadTime` latency - `Compressor.Audio / .Control` — feed-forward compressor; threshold/ratio/attack/release/kneeWidth/makeupGain - `Expander.Audio / .Control` — downward expander/gate; mirrors Compressor below threshold **Multi-channel:** all generators are single-channel in/out. Multi-channel use via MCE. For linked stereo compression, feed a shared `AmplitudeFollower` as side-chain. **Files:** - `Sources/Lyrebird/Generators/Dynamics/` (5 new files) - `docs/stdlib/dynamics.md` (new) - `Tests/LyrebirdTests/DynamicsTests.swift` (35 tests, 1369 → 1404) **Key architectural decisions:** - `LookAheadLimiter` uses pre-allocated monotonic deque (`_deque: [Int]`) for O(1) amortized sliding-window peak scan; deque capacity `max(2, _lookAheadSamples + 2)` - `FreqTracker` caps `fftSize` at 512 via `precondition` — O(halfSize²) YIN stays within RT callback budget at 44100 Hz / 512 block - YIN uses `- tau` index direction to keep all ring accesses in the past (algebraically symmetric, avoids future/stale reads) - `_rampTarget` initialized to `1.0` in all `Control` variants (matches `_prevGain = 1.0`; avoids first-block fade-from-silence) - `previousOutputValue` stores last signal sample (not gain coefficient) to satisfy `ControlGenerator` contract - `denormalsToZero()` on all one-pole smoother state after every write - `GeneratorEnum` conformance for `AmplitudeFollower`, `Compressor`, `Expander`; `FreqTracker` and `LookAheadLimiter` are Audio-only --- ## Phase 48 — ChannelSelect: Inline Channel Extraction **Tests at completion:** 1420 All `AudioGenerator` and `ControlGenerator` instances now support a `[n]` subscript and `.channel(n)` method returning a `ChannelSelect.Audio` or `ChannelSelect.Control` that extracts one channel from the source's multi-channel output. No bus routing required. **New type:** `ChannelSelect` (caseless enum namespace, `_Base`/`Audio`/`Control` pattern, `GeneratorEnum` conformance). `floatValue` uses `blockSize` count to avoid priming the fan-out cache with a 1-sample result. **Named aliases** (sugar over `self[n]`): - `Pan2`: `.left` (ch 0), `.right` (ch 1) - `Pan4`: `.frontLeft/frontRight/rearRight/rearLeft` (ch 0–3) - `FreqTracker`: `.freq` (ch 0), `.confidence` (ch 1) **`GeneratorArray`**: gets its own explicit `subscript(_ n: Int) -> ChannelSelect.Audio` (conforms to `Generator` not `AudioGenerator`, so the protocol extension doesn't reach it). **Key design decisions:** - Out-of-range `[n]` returns silence — no crash — because source channel count is a build-time property that can legitimately mismatch (e.g. wrapping a mono source) - Fan-out correctness free: `pan[0]` and `pan[1]` share one `Pan2` ref; segment-serial cache ensures one evaluation per segment - `floatValue` must use `blockSize` count (not `count: 1`) to avoid stale tail bug where the fan-out cache is primed with only sample [0] filled --- ## Phase 49 — Bus Allocator Language-side `AudioBus` / `ControlBus` value types backed by a `BusAllocator` on `SynthesisEngine`. Lets users request named bus objects (index + channel count) instead of managing raw integers. **New file:** `Sources/Lyrebird/Buses/BusAllocator.swift` **Modified:** `Sources/Lyrebird/Engine/SynthesisEngine.swift`, `Sources/Lyrebird/Generators/In.swift`, `Sources/Lyrebird/Generators/Out.swift` **New types:** ```swift public struct AudioBus { public let index: Int; public let channelCount: Int } public struct ControlBus { public let index: Int } ``` `AudioBus` and `ControlBus` are plain value types — no `ValidGeneratorInput` conformance (removed during review to prevent accidental RT allocation via the protocol path). **Allocator API (on `SynthesisEngine`):** ```swift public let busAllocator: BusAllocator // BusAllocator (NSLock-protected, language-side only): func allocateAudioBus(channelCount: Int) throws -> AudioBus func releaseAudioBus(_ bus: AudioBus) func allocateControlBus() throws -> ControlBus func releaseControlBus(_ bus: ControlBus) ``` **Key design decisions:** - Hardware buses (0..= 1)` + `guard channelCount <= n` prevent OOB before the loop - Double-free detected by `assert(!freeList[i])` in both audio and control release paths - `Out._Base` gains `_maxChannels: Int` (default `Int.max`); `Out.Audio(source:bus:AudioBus)` passes `bus.channelCount` so writes are clamped to the allocated block - `In.Audio.multi(bus: AudioBus) -> GeneratorArray` bridges multi-channel allocations **Tests (`Tests/LyrebirdTests/BusAllocatorTests.swift`):** 14 tests — allocate/release roundtrip, contiguous multi-channel, hardware bus pre-reservation, no-free-bus errors, In.Audio/In.Control/Out.Audio/Out.Control convenience inits, Out.Audio channel-clamp prevents adjacent-bus write, Out.Control write path, multi-channel GeneratorArray via multi(bus:) --- ## Phase 49b — In.Audio / In.Control Multi-Channel Static multi-channel reads for `In.Audio` and `In.Control`. Channel count fixed at init — no RT allocation. `In.Audio(bus: AudioBus)` now propagates `bus.channelCount` automatically. **Modified:** `Sources/Lyrebird/Generators/In.swift`, `Tests/LyrebirdTests/InGeneratorTests.swift` **API:** ```swift // Static channel count — N consecutive buses, N-channel [[LyrebirdFloat]] output In.Audio(bus: 4, channels: 3) // reads audioBuses[4], [5], [6] In.Control(bus: 10, channels: 2) // reads controlBuses[10] and [11]; independent ramps // AudioBus convenience — channels comes from allocation let stereo = try engine.busAllocator.allocateAudioBus(channelCount: 2) In.Audio(bus: stereo) // equivalent to In.Audio(bus: stereo.index, channels: 2) ``` **Key design decisions:** - `_Base.init(bus:channels:)` pre-allocates `channels`-row `_result` at init; `_computeSamples` only writes into existing rows — zero RT allocation - `In.Control` gains `_previousOutputValues: [LyrebirdFloat]` (one entry per channel); `previousOutputValue` computed property proxies index 0 to satisfy `ControlGenerator` protocol - `floatValue` always returns channel 0 (bus index) for both `In.Audio` and `In.Control` — consistent with single-channel behaviour - OOB channel bus index (bus + ch >= numBuses) breaks the inner loop silently rather than crashing — matches existing guard-let style in Lyrebird **Tests (`Tests/LyrebirdTests/InGeneratorTests.swift`):** 10 new tests — `In.Audio` multi-channel count, consecutive bus reads, single-channel default unchanged, `floatValue` channel-0, `AudioBus` convenience propagates channelCount; `In.Control` multi-channel count, consecutive bus ramps, per-channel independent ramp state, `previousOutputValue` proxies channel 0, single-channel default unchanged --- ## Phase 51 — DiskIn / DiskOut ✓ COMPLETE Streaming soundfile generators. Disk I/O runs on a background `DispatchQueue`; RT thread reads/writes a pre-allocated ring buffer. Mirrors SuperCollider's `DiskIn` / `DiskOut` and `VDiskIn`. **New files:** `Sources/Lyrebird/Generators/DiskIn.swift`, `Sources/Lyrebird/Generators/DiskOut.swift` **Dependencies:** `AudioToolbox` (`ExtAudioFile` — already used in `NRTDriver`), `SPSCQueue` (existing) ### DiskIn.Audio Double-buffer strategy — two halves, each `bufferFrames` frames × `channelCount`. All memory pre-allocated in `init`. - Background queue fills inactive half via `ExtAudioFileRead` + deinterleave - RT reads active half; at half-boundary, swaps halves and posts refill to SPSC queue - SR mismatch handled transparently by `ExtAudioFile` client format - BG wakeup via 500 µs Thread.sleep polling — DispatchSemaphore.signal() on RT thread causes kernel trap; replaced with lock-free SPSC + poll - deinit deadlock fix: `deinit` cannot call `_backgroundQueue.sync {}` (may run on BG thread when BG releases the last guard-let strong reference); instead sets `_stopped = true` and disposes directly — safe because BG's current iteration is complete before deinit can start - RT sets `_stopped = true` on EOF to end BG polling promptly **Init:** ```swift DiskIn.Audio( url: URL, channelCount: Int, sampleRate: Double = 48000, rate: any ValidGeneratorInput = 1.0 as LyrebirdFloat, // 0.1–4.0, forward only loop: Bool = false, doneAction: DoneAction = .nothing, bufferFrames: Int = 8192 ) ``` ### DiskOut.Audio Single circular ring buffer, `bufferFrames × channelCount`, pre-allocated in `init`. - RT writes frames into ring buffer, BG drains via `ExtAudioFileWrite` - 500 µs poll (same reasoning as DiskIn — no RT semaphore signal) - `writeError: Bool` public property surfaces `ExtAudioFileWrite` failures after `close()` - `close()` flushes and disposes; `deinit` is best-effort **Init:** ```swift DiskOut.Audio( source: any ValidGeneratorInput, channelCount: Int, url: URL, sampleRate: Double = 48000, format: DiskOutFormat = .aiff, // .aiff / .wav bufferFrames: Int = 8192 ) ``` **Tests (`Tests/LyrebirdTests/DiskInOutTests.swift`):** 9 tests — DiskIn reads DC signal, stereo channels, loop wrap, EOF freeNode flag, multi-buffer boundary crossing; DiskOut write + DiskIn read-back, stereo round-trip, two concurrent DiskIn instances, close() idempotent. --- ## Phase 52 — Math Generators: Waveshaping, Mapping, Unary/Binary ✓ COMPLETE Extended `MathGenerators.swift` with 23 new generators (46 variants including `.Audio` + `.Control`), all following the enum-namespace pattern (`public enum Foo { class _Base; final class Audio; final class Control }`). ### Waveshaping + Clipping (8 generators) | Generator | Operation | |-----------|-----------| | `Tanh.Audio/Control` | tanh(signal) — soft saturation | | `Pow.Audio/Control` | pow(signal, exp) | | `Clip.Audio/Control` | hard clip to [lo, hi] | | `Fold.Audio/Control` | mirror-fold at boundaries, O(1) closed-form via double-range wrap | | `Wrap.Audio/Control` | fmod-based wrap into [lo, hi) | | `SoftClip.Audio/Control` | tanh(signal × drive) / tanh(drive) | | `LinLin.Audio/Control` | linear → linear range map | | `LinExp.Audio/Control` | linear → exponential range map (outLo > 0) | ### Renamed + New Mapping Generators - `RangeGenerator` → **`BipolarMappingGenerator`** (maps [-1,1] → [low, high]) - **`UnipolarMappingGenerator`** (new): maps [0,1] → [low, high] ### Unary Math Generators (9 generators) | Generator | Operation | |-----------|-----------| | `Abs.Audio/Control` | \|signal\| | | `Sign.Audio/Control` | -1 / 0 / +1 | | `Floor.Audio/Control` | ⌊signal⌋ | | `Ceil.Audio/Control` | ⌈signal⌉ | | `Round.Audio/Control` | nearest integer, half away from zero | | `Sqrt.Audio/Control` | √signal (NaN for negative) | | `Reciprocal.Audio/Control` | 1/signal (±Inf for zero) | | `Log.Audio/Control` | ln(signal) | | `Exp.Audio/Control` | e^signal | ### Binary Math Generators (2 generators) | Generator | Operation | |-----------|-----------| | `Min.Audio/Control` | element-wise minimum of two signals | | `Max.Audio/Control` | element-wise maximum of two signals | ### Mapping Quartet — Exponential Input/Output (2 generators) | Generator | Input space | Output space | Precondition | |-----------|------------|-------------|--------------| | `ExpLin.Audio/Control` | exponential | linear | inLo > 0 | | `ExpExp.Audio/Control` | exponential | exponential | inLo > 0, outLo > 0 | Completes the SC mapping quartet alongside existing `LinLin` + `LinExp`. **Implementation notes:** - All `.Control` variants interpolate a ramp from `previousOutputValue` → target over `count` samples; last sample equals target exactly - `Fold._fold()` / `Wrap._wrap()` static helpers shared between Audio and Control to avoid duplication - ExpLin formula: `t = log(signal/inLo) / log(inHi/inLo); out = outLo + t*(outHi-outLo)` - ExpExp formula: `t = log(signal/inLo) / log(inHi/inLo); out = outLo * exp(t * log(outHi/outLo))` - All trig/math uses explicit module prefix (`Foundation.pow`, `Foundation.log`, `Swift.abs`, etc.) **Tests (`Tests/LyrebirdTests/MathGeneratorTests.swift`):** 69 new tests — deterministic Audio output, Control ramp reaches target at last sample, sub-block count correctness; geometric midpoint precision via `sqrt(lo*hi)` for LinExp/ExpLin tests. **Test count:** 1472 → **1547** (+75 tests including existing StdlibGeneratorTests additions for BipolarMappingGenerator + UnipolarMappingGenerator). **Docs updated:** `docs/stdlib/generators.md` (waveshaping, unary, binary, mapping quartet sections), `Sources/Lyrebird/Lyrebird.docc/Generators/MathAndArithmetic.md` (complete rewrite), `Sources/Lyrebird/Generators/GENERATORS.md` (math/utility naming table). --- ## Phase 46 — NRTDriver Soundfile Input ✓ COMPLETE Feed an audio file into the NRT engine as if it were live microphone input. Useful for offline processing chains (spectral analysis, filtering, re-synthesis of existing recordings) without requiring hardware. **New API:** ```swift NRTDriver(outputURL: URL, duration: Double, inputURL: URL? = nil, inputStartOffset: Double = 0.0) ``` `inputURL` defaults to `nil` — fully backward-compatible. `inputStartOffset` is in seconds. **Implementation (all changes in `Sources/Lyrebird/AudioDrivers/NRTDriver.swift`):** - Add `inputURL`, `inputStartOffset` stored properties - `setup()`: open `ExtAudioFileRef`, query file channel count (cap at `engine.numInputChannels`), set Float32 interleaved client format, seek to offset, pre-allocate interleaved read buffer (`blockSize × channelCount Float`) and per-channel staging buffers (`[[Float]]`) - Render loop: zero staging buffers, `ExtAudioFileRead` into interleaved buffer, deinterleave to staging, pass staging as `inputSamples`. EOF → remaining frames stay zero (staging zeroed before each read). - `defer` in `start()`: dispose input `ExtAudioFileRef` alongside output file - New error cases: `cannotOpenInputFile(OSStatus)`, `cannotSeekInputFile(OSStatus)`, `inputReadFailed(OSStatus)` **Key constraints:** - No allocation in render loop — all buffers pre-allocated in `setup()` - `ExtAudioFile` client format handles sample-rate conversion transparently if file SR ≠ engine SR - Channel count = `min(fileChannelCount, engine.numInputChannels)`; extra input buses stay zero **Tests (`Tests/LyrebirdTests/NRTDriverTests.swift`):** 10 tests covering stereo input, mono input, start offset, EOF pad-with-zeros, nil input backward compat. --- ## Phase 50 — Group Semantics + Node Positioning ✓ COMPLETE Extends `Group` and `Synthesizer` with release/free lifecycle semantics and flexible node insertion positions. Mirrors SuperCollider's `group.release`, `group.free`, `addBefore`, `addAfter`. **Modified:** `Sources/Lyrebird/NodeTree/Group.swift`, `Sources/Lyrebird/Synthesizer/Synthesizer.swift`, `Sources/Lyrebird/Engine/SynthesisEngine.swift`, `Sources/Lyrebird/Engine/ScheduledEvent.swift`, `Sources/Lyrebird/NodeTree/NodePosition.swift` (new file) ### Synthesizer.release() and Synthesizer.free() Added to `Synthesizer` protocol (language-side; not RT-called directly): ```swift func release(engine: SynthesisEngine) throws // set gate → 0; throws SynthesizerError.noGate if unsupported func free(engine: SynthesisEngine) // immediate kill — posts freeNode event ``` Protocol extension provides defaults: `release()` throws `.noGate`; `free()` posts engine remove event. Synthesizers with `EnvelopeGen` implement `release()` by posting a parameter-set event (`gate = 0.0`). ### Group lifecycle `Group.count` → `Atomic` (macOS 15 `Synchronization.Atomic`) so language-side timers can safely observe without racing the RT mutation path. **`Group.release(engine:)`** — language-side cascade: 1. Snapshot children list (language copy of identities, not RT list) 2. For each child: `try child.release(engine:)`. If throws `.noGate`, calls `child.free(engine:)` immediately 3. Starts a 0.1 s `DispatchSourceTimer` reading `group.count` atomically 4. When count == 0: cancels timer, calls `group.free(engine:)` on itself **`Group.free(engine:)`** — posts `.groupFree` scheduled event. RT `applyEvent`: - Walks group's linked list; enqueues each child `PreparedNode` and retained synth ref to `freeQueue` - Removes group from its own parent; enqueues group's node to `freeQueue` ### Node Positioning **`NodePosition` enum:** ```swift public enum NodePosition { case head(of: Group) case tail(of: Group) // default (current behaviour) case before(any Synthesizer) case after(any Synthesizer) } ``` `SynthesisEngine.add(_ synth: Synthesizer, position: NodePosition = .tail(of: rootGroup))` — extends existing add API. New internal `Group` methods (RT-thread, called from `applyEvent`): ```swift internal func addBefore(_ node: PreparedNode, target: any Synthesizer) -> Bool internal func addAfter(_ node: PreparedNode, target: any Synthesizer) -> Bool ``` Linear O(n) search; returns false if target not found (engine logs warning, falls back to tail insertion). New `ScheduledEvent` cases: `.addNode(PreparedNode, NodePosition)`, `.groupFree(Group, parentGroup: Group?)`. **Tests (`Tests/LyrebirdTests/GroupSemanticsTests.swift`):** 19 tests — release cascades gate=0 to EnvelopeGen children, non-gate synths freed immediately, group self-frees when empty, free() kills all children immediately, addBefore/addAfter place nodes correctly, nested group release recurses, count Atomic reads correctly across threads, fallback to tail when target not found, idempotent release. **Docs:** `docs/protocols/node-tree.md` updated with new lifecycle methods, position enum, and usage examples. --- ## Phase 53 — FreeVerb Stereo reverb generator implementing the Freeverb algorithm (Jezar at Dreampoint, public domain). Mono input → stereo output. All delay-line buffers pre-allocated in `init`. **New file:** `Sources/Lyrebird/Generators/Reverb/FreeVerb.swift` **Architecture:** 8 parallel filtered-feedback comb filters → 4 series allpass filters, per channel. L/R detuned by `spread` samples. Standard Freeverb comb delay sizes (L): `1116, 1188, 1277, 1356, 1422, 1491, 1557, 1617` Standard allpass sizes: `556, 441, 341, 225` R sizes = L + `spread` (default 23) Comb LP state update (Jezar): `filterState = out × damp2 + prevState × damp1` where `damp1 = damping × 0.4`, `damp2 = 1 − damp1`. All tuning constants extracted to named module-level `let` constants (`freeVerbFeedbackMin`, `freeVerbFeedbackRange`, `freeVerbDampingScale`, `freeVerbFixedGain`, `freeVerbAllpassFeedback`). Parameters all `ValidGeneratorInput`; read once per block. `sampleRate` param scales delay buffers from 44100 Hz reference. `spread` fixed at init. **Channel aliases:** `.left` / `.right` (same pattern as `Pan2`). **Tests (`Tests/LyrebirdTests/FreeVerbTests.swift`):** 8 tests — stereo output shape, dry pass-through (mix=0), wet differs from dry (mix=1), impulse response decays, L/R distinct via spread, roomSize affects decay rate, deterministic first-echo pin (block-2 index 92 == 0.015 with roomSize=0/damping=0), channel alias correctness. **Docs:** `docs/stdlib/generators.md` — new Reverb section. `Lyrebird.docc/Generators/Reverbs.md` — new DocC topic wired into `Lyrebird.md` nav. --- ## Phase 54 — GVerb Stereo reverb generator implementing a faithful port of SuperCollider's `GVerb` UGen (Griesinger algorithm). Initially implemented with a wrong comb-filter topology; fully rewritten to match SC's FDN+Hadamard architecture plus `dryLevel` param addition. **New file:** `Sources/Lyrebird/Generators/Reverb/GVerb.swift` **Architecture (matching SC `GVerb_next` exactly):** 1. Input one-pole LP damper (`inputBandwidth` controls passthrough; damping = `1 - inputBandwidth`) 2. Pre-tap Schroeder allpass diffuser (`ldifs[0]`, shared L/R) 3. 4-tap fixed tap-delay (44000 samples), early reflections `u[j]` read with exponential gains 4. Diffused signal written to tap delay each sample 5. 4 FDN delay lines read with negative gains + one-pole LP damping → `d[j]` 6. Alternating-sign mix: `±(tail*d[j] + early*u[j])` + `x * earlyLevel` 7. Hadamard FDN feedback matrix (`f = H·d/2`) 8. `u[j] + f[j]` written to FDN delay lines 9. 3-stage post-sum allpass diffusion per side (asymmetric L/R sizes for stereo separation) 10. `lOut = lsum + x * dryLevel; rOut = rsum + x * dryLevel` (dry bypasses all diffusion) **Init:** ```swift GVerb( source: any ValidGeneratorInput, roomSize: any ValidGeneratorInput = 30.0, // meters, clamped [1, 300] reverbTime: any ValidGeneratorInput = 5.0, // T60 seconds damping: any ValidGeneratorInput = 0.5, // FDN HF absorption [0, 1] inputBandwidth: any ValidGeneratorInput = 0.75, // input LP bandwidth [0, 1] spread: Double = 15.0, // init-time only; diffuser size scale earlyLevel: any ValidGeneratorInput = 0.4, // early tap mix level tailLevel: any ValidGeneratorInput = 0.5, // FDN late tail mix level dryLevel: any ValidGeneratorInput = 0.0, // dry bypass added after diffusion sampleRate: Double = gverbReferenceSampleRate ) ``` **Key constraints:** - FDN buffers pre-allocated to `max(1, Int(300/340 * sampleRate) + 1000)` each — no RT alloc. - Tap delays clamped to `[gverbMinTapDelaySamples, gverbTapDelaySize - 1]` to prevent out-of-bounds at sample rates above 44.1 kHz. - `spread` is init-time only (matches SC: `// spread can only be set at inittime`); used to compute asymmetric L/R post-sum diffuser sizes. - All SC-sourced domain constants (diffuser coefficients 0.75/0.625, size bases 210/159/562/410, spread multipliers, `gverbMinTapDelaySamples = 5`) promoted to named `private let` constants. Stereo output (2-channel `_result`). No Control variant. **Tests (`Tests/LyrebirdTests/GVerbTests.swift`):** 9 tests — stereo output shape, zero levels produce silence, impulse RT60 within expected range, roomSize change no crash, early and tail levels independently audible, stereo L/R distinct (asymmetric diffusers), parameters update mid-stream, channel aliases match subscripts, dryLevel passes direct signal at unity. **Docs:** `docs/stdlib/generators.md` — GVerb entry updated to reflect correct architecture. --- ## Phase 55 — Noise Family Expansion (Spectral-Colour + Event) ✓ COMPLETE Six new noise generators (Audio + Control each) plus `xorshift64NextRaw` PRNG split. - `xorshift64NextRaw(_:) -> UInt64` factored out of `xorshift64Next` (used by GrayNoise for bit-position picking) - `PinkNoise` — Paul Kellet 7-stage IIR pink filter (~−3 dB/oct); `denormalsToZero` on b0–b6 after each block; `pinkFilterCoeffB5 = 0.0168980` (positive, matches reference formula) - `BrownNoise` — random walk; `brownNoiseStepSize = 0.125` (SC-matching); reflected at ±1 - `GrayNoise` — stochastic Gray-code counter; `Int32(bitPattern: UInt32(1) << bitPos)` required for bitPos=31 - `ClipNoise` — sign of xorshift output (±1.0 only); stateless beyond rngState - `Dust` — Poisson-like positive impulses (`density` Hz); `dustUnipolarScale` shared with Dust2 - `Dust2` — bipolar version of Dust; `dust2BipolarScale/Offset` named constants All full-bandwidth Control variants (Pink/Brown/Gray/Clip/Dust/Dust2) override `calculatedSamples` with the canonical bypass guard to advance state once per audio block. 128 new tests total (1619 → 1747 across both phases). --- ## Phase 56 — Noise Family Expansion (Chaotic + Smooth) ✓ COMPLETE Two more noise generators using less common algorithms. - `Crackle` — SC's 2-pole chaotic map: `y[n] = |y[n-1] × chaos − y[n-2] − 0.05|`, bipolarised to [-1, 1]; deterministic (no seed); `Crackle.Control` overrides `calculatedSamples` to advance map once per audio block - `LFCurveNoise` — SC's `LFNoise2`; parabolic interpolation `(a*t + b)*t + y1`; mirrors `LFLineNoise` structure exactly; `LFCurveNoise.Audio.floatValue` routes through `calculatedSamples` (fan-out cache) **Review findings fixed:** Crackle.Control sub-block rate error (bypass added), LFCurveNoise.Audio.floatValue fan-out cache bypass (routed through calculatedSamples), PinkNoise.Control unique seed constant (0x9696...), PinkNoise b5 sign (pinkFilterCoeffB5 positive). --- ### Phase 59 — TimedDemand Generators (Synthesis Side) **Goal:** Synthesis-side counterpart to Phase 58. RT-safe. Trigger-based S&H (like existing `Demand.Audio/Control`) but passes elapsed seconds + call counter to the demand source, enabling time-evolving distributions and Brownian walks on the synthesis side. **`TimedDemandGenerator` protocol** (extends `DemandGenerator` for backwards compat): ```swift public protocol TimedDemandGenerator: DemandGenerator { func nextValue(elapsedSeconds: Double, counter: Int) -> Double? } extension TimedDemandGenerator { public func nextValue() -> Double? { nextValue(elapsedSeconds: 0, counter: 0) } } ``` **`TimedDemand.Audio` / `TimedDemand.Control`** — mirror `Demand.Audio/Control`, add: - `_startSampleTime: Int64 = -1` sentinel (unset) - `_counter: Int = 0` - First trigger edge: capture `graph.engine.currentTime + Int64(i)` (sample-accurate) - Each trigger: `elapsed = Double((currentTime + Int64(i)) - _startSampleTime) / sampleRate`; call `demand.nextValue(elapsedSeconds: elapsed, counter: _counter)`, increment `_counter` - `reset()`: clear `_heldValue=0`, `_startSampleTime=-1`, `_counter=0`, call `demand.reset()` **`RTTemporalParameter`** — Sendable RT-safe subset of `TemporalParameter`: `.value(Double)` and `.envelope(Envelope)` only (no closure). Used by `DTemporalTendency` and `DTemporalBrownian`. **`DTemporalTendency`** — all 16 `DistributionKind` variants with `RTTemporalParameter` parX/parY/parA?/parB?; uses `xorshift64NextRaw`; no heap allocation; PRNG state not restored on `reset()` (intentional — avoids repetition artifacts). **`DTemporalBrownian`** — RT random walk; `lo`/`hi`/`stepSize` as `RTTemporalParameter`; `_current: Double` state; auto-centres to midpoint on first pull when `start` not provided; clamps to `[min(lo,hi), max(lo,hi)]` (handles inverted bounds). **Review findings fixed:** intra-block trigger start-time used block-start `currentTime` instead of `currentTime + Int64(i)` — corrected in both Audio and Control paths; added `deterministicOutputWithMatchingSeeds` tests for `DTemporalTendency` and `DTemporalBrownian` (two instances, same seed, bit-exact identical sequences); removed unused `callCount` variable. **Files:** ``` Sources/Lyrebird/Generators/TemporalDemand/ RTTemporalParameter.swift TimedDemandGenerator.swift TimedDemand.swift // Audio + Control DTemporalTendency.swift DTemporalBrownian.swift Tests/LyrebirdTests/TimedDemandTests.swift ``` --- ## Phase 60 — Distribution Preview (LyrebirdScatterView + Sample Collection Helpers) **Goal:** Static Canvas-based scatter plot view for `[Double]` arrays + language-side batch sample collection on `TemporalStream`, `DemandGenerator`, and `TimedDemandGenerator`. **Tests:** 1959 (9 new in `Phase60ScatterCollectionTests.swift`) **New:** - `Sources/LyrebirdUI/LyrebirdScatterView.swift` — Canvas scatter plot; `yRange` auto or manual; zero-line guide; degenerate-range guard in `_yFor`; reuses `_envelopeYBounds` - `Tests/LyrebirdTests/Phase60ScatterCollectionTests.swift` — 9 tests **Modified:** - `Sources/Lyrebird/TemporalStream/TemporalStream.swift` — `collect(_:)` language-side batch pull - `Sources/Lyrebird/Generators/Demand/DemandGenerator.swift` — `samples(count:)` protocol extension - `Sources/Lyrebird/Generators/TemporalDemand/TimedDemandGenerator.swift` — `samples(count:timespan:)` distributes elapsed time evenly; removed misleading "shadows" doc claim - `Sources/Lyrebird/Lyrebird.docc/TemporalDemand.md` — "Previewing Distributions" section - `Sources/LyrebirdUI/LyrebirdUI.docc/LyrebirdUI.md` — Visualization topic group with `LyrebirdScatterView` **Key decision:** `_yFor` guard (`guard yMax > yMin else { return height / 2 }`) prevents division-by-zero from degenerate user-supplied `yRange` (equal bounds). Auto-path via `_envelopeYBounds` was already protected by `minimumLevelRange = 1e-6`. --- ## Phase 61 — PitchShift.Audio (Granular) **Goal:** Audio-rate granular pitch shifter on live input. Inherits `GranularBase` (pool + PRNG). Follows `InputGrain` pattern but auto-manages grain density and read-head position to maintain time while shifting pitch. ### Algorithm - Circular capture buffer (`lyrebirdInputGrainSize`, ≈3 s at 44.1 kHz) - Grains triggered at fixed `hopSamples = windowSamples / overlap` interval - Each grain reads at `pitchRatio` speed (phaseInc = pitchRatio) for `windowSamples` output samples - `pitchRatio` clamped to `[0.25, 4.0]` at RT; init-time precondition uses `lyrebirdMaxSupportedSampleRate` (192 kHz) to bound worst-case read span; runtime precondition in `_computeBlock` guards actual sampleRate - Hanning window from shared table; `timeDispersion` and `pitchDispersion` via xorshift64 PRNG ### New files | File | Contents | |------|----------| | `Sources/Lyrebird/Generators/Granular/PitchShift.swift` | `PitchShift._Base` + `PitchShift.Audio` | | `Tests/LyrebirdTests/PitchShiftTests.swift` | 10 tests (in `PitchShift` suite) | | `Sources/Lyrebird/Math/LyrebirdConstants.swift` | `lyrebirdMaxSupportedSampleRate = 192_000.0` added | ### API ```swift PitchShift.Audio( input: signal, // ValidGeneratorInput — live audio pitchRatio: 1.5, // ValidGeneratorInput — 1.0=no shift; clamped [0.25, 4.0] windowSize: 0.1, // Double — grain duration in seconds overlap: 4, // Int — simultaneous grains pitchDispersion: 0.0, // ValidGeneratorInput — per-grain random pitch spread (ratio) timeDispersion: 0.0, // ValidGeneratorInput — per-grain timing jitter (seconds) mul: 1.0, add: 0.0 ) ``` Output: mono (1 channel). Use MCE for stereo / multi-channel. **Key decision:** Mono out avoids per-grain trig cost (no equal-power pan computation); MCE handles multi-channel at the language level. Pitch ratio is polled once per block (not per-grain), consistent with other ValidGeneratorInput sources in granular generators. **1978 tests at completion.** --- ## Phase 62 — SpectralPitchShift (Phase Vocoder) **Goal:** Phase-vocoder pitch shifter as a `SpectralProcessor`, slotting into the existing `FFTAnalysis → [processors] → IFFTSynthesis` chain. ### Algorithm Per hop in `process(spectral:)`: 1. Load `pitchRatio` from `Atomic` with `.acquiring` ordering 2. Zero `_shiftedMag` scratch via `vDSP_vclr` 3. For each input bin k: compute instantaneous true-frequency bin via phase derivative; `deviation = (delta − expectedDelta).remainder(dividingBy: 2π)` — full IEEE 754 remainder handles large `expectedDelta` at high k 4. Remap magnitude to output bin `m = round(k × ratio)`; discard if `m ∉ [1, halfSize)` 5. For each output bin m: advance `_synthPhase[m]` by `trueFreqBin[k] × ratio × 2π × hop/fft`; wrap with `.remainder(dividingBy: 2π)` to handle multi-revolution steps at high bins 6. Write `_shiftedMag` and `_synthPhase` back; zero DC and Nyquist ### New files | File | Contents | |------|----------| | `Sources/Lyrebird/Generators/Spectral/SpectralPitchShift.swift` | `SpectralPitchShift: SpectralProcessor` | | `Tests/LyrebirdTests/PitchShiftTests.swift` | 9 tests (in `SpectralPitchShift` suite) | ### API ```swift let ps = SpectralPitchShift(fftSize: 2048, hopSize: 512, pitchRatio: 1.5) ps.pitchRatio = 2.0 // thread-safe update via Atomic (.releasing store) let analysis = FFTAnalysis(in: signal, fftSize: 2048, hopSize: 512, processors: [ps]) let output = IFFTSynthesis(spectral: analysis.spectralBuffer, fftSize: 2048, hopSize: 512) ``` **Key decision:** `deviation` and synthesis phase step both use `.remainder(dividingBy: 2π)` (IEEE 754 remainder) rather than a single `+/- 2π` conditional — single-wrap fails for `expectedDelta = 2π × k × hop/fft` at high bin indices (can exceed 1000+ radians at k≈1000 with default settings). `pitchRatio` load uses `.acquiring` ordering to correctly pair with the `.releasing` store from non-RT thread. **1978 tests at completion.** --- ### Phase 63 — Granular Modulation Upgrade + TimeStretch **63a — Granular ValidGeneratorInput promotion** Promote key per-grain-trigger parameters from `@LiveParam` to `ValidGeneratorInput` init arguments across all four buffer granular generators so they can be driven by oscillators, envelopes, and LFOs. | Generator | Parameters promoted | |-----------|---------------------| | `BufferGrain` | `position`, `duration`, `amp`, `pan`, `positionSpread`; `rate` renamed → `pitchRatio`; add `pitchDispersion` | | `InputGrain` | `position`, `duration`, `amp`, `pan`, `positionSpread`; `rate` renamed → `pitchRatio`; add `pitchDispersion` | | `SineGrain` | `duration`, `pan` | | `FMGrain` | `duration`, `pan` | `rateSpread` / `panSpread` retained as `@LiveParam` (spread is inherently random; no generator-driven benefit). **63b — TimeStretch.Audio** New buffer-based granular generator with a generator-driveable read pointer (`pos: any ValidGeneratorInput`). Sweeping `pos` with a Phasor produces time-stretching; `pitchRatio` independently controls grain playback speed — decoupling time position from pitch. Inspired by Josh's SC Warp1 UGen. New file: `Sources/Lyrebird/Generators/Granular/TimeStretch.swift` ```swift TimeStretch.Audio( buffer: LyrebirdBuffer, pos: any ValidGeneratorInput = 0.0, // normalized [0,1] read pointer pitchRatio: any ValidGeneratorInput = 1.0, // grain phaseInc multiplier windowSize: Double = 0.1, overlap: Int = 4, posDispersion: any ValidGeneratorInput = 0.0, pitchDispersion: any ValidGeneratorInput = 0.0, window: LyrebirdBuffer? = nil, loop: Bool = true, interpolation: TableInterpolation = .linear, seed: UInt64? = nil, mul: any ValidGeneratorInput = 1.0, add: any ValidGeneratorInput = 0.0 ) // @LiveParam: pan, panSpread, amp ``` Fixed-hop scheduling (`windowSamples / overlap`), stereo output, same `GranularBase` inheritance as other granular generators. **Key decisions:** `pitchDispersion` stored as `ValidGeneratorInput` (generator-driven random pitch spread) coexists with `rateSpread @LiveParam` (main-thread random spread) — additive at grain trigger time. `_hopCounter` initialised to `timeStretchInitialHopCounter` (named constant replacing `Int.max/2`) so first grain fires on sample 0. Scheduling state (`_windowSizeSamples`, `_hopSamples`) computed lazily on first block from actual `graph.engine.sampleRate` via `_schedulingReady` flag — avoids needing SR at init time. **1995 tests at completion.** --- ## Phase 64 — Spectral Frame Buffer Playback (PV_PlayBuf analogue) SuperCollider analogue: `PV_RecordBuf` + `PV_PlayBuf`. Adds spectral-domain buffer record and playback: capture polar FFT frames from any `FFTAnalysis` chain into a pre-allocated multi-frame buffer, then play them back at variable rate (phase-vocoder time-stretch/compress) or via a normalized position pointer for random access. ### New types #### `SpectralFrameBuffer` `Sources/Lyrebird/Spectral/SpectralFrameBuffer.swift` Pre-allocated multi-frame polar storage. `UnsafeMutablePointer` arrays; no CoW. Key API: - `framesWritten: Int` — atomic high-water mark; defaults to `frameCount`; updated by `SpectralRecordBuffer` after each hop. In loop mode, stays at `frameCount` once a full pass completes (via `_bufferFull` RT flag). - `interpolateMagnitudes(into:frameA:frameB:frac:)` — `vDSP_vintb` lerp; RT-safe - `interpolatePhases(into:frameA:frameB:frac:)` — shortest-path angular lerp; RT-safe; no accumulator drift - `phaseDelta(frameA:frameB:into:)` — principal-value inter-frame phase delta; RT-safe - `trimmed() -> SpectralFrameBuffer` — new buffer of `framesWritten` frames; precondition `framesWritten > 0` #### `.lbsf` FileIO `Sources/Lyrebird/Spectral/SpectralFrameBufferFileIO.swift` `write(to:)` uses `framesWritten` (not `frameCount`) in header and body — compact files from partial recordings. `load(url:)` reflects truncated reads in `_framesWritten`. Named constants for magic bytes (`lbsfMagic`) and header field offsets. Throwing `fh.write(contentsOf:)` propagates I/O errors. `SpectralFileError`: `cannotCreateFile`, `cannotOpenFile`, `invalidMagic`, `unsupportedVersion`. #### `SpectralRecordBuffer` `Sources/Lyrebird/Generators/Spectral/SpectralRecordBuffer.swift` Pass-through `SpectralProcessor`. `framesRecorded` is monotonically increasing. `_bufferFull` RT flag ensures `framesWritten` stays at `frameCount` throughout loop passes (never reverts to 0 on wrap). #### `SpectralPlayBuffer` `Sources/Lyrebird/Generators/Spectral/SpectralPlayBuffer.swift` Silent `AudioGenerator`. Phase-vocoder time-stretch playback. `startPos: Double = 0.0` init param; loop wraps back to `startPos` via `_startPos + (_playPos - _startPos).truncatingRemainder(dividingBy: span)`. Uses `framesWritten` as effective frame count so partially-recorded buffers play only valid content. #### `SpectralBufferRead` `Sources/Lyrebird/Generators/Spectral/SpectralBufferRead.swift` Silent `AudioGenerator`. Random-access position-pointer playback. `position: any ValidGeneratorInput` normalized `[0, 1]`. Reads stored analysis phases via `interpolatePhases` (shortest-path lerp, no accumulator). Position `1.0` maps to last *recorded* frame (`framesWritten − 1`). No drift on position jumps. ### Key design decisions - `_bufferFull` RT-only flag in `SpectralRecordBuffer` gates `framesWritten` updates: before first full pass, stores `_writePos`; after, stores `frameCount` regardless of where the write head is. This prevents `SpectralPlayBuffer`/`SpectralBufferRead` from computing `effectiveFrames = 0` on wrap. - `SpectralBufferRead` has no synthesis phase accumulator — uses `interpolatePhases` directly. Predictable for position jumps where accumulator drift would cause audible artifacts. - `write(to:)` uses `min(framesWritten, frameCount)` as the on-disk frame count, enabling compact storage of partial recordings without requiring `trimmed()` first. **2031 tests at completion.** --- ## Phase 65 — PlayBuf/RecordBuf Rename ✓ COMPLETE **Goal:** Rename `PlayBuf` → `PlayBuffer` and `RecordBuf` → `RecordBuffer` throughout the codebase for verbosity/clarity, matching the Lyrebird naming convention established with `SpectralBufferRead`. ### Changes - `Sources/Lyrebird/Generators/PlayBuf.swift` → `PlayBuffer.swift`; enum renamed `PlayBuffer`; all inner references updated; `@available(*, deprecated, renamed: "PlayBuffer") public typealias PlayBuf = PlayBuffer` appended - `Sources/Lyrebird/Generators/RecordBuf.swift` → `RecordBuffer.swift`; same treatment; deprecated `typealias RecordBuf = RecordBuffer` - `Tests/LyrebirdTests/PlayBufTests.swift` → `PlayBufferTests.swift`; `struct PlayBufferTests`; all `PlayBuffer.Audio`/`PlayBuffer.Control` calls updated - `Tests/LyrebirdTests/RecordBufTests.swift` → `RecordBufferTests.swift`; `struct RecordBufferTests`; `RecordBufferFixtureGen`; all calls updated - `Tests/LyrebirdTests/SpectralPlayBufTests.swift` — `struct SpectralPlayBufferTests` (struct name only; file kept as-is per convention) - Doc updates: `LyrebirdBuffer.swift`, `FreqTracker.swift`, `SpectralBufferRead.swift`, `BuiltInGenerators.md`, `NRTGuide.md`, `GeneratorProtocol.md`, `docs/stdlib/buffer-io-generators.md`, `docs/tooling/nrt-guide.md`, `docs/protocols/generator.md`, `docs/stdlib/generators.md`, `docs/stdlib/multichannel.md`, `~/.claude/agents/lyrebird_generator_agent.md` ### Notes - Deprecated typealiases provide backward compat — existing user code gets a fix-it but still compiles - `01-completed-working-order.md` references to Phase 29/29b retain old names as historical record (names were correct at time of implementation) **2031 tests at completion.** --- ## Phase 66 — Buffer Metadata + Duration Helpers **Goal:** Expose computed `duration` and `phasorFrequency` on both `LyrebirdBuffer` and `SpectralFrameBuffer` so callers can easily drive `Phasor`, `BufferRead`, `TimeStretch`, and `SpectralPlayBuffer` without manual arithmetic. ### LyrebirdBuffer additions ```swift /// Duration in seconds. `nil` when `sampleRate` is `nil` (manually-created buffers). public var duration: Double? { sampleRate.map { Double(count) / $0 } } /// Frequency to pass to `Phasor` to sweep position 0→1 in exactly one buffer duration. /// `nil` when `sampleRate` is `nil`. public var phasorFrequency: Double? { duration.map { 1.0 / $0 } } ``` ### SpectralFrameBuffer additions ```swift /// Duration of the recorded spectral data in seconds. /// Uses `framesWritten` (not `frameCount`) so partially-filled buffers report actual captured length. /// Returns `0` when `sampleRate == 0` (unknown). public var duration: Double { guard sampleRate > 0 else { return 0 } return Double(hopSize * framesWritten) / sampleRate } /// Frequency to drive a Phasor for `SpectralPlayBuffer` / `SpectralBufferRead` to sweep position /// 0→1 over the full recorded duration. Returns `nil` when `sampleRate == 0` or `framesWritten == 0`. public var phasorFrequency: Double? { let d = duration guard d > 0 else { return nil } return 1.0 / d } ``` **2040 tests at completion.** --- ## Phase 67 — BufferRead Generator ✓ COMPLETE **Goal:** New `BufferRead` generator for normalized-position `[0, 1]` random-access playback of `LyrebirdBuffer`. No internal play-head — position entirely external. ### What was built - `BufferRead.Audio` — audio-rate; samples position per-sample; outputs N channels matching `buffer.channelCount` - `BufferRead.Control` — block-rate; samples position once per block; linear ramp per channel; `calculatedSamples` bypass override; `_setupSubBlockBuffer(channels:)` in init - Both use `lyrebirdBufferRead(_:channel:phase:interpolation:loop:false)` for clamped interpolation - `MulAddSpec` applied to all channels at end of `_computeSamples` - `GeneratorEnum` conformance (`AudioType`/`ControlType`) - Added to `BuiltInGenerators.md` (Buffer Playback section + GeneratorEnum list) and `GENERATORS.md` (§12 Buffer/ index) ### Files - `Sources/Lyrebird/Generators/BufferRead.swift` — new - `Sources/Lyrebird/Generators/GENERATORS.md` — §12 added - `Sources/Lyrebird/Lyrebird.docc/BuiltInGenerators.md` — BufferRead added - `Tests/LyrebirdTests/BufferReadTests.swift` — 13 tests **2053 tests at completion.** --- ## Phase 68 — TimeStretch Multi-Channel + Remove Pan **Goal:** Make `TimeStretch.Audio` output N channels matching `buffer.channelCount` rather than hardcoded stereo. Remove `pan` and `panSpread` parameters (they belong on a separate spatial effect, not a time-stretcher). Stereo/multi-channel buffers are played back with channel relationships preserved. ### Design decisions **Why remove pan:** `TimeStretch` is a time-domain resynthesizer, not a spatial effect. Pan/panSpread make sense for granular synthesis where grains are scattered clouds (`BufferGrain`). A time-stretcher should preserve the buffer's original stereo/multi-channel relationship. Users who want spatial control can wrap `TimeStretch` in a `Pan2`/`PanN` downstream. **Channel count:** Determined at init from `buffer.channelCount`. `_result` pre-allocated to N rows. Each grain reads all N channels at the same phase position; the same windowed envelope and amplitude are applied to each channel independently. No panning math. ### `GrainState` changes `GrainState` currently stores `panGainL` / `panGainR`. These can be removed (or zeroed/ignored) since gain is now uniform across channels. `amp` remains. ### `_computeSamples` changes ```swift // Replace grainBufChannelCount constant with buffer.channelCount let numChannels = buffer.channelCount // Remove panBase / panSpreadVal reads // Remove panAngle / panGainL / panGainR computation when triggering grain // _grains[s].panGainL / .panGainR → remove // Per-grain accumulation: loop over channels for ch in 0..`. Bresenham/Euclidean distribution algorithm. Generates rumba clave E(3,8), Cinquillo E(5,8) with rotation, Bulgarian 7/8, and arbitrary Euclidean rhythms. Rotation parameter handles negative values via double-modulo. Edge cases: `steps < 1`, `pulses < 0`, `pulses > steps` all handled gracefully. **Markov** — `TemporalMarkov`: new `TemporalAlgorithm` alongside `TemporalTendency`/`TemporalBrownian`. Weighted state machine: each `State` holds a `TemporalParameter` value + `[Transition]` array. Cumulative weights pre-computed at init — `nextValue` is allocation-free. `pick == total` float edge case handled by `!picked` fallback to last transition. `initialState` clamped to valid range; empty-states guard prevents crash. Nested `State`/`Transition` types do not violate the one-public-type-per-file rule. 30 new tests: tresillo, E(5,8) bit pattern, Cinquillo rotation, alternation, exhaustion, reset, zero-weight exclusion, equal-weight all-states coverage, `TemporalParameter.closure` pass-through, `TemporalStream` integration. **2267 tests at completion.** --- ### Phase 73 — Jitter / Triggered Random Generators **Files added:** - `Sources/Lyrebird/Generators/Random/TriggeredRandom.swift` - `Sources/Lyrebird/Generators/Random/Jitter.swift` - `Tests/LyrebirdTests/TriggeredRandomTests.swift` - `Tests/LyrebirdTests/JitterTests.swift` **`TriggeredRandom.Control`** — holds a uniform random value in `[lo, hi]`. Fires a new sample on each ≤0→>0 trigger edge (first edge per audio block). Scans the full audio-rate trigger block for the crossing; `calculatedSamples` bypass ensures edge detection and PRNG draw happen exactly once per audio block. `_sampleUniform` from `DistributionSampling`. `fillRampedResult` ramp + mulAdd. Seed via `lyrebirdSeedXorshift64`. **`Jitter.Control`** — smoothed random walk around `center`. Each audio block: draws a bipolar step via `xorshift64Next` scaled by `amount * (1 - coeff)`, perturbs the smoother, applies one-pole lowpass toward center (`coeff = exp(-2π × speed × dt)`), clamps to `[center ± amount]`. `calculatedSamples` bypass prevents smoother from running N× per sub-block. Warm-up transient documented: smoother starts at 0.0 since `center` is a `ValidGeneratorInput` not evaluable at init time. Both generators intentionally omit `GeneratorEnum` — Control-rate only; no Audio variant would add meaningful resolution. **22 new tests** across both suites: rate, output count, fan-out cache, sub-block bypass, in-range output, held value between triggers, trigger edge semantics, deterministic seed, speed/amount response. **2289 tests at completion.** --- #### Phase 74 — Gendy Stochastic Synthesis Three Audio+Control variants after SC `Gendy1`/`Gendy2`/`Gendy3`. Stochastic waveform construction: per-cycle breakpoint update using Phase 57 distributions (all 16 DistributionKind cases via `gendySampleDist`). State machine holds amplitude and duration breakpoint arrays; updates stochastically on each segment crossing. - `Gendy1.Audio/Control` — linear interpolation; both amplitude and duration segments stochastic - `Gendy2.Audio/Control` — Catmull-Rom cubic interpolation for smoother waveforms; both amp and dur stochastic - `Gendy3.Audio/Control` — linear interpolation; stochastic amplitude only, duration fixed by `freq` param - `GendyHelpers.swift` — shared `gendySampleDist(_:param:rng:)` mapping all 16 DistributionKind cases to zero-centred bipolar steps - RT safety fix: `Gendy3.Control._computeSamples` clamps `_segPos` after `_segLen` update to prevent infinite loop when `freq` increases between blocks - `GeneratorEnum` conformance on all three; 61 new tests (deterministic seed, output range, non-silent, fan-out, sub-block bypass) **2364 tests at completion.** --- ## Phase 75 — Spectral Feature Extraction Postprocessors on `SpectralBuffer` output → scalar `Control`-rate values. Six new generators: - `SpectralCentroid.Control` — weighted mean frequency (brightness) in Hz: `Σ(k × mag[k]) / Σmag[k] × binHz` - `SpectralFlatness.Control` — geometric/arithmetic magnitude mean ratio in `[0,1]`; `log(0) = −∞` AM-GM collapse gives correct `0` for tonal (sparse) spectra - `SpectralSpread.Control` — magnitude-weighted frequency standard deviation in Hz (two-pass: centroid then variance) - `SpectralFlux.Control` — RMS of per-bin magnitude differences between consecutive frames; pre-allocated `_prevMag [Float]` buffer updated once per audio block; returns 0 on first frame - `SpectralEntropy.Control` — normalized Shannon entropy of magnitude spectrum in `[0,1]`; `1.0` = uniform (noise-like), `0.0` = tonal (single bin) - `SpectralRolloff.Control` — frequency below which `rolloffPercent` of total energy (squared magnitudes) falls; `rolloffPercent` is a `ValidGeneratorInput`, clamped to `[0,1]` All six generators are Control-only (no Audio variant, no `GeneratorEnum`). Each: - Overrides `calculatedSamples` to bypass the sub-block loop (spectral buffer written once per FFT hop, not per sub-block chunk) - Calls `_setupSubBlockBuffer()` in `init` - Uses `fillRampedResult` for output - Allocates no memory in `_computeSamples` 35 new tests covering silence, single-bin, equal-bin, and known-distribution cases for all six generators. **2399 tests at completion.** --- ## Phase 76 — State Variable Filter (SVF) Chamberlin / Zölzer SVF. One generator family with `SVF.Audio` and `SVF.Control` inner classes — 4-channel output from a single coefficient set: `[0]` = lowpass, `[1]` = highpass, `[2]` = bandpass, `[3]` = notch. Cheaper than 4 separate RBJ biquads. `freq` and `q` accept any `ValidGeneratorInput`. Denormal guard via `denormalsToZero` on `low` and `band` state every sample. `svfButterworthQ` (1/√2) default Q. `svfChannelCount = 4` named constant. Named channel aliases on both `Audio` and `Control`: `.lowpass` / `.highpass` / `.bandpass` / `.notch` (each returns a `ChannelSelect.Audio` or `ChannelSelect.Control`). `SVF.Control` overrides `calculatedSamples` to bypass the sub-block loop (canonical `AmplitudeFollower.Control` pattern). The IIR state must advance exactly once per audio block; without the override, the cached audio-rate input would be re-processed N times per block. `_computeSamples` reads input/freq/q at full `blockSize` and runs the per-sample loop over `count`. Foundation for modal / resonator bank (Phase 87). **2403 tests at completion.** --- ## Phase 77 — WavetableMorph Oscillator `WavetableMorph.Audio` and `WavetableMorph.Control`. Takes `[LyrebirdBuffer]` (≥ 2 mono tables, all same count) plus `freq`, `position` (fractional table index in `[0, N-1]`), and `phase` (cycles offset) — all `ValidGeneratorInput`. Per-sample linear interpolation between adjacent tables at fractional `position`; inner table reads support `.none` / `.linear` / `.cubic` interpolation. Mono output; MCE via `expand`/`GeneratorArray`. Audio variant evaluates `freq` / `position` / `phase` per sample (true FM, table-position modulation, phase modulation). Control variant evaluates them once per (sub-)block and emits a smooth ramp via `fillRampedResult` — same pattern as `OscTable.Control`. No `calculatedSamples` bypass needed because phase advances by `count` (not `blockSize`), so sub-block calls accumulate correctly. RT-safety: `_result` pre-allocated to `lyrebirdDefaultResultBufferSize`; pre-stored `_tableCountFloat` and `_maxPositionFloat` in `_Base` to avoid per-block conversions; indexed validity scan over all tables (avoids closure capture / per-element ARC traffic that `Array.contains(where:)` would incur on a class-element array). Generator inputs evaluated before the validity guard so modulator state advances on the silence path. Depends on Phase 69 (LyrebirdBuffer wavetable generation utilities) for production-quality table content. Pairs with `WavetableSet.interpolating(from:to:steps:)` and `WavetableSet.rotatingPhases(buffer:steps:)` factories. `GeneratorEnum` conformance: `AudioType = WavetableMorph.Audio`, `ControlType = WavetableMorph.Control`. **2426 tests at completion.** --- ## Phase 77-review-cleanup — Scalar input intra-block ramp fixes Cross-cutting fix for generators whose scalar `ValidGeneratorInput` parameters were read once per block via `floatValue(graph:)`. Phase 75b promoted `ParameterNode` / `UIParamNode` to `ControlGenerator`; scalar paths without a `_xIsGenerator` guard were silently dropping parameter ramping (or coarsening it to block-rate). Fix pattern: at init, store `_xIsGenerator = x is any Generator`; in `_computeSamples`, branch — generator path uses `calculatedSamples` (per-sample for inner trig/state, last-sample read for block-rate coefficients); scalar path keeps `floatValue` once per block. **Changes:** - `Pan2.swift`, `PanN.swift` — wire previously-dead `_panIsGenerator` / `_positionIsGenerator` bools to per-sample loop branch. - `Pan4.swift`, `AmbiEncoder1.swift` — `@LiveParam` properties always wrap as `ParameterNode` (a `ControlGenerator`), so per-sample evaluation is unconditional. Force-unwraps replaced with hoisted `guard let`. - `Compressor.swift`, `Expander.swift`, `AmplitudeFollower.swift` — `_xIsGenerator` guards added per scalar parameter (Audio + Control). New shared helper `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` in `MulAdd.swift` centralises the "read last sample of block, fall back to floatValue" pattern across 28 sites. - `LFStepNoise.swift`, `LFLineNoise.swift`, `LFCurveNoise.swift` — Audio variants gain `_freqIsGenerator` (Control variants were already correct). - `DelayLineFeedback.swift` — `decayTime` / `targetAmp` gain IsGenerator guards via the helper. - `WavetableMorph.swift` — dead `_tableCountFloat` field removed (only `_maxPositionFloat` consumed in `_computeSamples`). **Out of scope (intentionally block-rate per architect audit):** - Gendy1/2/3 — breakpoint state machine update is naturally block-rate. - Granular family (BufferGrain/FMGrain/SineGrain/TimeStretch/Jitter/TriggeredRandom) — grain scheduling is block-rate by design. - Reverb (FreeVerb / GVerb) — room params update once per block on purpose. **Tests:** per-fixed-generator test suites that wire a `ParameterNode` into the previously-scalar input, ramp the value, and assert intra-block change vs block-rate stairstep. New `rmsValue(_:[Double]) -> Double` helper in `TestHelpers.swift` (absorbs prior file-private duplication). **Documentation cleanup:** AmplitudeFollower phantom `mul`/`add` doc entries removed (init does not accept them); class-level `/// - Parameters:` blocks added to Pan4 / AmbiEncoder1 / PanN; dual-location parameter docs added to LFStepNoise / LFLineNoise / LFCurveNoise (Audio + Control). **2448 tests at completion.** --- ## Phase 78 — Karplus-Strong / Waveguide String ✓ COMPLETE **Goal:** plucked-string physical model via feedback delay line with controllable one-pole filter. Two Audio-only generators in `Sources/Lyrebird/Generators/KarplusStrong/`: ### KarplusStrong.Audio Trigger-based plucked-string model. On a ≤0→>0 trigger edge, a `_refillRemaining` counter is set to the delay line length; over the next N samples the `exciter` signal fills the delay line. The delay line then recirculates through a one-pole filter and feedback multiplier, producing natural plucked-string decay. Params: - `exciter: ValidGeneratorInput` — excitation signal (e.g. `WhiteNoise.Audio()`) - `trigger: ValidGeneratorInput` — ≤0→>0 edge fires fill - `freq: ValidGeneratorInput` — fundamental Hz; controls delay length (default `440.0`) - `feedback: ValidGeneratorInput` — feedback gain [0, 1]; sustain length (default `0.99`) - `coef: ValidGeneratorInput` — one-pole filter coefficient, suggested [-1, 1]; `0.5` = classic KS averaging; negative = brighter/metallic; `|coef| > 1` causes exponential growth (documented) (default `0.5`) - `sampleRate: Double` — structural param, sizes the delay line at init - `maxDelayTime: Double` — structural param; delay line = `ceil(maxDelayTime × sampleRate)` frames ### GatedKarplusStrong.Audio Continuous-gate variant. When `gate > 0`, `exciter` is written into the delay line each sample (sustained excitation). When `gate ≤ 0`, normal KS feedback loop runs. Supports audio-rate gate modulation (e.g. `LFDutyCycle.Audio` with varying duty width). Params: same as above except `gate: ValidGeneratorInput` replaces `trigger`. ### One-pole filter formula SC Pluck-style: `filtered = (1 - |coef|) × x + coef × prev`, then `y = filtered × feedback`. `_prevSample` tracks filter output (not raw delay read). `denormalsToZero` applied on every delay-line write. ### Fractional delay `delayFrac = sampleRate / freq`, clamped to `[1.0, delayLineSize - 1]`. Linear interpolation between adjacent delay-line positions: `pos0 = writePos - floor(delayFrac)`, `pos1 = pos0 - 1` (both wrapped). No `GeneratorEnum` conformance — Audio-only generators with per-sample IIR feedback have no meaningful Control-rate equivalent. **Tests:** `KarplusStrongTests.swift` (9 tests) + `GatedKarplusStrongTests.swift` (9 tests) — rate, silence before trigger/gate, output count, fan-out, state-advance-once, non-silence after trigger, decay over time, mulAdd, engine integration. **2471 tests at completion.** --- ## Phase 79 — Flanger / Chorus / Phaser ✓ COMPLETE Three Audio-only modulation effect generators in `Sources/Lyrebird/Generators/Modulation/`. ### Flanger.Audio Short modulated delay blended with dry signal. Sine LFO sweeps delay around `delayTime` by ± `depth × delayTime`. Feedback writes `dry + feedback × delayed` into the delay line before the dry/wet blend. Delay line pre-allocated to `ceil(maxDelayTime × sampleRate) + 2` samples. `denormalsToZero` on every delay-line write. Parameters: `input`, `delayTime` (sec, default 0.005), `depth` ([0,1], default 0.5), `rate` (Hz, default 0.5), `feedback` ([0,0.9], default 0.0), `mix` ([0,1], default 0.5), `sampleRate` (Double structural), `maxDelayTime` (Double structural, default 0.05), `mul`, `add`. ### Chorus.Audio Stereo 2-channel output. Two taps from a shared mono delay line driven by sine LFOs with initial phases 0 and π (0.5 normalised; named constant `halfCycleNormPhase`). No feedback. Tap 0 → channel 0 (left), tap 1 → channel 1 (right). `.left` / `.right` channel aliases via `ChannelSelect.Audio`. Delay line pre-allocated to `ceil(maxDelayTime × sampleRate) + 2` samples. Parameters: `input`, `delayTime` (sec, default 0.025), `depth` ([0,1], default 0.002), `rate` (Hz, default 1.5), `mix` ([0,1], default 0.5), `sampleRate` (Double structural), `maxDelayTime` (Double structural, default 0.1), `mul`, `add`. ### Phaser.Audio `stages` (4, 6, or 8) cascaded first-order all-pass stages, fixed at init by `precondition`. LFO sweeps the AP coefficient `a = (tan(π×f/sr) − 1) / (tan(π×f/sr) + 1)` around `centerFreq`. Stage recurrence: `y[n] = a × (x[n] − y[n−1]) + x[n−1]`; denormal chain: `chainIn = _apOut[s]` (cleaned value propagates, not raw `y`). Feedback feeds chain output back to input. `_apIn`/`_apOut` pre-allocated to `stages` doubles. Nyquist clamp: `sampleRate × nyquistFraction − nyquistMarginHz` (named constants). Parameters: `input`, `rate` (Hz, default 0.5), `depth` ([0,1], default 1.0), `centerFreq` (Hz, default 800.0), `feedback` ([0,0.9], default 0.0), `stages` (Int: 4/6/8, default 4, fixed), `mix` ([0,1], default 0.5), `sampleRate` (Double structural), `mul`, `add`. ### Design decisions - Audio-only (no Control variants, no `GeneratorEnum`) — per-sample delay-line reads and IIR state make block-rate equivalents meaningless - `sampleRate` and `maxDelayTime` are structural `Double` (not `ValidGeneratorInput`) to allow delay-line pre-allocation at init - All modulation params (`delayTime`, `depth`, `rate`, `feedback`, `mix`, `centerFreq`) accept `ValidGeneratorInput` for audio-rate modulation **Tests:** `FlangerTests.swift` (8 tests) + `ChorusTests.swift` (9 tests) + `PhaserTests.swift` (11 tests) — rate, silence, deterministic first-sample pinning, stereo channels, fan-out, state-advance-once, mulAdd, engine integration. **2506 tests at completion.** --- ## Phase 80 — FrequencyShifter (SSB / Hilbert) `FrequencyShifter.Audio`: Weaver method — two cascaded 4-stage first-order IIR all-pass chains approximate a 90° Hilbert transform; SSB modulation shifts all frequencies by a fixed Hz amount (not ratio). `shiftHz: ValidGeneratorInput` for audio-rate modulation. Stereo output (upper + lower sidebands). **Key design decisions:** - Audio-only — per-sample IIR all-pass chains and quadrature oscillator have no meaningful block-rate analog - No `GeneratorEnum` (Audio-only, matching `Flanger`/`Chorus`/`Phaser`/`KarplusStrong` precedent) - Single init with `sampleRate: Double = 44100.0` default (Flanger/Chorus/Phaser convention) - `precondition(sampleRate > 0)` guards against ±Inf `_twoPiOverSampleRate` - `denormalsToZero` applied to all 8 all-pass delay state slots + `xA`/`xB` before SSB mixing - `hilbertCoeffA`/`hilbertCoeffB` coefficients and `twoPi` / `hilbertSectionCount` are `private static let` - `.upper` (ch 0) and `.lower` (ch 1) named channel aliases via `ChannelSelect.Audio` - PitchShifting.md updated with FrequencyShifter section and harmonic-vs-inharmonic contrast note **Tests:** `FrequencyShifterTests.swift` (13 tests) — rate, channel count, fan-out, state-advance-once, deterministic first-sample (analytic: `a0*a1*a2*a3` from all-zero state), zero-shift passthrough, DC input oscillator visibility, audio-rate shift, mulAdd, denormal safety (1000 blocks), channel aliases, engine integration, sideband differentiation. **2520 tests at completion.** --- ## Phase 81 — Polyphonic Voice Allocator ✓ COMPLETE Language-side `VoicePool`. Manages N synthesizer instances as voices. On note-on: allocate via steal strategy; on note-off: gate off. Steal strategies: `.oldest`, `.quietest`, `.lowestAmplitude`, `.roundRobin`. Interacts with `Group`/`NodePosition` (Phase 50). No RT changes. **Key types:** - `VoicePool` — generic pool; `noteOn(note:) -> S`, `noteOff(note:)`, `allNotesOff()`; `voices: [S]` accessor - `VoiceStealStrategy` — `.oldest` (min triggerSerial), `.roundRobin` (cursor mod count), `.quietest`/`.lowestAmplitude` (Mirror scan for `@LiveParam` named `"amplitude"`, `"amp"`, or `"gain"`; falls back to `.oldest` when none found) - `VoiceState` — per-voice `isActive`, `note`, `triggerSerial`, `index` - `VoicePoolError.invalidVoiceCount` — thrown when `voiceCount < 1` **Tests:** `VoicePoolTests.swift` (21 tests) — init validation, basic noteOn/noteOff, polyphonic same-note handling, free-voice reuse, oldest sequential steal, round-robin wrap-around, quietest amp scan, lowestAmplitude alias, Mirror fallback to oldest when no amp param, allNotesOff, discardable result. **2541 tests at completion.** --- ## Phase 82 — Step Sequencer Language-side `StepSequencer` driven by `LyrebirdClock`. Iterates a fixed `SequencerStep` array on a background `LyrebirdTask`, firing `onNoteOn`/`onNoteOff` closures at beat-accurate sample times. **`SequencerStep`** (value type): - `pitch: Int` — MIDI pitch; negative = rest (no callbacks fired) - `velocity: Double` — default 0.8 - `gate: Double` — note-on duration as fraction of step duration; default 0.8 - `probability: Double` — 0.0–1.0 gate probability; default 1.0 (always fires) - `duration: Double` — step length in beats; default 1.0 - `parameterLocks: [String: Double]` — per-step parameter overrides delivered to `onNoteOn` - `static var rest: SequencerStep` — convenience; pitch = −1 **`StepSequencer`** (class, `@unchecked Sendable`): - `NSLock` protects `_steps`, `_onNoteOn`, `_onNoteOff`, and `_task` assignment - `Atomic` for `currentStep` — readable from any thread, updated after `waitUntil` - `start(engine:quantized:)` — lock-protected guard prevents TOCTOU race; resets `currentStep` to 0 - `pause()` / `resume()` / `stop()` delegate to `LyrebirdTask` - `reset()` — calls `_task?.reset()`, nils `_task`, stores 0 to `_currentStep` - Idle-burst-fire prevention: when `steps` is empty, resync `stepBeat = clock.currentBeat` after poll sleep so reassigning non-empty steps doesn't burst-fire past-due events - Minimum step duration constant `stepSequencerMinimumStepDuration = 0.001` beats prevents busy-loop on zero-duration steps **DocC:** `StepSequencer.md` article; `Scheduling.md` "## Step Sequencer" section added; `Lyrebird.md` "### Step Sequencer" topic group added. **Tests:** 22 tests across 3 suites: - `SequencerStepTests.swift` — struct defaults, custom values, rest pitch, mutability - `StepSequencerStructuralTests.swift` — initial state, currentStep, steps read/write, clock retention, idle stop/reset - `StepSequencerTimingTests.swift` — noteOn fires per step, noteOff after noteOn, rest skips callbacks, probability 0/1 extremes, step index delivery, wrap-around, parameter locks, state transitions, double-start noop, mid-playback step replacement **2563 tests at completion.** --- ## Phase 83 — Additive Synthesis Bank ✓ COMPLETE **Goal:** Close the spectral analysis→resynthesis pipeline by providing a single efficient generator that resynthesizes a `SpectralFrameBuffer` as a sum of N sine partials. ### What was built `AdditiveSynthesizer.Audio` (`Sources/Lyrebird/Generators/Spectral/AdditiveSynthesizer.swift`): - Reads magnitudes from a `SpectralFrameBuffer` at a normalized position via linear interpolation between adjacent frames (once per block) - Maintains per-bin Float phase accumulators (one per active partial), advanced per sample via `vDSP_vadd` - Synthesizes output via `vvsinf` (batch sin) + `vDSP_dotpr` (magnitude-weighted sum) — the full inner loop is three vDSP/vForce calls per sample - Phase increments computed lazily on first `_computeSamples` call (sampleRate unavailable at init); `_phaseIncrementsComputed` Bool flag gates one-time setup - Anti-aliasing zeroes bins whose frequency `k * recordSR / fftSize > nyquist` after magnitude interpolation - Phase wrapping via `remainder(dividingBy: 2π)` once per block prevents Float precision drift - `maxPartials` parameter caps active partial count; `0` = all bins (`halfSize − 1`) - `position: ValidGeneratorInput` — normalized [0, 1]; clamped internally; read once per block - Standard `MulAddSpec` / `_mulAdd.applyIfNeeded` for output scaling - Guard for `_activePartials == 0` (e.g. `fftSize == 2`) returns silence safely ### Tests `Tests/LyrebirdTests/AdditiveSynthesizerTests.swift` — 13 tests: - `rateIsAudio`, `outputCountMatchesRequest`, `silentWhenAllMagnitudesZero`, `nonSilentWithNonZeroMagnitude` - `fanOutReturnsCachedResult`, `stateAdvancesOncePerBlock` - `maxPartialsZeroUsesAllBins`, `maxPartialsCap` - `positionClampAbove`, `positionClampBelow` - `antialiasingZerosBinAboveNyquist` - `mulAddApplied`, `integrationWithEngine` **2583 tests at completion.** --- ## Phase 84 — Formant Grain Synthesis (FOF) ✓ COMPLETE **Goal:** Add IRCAM CHANT FOF (Fonction d'Onde Formantique) formant-grain synthesis. Each instance models one vocal-tract formant; stacking 3–5 instances at different `formantFreq` values synthesises vowel sounds. ### What was built `FormantGrain.Audio` (`Sources/Lyrebird/Generators/Granular/FormantGrain.swift`): - One grain per glottal pulse: sine² rise (half a period of `formantFreq`) → exponential decay (`exp(-π * bandwidth / sr)` per sample) - Pre-allocated pool of `lyrebirdGrainPoolSize` (64) `FOFGrainState` slots; struct value-type updates in-place (no RT allocation) - `octaviation ≥ 1` alternates successive grain sign → suboctave at half the glottal rate - All inputs (`glottalFreq`, `formantFreq`, `bandwidth`, `octaviation`, `amplitude`) sampled once per audio block (block-rate) - File-scope named constants: `fofGrainDeathThreshold` / `fofGrainRisePeakPhase` / `fofSineFullCycle` / `fofGlottalFreqMin` / `fofFormantFreqMin` / `fofBandwidthMin` - Standard `MulAddSpec` / `_mulAdd.applyIfNeeded` for output scaling ### Review-cycle hardening - `glottalFreq` clamped to `[fofGlottalFreqMin, sampleRate]` — prevents `hopSize < 1` infinite spawn loop - Pool-full handling: **steal-oldest** policy (lowest `spawnTick` UInt64) instead of silent drop — keeps audio audible under sustained over-saturation; unique to `FormantGrain` among the granular family - `sinePhase` wrap uses unconditional `truncatingRemainder` — handles arbitrary `sinePhaseInc` (e.g. when `formantFreq > sampleRate`) - `_glottalCount` promoted `Int → UInt64` with overflow-safe `&+=` increment ### Tests `Tests/LyrebirdTests/FormantGrainTests.swift` — 14 tests: - `rateIsAudio`, `outputIsMonoOnechannel`, `outputCountMatchesRequest` (verifies samples actually written) - `firstBlockIsNonSilent`, `grainPeakOccursAfterRisePhase`, `grainDecaysToSilenceAfterSufficientTime` - `poolSaturationDoesNotProduceNaN`, `poolFullStealsOldestGrain` (audible after pool overflow) - `glottalFreqAboveSampleRateIsClamped`, `formantFreqAboveSampleRateIsFinite` - `octaviationZeroAndOneProduceDifferentOutput` (epsilon compare) - `mulScalesOutput`, `sameParamsSameOutput`, `generatorDrivenFormantFreqIsFinite` ### Documentation - New `Sources/Lyrebird/Lyrebird.docc/Generators/GranularSynthesis.md` — covers `BufferGrain` / `SineGrain` / `FMGrain` / `InputGrain` / `PitchShift` / `TimeStretch` / `FormantGrain`; overview table; density-vs-hop-vs-glottal scheduling families; per-generator quickstarts; FOF parameters + steal-oldest policy - `BuiltInGenerators.md` Granular section adds `FormantGrain`, `TimeStretch`, links the new topic - Dual-location `/// - Parameters:` doc blocks on `FormantGrain` class and init **2597 tests at completion.** --- #### Phase 85 — Spectrum / Spectrogram View `SpectrumCapture`: RT tap wrapping `FFTAnalysis` output, double-buffered (matches `ScopeCapture` pattern, Phase 41). `LyrebirdSpectrumView` (SwiftUI, LyrebirdUI module): Canvas-based, log-frequency axis, dB magnitude, configurable FFT size and window. Optional waterfall mode. Companion to `LyrebirdScopeView`. **Key details:** - `SpectrumCapture` implements `SpectralProcessor` — registered on `FFTAnalysis(processors: [capture])`. Ping-pong `[[Float]]` double-buffer with `Atomic` acquire/release semantics, identical to `ScopeCapture`. `process(spectral:)` uses `magnitude(at:)` loop (handles DC/complex/Nyquist uniformly); `snapshot()` deep-copies front buffer on main thread. - `LyrebirdSpectrumView` polls at ~30 Hz via `.task`. Spectrum mode: log X (minHz–maxHz), dB Y (floorDB–ceilDB), green line. Waterfall mode (`waterfallRows > 0`): scrolling spectrogram with black→green brightness encoding; `waterfallHue` + `waterfallSaturationBoost` named constants. - 9 tests in `SpectrumCaptureTests.swift` cover init, zero snapshot, DC/Nyquist absolute-value storage, complex-bin round-trip, consecutive hops, ping-pong stress. **2606 tests at completion.** --- ## Phase 85.5 — Smoothing Filters (Lag / Decay / LeakDC Family) Seven SC-equivalent smoothing filter generators, each with Audio and Control variants. **New generators:** | Generator | SC equivalent | Description | |-----------|--------------|-------------| | `Lag` | `Lag.ar/.kr` | One-pole smoother; 60 dB lag time | | `LagUpDown` | `LagUpDown.ar/.kr` | Asymmetric smoother; separate rise/fall times | | `Lag2` | `Lag2.ar/.kr` | Two-cascaded Lag; smoother transition curve | | `Lag2UpDown` | `Lag2UpDown.ar/.kr` | Two-cascaded LagUpDown | | `Decay` | `Decay.ar/.kr` | Leaky integrator; 60 dB decay time | | `Decay2` | `Decay2.ar/.kr` | `Decay(decayTime) − Decay(attackTime)`; rounded attack | | `LeakDC` | `LeakDC.ar/.kr` | One-pole DC blocker: `y[n] = x[n] − x[n−1] + coef·y[n−1]` | **Key decisions:** - Shared `lagCoeff(time:sampleRate:)` helper in `LagHelpers.swift` used by all six time-parameterised generators (not LeakDC, which takes a direct coefficient). - Audio variants compute the coefficient at sample rate — applied per sample in the inner loop. - Control variants compute the coefficient at **control rate** (`sampleRate / blockSize`), matching SC's `.kr` convention: `time` is in seconds and the filter converges in that many wall-clock seconds regardless of block size. - All Control variants override `calculatedSamples` to bypass the sub-block loop (same pattern as `SVF.Control`/`AmplitudeFollower.Control`). - `LeakDC` exposes two public constants: `leakDCDefaultAudioCoef = 0.995` and `leakDCDefaultControlCoef = 0.9` (SC convention). - All generators: `GeneratorEnum` conformance, dual-location `/// - Parameters:` docs, `denormalsToZero()` on all IIR feedback state. - 71 new tests across 7 test files; `advanceBlock(engine)` required between iterations in all multi-block convergence tests. **2677 tests at completion.** --- ## Phase 86.75a — Classic SC PV Ports (single-buffer processors) Port six SuperCollider phase-vocoder generators authored by Josh in the early 2000s (`sc3-plugins/source/JoshUGens/JoshPVUGens.cpp`) to Lyrebird as `SpectralProcessor` conformers. No new infrastructure required: - `SpectralPartialFilter` / `SpectralNoiseFilter` (with `ClassifierMode.frequency | .phase`) — multi-frame stability classifiers; keep tonal partials or noise. - `SpectralMagnitudeMap` — `LyrebirdBuffer`-driven magnitude transfer function (`PV_MagMap`). - `SpectralHarmonicEnhance` — adds harmonic-series energy above existing bins (`PV_SpectralEnhance`). Time-varying params via `Atomic` / `Atomic`. Each ring buffer pre-allocated in `init` (`UnsafeMutablePointer.allocate(capacity:)`); no RT alloc, no shared base class. Per-Lyrebird convention `SpectralPartialFilter` and `SpectralNoiseFilter` duplicate the small body rather than share a `_Base` (precedent: `OscSawtooth` / `OscSquare`). Notable decisions: - **Ring history layout** — `_history[bin * numFrames + frame]`. Bin-major so each bin's history is contiguous; pass-2 averaging walks `numFrames` floats per bin. - **Warmup window** — first `numFrames` hops do not modify magnitudes (partial averages would trigger spurious zeroing). After warmup, classification kicks in. - **`.frequency` mode metric** — true bin frequency in Hz, computed from instantaneous phase deviation from bin centre then scaled by `sampleRate / (2π × hopSize)`. Wraps deviation via `.remainder(dividingBy: 2π)` to keep within principal value. - **`.phase` mode metric** — hop-to-hop phase difference in radians, wrapped to (−π, π]. Cheaper, slightly noisier for high bins. - **`SpectralHarmonicEnhance` index arithmetic** — `Int((Double(i * j) * ratioD).rounded())`. `Double` needed because `Float` mantissa is 24 bits and `i * j` for large `fftSize` (≥ 16k) with multiple partials can exceed that, shifting target by ±1 bin. - **`SpectralMagnitudeMap` floor** — frames whose maximum magnitude is below `magnitudeFloor` (default `1e-8`) are left untouched. Guards `0 / 0` and prevents amplifying numerical noise in silent passages. **16 new tests; 2694 total.** Each generator covered: stability survives / unstability zeroed (PartialFilter), inverse (NoiseFilter), warmup window, frequency-mode classification, identity / constant-half / below-floor / step-gate transfers (MagnitudeMap), harmonic placement / out-of-range skip / ratio-1 no-op / live-param round-trip (HarmonicEnhance). --- ## Phase 86.75b — Classic SC PV Ports (BinDelay + CrossMap) Continuation of the SC PV ports requiring new infrastructure. Built on the `LyrebirdBufferUpdates` API (`setValue` / `setRangeValues`) that landed earlier. ### New protocol - `SpectralProcessor2` — sibling of `SpectralProcessor` with `process(spectral:sideChain:)`. `FFTAnalysis.init` gains a `dualProcessors` array of `(SpectralProcessor2, sideChain: FFTAnalysis)` pairs. Side-chain must share `fftSize` and `hopSize` with the host (precondition-enforced) and must run earlier in the node tree so its `spectralBuffer` is current at hop-fire time. ### New generators - `SpectralBinDelay` — per-bin spectral delay with per-bin feedback. Maintains a ring of past spectral frames in rectangular form (real + imag). `delayTimes` and `feedbacks` are two `LyrebirdBuffer` instances, snapshotted to per-bin Int frame offsets at the top of each hop. Per-bin output is the delayed slot's value (read back as polar); the delayed slot is then attenuated by `feedbacks[k]` and summed back into the head slot — giving a feedback-loop topology in the spectral domain. Ring depth capped at `lyrebirdSpectralBinDelayMaxFrames = 512` (matches SC `MAXDELAYBUFS`). - `SpectralCrossMap` — dual-FFT cross-synthesis. Captures (or freezes) a per-bin gain mask from a side-chain spectrum and applies it to the main spectrum. `mode` is a continuous `[-1, 1]` control crossfading bandreject ↔ pass-through ↔ bandpass; `floor` thresholds the template and gates quiet bins to `1 - |mode|`. Two normalization strategies: `.maxMagnitude` (adaptive — divide by the loudest template bin) and `.windowScale` (fixed scaler chosen by `CrossMapWindowKind`: `.rectangular` / `.hann` / `.hamming`). ### New SwiftUI control - `LyrebirdUI.MultiSlider` — horizontal row of N adjacent vertical bars, each bound to one cell of a `LyrebirdBuffer` (via `setValue(_:at:)`). Drag a column to write that cell. Cross-platform via `PlatformColors`. Designed for live editing of `SpectralBinDelay` per-bin parameters or the `SpectralMagnitudeMap` transfer curve. ### Notable decisions - **Ring storage in rectangular form** — incoming polar bins are converted via `cosf` / `sinf` into the ring; outgoing delayed bins are converted back via `sqrtf` / `atan2f`. Storing rectangular makes the feedback sum (`ring[head] += attenuated(ring[del])`) a true complex add rather than a phase-incoherent magnitude add. - **Snapshot pattern over RT-direct read** — `SpectralBinDelay` reads `delayTimes` / `feedbacks` via per-bin `LyrebirdBuffer` subscripts at the top of each hop into pre-allocated scratch arrays, then processes from the snapshot. This matches the live-write contract documented in `BufferGuide.md`. - **`SpectralCrossMap` template captured into pre-allocated `_templateMag`** — no allocation in `process()`. `freeze` skips the capture step but otherwise the dispatch path is unchanged. ### Tests - `SpectralBinDelayTests`: zero-delay pass-through, fixed-N-hop latency, untouched bins are pass-through, live `LyrebirdBuffer.setValue` update. - `SpectralCrossMapTests`: uniform template pass-through, sparse template bandpass, mode = 0 pass-through, uniform template bandreject silence, freeze holds template, live property round-trip. - `SpectralProcessor2Tests`: end-to-end FFTAnalysis dispatch — verifies the registered dual processor is called with the host's and side-chain's spectral buffers as expected after several blocks. - `MultiSlider`: SwiftUI structural smoke (init does not crash; values initialised from buffer). **2720 tests at completion.** --- ## Phase 86 — Onset Detection `OnsetDetector` SpectralProcessor with two onset-detection-function methods: - `.spectralFlux` — half-wave-rectified Euclidean flux: `sqrt( Σ max(|X[k]| − |Xprev[k]|, 0)² )`. Sensitive to magnitude rises only — standard form for percussive-onset detection. - `.complexDomain` — predicts each bin's next complex value from previous magnitude and a linear phase extrapolation `2*phasePrev − phasePrevPrev`, then sums Euclidean distance to the actual bin. Captures both magnitude jumps and phase irregularities; better for soft / pitched onsets. Reference: Bello et al., "A Tutorial on Onset Detection in Music Signals", IEEE TSAP 2005. Adaptive threshold via rolling-median ODF window (default 7 frames, range [2, 64]); trigger fires when `ODF > max(rollingMedian, 1e-6) * threshold`. Configurable refractory window in hops (`minHopsBetweenOnsets`) suppresses double-triggering on long attack tails. RT-safe per-hop selection-sort median (no Swift `sort`). `OnsetDetector.Control` paired generator emits a single-sample pulse at sample 0 of any audio block during which one or more onsets fired; rest of block zero. Drives downstream `SendTrigger.Control` with a clean ≤0 → >0 edge even on back-to-back onset blocks. Communication via `Atomic` onset serial — RT increments on detection, Control compares cached last-seen value. `threshold`, `minHopsBetweenOnsets`, `lastODF`, and `lastMedian` exposed as `Atomic`-backed properties for live tuning and visualisation. **2742 tests at completion.** --- ## Phase 86.9 — Signal-Domain Analysis Utilities + Signal Analysis DocC Hub Three new signal-domain utility generators in `Sources/Lyrebird/Generators/Triggers/`: - `SignalChanged.Audio` / `.Control` — per-sample change detector. Emits `1.0` whenever `|input(i) − input(i-1)| > threshold`, else `0.0`. `threshold` is any `ValidGeneratorInput` (live-tunable, generator-driveable). Audio variant per-sample; Control variant collapses to one block-constant sample (any change anywhere in the block fires for the whole block). Output is square (no ramp) — change detection is binary by nature. - `Gate.Audio` / `.Control` — passthrough while `trig > 0`, holds last-passed input while `trig ≤ 0`. Held value updates continuously while gate is high so the falling-edge value is the most recently seen input. Control variant ramps to held value (`fillRampedResult`) for smooth control transitions. - `SampleAndHold.Audio` / `.Control` — SuperCollider `Latch` semantics. On each ≤0 → >0 trigger edge, captures `input` at that frame and outputs the captured value until the next edge. Audio variant per-edge (multiple captures per block possible); Control variant at-most-one capture per block (first edge wins) with ramped output. All three follow the established `_Base` + `Audio` + `Control` + `GeneratorEnum` pattern, mirror `SendTrigger` / `Demand` for trigger handling and cross-block state, and use `_xIsGenerator` cache flags + `lastGeneratorSampleOrFloat` / per-sample reads for `ValidGeneratorInput` parameters. State (`_prevSample`, `_heldValue`, `_prevTrig`) persists across blocks; before any qualifying event, output is `0.0`. DocC reorganisation: - New `Sources/Lyrebird/Lyrebird.docc/Generators/SignalAnalysis.md` top-level topic curates everything analyzer-style: change/edge detectors, hold/latch, amplitude and frequency tracking, dynamics processors, trigger-driven random, and the entire spectral analysis subsystem (with `SpectralFeatures.md` linked as a child article and all spectral symbols re-curated under it). - `Lyrebird.md` root collapses the previous `Spectral Analysis` and `Spectral Feature Extraction` blocks into a single `Signal Analysis` group pointing at `` and ``. SignalAnalysis owns the symbol curation now. - `SpectralFeatures.md` gains a one-line intro nudge crediting `SignalAnalysis` as the parent hub. **2773 tests at completion.** --- #### Phase 87 — Resonator / Modal Bank `ResonatorBank.Audio`: Klank-style parallel two-pole (Ringz) resonator bank driven from a 3-channel `LyrebirdBuffer` of `[freq, decay, amp]` triplets. Bank size = `buffer.count`. Coefficients are recomputed once per audio block from the buffer snapshot — live `setValue` / `setRangeValues` writes are picked up at block boundaries — then the per-sample inner loop is vectorised across the bank via `vDSP_vsmulD` / `vDSP_vmulD` / `vDSP_vsubD` pairs and `vDSP_sveD`. `denormalsToZero` is applied to `y1` per element each sample; mono summed output. Audio-only (no `GeneratorEnum`). Adds `Sources/Lyrebird/Generators/Filters/ResonatorBank.swift`, `Tests/LyrebirdTests/ResonatorBankTests.swift` (10 tests), and a `ResonatorBank` row in `Sources/Lyrebird/Lyrebird.docc/Generators/Filters.md`. **2783 tests at completion.** --- ## Phase MCE-A — Channel-aware `BinaryOpGenerator` + `outputChannelCount` **Problem.** `BinaryOpGenerator` (used by `+ - * /` between any operands where at least one side is a `Generator`) read only `.first` of each operand's `calculatedSamples` and produced a 1-row result. So `Pan2(...) * 0.5`, `In.Audio(bus:0, channels:2) + lfo`, `stereoFx + dryStereo`, etc. silently dropped every channel beyond 0 and yielded mono. `GeneratorArray` had correct element-wise + scalar-broadcast operators, but multi-row single Generators (Pan2/Pan4/PanN, AmbiEncoder1/AmbiDecoder1, SVF, FrequencyShifter.Audio, Chorus.Audio, TimeStretch.Audio, multi-channel In/BufferRead/PlayBuffer) were not GeneratorArrays and bypassed that path. **Design — what shipped.** 1. New `var outputChannelCount: Int { get }` on the `Generator` protocol. `GeneratorBase` provides default `{ 1 }` (`open var`, override-able). Multi-row generators override to return the fixed channel count set at `init` from a `let` constant or `_result.count`. Channel count is **structurally fixed at init** — never changes at runtime. 2. `BinaryOpGenerator` is channel-aware: - Reads `lhs.outputChannelCount` / `rhs.outputChannelCount` at `init` (graph build time, never RT). - Pre-allocates `_result` with `max(lhsChannels, rhsChannels)` rows × `lyrebirdDefaultResultBufferSize`. - Per-channel rules in `_computeSamples`: - `1 × N`: mono lhs broadcasts → row[i] = lhs[0] op rhs[i]. - `N × 1`: symmetric. - `N × N`: element-wise → row[i] = lhs[i] op rhs[i]. - `N × M` with both > 1 and `N ≠ M`: `precondition` traps at init with explicit message — no SC `wrapExtend`, no truncation. - Scalar literal fast-path (`lhsIsLiteral` / `rhsIsLiteral` flags) preserved; literal scalar treated as 1-channel. 3. **D3 — rate selection (resolved by reasoning, not by code).** `BinaryOpGenerator` remains unconditionally `AudioGenerator`. Even when both operands are control-rate, `BinaryOpGenerator` evaluates them through their interpolating `calculatedSamples` ramp and combines per-sample, producing audio-rate output — no `.Audio`/`.Control` split needed. The original concern was a misread. 4. Operator overload set unchanged (no new overloads; logic moves entirely inside `BinaryOpGenerator`). 5. **`mul:` / `add:` parameter asymmetry preserved.** `MulAddSpec.apply` reads only `.first` of `mul`/`add` input — applies channel 0 as a uniform scalar gain across all output rows. Documented as a deliberate asymmetry between operator path (full N-row broadcast) and parameter path (scalar gain). Changing `MulAddSpec` to be channel-aware is a larger separable change (semantics of N-channel `mul` against M-channel output for N≠M is non-obvious) and explicitly out of scope. 6. **Mismatch enforcement** is `precondition` at init (build-time, not RT). No compile-time check is possible — channel counts are runtime properties of the operand instance. **outputChannelCount overrides applied (~17 sites).** Pan2/Pan4/PanN/AmbiEncoder1/AmbiDecoder1; SVF._Base (covers SVF.Audio + SVF.Control); FrequencyShifter.Audio; Chorus.Audio; GeneratorArray; TimeStretch.Audio; In._Base (covers In.Audio + In.Control); Out.Audio (forwards to `(source as? any Generator)?.outputChannelCount ?? 1`); Out.Control; RecordBuffer._Base; PlayBuffer._Base; BufferRead.Audio; BufferRead.Control; DiskIn.Audio; DiskOut.Audio. **Tests +17 (2783 → 2800, then +3 for 4-channel coverage = 2803).** Stereo×scalar, scalar×stereo, mono+stereo broadcast both directions, stereo+stereo / stereo×stereo element-wise, 3-channel × 3-channel element-wise, scalar×3-channel broadcast, mono+4-channel broadcast (Pan4 shape), 4-channel × scalar, 4-channel + 4-channel element-wise, ChannelSelect on multi-row BinaryOp, floatValue=ch0sample0 from N-row, outputChannelCount=max(operands). 2×3 mismatch precondition documented as untestable via Swift Testing (`precondition` terminates the process rather than throwing). New `Tests/LyrebirdTests/GeneratorArrayTests.swift` covers element-wise + scalar broadcast on the existing GeneratorArray path. **Docs.** New "Multi-channel operators" sections in `docs/stdlib/multichannel.md` and `Sources/Lyrebird/Lyrebird.docc/Generators/MultiChannel.md`. `outputChannelCount` requirement and broadcasting rules added to `docs/protocols/generator.md` and `docs/protocols/writing-generators.md`. Stale `In.multi(...)` and "block-constant pan" claims fixed. `MulAdd.swift` `apply()` inline doc clarifies channel-0-only mul/add semantics. `CLAUDE.md` Hard Constraints gain the `outputChannelCount` override rule and the `mul:`/`add:` channel-0-only callout. `~/.claude/agents/lyrebird_generator_agent.md` and `~/.claude/agents/lyrebird_review_agent.md` updated so future agents flag missing overrides on multi-row generators. **2803 tests at completion.** --- ## Phase MCE-B — `GeneratorArray × N-row-generator` trap **Problem.** After Phase MCE-A made `BinaryOpGenerator` channel-aware, `GeneratorArray([a, b]) * Pan2(...)` would build inner `BinaryOpGenerator`s with 2-row results — but `GeneratorArray._computeSamples` reads only row 0 of each inner generator, so channels 1..N-1 of each per-element product would be silently dropped. **Design — what shipped.** 1. New file-private helper `_generatorArrayCheckOtherOperandMono(_:op:)` in `GeneratorArray.swift`. Reads the other operand's `outputChannelCount` (1 for `Double`/`Int`/`Closure`; the override on `Generator`s) and `precondition`-traps when > 1. Build-time only — never on the RT thread. 2. All eight `GeneratorArray op ValidGeneratorInput` and `ValidGeneratorInput op GeneratorArray` operator overloads route through the helper before constructing the inner element-wise `BinaryOpGenerator`s. 3. Trap message names the offending channel count and points the caller at explicit composition (`ChannelSelect` — `pan.left` / `pan.right` — or per-channel mono zipping). For arithmetic on multi-row generators directly, use `+ - * /` on the generator itself (no `GeneratorArray` wrapper needed; those operators broadcast properly thanks to MCE-A). 4. **`GeneratorArray.init` left permissive.** Existing patterns rely on the row-0-only silent-drop semantics for direct construction: - `AmbiDecoder1` documentation shows `GeneratorArray([encoder])`. - The `generatorArraySubscriptMatchesDirectChannel` test in `ChannelSelectTests.swift` deliberately tests the silent-drop pass-through. A doc comment on the init records the intentional asymmetry between init (silent-drop, preserved for compat) and operators (trap, fixed). **Tests +1 (2803 → 2804).** `arrayTimesMonoGenerator` verifies the passing case (`GeneratorArray * mono-generator` → element-wise scaling). The 2-channel × `arr` mismatch trap is documented as untestable via Swift Testing (`precondition` terminates the process rather than throwing). **Docs.** `docs/stdlib/multichannel.md` and `Sources/Lyrebird/Lyrebird.docc/Generators/MultiChannel.md` updated with the trap message and the recommended composition pattern. **2804 tests at completion.** --- ## Phase 88 — Vector Synthesis (Audio variant) `VectorOscillator.Audio`: four `LyrebirdBuffer` waveform inputs (lower-left A, lower-right B, upper-left C, upper-right D) + `freq` + `x: ValidGeneratorInput` + `y: ValidGeneratorInput` + optional `phase` and `interpolation`. 2D XY linear bilinear blend: X moves A↔B (and C↔D), Y moves AB↔CD. Per-buffer reads honour `TableInterpolation` (`.none` / `.linear` / `.cubic`); the XY blend itself is always linear. X and Y are clamped to `[0, 1]` per sample. Fewer bus round-trips than a language-side Pan4 + 4× `OscTable` composition. **Shared helper.** `Sources/Lyrebird/Generators/Oscillators/OscillatorTableReadHelpers.swift` exposes `internal @inline(__always)` `oscillatorTableReadNone` / `Linear` / `Cubic` + a combined `oscillatorTableRead` dispatcher. Contract: `phase ∈ [0, tableSize]` (closed — caller's wrap can FP-round to exactly `tableSizeFloat` after `truncatingRemainder` + `+= tableSizeFloat`). Helpers wrap the base index with `% tableSize` to defend against the boundary, which would otherwise trip `LyrebirdBuffer`'s subscript precondition on the RT thread. Replaces the prior fileprivate `oscTableRead` in `OscTable.swift` and `wavetableMorphControlRead` + inline `readTable` switches in `WavetableMorph.swift`. **Silence-path mul/add.** `OscTable.Audio`, `WavetableMorph.Audio`, and `VectorOscillator.Audio` all now apply `_mulAdd.applyIfNeeded` after the zero-fill on the buffer-invalid path. A constant `add` offset survives `LyrebirdBuffer.invalidate()` mid-stream without a hard discontinuity downstream. **RT discipline.** No allocation in `_computeSamples`; `_result` pre-allocated to `lyrebirdDefaultResultBufferSize`; opening `precondition(count <= _result[0].count)`; `is any Generator` classification done in init only; defensive `i < fs.count ? fs[i] : 0` bounds guards on every per-sample input access (matches `OscTable.Audio` pattern). Hoisted `switch _interpolation` — three specialised inner loops with no per-sample dispatch. **Phase 88b deferred.** `VectorOscillator.Control` + `GeneratorEnum` conformance + a `VectorOscillatorUI` synthesizer + macOS/iOS demo screens reusing the existing `LyrebirdUI.ParameterXY` pad land in a separate phase branch. **2828 tests at completion.** 18 in the new `VectorOscillator` suite (corners ≡ OscTable on each buffer, center = mean of four, X/Y clamp, phase 0.5 sine inversion @ 1e-10 tolerance, segmentSerial-asserted cache hit, freq/x/y as Generators, invalid-buffer silence still-advances-modulators, silence path applies add-offset, interpolation modes differentiated). The `OscTable` and `WavetableMorph` suites continue to pass unchanged through the shared-helper refactor. --- ## Phase 88b — Vector Synthesis fast-follow (Control + GeneratorEnum + UI demo) `VectorOscillator.Control` block-rate variant matching `WavetableMorph.Control` / `OscTable.Control` semantics: when `freq`, `x`, `y`, or `phase` is supplied as a Generator, only the first sample of its output block is read each control sub-block. Phase advances by `count * freq * tableSizeFloat / sampleRate` (sub-block-aware — scales with `count`, not `blockSize`). Ramped output via `fillRampedResult(into:from:to:mulAdd:graph:count:)`. Silence path on any-buffer-invalid ramps to 0 with mul/add applied. `_setupSubBlockBuffer()` called after `super.init()` per CLAUDE.md rule. Reuses `oscillatorTableRead` from `OscillatorTableReadHelpers.swift` (Phase 88). **`GeneratorEnum` conformance.** `AudioType = VectorOscillator.Audio`, `ControlType = VectorOscillator.Control`. Multi-line extension format. **`VectorOscillatorUI` demo synthesizer** (`Demos/Lyrebird{MacOSDemo,iOSDemo}/.../Synthesizers/VectorOscillatorUI.swift`). `SynthesizerBase` with `@UIParam` properties `x` (default 0.5), `y` (default 0.5), `frequency` (default 220 Hz, range 40–2000), `amplitude` (default 0.25). Four `LyrebirdBuffer`s of `lyrebirdDefaultTableSize` allocated in `init` (sine / 16-partial saw / triangle / Hanning — no allocation in `build()`). Wires `VectorOscillator.Audio($frequency, $x, $y, mul: $amplitude)` → `Pan2(input: osc, pan: 0.0)` → `output(bus: 0, source:)`. **`VectorOscillatorView`.** SwiftUI view: engine + synth toggle rows, `ParameterXY(xLabel: "X (A↔B)", yLabel: "Y (AB↔CD)", xRange/yRange: 0...1)` at 240×240 bound to `synth.$x` / `synth.$y`, two `ParameterKnob`s for frequency + amplitude, `LyrebirdStatusView`, `LyrebirdScopeView`. iOS variant wraps in a `ScrollView`; macOS variant uses fixed `frame(minWidth:)`. **`VectorOscillatorController`.** `@Observable` controller mirroring `NoteController` exactly — owns engine, synth, scopeCapture; `toggleEngine()` / `toggle()` semantics identical. **Demo selector.** `AppDelegate.swift` (macOS) and `LyrebirdiOSDemoApp.swift` (iOS) refactored from `useBinDelayDemo: Bool` to `enum Demo { case vector, binDelay, sineTone }` with default `.vector`. Switching demos is one-line edit at the top of the file. **Xcode projects updated.** Both `LyrebirdMacOSDemo.xcodeproj` and `LyrebirdiOSDemo.xcodeproj` add three `PBXFileReference` + `PBXBuildFile` entries each; group/source-build-phase entries updated. **2837 tests at completion** (was 2828; +9 new `.Control` tests + 1 GeneratorEnum conformance test). Both Xcode demo apps build clean (macOS, iOS arm64). No tests for demo code — demos aren't part of the test target. --- ## Phase 89 — Distance Modeling `SpatialDistance.Audio` — physically-plausible source-distance model for mono audio. Combines three perceptual distance cues in a single Audio-only generator (no `Control` variant, no `GeneratorEnum` conformance — structurally parameterised effect, sits alongside Flanger/Chorus/Phaser/FrequencyShifter in `Generators/Modulation/`). **Amplitude.** `referenceDistance / max(distance, referenceDistance)`. Inverse-distance attenuation; clamped to 1.0 within `referenceDistance` so near-field sources do not explode. **Air absorption.** One-pole lowpass with cutoff `airAbsorptionCutoff × (referenceDistance/dEff)²`. Per-sample cutoff is clamped to `[1.0, 0.499 × sampleRate]`. Coefficient `a = exp(−2π·fc/fs)`; output `(1−a)·x + a·y_prev`. A one-entry cutoff cache skips `exp()` when the cutoff is unchanged (the common scalar-distance case). **Doppler.** Fractional read pointer advancing at `1 − velocity/speedOfSound` per output sample, clamped to `[0.25, 4.0]` (matches `PitchShift` pitchRatio bounds). Linear interpolation. Delay length is clamped to `[1, delayLineCount − 2]` with snap-to-boundary; the buffer is pre-allocated from `maxDelayTime × sampleRate` (rounded up, plus a small headroom). Modulo arithmetic — buffer length is not constrained to a power of two (matches `Flanger.Audio`). **API.** ```swift public init( input: any ValidGeneratorInput, distance: any ValidGeneratorInput = 1.0, velocity: any ValidGeneratorInput = 0.0, referenceDistance: Double = 1.0, airAbsorptionCutoff: Double = 16000.0, speedOfSound: Double = 343.0, sampleRate: Double = 44100.0, maxDelayTime: Double = 1.0, mul: any ValidGeneratorInput = 1.0, add: any ValidGeneratorInput = 0.0 ) ``` `input`, `distance`, `velocity` accept any `ValidGeneratorInput`. Structural params (`referenceDistance`, `airAbsorptionCutoff`, `speedOfSound`, `sampleRate`, `maxDelayTime`) are `Double`; preconditions enforce `> 0` and `airAbsorptionCutoff < sampleRate/2`. **RT safety.** No allocation or `is`/`as?` casts on the RT thread (per-input `_xIsGenerator` flags pre-computed at init). `denormalsToZero(_:)` applied to LP state. `_mulAdd.applyIfNeeded` after the per-sample loop. No force unwraps. All magic numbers promoted to file-private named constants (`spatialDistanceMinReadRate`, `spatialDistanceMaxReadRate`, `spatialDistanceInitialDelaySamples`, `spatialDistanceMinDelaySamples`, `spatialDistanceMinCutoffHz`, `spatialDistanceMaxCutoffFraction`, `spatialDistanceTwoPi`). **2849 tests at completion** (was 2837; +12 SpatialDistance tests including a deterministic-first-sample numeric check). --- ## Phase 89.5 — Spring + Plate Reverbs Two character-reverb generators alongside `FreeVerb` and `GVerb` in `Sources/Lyrebird/Generators/Reverb/`. ### `SpringReverb.Audio` Schroeder-style spring-tank approximation. Top-level `public enum SpringReverb` namespace, with `public final class Audio: GeneratorBase, AudioGenerator`. Audio-only; no `.Control`; no `GeneratorEnum` conformance. **Topology.** Pre-delay → feedback loop containing a main delay line + 8 cascaded Schroeder all-pass filters (the "chirp") + one-pole HF damping LP + decay multiplier. - Main delay: ~0.05 s at runtime sample rate. - All-pass stages: monotonically increasing prime-near-1ms lengths `[37, 41, 47, 53, 59, 67, 73, 79]` at 44.1 kHz, scaled by `sampleRate/44100` rounded up. - All-pass coefficient: `tension × springReverbMaxAllpassCoeff` (max = 0.9). - Feedback gain from RT60: `g = exp(log(0.001) × totalLoopSamples / (max(decay, 0.001) × sampleRate))`, clamped to `[0, springReverbMaxFeedback = 0.999]`. - Damping LP: `state = (1 − dampCoeff) × x + dampCoeff × prev`, with `dampCoeff = damping × springReverbDampingScale` (max = 0.95). **Stereo.** When `stereo: true`, two parallel tanks share params per sample but use detuned all-pass lengths (right-tank lengths offset by `springReverbStereoSpread = 7` samples). `outputChannelCount` is `1` when `stereo: false`, `2` when `stereo: true`. Structurally fixed at init. **API.** ```swift public init( input: any ValidGeneratorInput, decay: any ValidGeneratorInput = 2.0, tension: any ValidGeneratorInput = 0.5, damping: any ValidGeneratorInput = 0.3, mix: any ValidGeneratorInput = 0.3, preDelay: Double = 0.005, sampleRate: Double = 44100.0, stereo: Bool = false, mul: any ValidGeneratorInput = 1.0, add: any ValidGeneratorInput = 0.0 ) ``` ### `PlateReverb.Audio` Jon Dattorro's 1997 "Effect Design Part 1: Reverberator and Other Filters" (J. Audio Eng. Soc. Vol. 45 No. 9) figure-of-eight tank. Top-level `public enum PlateReverb` namespace. Audio-only; mono in / native stereo out (2 rows). `.left` / `.right` channel aliases via `ChannelSelect.Audio`. **Topology.** ``` input → pre-delay → bandwidth LP → 4 input diffusers (allpass; lengths 142, 107, 379, 277; coeffs 0.75, 0.75, 0.625, 0.625) → Tank loop, two cross-coupled halves: [modulated AP (length 672/908, coeff −0.7, sin LFO ±8 samples)] → [delay (4453/4217)] → [damping LP] → [decay multiplier] → [AP (1800/2656, coeff 0.5)] → [delay (3720/3163)] → cross-feed to opposite half's tank input ``` All lengths and tap offsets are at the Dattorro reference rate of 29761 Hz, scaled to runtime `sampleRate` at init via `Int(base × sampleRate / 29761)`. Outputs are 7-tap weighted sums per channel from Dattorro Table 1, with gain ±0.6. **LFO modulation.** Two phase-offset LFOs (left starts at 0, right at π/2 = 0.25 normalised) at `modRate` Hz, sine-shaped, depth scaled by `modDepth × plateModMaxOffsetSamples × sampleRate/29761`. Modulated all-pass uses linear-interpolated fractional reads. **API.** ```swift public init( input: any ValidGeneratorInput, decay: any ValidGeneratorInput = 0.7, bandwidth: any ValidGeneratorInput = 0.9995, damping: any ValidGeneratorInput = 0.0005, modDepth: any ValidGeneratorInput = 0.5, modRate: any ValidGeneratorInput = 1.0, preDelay: any ValidGeneratorInput = 0.0, mix: any ValidGeneratorInput = 0.3, sampleRate: Double = 44100.0, mul: any ValidGeneratorInput = 1.0, add: any ValidGeneratorInput = 0.0 ) public override var outputChannelCount: Int { 2 } ``` `PlateReverb.Audio` provides `.left` and `.right` computed properties returning `ChannelSelect.Audio(self[0])` / `(self[1])`, matching the `FreeVerb.Audio` precedent. ### RT safety - All buffers pre-allocated at init from `sampleRate`-scaled lengths — modulus arithmetic via `%`, no power-of-two assumption. - `denormalsToZero(_:)` on every IIR feedback state write: damping LP states, all-pass buffer writes, both tank delay-line writes (per-channel), bandwidth LP state, main spring delay. - Per-input `_xIsGenerator` flags pre-computed at init — no `is` / `as?` casts on the RT thread. - Continuous params (`decay`/`tension`/`damping`/`mix`/`bandwidth`/`modDepth`/`modRate`/`preDelay`) read at block-rate via `floatValue` once per `_computeSamples`. The mod LFO advances per sample. - All Dattorro coefficients, lengths, tap offsets, LFO max offset, damping scales, etc. are file-private named `let` constants. Per-block `srScale` re-derivation is hoisted: `_tapApLBaseLen`, `_tapApRBaseLen`, `_modMaxOffsetScaled` are init-time stored `let`s used directly in the per-sample loop. - `_mulAdd.applyIfNeeded(to:graph:count:)` after the per-sample loop. ### Tests - `Tests/LyrebirdTests/SpringReverbTests.swift` — 11 tests: rate, output count, mono-default-output, stereo-flagged-output, silence in → silence out, mix=0 passthrough, deterministic-first-sample, decay produces tail, larger decay → longer tail, fan-out idempotency, mulAdd visible. - `Tests/LyrebirdTests/PlateReverbTests.swift` — 12 tests: rate, output count, 2-row output, silence in → silence out, mix=0 passthrough (L=R=dry), deterministic-first-sample, `.left`/`.right` alias correctness, decay produces tail, larger decay → longer tail, modulation breaks lag-1 autocorrelation, fan-out idempotency, mulAdd visible. **2872 tests at completion** (was 2849; +23: 11 SpringReverb + 12 PlateReverb). ### Non-blocking review observations (left as-is) - SpringReverb / PlateReverb input dispatch uses `_input.calculatedSamples(...).first` — multi-channel inputs silently drop channels >0. Consistent with the existing reverb precedent (`FreeVerb`, `GVerb`); not fixed in this phase. - LFO phase wrap is single-subtract `if _lfoPhase >= 1.0 { _lfoPhase -= 1.0 }` — fails only if `modRate ≥ sampleRate` (academic). Matches the existing `Flanger.Audio` LFO. Not fixed in this phase. - Spring's allpass write uses `x + α × apOut` (Schroeder direct form); Plate's uses Dattorro's `w = x + coeff × buf; y = −coeff × w + buf` form. Both are mathematically valid Schroeder allpasses — kept faithful to source idioms (Smith CCRMA spring vs. Dattorro 1997 plate). --- ## Phase 90 — STK Instrument Models (BowedString + Flute + Clarinet) Three Audio-only physical-modeling waveguide generators in `Sources/Lyrebird/Generators/PhysicalModels/`. All build on the same delay-line + reflection + nonlinear-element pattern as `KarplusStrong`. No `.Control` variant, no `GeneratorEnum` (per-sample feedback loops make block-rate evaluation undefined — same precedent as Phase 78 KarplusStrong, Phase 79 Flanger/Chorus/Phaser, Phase 80 FrequencyShifter, Phase 89 SpatialDistance, Phase 89.5 SpringReverb / PlateReverb). ### `BowedString.Audio` — Smith / Cook split waveguide Two circular delay lines (bridge half + neck half) split at `bowPosition` ∈ (0.02, 0.5]. Bow injection at the junction with Cook's hyperbolic friction table: fric = pow(|deltaV * bowForce| + 0.75, -4) // clamped [0, 1] bowOut = deltaV * fric // bowed energy Reflections: one-pole LP at the bridge end, perfect-inverting at the nut end. Output tapped at the bridge (natural pickup position). Inputs (all `any ValidGeneratorInput`): `freq` (Hz, default 220), `bowVelocity` (default 0.5), `bowForce` (default 3.0, friction-table slope), `bowPosition` (default 0.127 ≈ 1/8). Structural: `sampleRate`, `maxDelayTime`. ### `Flute.Audio` — Cook slide flute Two delay lines (`boreDelay` + `jetDelay`), bore one-pole LP reflection, cubic jet nonlinearity: jetOut = jetSum - jetSum * jetSum * jetSum // soft-clipped [-1, 1] Breath-noise exciter via the shared `xorshift64Next` PRNG helper (Phase 56 WhiteNoise infrastructure — no inline xorshift). `jetRatio` clamped to [0.05, 0.95] of total bore length. Output is post-LP bore signal scaled by `fluteOutputScale = 0.3`. Inputs: `freq` (Hz, default 440), `breathPressure` (default 0.5), `noiseGain` (default 0.03), `jetRatio` (default 0.32), `jetReflection` (default 0.5), `endReflection` (default 0.5). ### `Clarinet.Audio` — Cook single-reed cylindrical bore Single delay line of length `sampleRate / (2 * freq)` (half-wavelength → odd harmonics, period is twice the bore length). Sign-inverted closed-end reflection through a one-pole LP. Linear reed table: reed = clamp(0.7 + reedStiffness * pDiff, -1, 1) boreIn = reflPressure + reed * pDiff Default `reedStiffness = -0.44` (Cook's STK default — negative because the reed closes under positive pressure differential). Inputs: `freq` (Hz, default 220), `breathPressure` (default 0.6), `reedStiffness` (default -0.44, range [-1, 0]), `noiseGain` (default 0.03). ### Shared discipline - `precondition(delayLineLength >= 2)` at init from `Int(ceil(maxDelayTime * sampleRate))`. - `precondition(count <= _result[0].count)` at top of every `_computeSamples`. - `denormalsToZero` on every ring-buffer write **and** on the stored one-pole LP filter state (the Lyrebird review caught the missing LP-state denormal — silence-decay convergence into IEEE 754 denormal range within ~50–100 ms at 44.1 kHz would have caused a sustained CPU stall on the RT thread; fixed before merge). - `_mulAdd.applyIfNeeded(to: &_result, graph:, count:)` at end. - All non-trivial constants named (`bowedStringFrictionPower`, `fluteOutputScale`, `clarinetReedOffset`, …). - Dual `/// - Parameters:` doc blocks (class-level + init-level). - Multi-line init formatting (≥2 params). ### DocC New topic `Sources/Lyrebird/Lyrebird.docc/Generators/PhysicalModels.md` groups the existing `KarplusStrong` + `GatedKarplusStrong` with the three new instruments. `Lyrebird.md` root gains a "Physical Models" section pointer to ``. **2902 tests at completion** (was 2872; +30: 9 BowedString + 9 Flute + 9 Clarinet, plus 3 cross-generator tone-difference tests). ### Non-blocking review observations (left as-is) - Per-sample input dispatch uses `i < samples.count ? samples[i] : scalar` defensive bounds — the codebase contract guarantees `calculatedSamples(count:)` returns ≥ `count` samples, so the guard is redundant. Kept for symmetry with the documented KarplusStrong pattern; will be reviewed in a future architect-agent pass. - Flute jet-delay write stores the *pre-nonlinearity* `jetSum` rather than the *post-nonlinearity* `jetOut`. STK Flute writes the post-nonlinearity value back into the jet path; the Lyrebird formulation here is a simplified-Cook variant chosen at spec time. The instrument is still recognisably flute-like and tests pass. - Flute bore feedback applies `endReflection` to the bore-LP path only, not to the entire bore-return sum. Same comment — simplified-Cook variant, kept stable for this phase. - Flute total-delay clamp at `delayLineCount - 1` (rather than `2 * (delayLineCount - 1)` as in BowedString) means very low frequencies pitch up at the lower bound. Acceptable: the docstring states `maxDelayTime` should be sized for the lowest expected pitch. --- ## Phase 91 — Oversampling Wrapper (Halfband 2× / 4×) ✓ COMPLETE Halfband-FIR oversampling primitives in `Sources/Lyrebird/Oversampling/`, delivered as four allocation-free, RT-safe public value types rather than as a wrapper Generator. The wrapping-Generator framing in the original spec proved awkward — child Generators read `engine.sampleRate` and `engine.blockSize` from the graph, and faking those values for inner-rate evaluation breaks bus / fan-out cache invariants. The helper-struct shape is what Phase 92's Moog ladder (and high-frequency wavefolders / hard clippers more generally) actually want: the wrapping Generator constructs an upsampler, runs its own per-sample nonlinearity twice (or four times) per input, then runs a downsampler. ### Coefficient module — `HalfbandFIR.swift` 23-tap symmetric Type-1 linear-phase halfband FIR (Hamming-windowed sinc, cutoff `π/2`). The halfband property zeros every other tap except the centre, leaving 12 nonzero even-absolute-index taps plus the centre tap held at exactly `0.5`. Six folded coefficient pairs cover offsets `±1, ±3, ±5, ±7, ±9, ±11` from the centre. DC gain normalisation: the unwindowed sinc has DC gain exactly `1`, but Hamming windowing trims roughly 0.22 % off the odd-from-centre tap mass. The folded paired taps are scaled at module load (file-scope `let`, computed once, no RT cost) so total filter DC gain `centerCoef + 2 · sumFolded = 1.0` exactly. Centre tap is preserved at exactly `0.5`, which keeps the upsampler's odd output an exact passthrough of `x[n − 5]` (the `×2` zero-stuff gain compensation cancels with `0.5`). Group delay is `11` samples at the upsampled rate. ### 2× stages - **`HalfbandUpsampler2x`** — polyphase: per input sample, returns `(yEven, yOdd)`. `yEven` = `2 ·` folded sum over six paired taps of the 12-deep input delay line; `yOdd` = `delayLine[(writeIdx − 5) % 12]` exactly (gain-compensated centre passthrough). 12-element circular buffer, modulo indexing. - **`HalfbandDownsampler2x`** — direct-form symmetric FIR with a 23-element circular delay line at the upsampled rate. Per call: push two upsampled samples, compute folded-sum + centre tap. DC gain `1.0` exactly; no `×2` gain compensation. ### 4× stages — cascaded - **`HalfbandUpsampler4x`** — two cascaded `HalfbandUpsampler2x` stages. A single stage-2 instance is driven sequentially with both stage-1 outputs per call, preserving continuity between successive 4× output frames. - **`HalfbandDownsampler4x`** — two cascaded `HalfbandDownsampler2x` stages, mirror of the upsampler. Total 4× round-trip group delay `16.5` input-rate samples (non-integer because the inner half-rate stage straddles input phases — irrelevant for the typical per-sample-nonlinearity use case). ### RT-safety discipline - All state pre-allocated in `init()` (input delay-line `[Double]`, write index). `process(_:)` and `reset()` perform no allocation, take no locks, and call no Foundation routines. Safe to embed inside any `AudioGenerator` and call from the audio thread. - No force unwraps, no `try!`, no magic numbers (every literal named in `HalfbandFIR` enum or via `HalfbandUpsampler2x.delayLineLength`). - Multi-line init formatting on `HalfbandDownsampler4x.process(_:_:_:_:)` (4 params). - Class-level + parameter-level `/// - Parameters:` docs on all four public types. ### DocC New topic `Sources/Lyrebird/Lyrebird.docc/Generators/Oversampling.md` explains usage, halfband design, and RT-safety properties; includes a saturator usage sketch. `Lyrebird.md` root gains an "Oversampling" section pointing at the topic and the four public structs. ### Tests 19 new tests in 4 suites: - `HalfbandFIRTests` — length / counts, centre tap = `0.5` exactly, folded table size, total DC gain `1.0` exactly, alternating signs. - `HalfbandUpsampler2xTests` — DC gain ≈ 1, exact `x[n − 5]` passthrough on odd output, reset, impulse response. - `HalfbandDownsampler2xTests` — DC gain `1`, reset, even-phase impulse hits only the centre tap, odd-phase impulse traces the folded ringing pattern. - `HalfbandRoundTripTests` — 2× + 4× DC unity-gain, 2× + 4× sine RMS preservation (≤ 1.5 % tolerance for Hamming-window passband ripple), image rejection at 0.45 cycles per upsampled-rate sample, 4× cascade reset clears all stages. **2921 tests at completion** (was 2902; +19 oversampling). --- ## Phase 92 — Moog Ladder Filter `MoogLadder.Audio` — Huovilainen-style 4-pole resonant lowpass with per-stage `tanh` saturation, internal 2× oversampling via Phase 91 `HalfbandUpsampler2x` + `HalfbandDownsampler2x`, and SuperCollider-style half-sample feedback compensation. ### Algorithm At the oversampled rate `Fs_os = 2·Fs`: ``` g = min(0.999, 1 − exp(−2π · cutoff / Fs_os)) k = clamp(resonance, 0, 1.4) · 4.0 xfb = x − k · (y4 − 0.5 · x) // SC half-sample feedback comp s = tanh(xfb) y1 += g · (s − tanh(y1)) y2 += g · (tanh(y1) − tanh(y2)) y3 += g · (tanh(y2) − tanh(y3)) y4 += g · (tanh(y3) − tanh(y4)) out = y4 ``` Each input sample is upsampled to two oversampled samples via `HalfbandUpsampler2x`, the ladder runs twice, and the two resulting samples are decimated back to one output sample via `HalfbandDownsampler2x`. Total round-trip group delay is 11 input-rate samples (the halfband FIR group delay). ### Performance The naïve nested-tanh form recomputes `tanh(yN)` once when stage N updates and again when stage N+1 reads it. The implementation caches the post-update `tanh(yN)` in a local, halving the per-sample tanh count from 9 to 5. With 2× oversampling this works out to 10 tanh per input sample (plus the one inside the halfband round-trip's 23 multiply-adds). ### RT safety - Mono Audio-only — no `.Control`, no `GeneratorEnum` (consistent with Phases 78–80, 89, 89.5, 90 precedent for saturating audio filters). - `_result` pre-allocated to `lyrebirdDefaultResultBufferSize`. - `HalfbandUpsampler2x` / `HalfbandDownsampler2x` snapshot the shared `HalfbandFIR.foldedCoefs` table at `init` time so the lazy init runs off the RT thread. - `denormalsToZero(_:)` on every stage state every oversampled sample. - `_mulAdd.applyIfNeeded` used at the standard end-of-block point. ### Public surface - `MoogLadder.Audio(input:cutoff:resonance:mul:add:)` - File-scope constants: `moogLadderResonanceGain`, `moogLadderOversampleFactor`, `moogLadderHalfSampleComp`, `moogLadderMinCutoffHz`, `moogLadderMaxCutoffCoeff`, `moogLadderMaxResonance`. ### DocC New "Saturating Ladder Filters" section in `Filters.md`. New "Built-in users" note in `Oversampling.md` cross-linking back. ### Tests 13 new tests in `MoogLadderTests`: - Rate is `.audio`; `outputChannelCount == 1`. - Fan-out cache hit returns identical samples. - `WhiteNoise` integration produces only finite samples. - Constant-DC input settles to input level (lossless `tanh(yN) = tanh(driver)` identity). - Low-cutoff RMS is at least 2× smaller than high-cutoff RMS for white noise. - Impulse response with high resonance has ≥ 2× the RMS of low resonance. - Generator-driven `cutoff` and generator-driven `resonance` both produce finite output. - Negative cutoff is clamped to `moogLadderMinCutoffHz`. - Resonance above `moogLadderMaxResonance` is clamped, no NaN. - `mul`/`add` settled DC matches `2·x + 0.1` to within 0.01. - Zero input + zero state produces exact silence. **2949 tests at completion** (was 2921; +13 MoogLadder + 15 from prior merges not yet captured in the completion-table delta). --- ## Phase 93 — Convolution Reverb **Status:** Complete on `phase-93` branch. ### Goal Real-time partitioned convolution reverb. Convolves a mono audio input against an arbitrary impulse response stored in a `LyrebirdBuffer`. ### Algorithm — uniformly partitioned overlap-save 1. At init, the IR is split into `numPartitions = ceil(ir.count / P)` partitions of `P = partitionSize` samples (last partition zero-padded). Each partition is zero-padded to `N = 2P`, forward-FFT'd via `vDSP_fft_zrip`, and the resulting split-complex spectrum is stored per-channel in private `UnsafeMutablePointer` slabs. 2. At runtime, the input is buffered in `P`-sample chunks. When a chunk completes, the previous chunk + current chunk form a `2P` window which is forward-FFT'd and written to slot `_fdlPos` of an `numPartitions`-deep frequency-delay line (FDL). 3. For each output channel `c`, the FDL is multiplied-accumulated against the IR partition spectra: - **Bins 1..halfSize-1** use `vDSP_zvma` (split-complex MAC) — pointer arithmetic constructs `DSPSplitComplex` instances offset by `+1` so bin 0 is excluded from the vectorised path. - **Bin 0** packs the DC and Nyquist real values; vDSP's complex MAC would compute `(DC1·DC2 − Nyq1·Nyq2) + j(DC1·Nyq2 + Nyq1·DC2)` — wrong for packed real-FFT semantics. Instead, two scalar fused- multiply-adds maintain `accDC += X.r·H.r` and `accNyq += X.i·H.i`, patched into `_ySumReal[0]`/`_ySumImag[0]` after the partition loop. 4. Inverse FFT of the accumulator yields a `2P`-sample time-domain block. Overlap-save discards the first half; the second half is scaled by `1 / (4·fftSize)` and copied into a per-channel output stage drained one sample at a time on subsequent input samples. ### Scaling factor `vDSP_fft_zrip` forward scales every packed bin by 2; multiplying two forward FFTs (`X·H`) therefore yields packed values 4× the math truth. The inverse FFT contributes an additional `fftSize` factor. The combined correction is `1 / (4·fftSize)`. Cached at init in `_ifftScale` and applied via `vDSP_vsmul` to the second half of the IFFT output only. ### Latency Inherent latency equals `partitionSize` samples — one partition must accumulate before any output is produced. ### Multi-channel output `outputChannelCount` returns `ir.channelCount`. A mono input is convolved separately against every IR channel. Stereo room IRs (the typical case) yield stereo output; ambisonic / quadraphonic IRs yield matching N-channel output. `.left` / `.right` channel aliases mirror the rest of the reverb family. ### IR snapshot The IR is FFT-partitioned at `init` and not re-read afterwards. Mutating the source buffer via `setValue` does NOT update the convolution. To swap IRs, build a new `ConvolutionReverb.Audio`. Documented loudly. ### Limits - `convolutionReverbMaxPartitionSize` = 8192 (power-of-two precondition prevents unbounded FFT-table allocation). - `convolutionReverbMaxPartitionCount` = 16384 (caps total IR length at ~67 s × `P/256` at 48 kHz). Trap rather than silently allocate gigabytes. ### RT safety - All FDL spectra, scratch FFT arrays, IR partition spectra, input accumulator, output stage, and IFFT scratch pre-allocated in `init` via `UnsafeMutablePointer` raw allocations. - `FFTSetup` created once at `init`, destroyed in `deinit`. - `_computeSamples` / `_doPartitionStep` perform no heap allocation, no locking, no Swift array growth. - `_inputIsGenerator` classified at init, never queried at RT. - `_mulAdd.applyIfNeeded` at the standard end-of-block point. ### Public surface - `ConvolutionReverb.Audio(input:ir:partitionSize:mix:mul:add:)` - `convolutionReverbDefaultPartitionSize`, `convolutionReverbMaxPartitionSize`, `convolutionReverbMaxPartitionCount` public file-scope constants; `convolutionReverbForwardFFTScaleSquared` private. - `.left` / `.right` channel-alias extensions. ### DocC New "ConvolutionReverb" section in `Generators/Reverbs.md` with topology diagram, latency note, IR-snapshot warning, partition-size guidance, and channel-alias examples. Reverbs table updated to include the new entry. ### Tests 13 new tests in `ConvolutionReverbTests`: - Rate is `.audio`. - `outputChannelCount` matches `ir.channelCount` (1 / 2 / 4). - Silent input produces silent output (after warmup). - `mix = 0` is exact dry passthrough. - Unit-impulse IR is identity (after one-partition latency). - Delayed-impulse IR delays input by IR delay + partition latency. - Multi-partition IR (length > partitionSize) places echoes correctly. - `mulAdd` applied to dry-only output. - Stereo IR produces distinct left/right channels. - Fan-out cache hit returns identical samples. - `.left` / `.right` aliases construct. - Power-of-two `partitionSize` accepted. - Energy is preserved on identity IR (within 1e-3). **2962 tests at completion** (was 2949; +13 ConvolutionReverb). --- ## Phase 94 — MIDI File Import **Status:** Complete on `phase-94` branch. ### Goal Parse Standard MIDI Files (SMF formats 0 + 1) and dispatch their events through ``LyrebirdClock`` for sample-accurate playback. Pure language-side — no CoreMIDI dependency, no external library. ### Public surface `Sources/Lyrebird/MIDI/SMF/`: - ``MIDIFileError`` — typed error enum covering every parse-time failure mode (bad magic, format 2, SMPTE division, malformed VLQ, missing running status, system-common bytes in track, file-read failure, etc.). - ``MIDIFileEvent`` — beat-stamped event with `trackIndex` + `Kind` enum spanning channel messages (`.midi(MIDIMessage)`) and surfaced meta events (`.tempo`, `.timeSignature`, `.keySignature`, `.trackName`, `.instrumentName`, `.text`, `.copyright`, `.lyric`, `.marker`, `.cuePoint`, `.endOfTrack`). `.tempo` exposes a `.bpm` computed accessor. - ``MIDIFileTrack`` — `index` + optional `name` + `events` + convenience `lastBeat` / `channelEvents`. - ``MIDIFile`` — top-level type with `format` / `ticksPerQuarter` / `tracks` + `allEvents` (stable sort on `(beat, trackIndex)`) / `allChannelEvents` / `tempoMap` / `totalBeats` views + `parse(_:)` / `read(filePath:)` entry points. - ``MIDIFilePlayer`` — owns an internal ``LyrebirdRoutine``; walks `allEvents` calling `ctx.wait(beats:)` between them, dispatches `.midi` to the caller's handler, optionally applies `.tempo` to `clock.bpm` (or forwards via `metaHandler`), routes other meta to the optional `metaHandler`. ### Algorithm 1. Header chunk: validate `MThd` magic, length 6, format 0/1, tracks > 0, PPQ division (top bit clear, value > 0). 2. Track chunks: validate `MTrk` magic, read declared length, walk delta-time + event pairs. 3. Delta times decoded as 1–4-byte SMF variable-length quantities. 4. Channel events follow running-status rules; meta and sysex events clear running status. 5. Status nibble drives data-byte count: `0xC0`/`0xD0` (program change, channel pressure) take 1 data byte; everything else takes 2. 6. Meta events dispatched through ``decodeMetaEvent`` with named metaType constants — unrecognised types silently skipped. 7. SysEx payloads (`F0` / `F7`) advanced past, no event surfaced. 8. Tick→beat conversion at parse time: `beat = absoluteTicks / ticksPerQuarter`. ### Boundary handling - `SMFParser.init` re-bases sliced `Data` so byte indexing via `data[cursor + i]` is safe regardless of the input's `startIndex`. - `0xF1`–`0xF7` system-common bytes in tracks raise `unsupportedSystemCommonStatus` rather than mis-parsing as channel voice messages. - VLQ caps at four bytes (28 bits) per the SMF spec. ### Player threading ``MIDIFilePlayer.play`` synchronously joins any prior routine via ``LyrebirdRoutine/reset()`` before starting a fresh routine. Handler closures fire on the routine thread — keep them lightweight. ``stop`` / ``reset`` / ``state`` lifecycle behind an NSLock-protected slot. ### Tests 21 new tests across two suites: - `MIDIFileTests` (18 tests) — header parsing for formats 0 and 1; rejection of format 2, SMPTE division, bad magic, zero tracks; channel events with delta times; running status; tempo meta with BPM conversion; track name; time signature; multi-track merge with stable sort; large VLQ delta (`0x0FFF_FFFF`); sysex skipping; end-of-track surfaced; velocity-zero noteOn → noteOff; program change one-data-byte; `totalBeats`. - `MIDIFilePlayerTests` (3 tests) — player dispatches all channel events in order; `stop()` returns to `.idle`; tempo map applied to clock when `applyTempoMap == true`. **2983 tests at completion** (was 2962; +21 SMF parser/player). --- ## Score Phase A — Score System (types + DSL + flatten) **Status:** Complete on `score-A` branch. ### Goal Author musical scores in Swift directly. Notes, rests, chords, dynamics, articulations, and tuplets — all expressed in a result-builder DSL with exact rational tuplet math. Phase A is types + flatten only; player and SMF bridges follow. ### Public surface `Sources/Lyrebird/Score/`: - ``Fraction`` — `Int64` reduced rational with cross-cancellation in `*`, `Comparable`. Backbone of exact tuplet arithmetic. - ``NoteDuration`` — `.fraction(Fraction)` (preferred) or `.beats(Double)` escape hatch; named conveniences `.whole`, `.half`, `.quarter`, `.eighth`, `.sixteenth`, `.thirtySecond`, `.sixtyFourth`, `.zero` plus `.dotted(_:)` / `.doubleDotted(_:)`. - ``Pitch`` — `.midi(Int)` / `.freq(Double)` / `.named(NoteName, Int)` / `.rest` sentinel. Octave 4 contains middle C. `midiNote` is range- checked to `[0, 127]`. - ``NoteName`` — diatonic + sharp/flat enum with `.semitone`. - ``Dynamic`` — `.ppp`–`.fff` plus `.raw(Double)`. SC-style velocity table with `mf` at 0.6, `f` at 0.85; `midiVelocity` returns `[0, 127]`. - ``Articulation`` — `.normal`, `.staccato`, `.staccatissimo`, `.legato`, `.tenuto`, `.accent`, `.marcato`. `durationScale` modifies played duration; `velocityBonus` is added to the notated dynamic and clamped. - ``ScoreEvent`` — flat output of ``ScorePart/flatten()``: `beat` / `duration` / `pitch` / `velocity` / `voice` / `articulation`. - ``ScoreElement`` — `.note(_:duration:dynamic:articulation:voice:)` / `.rest(duration:)` / `.chord(_:duration:dynamic:articulation:voice:)` / `.tuplet(actual:normal:children:)`. Free-function constructors `Note`, `Rest`, `Chord`, `Tuplet` for the DSL. - ``ScorePart`` — named timeline with channel hint; `flatten()` walks the element tree. - ``Score`` — `bpm` + `timeSignature` + `parts`; DSL initialiser via `@ScorePartBuilder` and `@ScoreBuilder` result builders; `Part` free function constructor. ### Tuplet design ``Tuplet(actual: Int, inTimeOf normal: Int) { … }`` multiplies every child duration by `Fraction(normal, actual)`. Ratios compose under nesting via fraction multiplication: a 5-in-time-of-4 quintuplet wrapping a 3-in-time-of-2 triplet makes the total span exactly 2 beats — the cursor lands on a clean `Double` after the tuplet, no FP drift from sums of `1/3 + 1/3 + 1/3`. `_flatten` keeps the cursor in `Fraction` form for the duration of the walk and only emits `Double` on the final `ScoreEvent.beat` write. `.beats(Double)` durations re-encode the cursor at denominator `2^20` so mixed scores still produce sub-microsecond-stable beat positions. ### Rest semantics Rests advance the cursor only — they are NOT emitted as `ScoreEvent`s by `flatten()`. The `Pitch.rest` sentinel exists for callers building `ScoreEvent` instances directly (e.g. UI scrubbers that want to display silences as rest markers). `Pitch.rest.midiNote == nil`. ### Tests 28 new tests across two suites: - `FractionTests` (12): construction with reduction, sign normalisation, `zero` / `one`, addition (with reduction), multiplication (with cross-cancellation), tuplet scale composition, subtraction, comparison, `Double` conversion, `gcd` edges, exact `1/3 + 1/3 + 1/3 == 1` round-trip. - `ScoreTests` (16): single-note flatten, rest advances cursor without emitting, chord splits to N simultaneous events, triplet flatten, triplet leaves cursor at exact beat, nested quintuplet+triplet ratio composition, dotted quarter, dynamic→velocity mapping, articulation duration+velocity effects, velocity clamp at 1.0, full DSL Score, MIDI/named pitch agreement, enharmonic equivalence, MIDI out-of-range returns nil, rest sentinel `midiNote` nil, `midiVelocity` boundaries, `totalBeats` across parts, voice override. **3014 tests at completion** (was 2983 on `main`; +31 from Score Phase A plus 3 unrelated tests landed in upstream main). ### Phases B and C (deferred) - **Phase B**: `ScorePlayer` walking the flat event list against a `LyrebirdClock` on a `LyrebirdRoutine` thread, mirroring `MIDIFilePlayer`. - **Phase C**: SMF↔Score bridges — pair noteOn/noteOff into `ScoreEvent`s; emit SMF bytes from a `Score`. --- ## Score Phase A — spelling preservation (Letter + Accidental + NoteName struct) **Status:** Complete on `score-A-spelling` branch. ### Goal Preserve note spelling end-to-end so future MusicXML import / export round-trips losslessly. `C♭` and `B` are distinct `NoteName` values even though they share a MIDI number; quarter-tone accidentals are first-class. ### Public surface `Sources/Lyrebird/Score/`: - ``Letter`` — `c`, `d`, `e`, `f`, `g`, `a`, `b` enum. `rootSemitone: Int` (0–11) and `glyph: String` (`"C"`–`"B"`). - ``Accidental`` — nine-step microtonal grid: `doubleFlat`, `threeQuarterFlat`, `flat`, `quarterFlat`, `natural`, `quarterSharp`, `sharp`, `threeQuarterSharp`, `doubleSharp`. `semitones: Double` (`-2.0`…`+2.0` in 0.5-step increments), `cents: Int`, `isQuarterTone: Bool`, `glyph: String` (Unicode for half-steps; Lyrebird hybrid notation for quarter-tones). - ``NoteName`` — refactored from `enum` to `struct (letter, accidental)`. `Hashable` on the pair so spellings stay distinct. `semitones: Double` (full chromatic offset including accidental), `semitoneInt: Int?` (`nil` for quarter-tones), `glyph` combines letter + accidental. - Static-let factories cover every standard spelling (`.c`, `.cSharp`, `.dFlat`, `.cFlat`, `.bSharp`, `.eSharp`, `.fFlat`, `.cDoubleSharp`, `.dDoubleFlat`, plus quarter-tone variants `.cQuarterSharp`, `.dThreeQuarterFlat`, etc.) — existing call sites compile unchanged. `Pitch` updates: - ``Pitch/midiNoteFractional`` — new `Double?` accessor preserving quarter-tone precision. - ``Pitch/midiNote`` rounds via Swift round-half-away-from-zero. - ``Pitch/frequency`` derives from the fractional MIDI so quarter-tone pitches produce real cent offsets. ### Octave conventions The letter determines the notational octave regardless of accidental: ```swift Pitch.named(.cFlat, 4).midiNote // 59 — letter C in octave 4 Pitch.named(.bSharp, 3).midiNote // 60 — letter B in octave 3 ``` ### Quarter tones ```swift Pitch.named(.cQuarterSharp, 4).midiNoteFractional // 60.5 Pitch.named(.cQuarterSharp, 4).frequency // C4 × 2^(0.5/12) ``` ### Tests 19 new tests in `PitchSpellingTests`: - Letter root semitones for all seven letters. - Accidental semitone / cent / `isQuarterTone` mappings. - `NoteName.letter` / `accidental` accessibility. - Composed `semitones` for `cSharp` / `dFlat` (same MIDI, different spelling), `cFlat` / `bSharp` (cross-octave-boundary spellings), quarter-tone variants. - `semitoneInt` returns nil for quarter-tone accidentals. - Spelling preservation: `cSharp != dFlat`, `cFlat != b`, `bSharp != c` as `NoteName` and as `Pitch` values. - Octave is letter-based: `Cb4 → 59`, `B♯3 → 60`. - Double accidentals: `Cbb4 → 58`, `B𝄪3 → 61`. - Enharmonics share MIDI: `Cb4` MIDI matches `B3` MIDI. - Quarter-tone fractional MIDI: `cQuarterSharp4 → 60.5`, `dThreeQuarterFlat4 → 60.5`. - Quarter-tone frequency offset matches `2^(0.5/12)` ratio. - Glyph composition (`"C♯"`, `"B𝄫"`). - `Set` distinguishes spellings. - Default accidental is `.natural`. - Octave boundary: `bSharp8 → 120` (in range), `bSharp9 → nil`, `cFlat-1 → nil`. **3034 tests at completion** (was 3014 on `main` after Score Phase A; +19 spelling tests; +1 boundary test added during review). ### Source compatibility `NoteName` was an `enum: CaseIterable`; the struct refactor drops `CaseIterable` (no internal callers existed; no tests broke). The `semitone` API is preserved as a deprecated computed `var` that rounds quarter-tone pitches to the nearest integer rather than the previous case-table integer return. --- ## Score Phase B — ScorePlayer (clock-driven Score playback) **Status:** Complete on `score-B` branch. ### Goal Walk a ``Score`` against a ``LyrebirdClock`` on a background routine thread, mirroring the ``MIDIFilePlayer`` pattern. Two playback modes — high-level ``ScoreEvent`` dispatch and lower-level paired noteOn / noteOff MIDI dispatch. ### Public surface `Sources/Lyrebird/Score/`: - ``ScorePlayer`` — owns an internal ``LyrebirdRoutine``; lifecycle is ``play(applyScoreTempo:handler:)`` / ``playMIDI(applyScoreTempo:handler:)`` / ``stop()`` / ``reset()`` / ``state`` behind an NSLock-protected routine slot. Type changes: - ``ScoreEvent`` gains `channel: Int` (default `0`); populated from ``ScorePart/channel`` during `_flatten` so MIDI playback routes to the right channel. - ``Score`` gains computed `allEvents: [ScoreEvent]` — merged + stable- sorted by `(beat, channel)` for use as the player's input stream. Documented O(N log N) cost; not cached. ### Playback modes **Mode 1: `play(handler:)`** dispatches one ``ScoreEvent`` per notated event in beat order. Caller decides what to do with `pitch`, `velocity`, `duration`, `articulation`, `voice`, and `channel`. Appropriate when driving Lyrebird synthesizers directly through `@LiveParam` setters or scheduled adds. **Mode 2: `playMIDI(handler:)`** splits every event into paired noteOn / noteOff ``MIDIMessage``s. Note-offs land at `event.beat + event.duration`. The merged on/off stream is sorted by `(beat, midiOrderRank)` so a noteOff at the same beat as another note's noteOn is emitted FIRST — this avoids stuck-key behaviour in samplers when consecutive notes touch. Events whose ``Pitch/midiNote`` is `nil` (rests, out-of-range pitches) are silently skipped. ### Tempo handling `applyScoreTempo: Bool` (default `true`) writes ``Score/bpm`` into ``LyrebirdClock/bpm`` at start. Pass `false` to keep the clock's existing tempo and re-pace the score. ### Threading `play` / `playMIDI` / `reset` snapshot the previous routine slot **outside** `_routineLock` before calling `LyrebirdRoutine.reset()`. The lock is NEVER held across the blocking thread join — this prevents a deadlock that would otherwise occur if a handler closure calls back into any lock-protected `ScorePlayer` method (`stop`, `state`, etc.). Handler closures fire on the routine thread. ### Tests 10 new tests in `ScorePlayerTests`: - Part channel propagates through `flatten()` to every ``ScoreEvent``. - `Score.allEvents` merges and stable-sorts by `(beat, channel)`. - `play(handler:)` dispatches every channel event in beat order. - `play` writes `Score.bpm` to the clock by default. - `play(applyScoreTempo: false)` preserves clock bpm. - `playMIDI` emits paired noteOn / noteOff per event. - `midiOnOffStream` orders noteOff before noteOn at identical beat. - `midiOnOffStream` skips rests and out-of-range pitches. - `stop()` returns to `.idle` cleanly. - `ScoreEvent` default channel is `0`. **3044 tests at completion** (was 3034 on `main` after spelling phase; +10 player tests). --- ## Score Phase C — SMF ↔ Score bridges **Status:** Complete on `score-C` branch. ### Goal Bidirectional Standard MIDI File ↔ ``Score`` conversion. Round-trip monophonic Score events through `Score → SMF byte data → parse → Score` exactly. Pure language-side, no external dependency. ### Public surface `Sources/Lyrebird/MIDI/SMF/`: - `SMFEncoder` — internal helpers: VLQ encode (with 28-bit overflow precondition), BE `UInt16` / `UInt32`, header chunk, track chunk wrapper, paired noteOn / noteOff append, `FF 51` setTempo / `FF 58` timeSignature / `FF 03` trackName / `FF 2F` endOfTrack meta-event builders, BPM ↔ µs-per-quarter, time-signature denominator power-of-two encoding (with precondition). `Sources/Lyrebird/Score/`: - ``MIDIFile/toScore(partNamePrefix:skipChannelLessTracks:)`` — walks parsed events, pairs noteOn / noteOff per `(channel, note)` using a LIFO stack (overlapping repeats on the same pitch end the most-recent first). Orphan noteOns close at `trackEnd`. Tempo + time signature pulled from the earliest meta events in a single `allEvents` pass. Track names map to ``ScorePart/name``; first channel encountered in a track sets ``ScorePart/channel``. - ``Score/toMIDIFileBytes(ticksPerQuarter:)`` — emits SMF format 1. Track 0 carries setTempo + timeSignature + endOfTrack. Tracks 1..N each correspond to one ``ScorePart`` with a track-name meta and paired noteOn / noteOff at `event.beat × ppq` ticks. Note-offs at the same tick as another noteOn sort first to avoid stuck-key behaviour. Zero-velocity events clamp to MIDI velocity 1 (else parse-time noteOn → noteOff aliasing eats the note). ### Safety - Malformed SMF input cannot crash `toScore()`: `denPow2` is clamped to `maxTimeSignaturePow2 = 30` before `1 << denPow2`, well past any musical denominator and inside `Int` shift safety. - All chunk sizes / channel ranges / MIDI note ranges reference named constants (`Pitch.maxMidiNote`, `Score.midiMaxChannel`, `SMFEncoder.headerChunkTotalSize`, `trackChunkHeaderSize`, `defaultMIDIClocksPerBeat`, `defaultThirtySecondsPerQuarter`). ### Tests 18 new tests in `ScoreSMFBridgeTests`: - Score → SMF byte-level header shape (`MThd`, format word, ntrks word, division word). - Score → SMF round-trips through `MIDIFile.parse(_:)`. - Tempo meta (`FF 51`) emitted and parsed back. - Time-signature meta (`FF 58`) round-trips with `denPow2` correct. - Track-name meta (`FF 03`) emitted and parsed back as `ScorePart.name`. - Part channel dictates emitted MIDI channel. - Note-off ordered before note-on at same tick (no stuck keys). - Velocity 0 score events emit as MIDI velocity 1 (no noteOff aliasing). - SMF → Score preserves tempo / time signature. - SMF → Score preserves track name on resulting part. - SMF → Score pairs durations correctly. - Channel-less tracks dropped by default; kept on `skipChannelLessTracks: false`. - Full round-trip preserves monophonic events to ≤ 1e-3 beat / duration tolerance. - VLQ encoder edge cases (`0`, `127`, `128`, `480`, `0x0FFF_FFFF`). - Time-signature denominator power-of-two encoding (`1`–`16`). - Microseconds-per-quarter ↔ BPM round-trip. - Multi-part Score → multi-track SMF. **3062 tests at completion** (was 3044 on `main` after Phase B; +18 bridge tests). ### Phase D (deferred) MusicXML import / export on a separate branch when ready. MusicXML preserves pitch spelling (`` + ``), chord structure, voicing, and tuplet markers — the lossless path that SMF cannot provide. Phase D will round-trip ``NoteName`` (Letter + Accidental) exactly. --- ## Score Phase D — MusicXML 4.0 score-partwise bridges **Status:** Complete on `score-D` branch. ### Goal Lossless Score ↔ MusicXML round-trip, preserving pitch spelling (`` + `` + ``), chord groupings, articulations, tempo, and time signature. Pure language-side, Foundation `XMLParser` for read, raw string emission for write. ### Public surface `Sources/Lyrebird/Score/MusicXML/`: - ``MusicXMLError`` — typed errors: `xmlParseFailed`, `unsupportedRoot`, `unsupportedTimewiseDocument`, `fileReadFailed`. - ``Score/toMusicXMLString(divisions:)`` and ``Score/toMusicXMLData(divisions:)`` — emit `score-partwise` 4.0. - ``Score/fromMusicXML(data:)`` and ``Score/fromMusicXML(filePath:)`` — parse a document into a Score. Internal `_MusicXMLParser` is an `XMLParserDelegate` subclass with a chord-buffer flush so consecutive `` blocks aggregate into a single ``ScoreElement/chord(_:duration:dynamic:articulation:voice:)`` element. First-time-signature-wins via `inTime` / `sawTimeSignature` gating; multi-time-sig documents preserve only the first. ### What round-trips losslessly - Pitch spelling (Letter + Accidental, including doubles + the four quarter-tone steps via fractional `` 0.5 / -1.5 / etc.). - Letter-based octave (`C♭4 → MIDI 59`, octave stays 4). - Beat positions / durations via configurable `` (default 480). - Chord groupings (`` flag). - Articulations (``, ``, ``, ``, `` for marcato, `` as a direct child of `` for legato). - Tempo from either `` text OR `` attribute (covers MuseScore-style files that omit the metronome block). - First time signature. - Track / part names with XML entity escaping. ### v1 limitations - One measure per part on emit (no barline splits + ties). - No tuplet markers on emit — Tuplet-authored events come through with already-scaled durations and re-flatten correctly via beat math, but the XML carries no ``. - No `` / `` for multi-voice layering on parse — multi-voice scores may land out of order. - No `` round-trip. - No ``, ``, `` direction, beams, ornaments. ### Tests 27 new tests in `MusicXMLTests`: - Encode shape: ``, part-list, score-part, part-name, measure, pitch with step/alter/octave, natural notes (no ``), rest, chord (with `` flag), articulations, tempo + time signature, MIDI-pitch spelling, XML entity escaping. - Parse: simple note, spelling preservation (`Cb4` ≠ `B3`), quarter- tone alter, tempo from per-minute, tempo from sound attribute, time signature, timewise rejection, rest, chord shares onset, articulation, first-time-signature-wins on multi-time-sig documents. - Round-trip: spelling (`cFlat`/`bSharp`/`eSharp`/`fFlat`/quarter- tones), tempo + time signature, chord, articulation, legato via ``. - Malformed XML throws. **3089 tests at completion** (was 3062 on `main` after Phase C; +27 MusicXML tests). ### Score system end-to-end Phase A (types + DSL + tuplets) → Phase A spelling (Letter + Accidental + quarter-tones) → Phase B (ScorePlayer) → Phase C (SMF ↔ Score) → Phase D (MusicXML ↔ Score) closes the loop on the Lyrebird Score system: a fully Swift-native musical event representation that authors in code, plays through the audio engine, exchanges with notation tools via MusicXML, and exchanges with DAWs / sample libraries via SMF. --- ## Phase 96a — MIDI Clock follow `MIDIClockFollower` (`Sources/Lyrebird/MIDI/Sync/MIDIClockFollower.swift`) consumes `MIDIMessage` values delivered by a `MIDI` handler and follows a `LyrebirdClock`'s tempo from external 0xF8 clock bytes. **Algorithm.** Each `.clock` message captures `engine.currentTime` (atomic load, safe from the `lyrebird.midi` background queue). A rolling buffer of the last *N* tick sample-times (default `N = 24` = one quarter-note window) feeds an inter-tick average; with 24 ticks/quarter-note this gives `bpm = 60 / (avgSec * 24)`. The estimate is clamped to `[minBPM, maxBPM]` (defaults `20.0 ... 999.0`) and pushed to `clock.bpm` only when it changes by more than `bpmUpdateEpsilon = 0.01` BPM. The `clock.bpm` write happens *outside* the follower's own lock so the path `MIDIClockFollower._lock → LyrebirdClock._lock` cannot deadlock against any reverse path. **Transport.** `.start` and `.continue` set `_isRunning = true` and clear tick history. `.stop` sets `_isRunning = false` and clears history but does not touch `clock.bpm`. `_handleClock` is gated on `_isRunning`, so subsequent ticks while stopped are ignored. The default of `_isRunning = true` lets free-running clock sources without transport messages update `clock.bpm` out-of-the-box. **Beat-alignment limitation.** `LyrebirdClock` does not expose a phase-realignment API, so `.start` cannot reset the clock's beat phase to match the incoming transport position. Downstream code that needs alignment must snapshot `clock.currentBeat` at the moment `.start` is observed and offset its own beat math. **Test injection.** A second internal `init(clock:sampleRate:… timeProvider:)` accepts a `@Sendable () -> SampleTime` closure so the unit tests drive the follower with synthetic sample-times without a running engine. Public API is unchanged. **MIDIMessage extension.** `.continue` (0xFB) was missing; added to the enum (using the `` `continue` `` keyword escape), the `from(status:data1:data2:)` parser, and `bytes()`. The UMP encoder needed no change — system-realtime status bytes still route through the `(status & 0xF0) == 0xF0 ? 0x1 : 0x2` test. **Docs.** `docs/tooling/midi-clock-sync.md` is the user-facing guide; `docs/roadmap/ableton-link.md` stubs Phase 96b. **3122 tests at completion** (was 3108 on `main` after inter-phase ramps; +13 follower tests + 1 `.continue` round-trip). ### Phase 96b — Ableton Link Deferred. Stub at `docs/roadmap/ableton-link.md`. --- ## Phase 95 — Scanned Synthesis `ScannedSynthesizer.Audio` (`Sources/Lyrebird/Generators/PhysicalModels/ScannedSynthesizer.swift`) implements Mathews/Verplank 2000 scanned synthesis: a 1D ring of *N* masses connected by springs, updated at audio-block rate; a phasor scans the displacement array at audio rate as a continuously-evolving wavetable. **Network update.** Per audio block, two-pass explicit Euler: ``` // Pass 1 — accelerations from old state (Jacobi) accel[i] = stiffness * (x[i-1] - 2·x[i] + x[i+1]) - damping * v[i] - centeringForce * x[i] + extForce[i] // Pass 2 — integrate v[i] += accel[i] * dt x[i] += v[i] * dt ``` Two passes (rather than the simpler in-place loop) prevent the asymmetric Gauss-Seidel coupling that an in-place scheme would produce — every mass sees the same starting state, preserving ring symmetry. `dt = blockSize / sampleRate` precomputed at init. `denormalsToZero` flushes both `v` and `x` after each integration. A pre-allocated `_accelerations: [Double]` scratch array sized at `massCount` holds pass-1 results. **Excitation.** Excitation `ValidGeneratorInput` is sampled once per audio block via `lastGeneratorSampleOrFloat` and injected as an external force at a single configurable mass index (`excitationIndex`, default 0). Documented as block-rate sampling; finer detail requires smaller `blockSize`. **Audio-rate scan.** Per sample: phasor advances `freq * massCount / sampleRate`; `_positions[]` read through `oscillatorTableRead(phase:interpolation:)` (none / linear / cubic). The shared helper in `OscillatorTableReadHelpers.swift` gained `[Double]`-array overloads so the same Catmull-Rom code path serves both `LyrebirdBuffer` and in-place `[Double]` state — no Catmull-Rom literals duplicated in the generator. **Structural parameters.** `massCount` must be a power of two in `[4, scannedSynthesizerMaxMassCount = 1024]`; `excitationIndex` must be in `0 ..< massCount`. `sampleRate` and `blockSize` are required init params (no defaults) — `_dtPerBlock` is precomputed at init, not read from `graph.engine` on the RT thread. **Initial displacement.** `ScannedSynthesizerShape` enum (own file) chooses the init-time `_positions[]` preset: - `.gaussian` — bell curve centred mid-ring - `.sine` — one cycle around the ring - `.impulse` — single mass at `excitationIndex` displaced - `.zeros` — silent until excitation arrives **Shape.** `Audio` only (no `.Control`, no `GeneratorEnum`) — matches Phase 78/79/80/89/89.5/90 STK-style instrument precedent. `_computeSamples` only — no `calculatedSamples` override; the `Generator` extension's segment-serial caching gateway is sufficient. **Tests.** 16 `@Test` cases cover: `.zeros` + zero excitation → silence; `.gaussian` / `.sine` / `.impulse` initial states produce non-zero output; high damping decays faster than low damping; excitation drives a `.zeros` network; mul/add propagation; phasor wraps over many blocks (no NaN/Inf); all three interpolation modes produce finite output; state advances exactly once per block (fan-out single-evaluation invariant); engine integration via a wrapping `SynthesizerBase`. **3138 tests at completion** (was 3122 on `main` after Phase 96a; +16 ScannedSynthesizer tests). --- ## Phase 97 — MuTronIII Auto-Wah `MuTronIII` Generator — envelope-controlled resonant filter modelling the Musitronics Mu-Tron III (1972). Both `Audio` and `Control` rates. Mono output. **Topology (per audio sample, `Audio` variant):** ``` abs_x = |x[n]| × sensitivity // full-wave rectify + drive coeff = abs_x > _prevAmp ? attackCoeff : releaseCoeff _prevAmp = coeff·_prevAmp + (1−coeff)·abs_x // asymmetric 1-pole follower env = max(0, min(_prevAmp, 1.0)) sweep = direction == .up ? env : (1 − env) cutoff = freqLo · (freqHi / freqLo)^sweep // exponential pitch sweep // Chamberlin SVF (state: low, band) f = min(1.0, 2·sin(π·cutoff/sr)) q1 = 1.0 / max(1.0, peak) low = low + f·band high = x − low − q1·band band = f·high + band out = mode == .lowpass ? low : .bandpass ? band : high ``` The follower and SVF are inlined (not composed via sub-Generators) to keep the inner per-sample loop allocation- and dispatch-free. **Public API.** `MuTronIIIMode` (`.lowpass`/`.bandpass`/`.highpass`) and `MuTronIIISweep` (`.up`/`.down`) are `let` constants set at `init` — never checked on the RT path. Each enum lives in its own file. Init takes `input`, `mode`, `direction`, `sensitivity`, `peak`, `freqLo`, `freqHi`, `attackTime`, `releaseTime`, `mul`, `add`. Defaults match a classic bandpass auto-wah (peak = 4.0, freqLo = 80, freqHi = 3200, attack = 5 ms, release = 150 ms). **Guards.** Discovered across four review passes: - `_inputIsGenerator` classified at `init`; scalar inputs use `floatValue` once per block to avoid `Double.calculatedSamples` per-block heap allocation. - `sensitivity` clamped ≥ 0 (negative would push `_prevAmp` negative through `abs(x) · sensitivity` and break sweep direction). - `freqLo` clamped to `[0.001, Nyquist]`; `freqHi` clamped to `[freqLo, Nyquist]` (monotone ratio; pow base positive; sin doesn't wrap past `sr/2`). - `peak` clamped to `≥ 1.0` — Chamberlin SVF stability requires `q1 + f < 2`, and the Nyquist-clamped sweep can drive `f → 1.0`, so `q1 ≤ 1` is required. - `denormalsToZero` applied to `_prevAmp`, `_svfLow`, `_svfBand` after every IIR update. - `Control._computeSamples` advances state over `blockSize` samples once per audio block (standard bypass pattern), then `fillRampedResult` interpolates between previous and current targets across `count` output samples. **Block-rate parameter reads.** `sensitivity`, `peak`, `freqLo`, `freqHi`, `attackTime`, `releaseTime` all read once per block via `lastGeneratorSampleOrFloat`. Per-sample modulation of these isn't needed for musical auto-wah behaviour — the cutoff itself is recomputed every sample from `_prevAmp`, which is the actual modulation source. **Tests.** 24 `@Test` cases: rate, channel count, fan-out, sub-block bypass, integration into a SynthGraph (Audio + Control), default constructor, mode output difference, up vs down sweep, generator-driven `sensitivity`/`peak` LFO, block-boundary continuity, mul/add propagation, `GeneratorEnum` aliases, denormal guard after long silence, Control `previousOutputValue` ramp, audio/control parity, negative-sensitivity clamp (output equals `sensitivity = 0` reference within `1e-9`), `freqHi` above Nyquist clamp, non-positive `freqLo` clamp, and `deterministicSampleOutput` — hand-replicates the Chamberlin recurrence for samples 0 and 1 (highpass mode, `peak = 1`, `sensitivity = 0`, `freqLo = freqHi = 440 Hz`) and asserts exact match within `1e-12`. **Review history.** Required four passes: 1. Initial: blocked on RT alloc via scalar `Double.calculatedSamples`, `_mulAdd` skipped in Control nil-input fallback, no deterministic test. 2. Doc/code divergence: algorithm pseudocode said `q1 = 1 / max(0.0001, peak)` but code used `0.5` floor. 3. Same divergence: `Control` still had `minPeak = 0.5` after `Audio` was raised to `1.0` — `replace_all` only matched the doc strings, not the inline constants. 4. Clean. **3162 tests at completion** (was 3138 on `main` after Phase 95; +24 MuTronIII tests). --- ## Phase 99 — Spectral Filtering + Phase Manipulation **Goal:** Extend spectral toolkit with bin-domain filters, phase ops, and magnitude shaping. All polar-native (zero rect↔polar work), RT-safe, single `SpectralProcessor` register-call each. No new buffer plumbing. Seven new public `SpectralProcessor` types (`SpectralBrickwall`, `SpectralPhaseShift`, `SpectralGate`, `SpectralTilt`, `SpectralBlur`, `SpectralDiffuse`, `SpectralConvolve`) plus two shared helpers (`Sources/Lyrebird/Spectral/SpectralPhaseHelpers.swift`, `Sources/Lyrebird/Spectral/SpectralBinFromHz.swift`). `SpectralFreeze` refactored to consume `wrapPhasesInPlace`. **Generators** - `SpectralBrickwall(fftSize:sampleRate:mode:lowHz:highHz:)` — `BrickwallMode { case lp, hp, bp, br }`. Per hop: `vDSP_vclr` outside passband; DC + Nyquist zeroed when out of band. Phase untouched. `lowHz`/`highHz` `Atomic` live retunable. - `SpectralPhaseShift(fftSize:shift:)` — `PhaseShiftAmount { case deg90, deg180, deg270, radians(Double) }`. Per hop: `vDSP_vsadd` then `wrapPhasesInPlace`. `.deg180` flips DC + Nyquist sign (real-only). `.radians` retunable via `radians: Double` property; DC + Nyquist sign-flip is init-time only. `halfPi` named constant for cardinal cases. - `SpectralGate(fftSize:threshold:floor:)` + convenience `init(fftSize:thresholdDB:floor:)` (uses shared `dbToAmp` helper). Below-threshold bins multiplied by `floor` ∈ `[0, 1]`; DC + Nyquist gate on `abs(value)`, preserve sign. Both controls `Atomic`. - `SpectralTilt(fftSize:sampleRate:slopeDBPerOctave:pivotHz:)` — pre-computed `_gainTable` [halfSize+1] at init: `gain[k] = (binFreq[k]/pivot)^(slope/dBPerDoubling)`. Per hop: `vDSP_vmul`. DC bin gain forced to `1.0` (octave-relative slope undefined at DC). Slope/pivot init-only. - `SpectralBlur(fftSize:radius:)` — magnitude box-blur via two-pointer running sum. `_blurOut` allocated init; per hop runs `O(halfSize)` regardless of `radius`. Edge bins shrink window (no wrap). `radius` `Atomic` clamped `[0, halfSize/2]`. - `SpectralDiffuse(fftSize:amount:seed:)` — continuous phase randomization. Per bin per hop: draw target via `xorshift64Next`, blend by `amount` along shortest angular distance. `amount = 0` bypass; `amount = 1` full randomize. Seed via `lyrebirdSeedXorshift64(from:mixConstant:)` with file-scope `spectralDiffuseMixConstant` so concurrent instances are uncorrelated. - `SpectralConvolve(spectralBuffer:other:)` — frequency-domain complex multiply (mag * mag, phase + phase + wrap). Cross-synthesis (parallel `FFTAnalysis` chain feeding `other`) or static IR (preloaded `SpectralBuffer`). Either buffer invalid → live buffer cleared. **Shared helpers** - `wrapPhasesInPlace(_ p: UnsafeMutablePointer, count: Int)` — single-pass `(−π, π]` wrap, branchless. Extracted from `SpectralFreeze._runFrozenHop`; consumed by `SpectralFreeze`, `SpectralPhaseShift`, `SpectralConvolve`. - `binFromHz(_ hz: Float, fftSize: Int, sampleRate: Double) -> Int` — clamped `[0, halfSize]`, NaN-safe. **RT safety.** All seven `process` methods open with `guard spectral.fftSize == _fftSize else { return }` + `guard spectral.isValid else { return }` (no `precondition` string interpolation on RT). All scratch pre-allocated in `init`; no allocation in `process`. Cross-thread params via `Atomic`/`Atomic` with `.acquiring`/`.releasing` ordering. **Doc.** New "Spectral Filtering & Phase" section in `docs/stdlib/spectral.md` covering all seven types with worked examples. Class-level + init-level `/// - Parameters:` blocks on every public type. **Files added** ``` Sources/Lyrebird/Generators/Spectral/ BrickwallMode.swift PhaseShiftAmount.swift SpectralBlur.swift SpectralBrickwall.swift SpectralConvolve.swift SpectralDiffuse.swift SpectralGate.swift SpectralPhaseShift.swift SpectralTilt.swift Sources/Lyrebird/Spectral/ SpectralBinFromHz.swift SpectralPhaseHelpers.swift Tests/LyrebirdTests/ SpectralBlurTests.swift SpectralBrickwallTests.swift SpectralConvolveTests.swift SpectralDiffuseTests.swift SpectralGateTests.swift SpectralPhaseShiftTests.swift SpectralTiltTests.swift ``` **Tests added (50).** All `@Suite`/`@Test`/`#expect`. Coverage: rate/silence on invalid buffer, mode/cutoff edge cases, magnitude/phase invariants per processor, deterministic-seed for `SpectralDiffuse`, live-update propagation, dB↔linear convenience init equivalence, signed DC/Nyquist preservation/flip semantics, gain-table caching, peak smear plateau width, complex multiply per bin. **Review history.** Required five passes: 1. Initial: 7× `precondition(spectral.fftSize == _fftSize, "...")` on RT thread (string interpolation prohibited); inline `pow(10, dB/20)` magic literal in `SpectralGate`; `SpectralTilt` DC-bin gain via bin-1 frequency proxy (steep negative slopes amplified DC by ×21+). 2. `SpectralDiffuse` inline 3-branch seed code with bare `0x9E37...` mix multiplier — must use shared `lyrebirdSeedXorshift64(from:mixConstant:)` with named `spectralDiffuseMixConstant`. 3. `SpectralPhaseShift` + `SpectralBlur` two-param inits on a single line (multi-line format required ≥ 2 params); class-level `/// - Parameters:` block missing on all 7 new types. 4. Unused `import Foundation` in `SpectralBlur`/`SpectralGate`/`SpectralPhaseShift`/`SpectralDiffuse`/`SpectralBinFromHz` after upstream cleanups. 5. Clean. **3294 tests at completion** (was 3235 on `main` after Phase 98; +50 new spectral tests, +9 baseline drift from interim activity). --- ## Phase 100 — `SpectralFormantShift` **Goal:** Magnitude-envelope-preserving frequency-domain formant shift, independent of pitch. Pairs with existing `SpectralPitchShift` so a synth can drop pitch while leaving formants in place (or vice versa). New public `SpectralProcessor` `SpectralFormantShift`, a public enum `FormantShiftMethod { case cepstral; case magnitudeSmoothing(radiusBins: Int) }`, and an internal `CepstralEnvelopeEstimator` that owns its own real `FFTSetup` for the cepstral round trip. **Algorithm per hop.** 1. Build `_magSource` = `[|DC|, mag[1..halfSize-1], |Nyquist|]`. 2. Estimate envelope (`_envelope[halfSize+1]`): - `.cepstral` — `vvlogf` of `_magSource`, pack into half-complex, inverse real FFT to real cepstrum, lifter (zero indices `[cutoff, fftSize-cutoff]`), forward real FFT, divide out vDSP's 2·N round-trip scaling, `vvexpf`. - `.magnitudeSmoothing` — two-pointer running-sum box blur (same edge-shrink rule as `SpectralBlur`). 3. Whiten: `_residual[k] = _magSource[k] / (_envelope[k] + ε)`, `ε = 1e-9`. 4. Resample envelope: `_newEnvelope[k] = _envelope[k / shiftRatio]` with linear interpolation; one-bin linear fade past Nyquist, hard 0 beyond `halfSize + 1`. 5. Write `residual × newEnvelope` back; DC/Nyquist signs preserved. **API.** ```swift public final class SpectralFormantShift: SpectralProcessor { public init( fftSize: Int, shiftRatio: Double = 1.0, method: FormantShiftMethod = .cepstral, cepstralCutoffQuefrency: Int = 32 ) public var shiftRatio: Double { get set } // Atomic, clamped [0.25, 4.0] } ``` `shiftRatio == 1.0` is an explicit early-return bypass to avoid the cepstral cost when not in use. Live updates are `Atomic` with `.releasing` store / `.acquiring` load. Spec's `shiftRatio: any ValidGeneratorInput` API was rejected in favour of `Atomic` for consistency with `SpectralPitchShift`, `SpectralBlur`, and `SpectralGate` — every other `SpectralProcessor` in the codebase uses the same atomic-property pattern and `SpectralProcessor.process(spectral:)` has no `graph` parameter from which to evaluate a `ValidGeneratorInput`. **CepstralEnvelopeEstimator (internal).** Reusable helper. Owns `_logMag[halfSize+1]`, split-complex `_realp`/`_imagp[halfSize]`, real `_cepstrum[fftSize]`, and a private `FFTSetup`. `estimate(magnitudes:into:)` is allocation-free and RT-safe; `magnitudeFloor = 1e-12` guards `log(0)`. **RT safety.** `process(spectral:)` opens with `guard spectral.fftSize == _fftSize` and `guard spectral.isValid`; both early-out without touching the buffer. All five scratch buffers and the cepstrum's `FFTSetup` are allocated in `init`, deallocated in `deinit`. No allocation, locking, force-unwrapping, or `String` construction on the RT path. **Doc.** New `### SpectralFormantShift` section in `docs/stdlib/spectral.md` under "Spectral Filtering & Phase", with a paired `SpectralPitchShift` + `SpectralFormantShift` example. **Files added.** ``` Sources/Lyrebird/Generators/Spectral/ FormantShiftMethod.swift SpectralFormantShift.swift Sources/Lyrebird/Spectral/ CepstralEnvelopeEstimator.swift Tests/LyrebirdTests/ SpectralFormantShiftTests.swift ``` **Tests added (10).** `ratioOneIsBypass`, `cepstralPeakShiftsUp` (gaussian formant at bin 40 shifted to ~80 within ±8), `cepstralEnvelopeIsSmootherThanHarmonicInput` (lifter total-variation reduction on harmonic comb), `residualReapplyIsIdentity` (`residual × envelope ≈ input` within 5e-3 max relative error), `phaseUntouched`, `magnitudeSmoothingFallbackSmoke`, `dcSignPreserved` (strict `< 0` on signed DC + Nyquist), `invalidBufferIsNoOp`, `shiftRatioClampedOnLiveUpdate`, `mismatchedFftSizeIsNoOp`. **Review.** Two passes. Initial: `cepstralCutoffQuefrency: Int = 32` default literal lacked a named constant (now `defaultCepstralCutoffQuefrency`); `dcSignPreserved` used `<= 0` which vacuously passed on `_newEnvelope` collapse; round-trip identity test was named after the cepstrum but exercised only the divide-then-multiply float identity. Pass two: clean. **3304 tests at completion** (was 3294 on `main` after Phase 99; +10 new). --- ## Phase 101 — Ambisonic Toolkit (FOA core) Port of SC3 ATK FOA UGen set to Lyrebird. Self-contained `Foa*` namespace under `Sources/Lyrebird/Generators/Ambisonic/`. Source: Josh's `AtkUGens.cpp` from sc3-plugins. Operates on B-format `[W, X, Y, Z]` 4-row Generators. Coexists with existing `AmbiEncoder1` / `AmbiDecoder1` (Lyrebird-native panning primitives, unchanged) — ATK ships as parallel complete toolkit for SC parity. **Inventory (27 generators)** | Group | Count | Members | |-------|-------|---------| | A — single-angle transforms | 20 | `FoaRotate`, `FoaTilt`, `FoaTumble`, `FoaFocus{X,Y,Z}`, `FoaPush{X,Y,Z}`, `FoaPress{X,Y,Z}`, `FoaZoom{X,Y,Z}`, `FoaDirect{X,Y,Z}`, `FoaDirectO`, `FoaAsymmetry` | | B — single-gain (dB) transforms | 3 | `FoaDominate{X,Y,Z}` | | C — filters | 3 | `FoaNFC`, `FoaProximity`, `FoaPsychoShelf` | | D — encoder | 1 | `FoaPanB` (mono → BFormat, az/el) | | E — decoders | 3 | `FoaDecodeProjection`, `FoaDecodeStereo`, `FoaDecodeQuad` | **Architecture.** Group A subclasses `_FoaAngleBase`, Group B subclasses `_FoaGainBase`. Both bases own `@LiveParam` (angle / gain), 4×4 matrix cache, output `_result` buffer, mulAdd, and 4-row input precondition; subclasses override only `fillMatrix`. Group C filters are direct `GeneratorBase, AudioGenerator` finals with per-block IIR state + `denormalsToZero()` on every feedback var. Group D `FoaPanB` math identical to `AmbiEncoder1` but shipped as separate type for SC parity. Group E decoders pre-compute speaker coefficients at `init` (no per-sample trig). **`FoaMatrix4`** is a 16-tuple-of-`Double` value type with stack-only allocation, paired with an `@inline(__always)` `foaApply` free function. Math translated literally from the C++ `FILL_*_MATRIX` macros in `AtkUGens.cpp`. SC `UNWRAPANGLE` macro skipped — `@LiveParam` ramps stay continuous. **Review.** Two passes. Initial: five redundant `public func calculatedSamples` overrides on `_FoaAngleBase`/`_FoaGainBase`/`FoaNFC`/`FoaProximity`/`FoaPsychoShelf` flagged as §5 violations (`AudioGenerator` extension at `GeneratorCore/Generator.swift:161` already provides segment-serial fan-out caching; the sub-block bypass concern applies only to `ControlGenerator`). All five overrides deleted. Non-blocking polish: `_FoaGainBase` cache now keyed on dB (initialised to `.nan`) so per-sample `pow()` skips when gain is constant; `FoaDecodeStereo.stereoNorm` derives from named `foaDecodeStereoChannelCount`. Pass two: clean. **Docs.** New `docs/stdlib/ambisonic-toolkit.md` (authoritative FOA reference) + `docs/roadmap/atk-binaural.md` (Phase 102 stub). Old ATK section in `docs/stdlib/generators.md` pruned to a pointer. **3567 tests at completion** (was 3304 on `main` after Phase 100; +263 new). --- ## Phase 102a — Ambisonic Toolkit (FOA extra encoders) Two specialised FOA encoders for the ATK interface, complementing Phase 101's `FoaPanB` directional encoder. **Generators (2):** | Generator | Notes | |-----------|-------| | `FoaEncodeOmni` | Omnidirectional. `W = input`, `X = Y = Z = 0`. No `1/√2` factor on W — full amplitude to the pressure channel (omni convention vs FoaPanB's plane-wave SN3D convention). Useful as a neutral soundfield feed for testing transforms, or for sources with no meaningful direction (drones, dry sends). | | `FoaEncodeStereo` | `(left, right, angle = π/2)` → BFormat. Sums two opposing FoaPanB encodes at `+angle` and `-angle`, both elevation 0. Math: `W = (1/√2)·(L+R)`, `X = cos(angle)·(L+R)`, `Y = sin(angle)·(L−R)`, `Z = 0`. `angle` is a static `Double` at init (not `@LiveParam`). Coefficients (`_wScale`, `_xScale`, `_yScale`) pre-computed once at init. | **Architecture.** Both are direct `GeneratorBase, AudioGenerator` finals with 4-row output (`outputChannelCount == 4`). No `@LiveParam`. No per-block DSP state. No `calculatedSamples` override — Generator protocol extension handles fan-out caching (the rule established in the Phase 101 review). **Review.** Single clean pass — no blocking findings. Reviewer noted the pre-existing family-wide pattern of calling `_input.calculatedSamples` without an `_inputIsGenerator` guard (heap allocation when literal `Double` is passed) is inherited from Phase 101 and not a regression introduced by this phase. **Phase 102 split.** Phase 102 was originally scoped to include `FoaDecodeBinaural` (HRIR convolution decoder). Split into 102a (encoders, this phase) + 102b (binaural decoder, blocked on HRIR-source design decision — see `docs/roadmap/atk-binaural.md`). **Files added.** ``` Sources/Lyrebird/Generators/Ambisonic/ FoaEncodeOmni.swift FoaEncodeStereo.swift Tests/LyrebirdTests/Ambisonic/ FoaEncodeOmniTests.swift (13 tests) FoaEncodeStereoTests.swift (15 tests) ``` **Doc updates.** `docs/stdlib/ambisonic-toolkit.md` — added "Other encoders" section between `FoaPanB vs AmbiEncoder1` and "Soundfield transforms". Phase 102 preview section renamed to "Phase 102b preview". **3595 tests at completion** (was 3567 on `main` after Phase 101; +28 new). --- ## Phase 102b — Ambisonic Toolkit (FOA binaural decoder) `FoaDecodeBinaural` — FOA-to-stereo binaural decoder using HRIR convolution. Reuses the partitioned-FFT overlap-save infrastructure from Phase 93 (`ConvolutionReverb`), extended to a 4-input / 2-output MIMO shape. **Pipeline:** 1. Load HRIR set: bundled MIT KEMAR full set (`HRIRFile.bundledKemarFull`, 710 positions × 512-sample IRs at 44.1 kHz), or user URL via `try HRIRFile.load(contentsOf: someURL)`. 2. `FoaBinauralFilters.build(from:)` bakes 8 time-domain rendering filters (4 B-format channels × 2 ears) by treating every HRIR position as a virtual loudspeaker and summing weighted HRIRs using projection-decode coefficients `coef_W = √2/N`, `coef_X = cos(az)·cos(el)/N`, `coef_Y = sin(az)·cos(el)/N`, `coef_Z = sin(el)/N`. 3. At runtime: per-block MIMO partitioned-FFT — 4 FDLs, 8 IR partition spectra, per-ear accumulation `Σ_c Σ_p FDL_c[slot] * IR[c][e][p]` followed by single IFFT per ear. IFFT scale matches `ConvolutionReverb` exactly; DC/Nyquist bin packing handled identically. **Format & format-handling.** New `.lbhr` binary format v1 (24-byte header + per-position table + int16 samples, little-endian). `HRIRFile.load(contentsOf:)` validates magic, version, sample-rate / IR-length / position-count bounds, byte-count, and per-position `sampleOffset` in-bounds. Int16 → Float at load. `Sendable` value type after load. `scripts/build-kemar-hrir.py` builds `.lbhr` blobs from the MIT KEMAR upstream zip layout (`elev*/Lea.wav` + `Rea.wav`). User-supplied HRIR data in the same naming convention works through the same script. **Bundled resource.** `Sources/Lyrebird/Resources/HRTF/KEMAR/kemar-full.lbhr` (1.47 MB) added as a `.process("Resources")` declaration in `Package.swift`. `Bundle.module` flattens `HRTF/KEMAR/` → file at bundle root. MIT KEMAR by Gardner & Martin (MIT Media Lab, 1994); freely distributable. **API.** ```swift public final class FoaDecodeBinaural: GeneratorBase, AudioGenerator { public init( input: any ValidGeneratorInput, hrirSet: HRIRFile = .bundledKemarFull, partitionSize: Int = foaDecodeBinauralDefaultPartitionSize, // 256 mul: any ValidGeneratorInput = 1.0, add: any ValidGeneratorInput = 0.0 ) } ``` `outputChannelCount = 2` (L, R). `.left` / `.right` channel-select aliases. Inherent latency = `partitionSize` samples (the first `partitionSize` output samples are silence; subsequent blocks produce normal output). **RT safety.** All buffers (`UnsafeMutablePointer`) and FFT setups allocated in `init`, freed in `deinit`. Zero allocation on the RT thread. No force unwraps, locks, `String` construction, `is`/`as?`, or printing. **Review.** Single `lyrebird_review` pass — no blocking findings. Two non-blocking doc accuracy items fixed in a follow-up commit: 1. `FoaBinauralFilters` math docstring corrected: `FoaDecodeProjection` omits `/N` on X/Y/Z (per-speaker decode); the binaural builder divides all four coefs by N (sum-across-speakers normalisation). 2. `HRIRFile` azimuth-range docstring clarified: stored range depends on the writer. Bundled MIT KEMAR emits `[0, 2π)`; canonical Lyrebird convention is `[-π, π]`. Either works because downstream consumers use `sin`/`cos` (2π-periodic). **Files added (10 sources, 1 binary resource, 1 script, 3 test files):** ``` Sources/Lyrebird/Buffers/ HRIRFile.swift HRIRFileError.swift Sources/Lyrebird/Generators/Ambisonic/ FoaBinauralFilters.swift (internal) FoaDecodeBinaural.swift Sources/Lyrebird/Resources/HRTF/KEMAR/ kemar-full.lbhr (1.47 MB) scripts/ build-kemar-hrir.py Tests/LyrebirdTests/Buffers/ HRIRFileTests.swift (14 tests) Tests/LyrebirdTests/Ambisonic/ FoaBinauralFiltersTests.swift (7 tests) FoaDecodeBinauralTests.swift (18 tests) ``` **Files modified:** `Package.swift` (resources declaration), `docs/stdlib/ ambisonic-toolkit.md` (Binaural decoder section added). **Files deleted:** `docs/roadmap/atk-binaural.md` (obsolete stub). **3634 tests at completion** (was 3595 on `main` after Phase 102a; +39 new). --- ## Phase 103 — Runtime Source-Swap for `@LiveParam` Slots Replace the Generator wired into a `@LiveParam` / `@UIParam` parameter slot at runtime without stopping the synth. RT-safe (no allocation, no locks, no ARC retain/release on the audio thread). Foundation for hot-reload, live coding, A/B modulation comparisons, and patch-morphing workflows. Unblocks deferred §9.4 (Hot-reload / live coding). **Primary API.** ```swift synth.$freq.source = SineOsc.Control(freq: 0.5, mul: 100, add: 440) // LFO synth.$freq.source = nil // revert scalar synth.$freq.setSource(lfo, crossfadeBlocks: 4) // soft swap synth.setSource(synth.$freq, to: lfo, crossfadeBlocks: 4) // helper synth.freq = 880.0 // existing scalar ``` **Architecture.** - `SourcePacket` — Sendable value type carrying an `Unmanaged` opaque pointer (or nil = revert) + `crossfadeBlocks: UInt16`. Main-thread `passRetained` / RT-side `takeRetainedValue` — balanced retain/release, no ARC traffic on the audio thread. - `ParameterSourceQueue` — per-parameter SPSC<`SourcePacket`> wrapper. Capacity 4. Drain returns latest packet; older dropped payloads written into a pre-allocated scratch slice for the consumer to push onto the engine kill queue. Zero RT allocation. Overflow traps on main thread (programmer error — > 4 source writes per audio block is pathological). - `ParameterNode._sourceSlot` — RT-thread-owned current source. Drain + slot install at the top of `calculatedSamples`; output routes through the slot when non-nil, scalar-ramp otherwise. Old slot pushed to engine kill queue when superseded. - `SynthesisEngine.parameterSourceKillQueue` — shared `SPSCQueue` (capacity 256). Main-thread `drainParameterSourceKillQueue()` releases each via `Unmanaged.fromOpaque(ptr).release()`. Hooked into the existing background-timer drain (5 ms, .background QoS) and the synchronous `stop()` path. RT-side overflow degrades gracefully (drops pointer, sets atomic flag, main thread prints one-shot warning) rather than trapping — keeping the engine alive matters more than zero leaks in pathological cases. - Crossfade-N-blocks soft swap: `(total - remaining + 0.5) / total` mid-block-snapshot mix fraction applied uniformly within each block. Scalar↔generator transitions handled (scalar-ramp scratch path inlined). Mid-crossfade swap kills the in-progress old slot. `parameterNodeMax CrossfadeBlocks = 1024` sanity cap (main-thread precondition). - `UIParamNode` parity via `calculatedSamples` override forwarding to the underlying `ParameterNode.calculatedSamples` — caught in review pass 1 (would have been silently non-functional otherwise; `_computeSamples` delegation alone bypasses the source-swap pipeline). **API decisions.** - KeyPath approach `ReferenceWritableKeyPath` rejected because Swift 6 cannot satisfy `Root: SynthesizerBase` and `Root == Self` simultaneously on an open class. The direct `ParameterNode` argument (`synth.setSource(synth.$freq, to: lfo)`) is strictly safer: fully type-safe, no Foundation-private API, no runtime lookup. Used as the secondary surface; the primary API is the projected-value property (`synth.$freq.source = ...`). **ARC safety.** The critical detail is the RT-side cast inside `SourcePacket.takeRetained Source()`: `obj as! any Generator`. Pass 1 review rejected `as?` (runtime type check prohibited on RT path) and `unsafeBitCast` (width mismatch: `any Generator` is a 16-byte existential vs `AnyObject`'s 8-byte class reference). The shipped `as!` resolves to a class-to-class-protocol cast — a single witness-table-lookup, no allocation. Correct by construction because every retained pointer in `sourcePtr` is produced by `.handoff(_:)`, which only accepts `any Generator`. CLAUDE.md's "no force unwraps" rule governs optional `!`, not type-cast `!`. **Known limitation.** A source generator's own scalar parameters (anything declared on the source generator itself) cannot be updated via the consuming synth's `update Parameter` path, because `Mirror` reflection only registers parameters declared on the `SynthesizerBase` subclass, not on generators passed as sources. Documented in `@LiveParam` docstring + `ParameterInputs.md` + test 7 of the integration suite. **Review.** Two passes. Pass 1 blockers: 1. `SourcePacket.takeRetainedSource` used `as? any Generator` on the RT thread. Fix attempted with `unsafeBitCast` (failed: existential vs class-ref size mismatch); shipped fix uses `as!` with explanatory comment. 2. `UIParamNode` lacked a `calculatedSamples` override. `Control Generator.calculatedSamples` protocol extension was dispatching to `UIParamNode._computeSamples` → `_node._computeSamples` (scalar-only path), bypassing `_node.calculatedSamples` — the only path that drains the source queue and runs the crossfade state machine. `UIParamNode .source = lfo` was silently non-functional. Fixed by adding a `calculatedSamples` override forwarding to `_node.calculatedSamples`. Pass 2 clean. **Files added (5 sources, 1 modified existing engine, 4 test files):** ``` Sources/Lyrebird/Parameters/ SourcePacket.swift (new — internal Sendable packet) ParameterSourceQueue.swift (new — per-parameter SPSC wrapper) ParameterNode.swift (modified — source slot + drain + crossfade + public source property) LiveParam.swift (modified — Runtime source-swap docstring) Sources/Lyrebird/Synthesizer/ SynthesizerBase.swift (modified — setSource helper) Sources/Lyrebird/Engine/ SynthesisEngine.swift (modified — kill queue + drain hook) Sources/LyrebirdUI/ UIParamNode.swift (modified — parity surface + calculated Samples override) Sources/Lyrebird/Lyrebird.docc/ ParameterInputs.md (modified — Live source-swap section) docs/protocols/ synthesizer.md (modified — runtime source-swap subsection) Tests/LyrebirdTests/ ParameterSourceQueueTests.swift (21 tests) Parameters/ParameterNodeSourceSlotTests.swift (11 tests) Parameters/ParameterNodeSourceAPITests.swift (11 tests) Parameters/ParameterNodeCrossfadeTests.swift (11 tests) Parameters/ParameterSourceSwapIntegrationTests.swift (15 tests) Tests/LyrebirdUITests/ UIParamNodeTests.swift (modified — +2 source-swap tests) ``` **3703 tests at completion** (was 3634 on `main` after Phase 102b; +69 new). --- ## Phase 104a — AUv3 Wrapper Infrastructure Headless Swift API surface that bridges Lyrebird's `SynthesisEngine` + `SynthesizerBase` into the `AUAudioUnit` contract. Phase 104b will wrap an example subclass as an Xcode `.appex` extension target and run `auval` validation. Phase 104c adds MIDI input, default SwiftUI parameter UI, extended preset save/restore (Phase 103 source-slot generators), and effect-type AU support. **Subclass shape (end-user view):** ```swift final class MyFMSynth: SynthesizerBase { @LiveParam var carrierFreq: Double = 440 @LiveParam var modIndex: Double = 0.5 override func build() { let mod = OscSin.Audio(freq: $carrierFreq * 2, mul: $modIndex * $carrierFreq) output(bus: 0, source: OscSin.Audio(freq: $carrierFreq + mod) * 0.3) } } public final class MyFMSynthAudioUnit: LyrebirdAudioUnit { public override class func makeSynthesizer() -> SynthesizerBase { MyFMSynth() } public override class func parameterMetadata() -> [String: LyrebirdAUParameterInfo] { ["carrierFreq": .init(min: 20, max: 8000, unit: .hertz), "modIndex": .init(min: 0, max: 4)] } } ``` **Architecture.** - `AUv3RingBuffer` — per-channel power-of-two circular buffer. Single-threaded (all reads + writes from the AU render thread). Pre-allocated storage in `init`; `write` / `read` / `reset` are allocation-free. Index masking is a single AND op against `capacity − 1`. Used by `AUv3Driver` to decouple Lyrebird's fixed `blockSize` from the host's variable per-render `frameCount`. - `AUv3Driver` — passive `AudioDriver` conformer in `Sources/Lyrebird/AudioDrivers/`. `setup(engine:)` records the engine via `Unmanaged.passUnretained` (no ARC traffic on the render path), allocates the ring with capacity `2 × max(maxFramesToRender, blockSize)`, and allocates a per-channel `UnsafeMutablePointer` scratch array sized to `numOutputChannels` (used by `render` to stash AU buffer-list pointers without per-call heap allocation). `start()` / `stop()` are no-ops — the AU host drives rendering. `render(frameCount:outputData:)` advances the engine in fixed `blockSize` steps until the ring holds enough frames, then pops `frameCount` per channel into the host's `AudioBufferList`. Returns `kAudioUnitErr_Uninitialized` / `kAudioUnitErr_TooManyFramesToProcess` / `kAudioUnitErr_InvalidParameterValue` for the three host-contract violations. Suggested control block size: `lyrebirdDefaultControlBlockSize` (64). - `LyrebirdAudioUnit` — `open class` subclass of `AUAudioUnit` in `Sources/Lyrebird/AUv3/`. Required override: `makeSynthesizer()`. Optional overrides: `parameterMetadata()`, `lyrebirdBlockSize` (default 256), `lyrebirdOutputChannels` (default 2), `lyrebirdMaxFramesToRender` (default 1024). In `init` the synth is constructed once, the parameter tree is built (synth's `@LiveParam` wrappers exist as soon as the instance is constructed — `build()` not required), the output `AUAudioUnitBus` is prepared at `lyrebirdAUDefaultSampleRate = 44100`, the `AUInternalRenderBlock` closure is constructed capturing the driver via `Unmanaged.passUnretained` (no ARC retain/release inside the closure body), and `super.init(componentDescription:options:)` runs. Post-`super.init` we build the bus arrays (which need `self`), wire the parameter `implementorValueObserver` / `implementorValueProvider` / `implementorStringFromValueCallback` closures (capturing the address-to-`LiveParameterValue` dictionary by value), and seed `maximumFramesToRender` from the class hook. Bus arrays are stored as `AUAudioUnitBusArray?` with `guard let / fatalError` in the `outputBusses` / `inputBusses` overrides (CLAUDE.md disallows IUO stored properties). - `LyrebirdAUParameterMapping` — Mirror-driven discovery of `@LiveParam` / `@UIParam` slots. Walks `Mirror(reflecting: synth)` + every `superclassMirror` (oldest first) so inherited slots are included in declaration order. Each child whose value conforms to `LiveParameterWrapper` produces a `LyrebirdAUParameterEntry` with name, stable `AUParameterAddress` (0-based, declaration order), and the projected `LiveParameterValue` node. `buildParameterTree(for:metadata:)` emits one `AUParameter` per slot (seeded with the current scalar value, clamped to the metadata range) and returns the tree + the address-to-node dictionary used by the AU's observer/provider closures. - `LyrebirdAUParameterInfo` — value type carrying per-parameter `minValue` / `maxValue` / `unit` / `displayName` / `flags`. Defaults are permissive (`±lyrebirdAUParameterDefaultBound = 1e10`, `.generic` unit, readable+writable+canRamp flags) because `@LiveParam` itself carries no bounds — subclasses opt-in by overriding `parameterMetadata()`. - `fullState` — encodes scalar `@LiveParam` values as `[String: AUValue]` under namespaced key `lyrebirdAUFullStateKey = "lyrebird.parameterValues"`. Setter re-discovers slots (Mirror walk is stable across calls — same property order, same projected nodes) and writes each saved value via `node._writeAtomicValue(_:)` plus `AUParameter.value = ...` so host UI reflects the restored state. **Out of scope for 104a:** Phase 103 source-slot generators wired into a `ParameterNode.source` slot are not encoded. Saved state restores only scalar targets — source generators must be re-attached programmatically. 104c will extend with a `@PresetCodable` protocol for serialisable source generators. **Render path latency.** One engine block of inherent latency — the ring fills with `blockSize` frames before the host's first pull. At `blockSize=256` / 44.1 kHz that is ≈5.8 ms; at 48 kHz ≈5.3 ms. Hosts that need lower latency can override `lyrebirdBlockSize` per subclass. **Sample-rate negotiation.** `allocateRenderResources` reads the host-committed sample rate from `outputBus.format.sampleRate`, tears down any prior engine (`engine.remove(synth)` → `engine.stop()`), then creates a fresh `SynthesisEngine` at the new rate and re-adds the same synthesizer. The synth instance survives the cycle — its `@LiveParam` `ParameterNode`s are the same objects across re-add, so atomic state and host automation targets persist. **`Package.swift`.** AVFoundation widened from iOS-only to all platforms: `AUAudioUnit` lives in AVFAudio (part of AVFoundation) on both macOS and iOS, and is needed to compile the Lyrebird module — not just at AU host time. No other linker consumers depend on the iOS-only gating. **Review.** Two passes. Pass 1 flagged three blocking findings: 1. `LyrebirdAudioUnit._outputBusArrayBacking` / `_inputBusArrayBacking` were declared as `AUAudioUnitBusArray!` (the only IUO stored properties in `Sources/Lyrebird/`). The AU two-phase ObjC init requires the bus arrays to be assigned after `super.init`, but CLAUDE.md prohibits `!` on stored properties. Replaced with `AUAudioUnitBusArray?` plus `guard let / fatalError` in the public computed `outputBusses` / `inputBusses` overrides — same access pattern, no IUO. 2. `LyrebirdAUParameterMapping.swift` held two public types in one file (`LyrebirdAUParameterEntry` struct + `LyrebirdAUParameterMapping` enum). Split the entry struct into `Sources/Lyrebird/AUv3/LyrebirdAUParameterEntry.swift`. 3. `AUv3RingBufferTests` had five `UnsafeMutableBufferPointer.baseAddress!` force unwraps. Replaced each with `guard let base = buf.baseAddress else { Issue.record(...); return }`. Pass 2: clean. **Files added.** ``` Sources/Lyrebird/AUv3/ AUv3RingBuffer.swift LyrebirdAUParameterEntry.swift LyrebirdAUParameterInfo.swift LyrebirdAUParameterMapping.swift LyrebirdAudioUnit.swift LyrebirdAudioUnitError.swift Sources/Lyrebird/AudioDrivers/ AUv3Driver.swift Sources/Lyrebird/Lyrebird.docc/ AUv3.md (new topic) docs/roadmap/ auv3-extension-project.md (104b sketch) Tests/LyrebirdTests/AUv3/ AUv3DriverTests.swift (5 tests) AUv3RingBufferTests.swift (7 tests) LyrebirdAUParameterMappingTests.swift (10 tests) LyrebirdAudioUnitTests.swift (10 tests) ``` **Files modified.** `Package.swift` (widen AVFoundation link to all platforms), `Sources/Lyrebird/Lyrebird.docc/Lyrebird.md` (add AUv3 doc link under "Advanced"). **3737 tests at completion** (was 3703 on `main` after Phase 103; +34 new incremental count — 32 new test functions across 4 new files, 2 new suite-level wrappers). **New subfolder.** `Sources/Lyrebird/AUv3/` introduced for AU-specific glue. `AUv3Driver` placed in the existing `AudioDrivers/` subfolder since it is an `AudioDriver` conformer (consistent with `NRTDriver` / `OfflineDriver` / the hardware drivers). --- ## Phase 104b — AUv3 Reference Xcode Project + LyrebirdFM example End-to-end proof that Phase 104a's `LyrebirdAudioUnit` actually loads as a real AUv3 plugin. Lives under `Demos/LyrebirdAUv3Demo/` as a hand- written Xcode project with two targets and a 4-parameter example synth. Phase 104c will add MIDI input, SwiftUI parameter UI, source-slot preset save/restore, and effect-type AU support. **Targets (`Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo.xcodeproj`).** | Target | Type | Notes | |--------|------|-------| | `LyrebirdAUv3Demo` | `.app` | Minimal SwiftUI container app. Single ContentView with the "install me so the AU registers" message. Embed App Extensions copy phase (`dstSubfolderSpec = 13`) pulls the `.appex` into `Contents/PlugIns/`. `PBXTargetDependency` on the extension. | | `LyrebirdFMExtension` | `.appex` | `com.apple.product-type.app-extension`. `Info.plist` `AudioComponents` entry: `type=aumu`, `subtype=LBFM`, `manufacturer=RLZS`, `sandboxSafe=true`, `tags=[Synth]`. Principal class `LyrebirdFMExtension.LyrebirdFMAudioUnitViewController` — also conforms to `AUAudioUnitFactory`, so `createAudioUnit(with:)` is where `LyrebirdFMAudioUnit` is built. | **Example synth (`LyrebirdFM.swift`).** ```swift final class LyrebirdFM: SynthesizerBase { @LiveParam var carrierFreq: Double = 440.0 // [20, 8000] Hz @LiveParam var modRatio: Double = 2.0 // [0.25, 16] @LiveParam var modIndex: Double = 0.5 // [0, 8] @LiveParam var amp: Double = 0.3 // [0, 1] override func build() { let modFreq = $carrierFreq * $modRatio let modDepth = $modIndex * $carrierFreq let modulator = OscSin.Audio(freq: modFreq, mul: modDepth) let carrier = OscSin.Audio(freq: $carrierFreq + modulator) let voice = carrier * $amp output(bus: 0, source: voice) output(bus: 1, source: voice) } } ``` Mono carrier fanned to both stereo channels through the segment-serial fan-out cache. **AU subclass (`LyrebirdFMAudioUnit.swift`).** 12 lines — only the two required overrides: ```swift public override class func makeSynthesizer() -> SynthesizerBase { LyrebirdFM() } public override class func parameterMetadata() -> [String: LyrebirdAUParameterInfo] { [ "carrierFreq": .init(min: 20, max: 8000, unit: .hertz, displayName: "Carrier Freq"), "modRatio": .init(min: 0.25, max: 16, unit: .generic, displayName: "Mod Ratio"), "modIndex": .init(min: 0, max: 8, unit: .generic, displayName: "Mod Index"), "amp": .init(min: 0, max: 1, unit: .linearGain, displayName: "Output Amp"), ] } ``` **View controller (`LyrebirdFMAudioUnitViewController.swift`).** `AUViewController` + `AUAudioUnitFactory` conformance. `createAudioUnit(with:)` instantiates the `LyrebirdFMAudioUnit` and hands it to the host. `viewDidLoad` is an empty stub — Phase 104c populates with a SwiftUI parameter grid driven by `LyrebirdUI`. **Entitlements.** `com.apple.security.app-sandbox` on both targets; container app additionally has `com.apple.security.files.user-selected. read-only` for future preset-load workflows. Hardened runtime enabled. **Xcode 26 quirks.** 1. The extension target links **only** the `LyrebirdUI` SPM product, never `Lyrebird` directly. Linking `Lyrebird` produces "Swift package target 'Lyrebird' is linked as a static library by 'X' and 'Lyrebird', but cannot be built dynamically because there is a package product with the same name" — the `type: .dynamic` workaround already in place on the Lyrebird product fights with Xcode's static-link default for extension targets. Linking `LyrebirdUI` (which transitively depends on Lyrebird) sidesteps the collision without losing access to the Lyrebird module. 2. `SWIFT_USE_INTEGRATED_DRIVER=NO` is required (same as the rest of the Lyrebird SPM-in-Xcode story — explicit-module-build can't see SPM dynamic-framework module maps at scan time). 3. `BuildIndependentTargetsInParallel = 0` at the project level matches `parallelizeBuildables = "NO"` in the shared scheme. **Build verification.** `xcodebuild -scheme LyrebirdAUv3Demo -configuration Debug` and `-configuration Release` both completed successfully with `CODE_SIGN_IDENTITY="-"` `CODE_SIGNING_REQUIRED=NO` `CODE_SIGNING_ALLOWED=NO` `SWIFT_USE_INTEGRATED_DRIVER=NO`. The `.appex` is correctly embedded at `LyrebirdAUv3Demo.app/Contents/ PlugIns/LyrebirdFMExtension.appex`. **Out of automated scope.** `auval -v aumu LBFM RLZS`, Logic / GarageBand smoke tests, and iOS AUM testing all require: - An Apple Developer Team ID (any free or paid tier) populated in `DEVELOPMENT_TEAM`. - Running the container app once on macOS so the system AU registry picks up the extension via `LaunchServices` / `pluginkit`. The build's automatic `lsregister -f -R -trusted` invocation registers the bundle path but the AU host scanner still wants the app to have been launched at least once. - Manual host validation in a DAW. The autonomous `pluginkit -a` invocation was correctly refused by the agent sandbox — registering an unsigned extension system-wide is not appropriate without an explicit user decision. **Review.** Single iteration. Pass 1 flagged: 1. **Blocking** — orphan `Lyrebird` `XCSwiftPackageProductDependency` + `PBXBuildFile` left in `project.pbxproj` after the static-vs-dynamic resolution swap; the entry was dropped from the `PBXFrameworksBuildPhase` but the SPM product reference was not. Both removed. 2. **Major** — `BuildIndependentTargetsInParallel = 1` at the project level contradicted the scheme's `parallelizeBuildables="NO"`, re-enabling the Xcode 26 race for any `xcodebuild -target …` invocation. Set to `0`. 3. **Minor** — `docs/auv3-extension-guide.md` Common Pitfalls section linked into the agent's local `~/.claude/projects/...` memory path, inaccessible to contributors. Replaced with an inline summary of the workaround and its revert condition. 4. **Nit** — scheme `LaunchAction` was `Release`; switched to `Debug`. Pass 2: clean. `xcodebuild` Debug + Release re-verified after fixes. **Files added.** ``` Demos/LyrebirdAUv3Demo/ LyrebirdAUv3Demo.xcodeproj/ project.pbxproj project.xcworkspace/xcshareddata/swiftpm/Package.resolved xcshareddata/xcschemes/LyrebirdAUv3Demo.xcscheme LyrebirdAUv3Demo/ LyrebirdAUv3DemoApp.swift ContentView.swift Info.plist LyrebirdAUv3Demo.entitlements LyrebirdFMExtension/ LyrebirdFM.swift LyrebirdFMAudioUnit.swift LyrebirdFMAudioUnitViewController.swift Info.plist LyrebirdFMExtension.entitlements README.md (template walkthrough) docs/ auv3-extension-guide.md (step-by-step ship-your-own guide) ``` **No Swift library changes.** 104b is a packaging phase — Lyrebird sources are unchanged. Test count stays at **3737** (the baseline post-Phase 104a merge). --- ## Phase 104c — AUv3 MIDI / UI / Presets / Effect-AU Final sub-phase of the Phase 104 AUv3 rollout. Adds five capabilities on top of Phase 104a's `LyrebirdAudioUnit` so a Lyrebird plugin can be a fully-featured AUv3 instrument *or* effect: MIDI input dispatch, an auto-generated SwiftUI parameter UI, factory presets, source-slot preset save/restore, and effect-type (`aufx`) audio input. ### 1. MIDI render-block dispatch `LyrebirdAudioUnit` now walks the AU host's `AURenderEvent` chain inside `internalRenderBlock`, parses each `.MIDI` event into a `MIDIMessage` (via the existing `MIDIMessage.from(status:data1:data2:)` parser), and invokes an installed handler closure: ```swift public final var midiHandler: ((MIDIMessage, AUEventSampleTime) -> Void)? ``` **RT-safe handler swap.** The handler is boxed in `_MIDIHandlerBox` (a heap class holding the closure) and exposed to the render thread via an `Atomic` pointer-bit-pattern with acquire/release ordering. The setter `passRetained`s a fresh box, atomically exchanges the bit pattern, then releases the old box on the main thread *after* the swap retires — so a render-side acquiring load always sees either a fully-initialised box or `nil`, never a torn pointer. ARC traffic is zero on the RT side (`Unmanaged.fromOpaque.takeUnretainedValue`); the new/old release fires on the main thread inside the setter. ### 2. Voice-pool binding (main-thread adapter) `LyrebirdAUVoicePoolBinding` is a thin adapter that maps `MIDIMessage.noteOn` / `.noteOff` onto a `VoicePool` with a subclass-supplied configure closure (typical body: `voice.freq = midiToHz(note); voice.amp = velocity; voice.gate = 1`). It exposes an optional `channelFilter` to restrict to one MIDI channel. **Threading.** `VoicePool` is documented as main-thread-only (its `_states` array mutates without synchronisation, and the `.quietest` / `.lowestAmplitude` steal strategies walk `Mirror(reflecting:)`). The binding therefore cannot be called from the render thread. The doc-comment lays out the two RT→main bridging patterns (CoreMIDI via `MIDI`, or SPSC queue + main-thread drain via the existing `TriggerListener` pattern). A full RT-safe note-event SPSC bridge is **deferred to a future sub-phase** — 104c ships only the main-thread adapter. ### 3. Effect-type AU (`aufx`) New class hook `open class var lyrebirdInputChannels: Int { 0 }`. When overridden to a positive value the AU: 1. Allocates an `AUAudioUnitBus` for input with the same sample rate and channel count. 2. Creates its `SynthesisEngine` with matching `numInputChannels`. 3. `AUv3Driver` allocates a host-input staging buffer + pre-allocated `AudioBufferList` (single contiguous Float backing, one buffer per channel) and pulls one engine block of input per `engine.processBlock` call via `AURenderPullInputBlock` passed through from `internalRenderBlock`. 4. Stages host input into engine input buses (engine convention: inputs live at `[numOutputChannels, numOutputChannels + numInputChannels)`). 5. The synth's `build()` reads via the new `AUInput.Audio(channel:)` Generator, which resolves to `graph.engine.audioBuses[ numOutputChannels + channel]` at compute time. Defensive zero-fill if the engine was instantiated without input channels — no out-of-range read. The `withUnsafePointer(to:)` block in `_fillInputStagingFromHost` is nested around the `pullInput` call when the host did not supply a timestamp pointer — the stack-allocated `AudioTimeStamp` is only used within the closure body. ### 4. SwiftUI Mirror-driven parameter grid `LyrebirdUI.LyrebirdSynthView` walks the synth's `Mirror` (with superclass chain, oldest-first — matches `_autoRegisterLiveParams`'s order) collecting `@UIParam` slots and rendering one `ParameterKnob` per slot inside a `LazyVGrid` with adaptive columns. `@LiveParam` slots are skipped (no `@Observable` projected value to drive a knob). The optional `metadata: [String: LyrebirdAUParameterInfo]` argument supplies per-knob range, unit, and display name — the same dictionary shape used by `LyrebirdAUParameterMapping.buildParameterTree`. Layout constants (`lyrebirdSynthViewColumnMinWidth = 120`, `lyrebirdSynthViewGridSpacing = 16`, `lyrebirdSynthViewItemSpacing = 6`) are named `let`s at file scope (reviewable + overridable in a future pass). A static `LyrebirdSynthView.discover(synth:metadata:)` helper exposes the discovered slots for users that want a custom layout. ### 5. Factory presets + source-slot save/restore - `LyrebirdAUFactoryPreset` value type: `name` + `scalarValues: [String: AUValue]` + `sourceSlots: [String: LyrebirdAUPresetSourceDescriptor]`. - `open class func factoryPresetsForLyrebird() -> [LyrebirdAUFactoryPreset]` hook returning the list. The base class auto-translates into the AU's `factoryPresets` property (one `AUAudioUnitPreset` per entry, number = index) and a `currentPreset` setter that applies the selected entry's scalars (+ source slots) via `applyFactoryPreset(_:)`. - `LyrebirdAUPresetCodable` protocol marks Generators as preset-serialisable: `static var presetTypeID: String`, `var presetEncodedParameters: [String: AUValue]`, `static func presetMake(from:) -> any Generator`. - `LyrebirdAUPresetSourceRegistry` (NSLock-protected `[String: ([String: AUValue]) -> any Generator]`) registers conformers by `presetTypeID` so the restore path can reconstruct them. Unregistered type IDs in a saved state are silently skipped — that slot reverts to its scalar target. - `LyrebirdAudioUnit.fullState` payload restructured to nest: ```swift [lyrebirdAUFullStateKey: [ lyrebirdAUFullStateScalarKey: [String: AUValue], lyrebirdAUFullStateSourcesKey: [String: [String: AUValue]], lyrebirdAUFullStateSourceTypesKey: [String: String], ]] ``` The legacy flat 104a payload (`[lyrebirdAUFullStateKey: [String: AUValue]]`) is still read on restore — old saved states do not regress. ### Review history Three passes. Pass 1 blocking findings (5): 1. `_MIDIHandlerStorage.handler` data race — plain `var` optional closure read from RT, written from main. Replaced with `Atomic` + `_MIDIHandlerBox` pointer-swap pattern. 2. `_fillInputStagingFromHost` returned the pointer from a `withUnsafePointer { $0 }` closure — UB per Swift's unsafe-pointer contract. Nested the `pullInput` call inside the closure body. 3. `LyrebirdAUVoicePoolBinding` was documented as RT-thread callable but `VoicePool` is main-thread-only. Rewrote docs; removed all RT claims. 4. `AUInput.Audio` precondition message included `\(count)` interpolation — banned on the RT thread. Switched to a static string. 5. Missing dual-location `/// - Parameters:` blocks on `AUInput`, `LyrebirdAUVoicePoolBinding`, `LyrebirdSynthView`. Added. Pass 2 blocking findings (2): 1. `_MIDIHandlerStorage.deinit` had a `!` force unwrap on `UnsafeRawPointer(bitPattern:)`. Replaced with the same `guard let` pattern `setHandler` already used. 2. `LyrebirdSynthView` had three inline layout magic numbers (120, 16, 6). Extracted as three named `public let`s with doc comments. Pass 3: clean. No new findings. ### Test coverage 25 new tests across 7 files: ``` Tests/LyrebirdTests/AUv3/ AUInputTests.swift (4 tests) LyrebirdAUPresetRegistryTests.swift (3 tests) LyrebirdAUVoicePoolBindingTests.swift (3 tests) LyrebirdAudioUnitEffectTests.swift (3 tests) LyrebirdAudioUnitMIDITests.swift (5 tests) LyrebirdAudioUnitPresetTests.swift (4 tests) LyrebirdAudioUnitTests.swift (updated 1 existing test) Tests/LyrebirdUITests/ LyrebirdSynthViewTests.swift (3 tests) ``` Coverage: ring-buffer effect path, AURenderEvent chain walk (nil head, nil handler, single noteOn, single noteOff, chained events), preset registry register/make/unregister, factory-preset apply + currentPreset round-trip, voice-pool binding noteOn/noteOff/channel filter, SynthView UIParam-only discovery + metadata application + node identity. ### Files added ``` Sources/Lyrebird/AUv3/ AUInput.swift LyrebirdAUFactoryPreset.swift LyrebirdAUPresetCodable.swift LyrebirdAUVoicePoolBinding.swift Sources/LyrebirdUI/ LyrebirdSynthView.swift ``` ### Files modified ``` Sources/Lyrebird/AUv3/LyrebirdAudioUnit.swift (midiHandler + factoryPresets + currentPreset + fullState restructure + lyrebirdInputChannels) Sources/Lyrebird/AudioDrivers/AUv3Driver.swift (host-input pull + ABL) Sources/Lyrebird/Lyrebird.docc/AUv3.md (Phase 104c section) docs/auv3-extension-guide.md ("Phase 104c features" section) Tests/LyrebirdTests/AUv3/LyrebirdAudioUnitTests.swift (fullState namespaced-key test reads nested payload) ``` **3762 tests at completion** (was 3737 on `main` after Phase 104b merge; +25 new). --- ## Phase 105 — Spectral mono→N consolidation (SpectralChain.Audio + SpectralStereoDiffuse) Consolidates Lyrebird's STFT pipeline from a two-Generator (`FFTAnalysis` + `IFFTSynthesis`) shape into a single `SpectralChain.Audio` Generator that owns the forward FFT, the polar-domain processor chain, optional `SpectralProcessor2` sidechain processors, optional mono→N `SpectralFanOutProcessor`, and N inverse FFTs with windowed overlap-add resynthesis. Adds the first fan-out conformer, `SpectralStereoDiffuse` (mono → stereo decorrelation via anti-correlated phase randomisation). ### SpectralChain.Audio Three operating modes: | Mode | Configuration | Output | Use case | |------|---------------|--------|----------| | Mono resynthesis | `fanOut == nil`, `analyzeOnly == false` (default) | 1 channel | Replaces legacy `FFTAnalysis + IFFTSynthesis` | | Mono → N fan-out | `fanOut: SpectralFanOutProcessor`, `analyzeOnly == false` | `fanOut.outputChannelCount` channels | Stereo / quad / N-channel decorrelation | | Analyze-only | `analyzeOnly == true` | silent (mono) | Feature extractors, sidechain analyses | **Internals.** Single `vDSP_create_fftsetup` shared across all N IFFTs (same `fftSize` and `log2n`). Per-channel synthesis state lives in arrays of `UnsafeMutablePointer` (work `realp`/`imagp`, `timeDomainBuf`, `overlapBuf`) plus `[Float]` output rings. The analysis-side hopCounter and synthesis-side hopCounter tick independently so the synthesis read pointer can lag write by `hopSize` samples — matching legacy `IFFTSynthesis`'s `outputRingReadPos = ringSize - hopSize` initialisation and giving block 0 silence + block 1 first-hop output. Destination buffer aliasing in the no-fanOut + non-analyzeOnly path: `_destinations = [spectralBuffer]` avoids a per-hop polar→polar copy. When `fanOut != nil` and `!analyzeOnly`, N independent `SpectralBuffer` instances are allocated and populated per hop via `fanOut.process(source:into:channel:)`. **Golden-buffer test.** `monoResynthesisMatchesFFTAnalysisPlusIFFTSynthesis` feeds a 0.3 constant through both the legacy `FFTAnalysis + IFFTSynthesis` pair and a new `SpectralChain.Audio` for 6 blocks at `fftSize=64, hopSize=32`, then compares per-sample output. Δ < 1e-6 — the consolidation is behaviour-preserving for the mono path. ### SpectralFanOutProcessor + SpectralStereoDiffuse New protocol surface for mono→N: `process(source:into:channel:)` populates one destination polar buffer per output channel. The host `SpectralChain.Audio` calls it once per channel per hop after the standard `SpectralProcessor` chain and any sidechain processors run. **SpectralStereoDiffuse** is the first conformer. Per-channel xorshift64 PRNG states seeded from `seed` and `seed ^ spectralStereoDiffuseAntiSeedMask` so the two output channels are phase-uncorrelated. Per call: 1. DC and Nyquist forwarded unchanged. 2. Magnitudes `memcpy`'d from source to destination (passthrough). 3. Phases blended toward per-channel uniform random target in `(−π, π]` via shortest-angular-distance interpolation matching `SpectralDiffuse`'s formula. `amount` is `Atomic` clamped `[0, 1]`. `amount == 0` is exact bypass (verified by test). `amount == 1` produces wide decorrelated stereo (verified — < 5% bin-by-bin phase agreement between L/R). Magnitude conservation holds across all amount values (per-channel energy preserved; summing L + R does **not** reconstruct the input since the random phase realisations interfere — the intended decorrelation behaviour). ### Legacy types `FFTAnalysis` + `IFFTSynthesis` remain fully functional. Each gets a class-level "Note (Phase 105)" docstring callout pointing to `SpectralChain.Audio` as the preferred path. Hard `@available(*, deprecated)` annotation deferred so internal feature extractors (`SpectralCentroid` / `SpectralFlatness` / `SpectralFlux` / `SpectralEntropy` / `SpectralSpread` / `SpectralRolloff` / `OnsetDetector`) do not generate warnings. Migration of legacy call sites to the consolidated API is a future tightly-scoped phase. ### Review Two passes. Pass 1 blocking findings (2): 1. `_runAnalysisHop`'s fan-out guard was `if let fanOut, !analyzeOnly, _destinations.count > 1` — for any `SpectralFanOutProcessor` with `outputChannelCount == 1` the destinations array would have been allocated independently at init but `fanOut.process(...)` would never run, leaving the IFFT to read uninitialised data. Removed the count check. 2. `SpectralChain.Audio` had init-level `/// - Parameters:` only. CLAUDE.md requires dual-location blocks. Added an 11-parameter class-level block. Pass 2: clean. Both fixes verified by re-running the 17 new tests. ### Files added ``` Sources/Lyrebird/Generators/Spectral/ SpectralChain.swift SpectralFanOutProcessor.swift SpectralStereoDiffuse.swift Sources/Lyrebird/Lyrebird.docc/ SpectralChain.md Tests/LyrebirdTests/ SpectralChainTests.swift SpectralStereoDiffuseTests.swift ``` ### Files modified ``` Sources/Lyrebird/Generators/Spectral/FFTAnalysis.swift (docstring callout) Sources/Lyrebird/Generators/Spectral/IFFTSynthesis.swift (docstring callout) Sources/Lyrebird/Lyrebird.docc/Lyrebird.md (Spectral subsection) docs/stdlib/spectral.md (overview rewrite + Mono→N section) ``` **3779 tests at completion** (was 3762 on `main` after Phase 104c; +17 new). Full suite green except one pre-existing B6 timing flake unrelated to this branch. --- ## Phase 104d — AUv3 aux output + sidechain input busses Extends ``LyrebirdAudioUnit`` to declare and route ≥ 1 output bus and ≥ 0 input busses on top of the Phase 104a-c single-bus wrapper. Backward-compatible: single-bus subclasses (LyrebirdFM, every Phase 104a-c demo) keep working unchanged — the new class hooks default to the previous single-bus shape derived from `lyrebirdOutputChannels` / `lyrebirdInputChannels`. ### Public surface - ``LyrebirdAUBusSpec`` (new) — `Sendable` value type holding `name: String` + `channelCount: Int`. - ``LyrebirdAudioUnit/lyrebirdOutputBusses``, ``LyrebirdAudioUnit/lyrebirdInputBusses`` (new class vars) — arrays of ``LyrebirdAUBusSpec``. Defaults: `[Output × lyrebirdOutputChannels]` for output, `[Input × lyrebirdInputChannels]` for input when `lyrebirdInputChannels > 0` else `[]`. - ``AUInput/Audio/init(busIndex:channel:)`` (new designated init). Existing `init(channel:)` is a convenience for `busIndex: 0`. - ``SynthesisEngine/auInputBusOffsets``, ``SynthesisEngine/auOutputBusOffsets`` (new `public internal(set) var [Int]`) — populated by ``AUv3Driver/setup(engine:)`` so generators can map AU bus index → engine bus index. - ``AUv3Driver/configureBusMap(outputBusChannelCounts:inputBusChannelCounts:)`` (new) — called by `allocateRenderResources` before `engine.start()`. - ``AUv3Driver/render(frameCount:outputBusNumber:outputData:timestamp:pullInput:)`` — `outputBusNumber: Int = 0` parameter added (default keeps the legacy single-bus call shape working). - ``AUv3RingBuffer/write(fromAudioBuses:sourceBusOffset:channelCount:count:)`` (new overload) — slices a specific bus out of `engine.audioBuses`. Used by `AUv3Driver._distributeEngineOutputToRings`. - ``auv3RingBufferHeadroomFactor`` — named `public let = 2` controlling per-bus ring capacity. ### Driver architecture changes - One ``AUv3RingBuffer`` per AU output bus (was: one shared ring). Capacity `auv3RingBufferHeadroomFactor * max(maxFramesToRender, blockSize)` per channel. - One pre-allocated `AudioBufferList` + contiguous Float backing per AU input bus (was: one shared input ABL). - `render(outputBusNumber:...)` reads from the matching per-bus ring. Engine advances while the requested bus's ring needs more frames; other busses' rings buffer their output until the host pulls them. - `_fillInputStagingFromHost` iterates declared input busses, calls `pullInputBlock(...inputBusIndex...)` once per bus per engine block. ### Saturation policy AU spec lets a host pull bus 0 without ever pulling bus 1 — uncommon but legal. Without a guard, bus 1's ring would saturate after `capacity / blockSize` engine advances and trip the `AUv3RingBuffer.write` precondition on the RT thread. Fix: in `_distributeEngineOutputToRings`, if a ring's `availableToWrite < blockSize`, call `ring.reset()` before writing. Documented as a "freshest-block-wins" policy: hosts that neglect a bus for `> auv3RingBufferHeadroomFactor × capacity / blockSize` cycles will hear a discontinuity in that bus when next pulled. Typical hosts pull all buses synchronously and never trigger this path. Verified by the `asymmetricBusPullsDoNotCrash` test (64 pulls of bus 0 then one pull of bus 1, all returning `noErr`). ### Migration No migration required for existing single-bus subclasses. To add a sidechain or aux send, override the new class hooks: ```swift public final class StereoCompressorAU: LyrebirdAudioUnit { public override class func makeSynthesizer() -> SynthesizerBase { ... } public override class var lyrebirdOutputBusses: [LyrebirdAUBusSpec] { [.init(name: "Output", channelCount: 2)] } public override class var lyrebirdInputBusses: [LyrebirdAUBusSpec] { [ .init(name: "Main In", channelCount: 2), .init(name: "Sidechain", channelCount: 2), ] } } ``` The synth's `build()` uses `AUInput.Audio(busIndex: 0, channel: ch)` for main and `AUInput.Audio(busIndex: 1, channel: ch)` for sidechain. ### Review Two passes. Pass 1 blocking + minor findings (4): 1. **Blocking — RT crash** on asymmetric bus pulls. Fixed via the saturation guard described above. 2. **Blocking — missing render-loop sidechain coverage.** The original `auInputBusIndexResolves` test bypassed the driver entirely by seeding `engine.audioBuses` and calling `_computeSamples` directly. Added `renderLoopDispatchesPerInputBusPullBlock` that drives the full `internalRenderBlock` → driver → `_fillInputStagingFromHost` stack with a synthetic `pullInputBlock` filling bus 0 with +1.0 and bus 1 with -1.0; verifies main-input passthrough convergence + both bus pull-block invocations fire. 3. **Minor — magic number `2`** in `ringCapacity = 2 * max(...)`. Extracted to `auv3RingBufferHeadroomFactor` constant. 4. **Minor — `AUInput.Audio` class-level doc gap** (busIndex param missing). Added entry. Pass 2: clean. Build clean, swift test green at 3788 (3779 baseline + 9 new tests). ### Files added ``` Sources/Lyrebird/AUv3/LyrebirdAUBusSpec.swift Tests/LyrebirdTests/AUv3/LyrebirdAudioUnitMultiBusTests.swift ``` ### Files modified ``` Sources/Lyrebird/AUv3/LyrebirdAudioUnit.swift (bus-spec hooks, multi-bus init) Sources/Lyrebird/AUv3/AUInput.swift (init(busIndex:channel:), bus-map resolution) Sources/Lyrebird/AUv3/AUv3RingBuffer.swift (write(fromAudioBuses:sourceBusOffset:...) overload) Sources/Lyrebird/AudioDrivers/AUv3Driver.swift (configureBusMap, per-bus rings, outputBusNumber routing, _distributeEngineOutputToRings + saturation guard, per-input-bus pull) Sources/Lyrebird/Engine/SynthesisEngine.swift (auInputBusOffsets / auOutputBusOffsets) Sources/Lyrebird/Lyrebird.docc/AUv3.md ("Phase 104d additions" section) docs/auv3-extension-guide.md ("Phase 104d features" section) ``` **3788 tests at completion** (was 3779 on `main` after Phase 105; +9 new). swift test green except one pre-existing B6 timing flake unrelated to this branch. --- ## Phase 106 — FFT chain consolidation (legacy removal + synthOnly mode) Drops the legacy `FFTAnalysis` + `IFFTSynthesis` two-Generator pattern. All public spectral surface now routes through `SpectralChain.Audio` (Phase 105 consolidated pipeline). Adds a fourth operating mode — **synthOnly** — driven by a new `SpectralBufferGenerator` protocol; `SpectralBufferRead` and `SpectralPlayBuffer` conform, so no separately-wired IFFT consumer is needed for frame-buffer playback chains. ### What was deleted - `Sources/Lyrebird/Generators/Spectral/FFTAnalysis.swift` - `Sources/Lyrebird/Generators/Spectral/IFFTSynthesis.swift` ### New protocol ```swift public protocol SpectralBufferGenerator: Generator { var spectralBuffer: SpectralBuffer { get } var hopSize: Int { get } } ``` Conformers: `SpectralBufferRead`, `SpectralPlayBuffer`. Both expose their previously-private `_hopSize` as a public `let hopSize: Int`. ### New SpectralChain.Audio mode — synthOnly ```swift public convenience init( spectralSource: any SpectralBufferGenerator, fftSize: Int = 2048, hopSize: Int = 512, synthesisWindow: [Float]? = nil, processors: [any SpectralProcessor] = [], dualProcessors: [(processor: any SpectralProcessor2, sideChain: SpectralChain.Audio)] = [], fanOut: (any SpectralFanOutProcessor)? = nil, mul: any ValidGeneratorInput = 1.0, add: any ValidGeneratorInput = 0.0 ) ``` In synthOnly mode the chain: 1. Aliases its `spectralBuffer` to `spectralSource.spectralBuffer`. 2. Skips analysis-side allocations (`_inputRing`, `_windowedBuf`, `_fftAnalysisRealp`/`Imagp`). 3. In `_computeSamples`, drives the source via `calculatedSamples(count:)` once at the top of the block, then enters the per-sample loop. 4. At each analysis-hop boundary, skips windowing + forward FFT + polar conversion; dispatches `processors`, then `dualProcessors`, then any `fanOut` on the aliased buffer. 5. Runs the IFFT bank as in non-synthOnly modes. ### Hop-alignment constraint The chain pulls the source once per `_computeSamples` call. If `count > hopSize`, multiple source hops would fire and the chain would only read the final frame (earlier frames silently drop). A runtime precondition enforces `count <= hopSize` in synthOnly mode: ```swift precondition(count <= hopSize, "SpectralChain.Audio (synthOnly): count must be <= hopSize") ``` For typical configurations (`fftSize=2048, hopSize=512`, engine `blockSize=64..512`) this holds automatically. ### Migration of internal feature extractors Seven `.Control` extractors changed their `analysis:` init parameter type from `FFTAnalysis` to `SpectralChain.Audio`. `SpectralChain.Audio.processors` widened from `private` to `internal` so `OnsetDetector.Control`'s same-module precondition (`analysis.processors.contains(where:)`) still compiles: - `SpectralCentroid.Control` - `SpectralFlatness.Control` - `SpectralSpread.Control` - `SpectralFlux.Control` - `SpectralEntropy.Control` - `SpectralRolloff.Control` - `OnsetDetector.Control` The `dualProcessors` tuple type also changed: `(processor: SpectralProcessor2, sideChain: FFTAnalysis)` → `(processor: SpectralProcessor2, sideChain: SpectralChain.Audio)`. ### Pointer-safety fix `_fftAnalysisRealp` and `_fftAnalysisImagp` switched from `UnsafeMutablePointer` to `Optional>`. SynthOnly stores `nil` (no forward FFT scratch needed). `deinit` and the forward-FFT call sites are guarded with `if let`. This replaces a fragile `allocate(capacity: 0)` / `deallocate` round-trip that relied on implementation-defined semantics. ### Doc sweep - `docs/stdlib/spectral.md` rewritten around `SpectralChain.Audio`. Legacy two-Generator pipeline section removed. - `docs/stdlib/generators.md` spectral section rewritten. - DocC topics: `SpectralChain.md`, `SpectralFeatures.md`, `SignalAnalysis.md`, `BuiltInGenerators.md`, `PitchShifting.md`, `GranularSynthesis.md`. - `LyrebirdBuffer.swift` window factory docstrings (sineWindow, hanningWindow, rectangularWindow) updated to reference `SpectralChain.Audio(analysisWindow: synthesisWindow:)`. - `SpectralBuffer`, `SpectrumCapture`, `LyrebirdSpectrumView` doc-string updates. - Class-level `/// - Parameters:` block on `SpectralChain.Audio` extended to cover both audio-input and synthOnly init shapes (CLAUDE.md dual-location doc rule). ### Demos - Deleted duplicate `Demos/LyrebirdDemo/.../Synthesizers/PercSpectralPitchShift.swift` (root-level copy of the `Spectral/` subfolder file). - Rewrote `Synthesizers/Spectral/PercSpectralPitchShift.swift` to use `SpectralChain.Audio(input:processors:)` — drops the separate `IFFTSynthesis`. - New `Synthesizers/Spectral/PercSpectralStereoDiffuse.swift` — fan-out demo (mono → 2-channel decorrelated stereo via `SpectralStereoDiffuse`). - `BufferDemos.swift` wires `PercSpectralStereoDiffuse` as new Demo 5 with three `amount` sweep steps (0.0 / 0.5 / 1.0). TimeStretch shifts to Demo 6. - Stale `Synthesizers/Buffer/` and `Synthesizers/Granular/` subfolder duplicates (older content than the flat root copies) folded: flat root files moved into subfolders via `git mv` to match the Xcode pbxproj groups (which already pointed at the subfolders). pbxproj updated for `PercSpectralStereoDiffuse` (PBXFileReference + PBXBuildFile + Spectral group children). ### Tests Rewritten files: - `Tests/LyrebirdTests/FFTTests.swift` — reframed as `SpectralChain.Audio` tests (rate check, analyzeOnly silence, DC bin domination, round-trip unity-gain at 50% and 75% overlap, first-block silence). - `Tests/LyrebirdTests/SpectralAutoPullTests.swift` — engine-driven pulling of `SpectralChain.Audio` (standalone, paired with `SpectralCentroid.Control` / `SpectralFlux.Control`). - `Tests/LyrebirdTests/SpectralProcessor2Tests.swift` — dualProcessor dispatch through `SpectralChain.Audio`. - `Tests/LyrebirdTests/SpectralChainTests.swift` — Phase 105 golden-buffer parity test (`monoResynthesisMatchesFFTAnalysisPlusIFFTSynthesis`) removed (no legacy to compare); replaced with a DC unity-gain round-trip test. - `Tests/LyrebirdTests/OnsetDetectorTests.swift` — end-to-end + registration precondition retargeted. New suite: - `SpectralChain.Audio — synthOnly mode`: - `synthOnlyResynthesisProducesNonZeroAudio` — constant-DC `SpectralFrameBuffer` → `SpectralPlayBuffer` → `SpectralChain.Audio(spectralSource:)` → verifies non-zero audio in steady state after the IFFT bank's one-hop latency clears. - `synthOnlyDispatchesProcessorsOnAliasedBuffer` — counting `SpectralProcessor` verifies `callCount > 0`, `lastSeenDC == 100.0` (source's DC), and `chain.spectralBuffer === source.spectralBuffer` identity. ### Review history Two review passes. - **Pass 1.** Blocking: (a) missing test coverage for `SpectralChain.Audio(spectralSource:)` and `SpectralBufferGenerator`; (b) class-level `/// - Parameters:` block on `SpectralChain.Audio` covered only the `input:` init shape, missing `spectralSource:`; (c) fragile `UnsafeMutablePointer.allocate(capacity: 0)` stubs in synthOnly init/deinit. Caveman line-sweep also raised the frame-loss risk under `count > hopSize` — addressed by the runtime precondition added during fix commit `ed42d6a`. - **Pass 2.** Clean. ### Test count **3789 tests at completion** (was 3788 on `main` after Phase 104d merge; −1 obsolete Phase 105 parity test + 2 new synthOnly tests). Sequential `swift test --no-parallel` fully green. Pre-existing parallel-run flakes in `LyrebirdEventListRecording` (file-system contention across parallel test processes) and `ParameterSourceSwapIntegration` (timing-sensitive) remain unrelated to this branch. ## Phase 107 — `LyrebirdBuffer.nativeRateScale` (move helper off `PlayBuffer._Base`) Sample-rate compensation helper that converts a buffer's native sample rate into a `playRate` multiplier had been a method on `PlayBuffer._Base`. The helper used zero `PlayBuffer` state — only `buffer.sampleRate` and the passed-in engine rate — so any buffer-consuming generator (granular family, future warp/scrubbers, `BufRd`) was either copying the same `guard let bufRate = buffer.sampleRate` dance or paying a `PlayBuffer.Audio` allocation purely to reach the helper. Moved onto `LyrebirdBuffer` directly. - `Sources/Lyrebird/Buffers/LyrebirdBuffer.swift` (new public instance method, placed alongside `duration` / `phasorFrequency`): ```swift public func nativeRateScale(engineSampleRate: Double) -> Double { guard let bufRate = sampleRate else { return 1.0 } return bufRate / engineSampleRate } ``` The original `PlayBuffer._Base` version returned `Double(bufRate / engineSampleRate)` with a redundant cast — `LyrebirdBuffer.sampleRate` is already `Double?`, so the cast is dropped in the new implementation. - `Sources/Lyrebird/Generators/BufferIO/PlayBuffer.swift` — `_Base` helper deleted; class-level docstring example rewritten to `player.playRate = buffer.nativeRateScale(engineSampleRate: engine.sampleRate)`. - `Tests/LyrebirdTests/LyrebirdBufferRateScaleTests.swift` — new `@Suite("LyrebirdBuffer.nativeRateScale")` with four tests: nil `sampleRate` → `1.0`; matching rate → `1.0`; `48 kHz` buffer on `44.1 kHz` engine → `48000/44100`; `44.1 kHz` buffer on `48 kHz` engine → `0.91875` (also asserted to `1e-12`). Two prior cases at the bottom of `PlayBufferTests.swift` deleted. - `docs/stdlib/buffer-io-generators.md` updated to call out the new ownership (`LyrebirdBuffer.nativeRateScale`) and reuse-across-generators rationale. - Six demo files in `Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/` swept from `player.nativeRateScale(...)` to `player.buffer.nativeRateScale(...)`. (The `Demos/` tree had three duplicate top-level copies of `PercPlayBuffer.swift` / `PercPitchShift.swift` / `PercSpectralPitchShift.swift` mirrored in `Buffer/` / `Granular/` / `Spectral/` subfolders; the top-level duplicates were deleted on main ahead of this merge and the merge resolution accepted that deletion.) No RT-path involvement — helper is non-RT, called from `Synthesizer.build()` on the language thread. Single-pass `lyrebird_review_agent` run clean — no findings. 3790 tests pass. ## Phase 108 — PlayBuffer `rate` + `trigger` as `ValidGeneratorInput` Promoted `PlayBuffer.playRate` and `PlayBuffer.trigger` from `@LiveParam Double` to `any ValidGeneratorInput` init parameters on both `PlayBuffer.Audio` and `PlayBuffer.Control`. Renamed `playRate` → `rate` so the API matches the Lyrebird convention used by every other rate-shaped input (`freq`, `mul`, `add`, `phase`, `q`, etc.). `@LiveParam` is the right tool for "scalar tweaked from SwiftUI / MIDI CC"; it is the wrong tool for "rate generator that follows an envelope sample-accurately", which is what users actually want for varispeed / vibrato / envelope-gated retrigger. SC's `PlayBuf.ar` treats rate as a UGen input — Lyrebird now matches. - `Sources/Lyrebird/Generators/BufferIO/PlayBuffer.swift`: - `_Base.init` gains `rate: any ValidGeneratorInput = 1.0` + `trigger: any ValidGeneratorInput = 0.0`, propagated through `Audio.init` and `Control.init`. Both inits are multi-line (≥ 2 init params per CLAUDE.md style rule). - Both inputs classified at init via the standard `is any Generator` test, stored as `_rateInput` / `_rateIsGenerator` / `_triggerInput` / `_triggerIsGenerator` (no `as?` on the RT path). - `Audio._computeSamples` reads a full per-sample buffer when the input is a Generator, falls back to a scalar `floatValue(graph:)` via the `@inline(__always) func rateAt(_:) / triggerAt(_:)` pattern with `Optional<[Double]>?? scalarFallback` — no per-sample heap allocation. - `Control._computeSamples` uses the shared `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` helper for both rate and trigger — block-rate read of the last sample of the rendered buffer, falling back to `floatValue` for scalars. The `Control.calculatedSamples` bypass override is retained so per-block phase state advances exactly once per audio block regardless of sub-block count (canonical `Out.Control` pattern). - Trigger edge detection (`_prevTrigger`) preserved at block-aligned granularity (Audio: per-sample; Control: last sample of block). Sub-sample-accurate edge detection remains out of scope. - Dual `/// - Parameters:` doc blocks on both class and init for both `Audio` and `Control`. `@LiveParam` documentation removed. - `Tests/LyrebirdTests/PlayBufferTests.swift`: existing scalar cases rewritten against the new init signature; **+5 new tests**: scalar trigger reset at init, generator-driven rate varies phase per sample (LFO-modulated `rate`), generator-driven trigger resets on `Impulse` edge, Control trigger reset, Control reverse playback. Multi-block trigger cases use a `ParameterNode(0.0)` passed as `trigger:` — the idiomatic way to flip a generator-input value between blocks (same pattern used in `PanNParameterRampingTests`, `AmplitudeFollowerParameterRampingTests`, etc.). - `Sources/Lyrebird/Buffers/LyrebirdBuffer.swift`: `sampleRate` doc comment updated to reference `nativeRateScale(engineSampleRate:)` only (no longer mentions the removed `@LiveParam playRate` path). - `docs/stdlib/buffer-io-generators.md`: PlayBuffer section rewritten — Init blocks now show `rate:` / `trigger:` as `any ValidGeneratorInput`; three new examples (scalar rate, LFO-driven rate, `Impulse`-driven trigger + `ParameterNode` mutable trigger). Reverse-playback example uses `rate: -1.0` at init. - Demos: four `Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/` files swept (`Buffer/PercPlayBuffer.swift`, `Granular/PercPitchShift.swift`, `Spectral/PercSpectralPitchShift.swift`, `Spectral/PercSpectralStereoDiffuse.swift`). Each computes `let rateScale = buffer.nativeRateScale(engineSampleRate: engineSampleRate)` in `build()` and passes it at init as `rate: rateScale`. One latent compile bug in `PercSpectralStereoDiffuse` (was calling `player.nativeRateScale(...)` — a method that lived only on `LyrebirdBuffer`, not on `PlayBuffer._Base` after Phase 107) corrected in passing. Two `lyrebird_review_agent` passes: - **Pass 1** flagged one blocking finding: `Control._computeSamples` inlined the "last sample of buffer, fall back to floatValue" pattern instead of calling the shared `lastGeneratorSampleOrFloat` helper required by `docs/protocols/writing-generators.md` §13. The inlined fallback also diverged semantically — it returned `0.0` when `calculatedSamples.first` was `nil`, instead of the helper's correct fallback to `floatValue(graph:)`. - **Fix commit** (`9166333`) replaced both inlined blocks with two `lastGeneratorSampleOrFloat(...)` calls and removed the now-dead `_zeroFallback` stored property + its init assignment (`Audio` variant never used `_zeroFallback` — uses `Optional<[Double]>?? scalarFallback`). - **Pass 2** clean. 3794 tests pass. ## Phase 109 — `SpectralPolarClosure` + `SpectralComplexClosure` Closure-driven `SpectralProcessor` wrappers — same role `Closure` plays for time-domain DSP, but for in-place spectral mutation inside `SpectralChain.Audio`. Users can now prototype spectral effects inline in `Synthesizer.build()` without subclassing a new `SpectralProcessor` type for every experiment. Two variants, each with a co-located context struct and closure-body typealias: - **`SpectralPolarClosure`** (`Sources/Lyrebird/Generators/Spectral/SpectralPolarClosure.swift`, 203 lines). - `SpectralPolarContext`: `magnitudes`/`phases` as `UnsafeMutableBufferPointer` over the complex bins (length `fftSize/2 − 1`); `dcValue`/`nyquistValue` as single-element `UnsafeMutablePointer` (signed real scalars — DC and Nyquist are not mag/phase pairs); plus `binCount`, `sampleRate`, `fftSize`, `hopSize`, `frameIndex`. - Zero-copy access to the complex-bin storage via the existing `withUnsafeMutableMagnitudePointer` / `withUnsafeMutablePhasePointer` accessors on `SpectralBuffer`. DC/Nyquist are round-tripped through pre-allocated single-element pointers (two scalar copies per hop, no allocation) because the buffer's `_dcValue` / `_nyquistValue` are `private`. - **`SpectralComplexClosure`** (`Sources/Lyrebird/Generators/Spectral/SpectralComplexClosure.swift`, ~220 lines). - `SpectralComplexContext`: `real`/`imag` as `UnsafeMutableBufferPointer` of length `fftSize/2`, vDSP packed convention (`real[0] = DC`, `imag[0] = Nyquist`, remaining indices are the complex-bin real/imag pairs). - Pre-allocates two `UnsafeMutablePointer` scratch arrays in `init`, freed in `deinit`. `process(spectral:)` calls the existing `_readToRectangular` (polar → split-complex), invokes the closure body, then `_writeFromRectangular` (split-complex → polar) — the same internal accessors `SpectralChain.Audio` itself uses. - Round-trip cost is real but bounded (two vDSP calls each way per hop, ≤ 2048-bin scale). Documented explicitly so users know to pick the polar variant when they don't need Cartesian. `Float` element type throughout (not `Double` as the original plan suggested) — matches `SpectralBuffer` storage exactly, no per-hop convert cost. `hopSize` + `sampleRate` baked into the closure class at init since they live on `SpectralChain.Audio` rather than the buffer; populated into the context each hop. `_frameIndex` is a `var Int` on the closure class, incremented per hop — single-threaded RT access, no atomic needed. RT-safety contract documented hard at class level on both: closure body must not allocate, must not throw, must not `print`, must not call any `String`-constructing API. Acknowledged unenforceable — same contract as `Closure`. - `Sources/Lyrebird/Lyrebird.docc/Generators/SpectralClosures.md` — new DocC topic article covering both processors, a coordinate-system comparison table, full usage examples (polar gain, spectral freeze via reference-box capture), and the RT-safety contract. - `docs/stdlib/spectral.md` — new "Closure-driven spectral processors" section with context layout tables, examples, and updated RT-safety summary. - `Tests/LyrebirdTests/SpectralPolarClosureTests.swift` — **12 tests**: identity round-trip, gain mutation drops 6 dB, frame-index increment monotonic across hops, DC pass-through, Nyquist pass-through, single- frame mutation isolated, `isValid == false` guard, `fftSize` mismatch guard, plus `SpectralChain.Audio` integration tests. - `Tests/LyrebirdTests/SpectralComplexClosureTests.swift` — **15 tests**: same property coverage as polar plus complex-specific cases including `complexFreezeLatchesSpectrum` (full pre-allocated `memcpy` latch pattern — the canonical RT-safe freeze example). Two `lyrebird_review_agent` passes: - **Pass 1** flagged one blocking finding: dead `scratchReal` / `scratchImag` `Float` array declarations in the freeze example in `SpectralComplexClosure.swift` (the closure body actually captured via `Array(ctx.real)` / `Array(ctx.imag)`, leaving the two declared vars unused — misleading to readers thinking they showed the pre-allocated path). Also flagged one non-blocking typo: test method name `complexFreezeLatcesSpectrum` → `complexFreezeLatchesSpectrum`. - **Fix commit** (`dbbf5a3`) removed the dead `scratchReal`/`scratchImag` lines, rewrote the trailing `Note` to point readers at the test for the true pre-allocated `memcpy` pattern, and renamed the test method. - **Pass 2** clean on blocking findings; one non-blocking doc note about inaccurate Swift terminology in the DocC freeze note (`inout`-like semantics → captured reference box). - **Doc-fix commit** (`b04a585`) corrected the terminology. 3821 tests pass sequentially (`swift test --no-parallel`). Pre-existing `LyrebirdProcess` + `GrayNoise` parallel-run flakes (same family noted in the Phase 106 entry) remain unrelated. Phase 109 has no dependency on Phases 107 or 108 — independently mergeable. Shipped after 108 only because that was the chosen working order. --- ## Phase 110 — Extension SDK foundation (SPI promotions for out-of-tree Generator packages) Promotes the shared RT-safe helper symbols required by external Generator packages to `@_spi(LyrebirdExtensions) public`, so out-of-tree extension packages (LyrebirdATK, etc.) can implement Generators without forking core. Promotions in `MulAdd.swift`: - `MulAddSpec` (struct + init + stored properties) - `MulAddSpec.applyIfNeeded(to:graph:count:)` - `MulAddSpec.apply(to:graph:count:)` - `MulAddSpec.identity` static - `extractScalar(_:)` - `fillRampedResult(into:from:to:mulAdd:graph:count:)` - `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` Promotions in `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 are documented as MINOR-version-mutable; extension packages should pin tightly. Docs: - New `docs/protocols/extension-sdk.md` — tier-1 stable public surface + tier-2 SPI table, versioning policy, namespacing guidance for out-of-tree packages. - `docs/protocols/writing-generators.md` §13 — cross-link to extension-sdk.md. Tests: `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()` Both promoted to `@_spi(LyrebirdExtensions) public` and documented in `docs/protocols/extension-sdk.md` under a new "Test-helper hooks" subsection. Bulk import sweep across 231 test files to `@testable @_spi(LyrebirdExtensions) import Lyrebird` — mechanical, no test logic changed. 3821 tests in 440 suites pass. --- ## Phase 111 — Extract Ambisonic Toolkit (FOA) to LyrebirdATK external package Removes the entire `Foa*` UGen set, the bundled MIT KEMAR HRIR data, and the `HRIRFile.bundledKemar{Full,FullURL}` accessors from the Lyrebird core module. The exact same code (untouched algorithmically) now ships as the **LyrebirdATK** external Swift package — the first worked example of the Lyrebird Extension SDK (Phase 110, `docs/protocols/extension-sdk.md`). This is a deliberate API-breaking change. Consumers of the FOA toolkit must now add `LyrebirdATK` as a separate package dependency and `import LyrebirdATK` alongside `import Lyrebird`. See the LyrebirdATK README + `docs/ATK-Guide.md`. What moved out of core: - `Sources/Lyrebird/Generators/Ambisonic/` — 37 `Foa*` generators (Rotate, Tilt, Tumble, Focus{X,Y,Z}, Push{X,Y,Z}, Press{X,Y,Z}, Zoom{X,Y,Z}, Direct{X,Y,Z,O}, Asymmetry, Dominate{X,Y,Z}, NFC, Proximity, PsychoShelf, PanB, EncodeOmni, EncodeStereo, DecodeProjection, DecodeStereo, DecodeQuad, DecodeBinaural, BinauralFilters, AngleBase, GainBase, Matrix, Constants). - `Sources/Lyrebird/Resources/HRTF/KEMAR/kemar-full.lbhr` (1.47 MB) — bundled MIT KEMAR full HRIR set. `Resources/HRTF/` deleted. - `HRIRFile.bundledKemarFullURL` + `bundledKemarFull` static accessors — `Bundle.module` lookup now lives in `LyrebirdATK/Sources/LyrebirdATK/HRIRFile+BundledKEMAR.swift`, where `Bundle.module` resolves to the LyrebirdATK package's resource bundle. The generic `HRIRFile.load(contentsOf:)` loader stays in core, unchanged — extension packages and user code can still load arbitrary `.lbhr` files. - `Tests/LyrebirdTests/Ambisonic/` — 28 `Foa*` test suites. - The six KEMAR-loading tests in `Tests/LyrebirdTests/Buffers/HRIRFileTests.swift` (`bundledKemarLoadsSuccessfully`, `positionAzimuthsAreInValidRange`, `positionElevationsAreInValidRange`, `frontCentrePositionExists`, `allSamplesAreInValidRange`, `leftAndRightIRsDifferForOffAxisPositions`). Moved 1:1 to `LyrebirdATK/Tests/LyrebirdATKTests/HRIRFileBundledKEMARTests.swift`. Synthetic / negative / round-trip loader tests stay in core (they exercise the loader itself, not KEMAR). - `docs/stdlib/ambisonic-toolkit.md` → `LyrebirdATK/docs/ATK-Guide.md`. - `docs/stdlib/generators.md` ATK section rewritten as a pointer to the external package. - `scripts/build-kemar-hrir.py` → `LyrebirdATK/scripts/`. What changed in core: - `Package.swift` Lyrebird target — `resources: [.process("Resources")]` removed (no Resources directory remains). - `Sources/Lyrebird/Buffers/HRIRFile.swift` — Bundled-KEMAR extension block removed; class-level docstring rewritten to drop the `scripts/build-kemar-hrir.py` reference and to clarify that bundled HRIR data is owned by extension packages, not core. - `docs/stdlib/generators.md` — ATK section rewritten. Verification: - `swift test` (core): 3499 tests in 405 suites pass. - `swift test` (LyrebirdATK, against this branch via local path dep): 322 tests in 36 suites pass. - Sum: 3499 + 322 = 3821 = pre-extraction total. No tests deleted; every removed test moved 1:1 to LyrebirdATK. Versioning impact: source-breaking change. Recommended tag **Lyrebird 2.0.0** after merging. Consumers who depend on the previous (FOA-bundled) Lyrebird stay pinned to `0.9.x`. --- ## Phase 112 — Extension authors guide + README extensions section New `docs/extension-authors-guide.md`: end-to-end walk-through for building an out-of-tree Swift package that adds Generator / Synthesizer implementations. Companion to `docs/protocols/extension-sdk.md` (which lists the SPI surface); this guide shows how to wire it together, ship a versioned release, and avoid common pitfalls (SPI imports in tests, `Bundle.module` per-package, package-name case-sensitivity in target dependencies, SSH vs HTTPS for private repos, SemVer + compatibility matrix). LyrebirdATK is the canonical worked example referenced throughout. Authors clone its `Package.swift` / `Sources` / `Tests` / `README` / `LICENSE` as templates. `README.md` updates: - New "Extensions" section between "The lyrebird CLI" and "Project structure", listing known extension packages (LyrebirdATK) + pointers to the SDK doc and the new authors guide. - Documentation table picks up two new rows (`extension-sdk.md` + `extension-authors-guide.md`). No source code changed; doc-only commit. Test count unchanged at 3499 (core) / 3821 (core + LyrebirdATK). --- ## Phase 113 — Pan4 family refactor (`PanAz`, `PanAzDistance`, `PanXY`, `PanXYDistance`) Reshapes the 4-speaker panning family around an `open` `Pan4` base class holding the shared infrastructure (4-row output buffer, `_mulAdd`, `outputChannelCount = 4`, named channel aliases). Four concrete subclasses provide the actual generator behaviour. Old leaf `Pan4` (azimuth + elevation `@LiveParam` in `[-1, 1]`) is gone — its azimuth-only behaviour now lives in `PanAz` with proper radian semantics, and the four-corner equal-power gain math is reused via shared file-scope helpers. ### New shared infrastructure - **`Pan4.swift`** — refactored from leaf class to `open class Pan4: GeneratorBase, AudioGenerator`. Owns `internal var _result: [[Double]]` (4 rows pre-allocated to `lyrebirdDefaultResultBufferSize` in `init`), `internal let _mulAdd: MulAddSpec`, `outputChannelCount = 4` override, `floatValue(graph:)` impl that routes through `calculatedSamples`, and channel aliases (`frontLeft` / `frontRight` / `rearRight` / `rearLeft`) on an extension so subclasses inherit them. Default `_computeSamples` returns the zero-filled buffer; subclasses override. - **`Pan4Helpers.swift`** (new) — module-internal helpers shared by every subclass: - `azimuthToSquareBoundary(_ az: Double) -> (x: Double, y: Double)` — projects azimuth radians onto the unit-square boundary via `1 / max(|sin az|, |cos az|)` 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). Degenerate `(sin, cos) → (0, 0)` (NaN / subnormal cancellation) collapses to `(0, 0)`. - `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 `cos`/`sin`, and writes `source × gain` into the four `_result` rows at the given index. Both `@inline(__always) internal` — call cost vanishes after the optimiser. Power invariant `LF² + RF² + RR² + LR² = 1` for any clamped `(x, y)`. ### Subclasses - **`PanAz.swift`** (new) — polar 4-speaker pan. `@LiveParam azimuth: Double = 0.0` in **radians** (0 = front centre, increases clockwise; wraps modulo 2π via `sin`/`cos`). Position is fixed to the unit-square boundary via `azimuthToSquareBoundary`. `±π/4` and `±3π/4` hard-pan to the four speaker corners; `0`, `±π/2`, `π` give equal-energy splits at the cardinal edges. - **`PanAzDistance.swift`** (new) — polar pan with full distance modelling. `azimuth` (radians) + `distance` (unitless: `0` = listener, `1` = boundary, `> 1` = beyond) + `velocity` (m/s) all accept any `ValidGeneratorInput`. Distance shaping pipeline (single mono LP + single delay line) identical to `PanXYDistance` / `SpatialDistance`: amplitude `1 / max(|distance|, 1)`, air-absorption cutoff `∝ amp²`, Doppler delay-rate `1 − velocity / speedOfSound` clamped to `[0.25, 4.0]`. Negative distance is treated as `|distance|` (direction comes from azimuth alone). Chebyshev metric matches `PanXYDistance` exactly because the boundary projection has `max(|x_b|, |y_b|) = 1`. Same structural params (`airAbsorptionCutoff`, `speedOfSound`, `sampleRate`, `maxDelayTime`). - **`PanXY.swift`** (refactored from Phase 113 initial implementation) — cartesian `@LiveParam x` / `@LiveParam y` in `[-1, 1]`. Now subclasses `Pan4` (inherits output buffer + `_mulAdd` + aliases); the per-sample gain math is delegated to the shared `writeEqualPowerSquarePanSample` helper instead of inlined. Public API unchanged. - **`PanXYDistance.swift`** (refactored from Phase 113 initial implementation) — cartesian + Chebyshev distance shaping. Now subclasses `Pan4`; the distance pipeline (LP + Doppler + amp) still runs inline for state coherence, but the four-channel pan write uses the shared helper so the equal-power math is single-sourced. Public API unchanged. - **`SpatialDistanceConstants.swift`** — promoted the six file-private scalar constants (`spatialDistanceMinReadRate`, `spatialDistanceMaxReadRate`, `spatialDistanceInitialDelaySamples`, `spatialDistanceMinDelaySamples`, `spatialDistanceMinCutoffHz`, `spatialDistanceMaxCutoffFraction`, `spatialDistanceTwoPi`) from `SpatialDistance.swift` to module-internal so the distance subclasses reuse them. `SpatialDistance.swift` updated to point at the shared file; no behaviour change. ### Test migration + new coverage - **`PanningTests.swift`** — old `@Suite("Pan4")` rewritten as `@Suite("PanAz")`. Hard-corner tests at `±π/4` / `±3π/4`, cardinal-edge tests at `0` / `±π/2` / `π` (each verifies even split across the two adjacent corners), power invariant across 16 azimuths around the circle, azimuth wrap at `2π`, `mul` at RF corner, fan-out cache. - **`PanAzParameterRampingTests.swift`** (renamed via `git mv` from `Pan4ParameterRampingTests.swift`) — two ramp tests: front→RF corner, front→rear sweep. - **`PanAzDistanceTests.swift`** (new) — rate, channel count, silent input, first-block finite, boundary-corner equivalence to `PanAz`, `distance=0` equal-energy collapse, `1/d` halving at `distance=2` vs `1`, negative-distance absolute-value symmetry, Doppler down-shift, `mul`/`add`, fan-out cache. - **`ChannelSelectTests.swift`** — Pan4 alias test updated to use `PanAz` at `az = -π/4` for the LF hard-pan. - **`PanXYTests.swift`** / **`PanXYParameterRampingTests.swift`** / **`PanXYDistanceTests.swift`** — unchanged from the initial Phase 113 pass; still green via inheritance through the refactored base class. ### Documentation - `docs/stdlib/generators.md` — "Panning Extensions" section rewritten around a four-row family table; one subsection per concrete subclass. - `docs/stdlib/multichannel.md` — intro list + named-aliases table updated to spell out the family. - `Sources/Lyrebird/Lyrebird.docc/Generators/MultiChannel.md` — intro list expanded. - Class-level + init-level `/// - Parameters:` blocks on `Pan4`, `PanAz`, `PanAzDistance`, `PanXY`, `PanXYDistance` with units, ranges, defaults; class docstrings on `Pan4` lay out the base-class/subclass contract and the speaker layout table. ### Review history Phase 113 ran two review cycles. The first review (initial `PanXY` + `PanXYDistance` implementation, with old `Pan4` still on the elevation API) caught four blocking findings — dead `_referenceDistance`, dead `_sampleRate`, two `@Suite` per file, and `try?` swallowing an engine start failure — all resolved before re-review. The Pan4-family refactor that followed (this entry) passed `lyrebird_review_agent` 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 correctly propagates through the `extension Pan4`; deterministic NaN guard in `azimuthToSquareBoundary` flagged as safe. 3544 tests pass on this branch. --- ### Phase 114 — Generator boilerplate reduction (`_result` on base, `_checkCount`, default `floatValue`, buffer factories) Eliminates ~1000 lines of mechanical boilerplate that every new Generator (and every test fixture conforming to `Generator`) used to repeat verbatim. After Phase 114 a minimal mono `AudioGenerator` is six lines instead of ~18. **Four consolidations, landed as one phase.** 1. **`_result` lives on `GeneratorBase`.** Base now declares `public var _result: [[Double]]` and its designated initializer takes `init(channels: Int = 1)`, allocating `_result` with the requested row count. Mono subclasses drop their `private var _result: [[Double]]` declaration and the `_result = [[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)]` init line entirely — the implicit `super.init()` call sets up a 1-row buffer. Multi-row subclasses (Pan2/Pan4/PanN, AmbiEncoder1/AmbiDecoder1, BinaryOpGenerator, GeneratorArray, FreqTracker, SVF, Chorus, FrequencyShifter, FreeVerb, GVerb, PlateReverb, SpringReverb, ConvolutionReverb, SpectralChain, multi-channel In/Out/BufferRead/RecordBuffer/PlayBuffer/DiskIn/DiskOut, all granular generators) call `super.init(channels: N)` and drop their manual `_result = …` allocation. 2. **`_checkCount(_:)` on `GeneratorBase`.** New `@inlinable` method that traps with the canonical message if `count > _result[0].count`. Replaces the three-line `precondition(count <= _result[0].count, "count \(count) exceeds pre-allocated buffer (…). Ensure SynthesisEngine blockSize <= lyrebirdDefaultResultBufferSize.")` boilerplate. Sites with generator-specific debug messages (e.g. "RBJBandPassSkirt: …") are left as-is — they carry extra context. Canonical-form sites collapse to `_checkCount(count)`. 3. **Default `floatValue` on `AudioGenerator`.** New protocol extension provides the canonical `calculatedSamples(graph:count: blockSize).first?.first ?? 0` implementation for every `AudioGenerator` conformer. Most generators drop their `public func floatValue(graph: SynthGraph) -> Double { … }` stub entirely. Generators with different scalar semantics (`ConstantGeneratorInput` returns its stored value directly) keep their override. `ControlGenerator` conformers still must provide their own `floatValue` returning the block target — the AudioGenerator default deliberately does not apply. 4. **Buffer factory helpers.** New `Sources/Lyrebird/GeneratorCore/ResultBuffer.swift`: - `makeSampleBuffer(_ count: Int = lyrebirdDefaultResultBufferSize) -> [Double]` — one zero-filled channel. - `makeResultBuffer(channels: Int = 1) -> [[Double]]` — N-channel buffer with rows sized to `lyrebirdDefaultResultBufferSize`. `GeneratorBase` uses `makeResultBuffer(channels:)` internally to allocate `_result`. Subclasses owning a *separate* scratch buffer (e.g. `_zeroFallback` rows in DiskIn / BufferRead / RecordBuffer / InputGrain) call `makeSampleBuffer()` instead of inlining `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)`. Centralising the literal removes ~300 repetitions of the buffer-size constant from `_computeSamples`-adjacent code. **Multi-row override fixes uncovered en route.** While moving the allocation to base, several generators that lacked an `outputChannelCount` override on a clearly multi-row class were flagged and fixed: `FreqTracker` (2 channels — freq + amplitude rows), `FreeVerb` and `GVerb` (stereo). Previously these silently mono-ized under `+ - * /` operators. The codebase rule already required the override; the rewrite made the absence load-bearing. **`GranularBase` API extension.** `GranularBase.init(seed:)` becomes `init(seed:channels: Int = 1)` so granular subclasses (BufferGrain, SineGrain, FMGrain, InputGrain) can thread their stereo `channels: 2` through the base→GeneratorBase chain in one call. **Files changed.** New: - `Sources/Lyrebird/GeneratorCore/ResultBuffer.swift` — `makeSampleBuffer` + `makeResultBuffer`. Modified core: - `Sources/Lyrebird/GeneratorCore/GeneratorBase.swift` — owns `_result`, gains `init(channels:)` and `_checkCount(_:)`. - `Sources/Lyrebird/GeneratorCore/Generator.swift` — default `floatValue` on `AudioGenerator`; updated doc-comment skeleton. - `Sources/Lyrebird/Generators/Granular/GranularBase.swift` — channels-aware init. Modified ~150 generator files across `Generators/{Filters,Math,Oscillators,Noise,Envelopes,Modulation,Reverb,Granular,Panning,Buffer*,BusIO,Dynamics,Random,Triggers,Routing,Spectral,Demand,TemporalDemand,UI,PhysicalModels,Gendy,KarplusStrong,Delays,Core}/*` plus `AUv3/AUInput.swift`, `Parameters/ParameterNode.swift`, all to drop `_result` declarations, drop canonical floatValue stubs, route through `super.init(channels:)`, and use `_checkCount` / `makeSampleBuffer` where the form matched. Modified tests: - 17 test files lost their boilerplate `_result` declarations on private test-fixture generators; `_computeSamples` opens with `_checkCount(count)` and writes into the inherited `_result`. `BinaryOpGeneratorTests` (StereoConstantGen, TripleConstantGen, QuadConstantGen), `MulAddTests` (StereoConstantGen), `ConvolutionReverbTests` (SequenceSource), `ControlGeneratorTests` (CountingControl), `ParameterNodeSourceAPITests` / `ParameterNodeSourceSlotTests` / `ParameterSourceSwapIntegrationTests` / `ParameterNodeCrossfadeTests` (various ConstantControlSource / SentinelControlSource), `LyrebirdAUPresetRegistryTests` (FixturePresetGen), `ParameterSourceQueueTests` (MinimalGen), `AUv3DriverTests` (CounterGen). Modified docs: - `docs/protocols/writing-generators.md` — §2 (Buffer Pre-allocation), §3 (State Variables), §9 (Complete Skeleton), §13 (Shared Helpers — adds `_checkCount` and buffer factories to the table). - `Sources/Lyrebird/Lyrebird.docc/Generators/WritingGenerators.md` — rewritten code blocks to match new patterns. - `CLAUDE.md` — Generator protocol bullets + Shared Helpers list. **Verification.** - `swift build` clean. - `swift test` — 3544 tests in 409 suites pass (same count as Phase 113 — no test added or removed; the refactor preserves all behaviour). - `lyrebird_review_agent` — three review passes. Pass 1 flagged two doc blockers: `GeneratorBase._result` doc described the wrong post-super reassignment pattern, and the DocC `WritingGenerators.md` article still showed pre-Phase-114 patterns across five code blocks. Pass 2 caught two additional doc-only regressions: `GeneratorBase` class-level summary and a newly added `Generator` protocol comment both still said "Multi-row generators reassign `_result = makeResultBuffer(channels: N)`" instead of `super.init(channels: N)`. All rewritten to match the actual codebase pattern. Pass 2 also flagged `AUInput.Audio._computeSamples` as the only diff-touched site still on the inline `precondition` form — converted to `_checkCount(count)` since the message offered no extra context. Pass 3 clean. --- ## Phase 148 — Flaky Timing Tests ✓ COMPLETE Three test suites — `LyrebirdProcess`, `LyrebirdEventList`, and `LyrebirdEventListRecording` — were each producing 10–18 failures per `swift test` run, always concentrated on the same handful of tests that wait on engine-callback flags (`onFinished`, `play` completion, file-flush hook). The common shape: an `AsyncExpectation`-or-flag side-channel never flipped within the 1.5-second wall-clock timeout, and a subsequent assertion read a sentinel/uninitialised value (`elapsed == -1.0`, `releaseElapsed` astronomically large, `eventListNow == nil`). The previously-committed `FLAKY_TIMING_TESTS.md` census misread the astronomical `releaseElapsed == 62313514124.18649` value (~1975 years) as a `mach_absolute_time` / `mach_timebase_info` zero-init bug and made it investigation priority #1. The real cause is far more mundane: the test stores `Date.distantFuture` as a sentinel in a `Box` that the `onFinished` callback is expected to overwrite. When the callback times out, the box still holds `distantFuture`, and `finishedDate.get().timeIntervalSince(...)` returns a `distantFuture - realDate` delta that lands in the 60-billion-second neighbourhood. Not a timer bug. Census deleted. **Root cause.** Each suite has its own private `TestBlockDriver` fixture that drives the offline-driven `SynthesisEngine` by calling `processBlock(inputSamples: [])` on a background thread. The original loop was: ```swift while self._running { self._engine.processBlock(inputSamples: []) Thread.sleep(forTimeInterval: 0.001) } ``` At `blockSize = 64` and `sampleRate = 44_100`, one `processBlock` call advances engine time by `64 / 44_100 ≈ 1.451 ms`. The `Thread.sleep(forTimeInterval: 0.001)` call requests a 1 ms wall sleep but is highly inaccurate under contention — actual sleep durations of 1–10+ ms are common on a loaded machine. Engine time therefore advances at only ~1.45× realtime in the best case and slips below realtime when sleep stretches. Tests with 1.5 s wall-clock timeouts on engine events that need engine-time progress (envelope releases at 50 ms, process completions, stem flushes) fail when engine time hasn't caught up. **Fix.** Burst 32 `processBlock` calls per `Thread.sleep`: ```swift while self._running.load(ordering: .relaxed) { for _ in 0..` from `Synchronization`: ```swift private let _running = Atomic(false) _running.store(true, ordering: .relaxed) _running.load(ordering: .relaxed) _running.store(false, ordering: .relaxed) ``` The bare `Thread.sleep(forTimeInterval: 0.001)` literal violated the CLAUDE.md "no magic numbers" rule once the surrounding code got touched. Promoted to a named constant: ```swift private static let wallSleepSeconds: TimeInterval = 0.001 ``` `LyrebirdEventListTests.swift` and `LyrebirdEventListRecordingTests.swift` had `TestBlockDriver` copies that did not store the `Thread` reference, unlike `LyrebirdProcessTests.swift`. Added `private var _thread: Thread?` to both for parity (latent thread-lifetime hazard — the thread retains itself while running, but storing a strong reference matches the canonical pattern). **Tests.** 10 consecutive `swift test --filter "LyrebirdProcess$|LyrebirdEventList$|LyrebirdEventListRecording$"` runs pass clean (75 tests / 5 suites each run). Same suites previously produced 10–18 failures per run. Total test count unchanged at 3610 (no tests added or removed; fixture-only). **Pre-existing, out of scope.** Full `swift test` (no filter) aborts non-deterministically with `error: Exited with unexpected signal code 6` on this machine. The abort is preceded by hundreds of `objc[…]: Class … is implemented in both …LyrebirdPackageTests.xctest and …libLyrebirdLiveCompile.dylib` warnings — the Phase 142 `LyrebirdLiveCompile` product, which is declared `type: .dynamic` and linked dynamically by `Lyrebird`, gets statically merged into the test executable while `libLyrebirdLiveCompile.dylib` is also loaded for the live-compile test path. This same abort reproduces on clean `origin/main` with no changes applied. Deferred to a dedicated phase. Setting `OBJC_DISABLE_DUPLICATE_CLASS_CHECK=YES` silences the duplicate-class warnings but does not consistently prevent the related ARC `_ContiguousArrayStorage deallocated with non-zero retain count` abort that follows. **Files changed.** - `Tests/LyrebirdTests/Process/LyrebirdProcessTests.swift` - `Tests/LyrebirdTests/Process/LyrebirdEventListTests.swift` - `Tests/LyrebirdTests/Process/LyrebirdEventListRecordingTests.swift` - `docs/00-working-order.md` (row moved into summary table) - `FLAKY_TIMING_TESTS.md` deleted 5 files, +51/-87 lines net. **Verification.** - `swift test --filter` on the three target suites — 10/10 runs pass, 75 tests / 5 suites per run. - `lyrebird_review_agent` — two review passes. Pass 1 caught the `_running` race, the missing `_thread` storage in two of three fixtures, and the bare `0.001` magic number. Pass 2 clean. - Caveman line sweep — `LGTM` after fixes. --- ## Phase 149 — `lyrebird repl` Toolchain Fix ✓ COMPLETE `swift package repl` was removed from the current Swift toolchain — running it errors with `error: Unknown subcommand or plugin name 'repl'`. The Lyrebird CLI's `lyrebird repl` subcommand and the `lyrebird>` interactive-shell `repl` command both went through `REPLLauncher`, which still passed `["package", "repl"]` to the `swift` binary. Both code paths had been silently broken since the SPM change. Phase 145–147 (the LyrebirdScratchView / LyrebirdScratchDemo live-compile scratchpad) replaced the *user workflow* the old REPL filled, but the `lyrebird repl` CLI surface remained advertised in the docs and was not fixed. **Fix.** `REPLLauncher` is now a two-step invocation: 1. `swift build` — stages `.build/debug/Modules/Lyrebird.swiftmodule`, `.build/debug/libLyrebird.dylib`, and the LyrebirdC modulemap at `.build/debug/LyrebirdC.build/module.modulemap`. Output is inherited (stdout/stderr) so SPM compile errors stay visible. 2. `swift repl -I .build/debug/Modules -I .build/debug/LyrebirdC.build -L .build/debug -lLyrebird` — the same flags SPM was computing internally for `swift package repl`. The `-I` flags expose the Swift module and the C-module modulemap; `-L`/`-lLyrebird` links the dynamic library so `import Lyrebird` succeeds and runtime symbols resolve through the dylib's `@rpath`. Public surface change in `Sources/LyrebirdCLI/REPLLauncher.swift`: - `CLIError` gains `.buildFailed(exitCode: Int32)`. - `REPLLauncher.swiftArguments` (removed) → `buildArguments: ["build"]` + `replArguments: ["repl", "-I", ".build/debug/Modules", "-I", ".build/debug/LyrebirdC.build", "-L", ".build/debug", "-lLyrebird"]`. - `REPLLauncher.makeProcess(arguments:in:)` is the new designated factory; the existing no-arg form (`makeProcess(in:)`) defaults to `replArguments`. - New `REPLLauncher.build(in:)` runs `swift build`, throws `CLIError.buildFailed(exitCode:)` on non-zero exit, and surfaces signal-kill terminations as `exitCode: 1` (so callers piping the raw `Int32` into `exit(_:)` don't propagate misleading signal numbers). - `REPLLauncher.launch(in:)` now calls `build(in:)` first. `InteractiveShell.run` and `LyrebirdCLIMain.runREPL` both gain a `catch CLIError.buildFailed` arm that writes `"error: swift build failed (exit code N). REPL not started."` to stderr. **Docs swept.** `docs/tooling/repl.md`, `docs/tooling/cli-guide.md`, `docs/tooling/workflow.md`, `Sources/Lyrebird/Lyrebird.docc/CLIGuide.md`, `Sources/Lyrebird/Lyrebird.docc/REPLGuide.md` all describe the two-step invocation and explain why `swift package repl` was retired. **Tests.** `swiftArgumentsArePackageRepl` removed; replaced by `buildArgumentsAreSwiftBuild`, `replArgumentsPointAtBuildArtifacts` (asserts `-I` and `-L` token presence plus the four path values), `buildProcessArgumentsMatchBuildArguments`, `buildThrowsBuildFailedWhenNoPackageManifest` (invokes `build(in:)` in a `FileManager.default.temporaryDirectory` subdir with no `Package.swift`, asserts `CLIError.buildFailed` thrown with non-zero `exitCode`). `processArgumentsMatchSwiftArguments` renamed to `processArgumentsMatchReplArguments`. 10/10 `REPLLauncher` + `InteractiveShell` suite tests pass. **Origin of the work.** This fix was found as an uncommitted diff in the `.claude/worktrees/infallible-boyd-97598a` agent worktree (branch `claude/infallible-boyd-97598a`, last touched 2026-05-12) during the post-Phase-148 branch / worktree cleanup sweep. The agent had merged its branch tip back to main but left the REPL fix as uncommitted modifications in the worktree. Recovered by saving the diff to a patch, creating a fresh branch off the current `main`, and applying via `git apply --3way` — the patch applied cleanly despite Phase 137's scaffolder additions touching some of the same files (`InteractiveShell.swift`, `LyrebirdCLI.swift`, `CLICommand.swift`, `cli-guide.md`, `CLIGuide.md`). **Scope verification.** No code outside `Sources/LyrebirdCLI/` or `Tests/LyrebirdCLITests/` references `REPLLauncher`, the renamed `swiftArguments` constant, or any `CLIError` case — confirmed via grep across `Sources/`, `Tests/`, and `Demos/`. Templates emit no REPL plumbing; the only non-CLI mention of "REPL" in source is one cosmetic print statement in `ProjectScaffolder.swift`. The LyrebirdScratchView / LyrebirdScratchDemo live-compile scratchpad uses its own `swiftc` shell-out + `dlopen` path (Phase 142–147) and is independent of `lyrebird repl`. `LyrebirdScratchDemo` Xcode build SUCCEEDED on this branch. **Files changed.** - `Sources/LyrebirdCLI/REPLLauncher.swift` - `Sources/LyrebirdCLI/CLICommand.swift` - `Sources/LyrebirdCLI/InteractiveShell.swift` - `Sources/LyrebirdCLI/LyrebirdCLI.swift` - `Tests/LyrebirdCLITests/REPLLauncherTests.swift` - `docs/tooling/cli-guide.md` - `docs/tooling/repl.md` - `docs/tooling/workflow.md` - `Sources/Lyrebird/Lyrebird.docc/CLIGuide.md` - `Sources/Lyrebird/Lyrebird.docc/REPLGuide.md` 10 files, +188/-44 lines net. **Verification.** - `swift build` — clean. - `swift test --filter "REPLLauncher|InteractiveShell"` — 10/10 pass. - `swift test --filter "Scratch|LiveSession|LiveCompiler|SnippetHarness|ProjectScaffolder|InteractiveShell|REPLLauncher"` — 122/122 pass on this branch (verifies the scratchpad and scaffolder paths still work). - `xcodebuild build -workspace Lyrebird.xcworkspace -scheme LyrebirdScratchDemo` — BUILD SUCCEEDED. - `lyrebird_review_agent` — two review passes. Pass 1 caught the missing `buildFailed` test coverage, missing `-I`/`-L` flag-token assertions, and the signal-kill exit-code leak. Pass 2 clean. - Caveman line sweep — `LGTM` after fixes. --- ### Phase 151 — AppKit-in-core layering fix (`MouseTracker` extraction) ✓ shipped The `Mouse.X.Control` / `Mouse.Y.Control` / `Mouse.Click.Control` generators under `Sources/Lyrebird/Generators/UI/` import `AppKit` directly inside the core `Lyrebird` module via the `MouseTracker` singleton. Per CLAUDE.md the core module is supposed to stay UI-framework-free (`SwiftUI` is explicitly banned; the same layering principle applies to `AppKit`). Today the import is gated by `#if os(macOS)` so iOS builds compile cleanly, but it's the only remaining UI-framework leak in core. **Goal.** Remove `import AppKit` from `Sources/Lyrebird/` while preserving the `Mouse.X` / `Mouse.Y` / `Mouse.Click` user-facing API and the existing `MouseTracker.shared._x` test-injection hook (used by 1 test file). **Approach (preferred — bridge pattern).** Keep the `Mouse` Generator types in core (so `Mouse.X.Control()` continues to work with `import Lyrebird` only). Define a minimal protocol in core: ```swift public protocol MouseInputBridge: Sendable { var x: Double { get } // [0, 1] var y: Double { get } // [0, 1] var button: Double { get } // 0.0 or 1.0 } ``` Core ships: - The `MouseInputBridge` protocol. - `MouseInputBridge.install(_:)` static (single-slot Atomic pointer registry). - A no-op default bridge returning constant 0.5 / 0.5 / 0.0 so headless / iOS use is silent rather than null-dereferencing. - `Mouse.X.Control` / `Mouse.Y.Control` / `Mouse.Click.Control` reading from the registered bridge via `MouseInputBridge.current` on each block. The AppKit `MouseTracker` (NSEvent global monitor installer) moves to `Sources/LyrebirdUI/MouseTracker.swift` (or a new `Sources/LyrebirdMacUI/` target if SwiftUI dependency on `LyrebirdUI` is undesirable for headless consumers — judgement call when implementing). On macOS, calling `MouseTracker.installShared()` from app startup wires the AppKit-driven implementation into core. `MouseGeneratorTests` switches to a `SyntheticMouseBridge` value type that writes directly to its own atomics and registers itself. **Rejected alternative.** "Move `Mouse` Generators wholesale into LyrebirdUI" breaks the API surface (`Mouse.X.Control()` would require an extra `import LyrebirdUI` for any user wanting mouse control), conflates rendering UI with input-source generators, and inverts the dependency direction — LyrebirdUI imports Lyrebird, not the other way around. **Files touched.** - New: `Sources/Lyrebird/Generators/UI/MouseInputBridge.swift` (~40 lines: protocol, no-op default, atomic registry). - Modified: `Sources/Lyrebird/Generators/UI/Mouse.swift` — drop `import AppKit`, drop `#if os(macOS)` guard around the public types (now cross-platform), read from `MouseInputBridge.current` instead of `MouseTracker.shared`. - Deleted: `Sources/Lyrebird/Generators/UI/MouseTracker.swift` (moves to LyrebirdUI). - New: `Sources/LyrebirdUI/MouseTracker.swift` (the prior file content, now conforming to `MouseInputBridge`, plus `installShared()` static). - Modified: `Tests/LyrebirdTests/MouseGeneratorTests.swift` — replace the `MouseTracker.shared._x.store(...)` writes with a synthetic `MouseInputBridge` test fixture that the test installs in `setUp`. **Verification.** - `grep -rn "import AppKit\|import UIKit" Sources/Lyrebird/` returns zero hits (excluding the `Lyrebird.docc/` markdown). - `swift test` — all 3688 tests pass on macOS; new `MouseInputBridge` tests added covering install/replace and the no-op default. - `lyrebird_review` clean. **Out of scope.** iOS touch-input bridge (would conform `UITouch`-driven input to the same `MouseInputBridge` protocol). Defer until iOS demand. ### Phase 152 — Pre-run engine reconfig + master gain / mute ✓ shipped `SynthesisEngine` exposed `sampleRate`, `numOutputChannels`, and `numInputChannels` as `let` storage — once an engine was constructed there was no way to retry with a different I/O layout without tearing it down and rebuilding. Mirror gap: no master output volume control or mute on the engine; every demo wired its own scaling somewhere downstream. Both surfaces now live on the engine and on `LyrebirdEngineStatusView`. **Engine side (`Sources/Lyrebird/Engine/SynthesisEngine.swift`).** The three config fields are promoted to `public private(set) var` and gated by three new setters: `setSampleRate(_:)`, `setNumOutputChannels(_:)`, `setNumInputChannels(_:)`. Each is non-RT, throws `SynthesisEngineConfigError.engineIsRunning` while `isRunning == true`, and `SynthesisEngineConfigError.invalidValue(...)` on bad input (non-finite, non-positive, negative, or sums that overflow `numAudioBuses`). All three short-circuit on a no-op write so identity assignments don't churn the bus-allocator free list. `setSampleRate` also recomputes the internal `_blockDurationNs` used for CPU-load reporting and documents the caveat that pre-built generators keep their original coefficients (callers must rebuild affected synths after a rate change). Master output level + mute are two new atomic-backed public properties: `masterGain: Double` (linear amplitude, `Atomic`-packed bit pattern mirroring the existing CPU-bits scheme; relaxed orderings sufficient because RT-thread reads and main-thread writes are both monotonic scalars; setter rejects non-finite values to keep NaN out of the audio path) and `isMuted: Bool` (`Atomic`). At the end of every `processBlock`, after the scope tap captures pre-master audio, the engine runs a per-channel linear ramp from `_previousAppliedGain` to the live target across each output channel via `vDSP_vrampmul` — so slider moves and mute toggles never click. The implementation reseeds a local `var start = from` on every channel iteration because `vDSP_vrampmul` mutates its `*start` argument in place (documented API contract); without the reseed channels beyond 0 would flat-multiply at the target instead of ramping. A `from == to` fast path falls through to `vDSP_vsmul` (and skips the multiply entirely at unity). `_previousAppliedGain` is reseeded from the live `masterGain` / `isMuted` in `start()` so a stop→start cycle that ended muted doesn't replay a stale ramp on the first block after restart. **BusAllocator (`Sources/Lyrebird/Buses/BusAllocator.swift`).** `hardwareAudioEnd` is now a `var` and is mutated by the new internal `_reconfigureHardwareReservation(numOutputChannels:numInputChannels:)`, which the channel-count setters call to invalidate audio bus allocations and remark the hardware reservation under the existing `NSLock`. Control buses are intentionally left alone — they have no hardware reservation and shouldn't be invalidated by audio-channel changes. `_release` was refactored to take `honoursHardwareReservation: Bool` and read the live `hardwareAudioEnd` inside its `_lock.withLock` block, closing the TOCTOU race that the previous "read field, then take lock" shape opened up as soon as the field became mutable. **View (`Sources/LyrebirdUI/LyrebirdEngineStatusView.swift`).** Two new sections appended below the existing CPU rows. "Configuration": a sample- rate `Picker` (44.1k / 48k / 88.2k / 96k / 176.4k / 192k, dynamically augmented to include the engine's current rate when it isn't in the standard list — so non-stock device rates render correctly), and two `Stepper`s for output (1…32) and input (0…32) channel counts. The entire configuration block is `.disabled(isRunning)` with `.opacity(0.5)` while the engine runs. "Output": a `Toggle("Mute")` bound to `engine.isMuted`, plus a volume row pairing a `Slider` in the dB range `-90…+12` with a `TextField` showing the same value formatted as `%+.1f`. Both controls share `masterGainDb` state — moving the slider rewrites the text field via `onChange`, hitting return in the text field (or losing focus) parses, clips to the slider range, and writes back. Bad input reverts to the current model value. The TextField parser strips only a leading `+` rather than `replacingOccurrences(of: "+", with: "")` (which would mangle scientific notation). Slider `onChange` updates the engine via `engine.masterGain = pow(10, db / 20)`. UI clips to the bounded range; the underlying `engine.masterGain` setter still accepts any finite scalar. View `init` now seeds every `@State` from the live engine values (`sampleRate`, channel counts, `isRunning`, `isMuted`, `masterGain` → formatted dB + text) so the first frame matches the engine instead of hard-coded defaults — without this the Picker would flash blank when the engine sample rate differed from the default, and the volume text would briefly read `+0.0` when the caller had set a gain before mounting. A new private `linearToDb` helper provides a finite floor at the slider's lower bound so `masterGain == 0` doesn't produce `-inf` in the text field. A `pushConfigToEngine` wrapper guards each config setter `.onChange` against running-while-mirroring drift, suppressing spurious red config-error chips that would otherwise surface when `refresh()` mirrors an engine field back into the view while the engine is running. **Tests** — two new `@Suite` files. `SynthesisEngineConfigTests.swift` covers the three setters' happy paths, running-engine-throws cases, non-positive / non-finite / overflow rejection, and a post-resize `busAllocator` assertion that the next allocation lands after the new hardware reservation. `MasterGainMuteTests.swift` covers the get/set round trips, the NaN/Inf rejection in the `masterGain` setter, the end-of-block ramp math (`expectedLast = to + (from - to) / n` matching the `vDSP_vrampmul` step semantics), the multi-channel ramp regression test that detected the `*start`-leakage bug on the first review pass (4 output channels — channel 0 was always correct, channels 1–3 were the canary), the mute-zeros-output check, the assertion that master gain does not touch input buses, and a stop→start regression confirming the `_previousAppliedGain` reseed in `start()` prevents stale-mute ramp replay. **Review cycle.** First `lyrebird_review` pass flagged four blocking findings: the `vDSP_vrampmul` `*start` channel-leakage bug, the unnecessary `controlFreeList` wipe in `_reconfigureHardwareReservation`, the unlocked `hardwareAudioEnd` read in `releaseAudioBus`, and a same-file two-`@Suite` testing-rule violation. All four addressed in a second pass before merge; the multi-channel ramp test was added as the canary for the vDSP bug. Second pass also picked up several quality items folded in before merge: NaN/Inf guards on both the `masterGain` setter and `setSampleRate`, no-op short-circuit on all three config setters, dynamic Picker option list, leading-`+`-only TextField parsing, `pushConfigToEngine` running guard, init-seeded view state, the `setSampleRate` synth-coefficient caveat doc. **Out of scope.** Automatic graph invalidation on sample-rate change (callers responsible for rebuilding synths). iOS-side device-rate negotiation parity with macOS. Any feedback shim that would push live hardware reports back into the engine's stored config — the engine remains the source of truth and the driver negotiates against it on each `start()`. **Files touched.** - Modified: `Sources/Lyrebird/Engine/SynthesisEngine.swift` (mutable config storage + setters, master gain / mute atomic state, `applyMasterGainRamp` RT helper, `_previousAppliedGain` reseed in `start()`). - New: `Sources/Lyrebird/Engine/SynthesisEngineConfigError.swift`. - Modified: `Sources/Lyrebird/Buses/BusAllocator.swift` (`_reconfigureHardwareReservation` internal; `_release` refactored to honour the reservation under-lock). - Modified: `Sources/LyrebirdUI/LyrebirdEngineStatusView.swift` (configuration + output sections; init-seeded state; dynamic Picker options; `commitMasterGainText`; `pushConfigToEngine`). - New: `Tests/LyrebirdTests/SynthesisEngineConfigTests.swift`. - New: `Tests/LyrebirdTests/MasterGainMuteTests.swift`. **Verification.** - New tests in both files all pass; impacted baseline suites (engine init state / bus allocation / lifecycle / process block / bus index convention / state listener / BusAllocator) all green. - `lyrebird_review` clean on the second pass (all blocking findings from pass 1 resolved). --- ### Phase 153 — LyrebirdEventList fire-time tracking + body-closure backref ✓ shipped `LyrebirdEventList` already captured a wall-clock `_startDate` on the first fired event and appended every subsequent fire as a `LyrebirdTimelineEntry` with an offset relative to that origin. Two gaps remained: callers had no ergonomic way to query "when did event index N fire?" (had to walk the `timeline` array themselves), and a `LyrebirdProcess` body or `onRelease` closure had no handle on the owning `LyrebirdEventList` — the existing `ctx.eventListNow: Double?` exposed the elapsed wall-clock anchor but nothing that lets the closure cross-reference earlier fire times. Both gaps are now closed. **Query API (`Sources/Lyrebird/Process/LyrebirdEventList.swift`).** Two new public methods on `LyrebirdEventList`: - `func fireTimes(forEvent eventIndex: Int) -> [Double]` — every offset at which the index fired. Empty array if the event has not yet fired or `eventIndex` is out of range (no trap). - `func firstFireTime(forEvent eventIndex: Int) -> Double?` — first offset, or `nil`. Both filter / scan `_timeline` rather than maintaining a parallel index — acceptable because timelines are short (one entry per `play(eventIndex:)` call during a performance) and the call sites are not RT. **Thread-safety.** Body / `onRelease` closures run as `@Sendable async` tasks on background threads. `_timeline` is now protected by a new `private let _timelineLock = NSLock()`. Five mutation sites (`_appendTimelineEntry`, `clearTimeline`, `setTimeline`, `loadTimeline`, the `_timeline.removeAll()` inside `reset`) acquire the lock, as do the two cross-thread readers. The bare `var timeline` public getter and the internal `saveTimeline` / `playTimeline` paths remain unsynchronized; they are documented main-thread-only and run on the same thread as the mutators. The `@unchecked Sendable` rationale comment at the top of the class was rewritten to spell out the new locking protocol and call out which read paths are main-only. **Context backref (`LyrebirdProcess.swift` + `LyrebirdProcessContext.swift`).** Mirrors the existing wiring for `_eventListStartProvider` / `_eventListStartSampleTimeProvider`: - `LyrebirdProcess` gains `internal weak var _owningEventList: LyrebirdEventList?`. Set in `LyrebirdEventList.init`'s ownership-claim loop alongside the start providers; weak so the process does not retain the list (the list already retains the process via `_allProcesses`). - `LyrebirdProcessContext` gains a matching `internal weak var _owningEventList: LyrebirdEventList?` plus a public computed `var eventList: LyrebirdEventList? { _owningEventList }`. Populated by `LyrebirdProcess._play` next to the existing `context._eventListStart = _eventListStartProvider?()` line. A body closure can now write `ctx.eventList?.firstFireTime(forEvent: 0)` to learn the absolute offset of an earlier event, or `ctx.eventList?.fireTimes(forEvent: 2)` to enumerate every fire of a specific index. **Tests** (`Tests/LyrebirdTests/Process/LyrebirdEventListTests.swift`). Six new `@Test`s appended to the existing `LyrebirdEventList` suite: - `testFireTimesEmptyBeforePlay` — empty arrays / nil before any `next()`. - `testFirstFireTimeBasic` — three `next()` calls → `firstFireTime(0)` is exactly `0.0`, indices 1 and 2 strictly monotone-positive. - `testFireTimesOutOfRange` — out-of-range and negative indices return empty / nil without trapping. - `testFireTimesMultipleFires` — two `play(eventIndex: 1)` calls produce two distinct entries in `fireTimes(forEvent: 1)`. - `testContextOwningEventList` — owned process body sees `ctx.eventList === list`; standalone process body sees `ctx.eventList == nil`. - `testContextEventListFireTimesFromBody` — body of process started by event 1 reads `ctx.eventList?.firstFireTime(forEvent: 0) == 0.0` after a 10 ms sleep (synchronous append inside `play(eventIndex:)` runs before the background task wakes; ample margin). **Review cycle.** First `lyrebird_review` pass flagged three blocking findings: the stale `@unchecked Sendable` rationale comment claiming `_timeline` was main-thread only (contradicting the new cross-thread accessors), and two `t1!` / `t2!` force-unwraps inside `#expect(...)` in the new monotonic-offsets test (CLAUDE.md prohibits force-unwraps everywhere, including test code). All three were fixed: comment rewritten to describe the new locking protocol, force-unwraps replaced with `try #require(...)` bindings, public `var timeline` accessor got a "main-thread only" `- Important:` doc note. Second pass clean. **Files touched.** - Modified: `Sources/Lyrebird/Process/LyrebirdEventList.swift` (new lock + five locked mutation sites + two query methods + `_owningEventList` wired in ownership loop + `Sendable` rationale rewrite + `timeline` doc note). - Modified: `Sources/Lyrebird/Process/LyrebirdProcess.swift` (`_owningEventList` weak slot + plumbed into context in `_play`). - Modified: `Sources/Lyrebird/Process/LyrebirdProcessContext.swift` (`_owningEventList` slot + public `eventList` accessor). - Modified: `Tests/LyrebirdTests/Process/LyrebirdEventListTests.swift` (six new tests). **Verification.** - `swift test --filter "LyrebirdEventList|LyrebirdProcess"` — 81 tests pass (75 baseline + 6 new). - `swift build` clean. - `lyrebird_review` clean on the second pass. --- ### Phase 154 — Explicit type annotations on every inferred binding ✓ shipped Bulk sweep: every inferred `let` / `var` binding in `Sources/` (351 files, 6177 sites) and `Tests/` (223 files, 14249 sites) now carries an explicit `: Type` annotation. Motivation: Xcode's expression type-checker is markedly slower on long generic-heavy synth-graph expressions when intermediate locals are inferred; annotating the binding short-circuits a large slice of that work. Readability win for human readers too — every `let x = computation()` now reads `let x: ConcreteType = computation()` so the reader doesn't need to chase the inference graph. **Tooling.** New developer tool at `Tools/AnnotateBindings/annotate_bindings.py` (Python stdlib only, ~450 lines). Drives `/usr/bin/sourcekit-lsp` as a subprocess over LSP JSON-RPC: for each `.swift` file in the requested roots it sends `textDocument/didOpen` and requests `textDocument/inlayHint` for the full file range. SourceKit returns the inferred `: Type` strings as `InlayHint` objects with embedded `textEdits` that already specify the exact insertion. The tool applies the type-kind hints (`label` begins with `":"`) and skips parameter-name hints. Re-running the tool is idempotent: every annotated binding now ends in `:` which fails the line-suffix guard, so the second pass produces no edits. **Strict positional guard.** SourceKit emits inlay hints for many positions where Swift would not accept an inline `: T` annotation (closure-header parameters, capture lists, pattern destructures, `catch`/`case` binding patterns, etc.). The tool filters via a right-anchored regex match on `line[:col]`: ``` (?:^|[^A-Za-z_0-9])(let|var|for)\s+([A-Za-z_]\w*)$ ``` Combined with a pattern-context rejection (`\b(case|catch)\b` anywhere left of the matched binding keyword) and an unmatched-paren count (rules out tuple destructures `let (a, b) = …`), this rejects all of: - closure-header params `... { ptr in` - capture lists `... { [weak self] in` - tuple destructure `let (a, b) = ...` - compound bindings `let x = 5, y` - argument labels `foo(arg` - catch patterns `} catch let err as Foo` - case patterns `case let .foo(x)` while accepting `let x`, `var y`, `for i`, and `if let x` / `guard let x` shorthand. Each rule was added in response to a real build failure during sweep iteration (closure-param hints broke 16 files; capture-list hints broke 1 file; `catch let err` broke `LiveSession.swift`). **Edge cases hand-fixed.** - `Sources/LyrebirdUI/LiveCompile/LyrebirdScratchView.swift` — SourceKit inferred `let engineRefresh = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()` as `Publishers.Autoconnect`, but the file imports only `SwiftUI` not `Combine`. Reverted that single binding back to inferred form. The tool doesn't currently inspect the file's import set; future enhancement would either parse imports or shell out to a build to validate each batch. - Stale untracked `Sources/Lyrebird/Generators/UI/MouseTracker.swift` pre-existed in this checkout even though Phase 151 had deleted that exact path (canonical lives at `Sources/LyrebirdUI/MouseTracker.swift`). The sweep modified it, breaking its capture-list syntax. Removed manually after confirming via `git log` that Phase 151 commit `12c20be` was the canonical deletion. **Review cycle.** Two-agent `/lyrebird_review` pass (lyrebird_review_agent + caveman line sweep) clean — no blocking findings. Spot-checks across Engine, Buses, GeneratorCore, BusIO generators, filters, oscillators, spectral chain confirmed no RT-safety regressions, no accidental allocations (vDSP / Accelerate paths intact), no existential boxing changes. Non-blocking nits flagged on the tool file (`Tools/AnnotateBindings/annotate_bindings.py`): hardcoded `/usr/bin/sourcekit-lsp` path with no `xcrun --find` fallback, hardcoded `REPO_ROOT` default (mitigated by `--repo-root` CLI arg), regex doesn't strip `//` comments before counting parens, file URI built without percent-encoding. All false-negatives (skip legitimate annotations) not false-positives (would never apply a bad one). Tool is developer-only infrastructure — these nits left for a future cleanup pass if needed. **Verification.** - `swift build` — clean. - `swift test --no-parallel` — 3725 tests in 422 suites pass. - Targeted `swift test --filter "LyrebirdEventList|LyrebirdProcess|OscSin|OscTable|MulAdd|RBJ|Compressor"` — 252 tests pass after the Tests/ sweep. - Idempotency: re-running `python3 Tools/AnnotateBindings/annotate_bindings.py Sources/ Tests/` produces zero new edits. --- ### Phase 159 — `LyrebirdMessage` + `LyrebirdMessageView` ✓ shipped User-visible diagnostic channel kept strictly off the RT thread. Library authors call `LyrebirdMessageCenter.shared.{info,warning,error}()` to surface curated text to end users via `LyrebirdMessageView` (full) or `LyrebirdMessageBanner` (compact embed). `print()` is untouched and remains the separate developer-console stream. **Model (new `Sources/Lyrebird/Diagnostics/` subfolder).** - `LyrebirdMessageTier.swift` — `Sendable, Equatable, CaseIterable` enum: `.info` / `.warning` / `.error`. - `LyrebirdMessage.swift` — `Identifiable, Sendable, Equatable` struct carrying `id: UUID`, `timestamp: Date`, `tier`, `text`, optional `source`. - `LyrebirdMessageCenter.swift` — `@Observable @MainActor public final class` with a process-wide `shared` singleton, bounded FIFO ring (`defaultCapacity = 200`, mutable `capacity` prunes immediately when lowered), and `post(_:_:source:)` / `info` / `warning` / `error` / `clear` API. Non-main callers hop via `Task { @MainActor in ... }`. **Views (Sources/LyrebirdUI/).** - `LyrebirdMessageView` — scrollable list. Header: title + total count + Clear button. Filter row: three tier chips (INFO/WARN/ERR) with per-tier counts; tap a chip to toggle inclusion. Body: `LazyVStack` of message rows (timestamp `HH:mm:ss.SSS`, tier-coloured capsule, optional `source` caption, selectable text). Auto-scroll to newest via `ScrollViewReader`. Empty-state copy distinguishes "no messages" from "no messages match filter". Two inits: `@MainActor init()` defaulting to `.shared` and `init(center:)` for explicit binding. - `LyrebirdMessageBanner` — compact 3-line ticker for embedding. Each row: tier-coloured capsule + truncated message text. Tap invokes optional `onOpenFull` callback. Empty state shows a tray glyph. - `LyrebirdMessageHelpers.swift` — `LyrebirdMessageTierStyle` enum holding the tier→Color and tier→short-label maps (info=blue, warning=orange, error=red). Module-internal, shared between view and banner per the `*Helpers.swift` convention. - `LyrebirdMessageView.presentInWindow(...)` macOS helper opens a standalone `LyrebirdWindow` (matches `LyrebirdEventListView`). **Integration.** `LyrebirdEngineStatusView` gains a collapsible "Messages" section after the CPU metrics divider, before the configuration section. Collapsed state shows the banner with a tap-to-expand action; expanded state inlines the full view at `minHeight: 160, maxHeight: 260`. macOS additionally surfaces an "Open Window" button that calls `LyrebirdMessageView.presentInWindow()`; the view holds the `LyrebirdWindow` reference so subsequent clicks close-and-reopen. **Subfolder addition.** New `Sources/Lyrebird/Diagnostics/` subfolder for language-side, main-actor-only diagnostic types. Added to CLAUDE.md's subfolder list (alphabetically after `Capture/`). **Tests.** Eight new `@MainActor` tests in `Tests/LyrebirdTests/Diagnostics/LyrebirdMessageCenterTests.swift`: post stores tier/text/source correctly; convenience methods route to the right tier; ring prunes oldest when over capacity; reducing `capacity` prunes immediately; clear empties the ring; identity-uniqueness and non-future timestamp; capacity 1 keeps only newest; `allCases` ordering. **Review cycle.** Two passes. Pass 1 caught two blocking issues: (a) two public types in one file (`LyrebirdMessageTier` + `LyrebirdMessage` were originally in the same `.swift`) — split into separate files; (b) the `LyrebirdMessageTierStyle` enum was used cross-file from inside `LyrebirdMessageView.swift` instead of a `*Helpers.swift` — moved to `LyrebirdMessageHelpers.swift`. Also added a missing rationale line for the new `Diagnostics/` subfolder per CLAUDE.md's subfolder rule. Pass 2 clean. **Verification.** - `swift build` — clean. - `swift test --no-parallel` — 3827 tests in 432 suites pass (3819 → 3827, +8 from the new center tests). - All new files carry explicit `: Type` annotations on every `let` / `var`. - No RT-thread access to `LyrebirdMessageCenter` anywhere in `Sources/Lyrebird/`. --- ### Phase 160 — Node tree visualization ✓ shipped Main-thread mirror of the engine's node tree plus a SwiftUI view that renders it. Removes the only obstacle to displaying live tree state: the RT thread mutates `Group.head` / `PreparedNode.next` when it drains the pending event queue, so a direct main-thread walk during playback is a data race. **Model (`Sources/Lyrebird/NodeTree/`).** - `NodeTreeSnapshot.swift` — immutable value-type tree. `Node` carries `ObjectIdentifier id`, `Kind = .synth(className:) / .group / .parallelGroup`, `displayName`, and `children: [Node]` in head→tail order. - `NodeTreeMirror.swift` — `@Observable public final class` with an `@ObservationIgnored` internal mutable `MutableNode` tree keyed by `ObjectIdentifier`. Updates `snapshot` after every mutation. Not `@MainActor` only because the engine that hooks into it is not `@MainActor`; all mutators are documented main-thread. **Engine wiring (`Sources/Lyrebird/Engine/SynthesisEngine.swift`).** New `public let nodeTreeMirror`, seeded after `rootGroup` / `mainGroup` install. Hooks added to `schedule(_:at:)`, `schedule(_:after:)`, `add(_:position:)`, `remove(_:at:)`. Mirror updates fire **only when `pendingQueue.enqueue` returns `true`** — so mirror drift can't outrun the RT thread when the queue overflows. **Group / ParallelGroup.** - `Group.free(engine:)` records the mirror update after the enqueue. - `Group.release(engine:)`'s background `DispatchSourceTimer` previously called `self.free(engine:)` directly from `.global(qos: .utility)`; with the mirror hook in place this would race the main-thread reader. The timer handler now hops to `DispatchQueue.main.async` via a new `private struct GroupFreeArgs: @unchecked Sendable` carrier — same pattern as `LyrebirdRoutineContext.Args`. - `ParallelGroup.head` promoted `private → internal` so the mirror can walk the main-thread-populated children when the parallel group is added to the engine. Linked-list writes are still main-thread only (only `add(_:)` writes, called pre-`engine.add`). **View (`Sources/LyrebirdUI/LyrebirdNodeTreeView.swift`).** Recursive disclosure rows, head→tail reading order (top-to-bottom matches RT signal flow), depth-indented. Per-row layout: kind glyph (chevron for groups, dot for synths), `displayName` (bold monospaced), optional child-count badge for groups, 4-hex identity suffix derived from `ObjectIdentifier.hashValue & mask` (stable per object; no parsing of the stdlib `String(describing:)` internal format). Header has Expand All / Collapse All. macOS `presentInWindow(...)` opens a detached `LyrebirdWindow`. **Integration.** `LyrebirdEngineStatusView` gains a collapsible "Node Tree" section between the CPU metrics divider and the Messages section. macOS adds an "Open Window" button alongside the chevron (close-and- reopen toggle, matching the Messages window pattern). **Tests (`Tests/LyrebirdTests/NodeTree/NodeTreeMirrorTests.swift`).** Twelve `@Suite("NodeTreeMirror")` tests covering: initial snapshot shape; `engine.add` lands at mainGroup head; `add(_:position: .tail(of:))` appends; `engine.remove` drops the synth; `.before(_:)` / `.after(_:)` sibling insertion; nested group + child; child-remove preserves the parent group; `Group.free` drops the subtree; `ParallelGroup` add walks head→tail; `displayName` matches the runtime class; `.before(_:)` falls back to mainGroup head when the anchor is unknown. **Review cycle.** Three passes. Pass 1 caught a thread-safety violation (`Group.release` timer mutating mirror on the utility queue) plus multi-param init / magic-number `6` / dead-code `timestamp` field / redundant `@Bindable` on a read-only Observable. Pass 2 caught inaccurate "before"-vs-"after" doc wording in `SynthesisEngine.swift` and `NodeTreeMirror.swift` (the implementation updates after enqueue, not before) plus a brittle `String(describing: ObjectIdentifier)` parse in `_identityShort` — replaced with `hashValue & mask` formatting. Pass 3 clean. **Verification.** - `swift build` — clean. - `swift test --no-parallel` — 3839 tests in 433 suites pass (3827 → 3839, +12 from the new mirror tests). - All new files carry explicit `: Type` annotations on every binding. - No RT-thread access to `NodeTreeMirror` (mirror methods are reachable only from `engine.add` / `remove` / `schedule` / `Group.free` — all language-side main-thread paths). --- ### Phase 161 — Auto-free synths on envelope done ✓ shipped Surfaces SuperCollider-style "envelope done → node freed" semantics in Lyrebird. Previously, an `EnvelopeGen` with `doneAction == .freeNode` only flipped a flag; the owning `Synthesizer` lingered in the tree until some external code called `engine.remove`. Users coming from SC hit this as a sharp edge — synths spawned inside a `LyrebirdProcess` body accumulated in the tree, audible only as a load builds. Phase 161 makes opt-in auto-removal a first-class part of `SynthesizerBase`. **Protocol.** New `Sources/Lyrebird/Envelopes/DoneActionWatchable.swift`: ```swift public protocol DoneActionWatchable: AnyObject { var needsFree: Bool { get } } ``` `EnvelopeGen.Audio` and `EnvelopeGen.Control` conform out of the box. Other lifecycle generators (`PlayBuffer`, `DiskIn`, etc.) can opt in later by adopting the protocol and forwarding to their atomic flag. **SynthesizerBase API.** ```swift public final func autoFreeOnDone(_ probe: any DoneActionWatchable) ``` Called from inside `build()` with an `EnvelopeGen` whose `doneAction == .freeNode`. The synth stores the probe in an `internal _autoFreeProbe`; the engine inspects this on add and registers the synth in its auto-free watcher. **Engine watcher.** - `_autoFreeEntries: [_AutoFreeEntry]` — weak `synth`, weak `probe`. - Single shared `DispatchSourceTimer` on the `lyrebird.autofree` utility queue, 10 ms cadence (matches `LyrebirdProcess`). - `engine.add` / `schedule` / `remove` hooks call `_registerAutoFreeIfAny` / `_unregisterAutoFreeIfAny`. - On each tick: snapshot under lock, read atomic `needsFree` outside the lock, then re-acquire the lock to remove the fired-or-dead entries from the registry **before** dispatching `engine.remove` on main — closes a double-fire race that would otherwise corrupt the node-tree mirror via duplicate `didRemove` calls. - Dead-entry predicate `synth == nil || probe == nil` so an orphaned slot cannot pin the timer. - `engine.stop()` cancels the timer, clears the registry, and barriers via `_autoFreeWorker.sync {}`. Late-arriving main.async blocks guard `args.engine.isRunning` so any tick that escapes the barrier exits cleanly without enqueuing a stranded `.remove` event into a `pendingQueue` the now-idle RT thread will never drain. `_AutoFreeRemovalArgs: @unchecked Sendable` follows the existing `ContextAddArgs` / `GroupFreeArgs` cross-thread-carrier idiom. **Usage.** ```swift final class WindowedNote: SynthesizerBase { override func build() { let env: EnvelopeGen.Control = EnvelopeGen.Control( envelope: myEnv, timeScale: 8.0, doneAction: .freeNode ) autoFreeOnDone(env) output(bus: 0, source: someSignal * env) } } // Spawn a note inside a process body — auto-removed when the envelope // completes, no explicit engine.remove needed. ctx.add(WindowedNote()) ``` **Tests.** Five `@Suite("SynthesizerBase autoFreeOnDone")` tests in `Tests/LyrebirdTests/Envelopes/AutoFreeOnDoneTests.swift`: - `EnvelopeGen.Control + .freeNode` auto-removes. - `EnvelopeGen.Audio + .freeNode` auto-removes. - Manual `engine.remove` before the envelope completes unregisters cleanly (no double-remove). - Multiple staggered synths each auto-free independently. - Plain synth without `autoFreeOnDone(_:)` stays in the tree. The tests use a local `TestBlockDriver` (same pattern as `LyrebirdEventListTests`) to advance engine-time ~46× wall-time so envelope completion lands within the 200 ms async-sleep window. **Review cycle.** Three passes. Pass 1 caught the double-remove race (`_tickAutoFreeWatcher` dispatched without first dropping the fired entries — duplicate ticks would re-observe and corrupt the mirror), the orphaned-probe cleanup gap (predicate missed `probe == nil`), and an ARC leak via late-firing `DispatchQueue.main.async` after `stop()`. Pass 2 caught a narrow remaining window where a main.async block could land post-stop and enqueue into a `pendingQueue` whose RT-side drain was gone — fixed with an `isRunning` guard inside the closure. Pass 3 clean. **Verification.** - `swift build` — clean. - `swift test --no-parallel` — 3855 tests in 434 suites pass (3850 → 3855, +5 from `AutoFreeOnDoneTests`). - All new files carry explicit `: Type` annotations on every binding. - No RT-thread access to the watcher; the only RT touch is the atomic `needsFree` store inside `EnvelopeGen._Base` (pre-existing, unmodified). --- ### Phase 162 — `Envelope.releaseNode` aligned with SuperCollider's level-index convention ✓ shipped User-reported bug from MyPiece: `Envelope([0,1,0], [2,2], releaseNode: 1)` was holding at the silent post-decay level (`levels[2] = 0`) instead of the audible peak (`levels[1] = 1.0`). Pre-Phase-162 Lyrebird semantics treated `releaseNode` as a SEGMENT INDEX with hold value `levels[releaseNode + 1]`, which disagreed with SuperCollider's `Env` convention (where `releaseNode` is a LEVEL INDEX and the hold value is `levels[releaseNode]`). The user's mental model matched SC. **Semantic change.** `Envelope.releaseNode` is now a LEVEL INDEX. Valid range `[1, levels.count - 1]`. Hold value is `levels[releaseNode]`. The public type is unchanged (`Int?`). **Implementation.** `Sources/Lyrebird/Envelopes/EnvelopePacket.swift` converts the public level-index value to an internal segment-index (`releaseNode - 1`) at packet construction so the RT-side `EnvelopeGen` arithmetic stays untouched. `LyrebirdProcess.release(reltime:)` reads `_envelope.levels[releaseNodeIdx]` (was `+ 1`). `loopNode` (still a segment index) cross-validation is now `loopNode < releaseNode - 1`. **Sweep.** 45 in-tree `releaseNode: N` literals bumped to `N + 1` (`Sources/`, `Tests/`, `docs/`, `Demos/`, `LyrebirdBenchmark`) so existing hold-level behavior is preserved. Doc examples with stale comments (`ProcessSystem.md`, `Generators/Envelopes.md`, `ParameterInputs.md`) revised end-to-end: comments now spell out the level-index convention, and three examples whose `releaseNode` value was incorrect under both old and new semantics (silent hold despite a "holds at 0.5"-style comment) were corrected. **View helper.** `LyrebirdEnvelopeView._regionForSegment` was already treating its `releaseNode` parameter as a release-region start boundary equivalent to a LEVEL INDEX — so no view code change needed. The view-tests file uses raw integers that don't flow through `Envelope.init` and was left untouched. **Tests.** New 4-test `Tests/LyrebirdTests/Process/LyrebirdProcessReleaseNodeHoldTest.swift`: level-index identity (`env.levels[env.releaseNode!] == 1.0` for the exact MyPiece envelope), peak-hold under gate, out-of-range clamps to nil, releaseNode at final level. `StdlibGeneratorTests.swift` assertions `env.releaseNode == N` updated to match the bumped public value. **Review cycle.** Two passes. Pass 1 caught 11 stale comments and a force-unwrap in the new test; pass 2 caught 4 remaining stale comments. Pass 3 clean. **Verification.** - `swift build` — clean. - `swift test --no-parallel` — 3862 tests in 436 suites; one pre-existing intermittent flake (Crackle/Noise `floatValueInValidRange` under concurrent retain-count pressure) unchanged. - All four `LyrebirdProcessReleaseNodeHold` tests deterministic. --- ### Phase 163 — `midiToRatio` / `ratioToMidi` SC-style musical-math additions ✓ shipped Surfaces the existing `semitonesToRatio` / `ratioToSemitones` under SuperCollider-flavored names that mirror the `midiToHz` / `hzToMidi` pair, plus dot-syntax on `Double` and `Int` for ergonomic call sites. Driven by the MyPiece pitch-shift use case where `PitchShift.Audio` takes a frequency ratio but the composer reasons musically in semitones — `7.midiToRatio` reads cleaner than `semitonesToRatio(7.0)`. **Sources/Lyrebird/Math/LyrebirdMusicMath.swift.** - Free functions `midiToRatio(_:Double)`, `midiToRatio(_:Int)`, and `ratioToMidi(_:Double)` — `@inline(__always)` thunks delegating to `semitonesToRatio` / `ratioToSemitones`. Pure math, RT-safe like the existing siblings. - Array overloads `midiToRatio(_:[Double])` and `ratioToMidi(_:[Double])`. - `extension Double` — computed vars `midiToRatio` and `ratioToMidi` using `Lyrebird.midiToRatio(self)` / `Lyrebird.ratioToMidi(self)` module qualifier to disambiguate from the property name itself. - `extension Int` — computed var `midiToRatio` (no `ratioToMidi` since ratios aren't typically `Int`). - `Collection where Element == Double` — `midiToRatio()` and `ratioToMidi()` methods paired with the existing `semitonesToRatio()` collection method. - `Collection where Element == Int` — `midiToRatio()` method paired with the existing `midiToHz()` collection method. **Usage.** ```swift midiToRatio(12) // 2.0 midiToRatio(-12) // 0.5 ratioToMidi(2.0) // 12.0 // Dot syntax (SC-style): 12.midiToRatio // 2.0 (-12).midiToRatio // 0.5 2.0.ratioToMidi // 12.0 // In context: PitchShift.Audio(input: src, pitchRatio: 7.midiToRatio) // perfect fifth up // Collection forms: [0, 12, -12].midiToRatio() // [1.0, 2.0, 0.5] (Int) [0.0, 12.0, -12.0].midiToRatio() // [1.0, 2.0, 0.5] (Double) [1.0, 2.0, 0.5].ratioToMidi() // [0.0, 12.0, -12.0] ``` **Tests.** 14 new `@Test` cases in `Tests/LyrebirdTests/MusicMathTests.swift` covering: octave / fifth / unity checks on both free functions and dot syntax (Double + Int + negative + zero); array overloads (both directions); round-trip identity; equivalence with the existing `semitonesToRatio` (the synonym contract); non-positive ratio edge case (`0` → `-.infinity`, negative → `NaN`, inherited from `log2`); collection-method forms for `[Double]` and `[Int]`. **Docs.** `docs/stdlib/generators.md` and `Sources/Lyrebird/Lyrebird.docc/Generators/MusicalMath.md` both gain a paragraph explaining the SC-flavored synonyms, the dot-syntax ergonomics, and a `PitchShift` call-site example. **Review cycle.** Two passes. Pass 1 flagged the absent Collection-method symmetry (`semitonesToRatio()` already existed on `Collection`; the new synonyms must too) and the missing non-positive-ratio edge test — both non-blocking but addressed in the same diff. Pass 2 clean. **Verification.** - `swift build` — clean. - `swift test --no-parallel` — 3876 tests in 436 suites pass (3862 → 3876, +14 from the new MusicMath tests). - No RT-thread violations; all new code is pure floating-point math with `@inline(__always)` thunks. --- ### Phase 170 — `GeneratorInputProvider` as a first-class Generator input Pushes `GeneratorInputProvider` (landed pre-170 on `main`, commit `33d77a8`) down into Generator inits so callers can pass a provider directly anywhere that accepts `any ValidGeneratorInput`, with no `.make()` call at the synth/Generator boundary. After 170: `azimuth: providerField`, `freq: GeneratorInputProvider { LFNoise.Control(freq: 1) }`, `mul: 0.5` all work uniformly — the provider unwraps once at Generator init time and behaves identically to a directly-passed `any ValidGeneratorInput` from then on. **Motivation.** Today `GeneratorInputProvider` is consumed inside synth `build()` via `_field.make()`. That moves the call out of the `LyrebirdProcessFactory` body (the win that shipped on `main`), but synth authors still write `.make()` once per provider field. Phase 170 finishes the job: the provider becomes a transparent input source that any Generator init can accept, and `.make()` disappears from synth code entirely. **Design.** Extend `ValidGeneratorInput` with one new requirement: ```swift public protocol ValidGeneratorInput { // ...existing requirements... /// Resolve to a concrete signal source for storage at Generator init time. /// Default returns `self`. `GeneratorInputProvider` overrides to call `make()`. /// Called once per Generator init, non-RT. func _resolvedInput() -> any ValidGeneratorInput } extension ValidGeneratorInput { public func _resolvedInput() -> any ValidGeneratorInput { self } } extension GeneratorInputProvider: ValidGeneratorInput { public func _resolvedInput() -> any ValidGeneratorInput { make() } // trap impls for calculatedSamples / floatValue / intValue / needsInterpolation // / sampleBlock — these must never run; provider always resolves before storage } ``` Every Generator init that takes `any ValidGeneratorInput` calls `_resolvedInput()` exactly once on each input parameter before storing or type-classifying: ```swift public init(input: any ValidGeneratorInput, freq: any ValidGeneratorInput, mul: any ValidGeneratorInput = 1.0, add: any ValidGeneratorInput = 0.0) { let resolvedInput: any ValidGeneratorInput = input._resolvedInput() let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput() _input = resolvedInput _freq = resolvedFreq _inputIsGenerator = resolvedInput is any Generator _freqIsGenerator = resolvedFreq is any Generator _mulAdd = MulAddSpec(mul: mul, add: add) // mul/add resolved INSIDE MulAddSpec — do NOT pre-resolve super.init() } ``` Provider's `calculatedSamples` / `floatValue` / etc. impls trap with a `StaticString` `preconditionFailure` — these are unreachable in correct code because every Generator resolves before storing. The traps catch authoring bugs (Generator forgets to resolve a new input slot) at the first audio block rather than producing silent wrong audio. **Scope.** All built-in Generators in `Sources/Lyrebird/Generators/` that accept `any ValidGeneratorInput` in their init. Audit list (regex `init.*any ValidGeneratorInput`): - Oscillators: `OscSin`, `OscSaw`, `OscSquare`, `OscTriangle`, `OscDutyCycle`, `OscTable`, `OscBandLimited*`, `LF*`, `Impulse`, `Phasor`, `Blip`, `Pulse`, `Saw`, etc. - Filters: `LPF`, `HPF`, `BPF`, `Notch`, `AllPass`, `Resonz`, `MoogLadder`, `SVF*`, `Comb*`, `OnePole`, `OneZero`, `Integrator`, `Differentiator`, etc. - Envelopes: `EnvelopeGen`, `Line`, `XLine`, `Lag`, `Lag2`, `Lag3`, `Decay`, `Decay2`. - Distortions / shapers: `Clip`, `Wrap`, `Fold`, `SoftClip`, `WaveShaper`, `Tanh`, etc. - Noise: `WhiteNoise`, `PinkNoise`, `BrownNoise`, `LFNoise*`, `LFCurveNoise`, `Dust`, `Dust2`, `Crackle`, all `NoiseBase` family. - Math: `BinaryOpGenerator` (`+`/`-`/`*`/`/` etc.), `UnaryOpGenerator`, `LinLin`, `LinExp`, `ExpLin`, `RangeMapper`, `UnipolarRangeMapper`, `MulAdd`, `Sum3`, `Sum4`. - Bus I/O: `In.Audio`, `In.Control`, `Out.Audio`, `Out.Control`, `InFeedback`, `Send`, `SendTrigger`, `XOut`, `ReplaceOut`. - Buffer I/O: `PlayBuf`, `RecordBuffer`, `BufRd`, `BufWr`, `Phasor` (buffer index variant), `DiskOut`, `DiskIn`, `TimeStretch`, `GranularBuf*`. - Spatial: `Pan2`, `Pan4`, `PanAz`, `PanXY`, `PanB`, `AmbiEncoder1`, `AmbiPanner*`, `AmbiRotate`, `AmbiDecoder*`, FOA effects. - Spectral: `FFT`, `IFFT`, `PV_*` family inside `SpectralChain.Audio` (the per-stage param inputs). - Trigger / control: `Trig`, `TrigDelay`, `Latch`, `Schmidt`, `Stepper`, `Sweep`, `Demand.Audio`, `Demand.Control`. - Capture: `RunningMin`, `RunningMax`, `RunningSum`, `Amplitude`, peak/RMS helpers, `Tartini`, `BeatTrack` slot params. - Oversampling: `HalfbandUpsampler`, `HalfbandDownsampler` (input slot). - Physical models: `BowedString`, `Flute`, `Clarinet`, `ScannedSynthesizer` parameter slots. Estimated affected init sites: ~150 across ~120 files. Mechanical change; suitable for a code-mod script. **Implementation steps.** 1. Add `_resolvedInput()` protocol requirement + default impl in `ValidGeneratorInput.swift`. 2. Conform `GeneratorInputProvider` to `ValidGeneratorInput` with trap impls for `calculatedSamples` / `floatValue` / `intValue` / `needsInterpolation` / `sampleBlock` and the override of `_resolvedInput()`. 3. Write a script (`Tools/ResolveInputs/resolve_inputs.py`) that, given a path, finds every `init(...)` parameter of type `any ValidGeneratorInput` and inserts `let resolvedX: any ValidGeneratorInput = x._resolvedInput()` at the top of the init body, replacing references. Should preserve existing helper-call patterns (`MulAddSpec(...)`, `lastGeneratorSampleOrFloat`, `is any Generator` classification). Dry-run + apply modes mirroring `Tools/AnnotateBindings/annotate_bindings.py`. 4. Audit + hand-fix call sites the script can't handle: shared helpers that already take `any ValidGeneratorInput` (`MulAddSpec.init`, `lastGeneratorSampleOrFloat`, `OscillatorBase`, `NoiseBase`) — resolve once in the helper boundary instead of every Generator init that uses them. 5. Add tests covering: - Provider passed to a representative oscillator (`OscSaw.Audio`): output samples match the non-provider control case. - Provider passed to a filter freq slot: same. - Provider passed to a binary-op operand: same. - Trap fires when a provider is stored without resolution (use `@_spi` test hook that bypasses the resolve step, confirms trap). 6. Update `docs/protocols/writing-generators.md` §13 (shared helpers table) and §6 (init patterns) to document `_resolvedInput()` as mandatory and the trap behaviour. 7. Update `Sources/Lyrebird/Lyrebird.docc/GeneratorInputProvider.md` (new docc article) explaining the Process-factory → Generator pipeline end to end. 8. Refactor MyPiece `TimeStretchMoment.build()` to drop the `.make()` call — should compile unchanged otherwise (validates the trade-off works). **Trade-offs.** - **Pro:** uniform call-site syntax. Process factory → Synthesizer → Generator graph all share the same `any ValidGeneratorInput` surface. Provider becomes invisible after construction. No `.make()` anywhere in user-facing Generator-using code. - **Pro:** trap impls are an authoring-safety net — catch missing resolution at the first audio block. - **Con:** every existing Generator init touched. ~150 sites. Mostly mechanical via code-mod but reviewer load is non-trivial. - **Con:** protocol surface grows by one method. Any out-of-tree Generator (Extension SDK consumers) must add `_resolvedInput()` or rely on the default. Default is `return self`, so silent breakage is impossible — out-of-tree code keeps working but won't unwrap providers unless updated. Document in `docs/protocols/extension-sdk.md`. - **Con:** if any Generator init forgets to call `_resolvedInput()` on a new slot, the trap fires only when a provider is actually passed. Tests covering all init slots help, but coverage is the safety net. - **Risk:** literal-form ambiguity at call sites. `azimuth: 0.0` could in principle resolve to either `Double` (which conforms to `ValidGeneratorInput`) or to `GeneratorInputProvider` (via `ExpressibleByFloatLiteral`). Swift overload resolution prefers the more specific concrete type, so `Double` should win in the init's `any ValidGeneratorInput` parameter context. Smoke-test this on a few call sites before committing to the full sweep. - **Risk:** trap impls in provider — if a future codepath stores a provider in a place that bypasses Generator init (e.g. a `Closure` body holding a captured provider directly), the trap fires at audio time. Document the contract: provider is only passable to types whose init resolves it; never to bare evaluation contexts. **Out of scope for 170.** - Restructuring `MulAddSpec` or other internal helpers to themselves accept `GeneratorInputProvider` — they go through Generator init's resolution step, no work needed. - Provider variants that produce `any Generator` specifically (vs `any ValidGeneratorInput`) — current closure-returning-any-Generator already works because Generator conforms to `ValidGeneratorInput`. - Multi-channel provider semantics (one provider yielding N independent generators per make) — deferrable; current single-output is enough for the ambisonic and parameter-modulation use cases driving the work. **Validation.** - `swift test --no-parallel` green (no regression in 3955+ baseline). - New phase 170 tests pass (target 10+ new test cases). - MyPiece `TimeStretchMoment.build()` no longer references `.make()`; MyPiece `xcodebuild` succeeds. - One in-tree synth (pick `SCAnalogBass` or similar) refactored end-to-end to use providers for at least two of its slots, as worked-example. **Effort estimate.** 1–2 days for the code-mod + audit + tests; 0.5 day for documentation. Worth a phase branch (`phase-170-provider-as-generator-input`) to evaluate whether the call-site cleanup is worth the protocol-surface growth before merging. --- ## Phase 172 — EventList `ReplaceOut` master amp + caller-supplied `bus` + pre/post-master groups **Motivation.** A real-world MyPiece bug surfaced a long-standing architectural mistake in `LyrebirdEventList`. The EventList was internally allocating its own `_masterBus` and **silently overriding** every contained process's declared `procOut` to point at that bus (via `procOutOverride: masterBus` on `LyrebirdProcess._play`). `EventListMasterSynth` then read `_masterBus`, applied lag-smoothed master amp, and wrote to hardware out 0..N-1 (hardcoded `outBusIndex: 0`). This made the simple "process writes mono/stereo to hw out, master synth scales it" case work zero-config, but silently broke any process designed to feed a downstream effect chain — e.g. a `TimeStretchMomentProcess` whose `procOut` was set to an ambisonic routing bus expected to be read by a global `AmbisonicDecoder` placed `.after(engine.mainGroup)`. The decoder read silence; the master synth wrote raw, un-decoded B-format straight to hardware buses 0..3. **The fix — coupled refactor.** 1. **`LyrebirdEventList.init` takes a caller-supplied `bus: AudioBus`** (replacing `masterChannels: Int`). Channel count derives from `bus.channelCount`. No private bus is allocated by EventList; the caller owns the bus and is responsible for routing process `procOut` to it. Default value `AudioBus(index: 0, channelCount: 2)` preserves the simple-case ergonomics for callers that omit the parameter. 2. **`procOutOverride` removed from `LyrebirdProcess._play`.** All three EventList call sites (`playEvent`, `initProcess` first-event setup, `killProcess` teardown) drop the override; processes write to their own declared `procOut`. The parameter itself was pruned — dead code path that was the mechanism behind the original bug. 3. **New `ReplaceOut.Audio` / `ReplaceOut.Control` first-class overwrite bus write primitives.** Parallel to `Out.Audio` / `Out.Control` but **overwrite** the target bus instead of accumulating. New engine plumb: `SynthesisEngine.setAudioBus(_:offset:samples:count:)` writes via `vDSP_vdpsp` directly into the bus slice (no accumulate scratch); `SynthesisEngine.setControlBus(_:value:)` scalar overwrite; `ScratchBuses.replace(_:bus:offset:count:)` overwrites this child's scratch slot inside a `ParallelGroup`; `SynthGraph.setSamplesOnAudioBus` routes to the right backend. `SynthesizerBase.replaceOutput(bus:source:)` mirrors `output(bus:source:)`. ParallelGroup semantic: `ReplaceOut` only overwrites *this child's scratch contribution* — does **not** scrub other siblings' parallel writes nor any pre-existing engine-bus content; outside a ParallelGroup it scrubs the engine bus directly. 4. **`EventListMasterSynth` uses `ReplaceOut` for in-place amp scaling.** The master synth's `build()` is now `In.Audio(bus) * smoothAmp -> replaceOutput(bus)`. Multi-channel via `BinaryOpGenerator`'s channel-aware mono-broadcast (N-channel `inSig` × 1-channel `smoothAmp` = N-channel scaled). Replaces an interim "delta-add" trick (`bus += bus * (amp - 1) → bus *= amp` on top of additive `Out.Audio`) that was the first cut of the refactor — same per-sample cost (1 mul + 1 store vs 1 mul + 1 add) but `ReplaceOut` is a cleaner primitive and unblocks future patterns (bus-level limiters, master recorders, decoders that take ownership of hw-out buses). 5. **`preMasterGroup` and `postMasterGroup` inside `_masterGroup`.** Two caller-owned sub-groups give explicit insertion points for FX synths around the master amp. Evaluation order inside `_masterGroup` is strictly `_preMasterGroup → masterSynth → _postMasterGroup`. Public API: `eventList.preMasterGroup` / `eventList.postMasterGroup` (read-only `Group` accessors) + convenience `addPreMaster(_:)` / `addPostMaster(_:)` that append at `.tail(of:)` the respective group. Synths added via these helpers are children of `_masterGroup` and are freed when `_masterGroup.free()` runs in `_teardownMaster()` — their lifetime is bounded by the EventList session. After teardown the EventList re-allocates fresh empty pre/post groups so subsequent playback starts from a clean slate. **Use cases unblocked by the pre/post groups.** - **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. **Node tree shape post-refactor.** ``` mainGroup ├── group (event-list process group, head) │ └── processes write to their declared procOut └── _masterGroup ├── _preMasterGroup ← caller-FX (decoders / sends) ├── EventListMasterSynth ← In * amp → ReplaceOut, in place on `bus` └── _postMasterGroup ← caller-FX (limiters / mastering / tap recorders) [optional consumer placed `.after(engine.mainGroup)` reads scaled `bus`] ``` The five `_engine.add` calls in `_firstEventSetup` land in the engine's pending queue with equal `targetTime`. The queue uses a stable insertion sort, so FIFO order is preserved — re-ordering these `add` calls changes evaluation order, documented at the call site. **Test coverage.** 19 new tests across two new test files: `Tests/LyrebirdTests/ReplaceOutAudioGeneratorTests.swift` (9 tests covering overwrite, additive-then-replace sequencing, wipes-prior-additive, additive-after-replace, bus offset, channel clamping via AudioBus, multi- channel fan-out via GeneratorArray, pass-through return), `Tests/LyrebirdTests/ReplaceOutControlGeneratorTests.swift` (4 tests covering overwrite, wipes-prior-additive-control, correct-bus targeting), and `Tests/LyrebirdTests/Process/LyrebirdEventListPrePostGroupTests.swift` (6 tests covering group existence pre-play, `addPreMaster` / `addPostMaster` routing, evaluation order with amp=1.0, master scales pre but not post with amp=0.5, teardown frees children). Test-file split into Audio + Control suites addressed a blocking finding from `/lyrebird_review` requiring one `@Suite` per file. **Doc artefacts.** New `docs/engine/eventlist-routing-design.md` captures the original procOut-override bug, observed symptom, the in-place delta-add fix, the subsequent `ReplaceOut` refactor and trade-off table, the pre/post group design, lifecycle / ordering guarantees, and migration notes. `ProcessSystem.md` init-param table updated (`bus` row replaces `masterChannels`); new "Pre-master and post-master FX groups" section. **Caller migration.** Breaking change to `LyrebirdEventList.init`: replace `masterChannels: N` with `bus: AudioBus(index: 0, channelCount: N)` (or omit to take the default 2-channel hw-out bus). `LyrebirdEventList.buildFromFile` factory follows the same substitution. Each process should also have its `procOut` set to the bus passed to EventList (or to a routing bus consumed by a `addPreMaster`-registered decoder/effect). Tests + ProcessSystem doc + MyPiece caller all migrated. **Review.** One `/lyrebird_review` cycle: blocking finding (two `@Suite` structs in one file) fixed by splitting `ReplaceOutGeneratorTests.swift` into `ReplaceOutAudioGeneratorTests.swift` + `ReplaceOutControlGeneratorTests.swift`. Non-blocking nits addressed: `_lyrebirdAssertNotOnRTThread()` guard on `ReplaceOut.Audio.outputChannelCount` (build-time-only invariant trap); dropped duplicate `precondition(offset+count<=blockSize)` in `_computeSamples` (engine helpers assert internally); documented `ReplaceOut.Audio.floatValue` sink-only `0` return; documented `ReplaceOut.Control` channel-count divergence from `ReplaceOut.Audio` (matches `Out.Control` policy); explicit `rowCount` bind + `precondition(rowCount > 0)` in Control row pick; `ScratchBuses.replace` moves `dirty[bus] = true` inside `withUnsafeMutableBufferPointer` so empty buffer pointers don't mark dirty; stable-sort ordering comment in `_firstEventSetup`; pre/post group lifecycle comments in teardown re-alloc; `addPreMaster` / `addPostMaster` timing + lifetime guarantees in public API docstrings; design doc reordered to lead with `ReplaceOut` design and move delta-add to a "Historical Note" section; `testEvaluationOrder` warm-up block count documented. **Validation.** `swift build` clean. Touched-suite filter run (`swift test --no-parallel --filter "ReplaceOut|EventList|LyrebirdProcess"`): 116/116 pass deterministically. Full suite: 3979/3980 (one pre-existing `RTThreadIdentity.markingIsThreadLocalNotProcessGlobal` TLS-leak flake, or intermittent `LyrebirdBuffer` retain-race flake — different test each run, documented deferred in `MEMORY.md` → `project_parallel_test_crash.md`). MyPiece `xcodebuild` BUILD SUCCEEDED with `bus: dependencyContainer.ambisonicRoutingBus` in `QuartetEventManager.createEventList()`; the ambisonic-decode chain now hears all four quad-channel feeds with proper rotation, where pre-refactor it heard either 2 raw-B-format channels (default `masterChannels: 2`) or 3 raw-W/X/Y channels with silent Z (`masterChannels: engine.numOutputChannels`). --- ### Phase 173 — Input Conditioning Optimization (LookAheadLimiter + RecordBuffer + MixIn / SumChannels) Three coupled perf wins targeting the input-conditioning chain used at the head of a Lyrebird signal graph (mix N input buses → optional look-ahead limit → record into a buffer → route to output). Profiled via `MyPiece` on `/Users/josh/Desktop/MyPiece` — the `ConditionAndRecordInputs` and `MixAndRecordInputs` `SynthesizerBase` subclasses consume more CPU at session start than the per-input synth count justifies. Three independent optimizations, each ships on its own branch off `main` and merges before the next starts. **Why bundle as one phase.** All three changes live in the same conditioning chain and share verification fixtures (offline-render before/after RMS/peak parity + NRT CPU profile). Sequencing them under one phase number keeps the review surface coherent and the perf delta attributable. Each sub-branch still merges independently. #### Sub-phase 173a — LookAheadLimiter perf pass File: `Sources/Lyrebird/Generators/Dynamics/LookAheadLimiter.swift`. Current inner loop hits multiple non-power-of-2 `%` operations per sample, an extra ring buffer (`_peakRing`) whose only consumer is a triple-indirected deque lookup, and a per-sample `denormalsToZero` that the gain dynamics rarely need. Fixes: 1. **Modulo elimination.** Replace `_writePos % _ringSize`, `(_writePos - _lookAheadSamples + _ringSize) % _ringSize`, `(_dequeTail - 1) % _dequeCapacity`, `_deque[...] % _ringSize`, `_dequeHead % _dequeCapacity`, and `_dequeTail % _dequeCapacity` with explicit bounded indices (`_writeIdx`, `_readIdx`, `_dequeHeadIdx`, `_dequeTailIdx`, each maintained in `[0, capacity)`) and a branchless wrap-around (`idx += 1; if idx >= cap { idx -= cap }`). Several `idiv` instructions saved per sample. 2. **Drop `_peakRing` entirely.** Change deque payload from `Int` (absolute write-position) to a `(peakValue: Double, expireAtPos: Int)` pair. Front-pop compares `expireAtPos < _writePos - _lookAheadSamples`. Removes one `[Double]` of size `_lookAheadSamples + lyrebirdDefaultResultBufferSize + 1` from the working set and removes the nested `_peakRing[_deque[...] % _dequeCapacity] % _ringSize]` lookup. Deque becomes a small `[DequeEntry]` of size `_lookAheadSamples + 2`. Cache-line traffic measurably drops at large `lookAheadTime`. 3. **Precompute `1.0 - _releaseCoeff`** at init as `_attackComp: Double`. Used in the release-smoother branch; saves one subtract per sample. 4. **`denormalsToZero(_gain)` cadence.** Currently per sample. `_gain` lives in `[maxAmp/peak, 1.0]` — only enters denormal regime when `maxAmp` is near 0 and a sustained large input forces extreme reduction, which is itself pathological. Move to once-per-block. Verify with denormal-injection test (zero input + epsilon noise) that the once-per-block cadence is sufficient. 5. **`Double(sample)` and `Double(_delayRing[...] * _gain)` casts.** Both operands already `Double`. Drop the casts. 6. **`_lookAheadSamples == 0` specialization.** Currently mainline still does ring writes/reads + (now skipped) deque maintenance. Branch at the top of `_computeSamples`: when `_lookAheadSamples == 0`, run a peak-follower-only fast path (no ring, no deque, gain reduction tracks `|sample|` directly). Keeps zero-look-ahead use as a viable cheap mode. 7. **Empty-input fallback (lines 102–127).** The per-sample `while ... _peakRing[...] <= 0.0` deque drain loop fires once and clears, then the loop body is dead weight. Collapse: clear deque on entry, fill `_result[0]` with zeros (vDSP `vclr` over the channel), advance `_writePos` by `count`, return. **Tests.** - `Tests/LyrebirdTests/LookAheadLimiterTests.swift` — existing peak-ceiling + attack-instantaneity + release-smoothness + look-ahead-delay tests must pass byte-identical (offline NRT render) to a pre-173a checkpoint. - New denormal-cadence test: inject zero + tiny epsilon, verify once-per-block `denormalsToZero` keeps `_gain` flushed within tolerance over a long render (~10s). - New `_lookAheadSamples == 0` fast-path test: maxAmplitude bounce, peak follower behaviour matches the deque path at zero look-ahead. #### Sub-phase 173b — RecordBuffer.Audio perf pass File: `Sources/Lyrebird/Generators/BufferIO/RecordBuffer.swift`, `_computeSamples` of `RecordBuffer.Audio` (control-rate variant is one frame per block — not perf-critical, leave alone). Current hot loop has two passes (fill `_result`, then write buffer) and unconditional `buffer[writePos, ch]` read for the mix-with-existing math even when `preLevel == 0` (the default — overwrite mode, no read needed). Fixes: 1. **Fuse the two passes.** Combine the `_result[ch][i] = inputChannels[ch][i]` fill (lines 189–193) and the buffer write (206–223) into a single `for i in 0.. 0` per-sample gate.** Common case: gate stable across block. Check `runSamples[0]` and `runSamples[count - 1]`; when both > 0, branch to a no-gate inner loop. (Mid-block gate transitions still go through the per-sample path.) 8. **Mono specialization.** `channelCount == 1` dominates real workloads. The `for ch in 0..<1` and 2D `_result[ch][i]` / `inputChannels[ch][i]` indexing pay overhead. Specialize the mono branch — single pointer pair, scalar loop. **Tests.** - `Tests/LyrebirdTests/RecordBufAudioTests.swift` (or current equivalent) must pass byte-identical to a pre-173b checkpoint via offline NRT render for mono and stereo cases across all four `(rec, pre)` block-constant combinations. - New `pre == 0` fast-path test: render with `preLevel = 0.0`, verify output equals direct write (`buffer[writePos, ch] = rec * newSample`). - New mid-block `run` transition test: gate toggles inside a block, verify write-head advances only on positive samples. #### Sub-phase 173c — `MixIn` and `SumChannels` generators Two new built-in generators, one in `Sources/Lyrebird/Generators/BusIO/` and one in `Sources/Lyrebird/Generators/Channels/` (or wherever the existing `ChannelSelect` lives — match that home). Both replace patterns that today require chains of `+` operators and a corresponding chain of `BinaryOpGenerator.Audio` nodes, each with its own `_result` allocation and `MulAdd` pass. **`MixIn.Audio`** — `Sources/Lyrebird/Generators/BusIO/MixIn.swift` Reads N **non-contiguous** `AudioBus` indices and sums them into a single output (mono) or per-channel-grouped output (multi-channel). Replaces the `signal + In.Audio(bus: ...)` accumulator pattern used in `MixAndRecordInputs` and `ConditionAndRecordInputs`. Today that pattern creates N `In.Audio` nodes + (N-1) `BinaryOpGenerator.Audio` add nodes — each with its own `_result`, each running a full mul-add ramp pass. `MixIn.Audio` collapses to one node with one tight summation loop. Signature: ```swift public enum MixIn { public final class Audio: GeneratorBase, AudioGenerator { /// - Parameters: /// - buses: Non-empty array of `AudioBus` to sum. Buses need not be /// contiguous. All buses must have the same channel count. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. public init( buses: [AudioBus], mul: any ValidGeneratorInput = 1.0, add: any ValidGeneratorInput = 0.0 ) } } ``` Implementation notes: - `outputChannelCount` derives from `buses[0].channelCount` at init. Precondition all buses match. - Hot loop accumulates straight into `_result` row(s) via vDSP `vadd` (per channel, per source bus) when channels-per-bus is fixed. Falls back to a plain accumulation loop for channel counts vDSP doesn't fit. - Bus pointers fetched per block (buses are pre-allocated, not resized); hoist into raw `Double*` array of size `buses.count × channelCount` once per block. - `MulAdd` applied once at end of block via existing `_mulAdd.applyIfNeeded(to:graph:count:)` helper. - No `Control` variant — mixing block-rate bus reads is not a useful workflow (control buses already support `channels:` in `In.Control`). **`SumChannels.Audio`** — `Sources/Lyrebird/Generators/Channels/SumChannels.swift` Collapses any multi-channel `Generator` (or any `ValidGeneratorInput` that resolves to multi-channel) down to a single mono output by summing all rows. Common use case: stereo / quad output of a Synthesizer mixed down to mono for a metering bus, a side-chain detector, or a mono recording. Signature: ```swift public enum SumChannels { public final class Audio: GeneratorBase, AudioGenerator { /// - Parameters: /// - input: Multi-channel signal to collapse. Channel count /// captured at init via the input's `outputChannelCount`; /// mono input passes through unchanged. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. public init( input: any ValidGeneratorInput, mul: any ValidGeneratorInput = 1.0, add: any ValidGeneratorInput = 0.0 ) } } ``` Implementation notes: - `outputChannelCount = 1`. `_result` allocated single-row via `super.init(channels: 1)`. - Hot loop: `_result[0][i] = sum_ch inputChannels[ch][i]`. vDSP path per channel via `vaddD(_result[0], inputChannels[ch], _result[0])` for `ch in 1..= size { idx -= size }`. 2. **Once-per-block `denormalsToZero(_state)`** instead of per-sample. State ranges in IIR filters / envelope followers / feedback delays only enter denormal regime under pathological inputs; per-sample flush is overkill. 3. **State hoisting to locals** — single read at top of `_computeSamples`, single writeback at bottom. Keeps writes off the critical path. 4. **`LyrebirdBuffer._rawStorage` / `_rawStorageMutable` raw-pointer hoist** for buffer-traversing generators (already in place for granular family post-Phase 171). 5. **`withUnsafe(Mutable)BufferPointer` lift** of result rows + param arrays. 6. **Block-constant fast-path detection** on first + last sample of `@LiveParam` ramps (works because `ParameterNode` produces monotonic linear ramps — covered in 173b's design). 7. **Drop redundant `Double(...)` casts on already-`Double` operands.** ### Phase 174 — Dynamics family perf pass (`Compressor`, `Expander`, `AmplitudeFollower`) Direct port of the 173a pattern to the rest of the dynamics family. `LookAheadLimiter` was 173a; the remaining three dynamics generators share the same per-sample envelope-follower / gain-coefficient state. Files: - `Sources/Lyrebird/Generators/Dynamics/Compressor.swift` — `Audio` + `Control` variants, 2 `denormalsToZero` per-sample sites. - `Sources/Lyrebird/Generators/Dynamics/Expander.swift` — `Audio` + `Control` variants (same shape as Compressor). - `Sources/Lyrebird/Generators/Dynamics/AmplitudeFollower.swift` — `Audio` + `Control` variants, 2 `denormalsToZero` per-sample sites. Per-generator wins: 1. **`_env` / `_gain` once-per-block denormal flush.** Match `LookAheadLimiter`. 2. **State hoisted to locals.** `_env`, `_gain`, `attack` / `release` coefficients lifted at top, written back at bottom. 3. **Drop `Double(...)` casts on already-`Double` state.** 4. **Precompute `1.0 - coeff`** at init or at top of block if `attack` / `release` are scalar (block-constant from `floatValue`). For `@LiveParam` modulation, use the block-constant fast-path detection pattern from 173b to skip the smoothing per-sample arithmetic when params are at rest. 5. **`withUnsafeBufferPointer` lift** of input row + `_result[0]`. Tests — extend `Tests/LyrebirdTests/DynamicsTests.swift`: - `denormalCadenceCompressor` — sustained extreme reduction stays finite over ~2 s render. - `denormalCadenceExpander` — same for the noise-gate path. - `denormalCadenceAmplitudeFollower` — sustained near-zero input + tiny attack/release stays finite. - Existing parity tests must pass byte-equivalent. Branch: `phase-174-dynamics-perf`. Single branch (three generators all in `Generators/Dynamics/`; one coordinated review cycle). ### Phase 175 — Reverb family denormal + raw-pointer sweep Highest aggregate denormal-flush count across the catalog. Each reverb is a network of comb / allpass filters with feedback; current implementation flushes denormals per sample on every state element. Files (per `Sources/Lyrebird/Generators/Reverb/`): - `FreeVerb.swift` — 6 `denormalsToZero` sites (8 combs + 4 allpasses per channel). - `GVerb.swift` — 11 sites (FDN + Hadamard + tap-delay + post-sum diffusers). - `PlateReverb.swift` — 9 sites. - `SpringReverb.swift` — 3 sites. Per-reverb wins: 1. **Move denormal flush from per-sample to once-per-block** on every feedback state element (most are floats lying near 0 with rapid decay; block-rate flush still keeps them from drifting into denormals for the real-world signals these reverbs are designed for). 2. **Branchless wrap** on every internal comb / allpass ring buffer. 3. **Raw-pointer hoist** on each comb / allpass delay-line buffer (currently `[Double]` arrays with per-sample subscript). One block-rate bind per delay line. 4. **State hoisting** — feedback gains, filter coefficients lifted to locals. 5. **Verify FTZ engine flag interaction** — if `CoreAudioDriver` sets FTZ on the RT thread, the once-per-block flush may even be removable entirely on hardware that supports it. Document the decision. Tests: - Existing `FreeVerbTests` / `GVerbTests` / `PlateReverbTests` / `SpringReverbTests` must pass byte-equivalent (offline NRT render). - New `denormalLongTailStaysFinite` per reverb — drive 5 s of silence + epsilon, verify no NaN / inf and feedback state remains bounded. Branch: `phase-175-reverb-perf`. Single branch (one coordinated review cycle for the family). ### Phase 176 — Delay-line building blocks (`DelayLine`, `DelayLineFeedback`, `CombFilter`, `AllpassFilter`) Small unit footprint each, but these are the primitives every Reverb / Phaser / Flanger / Karplus-Strong builds on top of. Fix the foundation here and downstream generators benefit transitively (some of the Phase 175 wins are covered by sharing this layer's primitives; the explicit per-reverb sweep catches everything Phase 175's primitives don't). Files: - `Sources/Lyrebird/Generators/Delays/DelayLine.swift` - `Sources/Lyrebird/Generators/Delays/DelayLineFeedback.swift` - `Sources/Lyrebird/Generators/Filters/CombFilter.swift` (3 denormal sites). - `Sources/Lyrebird/Generators/Filters/AllpassFilter.swift` - `Sources/Lyrebird/Generators/Delays/DelayInterpolation.swift` (helper — audit interpolation `TableInterpolation` branch hoist; lift to local at top of compute). Per-generator wins: 1. **Branchless wrap on `_writeIdx`** + branchless wrap on `_readIdx`. Currently `(writePos - delaySamples + length) % length` per sample. 2. **Raw-pointer hoist** on internal delay buffer (`[Double]`). 3. **Interpolation branch hoist** — lift `_interpolation` enum to a local at top of `_computeSamples`, branch once per block. 4. **Block-constant `delayTime` detection** — when `delayTime` is at rest (block-constant), skip per-sample interpolation-coefficient recomputation. Use the 173b first+last fast-path check. 5. **`denormalsToZero(_feedbackState)` once-per-block** in `DelayLineFeedback` and `CombFilter`. Tests: - Existing delay / comb / allpass suites pass byte-equivalent. - New `delayLineRingWrapStress` — long render that forces multiple ring wraps and asserts output continuity across the wrap. Branch: `phase-176-delay-primitives-perf`. ### Phase 177 — `DiskOut.Audio` perf pass Direct 173b analogue. Reads audio bus → ring buffer → drains to disk. Heavy session-recording path. File: `Sources/Lyrebird/Generators/BufferIO/DiskOut.swift` Wins: 1. **Branchless ring-buffer wrap** (`% _ringSize` → branchless). 2. **Raw-pointer hoist** of bus storage (`engine.audioBuses[bus]`) and ring buffer. 3. **Block-constant `run` / `level` flag detection** matching 173b. 4. **Fused per-sample read + ring-write** into single loop body. 5. **Mono specialization** for the common single-channel recording case. Tests: - Existing `DiskOutTests` pass byte-equivalent on render-to-file. - New `diskOutRunGateFastPath` — verify default-flag fast path produces same output as legacy per-sample-gate path. Branch: `phase-177-diskout-perf`. ### Phase 178 — IIR filter library sweep Smallest per-file delta; aggregate matters in filter-heavy graphs. Single coordinated sweep so each filter follows the same canonical pattern. Files (per `Sources/Lyrebird/Generators/Filters/`): - `MoogLadder.swift` (5 denormal sites) - `SVF.swift` (6 sites) - `MuTronIII.swift` (6 sites) - `RBJBiquad.swift` (already touched per CLAUDE.md `runRBJBiquadBlock`) - `SecondOrderSection.swift` - `Lag.swift` / `Lag2.swift` / `LagUpDown.swift` - `Decay.swift` / `Decay2.swift` - `RingingFilter.swift` - `ResonatingFilter.swift` - `ResonatorBank.swift` - `Hilbert.swift` - `FirstOrderSection.swift` Per-filter wins: 1. **Move `denormalsToZero(_y1)` / `_x1` / `_z1` etc.** from per-sample to once-per-block on every IIR state element. The vast majority of these states are zero or rapidly-decaying values that never need a per-sample flush in the audio band. 2. **State hoisting to locals** — `_y1`, `_y2`, `_x1`, `_x2`, etc. lifted at top, written back at bottom. 3. **`withUnsafeBufferPointer` lift** on input row + `_result[0]`. 4. **Block-constant filter-coefficient detection** — `freq` / `q` / `Q` at rest produce constant blocks; pre-compute coefficients once per block and skip the per-sample recomputation. (Some filters already do this via the `runRBJBiquadBlock` helper; sweep verifies adoption across the whole library.) 5. **Drop redundant `Double(...)` casts.** Tests: - Existing filter suites (`MoogLadderTests`, `SVFTests`, `MuTronIIITests`, `RBJBiquadTests`, etc.) pass byte-equivalent. - New filter-library `denormalCascade` test — chain 16 lowpasses with near-zero coefficients on silence input, verify output remains finite over a long render. Branch: `phase-178-iir-filter-sweep`. ### Phases 179–181 — Generator perf sweep follow-on (code dedup) After the Phases 174–178 sweep landed, the Generator hot-loop pattern (state hoist + raw-pointer hoist + once-per-block denormal flush + block-constant fast path + branchless wrap) was applied consistently across the catalog, but five distinct sub-patterns ended up duplicated across the touched files. Phases 179–181 pull those into shared module- internal helpers — same machine code (every helper is `@inline(__always)`), large readability + maintainability win. Each phase ships on its own branch off `main`, single `/lyrebird_review` cycle, merges before next starts. ### Phase 179 — Filter helper consolidation Two new helpers in `Sources/Lyrebird/Generators/Filters/FilterHelpers.swift`: 1. **Two-pole resonator hot loops** — `RingingFilter.processScalar` / `processInterpolated` and `ResonatingFilter.processScalar` / `processInterpolated` bodies are byte-identical post-Phase-178. Move to shared module-internal free functions: ```swift @inline(__always) internal func runTwoPoleResonatorScalarBlock( input: [Double], into result: inout [Double], y1: inout Double, y2: inout Double, b0: Double, na1: Double, na2: Double, count: Int ) @inline(__always) internal func runTwoPoleResonatorInterpolatedBlock( input: [Double], into result: inout [Double], y1: inout Double, y2: inout Double, start: (b0: Double, na1: Double, na2: Double), end: (b0: Double, na1: Double, na2: Double), count: Int ) ``` Both consumer files shrink to a coefficient closure + two one-line helper calls. ~80 lines deleted. 2. **Per-sample coefficient lookup helper** — six current sites use `xxxSamples.map { $0[min(i, $0.count - 1)] } ?? scalarX`. Pull into: ```swift @inline(__always) internal func sampleOrFallback(_ block: [Double]?, scalar: Double, at i: Int) -> Double ``` Apply across `Lag.Audio` / `Lag2.Audio` / `LagUpDown.Audio` / `Lag2UpDown.Audio` / `Decay.Audio` / `Decay2.Audio` / `LeakDC.Audio` per-sample inner loops. Tests: existing 333-test filter suite passes byte-equivalent. No new tests needed. Branch: `phase-179-filter-helpers`. ### Phase 180 — Smoother step helpers Two related smoother-step abstractions designed together so the helper APIs are coherent across the rate-IIR (B) and dynamics-envelope (D) consumers. 1. **One-pole smoother step** — `Lag` / `Decay` families share the surrounding state-hoist + denormal-flush structure with two distinct formulas: - Lag: `y = b1*y1 + (1-b1)*x` - Decay: `y = x + b1*y1` (leaky integrator) ```swift @inline(__always) internal func onePoleLowPassStep( state: inout Double, x: Double, b1: Double, comp: Double ) -> Double // y = b1*state + comp*x; updates state; comp = 1 - b1 precomputed @inline(__always) internal func leakyIntegratorStep( state: inout Double, x: Double, b1: Double ) -> Double // y = x + b1*state; updates state ``` Apply to `Lag.Audio`, `Lag2.Audio` (cascade two `onePoleLowPassStep`), `Decay.Audio`, `Decay2.Audio` (cascade two `leakyIntegratorStep` for attack + decay), `LagUpDown.Audio` / `Lag2UpDown.Audio` (after the asymmetric coefficient selection). `LeakDC.Audio` stays inline — different topology (DC blocker, two states `x1` + `y1`). Lives in `Sources/Lyrebird/Generators/Filters/FilterHelpers.swift` alongside Phase 179's resonator helpers. 2. **Dynamics asymmetric attack/release smoother step** — `AmplitudeFollower`, `Compressor`, `Expander` Audio variants all have the same branch-on-direction smoother: ```swift if target < state { // (or > state for AmplitudeFollower) state = attackCoeff * state + attackComp * target } else { state = releaseCoeff * state + releaseComp * target } ``` Pull into: ```swift internal enum AttackReleaseDirection { case rising, falling } @inline(__always) internal func attackReleaseSmoother( state: inout Double, target: Double, attackCoeff: Double, attackComp: Double, releaseCoeff: Double, releaseComp: Double, direction: AttackReleaseDirection ) ``` `.rising` = use attack-coeff when target > state (AmplitudeFollower); `.falling` = use attack-coeff when target < state (Compressor / Expander — "gain target moving toward more reduction"). Lives in `Sources/Lyrebird/Generators/Dynamics/DynamicsHelpers.swift` (new file alongside `DynamicsBase.swift`). Tests: existing dynamics + lag/decay suites pass byte-equivalent. Branch: `phase-180-smoother-helpers`. ### Phase 181 — `sampleOrZero` sweep Module-internal helper in a new `Sources/Lyrebird/GeneratorCore/HotLoopHelpers.swift`: ```swift @inline(__always) internal func sampleOrZero(_ p: UnsafePointer, _ i: Int, _ n: Int) -> Double { i < n ? p[i] : 0 } ``` Sweep all Phase-174-178 files plus the four Phase-176 delay primitives: - `Dynamics/AmplitudeFollower.swift` / `Compressor.swift` / `Expander.swift` - `Filters/RBJBiquad.swift` (BiquadState + FirstOrderState overloads), `SecondOrderSection.swift`, `FirstOrderSection.swift`, `Lag.swift`, `Lag2.swift`, `LagUpDown.swift`, `Lag2UpDown.swift`, `LeakDC.swift`, `Decay.swift`, `Decay2.swift`, post-179 resonator-helper consumers - `Delays/DelayLine.swift`, `DelayLineFeedback.swift`, `Filters/CombFilter.swift`, `AllpassFilter.swift` — collapse the `sampleAt(_ i)` inline closures to direct `sampleOrZero(srcP, i, n)` calls (the inline closures themselves disappear) ~17 files touched. Each change one-line per call site. Tests: full filter + dynamics + delay touched-suite (~600 tests) passes byte-equivalent. Branch: `phase-181-sampleorzero-sweep`. ### Optional follow-on — `PlayBuffer.Audio` raw-pointer audit Verify Phase 171 (granular sweep) raw-pointer pattern was applied to `PlayBuffer.Audio` (`Sources/Lyrebird/Generators/BufferIO/PlayBuffer.swift`). If not, apply the same `_rawStorage` hoist + interpolation-branch hoist + inlined `.linear` read pattern used by `BufferGrain` and friends. If `PlayBuffer.Audio` is already covered by Phase 171, drop this work. Otherwise fold into Phase 177 (both touch `BufferIO/`). ### Optional follow-on — Modulation FX (`Phaser`, `Flanger`) Multi-stage allpass / delay chain with LFO. Same wins as Phase 176 (delay-line primitives) plus 178 (filter coefficient hoist). May be absorbed transitively when 176 + 178 land, depending on whether Phaser / Flanger reuse the shared delay-line primitives or inline their own. Phase ordering rationale: 1. **174 first** — direct port of 173a, smallest scope, fastest review cycle, gets the dynamics-perf story closed. 2. **175 next** — biggest aggregate win, but more files touched and a denser review. 3. **176** — fixes foundation under future reverb / modulation work; some transitive wins available to anyone using delay-line primitives. 4. **177** — small standalone perf pass, clean 173b analogue. 5. **178** — broadest sweep, single-pattern application, lowest per-file risk; saved for last because it touches the most files. --- ### Phase 182 — Pattern facade refactor + Demand* rename Refactor `Pattern` from a single concrete class into a thin facade backed by a module-internal `_PatternEngine` protocol, so future variants (series / geometric / random / brownian / repeat / switch / stutter / map / …) can ship as engine classes constructed by static factory methods on `Pattern`. Existing sequence behaviour moves into a `SequencePatternEngine` engine and is exposed via `Pattern.sequence(_:repeats:)`. The old initialiser `Pattern(values:repeats:)` is removed; every call site migrates to the new factory. The `ValueComputable` conformance on `Pattern` is preserved. In lockstep, rename the four existing demand-rate sources to spell out "Demand" instead of using the `D*` prefix: - `DSequence` → `DemandSequence` - `DRandom` → `DemandRandom` - `DTemporalBrownian` → `DemandTemporalBrownian` - `DTemporalTendency` → `DemandTemporalTendency` The `DemandGenerator` protocol name is unchanged; `Demand.Audio` / `Demand.Control` puller names are unchanged. No new types yet; this phase exists purely to land the architecture and naming so subsequent phases (183-190 — Pattern + Demand catalogue expansion) land cleanly. **Files** - `Sources/Lyrebird/Patterns/Pattern.swift` — split into thin facade + internal `_PatternEngine` protocol - `Sources/Lyrebird/Patterns/Engines/SequencePatternEngine.swift` — new - `Sources/Lyrebird/Patterns/PatternFactories.swift` — new (`sequence` factory; further factories land in 183+) - `Sources/Lyrebird/Patterns/EuclideanRhythm.swift` — uses `Pattern.sequence(...)` internally - `Sources/Lyrebird/Generators/Demand/DemandSequence.swift` ← was `DSequence.swift` - `Sources/Lyrebird/Generators/Demand/DemandRandom.swift` ← was `DRandom.swift` - `Sources/Lyrebird/Generators/TemporalDemand/DemandTemporalBrownian.swift` ← was `DTemporalBrownian.swift` - `Sources/Lyrebird/Generators/TemporalDemand/DemandTemporalTendency.swift` ← was `DTemporalTendency.swift` - Tests, demos, and docs sweep `\bD(Sequence|Random|TemporalBrownian|TemporalTendency)\b` → `Demand…` **Review-fix pass** (one `/lyrebird_review` cycle): one blocking finding — `SequencePatternEngine.init(values:repeats:)` was on a single line, violating the CLAUDE.md multi-line declaration rule (≥ 2 init params must each sit on their own line). Reformatted to multi-line. Pass 2 clean. Tests: 4008/4010 pass (2 pre-existing flakes documented as unrelated: `RTThreadIdentity.markingIsThreadLocalNotProcessGlobal` + `LyrebirdEventListRecording` SIGSEGV under full-suite multi-engine combos; both pass deterministically in isolation). ### Phase 183 — Atomic numeric Pattern sources First catalogue-expansion phase off the Phase 182 facade refactor. Adds the seven atomic numeric `Pattern` factories that subsequent phases (185-187 modifiers / combinators / map+filter) compose against. **Factories** (all on `public extension Pattern where T == Double`): | Factory | Engine | Algorithm | |---|---|---| | `Pattern.series(start:step:length:)` | `SeriesPatternEngine` | `start, start + step, start + 2·step, …` | | `Pattern.geometric(start:ratio:length:)` | `GeometricPatternEngine` | `start, start·ratio, start·ratio², …` | | `Pattern.uniformRandom(low:high:length:seed:)` | `UniformRandomPatternEngine` | uniform draw in `[low, high]` per call | | `Pattern.brownian(low:high:step:start:length:seed:)` | `BrownianPatternEngine` | random walk clamped to `[low, high]`; each step adds uniform delta in `[-step, step]`; `start` defaults to midpoint | | `Pattern.gaussian(mean:stdDev:length:seed:)` | `GaussianPatternEngine` | Box-Muller draws via `_sampleGauss` | | `Pattern.cauchy(location:scale:length:seed:)` | `CauchyPatternEngine` | inverse-CDF via `_sampleCauchy(posOnly: false)` | | `Pattern.beta(alpha:beta:length:seed:)` | `BetaPatternEngine` | two-Gamma method via `_sampleBetaRand(lo: 0, hi: 1, …)` | `length == -1` runs forever (matches existing `Pattern.sequence` convention). `seed == nil` is time-derived (matches `DemandRandom`). **Engine layout** ``` Sources/Lyrebird/Patterns/Engines/ SeriesPatternEngine.swift GeometricPatternEngine.swift UniformRandomPatternEngine.swift BrownianPatternEngine.swift GaussianPatternEngine.swift CauchyPatternEngine.swift BetaPatternEngine.swift ``` One public type per file. Each engine is a `final class` conforming to the module-internal `_PatternEngine` protocol introduced in Phase 182. **Helper reuse** - `Sources/Lyrebird/Distributions/DistributionSampling.swift` — `_sampleUniform`, `_sampleGauss`, `_sampleCauchy`, `_sampleBetaRand`. Same helpers consumed by `DemandTemporalTendency`; no duplication. - `lyrebirdSeedXorshift64(from:)` — shared init-time seed function. **`reset()` semantics** Rewinds the response counter / walk position only. Intentionally does **not** restore the PRNG state — mirrors the `DemandRandom` precedent. Documented at the class level on every random-engine source file. **Tests** — 33 tests across 7 new files (one `@Suite` per file per CLAUDE.md test-naming rule). Coverage per random engine: basic output, length exhaustion, infinite-mode non-exhaustion, `resetClearsExhaustion`, seed determinism (paired-instance bit-equality), and distribution sanity (Gaussian sample mean within 3·σ/√n, Cauchy sample median ≈ location, Beta sample mean ≈ α/(α+β)). `Series` / `Geometric` get exact deterministic-output checks. **Review-fix pass** (one `/lyrebird_review` cycle): - Missing `reset()` tests in 4 random-engine test files (`UniformRandom`, `Gaussian`, `Cauchy`, `Beta`). Added `resetClearsExhaustion` in each: exhausts finite-length pattern, asserts `isExhausted`, calls `reset()`, asserts `!isExhausted` and `next() != nil`. - Stale `import Foundation` in `PatternGaussianTests.swift` — removed. - Missing `#expect(pat.isExhausted)` in `PatternCauchyTests.producesFiniteValues` after the `count == 1_000` assertion — added. - Caveman line sweep: local `let next: Double` in `BrownianPatternEngine.next()` shadowed the enclosing method name — renamed to `clamped`. Pass 2 clean. Tests: 4042/4042 pass (33 new tests; 2 pre-existing `RTThreadIdentity.markingIsThreadLocalNotProcessGlobal` flakes did not fire on the clean run; tests pass deterministically in isolation as before). Commits on branch: - `6a2ca0c` Phase 183: atomic numeric Pattern sources - `006afea` Phase 183 review fix: reset() tests + caveman shadowing nit ### Phase 184 — Discrete-pool Pattern sources + closure escape hatch Second catalogue-expansion phase off the Phase 182 facade refactor. Adds the four discrete-pool (and closure-wrapping) `Pattern` factories that subsequent phases (185-187 modifiers / combinators / map+filter) compose against. **Factories** (all on `public extension Pattern`, generic over `T`): | Factory | Engine | Algorithm | |---|---|---| | `Pattern.shuffle(_:repeats:seed:)` | `ShufflePatternEngine` | Fisher-Yates permutes `values` once at init; cycles through permuted order. Same permutation replays on `reset()`. Matches SC `Pshuf` semantics. | | `Pattern.nonRepeatingRandom(_:repeats:seed:)` | `NonRepeatingRandomPatternEngine` | Random pick from `values`, never picking the same *index* as the previous pick. Documented index-vs-value caveat: with duplicate values in the pool, value-level repeats can still occur. Single-element pools always return that value. | | `Pattern.weightedRandom(_:weights:repeats:seed:)` | `WeightedRandomPatternEngine` | Pick proportional to weight via cumulative distribution. Preconditions trap on misuse: `values.count == weights.count`, all weights finite and ≥ 0, sum > 0. `cumulative[last]` forced to exactly `1.0` to handle FP rounding. | | `Pattern.closure(_:)` | `ClosurePatternEngine` | Wraps a `() -> T?` closure. Closure owns its own state. Once closure returns `nil`, engine latches exhausted. `reset()` clears the latch but cannot reset closure-internal state — documented escape-hatch semantics. | **Engine layout** ``` Sources/Lyrebird/Patterns/Engines/ ShufflePatternEngine.swift NonRepeatingRandomPatternEngine.swift WeightedRandomPatternEngine.swift ClosurePatternEngine.swift ``` All four conform to `_PatternEngine` (Phase 182). One public type per file. **`reset()` semantics** — rewinds counter / walk position / last-pick / latch state. PRNG seed intentionally NOT restored on the random variants — mirrors `DemandRandom` precedent so rhythmic retriggering keeps audible variety. **NonRepeating retry-loop safety** — the `_values.count == 1` early-return plus `_lastIndex` initialised to `-1` guarantees a different index always exists for pools of size ≥ 2; loop always terminates. **Tests** — 21 tests across 4 new files. Coverage includes basic output, length exhaustion, seed determinism, reset semantics, distribution sanity (weighted 9:1 bias on n=5000 within 3·SE), zero-weight-never-picked, latched-once-nil closure semantics, captured-state survival across calls. **Review-fix pass** (one `/lyrebird_review` cycle): - Blocking: `WeightedRandomPatternEngine.next()` was missing the `!_values.isEmpty` guard present in sibling engines. Init precondition prevented misuse via the factory, but the defensive guard was needed for consistency under any future direct construction. - Caveman nit 1: `weights.allSatisfy { $0 >= 0.0 }` admitted `+Infinity`, which then poisons the cumulative array (`Inf/Inf = NaN`). Tightened to `$0.isFinite && $0 >= 0.0`. - Caveman nit 2: documented the `u < _cumulative[i]` strict-less-than scan with implicit fallthrough behaviour for `u == 1.0` (`_uniform01` can return exactly 1.0 when `xorshift64NextRaw` returns `UInt64.max`) and for zero-weight buckets. Pass 2 clean. Tests: 4061/4063 pass (21 new tests; 2 pre-existing `RTThreadIdentity.markingIsThreadLocalNotProcessGlobal` flakes). Commits on branch: - `93fc8e6` Phase 184: discrete-pool Pattern sources + closure escape hatch - `fcbbb00` Phase 184 review fix: WeightedRandomPatternEngine guards + finite weights ### Phase 185 — Length/range Pattern modifiers Third catalogue-expansion phase off the Phase 182 facade refactor. Adds the four modifier `Pattern` factories that wrap any upstream pattern. Modifier phases unblock the multi-pattern composition phases (186 — switch / concat / roundRobin / tuple / interleave) by exercising the wrapped-pattern reset() propagation pattern. **Factories** (all on `public extension Pattern`, generic over `T`): | Factory | Engine | Algorithm | |---|---|---| | `Pattern.repeating(_:count:)` | `RepeatPatternEngine` | Replays upstream `count` times, calling `reset()` between cycles. `count == -1` infinite. Precondition `count >= -1`. Latches if upstream remains empty after a fresh reset (degenerate-source guard). Matches SC `Pn`. | | `Pattern.limit(_:count:)` | `LimitPatternEngine` | Emits at most `count` items returned (counts non-nil pulls only, not calls). If upstream exhausts first, latches at the same time. Precondition `count >= 0`. Matches SC `Pfin`. | | `Pattern.drop(_:count:)` | `DropPatternEngine` | Skips first `count` upstream values lazily on first `next()`, then passes through. If upstream exhausts during drop phase, returns nil. Precondition `count >= 0`. Matches SC `Pdrop`. | | `Pattern.stutter(_:count:)` | `StutterPatternEngine` | For each source value, emit it n times where n is the next value from a `Pattern`. count <= 0 consumes source but emits nothing — loop re-pulls next pair. Latches as soon as either upstream returns nil while pulling a new pair. Source pulled first, then count for that source value (matches SC `Pstutter`). | **Engine layout** ``` Sources/Lyrebird/Patterns/Engines/ RepeatPatternEngine.swift LimitPatternEngine.swift DropPatternEngine.swift StutterPatternEngine.swift ``` All four conform to `_PatternEngine` (Phase 182). One public type per file. All `reset()` propagate to the wrapped upstream pattern(s) plus clear local counter / latch / repeat-state. **Tests** — 19 tests across 4 new files. Coverage: basic output, edge cases (`count == 0`, upstream empty, count exceeds upstream, negative count on Stutter), reset semantics, latched-exhaustion paths. **Review-fix pass** (one `/lyrebird_review` cycle): - Blocking: `RepeatPatternEngine.init` was missing `precondition(count >= -1)`. Documented contract said `count == -1` is the infinite sentinel, but any negative value (`-2`, `-99`, etc.) was being silently treated as infinite because `_count >= 0` is false for all of them. Sibling engines `LimitPatternEngine` and `DropPatternEngine` already had analogous preconditions. Added. - Blocking: `StutterPatternEngine.next()` returned `_currentValue: T?` directly at the end. The loop invariant holds — `_currentValue` is non-nil whenever `_remainingRepeats > 0` — but the type system doesn't encode it. A future refactor could break the invariant and the bug would present as silent exhaustion rather than a crash or assertion. Fixed with defensive `guard let value: T = _currentValue else { _exhaustedLatch = true; return nil }` at the return site — invariant violations now latch exhaustion explicitly. - Missing test: `StutterPatternEngine` documented that negative count from the count pattern behaves identically to zero (consume source, emit nothing). No test covered it. Added `negativeCountSkipsValue`. Pass 2 clean. Tests: 4080/4081 pass (1 pre-existing `RTThreadIdentity.markingIsThreadLocalNotProcessGlobal` flake). Commits on branch: - `ba4cd76` Phase 185: length/range Pattern modifiers - `c148ea3` Phase 185 review fix: count preconditions + invariant guard ### Phase 186 — Multi-pattern composition Fourth catalogue-expansion phase off the Phase 182 facade refactor. Adds the five composition primitives that combine multiple upstream patterns — the piece that turns the 183–185 atomic-and-modifier catalogue into something expressive. Subsequent map / filter / transform (187) compose on top of these. **Factories** (all on `public extension Pattern`): | Factory | Engine | Algorithm | |---|---|---| | `Pattern.switching(_:index:)` | `SwitchPatternEngine` | SC `Pswitch1`. Each `next()` pulls one index from the index pattern, then one value from `patterns[index]`. Latches as soon as the index pattern exhausts, the selected sub-pattern exhausts, or the drawn index is out of range. Out-of-range latches rather than trapping — robust under live-edited index patterns. | | `Pattern.concatenate(_:)` | `ConcatenatePatternEngine` | Plays each pattern in turn. Advances `_activeIndex` when active sub-pattern returns nil. Latches after the last sub-pattern exhausts. | | `Pattern.roundRobin(_:)` | `RoundRobinPatternEngine` | SC `Ppatlace`. Pulls one value per pattern in rotation. When a pattern returns nil, its slot is marked dead via `_alive[i] = false` + `_aliveCount -= 1` and skipped on subsequent rotations. Latches once `_aliveCount == 0`. | | `Pattern.tuple(_:)` | `TuplePatternEngine` | Returns `Pattern<[T]>` (different element type — engine declares `Element = [T]`). Each `next()` pulls one value from each child, returning a size-stable `[T]` array. Latches as soon as any child returns nil. | | `Pattern.interleave(_:repeats:)` | `InterleavePatternEngine` | SC `Place` semantics. For each outer cycle `j` in `0..= -1`. | **Engine layout** ``` Sources/Lyrebird/Patterns/Engines/ SwitchPatternEngine.swift ConcatenatePatternEngine.swift RoundRobinPatternEngine.swift TuplePatternEngine.swift InterleavePatternEngine.swift ``` All five conform to `_PatternEngine` (Phase 182). One public type per file. Four engines declare `Element = T`; `TuplePatternEngine` declares `Element = [T]` to make the differing return element type explicit. All `reset()` propagate to wrapped upstream pattern(s) and clear local cursor / latch / dead-slot state. **Tests** — 24 tests across 5 new files. Coverage includes ordered output, ragged sub-pattern behaviour, exhaustion semantics per engine, out-of-range index latching, empty-input edge cases, repeats cycling, and reset semantics. **Review-fix passes** (two `/lyrebird_review` cycles): - **Pass 1 — two blockers**: - `RoundRobinPatternEngine.next()` defensive guard `attempts > _patterns.count` was off by one — allowed one extra hop past full ring traversal. Fixed to `>= _patterns.count`. - `InterleavePatternEngine` had two problems: `_cycleSize * _repeats` multiplication overflow path for large finite `repeats`, AND the engine diverged from SC `Place` semantics by emitting `lists.count × maxLen` per cycle rather than the SC outer-cycle `lists.count × repeats`. Rewrote engine to match SC `Place` exactly: each outer cycle `j` emits one value per sub-list with `sublist[j % sublist.count]` indexing. Eliminates both issues in a single rewrite. Tests updated to match new semantic. - **Pass 2 — one stale doc**: `PatternFactories.swift` factory-level doc comment for `Pattern.interleave` still described the pre-rewrite `lists.count × maxLen` semantic. Rewrote to match the engine-level doc (`lists.count × repeats`). - **Pass 3 clean.** Tests: 4104/4105 pass (24 new tests; 1 pre-existing `RTThreadIdentity.markingIsThreadLocalNotProcessGlobal` flake). Commits on branch: - `e5a203a` Phase 186: multi-pattern composition - `1d159c0` Phase 186 review fix: RoundRobin guard + Interleave SC Place parity - `602be77` Phase 186 review pass 2 fix: align interleave factory doc with engine ### Phase 187 — Map/filter/transform Pattern catalogue Fifth and final Pattern-side catalogue-expansion phase off the Phase 182 facade refactor. Closes the Pattern-side of the 183-187 sweep; Phases 188-190 mirror the work on the `Demand*` RT-side. **Factories** — nine new methods across two extension blocks. **Generic** (`public extension Pattern`): | Factory | Engine | Algorithm | |---|---|---| | `Pattern.map(_:_:)` | `MapPatternEngine` | SC `Pcollect`. Wraps `Pattern` with `(U) -> T` transform. Result element type can differ from upstream. Engine declares `Element = Out`. | | `Pattern.filter(_:where:)` | `FilterPatternEngine` | SC `Pselect`. Pulls upstream until predicate true or upstream exhausts. Documented spin caveat for infinite-source-never-matching-predicate. | | `Pattern.reject(_:where:)` | `FilterPatternEngine` (negated) | SC `Preject`. Routes the same engine class with a negated predicate — single engine, two factory entry points. | **Numeric** (`public extension Pattern where T == Double`): | Factory | Engine | Algorithm | |---|---|---| | `Pattern.accumulate(_:initial:)` | `AccumulatePatternEngine` | SC `Paccum`. Running sum starting from `initial`. Reset rewinds total. | | `Pattern.difference(_:)` | `DifferencePatternEngine` | SC `Pdiff`. First value passes through verbatim (treated as if prior sample were 0). Subsequent values = `x[n] - x[n-1]`. Reset clears previous-value memory. | | `Pattern.wrap(_:low:high:)` | `MapPatternEngine` (closure) | SC `Pwrap`. Floor-modulo into half-open `[low, high)` with FP-boundary post-clamp guarding against `wrapped == range` rounding artefacts and negative-side underflow. Precondition `high > low`. | | `Pattern.clip(_:low:high:)` | `MapPatternEngine` (closure) | SC `Pclip`. Clamps to `[low, high]`. `low == high` is allowed (collapses to constant). Precondition `high >= low`. | | `Pattern.round(_:step:)` | `MapPatternEngine` (closure) | SC `Pround`. Rounds to nearest multiple of `step`, ties away from zero (`.toNearestOrAwayFromZero` — Swift's default `.toNearestOrEven` banker's rounding would diverge from SC at `2.5 → 2` vs SC's `3`). Precondition `step > 0`. | | `Pattern.smooth(_:coefficient:)` | `SmoothPatternEngine` | SC `Psmooth`. One-pole exponential smoother `y[n] = c·y[n-1] + (1-c)·x[n]`. Coefficient clamped to `[0, 1]` at init. First sample passes through verbatim. Reset clears previous-output memory. | **Engine layout** ``` Sources/Lyrebird/Patterns/Engines/ MapPatternEngine.swift FilterPatternEngine.swift AccumulatePatternEngine.swift DifferencePatternEngine.swift SmoothPatternEngine.swift ``` Five new engines. The three stateless numeric transforms (`wrap` / `clip` / `round`) reuse `MapPatternEngine` via closure rather than introducing separate engines — no state to maintain. `PatternFactories.swift` gained `import Darwin` at the top for the `floor()` call in `Pattern.wrap` (matches existing `Sources/Lyrebird/Math/` + `Sources/Lyrebird/Generators/Filters/` conventions). **Tests** — 28 tests across 9 new files (one `@Suite` per file). Coverage includes basic output, element-type change for map, predicate filter behaviour, empty-result filter cases, running-sum + custom initial, first-value-verbatim difference, half-open wrap with negative ranges + FP-boundary sweep (`resultAlwaysStrictlyBelowHigh`), clip clamping including `low == high` constant case, round to fractional step + SC-parity tie-away-from-zero (`tiesAwayFromZeroMatchSCPround` covering `0.5 → 1`, `2.5 → 3`, `-1.5 → -2`), smoother coefficient edge cases (0 = pass-through, 1 = hold, clamp above 1), reset semantics across stateful engines. **Review passes**: - Lyrebird review cycle 1 clean — no architectural blockers. - Caveman pass 1 — three substantive findings: - `Pattern.round` used Swift default `.toNearestOrEven` but doc claimed "Matches SC `Pround`". Switched to `.toNearestOrAwayFromZero` + added `tiesAwayFromZeroMatchSCPround` test. - `Pattern.wrap` floor-modulo could leave result exactly at `range` for FP-boundary inputs. Added defensive `if wrapped >= range { wrapped -= range }; if wrapped < 0.0 { wrapped += range }` post-clamp. New `resultAlwaysStrictlyBelowHigh` test sweeps boundary inputs including `10.0`, `1e15`, `-1e15`. - `Pattern.wrap` doc comment claimed "Result is undefined if `low == high`" but the precondition traps that case. Removed misleading line. - Caveman pass 2 — one non-blocking stale comment in `PatternRoundTests` claimed `.rounded()` default is `.toNearestOrEven` after the engine switched modes. Aligned. - Pass 3 clean. Tests: 4131/4132 pass (28 new tests; 1 pre-existing `RTThreadIdentity.markingIsThreadLocalNotProcessGlobal` flake). Commits on branch: - `2bd6cf3` Phase 187: map/filter/transform Pattern catalogue - `b796898` Phase 187 caveman fix: SC parity for Pround + wrap boundary guard - `e4a24cc` Phase 187 pass 2 fix: stale rounding-mode comment in PatternRoundTests ### Phase 188 — Atomic numeric `Demand*` (Pattern-engine wrap consolidation) First RT-side mirror of the Pattern-side 183-187 sweep. Adds the four demand-rate counterparts to the Phase 183 atomic numeric Pattern factories. **Consolidation strategy** — per user direction, share algorithm where it overlaps. The four module-internal Pattern engines from Phase 183 were already RT-safe by construction (pure arithmetic + `xorshift64NextRaw` + `_sampleUniform`; no allocation, no locks, no `String` construction). Rather than duplicate ~120 lines of algorithm code, each new `Demand*` class is a thin `public final class` wrapper that stores the corresponding engine as a `private let _engine: ConcreteEngineType` and forwards `nextValue()` / `reset()` / `isExhausted` in one line each. | Class | Wraps | Mirrors | |---|---|---| | `DemandSeries` | `SeriesPatternEngine` | `Pattern.series(start:step:length:)` | | `DemandGeometric` | `GeometricPatternEngine` | `Pattern.geometric(start:ratio:length:)` | | `DemandUniformRandom` | `UniformRandomPatternEngine` | `Pattern.uniformRandom(low:high:length:seed:)` | | `DemandBrownian` | `BrownianPatternEngine` | `Pattern.brownian(low:high:step:start:length:seed:)` | **Access-control note** — Swift permits a `public final class` to hold a `private` stored property of a module-internal type. The internal engine class can be referenced by the public class's stored property because the property's access level (private) is at or below the engine's access level (internal). Compiles cleanly with no `@_implementationOnly` annotation required. **Roles in the catalogue**: - `DemandBrownian` is the plain stateless-parameter complement to the pre-existing `DemandTemporalBrownian` (which accepts `RTTemporalParameter` bounds / step that can evolve over time). - `DemandUniformRandom` complements the pool-based `DemandRandom` by drawing continuous values inside a numeric range rather than picking from a discrete set. **`reset()` semantics** match the Pattern side: rewinds counter / walk position but intentionally does NOT restore the PRNG seed on `DemandUniformRandom` / `DemandBrownian` (mirrors `DemandRandom` precedent so rhythmic retriggering keeps audible variety). **File layout** ``` Sources/Lyrebird/Generators/Demand/ DemandSeries.swift (new) DemandGeometric.swift (new) DemandUniformRandom.swift (new) DemandBrownian.swift (new) ``` All four sit next to `DemandSequence.swift` / `DemandRandom.swift` from Phase 182. One public type per file. **Tests** — 13 tests across 4 new files (one `@Suite` per file). Coverage mirrors the Phase 183 Pattern test suites: arithmetic / geometric output exactness, range-bounds invariants, seed determinism (paired-instance bit-equality), reset semantics, midpoint default for Brownian, fractional ratio decay for Geometric. **Review-fix passes** — both Lyrebird agent and caveman line sweep returned clean on first pass; zero fixes required. The `private let _engine: ConcreteType` (concrete module-internal type stored in private property of public class) pattern was specifically verified for access-control correctness during the architectural review. Tests: full-suite runs hit two pre-existing intermittent crashes (the `LyrebirdEventListRecording` SIGSEGV under multi-engine combos + the `RTThreadIdentity` cascade flake) documented MEMORY.md as unrelated to Phase 188. The Demand-suite touched-filter passes 87/87 deterministically (74 pre-existing + 13 new). Commits on branch: - `fc17369` Phase 188: atomic numeric Demand* (wrap Phase 183 Pattern engines) ### Phase 189 — Discrete-pool `Demand*` (Pattern-engine wrap consolidation) Second RT-side mirror of the Pattern-side 183-187 sweep. Adds the three discrete-pool demand-rate counterparts to the Phase 184 Pattern factories. **Factories** — three new `public final class` `DemandGenerator` conformers, each wrapping the corresponding Phase 184 module-internal Pattern engine parameterised over `T = Double`: | Class | Wraps | Mirrors | SC | |---|---|---|---| | `DemandShuffle` | `ShufflePatternEngine` | `Pattern.shuffle(_:repeats:seed:)` | `Dshuf` | | `DemandNonRepeatingRandom` | `NonRepeatingRandomPatternEngine` | `Pattern.nonRepeatingRandom(_:repeats:seed:)` | `Dxrand` | | `DemandWeightedRandom` | `WeightedRandomPatternEngine` | `Pattern.weightedRandom(_:weights:repeats:seed:)` | `Dwrand` | Same thin-wrap consolidation pattern as Phase 188 — each class ~30 lines, `private let _engine: ConcreteEngineType` holds the engine, `nextValue()` / `reset()` / `isExhausted` are one-line forwards. **RT-safety verification**: - `DemandShuffle` — Fisher-Yates runs at init only (off RT thread). `next()` is array-index arithmetic + bounded mod increment. Allocation-free. - `DemandNonRepeatingRandom` — retry loop bounded for any pool of size ≥ 2; single-element fast-path at init prevents infinite spin. `xorshift64NextRaw` pure arithmetic. - `DemandWeightedRandom` — cumulative distribution pre-built at init. `next()` is one `_uniform01` draw + O(N) linear scan over the pre-built `let` array. Init preconditions (`.isFinite && >= 0` weights, positive sum) trap on the language thread. `reset()` rewinds counter / last-pick / cycle state but intentionally does NOT restore the PRNG seed (mirrors `DemandRandom` precedent). **File layout** ``` Sources/Lyrebird/Generators/Demand/ DemandShuffle.swift (new) DemandNonRepeatingRandom.swift (new) DemandWeightedRandom.swift (new) ``` **Tests** — 12 tests across 3 new files (one `@Suite` per file). Coverage mirrors the Phase 184 Pattern test suites: shuffle covers all values + same permutation replays on reset + seed determinism + `resetClearsExhaustion`, non-repeating never picks same index twice + single-value pool always returns that value + seed determinism + reset, weighted distribution matches expected fraction within 3·SE + zero-weight never picked + seed determinism + reset. **Review-fix pass** (one `/lyrebird_review` cycle): - Blocking: `DemandShuffleTests` was missing the `resetClearsExhaustion` test that every Phase 188 peer carries. Added (exhaust finite shuffle, assert `isExhausted`, call `reset()`, assert `!isExhausted` and `nextValue() != nil`). Pass 2 clean. Commits on branch: - `7348d4e` Phase 189: discrete-pool Demand* (wrap Phase 184 Pattern engines) - `c36ba88` Phase 189 review fix: missing reset test on DemandShuffle ### Phase 190 — Composition `Demand*` (closes 182-190 catalogue sweep) Final phase of the 182-190 Pattern + Demand catalogue expansion. Adds the three composition `Demand*` types and closes the RT-side mirror of the Pattern catalogue. **Strategic departure from Phase 188-189**: where 188-189 wrapped Phase 183-184 Pattern engines parameterised over `Double`, the composition demand types in 190 cannot use the same wrap because Pattern engines take `Pattern` upstream while the demand side composes other `DemandGenerator` instances. Direct implementation is the cleaner fit; each class is short (~30 lines) and RT-safe by construction. **Classes**: | Class | SC | Algorithm | |---|---|---| | `DemandStutter` | (close to `Dstutter` w/ scalar count) | Wraps another `DemandGenerator` + scalar `Int count >= 1`. Each upstream value is emitted `count` times in a row before the next upstream pull. Scalar-only count (not `DemandGenerator`-driven) for zero-allocation init + straightforward RT path. | | `DemandSwitch` | `Dswitch1` | `index` is itself a `DemandGenerator`. Each `nextValue()` pulls one index, floor-casts via `Int(idxRaw.rounded(.down))` (true floor, not `Int(_:)`'s truncate-toward-zero), then pulls one value from `demands[idx]`. Latches on index exhaustion / sub-source exhaustion / out-of-range index. Out-of-range latches without trap for live-edit robustness. | | `DemandConcatenate` | (close to SC `Dser` / `Pseq`-of-streams) | Sequential play. Emits all of `demands[0]` until exhaustion, then advances to `demands[1]`, etc. While-loop in `nextValue()` correctly skips immediately-exhausted sub-sources. Latches after the last sub-source exhausts. | **RT-safety verification** — All three classes use only: - Direct method dispatch on the wrapped `DemandGenerator` reference(s) - Pure arithmetic (Int / Double ops, `.rounded(.down)`, modulo) - No allocation in `nextValue()` / `reset()` paths - No locks, no `String` construction (the `precondition` interpolation in `DemandStutter.init` is init-time only) - No `is`/`as?` runtime type checks - No force unwraps **Tests** — 13 tests across 3 new files (one `@Suite` per file). Coverage: - `DemandStutter` — repeats each value, count=1 pass-through, upstream exhaustion latches, reset replays both upstream + count counter. - `DemandSwitch` — pulls by index, index exhaustion latches, sub-source exhaustion latches, out-of-range index latches, fractional negative index floors-to-latch (new in review-fix pass), reset restarts all. - `DemandConcatenate` — plays each in turn, empty list exhausts immediately, mid-list exhausted sub-sources skipped, reset replays all. **Review-fix pass** (one `/lyrebird_review` cycle): - Blocking: `DemandSwitch.next()` used `Int(idxRaw)` which truncates toward zero, not floors. Doc comment claimed "floor-cast" but `Int(-0.5)` = 0 (toward zero), would silently pick `demands[0]` for fractional negative indices in `(-1.0, 0.0)` — divergence from the documented latch-on-out- of-range contract. Fixed with `Int(idxRaw.rounded(.down))`; added `negativeFractionalIndexFloorsToLatch` test. Pass 2 clean. --- ### Closing summary — Pattern + Demand catalogue sweep (Phases 182-190) **Pattern side** — 30 factory methods on `Pattern` (1 baseline `sequence` from the Phase 182 refactor + 29 new across Phases 183-187): | Category | Phase | Factories | |---|---|---| | Atomic numeric | 183 | `series`, `geometric`, `uniformRandom`, `brownian`, `gaussian`, `cauchy`, `beta` | | Discrete-pool + closure | 184 | `shuffle`, `nonRepeatingRandom`, `weightedRandom`, `closure` | | Length/range modifiers | 185 | `repeating`, `limit`, `drop`, `stutter` | | Multi-pattern composition | 186 | `switching`, `concatenate`, `roundRobin`, `tuple`, `interleave` | | Map/filter/transform | 187 | `map`, `filter`, `reject`, `accumulate`, `difference`, `wrap`, `clip`, `round`, `smooth` | All Pattern factories return `Pattern` (except `tuple` which returns `Pattern<[T]>`). Backed by 25 module-internal engines under `Sources/Lyrebird/Patterns/Engines/`, all conforming to the `_PatternEngine` protocol introduced by Phase 182. **Demand side** — 14 public `DemandGenerator` conformers total: | Status | Class | Wraps | |---|---|---| | Pre-existing (renamed in 182) | `DemandSequence` | — | | Pre-existing (renamed in 182) | `DemandRandom` | — | | Pre-existing (renamed in 182) | `DemandTemporalBrownian` | — | | Pre-existing (renamed in 182) | `DemandTemporalTendency` | — | | New (188) | `DemandSeries` | `SeriesPatternEngine` | | New (188) | `DemandGeometric` | `GeometricPatternEngine` | | New (188) | `DemandUniformRandom` | `UniformRandomPatternEngine` | | New (188) | `DemandBrownian` | `BrownianPatternEngine` | | New (189) | `DemandShuffle` | `ShufflePatternEngine` | | New (189) | `DemandNonRepeatingRandom` | `NonRepeatingRandomPatternEngine` | | New (189) | `DemandWeightedRandom` | `WeightedRandomPatternEngine` | | New (190) | `DemandStutter` | — (composes `DemandGenerator`) | | New (190) | `DemandSwitch` | — (composes `DemandGenerator`s) | | New (190) | `DemandConcatenate` | — (composes `DemandGenerator`s) | Wrap-based consolidation in Phases 188-189 saved ~270 lines of duplicate algorithm code while keeping the Pattern-side and Demand-side bit-equivalent under matching seeds + parameters. Phase 190 used direct implementation because the composition types compose other `DemandGenerator` instances (not Pattern engines). Commits on branch: - `ed99aeb` Phase 190: composition Demand* — closes 182-190 catalogue sweep - `e5f230e` Phase 190 review fix: DemandSwitch true-floor vs truncate-toward-zero --- ### Phase 196 — Engine Ownership + Lifecycle Safety **Status.** Active — branch `phase-196`. **Goal.** Make multi-engine usage safe by construction, eliminate the silent double-bind footgun, and fix the suspected refcount race behind the deferred parallel `swift test` crash. Single-engine code path stays surface-compatible: every safety mechanism lands inside `SynthesisEngine` and runs identically whether one engine or N engines are in process. **Why now.** Pre-ship is the only zero-cost window for the breaking pieces (`engine.add(_:)` returns `Bool` → `throws`; new `engine.identifier` stored `let`). Memory entry `project_parallel_test_crash.md` documents a `_ContiguousArrayStorage` refcount race that fires when two `SynthesisEngine` instances run concurrently in one process; production code never hits it *today*, but documented multi-engine usage (NRT batch render, multi-device RT) will. Closing the gap now keeps the documented path honest. **Scope.** | Item | What ships | Breaking? | |------|-----------|-----------| | 196.1 | `_engineBinding: Atomic` set-once binding on `SynthesizerBase` + `LyrebirdBuffer` with `_bind(to:)` / `_unbind(from:)` internal API. Two-tier `LyrebirdBuffer.bindReadOnly(to:)` for cross-engine wavetable share (refcount, not CAS). | No — internal only | | 196.2 | `engine.add(_:)` and `engine.add(_:position:)` return `Bool` → `throws`. New `EngineAddError` enum: `boundToOtherEngine(current: UUID, prior: UUID)`, `doubleAdd(engine: UUID)`, `pendingQueueFull`, `rebuildFailed(underlying:)`. Drop `@discardableResult`. | **Yes** — mechanical `try` sweep across all call sites | | 196.3 | `public let identifier: UUID = UUID()` on `SynthesisEngine`. Threaded into `EngineAddError` messages and the lifecycle registry. | **Yes** — additive (new public property) | | 196.4 | `EngineLifecycleCoordinator` (module-internal singleton, `NSLock`-protected) holding `[UUID: WeakEngineRef]`. Every `SynthesisEngine.init` registers, `deinit` unregisters. `engine.start()` / `engine.stop()` acquire the coordinator lock around teardown drain. Heads off the `freeWorker.sync` interleave suspected behind the parallel-test crash. | No — internal singleton | | 196.5 | `RetainQueue` typed wrapper around `SPSCQueue` + `Unmanaged.passRetained`. Overflow path calls `retained.release()` instead of dropping the result silently, balancing the refcount under burst load. All six enqueue sites in `SynthesisEngine.swift:1595–1666` migrate. | No — internal | | 196.6 | Multi-engine regression test: two engines, two threads, disjoint Synth graphs, ≥1000 segments each, join, stop. Runs under `swift test --no-parallel` (single test process, two threads inside). Acts as deterministic repro target for the parallel crash. | No | | 196.7 | Skill update: `~/.claude/skills/lyrebird_review/skill.md` line 58 and `lyrebird_review_cycle/skill.md` line 13 use `swift test --no-parallel` (canonical command per memory). Sync to repo mirror via `bash scripts/sync-claude-from-working.sh --apply`. | No | | 196.8 | Doc updates: `docs/engine/synthesis-engine.md` notes throwing `add`, identifier, binding rules; `docs/engine/multi-core.md` gains "Multiple engines — object ownership rules" subsection pointing forward to the Phase 197 host topic; `CLAUDE.md` "Interface Conventions" flags the `engine.add` signature change. | No | **Skipped after evaluation.** - `LyrebirdBuffer` default-immutable flip (was B3). Grep showed `LyrebirdBuffer` touched by 45 files with intrinsic mutation API (`setValue`, `setRangeValues`, `clear`, `fill`, `fillSine`, `fillHanning`, `fillTriangle`, `invalidate`, internal `write`, `withMutableStorage`) plus RT-side `RecordBuffer` writes and language-side realtime updates. Existing tear-free atomic-flag model is already RT-safe. Flipping the default would fight the type's actual usage pattern with no safety win. Kept opt-in `bindReadOnly` for cross-engine wavetable share; default stays exclusive-mutable. - Demoting `SynthesisEngine.init` visibility to force users through `EngineHost`. `EngineLifecycleCoordinator` (196.4) gives the same safety net without the migration cost; single-engine UX stays direct-ctor. - Tightening `Synthesizer` Sendable conformance beyond `@unchecked Sendable`. Touches every user-authored subclass; multi-engine reasoning works fine without it. **Exit criterion.** 1. `swift test --no-parallel` green. 2. New multi-engine regression test (196.6) green. 3. Parallel `swift test` either passes cleanly OR remaining failures are clearly attributable to a different surface (test-harness only, not engine internals) and documented in `MEMORY.md`. 4. `/lyrebird_review` clean. **Notes for execution.** - `engine.add(_:)` throws sweep is the chunky part — likely several hundred call sites across `Tests/` + `Demos/` + `Sources/`. Drive it with `grep -rn "\.add(.*Synth"` then mechanical `try` insertion. - `EngineLifecycleCoordinator` must `unregister` on `engine.deinit` for test-isolation correctness (xctest case persistence). - `RetainQueue.enqueue` overflow `release()` runs on caller thread; caller is main thread in `removeFromParent` / `engine.stop` paths (verify before landing). RT path drops silently as today — no behaviour change for RT callers. - Open question to resolve during execution: does `@TaskLocal _currentlyBuildingRef` give thread-local or process-global semantics when `withValue` is invoked outside a `Task { }`? If process-global, concurrent `engine.add` calls across engines corrupt each other and Phase 196 needs a module-internal lock around the build closure. 30-min spike before committing to the final shape of 196.1. **Commits on branch:** - `22d6f4b` Phase 196 + 197 plan - `62589a5` Phase 196.7: review skills use swift test --no-parallel - `eeceaf7` Phase 196.3: add SynthesisEngine.identifier UUID - `0e06516` Phase 196.4: EngineLifecycleCoordinator registry stub - `0674819` Phase 196.1 (part 1/2): SynthesizerBase ownership binding API - `c9543e9` Phase 196.1 (part 2/2): LyrebirdBuffer opt-in binding API - `f4b5be6` Phase 196.2: wire _bind into engine.add, convert Bool → throws - `b4bb5e8` Phase 196.5: typed RetainQueue wraps freeQueue - `050b082` Phase 196.6: multi-engine regression test suite - `032659c` Phase 196.8: docs — engine identity, binding rules, throws conversion - `488d2a3` Phase 196 review fix batch 1: blocking findings cleanup - `1846306` Phase 196 review fix batches 2-8: bug + risk findings - `780703a` Phase 196 re-review fixes: prune iteration UB, refcount underflow, EventList partial-state rollback - `3753f2b` Phase 196 third-pass review fixes: VoicePool partial-add rollback - `41e07aa` Phase 196 third-pass review nits: magic-number CAS pass cap, MessageCenter consistency --- ### Phase 197 — `EngineHost` Multi-Engine Facade **Status.** Planned — depends on Phase 196 landing. **Goal.** Add the blessed multi-engine entry point as a creation-owning host class wrapping the Phase 196 `EngineLifecycleCoordinator`. Single-engine path remains unchanged; host is opt-in convenience for N≥2. Same engine type underneath both paths. **Framing.** This is the "if you need multiple engines, here is the manager to use" specialised path. Docs surface the host as the canonical multi-engine direction; users keeping one engine continue to use the direct `SynthesisEngine()` ctor exactly as before. Interfaces stay uniform across both modes — host adds named roles, lifecycle serialisation, and NRT-pool ergonomics; it does not introduce a parallel engine type. **Scope.** | Item | What ships | |------|-----------| | 197.1 | `public final class EngineHost`. Creation-owning: `makeEngine(role:config:) throws -> SynthesisEngine`. Internally calls `SynthesisEngine.init` and registers with the Phase 196 coordinator. | | 197.2 | `public enum EngineHost.Role: Hashable` — cases `.nrtRender(slot: Int)`, `.rtOutput(deviceID: AudioDeviceID)`, `.auxiliary(name: String)`, `.custom(String)`. Throws on duplicate `.rtOutput(deviceID:)` registration (AUHAL device exclusivity enforced at API). | | 197.3 | Host lifecycle API: `startAll() throws`, `stopAll()`, `engine(for: Role) -> SynthesisEngine?`. Lifecycle calls held under host's `NSLock` so concurrent `startAll` / `stopAll` from different threads serialise. | | 197.4 | `host.renderConcurrent(jobs: [NRTJob]) -> AsyncThrowingStream`. Engine pool sized to `host.maxConcurrent`; streams results as each job finishes; supports task cancellation. | | 197.5 | `host.adopt(existing: SynthesisEngine) throws -> Role`. Escape hatch for wrapping externally-constructed engines (test fixtures, migration). Throws on duplicate role / device. | | 197.6 | New doc `docs/engine/multi-engine-host.md`: roles, lifecycle, binding rules, NRT pool example, AUHAL device exclusivity, drawbacks. Update `docs/engine/multi-core.md` "Multiple engines" section to point at it. Add `CLAUDE.md` doc-map row. | | 197.7 | Regression test extension: Phase 196's two-engine regression test gets a second variant using `EngineHost` instead of raw `SynthesisEngine()`. Both variants must pass — proves the uniformity contract (same engine type, same behaviour, same correctness under both entry points). | **Drawbacks acknowledged.** - New top-level public type = API-stability commitment. Ship under `@_spi(LyrebirdMultiEngine)` first if any signature uncertainty remains after 197.6 doc round. - God-object risk. Hard scope: lifecycle + ownership registry + NRT pool only. Routing stays in the bus system; scheduling stays per-engine; MIDI / OSC stay unchanged. - Host adoption optional → multi-engine bug reports without host context. Acceptable cost for keeping single-engine UX untouched. `MEMORY.md` triage note flags "ask whether the user has a `EngineHost`" as the first diagnostic question for any multi-engine crash report. **Exit criterion.** 1. Both regression-test variants (raw + host) green under `swift test --no-parallel`. 2. `host.renderConcurrent` NRT pool example in `multi-engine-host.md` runs end-to-end producing valid output files. 3. `/lyrebird_review` clean. **Commits on branch:** - `cf51840` Phase 197.1+2+3+5: EngineHost creation-owning facade - `f265ada` Phase 197.4: NRT pool — renderConcurrent AsyncThrowingStream - `40112fe` Phase 197.6+7: docs + host-variant regression test - `353afc1` Phase 197 review fixes: lock-nesting, snapshot-unlock-iterate, NRT input channels, doc + constant cleanup - `907dfeb` Phase 197 re-review fixes: lock-leak defer, stale docs, NRT safety - `be35b96` Phase 197 third-pass review fixes: class doc, magic literal, cancel-on-throw refill, NRT cancellation semantics - `8cfa768` Phase 197 fourth-pass review fix: doc-comment merging --- ### Phase 198 — Host Footgun Cleanup **Status.** Planned — follows directly from Phase 197 merge. **Goal.** Land the one real bug fix and the documentation / code-comment cleanups captured in `POST_197_FIXES.md` (repo root). The findings were all classified non-blocking during the five-cycle `/lyrebird_review` on phase-197 and explicitly deferred so Phase 197 could ship clean. Phase 198 discharges that follow-up. **Why now.** `POST_197_FIXES.md` is the only file at the repo root besides `CLAUDE.md` and `README*`. Wrapping it up into a normal phase and deleting the stub keeps the root tidy and prevents the follow-up from drifting indefinitely. **Scope.** | Item | Source ID | What ships | Code or doc? | |------|-----------|-----------|--------------| | 198.1 | F1 | `EngineHost.renderConcurrent` outer `catch` distinguishes `CancellationError` from genuine job throws — caller-initiated cancel now ends the stream cleanly via `continuation.finish()` (no throw). New regression test breaks the `for try await` early and asserts no error reaches the consumer. | Code + test | | 198.2 | F2 | New "Caveats and footguns" section in `docs/engine/multi-engine-host.md`. Subsection: NRT pool memory cost on high-core systems. Per-engine working-set table; mobile / shared-memory cap recommendation. | Doc | | 198.3 | F3 | Same Caveats section. Subsection: in-flight NRT jobs continue writing to disk after stream cancellation. Caller-side mitigation pattern (track pending output URLs; clean up post-cancel). | Doc | | 198.4 | F4 | Same Caveats section. Subsection: cross-job synth-instance sharing trips Phase 196 binding. Recommendation: construct fresh synth instances inside the `build` closure. Reference Phase 196's `bindRecoversFromStaleEnginePointer` known-limit doc. | Doc | | 198.5 | F5 | Same Caveats section. Subsection: cooperative thread pool starvation on long renders. User-side cap recommendation (`maxConcurrent: max(1, activeProcessorCount - 2)`); flag the host-side dispatch-onto-dedicated-queue redesign as deferred to Phase 199+. | Doc | | 198.6 | F6 | Strengthen the `.rtOutput(deviceID:)` doc on `EngineHostRole` to make the macOS-vs-iOS asymmetry explicit: on iOS the deviceID is host-bookkeeping only; AUHAL exclusivity is meaningless under `AVAudioSession`-routed RemoteIO. Recommend `.auxiliary(name:)` for non-output engines on iOS. | Doc | | 198.7 | F7 | New paragraph in `multi-engine-host.md` adoption section: `adopt(existing:role:)` TOCTOU window is benign — Swift ARC's strong-reference takeover at commit time makes the host's reference the lifeline if the original strong holder was racing `deinit`. | Doc | | 198.8 | F8 | Decide whether `.duplicateDevice(UInt32)` enum case stays, gains `@available(*, unavailable, message: "Reserved for forward compatibility; not produced by current code")`, or is dropped entirely. Re-evaluate against any in-flight role-design proposals at decision time. | Code | | 198.9 | F11 | Add `// TODO(phase-future)` code comment at the `SynthesisEngine.init` call inside `EngineHost.makeEngine` noting that the pre-validate-then-construct pattern depends on the init not throwing; if `EngineAddError.rebuildFailed` (reserved Phase 196 case) is ever actually produced by the ctor, the construction must be wrapped in `do/catch`. | Comment | | 198.10 | — | Delete `POST_197_FIXES.md` from repo root. The file's purpose ends when Phase 198 lands; the docs and code changes above carry the same content forward. | Cleanup | **Skipped after evaluation.** - F9 (synth construction cost paid by losing `makeEngine` race) — acceptable cost. Race rare, ctor cheap, ARC-collect clean. Reservation alternative re-evaluate only if benchmarking ever shows it matters. - F10 (`NRTJob.build` runs on background Task) — already documented in `NRTJob.build` doc comment. - Host-side `_executeJob` migration to a dedicated DispatchQueue (the Phase 199+ deferral mentioned in 198.5). Larger refactor — gather more user feedback on cooperative-pool impact before redesigning. **Exit criterion.** 1. `swift test --no-parallel` green; new F1 regression test passes. 2. `POST_197_FIXES.md` deleted; multi-engine-host.md Caveats section covers F2–F7 verbatim. 3. `/lyrebird_review` clean on first pass (the items are small and well-scoped; if the first pass flags new issues that's a signal Phase 198 grew unexpectedly). **Estimated scope.** Small — one code commit (F1 + test), one doc commit (F2–F7 Caveats section + F6 role-doc tightening), one cleanup commit (F8 decision + F9 comment + delete `POST_197_FIXES.md`). Two to three commits total; one session. --- **Commits on branch:** - `385dca9` Phase 198.1 (F1): CancellationError clean-finish on caller cancel - `d90197a` Phase 198.2-198.7: multi-engine-host.md Caveats section + role doc - `8fb88e0` Phase 198.8-198.10: drop dead .duplicateDevice case, add F11 TODO, delete POST_197_FIXES.md - `216650a` Phase 198 review fix: Task.isCancelled guard for build-thrown CancellationError + regression test - `84961ae` Phase 198 re-review nits: rethrow caught CancellationError, robust >= 1 result count, onTermination comment