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
@@ -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"
)
}
}
@@ -0,0 +1,359 @@
// UIParamNodeTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - Init
@MainActor
@Suite("UIParamNode init") struct UIParamNodeInitTests {
@Test func initialValueStoredAsObservable() {
let node: UIParamNode = UIParamNode(440.0)
#expect(node.value == 440.0)
}
@Test func initialValueReadableViaFloatValue() {
let engine: SynthesisEngine = makeUITestEngine()
let graph: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
let node: UIParamNode = UIParamNode(0.5)
#expect(node.floatValue(graph: graph) == 0.5)
}
@Test func initialValueReadableViaIntValue() {
let engine: SynthesisEngine = makeUITestEngine()
let graph: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
let node: UIParamNode = UIParamNode(3.7)
#expect(node.intValue(graph: graph) == 3)
}
@Test func intValueAfterUpdate() {
// intValue must reflect the updated value (direct atomic read, no ramp).
let engine: SynthesisEngine = makeUITestEngine()
let graph: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
let node: UIParamNode = UIParamNode(1.0)
node.update(5.7)
#expect(node.intValue(graph: graph) == 5)
}
@Test func intValueDoesNotPrimeFanOutCache() {
// Calling intValue then calculatedSamples in the same segment must produce a correct
// ramp — intValue must not consume the fan-out budget (no calculatedSamples side-effect).
let engine: SynthesisEngine = makeUITestEngine()
let blockCount: Int = 4
let node: UIParamNode = UIParamNode(0.0)
node.update(4.0)
let graph: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
// intValue call — must be a direct atomic read, no _computeSamples invocation.
_ = node.intValue(graph: graph)
// calculatedSamples in the same segment must still compute the correct ramp.
let result: [[Double]] = node.calculatedSamples(graph: graph, count: blockCount)
// Ramp 0→4 in 4 steps: [1.0, 2.0, 3.0, 4.0]
#expect(result[0][blockCount - 1] == 4.0,
"calculatedSamples after intValue must still produce the correct ramp target")
}
@Test func needsInterpolationIsTrue() {
let node: UIParamNode = UIParamNode(1.0)
#expect(node.needsInterpolation() == true)
}
}
// MARK: - Atomic update round-trip
@MainActor
@Suite("UIParamNode atomic update") struct UIParamNodeAtomicTests {
@Test func updateSetsObservableValue() {
let node: UIParamNode = UIParamNode(100.0)
node.update(200.0)
#expect(node.value == 200.0)
}
@Test func updateReflectsInFloatValue() {
let engine: SynthesisEngine = makeUITestEngine()
let graph: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
let node: UIParamNode = UIParamNode(100.0)
node.update(880.0)
#expect(node.floatValue(graph: graph) == 880.0)
}
@Test func multipleUpdatesRetainLatestValue() {
let engine: SynthesisEngine = makeUITestEngine()
let graph: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
let node: UIParamNode = UIParamNode(0.0)
node.update(1.0)
node.update(2.0)
node.update(3.0)
#expect(node.floatValue(graph: graph) == 3.0)
#expect(node.value == 3.0)
}
@Test func zeroRoundTrip() {
let engine: SynthesisEngine = makeUITestEngine()
let graph: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
let node: UIParamNode = UIParamNode(1.0)
node.update(0.0)
#expect(node.floatValue(graph: graph) == 0.0)
}
@Test func negativeValueRoundTrip() {
let engine: SynthesisEngine = makeUITestEngine()
let graph: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
let node: UIParamNode = UIParamNode(0.0)
node.update(-1.5)
#expect(node.floatValue(graph: graph) == -1.5)
}
}
// MARK: - calculatedSamples interpolation
@MainActor
@Suite("UIParamNode calculatedSamples") struct UIParamNodeCalcTests {
@Test func flatBlockWhenValueUnchanged() throws {
let engine: SynthesisEngine = makeUITestEngine()
let graph: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
let blockCount: Int = 4
let node: UIParamNode = UIParamNode(1.0)
let result: [[Double]] = node.calculatedSamples(graph: graph, count: blockCount)
#expect(result.count == 1)
// Buffer is pre-allocated to lyrebirdDefaultResultBufferSize — never resized.
// Only the first blockCount elements are meaningful.
#expect(result[0].count >= blockCount)
// No change — step = 0 — the first blockCount samples should all equal 1.0
for sample: Double in result[0].prefix(blockCount) {
#expect(sample == 1.0)
}
}
@Test func rampReachesTargetAtLastSample() throws {
let engine: SynthesisEngine = makeUITestEngine()
let graph: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
let blockCount: Int = 4
let node: UIParamNode = UIParamNode(0.0)
node.update(4.0)
let result: [[Double]] = node.calculatedSamples(graph: graph, count: blockCount)
// The meaningful range is [0..<blockCount]; index blockCount-1 is the last ramp sample.
#expect(result[0][blockCount - 1] == 4.0)
}
@Test func rampIsLinear() throws {
let engine: SynthesisEngine = makeUITestEngine()
let graph: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
let node: UIParamNode = UIParamNode(0.0)
node.update(4.0)
let result: [[Double]] = node.calculatedSamples(graph: graph, count: 4)
// Ramp from 0→4 in 4 steps: expected [1.0, 2.0, 3.0, 4.0] at indices 0–3
#expect(result[0][0] == 1.0)
#expect(result[0][1] == 2.0)
#expect(result[0][2] == 3.0)
#expect(result[0][3] == 4.0)
}
@Test func subsequentBlockIsFlatAtTarget() throws {
let engine: SynthesisEngine = makeUITestEngine()
let blockCount: Int = 4
let node: UIParamNode = UIParamNode(0.0)
node.update(2.0)
// Block 1 — ramp from 0 to 2.0.
let graph1: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
_ = node.calculatedSamples(graph: graph1, count: blockCount)
// Advance to the next segment so the fan-out cache is invalidated.
advanceUIBlock(engine)
// Block 2 — value unchanged, should be flat at 2.0.
let graph2: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
let second: [[Double]] = node.calculatedSamples(graph: graph2, count: blockCount)
// Only the first blockCount elements are meaningful after this call.
for sample: Double in second[0].prefix(blockCount) {
#expect(sample == 2.0)
}
}
@Test func sampleBlockMatchesFirstChannel() throws {
let engine: SynthesisEngine = makeUITestEngine()
let graph: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
// Use separate nodes with identical initial state so each call starts fresh.
let node2D: UIParamNode = UIParamNode(0.0)
node2D.update(4.0)
let via2D: [Double] = node2D.calculatedSamples(graph: graph, count: 4).first ?? []
let node1D: UIParamNode = UIParamNode(0.0)
node1D.update(4.0)
let via1D: [Double] = node1D.sampleBlock(graph: graph, count: 4, previousValue: 0.0)
#expect(via2D == via1D)
}
@Test func bufferStaysAtPreAllocatedSize() throws {
let engine: SynthesisEngine = makeUITestEngine()
let graph: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
let node: UIParamNode = UIParamNode(1.0)
let first: [[Double]] = node.calculatedSamples(graph: graph, count: 8)
let second: [[Double]] = node.calculatedSamples(graph: graph, count: 8)
// Buffer is fixed at lyrebirdDefaultResultBufferSize — never resized regardless of count.
#expect(first[0].count == lyrebirdDefaultResultBufferSize)
#expect(second[0].count == lyrebirdDefaultResultBufferSize)
}
}
// MARK: - ValidGeneratorInput wiring
@MainActor
@Suite("UIParamNode as ValidGeneratorInput") struct UIParamNodeWiringTests {
@Test func usableAsSourceParameter() throws {
let engine: SynthesisEngine = makeUITestEngine()
try engine.start()
let node: UIParamNode = UIParamNode(0.5)
class ParamSynth: SynthesizerBase {
let node: UIParamNode
init(node: UIParamNode) { self.node = node; super.init() }
override func build() {
addOutputGenerator(Out.Audio(bus: 0, source: node))
}
}
let synth: ParamSynth = ParamSynth(node: node)
try engine.add(synth)
engine.processBlock(inputSamples: [])
let bus0: [Float] = engine.audioBuses[0]
// Out accumulates, so bus 0 should be non-zero
let anyNonZero: Bool = bus0.contains { $0 != 0.0 }
#expect(anyNonZero)
}
@Test func updateReflectsInNextBlock() throws {
let engine: SynthesisEngine = makeUITestEngine()
try engine.start()
let node: UIParamNode = UIParamNode(0.0)
class ParamSynth: SynthesizerBase {
let node: UIParamNode
init(node: UIParamNode) { self.node = node; super.init() }
override func build() {
addOutputGenerator(Out.Audio(bus: 0, source: node))
}
}
let synth: ParamSynth = ParamSynth(node: node)
try engine.add(synth)
engine.processBlock(inputSamples: [])
// Bus 0 should be zero (node value was 0)
let allZero: Bool = engine.audioBuses[0].allSatisfy { $0 == 0.0 }
#expect(allZero)
// Update to 1.0 — next block ramps from 0 to 1.0; last sample reaches target.
node.update(1.0)
engine.processBlock(inputSamples: [])
let lastSample: Float = engine.audioBuses[0][7]
#expect(abs(lastSample - 1.0) < 1e-6)
}
}
// MARK: - Source-swap
@MainActor
@Suite("UIParamNode source swap") struct UIParamNodeSourceSwapTests {
@Test func sourceAssignmentRoutesThroughCalculatedSamples() {
// Verifies that UIParamNode.calculatedSamples forwards to
// _node.calculatedSamples — actually drains the source queue and
// renders the source's output, not the scalar ramp.
let engine: SynthesisEngine = makeUITestEngine()
let blockCount: Int = 8
let node: UIParamNode = UIParamNode(100.0)
node.update(100.0)
// Warm-up block to settle the scalar ramp at 100.
let graph0: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
_ = node.calculatedSamples(graph: graph0, count: blockCount)
advanceUIBlock(engine)
// Install a constant-value source generator that outputs 770.
node.source = ConstantTestGenerator(770.0)
// Next block should reflect the source's output, not the scalar 100.
let graph1: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
let result: [[Double]] = node.calculatedSamples(graph: graph1, count: blockCount)
// The source is a control-rate constant — calculatedSamples returns
// a one-row buffer containing the constant value.
#expect(result[0][blockCount - 1] == 770.0,
"UIParamNode.source must drive output via _node.calculatedSamples")
}
@Test func sourceNilRevertsToScalarRamp() {
let engine: SynthesisEngine = makeUITestEngine()
let blockCount: Int = 8
let node: UIParamNode = UIParamNode(100.0)
node.update(100.0)
let graph0: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
_ = node.calculatedSamples(graph: graph0, count: blockCount)
advanceUIBlock(engine)
node.source = ConstantTestGenerator(770.0)
let graph1: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
_ = node.calculatedSamples(graph: graph1, count: blockCount)
advanceUIBlock(engine)
// Revert. After enough blocks the scalar ramp should resettle at 100.
node.source = nil
for _ in 0..<8 {
let g: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
_ = node.calculatedSamples(graph: g, count: blockCount)
advanceUIBlock(engine)
}
let gFinal: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
let final: [[Double]] = node.calculatedSamples(graph: gFinal, count: blockCount)
#expect(abs(final[0][blockCount - 1] - 100.0) < 1e-9,
"UIParamNode.source = nil must revert to scalar")
}
}
/// Minimal ControlGenerator emitting a constant value, used to test that
/// `UIParamNode.source` actually routes through `_node.calculatedSamples`
/// and not the scalar ramp.
private final class ConstantTestGenerator: GeneratorBase, ControlGenerator, @unchecked Sendable {
private let _value: Double
private var _buf: [[Double]] = [[0.0]]
var previousOutputValue: Double
init(_ value: Double) {
_value = value
previousOutputValue = value
_buf = [[Double](repeating: value, count: lyrebirdDefaultResultBufferSize)]
}
func floatValue(graph: SynthGraph) -> Double { _value }
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
return _buf
}
}
// MARK: - Test helpers
/// Advances the fan-out cache serial by one, simulating a block boundary.
/// Mirror of `advanceBlock` in `LyrebirdTests/TestHelpers.swift` for use in UI tests.
private func advanceUIBlock(_ engine: SynthesisEngine) {
engine.advanceSegmentSerial()
}
private func makeUITestEngine() -> SynthesisEngine {
SynthesisEngine(
blockSize: 8,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 8,
numControlBuses: 8,
driver: OfflineDriver()
)
}
@@ -0,0 +1,158 @@
// UIParamTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - @UIParam property wrapper
@MainActor
@Suite("@UIParam property wrapper") struct UIParamTests {
@Test func wrappedValueReturnsInitialValue() {
class S {
@UIParam var freq: Double = 440.0
}
let s: S = S()
#expect(s.freq == 440.0)
}
@Test func wrappedValueSetterUpdatesValue() {
class S {
@UIParam var freq: Double = 440.0
}
let s: S = S()
s.freq = 880.0
#expect(s.freq == 880.0)
}
@Test func projectedValueIsUIParamNode() {
class S {
@UIParam var freq: Double = 440.0
}
let s: S = S()
let projected: Any = s.$freq
#expect(projected is UIParamNode)
}
@Test func projectedValueNodeValueMatchesWrappedValue() {
class S {
@UIParam var amp: Double = 0.5
}
let s: S = S()
#expect(s.$amp.value == s.amp)
s.amp = 0.8
#expect(s.$amp.value == 0.8)
}
@Test func projectedValueIsStableIdentity() {
class S {
@UIParam var freq: Double = 440.0
}
let s: S = S()
let ref1: UIParamNode = s.$freq
let ref2: UIParamNode = s.$freq
#expect(ref1 === ref2)
}
@Test func projectedValueConformsToValidGeneratorInput() {
class S {
@UIParam var freq: Double = 440.0
}
let s: S = S()
let input: any ValidGeneratorInput = s.$freq
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 8, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 0,
numAudioBuses: 8, numControlBuses: 8,
driver: OfflineDriver()
)
let graph: SynthGraph = SynthGraph(engine: engine, busOffset: 0)
#expect(input.floatValue(graph: graph) == 440.0)
}
@Test func multipleParamsAreIndependent() {
class S {
@UIParam var freq: Double = 440.0
@UIParam var amp: Double = 0.5
}
let s: S = S()
s.freq = 880.0
#expect(s.amp == 0.5) // amp unchanged
#expect(s.freq == 880.0)
#expect(s.$freq !== s.$amp)
}
@Test func wrappedValueSetterAndNodeUpdateAreEquivalent() {
class S {
@UIParam var freq: Double = 440.0
}
let s1: S = S()
let s2: S = S()
s1.freq = 660.0 // via wrappedValue setter
s2.$freq.update(660.0) // via node directly
#expect(s1.freq == s2.freq)
#expect(s1.$freq.value == s2.$freq.value)
}
}
// MARK: - @UIParam in a SynthesizerBase subclass
@MainActor
@Suite("@UIParam in synthesizer") struct UIParamInSynthTests {
final class ToneWithParam: SynthesizerBase {
@UIParam var frequency: Double = 440.0
@UIParam var amplitude: Double = 0.0
override func build() {
// Direct typed wiring — `$amplitude` is a UIParamNode (ControlGenerator)
// delivering a per-(sub-)block ramp.
addOutputGenerator(Out.Audio(bus: 0, source: $amplitude))
}
}
@Test func buildWiresParamToOutput() throws {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 8, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 0,
numAudioBuses: 8, numControlBuses: 8,
driver: OfflineDriver()
)
try engine.start()
let synth: UIParamInSynthTests.ToneWithParam = ToneWithParam()
synth.amplitude = 1.0
try engine.add(synth)
engine.processBlock(inputSamples: [])
let anyNonZero: Bool = engine.audioBuses[0].contains { $0 != 0.0 }
#expect(anyNonZero)
}
@Test func updatingParamAffectsNextBlock() throws {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 8, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 0,
numAudioBuses: 8, numControlBuses: 8,
driver: OfflineDriver()
)
try engine.start()
let synth: UIParamInSynthTests.ToneWithParam = ToneWithParam()
synth.amplitude = 0.0 // silent at first
try engine.add(synth)
engine.processBlock(inputSamples: [])
let allZero: Bool = engine.audioBuses[0].allSatisfy { $0 == 0.0 }
#expect(allZero)
synth.amplitude = 1.0
engine.processBlock(inputSamples: [])
let anyNonZero: Bool = engine.audioBuses[0].contains { $0 != 0.0 }
#expect(anyNonZero)
}
}
@@ -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)
}
}