Files
Lyrebird/docs/extension-authors-guide.md
josh f8878324fd v2.1.1 release: delay-click fix + internal consolidation
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>
2026-10-07 21:20:49 -07:00

11 KiB

Authoring a Lyrebird Extension Package

End-to-end walk-through for building an out-of-tree Swift package that adds Generator or Synthesizer implementations on top of Lyrebird.

The companion document is docs/protocols/extension-sdk.md, which lists every public + SPI symbol your package may depend on. This guide shows how to wire it together, ship a versioned release, and avoid the common pitfalls.

LyrebirdATK (the FOA toolkit, extracted from Lyrebird core in v0.9.1) is the canonical worked example. Repository layout, Package.swift shape, and test-helper patterns below all match LyrebirdATK exactly — clone it as a starting template.

Why a separate package?

  • Namespace isolation. Your module's types live under your module name; no collisions with core Lyrebird or other extension packages.
  • Independent release cadence. Tag and publish on your own schedule. Users pin the version range they want for your package, independently of Lyrebird.
  • Independent hosting. Anywhere SwiftPM can fetch from — GitHub, GitLab, Bitbucket, self-hosted git, or a local path during development.

Naming conventions

These are conventions, not compiler rules. Reviewers may suggest changes if they make your package harder to integrate.

What Convention Example
Package / module name Lyrebird<Vendor> LyrebirdATK, LyrebirdJoshFX
Type prefix Domain-meaningful Foa*, Hoa*, Pd*
Parameter-key prefix <package>.<param> "atk.azimuth"
Source files One public type per file FoaRotate.swift, not FoaTransforms.swift
Test suite per type <TypeName>Tests.swift FoaRotateTests.swift

Repository layout

LyrebirdMyPackage/
├── Package.swift
├── README.md
├── LICENSE
├── .gitignore
├── docs/
│   └── MyPackage-Guide.md           ← authoritative reference
├── scripts/
│   └── <any data-build scripts>
├── Sources/
│   └── LyrebirdMyPackage/
│       ├── MyGenerator.swift
│       ├── ...
│       └── Resources/               ← optional, processed by SwiftPM
└── Tests/
    └── LyrebirdMyPackageTests/
        ├── Helpers/
        │   └── TestHelpers.swift    ← engine/graph fixtures
        ├── MyGeneratorTests.swift
        └── ...

Same loose-file-at-root rule as core: every .swift lives in a subfolder. Use Sources/<Module>/<Group>/ to group large families.

Package.swift

// swift-tools-version: 6.0
import PackageDescription

let package = Package(
    name: "LyrebirdMyPackage",
    platforms: [.macOS(.v15), .iOS(.v18)],
    products: [
        .library(name: "LyrebirdMyPackage", targets: ["LyrebirdMyPackage"]),
    ],
    dependencies: [
        // Pin tightly to the Lyrebird MINOR range — @_spi(LyrebirdExtensions)
        // symbols are documented as MINOR-mutable.
        .package(
            url: "https://realizedsound.mooo.com/josh/Lyrebird.git",
            "0.9.1" ..< "1.0.0"
        ),
    ],
    targets: [
        .target(
            name: "LyrebirdMyPackage",
            dependencies: [
                .product(name: "Lyrebird", package: "Lyrebird"),
            ],
            // Drop the next clause if you ship no resources.
            resources: [.process("Resources")],
            linkerSettings: [
                .linkedFramework("Accelerate"),    // only if you call vDSP
            ]
        ),
        .testTarget(
            name: "LyrebirdMyPackageTests",
            dependencies: ["LyrebirdMyPackage"]
        ),
    ]
)

The package: "Lyrebird" argument matches the last path component of the dependency URL (Lyrebird.git → Lyrebird), case-insensitive. SPM is strict about this; mismatches produce an unhelpful "unknown package" error.

Pre-publication / private-repo dependencies

If you are pulling Lyrebird from a private repository, use the SSH URL form:

.package(
    url: "git@realizedsound.mooo.com:josh/Lyrebird.git",
    "0.9.1" ..< "1.0.0"
)

SPM resolves SSH URLs through your existing SSH agent. Once Lyrebird is publicly hosted, swap to the HTTPS URL.

Local-path dependency during development

While iterating on both Lyrebird and your extension in parallel, prefer a local path:

.package(path: "../Lyrebird")

The package: name in the target dependency is then the directory name ("Lyrebird"). Switch back to the version dep before tagging.

Importing Lyrebird

Every source file in your module that uses RT-safe helpers needs the SPI import:

import Foundation
@_spi(LyrebirdExtensions) import LyrebirdSynth

The plain import LyrebirdSynth is enough for files that only touch the stable public API. Pick one form per file; both is harmless but noisy.

Inside your test files, you generally want both access modes:

import Testing
import Foundation
import LyrebirdSynth
@_spi(LyrebirdExtensions) import LyrebirdSynth
@testable import LyrebirdMyPackage

@testable is what lets your tests reach internal types inside your own module (e.g. helper structs and base classes that you keep internal because they are implementation details). It does not grant SPI access on its own — that is what the explicit @_spi(LyrebirdExtensions) import is for.

Writing a Generator

Identical to the in-tree recipe in docs/protocols/writing-generators.md. Two points to internalise:

  1. Subclass GeneratorBase. Inherit _segmentSerial / _cachedResult / _subBlockBuffer — do not redeclare them. _setupSubBlockBuffer() is called from a sub-blocking ControlGenerator.Control.init after super.init() (a BlockRateControlGenerator conformer never sub-blocks and skips it).
  2. Use the shared RT-safe helpers. Inlining them is a review violation. Full table: writing-generators.md §13. SPI surface: extension-sdk.md.

