560724d116
- Fixed: SynthesizerBase subclasses' release/free now dispatch correctly (gated synths were hard-freed instead of released). - New: quickstart project template + LyrebirdQuickstartDemo. - Docs: every example typechecked or provably illustrative (426->542); ~20 wrong-API examples fixed; root docs brought under the compile guard. - Fixed: NRT/Score demo Package.swift build from terminal again. See RELEASES.md for details.
312 lines
14 KiB
Swift
312 lines
14 KiB
Swift
// Klang.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
// MARK: - Default sine table (module-level lazy, one per process)
|
|
|
|
/// Pre-computed sine table shared by every ``Klang`` instance that does not pass its own
|
|
/// table. Initialised once on the first `Klang.Audio` init (non-RT); later accesses — including
|
|
/// the RT render callback — are lock-free reads of an already-initialised value.
|
|
private let klangDefaultTable: LyrebirdBuffer = {
|
|
let buf: LyrebirdBuffer = LyrebirdBuffer(count: lyrebirdDefaultTableSize)
|
|
buf.fillSine()
|
|
return buf
|
|
}()
|
|
|
|
/// Number of channels (= per-partial parameters) required by ``Klang``: `freq`, `amp`,
|
|
/// `phase`. Each ``LyrebirdBuffer`` frame supplies one partial's parameters. The channel
|
|
/// order (`freq, amp, phase`) matches the SuperCollider `Klang` specification triple.
|
|
public let klangSpecChannelCount: Int = 3
|
|
|
|
/// Buffer channel index of the partial frequency (Hz).
|
|
public let klangFreqChannel: Int = 0
|
|
|
|
/// Buffer channel index of the per-partial amplitude (linear gain).
|
|
public let klangAmpChannel: Int = 1
|
|
|
|
/// Buffer channel index of the per-partial initial phase (cycles, `[0, 1)`). Read once at
|
|
/// `init` to seed the phase accumulator; ignored on later ``Klang/Audio/setBuffer(_:engine:)`` swaps.
|
|
public let klangPhaseChannel: Int = 2
|
|
|
|
/// Bank of N summed sine partials — the additive-synthesis counterpart of ``Klank``.
|
|
///
|
|
/// `Klang` reads a per-partial `[freq, amp, phase]` table from a single ``LyrebirdBuffer``
|
|
/// (`channelCount == 3`, one partial per frame) and outputs the sum of N sine oscillators on
|
|
/// one mono channel. Unlike ``Klank`` it takes **no input** — it is a pure source. It exposes
|
|
/// the two SuperCollider `Klang` modulation parameters — `freqscale`, `freqoffset` — which
|
|
/// scale and shift every partial frequency without re-specifying the table:
|
|
///
|
|
/// ```
|
|
/// freq_k_effective = freq_k · freqscale + freqoffset
|
|
/// ```
|
|
///
|
|
/// Both are any `ValidGeneratorInput`, snapshotted once per audio block (block-rate / "control
|
|
/// rate"). `freq` and `amp` are re-read from the table each block, so live `setValue` edits and
|
|
/// whole-table ``Klang/Audio/setBuffer(_:engine:)`` swaps retune the bank while it sounds. The `phase`
|
|
/// channel is **only** read at `init` to seed each partial's running phase accumulator — phases
|
|
/// free-run thereafter and are unaffected by later table swaps (so the bank never clicks on a
|
|
/// respecification).
|
|
///
|
|
/// ## Per-partial synthesis
|
|
///
|
|
/// ```
|
|
/// incr_k = freq_k_effective · tableSize / sr // phase advance per sample, table units
|
|
/// y[n] = Σ_k amp_k · sineTable[phase_k] // interpolated table read
|
|
/// phase_k += incr_k // wrapped into [0, tableSize)
|
|
/// ```
|
|
///
|
|
/// `amp` is unclamped (negative inverts phase). `freq_effective` is unclamped (negative
|
|
/// frequencies simply run the partial in reverse).
|
|
///
|
|
/// ## Usage
|
|
///
|
|
/// ```swift
|
|
/// let spec = LyrebirdBuffer(count: 4, channelCount: klangSpecChannelCount)
|
|
/// // A harmonic stack: [freq, amp, phase]
|
|
/// for (i, t) in [
|
|
/// (200.0, 0.50, 0.0),
|
|
/// (400.0, 0.25, 0.0),
|
|
/// (600.0, 0.12, 0.0),
|
|
/// (800.0, 0.06, 0.0),
|
|
/// ].enumerated() {
|
|
/// spec.setValue(t.0, frame: i, channel: klangFreqChannel)
|
|
/// spec.setValue(t.1, frame: i, channel: klangAmpChannel)
|
|
/// spec.setValue(t.2, frame: i, channel: klangPhaseChannel)
|
|
/// }
|
|
///
|
|
/// // Detune the whole stack up a fifth with an envelope.
|
|
/// let voice = Klang.Audio(buffer: spec, freqscale: 1.5)
|
|
/// ```
|
|
public enum Klang {
|
|
|
|
/// Audio-rate additive sine bank with block-rate `freqscale` / `freqoffset` modulation.
|
|
///
|
|
/// - Parameters:
|
|
/// - buffer: Partial table. Must have `channelCount == 3` and `count >= 1`. Frame `k`
|
|
/// provides partial `k`'s `[freq, amp, phase]`. Bank size = `buffer.count`. Live
|
|
/// `setValue` writes to `freq`/`amp` are picked up once per audio block; whole-table
|
|
/// swap via ``setBuffer(_:engine:)``. The `phase` channel seeds the accumulators at
|
|
/// `init` only.
|
|
/// - freqscale: Multiplier applied to every partial frequency. Snapshotted per block.
|
|
/// Defaults to `1.0`.
|
|
/// - freqoffset: Hz added to every partial frequency after scaling. Snapshotted per
|
|
/// block. Defaults to `0.0`.
|
|
/// - interpolation: Sine-table interpolation mode. Defaults to `.linear`.
|
|
/// - table: Sine table (power-of-two size, mono). Defaults to the module-level lazy global.
|
|
/// - mul: Output multiplier. Defaults to `1.0`.
|
|
/// - add: Output offset. Defaults to `0.0`.
|
|
public final class Audio: GeneratorBase, AudioGenerator {
|
|
|
|
// MARK: Inputs
|
|
|
|
/// Atomic slot — supports live whole-table swap via ``setBuffer(_:engine:)``.
|
|
/// Loaded once per audio block.
|
|
private let _slot: RTBufferSlot
|
|
|
|
private let _freqScaleInput: any ValidGeneratorInput
|
|
private let _freqScaleIsGenerator: Bool
|
|
private let _freqOffsetInput: any ValidGeneratorInput
|
|
private let _freqOffsetIsGenerator: Bool
|
|
|
|
// MARK: Sine table
|
|
|
|
private let _sineTable: LyrebirdBuffer
|
|
private let _interpolation: TableInterpolation
|
|
|
|
// MARK: State (one entry per partial)
|
|
|
|
private let _bankSize: Int
|
|
/// Per-partial phase in table-index units `[0, tableSize)`. Seeded at init from the
|
|
/// spec's `phase` channel; free-runs thereafter.
|
|
private var _phase: [Double]
|
|
|
|
// MARK: Output
|
|
private let _mulAdd: MulAddSpec
|
|
|
|
// MARK: Init
|
|
|
|
/// - Parameters:
|
|
/// - buffer: Partial table. Must have `channelCount == 3` and `count >= 1`. Frame `k`
|
|
/// provides partial `k`'s `[freq, amp, phase]`. Bank size = `buffer.count`. Live
|
|
/// `setValue` writes to `freq`/`amp` are picked up once per audio block; whole-table
|
|
/// swap via ``setBuffer(_:engine:)``. The `phase` channel seeds the accumulators at
|
|
/// `init` only.
|
|
/// - freqscale: Multiplier applied to every partial frequency. Snapshotted per block.
|
|
/// Defaults to `1.0`.
|
|
/// - freqoffset: Hz added to every partial frequency after scaling. Snapshotted per
|
|
/// block. Defaults to `0.0`.
|
|
/// - interpolation: Sine-table interpolation mode. Defaults to `.linear`.
|
|
/// - table: Sine table (power-of-two size, mono). Defaults to the module-level lazy global.
|
|
/// - mul: Output multiplier. Defaults to `1.0`.
|
|
/// - add: Output offset. Defaults to `0.0`.
|
|
public init(
|
|
buffer: LyrebirdBuffer,
|
|
freqscale: any ValidGeneratorInput = 1.0,
|
|
freqoffset: any ValidGeneratorInput = 0.0,
|
|
interpolation: TableInterpolation = .linear,
|
|
table: LyrebirdBuffer? = nil,
|
|
mul: any ValidGeneratorInput = 1.0,
|
|
add: any ValidGeneratorInput = 0.0
|
|
) {
|
|
precondition(
|
|
buffer.channelCount == klangSpecChannelCount,
|
|
"Klang: buffer must have channelCount == \(klangSpecChannelCount) "
|
|
+ "(freq, amp, phase); got channelCount=\(buffer.channelCount)"
|
|
)
|
|
precondition(
|
|
buffer.count >= 1,
|
|
"Klang: buffer must have count >= 1; got count=\(buffer.count)"
|
|
)
|
|
|
|
let resolvedTable: LyrebirdBuffer = table ?? klangDefaultTable
|
|
let tableSize: Int = resolvedTable.count
|
|
precondition(
|
|
tableSize > 0 && (tableSize & (tableSize - 1)) == 0,
|
|
"Klang requires a power-of-two table size; got \(tableSize)."
|
|
)
|
|
precondition(
|
|
resolvedTable.channelCount == lyrebirdBufferMonoChannelCount,
|
|
"Klang requires a mono table (channelCount == 1); got channelCount == \(resolvedTable.channelCount)."
|
|
)
|
|
self._sineTable = resolvedTable
|
|
self._interpolation = interpolation
|
|
self._slot = RTBufferSlot(initial: buffer)
|
|
|
|
let resolvedFreqScale: any ValidGeneratorInput = freqscale._resolvedInput()
|
|
self._freqScaleInput = resolvedFreqScale
|
|
self._freqScaleIsGenerator = resolvedFreqScale is any Generator
|
|
let resolvedFreqOffset: any ValidGeneratorInput = freqoffset._resolvedInput()
|
|
self._freqOffsetInput = resolvedFreqOffset
|
|
self._freqOffsetIsGenerator = resolvedFreqOffset is any Generator
|
|
|
|
let n: Int = buffer.count
|
|
self._bankSize = n
|
|
// Seed per-partial phase (cycles → table-index units, normalised to [0, tableSize)).
|
|
let tableSizeFloat: Double = Double(tableSize)
|
|
var seededPhase: [Double] = makeSampleBuffer(n)
|
|
for k: Int in 0..<n {
|
|
var p: Double = buffer[k, klangPhaseChannel] * tableSizeFloat
|
|
p = p.truncatingRemainder(dividingBy: tableSizeFloat)
|
|
if p < 0 { p += tableSizeFloat }
|
|
seededPhase[k] = p
|
|
}
|
|
self._phase = seededPhase
|
|
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
|
}
|
|
|
|
/// Replace the partial table. Pass `nil` to silence the bank (phase accumulators are
|
|
/// preserved). The new buffer must have `channelCount == klangSpecChannelCount` (3) and
|
|
/// `count == bankSize`. Only `freq`/`amp` of the new table take effect — the `phase`
|
|
/// channel is ignored so the bank keeps phase continuity across the swap. The displaced
|
|
/// buffer's retain is routed through the engine's buffer-swap kill queue for off-RT
|
|
/// release.
|
|
public func setBuffer(_ buffer: LyrebirdBuffer?, engine: SynthesisEngine) {
|
|
if let buffer: LyrebirdBuffer {
|
|
precondition(
|
|
buffer.channelCount == klangSpecChannelCount,
|
|
"Klang.setBuffer: buffer must have channelCount == \(klangSpecChannelCount), got \(buffer.channelCount)"
|
|
)
|
|
precondition(
|
|
buffer.count == _bankSize,
|
|
"Klang.setBuffer: buffer count must equal initial bank size \(_bankSize), got \(buffer.count)"
|
|
)
|
|
}
|
|
_slot.swap(buffer, engine: engine)
|
|
}
|
|
|
|
public func _computeSamples(
|
|
graph: SynthGraph,
|
|
count: Int
|
|
) -> [[Double]] {
|
|
_checkCount(count)
|
|
|
|
let n: Int = _bankSize
|
|
let sr: Double = graph.engine.sampleRate
|
|
let tableSize: Int = _sineTable.count
|
|
let tableSizeFloat: Double = Double(tableSize)
|
|
let tableMask: Int = tableSize - 1
|
|
|
|
// Snapshot block-rate modulation. Evaluated unconditionally so any wired
|
|
// modulation generator advances its state by `count` samples this block.
|
|
let freqScale: Double = lastGeneratorSampleOrFloat(
|
|
_freqScaleInput, isGenerator: _freqScaleIsGenerator, graph: graph, count: count)
|
|
let freqOffset: Double = lastGeneratorSampleOrFloat(
|
|
_freqOffsetInput, isGenerator: _freqOffsetIsGenerator, graph: graph, count: count)
|
|
|
|
// Slot empty / buffer invalidated / table invalidated → silence, hold phase.
|
|
guard let buffer: LyrebirdBuffer = _slot.load(engine: graph.engine),
|
|
buffer.isValid, _sineTable.isValid else {
|
|
for i: Int in 0..<count { _result[0][i] = 0 }
|
|
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
|
return _result
|
|
}
|
|
|
|
// Zero the output, then accumulate each partial's contribution.
|
|
for i: Int in 0..<count { _result[0][i] = 0 }
|
|
|
|
for k: Int in 0..<n {
|
|
let freq: Double = buffer[k, klangFreqChannel] * freqScale + freqOffset
|
|
let amp: Double = buffer[k, klangAmpChannel]
|
|
let increment: Double = freq * tableSizeFloat / sr
|
|
var phase: Double = _phase[k]
|
|
|
|
switch _interpolation {
|
|
case .none:
|
|
for i: Int in 0..<count {
|
|
_result[0][i] += amp * _sineTable[Int(phase) & tableMask]
|
|
phase = klangAdvance(phase, increment, tableSizeFloat)
|
|
}
|
|
case .linear:
|
|
for i: Int in 0..<count {
|
|
let intPhase: Int = Int(phase)
|
|
let frac: Double = phase - Double(intPhase)
|
|
let s0: Double = _sineTable[intPhase & tableMask]
|
|
let s1: Double = _sineTable[(intPhase + 1) & tableMask]
|
|
_result[0][i] += amp * (s0 + frac * (s1 - s0))
|
|
phase = klangAdvance(phase, increment, tableSizeFloat)
|
|
}
|
|
case .cubic:
|
|
for i: Int in 0..<count {
|
|
let intPhase: Int = Int(phase)
|
|
let t: Double = phase - Double(intPhase)
|
|
let pM1: Double = _sineTable[(intPhase - 1) & tableMask]
|
|
let p0: Double = _sineTable[intPhase & tableMask]
|
|
let p1: Double = _sineTable[(intPhase + 1) & tableMask]
|
|
let p2: Double = _sineTable[(intPhase + 2) & tableMask]
|
|
_result[0][i] += amp * catmullRomCubic(pM1, p0, p1, p2, t: t)
|
|
phase = klangAdvance(phase, increment, tableSizeFloat)
|
|
}
|
|
}
|
|
|
|
_phase[k] = phase
|
|
}
|
|
|
|
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
|
return _result
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Advance a table-units phase by `increment` and wrap into `[0, tableSizeFloat)`. Handles
|
|
/// the common single-step case branchlessly first, then a `truncatingRemainder` fallback for
|
|
/// large increments (very high partial frequency or wide `freqscale`).
|
|
@inline(__always)
|
|
private func klangAdvance(_ phase: Double, _ increment: Double, _ tableSizeFloat: Double) -> Double {
|
|
var p: Double = phase + increment
|
|
if p >= tableSizeFloat { p -= tableSizeFloat }
|
|
if p >= tableSizeFloat || p < 0 {
|
|
p = p.truncatingRemainder(dividingBy: tableSizeFloat)
|
|
if p < 0 { p += tableSizeFloat }
|
|
}
|
|
return p
|
|
}
|
|
|
|
// MARK: - GeneratorEnum
|
|
|
|
// GeneratorEnum conformance is intentionally omitted — Klang.Audio is Audio-only.
|
|
// Each partial advances its phase accumulator every sample, so a control-rate variant would
|
|
// need a distinct architecture (per-sample state on a control-rate input is the same as audio
|
|
// rate).
|