// 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(_ 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.. -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 = ap.baseAddress, let srcBase: UnsafePointer = 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 = ap.baseAddress, let bpBase: UnsafePointer = bp.baseAddress, let cpBase: UnsafeMutablePointer = 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.. -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.. = inBuf.baseAddress, let outBase: UnsafeMutablePointer = outBuf.baseAddress, let delayBase: UnsafeMutablePointer = 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.. = dst.baseAddress, let srcBase: UnsafePointer = 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.. -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)) } } 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)") } } } 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..