1.0.0 release

This commit is contained in:
2026-06-01 18:27:40 -07:00
parent b1ab0f102c
commit 1f20fcab20
1151 changed files with 230703 additions and 14 deletions
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Kind</key>
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
<key>Platforms</key>
<array>
<string>com.apple.platform.macosx</string>
<string>com.apple.platform.iphoneos</string>
</array>
<key>Description</key>
<string>A pair: a SynthesizerBase subclass with @LiveParam slots + a LyrebirdAudioUnit subclass that wraps it as an AUv3 component. Override only makeSynthesizer() and parameterMetadata(); LyrebirdAudioUnit handles render setup, parameter ramping, and CoreMIDI 2.0 input. Pair with an Info.plist AudioComponents entry (type: aumu, your subtype + manufacturer) to register the AU with the host. See LyrebirdAUv3Demo for a complete project.</string>
<key>Summary</key>
<string>Lyrebird AUv3 Source-Slot Synth (Synth + LyrebirdAudioUnit)</string>
<key>SortOrder</key>
<string>35</string>
<key>AllowedTypes</key>
<array>
<string>public.swift-source</string>
</array>
<key>DefaultCompletionName</key>
<string>MyAUSynth</string>
<key>MainTemplateFile</key>
<string>___FILEBASENAME___.swift</string>
<key>Options</key>
<array>
<dict>
<key>Identifier</key>
<string>productName</string>
<key>Required</key>
<true/>
<key>Name</key>
<string>AU synth name:</string>
<key>Description</key>
<string>Name of the Synthesizer + AudioUnit pair (used as the file name and the Synthesizer class; the AU is named &lt;Name&gt;AudioUnit).</string>
<key>Type</key>
<string>text</string>
<key>Default</key>
<string>MyAUSynth</string>
</dict>
</array>
</dict>
</plist>
@@ -0,0 +1,68 @@
//___FILEHEADER___
import Foundation
import AVFoundation
import AudioToolbox
import LyrebirdSynth
// MARK: - ___FILEBASENAMEASIDENTIFIER___
/// Synthesizer driven by the AUv3 host. Each `@LiveParam` slot maps to an
/// `AUParameter` exposed by the wrapper class below via
/// `parameterMetadata()`. The host writes parameter values through the AU's
/// `AUParameterTree`; `LyrebirdAudioUnit` forwards each write to the matching
/// `@LiveParam` (atomic, RT-safe).
public final class ___FILEBASENAMEASIDENTIFIER___: SynthesizerBase {
/// Fundamental frequency in Hz. Range [20, 8000].
@LiveParam public var frequency: Double = 440.0
/// Output amplitude (linear gain). Range [0, 1].
@LiveParam public var amplitude: Double = 0.3
public override func build() {
let osc = OscSin.Audio(freq: $frequency)
let voice = osc * $amplitude
// Mono → stereo for AUv3 host compatibility (most hosts negotiate
// stereo output buses).
output(bus: 0, source: voice)
output(bus: 1, source: voice)
}
}
// MARK: - ___FILEBASENAMEASIDENTIFIER___AudioUnit
/// AUv3 wrapper. Subclasses `LyrebirdAudioUnit`, which handles render setup,
/// parameter ramping, and CoreMIDI 2.0 input. Override only the two class
/// methods below.
///
/// To expose this AU to hosts (Logic, GarageBand, AUM, Loopy Pro, …):
///
/// 1. Make the containing target an Audio Unit App Extension (`.appex`).
/// 2. Add an `AudioComponents` array to the extension's Info.plist:
/// - `type: aumu` (music device) — change to `aufx` for effects
/// - `subtype: ABCD` — 4-char identifier you choose
/// - `manufacturer: WXYZ` — 4-char identifier you choose
/// - `name: ___FILEBASENAMEASIDENTIFIER___`
/// - `factoryFunction: $(PRODUCT_MODULE_NAME).___FILEBASENAMEASIDENTIFIER___AudioUnit`
/// - `version: 1`
/// 3. Set the extension's `NSExtensionPrincipalClass` to an
/// `AUViewController` that returns this AU from `createAudioUnit(with:)`.
/// 4. After build, validate with:
/// auval -v aumu ABCD WXYZ
///
/// See `Demos/LyrebirdAUv3Demo/LyrebirdFMExtension/` for a complete working
/// example with Info.plist, AUViewController, and a SwiftUI host app.
public final class ___FILEBASENAMEASIDENTIFIER___AudioUnit: LyrebirdAudioUnit {
public override class func makeSynthesizer() -> SynthesizerBase {
___FILEBASENAMEASIDENTIFIER___()
}
public override class func parameterMetadata() -> [String: LyrebirdAUParameterInfo] {
[
"frequency": .init(min: 20, max: 8000, unit: .hertz, displayName: "Frequency"),
"amplitude": .init(min: 0, max: 1, unit: .linearGain, displayName: "Amplitude"),
]
}
}
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Kind</key>
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
<key>Platforms</key>
<array>
<string>com.apple.platform.macosx</string>
<string>com.apple.platform.iphoneos</string>
</array>
<key>Description</key>
<string>A sample-playback Synthesizer that loads a LyrebirdBuffer from an audio file URL and plays it via PlayBuffer.Audio. Honours the file's native sample rate via nativeRateScale, supports loop / rate-modulation via @LiveParam. Loading runs at init (non-RT) and traps on file errors — convert to throwing init for production code.</string>
<key>Summary</key>
<string>Lyrebird Buffer Reader (file → PlayBuffer Synthesizer)</string>
<key>SortOrder</key>
<string>33</string>
<key>AllowedTypes</key>
<array>
<string>public.swift-source</string>
</array>
<key>DefaultCompletionName</key>
<string>MySamplePlayer</string>
<key>MainTemplateFile</key>
<string>___FILEBASENAME___.swift</string>
<key>Options</key>
<array>
<dict>
<key>Identifier</key>
<string>productName</string>
<key>Required</key>
<true/>
<key>Name</key>
<string>Synthesizer name:</string>
<key>Description</key>
<string>Name of the sample-player Synthesizer (also used as the file name).</string>
<key>Type</key>
<string>text</string>
<key>Default</key>
<string>MySamplePlayer</string>
</dict>
</array>
</dict>
</plist>
@@ -0,0 +1,87 @@
//___FILEHEADER___
import Foundation
import LyrebirdSynth
// MARK: - ___FILEBASENAMEASIDENTIFIER___
/// Sample-playback Synthesizer that loads an audio file at init and plays it
/// through `PlayBuffer.Audio`. Output channel count matches the loaded buffer.
///
/// `LyrebirdBuffer.loadAllChannels(url:)` reads every channel into a single
/// multichannel buffer and records the file's sample rate on it; passing
/// `buffer.nativeRateScale(engineSampleRate:)` to `PlayBuffer.Audio` rate:
/// ensures the file plays back at the correct pitch / speed when the engine
/// runs at a different sample rate than the file.
///
/// ## Usage
/// ```swift
/// let player = try ___FILEBASENAMEASIDENTIFIER___(
/// fileURL: URL(fileURLWithPath: "/path/to/sample.wav"),
/// loop: true,
/// engineSampleRate: engine.sampleRate
/// )
/// try engine.add(player)
///
/// // Modulate playback rate at runtime:
/// player.rate = 0.5 // half speed / one octave down
/// ```
public final class ___FILEBASENAMEASIDENTIFIER___: SynthesizerBase {
// MARK: - Parameters
/// Playback rate multiplier. `1.0` = native pitch, `2.0` = +1 octave,
/// `0.5` = −1 octave. Negative values reverse playback if the underlying
/// PlayBuffer is configured to honour them.
@LiveParam public var rate: Double = 1.0
/// Output amplitude (linear gain).
@LiveParam public var amplitude: Double = 1.0
// MARK: - State
private let buffer: LyrebirdBuffer
private let loop: Bool
private let engineSampleRate: Double
// MARK: - Init
/// - Parameters:
/// - fileURL: Path to a WAV / AIFF / CAF audio file. Loaded synchronously
/// on a non-RT thread; do not call from the audio callback.
/// - loop: When `true`, playback restarts from frame 0 after the end.
/// When `false`, the generator emits silence after the final frame
/// (or frees the node if `doneAction == .freeNode`).
/// - engineSampleRate: The engine's sample rate. Passed at init so the
/// `build()` closure (which has no engine reference) can compute the
/// native-sample-rate compensation. Get from `engine.sampleRate`.
public init(
fileURL: URL,
loop: Bool = false,
engineSampleRate: Double
) throws {
self.buffer = try LyrebirdBuffer.loadAllChannels(url: fileURL)
self.loop = loop
self.engineSampleRate = engineSampleRate
super.init()
}
// MARK: - Build
public override func build() {
// Compose rate: user-controlled `rate` multiplier × the buffer's
// native-sample-rate compensation. nativeRateScale falls back to 1.0
// when the buffer carries no recorded rate.
let nativeScale = buffer.nativeRateScale(engineSampleRate: engineSampleRate)
let combinedRate = $rate * nativeScale
let player = PlayBuffer.Audio(
buffer: buffer,
loop: loop,
doneAction: loop ? .nothing : .freeNode,
rate: combinedRate
)
output(bus: 0, source: player * $amplitude)
}
}
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Kind</key>
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
<key>Platforms</key>
<array>
<string>com.apple.platform.macosx</string>
<string>com.apple.platform.iphoneos</string>
</array>
<key>Description</key>
<string>A pure-value source conforming to DemandGenerator. Consumed by Demand.Audio / Demand.Control pullers — one value per ≤0→&gt;0 trigger edge. Owned by exactly one puller. Provide nextValue(), reset(), and isExhausted.</string>
<key>Summary</key>
<string>Lyrebird Demand Generator (DemandGenerator conformer)</string>
<key>SortOrder</key>
<string>20</string>
<key>AllowedTypes</key>
<array>
<string>public.swift-source</string>
</array>
<key>DefaultCompletionName</key>
<string>MyDemand</string>
<key>MainTemplateFile</key>
<string>___FILEBASENAME___.swift</string>
<key>Options</key>
<array>
<dict>
<key>Identifier</key>
<string>productName</string>
<key>Required</key>
<true/>
<key>Name</key>
<string>DemandGenerator name:</string>
<key>Description</key>
<string>Name of the DemandGenerator class (also used as the file name).</string>
<key>Type</key>
<string>text</string>
<key>Default</key>
<string>MyDemand</string>
</dict>
</array>
</dict>
</plist>
@@ -0,0 +1,64 @@
//___FILEHEADER___
import Foundation
import LyrebirdSynth
// MARK: - ___FILEBASENAMEASIDENTIFIER___
/// One-line description of ___FILEBASENAMEASIDENTIFIER___.
///
/// A `DemandGenerator` is a pull-based value source — it is **not** a `Generator`
/// and does not appear in the audio graph itself. It is consumed by a demand
/// puller (`Demand.Audio` or `Demand.Control`) which calls `nextValue()` on each
/// `≤ 0 → > 0` trigger edge. Each instance is owned by exactly one puller.
///
/// ## Usage
/// ```swift
/// let demand = ___FILEBASENAMEASIDENTIFIER___()
/// let pitchSeq = Demand.Control(
/// trig: Impulse.Control(freq: 2.0),
/// demand: demand
/// )
/// let osc = OscSin.Audio(freq: pitchSeq)
/// ```
public final class ___FILEBASENAMEASIDENTIFIER___: DemandGenerator {
// MARK: - State
/// Replace these stored properties with whatever state your value source needs
/// (current step, RNG state, table indices, etc.). State is mutated only inside
/// `nextValue()` and `reset()` — both run on the RT thread side of the demand
/// puller, so keep everything allocation-free and lock-free.
private var _step: Int = 0
// MARK: - Init
public init() {
// Initialise state. No allocation paths should run after this point on the
// RT thread.
}
// MARK: - DemandGenerator
/// `true` once this source has produced its final value. Returning `nil` from
/// `nextValue()` is also acceptable — pullers stop pulling when either signals
/// exhaustion.
public var isExhausted: Bool {
// TODO: return true when this source has no more values to produce.
return false
}
/// Returns the next value to emit, or `nil` if exhausted.
public func nextValue() -> Double? {
// TODO: produce the next value. Replace this body with your formula.
let value: Double = Double(_step)
_step += 1
return value
}
/// Reset internal state so the next `nextValue()` produces the source's first
/// value again. Called by demand pullers when their trigger source resets.
public func reset() {
_step = 0
}
}
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Kind</key>
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
<key>Platforms</key>
<array>
<string>com.apple.platform.macosx</string>
<string>com.apple.platform.iphoneos</string>
</array>
<key>Description</key>
<string>A Lyrebird RBJ biquad filter (in-tree only — uses module-internal runRBJBiquadBlock helper and BiquadCoeffs / BiquadState types). Drop this file under Sources/Lyrebird/Generators/Filters/. Audio-rate only; signature (input, freq, q, mul, add). Replace the coefficient closure with the EQ Cookbook formula for your filter shape.</string>
<key>Summary</key>
<string>Lyrebird Filter (RBJ biquad, Audio-only)</string>
<key>SortOrder</key>
<string>15</string>
<key>AllowedTypes</key>
<array>
<string>public.swift-source</string>
</array>
<key>DefaultCompletionName</key>
<string>MyFilter</string>
<key>MainTemplateFile</key>
<string>___FILEBASENAME___.swift</string>
<key>Options</key>
<array>
<dict>
<key>Identifier</key>
<string>productName</string>
<key>Required</key>
<true/>
<key>Name</key>
<string>Filter name:</string>
<key>Description</key>
<string>Name of the filter enum (also used as the file name).</string>
<key>Type</key>
<string>text</string>
<key>Default</key>
<string>MyFilter</string>
</dict>
</array>
</dict>
</plist>
@@ -0,0 +1,114 @@
//___FILEHEADER___
//
// In-tree template — drop this file under Sources/Lyrebird/Generators/Filters/.
// Uses the module-internal `runRBJBiquadBlock` helper and BiquadCoeffs / BiquadState
// types, so this template is not usable from a project that depends on Lyrebird
// as a package. External users should declare their own biquad state inline.
import Foundation
/// Second-order biquad filter using Robert Bristow-Johnson's Audio EQ Cookbook
/// coefficient formulas. Replace the `computeCoefficients` closure body with the
/// coefficient set for your filter shape (lowpass / highpass / bandpass / notch /
/// allpass / peaking / shelf).
///
/// `freq` and `q` accept any `ValidGeneratorInput`. Generator inputs trigger
/// block-boundary coefficient interpolation — 6 trig calls per block regardless
/// of block size.
///
/// ## Usage
/// ```swift
/// ___FILEBASENAMEASIDENTIFIER___.Audio(input: sig, freq: 1000.0, q: 0.707)
/// ___FILEBASENAMEASIDENTIFIER___.Audio(input: sig, freq: lfoGen, q: 2.0)
/// ```
///
/// - Parameters:
/// - input: Signal to filter.
/// - freq: Cutoff (or centre / corner) frequency in Hz. No internal clamping;
/// stay below Nyquist for alias-free output.
/// - q: Resonance / bandwidth factor. `0.707` = Butterworth (no peak).
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public enum ___FILEBASENAMEASIDENTIFIER___ {
/// Audio-rate ___FILEBASENAMEASIDENTIFIER___ filter.
public final class Audio: GeneratorBase, AudioGenerator {
private let inputSource: any ValidGeneratorInput
private let freqInput: any ValidGeneratorInput
private let qInput: any ValidGeneratorInput
private let freqIsGenerator: Bool
private let qIsGenerator: Bool
private var cachedCoeffs: BiquadCoeffs = .zero
private var prevFreq: Double = -1.0
private var prevQ: Double = -1.0
private var prevSampleRate: Double = -1.0
private var state: BiquadState = BiquadState()
private let _mulAdd: MulAddSpec
/// - Parameters:
/// - input: Signal to filter.
/// - freq: Cutoff frequency in Hz.
/// - q: Resonance factor.
/// - mul: Output multiplier.
/// - add: Output offset.
public init(
input: any ValidGeneratorInput,
freq: any ValidGeneratorInput,
q: any ValidGeneratorInput,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
self.inputSource = input
self.freqInput = freq
self.qInput = q
self.freqIsGenerator = freq is any Generator
self.qIsGenerator = q is any Generator
self._mulAdd = MulAddSpec(mul: mul, add: add)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
runRBJBiquadBlock(
inputSource: inputSource, freqInput: freqInput, qInput: qInput,
freqIsGenerator: freqIsGenerator, qIsGenerator: qIsGenerator,
state: &state, cachedCoeffs: &cachedCoeffs,
prevFreq: &prevFreq, prevQ: &prevQ, prevSampleRate: &prevSampleRate,
mulAdd: _mulAdd, result: &_result,
graph: graph, count: count,
computeCoefficients: { freq, q, sampleRate in
// Replace this body with the EQ Cookbook coefficient formula
// for your filter shape. Below is the lowpass formula as a
// starting reference — see RBJLowPass.swift for the canonical
// implementation that already lives in Lyrebird.
let w0 = 2.0 * .pi * freq / sampleRate
let cosW0 = cos(w0)
let sinW0 = sin(w0)
let alpha = sinW0 / (2.0 * q)
let b0 = (1.0 - cosW0) * 0.5
let b1 = 1.0 - cosW0
let b2 = (1.0 - cosW0) * 0.5
let a0 = 1.0 + alpha
let a1 = -2.0 * cosW0
let a2 = 1.0 - alpha
return BiquadCoeffs(
nb0: b0 / a0, nb1: b1 / a0, nb2: b2 / a0,
na1: a1 / a0, na2: a2 / a0
)
}
)
return _result
}
}
}
// GeneratorEnum conformance intentionally omitted — Audio-only filter.
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Kind</key>
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
<key>Platforms</key>
<array>
<string>com.apple.platform.macosx</string>
<string>com.apple.platform.iphoneos</string>
</array>
<key>Description</key>
<string>A Lyrebird Generator with both Audio-rate and Control-rate variants. Subclasses GeneratorBase and conforms to AudioGenerator / ControlGenerator. Includes the canonical _Base shared-state class, _checkCount guard, MulAddSpec wiring, and the sub-block linear-ramp pattern for the Control variant.</string>
<key>Summary</key>
<string>Lyrebird Generator (Audio + Control)</string>
<key>SortOrder</key>
<string>10</string>
<key>AllowedTypes</key>
<array>
<string>public.swift-source</string>
</array>
<key>DefaultCompletionName</key>
<string>MyGenerator</string>
<key>MainTemplateFile</key>
<string>___FILEBASENAME___.swift</string>
<key>Options</key>
<array>
<dict>
<key>Identifier</key>
<string>productName</string>
<key>Required</key>
<true/>
<key>Name</key>
<string>Generator name:</string>
<key>Description</key>
<string>Name of the Generator (also used as the file name).</string>
<key>Type</key>
<string>text</string>
<key>Default</key>
<string>MyGenerator</string>
</dict>
</array>
</dict>
</plist>
@@ -0,0 +1,132 @@
//___FILEHEADER___
import Foundation
@_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - ___FILEBASENAMEASIDENTIFIER___
/// One-line description of ___FILEBASENAMEASIDENTIFIER___.
///
/// Longer explanation: what the generator does, formula, edge cases.
///
/// ## Usage
/// ```swift
/// let g = ___FILEBASENAMEASIDENTIFIER___.Audio(signal)
/// let g = ___FILEBASENAMEASIDENTIFIER___.Control(signal)
/// ```
public enum ___FILEBASENAMEASIDENTIFIER___ {
/// Shared state between Audio and Control variants.
///
/// Holds input references + MulAddSpec. Stored properties live here so the
/// two final classes share the same field layout (and the same designated init).
public class _Base: GeneratorBase {
let inputSource: any ValidGeneratorInput
let _mulAdd: MulAddSpec
public init(
_ signal: any ValidGeneratorInput,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
inputSource = signal
_mulAdd = MulAddSpec(mul: mul, add: add)
// GeneratorBase.init() allocates _result with one mono row of
// lyrebirdDefaultResultBufferSize. Multi-channel generators call
// super.init(channels: N) instead.
}
}
/// Per-sample transform shared by Audio + Control. Replace this with the
/// generator's actual formula.
@inline(__always)
static func _transform(_ value: Double) -> Double {
// TODO: implement.
return value
}
/// Audio-rate ___FILEBASENAMEASIDENTIFIER___.
///
/// - Parameters:
/// - signal: Input signal.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Audio: _Base, AudioGenerator {
/// - Parameters:
/// - signal: Input signal.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public override init(
_ signal: any ValidGeneratorInput,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
super.init(signal, mul: mul, add: add)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
let block = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
let n = block.count
for i: Int in 0..<count {
_result[0][i] = ___FILEBASENAMEASIDENTIFIER___._transform(i < n ? block[i] : 0.0)
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
}
/// Control-rate ___FILEBASENAMEASIDENTIFIER___. Output is linearly interpolated
/// toward the block target.
///
/// - Parameters:
/// - signal: Input signal.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Control: _Base, ControlGenerator {
public var previousOutputValue: Double = 0.0
/// - Parameters:
/// - signal: Input signal.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public override init(
_ signal: any ValidGeneratorInput,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
super.init(signal, mul: mul, add: add)
_setupSubBlockBuffer()
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
var target = ___FILEBASENAMEASIDENTIFIER___._transform(
inputSource.floatValue(graph: graph)
)
if !_mulAdd.isIdentity {
target = target * _mulAdd.mulInput.floatValue(graph: graph)
+ _mulAdd.addInput.floatValue(graph: graph)
}
guard count > 0 else { return _result }
let rampStart: Double = previousOutputValue
previousOutputValue = target
let step = (target - rampStart) / Double(count)
for i: Int in 0..<count {
_result[0][i] = rampStart + step * Double(i + 1)
}
return _result
}
}
}
extension ___FILEBASENAMEASIDENTIFIER___: GeneratorEnum {
public typealias AudioType = ___FILEBASENAMEASIDENTIFIER___.Audio
public typealias ControlType = ___FILEBASENAMEASIDENTIFIER___.Control
}
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Kind</key>
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
<key>Platforms</key>
<array>
<string>com.apple.platform.macosx</string>
<string>com.apple.platform.iphoneos</string>
</array>
<key>Description</key>
<string>A Swift Testing @Suite that exercises a Generator across an engine block. Uses makeTestEngine / makeSynthGraph / advanceBlock helpers (live in Tests/LyrebirdTests/TestHelpers.swift). Includes finite-output + reset-state starter tests.</string>
<key>Summary</key>
<string>Lyrebird Generator Test Suite (@Suite + @Test)</string>
<key>SortOrder</key>
<string>24</string>
<key>AllowedTypes</key>
<array>
<string>public.swift-source</string>
</array>
<key>DefaultCompletionName</key>
<string>MyGeneratorTests</string>
<key>MainTemplateFile</key>
<string>___FILEBASENAME___.swift</string>
<key>Options</key>
<array>
<dict>
<key>Identifier</key>
<string>productName</string>
<key>Required</key>
<true/>
<key>Name</key>
<string>Test suite name:</string>
<key>Description</key>
<string>Name of the test suite type (also used as the file name). Convention: &lt;Type&gt;Tests.</string>
<key>Type</key>
<string>text</string>
<key>Default</key>
<string>MyGeneratorTests</string>
</dict>
</array>
</dict>
</plist>
@@ -0,0 +1,55 @@
//___FILEHEADER___
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - ___FILEBASENAMEASIDENTIFIER___
/// Test suite for ___FILEBASENAMEASIDENTIFIER___'s subject Generator.
///
/// Add @Test methods for: parameter ranges, edge cases (zero / negative freq,
/// out-of-range mul/add, exhausted state, reset), block-size correctness,
/// channel-count claims (`outputChannelCount`), and any RT-safety invariants.
///
/// `makeTestEngine`, `makeSynthGraph`, and `advanceBlock` live in
/// `Tests/LyrebirdTests/TestHelpers.swift` and are intentionally module-internal
/// — this file only compiles when dropped under `Tests/LyrebirdTests/`.
@Suite("___FILEBASENAMEASIDENTIFIER___")
struct ___FILEBASENAMEASIDENTIFIER___ {
/// Subject under test produces finite output for a single block.
@Test func outputIsFinite() throws {
let engine = makeTestEngine(blockSize: 64)
try engine.start()
defer { engine.stop() }
// Replace OscSin.Audio with the Generator you are testing.
let gen = OscSin.Audio(freq: 440.0)
let g = makeSynthGraph(engine: engine)
let out = gen.calculatedSamples(graph: g, count: 64)
let samples = Array((out.first ?? []).prefix(64))
#expect(samples.count == 64)
#expect(samples.allSatisfy { $0.isFinite })
}
/// Subject under test advances state across blocks — output of block 2
/// differs from output of block 1 for a non-DC signal.
@Test func stateAdvancesAcrossBlocks() throws {
let engine = makeTestEngine(blockSize: 64)
try engine.start()
defer { engine.stop() }
let gen = OscSin.Audio(freq: 440.0)
let g1 = makeSynthGraph(engine: engine)
let block1 = Array((gen.calculatedSamples(graph: g1, count: 64).first ?? []).prefix(64))
advanceBlock(engine)
let g2 = makeSynthGraph(engine: engine)
let block2 = Array((gen.calculatedSamples(graph: g2, count: 64).first ?? []).prefix(64))
#expect(block1 != block2, "Generator should advance state between blocks")
}
}
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Kind</key>
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
<key>Platforms</key>
<array>
<string>com.apple.platform.macosx</string>
<string>com.apple.platform.iphoneos</string>
</array>
<key>Description</key>
<string>A MIDI setup factory that opens the CoreMIDI client, registers a handler for incoming MIDIMessage values (noteOn / noteOff / controlChange / …), and returns a started MIDI instance. The handler closure runs on the lyrebird.midi queue — not the RT thread.</string>
<key>Summary</key>
<string>Lyrebird MIDI Handler (CoreMIDI input)</string>
<key>SortOrder</key>
<string>31</string>
<key>AllowedTypes</key>
<array>
<string>public.swift-source</string>
</array>
<key>DefaultCompletionName</key>
<string>MyMIDIHandler</string>
<key>MainTemplateFile</key>
<string>___FILEBASENAME___.swift</string>
<key>Options</key>
<array>
<dict>
<key>Identifier</key>
<string>productName</string>
<key>Required</key>
<true/>
<key>Name</key>
<string>MIDI handler name:</string>
<key>Description</key>
<string>Name of the factory function / type (also used as the file name).</string>
<key>Type</key>
<string>text</string>
<key>Default</key>
<string>MyMIDIHandler</string>
</dict>
</array>
</dict>
</plist>
@@ -0,0 +1,92 @@
//___FILEHEADER___
import Foundation
import LyrebirdSynth
// MARK: - ___FILEBASENAMEASIDENTIFIER___
/// Factory that wires up CoreMIDI input for `engine` and returns a started
/// `MIDI` instance.
///
/// The handler closure runs on the `lyrebird.midi` dispatch queue — not the
/// RT audio thread. From here you can:
/// - Mutate `@LiveParam` slots on Synthesizers (atomic, RT-safe)
/// - Call `engine.add(_:)` / `engine.remove(_:)` (lock-free, applied at the
/// next block boundary)
/// - Start / stop / pause `LyrebirdTask`s
///
/// ## Usage
/// ```swift
/// let midi = try make___FILEBASENAMEASIDENTIFIER___(engine: engine)
/// // …
/// midi.stop() // before engine deallocates
/// ```
///
/// - Parameter engine: Running `SynthesisEngine` whose Synthesizers receive
/// MIDI-driven parameter changes.
/// - Returns: Started `MIDI` with one handler registered.
/// - Throws: `MIDIError.alreadyStarted` if `start()` is called twice.
public func make___FILEBASENAMEASIDENTIFIER___(
engine: SynthesisEngine,
clientName: String = "Lyrebird"
) throws -> MIDI {
let midi = MIDI(engine: engine, clientName: clientName)
_ = midi.addHandler(name: "___FILEBASENAMEASIDENTIFIER___") { message, _ in
switch message {
case .noteOn(let channel, let note, let velocity):
// velocity == 0 is a "running-status" note off — handle as note off.
if velocity == 0 {
handleNoteOff(channel: channel, note: note, velocity: 0)
} else {
handleNoteOn(channel: channel, note: note, velocity: velocity)
}
case .noteOff(let channel, let note, let velocity):
handleNoteOff(channel: channel, note: note, velocity: velocity)
case .controlChange(let channel, let controller, let value):
handleControlChange(channel: channel, controller: controller, value: value)
default:
// pitch bend, channel pressure, polyphonic aftertouch, program
// change, system messages — extend MIDIMessage handling here.
break
}
}
try midi.start()
return midi
}
// MARK: - Per-message handlers (replace bodies with your own)
private func handleNoteOn(channel: UInt8, note: UInt8, velocity: UInt8) {
// TODO: convert (note, velocity) to (Hz, amp) and spawn a voice synth, e.g.
//
// let synth = MyVoice()
// synth.frequency = midiNoteToHz(note)
// synth.amplitude = Double(velocity) / 127.0
// try engine.add(synth)
// voicesByNote[note] = synth
_ = (channel, note, velocity)
}
private func handleNoteOff(channel: UInt8, note: UInt8, velocity: UInt8) {
// TODO: release / remove the voice synth that handleNoteOn started.
_ = (channel, note, velocity)
}
private func handleControlChange(channel: UInt8, controller: UInt8, value: UInt8) {
// TODO: map CCs to Synthesizer @LiveParams. E.g.:
//
// switch controller {
// case 7: masterSynth.amp = Double(value) / 127.0 // CC7 = volume
// case 74: filterSynth.cutoff = ccToCutoff(value) // CC74 = brightness
// default: break
// }
_ = (channel, controller, value)
}
/// Standard MIDI note number → Hz using the 12-tone equal-tempered scale
/// anchored at A4 = 69 = 440 Hz.
private func midiNoteToHz(_ note: UInt8) -> Double {
440.0 * pow(2.0, (Double(note) - 69.0) / 12.0)
}
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Kind</key>
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
<key>Platforms</key>
<array>
<string>com.apple.platform.macosx</string>
<string>com.apple.platform.iphoneos</string>
</array>
<key>Description</key>
<string>A multi-channel audio Generator that returns N rows from _computeSamples. Calls super.init(channels: N) to allocate N pre-allocated result rows; overrides outputChannelCount to expose the fixed channel count. Modeled on Pan2's two-channel shape. Pass directly to output(bus:source:) — Out writes channel k to bus+k.</string>
<key>Summary</key>
<string>Lyrebird Multi-Channel Generator (N-row output)</string>
<key>SortOrder</key>
<string>21</string>
<key>AllowedTypes</key>
<array>
<string>public.swift-source</string>
</array>
<key>DefaultCompletionName</key>
<string>MyMultiChannel</string>
<key>MainTemplateFile</key>
<string>___FILEBASENAME___.swift</string>
<key>Options</key>
<array>
<dict>
<key>Identifier</key>
<string>productName</string>
<key>Required</key>
<true/>
<key>Name</key>
<string>Generator name:</string>
<key>Description</key>
<string>Name of the multi-channel Generator class (also used as the file name).</string>
<key>Type</key>
<string>text</string>
<key>Default</key>
<string>MyMultiChannel</string>
</dict>
</array>
</dict>
</plist>
@@ -0,0 +1,85 @@
//___FILEHEADER___
import Foundation
@_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - ___FILEBASENAMEASIDENTIFIER___
/// One-line description of ___FILEBASENAMEASIDENTIFIER___.
///
/// Returns N output channels per render block. The channel count is fixed at
/// init time via `super.init(channels: N)` — `GeneratorBase` pre-allocates the
/// `_result` buffer with N rows. `outputChannelCount` returns the same N so
/// downstream operators (`+`, `-`, `*`, `/`) treat this as multi-channel rather
/// than mono.
///
/// Channel count must be derivable from a `let` at init — never runtime-mutable.
/// To support a user-chosen channel count, accept it as an `Int` init parameter
/// (see Pan4 etc).
///
/// ## Usage
/// ```swift
/// override func build() {
/// let src = OscSin.Audio(freq: 440.0)
/// // Out writes channel k to bus+k:
/// output(bus: 0, source: ___FILEBASENAMEASIDENTIFIER___(input: src))
/// }
/// ```
public final class ___FILEBASENAMEASIDENTIFIER___: GeneratorBase, AudioGenerator {
// MARK: - Channel count (fixed at init)
/// Output channel count. Hard-coded here as a starting value — replace with an
/// init parameter if your generator needs user-chosen channel counts.
private static let outChannels: Int = 2
public override var outputChannelCount: Int { Self.outChannels }
// MARK: - Inputs
private let _input: any ValidGeneratorInput
private let _mulAdd: MulAddSpec
// MARK: - Init
/// - Parameters:
/// - input: Source signal. Mono input fans out across all channels by
/// default; multi-row input maps element-wise (mismatched channel counts
/// should `precondition`-trap at init).
/// - mul: Output multiplier. Defaults to `1.0`. Channel-aware: scalar
/// broadcasts, equal-N multi-row applies element-wise.
/// - add: Output offset. Defaults to `0.0`. Same channel-aware policy.
public init(
input: any ValidGeneratorInput,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
_input = input
_mulAdd = MulAddSpec(mul: mul, add: add)
super.init(channels: Self.outChannels)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
let inputSamples = _input.calculatedSamples(graph: graph, count: count)
guard let ins = inputSamples.first else { return _result }
// TODO: replace this body with whatever per-channel processing you want.
// The starter logic copies the first input row into every output row —
// i.e. fans a mono source out to N identical channels. Real generators
// typically produce different content per channel (panning, decoder
// matrices, multi-bus routing, etc.).
for ch: Int in 0..<Self.outChannels {
for i: Int in 0..<count {
_result[ch][i] = ins[i]
}
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
}
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Kind</key>
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
<key>Platforms</key>
<array>
<string>com.apple.platform.macosx</string>
<string>com.apple.platform.iphoneos</string>
</array>
<key>Description</key>
<string>Top-level main.swift that renders a Lyrebird Synthesizer to disk via NRTDriver. NRT mode renders the full duration synchronously inside engine.start(). Drop this into the Sources directory of an executableTarget — Synthesizers must be added BEFORE start().</string>
<key>Summary</key>
<string>Lyrebird NRT Render (main.swift offline driver)</string>
<key>SortOrder</key>
<string>25</string>
<key>AllowedTypes</key>
<array>
<string>public.swift-source</string>
</array>
<key>DefaultCompletionName</key>
<string>main</string>
<key>MainTemplateFile</key>
<string>___FILEBASENAME___.swift</string>
<key>Options</key>
<array>
<dict>
<key>Identifier</key>
<string>productName</string>
<key>Required</key>
<true/>
<key>Name</key>
<string>File name:</string>
<key>Description</key>
<string>File name. Conventional Swift entry-point name is "main" for executableTargets.</string>
<key>Type</key>
<string>text</string>
<key>Default</key>
<string>main</string>
</dict>
</array>
</dict>
</plist>
@@ -0,0 +1,55 @@
//___FILEHEADER___
//
// Top-level main.swift — drop this into an executableTarget's Sources directory.
// NRT mode renders synchronously inside engine.start(); the call blocks until
// `duration` seconds of audio have been written to `outputURL`.
import Foundation
import LyrebirdSynth
// MARK: - Synthesizer
/// Replace this with your own Synthesizer. NRT renders whatever is in the engine
/// at the moment `start()` is called — Synthesizers added later via
/// `engine.add(_:)` will not be heard because the render loop has already exited.
final class ___FILEBASENAMEASIDENTIFIER______Synth: SynthesizerBase {
override func build() {
let env = EnvelopeGen.Audio(
envelope: Envelope(
levels: [0.0, 1.0, 0.6, 0.0],
durations: [0.02, 0.46, 0.5],
curves: [.lin, .exponential, .exponential]
),
doneAction: .freeNode
)
let osc = OscSin.Audio(freq: 440.0) * env * 0.3
output(bus: 0, source: Pan2(input: osc))
}
}
// MARK: - Render
let outputURL: URL = URL(fileURLWithPath: "output.caf")
let renderDuration: Double = 4.0
let blockSize: Int = 512
let sampleRate: Double = 44100
let numOutputChannels: Int = 2
let engine = SynthesisEngine(
blockSize: blockSize,
sampleRate: sampleRate,
numOutputChannels: numOutputChannels,
numInputChannels: 0,
driver: NRTDriver(outputURL: outputURL, duration: renderDuration)
)
// Synthesizers must be added BEFORE start() — NRTDriver renders the full
// duration synchronously inside start() and returns once the file is closed.
do {
try engine.add(___FILEBASENAMEASIDENTIFIER______Synth())
try engine.start()
print("Rendered \(renderDuration)s → \(outputURL.path)")
} catch {
fputs("Render failed: \(error)\n", stderr)
exit(1)
}
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Kind</key>
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
<key>Platforms</key>
<array>
<string>com.apple.platform.macosx</string>
<string>com.apple.platform.iphoneos</string>
</array>
<key>Description</key>
<string>A Lyrebird noise generator extending NoiseBase. Inherits rngState and _mulAdd, and uses the xorshift64 PRNG. Audio variant draws one sample per output sample; Control variant draws once per audio block and emits a linear ramp.</string>
<key>Summary</key>
<string>Lyrebird Noise Generator (NoiseBase subclass)</string>
<key>SortOrder</key>
<string>14</string>
<key>AllowedTypes</key>
<array>
<string>public.swift-source</string>
</array>
<key>DefaultCompletionName</key>
<string>MyNoise</string>
<key>MainTemplateFile</key>
<string>___FILEBASENAME___.swift</string>
<key>Options</key>
<array>
<dict>
<key>Identifier</key>
<string>productName</string>
<key>Required</key>
<true/>
<key>Name</key>
<string>Noise name:</string>
<key>Description</key>
<string>Name of the noise enum (also used as the file name).</string>
<key>Type</key>
<string>text</string>
<key>Default</key>
<string>MyNoise</string>
</dict>
</array>
</dict>
</plist>
@@ -0,0 +1,138 @@
//___FILEHEADER___
//
// In-tree template — drop this file under Sources/Lyrebird/Generators/Noise/.
// Extends `NoiseBase`, whose designated init is module-internal, so this
// template is not usable from a project that depends on Lyrebird as a package.
// External users should start from the basic `LyrebirdGenerator` template and
// declare rngState + xorshift64 inline.
// MARK: - ___FILEBASENAMEASIDENTIFIER___
/// One-line description of ___FILEBASENAMEASIDENTIFIER___.
///
/// Extends `NoiseBase` so `rngState: UInt64` and `_mulAdd` are inherited.
/// Use `xorshift64Next(&rngState)` to draw a `[-1, 1]` sample per call.
///
/// Each instance is independently seeded — concurrent instances produce
/// uncorrelated output.
///
/// ## Usage
/// ```swift
/// let n = ___FILEBASENAMEASIDENTIFIER___.Audio()
/// let n = ___FILEBASENAMEASIDENTIFIER___.Audio(seed: 42) // deterministic for tests
/// ```
public enum ___FILEBASENAMEASIDENTIFIER___ {
/// Shared PRNG state and output buffer for both rate variants.
public class _Base: NoiseBase {
override init(
initialRngState: UInt64,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
super.init(initialRngState: initialRngState, mul: mul, add: add)
}
/// Draw one sample in `[-1, 1]`. Replace this body with any
/// distribution-shaping logic — clip, fold, threshold, etc.
func nextSample() -> Double { xorshift64Next(&rngState) }
}
/// Audio-rate ___FILEBASENAMEASIDENTIFIER___.
///
/// - Parameters:
/// - seed: PRNG seed. Defaults to a time-derived value for unique instances.
/// Pass an explicit seed for reproducible test output.
/// - mul: Output multiplier applied after synthesis. Defaults to `1.0`.
/// - add: Offset added after multiplier. Defaults to `0.0`.
public final class Audio: _Base, AudioGenerator {
/// - Parameters:
/// - seed: PRNG seed.
/// - mul: Output multiplier.
/// - add: Output offset.
public init(
seed: UInt64? = nil,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
// Pick a unique mix constant so this Audio variant doesn't correlate
// with sibling Control / sibling generators when both default-seed
// within the same nanosecond.
let audioMixConstant: UInt64 = 0xA110_AAAA_5A5A_3C3C
let initialRngState = lyrebirdSeedXorshift64(from: seed, mixConstant: audioMixConstant)
super.init(initialRngState: initialRngState, mul: mul, add: add)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
for i: Int in 0..<count {
_result[0][i] = nextSample()
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
}
/// Control-rate ___FILEBASENAMEASIDENTIFIER___ — draws one new value per
/// audio block, emits a linear ramp to the new target. Override
/// `calculatedSamples` bypasses the sub-block loop so the draw rate stays
/// at one per audio block regardless of `controlBlockSize`.
///
/// - Parameters:
/// - seed: PRNG seed. Defaults to a time-derived value.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Control: _Base, ControlGenerator {
public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 0.0
/// - Parameters:
/// - seed: PRNG seed.
/// - mul: Output multiplier.
/// - add: Output offset.
public init(
seed: UInt64? = nil,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
let controlMixConstant: UInt64 = 0xB220_BBBB_A5A5_C3C3
let initialRngState = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant)
super.init(initialRngState: initialRngState, mul: mul, add: add)
_setupSubBlockBuffer()
}
// Bypass sub-block loop: one draw per audio block regardless of cbs.
public func calculatedSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_calculatedSamplesBlockRate(graph: graph, count: count)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
let target: Double = nextSample()
let rampStart: Double = _rampTarget
_rampTarget = target
guard count > 0 else { return _result }
previousOutputValue = fillRampedResult(
into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count)
return _result
}
}
}
extension ___FILEBASENAMEASIDENTIFIER___: GeneratorEnum {
public typealias AudioType = ___FILEBASENAMEASIDENTIFIER___.Audio
public typealias ControlType = ___FILEBASENAMEASIDENTIFIER___.Control
}
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Kind</key>
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
<key>Platforms</key>
<array>
<string>com.apple.platform.macosx</string>
<string>com.apple.platform.iphoneos</string>
</array>
<key>Description</key>
<string>An OSCServer setup factory that binds a UDP port, registers handlers for OSC address patterns (with glob/wildcard support), and returns a started server. Handler closures run on the lyrebird.osc.handlers queue — not the RT thread.</string>
<key>Summary</key>
<string>Lyrebird OSC Handler (UDP server)</string>
<key>SortOrder</key>
<string>32</string>
<key>AllowedTypes</key>
<array>
<string>public.swift-source</string>
</array>
<key>DefaultCompletionName</key>
<string>MyOSCHandler</string>
<key>MainTemplateFile</key>
<string>___FILEBASENAME___.swift</string>
<key>Options</key>
<array>
<dict>
<key>Identifier</key>
<string>productName</string>
<key>Required</key>
<true/>
<key>Name</key>
<string>OSC handler name:</string>
<key>Description</key>
<string>Name of the factory function (also used as the file name).</string>
<key>Type</key>
<string>text</string>
<key>Default</key>
<string>MyOSCHandler</string>
</dict>
</array>
</dict>
</plist>
@@ -0,0 +1,73 @@
//___FILEHEADER___
import Foundation
import LyrebirdSynth
// MARK: - ___FILEBASENAMEASIDENTIFIER___
/// Factory that opens a `OSCServer` on `port`, registers handlers for
/// a few starter address patterns, and returns a started server.
///
/// Handler closures run on the `lyrebird.osc.handlers` dispatch queue — not
/// the RT audio thread. From a handler you can:
/// - Mutate `@LiveParam` slots on Synthesizers (atomic, RT-safe)
/// - Call `engine.add(_:)` / `engine.remove(_:)` (lock-free)
/// - Start / stop / pause `LyrebirdTask`s
///
/// `addHandler(address:)` accepts OSC 1.0 glob patterns:
/// - `?` — any single character
/// - `*` — any sequence excluding `/`
/// - `[abc]` / `[a-z]` — character class
/// - `{a,b}` — alternation
///
/// ## Usage
/// ```swift
/// let osc = try make___FILEBASENAMEASIDENTIFIER___(engine: engine, port: 57120)
/// // …
/// osc.stop()
/// ```
public func make___FILEBASENAMEASIDENTIFIER___(
engine: SynthesisEngine,
port: UInt16 = 57120
) throws -> OSCServer {
let server = OSCServer(port: port, engine: engine)
// /freq <float|int> → set a frequency parameter somewhere.
server.addHandler(address: "/freq") { msg, _ in
guard let arg = msg.arguments.first else { return }
let hz = doubleValue(arg)
// TODO: route `hz` to your Synthesizer's frequency @LiveParam.
_ = hz
}
// /amp <float|int> → set a gain parameter.
server.addHandler(address: "/amp") { msg, _ in
guard let arg = msg.arguments.first else { return }
let gain = doubleValue(arg)
// TODO: route `gain` (typically [0, 1]) to your master amplitude.
_ = gain
}
// /note/{on,off} → spawn / release voice synths.
server.addHandler(address: "/note/{on,off}") { msg, _ in
// Inspect msg.address to branch; arguments are [note: Int32, vel: Float].
// TODO: spawn / release a voice synth.
_ = msg
}
try server.start()
return server
}
// MARK: - Argument helpers
/// Coerce an `OSCArgument` to `Double` for parameter assignment.
/// Returns `0.0` for non-numeric types.
private func doubleValue(_ arg: OSCArgument) -> Double {
switch arg {
case .int32(let v): return Double(v)
case .float32(let v): return Double(v)
case .bool(let v): return v ? 1.0 : 0.0
default: return 0.0
}
}
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Kind</key>
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
<key>Platforms</key>
<array>
<string>com.apple.platform.macosx</string>
<string>com.apple.platform.iphoneos</string>
</array>
<key>Description</key>
<string>A Lyrebird oscillator extending OscillatorBase (in-tree only — extends a module-internal base). Drop this file under Sources/Lyrebird/Generators/Oscillators/. Inherits _phase, _freqInput, _freqIsGenerator, and _mulAdd. Audio variant evaluates phase per sample; Control variant advances phase once per audio block via _calculatedSamplesBlockRate.</string>
<key>Summary</key>
<string>Lyrebird Oscillator (OscillatorBase subclass)</string>
<key>SortOrder</key>
<string>13</string>
<key>AllowedTypes</key>
<array>
<string>public.swift-source</string>
</array>
<key>DefaultCompletionName</key>
<string>MyOsc</string>
<key>MainTemplateFile</key>
<string>___FILEBASENAME___.swift</string>
<key>Options</key>
<array>
<dict>
<key>Identifier</key>
<string>productName</string>
<key>Required</key>
<true/>
<key>Name</key>
<string>Oscillator name:</string>
<key>Description</key>
<string>Name of the oscillator enum (also used as the file name).</string>
<key>Type</key>
<string>text</string>
<key>Default</key>
<string>MyOsc</string>
</dict>
</array>
</dict>
</plist>
@@ -0,0 +1,177 @@
//___FILEHEADER___
//
// In-tree template — drop this file under Sources/Lyrebird/Generators/Oscillators/.
// Extends `OscillatorBase`, whose designated init is module-internal, so this
// template is not usable from a project that depends on Lyrebird as a package.
// External users should start from the basic `LyrebirdGenerator` template and
// declare phase / freq / MulAddSpec inline.
// MARK: - ___FILEBASENAMEASIDENTIFIER___
/// One-line description of ___FILEBASENAMEASIDENTIFIER___.
///
/// Extends `OscillatorBase` so the standard `_phase` / `_freqInput` /
/// `_freqIsGenerator` / `_mulAdd` fields are inherited — no need to redeclare them.
/// `super.init(freq:phase:mul:add:)` normalises `phase` into `[0, 1)`.
///
/// ## Usage
/// ```swift
/// let osc = ___FILEBASENAMEASIDENTIFIER___.Audio(freq: 440.0)
/// let lfo = ___FILEBASENAMEASIDENTIFIER___.Control(freq: 2.0)
/// ```
///
/// - Parameters:
/// - freq: Frequency in Hz. No internal clamping; aliasing increases toward Nyquist.
/// - phase: Initial phase offset in normalized cycles `[0, 1)`. Defaults to `0.0`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public enum ___FILEBASENAMEASIDENTIFIER___ {
/// Shared base — inherits all oscillator state from `OscillatorBase`.
public class _Base: OscillatorBase {}
/// Per-sample waveform function. Replace the formula below — `phase` is in
/// `[0, 1)`, output should typically be `[-1, 1]`.
@inline(__always)
static func _waveform(_ phase: Double) -> Double {
// Default: sawtooth. Replace with your formula.
return 2.0 * phase - 1.0
}
/// Audio-rate ___FILEBASENAMEASIDENTIFIER___. Evaluates frequency per sample.
///
/// - Parameters:
/// - freq: Frequency in Hz. No internal clamping.
/// - phase: Initial phase offset in normalized cycles `[0, 1)`. Defaults to `0.0`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Audio: _Base, AudioGenerator {
/// - Parameters:
/// - freq: Frequency in Hz. No internal clamping.
/// - phase: Initial phase offset in normalized cycles `[0, 1)`. Defaults to `0.0`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public override init(
freq: any ValidGeneratorInput,
phase: Double = 0.0,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
super.init(freq: freq, phase: phase, mul: mul, add: add)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
let sampleRate = Double(graph.engine.sampleRate)
let freqSamples: [Double]?
let scalarDt: Double
if _freqIsGenerator {
freqSamples = _freqInput.calculatedSamples(graph: graph, count: count).first
scalarDt = 0
} else {
freqSamples = nil
scalarDt = _freqInput.floatValue(graph: graph) / sampleRate
}
for i: Int in 0..<count {
let dt: Double
if let fs: [Double] = freqSamples {
dt = (i < fs.count ? fs[i] : 0) / sampleRate
} else {
dt = scalarDt
}
_result[0][i] = ___FILEBASENAMEASIDENTIFIER___._waveform(_phase)
_phase += dt
if _phase >= 1.0 { _phase -= 1.0 }
else if _phase < 0.0 { _phase += 1.0 }
if _phase >= 1.0 || _phase < 0.0 {
_phase = _phase.truncatingRemainder(dividingBy: 1.0)
if _phase < 0.0 { _phase += 1.0 }
}
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
}
/// Control-rate ___FILEBASENAMEASIDENTIFIER___. Advances phase once per audio block,
/// emits a linear ramp toward the new target.
///
/// - Parameters:
/// - freq: Frequency in Hz. No internal clamping.
/// - phase: Initial phase offset in normalized cycles `[0, 1)`. Defaults to `0.0`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Control: _Base, ControlGenerator {
public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 0.0
/// - Parameters:
/// - freq: Frequency in Hz. No internal clamping.
/// - phase: Initial phase offset in normalized cycles `[0, 1)`. Defaults to `0.0`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public override init(
freq: any ValidGeneratorInput,
phase: Double = 0.0,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
super.init(freq: freq, phase: phase, mul: mul, add: add)
_setupSubBlockBuffer()
}
// Bypass sub-block loop: phase advances exactly once per audio block.
public func calculatedSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_calculatedSamplesBlockRate(graph: graph, count: count)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
let sampleRate = Double(graph.engine.sampleRate)
let countFloat: Double = Double(count)
let freq: Double
if _freqIsGenerator {
freq = _freqInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0
} else {
freq = _freqInput.floatValue(graph: graph)
}
let dt = freq / sampleRate
_phase += dt * countFloat
normalizeLFPhase(&_phase)
let target = ___FILEBASENAMEASIDENTIFIER___._waveform(_phase)
let rampStart: Double = _rampTarget
_rampTarget = target
guard count > 0 else { return _result }
previousOutputValue = fillRampedResult(
into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count)
return _result
}
}
}
extension ___FILEBASENAMEASIDENTIFIER___: GeneratorEnum {
public typealias AudioType = ___FILEBASENAMEASIDENTIFIER___.Audio
public typealias ControlType = ___FILEBASENAMEASIDENTIFIER___.Control
}
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Kind</key>
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
<key>Platforms</key>
<array>
<string>com.apple.platform.macosx</string>
<string>com.apple.platform.iphoneos</string>
</array>
<key>Description</key>
<string>A LyrebirdProcess factory function. Returns a configured process with an envelope-governed lifetime, an async body closure that adds synths and waits, and optional onRelease / onFinished callbacks. Equivalent to SuperCollider's ProcMod.</string>
<key>Summary</key>
<string>Lyrebird Process (envelope-governed audio process)</string>
<key>SortOrder</key>
<string>34</string>
<key>AllowedTypes</key>
<array>
<string>public.swift-source</string>
</array>
<key>DefaultCompletionName</key>
<string>MyProcess</string>
<key>MainTemplateFile</key>
<string>___FILEBASENAME___.swift</string>
<key>Options</key>
<array>
<dict>
<key>Identifier</key>
<string>productName</string>
<key>Required</key>
<true/>
<key>Name</key>
<string>Process name:</string>
<key>Description</key>
<string>Name of the process factory function (also used as the file name).</string>
<key>Type</key>
<string>text</string>
<key>Default</key>
<string>MyProcess</string>
</dict>
</array>
</dict>
</plist>
@@ -0,0 +1,90 @@
//___FILEHEADER___
import Foundation
import LyrebirdSynth
// MARK: - ___FILEBASENAMEASIDENTIFIER___
/// Factory for a self-contained `LyrebirdProcess`. The process allocates a
/// private route bus, spawns an envelope-driven synth that mixes from that
/// bus to `procOut`, and runs the `body` closure on an async task.
///
/// Lyrebird equivalent of SuperCollider's `ProcMod`.
///
/// ## Lifecycle
/// 1. `play(engine:)` — allocate resources, start the envelope + body task.
/// 2. While running — add synths via `ctx.add(_:)`, wait via `ctx.wait(_:)`,
/// mutate `amp` from any thread.
/// 3. `release()` — open the envelope gate; tail plays out, process auto-frees.
/// (Only meaningful when the envelope has a `releaseNode`.)
/// 4. `kill()` — force teardown regardless of envelope state.
///
/// ## Usage
/// ```swift
/// let factory = ___FILEBASENAMEASIDENTIFIER___()
/// let proc = factory.createProcess()
/// proc.play(engine: engine)
/// // …
/// proc.release() // graceful — runs the envelope tail
/// // or: proc.kill() // immediate
/// ```
public struct ___FILEBASENAMEASIDENTIFIER___: LyrebirdProcessFactory {
public init() {}
public func createProcess() -> LyrebirdProcess {
LyrebirdProcess(
id: "___FILEBASENAMEASIDENTIFIER___",
envelope: Envelope(
// 4-point envelope: attack → sustain → release → silence.
// releaseNode index 2 means "hold at level[2] until release() is called",
// then continue from there to the end.
levels: [0.0, 1.0, 0.6, 0.0],
durations: [0.05, 0.5, 1.5],
curves: [.sine, .exponential, .exponential],
releaseNode: 2
),
amp: 0.8,
ampLag: 0.02,
numChannels: 2,
procOut: 0, // hardware output; overridden by a parent EventList
target: .tail,
body: { ctx in
// The process body runs as an async Task. Schedule synths and
// wait between events. The task is cancelled on `release()` /
// `kill()` — `ctx.wait` re-throws CancellationError, which the
// surrounding LyrebirdProcess infrastructure handles cleanly.
//
// Replace the starter body below with your event sequence.
let synth: ExampleNote = ExampleNote()
ctx.add(synth)
await ctx.wait(0.1) // let the attack settle
},
onRelease: { ctx in
// Optional. Called on main thread when release() is invoked,
// before the envelope tail begins. Use to mutate / remove synths
// before the fade.
_ = ctx
},
onFinished: {
// Optional. Called on main thread after the group and route bus
// are freed. Resources are already gone — no context available.
}
)
}
}
// MARK: - Example Synthesizer used by the process body
/// Replace this stub with your own Synthesizer. The body closure above adds
/// one instance; rewrite the body to schedule whatever pattern fits your
/// process.
private final class ExampleNote: SynthesizerBase {
@LiveParam var frequency: Double = 440.0
override func build() {
let osc = OscSin.Audio(freq: $frequency)
output(bus: 0, source: osc * 0.5)
}
}
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Kind</key>
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
<key>Platforms</key>
<array>
<string>com.apple.platform.macosx</string>
<string>com.apple.platform.iphoneos</string>
</array>
<key>Description</key>
<string>A SpectralProcessor — transforms a SpectralBuffer in-place after each FFT hop. Runs on the RT thread; mutate magnitude/phase per bin with no allocation, no locking. Use with SpectralChain.Audio as a .mono stage.</string>
<key>Summary</key>
<string>Lyrebird Spectral Processor (FFT-domain transform)</string>
<key>SortOrder</key>
<string>30</string>
<key>AllowedTypes</key>
<array>
<string>public.swift-source</string>
</array>
<key>DefaultCompletionName</key>
<string>MySpectralProcessor</string>
<key>MainTemplateFile</key>
<string>___FILEBASENAME___.swift</string>
<key>Options</key>
<array>
<dict>
<key>Identifier</key>
<string>productName</string>
<key>Required</key>
<true/>
<key>Name</key>
<string>SpectralProcessor name:</string>
<key>Description</key>
<string>Name of the SpectralProcessor class (also used as the file name).</string>
<key>Type</key>
<string>text</string>
<key>Default</key>
<string>MySpectralProcessor</string>
</dict>
</array>
</dict>
</plist>
@@ -0,0 +1,62 @@
//___FILEHEADER___
import Foundation
import LyrebirdSynth
// MARK: - ___FILEBASENAMEASIDENTIFIER___
/// One-line description of ___FILEBASENAMEASIDENTIFIER___.
///
/// A `SpectralProcessor` transforms the FFT-domain `SpectralBuffer`
/// in-place after each forward-FFT hop. Wire it into a `SpectralChain.Audio`
/// as a `.mono` stage:
///
/// ```swift
/// let proc = ___FILEBASENAMEASIDENTIFIER___()
/// let chain = SpectralChain.Audio(
/// input: source,
/// fftSize: 2048,
/// stages: [.mono(proc)]
/// )
/// output(bus: 0, source: chain)
/// ```
///
/// ## RT contract
///
/// `process(spectral:)` runs on the RT thread. It must:
/// - Not allocate
/// - Not lock
/// - Not call into Foundation / Swift stdlib methods that may allocate
///
/// Read parameters from `@LiveParam` slots on a Synthesizer that owns this
/// processor — those reads are atomic and RT-safe.
public final class ___FILEBASENAMEASIDENTIFIER___: SpectralProcessor {
// MARK: - Configuration
/// Internal state that controls the spectral transform. Mutate from non-RT
/// threads via atomic operations or `@LiveParam`-style projections.
private var _someParameter: Double = 1.0
// MARK: - Init
public init() {
// No allocation paths should run after this point on the RT thread.
}
// MARK: - SpectralProcessor
public func process(spectral: SpectralBuffer, engine: SynthesisEngine) {
// Walk every bin in the half-spectrum [0, binCount). DC and Nyquist
// are real-only — phase at those bins is undefined.
//
// The starter body below applies a uniform magnitude scale to every
// bin. Replace with your transform (spectral filtering, formant shift,
// freezing, cross-synthesis, etc.). The subscripts compile to direct
// memory reads/writes through the buffer's pre-allocated storage.
for bin in 0..<spectral.binCount {
let mag = spectral[magnitude: bin]
spectral[magnitude: bin] = mag * Float(_someParameter)
}
}
}
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Kind</key>
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
<key>Platforms</key>
<array>
<string>com.apple.platform.macosx</string>
<string>com.apple.platform.iphoneos</string>
</array>
<key>Description</key>
<string>A Lyrebird Synthesizer subclassing SynthesizerBase with @LiveParam parameter slots and a build() body wiring a small signal graph to output bus 0. Pair with engine.add(_:) to start audio.</string>
<key>Summary</key>
<string>Lyrebird Synthesizer (SynthesizerBase + @LiveParam)</string>
<key>SortOrder</key>
<string>11</string>
<key>AllowedTypes</key>
<array>
<string>public.swift-source</string>
</array>
<key>DefaultCompletionName</key>
<string>MySynth</string>
<key>MainTemplateFile</key>
<string>___FILEBASENAME___.swift</string>
<key>Options</key>
<array>
<dict>
<key>Identifier</key>
<string>productName</string>
<key>Required</key>
<true/>
<key>Name</key>
<string>Synthesizer name:</string>
<key>Description</key>
<string>Name of the Synthesizer subclass (also used as the file name).</string>
<key>Type</key>
<string>text</string>
<key>Default</key>
<string>MySynth</string>
</dict>
</array>
</dict>
</plist>
@@ -0,0 +1,41 @@
//___FILEHEADER___
import Foundation
import LyrebirdSynth
// MARK: - ___FILEBASENAMEASIDENTIFIER___
/// One-line description of ___FILEBASENAMEASIDENTIFIER___.
///
/// Subclasses `SynthesizerBase`. `@LiveParam` slots are atomic, RT-safe to
/// assign from any thread; the audio thread reads them with acquiring loads.
///
/// ## Usage
/// ```swift
/// let synth = ___FILEBASENAMEASIDENTIFIER___()
/// try engine.add(synth)
///
/// // Mutate while audio runs — no try, no throws.
/// synth.frequency = 880.0
///
/// engine.remove(synth)
/// ```
public final class ___FILEBASENAMEASIDENTIFIER___: SynthesizerBase {
// MARK: - Parameters
/// Fundamental frequency in Hz.
@LiveParam public var frequency: Double = 440.0
/// Output amplitude (linear gain). `0.0` = silence, `1.0` = unity.
@LiveParam public var amplitude: Double = 0.25
// MARK: - Build
public override func build() {
// Wire the signal graph here. Use `$paramName` (projected value) to
// pass a LiveParam as a generator input — it tracks runtime changes.
let osc = OscSin.Audio(freq: $frequency)
output(bus: 0, source: osc * $amplitude)
}
}
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Kind</key>
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
<key>Platforms</key>
<array>
<string>com.apple.platform.macosx</string>
<string>com.apple.platform.iphoneos</string>
</array>
<key>Description</key>
<string>A SynthesizerBase subclass with @UIParam slots — exposes parameters that bind to ParameterKnob / ParameterSlider in SwiftUI. Includes a starter build() with sine + Pan2. Pair with a SwiftUI view that takes the synth and reads synth.$paramName for each control. Requires LyrebirdUI module.</string>
<key>Summary</key>
<string>Lyrebird Synthesizer (UI-bindable @UIParam)</string>
<key>SortOrder</key>
<string>22</string>
<key>AllowedTypes</key>
<array>
<string>public.swift-source</string>
</array>
<key>DefaultCompletionName</key>
<string>MyUISynth</string>
<key>MainTemplateFile</key>
<string>___FILEBASENAME___.swift</string>
<key>Options</key>
<array>
<dict>
<key>Identifier</key>
<string>productName</string>
<key>Required</key>
<true/>
<key>Name</key>
<string>Synthesizer name:</string>
<key>Description</key>
<string>Name of the Synthesizer subclass (also used as the file name).</string>
<key>Type</key>
<string>text</string>
<key>Default</key>
<string>MyUISynth</string>
</dict>
</array>
</dict>
</plist>
@@ -0,0 +1,49 @@
//___FILEHEADER___
import Foundation
import LyrebirdSynth
import LyrebirdUI
// MARK: - ___FILEBASENAMEASIDENTIFIER___
/// One-line description of ___FILEBASENAMEASIDENTIFIER___.
///
/// `@UIParam` slots expose both an atomic RT-safe parameter (like `@LiveParam`)
/// AND a `UIParamNode` projected value that binds directly to SwiftUI controls
/// in the LyrebirdUI module — `ParameterKnob`, `ParameterSlider`, `ParameterXY`.
///
/// ## Usage
/// ```swift
/// let synth = ___FILEBASENAMEASIDENTIFIER___()
/// try engine.add(synth)
///
/// // In a SwiftUI View:
/// VStack {
/// ParameterKnob("Freq", node: synth.$frequency, range: 110...880)
/// ParameterKnob("Amp", node: synth.$amplitude, range: 0...1)
/// ParameterKnob("Pan", node: synth.$pan, range: -1...1)
/// }
///
/// // From code, mutate directly — atomic, RT-safe:
/// synth.frequency = 660.0
/// ```
public final class ___FILEBASENAMEASIDENTIFIER___: SynthesizerBase {
// MARK: - Parameters
/// Fundamental frequency in Hz.
@UIParam public var frequency: Double = 440.0
/// Output amplitude (linear gain). `0.0` = silence, `1.0` = unity.
@UIParam public var amplitude: Double = 0.25
/// Stereo pan. `-1` = hard left, `0` = center, `+1` = hard right.
@UIParam public var pan: Double = 0.0
// MARK: - Build
public override func build() {
let osc = OscSin.Audio(freq: $frequency)
output(bus: 0, source: Pan2(input: osc * $amplitude, pan: $pan))
}
}
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Kind</key>
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
<key>Platforms</key>
<array>
<string>com.apple.platform.macosx</string>
<string>com.apple.platform.iphoneos</string>
</array>
<key>Description</key>
<string>A LyrebirdTask factory function — emits a closure-bodied LyrebirdTask that schedules Synthesizer events on a background thread, with pause/resume/stop support. Use the LyrebirdRoutineContext to add nodes and wait between events.</string>
<key>Summary</key>
<string>Lyrebird Task (scheduling factory)</string>
<key>SortOrder</key>
<string>12</string>
<key>AllowedTypes</key>
<array>
<string>public.swift-source</string>
</array>
<key>DefaultCompletionName</key>
<string>MyTask</string>
<key>MainTemplateFile</key>
<string>___FILEBASENAME___.swift</string>
<key>Options</key>
<array>
<dict>
<key>Identifier</key>
<string>productName</string>
<key>Required</key>
<true/>
<key>Name</key>
<string>Task name:</string>
<key>Description</key>
<string>Name of the task factory (also used as the file name). The factory function is named make&lt;Name&gt;().</string>
<key>Type</key>
<string>text</string>
<key>Default</key>
<string>MyTask</string>
</dict>
</array>
</dict>
</plist>
@@ -0,0 +1,61 @@
//___FILEHEADER___
import Foundation
import LyrebirdSynth
// MARK: - ___FILEBASENAMEASIDENTIFIER___
/// Factory for a `LyrebirdTask` that runs a scheduled-event loop on its own
/// background thread.
///
/// The task body receives a `LyrebirdRoutineContext` providing:
/// - `add(_:)` — attach a Synthesizer to the engine
/// - `wait(seconds:)` — sleep, respecting `pause()` / `stop()`
/// - `wait(beats:tempo:)` — tempo-aware sleep
///
/// Throwing `LyrebirdRoutineError.stopped` (raised internally by `wait` when
/// `stop()` is called) exits cleanly.
///
/// ## Usage
/// ```swift
/// let task = make___FILEBASENAMEASIDENTIFIER___()
/// task.start(engine: engine)
///
/// task.pause() // freeze event stream
/// task.resume() // continue from where it stopped
/// task.stop() // exit the loop cleanly
/// ```
public func make___FILEBASENAMEASIDENTIFIER___() -> LyrebirdTask {
LyrebirdTask { ctx in
// Replace this with whatever event sequence the task should run.
// The example below schedules one short Synthesizer every 250 ms
// until `stop()` is called.
while true {
let note: ExampleNote = ExampleNote()
ctx.add(note)
try ctx.wait(seconds: 0.25)
}
}
}
// MARK: - Example Synthesizer used by the task
/// Minimal Synthesizer scheduled by `make___FILEBASENAMEASIDENTIFIER___`.
/// Replace with your own Synthesizer type and remove this stub.
private final class ExampleNote: SynthesizerBase {
@LiveParam var frequency: Double = 440.0
override func build() {
let env = EnvelopeGen.Audio(
envelope: Envelope(
levels: [0.0, 1.0, 0.0],
durations: [0.005, 0.2],
curves: [.lin, .exponential]
),
doneAction: .freeNode
)
let osc = OscSin.Audio(freq: $frequency)
output(bus: 0, source: osc * env * 0.2)
}
}
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Kind</key>
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
<key>Platforms</key>
<array>
<string>com.apple.platform.macosx</string>
<string>com.apple.platform.iphoneos</string>
</array>
<key>Description</key>
<string>A SwiftUI View bound to a SynthesizerBase subclass with @UIParam slots. Uses ParameterKnob to drive frequency / amplitude / pan and embeds a LyrebirdScopeView showing the engine's output. Requires LyrebirdUI module.</string>
<key>Summary</key>
<string>Lyrebird UI View (SwiftUI w/ ParameterKnob + Scope)</string>
<key>SortOrder</key>
<string>23</string>
<key>AllowedTypes</key>
<array>
<string>public.swift-source</string>
</array>
<key>DefaultCompletionName</key>
<string>MySynthView</string>
<key>MainTemplateFile</key>
<string>___FILEBASENAME___.swift</string>
<key>Options</key>
<array>
<dict>
<key>Identifier</key>
<string>productName</string>
<key>Required</key>
<true/>
<key>Name</key>
<string>View name:</string>
<key>Description</key>
<string>Name of the SwiftUI View (also used as the file name).</string>
<key>Type</key>
<string>text</string>
<key>Default</key>
<string>MySynthView</string>
</dict>
</array>
</dict>
</plist>
@@ -0,0 +1,108 @@
//___FILEHEADER___
import SwiftUI
import LyrebirdSynth
import LyrebirdUI
// MARK: - ___FILEBASENAMEASIDENTIFIER___
/// SwiftUI view that drives a `SynthesizerBase` subclass with `@UIParam` slots
/// and visualises its output via `LyrebirdScopeView`.
///
/// Owns a controller object that:
/// 1. Holds the `SynthesisEngine` reference passed in.
/// 2. Holds the synth (replace `MyUISynth` with your `@UIParam`-annotated
/// synthesizer — see the `LyrebirdSynthesizer (UI)` file template).
/// 3. Wires `engine.scopeTap` to a `ScopeCapture` so the scope view
/// sees real audio.
///
/// ## Usage
/// ```swift
/// // In your App / scene root:
/// ___FILEBASENAMEASIDENTIFIER___(engine: engine)
/// ```
public struct ___FILEBASENAMEASIDENTIFIER___: View {
@State private var controller: Controller
public init(engine: SynthesisEngine) {
_controller = State(wrappedValue: Controller(engine: engine))
}
public var body: some View {
VStack(spacing: 20) {
HStack {
Text("___FILEBASENAMEASIDENTIFIER___").font(.headline)
Spacer()
Button(controller.isPlaying ? "Stop" : "Start") {
controller.toggle()
}
.buttonStyle(.bordered)
.tint(controller.isPlaying ? .red : .green)
}
ParameterSlider(
"Frequency",
node: controller.synth.$frequency,
range: 110...880
)
HStack(spacing: 24) {
ParameterKnob("Amplitude", node: controller.synth.$amplitude, range: 0...1)
ParameterKnob("Pan", node: controller.synth.$pan, range: -1...1)
}
Divider()
LyrebirdStatusView(engine: controller.engine)
Divider()
LyrebirdScopeView(capture: controller.scope)
.frame(height: 120)
}
.padding()
}
// MARK: - Controller
/// Owns the synth, scope capture, and play/stop state. Lives for the
/// lifetime of the view via `@State`.
@Observable
final class Controller {
let engine: SynthesisEngine
let synth: MyUISynth = MyUISynth()
let scope: ScopeCapture
var isPlaying: Bool = false
init(engine: SynthesisEngine) {
self.engine = engine
self.scope = ScopeCapture(buses: [0, 1], bufferSize: 2048)
engine.scopeTap = scope
}
func toggle() {
if isPlaying {
engine.remove(synth)
} else {
do { try engine.add(synth) } catch { print("[Lyrebird] engine.add failed: \(error)") }
}
isPlaying.toggle()
}
}
}
// MARK: - Placeholder synth (replace with your own)
/// Replace this with your own `@UIParam`-annotated SynthesizerBase subclass
/// (generated from the `LyrebirdSynthesizer (UI)` template). The Controller
/// above references it directly — keep the parameter names in sync, or rename
/// the slot bindings above to match your synth.
public final class MyUISynth: SynthesizerBase {
@UIParam public var frequency: Double = 440.0
@UIParam public var amplitude: Double = 0.25
@UIParam public var pan: Double = 0.0
public override func build() {
let osc = OscSin.Audio(freq: $frequency)
output(bus: 0, source: Pan2(input: osc * $amplitude, pan: $pan))
}
}