Music XML updates and optimizations
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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:)")
|
||||
}
|
||||
}
|
||||
@@ -458,3 +458,163 @@ benchEngine(label: " PitchShift.Audio ×16",
|
||||
warmupIter: psWarmup, benchIter: psIter)
|
||||
|
||||
print("\nblockSize=\(blockSize) sampleRate=44100 graph=16×(OscSin→EnvGen→Pan2→Out) warmup=\(crWarmup) iterations=\(crIter)")
|
||||
|
||||
// ============================================================
|
||||
// MARK: - Generator consolidation + RT performance baseline (GP group)
|
||||
//
|
||||
// Reference numbers for the GP perf phases. Each synth drives a target
|
||||
// generator hard (chained instances) so the target dominates the constant
|
||||
// engine/Pan2/Out overhead; the before/after delta on the identical graph
|
||||
// isolates the generator change. Driven via benchEngine so the engine advances
|
||||
// its segment serial every block (no fan-out cache artifact). Swept at
|
||||
// cbs=512 (one control tick/callback) and cbs=64 (8 sub-blocks/callback) to
|
||||
// show the win-curve across control block sizes.
|
||||
// ============================================================
|
||||
|
||||
print("\n--- GP performance baseline (8-voice target graphs) ---\n")
|
||||
|
||||
let gpVoiceCount: Int = 8
|
||||
let gpWarmup: Int = 500
|
||||
let gpIter: Int = 10_000
|
||||
|
||||
/// `gen × gen` and `gen + gen` arithmetic tree — exercises BinaryOpGenerator's
|
||||
/// generator-vs-generator path (vDSP_vmulD / vDSP_vaddD targets in GP-5).
|
||||
final class BinaryOpVectorSynth: SynthesizerBase {
|
||||
let freq: Double
|
||||
let bus: Int
|
||||
init(freq: Double, bus: Int) {
|
||||
self.freq = freq
|
||||
self.bus = bus
|
||||
super.init()
|
||||
}
|
||||
override func build() {
|
||||
let f: Double = freq
|
||||
let o1: OscSin.Audio = OscSin.Audio(freq: f)
|
||||
let o2: OscSin.Audio = OscSin.Audio(freq: f * 1.5)
|
||||
let o3: OscSin.Audio = OscSin.Audio(freq: f * 2.0)
|
||||
let o4: OscSin.Audio = OscSin.Audio(freq: f * 0.5)
|
||||
let mix: any Generator = (o1 * o2) + (o3 * o4)
|
||||
let mix2: any Generator = (mix * o3) + (o2 * o4)
|
||||
Out.Audio(bus: bus, source: Pan2(input: mix2 * 0.2, pan: 0.0))
|
||||
}
|
||||
}
|
||||
|
||||
/// Alternating `gen × scalar` / `gen + scalar` chain — exercises
|
||||
/// BinaryOpGenerator's generator-vs-scalar path (vDSP_vsmulD / vsaddD in GP-5).
|
||||
final class BinaryOpScalarSynth: SynthesizerBase {
|
||||
let freq: Double
|
||||
let bus: Int
|
||||
init(freq: Double, bus: Int) {
|
||||
self.freq = freq
|
||||
self.bus = bus
|
||||
super.init()
|
||||
}
|
||||
override func build() {
|
||||
let o: OscSin.Audio = OscSin.Audio(freq: freq)
|
||||
let chain: any Generator = ((((o * 0.8) + 0.1) * 0.7) + 0.05) * 0.6
|
||||
Out.Audio(bus: bus, source: Pan2(input: chain, pan: 0.0))
|
||||
}
|
||||
}
|
||||
|
||||
/// Chained unary transcendental math — `Exp(Sqrt(Abs(Sin(x))))`. GP-4 vForce
|
||||
/// targets (vvsin / vvsqrt / vvexp; Abs → vDSP_vabsD). Abs keeps Sqrt input
|
||||
/// non-negative.
|
||||
final class UnaryMathSynth: SynthesizerBase {
|
||||
let freq: Double
|
||||
let bus: Int
|
||||
init(freq: Double, bus: Int) {
|
||||
self.freq = freq
|
||||
self.bus = bus
|
||||
super.init()
|
||||
}
|
||||
override func build() {
|
||||
let o: OscSin.Audio = OscSin.Audio(freq: freq)
|
||||
let s: Sin.Audio = Sin.Audio(o)
|
||||
let a: Abs.Audio = Abs.Audio(s)
|
||||
let r: Sqrt.Audio = Sqrt.Audio(a)
|
||||
let e: Exp.Audio = Exp.Audio(r, mul: 0.1)
|
||||
Out.Audio(bus: bus, source: Pan2(input: e, pan: 0.0))
|
||||
}
|
||||
}
|
||||
|
||||
/// `LinLin.Audio` linear remap — GP-6 `vDSP_vsmsaD` target.
|
||||
final class LinLinSynth: SynthesizerBase {
|
||||
let freq: Double
|
||||
let bus: Int
|
||||
init(freq: Double, bus: Int) {
|
||||
self.freq = freq
|
||||
self.bus = bus
|
||||
super.init()
|
||||
}
|
||||
override func build() {
|
||||
let o: OscSin.Audio = OscSin.Audio(freq: freq)
|
||||
let m: LinLin.Audio = LinLin.Audio(o, inLo: -1.0, inHi: 1.0, outLo: 0.0, outHi: 0.2)
|
||||
Out.Audio(bus: bus, source: Pan2(input: m, pan: 0.0))
|
||||
}
|
||||
}
|
||||
|
||||
/// `SVF.Audio` with a generator-driven cutoff (OscSin LFO sweeping 500–2500 Hz)
|
||||
/// — forces the per-sample `sin()` coefficient path that GP-2/P4 replaces with
|
||||
/// block-boundary interpolation.
|
||||
final class SVFGenFreqSynth: SynthesizerBase {
|
||||
let freq: Double
|
||||
let bus: Int
|
||||
init(freq: Double, bus: Int) {
|
||||
self.freq = freq
|
||||
self.bus = bus
|
||||
super.init()
|
||||
}
|
||||
override func build() {
|
||||
let o: OscSin.Audio = OscSin.Audio(freq: freq)
|
||||
let lfo: OscSin.Audio = OscSin.Audio(freq: 2.0, mul: 1000.0, add: 1500.0)
|
||||
let svf: SVF.Audio = SVF.Audio(input: o, freq: lfo, q: 2.0)
|
||||
Out.Audio(bus: bus, source: Pan2(input: svf.lowpass, pan: 0.0))
|
||||
}
|
||||
}
|
||||
|
||||
/// `Chorus.Audio` on a single oscillator — GP-7 power-of-two delay-line target.
|
||||
final class ChorusBenchSynth: SynthesizerBase {
|
||||
let freq: Double
|
||||
let bus: Int
|
||||
init(freq: Double, bus: Int) {
|
||||
self.freq = freq
|
||||
self.bus = bus
|
||||
super.init()
|
||||
}
|
||||
override func build() {
|
||||
let o: OscSin.Audio = OscSin.Audio(freq: freq)
|
||||
let ch: Chorus.Audio = Chorus.Audio(input: o)
|
||||
Out.Audio(bus: bus, source: Pan2(input: ch, pan: 0.0))
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor func gpPopulate(_ engine: SynthesisEngine, _ make: (Double, Int) -> SynthesizerBase) {
|
||||
for i: Int in 0..<gpVoiceCount {
|
||||
let f: Double = 220.0 * pow(2.0, Double(i) / 12.0)
|
||||
do {
|
||||
try engine.add(make(f, 0))
|
||||
} catch {
|
||||
fatalError("engine.add failed in gpPopulate: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let gpTargets: [(label: String, make: (Double, Int) -> SynthesizerBase)] = [
|
||||
("BinaryOp gen×gen / gen+gen", { BinaryOpVectorSynth(freq: $0, bus: $1) }),
|
||||
("BinaryOp gen×scalar / +scalar", { BinaryOpScalarSynth(freq: $0, bus: $1) }),
|
||||
("Unary math Exp(Sqrt(Abs(Sin)))", { UnaryMathSynth(freq: $0, bus: $1) }),
|
||||
("LinLin.Audio", { LinLinSynth(freq: $0, bus: $1) }),
|
||||
("SVF.Audio gen-driven freq", { SVFGenFreqSynth(freq: $0, bus: $1) }),
|
||||
("Chorus.Audio", { ChorusBenchSynth(freq: $0, bus: $1) }),
|
||||
]
|
||||
|
||||
for target: (label: String, make: (Double, Int) -> SynthesizerBase) in gpTargets {
|
||||
for cbs: Int in [512, 64] {
|
||||
benchEngine(label: " \(target.label) cbs=\(cbs)",
|
||||
controlBlockSize: cbs,
|
||||
populate: { gpPopulate($0, target.make) },
|
||||
warmupIter: gpWarmup, benchIter: gpIter)
|
||||
}
|
||||
}
|
||||
|
||||
print("\nblockSize=\(blockSize) voices=\(gpVoiceCount) warmup=\(gpWarmup) iterations=\(gpIter)")
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
// CLICommand.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Top-level commands parsed from `CommandLine.arguments`.
|
||||
public enum CLICommand: Equatable {
|
||||
/// Build the current package, then launch `swift repl` with Lyrebird available.
|
||||
case repl
|
||||
/// Enter the LineNoise-powered `lyrebird>` interactive shell (no subcommand given).
|
||||
case interactive
|
||||
/// Print usage help.
|
||||
case help
|
||||
/// Print the lyrebird version string.
|
||||
case version
|
||||
/// Scaffold a new Lyrebird project in a directory named `name` using `template`.
|
||||
/// When `lyrebirdPath` is set, the generated `Package.swift` and (where
|
||||
/// applicable) `.xcodeproj` reference Lyrebird as a local SPM package at
|
||||
/// that absolute path instead of pulling from the published Git URL.
|
||||
case new(name: String, template: ProjectTemplate, lyrebirdPath: String?)
|
||||
/// Run the current project with `swift run`.
|
||||
case run(release: Bool)
|
||||
/// Export a named Synthesizer template to a Swift source file.
|
||||
/// When `overwrite` is `true`, an existing file at the destination is replaced.
|
||||
case export(name: String, to: String?, overwrite: Bool)
|
||||
/// Install Lyrebird Xcode file templates to the user template directory.
|
||||
/// When `force` is `true`, replaces any existing installation.
|
||||
case installTemplates(force: Bool)
|
||||
/// Remove Lyrebird Xcode file templates from the user template directory.
|
||||
case uninstallTemplates
|
||||
|
||||
/// Parse the command from a raw arguments array (typically `CommandLine.arguments`).
|
||||
///
|
||||
/// - Parameter arguments: The full argument vector. `arguments[0]` is the binary name;
|
||||
/// `arguments[1]` (if present) is the subcommand.
|
||||
/// - Returns: The matching command, or `.help` for unrecognised or malformed subcommands.
|
||||
public static func parse(_ arguments: [String]) -> CLICommand {
|
||||
guard arguments.count > 1 else { return .interactive }
|
||||
switch arguments[1].lowercased() {
|
||||
case "repl":
|
||||
return .repl
|
||||
|
||||
case "version", "--version":
|
||||
return .version
|
||||
|
||||
case "help", "--help", "-h":
|
||||
return .help
|
||||
|
||||
case "new":
|
||||
guard arguments.count > 2, !arguments[2].isEmpty else { return .help }
|
||||
// If the positional argument looks like a flag, the user omitted the name.
|
||||
guard !arguments[2].hasPrefix("-") else { return .help }
|
||||
let template: ProjectTemplate
|
||||
if let tIdx: Array<String>.Index = arguments.firstIndex(of: "--template"),
|
||||
tIdx + 1 < arguments.count,
|
||||
let t: ProjectTemplate = ProjectTemplate(string: arguments[tIdx + 1]) {
|
||||
template = t
|
||||
} else {
|
||||
template = .basic
|
||||
}
|
||||
// Optional `--lyrebird-path <abs-path>` for local-checkout use.
|
||||
// Value must not be a flag token.
|
||||
let lyrebirdPath: String?
|
||||
if let pIdx: Array<String>.Index = arguments.firstIndex(of: "--lyrebird-path"),
|
||||
pIdx + 1 < arguments.count,
|
||||
!arguments[pIdx + 1].hasPrefix("-") {
|
||||
lyrebirdPath = arguments[pIdx + 1]
|
||||
} else {
|
||||
lyrebirdPath = nil
|
||||
}
|
||||
return .new(name: arguments[2],
|
||||
template: template,
|
||||
lyrebirdPath: lyrebirdPath)
|
||||
|
||||
case "run":
|
||||
let release: Bool = arguments.contains("--release")
|
||||
return .run(release: release)
|
||||
|
||||
case "install-templates":
|
||||
let force: Bool = arguments.contains("--force")
|
||||
return .installTemplates(force: force)
|
||||
|
||||
case "uninstall-templates":
|
||||
return .uninstallTemplates
|
||||
|
||||
case "export":
|
||||
guard arguments.count > 2, !arguments[2].isEmpty else { return .help }
|
||||
let synthName: String = arguments[2]
|
||||
// If the positional argument looks like a flag, the user omitted the name.
|
||||
guard !synthName.hasPrefix("-") else { return .help }
|
||||
// Look for `--to <path>` anywhere after the subcommand.
|
||||
// Guard that the value following `--to` is not itself a flag token.
|
||||
let toPath: String?
|
||||
if let toIdx: Array<String>.Index = arguments.firstIndex(of: "--to"),
|
||||
toIdx + 1 < arguments.count,
|
||||
!arguments[toIdx + 1].hasPrefix("-") {
|
||||
toPath = arguments[toIdx + 1]
|
||||
} else {
|
||||
toPath = nil
|
||||
}
|
||||
let overwrite: Bool = arguments.contains("--overwrite")
|
||||
return .export(name: synthName, to: toPath, overwrite: overwrite)
|
||||
|
||||
default:
|
||||
return .help
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// ProjectRunner.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - ProjectRunner
|
||||
|
||||
/// Wraps `swift run` to build and launch the current Lyrebird project.
|
||||
///
|
||||
/// `lyrebird run` and `lyrebird run --release` are thin wrappers: they locate the
|
||||
/// `swift` binary and exec `swift run` (optionally with `-c release`) in the current
|
||||
/// working directory. stdin / stdout / stderr are inherited so compiler output and
|
||||
/// runtime output appear directly in the user's terminal.
|
||||
///
|
||||
/// The runner does **not** verify that a `Package.swift` is present before launching —
|
||||
/// SPM provides a clear error message in that case.
|
||||
public enum ProjectRunner {
|
||||
|
||||
// MARK: - Errors
|
||||
|
||||
/// Errors thrown by `ProjectRunner`.
|
||||
public enum Error: Swift.Error, Equatable {
|
||||
/// The `swift` binary could not be found on this system.
|
||||
case swiftNotFound
|
||||
/// The process exited with a non-zero status.
|
||||
case buildFailed(exitCode: Int32)
|
||||
}
|
||||
|
||||
// MARK: - Public API
|
||||
|
||||
/// Build and run the Swift package in `directory`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - release: When `true`, passes `-c release` to `swift run` for an optimised build.
|
||||
/// - directory: The directory containing `Package.swift`.
|
||||
/// Defaults to the current working directory.
|
||||
/// - Throws: `ProjectRunner.Error.swiftNotFound` if the toolchain is absent;
|
||||
/// `ProjectRunner.Error.buildFailed` if `swift run` exits non-zero.
|
||||
public static func run(
|
||||
release: Bool = false,
|
||||
in directory: String = FileManager.default.currentDirectoryPath
|
||||
) throws {
|
||||
let process: Process = try makeProcess(release: release, in: directory)
|
||||
try process.run()
|
||||
process.waitUntilExit()
|
||||
let exitCode: Int32 = process.terminationStatus
|
||||
guard exitCode == 0 else {
|
||||
throw Error.buildFailed(exitCode: exitCode)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Internal
|
||||
|
||||
/// Builds a `Process` configured to run `swift run` (or `swift run -c release`).
|
||||
///
|
||||
/// Exposed for testing so callers can inspect the process configuration without
|
||||
/// actually launching a build.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - release: When `true`, appends `-c release` to the swift arguments.
|
||||
/// - directory: Working directory for the SPM invocation.
|
||||
/// - Throws: `ProjectRunner.Error.swiftNotFound` if the toolchain is absent.
|
||||
public static func makeProcess(
|
||||
release: Bool = false,
|
||||
in directory: String = FileManager.default.currentDirectoryPath
|
||||
) throws -> Process {
|
||||
let swiftPath: String = try findSwift()
|
||||
var arguments: [String] = ["run"]
|
||||
if release {
|
||||
arguments += ["-c", "release"]
|
||||
}
|
||||
let process: Process = Process()
|
||||
process.executableURL = URL(fileURLWithPath: swiftPath)
|
||||
process.arguments = arguments
|
||||
process.currentDirectoryURL = URL(fileURLWithPath: directory)
|
||||
// stdin / stdout / stderr intentionally not set — inherited for interactive output.
|
||||
return process
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Returns the path to the `swift` binary.
|
||||
///
|
||||
/// Checks, in order:
|
||||
/// - `/usr/bin/swift` — Xcode Command Line Tools / Xcode toolchain
|
||||
/// - `/usr/local/bin/swift` — standalone toolchain (Intel Mac default)
|
||||
/// - `/opt/homebrew/bin/swift` — Homebrew toolchain on Apple Silicon
|
||||
///
|
||||
/// Throws `ProjectRunner.Error.swiftNotFound` if none of the candidates exist.
|
||||
static func findSwift() throws -> String {
|
||||
let candidates: [String] = ["/usr/bin/swift", "/usr/local/bin/swift", "/opt/homebrew/bin/swift"]
|
||||
for path: String in candidates where FileManager.default.isExecutableFile(atPath: path) {
|
||||
return path
|
||||
}
|
||||
throw Error.swiftNotFound
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,898 @@
|
||||
// ProjectScaffolder.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - ProjectTemplate
|
||||
|
||||
/// Template style for a scaffolded Lyrebird project.
|
||||
public enum ProjectTemplate: String, CaseIterable, Equatable {
|
||||
/// Minimal engine setup with `CoreAudioDriver` and `RunLoop.main.run()`.
|
||||
case basic = "basic"
|
||||
/// Real-time demo: `SineTone` synthesizer with `@LiveParam` frequency and amplitude.
|
||||
case demo = "demo"
|
||||
/// GUI demo: `@UIParam` synthesizer with a `LyrebirdWindow` SwiftUI panel.
|
||||
case uiDemo = "ui-demo"
|
||||
/// Non-real-time render: `NRTDriver` writes a `.caf` file and exits.
|
||||
case nrt = "nrt"
|
||||
/// Score / MusicXML render: builds a `Score` with the DSL, exports a
|
||||
/// `.musicxml` document, and renders the score offline with `NRTDriver`.
|
||||
case score = "score"
|
||||
/// macOS `.app` bundle wrapping an AppKit + SwiftUI host of a `@UIParam` synth.
|
||||
/// Generates a full `<name>.xcodeproj` referencing Lyrebird via remote SPM dep.
|
||||
case macosUIXcode = "macos-ui-xcode"
|
||||
/// iOS `.app` bundle with `iOSAudioDriver` + SwiftUI UI.
|
||||
/// Generates a full `<name>.xcodeproj` referencing Lyrebird via remote SPM dep.
|
||||
case iosUI = "ios-ui"
|
||||
/// AUv3 host `.app` + `aumu` plugin extension wrapping a Lyrebird synth.
|
||||
/// Generates a full `<name>.xcodeproj` with two targets and entitlements files.
|
||||
case auv3 = "auv3"
|
||||
|
||||
/// Case-insensitive init from a raw string. Accepts hyphen-free aliases too.
|
||||
public init?(string: String) {
|
||||
switch string.lowercased() {
|
||||
case "basic": self = .basic
|
||||
case "demo": self = .demo
|
||||
case "ui-demo", "uidemo", "ui_demo": self = .uiDemo
|
||||
case "nrt": self = .nrt
|
||||
case "score", "score-musicxml", "scoremusicxml", "musicxml":
|
||||
self = .score
|
||||
case "macos-ui-xcode", "macosuixcode", "macos_ui_xcode":
|
||||
self = .macosUIXcode
|
||||
case "ios-ui", "iosui", "ios_ui":
|
||||
self = .iosUI
|
||||
case "auv3", "au-v3", "au_v3":
|
||||
self = .auv3
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the template emits a full `.xcodeproj` skeleton in addition
|
||||
/// to the Swift Package. The simpler four templates (basic/demo/ui-demo/nrt)
|
||||
/// rely on Xcode's "Open Package.swift" path; these three need a real
|
||||
/// `.xcodeproj` because they ship an `.app` bundle, app entitlements, or
|
||||
/// (auv3) an `.appex` extension target — none of which SwiftPM can express.
|
||||
public var shipsXcodeProject: Bool {
|
||||
switch self {
|
||||
case .basic, .demo, .uiDemo, .nrt, .score: return false
|
||||
case .macosUIXcode, .iosUI, .auv3: return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ProjectScaffolder
|
||||
|
||||
/// Scaffolds a new Lyrebird project as a Swift Package.
|
||||
///
|
||||
/// `lyrebird new <name>` creates:
|
||||
///
|
||||
/// ```
|
||||
/// <name>/
|
||||
/// ├── Package.swift
|
||||
/// ├── <name>.xcworkspace/
|
||||
/// │ └── contents.xcworkspacedata (references Package.swift — open in Xcode)
|
||||
/// ├── Sources/
|
||||
/// │ └── <name>/
|
||||
/// │ └── main.swift (+ AppDelegate.swift, <name>Synth.swift for ui-demo)
|
||||
/// └── Tests/
|
||||
/// └── <name>Tests/
|
||||
/// └── <name>Tests.swift
|
||||
/// ```
|
||||
///
|
||||
/// Pass `--template demo`, `--template ui-demo`, or `--template nrt` to get richer
|
||||
/// starting points.
|
||||
public enum ProjectScaffolder {
|
||||
|
||||
// MARK: - Errors
|
||||
|
||||
/// Errors thrown by `ProjectScaffolder`.
|
||||
public enum Error: Swift.Error, Equatable {
|
||||
/// The project directory already exists.
|
||||
case projectExists(name: String)
|
||||
/// The project name is empty or contains characters not valid in a Swift module name.
|
||||
case invalidName(name: String)
|
||||
/// A file or directory could not be created.
|
||||
case fileSystemError(path: String, reason: String)
|
||||
}
|
||||
|
||||
// MARK: - Public API
|
||||
|
||||
/// Absolute path to the Lyrebird checkout this CLI was *built* from, derived
|
||||
/// from the compile-time source location of this file
|
||||
/// (`<root>/Sources/LyrebirdCLI/ProjectScaffolder.swift`).
|
||||
///
|
||||
/// Used as the default SPM dependency for scaffolded projects when the caller
|
||||
/// passes no explicit `--lyrebird-path`, so generated projects track the
|
||||
/// current `main` API rather than the published `from:` tag — which lags
|
||||
/// unreleased Score/Generator features (e.g. `Part(clef:)`,
|
||||
/// `ScoreEvent.performedDuration`). This is the pre-1.0-stable policy: the
|
||||
/// template source and the dependency it pins both come from one checkout, so
|
||||
/// they never drift.
|
||||
///
|
||||
/// Returns `nil` when the derived root no longer holds the Lyrebird
|
||||
/// `Package.swift` (the binary was installed away from its source tree);
|
||||
/// callers then fall back to the remote versioned dependency.
|
||||
static var defaultLyrebirdCheckoutPath: String? {
|
||||
lyrebirdCheckoutRoot(forSourceFile: #filePath)
|
||||
}
|
||||
|
||||
/// Testable core of ``defaultLyrebirdCheckoutPath``. Given a source file at
|
||||
/// `<root>/Sources/LyrebirdCLI/<file>.swift`, walks up three directory
|
||||
/// levels to `<root>` and returns it iff `<root>/Package.swift` exists and
|
||||
/// names Lyrebird. Returns `nil` otherwise. Split out so the happy- and
|
||||
/// nil-paths can be unit-tested with synthetic paths (the computed property
|
||||
/// is hard-wired to its own `#filePath`).
|
||||
static func lyrebirdCheckoutRoot(forSourceFile sourceFile: String) -> String? {
|
||||
let root: URL = URL(fileURLWithPath: sourceFile)
|
||||
.deletingLastPathComponent() // strip <file>.swift → Sources/LyrebirdCLI/
|
||||
.deletingLastPathComponent() // → Sources/
|
||||
.deletingLastPathComponent() // → <root>/
|
||||
let manifest: String = root.appendingPathComponent("Package.swift").path
|
||||
guard FileManager.default.fileExists(atPath: manifest) else { return nil }
|
||||
// Guard against pointing at an unrelated parent Package.swift.
|
||||
guard let contents: String = try? String(contentsOfFile: manifest, encoding: .utf8),
|
||||
contents.contains("Lyrebird") else { return nil }
|
||||
return root.path
|
||||
}
|
||||
|
||||
/// Scaffold a new Lyrebird project named `name` inside `parentDirectory`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - name: The project name. Must be a non-empty identifier valid as a Swift module name.
|
||||
/// - template: Starter template style (default `.basic`).
|
||||
/// - parentDirectory: Directory in which to create the project folder.
|
||||
/// Defaults to the current working directory.
|
||||
/// - lyrebirdPath: Absolute path to a local Lyrebird checkout to wire into
|
||||
/// the generated `Package.swift` as a `path:` dependency. `nil` → use
|
||||
/// the published remote package. This is a faithful passthrough: the
|
||||
/// `new` CLI command resolves `nil` to ``defaultLyrebirdCheckoutPath``
|
||||
/// *before* calling this (see `LyrebirdCLI.runNew`), so default
|
||||
/// scaffolds track current `main`; direct library callers get the
|
||||
/// documented `nil` → remote behaviour.
|
||||
/// - Throws: `ProjectScaffolder.Error` on name validation failure or file system errors.
|
||||
public static func scaffold(
|
||||
name: String,
|
||||
template: ProjectTemplate = .basic,
|
||||
in parentDirectory: String = FileManager.default.currentDirectoryPath,
|
||||
lyrebirdPath: String? = nil
|
||||
) throws {
|
||||
try validateName(name)
|
||||
|
||||
let projectRoot: String = (parentDirectory as NSString).appendingPathComponent(name)
|
||||
let fm: FileManager = FileManager.default
|
||||
|
||||
guard !fm.fileExists(atPath: projectRoot) else {
|
||||
throw Error.projectExists(name: name)
|
||||
}
|
||||
|
||||
do {
|
||||
try fm.createDirectory(atPath: projectRoot,
|
||||
withIntermediateDirectories: true,
|
||||
attributes: nil)
|
||||
} catch {
|
||||
throw Error.fileSystemError(path: projectRoot,
|
||||
reason: error.localizedDescription)
|
||||
}
|
||||
|
||||
if template.shipsXcodeProject {
|
||||
try scaffoldXcodeProject(name: name,
|
||||
template: template,
|
||||
projectRoot: projectRoot,
|
||||
lyrebirdPath: lyrebirdPath,
|
||||
fm: fm)
|
||||
} else {
|
||||
try scaffoldSwiftPackage(name: name,
|
||||
template: template,
|
||||
projectRoot: projectRoot,
|
||||
lyrebirdPath: lyrebirdPath,
|
||||
fm: fm)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SPM-only scaffold
|
||||
|
||||
private static func scaffoldSwiftPackage(
|
||||
name: String,
|
||||
template: ProjectTemplate,
|
||||
projectRoot: String,
|
||||
lyrebirdPath: String?,
|
||||
fm: FileManager
|
||||
) throws {
|
||||
let sourcesDir: String = (projectRoot as NSString)
|
||||
.appendingPathComponent("Sources/\(name)")
|
||||
let testsDir: String = (projectRoot as NSString)
|
||||
.appendingPathComponent("Tests/\(name)Tests")
|
||||
let workspaceDir: String = (projectRoot as NSString)
|
||||
.appendingPathComponent("\(name).xcworkspace")
|
||||
|
||||
for dir: String in [sourcesDir, testsDir, workspaceDir] {
|
||||
do {
|
||||
try fm.createDirectory(atPath: dir,
|
||||
withIntermediateDirectories: true,
|
||||
attributes: nil)
|
||||
} catch {
|
||||
try? fm.removeItem(atPath: projectRoot)
|
||||
throw Error.fileSystemError(path: dir,
|
||||
reason: error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
var files: [(path: String, content: String)] = [
|
||||
(
|
||||
(projectRoot as NSString).appendingPathComponent("Package.swift"),
|
||||
packageManifest(name: name, template: template, lyrebirdPath: lyrebirdPath)
|
||||
),
|
||||
(
|
||||
(sourcesDir as NSString).appendingPathComponent("main.swift"),
|
||||
mainSwift(name: name, template: template)
|
||||
),
|
||||
(
|
||||
(testsDir as NSString).appendingPathComponent("\(name)Tests.swift"),
|
||||
testsSwift(name: name)
|
||||
),
|
||||
(
|
||||
(workspaceDir as NSString).appendingPathComponent("contents.xcworkspacedata"),
|
||||
workspaceContents()
|
||||
),
|
||||
]
|
||||
|
||||
if template == .uiDemo {
|
||||
files += [
|
||||
(
|
||||
(sourcesDir as NSString).appendingPathComponent("AppDelegate.swift"),
|
||||
appDelegateSwift(name: name)
|
||||
),
|
||||
(
|
||||
(sourcesDir as NSString).appendingPathComponent("\(name)Synth.swift"),
|
||||
synthSwift(name: name)
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
try writeFiles(files.map { ($0.path, $0.content) },
|
||||
fm: fm, projectRoot: projectRoot)
|
||||
}
|
||||
|
||||
// MARK: - Xcode-project scaffold dispatch
|
||||
|
||||
private static func scaffoldXcodeProject(
|
||||
name: String,
|
||||
template: ProjectTemplate,
|
||||
projectRoot: String,
|
||||
lyrebirdPath: String?,
|
||||
fm: FileManager
|
||||
) throws {
|
||||
// Every xcode-bearing template ships an `<name>.xcworkspace` that
|
||||
// references the generated `<name>.xcodeproj`. The workspace is
|
||||
// separate from the SPM-only `workspaceContents()` shape because
|
||||
// there is no `Package.swift` at the project root here.
|
||||
let workspaceDir: String = (projectRoot as NSString)
|
||||
.appendingPathComponent("\(name).xcworkspace")
|
||||
do {
|
||||
try fm.createDirectory(atPath: workspaceDir,
|
||||
withIntermediateDirectories: true,
|
||||
attributes: nil)
|
||||
} catch {
|
||||
try? fm.removeItem(atPath: projectRoot)
|
||||
throw Error.fileSystemError(path: workspaceDir,
|
||||
reason: error.localizedDescription)
|
||||
}
|
||||
|
||||
let workspaceFile: String = (workspaceDir as NSString)
|
||||
.appendingPathComponent("contents.xcworkspacedata")
|
||||
try writeFiles([(workspaceFile,
|
||||
xcodeWorkspaceContents(name: name,
|
||||
lyrebirdPath: lyrebirdPath))],
|
||||
fm: fm, projectRoot: projectRoot)
|
||||
|
||||
switch template {
|
||||
case .macosUIXcode:
|
||||
try writeMacOSUIXcodeFiles(name: name, projectRoot: projectRoot,
|
||||
lyrebirdPath: lyrebirdPath, fm: fm)
|
||||
case .iosUI:
|
||||
try writeIOSUIFiles(name: name, projectRoot: projectRoot,
|
||||
lyrebirdPath: lyrebirdPath, fm: fm)
|
||||
case .auv3:
|
||||
try writeAUv3Files(name: name, projectRoot: projectRoot,
|
||||
lyrebirdPath: lyrebirdPath, fm: fm)
|
||||
case .basic, .demo, .uiDemo, .nrt, .score:
|
||||
// Unreachable — shipsXcodeProject filters these out at dispatch.
|
||||
try? fm.removeItem(atPath: projectRoot)
|
||||
throw Error.fileSystemError(
|
||||
path: projectRoot,
|
||||
reason: "scaffoldXcodeProject called with non-Xcode template \(template.rawValue)"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Workspace XML for xcode-bearing templates — references the generated
|
||||
/// `<name>.xcodeproj`. When `lyrebirdPath` is set, the workspace also
|
||||
/// references the Lyrebird `Package.swift` at that absolute path so
|
||||
/// Xcode's IDE-level SPM resolver picks it up at workspace open.
|
||||
/// Without this extra FileRef, opening the workspace in Xcode (vs.
|
||||
/// running `xcodebuild` from the CLI) can fail with "Missing package
|
||||
/// product 'LyrebirdUI'" — the IDE resolver doesn't always crawl into
|
||||
/// member-project `XCLocalSwiftPackageReference` deps automatically.
|
||||
public static func xcodeWorkspaceContents(
|
||||
name: String,
|
||||
lyrebirdPath: String? = nil
|
||||
) -> String {
|
||||
var refs: String = " <FileRef\n location = \"group:\(name).xcodeproj\">\n </FileRef>"
|
||||
if let path: String = lyrebirdPath {
|
||||
let escaped: String = pbxQuoteEscape(path)
|
||||
refs += "\n <FileRef\n location = \"absolute:\(escaped)\">\n </FileRef>"
|
||||
}
|
||||
return """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
\(refs)
|
||||
</Workspace>
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - Template constants
|
||||
|
||||
// Module-internal so extension files (Xcode-template generators) can
|
||||
// reach them. Single source of truth for the engine defaults written
|
||||
// into every scaffolded `main.swift` / app delegate / iOS app shell.
|
||||
static let scaffoldDefaultBlockSize: Int = 512
|
||||
static let scaffoldDefaultSampleRate: Int = 44100
|
||||
static let scaffoldDefaultOutputChannels: Int = 2
|
||||
static let scaffoldDefaultInputChannels: Int = 2
|
||||
static let scaffoldDefaultNRTDuration: Double = 4.0
|
||||
|
||||
// MARK: - Package manifest
|
||||
|
||||
/// `Package.swift` content for a project using the given template.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - name: Module / package name written into the generated manifest.
|
||||
/// Must already be validated as a legal Swift identifier.
|
||||
/// - template: Starter template the manifest is tailored for. Controls
|
||||
/// which target/product entries appear. Defaults to `.basic`.
|
||||
/// - lyrebirdPath: When non-nil, Lyrebird is declared as a local SPM
|
||||
/// dependency (`.package(path: ...)`) at this absolute path. When
|
||||
/// nil, falls back to the published Git URL (``lyrebirdPackageURL``).
|
||||
/// Used by `lyrebird new --lyrebird-path` for users who don't yet
|
||||
/// have access to the public repository.
|
||||
public static func packageManifest(
|
||||
name: String,
|
||||
template: ProjectTemplate = .basic,
|
||||
lyrebirdPath: String? = nil
|
||||
) -> String {
|
||||
// byName resolves only when the product name matches the package
|
||||
// name (`Lyrebird`). Sibling products (`LyrebirdUI`) need the
|
||||
// explicit `.product(name:package:)` form regardless of whether
|
||||
// the dep is local or remote.
|
||||
let targetDeps: String
|
||||
switch template {
|
||||
case .basic, .demo, .nrt, .score:
|
||||
targetDeps = #""Lyrebird""#
|
||||
case .uiDemo:
|
||||
targetDeps = #""Lyrebird", .product(name: "LyrebirdUI", package: "Lyrebird")"#
|
||||
case .macosUIXcode, .iosUI, .auv3:
|
||||
// Xcode-bearing templates don't emit a `Package.swift` — dispatch
|
||||
// never reaches this function for them. Defensive fallthrough.
|
||||
targetDeps = #""Lyrebird", .product(name: "LyrebirdUI", package: "Lyrebird")"#
|
||||
}
|
||||
let depLine: String
|
||||
if let path: String = lyrebirdPath {
|
||||
// `name:` is required so byName target deps (e.g. `"Lyrebird"`)
|
||||
// resolve — SPM otherwise uses the directory basename as the
|
||||
// package identity, which is unlikely to match `"Lyrebird"`
|
||||
// (worktree paths, renamed checkouts, etc.).
|
||||
// Path escaped for safe embedding in a Swift string literal —
|
||||
// same `\\` then `"` escape semantics as `pbxQuoteEscape`.
|
||||
let escapedPath: String = pbxQuoteEscape(path)
|
||||
depLine = #".package(name: "Lyrebird", path: "\#(escapedPath)"),"#
|
||||
} else {
|
||||
depLine = #".package(url: "\#(lyrebirdPackageURL)", from: "\#(lyrebirdMinimumVersion)"),"#
|
||||
}
|
||||
return """
|
||||
// swift-tools-version: 6.0
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "\(name)",
|
||||
platforms: [.macOS(.v15)],
|
||||
dependencies: [
|
||||
\(depLine)
|
||||
],
|
||||
targets: [
|
||||
.executableTarget(
|
||||
name: "\(name)",
|
||||
dependencies: [\(targetDeps)]
|
||||
),
|
||||
.testTarget(
|
||||
name: "\(name)Tests",
|
||||
dependencies: ["\(name)"]
|
||||
),
|
||||
]
|
||||
)
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - main.swift templates
|
||||
|
||||
/// `main.swift` content for the given template (defaults to `.basic`).
|
||||
public static func mainSwift(
|
||||
name: String,
|
||||
template: ProjectTemplate = .basic
|
||||
) -> String {
|
||||
switch template {
|
||||
case .basic: return mainSwiftBasic(name: name)
|
||||
case .demo: return mainSwiftDemo(name: name)
|
||||
case .uiDemo: return mainSwiftUIDemo(name: name)
|
||||
case .nrt: return mainSwiftNRT(name: name)
|
||||
case .score: return mainSwiftScore(name: name)
|
||||
case .macosUIXcode, .iosUI, .auv3:
|
||||
// Xcode-bearing templates don't emit a `main.swift` under
|
||||
// `Sources/<name>/`. Dispatch never reaches this function for
|
||||
// them. Defensive fallthrough to the basic skeleton.
|
||||
return mainSwiftBasic(name: name)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: basic
|
||||
|
||||
private static func mainSwiftBasic(name: String) -> String {
|
||||
"""
|
||||
// \(name) — entry point
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// Configure the synthesis engine.
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: \(scaffoldDefaultBlockSize),
|
||||
sampleRate: \(scaffoldDefaultSampleRate),
|
||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
||||
numInputChannels: \(scaffoldDefaultInputChannels),
|
||||
driver: CoreAudioDriver()
|
||||
)
|
||||
|
||||
// Add your Synthesizers here.
|
||||
// try engine.add(MySynth())
|
||||
|
||||
do {
|
||||
try engine.start()
|
||||
} catch {
|
||||
fatalError("Engine failed to start: \\(error)")
|
||||
}
|
||||
|
||||
print("\(name) running — press Ctrl+C to stop")
|
||||
RunLoop.main.run()
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: demo
|
||||
|
||||
private static func mainSwiftDemo(name: String) -> String {
|
||||
"""
|
||||
// \(name) — real-time demo
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// MARK: - SineTone
|
||||
|
||||
final class SineTone: SynthesizerBase {
|
||||
@LiveParam var freq: Double = 440.0
|
||||
@LiveParam var amp: Double = 0.25
|
||||
|
||||
override func build() {
|
||||
let osc = OscSin.Audio(freq: $freq)
|
||||
output(bus: 0, source: Pan2(input: osc * $amp))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Main
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: \(scaffoldDefaultBlockSize),
|
||||
sampleRate: \(scaffoldDefaultSampleRate),
|
||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
||||
numInputChannels: \(scaffoldDefaultInputChannels),
|
||||
driver: CoreAudioDriver()
|
||||
)
|
||||
|
||||
do {
|
||||
try engine.start()
|
||||
} catch {
|
||||
fatalError("Engine failed to start: \\(error)")
|
||||
}
|
||||
|
||||
let tone = SineTone()
|
||||
do {
|
||||
try engine.add(tone)
|
||||
} catch {
|
||||
fatalError("Engine.add failed: \\(error)")
|
||||
}
|
||||
|
||||
print("\(name) running — press Ctrl+C to stop")
|
||||
print("Update tone.freq or tone.amp from the REPL to change parameters.")
|
||||
RunLoop.main.run()
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: ui-demo (main.swift only — AppDelegate and Synth are separate files)
|
||||
|
||||
private static func mainSwiftUIDemo(name: String) -> String {
|
||||
"""
|
||||
// \(name) — GUI demo
|
||||
import AppKit
|
||||
import LyrebirdSynth
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: \(scaffoldDefaultBlockSize),
|
||||
sampleRate: \(scaffoldDefaultSampleRate),
|
||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
)
|
||||
|
||||
let delegate = AppDelegate(engine: engine)
|
||||
NSApplication.shared.setActivationPolicy(.regular)
|
||||
NSApplication.shared.delegate = delegate
|
||||
NSApplication.shared.run()
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: nrt
|
||||
|
||||
private static func mainSwiftNRT(name: String) -> String {
|
||||
"""
|
||||
// \(name) — non-real-time render
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// MARK: - \(name)Synth
|
||||
|
||||
final class \(name)Synth: SynthesizerBase {
|
||||
override func build() {
|
||||
let env = EnvelopeGen.Audio(
|
||||
envelope: Envelope(
|
||||
levels: [0, 1, 0.6, 0],
|
||||
durations: [0.02, 0.46, 0.5],
|
||||
curves: [0, 0, 0]
|
||||
)
|
||||
)
|
||||
let osc = OscSin.Audio(freq: 440.0) * env * 0.3
|
||||
output(bus: 0, source: Pan2(input: osc))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Render
|
||||
|
||||
let outputURL = URL(fileURLWithPath: "output.caf")
|
||||
let renderDuration = \(scaffoldDefaultNRTDuration)
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: \(scaffoldDefaultBlockSize),
|
||||
sampleRate: \(scaffoldDefaultSampleRate),
|
||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
||||
numInputChannels: 0,
|
||||
driver: NRTDriver(outputURL: outputURL, duration: renderDuration)
|
||||
)
|
||||
|
||||
// Add synthesizers BEFORE start() — NRTDriver renders synchronously inside start().
|
||||
do {
|
||||
try engine.add(\(name)Synth())
|
||||
} catch {
|
||||
fputs("engine.add failed: \\(error)\\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
|
||||
do {
|
||||
try engine.start()
|
||||
print("Rendered \\(renderDuration)s → \\(outputURL.path)")
|
||||
} catch {
|
||||
fputs("Render failed: \\(error)\\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: score
|
||||
|
||||
private static func mainSwiftScore(name: String) -> String {
|
||||
"""
|
||||
// \(name) — Score / MusicXML render
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// MARK: - ScoreVoice
|
||||
|
||||
/// One self-freeing voice per score event. The envelope's `freeNode`
|
||||
/// done-action removes the synth when its note finishes, so scheduled
|
||||
/// voices never accumulate during the offline render.
|
||||
final class ScoreVoice: SynthesizerBase {
|
||||
let freqHz: Double
|
||||
let amp: Double
|
||||
let durSeconds: Double
|
||||
let pan: Double
|
||||
|
||||
init(freqHz: Double, amp: Double, durSeconds: Double, pan: Double = 0.0) {
|
||||
self.freqHz = freqHz
|
||||
self.amp = amp
|
||||
self.durSeconds = durSeconds
|
||||
self.pan = pan
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
let attack = 0.01
|
||||
let release = 0.06
|
||||
let sustain = max(0.0, durSeconds - attack - release)
|
||||
let envelope = Envelope(
|
||||
levels: [0.0, 1.0, 0.8, 0.0],
|
||||
durations: [attack, sustain, release],
|
||||
curves: [-4.0, 0.0, -6.0]
|
||||
)
|
||||
let osc = OscSawtooth.Audio(freq: freqHz)
|
||||
let env = EnvelopeGen.Control(envelope: envelope, doneAction: .freeNode)
|
||||
output(bus: 0, source: Pan2(input: osc * env * amp, pan: pan))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Build the score
|
||||
|
||||
let bpm = 120.0
|
||||
let secondsPerBeat = 60.0 / bpm
|
||||
|
||||
// Author music with the Score DSL: Note, Rest, Chord, Tuplet, dynamics,
|
||||
// and articulations. Pitch spelling (letter + accidental) is preserved
|
||||
// through MusicXML export. `Generate` and `PatternNotes` add algorithmic
|
||||
// generation (see the "texture" part below).
|
||||
//
|
||||
// Further notation (see the Lyrebird ScoreSystem docs): Slur / Crescendo /
|
||||
// Diminuendo spans, per-note `spanners:` (overlapping spans, glissandi /
|
||||
// slides), per-note `display:` (NoteDisplay — notehead/size/hide stem or
|
||||
// beam), `Section("…") { }` blocks with rehearsal marks, and a `pageLayout:`
|
||||
// (PageLayout — page size, orientation, margins).
|
||||
let score = Score(bpm: bpm, timeSignature: TimeSignature(4, 4)) {
|
||||
Part("lead") {
|
||||
// A crescendo hairpin over the opening arpeggio (notation-only).
|
||||
Crescendo {
|
||||
Note(.named(.c, 5), dur: .quarter, dyn: .mf, art: .staccato)
|
||||
Note(.named(.e, 5), dur: .quarter, dyn: .mf, art: .staccato)
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .f, art: .accent)
|
||||
}
|
||||
Rest(dur: .quarter)
|
||||
Tuplet(3, inTimeOf: 2) {
|
||||
Note(.named(.b, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.a, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .mp)
|
||||
}
|
||||
Chord([.named(.c, 5), .named(.e, 5), .named(.g, 5)], dur: .half, dyn: .f, art: .tenuto)
|
||||
}
|
||||
Part("bass", channel: 1, clef: .bass) {
|
||||
Note(.named(.c, 3), dur: .whole, dyn: .mp)
|
||||
Note(.named(.g, 2), dur: .half, dyn: .p)
|
||||
Note(.named(.c, 3), dur: .half, dyn: .mp, art: .tenuto)
|
||||
}
|
||||
// Texture — algorithmic generation. `Generate` maps an index range
|
||||
// through the builder; `PatternNotes` pulls from a `Pattern` source.
|
||||
Part("texture", channel: 2) {
|
||||
Generate(8) { i in
|
||||
Note(midi: 72 + (i % 6) * 2, dur: .sixteenth, dyn: .pp, art: .staccato)
|
||||
}
|
||||
PatternNotes(count: 4, midi: Pattern.series(start: 60, step: 3, length: 4), dur: .eighth, dyn: .p)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Output location
|
||||
|
||||
// Write next to this project's source rather than the launch directory.
|
||||
// `LyrebirdPaths.projectRoot()` walks up from this file to the folder
|
||||
// containing Package.swift, so output lands in the project regardless of
|
||||
// how the binary is launched (lyrebird run, swift run, or Xcode — whose
|
||||
// working directory is DerivedData). Dev-time convenience; for a shipped
|
||||
// app writing user data, use `LyrebirdPaths.documents` instead.
|
||||
let outputDir = LyrebirdPaths.projectRoot() ?? LyrebirdPaths.currentWorkingDirectory
|
||||
|
||||
// MARK: - Export MusicXML
|
||||
|
||||
let xmlURL = outputDir.appendingPathComponent("score.musicxml")
|
||||
do {
|
||||
let xml = score.toMusicXMLString()
|
||||
try xml.write(to: xmlURL, atomically: true, encoding: .utf8)
|
||||
print("MusicXML written → \\(xmlURL.path)")
|
||||
} catch {
|
||||
fputs("MusicXML export failed: \\(error)\\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
|
||||
// Round-trip sanity check: parse the document back in and compare counts.
|
||||
do {
|
||||
let restored = try Score.fromMusicXML(data: score.toMusicXMLData())
|
||||
print("Round-trip events: \\(score.allEvents.count) → \\(restored.allEvents.count)")
|
||||
} catch {
|
||||
fputs("MusicXML round-trip failed: \\(error)\\n", stderr)
|
||||
}
|
||||
|
||||
// MARK: - Render the score offline
|
||||
|
||||
let tailSeconds = 1.5
|
||||
let renderDuration = score.totalBeats * secondsPerBeat + tailSeconds
|
||||
let outputURL = outputDir.appendingPathComponent("score.caf")
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: \(scaffoldDefaultBlockSize),
|
||||
sampleRate: \(scaffoldDefaultSampleRate),
|
||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
||||
numInputChannels: 0,
|
||||
driver: NRTDriver(outputURL: outputURL, duration: renderDuration)
|
||||
)
|
||||
|
||||
// Schedule one voice per sounding event BEFORE start() — NRTDriver
|
||||
// renders synchronously inside start().
|
||||
var scheduled = 0
|
||||
for event in score.allEvents {
|
||||
guard !event.isRest else { continue }
|
||||
guard let freqHz = event.pitch.frequency else { continue }
|
||||
let pan = event.channel == 0 ? -0.4 : 0.5
|
||||
let voice = ScoreVoice(
|
||||
freqHz: freqHz,
|
||||
amp: event.velocity * 0.35,
|
||||
durSeconds: event.performedDuration * secondsPerBeat,
|
||||
pan: pan
|
||||
)
|
||||
do {
|
||||
try engine.schedule(voice, after: event.beat * secondsPerBeat)
|
||||
scheduled += 1
|
||||
} catch {
|
||||
fputs("engine.schedule failed: \\(error)\\n", stderr)
|
||||
}
|
||||
}
|
||||
print("Scheduled \\(scheduled) voices.")
|
||||
|
||||
do {
|
||||
try engine.start()
|
||||
print("Rendered \\(renderDuration)s → \\(outputURL.path)")
|
||||
} catch {
|
||||
fputs("Render failed: \\(error)\\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - ui-demo additional files
|
||||
|
||||
/// `AppDelegate.swift` content for a ui-demo project.
|
||||
public static func appDelegateSwift(name: String) -> String {
|
||||
"""
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
let engine: SynthesisEngine
|
||||
let synth: \(name)Synth
|
||||
var window: LyrebirdWindow?
|
||||
|
||||
@MainActor
|
||||
init(engine: SynthesisEngine) {
|
||||
self.engine = engine
|
||||
self.synth = \(name)Synth()
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func applicationDidFinishLaunching(_ notification: Notification) {
|
||||
do {
|
||||
try engine.start()
|
||||
} catch {
|
||||
print("Engine.start failed: \\(error)")
|
||||
NSApp.terminate(nil)
|
||||
return
|
||||
}
|
||||
do {
|
||||
try engine.add(synth)
|
||||
} catch {
|
||||
print("Engine.add failed: \\(error)")
|
||||
engine.stop()
|
||||
NSApp.terminate(nil)
|
||||
return
|
||||
}
|
||||
|
||||
window = LyrebirdWindow(title: "\(name)", width: 320, height: 200)
|
||||
window?.open {
|
||||
VStack(spacing: 16) {
|
||||
ParameterSlider("Frequency", node: self.synth.$freq, range: 110...1760)
|
||||
ParameterKnob("Amplitude", node: self.synth.$amp, range: 0...1)
|
||||
ParameterKnob("Pan", node: self.synth.$pan, range: -1...1)
|
||||
}
|
||||
.padding(24)
|
||||
}
|
||||
}
|
||||
|
||||
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
|
||||
true
|
||||
}
|
||||
|
||||
func applicationWillTerminate(_ notification: Notification) {
|
||||
engine.stop()
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
/// `<name>Synth.swift` content for a ui-demo project.
|
||||
public static func synthSwift(name: String) -> String {
|
||||
"""
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
final class \(name)Synth: SynthesizerBase {
|
||||
@UIParam var freq: Double = 440.0
|
||||
@UIParam var amp: Double = 0.25
|
||||
@UIParam var pan: Double = 0.0
|
||||
|
||||
override func build() {
|
||||
let osc = OscSin.Audio(freq: $freq)
|
||||
output(bus: 0, source: Pan2(input: osc * $amp, pan: $pan))
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - Xcode workspace
|
||||
|
||||
/// `contents.xcworkspacedata` body. The single `FileRef` points at the
|
||||
/// workspace's enclosing directory (`group:.`) — the package root that
|
||||
/// holds `Package.swift` — so Xcode recognises it as a Swift package and
|
||||
/// opens the full `Sources/` / `Tests/` tree with a runnable scheme.
|
||||
/// (Referencing the `Package.swift` *file* instead loads a single loose
|
||||
/// document with no schemes — `xcodebuild -list` reports "no schemes".)
|
||||
/// Identical for every SPM template — the file lives at
|
||||
/// `<name>.xcworkspace/contents.xcworkspacedata`.
|
||||
public static func workspaceContents() -> String {
|
||||
"""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
<FileRef
|
||||
location = "group:.">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - Tests template
|
||||
|
||||
/// Starter test file content (shared across all templates).
|
||||
public static func testsSwift(name: String) -> String {
|
||||
"""
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
|
||||
@Suite("\(name)")
|
||||
struct \(name)Tests {
|
||||
|
||||
@Test func engineStartsClean() throws {
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: \(scaffoldDefaultBlockSize),
|
||||
sampleRate: \(scaffoldDefaultSampleRate),
|
||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
||||
numInputChannels: \(scaffoldDefaultInputChannels),
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
try engine.start()
|
||||
engine.processBlock(inputSamples: [])
|
||||
engine.stop()
|
||||
#expect(engine.audioBuses[0].allSatisfy { $0 == 0.0 })
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Validate that `name` is a non-empty Swift-compatible identifier.
|
||||
static func validateName(_ name: String) throws {
|
||||
try validateSwiftIdentifier(name, invalidNameError: Error.invalidName(name: name))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// REPLLauncher.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Errors thrown by `REPLLauncher`.
|
||||
public enum CLIError: Error {
|
||||
/// The `swift` binary could not be found on this system.
|
||||
case swiftNotFound
|
||||
/// `swift build` exited non-zero. REPL launch was aborted.
|
||||
case buildFailed(exitCode: Int32)
|
||||
}
|
||||
|
||||
/// Locates the Swift toolchain, builds the current package, and launches `swift repl`
|
||||
/// with module/library flags pointing at the package's `.build/debug` artifacts so
|
||||
/// `import LyrebirdSynth` works immediately.
|
||||
///
|
||||
/// The Swift Package Manager's `swift package repl` subcommand was removed from the
|
||||
/// toolchain. The replacement is a two-step invocation: `swift build` to produce the
|
||||
/// package's `.swiftmodule` + library, then `swift repl` with `-I` / `-L` / `-l` flags
|
||||
/// pointing at `.build/debug`. See `docs/tooling/repl.md`.
|
||||
public enum REPLLauncher {
|
||||
|
||||
/// Arguments passed to `swift` for the build step that precedes the REPL.
|
||||
public static let buildArguments: [String] = ["build"]
|
||||
|
||||
/// Arguments passed to `swift` to start the REPL. Resolves modules from the package's
|
||||
/// `.build/debug` directory:
|
||||
/// - `-I .build/debug/Modules` — Swift modules (LyrebirdSynth.swiftmodule, ...)
|
||||
/// - `-I .build/debug/LyrebirdC.build` — LyrebirdC C-module modulemap
|
||||
/// - `-L .build/debug -lLyrebird` — link the Lyrebird dylib
|
||||
///
|
||||
/// Paths are relative; `makeProcess(in:)` sets the working directory so the user can
|
||||
/// run from a project root whose `Package.swift` depends on Lyrebird (or from the
|
||||
/// Lyrebird package directory itself).
|
||||
public static let replArguments: [String] = [
|
||||
"repl",
|
||||
"-I", ".build/debug/Modules",
|
||||
"-I", ".build/debug/LyrebirdC.build",
|
||||
"-L", ".build/debug",
|
||||
"-lLyrebird"
|
||||
]
|
||||
|
||||
/// Path to the shared Lyrebird history file used by the interactive shell
|
||||
/// and other tooling that needs persistent command history.
|
||||
public static var historyFilePath: String {
|
||||
FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent(".lyrebird_history").path
|
||||
}
|
||||
|
||||
/// Returns the path to the `swift` binary.
|
||||
///
|
||||
/// Checks `/usr/bin/swift` (Xcode toolchain on macOS) and `/usr/local/bin/swift`
|
||||
/// (standalone toolchain). Throws `CLIError.swiftNotFound` if neither exists.
|
||||
public static func findSwift() throws -> String {
|
||||
let candidates: [String] = ["/usr/bin/swift", "/usr/local/bin/swift"]
|
||||
for path: String in candidates where FileManager.default.isExecutableFile(atPath: path) {
|
||||
return path
|
||||
}
|
||||
throw CLIError.swiftNotFound
|
||||
}
|
||||
|
||||
/// Builds a `Process` that runs `swift` with the given arguments in `directory`.
|
||||
/// stdin / stdout / stderr inherited from the calling process.
|
||||
public static func makeProcess(
|
||||
arguments: [String],
|
||||
in directory: String = FileManager.default.currentDirectoryPath
|
||||
) throws -> Process {
|
||||
let swiftPath: String = try findSwift()
|
||||
let process: Process = Process()
|
||||
process.executableURL = URL(fileURLWithPath: swiftPath)
|
||||
process.arguments = arguments
|
||||
process.currentDirectoryURL = URL(fileURLWithPath: directory)
|
||||
return process
|
||||
}
|
||||
|
||||
/// Builds a `Process` configured to run `swift repl` with module/library flags in `directory`.
|
||||
public static func makeProcess(
|
||||
in directory: String = FileManager.default.currentDirectoryPath
|
||||
) throws -> Process {
|
||||
try makeProcess(arguments: replArguments, in: directory)
|
||||
}
|
||||
|
||||
/// Runs `swift build` and waits for it to finish. Throws `CLIError.buildFailed`
|
||||
/// if the build exited non-zero. If the build was killed by a signal,
|
||||
/// `exitCode` is reported as `1` (rather than the raw signal number, which
|
||||
/// would mislead callers that propagate it through `exit(_:)`).
|
||||
public static func build(
|
||||
in directory: String = FileManager.default.currentDirectoryPath
|
||||
) throws {
|
||||
let process: Process = try makeProcess(arguments: buildArguments, in: directory)
|
||||
try process.run()
|
||||
process.waitUntilExit()
|
||||
if process.terminationReason != .exit {
|
||||
throw CLIError.buildFailed(exitCode: 1)
|
||||
}
|
||||
if process.terminationStatus != 0 {
|
||||
throw CLIError.buildFailed(exitCode: process.terminationStatus)
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the package, then launches `swift repl` with Lyrebird available.
|
||||
/// Blocks until the REPL session ends.
|
||||
///
|
||||
/// - Parameter directory: Working directory for the SPM + REPL invocation.
|
||||
/// Defaults to the current directory. Must contain a `Package.swift`.
|
||||
public static func launch(
|
||||
in directory: String = FileManager.default.currentDirectoryPath
|
||||
) throws {
|
||||
try build(in: directory)
|
||||
let process: Process = try makeProcess(in: directory)
|
||||
try process.run()
|
||||
process.waitUntilExit()
|
||||
}
|
||||
}
|
||||
Vendored
+1
-1
@@ -157,7 +157,7 @@ public enum ___FILEBASENAMEASIDENTIFIER___ {
|
||||
|
||||
let dt = freq / sampleRate
|
||||
_phase += dt * countFloat
|
||||
normalizeLFPhase(&_phase)
|
||||
normalizeOscPhase(&_phase)
|
||||
|
||||
let target = ___FILEBASENAMEASIDENTIFIER___._waveform(_phase)
|
||||
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
// TemplateInstaller.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Installs the bundled Lyrebird Xcode file templates into the user template
|
||||
/// directory so Xcode's New File dialog (⌘N) discovers them.
|
||||
///
|
||||
/// The templates ship as a copied SPM resource on the `LyrebirdCLI` target —
|
||||
/// `Bundle.module.resourceURL.appendingPathComponent("XcodeTemplates")` resolves
|
||||
/// to the directory holding every `.xctemplate` bundle.
|
||||
///
|
||||
/// User template destination:
|
||||
/// `~/Library/Developer/Xcode/Templates/File Templates/Lyrebird/`
|
||||
///
|
||||
/// Apple guarantees this path is the user-scoped template scan root used by
|
||||
/// every recent Xcode version. No Xcode restart is required — the dialog
|
||||
/// rescans on next open.
|
||||
public enum TemplateInstaller {
|
||||
|
||||
/// Errors thrown by `install` / `uninstall`.
|
||||
public enum Error: Swift.Error, Equatable {
|
||||
/// Resource bundle did not contain the expected `XcodeTemplates` directory.
|
||||
/// Indicates a build configuration problem, not a user error.
|
||||
case bundleMissingTemplates(expectedPath: String)
|
||||
/// Destination exists already and `force` was `false`.
|
||||
case destinationExists(path: String)
|
||||
/// Underlying `FileManager` error wrapped with the path that failed.
|
||||
case fileSystemError(path: String, reason: String)
|
||||
}
|
||||
|
||||
/// Subdirectory name inside the LyrebirdCLI resource bundle.
|
||||
static let resourceSubdir: String = "XcodeTemplates"
|
||||
|
||||
/// Last path component under the user's Xcode template dir. The "File Templates"
|
||||
/// parent is fixed by Xcode; only this trailing segment is owned by Lyrebird and
|
||||
/// can therefore be safely removed by `uninstall`.
|
||||
public static let installDirName: String = "Lyrebird"
|
||||
|
||||
/// `~/Library/Developer/Xcode/Templates/File Templates/Lyrebird/`
|
||||
public static var destinationURL: URL {
|
||||
FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent("Library/Developer/Xcode/Templates/File Templates/\(installDirName)", isDirectory: true)
|
||||
}
|
||||
|
||||
/// Resolves `Bundle.module`'s `XcodeTemplates` resource subdir, or throws if missing.
|
||||
static func sourceURL() throws -> URL {
|
||||
guard let resourceURL: URL = Bundle.module.resourceURL else {
|
||||
throw Error.bundleMissingTemplates(expectedPath: "<no resourceURL>")
|
||||
}
|
||||
let candidate: URL = resourceURL.appendingPathComponent(resourceSubdir, isDirectory: true)
|
||||
guard FileManager.default.fileExists(atPath: candidate.path) else {
|
||||
throw Error.bundleMissingTemplates(expectedPath: candidate.path)
|
||||
}
|
||||
return candidate
|
||||
}
|
||||
|
||||
/// Lists the `.xctemplate` bundle names inside the source resource directory.
|
||||
public static func availableTemplates() throws -> [String] {
|
||||
let src: URL = try sourceURL()
|
||||
let contents: [String] = try FileManager.default.contentsOfDirectory(atPath: src.path)
|
||||
return contents.filter { $0.hasSuffix(".xctemplate") }.sorted()
|
||||
}
|
||||
|
||||
/// Copies every `.xctemplate` from the bundle to `destinationURL`.
|
||||
///
|
||||
/// - Parameter force: When `true`, overwrites an existing destination directory.
|
||||
/// When `false`, throws `Error.destinationExists` if the destination already
|
||||
/// exists. Per-template overwrite is unconditional once we've decided to write
|
||||
/// — `force` is the top-level guard.
|
||||
/// - Returns: Number of templates copied.
|
||||
@discardableResult
|
||||
public static func install(force: Bool = false) throws -> Int {
|
||||
let src: URL = try sourceURL()
|
||||
let dest: URL = destinationURL
|
||||
let fm: FileManager = FileManager.default
|
||||
|
||||
if fm.fileExists(atPath: dest.path) {
|
||||
if !force {
|
||||
throw Error.destinationExists(path: dest.path)
|
||||
}
|
||||
do {
|
||||
try fm.removeItem(at: dest)
|
||||
} catch {
|
||||
throw Error.fileSystemError(path: dest.path, reason: error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
// Recreate the destination dir.
|
||||
do {
|
||||
try fm.createDirectory(at: dest, withIntermediateDirectories: true)
|
||||
} catch {
|
||||
throw Error.fileSystemError(path: dest.path, reason: error.localizedDescription)
|
||||
}
|
||||
|
||||
// Copy each .xctemplate bundle.
|
||||
let templates: [String] = try availableTemplates()
|
||||
for name: String in templates {
|
||||
let from: URL = src.appendingPathComponent(name, isDirectory: true)
|
||||
let to: URL = dest.appendingPathComponent(name, isDirectory: true)
|
||||
do {
|
||||
try fm.copyItem(at: from, to: to)
|
||||
} catch {
|
||||
throw Error.fileSystemError(path: to.path, reason: error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
return templates.count
|
||||
}
|
||||
|
||||
/// Removes the entire `~/Library/.../File Templates/Lyrebird/` directory.
|
||||
///
|
||||
/// - Returns: `true` if the directory existed and was removed; `false` if it
|
||||
/// was not installed.
|
||||
@discardableResult
|
||||
public static func uninstall() throws -> Bool {
|
||||
let dest: URL = destinationURL
|
||||
let fm: FileManager = FileManager.default
|
||||
guard fm.fileExists(atPath: dest.path) else { return false }
|
||||
do {
|
||||
try fm.removeItem(at: dest)
|
||||
} catch {
|
||||
throw Error.fileSystemError(path: dest.path, reason: error.localizedDescription)
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user