1.0.0 release

This commit is contained in:
2026-06-01 18:27:40 -07:00
parent b1ab0f102c
commit 1f20fcab20
1151 changed files with 230703 additions and 14 deletions
+460
View File
@@ -0,0 +1,460 @@
// 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))
}
}
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..<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))
}
}
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)")
}
}
}
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)")