Minimal example — an audio-rate gain stage:

@_spi(LyrebirdExtensions) import LyrebirdSynth

public final class MyGain: GeneratorBase, AudioGenerator {
    private let _input:  any ValidGeneratorInput
    private var _result: [[Double]]
    private let _mulAdd: MulAddSpec

    public override var outputChannelCount: Int { 1 }

    public init(
        input: any ValidGeneratorInput,
        gain:  any ValidGeneratorInput = 1.0,
        mul:   any ValidGeneratorInput = 1.0,
        add:   any ValidGeneratorInput = 0.0
    ) {
        _input  = input
        _result = [[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)]
        _mulAdd = MulAddSpec(mul: gain * mul, add: add)
        super.init()
    }

    public func floatValue(graph: SynthGraph) -> Double {
        calculatedSamples(graph: graph, count: graph.engine.blockSize).first?.first ?? 0.0
    }

    public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
        precondition(count <= _result[0].count,
                     "MyGain: count \(count) exceeds buffer \(_result[0].count)")
        let src = _input.calculatedSamples(graph: graph, count: count)
        let row = src.first ?? []
        for i in 0..<count { _result[0][i] = row.indices.contains(i) ? row[i] : 0 }
        _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
        return _result
    }
}

Bundled resources

If your package needs to ship binary data (HRIR files, wavetables, IRs):

  1. Place the file under Sources/LyrebirdMyPackage/Resources/<subdir>/foo.bin.
  2. Declare resources: [.process("Resources")] on the target.
  3. Look the file up at runtime via Bundle.module from a file inside your module — Bundle.module resolves to your package's resource bundle, not Lyrebird's.
public extension MyType {
    static var bundledFoo: URL {
        guard let url = Bundle.module.url(forResource: "foo", withExtension: "bin")
        else { preconditionFailure("foo.bin missing from LyrebirdMyPackage bundle") }
        return url
    }
}

SwiftPM's .process(...) flattens subdirectories, so the lookup uses the file name only (no subdir prefix).

LyrebirdATK's HRIRFile+BundledKEMAR.swift is the reference implementation.

Writing tests

Tests live in Tests/LyrebirdMyPackageTests/. Use Swift Testing (@Test, #expect, @Suite), not XCTest.

You will need a small local TestHelpers.swift mirroring the core engine / graph fixtures. Lyrebird's in-tree TestHelpers.swift is internal to the core test target and not part of the published API; reproduce only the helpers you need:

import Testing
import LyrebirdSynth
@_spi(LyrebirdExtensions) import LyrebirdSynth

func makeTestEngine(blockSize: Int = 512, sampleRate: Double = 44_100) -> SynthesisEngine {
    SynthesisEngine(
        blockSize: blockSize,
        sampleRate: sampleRate,
        numOutputChannels: 2,
        numInputChannels:  2,
        numAudioBuses:     128,
        numControlBuses:   4_096,
        eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
        driver: OfflineDriver()
    )
}

func makeSynthGraph(engine: SynthesisEngine, busOffset: Int = 0) -> SynthGraph {
    SynthGraph(engine: engine, busOffset: busOffset)
}

/// Advance the fan-out cache serial — call between back-to-back
/// `calculatedSamples` invocations on the same generator within one test.
func advanceBlock(_ engine: SynthesisEngine) {
    engine.advanceSegmentSerial()
}

SynthesisEngine.advanceSegmentSerial() is @_spi(LyrebirdExtensions) — that is why the test helper file imports the SPI surface explicitly.

Versioning your package

Follow SemVer:

  • MAJOR — source-breaking changes (renamed types, removed APIs, changed function signatures, behaviour changes that break existing user code).
  • MINOR — additive (new generators, new init parameters with defaults, new optional behaviour).
  • PATCH — bug fixes, doc updates, internal refactors.

Document your Lyrebird-compatibility range in the README:

## Compatibility matrix

| LyrebirdMyPackage | Lyrebird |
|---|---|
| 0.1.x | 0.9.x   |
| 0.2.x | 0.10.x  |
| 1.0.x | 1.0.x   |

When Lyrebird's MINOR rolls over, audit the SPI diff before bumping your support range — @_spi(LyrebirdExtensions) is the only API tier where signatures may change in a Lyrebird MINOR.

Tag releases as vMAJOR.MINOR.PATCH:

git tag -a v0.1.0 -m "Initial release"
git push origin v0.1.0

Reviewing your package

The Lyrebird review agents (lyrebird_review_agent, pr_review_agent) live in core's .claude/agents/. To run them against your extension package, copy or symlink the agent definitions into your own .claude/agents/ directory. Both agents are RT-safety focused and will flag the same kinds of issues they catch in core (force unwraps, magic numbers, helper inlining, missing dual doc comments).

You can also run swift test from CI against the lowest and highest pinned Lyrebird versions in your compatibility range — this catches accidental SPI breakage early.

Reference

Topic Where
Stable public + SPI surface docs/protocols/extension-sdk.md
Generator implementation rules docs/protocols/writing-generators.md
Shared RT-safe helpers (§13) docs/protocols/writing-generators.md
Synthesizer protocol docs/protocols/synthesizer.md
Worked example LyrebirdATK — clone its Package.swift, Sources/, Tests/, README, LICENSE as templates