# Contributing to Lyrebird Two distinct paths, depending on what you're building: 1. **A new built-in Generator** that lands *in this repo* (`Sources/Lyrebird/Generators/…`) — for primitives that belong in the core standard library: oscillators, filters, effects, noise sources, math operators, bus I/O. 2. **An out-of-tree Swift package** that depends on Lyrebird and adds its own Generators / Synthesizers — for domain-specific or third-party libraries you publish and version yourself (e.g. `LyrebirdATK`). If you're unsure which you want: contribute in-tree only if the unit is small, general-purpose, and broadly useful. Anything large, opinionated, or with heavy data/dependencies belongs in its own package. This guide assumes you've read [`README.md`](README.md), [`ARCHITECTURE.md`](ARCHITECTURE.md) (especially the threading model), and [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md). --- ## The one rule everything follows **The real-time audio thread never allocates, never locks, never blocks.** Every constraint below derives from that. If you internalize nothing else, internalize this: anything reachable from a generator's `_computeSamples` / `calculatedSamples` that allocates memory, takes a lock, logs, builds a `String`, force-unwraps, or does a runtime cast is a defect. See [`ARCHITECTURE.md`](ARCHITECTURE.md) §6 for how this is enforced and why. --- ## Part 1 — Contributing a built-in Generator ### Before you start - Read [`docs/protocols/writing-generators.md`](docs/protocols/writing-generators.md) end to end. It is the authoritative spec; this section is a checklist, not a replacement. - §13 of that doc is the **shared RT-safe helper catalog**. Inlining boilerplate that a helper already provides is a review-blocking violation. Skim it before writing a loop by hand. - The hard constraints in [`CLAUDE.md`](CLAUDE.md) ("Hard Constraints", "Swift Code Style Rules", "Shared RT-Safe Helpers — Must Use") are enforced by the review agents. Read them. ### Workflow 1. **Branch.** Each unit of work lives on its own branch off `main` (`phase-` or a descriptive name). Never commit directly to `main`. 2. **Scaffold.** Use the Xcode file templates rather than copying an existing file by hand: ```bash lyrebird install-templates # one-time ``` Then **New File… ▸ Lyrebird** picks the right template: *Generator*, *Oscillator*, *Noise Generator*, *Filter*, *Multi-Channel Generator*, *DemandGenerator*, plus a *Generator Test Suite*. 3. **Implement** following the rules below. 4. **Test** — every new Generator needs a test suite (see checklist). 5. **Review** — run `/lyrebird_review` on your branch. No merge with blocking findings. ### Decide: Audio rate or Control rate? - **`AudioGenerator`** — per-sample processing (`.audio` rate). Oscillators, filters, anything whose output must be sample-accurate. - **`ControlGenerator`** — block-rate, may sub-block (`.control` rate). Envelopes, LFOs, slow modulation. Cheaper. A `ControlGenerator` feeds an `AudioGenerator` input transparently. If a unit is useful at both rates, implement both via the **enum namespace pattern** (`Foo.Audio` / `Foo.Control` + `GeneratorEnum` conformance). `docs/protocols/writing-generators.md` §1 walks this. ### Hard rules for the generator body - **Subclass `GeneratorBase`.** It provides `_segmentSerial`, `_cachedResult`, `_subBlockBuffer`, and `_result` (mono, pre-allocated). Never redeclare these. - **First line of every `_computeSamples` is `_checkCount(count)`.** It traps if `count` exceeds the pre-allocated buffer. No grow path exists. - **Pre-allocate everything in `init`.** Bus memory, scratch buffers, vDSP setup objects. `init` runs off the RT thread; `_computeSamples` must only read/write existing storage. Use `makeResultBuffer(channels:)` / `makeSampleBuffer(_:)` instead of `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)` literals. - **Use `count`, never `engine.blockSize`,** for phase/state advancement — a `Control._computeSamples` may run several times per audio block in sub-block mode. - **Control generators with per-audio-block state** (bus writers, position advancers, gain smoothers, trigger detectors, random drawers, analysers) conform the `Control` to `BlockRateControlGenerator` to bypass the sub-block loop (no `calculatedSamples` override, no `_setupSubBlockBuffer()`). See writing-generators.md §15. - **Multi-row generators** (`_result.count > 1`) call `super.init(channels: N)` and override `outputChannelCount`. Missing the override silently mono-izes the generator under `+ - * /`. Channel count must be a `let` fixed at init. - **Extend the right base** where one exists: `OscillatorBase`, `NoiseBase`. Don't re-declare `_phase` / `_mulAdd` / `rngState` inline. - **Denormal hygiene** — flush denormals to zero in feedback paths (filters, delays, reverbs). ### Swift code style (review-blocking) - **No force unwraps.** No `!` on optionals, no `try!`. Use `guard let` / `if let` / `?? fallback` / `throws`. - **No magic numbers.** Every non-trivial literal gets a named `let` (exempt: `0`, `1`, `-1`, `2` where arithmetic meaning is obvious). - **Explicit type annotations on every binding** — `let x: Int = …`, `for i: Int in …`. (Exceptions: closure params, tuple destructures, pattern-match bindings.) Tool: `Tools/AnnotateBindings/annotate_bindings.py`. - **Doc comments on every public `init` parameter, in two places** (class-level `/// - Parameters:` block *and* on the `init` itself) — state what it does, unit (Hz / dB / seconds / ratio / [0,1] / frames), range/clamping, default. This is what makes Xcode Quick Help useful from both the type and the call site. - **Filter resonance naming:** `q:` for quality-factor filters (RBJ, SVF, Butterworth — `0.707` = Butterworth); `resonance:` for raw-feedback filters (Moog ladder, `[0,1]`). Route to whichever the algorithm uses naturally. - **Multi-line declaration format** when ≥ 2 type aliases or ≥ 2 init params. ### File organization (review-blocking) - **One public type per file.** Each Generator family in its own file (`OscSawtooth.swift`, `Clip.swift`). - **Never drop a new `.swift` at `Sources/Lyrebird/` root.** Place into the matching subfolder (`Generators/`, `GeneratorCore/`, `Filters/`, `Math/`, etc.). If none fits, propose a new subfolder in the PR description — don't land at root. - Shared file-scope helpers go in `*Helpers.swift` with `internal` access. ### Testing checklist One `@Suite` per test file, named `Tests.swift`, using Swift Testing (`@Test`, `#expect`). At minimum: - Output is non-silent / correct for a known input. - Audio and Control variants agree where both exist. - Edge counts: `count` of 1, sub-block sizes, full block. - Block-boundary instance reuse (state persists correctly across blocks). - Multi-channel: `outputChannelCount` correct; operator broadcasting behaves. Run the suite: ```bash swift test --no-parallel --filter Tests ``` Full suite before merge: ```bash swift test --no-parallel ``` > Always `--no-parallel`. The default parallel runner SIGABRTs at xctest teardown on multi-engine combos — a known, production-irrelevant flake. One pre-existing flake (`RTThreadIdentity` retain-race) may show on the full run; the filtered suite is deterministic. ### Submitting - Branch off `main`, implement, test, run `/lyrebird_review` until clean. - PR description: one-line rationale, list of files, and (if you added a subfolder) why. - Update DocC: add the type to the relevant `Sources/Lyrebird/Lyrebird.docc/` topic and, where appropriate, `docs/stdlib/generators.md`. --- ## Part 2 — Contributing an out-of-tree Swift package For Generators / Synthesizers you publish and version yourself. The reference implementation is `LyrebirdATK` (ambisonics). Authoritative docs: - [`docs/protocols/extension-sdk.md`](docs/protocols/extension-sdk.md) — the stable public API surface (tier 1) and `@_spi(LyrebirdExtensions)` symbols (tier 2) you may rely on, plus versioning policy. - [`docs/extension-authors-guide.md`](docs/extension-authors-guide.md) — end-to-end walk-through building a package using LyrebirdATK as the model. ### Why a separate package? In-tree contribution couples you to Lyrebird's release cycle and review bar. A separate package lets you own your source, ship your own releases, and pull heavy data or third-party dependencies that don't belong in core. Core users add your package and pin the version range they want. ### Naming - Package and module: prefix with `Lyrebird` if it's a general toolkit (`LyrebirdATK`), or use your own namespace otherwise. - Generators follow the same enum-namespace + `.Audio`/`.Control` conventions as core. Don't shadow core type names. ### `Package.swift` shape ```swift // swift-tools-version: 6.0 import PackageDescription let package = Package( name: "LyrebirdMyExtension", platforms: [.macOS(.v15), .iOS(.v18)], // match core's floor — Synchronization.Atomic products: [ .library(name: "LyrebirdMyExtension", targets: ["LyrebirdMyExtension"]), ], dependencies: [ .package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.0.0"), ], targets: [ .target( name: "LyrebirdMyExtension", dependencies: [.product(name: "Lyrebird", package: "Lyrebird")]), .testTarget( name: "LyrebirdMyExtensionTests", dependencies: ["LyrebirdMyExtension"]), ] ) ``` > Replace the URL with the real repository once published. During development, depend on a local checkout instead: `.package(name: "Lyrebird", path: "/path/to/LyrebirdII")`. ### What you may import ```swift import LyrebirdSynth // tier-1 stable API — Generator/Synthesizer/GeneratorBase, engine types import struct LyrebirdSynth.MulAddSpec // tier-2 symbols require @_spi ``` For tier-2 helpers (MulAdd helpers, the xorshift64 PRNG, test hooks): ```swift @_spi(LyrebirdExtensions) import LyrebirdSynth ``` - **Tier 1** is the contract: it follows semver and won't break within a major version. - **Tier 2** (`@_spi(LyrebirdExtensions)`) is available but may change between minor versions — pin a tight range if you depend on it. See `extension-sdk.md` § Versioning policy. ### Same RT rules apply A Generator in your package runs on the same RT thread under the same contract. Everything in Part 1's "Hard rules for the generator body" and "Swift code style" applies identically — subclass `GeneratorBase`, `_checkCount(count)` first, pre-allocate in `init`, no allocation/locks/force-unwraps on the RT path. Reuse the tier-2 helpers (`sampleOrZero`, `resolveGeneratorOrScalar`, etc.) where they're `@_spi`-exposed rather than re-rolling them. ### Testing, compatibility, publishing - Test with Swift Testing, same as core. Verify your package builds against the **minimum** Lyrebird version in your dependency range, not just the latest. - Maintain a compatibility matrix (your version ↔ Lyrebird version) — see `extension-authors-guide.md` § Compatibility matrix. - Tag releases semver. Document which Lyrebird major version each release targets. ### Listing your package Once published, open a PR adding a row to the **Extensions** table in [`README.md`](README.md). One line: package name (linked) + short description. --- ## Repo maintenance contributors If you also edit the Claude agent definitions or skills (maintainers working in `~/.claude/`): - Edit only the working copies in `~/.claude/`. Sync the repo mirrors with: ```bash bash scripts/sync-claude-from-working.sh --apply bash scripts/sync-claude-from-working.sh --check # CI / pre-commit drift check ``` - Enable the pre-commit drift guard once per clone: `git config core.hooksPath .githooks`. --- ## Questions Architecture / threading questions: [`ARCHITECTURE.md`](ARCHITECTURE.md). Generator authoring: [`docs/protocols/writing-generators.md`](docs/protocols/writing-generators.md). Extension packages: [`docs/extension-authors-guide.md`](docs/extension-authors-guide.md). Dev/release workflow (dev remote vs release remote, dogfood vs consumer projects, the static/dynamic product split): [`docs/DEVELOPMENT_AND_RELEASE.md`](docs/DEVELOPMENT_AND_RELEASE.md). Everything else: the task→doc map in [`CLAUDE.md`](CLAUDE.md). --- ## License Lyrebird is MIT-licensed ([`LICENSE`](LICENSE)). By contributing in-tree, you agree your contributions are licensed under the same terms. Out-of-tree packages you publish keep whatever license you choose.