Mirror of Lyrebird dev HEAD (9f791c7c) minus maintainer-only paths. Patch release: fixes the allpass fractional-delay click (DelayLine/CombFilter/AllpassFilter/ DelayLineFeedback under a modulated delay) and lands the internal code-quality consolidation pass (~160 deduped sites + shared base classes/helpers, bit-identical output). No public API removed or changed. See RELEASES.md. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
43 KiB
Lyrebird — Claude Context
Native macOS/iOS audio synthesis framework in Swift. Users implement Generator and Synthesizer protocols; Lyrebird engine handles Core Audio I/O and signal-graph evaluation. No separate scripting language.
Pick the Right Agent First
Eight agents live in ~/.claude/agents/ (maintainer's source of truth) and are mirrored into the repo at .claude/agents/ (auto-discovered) and claude/agents/ (installer source). Invoked automatically when task description matches; you can also invoke explicitly.
| Agent | Use when |
|---|---|
lyrebird_demo_agent |
Any demo work — CLI demos, macOS GUI, iOS GUI, NoteController, Xcode project edits. |
lyrebird_generator_agent |
Any new Generator — oscillator, filter, effect, noise, math operator, bus I/O. |
lyrebird_engine_agent |
Engine internals — SynthesisEngine, CoreAudioDriver/iOSAudioDriver, AUHAL, SPSCQueue, ScheduledEvent, Group/ParallelGroup, RT thread architecture. |
lyrebird_language_agent |
Non-RT language side — SynthesizerBase, @LiveParam, ParameterNode, LyrebirdRoutine/Task/Clock, Pattern, MIDI, OSC, NRT, Score, demand pattern usage. |
lyrebird_swiftui_agent |
LyrebirdUI module — ParameterKnob/Slider/XY/Button/Label, scope/envelope views, platform-conditional code. (@UIParam/UIParamNode themselves live in core Lyrebird.) |
lyrebird_architect_agent |
Cross-cutting analysis — duplicate patterns, API consistency, SC naming alignment, refactor planning. No implementation. |
lyrebird_review_agent |
Pre-merge review (via /lyrebird_review) — RT safety, bus rules, protocol correctness, helper usage, test coverage. |
pr_review_agent |
General pre-PR review — bugs, security, code smells. Broader scope than lyrebird_review. |
Repo mirror sync (after editing working copies in ~/.claude/):
bash scripts/sync-claude-from-working.sh # dry-run
bash scripts/sync-claude-from-working.sh --apply
bash scripts/sync-claude-from-working.sh --check # CI: exit 1 on drift
Edit only in ~/.claude/. Script keeps .claude/ and claude/ in sync. New agents/skills must be added to the repo manually the first time, then this script keeps them in sync.
Pre-commit hook (one-time setup per clone — blocks commits with stale repo mirror):
git config core.hooksPath .githooks
The .githooks/pre-commit hook calls --check. Skips silently when ~/.claude/agents/ is absent (contributors without working copies are not blocked). Bypass for one commit with git commit --no-verify.
Repo Guard Scripts
These guards catch classes of regression that swift build / swift test structurally cannot. Both are manual/CI (too slow for pre-commit). Run before a release or a merge that touches their surface.
| Script | Guards | Run when |
|---|---|---|
bash scripts/check-swift6-consumer.sh |
The zero-annotation consumer guarantee — builds RegressionFixtures/MainActorConsumer under .swiftLanguageMode(.v6) + -default-isolation MainActor. The main package does not build under that flag, so the test suite cannot catch an isolation regression. |
Any change to SynthesizerBase / Synthesizer actor isolation. Non-negotiable: swift test passing is not evidence here. |
bash scripts/check-docc.sh |
New DocC warnings — broken symbol links, ambiguous refs, article/symbol collisions. DocC links pin a symbol's full signature, so adding one parameter silently breaks every link to it. Nothing else checks this. | Any change to a public signature, or edits to .docc / doc comments. |
bash scripts/check-doc-impact.sh [range] |
Reports (never fails) which docs a diff's public-API changes may have invalidated. Doc rot is usually caused by an API change, and a diff-only read cannot find the stale references — they live in files the diff never touches. Run by /lyrebird_review step 2b; suppresses refs the compile guard already covers. |
Any change to a public signature. |
bash scripts/check-doc-snippets.sh |
Doc examples that stop compiling. swift build never sees a code fence and check-docc.sh only validates links, so examples rot silently — engine.add became throwing and 11 examples kept calling it without try; LyrebirdFloat was deleted and 75 references outlived it. Both are type errors, so the fences are typechecked against the real API. |
Any change to a public signature, or edits to .docc / doc comments. |
check-docc.sh is a ratchet: it fails on warnings absent from scripts/docc-warnings-baseline.txt. That baseline is now empty — the catalog is at zero warnings — so in practice any new warning fails the build. Keep it that way; the baseline may only shrink. (--strict asserts zero explicitly and is equivalent while the baseline is empty. --update-baseline exists for the rare deliberate exception — prefer fixing the link.)
Golden values need a test, not a guard. A typecheck proves an example still compiles; it cannot see a documented result drift. Where a doc asserts concrete output (// → 0.744, 0.046, …), pin it with a test — DistributionKindGoldenValueTests and _DocTheorySnippetCheckTests are the two instances. This is not optional pedantry: three of the four DistributionKind sequences had silently drifted, and their fences also passed a seed: argument to a type that has no such parameter.
check-doc-snippets.sh checks the fences recorded in scripts/doc-snippets-manifest.txt (currently 426 of 1458). That set is produced by asking the compiler which fences compile — --classify — never by hand-annotating fences. A fence that compiles under no preamble self-excludes, which is how iOS-only examples, Package.swift snippets and pseudo-code drop out with no skip list. Coverage is therefore partial by construction: a fragment like try engine.add(MySynth()), which needs both an engine and a MySynth in scope, is not checked. The fix for an important uncovered example is to make it self-contained in the doc — which is better documentation anyway — not to grow the preamble table. Re-run --classify after adding examples or deliberately changing what is checkable.
Task → Doc Map
Engine / RT core
- Engine init, audio driver, render pass →
docs/engine/synthesis-engine.md,docs/engine/core-audio-driver.md,docs/signal-flow/signal-flow.md - Linux live audio (
ALSAAudioDriver,makeDefaultAudioDriver(), libasound build requirement) →docs/engine/alsa-audio-driver.md - Portable WAV read/write off Apple (
WavFileWriter/WavFileReader, header layout,WavFileError) →docs/engine/portable-wav-codec.md - Bus memory / In / Out →
docs/engine/bus-system.md - Sample-accurate scheduling →
docs/engine/scheduling.md - ParallelGroup / multi-core →
docs/engine/multi-core.md - Multi-engine host (
EngineHost) + NRT batch render pool →docs/engine/multi-engine-host.md
Generators
- Generator protocol + DemandGenerator →
docs/protocols/generator.md - Implementing a new Generator →
docs/protocols/writing-generators.md(§13 = shared helpers) - Inline custom per-sample DSP / single-sample feedback without a new Generator type (
SampleLoop— pre-allocated output, typedinoutfeedback state, channel inference + broadcast) →Sources/Lyrebird/Generators/Core/SampleLoop.swift - Built-in generator catalog →
docs/stdlib/generators.md - Multi-channel /
outputChannelCount/ channel-aware operators →docs/stdlib/multichannel.md - Musical math (MIDI↔Hz, dB, intervals) →
docs/stdlib/generators.md(LyrebirdMusicMath section) - Physical models (BowedString, Flute, Clarinet, ScannedSynthesizer) →
Sources/Lyrebird/Lyrebird.docc/Generators/PhysicalModels.md,Sources/Lyrebird/Lyrebird.docc/Generators/ScannedSynthesis.md - Oversampling primitives (
HalfbandUpsampler/HalfbandDownsampler2×/4×) →Sources/Lyrebird/Lyrebird.docc/Generators/Oversampling.md - Spectral processors / FFT chain →
docs/stdlib/spectral.md - Extension SDK / out-of-tree generator packages (SPI surface, versioning) →
docs/protocols/extension-sdk.md
Synthesizer / language side
- Synthesizer protocol →
docs/protocols/synthesizer.md - Node tree / Group nesting / bus routing →
docs/protocols/node-tree.md - Routines / tasks / clock / MIDI / OSC →
docs/tooling/routine-task.md Pattern<T>factory catalog (sequence, series, geometric, uniformRandom, brownian, gaussian, cauchy, beta, shuffle, nonRepeatingRandom, weightedRandom, closure, repeating, limit, drop, stutter, switching, concatenate, roundRobin, tuple, interleave, map, filter, reject, accumulate, difference, wrap, clip, round, smooth) →docs/tooling/routine-task.md(§ Pattern Factory Reference) +Sources/Lyrebird/Lyrebird.docc/RoutineTask.md- MIDI clock sync (
MIDIClockFollower) →docs/tooling/midi-clock-sync.md - Linux MIDI (
MIDIvia ALSA sequencer —MIDI/ALSAMIDI.swift,ALSASeqMIDIEventmapping; needs CALSA/libasound) →Sources/Lyrebird/MIDI/ALSAMIDI.swift - Linux OSC (
OSCClient/OSCServerPOSIX-UDP transport off Apple,OSCServerError; codec unchanged) →Sources/Lyrebird/OSC/OSCServer.swift - Non-RT parameter value sources /
ValueComputable/ValueComputableClosure(consumed byLyrebirdProcessparameters) →Sources/Lyrebird/Lyrebird.docc/ValueComputable.md - TemporalStream / language-side value generation →
Sources/Lyrebird/Lyrebird.docc/TemporalDemand.md - Polyphonic voice pool / step sequencer →
docs/tooling/routine-task.md - Score / ScorePlayer / SMF / MusicXML →
Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md - Pitch / scale theory toolkit (spelling-aware
Interval/Scale/PitchCollection/ 12-tone rows, diatonic-vs-chromatic transposition, scale mapping; → notation + Hz/seconds for synthesis) →docs/stdlib/theory.md(types underSources/Lyrebird/Score/Theory/) - Performance event sequencing /
LyrebirdProcess/LyrebirdEventList→Sources/Lyrebird/Lyrebird.docc/ProcessSystem.md - NRT / offline render →
docs/tooling/nrt-guide.md
Tooling / project
- CLI / REPL / hot-swap →
docs/tooling/cli-guide.md,docs/tooling/repl.md - Project scaffolding / package targets →
docs/tooling/project-system.md,docs/tooling/targets.md - Dev workflow / phase branches / build →
docs/tooling/workflow.md - Linux user setup (toolchain, VS Code, build/test, run a sample) →
docs/linux-getting-started.md - Xcode project templates →
docs/tooling/xcode-templates.md - AUv3 plugin internals (
LyrebirdAudioUnit,LyrebirdAUVoicePoolBinding,AUInput, preset codable, parameter slots) →Sources/Lyrebird/Lyrebird.docc/AUv3.md
UI
- LyrebirdUI / parameter binding →
docs/ui/gui-system.md - Live-compile scratchpad (
LyrebirdScratchView,LyrebirdLiveCompile,LyrebirdLiveCompileUI) →LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md. Lives in the separateLiveCompile/SwiftPM sub-package (Phase 167) — cross-package dependency forceslibLyrebirdLiveCompile.dylibto dynamic-linklibLyrebird.dylibinstead of statically embedding it, eliminating the ObjC class double-registration crash that aborted fullswift testruns in the single-package layout. Build sub-package with(cd LiveCompile && swift build)/(cd LiveCompile && swift test). - Interpreted graph-DSL (
LyrebirdGraphDSLtarget — cross-platform, no swiftc) + its code-gen (Tools/DSLRegistryGen, separate SwiftPM package so swift-syntax stays out of the main build; runscripts/generate-dsl-registry.sh, committed output,--checkdrift guard) →docs/tooling/graph-dsl-design.md. Registry (Sources/LyrebirdGraphDSL/Generated/GeneratedDSLRegistry.swift) is generated from generator init signatures — regenerate + commit after changing a public generator init. In progress (LC-8); language/parser not yet built.
Diagnostics
- User-visible messages (
LyrebirdMessage,LyrebirdMessageCenter,LyrebirdMessageView/ Banner) + node-tree mirror (NodeTreeMirror,NodeTreeSnapshot,LyrebirdNodeTreeView) →docs/diagnostics-guide.md - Developer-side debugging (per-instance RT debug tap
SynthesizerBase.debugTap,GeneratorBase.debugTag, LLDB breakpoint recipes for inspecting a live voice / generator) →Sources/Lyrebird/Lyrebird.docc/Debugging.md
Planning
- What to build next →
docs/00-working-order.md - Completed phases →
docs/01-completed-working-order.md
Hard Constraints
One-liners. Detail and rationale lives in linked docs.
Platform / build
- macOS 15+ / iOS 18+ / swift-tools 6.0 —
Synchronization.Atomicrequires macOS 15. - No AVAudioEngine. Use
kAudioUnitSubType_HALOutput(full duplex AUHAL) on macOS, RemoteIO on iOS, blockingsnd_pcm_writeion a dedicated thread (ALSA) on Linux. - Never name a concrete driver in code that is meant to build on more than one platform — call
makeDefaultAudioDriver(). Which drivers exist depends on how Lyrebird itself was built (a Linux build without libasound, or one cross-compiled from macOS, has noALSAAudioDriver), so a consumer-side#ifis a guess. Code already locked to one platform is exempt and should name its driver directly — e.g. the AppKit-onlyui-demoscaffold template emitsCoreAudioDriver(). - No Xcode Playgrounds. All tests use Swift Testing (
@Test,#expect,@Suite).
RT thread (render callback) — docs/engine/synthesis-engine.md, docs/protocols/writing-generators.md
- No allocation, locks, blocking,
print,Stringconstruction, oris/as?runtime type checks. Classify inputs atinit. - No
!force unwraps. Useguard let,if let,?? fallback, orthrows. - All bus memory pre-allocated at
start(). Never resized. - Generator output buffers pre-allocated to
lyrebirdDefaultResultBufferSize(512).SynthesisEngine.initenforcesblockSize ≤ 512. Every_computeSamplesopens with_checkCount(count)(inherited fromGeneratorBase). No grow path. - No shared mutable state between Synthesizer instances — graph-copy-per-instance.
Module layering
- No
SwiftUI,AppKit, orUIKitimports in coreLyrebirdmodule. UI lives inLyrebirdUIonly. - Platform-specific input sources (e.g. AppKit
NSEventmouse monitors) live inLyrebirdUIand conform to a core protocol/base class (e.g.MouseInputBridge) that core Generators read from. Install via the registry (e.g.MouseInput.install(_:)) at app startup.
Generator protocol — docs/protocols/writing-generators.md
GeneratorBaseis the required base class. Provides_segmentSerial,_cachedResult,_subBlockBuffer, and_result(mono, pre-allocated tolyrebirdDefaultResultBufferSize, zero-filled). Never redeclare these as stored properties.- Mono generators inherit
_resultdirectly — no declaration, no init line. Multi-row generators callsuper.init(channels: N)from their designatedinitto allocate N rows in one shot. Dynamic channel counts passchannels: outChannelscomputed ininit. - Open every
_computeSampleswith_checkCount(count)— the inherited helper that traps ifcount > _result[0].count. Replaces the long-formprecondition(...)boilerplate. floatValueis provided by theAudioGeneratorprotocol extension (returnscalculatedSamples(...).first?.first ?? 0). Do not redeclare inAudioGeneratorconformers unless you need different scalar semantics (e.g.ConstantGeneratorInput).ControlGeneratorconformers must provide their ownfloatValuereturning the block target.- Buffer factories
makeResultBuffer(channels:)/makeSampleBuffer(_:)(inResultBuffer.swift) replace[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)literals when a generator owns a separately-allocated scratch buffer. - Every sub-blocking
ControlGenerator.Control.initcalls_setupSubBlockBuffer()(or_setupSubBlockBuffer(channels: N)) aftersuper.init(). Never call on the RT thread. Exception:BlockRateControlGeneratorconformers never sub-block and omit the call (see the bypass bullet below). Control._computeSamplesusescount(notgraph.engine.blockSize) for phase/state advancement —_computeSamplesmay run N times per audio block in sub-block mode.- Control generators with per-audio-block state (bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers, analysers) must advance once per audio block, bypassing the sub-block loop. Conform to
BlockRateControlGenerator(marker protocol inGeneratorCore/BlockRateControlGenerator.swift) — itscalculatedSamplesdefault routes to the block-rate gateway and the conformer skips_setupSubBlockBuffer(). This replaced the old per-generatorcalculatedSamples { _calculatedSamplesBlockRate(...) }forwarder. A true sub-blocking Control must NOT conform. Seedocs/protocols/writing-generators.md§15 for the decision rule. - Multi-row generators (any with
_result.count > 1) overridevar outputChannelCount: Int { get }to return the fixed channel count set atinit.GeneratorBasedefaults to1. Missing override silently mono-izes the generator under+ - * /operators. Channel count must be derivable from aletat init — never runtime-mutable. Detail + cases:docs/stdlib/multichannel.md. mul:/add:parameters are channel-aware: mono input broadcasts; equal-N applies element-wise; mismatched multi-row precondition-traps. Same policy asBinaryOpGenerator. Detail:docs/stdlib/multichannel.md.
File Organisation
Every new .swift file starts with the MIT SPDX header. First five lines, before any import:
// <FileName>.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
(Blank line after the header, then the file body.) Applies to all source under Sources/, Tests/, Demos/, and LiveCompile/. Exception: Xcode file-template resources at Sources/LyrebirdCLI/Resources/XcodeTemplates/*.xctemplate/___FILEBASENAME___.swift — these keep only Xcode's injected //___FILEHEADER___ (the header belongs to whoever instantiates the template, not to Lyrebird). Likewise, scaffolder/exporter code that emits user-facing Swift source must not bake the Lyrebird copyright into the generated string. Review-blocking: a new tracked .swift without the header is a violation.
One public type per Swift source file. Generator enums, classes, protocols, support types each in their own file.
- Generator family per file (
OscSawtooth.swift,LFSquare.swift,Clip.swift, etc.). - Shared file-scope helpers go in
*Helpers.swift(e.g.OscBandLimitedHelpers.swift). Accessinternal(no modifier) so visible across files. - Type-coupled support types (error enums, format enums) each in their own file (e.g.
DiskInError.swift,DiskOutFormat.swift). - One
@Suiteper test file, named<TypeName>Tests.swift.
Never drop new files at Sources/Lyrebird/ root. Every new .swift file goes into a subfolder grouped by function. Existing top-level subfolders (alphabetical):
AUv3/ AudioDrivers/ Buffers/ Buses/ Capture/ Diagnostics/ Distributions/ Engine/ Envelopes/ External/ GeneratorCore/ Generators/ Kinds/ MIDI/ Math/ NodeTree/ OSC/ Oversampling/ Parameters/ Patterns/ Process/ Scheduling/ Score/ Spectral/ Synthesizer/ TemporalStream/ Trigger/ Utilities/ ValueCompute/ Voices/
Rule:
- Place into an existing subfolder if function matches (
Generators/= concreteGeneratorimplementations,GeneratorCore/= protocol layer +MulAdd,Engine/= RT core,Buses/= bus memory + allocation,NodeTree/=Group/ParallelGroup/NodePosition/PreparedNode,Math/= constants + numeric utilities,Kinds/= cross-cutting enum descriptors, etc.). - If no folder fits, propose a new subfolder in the PR description (one-line rationale, list of files going in) rather than landing files at root. Reviewers accept or redirect.
- Subfolder may have further nesting when a family is large (e.g.
Generators/BufferIO/,TemporalStream/Algorithms/).
Loose .swift at Sources/Lyrebird/ root is a review-blocking violation. Sources/Lyrebird/Lyrebird.docc/ is the only non-folder exception at root.
Review agents flag any new file introducing a second unrelated public type without explicit prior approval, and flag any new .swift landed at Sources/Lyrebird/ root.
Interface Conventions
Filter resonance parameter naming:
q:— used for filters parameterised by a quality factor (RBJ cookbook, SVF, Butterworth cascade, resonator banks).q = 1/sqrt(2) ≈ 0.707is Butterworth (no peak); higher values produce sharper peaks. Range typically[0.1, ~100].resonance:— used for filters parameterised by a raw feedback factor (Moog ladder and other emulation filters). Range typically[0.0, ~1.0]where1.0is the self-oscillation threshold. Engine may clamp slightly above 1.0 to avoid runaway.
Both are documented at the parameter level; the distinction is principled (different DSP families parameterise resonance differently), and call-site choice should reflect the underlying model rather than a uniform name. New filters route to whichever parameter the underlying algorithm uses naturally.
engine.add / engine.schedule are throwing (Phase 196). Replaced the legacy Bool-returning signatures with structured throws on all four add/schedule entry points:
public func add(_ synth: any Synthesizer) throws
public func add(_ synth: any Synthesizer, position: NodePosition) throws
public func schedule(_ synth: any Synthesizer, at time: SampleTime) throws
public func schedule(_ synth: any Synthesizer, after seconds: Double) throws
Throws EngineAddError: .boundToOtherEngine(current:prior:) (cross-engine), .doubleAdd(engine:) (same-engine re-add), .pendingQueueFull, .rebuildFailed(underlying:). Both UUIDs surface in cross-engine errors via SynthesisEngine.identifier: UUID. Internal _bind(to:) throws / _unbind(from:) on SynthesizerBase back the precondition via single-shot atomic CAS. LyrebirdBuffer has opt-in two-tier binding (bindExclusive / bindReadOnly) for cross-engine sharing — see docs/engine/multi-core.md § Object ownership rules.
engine.remove(_:) and engine.remove(_:at:) still return Bool — they unbind synchronously on successful enqueue. Documented constraint: allow one processBlock between remove and re-add of the same instance.
engine.stop() also unbinds every non-persistent synth it was hosting (including ones nested inside drained Group subtrees) as part of its node-tree teardown, so a stop-then-re-add of the same instance — to the same engine or a different one — needs no such wait; the RT thread is already halted before stop()'s unbind pass runs. See docs/engine/synthesis-engine.md § stop() node-tree teardown contract.
Call-site pattern: every engine.add invocation needs try. In non-throwing contexts (closures dispatched to DispatchQueue.main.async, non-throwing methods), wrap in do { try engine.add(synth) } catch { print("[Lyrebird] engine.add failed: \(error)") } — the existing LyrebirdRoutineContext / LyrebirdMessageContext / LyrebirdProcessContext adapters use this pattern.
Swift Code Style Rules
Hard rules. Review agents flag violations.
No phase numbers in code or docs
Never write phase numbers (Phase 228, Phase 228c, phase-224, pre-Phase-209c, // Phase 216:, (Phase 201), — Phase 214) in source comments, doc-comments (///), .docc markdown, @Suite/@Test display strings, or test function / type / file names. Phase numbers are meaningless to external readers — they belong only in planning docs (docs/00-working-order.md, docs/01-completed-working-order.md), commit messages, and MEMORY.md/phase history. Describe the behavior or reason instead:
// WRONG
// Phase 216: emit a tempo direction for this measure when a TempoChange targets it.
let cap = ... // Phase 228c
/// > Note: Phase 224 wires this as model state.
@Suite("EngineHost (Phase 197)")
// RIGHT
// Emit a tempo direction for this measure when a TempoChange targets it.
let cap = ...
/// > Note: this is model state.
@Suite("EngineHost")
Exception: the DSP term "phase" that is NOT a planning reference — oscillator phase, phase accumulator, phase offset, _phase, initPhase, phase modulation, "Phase 0.25 in an 8-sample table" — is a real audio term, never touch it. The rule targets Phase <number> planning tags only.
No force unwraps
Never ! on optionals or try!. Hotspots: UnsafeBufferPointer.baseAddress in Accelerate calls, Array.first!/last! on output channels, try! in test helpers, dict[key]!.
// WRONG
vDSP_vsmulD(buf.baseAddress!, 1, &gain, out.baseAddress!, 1, n)
// RIGHT
buf.withUnsafeMutableBufferPointer { b in
guard let base = b.baseAddress else { return }
vDSP_vsmulD(base, 1, &gain, outBase, 1, n)
}
No magic numbers
Every non-trivial literal needs a named let. Exempt: 0, 1, -1, 2 when arithmetic meaning is obvious. Hotspots: queue capacities, trig scale factors (1.0/sqrt(2.0), 0.5*.pi), vDSP delay-state sizes, normalisation/gain constants.
// WRONG: SPSCQueue<OpaquePointer>(capacity: 32)
// RIGHT: let killQueueCapacity = 32; SPSCQueue<OpaquePointer>(capacity: killQueueCapacity)
Doc comments on public Generator init parameters
Every new public Generator type documents init parameters in two places so Xcode Quick Help works from both type name and call site:
- Class-level
/// - Parameters:block on theAudio/Controlclass. - Init-level
/// - Parameters:block on theinititself.
Each entry states: what it does, unit (Hz / dB / seconds / ratio / [0, 1] / frames), valid range or clamping, default when non-obvious.
/// Audio-rate lowpass filter.
///
/// - Parameters:
/// - input: Signal to filter.
/// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist.
/// - q: Resonance factor. `0.707` = Butterworth (no peak). Defaults to `0.707`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Audio: _Base, AudioGenerator {
/// - Parameters:
/// - input: Signal to filter.
/// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist.
/// - q: Resonance factor. `0.707` = Butterworth (no peak). Defaults to `0.707`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public init(input: any ValidGeneratorInput, freq: any ValidGeneratorInput,
q: any ValidGeneratorInput = 0.707,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0) { … }
}
Exception: unary/binary math operators where the class-level formula makes every param self-evident (Abs, Sign, Floor, etc.) only need /// - Parameter signal: Input signal. at both levels.
Multi-line declarations
Multi-line format required when ≥ 2 type aliases or ≥ 2 init parameters:
// GeneratorEnum
extension Wrap: GeneratorEnum {
public typealias AudioType = Wrap.Audio
public typealias ControlType = Wrap.Control
}
// Init with ≥ 2 params
public init(
input: any ValidGeneratorInput,
freq: any ValidGeneratorInput,
q: any ValidGeneratorInput,
mul: any ValidGeneratorInput = 1.0
) { … }
// Single-param exception
public init(_ signal: any ValidGeneratorInput) { … }
Explicit type annotations on bindings
Every let / var binding — stored properties on classes/structs/enums, locals inside functions, and for x in … loops — must carry an explicit : Type annotation. Inferred bindings (let x = expr) are a review-blocking violation in new and modified code.
// WRONG
let buf = LyrebirdBuffer(count: tableSize)
let intPhase = Int(phase)
let frac = phase - Double(intPhase)
for i in 0..<count { ... }
// RIGHT
let buf: LyrebirdBuffer = LyrebirdBuffer(count: tableSize)
let intPhase: Int = Int(phase)
let frac: Double = phase - Double(intPhase)
for i: Int in 0..<count { ... }
Rationale: Xcode's expression type-checker is markedly slower on long generic-heavy synth-graph expressions when intermediate locals are inferred; annotating each binding short-circuits a large slice of that work. Readability win for human readers too — the reader doesn't need to chase the inference graph to learn the type.
Exceptions (Swift grammar forbids : T here):
- Closure-header parameters —
{ x in … }. Adding a type annotation requires inserting parens ({ (x: T) in … }), which is awkward and often hurts readability. Leave closure params inferred unless the type is genuinely unclear from context. - Tuple-pattern destructures —
let (a, b) = tuple. Tuple patterns don't accept inline annotations on their elements. - Pattern-matching contexts —
catch let err as Foo,case let .foo(x). The binding is a pattern variable, not a value binding.
Tool: Tools/AnnotateBindings/annotate_bindings.py drives sourcekit-lsp to fill in annotations on any new or refactored file. Phase 154 swept the entire pre-existing codebase; every new file is expected to carry annotations from the start.
Shared RT-Safe Helpers — Must Use
Module-level helpers exist to eliminate repeated boilerplate; inlining any of them in a new generator is a review violation:
-
_checkCount(_:)—GeneratorBasemethod; first line of every_computeSamples -
BlockRateControlGenerator—GeneratorCore/BlockRateControlGenerator.swift; marker protocol aControlGeneratorconforms to when its state must advance once per audio block (IIR filters, bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers, analysers). Supplies the block-ratecalculatedSamplesgateway for free and lets the conformer skip_setupSubBlockBuffer(). The standard way to bypass sub-blocking — superseded the per-generator_calculatedSamplesBlockRateforwarder. A true sub-blocker must NOT conform. -
_calculatedSamplesBlockRate(graph:count:)—Generatorextension; the block-rate gateway theBlockRateControlGeneratordefault calls. Call it directly only in the rare case a generator needs the bypass but cannot conform to the marker -
OscillatorBase—Generators/Oscillators/OscillatorBase.swift; extend instead of declaring_freqInput/_freqIsGenerator/_phase/_mulAddinline. Designatedinit(freq:phase:mul:add:)performs canonical phase normalisation. Used by LF / band-limited oscillators (LFSawtooth, LFSquare, LFTriangle, LFDutyCycle, OscSawtooth, OscSquare, OscTriangle, OscDutyCycle) andImpulse(post-super-init writes_phase = 1.0 - initPhasesoinitPhase == 0fires at sample 0). Table-lookup oscillators (OscSin,OscTable) intentionally excluded — they store_phasein table-index units to avoid a per-sample multiply in the inner loop. -
NoiseBase—Generators/Noise/NoiseBase.swift; extend instead of declaringrngState: UInt64+_mulAdd: MulAddSpecinline. Designatedinit(initialRngState:mul:add:). Used by 23 noise generators across 3 tiers (parameterless, extra-state, distribution-parameterised). LF noise variants and Crackle intentionally excluded. -
UnaryMathBase—Generators/Math/UnaryMathBase.swift; extend instead of declaringinputSource+_mulAddinline. Designatedinit(_:mul:add:). The shared_Basefor the single-input math operators — each ispublic class _Base: UnaryMathBase {}, withAudio/Controlsupplying only the per-operator kernel. Used by 14 operators (Abs, Ceil, Floor, Round, Sign, Sqrt, Log, Exp, Sin, Cos, Tan, Tanh, Reciprocal, DbAmp). Multi-input math (Max, Min, Ring1–4, ExpExp, ExpLin, …) keeps its own_Base. -
SpectralFeatureControlBase—Generators/Spectral/SpectralFeatureControlBase.swift; shared base for the control-rate spectral feature analysers (SpectralCentroid, SpectralSpread, SpectralFlatness, SpectralEntropy, SpectralFlux, SpectralRolloff). Owns the analysis handle, spectral buffer, MulAddSpec, ramp state, sub-block bypass, and the drive-analysis →computeFeature→ ramp body; eachControlsubclass adds only its own params/state and overridescomputeFeature(graph:count:) -> Double. -
runRBJBiquadBlock(...)—Generators/Filters/RBJBiquadHelpers.swift; module-internal helper holding the shared_computeSamplesbody for(freq, q)RBJ biquad filters (LP / HP / AP / Notch). Concrete filters pass the coefficient formula as a closure. -
runTwoPoleResonatorScalarBlock(input:into:y1:y2:b0:na1:na2:count:)/runTwoPoleResonatorInterpolatedBlock(input:into:y1:y2:start:end:count:)—Generators/Filters/FilterHelpers.swift; shared per-sample loop body for two-pole resonator filters (y[n] = b0·x[n] − na1·y[n−1] − na2·y[n−2]). Consumed byRingingFilter+ResonatingFilter— concrete filter passes its coefficient-computation function and one-line helper calls. -
sampleOrFallback(_:scalar:at:)—Generators/Filters/FilterHelpers.swift; per-sample coefficient lookup with zero-fallback past block end. Replaces thexxxSamples.map { i < $0.count ? $0[i] : 0 } ?? scalarXpattern. Used bySecondOrderSection(5 coefficient slots) +FirstOrderSection(3 slots).Lag/Decayfamily use a different end-clamp +lagCoeffwrapping convention; helper doesn't apply there. -
onePoleLowPassStep(state:x:b1:comp:)—Generators/Filters/FilterHelpers.swift;y = b1·state + comp·x, mutates state, returns y.comp = 1 − b1precomputed by caller. Used byLag.Audio/Lag2.Audio(cascade two) /LagUpDown.Audio/Lag2UpDown.Audio(after asymmetric coefficient selection). -
leakyIntegratorStep(state:x:b1:)—Generators/Filters/FilterHelpers.swift;y = x + b1·state, mutates state, returns y. SCDecay/Decay2convention (input not attenuated by1 − b1). Used byDecay.Audio+Decay2.Audio(cascade two for attack/decay difference). -
attackReleaseSmoother(state:target:attackCoeff:attackComp:releaseCoeff:releaseComp:direction:)—Generators/Dynamics/DynamicsHelpers.swift; asymmetric attack/release smoother step with direction selector (.risingfor envelope followers;.fallingfor compressor/expander gain-target smoothing). Used byAmplitudeFollower.Audio(.rising) +Compressor.Audio/Expander.Audio(.falling). -
sampleOrZero(_ p: UnsafePointer<Double>, _ i: Int, _ n: Int) -> Double—GeneratorCore/HotLoopHelpers.swift;i < n ? p[i] : 0. Replaces the per-sample(i < n) ? srcP[i] : 0boilerplate inside hot loops that read an input row via raw pointer. Module-internal helper used across Filters (Lag / Lag2 / LagUpDown / Lag2UpDown / LeakDC / Decay / Decay2 / SecondOrderSection / FirstOrderSection / RBJBiquad / CombFilter / AllpassFilter) and Delays (DelayLine / DelayLineFeedback).@_spi(LyrebirdExtensions) publicso out-of-tree generators can adopt the same helper. -
resolveGeneratorOrScalar(_:isGenerator:graph:count:) -> (samples: [Double]?, scalar: Double)—GeneratorCore/InputResolutionHelpers.swift; block-rate input resolution. Replaces the 8-lineif _xxxIsGenerator { xxxSamples = ...; scalarXxx = 0 } else { xxxSamples = nil; scalarXxx = ... }boilerplate at the top of any_computeSamplesthat pulls multipleValidGeneratorInputparameters. Used across many multi-input generators (Flute,Clarinet,KarplusStrong/GatedKarplusStrong,BowedString,PlayBuffer,SpatialDistance,MuTronIII,Hilbert, the spatial panners, and more). Tuple destructure at the call site is the CLAUDE.md-documented exception to the explicit-type-annotation rule.@inline(__always) @_spi(LyrebirdExtensions) public. -
applySpatialDistanceFiltering(...)—Generators/Panning/SpatialDistanceHelpers.swift; module-internal shared per-sample pipeline forPanXYDistance(Cartesian) andPanAzDistance(polar). Both callers pre-compute(panX, panY)and the Chebyshev distance metricposDfrom their respective coordinate frames; the rest of the pipeline (amplitude attenuation, cutoff-coefficient caching, Doppler read-rate, delay-line write/read/wrap/clamp, one-pole lowpass, equal-power 4-corner pan) is identical and lives here. Mutates delay-line + one-pole state in place viainout.@inline(__always) internal. -
plateReverbInputDiffusion(...)/plateReverbTankHalf(...)—Generators/Reverb/PlateReverbHelpers.swift; PlateReverb-specific per-sample sub-blocks.plateReverbInputDiffusionruns the 4-stage cascaded Schroeder allpass network on a single sample.plateReverbTankHalfruns one half of the figure-of-eight tank (modulated allpass → delay 1 → damping LP → decay scale → allpass 2 → delay 2 write). Consumed twice per sample byPlateReverb._computeSamples(left and right halves). All state mutatedinout.@inline(__always) internal. -
gverbReadEarlyTaps(...)/gverbFDNDamperCascade(...)—Generators/Reverb/GVerbHelpers.swift; GVerb-specific per-sample sub-blocks.gverbReadEarlyTapsreads four pre-FDN early-reflection taps with branchless wrap + per-tap gains and returns a 4-tuple.gverbFDNDamperCascadeapplies the FDN one-pole LP damper cascadey = x*(1-damp) + prev*dampto four raw FDN reads, mutatesfdnDampState[0..3]with denormal flush, returns 4-tuple. Both@inline(__always) internal. -
makeResultBuffer(channels:)/makeSampleBuffer(_:)—ResultBuffer.swift; replaces the[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)literal -
_mulAdd.applyIfNeeded(to:graph:count:) -
fillRampedResult(into:from:to:mulAdd:graph:count:) -
fillScalarRampedResult(into:previousOutputValue:target:count:)—MulAdd.swift; canonical body of everyMath.Control_computeSamplesramp (28 generators). Distinct fromfillRampedResultbecause the caller has pre-foldedmul/addinto the scalartarget— the helper writes the ramp without re-applyingMulAddSpec.apply. -
fillHeldResult(into:value:previousOutputValue:mulAdd:graph:count:)—MulAdd.swift; held-constant counterpart offillScalarRampedResult— fills a block with one value, applies mul/add, setspreviousOutputValueto the last sample. For block-rateControlpaths whose output holds one value (one-pole smoothersLag/Decay/LeakDC/Slew/Formlet, block-constant analysisZeroCrossing/Slope/RunningMin/Max, trigger/counter latchesTrig/Schmidt/PulseCount/Stepper; 20 sites). No-op atcount == 0. NOT for per-sample-varying output. -
MulAddSpec.applyScalar(_:graph:)—MulAdd.swift; folds scalarmul/addinto one block-constanttarget(returns it unchanged on identity). The scalar counterpart ofapplyIfNeeded; used by the 36 scalar-fold paths (Math.Control plus Routing/Waveshaping crossfades and shapers) beforefillScalarRampedResult. -
firstGeneratorSampleOrFloat(_:isGenerator:graph:count:)/lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)—GeneratorCore/InputResolutionHelpers.swift; block-rate read of a generator-or-scalar input.first…reads the block's first sample (0if empty) — oscillator/LF/noiseControlpaths;last…reads the final sample (ramp endpoint) — dynamics + delay-time paths. Both fall back tofloatValuefor non-generators -
xorshift64Next(_:) -
lyrebirdSeedXorshift64(from:mixConstant:)/lyrebirdSeedXorshift64(from:)—Math/LyrebirdConstants.swift; init-time xorshift64 seed helper. Two-arg form decorrelates Audio/Control pairs viamixConstant; one-arg form is the convenience for stand-alone single-state owners (e.g.DemandTemporalTendency/DemandTemporalBrownian) -
catmullRomCubic(_:_:_:_:t:)—Math/CubicInterpolation.swift; the single shared 4-point Catmull-Rom cubic kernel. Pass(pM1, p0, p1, p2, t:)— the sample before the segment, the two bracketing it, the one after, andt ∈ [0, 1]. Use instead of inlining thet²/t³expanded form.@inline(__always) @_spi(LyrebirdExtensions) public. Consumers: oscillator table reads (OscSin/oscillatorTableReadCubic),PlayBuffer,chaoticInterpolate, and the fractional-delay lines (DelayLine/DelayLineFeedback/CombFilter/AllpassFilter). -
RTScratchBuffer<Element>—Buffers/RTScratchBuffer.swift; a~Copyablesingle-owner heap scratch buffer that replaces hand-pairedallocate/deinitialize/deallocatein scratch-owning generators (the Spectral/FFT family).init(count:)zero-fills (Element: Numeric);init(count:repeating:)fills any value.@inline(__always)baseAddress/count/subscript(nonmutating set) so the hot loop matches the raw pointer. Store as aletassigned ininit— never a per-call local. Not for[UnsafeMutablePointer]per-channel arrays (a~Copyablecannot beArray-stored) or capacity-1 scalar boxes used via.pointee.@_spi(LyrebirdExtensions) public.
Full table, signatures, examples, and the per-generator exceptions (notably MathGenerators.Control and the non-standard ControlGenerator ramp paths) live in docs/protocols/writing-generators.md §13. That document is the single source of truth — when adding or removing a helper, update §13 and reference it from here.
Code Review
/lyrebird_review required before every merge to main. Run on feature branch after all work complete. No merge with blocking findings — fix and re-run until clean.
Skill behaviour:
swift test— stops on failure- Invokes
lyrebird_review_agent(RT safety, bus rules, protocol correctness, helper usage, test coverage) - Clean pass → appends one-line phase-completion entry to
MEMORY.md
Phase completion checklist + branch policy: docs/00-working-order.md. After merging a phase to main, move its section from docs/00-working-order.md into docs/01-completed-working-order.md and update the summary table.
Protocol Hierarchy
Generator (base)
├── AudioGenerator (.audio rate — sample-rate processing)
└── ControlGenerator (.control rate — block-rate processing, may sub-block)
DemandGenerator (NOT a Generator — pure value source, pull-based)
├── DemandSequence (sequential cycling)
└── DemandRandom (random pick, xorshift64 PRNG)
Consumed by Demand.Audio (sample-accurate) / Demand.Control (didTrigger gate)
one value per ≤0→>0 trigger edge. Owned by exactly one puller.
ValidGeneratorInput
├── Float / Double / Int literals
├── any Generator
└── Closure (wraps ClosureBody)
Synthesizer
└── DAG of Generator instances (direct wiring)
└── In/Out generators communicate via bus system
Node tree
SynthesisEngine
└── rootGroup (Group, persistent)
├── [pre-main nodes] ← .before(engine.mainGroup)
├── mainGroup (Group, persistent) ← engine.add(_:) default target (head-insertion)
│ └── Synthesizer instances
└── [post-main nodes] ← .after(engine.mainGroup)
Legacy Code
legacy/Lyrebird/LyrebirdSynth/Lyrebird/ — useful patterns:
LyrebirdTypes.swift— ValidGeneratorInput protocol, type aliasesLyrebirdUgen.swift— Generator baseLyrebirdNode.swift— node tree / groupsLyrebirdGraph.swift— build closure pattern, graph copyUGens/— oscillators, filters, envelopes, delays (modernize as Generators, don't copy)