Lyrebird 2.0.0 — Linux support

Consolidated release: the cross-platform Linux port (engine, generators, CLI,
REPL, NRT, portable DSP), live ALSA audio + ALSA MIDI + POSIX OSC + portable
WAV codec, the GTK4 GUI (LyrebirdUI on the SwiftOpenUI backend), and the Linux
live-coding scratchpad (LiveCompile). Apple platforms unchanged; all additive.
See RELEASES.md and LINUX_README.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-09-10 21:09:11 -07:00
parent 77580ee98e
commit b6fdee8bfc
293 changed files with 16800 additions and 775 deletions
@@ -62,7 +62,17 @@ struct ProjectScaffolderBuildTests {
/// Raw strings (not `ProjectTemplate` cases) are the parametrized arguments
/// because `@Test(arguments:)` requires `Sendable` and the public
/// `ProjectTemplate` enum does not declare the conformance.
static let spmTemplateRawValues: [String] = ["quickstart", "basic", "demo", "nrt", "score", "ui-demo"]
///
/// `ui-demo` emits `import AppKit` / `NSApplication`, so it is Apple-only by
/// construction and is dropped off Apple rather than being expected to
/// build there.
static let spmTemplateRawValues: [String] = {
var templates: [String] = ["quickstart", "basic", "demo", "nrt", "score"]
#if canImport(AppKit)
templates.append("ui-demo")
#endif
return templates
}()
@Test(arguments: spmTemplateRawValues)
func templateBuildsAgainstLiveLyrebird(_ rawValue: String) throws {
@@ -100,15 +110,54 @@ struct ProjectScaffolderBuildTests {
`swift build` failed for template \(template.rawValue) (exit \(result.exitCode)):
\(result.output)
""")
guard result.exitCode == 0 else { return }
// Compiling is not the same as working. The offline-render templates
// pick an output container, and a container the platform cannot write
// (CAF off Apple) fails only at run time — a build-only check calls
// that healthy. So actually run them and require the file to appear.
guard let expectedOutput: String = Self.renderedOutputFileName(for: template) else { return }
let run: (exitCode: Int32, output: String) = try Self.runSwiftRun(in: projectRoot)
#expect(run.exitCode == 0,
"""
`swift run` failed for template \(template.rawValue) (exit \(run.exitCode)):
\(run.output)
""")
let renderedPath: String = (projectRoot as NSString).appendingPathComponent(expectedOutput)
#expect(fm.fileExists(atPath: renderedPath),
"template \(template.rawValue) ran but wrote no \(expectedOutput)")
}
/// The file a template is expected to render, or `nil` for templates that
/// open an audio device or a window instead of writing one.
private static func renderedOutputFileName(for template: ProjectTemplate) -> String? {
switch template.rawValue {
case "nrt": return "output.wav"
case "score": return "score.wav"
default: return nil
}
}
/// Run `swift run` in `directory`, capturing merged stdout+stderr.
private static func runSwiftRun(in directory: String) throws -> (exitCode: Int32, output: String) {
try runProcess(["swift", "run"], in: directory)
}
// MARK: - swift build runner
/// Run `swift build` in `directory`, capturing merged stdout+stderr.
private static func runSwiftBuild(in directory: String) throws -> (exitCode: Int32, output: String) {
try runProcess(["swift", "build"], in: directory)
}
/// Run a command in `directory`, capturing merged stdout+stderr.
private static func runProcess(
_ arguments: [String],
in directory: String
) throws -> (exitCode: Int32, output: String) {
let process: Process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
process.arguments = ["swift", "build"]
process.arguments = arguments
process.currentDirectoryURL = URL(fileURLWithPath: directory)
let pipe: Pipe = Pipe()
@@ -91,9 +91,29 @@ struct ProjectScaffolderTests {
#expect(source.contains("import LyrebirdSynth"))
}
@Test func mainSwiftReferencesCoreAudioDriver() {
let source: String = ProjectScaffolder.mainSwift(name: "Demo")
#expect(source.contains("CoreAudioDriver"))
@Test func mainSwiftDefersDriverChoiceToTheLibrary() {
// A scaffolded CLI project has to build wherever it was created, and
// which drivers exist is not something consumer code can test for: the
// Linux driver is absent from a build without libasound, and from a
// Linux binary cross-compiled on a Mac. Naming a concrete driver — or
// writing the `#if` in the emitted source — produces a project that
// fails to compile on those configurations.
for template: ProjectTemplate in [.quickstart, .basic, .demo] {
let source: String = ProjectScaffolder.mainSwift(name: "Demo", template: template)
#expect(source.contains("makeDefaultAudioDriver()"), "\(template)")
#expect(source.contains("driver: driver"), "\(template)")
#expect(!source.contains("CoreAudioDriver()"), "\(template)")
#expect(!source.contains("ALSAAudioDriver()"), "\(template)")
}
}
@Test func appKitTemplateStaysAppleOnly() {
// The GUI template imports AppKit, so it is macOS-only by construction;
// a platform switch there would imply a portability it does not have.
let source: String = ProjectScaffolder.mainSwift(name: "Demo", template: .uiDemo)
#expect(source.contains("import AppKit"))
#expect(source.contains("CoreAudioDriver()"))
#expect(!source.contains("ALSAAudioDriver"))
}
// MARK: - testsSwift template
@@ -633,7 +653,9 @@ struct ProjectScaffolderTests {
let source: String = ProjectScaffolder.mainSwift(name: "Demo", template: .demo)
#expect(source.contains("@LiveParam"))
#expect(source.contains("SineTone"))
#expect(source.contains("CoreAudioDriver"))
// Driver choice belongs to the library — see
// `mainSwiftDefersDriverChoiceToTheLibrary`.
#expect(source.contains("makeDefaultAudioDriver()"))
}
@Test func demoMainSwiftContainsName() {
@@ -712,7 +734,10 @@ struct ProjectScaffolderTests {
let source: String = ProjectScaffolder.mainSwift(name: "MyRender", template: .nrt)
#expect(source.contains("NRTDriver"))
#expect(source.contains("renderDuration"))
#expect(source.contains("output.caf"))
// WAV, not CAF: CAF is Apple-only, so a CAF render fails at run time
// on Linux even though the project compiles there.
#expect(source.contains("output.wav"))
#expect(source.contains(".wavFloat32"))
}
@Test func nrtMainSwiftContainsName() {
@@ -738,7 +763,8 @@ struct ProjectScaffolderTests {
@Test func scoreMainSwiftRendersOfflineWithNRTDriver() {
let source: String = ProjectScaffolder.mainSwift(name: "MyPiece", template: .score)
#expect(source.contains("NRTDriver"))
#expect(source.contains("score.caf"))
#expect(source.contains("score.wav"))
#expect(source.contains(".wavFloat32"))
#expect(source.contains("engine.schedule"))
// Must not embed the Lyrebird copyright in emitted user source.
#expect(!source.contains("Joshua Parmenter"))
@@ -0,0 +1,374 @@
// ScalarDSPParityTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable import LyrebirdDSP
// The portable scalar cores in `ScalarDSP.swift` are the non-Apple fallback for
// Accelerate's vDSP. A wrong operand order (vDSP's `vsub`/`vdiv` take the
// second operand first) would be a silent, Linux-only DSP bug. These tests run
// each scalar core against the *real* vDSP on Apple and require agreement, so
// the fallback is proven against the thing it replaces. Off Apple there is no
// reference to compare to, so the suite is Apple-only.
#if canImport(Accelerate)
import Accelerate
@Suite("ScalarDSP vDSP parity")
struct ScalarDSPParityTests {
private static let n: Int = 37 // deliberately not a power of two
private static let tolerance: Double = 1e-12
private func makeInput(_ seed: Double) -> [Double] {
var out: [Double] = [Double](repeating: 0, count: Self.n)
for i: Int in 0..<Self.n {
out[i] = sin(Double(i) * 0.31 + seed) * 3.0 - 0.5
}
return out
}
private func expectClose(_ a: [Double], _ b: [Double], _ label: String, _ tol: Double = tolerance) {
#expect(a.count == b.count)
for i: Int in 0..<a.count {
let diff: Double = abs(a[i] - b[i])
#expect(diff <= tol, "\(label): index \(i) scalar=\(a[i]) vDSP=\(b[i])")
}
}
/// Runs `body` with the base pointers of one read-only and one write buffer,
/// recording a test failure (rather than force-unwrapping) if either is empty.
private func withBases(
_ input: [Double],
_ output: inout [Double],
_ body: (UnsafePointer<Double>, UnsafeMutablePointer<Double>) -> Void
) {
input.withUnsafeBufferPointer { ip in
output.withUnsafeMutableBufferPointer { op in
guard let iBase: UnsafePointer<Double> = ip.baseAddress,
let oBase: UnsafeMutablePointer<Double> = op.baseAddress else {
Issue.record("empty buffer")
return
}
body(iBase, oBase)
}
}
}
@Test("c = a * scalar (vsmulD)")
func vScalarMul() {
let a: [Double] = makeInput(0.1)
var scalar: Double = 1.75
var ref: [Double] = [Double](repeating: 0, count: Self.n)
var got: [Double] = [Double](repeating: 0, count: Self.n)
vDSP_vsmulD(a, 1, &scalar, &ref, 1, vDSP_Length(Self.n))
withBases(a, &got) { aBase, gBase in
_lbVScalarMul(aBase, 1, scalar, gBase, 1, Self.n)
}
expectClose(got, ref, "vsmul")
}
@Test("c = a + b (vaddD)")
func vAdd() {
let a: [Double] = makeInput(0.1)
let b: [Double] = makeInput(2.3)
var ref: [Double] = [Double](repeating: 0, count: Self.n)
var got: [Double] = [Double](repeating: 0, count: Self.n)
vDSP_vaddD(a, 1, b, 1, &ref, 1, vDSP_Length(Self.n))
b.withUnsafeBufferPointer { bp in
guard let bBase: UnsafePointer<Double> = bp.baseAddress else { Issue.record("empty"); return }
withBases(a, &got) { aBase, gBase in
_lbVAdd(aBase, 1, bBase, 1, gBase, 1, Self.n)
}
}
expectClose(got, ref, "vadd")
}
@Test("c = a - b, operand order (vsubD)")
func vSub() {
let a: [Double] = makeInput(0.1)
let b: [Double] = makeInput(2.3)
var ref: [Double] = [Double](repeating: 0, count: Self.n)
var got: [Double] = [Double](repeating: 0, count: Self.n)
// vDSP_vsubD(B, IB, A, IA, C, IC, N) computes C = A - B.
vDSP_vsubD(b, 1, a, 1, &ref, 1, vDSP_Length(Self.n))
b.withUnsafeBufferPointer { bp in
guard let bBase: UnsafePointer<Double> = bp.baseAddress else { Issue.record("empty"); return }
withBases(a, &got) { aBase, gBase in
_lbVSub(aBase, 1, bBase, 1, gBase, 1, Self.n)
}
}
expectClose(got, ref, "vsub")
}
@Test("c = a / b, operand order (vdivD)")
func vDiv() {
let a: [Double] = makeInput(0.1)
let b: [Double] = makeInput(2.3).map { $0 + 5.0 } // keep divisor away from 0
var ref: [Double] = [Double](repeating: 0, count: Self.n)
var got: [Double] = [Double](repeating: 0, count: Self.n)
// vDSP_vdivD(B, IB, A, IA, C, IC, N) computes C = A / B.
vDSP_vdivD(b, 1, a, 1, &ref, 1, vDSP_Length(Self.n))
b.withUnsafeBufferPointer { bp in
guard let bBase: UnsafePointer<Double> = bp.baseAddress else { Issue.record("empty"); return }
withBases(a, &got) { aBase, gBase in
_lbVDiv(aBase, 1, bBase, 1, gBase, 1, Self.n)
}
}
expectClose(got, ref, "vdiv")
}
@Test("d = a*mul + add (vsmsaD)")
func vScalarMulScalarAdd() {
let a: [Double] = makeInput(0.1)
var mul: Double = 2.5
var add: Double = -1.25
var ref: [Double] = [Double](repeating: 0, count: Self.n)
var got: [Double] = [Double](repeating: 0, count: Self.n)
vDSP_vsmsaD(a, 1, &mul, &add, &ref, 1, vDSP_Length(Self.n))
withBases(a, &got) { aBase, gBase in
_lbVScalarMulScalarAdd(aBase, 1, mul, add, gBase, 1, Self.n)
}
expectClose(got, ref, "vsmsa")
}
@Test("d = a*mul + c(vector) (vsmaD)")
func vScalarMulVAdd() {
let a: [Double] = makeInput(0.1)
let c: [Double] = makeInput(1.7)
var mul: Double = 0.8
var ref: [Double] = [Double](repeating: 0, count: Self.n)
var got: [Double] = [Double](repeating: 0, count: Self.n)
vDSP_vsmaD(a, 1, &mul, c, 1, &ref, 1, vDSP_Length(Self.n))
c.withUnsafeBufferPointer { cp in
guard let cBase: UnsafePointer<Double> = cp.baseAddress else { Issue.record("empty"); return }
withBases(a, &got) { aBase, gBase in
_lbVScalarMulVAdd(aBase, 1, mul, cBase, 1, gBase, 1, Self.n)
}
}
expectClose(got, ref, "vsma")
}
@Test("scalar reductions (maxmgvD, sveD)")
func reductions() {
let a: [Double] = makeInput(0.1)
var refMax: Double = 0
var refSum: Double = 0
vDSP_maxmgvD(a, 1, &refMax, vDSP_Length(Self.n))
vDSP_sveD(a, 1, &refSum, vDSP_Length(Self.n))
var gotMax: Double = 0
var gotSum: Double = 0
a.withUnsafeBufferPointer { ap in
guard let aBase: UnsafePointer<Double> = ap.baseAddress else { Issue.record("empty"); return }
gotMax = _lbMaxMagnitude(aBase, 1, Self.n)
gotSum = _lbSum(aBase, 1, Self.n)
}
#expect(abs(gotMax - refMax) <= Self.tolerance)
#expect(abs(gotSum - refSum) <= 1e-10)
}
@Test("double→float conversion (vdpsp)")
func convertDoubleToFloat() {
let a: [Double] = makeInput(0.1)
var ref: [Float] = [Float](repeating: 0, count: Self.n)
var got: [Float] = [Float](repeating: 0, count: Self.n)
vDSP_vdpsp(a, 1, &ref, 1, vDSP_Length(Self.n))
a.withUnsafeBufferPointer { ap in
got.withUnsafeMutableBufferPointer { gp in
guard let aBase: UnsafePointer<Double> = ap.baseAddress,
let gBase: UnsafeMutablePointer<Float> = gp.baseAddress else { Issue.record("empty"); return }
_lbConvertDoubleToFloat(aBase, 1, gBase, 1, Self.n)
}
}
for i: Int in 0..<Self.n { #expect(got[i] == ref[i]) }
}
@Test("row-major matrix multiply (mmulD)")
func matMul() {
// C[3×2] = A[3×4] · B[4×2]
let m: Int = 3, n: Int = 2, p: Int = 4
var a: [Double] = (0..<(m * p)).map { sin(Double($0) * 0.7) }
var b: [Double] = (0..<(p * n)).map { cos(Double($0) * 0.4) - 0.3 }
var ref: [Double] = [Double](repeating: 0, count: m * n)
var got: [Double] = [Double](repeating: 0, count: m * n)
vDSP_mmulD(&a, 1, &b, 1, &ref, 1, vDSP_Length(m), vDSP_Length(n), vDSP_Length(p))
a.withUnsafeBufferPointer { ap in b.withUnsafeBufferPointer { bp in
got.withUnsafeMutableBufferPointer { gp in
guard let aB = ap.baseAddress, let bB = bp.baseAddress, let gB = gp.baseAddress else { Issue.record("empty"); return }
_lbMatMul(aB, 1, bB, 1, gB, 1, m, n, p)
}
} }
for i: Int in 0..<(m * n) { #expect(abs(got[i] - ref[i]) <= Self.tolerance) }
}
@Test("biquad cascade matches vDSP (2 sections)")
func biquad() {
let m: Int = 2
// Two stable sections: [b0, b1, b2, a1, a2] each.
var coeffs: [Double] = [0.5, 0.3, 0.1, -0.2, 0.05,
0.7, -0.1, 0.02, 0.15, -0.30]
let input: [Double] = makeInput(0.2)
var ref: [Double] = [Double](repeating: 0, count: Self.n)
var got: [Double] = [Double](repeating: 0, count: Self.n)
var refDelay: [Double] = [Double](repeating: 0, count: 2 * m + 2)
var gotDelay: [Double] = [Double](repeating: 0, count: 2 * m + 2)
guard let setup: vDSP_biquad_SetupD = vDSP_biquad_CreateSetupD(&coeffs, vDSP_Length(m)) else {
Issue.record("vDSP_biquad_CreateSetupD returned nil"); return
}
defer { vDSP_biquad_DestroySetupD(setup) }
input.withUnsafeBufferPointer { ip in
guard let iBase: UnsafePointer<Double> = ip.baseAddress else { Issue.record("empty"); return }
vDSP_biquadD(setup, &refDelay, iBase, 1, &ref, 1, vDSP_Length(Self.n))
}
input.withUnsafeBufferPointer { ip in
got.withUnsafeMutableBufferPointer { gp in
coeffs.withUnsafeBufferPointer { cp in
guard let iBase = ip.baseAddress, let gBase = gp.baseAddress, let cBase = cp.baseAddress else { Issue.record("empty"); return }
_lbRunBiquad(cBase, m, &gotDelay, iBase, 1, gBase, 1, Self.n)
}
}
}
for i: Int in 0..<Self.n {
#expect(abs(got[i] - ref[i]) <= 1e-9, "biquad index \(i): got \(got[i]) vDSP \(ref[i])")
}
}
@Test("real FFT forward matches vDSP_fft_zrip (n=16)")
func fftForward() {
let log2n: vDSP_Length = 4
let n: Int = 16
let half: Int = n / 2
let r: [Float] = (0..<n).map { Float(sin(Double($0) * 0.9) + 0.3 * cos(Double($0) * 0.35)) }
var rpV: [Float] = [Float](repeating: 0, count: half)
var ipV: [Float] = [Float](repeating: 0, count: half)
var rpM: [Float] = [Float](repeating: 0, count: half)
var ipM: [Float] = [Float](repeating: 0, count: half)
for j: Int in 0..<half {
rpV[j] = r[2 * j]; ipV[j] = r[2 * j + 1]
rpM[j] = r[2 * j]; ipM[j] = r[2 * j + 1]
}
var workRe: [Float] = [Float](repeating: 0, count: n)
var workIm: [Float] = [Float](repeating: 0, count: n)
guard let setup: FFTSetup = vDSP_create_fftsetup(log2n, FFTRadix(kFFTRadix2)) else {
Issue.record("create_fftsetup nil"); return
}
defer { vDSP_destroy_fftsetup(setup) }
rpV.withUnsafeMutableBufferPointer { rp in ipV.withUnsafeMutableBufferPointer { ip in
guard let a = rp.baseAddress, let b = ip.baseAddress else { return }
var split: DSPSplitComplex = DSPSplitComplex(realp: a, imagp: b)
vDSP_fft_zrip(setup, &split, 1, log2n, FFTDirection(kFFTDirection_Forward))
} }
rpM.withUnsafeMutableBufferPointer { rp in ipM.withUnsafeMutableBufferPointer { ip in
workRe.withUnsafeMutableBufferPointer { wr in workIm.withUnsafeMutableBufferPointer { wi in
guard let a = rp.baseAddress, let b = ip.baseAddress, let c = wr.baseAddress, let d = wi.baseAddress else { return }
_lbRealFFTForward(a, b, half, c, d)
} }
} }
let tol: Float = 1e-2
for k: Int in 0..<half {
#expect(abs(rpM[k] - rpV[k]) <= tol, "fft realp[\(k)]: mine \(rpM[k]) vDSP \(rpV[k])")
#expect(abs(ipM[k] - ipV[k]) <= tol, "fft imagp[\(k)]: mine \(ipM[k]) vDSP \(ipV[k])")
}
}
@Test("real FFT forward→inverse matches vDSP (n=16)")
func fftRoundTrip() {
let log2n: vDSP_Length = 4
let n: Int = 16
let half: Int = n / 2
let r: [Float] = (0..<n).map { Float(cos(Double($0) * 0.5) - 0.2 * Double($0 % 3)) }
var rpV: [Float] = [Float](repeating: 0, count: half)
var ipV: [Float] = [Float](repeating: 0, count: half)
var rpM: [Float] = [Float](repeating: 0, count: half)
var ipM: [Float] = [Float](repeating: 0, count: half)
for j: Int in 0..<half {
rpV[j] = r[2 * j]; ipV[j] = r[2 * j + 1]
rpM[j] = r[2 * j]; ipM[j] = r[2 * j + 1]
}
var workRe: [Float] = [Float](repeating: 0, count: n)
var workIm: [Float] = [Float](repeating: 0, count: n)
guard let setup: FFTSetup = vDSP_create_fftsetup(log2n, FFTRadix(kFFTRadix2)) else {
Issue.record("create_fftsetup nil"); return
}
defer { vDSP_destroy_fftsetup(setup) }
rpV.withUnsafeMutableBufferPointer { rp in ipV.withUnsafeMutableBufferPointer { ip in
guard let a = rp.baseAddress, let b = ip.baseAddress else { return }
var split: DSPSplitComplex = DSPSplitComplex(realp: a, imagp: b)
vDSP_fft_zrip(setup, &split, 1, log2n, FFTDirection(kFFTDirection_Forward))
vDSP_fft_zrip(setup, &split, 1, log2n, FFTDirection(kFFTDirection_Inverse))
} }
rpM.withUnsafeMutableBufferPointer { rp in ipM.withUnsafeMutableBufferPointer { ip in
workRe.withUnsafeMutableBufferPointer { wr in workIm.withUnsafeMutableBufferPointer { wi in
guard let a = rp.baseAddress, let b = ip.baseAddress, let c = wr.baseAddress, let d = wi.baseAddress else { return }
_lbRealFFTForward(a, b, half, c, d)
_lbRealFFTInverse(a, b, half, c, d)
} }
} }
// Both should equal 2n × original (packed even/odd); compare to each other.
let tol: Float = 1e-1
for k: Int in 0..<half {
#expect(abs(rpM[k] - rpV[k]) <= tol, "roundtrip realp[\(k)]: mine \(rpM[k]) vDSP \(rpV[k])")
#expect(abs(ipM[k] - ipV[k]) <= tol, "roundtrip imagp[\(k)]: mine \(ipM[k]) vDSP \(ipV[k])")
}
}
@Test("input × ramp, with start mutation (vrampmul)")
func rampMul() {
let input: [Float] = (0..<Self.n).map { Float(sin(Double($0) * 0.3)) }
var startRef: Float = 0.25, startGot: Float = 0.25
var stepRef: Float = 0.03
let step: Float = 0.03
var ref: [Float] = [Float](repeating: 0, count: Self.n)
var got: [Float] = [Float](repeating: 0, count: Self.n)
input.withUnsafeBufferPointer { ip in
guard let iB = ip.baseAddress else { Issue.record("empty"); return }
ref.withUnsafeMutableBufferPointer { rp in
guard let rB = rp.baseAddress else { return }
vDSP_vrampmul(iB, 1, &startRef, &stepRef, rB, 1, vDSP_Length(Self.n))
}
got.withUnsafeMutableBufferPointer { gp in
guard let gB = gp.baseAddress else { return }
_lbRampMul(iB, 1, &startGot, step, gB, 1, Self.n)
}
}
for i: Int in 0..<Self.n { #expect(abs(got[i] - ref[i]) <= 1e-5) }
#expect(abs(startGot - startRef) <= 1e-5, "start mutation: mine \(startGot) vDSP \(startRef)")
}
@Test("Hann window matches vDSP (n=32)")
func hannWindow() {
let n: Int = 32
var ref: [Float] = [Float](repeating: 0, count: n)
var got: [Float] = [Float](repeating: 0, count: n)
ref.withUnsafeMutableBufferPointer { rp in
guard let rB = rp.baseAddress else { return }
vDSP_hann_window(rB, vDSP_Length(n), Int32(vDSP_HANN_DENORM))
}
got.withUnsafeMutableBufferPointer { gp in
guard let gB = gp.baseAddress else { return }
_lbHannWindow(gB, n)
}
for i: Int in 0..<n { #expect(abs(got[i] - ref[i]) <= 1e-6, "hann[\(i)]: mine \(got[i]) vDSP \(ref[i])") }
}
@Test("c[i] = start + i*step (vrampD)")
func vRamp() {
var start: Double = 0.3
var step: Double = 0.07
var ref: [Double] = [Double](repeating: 0, count: Self.n)
var got: [Double] = [Double](repeating: 0, count: Self.n)
vDSP_vrampD(&start, &step, &ref, 1, vDSP_Length(Self.n))
got.withUnsafeMutableBufferPointer { g in
guard let gBase: UnsafeMutablePointer<Double> = g.baseAddress else { Issue.record("empty"); return }
_lbVRamp(0.3, 0.07, gBase, 1, Self.n)
}
expectClose(got, ref, "vramp")
}
}
#endif
@@ -0,0 +1,156 @@
// ALSAAudioDriverTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// Linux-only: `ALSAAudioDriver` exists solely where libasound does. These tests
// run headless — a CI container has no sound device — so they cover the paths
// that must behave correctly *without* hardware: refusing to start unconfigured,
// failing cleanly on a device that cannot be opened, and surviving redundant
// stops. Their other job is to prove the driver was actually compiled into the
// module: if the CALSA dependency ever stops resolving, the whole file compiles
// away to nothing and everything else would still pass.
//
// Guarded on `canImport(CALSA)` rather than `os(Linux)` so the file tracks the
// driver's own condition exactly: a Linux build with `LYREBIRD_DISABLE_ALSA=1`
// has no driver, and an `os(Linux)` guard would leave these tests referencing a
// type that is not there.
#if canImport(CALSA)
import Testing
@_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("ALSAAudioDriver (headless)")
struct ALSAAudioDriverTests {
/// A name no ALSA configuration will resolve, so `snd_pcm_open` fails on
/// any machine — with or without a sound card.
private static let unopenableDevice: String = "lyrebird-nonexistent-pcm"
@Test func startWithoutSetupThrowsNotConfigured() {
let driver: ALSAAudioDriver = ALSAAudioDriver()
#expect(throws: ALSAError.notConfigured) {
try driver.start()
}
}
@Test func startOnUnopenableDeviceThrowsAndDoesNotRun() throws {
let driver: ALSAAudioDriver = ALSAAudioDriver()
driver.device = Self.unopenableDevice
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
driver: driver
)
try driver.setup(engine: engine)
var thrown: ALSAError?
do {
try driver.start()
} catch let error as ALSAError {
thrown = error
}
guard case .playbackDeviceOpenFailed(let device, _)? = thrown else {
Issue.record("expected playbackDeviceOpenFailed, got \(String(describing: thrown))")
return
}
#expect(device == Self.unopenableDevice)
#expect(driver.lastError == nil, "no render thread ran, so nothing should have failed inside one")
}
@Test func failedStartLeavesNoWedgedState() throws {
// A start that throws must not leave the running flag set or a device
// half-open, or every later start would fail for the wrong reason.
let driver: ALSAAudioDriver = ALSAAudioDriver()
driver.device = Self.unopenableDevice
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
driver: driver
)
try driver.setup(engine: engine)
for attempt: Int in 0..<3 {
var thrown: ALSAError?
do {
try driver.start()
} catch let error as ALSAError {
thrown = error
}
guard case .playbackDeviceOpenFailed? = thrown else {
Issue.record("attempt \(attempt): expected playbackDeviceOpenFailed, got \(String(describing: thrown))")
return
}
driver.stop()
}
}
@Test func engineRetainRoundTripBalances() throws {
// The render thread pins the engine with a retain handed over as a bit
// pattern, released by the loop's `defer`. Nothing hardware is involved
// in that balance, so pin it here rather than leaving it to run only on
// a real device: a missing release leaks the engine, a double release
// is a use-after-free.
weak var weakEngine: SynthesisEngine?
var bits: UInt = 0
do {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
driver: OfflineDriver()
)
weakEngine = engine
bits = ALSAAudioDriver.retainForRenderThread(Unmanaged.passUnretained(engine))
}
// The local strong reference is gone, but the render-thread retain is
// still holding the engine alive.
#expect(weakEngine != nil, "retainForRenderThread must keep the engine alive")
ALSAAudioDriver.releaseEngine(bits: bits)
#expect(weakEngine == nil, "releaseEngine must balance the retain exactly")
}
@Test func stallBudgetGivesUpOnlyAfterTheLimit() {
// The loop that consults this only runs against real hardware, so the
// boundary is pinned here: one attempt early kills a stream that was
// merely slow, one late means a wedged device spins forever at
// SCHED_FIFO.
#expect(ALSAAudioDriver.stallBudgetExhausted(consecutiveStalls: 1) == false)
#expect(ALSAAudioDriver.stallBudgetExhausted(
consecutiveStalls: ALSAAudioDriver.maxConsecutiveStalls) == false)
#expect(ALSAAudioDriver.stallBudgetExhausted(
consecutiveStalls: ALSAAudioDriver.maxConsecutiveStalls + 1) == true)
}
@Test func stopIsSafeBeforeStartAndWhenRepeated() {
let driver: ALSAAudioDriver = ALSAAudioDriver()
driver.stop()
driver.stop()
}
@Test func defaultsTargetTheUserConfiguredDevice() {
let driver: ALSAAudioDriver = ALSAAudioDriver()
// "default" honours ~/.asoundrc and dmix; addressing hw:N,M directly
// would lock out every other application on the machine.
#expect(driver.device == "default")
#expect(driver.captureDevice == "default")
#expect(driver.allowSoftwareResampling == false)
#expect(driver.linkedStreams == false)
#expect(driver.hasRealtimePriority == false)
}
@Test func suggestsTheSameControlBlockSizeAsOtherLiveDrivers() {
let driver: ALSAAudioDriver = ALSAAudioDriver()
#expect(driver.suggestedControlBlockSize == 64)
}
}
#endif
@@ -0,0 +1,93 @@
// ALSAMIDITests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// Linux-only: the ALSA-sequencer `MIDI` backend exists where CALSA does and
// CoreMIDI does not. These run headless — a CI container may or may not expose
// the kernel sequencer — so they cover the parts that need no controller: the
// handler registry, the not-started guards, and safe teardown, plus a tolerant
// start/stop that accepts either outcome. Receiving from real hardware is the
// deferred acceptance check (see LINUX_PLAN.md). The file also guards that the
// backend is actually compiled in: if CALSA stops resolving, it vanishes and
// every other test still passes.
#if !canImport(CoreMIDI) && canImport(CALSA)
import Testing
@_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("ALSA MIDI (headless)")
struct ALSAMIDITests {
private func makeEngine() -> SynthesisEngine {
SynthesisEngine(
blockSize: 64, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 0,
driver: OfflineDriver()
)
}
@Test func addHandlerReturnsDistinctTokensAndRemoveIsSafe() {
let midi: MIDI = MIDI(engine: makeEngine())
let a: MIDIHandlerToken = midi.addHandler(name: "a") { _, _ in }
let b: MIDIHandlerToken = midi.addHandler(name: "b") { _, _ in }
#expect(a != b)
midi.removeHandler(a)
midi.removeHandler(b)
midi.removeHandler(a) // removing twice is a no-op, not a crash
}
@Test func sendBeforeStartThrowsNotStarted() {
let midi: MIDI = MIDI(engine: makeEngine())
let dest: MIDIDestination = MIDIDestination(name: "x", client: 128, port: 0)
#expect(throws: MIDIError.notStarted) {
try midi.send(.noteOn(channel: 0, note: 60, velocity: 100), to: dest)
}
#expect(throws: MIDIError.notStarted) {
try midi.sendVirtual(.noteOn(channel: 0, note: 60, velocity: 100))
}
#expect(throws: MIDIError.notStarted) {
try midi.createVirtualOutput(name: "out")
}
}
@Test func stopBeforeStartAndRepeatedStopAreSafe() {
let midi: MIDI = MIDI(engine: makeEngine())
midi.stop()
midi.stop()
}
@Test func sourcesAreEmptyBeforeStart() {
let midi: MIDI = MIDI(engine: makeEngine())
#expect(midi.sources.isEmpty)
#expect(midi.destinations.isEmpty)
}
@Test func startThenStopEitherOpensOrFailsCleanly() {
// The kernel sequencer may be absent in a container. Success must leave
// a startable/stoppable client; failure must be a setup error, not a
// crash, and must leave the client re-startable.
let midi: MIDI = MIDI(engine: makeEngine())
do {
try midi.start()
// Opened: a second start is rejected, and stop tears down cleanly.
#expect(throws: MIDIError.alreadyStarted) { try midi.start() }
midi.stop()
// After a clean stop it can start again (or fail cleanly again).
do { try midi.start(); midi.stop() } catch is MIDIError {} catch { Issue.record("unexpected \(error)") }
} catch let error as MIDIError {
guard case .clientCreateFailed = error else {
Issue.record("expected clientCreateFailed when the sequencer is absent, got \(error)")
return
}
// A failed start must not have latched isStarted — retry is allowed.
#expect(throws: MIDIError.self) { try midi.start() }
} catch {
Issue.record("unexpected error type \(error)")
}
}
}
#endif
@@ -0,0 +1,47 @@
// ALSARecoveryActionTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import LyrebirdSynth
// The xrun policy decides whether the render loop recovers, retries, or dies.
// It is pure arithmetic over ALSA's return value, so it is tested on every
// platform even though the driver consuming it is Linux-only.
@Suite("ALSA transfer recovery policy")
struct ALSARecoveryActionTests {
@Test func successReportsFramesTransferred() {
#expect(ALSARecoveryAction.classify(512) == .transferred(frames: 512))
}
@Test func shortTransferIsStillSuccess() {
// A partial write is normal; the loop resumes from where it stopped.
#expect(ALSARecoveryAction.classify(37) == .transferred(frames: 37))
}
@Test func zeroFramesIsSuccessNotAnError() {
#expect(ALSARecoveryAction.classify(0) == .transferred(frames: 0))
}
@Test func signalInterruptionIsDistinctFromDeviceNotReady() {
// Kept apart on purpose: a signal is not a device fault, so it reissues
// immediately and must not spend the patience budget that a device
// which never becomes ready does.
#expect(ALSARecoveryAction.classify(-4) == .interrupted) // -EINTR
#expect(ALSARecoveryAction.classify(-11) == .wouldBlock) // -EAGAIN
}
@Test func underrunAndSuspendRecover() {
#expect(ALSARecoveryAction.classify(-32) == .recover) // -EPIPE (xrun)
#expect(ALSARecoveryAction.classify(-86) == .recover) // -ESTRPIPE (suspended)
}
@Test func unknownErrorIsFatal() {
#expect(ALSARecoveryAction.classify(-19) == .fail) // -ENODEV, device unplugged
#expect(ALSARecoveryAction.classify(-77) == .fail) // -EBADFD
}
}
@@ -0,0 +1,76 @@
// ALSASeqMIDIEventTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import LyrebirdSynth
// The seq-event → MIDIMessage mapping is the one piece of the Linux MIDI backend
// that carries real semantic decisions (note-on velocity 0 → note-off, the
// pitch-bend offset). It is pure Swift, so it is pinned here on every platform
// rather than only against a connected controller.
@Suite("ALSA sequencer MIDI mapping")
struct ALSASeqMIDIEventTests {
@Test func noteOnMaps() {
#expect(midiMessage(for: .noteOn(channel: 2, note: 60, velocity: 100))
== .noteOn(channel: 2, note: 60, velocity: 100))
}
@Test func noteOnWithZeroVelocityBecomesNoteOff() {
// The exact convention the CoreMIDI path applies, so a controller that
// sends note-on/vel-0 for note-off behaves the same on both platforms.
#expect(midiMessage(for: .noteOn(channel: 0, note: 64, velocity: 0))
== .noteOff(channel: 0, note: 64, velocity: 0))
}
@Test func noteOffMaps() {
#expect(midiMessage(for: .noteOff(channel: 9, note: 40, velocity: 20))
== .noteOff(channel: 9, note: 40, velocity: 20))
}
@Test func controllerMaps() {
#expect(midiMessage(for: .controller(channel: 1, param: 7, value: 127))
== .controlChange(channel: 1, controller: 7, value: 127))
}
@Test func programAndPressureMap() {
#expect(midiMessage(for: .programChange(channel: 3, program: 12))
== .programChange(channel: 3, program: 12))
#expect(midiMessage(for: .channelPressure(channel: 3, pressure: 55))
== .aftertouch(channel: 3, pressure: 55))
#expect(midiMessage(for: .keyPressure(channel: 3, note: 60, pressure: 44))
== .polyAftertouch(channel: 3, note: 60, pressure: 44))
}
@Test func pitchBendPreservesSignedValue() {
#expect(midiMessage(for: .pitchBend(channel: 0, value: 0))
== .pitchBend(channel: 0, value: 0))
#expect(midiMessage(for: .pitchBend(channel: 5, value: -8192))
== .pitchBend(channel: 5, value: -8192))
#expect(midiMessage(for: .pitchBend(channel: 5, value: 8191))
== .pitchBend(channel: 5, value: 8191))
}
@Test func pitchBendClampsOutOfRangeRatherThanWrapping() {
// An out-of-range value must saturate, not overflow the 14-bit field.
#expect(midiMessage(for: .pitchBend(channel: 0, value: 99999))
== .pitchBend(channel: 0, value: 8191))
#expect(midiMessage(for: .pitchBend(channel: 0, value: -99999))
== .pitchBend(channel: 0, value: -8192))
}
@Test func realtimeAndSysexMap() {
#expect(midiMessage(for: .clock) == .clock)
#expect(midiMessage(for: .start) == .start)
#expect(midiMessage(for: .continue) == .continue)
#expect(midiMessage(for: .stop) == .stop)
#expect(midiMessage(for: .activeSensing) == .activeSensing)
#expect(midiMessage(for: .reset) == .reset)
#expect(midiMessage(for: .sysex([0xF0, 0x7E, 0x7F, 0xF7]))
== .sysex([0xF0, 0x7E, 0x7F, 0xF7]))
}
}
@@ -0,0 +1,180 @@
// FilterGoldenValueTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@_spi(LyrebirdExtensions) import LyrebirdSynth
// Golden impulse responses for the filters that route their inner loop through
// the vector-math seam (`LyrebirdDSP`). On Apple that seam is real Accelerate;
// off Apple it is the portable scalar re-implementation, and nothing else
// verifies that the substitution produces the same *audio* — the parity suite
// in `LyrebirdDSPTests` compares against real vDSP and is therefore Apple-only.
//
// These goldens were captured on macOS (arm64, vDSP-backed). A packing error,
// a wrong scale factor, or a swapped operand (vDSP's `vsub`/`vdiv` take the
// second operand first — the classic way to get this wrong) moves these numbers
// far more than the tolerance allows.
//
// Regenerating: run the same graph on macOS and print `String(format: "%+.15e")`
// per sample. Only do that after establishing the change was intended — an
// unexplained golden drift is the bug this file exists to catch.
@MainActor
@Suite("Portable DSP golden values — filters")
struct FilterGoldenValueTests {
/// Impulse responses run O(1e-2) down to O(1e-5) across a response, so the
/// tolerance is written as a floor plus a proportional term: the floor
/// keeps the small tail samples from demanding impossible precision, and
/// the relative term carries the large ones. These are IIR filters whose
/// coefficients come from the platform's `tan`/`exp`, so a last-bit libm
/// difference compounds down the response — at 1e-7 relative, that has room
/// to breathe while still pinning ~7 significant digits.
private static let absoluteTolerance: Double = 1e-9
private static let relativeTolerance: Double = 1e-7
private static let goldenSampleCount: Int = 32
/// A single impulse at sample 0 (`Impulse` at 1 Hz does not repeat inside
/// one 64-sample block at 44.1 kHz).
private func impulse() -> Impulse.Audio {
Impulse.Audio(freq: 1.0)
}
// MARK: - Butterworth cascade (vDSP_biquadD opaque-setup path)
@Test func butterworthLowPassOrder4ImpulseResponse() throws {
let engine: SynthesisEngine = makePortableTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
defer { engine.stop() }
let filter: ButterworthLowPass.Audio = ButterworthLowPass.Audio(
input: impulse(),
freq: 1000.0,
order: 4
)
let out: [Double] = collectPortableBlocks(filter, engine: engine, blocks: 1)
let golden: [Double] = [
+2.152095121410931e-05, +1.641584629441634e-04, +6.181119607743385e-04,
+1.580531666013951e-03, +3.174639459072925e-03, +5.440148926700136e-03,
+8.352290048424874e-03, +1.183836980297112e-02, +1.579203946268454e-02,
+2.008543829951385e-02, +2.457938189196052e-02, +2.913176110580052e-02,
+3.360431504564020e-02, +3.786793778308615e-02, +4.180667442658070e-02,
+4.532055709715214e-02, +4.832742562570271e-02, +5.076387132477716e-02,
+5.258543506425273e-02, +5.376618316618124e-02, +5.429777641318197e-02,
+5.418813883228489e-02, +5.345982397463169e-02, +5.214816726824802e-02,
+5.029930378515230e-02, +4.796812154322546e-02, +4.521621136182290e-02,
+4.210986540661170e-02, +3.871816798451624e-02, +3.511121396581181e-02,
+3.135848248891489e-02, +2.752738640479642e-02,
]
#expect(golden.count == Self.goldenSampleCount)
expectMatchesGolden(out, golden, absolute: Self.absoluteTolerance,
relative: Self.relativeTolerance, "ButterworthLowPass order 4 @ 1 kHz")
}
@Test func butterworthHighPassOrder2ImpulseResponse() throws {
let engine: SynthesisEngine = makePortableTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
defer { engine.stop() }
let filter: ButterworthHighPass.Audio = ButterworthHighPass.Audio(
input: impulse(),
freq: 2000.0,
order: 2
)
let out: [Double] = collectPortableBlocks(filter, engine: engine, blocks: 1)
let golden: [Double] = [
+8.173653471988668e-01, -3.260532537283749e-01, -2.509776927823263e-01,
-1.839145896391800e-01, -1.267185424557680e-01, -7.996528515637492e-02,
-4.333706504275574e-02, -1.594032798238100e-02, +3.443212698672361e-03,
+1.616692265076786e-02, +2.358340028385290e-02, +2.695373298540346e-02,
+2.739300334053809e-02, +2.584368988589170e-02, +2.306950121182690e-02,
+1.966328190177202e-02, +1.606379176647005e-02, +1.257728686358794e-02,
+9.400857984146530e-03, +6.645373641256291e-03, +4.356615194170972e-03,
+2.533781752345395e-03, +1.144992174962703e-03, +1.397371003516062e-04,
-5.415452602600245e-04, -9.604599425804916e-04, -1.175833047846857e-03,
-1.240675703549870e-03, -1.200546080581319e-03, -1.092956025864731e-03,
-9.475158033258457e-04, -7.865624259116227e-04,
]
#expect(golden.count == Self.goldenSampleCount)
expectMatchesGolden(out, golden, absolute: Self.absoluteTolerance,
relative: Self.relativeTolerance, "ButterworthHighPass order 2 @ 2 kHz")
}
// MARK: - Resonator banks (vDSP vector kernel: vsmulD / vmulD / vsubD / sveD)
@Test func klankImpulseResponse() throws {
let engine: SynthesisEngine = makePortableTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
defer { engine.stop() }
// Two modes: (freq, amp, decay).
let spec: LyrebirdBuffer = LyrebirdBuffer(count: 2, channelCount: klankSpecChannelCount)
spec.setValue(440.0, frame: 0, channel: klankFreqChannel)
spec.setValue(1.0, frame: 0, channel: klankAmpChannel)
spec.setValue(0.5, frame: 0, channel: klankDecayChannel)
spec.setValue(1320.0, frame: 1, channel: klankFreqChannel)
spec.setValue(0.7, frame: 1, channel: klankAmpChannel)
spec.setValue(0.25, frame: 1, channel: klankDecayChannel)
let bank: Klank.Audio = Klank.Audio(input: impulse(), buffer: spec)
let out: [Double] = collectPortableBlocks(bank, engine: engine, blocks: 1)
let golden: [Double] = [
+7.516780834059488e-04, +1.485928026159716e-03, +2.186657458347529e-03,
+2.838891794961642e-03, +3.429262631979223e-03, +3.946439424747222e-03,
+4.381489452541366e-03, +4.728153616775348e-03, +4.983028599068313e-03,
+5.145649213721204e-03, +5.218468310109081e-03, +5.206735189726312e-03,
+5.118277072830178e-03, +4.963191555058374e-03, +4.753461115256087e-03,
+4.502503462429247e-03, +4.224673746663460e-03, +3.934736327817053e-03,
+3.647324838731323e-03, +3.376409660659641e-03, +3.134791635034020e-03,
+2.933639878788013e-03, +2.782089984828247e-03, +2.686916731598987e-03,
+2.652292772810991e-03, +2.679641724461021e-03, +2.767590719423414e-03,
+2.912023978509201e-03, +3.106235375324165e-03, +3.341174476490087e-03,
+3.605777241969424e-03, +3.887369588332656e-03,
]
#expect(golden.count == Self.goldenSampleCount)
expectMatchesGolden(out, golden, absolute: Self.absoluteTolerance,
relative: Self.relativeTolerance, "Klank 440/1320 Hz")
}
@Test func resonatorBankImpulseResponse() throws {
let engine: SynthesisEngine = makePortableTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
defer { engine.stop() }
// Two resonators: (freq, decay, amp) — note the channel order differs
// from Klank's, which is exactly the kind of thing a golden pins down.
let spec: LyrebirdBuffer = LyrebirdBuffer(count: 2, channelCount: resonatorBankChannelCount)
spec.setValue(300.0, frame: 0, channel: resonatorBankFreqChannel)
spec.setValue(0.4, frame: 0, channel: resonatorBankDecayChannel)
spec.setValue(1.0, frame: 0, channel: resonatorBankAmpChannel)
spec.setValue(900.0, frame: 1, channel: resonatorBankFreqChannel)
spec.setValue(0.2, frame: 1, channel: resonatorBankDecayChannel)
spec.setValue(0.5, frame: 1, channel: resonatorBankAmpChannel)
let bank: ResonatorBank.Audio = ResonatorBank.Audio(input: impulse(), buffer: spec)
let out: [Double] = collectPortableBlocks(bank, engine: engine, blocks: 1)
let golden: [Double] = [
+7.829622372711453e-04, +1.557867646906840e-03, +2.317707696839478e-03,
+3.055706174578748e-03, +3.765419676725673e-03, +4.440832554694747e-03,
+5.076444786145945e-03, +5.667351359912787e-03, +6.209311903449615e-03,
+6.698809443657687e-03, +7.133097371698757e-03, +7.510233877089432e-03,
+7.829103322772969e-03, +8.089424247582720e-03, +8.291743902008049e-03,
+8.437419443840962e-03, +8.528586138498235e-03, +8.568113121003890e-03,
+8.559547479309104e-03, +8.507047608511223e-03, +8.415306959516080e-03,
+8.289469460939336e-03, +8.135038027046442e-03, +7.957777675122603e-03,
+7.763614861067067e-03, +7.558534700859674e-03, +7.348477776928855e-03,
+7.139238231888766e-03, +6.936364827597349e-03, +6.745066595464517e-03,
+6.570124625307941e-03, +6.415811436146689e-03,
]
#expect(golden.count == Self.goldenSampleCount)
expectMatchesGolden(out, golden, absolute: Self.absoluteTolerance,
relative: Self.relativeTolerance, "ResonatorBank 300/900 Hz")
}
}
@@ -0,0 +1,87 @@
// InterleaveHelpersTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@_spi(LyrebirdExtensions) import LyrebirdSynth
// Planar↔interleaved conversion is the part of a hardware driver that fails
// quietly: a transposed index produces channel-swapped or aliased audio rather
// than an error, and on a headless CI box nobody hears it. These run everywhere.
@Suite("Driver channel interleaving")
struct InterleaveHelpersTests {
private func interleaved(
_ buses: [[Float]],
frameCount: Int,
channelCount: Int
) -> [Float] {
var out: [Float] = [Float](repeating: .nan, count: frameCount * channelCount)
out.withUnsafeMutableBufferPointer { dst in
guard let base: UnsafeMutablePointer<Float> = dst.baseAddress else { return }
lyrebirdInterleave(buses, into: base, frameCount: frameCount, channelCount: channelCount)
}
return out
}
@Test func interleavesStereoInFrameOrder() {
let buses: [[Float]] = [
[1, 2, 3],
[-1, -2, -3],
]
let out: [Float] = interleaved(buses, frameCount: 3, channelCount: 2)
#expect(out == [1, -1, 2, -2, 3, -3])
}
@Test func missingChannelIsWrittenAsSilence() {
// Engine configured for more output channels than buses provided.
let buses: [[Float]] = [[1, 2]]
let out: [Float] = interleaved(buses, frameCount: 2, channelCount: 3)
#expect(out == [1, 0, 0, 2, 0, 0])
}
@Test func shortBusIsPaddedWithSilence() {
let buses: [[Float]] = [
[1, 2],
[-1, -2, -3, -4],
]
// Channel 0 runs out after two frames; the rest of its frames are
// silence while channel 1 keeps playing.
let out: [Float] = interleaved(buses, frameCount: 4, channelCount: 2)
#expect(out == [1, -1, 2, -2, 0, -3, 0, -4])
}
@Test func deinterleaveIsTheInverseOfInterleave() {
let frameCount: Int = 5
let channelCount: Int = 3
let original: [[Float]] = (0..<channelCount).map { channel in
(0..<frameCount).map { Float(channel * 100 + $0) }
}
let packed: [Float] = interleaved(original, frameCount: frameCount, channelCount: channelCount)
var recovered: [[Float]] = [[Float]](
repeating: [Float](repeating: 0, count: frameCount),
count: channelCount
)
packed.withUnsafeBufferPointer { src in
guard let base: UnsafePointer<Float> = src.baseAddress else { return }
lyrebirdDeinterleave(base, into: &recovered, frameCount: frameCount, channelCount: channelCount)
}
#expect(recovered == original)
}
@Test func deinterleaveIgnoresChannelsWithNoDestinationBus() {
// Two channels arriving, one staging bus: the extra channel is dropped
// rather than overrunning the array.
let packed: [Float] = [1, -1, 2, -2]
var buses: [[Float]] = [[Float](repeating: 0, count: 2)]
packed.withUnsafeBufferPointer { src in
guard let base: UnsafePointer<Float> = src.baseAddress else { return }
lyrebirdDeinterleave(base, into: &buses, frameCount: 2, channelCount: 2)
}
#expect(buses == [[1, 2]])
}
}
@@ -0,0 +1,279 @@
// OSCLoopbackTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@_spi(LyrebirdExtensions) import LyrebirdSynth
#if canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#endif
// End-to-end OSC over real UDP loopback: an `OSCServer` bound to 127.0.0.1 and an
// `OSCClient` sending to it. On Apple this drives `Network.framework`; off Apple
// it drives the POSIX-socket transport added for Linux — and, unlike the MIDI and
// audio backends, needs no hardware, so it runs everywhere and is the actual
// acceptance check for OSC on Linux.
@MainActor
@Suite("OSC UDP loopback")
struct OSCLoopbackTests {
private func makeEngine() -> SynthesisEngine {
SynthesisEngine(
blockSize: 64, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 0,
driver: OfflineDriver()
)
}
/// Bind a server on some free port in a high range, retrying past a port
/// already in use. Returns the started server and its port.
private func startServer(
_ engine: SynthesisEngine,
configure: (OSCServer) -> Void
) throws -> OSCServer {
var lastError: (any Error)?
for candidate: UInt16 in stride(from: UInt16(9800), through: UInt16(9840), by: 1) {
let server: OSCServer = OSCServer(port: candidate, engine: engine)
configure(server)
do {
try server.start()
return server
} catch {
lastError = error // port in use — try the next
}
}
throw lastError ?? OSCTestError.noFreePort
}
private enum OSCTestError: Error { case noFreePort }
/// Fire the client repeatedly until the handler signals or the deadline
/// passes — covers both the listener-not-yet-ready startup race and UDP's
/// own permission to drop a datagram.
private func waitForDelivery(
send: () -> Void,
arrived: DispatchSemaphore,
timeout: TimeInterval = 3.0
) -> Bool {
let deadline: Date = Date(timeIntervalSinceNow: timeout)
while Date() < deadline {
send()
if arrived.wait(timeout: .now() + 0.05) == .success { return true }
}
return false
}
@Test func messageRoundTripsWithArguments() throws {
let engine: SynthesisEngine = makeEngine()
let arrived: DispatchSemaphore = DispatchSemaphore(value: 0)
let received: LockedBox = LockedBox()
let server: OSCServer = try startServer(engine) { s in
s.addHandler(address: "/synth/freq") { msg, _ in
received.set(address: msg.address,
int: msg[0]?.intValue,
float: msg[1]?.floatValue,
string: msg[2]?.stringValue)
arrived.signal()
}
}
defer { server.stop() }
let client: OSCClient = OSCClient(host: "127.0.0.1", port: server.port)
let delivered: Bool = waitForDelivery(
send: {
client.send(address: "/synth/freq",
args: [.int32(440), .float32(1.5), .string("hi")])
},
arrived: arrived
)
#expect(delivered, "the message never arrived over loopback")
#expect(received.address == "/synth/freq")
#expect(received.int == 440)
#expect(received.float == 1.5)
#expect(received.string == "hi")
}
@Test func patternAddressMatchesOnDelivery() throws {
let engine: SynthesisEngine = makeEngine()
let arrived: DispatchSemaphore = DispatchSemaphore(value: 0)
let hitCount: LockedCounter = LockedCounter()
let server: OSCServer = try startServer(engine) { s in
// Glob pattern: should match "/synth/cutoff".
s.addHandler(address: "/synth/*") { _, _ in
hitCount.increment()
arrived.signal()
}
}
defer { server.stop() }
let client: OSCClient = OSCClient(host: "127.0.0.1", port: server.port)
let delivered: Bool = waitForDelivery(
send: { client.send(address: "/synth/cutoff", args: [.float32(0.5)]) },
arrived: arrived
)
#expect(delivered, "the wildcard handler never fired")
#expect(hitCount.value >= 1)
}
@Test func removedHandlerStopsReceiving() throws {
let engine: SynthesisEngine = makeEngine()
let arrived: DispatchSemaphore = DispatchSemaphore(value: 0)
let hits: LockedCounter = LockedCounter()
var token: OSCHandlerToken?
let server: OSCServer = try startServer(engine) { s in
token = s.addHandler(address: "/x") { _, _ in
hits.increment()
arrived.signal()
}
}
defer { server.stop() }
// Confirm the handler works, then remove it and confirm silence.
let client: OSCClient = OSCClient(host: "127.0.0.1", port: server.port)
#expect(waitForDelivery(send: { client.send(address: "/x") }, arrived: arrived),
"handler should fire before removal")
if let token: OSCHandlerToken = token { server.removeHandler(token) }
let countAfterRemoval: Int = hits.value
// Send several more; none should reach the removed handler.
for _ in 0..<10 { client.send(address: "/x") }
Thread.sleep(forTimeInterval: 0.3)
#expect(hits.value == countAfterRemoval, "a removed handler must not keep receiving")
}
// The POSIX receive loop must survive a zero-length UDP datagram — a valid
// packet any peer can send. The bug this guards (recv==0 treated as a close,
// killing the listener) lived only in the non-Network transport, so the test
// does too. On Apple the empty datagram is filtered by the `!data.isEmpty`
// guard in the NWListener path.
#if !canImport(Network)
@Test func emptyDatagramDoesNotKillListener() throws {
let engine: SynthesisEngine = makeEngine()
let arrived: DispatchSemaphore = DispatchSemaphore(value: 0)
let server: OSCServer = try startServer(engine) { s in
s.addHandler(address: "/ping") { _, _ in arrived.signal() }
}
defer { server.stop() }
// Fire a raw zero-length datagram straight at the port.
let raw: Int32 = socket(AF_INET, Int32(SOCK_DGRAM.rawValue), 0)
#expect(raw >= 0)
if raw >= 0 {
var addr: sockaddr_in = sockaddr_in()
addr.sin_family = sa_family_t(AF_INET)
addr.sin_port = server.port.bigEndian
_ = inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr)
_ = withUnsafePointer(to: &addr) { ptr in
ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { sa in
connect(raw, sa, socklen_t(MemoryLayout<sockaddr_in>.size))
}
}
// A couple of empty datagrams — the old code broke on the first.
for _ in 0..<3 { _ = sendto(raw, nil, 0, Int32(MSG_NOSIGNAL), nil, 0) }
close(raw)
}
// The listener must still be alive: a normal message gets through.
let client: OSCClient = OSCClient(host: "127.0.0.1", port: server.port)
let delivered: Bool = waitForDelivery(
send: { client.send(address: "/ping") },
arrived: arrived
)
#expect(delivered, "an empty datagram killed the listener")
}
#endif
@Test func doubleStartIsIdempotent() throws {
// Calling start() on an already-started server returns without binding a
// second socket or launching a second thread, and the server keeps
// working. On Apple this is NWListener's duplicate-cancel; off Apple it
// is the atomic `isStarted` claim.
let engine: SynthesisEngine = makeEngine()
let arrived: DispatchSemaphore = DispatchSemaphore(value: 0)
let server: OSCServer = try startServer(engine) { s in
s.addHandler(address: "/twice") { _, _ in arrived.signal() }
}
defer { server.stop() }
try server.start() // second start — must be a clean no-op
try server.start() // and a third
let client: OSCClient = OSCClient(host: "127.0.0.1", port: server.port)
#expect(waitForDelivery(send: { client.send(address: "/twice") }, arrived: arrived),
"server should still deliver after redundant start() calls")
}
// Linux-only: the atomic `isStarted` claim being hardened lives in the POSIX
// branch. On Apple, `NWListener` reports a bind failure asynchronously, so a
// fixed-port concurrent-start test cannot assert deterministically there —
// and that path was already duplicate-safe via NWListener's own cancel.
#if !canImport(Network)
@Test func concurrentStartsAreSerializedByTheClaim() throws {
// Start the server on a known-free port, then fire many start() calls at
// it concurrently. Each must return cleanly (the claim sees `isStarted`
// already set) — no second bind, no second thread, no crash — and the
// server must keep delivering.
let engine: SynthesisEngine = makeEngine()
let arrived: DispatchSemaphore = DispatchSemaphore(value: 0)
let server: OSCServer = try startServer(engine) { s in
s.addHandler(address: "/race") { _, _ in arrived.signal() }
}
defer { server.stop() }
let group: DispatchGroup = DispatchGroup()
let failures: LockedCounter = LockedCounter()
for _ in 0..<8 {
DispatchQueue.global().async(group: group) {
do { try server.start() } catch { failures.increment() }
}
}
group.wait()
#expect(failures.value == 0, "\(failures.value) redundant concurrent start()s threw")
let client: OSCClient = OSCClient(host: "127.0.0.1", port: server.port)
#expect(waitForDelivery(send: { client.send(address: "/race") }, arrived: arrived),
"server should still deliver after concurrent start() calls")
}
#endif
@Test func stopIsIdempotentAndSafeBeforeStart() {
let server: OSCServer = OSCServer(port: 9899, engine: makeEngine())
server.stop()
server.stop()
}
}
// MARK: - Small thread-safe test boxes
private final class LockedBox: @unchecked Sendable {
private let lock: NSLock = NSLock()
private var _address: String?
private var _int: Int32?
private var _float: Float?
private var _string: String?
func set(address: String?, int: Int32?, float: Float?, string: String?) {
lock.withLock { _address = address; _int = int; _float = float; _string = string }
}
var address: String? { lock.withLock { _address } }
var int: Int32? { lock.withLock { _int } }
var float: Float? { lock.withLock { _float } }
var string: String? { lock.withLock { _string } }
}
private final class LockedCounter: @unchecked Sendable {
private let lock: NSLock = NSLock()
private var _value: Int = 0
func increment() { lock.withLock { _value += 1 } }
var value: Int { lock.withLock { _value } }
}
@@ -0,0 +1,264 @@
// PortableFileIOTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@_spi(LyrebirdExtensions) import LyrebirdSynth
// Exercises the off-Apple file-I/O paths — `LyrebirdBuffer.load` / `loadAllChannels`
// / `fill` / `write` and `DiskIn.Audio` — through the portable `WavFileWriter` /
// `WavFileReader` backend. Fixtures are written with `WavFileWriter` (portable,
// both platforms) so these run everywhere, unlike the AudioToolbox-based
// `LyrebirdBufferFileIOTests` in the macOS-only suite. On Apple these same paths
// go through `ExtAudioFile`; a round trip that agrees on both is the point.
@Suite("Portable file I/O — LyrebirdBuffer")
struct PortableBufferFileIOTests {
private func tempURL() -> URL {
FileManager.default.temporaryDirectory
.appendingPathComponent("lyrebird-fileio-\(UUID().uuidString).wav")
}
/// Distinct, in-range value for (frame, channel) so a transposed read shows up.
private func sample(frame: Int, channel: Int) -> Float {
Float((sin(Double(frame) * 0.02 + Double(channel) * 1.3)) * 0.6)
}
private func writeWAV(frames: Int, channels: Int, sampleRate: Double = 44100) throws -> URL {
let url: URL = tempURL()
var interleaved: [Float] = [Float](repeating: 0, count: frames * channels)
for f: Int in 0..<frames {
for c: Int in 0..<channels {
interleaved[f * channels + c] = sample(frame: f, channel: c)
}
}
let writer: WavFileWriter = try WavFileWriter(
url: url, channels: channels, sampleRate: sampleRate, encoding: .float32
)
try writer.write(interleaved: interleaved, frames: frames)
try writer.finalize()
return url
}
@Test func loadMonoRoundTrips() throws {
let frames: Int = 500
let url: URL = try writeWAV(frames: frames, channels: 1)
defer { try? FileManager.default.removeItem(at: url) }
let buffer: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
#expect(buffer.count == frames)
#expect(buffer.channelCount == 1)
for f: Int in 0..<frames {
#expect(abs(buffer[f, 0] - Double(sample(frame: f, channel: 0))) < 1e-6, "frame \(f)")
}
}
@Test func loadAllChannelsRoundTrips() throws {
let frames: Int = 400
let channels: Int = 2
let url: URL = try writeWAV(frames: frames, channels: channels)
defer { try? FileManager.default.removeItem(at: url) }
let buffer: LyrebirdBuffer = try LyrebirdBuffer.loadAllChannels(url: url)
#expect(buffer.count == frames)
#expect(buffer.channelCount == channels)
for f: Int in 0..<frames {
for c: Int in 0..<channels {
#expect(abs(buffer[f, c] - Double(sample(frame: f, channel: c))) < 1e-6,
"frame \(f) channel \(c)")
}
}
}
@Test func loadSelectsTheRequestedChannel() throws {
let frames: Int = 300
let url: URL = try writeWAV(frames: frames, channels: 2)
defer { try? FileManager.default.removeItem(at: url) }
let right: LyrebirdBuffer = try LyrebirdBuffer.load(url: url, channel: 1)
for f: Int in 0..<frames {
#expect(abs(right[f, 0] - Double(sample(frame: f, channel: 1))) < 1e-6, "frame \(f)")
}
}
@Test func loadChannelOutOfRangeThrows() throws {
let url: URL = try writeWAV(frames: 100, channels: 1)
defer { try? FileManager.default.removeItem(at: url) }
#expect(throws: LyrebirdBufferIOError.channelOutOfRange(requested: 1, available: 1)) {
_ = try LyrebirdBuffer.load(url: url, channel: 1)
}
}
@Test func fillTruncatesLongerFileAndPadsShorterFile() throws {
let fileFrames: Int = 200
let url: URL = try writeWAV(frames: fileFrames, channels: 1)
defer { try? FileManager.default.removeItem(at: url) }
// Buffer shorter than the file: read stops at the buffer's length.
let short: LyrebirdBuffer = LyrebirdBuffer(count: 120)
try short.fill(fromFile: url)
for f: Int in 0..<120 {
#expect(abs(short[f, 0] - Double(sample(frame: f, channel: 0))) < 1e-6, "short \(f)")
}
// Buffer longer than the file: the tail is zero-padded.
let long: LyrebirdBuffer = LyrebirdBuffer(count: 260)
try long.fill(fromFile: url)
for f: Int in 0..<fileFrames {
#expect(abs(long[f, 0] - Double(sample(frame: f, channel: 0))) < 1e-6, "long \(f)")
}
for f: Int in fileFrames..<260 {
#expect(long[f, 0] == 0, "pad \(f)")
}
}
@Test func loadNormalisesToUnitPeak() throws {
// A quiet file: the loudest sample is well under 1. Normalising must
// scale the peak to ±1 while preserving the waveform shape.
let frames: Int = 256
let url: URL = tempURL()
defer { try? FileManager.default.removeItem(at: url) }
var interleaved: [Float] = [Float](repeating: 0, count: frames)
for f: Int in 0..<frames { interleaved[f] = Float(sin(Double(f) * 0.05)) * 0.25 }
let writer: WavFileWriter = try WavFileWriter(url: url, channels: 1, sampleRate: 44100, encoding: .float32)
try writer.write(interleaved: interleaved, frames: frames)
try writer.finalize()
let buffer: LyrebirdBuffer = try LyrebirdBuffer.load(url: url, normalise: true)
var peak: Double = 0
for f: Int in 0..<frames { peak = max(peak, abs(buffer[f, 0])) }
#expect(abs(peak - 1.0) < 1e-5, "normalised peak \(peak) should be ~1")
}
@Test func writeThenLoadRoundTripsInt16() throws {
let frames: Int = 400
let url: URL = tempURL()
defer { try? FileManager.default.removeItem(at: url) }
let source: LyrebirdBuffer = LyrebirdBuffer(count: frames)
for f: Int in 0..<frames { source.setValue(Double(sample(frame: f, channel: 0)), frame: f, channel: 0) }
try source.write(to: url, format: .wavInt16, sampleRate: 44100)
let reloaded: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
#expect(reloaded.count == frames)
for f: Int in 0..<frames {
// 16-bit quantisation: one step is ~3e-5 of full scale.
#expect(abs(reloaded[f, 0] - source[f, 0]) < 1e-4, "frame \(f)")
}
}
#if !canImport(AudioToolbox)
@Test func writeToAppleOnlyContainerThrowsOffApple() throws {
let url: URL = tempURL()
defer { try? FileManager.default.removeItem(at: url) }
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: 16)
// CAF has no portable encoder; the WAV encodings do.
#expect(throws: LyrebirdBufferIOError.unsupportedFormatOnPlatform(.cafFloat32)) {
try buffer.write(to: url, format: .cafFloat32)
}
}
#endif
}
@Suite("Portable file I/O — DiskIn")
struct PortableDiskInTests {
private func tempURL() -> URL {
FileManager.default.temporaryDirectory
.appendingPathComponent("lyrebird-diskin-\(UUID().uuidString).wav")
}
private func ramp(frame: Int, channel: Int) -> Float {
Float(sin(Double(frame) * 0.013 + Double(channel))) * 0.5
}
private func writeWAV(frames: Int, channels: Int, sampleRate: Double) throws -> URL {
let url: URL = tempURL()
var interleaved: [Float] = [Float](repeating: 0, count: frames * channels)
for f: Int in 0..<frames {
for c: Int in 0..<channels { interleaved[f * channels + c] = ramp(frame: f, channel: c) }
}
let writer: WavFileWriter = try WavFileWriter(
url: url, channels: channels, sampleRate: sampleRate, encoding: .float32
)
try writer.write(interleaved: interleaved, frames: frames)
try writer.finalize()
return url
}
@Test func streamsFileAtMatchingRateSampleAccurate() throws {
// Engine rate == file rate → the read-rate scale is 1, and at play rate
// 1.0 the read position lands on integer frames, so the streamed output
// is the file's channel-0 samples exactly (no interpolation error).
let sampleRate: Double = 44100
let fileFrames: Int = 4000
let url: URL = try writeWAV(frames: fileFrames, channels: 2, sampleRate: sampleRate)
defer { try? FileManager.default.removeItem(at: url) }
let engine: SynthesisEngine = makePortableTestEngine(blockSize: 64, sampleRate: sampleRate)
try engine.start()
defer { engine.stop() }
let player: DiskIn.Audio = try DiskIn.Audio(
url: url, channelCount: 2, sampleRate: sampleRate, rate: 1.0
)
// 40 blocks × 64 = 2560 samples, all inside the first (synchronously
// filled) half — deterministic, no background-refill dependency.
let out: [Double] = collectPortableBlocks(player, engine: engine, blocks: 40, channel: 0)
for i: Int in 0..<out.count {
#expect(abs(out[i] - Double(ramp(frame: i, channel: 0))) < 1e-6, "sample \(i)")
}
}
// Portable-only: on Apple `ExtAudioFile` performs the sample-rate
// conversion inside `DiskIn`, so the read position advances at rate 1 and
// the exact frame mapping below does not hold. Rate-ratio folding is a
// property of the portable backend, so this test tracks that backend's guard.
#if !canImport(AudioToolbox)
@Test func foldsSampleRateRatioIntoPlaybackSpeed() throws {
// File at half the engine rate: the portable read-rate scale is 0.5, so
// the read position advances half a frame per output sample. Output
// sample 2k then lands on file frame k (integer, no interpolation error).
let fileRate: Double = 22050
let engineRate: Double = 44100
let fileFrames: Int = 3000
let url: URL = try writeWAV(frames: fileFrames, channels: 1, sampleRate: fileRate)
defer { try? FileManager.default.removeItem(at: url) }
let engine: SynthesisEngine = makePortableTestEngine(blockSize: 64, sampleRate: engineRate)
try engine.start()
defer { engine.stop() }
let player: DiskIn.Audio = try DiskIn.Audio(
url: url, channelCount: 1, sampleRate: engineRate, rate: 1.0
)
let out: [Double] = collectPortableBlocks(player, engine: engine, blocks: 30, channel: 0)
// The read position lands on integer file frames at every even output
// sample; agreement is to Float round-trip precision (the fixture and
// the stream both pass through 32-bit samples), which is looser than
// the sample-accurate matching-rate case above.
var k: Int = 0
while k * 2 < out.count {
#expect(abs(out[k * 2] - Double(ramp(frame: k, channel: 0))) < 1e-5, "even sample \(k * 2)")
k += 1
}
// And it is genuinely slower: output well past the file's own frame
// count is still inside the file, because playback consumes half a file
// frame per output sample.
#expect(out.count > fileFrames / 2)
}
#endif
@Test func nonWavFileThrows() throws {
let url: URL = tempURL()
defer { try? FileManager.default.removeItem(at: url) }
try Data([0, 1, 2, 3, 4, 5, 6, 7]).write(to: url)
#expect(throws: (any Error).self) {
_ = try DiskIn.Audio(url: url, channelCount: 1, sampleRate: 44100)
}
}
}
@@ -0,0 +1,76 @@
// PortableTestSupport.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@_spi(LyrebirdExtensions) import LyrebirdSynth
// Local copies of the engine/collect helpers used by `LyrebirdTests`. SwiftPM
// test targets cannot share sources, and this target is deliberately limited to
// the public (+ extension-SPI) surface — part of what is being proven is that
// the portable surface is reachable and correct off Apple.
/// Offline engine for deterministic block-by-block generator evaluation.
func makePortableTestEngine(
blockSize: Int = 64,
sampleRate: Double = 44100
) -> SynthesisEngine {
SynthesisEngine(
blockSize: blockSize,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 2,
driver: OfflineDriver()
)
}
/// Drive a generator for `blocks` blocks and return `blockSize` samples per block.
func collectPortableBlocks(
_ gen: any Generator,
engine: SynthesisEngine,
blocks: Int,
channel: Int = 0
) -> [Double] {
let bs: Int = engine.blockSize
var out: [Double] = []
out.reserveCapacity(blocks * bs)
for _ in 0..<blocks {
let g: SynthGraph = SynthGraph(engine: engine)
let block: [Double] = gen.calculatedSamples(graph: g, count: bs)[channel]
out += block.prefix(bs)
engine.advanceSegmentSerial()
}
return out
}
/// Per-sample comparison against a recorded golden vector.
///
/// Goldens are captured on Apple (vDSP-backed, known good). Off Apple the same
/// maths runs through the portable scalar cores in `LyrebirdDSP`, and on any
/// platform the compiler is free to contract multiplies and adds differently,
/// so agreement is to a tolerance rather than bit-exact. The tolerance is
/// `absolute + relative * |golden|` — tight enough that a packing, scaling or
/// operand-order error cannot pass, loose enough to survive
/// last-bit rounding differences between implementations and architectures.
func expectMatchesGolden(
_ actual: [Double],
_ golden: [Double],
absolute: Double,
relative: Double = 0,
_ label: String,
sourceLocation: SourceLocation = #_sourceLocation
) {
#expect(actual.count >= golden.count,
"\(label): produced \(actual.count) samples, golden has \(golden.count)",
sourceLocation: sourceLocation)
guard actual.count >= golden.count else { return }
for i: Int in 0..<golden.count {
let tol: Double = absolute + relative * abs(golden[i])
let diff: Double = abs(actual[i] - golden[i])
#expect(diff <= tol,
"\(label): index \(i) actual=\(actual[i]) golden=\(golden[i]) diff=\(diff) tol=\(tol)",
sourceLocation: sourceLocation)
}
}
@@ -0,0 +1,145 @@
// SpectralGoldenValueTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@_spi(LyrebirdExtensions) import LyrebirdSynth
// Golden values for the real-FFT path through `SpectralChain` — the only place
// the portable `vDSP_fft_zrip` / `vDSP_ctoz` / `vDSP_ztoc` replacements are
// exercised as *audio* rather than as isolated primitives.
//
// Two directions are pinned:
// • forward — the analysis magnitude spectrum of a bin-centred sine, which
// depends on the split-complex packing (DC and Nyquist share one complex
// slot) and on vDSP's factor-of-two real-FFT scaling. Get either wrong and
// the peak lands in the wrong bin or at the wrong height.
// • inverse — the resynthesised waveform after windowed overlap-add, which
// only comes back out as a clean unit-amplitude sine if forward and inverse
// agree on both conventions.
//
// Captured on macOS (arm64, vDSP-backed). Internals here are `Float`, so the
// tolerances are looser than the double-precision filter goldens.
@MainActor
@Suite("Portable DSP golden values — spectral")
struct SpectralGoldenValueTests {
private static let fftSize: Int = 64
private static let hopSize: Int = 32
private static let sampleRate: Double = 44100
/// Sine placed exactly on bin 8 so the analysis peak is unambiguous.
private static let analysisBin: Int = 8
private static var binFrequency: Double {
sampleRate * Double(analysisBin) / Double(fftSize)
}
/// Blocks needed to fill the analysis ring and reach steady-state overlap-add.
private static let warmUpBlocks: Int = 8
@Test func analysisMagnitudeSpectrumOfBinCentredSine() throws {
let engine: SynthesisEngine = makePortableTestEngine(
blockSize: Self.hopSize,
sampleRate: Self.sampleRate
)
try engine.start()
defer { engine.stop() }
let chain: SpectralChain.Audio = SpectralChain.Audio(
input: OscSin.Audio(freq: Self.binFrequency),
fftSize: Self.fftSize,
hopSize: Self.hopSize,
analyzeOnly: true
)
for _ in 0..<Self.warmUpBlocks {
let g: SynthGraph = SynthGraph(engine: engine)
_ = chain.calculatedSamples(graph: g, count: Self.hopSize)
engine.advanceSegmentSerial()
}
var magnitudes: [Double] = []
magnitudes.reserveCapacity(Self.fftSize / 2 + 1)
for bin: Int in 0...(Self.fftSize / 2) {
magnitudes.append(Double(chain.spectralBuffer.magnitude(at: bin)))
}
// Bins 0 and 32 (DC / Nyquist) are float-epsilon noise, not signal.
let golden: [Double] = [
+4.768371582031250e-07, +8.266706019639969e-02, +1.825404316186905e-01,
+3.267964720726013e-01, +5.753288269042969e-01, +1.103066682815552e+00,
+2.663390159606934e+00, +1.353493118286133e+01, +4.078461074829102e+01,
+1.354466724395752e+01, +2.683343172073364e+00, +1.134257316589355e+00,
+6.194505095481873e-01, +3.864569664001465e-01, +2.616786956787109e-01,
+1.872759908437729e-01, +1.394553184509277e-01, +1.069587841629982e-01,
+8.389673382043839e-02, +6.694645434617996e-02, +5.412036180496216e-02,
+4.416543245315552e-02, +3.626501560211182e-02, +2.986478805541992e-02,
+2.457809448242188e-02, +2.012777328491211e-02, +1.631212420761585e-02,
+1.297473907470703e-02, +9.998649358749390e-03, +7.285922765731812e-03,
+4.758469760417938e-03, +2.349850023165345e-03, +4.768371582031250e-07,
]
#expect(golden.count == Self.fftSize / 2 + 1)
// Float-precision magnitudes spanning ~5 decades: a small absolute floor
// for the near-zero bins plus a relative term for the peak.
expectMatchesGolden(
magnitudes, golden,
absolute: 1e-5, relative: 1e-4,
"SpectralChain analysis spectrum, sine on bin \(Self.analysisBin)"
)
// The peak must be bin 8 — a packing error would move it even if the
// per-bin tolerances above somehow passed.
var peakBin: Int = 0
for bin: Int in 1..<magnitudes.count where magnitudes[bin] > magnitudes[peakBin] {
peakBin = bin
}
#expect(peakBin == Self.analysisBin, "peak landed in bin \(peakBin)")
}
@Test func resynthesisReconstructsInputSine() throws {
let engine: SynthesisEngine = makePortableTestEngine(
blockSize: Self.hopSize,
sampleRate: Self.sampleRate
)
try engine.start()
defer { engine.stop() }
let chain: SpectralChain.Audio = SpectralChain.Audio(
input: OscSin.Audio(freq: Self.binFrequency),
fftSize: Self.fftSize,
hopSize: Self.hopSize
)
var resynthesised: [Double] = []
for _ in 0..<Self.warmUpBlocks {
let g: SynthGraph = SynthGraph(engine: engine)
let out: [[Double]] = chain.calculatedSamples(graph: g, count: Self.hopSize)
resynthesised += out[0].prefix(Self.hopSize)
engine.advanceSegmentSerial()
}
let steadyState: [Double] = Array(resynthesised.suffix(Self.hopSize))
// Unit-amplitude sine, 8 cycles per 64 samples: 0, √2/2, 1, √2/2, 0, …
let golden: [Double] = [
-3.450122409986989e-09, +7.071065306663513e-01, +9.999998807907104e-01,
+7.071067094802856e-01, +1.732368737350498e-08, -7.071065902709961e-01,
-9.999997615814209e-01, -7.071067690849304e-01, -2.017156930378405e-08,
+7.071066498756409e-01, +9.999998211860657e-01, +7.071067094802856e-01,
+1.311730279951462e-08, -7.071066498756409e-01, -1.000000119209290e+00,
-7.071068286895752e-01, +6.974591570951816e-09, +7.071067690849304e-01,
+1.000000119209290e+00, +7.071067094802856e-01, -1.933644000473578e-08,
-7.071067094802856e-01, -9.999998807907104e-01, -7.071067690849304e-01,
+1.925623216436634e-08, +7.071065902709961e-01, +9.999997615814209e-01,
+7.071066498756409e-01, -6.058438195566396e-09, -7.071065902709961e-01,
-9.999998807907104e-01, -7.071066498756409e-01,
]
#expect(golden.count == Self.hopSize)
// The round trip passes through `Float` twice; 1e-5 is ~5 significant
// digits, far tighter than any scaling or windowing error would survive.
expectMatchesGolden(
steadyState, golden,
absolute: 1e-5,
"SpectralChain round-trip resynthesis"
)
}
}
@@ -5,7 +5,6 @@
// SPDX-License-Identifier: MIT
import Testing
@testable import LyrebirdUI
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - Init
@@ -5,7 +5,6 @@
// SPDX-License-Identifier: MIT
import Testing
@testable import LyrebirdUI
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - @UIParam property wrapper
@@ -35,7 +34,8 @@ import Testing
@UIParam var freq: Double = 440.0
}
let s: S = S()
#expect(s.$freq is UIParamNode)
let projected: Any = s.$freq
#expect(projected is UIParamNode)
}
@Test func projectedValueNodeValueMatchesWrappedValue() {
@@ -0,0 +1,270 @@
// WavCodecHeaderTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@_spi(LyrebirdExtensions) import LyrebirdSynth
// Headers no writer of ours emits, but real files carry: a `fmt ` chunk too
// short for the fields the reader loads at fixed offsets, and
// WAVE_FORMAT_EXTENSIBLE, which is what most 24-bit and multichannel writers
// actually produce.
@Suite("Portable WAV codec — header edge cases")
struct WavCodecHeaderTests {
private func tempURL() -> URL {
FileManager.default.temporaryDirectory
.appendingPathComponent("lyrebird-wavhdr-\(UUID().uuidString).wav")
}
/// Builds a WAV whose `fmt ` chunk is written verbatim, so a test can hand
/// the reader a header no writer of ours would produce.
private func writeWav(fmtChunk: [UInt8], dataBytes: [UInt8], to url: URL) throws {
var file: [UInt8] = []
func appendLE32(_ value: UInt32) {
file.append(contentsOf: [
UInt8(truncatingIfNeeded: value),
UInt8(truncatingIfNeeded: value >> 8),
UInt8(truncatingIfNeeded: value >> 16),
UInt8(truncatingIfNeeded: value >> 24),
])
}
file.append(contentsOf: Array("RIFF".utf8))
appendLE32(UInt32(4 + 8 + fmtChunk.count + 8 + dataBytes.count))
file.append(contentsOf: Array("WAVE".utf8))
file.append(contentsOf: Array("fmt ".utf8))
appendLE32(UInt32(fmtChunk.count))
file.append(contentsOf: fmtChunk)
file.append(contentsOf: Array("data".utf8))
appendLE32(UInt32(dataBytes.count))
file.append(contentsOf: dataBytes)
try Data(file).write(to: url)
}
private func le16(_ value: UInt16) -> [UInt8] {
[UInt8(truncatingIfNeeded: value), UInt8(truncatingIfNeeded: value >> 8)]
}
private func le32(_ value: UInt32) -> [UInt8] {
[
UInt8(truncatingIfNeeded: value),
UInt8(truncatingIfNeeded: value >> 8),
UInt8(truncatingIfNeeded: value >> 16),
UInt8(truncatingIfNeeded: value >> 24),
]
}
/// 16-byte PCM `fmt ` body.
private func pcmFmt(tag: UInt16, channels: UInt16, rate: UInt32, bits: UInt16) -> [UInt8] {
let blockAlign: UInt16 = channels * (bits / 8)
var out: [UInt8] = []
out += le16(tag)
out += le16(channels)
out += le32(rate)
out += le32(rate * UInt32(blockAlign))
out += le16(blockAlign)
out += le16(bits)
return out
}
@Test("a fmt chunk too short to hold its fields throws instead of trapping")
func shortFmtChunkThrows() throws {
// 14 bytes: everything except bitsPerSample, which the reader loads at
// offset 14. Before the length check this indexed past the chunk.
let url: URL = tempURL()
defer { try? FileManager.default.removeItem(at: url) }
let truncatedFmt: [UInt8] = Array(pcmFmt(tag: 1, channels: 1, rate: 44100, bits: 16).prefix(14))
try writeWav(fmtChunk: truncatedFmt, dataBytes: [0, 0, 0, 0], to: url)
#expect(throws: WavFileError.truncated) {
_ = try WavFileReader(url: url)
}
}
@Test("WAVE_FORMAT_EXTENSIBLE is read via its SubFormat GUID")
func extensibleFormatIsAccepted() throws {
// What most 24-bit and multichannel writers actually emit. The header
// is a PCM header with tag 0xFFFE plus a 22-byte extension whose GUID
// opens with the real format tag (1 = PCM).
let url: URL = tempURL()
defer { try? FileManager.default.removeItem(at: url) }
var fmt: [UInt8] = pcmFmt(tag: 0xFFFE, channels: 2, rate: 48000, bits: 24)
fmt += le16(22) // cbSize
fmt += le16(24) // validBitsPerSample
fmt += le32(3) // channel mask: front left + right
fmt += le16(1) // SubFormat GUID: leading tag = PCM
fmt += [UInt8](repeating: 0, count: 14) // rest of the GUID
// Two frames of stereo 24-bit silence.
let data: [UInt8] = [UInt8](repeating: 0, count: 2 * 2 * 3)
try writeWav(fmtChunk: fmt, dataBytes: data, to: url)
let reader: WavFileReader = try WavFileReader(url: url)
defer { reader.close() }
#expect(reader.encoding == .int24)
#expect(reader.channels == 2)
#expect(reader.sampleRate == 48000)
#expect(reader.frameCount == 2)
}
@Test("an unreadable extensible SubFormat is still reported, not guessed")
func extensibleWithUnsupportedSubFormatThrows() throws {
let url: URL = tempURL()
defer { try? FileManager.default.removeItem(at: url) }
var fmt: [UInt8] = pcmFmt(tag: 0xFFFE, channels: 1, rate: 44100, bits: 16)
fmt += le16(22)
fmt += le16(16)
fmt += le32(4)
fmt += le16(0x0011) // ADPCM — not something we decode
fmt += [UInt8](repeating: 0, count: 14)
try writeWav(fmtChunk: fmt, dataBytes: [0, 0], to: url)
#expect(throws: WavFileError.unsupportedFormat(formatTag: 0x0011, bitsPerSample: 16)) {
_ = try WavFileReader(url: url)
}
}
@Test("a float32 file declares cbSize and carries a fact chunk")
func float32HeaderIsSpecCompliant() throws {
// RIFF requires non-PCM tags to declare `cbSize` — an 18-byte `fmt `
// body — and to carry a `fact` chunk holding the sample count. Writers
// that emit the plain 16-byte PCM header for float data are rejected by
// strict readers.
let url: URL = tempURL()
defer { try? FileManager.default.removeItem(at: url) }
let channels: Int = 2
let frames: Int = 10
let writer: WavFileWriter = try WavFileWriter(
url: url, channels: channels, sampleRate: 48000, encoding: .float32
)
try writer.write(
interleaved: [Float](repeating: 0.25, count: frames * channels),
frames: frames
)
try writer.finalize()
let bytes: [UInt8] = [UInt8](try Data(contentsOf: url))
func le16(at offset: Int) -> UInt16 {
UInt16(bytes[offset]) | (UInt16(bytes[offset + 1]) << 8)
}
func le32(at offset: Int) -> UInt32 {
UInt32(bytes[offset])
| (UInt32(bytes[offset + 1]) << 8)
| (UInt32(bytes[offset + 2]) << 16)
| (UInt32(bytes[offset + 3]) << 24)
}
#expect(String(decoding: bytes[12..<16], as: UTF8.self) == "fmt ")
#expect(le32(at: 16) == 18, "fmt body must be 18 bytes for a non-PCM tag")
#expect(le16(at: 20) == 3, "format tag 3 = IEEE float")
#expect(le16(at: 36) == 0, "cbSize: no format extension")
#expect(String(decoding: bytes[38..<42], as: UTF8.self) == "fact")
#expect(le32(at: 42) == 4, "fact body is one UInt32")
#expect(le32(at: 46) == UInt32(frames), "fact holds the per-channel sample count")
#expect(String(decoding: bytes[50..<54], as: UTF8.self) == "data")
#expect(le32(at: 54) == UInt32(frames * channels * 4))
// RIFF size counts everything after the first eight bytes.
#expect(le32(at: 4) == UInt32(bytes.count - 8))
}
@Test("an integer file keeps the canonical 44-byte header")
func int16HeaderStaysCanonical() throws {
let url: URL = tempURL()
defer { try? FileManager.default.removeItem(at: url) }
let writer: WavFileWriter = try WavFileWriter(
url: url, channels: 1, sampleRate: 44100, encoding: .int16
)
try writer.write(interleaved: [Float](repeating: 0, count: 4), frames: 4)
try writer.finalize()
let bytes: [UInt8] = [UInt8](try Data(contentsOf: url))
func le32(at offset: Int) -> UInt32 {
UInt32(bytes[offset])
| (UInt32(bytes[offset + 1]) << 8)
| (UInt32(bytes[offset + 2]) << 16)
| (UInt32(bytes[offset + 3]) << 24)
}
#expect(le32(at: 16) == 16, "PCM fmt body stays 16 bytes")
#expect(String(decoding: bytes[36..<40], as: UTF8.self) == "data")
#expect(le32(at: 40) == UInt32(4 * 2))
#expect(bytes.count == 44 + 4 * 2)
}
@Test("the 4 GB RIFF boundary throws instead of trapping")
func riffSizeOverflowThrows() throws {
// The conversion this guards used to be a plain `UInt32(...)`, which
// traps — and a trap an hour into an offline render is the worst
// possible outcome. Tested through the size computation so the boundary
// can be crossed without writing four gigabytes.
let header: Int = 44
let justUnder: Int = Int(UInt32.max) - header + 8
#expect(try WavFileWriter.riffChunkSize(headerBytes: header, dataBytes: justUnder) == UInt32.max)
#expect(throws: WavFileError.fileTooLarge(bytes: Int(UInt32.max) + 1)) {
_ = try WavFileWriter.riffChunkSize(headerBytes: header, dataBytes: justUnder + 1)
}
}
@Test("an odd data payload is padded to a word boundary")
func oddDataPayloadIsPadded() throws {
// int24 mono with an odd frame count produces an odd `data` chunk. RIFF
// requires the next chunk to start on a word boundary, so a pad byte
// follows the payload — counted in the RIFF size, not the data size.
let url: URL = tempURL()
defer { try? FileManager.default.removeItem(at: url) }
let frames: Int = 3 // 3 frames x 1 channel x 3 bytes = 9, odd
let writer: WavFileWriter = try WavFileWriter(
url: url, channels: 1, sampleRate: 44100, encoding: .int24
)
try writer.write(interleaved: [Float](repeating: 0.5, count: frames), frames: frames)
try writer.finalize()
let bytes: [UInt8] = [UInt8](try Data(contentsOf: url))
func le32(at offset: Int) -> UInt32 {
UInt32(bytes[offset])
| (UInt32(bytes[offset + 1]) << 8)
| (UInt32(bytes[offset + 2]) << 16)
| (UInt32(bytes[offset + 3]) << 24)
}
#expect(le32(at: 40) == UInt32(frames * 3), "data size counts payload only")
#expect(bytes.count == 44 + frames * 3 + 1, "a pad byte follows the payload")
#expect(le32(at: 4) == UInt32(bytes.count - 8), "RIFF size includes the pad")
#expect(bytes[bytes.count - 1] == 0)
}
@Test("a data size larger than the file is clamped to what is there")
func oversizedDataChunkIsClamped() throws {
// Streaming writers leave a placeholder `data` size they never patch.
// Believing it produces a nonsense frame count and a mid-render throw
// rather than a clean end of file.
let url: URL = tempURL()
defer { try? FileManager.default.removeItem(at: url) }
let realFrames: Int = 4
let channels: Int = 2
var file: [UInt8] = []
file += Array("RIFF".utf8)
file += le32(0xFFFF_FFFF)
file += Array("WAVE".utf8)
file += Array("fmt ".utf8)
file += le32(16)
file += pcmFmt(tag: 1, channels: UInt16(channels), rate: 44100, bits: 16)
file += Array("data".utf8)
file += le32(0xFFFF_FFFF) // lying placeholder
file += [UInt8](repeating: 0, count: realFrames * channels * 2)
try Data(file).write(to: url)
let reader: WavFileReader = try WavFileReader(url: url)
defer { reader.close() }
#expect(reader.frameCount == realFrames)
let all: [Float] = try reader.read(frames: realFrames * 4)
#expect(all.count == realFrames * channels)
}
}
@@ -0,0 +1,154 @@
// WavCodecTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
@Suite("Portable WAV codec")
struct WavCodecTests {
private func tempURL(_ ext: String) -> URL {
let dir: URL = FileManager.default.temporaryDirectory
return dir.appendingPathComponent("lyrebird-wavtest-\(UUID().uuidString).\(ext)")
}
private func makeInterleaved(frames: Int, channels: Int) -> [Float] {
var out: [Float] = [Float](repeating: 0, count: frames * channels)
for f: Int in 0..<frames {
for c: Int in 0..<channels {
// distinct, in-range per (frame, channel)
out[f * channels + c] = Float(sin(Double(f) * 0.05 + Double(c))) * 0.8
}
}
return out
}
@Test("float32 round-trips exactly (stereo)")
func float32RoundTrip() throws {
let url: URL = tempURL("wav")
defer { try? FileManager.default.removeItem(at: url) }
let frames: Int = 500
let channels: Int = 2
let input: [Float] = makeInterleaved(frames: frames, channels: channels)
let writer: WavFileWriter = try WavFileWriter(url: url, channels: channels, sampleRate: 48000, encoding: .float32)
// write in two uneven blocks to exercise streaming
try writer.write(interleaved: Array(input[0..<(180 * channels)]), frames: 180)
try writer.write(interleaved: Array(input[(180 * channels)...]), frames: frames - 180)
try writer.finalize()
let reader: WavFileReader = try WavFileReader(url: url)
#expect(reader.channels == channels)
#expect(reader.sampleRate == 48000)
#expect(reader.frameCount == frames)
#expect(reader.encoding == .float32)
var got: [Float] = []
while true {
let block: [Float] = try reader.read(frames: 128)
if block.isEmpty { break }
got.append(contentsOf: block)
}
reader.close()
#expect(got.count == input.count)
for i: Int in 0..<input.count {
#expect(got[i] == input[i], "float32 index \(i): got \(got[i]) want \(input[i])")
}
}
@Test("int16 round-trips within quantization tolerance (mono)")
func int16RoundTrip() throws {
let url: URL = tempURL("wav")
defer { try? FileManager.default.removeItem(at: url) }
let frames: Int = 400
let input: [Float] = makeInterleaved(frames: frames, channels: 1)
let writer: WavFileWriter = try WavFileWriter(url: url, channels: 1, sampleRate: 44100, encoding: .int16)
try writer.write(interleaved: input, frames: frames)
try writer.finalize()
let reader: WavFileReader = try WavFileReader(url: url)
#expect(reader.encoding == .int16)
#expect(reader.frameCount == frames)
let got: [Float] = try reader.read(frames: frames)
reader.close()
#expect(got.count == input.count)
let tol: Float = 1.0 / 16000.0 // ~2 LSB: covers rounding + the 32767/32768 scale asymmetry
for i: Int in 0..<input.count {
#expect(abs(got[i] - input[i]) <= tol, "int16 index \(i): got \(got[i]) want \(input[i])")
}
}
@Test("int24 round-trips within quantization tolerance (stereo)")
func int24RoundTrip() throws {
let url: URL = tempURL("wav")
defer { try? FileManager.default.removeItem(at: url) }
let frames: Int = 300
let channels: Int = 2
let input: [Float] = makeInterleaved(frames: frames, channels: channels)
let writer: WavFileWriter = try WavFileWriter(url: url, channels: channels, sampleRate: 96000, encoding: .int24)
try writer.write(interleaved: input, frames: frames)
try writer.finalize()
let reader: WavFileReader = try WavFileReader(url: url)
#expect(reader.encoding == .int24)
#expect(reader.channels == channels)
let got: [Float] = try reader.read(frames: frames)
reader.close()
#expect(got.count == input.count)
let tol: Float = 1.0 / 8_000_000.0
for i: Int in 0..<input.count {
#expect(abs(got[i] - input[i]) <= tol)
}
}
@Test("non-WAVE data is rejected")
func rejectsNonWave() throws {
let url: URL = tempURL("bin")
defer { try? FileManager.default.removeItem(at: url) }
try Data([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c]).write(to: url)
#expect(throws: WavFileError.self) {
_ = try WavFileReader(url: url)
}
}
@Test("skip advances without reading the skipped frames")
func skipSeeksPastFrames() throws {
let url: URL = tempURL("wav")
defer { try? FileManager.default.removeItem(at: url) }
let channels: Int = 2
let frames: Int = 64
let samples: [Float] = makeInterleaved(frames: frames, channels: channels)
let writer: WavFileWriter = try WavFileWriter(
url: url, channels: channels, sampleRate: 44100, encoding: .float32
)
try writer.write(interleaved: samples, frames: frames)
try writer.finalize()
let reader: WavFileReader = try WavFileReader(url: url)
defer { reader.close() }
let skipped: Int = 40
try reader.skip(frames: skipped)
let tail: [Float] = try reader.read(frames: frames)
// Skipping must land on the same samples a read-and-discard would.
#expect(tail.count == (frames - skipped) * channels)
for i: Int in 0..<tail.count {
#expect(tail[i] == samples[skipped * channels + i], "index \(i)")
}
// Skipping past the end exhausts the reader rather than erroring.
try reader.skip(frames: frames * 10)
#expect(try reader.read(frames: 8).isEmpty)
}
}
@@ -0,0 +1,152 @@
// EngineStopUnbindTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
/// `SynthesisEngine.stop()` teardown contract: every non-persistent node is
/// unlinked AND every non-persistent synth's binding is released, so a synth
/// that was hosted by a now-stopped engine can be `add`ed again — to the same
/// engine or a different one — with no `EngineAddError.doubleAdd` and no
/// "wait one processBlock" constraint (unlike `remove(_:)`).
@MainActor
@Suite("Engine stop unbind")
struct EngineStopUnbindTests {
/// A synth added, started, and stopped can be re-added to the same
/// engine immediately — no intervening `processBlock` needed, because
/// `stop()` already halted the RT thread before the unbind pass runs.
@Test func reAddSameInstanceAfterStopDoesNotThrowDoubleAdd() throws {
let engine: SynthesisEngine = makeTestEngine()
try engine.start()
let synth: ConstantSynth = ConstantSynth(value: 0.1, outputBus: 0)
try engine.add(synth)
engine.processBlock(inputSamples: [])
#expect(engine.synthesizerCount == 1)
engine.stop()
// rootGroup / mainGroup persist across stop: rootGroup still holds
// exactly the mainGroup PreparedNode, mainGroup is emptied.
#expect(engine.rootGroup.count == 1)
#expect(engine.mainGroup.count == 0)
#expect(engine.synthesizerCount == 0)
#expect(engine.groupCount == 0)
#expect(throws: Never.self) {
try engine.add(synth)
}
}
/// Same synth instance, stopped on one engine, can be added to a
/// *different* engine — `stop()`'s unbind pass releases the exclusive
/// binding, so this does not throw `.boundToOtherEngine`.
@Test func reAddSameInstanceToDifferentEngineAfterStopDoesNotThrowBoundToOther() throws {
let engineA: SynthesisEngine = makeTestEngine()
let engineB: SynthesisEngine = makeTestEngine()
try engineA.start()
let synth: ConstantSynth = ConstantSynth(value: 0.2, outputBus: 0)
try engineA.add(synth)
engineA.processBlock(inputSamples: [])
engineA.stop()
try engineB.start()
#expect(throws: Never.self) {
try engineB.add(synth)
}
engineB.stop()
}
/// Synths nested inside a `Group` subtree that `stop()` drains are also
/// unbound — not just the top-level nodes directly under `mainGroup`.
@Test func stopUnbindsSynthsNestedInsideDrainedGroups() throws {
let engine: SynthesisEngine = makeTestEngine()
try engine.start()
let outer: Group = Group()
let inner: Group = Group()
let synth: ConstantSynth = ConstantSynth(value: 0.3, outputBus: 0)
try engine.add(outer)
try engine.add(inner, position: .tail(of: outer))
try engine.add(synth, position: .tail(of: inner))
engine.processBlock(inputSamples: [])
#expect(engine.synthesizerCount == 1)
#expect(engine.groupCount == 2)
engine.stop()
#expect(engine.synthesizerCount == 0)
#expect(engine.groupCount == 0)
// The nested synth's binding was released by stop()'s subtree
// unbind pass — re-add to a fresh engine succeeds with no
// `.doubleAdd` / `.boundToOtherEngine`.
let engine2: SynthesisEngine = makeTestEngine()
try engine2.start()
#expect(throws: Never.self) {
try engine2.add(synth)
}
engine2.stop()
}
/// Pre-main and post-main nodes (added `.before` / `.after` the persistent
/// `mainGroup`, so they live directly under `rootGroup` and NOT inside
/// `mainGroup`) are unbound by `stop()` too — the teardown drains the whole
/// rootGroup subtree, not just `mainGroup`.
@Test func stopUnbindsPreAndPostMainNodes() throws {
let engine: SynthesisEngine = makeTestEngine()
try engine.start()
let pre: ConstantSynth = ConstantSynth(value: 0.5, outputBus: 0)
let post: ConstantSynth = ConstantSynth(value: 0.6, outputBus: 0)
try engine.add(pre, position: .before(engine.mainGroup))
try engine.add(post, position: .after(engine.mainGroup))
engine.processBlock(inputSamples: [])
#expect(engine.synthesizerCount == 2)
engine.stop()
#expect(engine.synthesizerCount == 0)
// rootGroup keeps only the persistent mainGroup; both flanking nodes gone.
#expect(engine.mainGroup.count == 0)
#expect(engine.rootGroup.count == 1)
// Both bindings released — re-add to a fresh engine succeeds.
let engine2: SynthesisEngine = makeTestEngine()
try engine2.start()
#expect(throws: Never.self) {
try engine2.add(pre)
try engine2.add(post)
}
engine2.stop()
}
/// A synth explicitly `remove`d (and drained via `processBlock`) before
/// `stop()` is already unbound and no longer in the tree. `stop()`'s
/// unbind pass must not trap or double-unbind when it later walks a
/// tree that never contained the synth.
@Test func removeBeforeStopDoesNotTrapDuringStopUnbindPass() throws {
let engine: SynthesisEngine = makeTestEngine()
try engine.start()
let synth: ConstantSynth = ConstantSynth(value: 0.4, outputBus: 0)
try engine.add(synth)
engine.processBlock(inputSamples: [])
_ = engine.remove(synth)
engine.processBlock(inputSamples: [])
#expect(engine.synthesizerCount == 0)
// Must not trap / corrupt engine state.
engine.stop()
#expect(engine.synthesizerCount == 0)
#expect(engine.mainGroup.count == 0)
#expect(engine.rootGroup.count == 1)
#expect(throws: Never.self) {
try engine.add(synth)
}
}
}