Files

621 lines
22 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// main.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Accelerate
import Foundation
import LyrebirdSynth
// MARK: - Config
let blockSize: Int = 512
let warmup: Int = 2_000
let iterations: Int = 50_000
// MARK: - Helpers
@discardableResult
@inline(never)
func sink<T>(_ x: T) -> T { x }
func ns(_ d: Duration) -> Double {
Double(d.components.seconds) * 1e9 + Double(d.components.attoseconds) / 1e9
}
func report(
_ label: String,
_ total: Duration,
_ iters: Int
) {
let perBlock: Double = ns(total) / Double(iters)
let perSample: Double = perBlock / Double(blockSize)
let padded: String = label.padding(toLength: 40, withPad: " ", startingAt: 0)
print("\(padded) \(String(format: "%8.1f", perBlock)) ns/block \(String(format: "%5.2f", perSample)) ns/sample")
}
func bench(
_ label: String,
_ body: (
) -> Void) {
// warm up
for _ in 0..<warmup { body() }
// time
let start: ContinuousClock.Instant = ContinuousClock.now
for _ in 0..<iterations { body() }
report(label, ContinuousClock.now - start, iterations)
}
// MARK: - LPF coefficients at 1 kHz / 44100 Hz (typical production filter)
let sampleRate: Double = 44100.0
let freq: Double = 1000.0
let q: Double = 0.707
let w0: Double = 2.0 * Double.pi * freq / sampleRate
let alpha: Double = sin(w0) / (2.0 * q)
let cosW0: Double = cos(w0)
let b0: Double = (1.0 - cosW0) / 2.0; let b1: Double = 1.0 - cosW0; let b2: Double = b0
let a0: Double = 1.0 + alpha; let a1: Double = -2.0 * cosW0; let a2: Double = 1.0 - alpha
let nb0: Double = b0/a0, nb1 = b1/a0, nb2 = b2/a0
let na1: Double = a1/a0, na2 = a2/a0 // positive; subtracted in loop / vDSP
var inputBuf: [Double] = [Double](repeating: 0, count: blockSize)
var outputBuf: [Double] = [Double](repeating: 0, count: blockSize)
inputBuf[0] = 1.0 // impulse
// ============================================================
// MARK: - 1. Single biquad — scalar Direct Form I
// ============================================================
bench("1-section scalar") {
var x1: Double = 0.0, x2 = 0.0, y1 = 0.0, y2 = 0.0
for i: Int in 0..<blockSize {
let x: Double = inputBuf[i]
let y: Double = nb0*x + nb1*x1 + nb2*x2 - na1*y1 - na2*y2
outputBuf[i] = y
x2 = x1; x1 = x
y2 = y1; y1 = y < 1e-30 && y > -1e-30 ? 0 : y
}
sink(outputBuf[blockSize - 1])
}
// ============================================================
// MARK: - 2. Single biquad — vDSP_deq22D
// A: [history_x1, history_x2, x0..x(N-1)] (N+2 elements)
// B: [b0, b1, b2, a1, a2]
// C: [history_y1, history_y2, y0..y(N-1)] (N+2 elements)
// N: blockSize
// ============================================================
var deq22A: [Double] = [Double](repeating: 0, count: blockSize + 2)
var deq22C: [Double] = [Double](repeating: 0, count: blockSize + 2)
var deq22B: [Double] = [nb0, nb1, nb2, na1, na2]
// Load impulse into position 2 (first real sample slot)
deq22A[2] = 1.0
bench("1-section vDSP_deq22D") {
// Copy input into A[2...] each iteration to simulate stateless processing.
// (In production the state is maintained via the prepended history elements.)
deq22A.withUnsafeMutableBufferPointer { ap in
inputBuf.withUnsafeBufferPointer { src in
guard let apBase: UnsafeMutablePointer<Double> = ap.baseAddress, let srcBase: UnsafePointer<Double> = src.baseAddress else { return }
(apBase + 2).update(from: srcBase, count: blockSize)
}
}
deq22A.withUnsafeBufferPointer { ap in
deq22B.withUnsafeBufferPointer { bp in
deq22C.withUnsafeMutableBufferPointer { cp in
guard let apBase: UnsafePointer<Double> = ap.baseAddress,
let bpBase: UnsafePointer<Double> = bp.baseAddress,
let cpBase: UnsafeMutablePointer<Double> = cp.baseAddress else { return }
vDSP_deq22D(apBase, 1, bpBase, cpBase, 1, vDSP_Length(blockSize))
}
}
}
sink(deq22C[blockSize + 1])
}
// ============================================================
// MARK: - 3. 4-section cascade — scalar Direct Form I
// Simulates an 8th-order Butterworth LP (4 cascaded biquads)
// ============================================================
// Four identical LPF biquads in cascade (illustrative; real Butterworth would
// have different Q per stage, but timing is the same).
bench("4-section scalar cascade") {
var out0: [Double] = outputBuf
for _ in 0..<4 {
var x1: Double = 0.0, x2 = 0.0, y1 = 0.0, y2 = 0.0
var tmp: [Double] = [Double](repeating: 0, count: blockSize)
for i: Int in 0..<blockSize {
let x: Double = out0[i]
let y: Double = nb0*x + nb1*x1 + nb2*x2 - na1*y1 - na2*y2
tmp[i] = y
x2 = x1; x1 = x
y2 = y1; y1 = y < 1e-30 && y > -1e-30 ? 0 : y
}
out0 = tmp
}
sink(out0[blockSize - 1])
}
// ============================================================
// MARK: - 4. 4-section cascade — vDSP_biquadD
// Setup created ONCE; reused each iteration (simulates pre-allocated generator).
// Delay buffer (2*(sections+1) doubles) is the only per-block state.
// ============================================================
let numSections: Int = 4
// Coefficients: [b0, b1, b2, a1, a2] × numSections
var biquadCoeffs: [Double] = [Double](repeating: 0, count: 5 * numSections)
for s: Int in 0..<numSections {
biquadCoeffs[s * 5 + 0] = nb0
biquadCoeffs[s * 5 + 1] = nb1
biquadCoeffs[s * 5 + 2] = nb2
biquadCoeffs[s * 5 + 3] = na1
biquadCoeffs[s * 5 + 4] = na2
}
guard let biquadSetup: vDSP_biquad_SetupD = vDSP_biquad_CreateSetupD(&biquadCoeffs, vDSP_Length(numSections)) else {
print("ERROR: vDSP_biquad_CreateSetupD returned nil")
exit(1)
}
defer { vDSP_biquad_DestroySetupD(biquadSetup) }
// Delay buffer: 2*(sections+1) doubles; zeroed = initial state
var biquadDelay: [Double] = [Double](repeating: 0, count: 2 * (numSections + 1))
bench("4-section vDSP_biquadD (pre-alloc setup)") {
inputBuf.withUnsafeBufferPointer { inBuf in
outputBuf.withUnsafeMutableBufferPointer { outBuf in
biquadDelay.withUnsafeMutableBufferPointer { delay in
guard let inBase: UnsafePointer<Double> = inBuf.baseAddress,
let outBase: UnsafeMutablePointer<Double> = outBuf.baseAddress,
let delayBase: UnsafeMutablePointer<Double> = delay.baseAddress else { return }
vDSP_biquadD(biquadSetup,
delayBase,
inBase, 1,
outBase, 1,
vDSP_Length(blockSize))
}
}
}
// Reset delay each iteration so each run starts from the same initial state.
for i: Int in 0..<biquadDelay.count { biquadDelay[i] = 0 }
sink(outputBuf[blockSize - 1])
}
// ============================================================
// MARK: - 5. 4-section cascade — scalar, optimised (no inner alloc)
// Realistic version: uses pre-allocated ping-pong scratch buffers.
// ============================================================
var scratch0: [Double] = [Double](repeating: 0, count: blockSize)
var scratch1: [Double] = [Double](repeating: 0, count: blockSize)
bench("4-section scalar (pre-alloc scratch)") {
// Copy input into scratch0
inputBuf.withUnsafeBufferPointer { src in
scratch0.withUnsafeMutableBufferPointer { dst in
guard let dstBase: UnsafeMutablePointer<Double> = dst.baseAddress, let srcBase: UnsafePointer<Double> = src.baseAddress else { return }
dstBase.update(from: srcBase, count: blockSize)
}
}
for _ in 0..<4 {
var x1: Double = 0.0, x2 = 0.0, y1 = 0.0, y2 = 0.0
for i: Int in 0..<blockSize {
let x: Double = scratch0[i]
let y: Double = nb0*x + nb1*x1 + nb2*x2 - na1*y1 - na2*y2
scratch1[i] = y
x2 = x1; x1 = x
y2 = y1; y1 = y < 1e-30 && y > -1e-30 ? 0 : y
}
swap(&scratch0, &scratch1)
}
sink(scratch0[blockSize - 1])
}
print("\nblockSize=\(blockSize) warmup=\(warmup) iterations=\(iterations)")
// ============================================================
// MARK: - Control-rate sub-block benchmark
//
// Measures processBlock overhead for a graph with 16 voices, each containing
// OscSin.Audio → EnvelopeGen.Control (amp) → Pan2 → Out.Audio.
// EnvelopeGen.Control is the primary beneficiary of sub-block control rate.
// - full block (512) — baseline, one control tick per callback
// - half block (256) — 2 sub-blocks per callback
// - 64 samples — 8 sub-blocks per callback
// ============================================================
print("\n--- Control-rate sub-block overhead (16-voice SineTone graph) ---\n")
func makeBenchEngine(controlBlockSize cbs: Int) -> SynthesisEngine {
SynthesisEngine(
blockSize: blockSize,
controlBlockSize: cbs,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 64,
numControlBuses: 128,
driver: OfflineDriver()
)
}
let benchEnvelope: Envelope = Envelope(
levels: [0.0, 0.05, 0.05, 0.0],
durations: [0.01, 99.0, 0.5],
curves: [.lin, .lin, .lin],
releaseNode: 3
)
// EnvelopeGen.Control amplitude modulation — one floatValue per control sub-block
final class SineToneControlEnvSynth: SynthesizerBase {
@LiveParam var freq: Double
let bus: Int
init(
freq: Double,
bus: Int
) {
self.bus = bus
self.freq = freq
super.init()
}
override func build() {
let ampEnv: EnvelopeGen.Control = EnvelopeGen.Control(envelope: benchEnvelope)
let osc: OscSin.Audio = OscSin.Audio(freq: $freq, mul: ampEnv)
Out.Audio(bus: bus, source: Pan2(input: osc, pan: 0.0))
}
}
// EnvelopeGen.Audio amplitude modulation — full sample-accurate envelope per block
final class SineToneAudioEnvSynth: SynthesizerBase {
@LiveParam var freq: Double
let bus: Int
init(
freq: Double,
bus: Int
) {
self.bus = bus
self.freq = freq
super.init()
}
override func build() {
let ampEnv: EnvelopeGen.Audio = EnvelopeGen.Audio(envelope: benchEnvelope)
let osc: OscSin.Audio = OscSin.Audio(freq: $freq, mul: ampEnv)
Out.Audio(bus: bus, source: Pan2(input: osc, pan: 0.0))
}
}
@MainActor func populateControlEnv(_ engine: SynthesisEngine) {
for i: Int in 0..<16 {
do {
try engine.add(SineToneControlEnvSynth(freq: 220.0 * pow(2.0, Double(i) / 12.0), bus: 0))
} catch {
fatalError("engine.add failed in populateControlEnv: \(error)")
}
}
}
@MainActor func populateAudioEnv(_ engine: SynthesisEngine) {
for i: Int in 0..<16 {
do {
try engine.add(SineToneAudioEnvSynth(freq: 220.0 * pow(2.0, Double(i) / 12.0), bus: 0))
} catch {
fatalError("engine.add failed in populateAudioEnv: \(error)")
}
}
}
func benchEngine(
label: String,
controlBlockSize cbs: Int,
populate: (SynthesisEngine
) -> Void,
warmupIter: Int, benchIter: Int) {
let engine: SynthesisEngine = makeBenchEngine(controlBlockSize: cbs)
populate(engine)
do { try engine.start() } catch { fatalError("benchEngine: engine.start() failed — \(error)") }
let emptyInput: [[Float]] = []
for _ in 0..<warmupIter { engine.processBlock(inputSamples: emptyInput) }
let t0: ContinuousClock.Instant = ContinuousClock.now
for _ in 0..<benchIter { engine.processBlock(inputSamples: emptyInput) }
let elapsed: Duration = ContinuousClock.now - t0
engine.stop()
let perBlock: Double = ns(elapsed) / Double(benchIter)
let perSample: Double = perBlock / Double(blockSize)
let padded: String = label.padding(toLength: 46, withPad: " ", startingAt: 0)
print("\(padded) \(String(format: "%8.1f", perBlock)) ns/block \(String(format: "%5.2f", perSample)) ns/sample")
}
let crWarmup: Int = 500
let crIter: Int = 10_000
print("EnvelopeGen.Audio (full audio rate, cbs=512):")
benchEngine(label: " EnvGen.Audio cbs=512",
controlBlockSize: 512, populate: populateAudioEnv,
warmupIter: crWarmup, benchIter: crIter)
print("\nEnvelopeGen.Control at various controlBlockSizes:")
for cbs: Int in [512, 256, 128, 64, 32, 1] {
let subBlocks: Int = blockSize / cbs
benchEngine(label: " EnvGen.Control cbs=\(cbs) (\(subBlocks) sub-block\(subBlocks == 1 ? "" : "s"))",
controlBlockSize: cbs, populate: populateControlEnv,
warmupIter: crWarmup, benchIter: crIter)
}
// ============================================================
// MARK: - PitchShift A/B benchmark (tunable grain-pool vs 4-head SOLA)
//
// Compares the dynamic grain-pool TuneablePitchShift.Audio against the
// SC-faithful PitchShift.Audio 4-head SOLA primary. Both are driven from an
// OscSin so the capture buffer fills with a non-trivial signal.
// ============================================================
print("\n--- PitchShift A/B (tunable grain-pool vs 4-head SOLA) ---\n")
final class TuneablePitchShiftSynth: SynthesizerBase {
@LiveParam var freq: Double
let bus: Int
let overlap: Int
init(
freq: Double,
bus: Int,
overlap: Int
) {
self.bus = bus
self.freq = freq
self.overlap = overlap
super.init()
}
override func build() {
let osc: OscSin.Audio = OscSin.Audio(freq: $freq)
let ps: TuneablePitchShift.Audio = TuneablePitchShift.Audio(input: osc, pitchRatio: 1.5,
windowSize: 0.05, overlap: overlap)
Out.Audio(bus: bus, source: Pan2(input: ps, pan: 0.0))
}
}
final class PitchShiftSynth: SynthesizerBase {
@LiveParam var freq: Double
let bus: Int
init(
freq: Double,
bus: Int
) {
self.bus = bus
self.freq = freq
super.init()
}
override func build() {
let osc: OscSin.Audio = OscSin.Audio(freq: $freq)
let ps: PitchShift.Audio = PitchShift.Audio(input: osc, pitchRatio: 1.5,
windowSize: 0.05)
Out.Audio(bus: bus, source: Pan2(input: ps, pan: 0.0))
}
}
@MainActor func populatePoolN(_ engine: SynthesisEngine, count: Int, overlap: Int) {
for i: Int in 0..<count {
do {
try engine.add(TuneablePitchShiftSynth(
freq: 220.0 * pow(2.0, Double(i) / 12.0),
bus: 0,
overlap: overlap
))
} catch {
fatalError("engine.add failed in populatePoolN: \(error)")
}
}
}
@MainActor func populate4HeadN(_ engine: SynthesisEngine, count: Int) {
for i: Int in 0..<count {
do {
try engine.add(PitchShiftSynth(
freq: 220.0 * pow(2.0, Double(i) / 12.0),
bus: 0
))
} catch {
fatalError("engine.add failed in populate4HeadN: \(error)")
}
}
}
let psWarmup: Int = 500
let psIter: Int = 5_000
print("Single instance:")
benchEngine(label: " TuneablePitchShift.Audio overlap=4",
controlBlockSize: 512, populate: { populatePoolN($0, count: 1, overlap: 4) },
warmupIter: psWarmup, benchIter: psIter)
benchEngine(label: " TuneablePitchShift.Audio overlap=8 (default)",
controlBlockSize: 512, populate: { populatePoolN($0, count: 1, overlap: 8) },
warmupIter: psWarmup, benchIter: psIter)
benchEngine(label: " PitchShift.Audio (4-head fixed)",
controlBlockSize: 512, populate: { populate4HeadN($0, count: 1) },
warmupIter: psWarmup, benchIter: psIter)
print("\n16 instances in parallel:")
benchEngine(label: " TuneablePitchShift.Audio overlap=4 ×16",
controlBlockSize: 512, populate: { populatePoolN($0, count: 16, overlap: 4) },
warmupIter: psWarmup, benchIter: psIter)
benchEngine(label: " TuneablePitchShift.Audio overlap=8 ×16",
controlBlockSize: 512, populate: { populatePoolN($0, count: 16, overlap: 8) },
warmupIter: psWarmup, benchIter: psIter)
benchEngine(label: " PitchShift.Audio ×16",
controlBlockSize: 512, populate: { populate4HeadN($0, count: 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)")