Music XML updates and optimizations

This commit is contained in:
2026-06-16 20:55:32 -07:00
parent ca1ee503cc
commit 73191c958f
97 changed files with 5459 additions and 2031 deletions
@@ -0,0 +1,27 @@
// EngineDispatch.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Dispatch a throwing engine mutation to the main queue — preserving the
/// `SynthesisEngine.pendingQueue` single-producer invariant — and log on failure.
///
/// Shared by the language-side context types (`LyrebirdRoutineContext`,
/// `LyrebirdProcessContext`) whose `add` / `schedule` calls cross from a routine
/// or process thread onto the main thread. `label` names the call site in the
/// failure message only.
func lyrebirdDispatchEngineOp(
_ label: String,
_ work: @escaping @MainActor () throws -> Void
) {
DispatchQueue.main.async {
// The block runs on the main queue, so main-actor isolation holds.
MainActor.assumeIsolated {
do { try work() }
catch { print("[Lyrebird] \(label) failed: \(error)") }
}
}
}
@@ -72,7 +72,7 @@ public final class DelayLine: GeneratorBase, AudioGenerator {
self.delayIsGenerator = resolvedDelay is any Generator
let maxSamples: Int = Int(ceil(maxDelay * sampleRate)) + 1
let bufSize: Int = Self.nextPowerOf2(max(maxSamples, 2))
let bufSize: Int = lyrebirdNextPowerOfTwo(max(maxSamples, 2))
self.buffer = [Double](repeating: 0, count: bufSize)
self.bufferMask = bufSize - 1
self.maxDelaySamples = maxSamples - 1
@@ -220,13 +220,6 @@ public final class DelayLine: GeneratorBase, AudioGenerator {
let d: Double = y1
return ((a * frac + b) * frac + c) * frac + d
}
private static func nextPowerOf2(_ n: Int) -> Int {
guard n > 1 else { return 1 }
var result: Int = 1
while result < n { result <<= 1 }
return result
}
}
// MARK: - GeneratorEnum
@@ -129,7 +129,7 @@ public final class DelayLineFeedback: GeneratorBase, AudioGenerator {
self.targetAmpIsGenerator = resolvedTargetAmp is any Generator
let maxSamples: Int = Int(ceil(maxDelay * sampleRate)) + 1
let bufSize: Int = Self.nextPowerOf2(max(maxSamples, 2))
let bufSize: Int = lyrebirdNextPowerOfTwo(max(maxSamples, 2))
self.buffer = [Double](repeating: 0, count: bufSize)
self.bufferMask = bufSize - 1
self.maxDelaySamples = maxSamples - 1
@@ -319,13 +319,6 @@ public final class DelayLineFeedback: GeneratorBase, AudioGenerator {
let d: Double = y1
return ((a * frac + b) * frac + c) * frac + d
}
private static func nextPowerOf2(_ n: Int) -> Int {
guard n > 1 else { return 1 }
var result: Int = 1
while result < n { result <<= 1 }
return result
}
}
// MARK: - GeneratorEnum
@@ -86,7 +86,7 @@ public final class AllpassFilter: GeneratorBase, AudioGenerator {
self.interpolation = interpolation
let maxSamples: Int = Int(ceil(maxDelay * sampleRate)) + 1
let bufSize: Int = Self.nextPowerOf2(max(maxSamples, 2))
let bufSize: Int = lyrebirdNextPowerOfTwo(max(maxSamples, 2))
self.inputBuf = [Double](repeating: 0, count: bufSize)
self.outputBuf = [Double](repeating: 0, count: bufSize)
self.bufferMask = bufSize - 1
@@ -258,13 +258,6 @@ public final class AllpassFilter: GeneratorBase, AudioGenerator {
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
private static func nextPowerOf2(_ n: Int) -> Int {
guard n > 1 else { return 1 }
var r: Int = 1
while r < n { r <<= 1 }
return r
}
}
// MARK: - Local cubic interpolation
@@ -4,14 +4,19 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Accelerate
import Foundation
/// Cascaded Butterworth bandpass filter, orders 1–8 per section (2 × order total poles).
///
/// Implemented as an N-th order Butterworth HP section (cutoff = `lowFreq`) cascaded with
/// an N-th order Butterworth LP section (cutoff = `highFreq`). Both sections share the same
/// Butterworth Q values. The unified ping-pong cascade routes through a single `_scratch`
/// buffer — no extra allocation on the RT thread.
/// Implemented as two `ButterworthSectionEngine` instances in series: an N-th order
/// Butterworth HP section (cutoff = `lowFreq`) cascaded with an N-th order Butterworth
/// LP section (cutoff = `highFreq`). The HP engine writes into an intermediate buffer
/// `_inter`; the LP engine reads `_inter` and writes to the final output. Both sections
/// share the same per-stage Butterworth Q values.
///
/// Each engine manages its own scratch buffer and background-thread vDSP setup builder
/// independently — no shared mutable state between the two sections on the RT thread.
///
/// Per-stage Q values follow the Butterworth pole formula:
/// ```
@@ -47,30 +52,11 @@ public enum ButterworthBandPass {
/// Per-stage Butterworth Q values — `⌊order/2⌋` entries. Shared by both HP and LP sections.
public let butterworthQs: [Double]
// HP section
private var hpBiquadStages: [BiquadState]
private var hpFirstOrder: FirstOrderState?
private var cachedHPBiquadCoeffs: [BiquadCoeffs]
private var cachedHPFO: (b0: Double, b1: Double, na1: Double) = (0, 0, 0)
// LP section
private var lpBiquadStages: [BiquadState]
private var lpFirstOrder: FirstOrderState?
private var cachedLPBiquadCoeffs: [BiquadCoeffs]
private var cachedLPFO: (b0: Double, b1: Double, na1: Double) = (0, 0, 0)
private var prevLowFreq: Double = -1.0
private var prevHighFreq: Double = -1.0
private var prevSampleRate: Double = -1.0
private var _scratch: [Double]
private let hpEngine: ButterworthSectionEngine // HP section (lowFreq cutoff)
private let lpEngine: ButterworthSectionEngine // LP section (highFreq cutoff)
private var _inter: [Double] // HP output / LP input
private let _mulAdd: MulAddSpec
/// Number of stages in each LP/HP section.
private let sectionStageCount: Int
/// Total stages = 2 × sectionStageCount.
private let totalStageCount: Int
/// - Parameters:
/// - input: Signal to filter.
/// - lowFreq: Lower edge of the passband in Hz (HP cutoff — content below this is attenuated). No internal clamping; stay below `highFreq` and Nyquist.
@@ -86,7 +72,6 @@ public enum ButterworthBandPass {
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
let resolvedLowFreq: any ValidGeneratorInput = lowFreq._resolvedInput()
let resolvedHighFreq: any ValidGeneratorInput = highFreq._resolvedInput()
@@ -98,35 +83,24 @@ public enum ButterworthBandPass {
let clampedOrder: Int = min(max(order, 1), maxButterworthOrder)
self.order = clampedOrder
self.butterworthQs = computeButterworthQs(order: clampedOrder)
let numBiquads: Int = clampedOrder / 2
var qs: [Double] = [Double]()
if numBiquads > 0 {
for k: Int in 1...numBiquads {
let angle: Double = Double.pi * Double(2 * k + clampedOrder - 1)
/ Double(2 * clampedOrder)
qs.append(-1.0 / (2.0 * cos(angle)))
}
}
self.butterworthQs = qs
let hasFO: Bool = clampedOrder % 2 == 1
let stagesPerSection: Int = numBiquads + (hasFO ? 1 : 0)
let numFilterSections: Int = 2 // HP section + LP section
self.sectionStageCount = stagesPerSection
self.totalStageCount = stagesPerSection * numFilterSections
self.hpBiquadStages = [BiquadState](repeating: BiquadState(), count: numBiquads)
self.hpFirstOrder = hasFO ? FirstOrderState() : nil
self.cachedHPBiquadCoeffs = [BiquadCoeffs](repeating: .zero, count: numBiquads)
self.lpBiquadStages = [BiquadState](repeating: BiquadState(), count: numBiquads)
self.lpFirstOrder = hasFO ? FirstOrderState() : nil
self.cachedLPBiquadCoeffs = [BiquadCoeffs](repeating: .zero, count: numBiquads)
self._scratch = makeSampleBuffer()
self.hpEngine = ButterworthSectionEngine(
order: clampedOrder,
foCoeffs: { foHPCoeffs(freq: $0, sr: $1) },
biquadCoeffs: { rbjHighPassCoeffs(freq: $0, q: $1, sampleRate: $2) },
threadName: "LyrebirdButterworthBP-HP.vDSP"
)
self.lpEngine = ButterworthSectionEngine(
order: clampedOrder,
foCoeffs: { foLPCoeffs(freq: $0, sr: $1) },
biquadCoeffs: { rbjLowPassCoeffs(freq: $0, q: $1, sampleRate: $2) },
threadName: "LyrebirdButterworthBP-LP.vDSP"
)
self._inter = makeSampleBuffer()
self._mulAdd = MulAddSpec(mul: mul, add: add)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
@@ -138,234 +112,69 @@ public enum ButterworthBandPass {
}
let sr: Double = graph.engine.sampleRate
if lowFreqIsGenerator || highFreqIsGenerator {
let lowSamples: [Double]? = lowFreqIsGenerator
? lowFreqInput.calculatedSamples(graph: graph, count: count).first
: nil
let highSamples: [Double]? = highFreqIsGenerator
? highFreqInput.calculatedSamples(graph: graph, count: count).first
: nil
let lastI: Int = count - 1
let lf0: Double = lowSamples.map { $0.isEmpty ? lowFreqInput.floatValue(graph: graph) : $0[0] }
?? lowFreqInput.floatValue(graph: graph)
let lfN: Double = lowSamples.map { $0.isEmpty ? lf0 : $0[min($0.count - 1, lastI)] } ?? lf0
let hf0: Double = highSamples.map { $0.isEmpty ? highFreqInput.floatValue(graph: graph) : $0[0] }
?? highFreqInput.floatValue(graph: graph)
let hfN: Double = highSamples.map { $0.isEmpty ? hf0 : $0[min($0.count - 1, lastI)] } ?? hf0
runAudioRate(input: inputBlock, lf0: lf0, lfN: lfN, hf0: hf0, hfN: hfN, sr: sr, count: count)
} else {
let lowFreq: Double = lowFreqInput.floatValue(graph: graph)
let highFreq: Double = highFreqInput.floatValue(graph: graph)
if lowFreq != prevLowFreq || highFreq != prevHighFreq || sr != prevSampleRate {
recomputeScalarCoeffs(lowFreq: lowFreq, highFreq: highFreq, sr: sr)
prevLowFreq = lowFreq; prevHighFreq = highFreq; prevSampleRate = sr
// Resolve the HP-section cutoff (lowFreq — the lower passband edge).
let hpScalarFreq: Double
let hpF0: Double
let hpFN: Double
if lowFreqIsGenerator {
let lowSamples: [[Double]] = lowFreqInput.calculatedSamples(graph: graph, count: count)
if let s: [Double] = lowSamples.first, !s.isEmpty {
hpF0 = s[0]
hpFN = s[min(s.count - 1, count - 1)]
} else {
let fv: Double = lowFreqInput.floatValue(graph: graph)
hpF0 = fv; hpFN = fv
}
runScalar(input: inputBlock, count: count)
hpScalarFreq = 0.0
} else {
hpScalarFreq = lowFreqInput.floatValue(graph: graph)
hpF0 = 0.0; hpFN = 0.0
}
// Resolve the LP-section cutoff (highFreq — the upper passband edge).
let lpScalarFreq: Double
let lpF0: Double
let lpFN: Double
if highFreqIsGenerator {
let highSamples: [[Double]] = highFreqInput.calculatedSamples(graph: graph, count: count)
if let s: [Double] = highSamples.first, !s.isEmpty {
lpF0 = s[0]
lpFN = s[min(s.count - 1, count - 1)]
} else {
let fv: Double = highFreqInput.floatValue(graph: graph)
lpF0 = fv; lpFN = fv
}
lpScalarFreq = 0.0
} else {
lpScalarFreq = highFreqInput.floatValue(graph: graph)
lpF0 = 0.0; lpFN = 0.0
}
// Series: HP section (lowFreq cutoff) → intermediate buffer → LP section (highFreq cutoff) → output.
hpEngine.process(
input: inputBlock,
freqIsGenerator: lowFreqIsGenerator,
scalarFreq: hpScalarFreq,
f0: hpF0,
fN: hpFN,
sr: sr,
count: count,
into: &_inter
)
lpEngine.process(
input: _inter,
freqIsGenerator: highFreqIsGenerator,
scalarFreq: lpScalarFreq,
f0: lpF0,
fN: lpFN,
sr: sr,
count: count,
into: &_result[0]
)
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
// MARK: - Coefficient computation
private func recomputeScalarCoeffs(
lowFreq: Double,
highFreq: Double,
sr: Double
) {
if hpFirstOrder != nil { cachedHPFO = foHPCoeffs(freq: lowFreq, sr: sr) }
for i: Int in 0..<hpBiquadStages.count {
cachedHPBiquadCoeffs[i] = rbjHighPassCoeffs(freq: lowFreq, q: butterworthQs[i], sampleRate: sr)
}
if lpFirstOrder != nil { cachedLPFO = foLPCoeffs(freq: highFreq, sr: sr) }
for i: Int in 0..<lpBiquadStages.count {
cachedLPBiquadCoeffs[i] = rbjLowPassCoeffs(freq: highFreq, q: butterworthQs[i], sampleRate: sr)
}
}
// MARK: - Unified cascade
/// Buffer routing: stage `i` of `stageCount` total writes to `_result[0]` when `(stageCount+i)%2==1`,
/// else to `_scratch`. LP stages (i ≥ sectionStageCount) always have i > 0.
private func runScalar(
input: [Double],
count: Int
) {
let stageCount: Int = totalStageCount
// HP section (stages 0 ..< sectionStageCount)
var si: Int = 0
if var fo: FirstOrderState = hpFirstOrder {
let writesResult: Bool = (stageCount + 0) % 2 == 1
if writesResult {
fo.processBlock(input: input, b0: cachedHPFO.b0, b1: cachedHPFO.b1, na1: cachedHPFO.na1,
into: &_result[0], count: count)
} else {
fo.processBlock(input: input, b0: cachedHPFO.b0, b1: cachedHPFO.b1, na1: cachedHPFO.na1,
into: &_scratch, count: count)
}
hpFirstOrder = fo
si = 1
}
for bi: Int in 0..<hpBiquadStages.count {
let i: Int = si + bi
let writesResult: Bool = (stageCount + i) % 2 == 1
if writesResult {
if i == 0 {
hpBiquadStages[bi].processBlock(input: input, coeffs: cachedHPBiquadCoeffs[bi],
into: &_result[0], count: count)
} else {
hpBiquadStages[bi].processBlock(input: _scratch, coeffs: cachedHPBiquadCoeffs[bi],
into: &_result[0], count: count)
}
} else {
if i == 0 {
hpBiquadStages[bi].processBlock(input: input, coeffs: cachedHPBiquadCoeffs[bi],
into: &_scratch, count: count)
} else {
hpBiquadStages[bi].processBlock(input: _result[0], coeffs: cachedHPBiquadCoeffs[bi],
into: &_scratch, count: count)
}
}
}
// LP section (stages sectionStageCount ..< totalStageCount; i > 0 always)
var lpi: Int = sectionStageCount
if var fo: FirstOrderState = lpFirstOrder {
let i: Int = lpi
let writesResult: Bool = (stageCount + i) % 2 == 1
if writesResult {
fo.processBlock(input: _scratch, b0: cachedLPFO.b0, b1: cachedLPFO.b1, na1: cachedLPFO.na1,
into: &_result[0], count: count)
} else {
fo.processBlock(input: _result[0], b0: cachedLPFO.b0, b1: cachedLPFO.b1, na1: cachedLPFO.na1,
into: &_scratch, count: count)
}
lpFirstOrder = fo
lpi += 1
}
for bi: Int in 0..<lpBiquadStages.count {
let i: Int = lpi + bi
let writesResult: Bool = (stageCount + i) % 2 == 1
if writesResult {
lpBiquadStages[bi].processBlock(input: _scratch, coeffs: cachedLPBiquadCoeffs[bi],
into: &_result[0], count: count)
} else {
lpBiquadStages[bi].processBlock(input: _result[0], coeffs: cachedLPBiquadCoeffs[bi],
into: &_scratch, count: count)
}
}
}
private func runAudioRate(
input: [Double],
lf0: Double,
lfN: Double,
hf0: Double,
hfN: Double,
sr: Double,
count: Int
) {
let stageCount: Int = totalStageCount
// Precompute HP boundary coefficients
let hpFOS: (b0: Double, b1: Double, na1: Double)
let hpFOE: (b0: Double, b1: Double, na1: Double)
if hpFirstOrder != nil {
hpFOS = foHPCoeffs(freq: lf0, sr: sr)
hpFOE = foHPCoeffs(freq: lfN, sr: sr)
} else {
hpFOS = (0, 0, 0); hpFOE = (0, 0, 0)
}
// Precompute LP boundary coefficients
let lpFOS: (b0: Double, b1: Double, na1: Double)
let lpFOE: (b0: Double, b1: Double, na1: Double)
if lpFirstOrder != nil {
lpFOS = foLPCoeffs(freq: hf0, sr: sr)
lpFOE = foLPCoeffs(freq: hfN, sr: sr)
} else {
lpFOS = (0, 0, 0); lpFOE = (0, 0, 0)
}
// HP section
var si: Int = 0
if var fo: FirstOrderState = hpFirstOrder {
let writesResult: Bool = (stageCount + 0) % 2 == 1
if writesResult {
fo.processBlock(input: input,
startB0: hpFOS.b0, startB1: hpFOS.b1, startNa1: hpFOS.na1,
endB0: hpFOE.b0, endB1: hpFOE.b1, endNa1: hpFOE.na1,
into: &_result[0], count: count)
} else {
fo.processBlock(input: input,
startB0: hpFOS.b0, startB1: hpFOS.b1, startNa1: hpFOS.na1,
endB0: hpFOE.b0, endB1: hpFOE.b1, endNa1: hpFOE.na1,
into: &_scratch, count: count)
}
hpFirstOrder = fo
si = 1
}
for bi: Int in 0..<hpBiquadStages.count {
let i: Int = si + bi
let writesResult: Bool = (stageCount + i) % 2 == 1
let startC: BiquadCoeffs = rbjHighPassCoeffs(freq: lf0, q: butterworthQs[bi], sampleRate: sr)
let endC: BiquadCoeffs = rbjHighPassCoeffs(freq: lfN, q: butterworthQs[bi], sampleRate: sr)
if writesResult {
if i == 0 {
hpBiquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
into: &_result[0], count: count)
} else {
hpBiquadStages[bi].processBlock(input: _scratch, startCoeffs: startC, endCoeffs: endC,
into: &_result[0], count: count)
}
} else {
if i == 0 {
hpBiquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
into: &_scratch, count: count)
} else {
hpBiquadStages[bi].processBlock(input: _result[0], startCoeffs: startC, endCoeffs: endC,
into: &_scratch, count: count)
}
}
}
// LP section (i > 0 always)
var lpi: Int = sectionStageCount
if var fo: FirstOrderState = lpFirstOrder {
let i: Int = lpi
let writesResult: Bool = (stageCount + i) % 2 == 1
if writesResult {
fo.processBlock(input: _scratch,
startB0: lpFOS.b0, startB1: lpFOS.b1, startNa1: lpFOS.na1,
endB0: lpFOE.b0, endB1: lpFOE.b1, endNa1: lpFOE.na1,
into: &_result[0], count: count)
} else {
fo.processBlock(input: _result[0],
startB0: lpFOS.b0, startB1: lpFOS.b1, startNa1: lpFOS.na1,
endB0: lpFOE.b0, endB1: lpFOE.b1, endNa1: lpFOE.na1,
into: &_scratch, count: count)
}
lpFirstOrder = fo
lpi += 1
}
for bi: Int in 0..<lpBiquadStages.count {
let i: Int = lpi + bi
let writesResult: Bool = (stageCount + i) % 2 == 1
let startC: BiquadCoeffs = rbjLowPassCoeffs(freq: hf0, q: butterworthQs[bi], sampleRate: sr)
let endC: BiquadCoeffs = rbjLowPassCoeffs(freq: hfN, q: butterworthQs[bi], sampleRate: sr)
if writesResult {
lpBiquadStages[bi].processBlock(input: _scratch, startCoeffs: startC, endCoeffs: endC,
into: &_result[0], count: count)
} else {
lpBiquadStages[bi].processBlock(input: _result[0], startCoeffs: startC, endCoeffs: endC,
into: &_scratch, count: count)
}
}
}
}
}
@@ -4,17 +4,20 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Accelerate
import Foundation
/// Cascaded Butterworth band-reject (notch) filter, orders 1–8 per section (2 × order total poles).
///
/// Implemented as two parallel paths summed: an N-th order Butterworth LP section
/// (cutoff = `lowFreq`) plus an N-th order Butterworth HP section (cutoff = `highFreq`).
/// Content between `lowFreq` and `highFreq` is attenuated; content outside that band passes.
/// Implemented as two parallel `ButterworthSectionEngine` instances summed: an N-th order
/// Butterworth LP section (cutoff = `lowFreq`) plus an N-th order Butterworth HP section
/// (cutoff = `highFreq`). Content between `lowFreq` and `highFreq` is attenuated; content
/// outside that band passes.
///
/// The LP cascade writes to a dedicated `_lpResult` buffer; the HP cascade writes to
/// `_result[0]`. Both share a single `_scratch` buffer (used sequentially). Final output
/// is the element-wise sum written back into `_result[0]`. No RT allocation.
/// The LP engine writes to a dedicated `_lpOut` buffer; the HP engine writes to `_result[0]`.
/// Both engines have independent scratch buffers and background-thread vDSP setup builders —
/// no shared mutable state between the two sections on the RT thread. The final output is the
/// element-wise sum (`vDSP_vaddD`) of `_lpOut` into `_result[0]`. No RT allocation.
///
/// ## Usage
/// ```swift
@@ -45,32 +48,15 @@ public enum ButterworthBandReject {
/// Per-stage Butterworth Q values — `⌊order/2⌋` entries. Shared by both LP and HP sections.
public let butterworthQs: [Double]
// LP section
private var lpBiquadStages: [BiquadState]
private var lpFirstOrder: FirstOrderState?
private var cachedLPBiquadCoeffs: [BiquadCoeffs]
private var cachedLPFO: (b0: Double, b1: Double, na1: Double) = (0, 0, 0)
// HP section
private var hpBiquadStages: [BiquadState]
private var hpFirstOrder: FirstOrderState?
private var cachedHPBiquadCoeffs: [BiquadCoeffs]
private var cachedHPFO: (b0: Double, b1: Double, na1: Double) = (0, 0, 0)
private var prevLowFreq: Double = -1.0
private var prevHighFreq: Double = -1.0
private var prevSampleRate: Double = -1.0
private var _lpResult: [Double] // LP cascade output
private var _scratch: [Double] // shared intermediate buffer
private let lpEngine: ButterworthSectionEngine // LP section (lowFreq cutoff)
private let hpEngine: ButterworthSectionEngine // HP section (highFreq cutoff)
private var _lpOut: [Double] // LP cascade output buffer
private let _mulAdd: MulAddSpec
private let sectionStageCount: Int
/// - Parameters:
/// - input: Signal to filter.
/// - lowFreq: Upper edge of the reject band in Hz (LP cutoff — content below this is passed by the LP path). No internal clamping; stay below `highFreq` and Nyquist.
/// - highFreq: Lower edge of the reject band in Hz (HP cutoff — content above this is passed by the HP path). No internal clamping; stay above `lowFreq`.
/// - lowFreq: Lower edge of the reject band in Hz (LP cutoff — content below this is passed by the LP path). No internal clamping; stay below `highFreq` and Nyquist.
/// - highFreq: Upper edge of the reject band in Hz (HP cutoff — content above this is passed by the HP path). No internal clamping; stay above `lowFreq`.
/// - order: Filter order per section 1–8 (clamped internally). Total poles = 2 × order. Higher order = deeper, narrower notch but higher CPU cost. Defaults to `2`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
@@ -82,7 +68,6 @@ public enum ButterworthBandReject {
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
let resolvedLowFreq: any ValidGeneratorInput = lowFreq._resolvedInput()
let resolvedHighFreq: any ValidGeneratorInput = highFreq._resolvedInput()
@@ -94,33 +79,24 @@ public enum ButterworthBandReject {
let clampedOrder: Int = min(max(order, 1), maxButterworthOrder)
self.order = clampedOrder
self.butterworthQs = computeButterworthQs(order: clampedOrder)
let numBiquads: Int = clampedOrder / 2
var qs: [Double] = [Double]()
if numBiquads > 0 {
for k: Int in 1...numBiquads {
let angle: Double = Double.pi * Double(2 * k + clampedOrder - 1)
/ Double(2 * clampedOrder)
qs.append(-1.0 / (2.0 * cos(angle)))
}
}
self.butterworthQs = qs
let hasFO: Bool = clampedOrder % 2 == 1
self.sectionStageCount = numBiquads + (hasFO ? 1 : 0)
self.lpBiquadStages = [BiquadState](repeating: BiquadState(), count: numBiquads)
self.lpFirstOrder = hasFO ? FirstOrderState() : nil
self.cachedLPBiquadCoeffs = [BiquadCoeffs](repeating: .zero, count: numBiquads)
self.hpBiquadStages = [BiquadState](repeating: BiquadState(), count: numBiquads)
self.hpFirstOrder = hasFO ? FirstOrderState() : nil
self.cachedHPBiquadCoeffs = [BiquadCoeffs](repeating: .zero, count: numBiquads)
self._lpResult = makeSampleBuffer()
self._scratch = makeSampleBuffer()
self.lpEngine = ButterworthSectionEngine(
order: clampedOrder,
foCoeffs: { foLPCoeffs(freq: $0, sr: $1) },
biquadCoeffs: { rbjLowPassCoeffs(freq: $0, q: $1, sampleRate: $2) },
threadName: "LyrebirdButterworthBR-LP.vDSP"
)
self.hpEngine = ButterworthSectionEngine(
order: clampedOrder,
foCoeffs: { foHPCoeffs(freq: $0, sr: $1) },
biquadCoeffs: { rbjHighPassCoeffs(freq: $0, q: $1, sampleRate: $2) },
threadName: "LyrebirdButterworthBR-HP.vDSP"
)
self._lpOut = makeSampleBuffer()
self._mulAdd = MulAddSpec(mul: mul, add: add)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
@@ -132,250 +108,78 @@ public enum ButterworthBandReject {
}
let sr: Double = graph.engine.sampleRate
if lowFreqIsGenerator || highFreqIsGenerator {
let lowSamples: [Double]? = lowFreqIsGenerator
? lowFreqInput.calculatedSamples(graph: graph, count: count).first
: nil
let highSamples: [Double]? = highFreqIsGenerator
? highFreqInput.calculatedSamples(graph: graph, count: count).first
: nil
let lastI: Int = count - 1
let lf0: Double = lowSamples.map { $0.isEmpty ? lowFreqInput.floatValue(graph: graph) : $0[0] }
?? lowFreqInput.floatValue(graph: graph)
let lfN: Double = lowSamples.map { $0.isEmpty ? lf0 : $0[min($0.count - 1, lastI)] } ?? lf0
let hf0: Double = highSamples.map { $0.isEmpty ? highFreqInput.floatValue(graph: graph) : $0[0] }
?? highFreqInput.floatValue(graph: graph)
let hfN: Double = highSamples.map { $0.isEmpty ? hf0 : $0[min($0.count - 1, lastI)] } ?? hf0
runLPAudioRate(input: inputBlock, f0: lf0, fN: lfN, sr: sr, count: count)
runHPAudioRate(input: inputBlock, f0: hf0, fN: hfN, sr: sr, count: count)
} else {
let lowFreq: Double = lowFreqInput.floatValue(graph: graph)
let highFreq: Double = highFreqInput.floatValue(graph: graph)
if lowFreq != prevLowFreq || highFreq != prevHighFreq || sr != prevSampleRate {
recomputeScalarCoeffs(lowFreq: lowFreq, highFreq: highFreq, sr: sr)
prevLowFreq = lowFreq; prevHighFreq = highFreq; prevSampleRate = sr
// Resolve low-frequency (LP cutoff) inputs.
let lpScalarFreq: Double
let lpF0: Double
let lpFN: Double
if lowFreqIsGenerator {
let lowSamples: [[Double]] = lowFreqInput.calculatedSamples(graph: graph, count: count)
if let s: [Double] = lowSamples.first, !s.isEmpty {
lpF0 = s[0]
lpFN = s[min(s.count - 1, count - 1)]
} else {
let fv: Double = lowFreqInput.floatValue(graph: graph)
lpF0 = fv; lpFN = fv
}
runLPScalar(input: inputBlock, count: count)
runHPScalar(input: inputBlock, count: count)
lpScalarFreq = 0.0
} else {
lpScalarFreq = lowFreqInput.floatValue(graph: graph)
lpF0 = 0.0; lpFN = 0.0
}
// Parallel sum: LP (in _lpResult) + HP (in _result[0]) → _result[0]
for i: Int in 0..<count { _result[0][i] += _lpResult[i] }
// Resolve high-frequency (HP cutoff) inputs.
let hpScalarFreq: Double
let hpF0: Double
let hpFN: Double
if highFreqIsGenerator {
let highSamples: [[Double]] = highFreqInput.calculatedSamples(graph: graph, count: count)
if let s: [Double] = highSamples.first, !s.isEmpty {
hpF0 = s[0]
hpFN = s[min(s.count - 1, count - 1)]
} else {
let fv: Double = highFreqInput.floatValue(graph: graph)
hpF0 = fv; hpFN = fv
}
hpScalarFreq = 0.0
} else {
hpScalarFreq = highFreqInput.floatValue(graph: graph)
hpF0 = 0.0; hpFN = 0.0
}
// Parallel: LP section (lowFreq) and HP section (highFreq) each process the raw input.
lpEngine.process(
input: inputBlock,
freqIsGenerator: lowFreqIsGenerator,
scalarFreq: lpScalarFreq,
f0: lpF0,
fN: lpFN,
sr: sr,
count: count,
into: &_lpOut
)
hpEngine.process(
input: inputBlock,
freqIsGenerator: highFreqIsGenerator,
scalarFreq: hpScalarFreq,
f0: hpF0,
fN: hpFN,
sr: sr,
count: count,
into: &_result[0]
)
// Sum: LP (in _lpOut) + HP (in _result[0]) → _result[0]
_lpOut.withUnsafeBufferPointer { lpBuf in
_result[0].withUnsafeMutableBufferPointer { outBuf in
guard let lpBase: UnsafePointer<Double> = lpBuf.baseAddress,
let outBase: UnsafeMutablePointer<Double> = outBuf.baseAddress else { return }
vDSP_vaddD(lpBase, 1, outBase, 1, outBase, 1, vDSP_Length(count))
}
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
// MARK: - Coefficient computation
private func recomputeScalarCoeffs(
lowFreq: Double,
highFreq: Double,
sr: Double
) {
if lpFirstOrder != nil { cachedLPFO = foLPCoeffs(freq: lowFreq, sr: sr) }
for i: Int in 0..<lpBiquadStages.count {
cachedLPBiquadCoeffs[i] = rbjLowPassCoeffs(freq: lowFreq, q: butterworthQs[i], sampleRate: sr)
}
if hpFirstOrder != nil { cachedHPFO = foHPCoeffs(freq: highFreq, sr: sr) }
for i: Int in 0..<hpBiquadStages.count {
cachedHPBiquadCoeffs[i] = rbjHighPassCoeffs(freq: highFreq, q: butterworthQs[i], sampleRate: sr)
}
}
// MARK: - LP cascade (primary buffer = _lpResult)
private func runLPScalar(
input: [Double],
count: Int
) {
let stageCount: Int = sectionStageCount
var si: Int = 0
if var fo: FirstOrderState = lpFirstOrder {
let writesResult: Bool = (stageCount + 0) % 2 == 1
if writesResult {
fo.processBlock(input: input, b0: cachedLPFO.b0, b1: cachedLPFO.b1, na1: cachedLPFO.na1,
into: &_lpResult, count: count)
} else {
fo.processBlock(input: input, b0: cachedLPFO.b0, b1: cachedLPFO.b1, na1: cachedLPFO.na1,
into: &_scratch, count: count)
}
lpFirstOrder = fo
si = 1
}
for bi: Int in 0..<lpBiquadStages.count {
let i: Int = si + bi
let writesResult: Bool = (stageCount + i) % 2 == 1
if writesResult {
if i == 0 {
lpBiquadStages[bi].processBlock(input: input, coeffs: cachedLPBiquadCoeffs[bi],
into: &_lpResult, count: count)
} else {
lpBiquadStages[bi].processBlock(input: _scratch, coeffs: cachedLPBiquadCoeffs[bi],
into: &_lpResult, count: count)
}
} else {
if i == 0 {
lpBiquadStages[bi].processBlock(input: input, coeffs: cachedLPBiquadCoeffs[bi],
into: &_scratch, count: count)
} else {
lpBiquadStages[bi].processBlock(input: _lpResult, coeffs: cachedLPBiquadCoeffs[bi],
into: &_scratch, count: count)
}
}
}
}
// MARK: - HP cascade (primary buffer = _result[0])
private func runHPScalar(
input: [Double],
count: Int
) {
let stageCount: Int = sectionStageCount
var si: Int = 0
if var fo: FirstOrderState = hpFirstOrder {
let writesResult: Bool = (stageCount + 0) % 2 == 1
if writesResult {
fo.processBlock(input: input, b0: cachedHPFO.b0, b1: cachedHPFO.b1, na1: cachedHPFO.na1,
into: &_result[0], count: count)
} else {
fo.processBlock(input: input, b0: cachedHPFO.b0, b1: cachedHPFO.b1, na1: cachedHPFO.na1,
into: &_scratch, count: count)
}
hpFirstOrder = fo
si = 1
}
for bi: Int in 0..<hpBiquadStages.count {
let i: Int = si + bi
let writesResult: Bool = (stageCount + i) % 2 == 1
if writesResult {
if i == 0 {
hpBiquadStages[bi].processBlock(input: input, coeffs: cachedHPBiquadCoeffs[bi],
into: &_result[0], count: count)
} else {
hpBiquadStages[bi].processBlock(input: _scratch, coeffs: cachedHPBiquadCoeffs[bi],
into: &_result[0], count: count)
}
} else {
if i == 0 {
hpBiquadStages[bi].processBlock(input: input, coeffs: cachedHPBiquadCoeffs[bi],
into: &_scratch, count: count)
} else {
hpBiquadStages[bi].processBlock(input: _result[0], coeffs: cachedHPBiquadCoeffs[bi],
into: &_scratch, count: count)
}
}
}
}
// MARK: - Audio-rate paths
private func runLPAudioRate(
input: [Double],
f0: Double,
fN: Double,
sr: Double,
count: Int
) {
let stageCount: Int = sectionStageCount
var si: Int = 0
if var fo: FirstOrderState = lpFirstOrder {
let s: (b0: Double, b1: Double, na1: Double) = foLPCoeffs(freq: f0, sr: sr)
let e: (b0: Double, b1: Double, na1: Double) = foLPCoeffs(freq: fN, sr: sr)
let writesResult: Bool = (stageCount + 0) % 2 == 1
if writesResult {
fo.processBlock(input: input,
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
into: &_lpResult, count: count)
} else {
fo.processBlock(input: input,
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
into: &_scratch, count: count)
}
lpFirstOrder = fo
si = 1
}
for bi: Int in 0..<lpBiquadStages.count {
let i: Int = si + bi
let writesResult: Bool = (stageCount + i) % 2 == 1
let startC: BiquadCoeffs = rbjLowPassCoeffs(freq: f0, q: butterworthQs[bi], sampleRate: sr)
let endC: BiquadCoeffs = rbjLowPassCoeffs(freq: fN, q: butterworthQs[bi], sampleRate: sr)
if writesResult {
if i == 0 {
lpBiquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
into: &_lpResult, count: count)
} else {
lpBiquadStages[bi].processBlock(input: _scratch, startCoeffs: startC, endCoeffs: endC,
into: &_lpResult, count: count)
}
} else {
if i == 0 {
lpBiquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
into: &_scratch, count: count)
} else {
lpBiquadStages[bi].processBlock(input: _lpResult, startCoeffs: startC, endCoeffs: endC,
into: &_scratch, count: count)
}
}
}
}
private func runHPAudioRate(
input: [Double],
f0: Double,
fN: Double,
sr: Double,
count: Int
) {
let stageCount: Int = sectionStageCount
var si: Int = 0
if var fo: FirstOrderState = hpFirstOrder {
let s: (b0: Double, b1: Double, na1: Double) = foHPCoeffs(freq: f0, sr: sr)
let e: (b0: Double, b1: Double, na1: Double) = foHPCoeffs(freq: fN, sr: sr)
let writesResult: Bool = (stageCount + 0) % 2 == 1
if writesResult {
fo.processBlock(input: input,
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
into: &_result[0], count: count)
} else {
fo.processBlock(input: input,
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
into: &_scratch, count: count)
}
hpFirstOrder = fo
si = 1
}
for bi: Int in 0..<hpBiquadStages.count {
let i: Int = si + bi
let writesResult: Bool = (stageCount + i) % 2 == 1
let startC: BiquadCoeffs = rbjHighPassCoeffs(freq: f0, q: butterworthQs[bi], sampleRate: sr)
let endC: BiquadCoeffs = rbjHighPassCoeffs(freq: fN, q: butterworthQs[bi], sampleRate: sr)
if writesResult {
if i == 0 {
hpBiquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
into: &_result[0], count: count)
} else {
hpBiquadStages[bi].processBlock(input: _scratch, startCoeffs: startC, endCoeffs: endC,
into: &_result[0], count: count)
}
} else {
if i == 0 {
hpBiquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
into: &_scratch, count: count)
} else {
hpBiquadStages[bi].processBlock(input: _result[0], startCoeffs: startC, endCoeffs: endC,
into: &_scratch, count: count)
}
}
}
}
}
}
@@ -0,0 +1,123 @@
// ButterworthCascadeBase.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Thin Generator shell for the lowpass / highpass Butterworth filters.
///
/// All single-cascade machinery (biquad stages, optional first-order section, cached
/// coefficients, scratch buffer, vDSP background-thread builder) lives in
/// `ButterworthSectionEngine`. This class owns one engine, resolves its `input` and
/// `freq` inputs, delegates the per-block computation, and applies `mul`/`add`.
///
/// Concrete filters subclass this and inject only their per-stage coefficient formulas
/// and a thread name; all state and lifecycle live in the engine.
///
/// ## vDSP acceleration
/// For constant or block-rate `freq` (non-generator), a background thread builds a
/// `vDSP_biquad_SetupD` from the current coefficients and delivers it via a lock-free
/// `SPSCQueue`. Once the setup arrives the biquad cascade uses `vDSP_biquadD`; the
/// first-order section (odd orders) stays scalar. Audio-rate `freq` always uses the
/// scalar interpolating path. All machinery lives inside `ButterworthSectionEngine`.
public class _ButterworthCascadeBase: GeneratorBase, AudioGenerator {
private let inputSource: any ValidGeneratorInput
private let freqInput: any ValidGeneratorInput
private let freqIsGenerator: Bool
private let _mulAdd: MulAddSpec
private let engine: ButterworthSectionEngine
/// Filter order, clamped to `[1, maxButterworthOrder]` at init.
public var order: Int { engine.order }
/// Per-stage Butterworth Q values — `⌊order/2⌋` entries, computed once at init.
public var butterworthQs: [Double] { engine.butterworthQs }
// MARK: - Init
/// - Parameters:
/// - input: Signal to filter.
/// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist (sampleRate / 2).
/// - order: Filter order 1–8 (clamped internally).
/// - mul: Output multiplier.
/// - add: Output offset.
/// - foCoeffs: First-order section coefficient formula `(freq, sr) -> (b0, b1, na1)`.
/// - biquadCoeffs: Biquad-stage coefficient formula `(freq, q, sampleRate) -> BiquadCoeffs`.
/// - threadName: Name for the background vDSP setup-builder thread.
init(
input: any ValidGeneratorInput,
freq: any ValidGeneratorInput,
order: Int,
mul: any ValidGeneratorInput,
add: any ValidGeneratorInput,
foCoeffs: @escaping (Double, Double) -> (b0: Double, b1: Double, na1: Double),
biquadCoeffs: @escaping (Double, Double, Double) -> BiquadCoeffs,
threadName: String
) {
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
self.inputSource = resolvedInput
self.freqInput = resolvedFreq
self.freqIsGenerator = resolvedFreq is any Generator
self._mulAdd = MulAddSpec(mul: mul, add: add)
self.engine = ButterworthSectionEngine(
order: order,
foCoeffs: foCoeffs,
biquadCoeffs: biquadCoeffs,
threadName: threadName
)
super.init()
}
// MARK: - Compute
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
guard let inputBlock: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first else {
return _result
}
let sr: Double = graph.engine.sampleRate
let f0: Double
let fN: Double
let scalarFreq: Double
if freqIsGenerator {
let freqSamplesOuter: [[Double]] = freqInput.calculatedSamples(graph: graph, count: count)
if let freqSamples: [Double] = freqSamplesOuter.first, !freqSamples.isEmpty {
f0 = freqSamples[0]
fN = freqSamples[min(freqSamples.count - 1, count - 1)]
} else {
let fv: Double = freqInput.floatValue(graph: graph)
f0 = fv
fN = fv
}
scalarFreq = 0.0
} else {
scalarFreq = freqInput.floatValue(graph: graph)
f0 = 0.0
fN = 0.0
}
engine.process(
input: inputBlock,
freqIsGenerator: freqIsGenerator,
scalarFreq: scalarFreq,
f0: f0,
fN: fN,
sr: sr,
count: count,
into: &_result[0]
)
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
}
@@ -0,0 +1,32 @@
// ButterworthHelpers.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
// MARK: - Butterworth pole-Q helper
/// Computes per-stage Butterworth Q values for a filter of the given (already-clamped) order.
///
/// Returns `⌊order / 2⌋` Q values, one per biquad stage, using the pole formula:
/// ```
/// Q_k = −1 / (2 · cos(π · (2k + order − 1) / (2 · order))) k = 1 … ⌊order / 2⌋
/// ```
///
/// - Parameter order: Filter order, already clamped to `[1, maxButterworthOrder]`.
/// - Returns: Array of Q values, empty when `order == 1` (first-order section only, no biquads).
internal func computeButterworthQs(order: Int) -> [Double] {
let numBiquads: Int = order / 2
guard numBiquads > 0 else { return [] }
var qs: [Double] = [Double]()
qs.reserveCapacity(numBiquads)
let twiceOrder: Double = Double(2 * order)
for k: Int in 1...numBiquads {
let numerator: Double = Double.pi * Double(2 * k + order - 1)
let angle: Double = numerator / twiceOrder
qs.append(-1.0 / (2.0 * cos(angle)))
}
return qs
}
@@ -4,17 +4,14 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Accelerate
import Foundation
/// Cascaded Butterworth highpass filter, orders 1–8.
///
/// Mirror of `ButterworthLowPass` — identical cascade logic; only the per-stage coefficient
/// formula differs (RBJ HPF instead of LPF, and the bilinear first-order section is a HPF).
///
/// ## vDSP acceleration
///
/// Same Option-B background-thread strategy as `ButterworthLowPass`. See that class for details.
/// Mirror of `ButterworthLowPass`: all cascade machinery lives in
/// `_ButterworthCascadeBase`; this type injects the highpass coefficient
/// formulas — RBJ highpass per biquad stage, and a bilinear first-order highpass
/// for odd orders.
///
/// ## Usage
/// ```swift
@@ -30,369 +27,34 @@ import Foundation
/// - add: Output offset. Defaults to `0.0`.
public enum ButterworthHighPass {
public final class Audio: GeneratorBase, AudioGenerator {
public final class Audio: _ButterworthCascadeBase {
private static let bgPollInterval: TimeInterval = 0.001
private let inputSource: any ValidGeneratorInput
private let freqInput: any ValidGeneratorInput
private let freqIsGenerator: Bool
/// Filter order, clamped to `[1, maxButterworthOrder]` at init.
public let order: Int
/// Per-stage Butterworth Q values — `⌊order/2⌋` entries, computed once at init.
public let butterworthQs: [Double]
private var biquadStages: [BiquadState]
private var firstOrderState: FirstOrderState?
private var _scratch: [Double]
private var cachedBiquadCoeffs: [BiquadCoeffs]
private var cachedFO: (b0: Double, b1: Double, na1: Double) = (0, 0, 0)
private var prevFreq: Double = -1.0
private var prevSampleRate: Double = -1.0
private let _mulAdd: MulAddSpec
// MARK: - vDSP cascade (background-thread Option B, RT-safe)
private var _vdspSetup: OpaquePointer?
private var _vdspDelay: [Double]
private let _vdspCoeffQueue: SPSCQueue<BiquadCoeffPacket>
private let _vdspRespQueue: SPSCQueue<OpaquePointer>
private let _vdspKillQueue: SPSCQueue<OpaquePointer>
private let _bgDoneSema: DispatchSemaphore
private let _bgSleepSema: DispatchSemaphore
private var _vdspThread: Thread?
// MARK: - Init
/// - Parameters:
/// - input: Signal to filter.
/// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist (sampleRate / 2).
/// - order: Filter order 1–8 (clamped internally). Each order adds −6 dB/oct slope. Higher order = steeper rolloff but higher CPU cost. Defaults to `4`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public init(
input: any ValidGeneratorInput,
freq: any ValidGeneratorInput,
order: Int,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
self.inputSource = resolvedInput
self.freqInput = resolvedFreq
self.freqIsGenerator = resolvedFreq is any Generator
let clampedOrder: Int = min(max(order, 1), maxButterworthOrder)
self.order = clampedOrder
let numBiquads: Int = clampedOrder / 2
var qs: [Double] = [Double]()
if numBiquads > 0 {
for k: Int in 1...numBiquads {
let angle: Double = Double.pi * Double(2 * k + clampedOrder - 1)
/ Double(2 * clampedOrder)
qs.append(-1.0 / (2.0 * cos(angle)))
}
}
self.butterworthQs = qs
self.biquadStages = [BiquadState](repeating: BiquadState(), count: numBiquads)
self.firstOrderState = clampedOrder % 2 == 1 ? FirstOrderState() : nil
self._scratch = makeSampleBuffer()
self.cachedBiquadCoeffs = [BiquadCoeffs](repeating: .zero, count: numBiquads)
self._vdspSetup = nil
let biquadDelayStateCount: Int = 2 * (numBiquads + 1)
self._vdspDelay = numBiquads > 0
? [Double](repeating: 0, count: biquadDelayStateCount)
: []
self._vdspCoeffQueue = SPSCQueue(capacity: butterworthCoeffQueueCapacity)
self._vdspRespQueue = SPSCQueue(capacity: butterworthRespQueueCapacity)
self._vdspKillQueue = SPSCQueue(capacity: butterworthKillQueueCapacity)
self._bgDoneSema = DispatchSemaphore(value: 0)
self._bgSleepSema = DispatchSemaphore(value: 0)
self._mulAdd = MulAddSpec(mul: mul, add: add)
if numBiquads > 0 {
let cq: SPSCQueue<BiquadCoeffPacket> = _vdspCoeffQueue
let rq: SPSCQueue<OpaquePointer> = _vdspRespQueue
let kq: SPSCQueue<OpaquePointer> = _vdspKillQueue
let doneSema: DispatchSemaphore = _bgDoneSema
let sleepSema: DispatchSemaphore = _bgSleepSema
let t: Thread = Thread {
var shouldStop: Bool = false
while !shouldStop {
while let ptr: OpaquePointer = kq.dequeue() {
vDSP_biquad_DestroySetupD(ptr)
}
if let packet: BiquadCoeffPacket = cq.dequeue() {
packet.withUnsafeCoeffPtr { ptr in
if let setup: vDSP_biquad_SetupD = vDSP_biquad_CreateSetupD(
ptr, vDSP_Length(packet.numSections)
) {
if !rq.enqueue(setup) {
vDSP_biquad_DestroySetupD(setup)
}
}
}
}
if sleepSema.wait(timeout: .now() + Audio.bgPollInterval) == .success { shouldStop = true }
}
while let ptr: OpaquePointer = kq.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
while let ptr: OpaquePointer = rq.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
doneSema.signal()
}
t.name = "LyrebirdButterworthHP.vDSP"
t.qualityOfService = .userInteractive
_vdspThread = t
t.start()
}
}
// MARK: - Deinit
deinit {
if _vdspThread != nil {
_bgSleepSema.signal()
_bgDoneSema.wait()
}
if let setup: OpaquePointer = _vdspSetup {
vDSP_biquad_DestroySetupD(setup)
}
while let ptr: OpaquePointer = _vdspRespQueue.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
while let ptr: OpaquePointer = _vdspKillQueue.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
}
// MARK: - Generator protocol
// MARK: - Compute
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
guard let inputBlock: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first else {
return _result
}
let sr: Double = graph.engine.sampleRate
let hasFO: Bool = firstOrderState != nil
let totalStages: Int = biquadStages.count + (hasFO ? 1 : 0)
guard totalStages > 0 else {
let n: Int = min(count, inputBlock.count)
inputBlock.withUnsafeBufferPointer { srcBuf in
_result[0].withUnsafeMutableBufferPointer { dstBuf in
guard let srcBase: UnsafePointer<Double> = srcBuf.baseAddress,
let dstBase: UnsafeMutablePointer<Double> = dstBuf.baseAddress else { return }
if n > 0 { dstBase.update(from: srcBase, count: n) }
if n < count {
vDSP_vclrD(dstBase + n, 1, vDSP_Length(count - n))
}
}
}
return _result
}
if freqIsGenerator {
let freqSamplesOuter: [[Double]] = freqInput.calculatedSamples(graph: graph, count: count)
let f0: Double
let fN: Double
if let freqSamples: [Double] = freqSamplesOuter.first, !freqSamples.isEmpty {
f0 = freqSamples[0]
fN = freqSamples[min(freqSamples.count - 1, count - 1)]
} else {
f0 = freqInput.floatValue(graph: graph)
fN = f0
}
runAudioRate(input: inputBlock, f0: f0, fN: fN, sr: sr, N: totalStages, count: count)
} else {
let freq: Double = freqInput.floatValue(graph: graph)
if freq != prevFreq || sr != prevSampleRate {
recomputeScalarCoeffs(freq: freq, sr: sr)
prevFreq = freq; prevSampleRate = sr
if !biquadStages.isEmpty {
let packet: BiquadCoeffPacket = BiquadCoeffPacket(from: cachedBiquadCoeffs)
if !_vdspCoeffQueue.enqueue(packet) {
// Queue full — reset sentinels so next block retries.
prevFreq = -1.0; prevSampleRate = -1.0
}
}
}
if let newSetup: OpaquePointer = _vdspRespQueue.dequeue() {
if let old: OpaquePointer = _vdspSetup {
if !_vdspKillQueue.enqueue(old) {
// Kill queue full (capacity 32, bg thread drains every 1ms).
// Emergency same-thread destroy to prevent leak; violates RT-alloc rule
// but is unreachable under normal operation.
vDSP_biquad_DestroySetupD(old)
}
}
_vdspSetup = newSetup
}
if let setup: OpaquePointer = _vdspSetup {
runVDSP(input: inputBlock, count: count, setup: setup)
} else {
runScalar(input: inputBlock, N: totalStages, count: count)
}
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
// MARK: - Coefficient computation
private func recomputeScalarCoeffs(
freq: Double,
sr: Double
) {
if firstOrderState != nil {
cachedFO = foHPCoeffs(freq: freq, sr: sr)
}
for i: Int in 0..<biquadStages.count {
cachedBiquadCoeffs[i] = rbjHighPassCoeffs(freq: freq, q: butterworthQs[i], sampleRate: sr)
}
}
// MARK: - vDSP cascade path
private func runVDSP(
input: [Double],
count: Int,
setup: OpaquePointer
) {
if var fo: FirstOrderState = firstOrderState {
fo.processBlock(input: input,
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
into: &_scratch, count: count)
firstOrderState = fo
_scratch.withUnsafeBufferPointer { inBuf in
_result[0].withUnsafeMutableBufferPointer { outBuf in
_vdspDelay.withUnsafeMutableBufferPointer { delay in
guard let d: UnsafeMutablePointer<Double> = delay.baseAddress, let i: UnsafePointer<Double> = inBuf.baseAddress,
let o: UnsafeMutablePointer<Double> = outBuf.baseAddress else { return }
vDSP_biquadD(setup, d, i, 1, o, 1, vDSP_Length(count))
}
}
}
} else {
input.withUnsafeBufferPointer { inBuf in
_result[0].withUnsafeMutableBufferPointer { outBuf in
_vdspDelay.withUnsafeMutableBufferPointer { delay in
guard let d: UnsafeMutablePointer<Double> = delay.baseAddress, let i: UnsafePointer<Double> = inBuf.baseAddress,
let o: UnsafeMutablePointer<Double> = outBuf.baseAddress else { return }
vDSP_biquadD(setup, d, i, 1, o, 1, vDSP_Length(count))
}
}
}
}
}
// MARK: - Scalar cascade path
private func runScalar(
input: [Double],
N: Int,
count: Int
) {
var si: Int = 0
if var fo: FirstOrderState = firstOrderState {
let writesResult: Bool = (N + 0) % 2 == 1
if writesResult {
fo.processBlock(input: input,
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
into: &_result[0], count: count)
} else {
fo.processBlock(input: input,
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
into: &_scratch, count: count)
}
firstOrderState = fo
si = 1
}
for bi: Int in 0..<biquadStages.count {
let i: Int = si + bi
let writesResult: Bool = (N + i) % 2 == 1
let readsResult: Bool = i > 0 && (N + i) % 2 == 0
if writesResult {
if i == 0 {
biquadStages[bi].processBlock(input: input, coeffs: cachedBiquadCoeffs[bi],
into: &_result[0], count: count)
} else {
biquadStages[bi].processBlock(input: _scratch, coeffs: cachedBiquadCoeffs[bi],
into: &_result[0], count: count)
}
} else {
if readsResult {
biquadStages[bi].processBlock(input: _result[0], coeffs: cachedBiquadCoeffs[bi],
into: &_scratch, count: count)
} else {
biquadStages[bi].processBlock(input: input, coeffs: cachedBiquadCoeffs[bi],
into: &_scratch, count: count)
}
}
}
}
private func runAudioRate(
input: [Double],
f0: Double,
fN: Double,
sr: Double,
N: Int,
count: Int
) {
var si: Int = 0
if var fo: FirstOrderState = firstOrderState {
let s: (b0: Double, b1: Double, na1: Double) = foHPCoeffs(freq: f0, sr: sr)
let e: (b0: Double, b1: Double, na1: Double) = foHPCoeffs(freq: fN, sr: sr)
let writesResult: Bool = (N + 0) % 2 == 1
if writesResult {
fo.processBlock(input: input,
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
into: &_result[0], count: count)
} else {
fo.processBlock(input: input,
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
into: &_scratch, count: count)
}
firstOrderState = fo
si = 1
}
for bi: Int in 0..<biquadStages.count {
let i: Int = si + bi
let writesResult: Bool = (N + i) % 2 == 1
let readsResult: Bool = i > 0 && (N + i) % 2 == 0
let startC: BiquadCoeffs = rbjHighPassCoeffs(freq: f0, q: butterworthQs[bi], sampleRate: sr)
let endC: BiquadCoeffs = rbjHighPassCoeffs(freq: fN, q: butterworthQs[bi], sampleRate: sr)
if writesResult {
if i == 0 {
biquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
into: &_result[0], count: count)
} else {
biquadStages[bi].processBlock(input: _scratch, startCoeffs: startC, endCoeffs: endC,
into: &_result[0], count: count)
}
} else {
if readsResult {
biquadStages[bi].processBlock(input: _result[0], startCoeffs: startC, endCoeffs: endC,
into: &_scratch, count: count)
} else {
biquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
into: &_scratch, count: count)
}
}
/// - Parameters:
/// - input: Signal to filter.
/// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist (sampleRate / 2).
/// - order: Filter order 1–8 (clamped internally). Each order adds −6 dB/oct slope. Higher order = steeper rolloff but higher CPU cost. Defaults to `4`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public init(
input: any ValidGeneratorInput,
freq: any ValidGeneratorInput,
order: Int,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
super.init(
input: input,
freq: freq,
order: order,
mul: mul,
add: add,
foCoeffs: { foHPCoeffs(freq: $0, sr: $1) },
biquadCoeffs: { rbjHighPassCoeffs(freq: $0, q: $1, sampleRate: $2) },
threadName: "LyrebirdButterworthHP.vDSP"
)
}
}
}
} // close enum ButterworthHighPass
// MARK: - First-order HP coefficient helper
@@ -4,29 +4,14 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Accelerate
import Foundation
/// Cascaded Butterworth lowpass filter, orders 1–8.
///
/// Order is fixed at `init`. For even orders the filter is all biquad stages; for odd
/// orders a first-order section precedes the biquad cascade. All buffers are pre-allocated —
/// no heap allocation occurs on the RT thread.
///
/// Per-stage Q values are derived at `init` from the Butterworth pole formula:
/// ```
/// Q_k = −1 / (2 · cos(π · (2k + N − 1) / (2N))) k = 1 … ⌊N/2⌋
/// ```
/// At block rate the shared `freq` input modulates all stage coefficients simultaneously.
/// Audio-rate `freq` uses block-boundary coefficient interpolation independently per stage.
///
/// ## vDSP acceleration
///
/// For constant or block-rate `freq` (non-generator), a background thread builds a
/// `vDSP_biquad_SetupD` from the current coefficients and delivers it via a lock-free
/// `SPSCQueue`. Once the setup arrives the biquad cascade uses `vDSP_biquadD`; the
/// first-order section (odd orders) stays scalar. Audio-rate `freq` always uses the
/// scalar interpolating path.
/// All cascade machinery (per-stage Butterworth Q, scalar / audio-rate-interpolated
/// paths, and the background-thread `vDSP_biquad_SetupD` builder) lives in
/// `_ButterworthCascadeBase`. This type injects the lowpass coefficient formulas:
/// RBJ lowpass per biquad stage, and a bilinear first-order lowpass for odd orders.
///
/// ## Usage
/// ```swift
@@ -42,391 +27,34 @@ import Foundation
/// - add: Output offset. Defaults to `0.0`.
public enum ButterworthLowPass {
public final class Audio: GeneratorBase, AudioGenerator {
public final class Audio: _ButterworthCascadeBase {
private static let bgPollInterval: TimeInterval = 0.001
private let inputSource: any ValidGeneratorInput
private let freqInput: any ValidGeneratorInput
private let freqIsGenerator: Bool
/// Filter order, clamped to `[1, maxButterworthOrder]` at init.
public let order: Int
/// Per-stage Butterworth Q values — `⌊order/2⌋` entries, computed once at init.
public let butterworthQs: [Double]
private var biquadStages: [BiquadState]
private var firstOrderState: FirstOrderState?
private var _scratch: [Double]
private var cachedBiquadCoeffs: [BiquadCoeffs]
private var cachedFO: (b0: Double, b1: Double, na1: Double) = (0, 0, 0)
private var prevFreq: Double = -1.0
private var prevSampleRate: Double = -1.0
private let _mulAdd: MulAddSpec
// MARK: - vDSP cascade (background-thread Option B, RT-safe)
// Current live Double biquad setup. nil until background thread delivers first setup.
// Only accessed from _computeSamples (RT thread) — no concurrent access.
private var _vdspSetup: OpaquePointer?
// Delay buffer: 2*(numBiquads+1) Doubles. Pre-allocated; never resized.
private var _vdspDelay: [Double]
// RT → bg: new coefficient packets to build a setup from.
private let _vdspCoeffQueue: SPSCQueue<BiquadCoeffPacket>
// bg → RT: newly-built setups ready to swap in.
private let _vdspRespQueue: SPSCQueue<OpaquePointer>
// RT → bg: old setups to destroy (avoids dealloc on RT thread).
private let _vdspKillQueue: SPSCQueue<OpaquePointer>
// Signals deinit that the background thread has exited cleanly.
private let _bgDoneSema: DispatchSemaphore
// Doubles as sleep timer and stop signal: deinit signals it to wake the thread early.
// Thread.cancel() / pthread_cancel is NOT used — pthread_cancel kills the thread at
// nanosleep (a POSIX cancellation point), bypassing doneSema.signal() and deadlocking
// _bgDoneSema.wait() in deinit.
private let _bgSleepSema: DispatchSemaphore
private var _vdspThread: Thread?
// MARK: - Init
/// - Parameters:
/// - input: Signal to filter.
/// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist (sampleRate / 2).
/// - order: Filter order 1–8 (clamped internally). Each order adds −6 dB/oct slope. Higher order = steeper rolloff but higher CPU cost. Defaults to `4`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public init(
input: any ValidGeneratorInput,
freq: any ValidGeneratorInput,
order: Int,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
self.inputSource = resolvedInput
self.freqInput = resolvedFreq
self.freqIsGenerator = resolvedFreq is any Generator
let clampedOrder: Int = min(max(order, 1), maxButterworthOrder)
self.order = clampedOrder
let numBiquads: Int = clampedOrder / 2
var qs: [Double] = [Double]()
if numBiquads > 0 {
for k: Int in 1...numBiquads {
let angle: Double = Double.pi * Double(2 * k + clampedOrder - 1)
/ Double(2 * clampedOrder)
qs.append(-1.0 / (2.0 * cos(angle)))
}
}
self.butterworthQs = qs
self.biquadStages = [BiquadState](repeating: BiquadState(), count: numBiquads)
self.firstOrderState = clampedOrder % 2 == 1 ? FirstOrderState() : nil
self._scratch = makeSampleBuffer()
self.cachedBiquadCoeffs = [BiquadCoeffs](repeating: .zero, count: numBiquads)
self._vdspSetup = nil
let biquadDelayStateCount: Int = 2 * (numBiquads + 1)
self._vdspDelay = numBiquads > 0
? [Double](repeating: 0, count: biquadDelayStateCount)
: []
self._vdspCoeffQueue = SPSCQueue(capacity: butterworthCoeffQueueCapacity)
self._vdspRespQueue = SPSCQueue(capacity: butterworthRespQueueCapacity)
self._vdspKillQueue = SPSCQueue(capacity: butterworthKillQueueCapacity)
self._bgDoneSema = DispatchSemaphore(value: 0)
self._bgSleepSema = DispatchSemaphore(value: 0)
self._mulAdd = MulAddSpec(mul: mul, add: add)
// Start background setup thread only when there are biquad sections (order >= 2).
if numBiquads > 0 {
let cq: SPSCQueue<BiquadCoeffPacket> = _vdspCoeffQueue
let rq: SPSCQueue<OpaquePointer> = _vdspRespQueue
let kq: SPSCQueue<OpaquePointer> = _vdspKillQueue
let doneSema: DispatchSemaphore = _bgDoneSema
let sleepSema: DispatchSemaphore = _bgSleepSema
let t: Thread = Thread {
var shouldStop: Bool = false
while !shouldStop {
while let ptr: OpaquePointer = kq.dequeue() {
vDSP_biquad_DestroySetupD(ptr)
}
if let packet: BiquadCoeffPacket = cq.dequeue() {
packet.withUnsafeCoeffPtr { ptr in
if let setup: vDSP_biquad_SetupD = vDSP_biquad_CreateSetupD(
ptr, vDSP_Length(packet.numSections)
) {
if !rq.enqueue(setup) {
vDSP_biquad_DestroySetupD(setup)
}
}
}
}
// .success = woken early by deinit (stop signal); .timedOut = normal poll.
if sleepSema.wait(timeout: .now() + Audio.bgPollInterval) == .success { shouldStop = true }
}
// Drain queues on exit so deinit can safely claim ownership.
while let ptr: OpaquePointer = kq.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
while let ptr: OpaquePointer = rq.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
doneSema.signal()
}
t.name = "LyrebirdButterworthLP.vDSP"
t.qualityOfService = .userInteractive
_vdspThread = t
t.start()
}
}
// MARK: - Deinit
deinit {
if _vdspThread != nil {
_bgSleepSema.signal() // wake thread from its 1ms sleep, stop signal
_bgDoneSema.wait() // wait for thread to drain queues and exit
}
if let setup: OpaquePointer = _vdspSetup {
vDSP_biquad_DestroySetupD(setup)
}
// Thread drained these on exit; drain again as safety (no-ops when already empty).
while let ptr: OpaquePointer = _vdspRespQueue.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
while let ptr: OpaquePointer = _vdspKillQueue.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
}
// MARK: - Generator protocol
// MARK: - Compute
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
guard let inputBlock: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first else {
return _result
}
let sr: Double = graph.engine.sampleRate
let hasFO: Bool = firstOrderState != nil
let totalStages: Int = biquadStages.count + (hasFO ? 1 : 0)
guard totalStages > 0 else {
let n: Int = min(count, inputBlock.count)
inputBlock.withUnsafeBufferPointer { srcBuf in
_result[0].withUnsafeMutableBufferPointer { dstBuf in
guard let srcBase: UnsafePointer<Double> = srcBuf.baseAddress,
let dstBase: UnsafeMutablePointer<Double> = dstBuf.baseAddress else { return }
if n > 0 { dstBase.update(from: srcBase, count: n) }
if n < count {
vDSP_vclrD(dstBase + n, 1, vDSP_Length(count - n))
}
}
}
return _result
}
if freqIsGenerator {
let freqSamplesOuter: [[Double]] = freqInput.calculatedSamples(graph: graph, count: count)
let f0: Double
let fN: Double
if let freqSamples: [Double] = freqSamplesOuter.first, !freqSamples.isEmpty {
f0 = freqSamples[0]
fN = freqSamples[min(freqSamples.count - 1, count - 1)]
} else {
f0 = freqInput.floatValue(graph: graph)
fN = f0
}
runAudioRate(input: inputBlock, f0: f0, fN: fN, sr: sr, N: totalStages, count: count)
} else {
let freq: Double = freqInput.floatValue(graph: graph)
if freq != prevFreq || sr != prevSampleRate {
recomputeScalarCoeffs(freq: freq, sr: sr)
prevFreq = freq; prevSampleRate = sr
if !biquadStages.isEmpty {
let packet: BiquadCoeffPacket = BiquadCoeffPacket(from: cachedBiquadCoeffs)
if !_vdspCoeffQueue.enqueue(packet) {
// Queue full — reset sentinels so next block retries.
prevFreq = -1.0; prevSampleRate = -1.0
}
}
}
// Swap in any new setup the background thread prepared.
if let newSetup: OpaquePointer = _vdspRespQueue.dequeue() {
if let old: OpaquePointer = _vdspSetup {
if !_vdspKillQueue.enqueue(old) {
// Kill queue full (capacity 32, bg thread drains every 1ms).
// Emergency same-thread destroy to prevent leak; violates RT-alloc rule
// but is unreachable under normal operation.
vDSP_biquad_DestroySetupD(old)
}
}
_vdspSetup = newSetup
}
if let setup: OpaquePointer = _vdspSetup {
runVDSP(input: inputBlock, count: count, setup: setup)
} else {
runScalar(input: inputBlock, N: totalStages, count: count)
}
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
// MARK: - Coefficient computation
private func recomputeScalarCoeffs(
freq: Double,
sr: Double
) {
if firstOrderState != nil {
cachedFO = foLPCoeffs(freq: freq, sr: sr)
}
for i: Int in 0..<biquadStages.count {
cachedBiquadCoeffs[i] = rbjLowPassCoeffs(freq: freq, q: butterworthQs[i], sampleRate: sr)
}
}
// MARK: - vDSP cascade path
/// Runs the biquad cascade via `vDSP_biquadD`. For odd orders, the first-order section
/// runs scalar first (into `_scratch`); the biquad cascade then reads from `_scratch`.
private func runVDSP(
input: [Double],
count: Int,
setup: OpaquePointer
) {
if var fo: FirstOrderState = firstOrderState {
fo.processBlock(input: input,
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
into: &_scratch, count: count)
firstOrderState = fo
_scratch.withUnsafeBufferPointer { inBuf in
_result[0].withUnsafeMutableBufferPointer { outBuf in
_vdspDelay.withUnsafeMutableBufferPointer { delay in
guard let d: UnsafeMutablePointer<Double> = delay.baseAddress, let i: UnsafePointer<Double> = inBuf.baseAddress,
let o: UnsafeMutablePointer<Double> = outBuf.baseAddress else { return }
vDSP_biquadD(setup, d, i, 1, o, 1, vDSP_Length(count))
}
}
}
} else {
input.withUnsafeBufferPointer { inBuf in
_result[0].withUnsafeMutableBufferPointer { outBuf in
_vdspDelay.withUnsafeMutableBufferPointer { delay in
guard let d: UnsafeMutablePointer<Double> = delay.baseAddress, let i: UnsafePointer<Double> = inBuf.baseAddress,
let o: UnsafeMutablePointer<Double> = outBuf.baseAddress else { return }
vDSP_biquadD(setup, d, i, 1, o, 1, vDSP_Length(count))
}
}
}
}
}
// MARK: - Scalar cascade path
/// Buffer routing rule: stage `i` of `N` total writes to `_result[0]` when
/// `(N + i) % 2 == 1`, otherwise writes to `_scratch`.
/// When `i > 0` and writes to `_result[0]`, it reads from `_scratch` and vice versa.
private func runScalar(
input: [Double],
N: Int,
count: Int
) {
var si: Int = 0
if var fo: FirstOrderState = firstOrderState {
let writesResult: Bool = (N + 0) % 2 == 1
if writesResult {
fo.processBlock(input: input,
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
into: &_result[0], count: count)
} else {
fo.processBlock(input: input,
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
into: &_scratch, count: count)
}
firstOrderState = fo
si = 1
}
for bi: Int in 0..<biquadStages.count {
let i: Int = si + bi
let writesResult: Bool = (N + i) % 2 == 1
let readsResult: Bool = i > 0 && (N + i) % 2 == 0
if writesResult {
if i == 0 {
biquadStages[bi].processBlock(input: input, coeffs: cachedBiquadCoeffs[bi],
into: &_result[0], count: count)
} else {
biquadStages[bi].processBlock(input: _scratch, coeffs: cachedBiquadCoeffs[bi],
into: &_result[0], count: count)
}
} else {
if readsResult {
biquadStages[bi].processBlock(input: _result[0], coeffs: cachedBiquadCoeffs[bi],
into: &_scratch, count: count)
} else {
biquadStages[bi].processBlock(input: input, coeffs: cachedBiquadCoeffs[bi],
into: &_scratch, count: count)
}
}
}
}
private func runAudioRate(
input: [Double],
f0: Double,
fN: Double,
sr: Double,
N: Int,
count: Int
) {
var si: Int = 0
if var fo: FirstOrderState = firstOrderState {
let s: (b0: Double, b1: Double, na1: Double) = foLPCoeffs(freq: f0, sr: sr)
let e: (b0: Double, b1: Double, na1: Double) = foLPCoeffs(freq: fN, sr: sr)
let writesResult: Bool = (N + 0) % 2 == 1
if writesResult {
fo.processBlock(input: input,
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
into: &_result[0], count: count)
} else {
fo.processBlock(input: input,
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
into: &_scratch, count: count)
}
firstOrderState = fo
si = 1
}
for bi: Int in 0..<biquadStages.count {
let i: Int = si + bi
let writesResult: Bool = (N + i) % 2 == 1
let readsResult: Bool = i > 0 && (N + i) % 2 == 0
let startC: BiquadCoeffs = rbjLowPassCoeffs(freq: f0, q: butterworthQs[bi], sampleRate: sr)
let endC: BiquadCoeffs = rbjLowPassCoeffs(freq: fN, q: butterworthQs[bi], sampleRate: sr)
if writesResult {
if i == 0 {
biquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
into: &_result[0], count: count)
} else {
biquadStages[bi].processBlock(input: _scratch, startCoeffs: startC, endCoeffs: endC,
into: &_result[0], count: count)
}
} else {
if readsResult {
biquadStages[bi].processBlock(input: _result[0], startCoeffs: startC, endCoeffs: endC,
into: &_scratch, count: count)
} else {
biquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
into: &_scratch, count: count)
}
}
/// - Parameters:
/// - input: Signal to filter.
/// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist (sampleRate / 2).
/// - order: Filter order 1–8 (clamped internally). Each order adds −6 dB/oct slope. Higher order = steeper rolloff but higher CPU cost. Defaults to `4`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public init(
input: any ValidGeneratorInput,
freq: any ValidGeneratorInput,
order: Int,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
super.init(
input: input,
freq: freq,
order: order,
mul: mul,
add: add,
foCoeffs: { foLPCoeffs(freq: $0, sr: $1) },
biquadCoeffs: { rbjLowPassCoeffs(freq: $0, q: $1, sampleRate: $2) },
threadName: "LyrebirdButterworthLP.vDSP"
)
}
}
}
} // close enum ButterworthLowPass
// MARK: - First-order LP coefficient helper
@@ -0,0 +1,409 @@
// ButterworthSectionEngine.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Accelerate
import Foundation
/// Internal cascade engine for a single Butterworth LP or HP section.
///
/// Encapsulates all single-cascade machinery: biquad stages, optional first-order
/// state, cached coefficients, scratch buffer, and the background-thread
/// `vDSP_biquad_SetupD` builder (SPSC queues + semaphore deinit handshake).
/// Coefficient formulas are injected via two stored closures and a thread name.
///
/// This class is NOT a `Generator`. It is a shared computation engine owned by
/// `_ButterworthCascadeBase` (one engine, LP/HP), `ButterworthBandPass.Audio`
/// (two engines in series), and `ButterworthBandReject.Audio` (two engines in
/// parallel, summed). All buffer writes go into the caller-supplied `output`
/// inout slice — no internal `_result` allocation.
///
/// Order is fixed at `init`. For even orders the filter is all biquad stages;
/// for odd orders a first-order section precedes the biquad cascade. All buffers
/// are pre-allocated — no heap allocation occurs on the RT thread.
///
/// ## vDSP acceleration
/// For constant or block-rate `freq` (non-generator), a background thread builds
/// a `vDSP_biquad_SetupD` from the current coefficients and delivers it via a
/// lock-free `SPSCQueue`. Once the setup arrives the biquad cascade uses
/// `vDSP_biquadD`; the first-order section (odd orders) stays scalar. Audio-rate
/// `freq` always uses the scalar interpolating path.
final class ButterworthSectionEngine {
private static let bgPollInterval: TimeInterval = 0.001
/// Filter order, clamped to `[1, maxButterworthOrder]` at init.
let order: Int
/// Per-stage Butterworth Q values — `⌊order/2⌋` entries, computed once at init.
let butterworthQs: [Double]
private var biquadStages: [BiquadState]
private var firstOrderState: FirstOrderState?
private var scratch: [Double]
private var cachedBiquadCoeffs: [BiquadCoeffs]
private var cachedFO: (b0: Double, b1: Double, na1: Double) = (0, 0, 0)
private var prevFreq: Double = -1.0
private var prevSampleRate: Double = -1.0
/// First-order section coefficients for a cutoff `freq` at sample rate `sr`.
private let foCoeffs: (Double, Double) -> (b0: Double, b1: Double, na1: Double)
/// Biquad-stage coefficients for `(freq, q, sampleRate)`.
private let biquadCoeffsFunc: (Double, Double, Double) -> BiquadCoeffs
// MARK: - vDSP cascade (background-thread RT-safe)
// Current live Double biquad setup. nil until background thread delivers first setup.
// Only accessed from process(...) (RT thread) — no concurrent access.
private var vdspSetup: OpaquePointer?
// Delay buffer: 2*(numBiquads+1) Doubles. Pre-allocated; never resized.
private var vdspDelay: [Double]
// RT → bg: new coefficient packets to build a setup from.
private let vdspCoeffQueue: SPSCQueue<BiquadCoeffPacket>
// bg → RT: newly-built setups ready to swap in.
private let vdspRespQueue: SPSCQueue<OpaquePointer>
// RT → bg: old setups to destroy (avoids dealloc on RT thread).
private let vdspKillQueue: SPSCQueue<OpaquePointer>
// Signals deinit that the background thread has exited cleanly.
private let bgDoneSema: DispatchSemaphore
// Doubles as sleep timer and stop signal: deinit signals it to wake the thread early.
// Thread.cancel() / pthread_cancel is NOT used — pthread_cancel kills the thread at
// nanosleep (a POSIX cancellation point), bypassing doneSema.signal() and deadlocking
// bgDoneSema.wait() in deinit.
private let bgSleepSema: DispatchSemaphore
private var vdspThread: Thread?
// MARK: - Init
/// Creates a single-cascade Butterworth section engine.
///
/// - Parameters:
/// - order: Filter order 1–8 (clamped internally).
/// - foCoeffs: First-order section coefficient formula `(freq, sr) -> (b0, b1, na1)`.
/// - biquadCoeffs: Biquad-stage coefficient formula `(freq, q, sampleRate) -> BiquadCoeffs`.
/// - threadName: Name for the background vDSP setup-builder thread.
init(
order: Int,
foCoeffs: @escaping (Double, Double) -> (b0: Double, b1: Double, na1: Double),
biquadCoeffs: @escaping (Double, Double, Double) -> BiquadCoeffs,
threadName: String
) {
let clampedOrder: Int = min(max(order, 1), maxButterworthOrder)
self.order = clampedOrder
self.foCoeffs = foCoeffs
self.biquadCoeffsFunc = biquadCoeffs
let numBiquads: Int = clampedOrder / 2
self.butterworthQs = computeButterworthQs(order: clampedOrder)
self.biquadStages = [BiquadState](repeating: BiquadState(), count: numBiquads)
self.firstOrderState = clampedOrder % 2 == 1 ? FirstOrderState() : nil
self.scratch = makeSampleBuffer()
self.cachedBiquadCoeffs = [BiquadCoeffs](repeating: .zero, count: numBiquads)
self.vdspSetup = nil
let biquadDelayStateCount: Int = 2 * (numBiquads + 1)
self.vdspDelay = numBiquads > 0
? [Double](repeating: 0, count: biquadDelayStateCount)
: []
self.vdspCoeffQueue = SPSCQueue(capacity: butterworthCoeffQueueCapacity)
self.vdspRespQueue = SPSCQueue(capacity: butterworthRespQueueCapacity)
self.vdspKillQueue = SPSCQueue(capacity: butterworthKillQueueCapacity)
self.bgDoneSema = DispatchSemaphore(value: 0)
self.bgSleepSema = DispatchSemaphore(value: 0)
// Start background setup thread only when there are biquad sections (order >= 2).
if numBiquads > 0 {
let cq: SPSCQueue<BiquadCoeffPacket> = vdspCoeffQueue
let rq: SPSCQueue<OpaquePointer> = vdspRespQueue
let kq: SPSCQueue<OpaquePointer> = vdspKillQueue
let doneSema: DispatchSemaphore = bgDoneSema
let sleepSema: DispatchSemaphore = bgSleepSema
let pollInterval: TimeInterval = ButterworthSectionEngine.bgPollInterval
let t: Thread = Thread {
var shouldStop: Bool = false
while !shouldStop {
while let ptr: OpaquePointer = kq.dequeue() {
vDSP_biquad_DestroySetupD(ptr)
}
if let packet: BiquadCoeffPacket = cq.dequeue() {
packet.withUnsafeCoeffPtr { ptr in
if let setup: vDSP_biquad_SetupD = vDSP_biquad_CreateSetupD(
ptr, vDSP_Length(packet.numSections)
) {
if !rq.enqueue(setup) {
vDSP_biquad_DestroySetupD(setup)
}
}
}
}
// .success = woken early by deinit (stop signal); .timedOut = normal poll.
if sleepSema.wait(timeout: .now() + pollInterval) == .success { shouldStop = true }
}
// Drain queues on exit so deinit can safely claim ownership.
while let ptr: OpaquePointer = kq.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
while let ptr: OpaquePointer = rq.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
doneSema.signal()
}
t.name = threadName
t.qualityOfService = .userInteractive
vdspThread = t
t.start()
}
}
// MARK: - Deinit
deinit {
if vdspThread != nil {
bgSleepSema.signal() // wake thread from its 1ms sleep, stop signal
bgDoneSema.wait() // wait for thread to drain queues and exit
}
if let setup: OpaquePointer = vdspSetup {
vDSP_biquad_DestroySetupD(setup)
}
// Thread drained these on exit; drain again as safety (no-ops when already empty).
while let ptr: OpaquePointer = vdspRespQueue.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
while let ptr: OpaquePointer = vdspKillQueue.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
}
// MARK: - Process
/// Runs one block of the cascade, writing results into `output`.
///
/// This method is the RT-safe per-block entry point. It selects the correct
/// path (vDSP accelerated, scalar, or audio-rate interpolated) based on
/// `freqIsGenerator` and the current coefficient cache state.
///
/// - Parameters:
/// - input: Input sample block. Must have at least `count` elements.
/// - freqIsGenerator: `true` when `freq` was classified as a `Generator` at init time.
/// - scalarFreq: Scalar frequency value (used when `freqIsGenerator == false`).
/// - f0: Frequency at the start of this block (used when `freqIsGenerator == true`).
/// - fN: Frequency at the end of this block (used when `freqIsGenerator == true`).
/// - sr: Current sample rate in Hz.
/// - count: Number of samples to process.
/// - output: Destination buffer. Must have at least `count` writable elements.
func process(
input: [Double],
freqIsGenerator: Bool,
scalarFreq: Double,
f0: Double,
fN: Double,
sr: Double,
count: Int,
into output: inout [Double]
) {
let hasFO: Bool = firstOrderState != nil
let totalStages: Int = biquadStages.count + (hasFO ? 1 : 0)
guard totalStages > 0 else {
let n: Int = min(count, input.count)
input.withUnsafeBufferPointer { srcBuf in
output.withUnsafeMutableBufferPointer { dstBuf in
guard let srcBase: UnsafePointer<Double> = srcBuf.baseAddress,
let dstBase: UnsafeMutablePointer<Double> = dstBuf.baseAddress else { return }
if n > 0 { dstBase.update(from: srcBase, count: n) }
if n < count {
vDSP_vclrD(dstBase + n, 1, vDSP_Length(count - n))
}
}
}
return
}
if freqIsGenerator {
runAudioRate(input: input, f0: f0, fN: fN, sr: sr, N: totalStages,
count: count, into: &output)
} else {
if scalarFreq != prevFreq || sr != prevSampleRate {
recomputeScalarCoeffs(freq: scalarFreq, sr: sr)
prevFreq = scalarFreq; prevSampleRate = sr
if !biquadStages.isEmpty {
let packet: BiquadCoeffPacket = BiquadCoeffPacket(from: cachedBiquadCoeffs)
if !vdspCoeffQueue.enqueue(packet) {
// Queue full — reset sentinels so next block retries.
prevFreq = -1.0; prevSampleRate = -1.0
}
}
}
// Swap in any new setup the background thread prepared.
if let newSetup: OpaquePointer = vdspRespQueue.dequeue() {
if let old: OpaquePointer = vdspSetup {
if !vdspKillQueue.enqueue(old) {
// Kill queue full (capacity 32, bg thread drains every 1ms).
// Emergency same-thread destroy to prevent leak; violates RT-alloc rule
// but is unreachable under normal operation.
vDSP_biquad_DestroySetupD(old)
}
}
vdspSetup = newSetup
}
if let setup: OpaquePointer = vdspSetup {
runVDSP(input: input, count: count, setup: setup, into: &output)
} else {
runScalar(input: input, N: totalStages, count: count, into: &output)
}
}
}
// MARK: - Coefficient computation
private func recomputeScalarCoeffs(
freq: Double,
sr: Double
) {
if firstOrderState != nil {
cachedFO = foCoeffs(freq, sr)
}
for i: Int in 0..<biquadStages.count {
cachedBiquadCoeffs[i] = biquadCoeffsFunc(freq, butterworthQs[i], sr)
}
}
// MARK: - vDSP cascade path
/// Runs the biquad cascade via `vDSP_biquadD`. For odd orders, the first-order section
/// runs scalar first (into `scratch`); the biquad cascade then reads from `scratch`.
private func runVDSP(
input: [Double],
count: Int,
setup: OpaquePointer,
into output: inout [Double]
) {
if var fo: FirstOrderState = firstOrderState {
fo.processBlock(input: input,
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
into: &scratch, count: count)
firstOrderState = fo
scratch.withUnsafeBufferPointer { inBuf in
output.withUnsafeMutableBufferPointer { outBuf in
vdspDelay.withUnsafeMutableBufferPointer { delay in
guard let d: UnsafeMutablePointer<Double> = delay.baseAddress,
let i: UnsafePointer<Double> = inBuf.baseAddress,
let o: UnsafeMutablePointer<Double> = outBuf.baseAddress else { return }
vDSP_biquadD(setup, d, i, 1, o, 1, vDSP_Length(count))
}
}
}
} else {
input.withUnsafeBufferPointer { inBuf in
output.withUnsafeMutableBufferPointer { outBuf in
vdspDelay.withUnsafeMutableBufferPointer { delay in
guard let d: UnsafeMutablePointer<Double> = delay.baseAddress,
let i: UnsafePointer<Double> = inBuf.baseAddress,
let o: UnsafeMutablePointer<Double> = outBuf.baseAddress else { return }
vDSP_biquadD(setup, d, i, 1, o, 1, vDSP_Length(count))
}
}
}
}
}
// MARK: - Scalar cascade path
/// Buffer routing rule: stage `i` of `N` total writes to `output` when
/// `(N + i) % 2 == 1`, otherwise writes to `scratch`.
/// When `i > 0` and writes to `output`, it reads from `scratch` and vice versa.
private func runScalar(
input: [Double],
N: Int,
count: Int,
into output: inout [Double]
) {
var si: Int = 0
if var fo: FirstOrderState = firstOrderState {
let writesResult: Bool = (N + 0) % 2 == 1
if writesResult {
fo.processBlock(input: input,
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
into: &output, count: count)
} else {
fo.processBlock(input: input,
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
into: &scratch, count: count)
}
firstOrderState = fo
si = 1
}
for bi: Int in 0..<biquadStages.count {
let i: Int = si + bi
let writesResult: Bool = (N + i) % 2 == 1
let readsResult: Bool = i > 0 && (N + i) % 2 == 0
if writesResult {
if i == 0 {
biquadStages[bi].processBlock(input: input, coeffs: cachedBiquadCoeffs[bi],
into: &output, count: count)
} else {
biquadStages[bi].processBlock(input: scratch, coeffs: cachedBiquadCoeffs[bi],
into: &output, count: count)
}
} else {
if readsResult {
biquadStages[bi].processBlock(input: output, coeffs: cachedBiquadCoeffs[bi],
into: &scratch, count: count)
} else {
biquadStages[bi].processBlock(input: input, coeffs: cachedBiquadCoeffs[bi],
into: &scratch, count: count)
}
}
}
}
private func runAudioRate(
input: [Double],
f0: Double,
fN: Double,
sr: Double,
N: Int,
count: Int,
into output: inout [Double]
) {
var si: Int = 0
if var fo: FirstOrderState = firstOrderState {
let s: (b0: Double, b1: Double, na1: Double) = foCoeffs(f0, sr)
let e: (b0: Double, b1: Double, na1: Double) = foCoeffs(fN, sr)
let writesResult: Bool = (N + 0) % 2 == 1
if writesResult {
fo.processBlock(input: input,
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
into: &output, count: count)
} else {
fo.processBlock(input: input,
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
into: &scratch, count: count)
}
firstOrderState = fo
si = 1
}
for bi: Int in 0..<biquadStages.count {
let i: Int = si + bi
let writesResult: Bool = (N + i) % 2 == 1
let readsResult: Bool = i > 0 && (N + i) % 2 == 0
let startC: BiquadCoeffs = biquadCoeffsFunc(f0, butterworthQs[bi], sr)
let endC: BiquadCoeffs = biquadCoeffsFunc(fN, butterworthQs[bi], sr)
if writesResult {
if i == 0 {
biquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
into: &output, count: count)
} else {
biquadStages[bi].processBlock(input: scratch, startCoeffs: startC, endCoeffs: endC,
into: &output, count: count)
}
} else {
if readsResult {
biquadStages[bi].processBlock(input: output, startCoeffs: startC, endCoeffs: endC,
into: &scratch, count: count)
} else {
biquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
into: &scratch, count: count)
}
}
}
}
}
@@ -81,7 +81,7 @@ public final class CombFilter: GeneratorBase, AudioGenerator {
self.interpolation = interpolation
let maxSamples: Int = Int(ceil(maxDelay * sampleRate)) + 1
let bufSize: Int = Self.nextPowerOf2(max(maxSamples, 2))
let bufSize: Int = lyrebirdNextPowerOfTwo(max(maxSamples, 2))
self.buffer = [Double](repeating: 0, count: bufSize)
self.bufferMask = bufSize - 1
self.maxDelaySamples = maxSamples - 1
@@ -231,13 +231,6 @@ public final class CombFilter: GeneratorBase, AudioGenerator {
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
private static func nextPowerOf2(_ n: Int) -> Int {
guard n > 1 else { return 1 }
var r: Int = 1
while r < n { r <<= 1 }
return r
}
}
// MARK: - Catmull-Rom cubic interpolation (local copy, avoids cross-file dependency)
+28 -134
View File
@@ -4,8 +4,6 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Darwin
/// Butterworth Q (1/√2) — maximally flat magnitude response, no resonant peak. Default for SVF.
public let svfButterworthQ: Double = 0.7071067811865475 // 1.0 / sqrt(2.0)
@@ -153,74 +151,21 @@ public enum SVF {
let scalarQ: Double = qSamples == nil ? qInput.floatValue(graph: graph) : 0.0
let piOverSr: Double = Double.pi / sampleRate // π/sr; freq coeff = 2·sin(π·f/sr)
let minQDamping: Double = 0.0001 // prevents 1/q divide-by-zero
let fCoeffMax: Double = 1.0 // stability bound for Chamberlin SVF
// Pre-compute scalar coefficients when inputs are not generators.
let scalarF: Double
let scalarQ1: Double
if !freqIsGenerator && !qIsGenerator {
scalarF = min(fCoeffMax, max(0.0, 2.0 * Darwin.sin(piOverSr * scalarFreq)))
scalarQ1 = 1.0 / max(minQDamping, scalarQ)
} else {
scalarF = 0.0
scalarQ1 = 0.0
}
for i: Int in 0..<count {
let x: Double = ins[min(ins.count - 1, i)]
// Resolve per-sample freq/q when driven by generators.
let f: Double
let q1: Double
if freqIsGenerator || qIsGenerator {
let rawFreq: Double
let rawQ: Double
if let fs: [Double] = freqSamples {
rawFreq = fs[min(fs.count - 1, i)]
} else {
rawFreq = scalarFreq
}
if let qs: [Double] = qSamples {
rawQ = qs[min(qs.count - 1, i)]
} else {
rawQ = scalarQ
}
guard rawFreq > 0.0 else {
_result[0][i] = 0.0
_result[1][i] = 0.0
_result[2][i] = 0.0
_result[3][i] = 0.0
continue
}
f = min(fCoeffMax, 2.0 * Darwin.sin(piOverSr * rawFreq))
q1 = 1.0 / max(minQDamping, rawQ)
} else {
guard scalarFreq > 0.0 else {
_result[0][i] = 0.0
_result[1][i] = 0.0
_result[2][i] = 0.0
_result[3][i] = 0.0
continue
}
f = scalarF
q1 = scalarQ1
}
// Chamberlin SVF recurrence.
low = low + f * band
let high: Double = x - low - q1 * band
band = f * high + band
let notch: Double = high + low
low = denormalsToZero(low)
band = denormalsToZero(band)
_result[0][i] = low
_result[1][i] = high
_result[2][i] = band
_result[3][i] = notch
}
runSVFBlock(
ins: ins,
freqSamples: freqSamples,
qSamples: qSamples,
scalarFreq: scalarFreq,
scalarQ: scalarQ,
freqIsGenerator: freqIsGenerator,
qIsGenerator: qIsGenerator,
piOverSr: piOverSr,
low: &low,
band: &band,
result: &_result,
count: count
)
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
@@ -323,72 +268,21 @@ public enum SVF {
let scalarQ: Double = qSamples == nil ? qInput.floatValue(graph: graph) : 0.0
let piOverSr: Double = Double.pi / sampleRate
let minQDamping: Double = 0.0001
let fCoeffMax: Double = 1.0
let scalarF: Double
let scalarQ1: Double
if !freqIsGenerator && !qIsGenerator {
scalarF = min(fCoeffMax, max(0.0, 2.0 * Darwin.sin(piOverSr * scalarFreq)))
scalarQ1 = 1.0 / max(minQDamping, scalarQ)
} else {
scalarF = 0.0
scalarQ1 = 0.0
}
for i: Int in 0..<count {
let x: Double = ins[min(ins.count - 1, i)]
let f: Double
let q1: Double
if freqIsGenerator || qIsGenerator {
let rawFreq: Double
let rawQ: Double
if let fs: [Double] = freqSamples {
rawFreq = fs[min(fs.count - 1, i)]
} else {
rawFreq = scalarFreq
}
if let qs: [Double] = qSamples {
rawQ = qs[min(qs.count - 1, i)]
} else {
rawQ = scalarQ
}
guard rawFreq > 0.0 else {
_result[0][i] = 0.0
_result[1][i] = 0.0
_result[2][i] = 0.0
_result[3][i] = 0.0
continue
}
f = min(fCoeffMax, 2.0 * Darwin.sin(piOverSr * rawFreq))
q1 = 1.0 / max(minQDamping, rawQ)
} else {
guard scalarFreq > 0.0 else {
_result[0][i] = 0.0
_result[1][i] = 0.0
_result[2][i] = 0.0
_result[3][i] = 0.0
continue
}
f = scalarF
q1 = scalarQ1
}
// Chamberlin SVF recurrence.
low = low + f * band
let high: Double = x - low - q1 * band
band = f * high + band
let notch: Double = high + low
low = denormalsToZero(low)
band = denormalsToZero(band)
_result[0][i] = low
_result[1][i] = high
_result[2][i] = band
_result[3][i] = notch
}
runSVFBlock(
ins: ins,
freqSamples: freqSamples,
qSamples: qSamples,
scalarFreq: scalarFreq,
scalarQ: scalarQ,
freqIsGenerator: freqIsGenerator,
qIsGenerator: qIsGenerator,
piOverSr: piOverSr,
low: &low,
band: &band,
result: &_result,
count: count
)
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
@@ -0,0 +1,134 @@
// SVFHelpers.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Darwin
/// Minimum damping denominator — prevents the `1/q` divide-by-zero in the SVF.
let svfMinQDamping: Double = 0.0001
/// Stability bound for the Chamberlin SVF frequency coefficient `f`.
let svfFCoeffMax: Double = 1.0
/// Shared per-block body for `SVF.Audio` and `SVF.Control` — runs the Chamberlin
/// state-variable recurrence over `count` samples, writing the four outputs
/// (low / high / band / notch) into `result` rows 0…3.
///
/// `low` and `band` are the two IIR delay elements, advanced in place.
///
/// ## Frequency-coefficient interpolation
/// When `freq` is generator-driven the cutoff coefficient `f = 2·sin(π·freq/sr)`
/// is evaluated with `sin()` only at the first and last sample of the block and
/// linearly interpolated for the samples in between — the same coefficient-ramp
/// technique the RBJ biquads use. This replaces one transcendental call per
/// sample with two per block. The per-sample `freq > 0 → silence` guard is still
/// applied from the raw (un-interpolated) frequency so individual samples whose
/// cutoff drops to zero are zeroed exactly as before.
///
/// - Parameters:
/// - ins: Input signal block (last value repeats if shorter than `count`).
/// - freqSamples: Per-sample cutoff in Hz when `freq` is generator-driven, else `nil`.
/// - qSamples: Per-sample Q when `q` is generator-driven, else `nil`.
/// - scalarFreq: Cutoff in Hz used when `freq` is not generator-driven.
/// - scalarQ: Q used when `q` is not generator-driven.
/// - freqIsGenerator: Whether `freq` is generator-driven (classified at init).
/// - qIsGenerator: Whether `q` is generator-driven (classified at init).
/// - piOverSr: `π / sampleRate`, precomputed by the caller.
/// - low: Lowpass IIR accumulator, advanced in place.
/// - band: Bandpass IIR accumulator, advanced in place.
/// - result: Output buffer; rows 0…3 receive low / high / band / notch.
/// - count: Number of samples to process.
@inline(__always)
func runSVFBlock(
ins: [Double],
freqSamples: [Double]?,
qSamples: [Double]?,
scalarFreq: Double,
scalarQ: Double,
freqIsGenerator: Bool,
qIsGenerator: Bool,
piOverSr: Double,
low: inout Double,
band: inout Double,
result: inout [[Double]],
count: Int
) {
let minQDamping: Double = svfMinQDamping
let fCoeffMax: Double = svfFCoeffMax
// Scalar coefficients reused for whichever input is not generator-driven.
// `scalarFCoeff` is computed whenever `freq` is scalar — even if `q` is a
// generator — matching the original per-sample formula for that mixed case.
let scalarFCoeff: Double = freqIsGenerator
? 0.0
: min(fCoeffMax, max(0.0, 2.0 * Darwin.sin(piOverSr * scalarFreq)))
let scalarQ1: Double = qIsGenerator ? 0.0 : 1.0 / max(minQDamping, scalarQ)
// Block-boundary cutoff-coefficient ramp for the generator-driven case.
var fFirst: Double = 0.0
var fStep: Double = 0.0
if freqIsGenerator, let fs: [Double] = freqSamples, count > 0, !fs.isEmpty {
let firstRaw: Double = fs[0]
let lastRaw: Double = fs[min(fs.count - 1, count - 1)]
// `max(0.0, ...)` matches the scalar path: a freq above the sample rate makes
// `sin(π·freq/sr)` negative, which would destabilise the Chamberlin recurrence.
let cFirst: Double = firstRaw > 0.0 ? min(fCoeffMax, max(0.0, 2.0 * Darwin.sin(piOverSr * firstRaw))) : 0.0
let cLast: Double = lastRaw > 0.0 ? min(fCoeffMax, max(0.0, 2.0 * Darwin.sin(piOverSr * lastRaw))) : 0.0
fFirst = cFirst
fStep = count > 1 ? (cLast - cFirst) / Double(count - 1) : 0.0
}
for i: Int in 0..<count {
let x: Double = ins[min(ins.count - 1, i)]
let f: Double
let q1: Double
if freqIsGenerator || qIsGenerator {
let rawFreq: Double
if freqIsGenerator, let fs: [Double] = freqSamples {
rawFreq = fs[min(fs.count - 1, i)]
} else {
rawFreq = scalarFreq
}
guard rawFreq > 0.0 else {
result[0][i] = 0.0
result[1][i] = 0.0
result[2][i] = 0.0
result[3][i] = 0.0
continue
}
f = freqIsGenerator ? (fFirst + fStep * Double(i)) : scalarFCoeff
if qIsGenerator, let qs: [Double] = qSamples {
q1 = 1.0 / max(minQDamping, qs[min(qs.count - 1, i)])
} else {
q1 = scalarQ1
}
} else {
guard scalarFreq > 0.0 else {
result[0][i] = 0.0
result[1][i] = 0.0
result[2][i] = 0.0
result[3][i] = 0.0
continue
}
f = scalarFCoeff
q1 = scalarQ1
}
// Chamberlin SVF recurrence.
low = low + f * band
let high: Double = x - low - q1 * band
band = f * high + band
let notch: Double = high + low
low = denormalsToZero(low)
band = denormalsToZero(band)
result[0][i] = low
result[1][i] = high
result[2][i] = band
result[3][i] = notch
}
}
+1 -2
View File
@@ -44,8 +44,7 @@ public enum Abs {
) -> [[Double]] {
_checkCount(count)
let block: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
let n: Int = block.count
for i: Int in 0..<count { _result[0][i] = Swift.abs(i < n ? block[i] : 0.0) }
unaryVectorAbs(block, into: &_result, count: count)
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
@@ -78,6 +78,9 @@ public final class BinaryOpGenerator: GeneratorBase, AudioGenerator {
private let rhs: any ValidGeneratorInput
private let op: (Double, Double) -> Double
/// Arithmetic operator kind for vDSP dispatch, or `nil` for an arbitrary
/// closure (`.other`-style), which uses the per-sample `op` fallback.
private let kind: BinaryOpKind?
/// Output channel count — `max(lhsChannels, rhsChannels)`. Read by downstream
/// `BinaryOpGenerator` instances to compose multi-channel arithmetic.
@@ -95,16 +98,18 @@ public final class BinaryOpGenerator: GeneratorBase, AudioGenerator {
/// Channel count of `rhs` at init.
private let rhsChannels: Int
public init(
private init(
lhs: any ValidGeneratorInput,
rhs: any ValidGeneratorInput,
op: @escaping (Double, Double) -> Double
op: @escaping (Double, Double) -> Double,
kind: BinaryOpKind?
) {
let resolvedLhs: any ValidGeneratorInput = lhs._resolvedInput()
let resolvedRhs: any ValidGeneratorInput = rhs._resolvedInput()
self.lhs = resolvedLhs
self.rhs = resolvedRhs
self.op = op
self.kind = kind
// Classify inputs at construction time — types are fixed after init, so we only
// pay the is-any-Generator runtime cost once rather than once per RT block.
self.lhsIsLiteral = !resolvedLhs.needsInterpolation() && !(resolvedLhs is any Generator)
@@ -123,6 +128,34 @@ public final class BinaryOpGenerator: GeneratorBase, AudioGenerator {
super.init(channels: max(lhsCh, rhsCh))
}
/// Construct from an arbitrary closure. The per-sample closure path is used
/// (no vDSP dispatch) since the operation is not one of the four arithmetic kinds.
public convenience init(
lhs: any ValidGeneratorInput,
rhs: any ValidGeneratorInput,
op: @escaping (Double, Double) -> Double
) {
self.init(lhs: lhs, rhs: rhs, op: op, kind: nil)
}
/// Construct from one of the four arithmetic operator kinds — enables the
/// vDSP dispatch path. The matching scalar closure backs the fallback loop
/// (both-literals, short/unaligned rows).
convenience init(
lhs: any ValidGeneratorInput,
rhs: any ValidGeneratorInput,
kind: BinaryOpKind
) {
let opClosure: (Double, Double) -> Double
switch kind {
case .add: opClosure = (+)
case .subtract: opClosure = (-)
case .multiply: opClosure = (*)
case .divide: opClosure = (/)
}
self.init(lhs: lhs, rhs: rhs, op: opClosure, kind: kind)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
@@ -161,7 +194,11 @@ public final class BinaryOpGenerator: GeneratorBase, AudioGenerator {
continue
}
let ls: [Double] = lhsSamples[lhsRow]
for i: Int in 0..<count { _result[ch][i] = op(ls[i], rhsScalar) }
if let k: BinaryOpKind = kind, ls.count >= count {
binaryOpVectorScalarRHS(ls, rhsScalar, k, into: &_result[ch], count: count)
} else {
for i: Int in 0..<count { _result[ch][i] = op(ls[i], rhsScalar) }
}
} else if lhsIsLiteral {
// Scalar op generator (e.g. 0.5 * stereoGen)
guard rhsRow < rhsSamples.count else {
@@ -169,7 +206,11 @@ public final class BinaryOpGenerator: GeneratorBase, AudioGenerator {
continue
}
let rs: [Double] = rhsSamples[rhsRow]
for i: Int in 0..<count { _result[ch][i] = op(lhsScalar, rs[i]) }
if let k: BinaryOpKind = kind, rs.count >= count {
binaryOpScalarLHSVector(lhsScalar, rs, k, into: &_result[ch], count: count)
} else {
for i: Int in 0..<count { _result[ch][i] = op(lhsScalar, rs[i]) }
}
} else {
// Both generators
guard lhsRow < lhsSamples.count, rhsRow < rhsSamples.count else {
@@ -178,7 +219,11 @@ public final class BinaryOpGenerator: GeneratorBase, AudioGenerator {
}
let ls: [Double] = lhsSamples[lhsRow]
let rs: [Double] = rhsSamples[rhsRow]
for i: Int in 0..<count { _result[ch][i] = op(ls[i], rs[i]) }
if let k: BinaryOpKind = kind, ls.count >= count, rs.count >= count {
binaryOpVectorVector(ls, rs, k, into: &_result[ch], count: count)
} else {
for i: Int in 0..<count { _result[ch][i] = op(ls[i], rs[i]) }
}
}
}
return _result
@@ -202,44 +247,44 @@ public final class BinaryOpGenerator: GeneratorBase, AudioGenerator {
// Generator op Generator (tiebreaker — avoids ambiguity when both sides conform to Generator)
public func + <L: Generator, R: Generator>(lhs: L, rhs: R) -> BinaryOpGenerator {
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: +)
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .add)
}
public func - <L: Generator, R: Generator>(lhs: L, rhs: R) -> BinaryOpGenerator {
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: -)
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .subtract)
}
public func * <L: Generator, R: Generator>(lhs: L, rhs: R) -> BinaryOpGenerator {
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: *)
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .multiply)
}
public func / <L: Generator, R: Generator>(lhs: L, rhs: R) -> BinaryOpGenerator {
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: /)
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .divide)
}
// Generator op ValidGeneratorInput
public func + <L: Generator>(lhs: L, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: +)
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .add)
}
public func - <L: Generator>(lhs: L, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: -)
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .subtract)
}
public func * <L: Generator>(lhs: L, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: *)
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .multiply)
}
public func / <L: Generator>(lhs: L, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: /)
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .divide)
}
// ValidGeneratorInput op Generator
public func + <R: Generator>(lhs: any ValidGeneratorInput, rhs: R) -> BinaryOpGenerator {
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: +)
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .add)
}
public func - <R: Generator>(lhs: any ValidGeneratorInput, rhs: R) -> BinaryOpGenerator {
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: -)
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .subtract)
}
public func * <R: Generator>(lhs: any ValidGeneratorInput, rhs: R) -> BinaryOpGenerator {
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: *)
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .multiply)
}
public func / <R: Generator>(lhs: any ValidGeneratorInput, rhs: R) -> BinaryOpGenerator {
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: /)
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .divide)
}
// ValidGeneratorInput op ValidGeneratorInput — both existential.
@@ -247,14 +292,14 @@ public func / <R: Generator>(lhs: any ValidGeneratorInput, rhs: R) -> BinaryOpGe
// `freq: any ValidGeneratorInput`). Swift still picks the stdlib `Double op Double`
// overload for concrete Double expressions, so pure scalar arithmetic is unaffected.
public func + (lhs: any ValidGeneratorInput, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: +)
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .add)
}
public func - (lhs: any ValidGeneratorInput, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: -)
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .subtract)
}
public func * (lhs: any ValidGeneratorInput, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: *)
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .multiply)
}
public func / (lhs: any ValidGeneratorInput, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: /)
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .divide)
}
@@ -0,0 +1,117 @@
// BinaryOpVectorHelpers.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Accelerate
/// The four arithmetic operators `BinaryOpGenerator` can dispatch to vDSP. A
/// generator built from an arbitrary closure (not one of these four) carries no
/// kind and falls back to the per-sample closure loop.
enum BinaryOpKind {
case add
case subtract
case multiply
case divide
}
// Vectorised `BinaryOpGenerator` inner loops. Each dispatches one output row.
// All four operators map to correctly-rounded vDSP routines, so results are
// bit-identical to the scalar `lhs op rhs` loop — divide uses true division
// (vsdivD / svdivD / vdivD), never reciprocal-multiply, to preserve that.
//
// vDSP subtract/divide take operands in `C = A - B` / `C = A / B` order with the
// "B" (subtrahend / divisor) pointer FIRST — the calls below pass them reversed
// accordingly.
/// `out[i] = ls[i] <op> scalar`. Caller guarantees `ls.count >= count`.
@inline(__always)
func binaryOpVectorScalarRHS(
_ ls: [Double],
_ scalar: Double,
_ kind: BinaryOpKind,
into out: inout [Double],
count: Int
) {
var s: Double = scalar
ls.withUnsafeBufferPointer { lp in
out.withUnsafeMutableBufferPointer { op in
guard let a: UnsafePointer<Double> = lp.baseAddress,
let c: UnsafeMutablePointer<Double> = op.baseAddress else { return }
let n: vDSP_Length = vDSP_Length(count)
switch kind {
case .add:
vDSP_vsaddD(a, 1, &s, c, 1, n)
case .multiply:
vDSP_vsmulD(a, 1, &s, c, 1, n)
case .subtract:
var neg: Double = -scalar // ls - s == ls + (-s), bit-exact
vDSP_vsaddD(a, 1, &neg, c, 1, n)
case .divide:
vDSP_vsdivD(a, 1, &s, c, 1, n) // C[i] = ls[i] / s (true division)
}
}
}
}
/// `out[i] = scalar <op> rs[i]`. Caller guarantees `rs.count >= count`.
@inline(__always)
func binaryOpScalarLHSVector(
_ scalar: Double,
_ rs: [Double],
_ kind: BinaryOpKind,
into out: inout [Double],
count: Int
) {
var s: Double = scalar
rs.withUnsafeBufferPointer { rp in
out.withUnsafeMutableBufferPointer { op in
guard let b: UnsafePointer<Double> = rp.baseAddress,
let c: UnsafeMutablePointer<Double> = op.baseAddress else { return }
let n: vDSP_Length = vDSP_Length(count)
switch kind {
case .add:
vDSP_vsaddD(b, 1, &s, c, 1, n) // s + rs == rs + s
case .multiply:
vDSP_vsmulD(b, 1, &s, c, 1, n) // commutative
case .subtract:
var negOne: Double = -1.0 // rs*(-1) + s == s - rs, bit-exact
vDSP_vsmsaD(b, 1, &negOne, &s, c, 1, n)
case .divide:
vDSP_svdivD(&s, b, 1, c, 1, n) // C[i] = s / rs[i] (true division)
}
}
}
}
/// `out[i] = ls[i] <op> rs[i]`. Caller guarantees both counts `>= count`.
@inline(__always)
func binaryOpVectorVector(
_ ls: [Double],
_ rs: [Double],
_ kind: BinaryOpKind,
into out: inout [Double],
count: Int
) {
ls.withUnsafeBufferPointer { lp in
rs.withUnsafeBufferPointer { rp in
out.withUnsafeMutableBufferPointer { op in
guard let a: UnsafePointer<Double> = lp.baseAddress,
let b: UnsafePointer<Double> = rp.baseAddress,
let c: UnsafeMutablePointer<Double> = op.baseAddress else { return }
let n: vDSP_Length = vDSP_Length(count)
switch kind {
case .add:
vDSP_vaddD(a, 1, b, 1, c, 1, n)
case .multiply:
vDSP_vmulD(a, 1, b, 1, c, 1, n)
case .subtract:
vDSP_vsubD(b, 1, a, 1, c, 1, n) // C = A - B = ls - rs (B first)
case .divide:
vDSP_vdivD(b, 1, a, 1, c, 1, n) // C = A / B = ls / rs (B first)
}
}
}
}
}
+1 -2
View File
@@ -46,8 +46,7 @@ public enum Ceil {
) -> [[Double]] {
_checkCount(count)
let block: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
let n: Int = block.count
for i: Int in 0..<count { _result[0][i] = Foundation.ceil(i < n ? block[i] : 0.0) }
unaryVectorCeil(block, into: &_result, count: count)
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
+1 -2
View File
@@ -47,8 +47,7 @@ public enum Cos {
) -> [[Double]] {
_checkCount(count)
let block: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
let n: Int = block.count
for i: Int in 0..<count { _result[0][i] = Foundation.cos(i < n ? block[i] : 0.0) }
unaryVectorCos(block, into: &_result, count: count)
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
+1 -2
View File
@@ -46,8 +46,7 @@ public enum Exp {
) -> [[Double]] {
_checkCount(count)
let block: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
let n: Int = block.count
for i: Int in 0..<count { _result[0][i] = Foundation.exp(i < n ? block[i] : 0.0) }
unaryVectorExp(block, into: &_result, count: count)
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
+1 -2
View File
@@ -46,8 +46,7 @@ public enum Floor {
) -> [[Double]] {
_checkCount(count)
let block: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
let n: Int = block.count
for i: Int in 0..<count { _result[0][i] = Foundation.floor(i < n ? block[i] : 0.0) }
unaryVectorFloor(block, into: &_result, count: count)
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
+20 -3
View File
@@ -4,6 +4,8 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Accelerate
// MARK: - LinLin
/// Maps signal from [inLo, inHi] linearly to [outLo, outHi].
@@ -88,10 +90,25 @@ public enum LinLin {
let outLo: Double = outLoInput.floatValue(graph: graph)
let outRange: Double = outHiInput.floatValue(graph: graph) - outLo
// inRange == 0 produces NaN/±Inf per IEEE 754 — intentional.
// The map is affine in x: f(x) = a·x + b with a = outRange/inRange,
// b = outLo − inLo·a. The full-block path applies it as one fused
// multiply-add (vDSP_vsmsaD).
let n: Int = block.count
for i: Int in 0..<count {
let x: Double = i < n ? block[i] : 0.0
_result[0][i] = outLo + (x - inLo) / inRange * outRange
if n >= count {
var a: Double = outRange / inRange
var b: Double = outLo - inLo * a
block.withUnsafeBufferPointer { src in
_result[0].withUnsafeMutableBufferPointer { dst in
guard let s: UnsafePointer<Double> = src.baseAddress,
let d: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
vDSP_vsmsaD(s, 1, &a, &b, d, 1, vDSP_Length(count))
}
}
} else {
for i: Int in 0..<count {
let x: Double = i < n ? block[i] : 0.0
_result[0][i] = outLo + (x - inLo) / inRange * outRange
}
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
+1 -2
View File
@@ -46,8 +46,7 @@ public enum Log {
) -> [[Double]] {
_checkCount(count)
let block: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
let n: Int = block.count
for i: Int in 0..<count { _result[0][i] = Foundation.log(i < n ? block[i] : 1.0) }
unaryVectorLog(block, into: &_result, count: count)
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
+1 -2
View File
@@ -47,8 +47,7 @@ public enum Sin {
) -> [[Double]] {
_checkCount(count)
let block: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
let n: Int = block.count
for i: Int in 0..<count { _result[0][i] = Foundation.sin(i < n ? block[i] : 0.0) }
unaryVectorSin(block, into: &_result, count: count)
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
+1 -2
View File
@@ -46,8 +46,7 @@ public enum Sqrt {
) -> [[Double]] {
_checkCount(count)
let block: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
let n: Int = block.count
for i: Int in 0..<count { _result[0][i] = Foundation.sqrt(i < n ? block[i] : 0.0) }
unaryVectorSqrt(block, into: &_result, count: count)
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
@@ -0,0 +1,114 @@
// UnaryMathVectorHelpers.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Accelerate
// Vectorised inner loops for the unary math waveshapers (Sin / Cos / Exp / Log /
// Sqrt / Floor / Ceil / Abs). Each `.Audio._computeSamples` resolves its input
// block, then calls the matching `unaryVector*` wrapper instead of a per-sample
// scalar `Foundation.*` loop.
//
// Split-path strategy: when the upstream block is full-length (`n >= count`,
// the normal case at any block size) the whole block is transformed in one
// Accelerate call. Only a short upstream block (`n < count`) falls back to the
// staged path, which zero/pad-extends into the output row and transforms it in
// place — so the vForce/vDSP routine still runs, just over a padded buffer.
/// Core split-path driver. `transform(dst, src, n)` must transform `src[0..<n]`
/// into `dst[0..<n]` (in-place safe — the fallback passes `dst` as both).
///
/// - Parameters:
/// - block: Resolved input samples (may be shorter than `count`).
/// - pad: Value substituted for samples past the end of a short input block.
/// - result: Output buffer; row 0 receives the transformed samples.
/// - count: Number of samples to produce.
/// - transform: Vector transform applied to `count` samples (src → dst).
@inline(__always)
func applyUnaryVectorTransform(
_ block: [Double],
pad: Double,
into result: inout [[Double]],
count: Int,
_ transform: (_ dst: UnsafeMutablePointer<Double>, _ src: UnsafePointer<Double>, _ n: Int) -> Void
) {
let n: Int = block.count
result[0].withUnsafeMutableBufferPointer { dst in
guard let d: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
if n >= count {
block.withUnsafeBufferPointer { src in
guard let s: UnsafePointer<Double> = src.baseAddress else { return }
transform(d, s, count)
}
} else {
for i: Int in 0..<count { d[i] = i < n ? block[i] : pad }
transform(d, UnsafePointer(d), count)
}
}
}
@inline(__always)
func unaryVectorSin(_ block: [Double], into result: inout [[Double]], count: Int) {
applyUnaryVectorTransform(block, pad: 0.0, into: &result, count: count) { d, s, c in
var len: Int32 = Int32(c)
vvsin(d, s, &len)
}
}
@inline(__always)
func unaryVectorCos(_ block: [Double], into result: inout [[Double]], count: Int) {
applyUnaryVectorTransform(block, pad: 0.0, into: &result, count: count) { d, s, c in
var len: Int32 = Int32(c)
vvcos(d, s, &len)
}
}
@inline(__always)
func unaryVectorExp(_ block: [Double], into result: inout [[Double]], count: Int) {
applyUnaryVectorTransform(block, pad: 0.0, into: &result, count: count) { d, s, c in
var len: Int32 = Int32(c)
vvexp(d, s, &len)
}
}
@inline(__always)
func unaryVectorLog(_ block: [Double], into result: inout [[Double]], count: Int) {
// Pad with 1.0 so padded samples map to log(1) = 0, matching the scalar fallback.
applyUnaryVectorTransform(block, pad: 1.0, into: &result, count: count) { d, s, c in
var len: Int32 = Int32(c)
vvlog(d, s, &len)
}
}
@inline(__always)
func unaryVectorSqrt(_ block: [Double], into result: inout [[Double]], count: Int) {
applyUnaryVectorTransform(block, pad: 0.0, into: &result, count: count) { d, s, c in
var len: Int32 = Int32(c)
vvsqrt(d, s, &len)
}
}
@inline(__always)
func unaryVectorFloor(_ block: [Double], into result: inout [[Double]], count: Int) {
applyUnaryVectorTransform(block, pad: 0.0, into: &result, count: count) { d, s, c in
var len: Int32 = Int32(c)
vvfloor(d, s, &len)
}
}
@inline(__always)
func unaryVectorCeil(_ block: [Double], into result: inout [[Double]], count: Int) {
applyUnaryVectorTransform(block, pad: 0.0, into: &result, count: count) { d, s, c in
var len: Int32 = Int32(c)
vvceil(d, s, &len)
}
}
@inline(__always)
func unaryVectorAbs(_ block: [Double], into result: inout [[Double]], count: Int) {
applyUnaryVectorTransform(block, pad: 0.0, into: &result, count: count) { d, s, c in
vDSP_vabsD(s, 1, d, 1, vDSP_Length(c))
}
}
@@ -81,6 +81,13 @@ public enum Chorus {
// MARK: Delay line and LFO state
private var _delayLine: [Double]
/// `_delayLine.count - 1`. The buffer is sized to a power of two so the
/// circular index wrap is `& _delayMask` rather than `% count`.
private let _delayMask: Int
/// Maximum fractional delay in samples — derived from `maxDelayTime`, not
/// the (power-of-two-rounded) buffer length, so the audible delay range is
/// unchanged by the buffer over-allocation.
private let _maxDelayFrac: Double
private var _writePos: Int = 0
/// Phase for tap 0 (channel 0 / left). Normalised [0, 1).
private var _lfoPhase0: Double = 0.0
@@ -146,7 +153,12 @@ public enum Chorus {
_sampleRate = sampleRate
_sampleRateRecip = 1.0 / sampleRate
_delayLine = [Double](repeating: 0, count: delayLineLength)
// Semantic max delay comes from delayLineLength; the backing buffer is
// rounded up to a power of two so the index wrap is a single AND.
_maxDelayFrac = Double(delayLineLength - 2)
let bufferLength: Int = lyrebirdNextPowerOfTwo(delayLineLength)
_delayMask = bufferLength - 1
_delayLine = [Double](repeating: 0, count: bufferLength)
_mulAdd = MulAddSpec(mul: mul, add: add)
// Two output channels: left (tap 0) and right (tap 1).
super.init(channels: 2)
@@ -156,62 +168,26 @@ public enum Chorus {
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count)
let delayLineCount: Int = _delayLine.count
let wrapOffset: Int = delayLineCount * 2
let maxDelayFrac: Double = Double(delayLineCount - 2)
let delayMask: Int = _delayMask
let wrapOffset: Int = _delayLine.count // multiple of (mask + 1): vanishes under & mask
let maxDelayFrac: Double = _maxDelayFrac
// Fetch input blocks.
let inputSamples: [Double]?
let scalarInput: Double
if _inputIsGenerator {
inputSamples = _inputSource.calculatedSamples(graph: graph, count: count).first
scalarInput = 0
} else {
inputSamples = nil
scalarInput = _inputSource.floatValue(graph: graph)
}
let delayTimeSamples: [Double]?
let scalarDelayTime: Double
if _delayTimeIsGenerator {
delayTimeSamples = _delayTimeSource.calculatedSamples(graph: graph, count: count).first
scalarDelayTime = 0
} else {
delayTimeSamples = nil
scalarDelayTime = _delayTimeSource.floatValue(graph: graph)
}
let depthSamples: [Double]?
let scalarDepth: Double
if _depthIsGenerator {
depthSamples = _depthSource.calculatedSamples(graph: graph, count: count).first
scalarDepth = 0
} else {
depthSamples = nil
scalarDepth = _depthSource.floatValue(graph: graph)
}
let rateSamples: [Double]?
let scalarRate: Double
if _rateIsGenerator {
rateSamples = _rateSource.calculatedSamples(graph: graph, count: count).first
scalarRate = 0
} else {
rateSamples = nil
scalarRate = _rateSource.floatValue(graph: graph)
}
let mixSamples: [Double]?
let scalarMix: Double
if _mixIsGenerator {
mixSamples = _mixSource.calculatedSamples(graph: graph, count: count).first
scalarMix = 0
} else {
mixSamples = nil
scalarMix = _mixSource.floatValue(graph: graph)
}
let twoPi: Double = 2.0 * Double.pi
let (inputSamples, scalarInput) = resolveGeneratorOrScalar(
_inputSource, isGenerator: _inputIsGenerator, graph: graph, count: count
)
let (delayTimeSamples, scalarDelayTime) = resolveGeneratorOrScalar(
_delayTimeSource, isGenerator: _delayTimeIsGenerator, graph: graph, count: count
)
let (depthSamples, scalarDepth) = resolveGeneratorOrScalar(
_depthSource, isGenerator: _depthIsGenerator, graph: graph, count: count
)
let (rateSamples, scalarRate) = resolveGeneratorOrScalar(
_rateSource, isGenerator: _rateIsGenerator, graph: graph, count: count
)
let (mixSamples, scalarMix) = resolveGeneratorOrScalar(
_mixSource, isGenerator: _mixIsGenerator, graph: graph, count: count
)
for i: Int in 0..<count {
let dry: Double
@@ -263,24 +239,24 @@ public enum Chorus {
let baseDelaySamples: Double = baseDelaySec * _sampleRate
// --- Tap 0 (left channel, LFO phase 0) ---
let lfo0: Double = sin(_lfoPhase0 * twoPi)
let lfo0: Double = sin(_lfoPhase0 * lyrebirdTwoPi)
let delay0: Double = max(1.0, min(maxDelayFrac, baseDelaySamples + clampedDepth * baseDelaySamples * lfo0))
let iDelay0: Int = Int(delay0)
let frac0: Double = delay0 - Double(iDelay0)
let pos0a: Int = (_writePos - iDelay0 + wrapOffset) % delayLineCount
let pos0b: Int = (_writePos - iDelay0 - 1 + wrapOffset) % delayLineCount
let pos0a: Int = (_writePos - iDelay0 + wrapOffset) & delayMask
let pos0b: Int = (_writePos - iDelay0 - 1 + wrapOffset) & delayMask
let tap0: Double = _delayLine[pos0a] * (1.0 - frac0) + _delayLine[pos0b] * frac0
// --- Tap 1 (right channel, LFO phase π) ---
let lfo1: Double = sin(_lfoPhase1 * twoPi)
let lfo1: Double = sin(_lfoPhase1 * lyrebirdTwoPi)
let delay1: Double = max(1.0, min(maxDelayFrac, baseDelaySamples + clampedDepth * baseDelaySamples * lfo1))
let iDelay1: Int = Int(delay1)
let frac1: Double = delay1 - Double(iDelay1)
let pos1a: Int = (_writePos - iDelay1 + wrapOffset) % delayLineCount
let pos1b: Int = (_writePos - iDelay1 - 1 + wrapOffset) % delayLineCount
let pos1a: Int = (_writePos - iDelay1 + wrapOffset) & delayMask
let pos1b: Int = (_writePos - iDelay1 - 1 + wrapOffset) & delayMask
let tap1: Double = _delayLine[pos1a] * (1.0 - frac1) + _delayLine[pos1b] * frac1
_writePos = (_writePos + 1) % delayLineCount
_writePos = (_writePos + 1) & delayMask
let clampedMix: Double = max(0.0, min(1.0, mix))
let dryGain: Double = 1.0 - clampedMix
@@ -91,6 +91,12 @@ public enum Flanger {
// MARK: Delay line state
private var _delayLine: [Double]
/// `_delayLine.count - 1`. Buffer is power-of-two sized so the circular
/// index wrap is `& _delayMask` rather than `% count`.
private let _delayMask: Int
/// Maximum fractional delay in samples — from `maxDelayTime`, not the
/// power-of-two buffer length, so the audible delay range is unchanged.
private let _maxDelayFrac: Double
private var _writePos: Int = 0
private var _lfoPhase: Double = 0.0
@@ -157,7 +163,12 @@ public enum Flanger {
_sampleRate = sampleRate
_sampleRateRecip = 1.0 / sampleRate
_delayLine = [Double](repeating: 0, count: delayLineLength)
// Semantic max delay from delayLineLength; backing buffer rounded up
// to a power of two so the index wrap is a single AND.
_maxDelayFrac = Double(delayLineLength - 2)
let bufferLength: Int = lyrebirdNextPowerOfTwo(delayLineLength)
_delayMask = bufferLength - 1
_delayLine = [Double](repeating: 0, count: bufferLength)
_mulAdd = MulAddSpec(mul: mul, add: add)
super.init()
@@ -167,73 +178,32 @@ public enum Flanger {
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count)
let delayLineCount: Int = _delayLine.count
// Wrap offset large enough to keep subtracted positions positive.
let wrapOffset: Int = delayLineCount * 2
let delayMask: Int = _delayMask
// Wrap offset large enough to keep subtracted positions positive;
// a multiple of (mask + 1), so it vanishes under & mask.
let wrapOffset: Int = _delayLine.count
// Fetch input blocks.
let inputSamples: [Double]?
let scalarInput: Double
if _inputIsGenerator {
inputSamples = _inputSource.calculatedSamples(graph: graph, count: count).first
scalarInput = 0
} else {
inputSamples = nil
scalarInput = _inputSource.floatValue(graph: graph)
}
let (inputSamples, scalarInput) = resolveGeneratorOrScalar(
_inputSource, isGenerator: _inputIsGenerator, graph: graph, count: count
)
let (delayTimeSamples, scalarDelayTime) = resolveGeneratorOrScalar(
_delayTimeSource, isGenerator: _delayTimeIsGenerator, graph: graph, count: count
)
let (depthSamples, scalarDepth) = resolveGeneratorOrScalar(
_depthSource, isGenerator: _depthIsGenerator, graph: graph, count: count
)
let (rateSamples, scalarRate) = resolveGeneratorOrScalar(
_rateSource, isGenerator: _rateIsGenerator, graph: graph, count: count
)
let (feedbackSamples, scalarFeedback) = resolveGeneratorOrScalar(
_feedbackSource, isGenerator: _feedbackIsGenerator, graph: graph, count: count
)
let (mixSamples, scalarMix) = resolveGeneratorOrScalar(
_mixSource, isGenerator: _mixIsGenerator, graph: graph, count: count
)
let delayTimeSamples: [Double]?
let scalarDelayTime: Double
if _delayTimeIsGenerator {
delayTimeSamples = _delayTimeSource.calculatedSamples(graph: graph, count: count).first
scalarDelayTime = 0
} else {
delayTimeSamples = nil
scalarDelayTime = _delayTimeSource.floatValue(graph: graph)
}
let depthSamples: [Double]?
let scalarDepth: Double
if _depthIsGenerator {
depthSamples = _depthSource.calculatedSamples(graph: graph, count: count).first
scalarDepth = 0
} else {
depthSamples = nil
scalarDepth = _depthSource.floatValue(graph: graph)
}
let rateSamples: [Double]?
let scalarRate: Double
if _rateIsGenerator {
rateSamples = _rateSource.calculatedSamples(graph: graph, count: count).first
scalarRate = 0
} else {
rateSamples = nil
scalarRate = _rateSource.floatValue(graph: graph)
}
let feedbackSamples: [Double]?
let scalarFeedback: Double
if _feedbackIsGenerator {
feedbackSamples = _feedbackSource.calculatedSamples(graph: graph, count: count).first
scalarFeedback = 0
} else {
feedbackSamples = nil
scalarFeedback = _feedbackSource.floatValue(graph: graph)
}
let mixSamples: [Double]?
let scalarMix: Double
if _mixIsGenerator {
mixSamples = _mixSource.calculatedSamples(graph: graph, count: count).first
scalarMix = 0
} else {
mixSamples = nil
scalarMix = _mixSource.floatValue(graph: graph)
}
let twoPi: Double = 2.0 * Double.pi
let maxDelayFrac: Double = Double(delayLineCount - 2)
let maxDelayFrac: Double = _maxDelayFrac
for i: Int in 0..<count {
let dry: Double
@@ -283,7 +253,7 @@ public enum Flanger {
if _lfoPhase >= 1.0 { _lfoPhase -= 1.0 }
// Compute modulated delay in samples (LFO sine output in [-1, 1]).
let lfoOut: Double = sin(_lfoPhase * twoPi)
let lfoOut: Double = sin(_lfoPhase * lyrebirdTwoPi)
let clampedDepth: Double = max(0.0, min(1.0, depth))
let modDelay: Double = baseDelay * _sampleRate * (1.0 + clampedDepth * lfoOut)
let clampedDelay: Double = max(1.0, min(maxDelayFrac, modDelay))
@@ -293,8 +263,8 @@ public enum Flanger {
let frac: Double = clampedDelay - Double(iDelay)
// Circular read positions.
let pos0: Int = (_writePos - iDelay + wrapOffset) % delayLineCount
let pos1: Int = (_writePos - iDelay - 1 + wrapOffset) % delayLineCount
let pos0: Int = (_writePos - iDelay + wrapOffset) & delayMask
let pos1: Int = (_writePos - iDelay - 1 + wrapOffset) & delayMask
let delayed: Double = _delayLine[pos0] * (1.0 - frac) + _delayLine[pos1] * frac
// Write feedback-enhanced input into delay line.
@@ -302,7 +272,7 @@ public enum Flanger {
let clampedFeedback: Double = max(0.0, min(maxFeedbackGain, feedback))
_delayLine[_writePos] = denormalsToZero(dry + clampedFeedback * delayed)
_writePos = (_writePos + 1) % delayLineCount
_writePos = (_writePos + 1) & delayMask
// Dry/wet mix.
let clampedMix: Double = max(0.0, min(1.0, mix))
@@ -182,67 +182,25 @@ public enum Phaser {
_checkCount(count)
// Fetch input blocks.
let inputSamples: [Double]?
let scalarInput: Double
if _inputIsGenerator {
inputSamples = _inputSource.calculatedSamples(graph: graph, count: count).first
scalarInput = 0
} else {
inputSamples = nil
scalarInput = _inputSource.floatValue(graph: graph)
}
let (inputSamples, scalarInput) = resolveGeneratorOrScalar(
_inputSource, isGenerator: _inputIsGenerator, graph: graph, count: count
)
let (rateSamples, scalarRate) = resolveGeneratorOrScalar(
_rateSource, isGenerator: _rateIsGenerator, graph: graph, count: count
)
let (depthSamples, scalarDepth) = resolveGeneratorOrScalar(
_depthSource, isGenerator: _depthIsGenerator, graph: graph, count: count
)
let (centerFreqSamples, scalarCenterFreq) = resolveGeneratorOrScalar(
_centerFreqSource, isGenerator: _centerFreqIsGenerator, graph: graph, count: count
)
let (feedbackSamples, scalarFeedback) = resolveGeneratorOrScalar(
_feedbackSource, isGenerator: _feedbackIsGenerator, graph: graph, count: count
)
let (mixSamples, scalarMix) = resolveGeneratorOrScalar(
_mixSource, isGenerator: _mixIsGenerator, graph: graph, count: count
)
let rateSamples: [Double]?
let scalarRate: Double
if _rateIsGenerator {
rateSamples = _rateSource.calculatedSamples(graph: graph, count: count).first
scalarRate = 0
} else {
rateSamples = nil
scalarRate = _rateSource.floatValue(graph: graph)
}
let depthSamples: [Double]?
let scalarDepth: Double
if _depthIsGenerator {
depthSamples = _depthSource.calculatedSamples(graph: graph, count: count).first
scalarDepth = 0
} else {
depthSamples = nil
scalarDepth = _depthSource.floatValue(graph: graph)
}
let centerFreqSamples: [Double]?
let scalarCenterFreq: Double
if _centerFreqIsGenerator {
centerFreqSamples = _centerFreqSource.calculatedSamples(graph: graph, count: count).first
scalarCenterFreq = 0
} else {
centerFreqSamples = nil
scalarCenterFreq = _centerFreqSource.floatValue(graph: graph)
}
let feedbackSamples: [Double]?
let scalarFeedback: Double
if _feedbackIsGenerator {
feedbackSamples = _feedbackSource.calculatedSamples(graph: graph, count: count).first
scalarFeedback = 0
} else {
feedbackSamples = nil
scalarFeedback = _feedbackSource.floatValue(graph: graph)
}
let mixSamples: [Double]?
let scalarMix: Double
if _mixIsGenerator {
mixSamples = _mixSource.calculatedSamples(graph: graph, count: count).first
scalarMix = 0
} else {
mixSamples = nil
scalarMix = _mixSource.floatValue(graph: graph)
}
let twoPi: Double = 2.0 * Double.pi
let piOverSr: Double = Double.pi * _sampleRateRecip
let minFreq: Double = 1.0
@@ -295,7 +253,7 @@ public enum Phaser {
// Compute sweep frequency from LFO.
let clampedDepth: Double = max(0.0, min(1.0, depth))
let lfoOut: Double = sin(_lfoPhase * twoPi)
let lfoOut: Double = sin(_lfoPhase * lyrebirdTwoPi)
let sweepFreq: Double = max(minFreq, min(_nyquistLimit, centerFreq * (1.0 + clampedDepth * lfoOut)))
// Compute first-order all-pass coefficient.
@@ -202,7 +202,7 @@ public enum LFDutyCycle {
let dt: Double = freq / sampleRate
_phase += dt * countFloat
normalizeLFPhase(&_phase)
normalizeOscPhase(&_phase)
let target: Double = _phase < duty ? 1.0 : -1.0
@@ -13,13 +13,5 @@ let lfHalfPhase: Double = 0.5
/// Amplitude spans 2 over a half period (0.5), so slope = 2 / 0.5 = 4.
let lfTriangleSlope: Double = 4.0
/// Normalises `phase` to `[0, 1)` after a block-sized increment.
/// Fast path handles the common case; slow path handles extreme freq × count.
@inline(__always)
func normalizeLFPhase(_ phase: inout Double) {
if phase >= 1.0 { phase -= 1.0 }
if phase >= 1.0 || phase < 0 {
phase = phase.truncatingRemainder(dividingBy: 1.0)
if phase < 0 { phase += 1.0 }
}
}
// Phase normalisation is provided by `normalizeOscPhase` in OscBandLimitedHelpers.swift,
// shared by all LF and band-limited oscillators.
@@ -149,7 +149,7 @@ public enum LFSawtooth {
let dt: Double = freq / sampleRate
_phase += dt * countFloat
normalizeLFPhase(&_phase)
normalizeOscPhase(&_phase)
let target: Double = 2.0 * _phase - 1.0
@@ -149,7 +149,7 @@ public enum LFSquare {
let dt: Double = freq / sampleRate
_phase += dt * countFloat
normalizeLFPhase(&_phase)
normalizeOscPhase(&_phase)
let target: Double = _phase < lfHalfPhase ? 1.0 : -1.0
@@ -156,7 +156,7 @@ public enum LFTriangle {
let dt: Double = freq / sampleRate
_phase += dt * countFloat
normalizeLFPhase(&_phase)
normalizeOscPhase(&_phase)
let triangleDescendingIntercept: Double = lfTriangleSlope - 1.0
let target: Double
@@ -70,9 +70,12 @@ let oscBLHalfPhase: Double = 0.5
let oscBLTriangleSlope: Double = 4.0
/// Normalises `phase` to `[0, 1)` after a block-sized increment.
/// Fast path handles the common case; slow path (truncatingRemainder) handles extreme freq × count.
///
/// Fast path subtracts 1.0 for the common single-wrap case; slow path uses
/// `truncatingRemainder` to handle extreme `freq × count` values. Shared by
/// all LF and band-limited oscillators.
@inline(__always)
func normalizeBLPhase(_ phase: inout Double) {
func normalizeOscPhase(_ phase: inout Double) {
if phase >= 1.0 { phase -= 1.0 }
if phase >= 1.0 || phase < 0 {
phase = phase.truncatingRemainder(dividingBy: 1.0)
@@ -216,7 +216,7 @@ public enum OscDutyCycle {
let dt: Double = freq / sampleRate
_phase += dt * countFloat
normalizeBLPhase(&_phase)
normalizeOscPhase(&_phase)
let target: Double = _phase < duty ? 1.0 : -1.0
@@ -157,7 +157,7 @@ public enum OscSawtooth {
let dt: Double = freq / sampleRate
_phase += dt * countFloat
normalizeBLPhase(&_phase)
normalizeOscPhase(&_phase)
let target: Double = 2.0 * _phase - 1.0
@@ -158,7 +158,7 @@ public enum OscSquare {
let dt: Double = freq / sampleRate
_phase += dt * countFloat
normalizeBLPhase(&_phase)
normalizeOscPhase(&_phase)
let target: Double = _phase < oscBLHalfPhase ? 1.0 : -1.0
@@ -169,7 +169,7 @@ public enum OscTriangle {
let dt: Double = freq / sampleRate
_phase += dt * countFloat
normalizeBLPhase(&_phase)
normalizeOscPhase(&_phase)
let triangleDescendingIntercept: Double = oscBLTriangleSlope - 1.0
let target: Double
@@ -387,7 +387,6 @@ public enum ScannedSynthesizer {
private func _applyInitialDisplacement(_ shape: ScannedSynthesizerShape) {
let n: Int = _massCount
let nFloat: Double = _massCountFloat
let twoPi: Double = 2.0 * Double.pi
switch shape {
case .zeros:
// Already zero from init.
@@ -395,7 +394,7 @@ public enum ScannedSynthesizer {
case .sine:
for i: Int in 0..<n {
_positions[i] = sin(twoPi * Double(i) / nFloat)
_positions[i] = sin(lyrebirdTwoPi * Double(i) / nFloat)
}
case .impulse:
@@ -144,10 +144,9 @@ public enum Jitter {
// One-pole smoothing coefficient: exp(-2π × speed × dt)
// dt = count / sampleRate seconds (one audio block).
let twoPi: Double = 2.0 * Double.pi
let dt: Double = Double(count) / sampleRate
let safeSpeed: Double = max(0.0, speed)
let coeff: Double = safeSpeed > 0.0 ? exp(-twoPi * safeSpeed * dt) : 1.0
let coeff: Double = safeSpeed > 0.0 ? exp(-lyrebirdTwoPi * safeSpeed * dt) : 1.0
// Bipolar random step in [-amount, amount], scaled by (1 - coeff) to
// inject energy proportional to how fast the smoother will respond.
@@ -128,6 +128,13 @@ func lyrebirdSeedXorshift64(from seed: UInt64?) -> UInt64 {
lyrebirdSeedXorshift64(from: seed, mixConstant: 0)
}
// MARK: - Mathematical constants
/// Two π: the radian measure of a full cycle.
///
/// Shared by oscillator, modulation, and filter code. Avoids per-function `let twoPi` locals.
internal let lyrebirdTwoPi: Double = 2.0 * Double.pi
// MARK: - Sample rate limits
/// Maximum sample rate supported by Lyrebird hardware drivers.
+17
View File
@@ -0,0 +1,17 @@
// PowerOfTwo.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Smallest power of two `>= n`. Returns `1` for `n <= 1`.
///
/// Used to size circular buffers so the read/write index wrap can be a single
/// bitwise `& (count - 1)` instead of an integer `% count`.
@inline(__always)
func lyrebirdNextPowerOfTwo(_ n: Int) -> Int {
guard n > 1 else { return 1 }
var result: Int = 1
while result < n { result <<= 1 }
return result
}
@@ -10,13 +10,12 @@
/// Gamma draws (shared `_sampleBetaRand` helper with `lo: 0, hi: 1`).
/// `length == -1` runs forever. `reset()` rewinds the response counter but
/// intentionally does not restore the PRNG seed.
internal final class BetaPatternEngine: _PatternEngine {
internal final class BetaPatternEngine: _RandomPatternBase, _PatternEngine {
internal typealias Element = Double
private let _alpha: Double
private let _beta: Double
private let _length: Int
private var _rngState: UInt64
private var _index: Int = 0
internal init(
@@ -28,11 +27,11 @@ internal final class BetaPatternEngine: _PatternEngine {
_alpha = alpha
_beta = beta
_length = length
_rngState = lyrebirdSeedXorshift64(from: seed)
super.init(seed: seed)
}
internal var isExhausted: Bool {
_length >= 0 && _index >= _length
isCounterExhausted(count: _index, limit: _length)
}
internal func next() -> Double? {
@@ -11,7 +11,7 @@
/// midpoint. `length == -1` runs forever. `reset()` restores the starting
/// position but intentionally does not restore the PRNG seed — mirrors the
/// `DemandRandom` convention.
internal final class BrownianPatternEngine: _PatternEngine {
internal final class BrownianPatternEngine: _RandomPatternBase, _PatternEngine {
internal typealias Element = Double
private let _low: Double
@@ -19,7 +19,6 @@ internal final class BrownianPatternEngine: _PatternEngine {
private let _step: Double
private let _initialState: Double
private let _length: Int
private var _rngState: UInt64
private var _index: Int = 0
private var _current: Double
@@ -37,12 +36,12 @@ internal final class BrownianPatternEngine: _PatternEngine {
let midpoint: Double = (low + high) * 0.5
_initialState = start ?? midpoint
_length = length
_rngState = lyrebirdSeedXorshift64(from: seed)
_current = _initialState
super.init(seed: seed)
}
internal var isExhausted: Bool {
_length >= 0 && _index >= _length
isCounterExhausted(count: _index, limit: _length)
}
internal func next() -> Double? {
@@ -11,13 +11,12 @@
/// `_sampleCauchy` helper, `posOnly: false`). `length == -1` runs forever.
/// `reset()` rewinds the response counter but intentionally does not restore
/// the PRNG seed.
internal final class CauchyPatternEngine: _PatternEngine {
internal final class CauchyPatternEngine: _RandomPatternBase, _PatternEngine {
internal typealias Element = Double
private let _location: Double
private let _scale: Double
private let _length: Int
private var _rngState: UInt64
private var _index: Int = 0
internal init(
@@ -29,11 +28,11 @@ internal final class CauchyPatternEngine: _PatternEngine {
_location = location
_scale = scale
_length = length
_rngState = lyrebirdSeedXorshift64(from: seed)
super.init(seed: seed)
}
internal var isExhausted: Bool {
_length >= 0 && _index >= _length
isCounterExhausted(count: _index, limit: _length)
}
internal func next() -> Double? {
@@ -37,9 +37,7 @@ internal final class ConcatenatePatternEngine<T>: _PatternEngine {
}
internal func reset() {
for p: Pattern<T> in _patterns {
p.reset()
}
resetAll(_patterns)
_activeIndex = 0
}
}
@@ -10,13 +10,12 @@
/// `stdDev` via Box-Muller transform (shared `_sampleGauss` helper).
/// `length == -1` runs forever. `reset()` rewinds the response counter but
/// intentionally does not restore the PRNG seed.
internal final class GaussianPatternEngine: _PatternEngine {
internal final class GaussianPatternEngine: _RandomPatternBase, _PatternEngine {
internal typealias Element = Double
private let _mean: Double
private let _stdDev: Double
private let _length: Int
private var _rngState: UInt64
private var _index: Int = 0
internal init(
@@ -28,11 +27,11 @@ internal final class GaussianPatternEngine: _PatternEngine {
_mean = mean
_stdDev = stdDev
_length = length
_rngState = lyrebirdSeedXorshift64(from: seed)
super.init(seed: seed)
}
internal var isExhausted: Bool {
_length >= 0 && _index >= _length
isCounterExhausted(count: _index, limit: _length)
}
internal func next() -> Double? {
@@ -29,7 +29,7 @@ internal final class GeometricPatternEngine: _PatternEngine {
}
internal var isExhausted: Bool {
_length >= 0 && _index >= _length
isCounterExhausted(count: _index, limit: _length)
}
internal func next() -> Double? {
@@ -18,13 +18,12 @@
/// non-repetition is required.
///
/// Single-element pools always return that value (no constraint to enforce).
internal final class NonRepeatingRandomPatternEngine<T>: _PatternEngine {
internal final class NonRepeatingRandomPatternEngine<T>: _RandomPatternBase, _PatternEngine {
internal typealias Element = T
private let _values: [T]
private let _repeats: Int
private var _responseCount: Int = 0
private var _rngState: UInt64
private var _lastIndex: Int = -1
internal init(
@@ -34,11 +33,11 @@ internal final class NonRepeatingRandomPatternEngine<T>: _PatternEngine {
) {
_values = values
_repeats = repeats
_rngState = lyrebirdSeedXorshift64(from: seed)
super.init(seed: seed)
}
internal var isExhausted: Bool {
_repeats >= 0 && _responseCount >= _repeats
isCounterExhausted(count: _responseCount, limit: _repeats)
}
internal func next() -> T? {
@@ -0,0 +1,17 @@
// PatternEngineHelpers.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Returns `true` when a finite counter has reached or exceeded its limit.
/// `limit < 0` means infinite — always returns `false`.
@inline(__always)
func isCounterExhausted(count: Int, limit: Int) -> Bool {
limit >= 0 && count >= limit
}
/// Calls `reset()` on every pattern in `patterns`.
func resetAll<T>(_ patterns: [Pattern<T>]) {
for p: Pattern<T> in patterns { p.reset() }
}
@@ -0,0 +1,19 @@
// RandomPatternBase.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Shared base for pattern engines that own a persistent xorshift64 PRNG state.
///
/// Subclasses inherit `_rngState` and call `super.init(seed:)` to seed it via
/// `lyrebirdSeedXorshift64(from:)`. `reset()` intentionally does not reseed —
/// mirrors the `DemandRandom` convention so retriggering avoids audible repetition.
internal class _RandomPatternBase {
/// xorshift64 PRNG state. Subclasses read and advance this via `xorshift64NextRaw`.
internal var _rngState: UInt64
internal init(seed: UInt64?) {
_rngState = lyrebirdSeedXorshift64(from: seed)
}
}
@@ -53,9 +53,7 @@ internal final class RoundRobinPatternEngine<T>: _PatternEngine {
}
internal func reset() {
for p: Pattern<T> in _patterns {
p.reset()
}
resetAll(_patterns)
for i: Int in 0..<_alive.count {
_alive[i] = true
}
@@ -38,7 +38,7 @@ internal final class SequencePatternEngine<T>: _PatternEngine {
}
internal var isExhausted: Bool {
_repeats >= 0 && _cycleCount >= _repeats
isCounterExhausted(count: _cycleCount, limit: _repeats)
}
internal func next() -> T? {
@@ -27,7 +27,7 @@ internal final class SeriesPatternEngine: _PatternEngine {
}
internal var isExhausted: Bool {
_length >= 0 && _index >= _length
isCounterExhausted(count: _index, limit: _length)
}
internal func next() -> Double? {
@@ -38,7 +38,7 @@ internal final class ShufflePatternEngine<T>: _PatternEngine {
}
internal var isExhausted: Bool {
_repeats >= 0 && _cycleCount >= _repeats
isCounterExhausted(count: _cycleCount, limit: _repeats)
}
internal func next() -> T? {
@@ -49,9 +49,7 @@ internal final class SwitchPatternEngine<T>: _PatternEngine {
}
internal func reset() {
for p: Pattern<T> in _patterns {
p.reset()
}
resetAll(_patterns)
_indexPattern.reset()
_exhaustedLatch = false
}
@@ -44,9 +44,7 @@ internal final class TuplePatternEngine<T>: _PatternEngine {
}
internal func reset() {
for p: Pattern<T> in _patterns {
p.reset()
}
resetAll(_patterns)
_exhaustedLatch = false
}
}
@@ -11,13 +11,12 @@
/// counter but intentionally does not restore the PRNG seed — mirrors the
/// `DemandRandom` convention so rhythmic retriggering of the same pattern
/// instance does not produce audible repetition.
internal final class UniformRandomPatternEngine: _PatternEngine {
internal final class UniformRandomPatternEngine: _RandomPatternBase, _PatternEngine {
internal typealias Element = Double
private let _low: Double
private let _high: Double
private let _length: Int
private var _rngState: UInt64
private var _index: Int = 0
internal init(
@@ -29,11 +28,11 @@ internal final class UniformRandomPatternEngine: _PatternEngine {
_low = low
_high = high
_length = length
_rngState = lyrebirdSeedXorshift64(from: seed)
super.init(seed: seed)
}
internal var isExhausted: Bool {
_length >= 0 && _index >= _length
isCounterExhausted(count: _index, limit: _length)
}
internal func next() -> Double? {
@@ -15,14 +15,13 @@
/// Weights are normalised at init into a cumulative distribution; `next()` is
/// O(N) linear search (acceptable — pools are typically small). All weights
/// must be ≥ 0 and the sum must be > 0; violations trap at init.
internal final class WeightedRandomPatternEngine<T>: _PatternEngine {
internal final class WeightedRandomPatternEngine<T>: _RandomPatternBase, _PatternEngine {
internal typealias Element = T
private let _values: [T]
private let _cumulative: [Double] // normalised, last entry == 1.0
private let _repeats: Int
private var _responseCount: Int = 0
private var _rngState: UInt64
internal init(
values: [T],
@@ -61,11 +60,11 @@ internal final class WeightedRandomPatternEngine<T>: _PatternEngine {
_values = values
_cumulative = cum
_repeats = repeats
_rngState = lyrebirdSeedXorshift64(from: seed)
super.init(seed: seed)
}
internal var isExhausted: Bool {
_repeats >= 0 && _responseCount >= _repeats
isCounterExhausted(count: _responseCount, limit: _repeats)
}
internal func next() -> T? {
@@ -297,9 +297,8 @@ public final class LyrebirdProcessContext: @unchecked Sendable {
}
for synth: any Synthesizer in synths {
let args: ContextAddArgs = ContextAddArgs(engine, synth, nodePosition)
DispatchQueue.main.async {
do { try args.engine.add(args.synth, position: args.position) }
catch { print("[Lyrebird] ProcessContext.add failed: \(error)") }
lyrebirdDispatchEngineOp("ProcessContext.add") {
try args.engine.add(args.synth, position: args.position)
}
}
}
@@ -187,9 +187,8 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
public func add(_ synth: any Synthesizer) {
let args: Args = Args(_engine, synth)
DispatchQueue.main.async {
do { try args.engine.add(args.synth) }
catch { print("[Lyrebird] RoutineContext.add failed: \(error)") }
lyrebirdDispatchEngineOp("RoutineContext.add") {
try args.engine.add(args.synth)
}
}
@@ -198,9 +197,8 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
at time: SampleTime
) {
let args: Args = Args(_engine, synth)
DispatchQueue.main.async {
do { try args.engine.schedule(args.synth, at: time) }
catch { print("[Lyrebird] RoutineContext.schedule(at:) failed: \(error)") }
lyrebirdDispatchEngineOp("RoutineContext.schedule(at:)") {
try args.engine.schedule(args.synth, at: time)
}
}
@@ -209,9 +207,8 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
after seconds: Double
) {
let args: Args = Args(_engine, synth)
DispatchQueue.main.async {
do { try args.engine.schedule(args.synth, after: seconds) }
catch { print("[Lyrebird] RoutineContext.schedule(after:) failed: \(error)") }
lyrebirdDispatchEngineOp("RoutineContext.schedule(after:)") {
try args.engine.schedule(args.synth, after: seconds)
}
}
@@ -0,0 +1,80 @@
// MusicXMLDirectionHelpers.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// MARK: - Shared direction-wrapper helper
/// Emit a `<direction placement="P">` wrapper with an inner `<direction-type>` block.
///
/// Produces exactly:
/// ```
/// <direction placement="P">
/// <direction-type>
/// …content()…
/// </direction-type>
/// <staff>N</staff> ← only when staff != nil
/// …trailing…
/// </direction>
/// ```
///
/// - Parameters:
/// - placement: MusicXML `placement` attribute value (e.g. `"above"`, `"below"`).
/// - staff: When non-nil, emits `<staff>N</staff>` after `</direction-type>`.
/// - trailing: Raw XML appended after `</direction-type>` (and after `<staff>` when present)
/// and before `</direction>`. Defaults to `""`.
/// - content: Closure returning the inner markup placed inside `<direction-type>`.
/// - Returns: The complete direction XML fragment including trailing newline.
func directionXML(
placement: String,
staff: Int? = nil,
trailing: String = "",
content: () -> String
) -> String {
var xml: String = ""
xml += " <direction placement=\"\(placement)\">\n"
xml += " <direction-type>\n"
xml += content()
xml += " </direction-type>\n"
if let staffNumber: Int = staff {
xml += " <staff>\(staffNumber)</staff>\n"
}
xml += trailing
xml += " </direction>\n"
return xml
}
// MARK: - Shared pitch-block helper
/// Emit a `<pitch>` block with step, optional alter, and octave.
///
/// Produces exactly:
/// ```
/// <pitch>
/// <step>S</step>
/// <alter>A</alter> ← only when alter != nil and alter != 0
/// <octave>O</octave>
/// </pitch>
/// ```
///
/// The `<alter>` value is formatted via `Score.formatAlter(_:)` — the same
/// formatter used by `encodeNamedPitch`. Integer alter values (e.g. `1.0`,
/// `-1.0`) produce the same digit string as plain `Int` interpolation.
///
/// - Parameters:
/// - stepGlyph: The letter glyph, e.g. `"C"`, `"F"`.
/// - alter: Semitone adjustment in `Double`. Pass `nil` (or `0`) to suppress the `<alter>` line.
/// - octave: MusicXML octave number.
/// - Returns: The `<pitch>…</pitch>` XML fragment including trailing newline.
func pitchBlockXML(stepGlyph: String, alter: Double?, octave: Int) -> String {
var xml: String = ""
xml += " <pitch>\n"
xml += " <step>\(stepGlyph)</step>\n"
if let a: Double = alter, a != 0.0 {
xml += " <alter>\(Score.formatAlter(a))</alter>\n"
}
xml += " <octave>\(octave)</octave>\n"
xml += " </pitch>\n"
return xml
}
@@ -802,16 +802,12 @@ extension Score {
name: NoteName,
octave: Int
) -> String {
var xml: String = ""
xml += " <pitch>\n"
xml += " <step>\(name.letter.glyph)</step>\n"
let alter: Double = name.accidental.semitones
if alter != 0.0 {
xml += " <alter>\(formatAlter(alter))</alter>\n"
}
xml += " <octave>\(octave)</octave>\n"
xml += " </pitch>\n"
return xml
return pitchBlockXML(
stepGlyph: name.letter.glyph,
alter: alter != 0.0 ? alter : nil,
octave: octave
)
}
/// Map a MIDI note number to a natural-letter spelling, preferring
@@ -820,15 +816,11 @@ extension Score {
let octave: Int = (midi / Pitch.semitonesPerOctave) - Pitch.midiOctaveOffset
let semitone: Int = midi % Pitch.semitonesPerOctave
let (letter, alter): (Letter, Int) = Score.midiSemitoneSpelling[semitone]
var xml: String = ""
xml += " <pitch>\n"
xml += " <step>\(letter.glyph)</step>\n"
if alter != 0 {
xml += " <alter>\(alter)</alter>\n"
}
xml += " <octave>\(octave)</octave>\n"
xml += " </pitch>\n"
return xml
return pitchBlockXML(
stepGlyph: letter.glyph,
alter: alter != 0 ? Double(alter) : nil,
octave: octave
)
}
/// Default spelling used for `Pitch.midi(_:)` events.
@@ -855,24 +847,16 @@ extension Score {
/// Only the open event (crescendo or diminuendo) is emitted here; the close
/// is emitted by ``emitWedgeStopDirectionXML()``.
func emitWedgeStartDirectionXML(kind: WedgeKind) -> String {
var xml: String = ""
xml += " <direction placement=\"below\">\n"
xml += " <direction-type>\n"
xml += " <wedge type=\"\(kind.musicXMLType)\"/>\n"
xml += " </direction-type>\n"
xml += " </direction>\n"
return xml
directionXML(placement: "below") {
" <wedge type=\"\(kind.musicXMLType)\"/>\n"
}
}
/// Emit a `<direction placement="below">` block containing a wedge-stop event.
func emitWedgeStopDirectionXML() -> String {
var xml: String = ""
xml += " <direction placement=\"below\">\n"
xml += " <direction-type>\n"
xml += " <wedge type=\"stop\"/>\n"
xml += " </direction-type>\n"
xml += " </direction>\n"
return xml
directionXML(placement: "below") {
" <wedge type=\"stop\"/>\n"
}
}
// MARK: - Pedal direction emission
@@ -892,16 +876,9 @@ extension Score {
kind: PedalKind,
staff: Int?
) -> String {
var xml: String = ""
xml += " <direction placement=\"below\">\n"
xml += " <direction-type>\n"
xml += " <pedal type=\"\(kind.musicXMLType)\" line=\"yes\"/>\n"
xml += " </direction-type>\n"
if let staffNumber: Int = staff {
xml += " <staff>\(staffNumber)</staff>\n"
directionXML(placement: "below", staff: staff) {
" <pedal type=\"\(kind.musicXMLType)\" line=\"yes\"/>\n"
}
xml += " </direction>\n"
return xml
}
// MARK: - Grace note emission
@@ -1041,20 +1018,20 @@ extension Score {
let nienteAttribute: String = (nienteAtStart || nienteAtEnd) ? " niente=\"yes\"" : ""
// Wedge start
xml += " <direction placement=\"below\">\n"
xml += " <direction-type>\n"
xml += " <wedge type=\"\(wedgeKind)\"\(nienteAttribute)/>\n"
xml += " </direction-type>\n"
xml += " <offset>\(offsetDivisions)</offset>\n"
xml += " </direction>\n"
xml += directionXML(
placement: "below",
trailing: " <offset>\(offsetDivisions)</offset>\n"
) {
" <wedge type=\"\(wedgeKind)\"\(nienteAttribute)/>\n"
}
// Wedge stop
xml += " <direction placement=\"below\">\n"
xml += " <direction-type>\n"
xml += " <wedge type=\"stop\"/>\n"
xml += " </direction-type>\n"
xml += " <offset>\(nextOffsetDivisions)</offset>\n"
xml += " </direction>\n"
xml += directionXML(
placement: "below",
trailing: " <offset>\(nextOffsetDivisions)</offset>\n"
) {
" <wedge type=\"stop\"/>\n"
}
}
}
return xml
@@ -1076,21 +1053,21 @@ extension Score {
dynamic: Dynamic,
offsetDivisions: Int
) -> String {
var xml: String = ""
xml += " <direction placement=\"below\">\n"
xml += " <direction-type>\n"
xml += " <dynamics>\n"
if let name: String = dynamic.musicXMLDynamic {
xml += " <\(name)/>\n"
} else if case .raw(let v) = dynamic {
let safe: Double = v.isFinite ? v : 0.0
xml += " <other-dynamics>\(safe)</other-dynamics>\n"
directionXML(
placement: "below",
trailing: " <offset>\(offsetDivisions)</offset>\n"
) {
var inner: String = ""
inner += " <dynamics>\n"
if let name: String = dynamic.musicXMLDynamic {
inner += " <\(name)/>\n"
} else if case .raw(let v) = dynamic {
let safe: Double = v.isFinite ? v : 0.0
inner += " <other-dynamics>\(safe)</other-dynamics>\n"
}
inner += " </dynamics>\n"
return inner
}
xml += " </dynamics>\n"
xml += " </direction-type>\n"
xml += " <offset>\(offsetDivisions)</offset>\n"
xml += " </direction>\n"
return xml
}
// MARK: - Dynamic direction emission
@@ -1142,23 +1119,21 @@ extension Score {
/// is the Lyrebird-side playback path (`ScoreEvent.velocity`), not a
/// MusicXML playback signal.
func emitDirectionXML(dynamic: Dynamic) -> String {
var xml: String = ""
xml += " <direction placement=\"below\">\n"
xml += " <direction-type>\n"
xml += " <dynamics>\n"
if let name: String = dynamic.musicXMLDynamic {
xml += " <\(name)/>\n"
} else if case .raw(let v) = dynamic {
// Swift's default Double description is the shortest decimal that
// round-trips back to the same bit pattern via `Double(_:)`.
// Guard non-finite (NaN/±Inf carry no velocity meaning).
let safe: Double = v.isFinite ? v : 0.0
xml += " <other-dynamics>\(safe)</other-dynamics>\n"
directionXML(placement: "below") {
var inner: String = ""
inner += " <dynamics>\n"
if let name: String = dynamic.musicXMLDynamic {
inner += " <\(name)/>\n"
} else if case .raw(let v) = dynamic {
// Swift's default Double description is the shortest decimal that
// round-trips back to the same bit pattern via `Double(_:)`.
// Guard non-finite (NaN/±Inf carry no velocity meaning).
let safe: Double = v.isFinite ? v : 0.0
inner += " <other-dynamics>\(safe)</other-dynamics>\n"
}
inner += " </dynamics>\n"
return inner
}
xml += " </dynamics>\n"
xml += " </direction-type>\n"
xml += " </direction>\n"
return xml
}
// MARK: - Numeric formatting helpers
@@ -1157,6 +1157,50 @@ extension Score {
measureOpen = true
}
}
// The atom's FINAL piece exactly filled the current measure
// (`leftover` and `remaining` reached zero together, so the
// in-loop close above — guarded by `leftover > .zero` — did not
// fire). Close the now-full measure here, mirroring the fit
// branch's `remaining == .zero` close. Without this the measure
// stays open with `remaining == .zero`; the NEXT atom then can
// neither fit (`sd <= 0` is false) nor split cleanly — the split
// loop emits a spurious `max(1, …)` one-division piece before the
// bar finally closes, shifting every following note by a division.
if remaining == .zero && measureOpen {
// Flush trailing zero-duration atoms (grace notes, clef
// changes, pedal marks) into the just-filled measure.
while let nextAtom: _Atom = atomQueue.first, nextAtom.soundingDuration == .zero {
let zeroAtom: _Atom = atomQueue.removeFirst()
emitZeroDurationAtom(zeroAtom, isMultiStaff: isMultiStaff, into: &xml)
}
xml += rightBarlineXML(measureNumber: measureIndex, repeats: repeats)
xml += " </measure>\n"
measureOpen = false
measureIndex += 1
measureCap = measureCapacity(forMeasure: measureIndex, meterMap: meterMap)
remaining = measureCap
if !atomQueue.isEmpty {
xml += openMeasure(
number: measureIndex,
divisions: divisions,
bpm: bpm,
meterMap: meterMap,
keySignature: keySignature,
clef: clef,
transpose: transpose,
isFirst: false,
repeats: repeats,
tempoChanges: tempoChanges,
rehearsalMarks: rehearsalMarks,
isMultiStaff: isMultiStaff,
staveCount: staveCount,
staffClefs: staffClefs,
rehearsalMarksAsStaffText: rehearsalMarksAsStaffText
)
measureOpen = true
}
}
}
}
@@ -1370,17 +1414,13 @@ extension Score {
/// Defaults to `false`.
/// - Returns: The XML string fragment (including trailing newline).
func rehearsalDirectionXML(label: String, asStaffText: Bool = false) -> String {
var xml: String = ""
xml += " <direction placement=\"above\">\n"
xml += " <direction-type>\n"
if asStaffText {
xml += " <words enclosure=\"rectangle\" font-weight=\"bold\">\(escape(label))</words>\n"
} else {
xml += " <rehearsal>\(escape(label))</rehearsal>\n"
directionXML(placement: "above") {
if asStaffText {
" <words enclosure=\"rectangle\" font-weight=\"bold\">\(escape(label))</words>\n"
} else {
" <rehearsal>\(escape(label))</rehearsal>\n"
}
}
xml += " </direction-type>\n"
xml += " </direction>\n"
return xml
}
/// Emit a complete tempo `<direction placement="above">` block.
@@ -1391,17 +1431,17 @@ extension Score {
/// - Parameter bpm: Tempo in quarter-note beats per minute.
/// - Returns: The XML string fragment (including trailing newline).
func tempoDirectionXML(bpm: Double) -> String {
var xml: String = ""
xml += " <direction placement=\"above\">\n"
xml += " <direction-type>\n"
xml += " <metronome>\n"
xml += " <beat-unit>quarter</beat-unit>\n"
xml += " <per-minute>\(formatBPM(bpm))</per-minute>\n"
xml += " </metronome>\n"
xml += " </direction-type>\n"
xml += " <sound tempo=\"\(formatBPM(bpm))\"/>\n"
xml += " </direction>\n"
return xml
directionXML(
placement: "above",
trailing: " <sound tempo=\"\(formatBPM(bpm))\"/>\n"
) {
var inner: String = ""
inner += " <metronome>\n"
inner += " <beat-unit>quarter</beat-unit>\n"
inner += " <per-minute>\(formatBPM(bpm))</per-minute>\n"
inner += " </metronome>\n"
return inner
}
}
// MARK: - Barline helpers
+152 -19
View File
@@ -172,15 +172,14 @@ public struct Score: Sendable {
self.keySignature = keySignature
self.repeats = repeats
self.tempoChanges = tempoChanges
// Expand FillMeasure markers against each part's effective meter.
// Parts with a per-part meterMap use their own map; others use the resolved
// score-level map. This is the final funnel for flat, DSL, and section paths.
// Resolve each part's entrance offset (prepended rests) and expand
// FillMeasure markers against the part's effective meter. Parts with a
// per-part meterMap use their own map; others use the resolved score-level
// map. This is the final funnel for flat, DSL, and section paths — the
// assembled parts carry `offset: nil` (the offset is consumed into rests).
self.parts = parts.map { part in
let effectiveMap: MeterMap = part.meterMap ?? resolvedMap
let expanded: [ScoreElement] = Score.expandFillMeasures(
in: part.elements,
meter: effectiveMap
)
let expanded: [ScoreElement] = Score._resolvePartElements(part, meter: effectiveMap)
return ScorePart(
name: part.name,
channel: part.channel,
@@ -457,21 +456,19 @@ public struct Score: Sendable {
)
}
// Expand FillMeasure markers in this section's parts against the
// section's effective meter BEFORE the beat-span calculation so that
// the resolved rests count toward `_beatSpan` and `_measureSpan`.
// After expansion the section parts carry no `.fillMeasure` elements,
// so site-1's expansion in the designated init is a harmless no-op.
// Resolve each part's entrance offset (prepended rests) and expand
// FillMeasure markers against the section's effective meter BEFORE the
// beat-span calculation so that both count toward `_beatSpan` and
// `_measureSpan`. After this the section parts carry no offset and no
// `.fillMeasure` elements, so site-1's expansion in the designated init
// is a harmless no-op.
var sectionExpandedParts: [ScorePart] = []
sectionExpandedParts.reserveCapacity(section.parts.count)
for part: ScorePart in section.parts {
// A polymetric part inside a section fills to ITS OWN bar grid,
// matching the designated-init policy (`part.meterMap ?? score map`).
// A polymetric part inside a section offsets / fills to ITS OWN bar
// grid, matching the designated-init policy (`part.meterMap ?? map`).
let partMeter: MeterMap = part.meterMap ?? effectiveSectionMap
let expanded: [ScoreElement] = Score.expandFillMeasures(
in: part.elements,
meter: partMeter
)
let expanded: [ScoreElement] = Score._resolvePartElements(part, meter: partMeter)
sectionExpandedParts.append(ScorePart(
name: part.name,
channel: part.channel,
@@ -583,7 +580,16 @@ public struct Score: Sendable {
var elems: [ScoreElement] = sectionPart.elements
let gap: Fraction = sectionBeatSpan - partBeats
if gap > .zero {
let padRests: [ScoreElement] = Score._makeRestElements(beats: gap)
// Bar-aligned pad: full bars in the gap become clean
// whole-measure rests instead of greedy largest-value
// rests that straddle barlines and fragment into
// metrically-wrong groupings (e.g. a quarter + dotted-half
// crossing the mid-bar beat).
let padRests: [ScoreElement] = Score._makeBarAlignedRestElements(
startBeat: partBeats,
gap: gap,
meterMap: effectiveSectionMap
)
elems.append(contentsOf: padRests)
}
accumulatedElements[partID, default: []].append(contentsOf: elems)
@@ -794,6 +800,49 @@ public struct Score: Sendable {
elements.reduce(Fraction.zero) { $0 + scoreElementBeatSpan($1) }
}
/// Resolve a ``ScoreOffset`` into the leading rest elements that delay a
/// part's entrance, measured against `meter`.
///
/// - ``ScoreOffset/measures(_:)`` → one whole-measure rest per bar (bars
/// `1..count` under `meter`), so the empty bars engrave cleanly.
/// - ``ScoreOffset/beats(_:)`` / ``ScoreOffset/fraction(_:)`` → a decomposed
/// rest of that many quarter-beats (may land mid-bar).
///
/// Returns `[]` for `nil` or a non-positive offset.
static func _resolveOffsetRests(
_ offset: ScoreOffset?,
meter: MeterMap
) -> [ScoreElement] {
guard let offset: ScoreOffset = offset else { return [] }
switch offset {
case .measures(let count):
guard count > 0 else { return [] }
return Score._makeTacetRests(measureCount: count, meterMap: meter)
case .beats(let beats):
guard beats > 0 else { return [] }
return Score._makeRestElements(beats: fractionFromBeats(beats))
case .fraction(let frac):
guard frac > .zero else { return [] }
return Score._makeRestElements(beats: frac)
}
}
/// Prepend a part's resolved offset rests, then expand any `.fillMeasure`
/// markers — the canonical per-part build-time element transform shared by
/// the flat designated init and section lowering.
///
/// Offset rests are prepended BEFORE expansion so a later `.fillMeasure`
/// fills relative to the part's delayed entrance (the cursor origin includes
/// the offset).
static func _resolvePartElements(
_ part: ScorePart,
meter: MeterMap
) -> [ScoreElement] {
let offsetRests: [ScoreElement] = Score._resolveOffsetRests(part.offset, meter: meter)
let withOffset: [ScoreElement] = offsetRests + part.elements
return Score.expandFillMeasures(in: withOffset, meter: meter)
}
/// Compute the number of full bars required to contain `beats` quarters
/// under `meterMap`.
///
@@ -860,6 +909,90 @@ public struct Score: Sendable {
return result
}
/// Build rest elements filling `gap` quarters starting at `startBeat`,
/// aligned to the bar grid of `meterMap`.
///
/// Unlike ``_makeRestElements(beats:)`` — which greedily decomposes a span
/// into the largest representable note values regardless of metric position
/// (a 21-beat gap becomes three double-dotted-whole rests that straddle
/// barlines) — this walks the bar grid from `startBeat`:
///
/// 1. A leading pickup region (when `meterMap.anacrusis > 0` and `startBeat`
/// falls inside it) is filled up to the bar-1 downbeat.
/// 2. Every FULL bar in the span emits a single bar-capacity rest, so the
/// encoder renders a clean whole-measure rest rather than a fragmented
/// pair (e.g. quarter + dotted-half crossing the mid-bar strong beat).
/// 3. Partial bars at the start (mid-bar entrance) or end are decomposed
/// with ``_makeRestElements(beats:)``.
///
/// Used by section lowering to pad a short part to its section's beat span.
///
/// - Parameters:
/// - startBeat: Absolute quarter-beat where the gap begins (the part's
/// content beat span), measured from beat 0 including any pickup.
/// - gap: Number of quarter-beats to fill.
/// - meterMap: Meter grid the rests align to.
/// - Returns: Bar-aligned rest elements totalling `gap` quarters.
static func _makeBarAlignedRestElements(
startBeat: Fraction,
gap: Fraction,
meterMap: MeterMap
) -> [ScoreElement] {
guard gap > .zero else { return [] }
var result: [ScoreElement] = []
var cursor: Fraction = startBeat
var remainingGap: Fraction = gap
// Pickup region [0, anacrusis): fill up to the bar-1 downbeat first so
// the subsequent full-bar logic starts on a barline.
let anacrusis: Fraction = meterMap.anacrusis
if anacrusis > .zero && cursor < anacrusis {
let toDownbeat: Fraction = anacrusis - cursor
let piece: Fraction = remainingGap <= toDownbeat ? remainingGap : toDownbeat
result.append(contentsOf: Score._makeRestElements(beats: piece))
cursor = cursor + piece
remainingGap = remainingGap - piece
}
// Full bars: walk the grid, emitting one bar-capacity rest per full bar
// and decomposing any partial entrance / tail.
var bar: Int = 1
var barStart: Fraction = anacrusis
while remainingGap > .zero {
let cap: Fraction = meterMap.timeSignature(atBar: bar).measureQuarters
guard cap > .zero else {
// Degenerate meter (zero-capacity bar) — never produced by a
// valid MeterMap, but never silently drop the remaining gap:
// fall back to a flat decomposition so the part still spans the
// full section length.
result.append(contentsOf: Score._makeRestElements(beats: remainingGap))
remainingGap = .zero
break
}
let barEnd: Fraction = barStart + cap
if cursor >= barEnd {
barStart = barEnd
bar += 1
continue
}
let offsetInBar: Fraction = cursor - barStart
let toBarEnd: Fraction = cap - offsetInBar
let piece: Fraction = remainingGap <= toBarEnd ? remainingGap : toBarEnd
if offsetInBar == .zero && piece == cap {
result.append(.rest(duration: .fraction(cap)))
} else {
result.append(contentsOf: Score._makeRestElements(beats: piece))
}
cursor = cursor + piece
remainingGap = remainingGap - piece
if cursor == barEnd {
barStart = barEnd
bar += 1
}
}
return result
}
/// Build whole-measure rest elements for `measureCount` bars under `meterMap`.
///
/// Each bar gets a single rest whose duration equals the bar's capacity.
+47
View File
@@ -0,0 +1,47 @@
// ScoreOffset.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// A leading delay applied to a ``ScorePart`` so the instrument enters later
/// than the start of its section (or, in a flat score, later than beat 0).
///
/// The offset is **resolved at Score build time** into concrete leading rests
/// prepended to the part's elements — exactly the way ``ScoreElement/fillMeasure``
/// is resolved. Once resolved it flows through every downstream path (section
/// beat-span sizing, rest-pad-to-span, MusicXML bar splitting, ``ScorePart/flatten()``)
/// with no special handling, and the stored ``ScorePart/offset`` on the assembled
/// score is `nil` (the offset has been *consumed* into rests).
///
/// ## Units
///
/// - ``measures(_:)`` — meter-dependent. Counts whole bars under the part's
/// effective meter, starting from the part's first full bar. Resolves to one
/// whole-measure rest per bar so the empty bars engrave cleanly. An anacrusis
/// pickup (first section only) is **not** consumed by the offset — measures
/// count from bar 1.
/// - ``beats(_:)`` — meter-agnostic. A count of quarter-beats (`1.0` = one
/// quarter note), resolved to a decomposed rest. May land mid-bar; the encoder
/// already splits following content across barlines.
/// - ``fraction(_:)`` — meter-agnostic, exact quarter-beats as a ``Fraction``.
///
/// ## Round-trip
///
/// Like ``ScoreElement/fillMeasure``, an offset is **emit-resolved**, not a
/// stored MusicXML concept — a score decoded from MusicXML carries `offset == nil`
/// (the leading rests are its representation).
public enum ScoreOffset: Sendable, Equatable {
/// Enter `count` whole bars into the part's timeline (meter-dependent).
/// Negative or zero counts resolve to no offset.
case measures(Int)
/// Enter `count` quarter-beats into the part's timeline (meter-agnostic,
/// `1.0` = one quarter note). Negative or zero values resolve to no offset.
case beats(Double)
/// Enter an exact ``Fraction`` of quarter-beats into the part's timeline
/// (meter-agnostic). Negative or zero values resolve to no offset.
case fraction(Fraction)
}
+20
View File
@@ -90,6 +90,22 @@ public struct ScorePart: Sendable {
/// ``Score/fromMusicXML(data:)``.
public let meterMap: MeterMap?
/// Leading entrance delay for this part.
///
/// When non-nil, the part enters later than the start of its section (or, in
/// a flat score, later than beat 0): a leading rest of the resolved length is
/// prepended to ``elements`` at Score build time. See ``ScoreOffset``.
///
/// This is **consumed** during ``Score`` construction — the offset is turned
/// into concrete leading rests and the assembled score's stored parts carry
/// `offset == nil` (the rests are its representation, exactly as
/// ``ScoreElement/fillMeasure`` markers are gone after expansion). Authoring
/// values are set here; do not expect to read a non-nil `offset` back off an
/// assembled or decoded ``Score``.
///
/// Defaults to `nil` (no delay — the part starts at beat 0).
public let offset: ScoreOffset?
/// Top-level elements in document order.
public let elements: [ScoreElement]
@@ -106,6 +122,8 @@ public struct ScorePart: Sendable {
/// - meterMap: Per-part meter-map override for polymeter — a complete,
/// all-or-nothing replacement of the score-level ``Score/meterMap``. `nil`
/// (default) inherits the score map.
/// - offset: Leading entrance delay, resolved to prepended rests at build
/// time. `nil` (default) starts the part at beat 0. See ``ScoreOffset``.
/// - elements: Top-level ``ScoreElement`` values in document order.
/// - id: Cross-section identity key. When `nil` (the default), `id` is set
/// equal to `name`. Used by ``ScoreSection`` lowering to match the same
@@ -117,6 +135,7 @@ public struct ScorePart: Sendable {
keySignature: KeySignature? = nil,
transpose: Transpose? = nil,
meterMap: MeterMap? = nil,
offset: ScoreOffset? = nil,
elements: [ScoreElement],
id: String? = nil
) {
@@ -129,6 +148,7 @@ public struct ScorePart: Sendable {
self.keySignature = keySignature
self.transpose = transpose
self.meterMap = meterMap
self.offset = offset
self.elements = elements
}
@@ -66,6 +66,10 @@ public enum ScorePartBuilder {
/// this part uses its own complete ``MeterMap`` instead of the score-level
/// ``Score/meterMap`` — an all-or-nothing override. Defaults to `nil`
/// (inherit the score map).
/// - offset: Leading entrance delay — the part starts later than the section
/// start (or beat 0 in a flat score) by the resolved number of measures or
/// beats. Resolved to prepended rests at build time. Defaults to `nil`
/// (enter at beat 0). See ``ScoreOffset``.
/// - id: Cross-section identity key. When `nil` (the default), `id` is set
/// equal to `name`. Used by ``ScoreSection`` lowering to match the same
/// instrument across sections even when the display `name` changes.
@@ -77,6 +81,7 @@ public func Part(
keySignature: KeySignature? = nil,
transpose: Transpose? = nil,
meterMap: MeterMap? = nil,
offset: ScoreOffset? = nil,
id: String? = nil,
@ScoreBuilder elements: () -> [ScoreElement]
) -> ScorePart {
@@ -87,6 +92,7 @@ public func Part(
keySignature: keySignature,
transpose: transpose,
meterMap: meterMap,
offset: offset,
elements: elements(),
id: id
)
@@ -23,16 +23,14 @@
/// let stream = TemporalStream(walk, seed: 7)
/// while let freq = stream.next() { ... }
/// ```
public final class TemporalBrownian: TemporalAlgorithm {
public final class TemporalBrownian: TemporalAlgorithmBase {
private let _lo: TemporalParameter
private let _hi: TemporalParameter
private let _stepSize: TemporalParameter
private let _repeats: Int
private let _explicitStart: Double?
private var _current: Double = 0.0
private var _callCount: Int = 0
private var _initialised: Bool = false
/// - Parameters:
@@ -49,21 +47,18 @@ public final class TemporalBrownian: TemporalAlgorithm {
start: Double? = nil,
repeats: Int = -1
) {
_lo = lo
_hi = hi
_stepSize = stepSize
_repeats = repeats
_explicitStart = start
if let s: Double = start {
_current = s
_initialised = true
}
super.init(repeats: repeats)
}
public var isExhausted: Bool { _repeats >= 0 && _callCount >= _repeats }
public func nextValue(
override public func nextValue(
elapsed: Double,
counter: Int,
rng: inout UInt64
@@ -85,8 +80,8 @@ public final class TemporalBrownian: TemporalAlgorithm {
return _current
}
public func reset() {
_callCount = 0
override public func reset() {
super.reset()
_initialised = false
if let s: Double = _explicitStart {
_current = s
@@ -44,7 +44,7 @@
/// - Out-of-range `to` indices are clamped to `[0, stateCount-1]`.
/// - Cumulative weights are pre-computed at init; `nextValue` is allocation-free.
/// - A state with no transitions (empty `transitions` array) stays in place forever.
public final class TemporalMarkov: TemporalAlgorithm {
public final class TemporalMarkov: TemporalAlgorithmBase {
// MARK: - Nested types
@@ -107,11 +107,9 @@ public final class TemporalMarkov: TemporalAlgorithm {
private let _states: [State]
private let _initialState: Int
private let _repeats: Int
private let _cumulativeWeights: [[Double]]
private var _currentState: Int
private var _callCount: Int = 0
// MARK: - Init
@@ -127,7 +125,6 @@ public final class TemporalMarkov: TemporalAlgorithm {
_states = states
_initialState = max(0, min(initialState, states.count - 1))
_currentState = _initialState
_repeats = repeats
_cumulativeWeights = states.map { state in
var cumulative: [Double] = [Double]()
cumulative.reserveCapacity(state.transitions.count)
@@ -138,13 +135,12 @@ public final class TemporalMarkov: TemporalAlgorithm {
}
return cumulative
}
super.init(repeats: repeats)
}
// MARK: - TemporalAlgorithm
// MARK: - TemporalAlgorithmBase
public var isExhausted: Bool { _repeats >= 0 && _callCount >= _repeats }
public func nextValue(
override public func nextValue(
elapsed: Double,
counter: Int,
rng: inout UInt64
@@ -174,8 +170,8 @@ public final class TemporalMarkov: TemporalAlgorithm {
return value
}
public func reset() {
override public func reset() {
super.reset()
_currentState = _initialState
_callCount = 0
}
}
@@ -19,11 +19,9 @@
/// let stream = TemporalStream(pick, seed: 1)
/// while let freq = stream.next() { ... } // 10 random picks, then nil
/// ```
public final class TemporalRandomPick: TemporalAlgorithm {
public final class TemporalRandomPick: TemporalAlgorithmBase {
private let _values: [TemporalParameter]
private let _repeats: Int
private var _callCount: Int = 0
/// - Parameters:
/// - values: Pool to pick from. Each can be `.value`, `.envelope`, or `.closure`.
@@ -33,12 +31,10 @@ public final class TemporalRandomPick: TemporalAlgorithm {
repeats: Int = -1
) {
_values = values
_repeats = repeats
super.init(repeats: repeats)
}
public var isExhausted: Bool { _repeats >= 0 && _callCount >= _repeats }
public func nextValue(
override public func nextValue(
elapsed: Double,
counter: Int,
rng: inout UInt64
@@ -51,7 +47,7 @@ public final class TemporalRandomPick: TemporalAlgorithm {
return result
}
public func reset() {
_callCount = 0
override public func reset() {
super.reset()
}
}
@@ -18,6 +18,9 @@
/// let stream = TemporalStream(seq)
/// while let freq = stream.next() { ... } // 6 values, then nil
/// ```
/// Exhaustion is cycle-based (counts full passes through `values`), so this stays a
/// direct `TemporalAlgorithm` conformer rather than subclassing `TemporalAlgorithmBase`
/// (whose counter is per-call); it still shares the `isCounterExhausted` guard helper.
public final class TemporalSequence: TemporalAlgorithm {
private let _values: [TemporalParameter]
@@ -36,7 +39,9 @@ public final class TemporalSequence: TemporalAlgorithm {
_repeats = repeats
}
public var isExhausted: Bool { _repeats >= 0 && _cycleCount >= _repeats }
public var isExhausted: Bool {
isCounterExhausted(count: _cycleCount, limit: _repeats)
}
public func nextValue(
elapsed: Double,
@@ -55,15 +55,13 @@
/// let points = TemporalStream(tendency, seed: 1).collect(200)
/// LyrebirdScatterView(points)
/// ```
public final class TemporalTendency: TemporalAlgorithm {
public final class TemporalTendency: TemporalAlgorithmBase {
private let _distribution: DistributionKind
private let _parX: TemporalParameter
private let _parY: TemporalParameter
private let _parA: TemporalParameter?
private let _parB: TemporalParameter?
private let _repeats: Int
private var _callCount: Int = 0
/// - Parameters:
/// - distribution: Which distribution family to sample from.
@@ -84,18 +82,15 @@ public final class TemporalTendency: TemporalAlgorithm {
parB: TemporalParameter? = nil,
repeats: Int = -1
) {
_distribution = distribution
_parX = parX
_parY = parY
_parA = parA
_parB = parB
_repeats = repeats
super.init(repeats: repeats)
}
public var isExhausted: Bool { _repeats >= 0 && _callCount >= _repeats }
public func nextValue(
override public func nextValue(
elapsed: Double,
counter: Int,
rng: inout UInt64
@@ -110,8 +105,8 @@ public final class TemporalTendency: TemporalAlgorithm {
return sample
}
public func reset() {
_callCount = 0
override public func reset() {
super.reset()
}
// MARK: - Private
@@ -0,0 +1,54 @@
// TemporalAlgorithmBase.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Shared base for counter-driven `TemporalAlgorithm` implementations.
///
/// Provides `_repeats` and `_callCount` storage, a counter-based `isExhausted`,
/// and a `reset()` that zeroes `_callCount`. Subclasses override
/// `nextValue(elapsed:counter:rng:)` and extend `reset()` via `super.reset()`
/// to clear algorithm-specific state.
///
/// `TemporalClosure` does not subclass this because it exhausts via closure nil
/// rather than a repeat counter.
open class TemporalAlgorithmBase: TemporalAlgorithm {
/// Total calls before exhaustion. `-1` = infinite.
let _repeats: Int
/// Number of `nextValue` calls completed so far.
var _callCount: Int = 0
/// - Parameter repeats: Total calls before exhaustion. `-1` = infinite.
public init(repeats: Int) {
_repeats = repeats
}
/// `true` once `_callCount` has reached `_repeats`. Always `false` when `_repeats < 0`.
open var isExhausted: Bool {
isCounterExhausted(count: _callCount, limit: _repeats)
}
/// Resets `_callCount` to zero. Subclasses must call `super.reset()` then
/// reset algorithm-specific state.
open func reset() {
_callCount = 0
}
/// Subclasses must override this method to produce values.
///
/// - Parameters:
/// - elapsed: Seconds (or beats) since the owning `TemporalStream` received its first call.
/// - counter: Zero-based call index from the owning `TemporalStream`.
/// - rng: Shared PRNG state from the owning stream.
/// - Returns: The next value, or `nil` to signal exhaustion.
open func nextValue(
elapsed: Double,
counter: Int,
rng: inout UInt64
) -> Double? {
fatalError("TemporalAlgorithmBase: subclass must override nextValue(elapsed:counter:rng:)")
}
}