prep for 1.2.0 release updates

This commit is contained in:
2026-06-21 11:45:58 -07:00
parent 73191c958f
commit 032b7c39d3
286 changed files with 21116 additions and 121 deletions
+66 -8
View File
@@ -47,27 +47,27 @@ struct CLICommandTests {
// MARK: - new
@Test func newSubcommandParsed() {
#expect(CLICommand.parse(["lyrebird", "new", "MySynth"]) == .new(name: "MySynth", template: .basic, lyrebirdPath: nil))
#expect(CLICommand.parse(["lyrebird", "new", "MySynth"]) == .new(name: "MySynth", template: .basic, lyrebirdPath: nil, shoegazePath: nil))
}
@Test func newWithTemplateDemoParsed() {
#expect(CLICommand.parse(["lyrebird", "new", "MySynth", "--template", "demo"])
== .new(name: "MySynth", template: .demo, lyrebirdPath: nil))
== .new(name: "MySynth", template: .demo, lyrebirdPath: nil, shoegazePath: nil))
}
@Test func newWithTemplateUIDemoParsed() {
#expect(CLICommand.parse(["lyrebird", "new", "MySynth", "--template", "ui-demo"])
== .new(name: "MySynth", template: .uiDemo, lyrebirdPath: nil))
== .new(name: "MySynth", template: .uiDemo, lyrebirdPath: nil, shoegazePath: nil))
}
@Test func newWithTemplateNRTParsed() {
#expect(CLICommand.parse(["lyrebird", "new", "MySynth", "--template", "nrt"])
== .new(name: "MySynth", template: .nrt, lyrebirdPath: nil))
== .new(name: "MySynth", template: .nrt, lyrebirdPath: nil, shoegazePath: nil))
}
@Test func newWithUnknownTemplateFallsBackToBasic() {
#expect(CLICommand.parse(["lyrebird", "new", "MySynth", "--template", "bogus"])
== .new(name: "MySynth", template: .basic, lyrebirdPath: nil))
== .new(name: "MySynth", template: .basic, lyrebirdPath: nil, shoegazePath: nil))
}
@Test func newWithoutNameParsesToHelp() {
@@ -89,7 +89,8 @@ struct CLICommandTests {
"--lyrebird-path", "/Users/josh/Documents/LyrebirdII"
]) == .new(name: "MyPiece",
template: .basic,
lyrebirdPath: "/Users/josh/Documents/LyrebirdII"))
lyrebirdPath: "/Users/josh/Documents/LyrebirdII",
shoegazePath: nil))
}
@Test func newWithTemplateAndLyrebirdPathParsed() {
@@ -99,13 +100,70 @@ struct CLICommandTests {
"--lyrebird-path", "/abs/path"
]) == .new(name: "MyApp",
template: .macosUIXcode,
lyrebirdPath: "/abs/path"))
lyrebirdPath: "/abs/path",
shoegazePath: nil))
}
@Test func newWithoutLyrebirdPathReportsNil() {
#expect(CLICommand.parse([
"lyrebird", "new", "MyPiece"
]) == .new(name: "MyPiece", template: .basic, lyrebirdPath: nil))
]) == .new(name: "MyPiece", template: .basic, lyrebirdPath: nil, shoegazePath: nil))
}
// MARK: - shoegaze template
@Test func newWithTemplateShoegaze() {
let cmd: CLICommand = CLICommand.parse(["lyrebird", "new", "MyRig", "--template", "shoegaze"])
#expect(cmd == .new(name: "MyRig", template: .shoegaze, lyrebirdPath: nil, shoegazePath: nil))
}
@Test func newWithShoegazePathParsed() {
let cmd: CLICommand = CLICommand.parse([
"lyrebird", "new", "MyRig",
"--template", "shoegaze",
"--lyrebird-path", "/abs/Lyrebird",
"--shoegaze-path", "/abs/ShoeGaze",
])
#expect(cmd == .new(
name: "MyRig",
template: .shoegaze,
lyrebirdPath: "/abs/Lyrebird",
shoegazePath: "/abs/ShoeGaze"
))
}
@Test func newShoegazeWithoutShoegazePathHasNilShoegazePath() {
let cmd: CLICommand = CLICommand.parse([
"lyrebird", "new", "MyRig",
"--template", "shoegaze",
"--lyrebird-path", "/abs/Lyrebird",
])
#expect(cmd == .new(
name: "MyRig",
template: .shoegaze,
lyrebirdPath: "/abs/Lyrebird",
shoegazePath: nil
))
}
@Test func shoegazePathValueNotConsumedWhenFlagToken() {
// `--shoegaze-path --lyrebird-path /abs/Lyrebird` — the value slot for
// `--shoegaze-path` is `--lyrebird-path` (starts with "-") → shoegazePath = nil.
// `firstIndex(of: "--lyrebird-path")` finds the first occurrence (index 6)
// whose next token is also "--lyrebird-path" (starts with "-") → lyrebirdPath = nil too.
let args: [String] = [
"lyrebird", "new", "MyRig",
"--template", "shoegaze",
"--shoegaze-path", "--lyrebird-path",
"--lyrebird-path", "/abs/Lyrebird",
]
let cmd: CLICommand = CLICommand.parse(args)
#expect(cmd == .new(
name: "MyRig",
template: .shoegaze,
lyrebirdPath: nil,
shoegazePath: nil
))
}
// MARK: - run
@@ -237,6 +237,12 @@ struct ProjectScaffolderTests {
#expect(ProjectTemplate(string: "iosui") == .iosUI)
#expect(ProjectTemplate(string: "auv3") == .auv3)
#expect(ProjectTemplate(string: "AUV3") == .auv3)
#expect(ProjectTemplate(string: "shoegaze") == .shoegaze)
#expect(ProjectTemplate(string: "shoe-gaze") == .shoegaze)
#expect(ProjectTemplate(string: "SHOEGAZE") == .shoegaze)
#expect(ProjectTemplate(string: "shoegaze-ios") == .shoegazeIOS)
#expect(ProjectTemplate(string: "shoegazeios") == .shoegazeIOS)
#expect(ProjectTemplate(string: "SHOEGAZE-IOS") == .shoegazeIOS)
}
@Test func shipsXcodeProjectClassification() {
@@ -245,9 +251,244 @@ struct ProjectScaffolderTests {
#expect(ProjectTemplate.uiDemo.shipsXcodeProject == false)
#expect(ProjectTemplate.nrt.shipsXcodeProject == false)
#expect(ProjectTemplate.score.shipsXcodeProject == false)
// shoegaze is now an Xcode-bearing template (macOS .app bundle).
#expect(ProjectTemplate.shoegaze.shipsXcodeProject == true)
#expect(ProjectTemplate.macosUIXcode.shipsXcodeProject == true)
#expect(ProjectTemplate.iosUI.shipsXcodeProject == true)
#expect(ProjectTemplate.auv3.shipsXcodeProject == true)
#expect(ProjectTemplate.shoegazeIOS.shipsXcodeProject == true)
}
// MARK: - shoegaze template (macOS Xcode app)
@Test func shoegazeMacOSScaffoldCreatesAllFiles() throws {
let fm: FileManager = FileManager.default
let tmp: String = fm.temporaryDirectory
.appendingPathComponent("LyrebirdScaffolderTest_\(UUID().uuidString)").path
try fm.createDirectory(atPath: tmp, withIntermediateDirectories: true, attributes: nil)
defer { try? fm.removeItem(atPath: tmp) }
try ProjectScaffolder.scaffold(name: "MyRig", template: .shoegaze, in: tmp)
let root: String = (tmp as NSString).appendingPathComponent("MyRig")
let expected: [String] = [
"MyRig.xcodeproj/project.pbxproj",
"MyRig.xcodeproj/xcshareddata/xcschemes/MyRig.xcscheme",
"MyRig.xcworkspace/contents.xcworkspacedata",
"MyRig/MyRigApp.swift",
"MyRig/MyRigAppModel.swift",
"MyRig/Info.plist",
]
for rel: String in expected {
let path: String = (root as NSString).appendingPathComponent(rel)
#expect(fm.fileExists(atPath: path),
"missing shoegaze macOS file: \(rel)")
}
}
@Test func shoegazeMacOSWorkspaceReferencesXcodeproj() throws {
let fm: FileManager = FileManager.default
let tmp: String = fm.temporaryDirectory
.appendingPathComponent("LyrebirdScaffolderTest_\(UUID().uuidString)").path
try fm.createDirectory(atPath: tmp, withIntermediateDirectories: true, attributes: nil)
defer { try? fm.removeItem(atPath: tmp) }
try ProjectScaffolder.scaffold(name: "MyRig", template: .shoegaze, in: tmp)
let workspacePath: String = (tmp as NSString)
.appendingPathComponent("MyRig/MyRig.xcworkspace/contents.xcworkspacedata")
let contents: String = try String(contentsOfFile: workspacePath, encoding: .utf8)
#expect(contents.contains("group:MyRig.xcodeproj"))
}
@Test func shoegazeMacOSAppSwiftContainsShoeGazeView() {
let src: String = ProjectScaffolder.shoegazeMacOSAppSwift(name: "MyRig")
#expect(src.contains("ShoeGazeView"))
#expect(src.contains("import LyrebirdShoeGazeUI"))
#expect(src.contains("@main"))
#expect(src.contains("toggleMute"))
#expect(src.contains(".keyboardShortcut"))
// Must not embed the Lyrebird copyright in emitted user source.
#expect(!src.contains("Joshua Parmenter"))
}
@Test func shoegazeMacOSAppSwiftSubstitutesName() {
let src: String = ProjectScaffolder.shoegazeMacOSAppSwift(name: "GuitarPedals")
#expect(src.contains("GuitarPedalsApp"))
#expect(src.contains("GuitarPedalsAppModel"))
}
@Test func shoegazeMacOSAppModelContainsEngineAndBoard() {
let src: String = ProjectScaffolder.shoegazeMacOSAppModelSwift(name: "MyRig")
#expect(src.contains("import LyrebirdShoeGaze"))
#expect(src.contains("CoreAudioDriver"))
#expect(src.contains("ShoeGaze(engine:"))
#expect(src.contains("OverdrivePedal"))
#expect(src.contains("DelayPedal"))
#expect(src.contains("ReverbPedal"))
#expect(src.contains("ModulationPedal"))
#expect(src.contains("@Observable"))
#expect(src.contains("toggleMute"))
// Must not embed the Lyrebird copyright in emitted user source.
#expect(!src.contains("Joshua Parmenter"))
}
@Test func shoegazeMacOSAppModelSubstitutesName() {
let src: String = ProjectScaffolder.shoegazeMacOSAppModelSwift(name: "GuitarPedals")
#expect(src.contains("GuitarPedalsAppModel"))
#expect(src.contains("GuitarPedals"))
}
@Test func shoegazeMacOSInfoPlistContainsMicrophoneKey() {
let plist: String = ProjectScaffolder.shoegazeMacOSInfoPlist(name: "MyRig")
#expect(plist.contains("NSMicrophoneUsageDescription"))
#expect(plist.contains("LSMinimumSystemVersion"))
#expect(plist.contains("NSHighResolutionCapable"))
#expect(plist.contains("public.app-category.music"))
#expect(plist.contains("NSPrincipalClass"))
}
@Test func shoegazeMacOSPBXProjReferencesMacOSXAndShoeGaze() {
let pbx: String = ProjectScaffolder.shoegazeMacOSPBXProj(name: "MyRig")
#expect(pbx.contains("SDKROOT = macosx"))
#expect(pbx.contains("MACOSX_DEPLOYMENT_TARGET = 15.0"))
#expect(pbx.contains("ENABLE_HARDENED_RUNTIME = YES"))
#expect(pbx.contains("LyrebirdShoeGaze"))
#expect(pbx.contains("LyrebirdShoeGazeUI"))
#expect(pbx.contains("LyrebirdUI"))
#expect(pbx.contains("Lyrebird"))
#expect(pbx.contains(ProjectScaffolder.shoegazePackageURL))
#expect(pbx.contains("MyRig.app"))
}
@Test func shoegazeMacOSPBXProjUsesLocalRefsWhenPathsSet() {
let pbx: String = ProjectScaffolder.shoegazeMacOSPBXProj(
name: "MyRig",
lyrebirdPath: "/abs/Lyrebird",
shoegazePath: "/abs/ShoeGaze"
)
#expect(pbx.contains("XCLocalSwiftPackageReference"))
#expect(pbx.contains(#"relativePath = "/abs/ShoeGaze""#))
#expect(pbx.contains(#"relativePath = "/abs/Lyrebird""#))
#expect(!pbx.contains("XCRemoteSwiftPackageReference"))
}
@Test func shoegazeMacOSPBXProjUsesRemoteRefsWhenPathsNil() {
let pbx: String = ProjectScaffolder.shoegazeMacOSPBXProj(name: "MyRig")
#expect(pbx.contains("XCRemoteSwiftPackageReference"))
#expect(pbx.contains(ProjectScaffolder.shoegazePackageURL))
#expect(pbx.contains(ProjectScaffolder.lyrebirdPackageURL))
}
// MARK: - shoegaze-ios template
@Test func shoegazeIOSScaffoldCreatesAllFiles() throws {
let fm: FileManager = FileManager.default
let tmp: String = fm.temporaryDirectory
.appendingPathComponent("LyrebirdScaffolderTest_\(UUID().uuidString)").path
try fm.createDirectory(atPath: tmp, withIntermediateDirectories: true, attributes: nil)
defer { try? fm.removeItem(atPath: tmp) }
try ProjectScaffolder.scaffold(name: "MyRig", template: .shoegazeIOS, in: tmp)
let root: String = (tmp as NSString).appendingPathComponent("MyRig")
let expected: [String] = [
"MyRig.xcodeproj/project.pbxproj",
"MyRig.xcodeproj/xcshareddata/xcschemes/MyRig.xcscheme",
"MyRig.xcworkspace/contents.xcworkspacedata",
"MyRig/MyRigApp.swift",
"MyRig/MyRigAppModel.swift",
"MyRig/Info.plist",
]
for rel: String in expected {
let path: String = (root as NSString).appendingPathComponent(rel)
#expect(fm.fileExists(atPath: path),
"missing shoegaze-ios file: \(rel)")
}
}
@Test func shoegazeIOSAppSwiftContainsShoeGazeView() {
let src: String = ProjectScaffolder.shoegazeIOSAppSwift(name: "MyRig")
#expect(src.contains("ShoeGazeView"))
#expect(src.contains("import LyrebirdShoeGazeUI"))
#expect(src.contains("@main"))
#expect(src.contains("NavigationStack"))
#expect(src.contains("ScrollView"))
// Must not embed the Lyrebird copyright in emitted user source.
#expect(!src.contains("Joshua Parmenter"))
}
@Test func shoegazeIOSAppSwiftSubstitutesName() {
let src: String = ProjectScaffolder.shoegazeIOSAppSwift(name: "GuitarPedals")
#expect(src.contains("GuitarPedalsApp"))
#expect(src.contains("GuitarPedalsAppModel"))
}
@Test func shoegazeIOSAppModelContainsEngineAndBoard() {
let src: String = ProjectScaffolder.shoegazeIOSAppModelSwift(name: "MyRig")
#expect(src.contains("import LyrebirdShoeGaze"))
#expect(src.contains("iOSAudioDriver"))
#expect(src.contains("AVAudioSession"))
#expect(src.contains("ShoeGaze(engine:"))
#expect(src.contains("OverdrivePedal"))
#expect(src.contains("DelayPedal"))
#expect(src.contains("ReverbPedal"))
#expect(src.contains("ModulationPedal"))
#expect(src.contains("@Observable"))
// Must not embed the Lyrebird copyright in emitted user source.
#expect(!src.contains("Joshua Parmenter"))
}
@Test func shoegazeIOSAppModelSubstitutesName() {
let src: String = ProjectScaffolder.shoegazeIOSAppModelSwift(name: "GuitarPedals")
#expect(src.contains("GuitarPedalsAppModel"))
#expect(src.contains("GuitarPedals"))
}
@Test func shoegazeIOSPBXProjReferencesIPhoneOSAndShoeGaze() {
let pbx: String = ProjectScaffolder.shoegazeIOSPBXProj(name: "MyRig")
#expect(pbx.contains("SDKROOT = iphoneos"))
#expect(pbx.contains("IPHONEOS_DEPLOYMENT_TARGET = 18.0"))
#expect(pbx.contains("TARGETED_DEVICE_FAMILY"))
#expect(pbx.contains("LyrebirdShoeGaze"))
#expect(pbx.contains("LyrebirdShoeGazeUI"))
#expect(pbx.contains("LyrebirdUI"))
#expect(pbx.contains(ProjectScaffolder.shoegazePackageURL))
#expect(pbx.contains("MyRig.app"))
}
@Test func shoegazeIOSPBXProjUsesLocalShoegazeRefWhenPathSet() {
let pbx: String = ProjectScaffolder.shoegazeIOSPBXProj(
name: "MyRig",
lyrebirdPath: "/abs/Lyrebird",
shoegazePath: "/abs/ShoeGaze"
)
#expect(pbx.contains("XCLocalSwiftPackageReference"))
#expect(pbx.contains(#"relativePath = "/abs/ShoeGaze""#))
#expect(pbx.contains(#"relativePath = "/abs/Lyrebird""#))
#expect(!pbx.contains("XCRemoteSwiftPackageReference"))
}
@Test func shoegazeIOSPBXProjUsesRemoteRefWhenPathsNil() {
let pbx: String = ProjectScaffolder.shoegazeIOSPBXProj(name: "MyRig")
#expect(pbx.contains("XCRemoteSwiftPackageReference"))
#expect(pbx.contains(ProjectScaffolder.shoegazePackageURL))
#expect(pbx.contains(ProjectScaffolder.lyrebirdPackageURL))
}
@Test func shoegazeIOSWorkspaceReferencesXcodeproj() throws {
let fm: FileManager = FileManager.default
let tmp: String = fm.temporaryDirectory
.appendingPathComponent("LyrebirdScaffolderTest_\(UUID().uuidString)").path
try fm.createDirectory(atPath: tmp, withIntermediateDirectories: true, attributes: nil)
defer { try? fm.removeItem(atPath: tmp) }
try ProjectScaffolder.scaffold(name: "MyRig", template: .shoegazeIOS, in: tmp)
let workspacePath: String = (tmp as NSString)
.appendingPathComponent("MyRig/MyRig.xcworkspace/contents.xcworkspacedata")
let contents: String = try String(contentsOfFile: workspacePath, encoding: .utf8)
#expect(contents.contains("group:MyRig.xcodeproj"))
}
// MARK: - Xcode-bearing templates: structure
@@ -37,6 +37,13 @@ struct TemplateInstallerTests {
#expect(names.contains("LyrebirdGenerator.xctemplate"))
}
@Test func availableTemplatesIncludesShoeGazePedal() throws {
let names: [String] = try TemplateInstaller.availableTemplates()
// The ShoeGaze Pedal template scaffolds a `Pedal` subclass for the
// guitar-pedalboard sample project.
#expect(names.contains("LyrebirdShoeGazePedal.xctemplate"))
}
// MARK: - Destination URL
@Test func destinationURLIsInHomeLibrary() {
@@ -185,4 +185,28 @@ struct WorkflowIntegrationTests {
#expect(try parseCheck(source: source, fileName: "main.swift"),
"nrt template main.swift must pass swiftc -parse")
}
@Test func shoegazeIOSAppSwiftIsValidSwiftSyntax() throws {
let source: String = ProjectScaffolder.shoegazeIOSAppSwift(name: "MyRig")
#expect(try parseCheck(source: source, fileName: "MyRigApp.swift"),
"shoegaze-ios App.swift must pass swiftc -parse")
}
@Test func shoegazeIOSAppModelSwiftIsValidSwiftSyntax() throws {
let source: String = ProjectScaffolder.shoegazeIOSAppModelSwift(name: "MyRig")
#expect(try parseCheck(source: source, fileName: "MyRigAppModel.swift"),
"shoegaze-ios AppModel.swift must pass swiftc -parse")
}
@Test func shoegazeMacOSAppSwiftIsValidSwiftSyntax() throws {
let source: String = ProjectScaffolder.shoegazeMacOSAppSwift(name: "MyRig")
#expect(try parseCheck(source: source, fileName: "MyRigApp.swift"),
"shoegaze macOS App.swift must pass swiftc -parse")
}
@Test func shoegazeMacOSAppModelSwiftIsValidSwiftSyntax() throws {
let source: String = ProjectScaffolder.shoegazeMacOSAppModelSwift(name: "MyRig")
#expect(try parseCheck(source: source, fileName: "MyRigAppModel.swift"),
"shoegaze macOS AppModel.swift must pass swiftc -parse")
}
}
@@ -0,0 +1,111 @@
// BeatTrackFeatureTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("BeatTrack.Control — feature-fed (feature)")
struct BeatTrackFeatureTests {
let engine: SynthesisEngine
var graph: SynthGraph { makeSynthGraph(engine: engine) }
let blockSize: Int = 512
let sampleRate: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 512, sampleRate: 44100)
try engine.start()
}
@Test func rateIsControl() {
let gen: BeatTrack.Control = BeatTrack.Control(feature: 0.0)
#expect(gen.rate == .control)
}
@Test func fourOutputRows() {
let gen: BeatTrack.Control = BeatTrack.Control(feature: 0.0)
#expect(gen.outputChannelCount == 4)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(out.count == 4)
for row: Int in 0..<4 {
#expect(Array(out[row].prefix(blockSize)).count == blockSize)
}
}
/// Each output row is flat across the block (block-quantised triggers / tempo).
@Test func rowsAreFlat() {
let gen: BeatTrack.Control = BeatTrack.Control(feature: 0.5)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
for row: Int in 0..<4 {
let first: Double = out[row][0]
for i: Int in 0..<blockSize {
#expect(out[row][i] == first, "row \(row) not flat at \(i)")
}
}
}
/// Pre-lock tempo (row 3) defaults to the preferred BPM.
@Test func preLockTempoIsPreferred() {
let gen: BeatTrack.Control = BeatTrack.Control(feature: 0.0)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(abs(out[3][0] - beatTrackPreferredBPM) < 1e-9)
}
/// A 2 Hz impulse feature (120 BPM) drives the tempo output to ≈120.
@Test func locksToImpulseFeature() {
// 2 Hz impulse → beat every 0.5 s → 120 BPM.
let feature: Impulse.Audio = Impulse.Audio(freq: 2.0)
let gen: BeatTrack.Control = BeatTrack.Control(feature: feature)
var lastTempo: Double = 0.0
// ~9 s of audio at 512-sample blocks.
for _ in 0..<800 {
let g: SynthGraph = makeSynthGraph(engine: engine)
let out: [[Double]] = gen.calculatedSamples(graph: g, count: blockSize)
lastTempo = out[3][0]
advanceBlock(engine)
}
#expect(abs(lastTempo - 120.0) < 120.0 * 0.10,
"expected ≈120 BPM, got \(lastTempo)")
}
/// The `odf:` enum init and the `feature:` convenience init are equivalent.
@Test func enumInitMatchesConvenience() {
let feature: Impulse.Audio = Impulse.Audio(freq: 2.0)
let gen: BeatTrack.Control = BeatTrack.Control(odf: .feature(feature))
var lastTempo: Double = 0.0
for _ in 0..<800 {
let g: SynthGraph = makeSynthGraph(engine: engine)
let out: [[Double]] = gen.calculatedSamples(graph: g, count: blockSize)
lastTempo = out[3][0]
advanceBlock(engine)
}
#expect(abs(lastTempo - 120.0) < 120.0 * 0.10,
"enum-init feature path: expected ≈120 BPM, got \(lastTempo)")
}
/// Silence: no NaN/Inf in any row, tempo finite.
@Test func silenceProducesNoNaN() {
let gen: BeatTrack.Control = BeatTrack.Control(feature: 0.0)
for _ in 0..<200 {
let g: SynthGraph = makeSynthGraph(engine: engine)
let out: [[Double]] = gen.calculatedSamples(graph: g, count: blockSize)
for row: Int in 0..<4 {
for i: Int in 0..<blockSize {
#expect(out[row][i].isFinite, "row \(row) sample \(i) not finite")
}
}
advanceBlock(engine)
}
}
@Test func floatValueReturnsBeatRow() {
let gen: BeatTrack.Control = BeatTrack.Control(feature: 0.0)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(gen.floatValue(graph: graph) == gen.previousOutputValue)
}
}
@@ -0,0 +1,89 @@
// BeatTrackSpectralFluxTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("BeatTrack.Control — FFT-fed (spectralFlux)")
struct BeatTrackSpectralFluxTests {
let sampleRate: Double = 44100
let fftSize: Int = 1024
let hopSize: Int = 512
let blockSize: Int = 512
private func makeEngine() throws -> SynthesisEngine {
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
try engine.start()
return engine
}
@Test func rateIsControl() throws {
let engine: SynthesisEngine = try makeEngine()
defer { engine.stop() }
let chain: SpectralChain.Audio = SpectralChain.Audio(
input: Double(0.0), fftSize: fftSize, hopSize: hopSize, analyzeOnly: true)
let gen: BeatTrack.Control = BeatTrack.Control(analysis: chain)
#expect(gen.rate == .control)
#expect(gen.outputChannelCount == 4)
}
/// The `odf:` enum init and the `analysis:` convenience init are equivalent.
@Test func enumInitMatchesConvenience() throws {
let engine: SynthesisEngine = try makeEngine()
defer { engine.stop() }
let chain: SpectralChain.Audio = SpectralChain.Audio(
input: Double(0.0), fftSize: fftSize, hopSize: hopSize, analyzeOnly: true)
let gen: BeatTrack.Control = BeatTrack.Control(odf: .spectralFlux(analysis: chain))
#expect(gen.rate == .control)
#expect(gen.outputChannelCount == 4)
}
/// FFT-fed path: a 2 Hz click track (120 BPM) drives spectral flux that locks
/// the tempo near 120. Looser tolerance than the feature-fed path due to FFT
/// time-smearing of the onset.
@Test func locksToClickTrack() throws {
let engine: SynthesisEngine = try makeEngine()
defer { engine.stop() }
// Broadband clicks at 2 Hz → spectral flux spikes at the beat rate.
let clicks: Impulse.Audio = Impulse.Audio(freq: 2.0)
let chain: SpectralChain.Audio = SpectralChain.Audio(
input: clicks, fftSize: fftSize, hopSize: hopSize, analyzeOnly: true)
let gen: BeatTrack.Control = BeatTrack.Control(analysis: chain)
var lastTempo: Double = 0.0
for _ in 0..<900 {
let g: SynthGraph = makeSynthGraph(engine: engine)
let out: [[Double]] = gen.calculatedSamples(graph: g, count: blockSize)
lastTempo = out[3][0]
advanceBlock(engine)
}
#expect(abs(lastTempo - 120.0) < 120.0 * 0.15,
"expected ≈120 BPM from click track, got \(lastTempo)")
}
/// Silent input: no NaN/Inf, tempo finite (holds the default).
@Test func silenceProducesNoNaN() throws {
let engine: SynthesisEngine = try makeEngine()
defer { engine.stop() }
let chain: SpectralChain.Audio = SpectralChain.Audio(
input: Double(0.0), fftSize: fftSize, hopSize: hopSize, analyzeOnly: true)
let gen: BeatTrack.Control = BeatTrack.Control(analysis: chain)
for _ in 0..<200 {
let g: SynthGraph = makeSynthGraph(engine: engine)
let out: [[Double]] = gen.calculatedSamples(graph: g, count: blockSize)
for row: Int in 0..<4 {
for i: Int in 0..<blockSize {
#expect(out[row][i].isFinite)
}
}
advanceBlock(engine)
}
}
}
@@ -0,0 +1,158 @@
// BeatTrackerCoreTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@Suite("BeatTrackerCore")
struct BeatTrackerCoreTests {
let sampleRate: Double = 44100
/// Samples per feature at the default feature rate — drive one feature per `processBlock`.
var featureHop: Int { max(1, Int((sampleRate / beatTrackFeatureRateHz).rounded())) }
private func makeCore(
minBPM: Double = beatTrackMinBPM,
maxBPM: Double = beatTrackMaxBPM,
preferredBPM: Double = beatTrackPreferredBPM
) -> BeatTrackerCore {
BeatTrackerCore(
minBPM: minBPM,
maxBPM: maxBPM,
preferredBPM: preferredBPM,
windowSeconds: beatTrackMaxWindowSeconds,
featureRateHz: beatTrackFeatureRateHz
)
}
/// Feed `features` features (one per block), firing an impulse ODF every
/// `periodFeatures`-th feature. Returns counts of each trigger.
@discardableResult
private func driveImpulseTrain(
_ core: BeatTrackerCore,
periodFeatures: Int,
features: Int
) -> (beats: Int, eighths: Int, sixteenths: Int) {
var beats: Int = 0
var eighths: Int = 0
var sixteenths: Int = 0
for f: Int in 0..<features {
let odf: Double = (f % periodFeatures == 0) ? 1.0 : 0.0
core.processBlock(odf: odf, sampleCount: featureHop, sampleRate: sampleRate)
if core.beatTriggered { beats += 1 }
if core.eighthTriggered { eighths += 1 }
if core.sixteenthTriggered { sixteenths += 1 }
}
return (beats, eighths, sixteenths)
}
// MARK: - Tempo lock
/// Impulse train at 90 features-period-ish locks the tempo near the
/// corresponding BPM (below the 120 preference centre).
@Test func locksTempoBelowPreferred() {
let core: BeatTrackerCore = makeCore()
// 57 features ≈ 60·86/57 ≈ 90.5 BPM.
let period: Int = 57
driveImpulseTrain(core, periodFeatures: period, features: 800)
let expected: Double = 60.0 * beatTrackFeatureRateHz / Double(period)
#expect(abs(core.tempoBPM - expected) < expected * 0.06,
"expected ≈\(expected) BPM, got \(core.tempoBPM)")
}
/// Impulse train above the preference centre also locks — guards against a
/// hard-coded / preferred-only result.
@Test func locksTempoAbovePreferred() {
let core: BeatTrackerCore = makeCore()
// 36 features ≈ 60·86/36 ≈ 143.3 BPM.
let period: Int = 36
driveImpulseTrain(core, periodFeatures: period, features: 800)
let expected: Double = 60.0 * beatTrackFeatureRateHz / Double(period)
#expect(abs(core.tempoBPM - expected) < expected * 0.06,
"expected ≈\(expected) BPM, got \(core.tempoBPM)")
}
/// Two distinct inputs must produce two distinct tempo estimates.
@Test func distinctInputsGiveDistinctTempi() {
let slow: BeatTrackerCore = makeCore()
let fast: BeatTrackerCore = makeCore()
driveImpulseTrain(slow, periodFeatures: 57, features: 800)
driveImpulseTrain(fast, periodFeatures: 36, features: 800)
#expect(fast.tempoBPM > slow.tempoBPM + 30.0,
"fast \(fast.tempoBPM) should clearly exceed slow \(slow.tempoBPM)")
}
// MARK: - Beat spacing / subdivisions
@Test func beatCountMatchesPeriod() {
let core: BeatTrackerCore = makeCore()
let period: Int = 43 // ≈120 BPM
let features: Int = 860 // ~20 beats
let counts: (beats: Int, eighths: Int, sixteenths: Int) =
driveImpulseTrain(core, periodFeatures: period, features: features)
let expectedBeats: Double = Double(features) / Double(period)
#expect(abs(Double(counts.beats) - expectedBeats) <= 2.0,
"expected ≈\(expectedBeats) beats, got \(counts.beats)")
}
@Test func subdivisionsFireFasterThanBeat() {
let core: BeatTrackerCore = makeCore()
let counts: (beats: Int, eighths: Int, sixteenths: Int) =
driveImpulseTrain(core, periodFeatures: 43, features: 860)
// Eighth ≈ 2×, sixteenth ≈ 4× the beat rate.
#expect(abs(Double(counts.eighths) - 2.0 * Double(counts.beats)) <= 3.0,
"eighths \(counts.eighths) ≉ 2× beats \(counts.beats)")
#expect(abs(Double(counts.sixteenths) - 4.0 * Double(counts.beats)) <= 5.0,
"sixteenths \(counts.sixteenths) ≉ 4× beats \(counts.beats)")
}
// MARK: - Edge cases
/// Silence: tempo holds the pre-lock default, stays finite, and the phase
/// free-runs (beats still fire).
@Test func silenceHoldsTempoAndFreeRuns() {
let core: BeatTrackerCore = makeCore()
var beats: Int = 0
for _ in 0..<800 {
core.processBlock(odf: 0.0, sampleCount: featureHop, sampleRate: sampleRate)
if core.beatTriggered { beats += 1 }
}
#expect(core.tempoBPM.isFinite)
#expect(abs(core.tempoBPM - beatTrackPreferredBPM) < 1e-9,
"silence should hold the preferred tempo, got \(core.tempoBPM)")
#expect(beats > 0, "phase should free-run at the default tempo")
}
/// Constant (DC) ODF: whitening removes the offset, so no NaN/Inf and tempo
/// stays finite and sane (no degenerate lock).
@Test func dcInputStaysFinite() {
let core: BeatTrackerCore = makeCore()
for _ in 0..<800 {
core.processBlock(odf: 0.5, sampleCount: featureHop, sampleRate: sampleRate)
}
#expect(core.tempoBPM.isFinite)
#expect(core.tempoBPM >= beatTrackMinBPM && core.tempoBPM <= beatTrackMaxBPM,
"tempo \(core.tempoBPM) out of bounds for DC input")
}
/// Blocks longer than one feature hop still advance the tracker (multiple
/// features per block) and lock tempo. Each big block spans 4 feature hops;
/// an onset every 11 big blocks → 44 features ≈ 117 BPM.
@Test func longBlockEmitsMultipleFeaturesAndLocks() {
let core: BeatTrackerCore = makeCore()
let bigBlock: Int = featureHop * 4
let periodBlocks: Int = 11
for b: Int in 0..<260 {
let odf: Double = (b % periodBlocks == 0) ? 1.0 : 0.0
core.processBlock(odf: odf, sampleCount: bigBlock, sampleRate: sampleRate)
}
let expected: Double = 60.0 * beatTrackFeatureRateHz / Double(periodBlocks * 4)
#expect(core.tempoBPM.isFinite)
#expect(abs(core.tempoBPM - expected) < expected * 0.08,
"expected ≈\(expected) BPM, got \(core.tempoBPM)")
}
}
@@ -0,0 +1,179 @@
// LoudnessControlTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("Loudness.Control")
struct LoudnessControlTests {
let engine: SynthesisEngine
var graph: SynthGraph { makeSynthGraph(engine: engine) }
let blockSize: Int = 512
let sampleRate: Double = 44100
let fftSize: Int = 2048
init() throws {
engine = makeTestEngine(blockSize: 512, sampleRate: 44100)
try engine.start()
}
/// A spectral buffer holding a single tone (one bin) at `freqHz` with the
/// given magnitude; every other bin is zero.
private func toneBuffer(freqHz: Double, magnitude: Float) -> SpectralBuffer {
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let binHz: Double = sampleRate / Double(fftSize)
let bin: Int = Int((freqHz / binHz).rounded())
buf.setMagnitude(magnitude, at: bin)
return buf
}
/// dB offset so a unit-magnitude tone bin reads `targetDB` SPL.
/// `bandLevel = 20·log10(mag) + calibrationDB`; with `mag = 1` → `calibrationDB`.
private func calibrationFor(targetDB: Double, magnitude: Float) -> Double {
targetDB - 20.0 * Foundation.log10(Double(magnitude))
}
private func readLoudness(_ gen: Loudness.Control) -> Double {
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
return out[0][blockSize - 1]
}
private let models: [LoudnessModel] = [
.barkEstimate,
.realtimeZwicker(smask: loudnessDefaultSMask, tmask: loudnessDefaultTMask),
.iso532b(field: .free)
]
// MARK: - Shape
@Test func rateIsControlSingleRow() {
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let gen: Loudness.Control = Loudness.Control(spectral: buf, sampleRate: sampleRate)
#expect(gen.rate == .control)
#expect(gen.outputChannelCount == 1)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(out.count == 1)
#expect(Array(out[0].prefix(blockSize)).count == blockSize)
}
// MARK: - Silence
@Test func silenceIsZeroAndFinite() {
for model: LoudnessModel in models {
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let gen: Loudness.Control = Loudness.Control(
model: model, spectral: buf, sampleRate: sampleRate)
let n: Double = readLoudness(gen)
#expect(n.isFinite, "silence not finite for \(model)")
#expect(n < 0.05, "silence should be ~0 sones, got \(n) for \(model)")
}
}
// MARK: - Monotonic
@Test func louderToneGivesMoreSones() {
for model: LoudnessModel in models {
let quiet: Loudness.Control = Loudness.Control(
model: model, spectral: toneBuffer(freqHz: 1000, magnitude: 1.0),
sampleRate: sampleRate, calibrationDB: 70)
let loud: Loudness.Control = Loudness.Control(
model: model, spectral: toneBuffer(freqHz: 1000, magnitude: 10.0),
sampleRate: sampleRate, calibrationDB: 70)
let nQuiet: Double = readLoudness(quiet)
let nLoud: Double = readLoudness(loud)
#expect(nLoud > nQuiet,
"louder tone should be louder for \(model): \(nLoud) vs \(nQuiet)")
}
}
// MARK: - Stevens doubling (barkEstimate is exact power-law)
@Test func tenDBRoughlyDoublesBarkEstimate() {
// +10 dB = magnitude × sqrt(10).
let m0: Float = 1.0
let m1: Float = Float(Foundation.pow(10.0, 0.5))
let lo: Loudness.Control = Loudness.Control(
model: .barkEstimate, spectral: toneBuffer(freqHz: 1000, magnitude: m0),
sampleRate: sampleRate, calibrationDB: 60)
let hi: Loudness.Control = Loudness.Control(
model: .barkEstimate, spectral: toneBuffer(freqHz: 1000, magnitude: m1),
sampleRate: sampleRate, calibrationDB: 60)
let ratio: Double = readLoudness(hi) / max(1e-9, readLoudness(lo))
#expect(abs(ratio - 2.0) < 0.2, "expected ≈2× per +10 dB, got \(ratio)")
}
// MARK: - Calibration anchor: 1 kHz @ 40 dB ≈ 1 sone
@Test func anchorBarkEstimate() {
let cal: Double = calibrationFor(targetDB: 40, magnitude: 1.0)
let gen: Loudness.Control = Loudness.Control(
model: .barkEstimate, spectral: toneBuffer(freqHz: 1000, magnitude: 1.0),
sampleRate: sampleRate, calibrationDB: cal)
let n: Double = readLoudness(gen)
#expect(abs(n - 1.0) < 0.3, "barkEstimate 1 kHz@40 dB expected ≈1 sone, got \(n)")
}
@Test func anchorISO532B() {
let cal: Double = calibrationFor(targetDB: 40, magnitude: 1.0)
let gen: Loudness.Control = Loudness.Control(
model: .iso532b(field: .free), spectral: toneBuffer(freqHz: 1000, magnitude: 1.0),
sampleRate: sampleRate, calibrationDB: cal)
let n: Double = readLoudness(gen)
#expect(n > 0.5 && n < 1.7, "iso532b 1 kHz@40 dB expected ≈1 sone, got \(n)")
}
@Test func anchorRealtimeZwicker() {
let cal: Double = calibrationFor(targetDB: 40, magnitude: 1.0)
let gen: Loudness.Control = Loudness.Control(
model: .realtimeZwicker(smask: loudnessDefaultSMask, tmask: loudnessDefaultTMask),
spectral: toneBuffer(freqHz: 1000, magnitude: 1.0),
sampleRate: sampleRate, calibrationDB: cal)
let n: Double = readLoudness(gen)
#expect(n > 0.5 && n < 2.0, "realtimeZwicker 1 kHz@40 dB expected ≈1 sone, got \(n)")
}
// MARK: - Field
@Test func diffuseDiffersFromFreeForHighTone() {
// 5 kHz: DDF correction is large (+4 dB), so diffuse ≠ free.
let cal: Double = calibrationFor(targetDB: 60, magnitude: 1.0)
let free: Loudness.Control = Loudness.Control(
model: .iso532b(field: .free), spectral: toneBuffer(freqHz: 5000, magnitude: 1.0),
sampleRate: sampleRate, calibrationDB: cal)
let diffuse: Loudness.Control = Loudness.Control(
model: .iso532b(field: .diffuse), spectral: toneBuffer(freqHz: 5000, magnitude: 1.0),
sampleRate: sampleRate, calibrationDB: cal)
#expect(abs(readLoudness(free) - readLoudness(diffuse)) > 0.05,
"free vs diffuse should differ for a 5 kHz tone")
}
// MARK: - Live chain integration
@Test func runsOverLiveChainFinite() throws {
let osc: OscSin.Audio = OscSin.Audio(freq: 1000.0, mul: 0.5)
let chain: SpectralChain.Audio = SpectralChain.Audio(
input: osc, fftSize: fftSize, hopSize: 512, analyzeOnly: true)
let gen: Loudness.Control = Loudness.Control(
model: .iso532b(field: .free), analysis: chain, sampleRate: sampleRate)
for _ in 0..<60 {
let g: SynthGraph = makeSynthGraph(engine: engine)
let out: [[Double]] = gen.calculatedSamples(graph: g, count: blockSize)
for i: Int in 0..<blockSize { #expect(out[0][i].isFinite) }
advanceBlock(engine)
}
#expect(gen.previousOutputValue > 0.0, "a 1 kHz tone through the chain should read > 0 sones")
}
@Test func floatValueReturnsLatest() {
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let gen: Loudness.Control = Loudness.Control(spectral: buf, sampleRate: sampleRate)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(gen.floatValue(graph: graph) == gen.previousOutputValue)
}
}
@@ -0,0 +1,144 @@
// RunningMaxAudioTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("RunningMax.Audio")
struct RunningMaxAudioTests {
let engine: SynthesisEngine
var graph: SynthGraph { makeSynthGraph(engine: engine) }
let blockSize: Int = 64
let sampleRate: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func rateIsAudio() {
let gen: RunningMax.Audio = RunningMax.Audio(input: 0.0)
#expect(gen.rate == .audio)
}
/// Output count matches request.
@Test func outputCountMatchesRequest() {
let gen: RunningMax.Audio = RunningMax.Audio(input: 0.5)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(Array(out[0].prefix(blockSize)).count == blockSize)
}
/// First sample initializes extreme to the first input value.
@Test func firstSampleInitializesToFirstInput() {
let inputVal: Double = 0.3
let gen: RunningMax.Audio = RunningMax.Audio(input: inputVal)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(abs(out[0][0] - inputVal) < 1e-12,
"first sample should equal first input \(inputVal), got \(out[0][0])")
}
/// Tracks increasing extreme over a varying input.
///
/// Input starts at 0.0 and increases by 0.01 per sample.
/// The running maximum should track every new maximum.
@Test func tracksIncreasingExtreme() {
let inputSignal: Closure = Closure { _, i in Double(i) * 0.01 }
let gen: RunningMax.Audio = RunningMax.Audio(input: inputSignal)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
let expected: Double = Double(i) * 0.01
#expect(abs(out[0][i] - expected) < 1e-12,
"sample \(i): expected max \(expected), got \(out[0][i])")
}
}
/// Ignores values less than the current maximum.
@Test func ignoresValuesLessThanCurrentMax() {
// Input: 0.8 at sample 0 (init), then alternating 0.1 and 0.8.
// The maximum should stay at 0.8 throughout.
let inputSignal: Closure = Closure { _, i in i == 0 ? 0.8 : (i % 2 == 0 ? 0.8 : 0.1) }
let gen: RunningMax.Audio = RunningMax.Audio(input: inputSignal)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
#expect(abs(out[0][i] - 0.8) < 1e-12,
"maximum should stay 0.8, got \(out[0][i]) at sample \(i)")
}
}
/// Rising trig edge resets extreme to the current input value at that frame.
@Test func trigRisingEdgeResetsToCurrentInput() {
// Input: 0.9 for first 32 samples, then 0.2 for 32+.
// Trig rises at sample 32 while input is 0.2, resetting max to 0.2.
let inputSignal: Closure = Closure { _, i in i < 32 ? 0.9 : 0.2 }
let trigSignal: Closure = Closure { _, i in i < 32 ? 0.0 : 1.0 }
let gen: RunningMax.Audio = RunningMax.Audio(input: inputSignal, trig: trigSignal)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
// Samples 0..31: running max = 0.9.
for i: Int in 0..<32 {
#expect(abs(out[0][i] - 0.9) < 1e-12,
"sample \(i): expected 0.9, got \(out[0][i])")
}
// Sample 32: reset to input at frame 32 = 0.2.
#expect(abs(out[0][32] - 0.2) < 1e-12,
"sample 32 after reset: expected 0.2, got \(out[0][32])")
// Samples 33+: running max of 0.2 (input stays at 0.2, no further reset).
for i: Int in 33..<blockSize {
#expect(abs(out[0][i] - 0.2) < 1e-12,
"sample \(i): expected 0.2 (no new maximum), got \(out[0][i])")
}
}
/// Cross-block continuity: extreme carries across audio blocks.
@Test func crossBlockContinuity() {
let firstSerial: UInt64 = engine.segmentSerial
// Block 1: input = 0.7 (sets max to 0.7).
// Block 2: input = 0.3 (max stays 0.7).
let inputSignal: Closure = Closure { graph, _ in
graph.engine.segmentSerial == firstSerial ? 0.7 : 0.3
}
let gen: RunningMax.Audio = RunningMax.Audio(input: inputSignal)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
advanceBlock(engine)
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
// The maximum from block 1 (0.7) should persist in block 2.
for i: Int in 0..<blockSize {
#expect(abs(out2[0][i] - 0.7) < 1e-12,
"block 2 sample \(i): expected max 0.7, got \(out2[0][i])")
}
}
/// Fan-out: two calls same segment return identical first channel.
@Test func fanOut() {
let inputSignal: Closure = Closure { _, i in Double(i) * 0.01 }
let gen: RunningMax.Audio = RunningMax.Audio(input: inputSignal)
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
#expect(out1[0][i] == out2[0][i])
}
}
/// mul/add: output is original*2+1.
@Test func mulAdd() {
let inputSignal: Closure = Closure { _, i in Double(i) * 0.01 }
let genBase: RunningMax.Audio = RunningMax.Audio(input: inputSignal)
let genScaled: RunningMax.Audio = RunningMax.Audio(
input: inputSignal,
mul: 2.0,
add: 1.0
)
let base: [[Double]] = genBase.calculatedSamples(graph: graph, count: blockSize)
let scaled: [[Double]] = genScaled.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
let expected: Double = base[0][i] * 2.0 + 1.0
#expect(abs(scaled[0][i] - expected) < 1e-12,
"mulAdd sample \(i): expected \(expected) got \(scaled[0][i])")
}
}
}
@@ -0,0 +1,139 @@
// RunningMaxControlTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("RunningMax.Control")
struct RunningMaxControlTests {
let engine: SynthesisEngine
var graph: SynthGraph { makeSynthGraph(engine: engine) }
let blockSize: Int = 64
let sampleRate: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func rateIsControl() {
let gen: RunningMax.Control = RunningMax.Control(input: 0.0)
#expect(gen.rate == .control)
}
/// Output count matches request.
@Test func outputCountMatchesRequest() {
let gen: RunningMax.Control = RunningMax.Control(input: 0.5)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(Array(out[0].prefix(blockSize)).count == blockSize)
}
/// Block-final extreme is flat (vDSP_vfillD): all samples equal the final max.
@Test func outputBlockIsFlat() {
let inputSignal: Closure = Closure { _, i in Double(i) * 0.001 }
let gen: RunningMax.Control = RunningMax.Control(input: inputSignal)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let expected: Double = out[0][blockSize - 1]
for i: Int in 0..<blockSize {
#expect(out[0][i] == expected,
"expected flat block, sample \(i) = \(out[0][i]) differs from last = \(expected)")
}
}
/// Block-final value matches the running maximum of all audio samples in the block.
@Test func blockFinalValueIsRunningMaxOfBlock() {
// Input ascends 0.0 → 0.63 over the block. The maximum after scanning = (blockSize-1)*0.01.
let inputSignal: Closure = Closure { _, i in Double(i) * 0.01 }
let gen: RunningMax.Control = RunningMax.Control(input: inputSignal)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
let expectedMax: Double = Double(blockSize - 1) * 0.01
#expect(abs(gen.previousOutputValue - expectedMax) < 1e-12,
"block final value should be \(expectedMax), got \(gen.previousOutputValue)")
}
/// Trig rising edge in a block resets extreme to current input at that frame.
@Test func trigEdgeInBlockResetsExtreme() {
// Input: 0.9 for first 32 samples, then 0.2 for 32..63.
// Trig rises at sample 32. At reset, current input = 0.2,
// so new max after the reset = 0.2 (input stays at 0.2 for remaining samples).
let inputSignal: Closure = Closure { _, i in i < 32 ? 0.9 : 0.2 }
let trigSignal: Closure = Closure { _, i in i < 32 ? 0.0 : 1.0 }
let gen: RunningMax.Control = RunningMax.Control(input: inputSignal, trig: trigSignal)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
// After reset at sample 32 (input=0.2), remaining samples are also 0.2.
// Running max after reset = 0.2.
#expect(abs(gen.previousOutputValue - 0.2) < 1e-12,
"after trig reset at sample 32 (input=0.2), block max should be 0.2, got \(gen.previousOutputValue)")
}
/// floatValue returns previousOutputValue.
@Test func floatValueReturnsPreviousOutputValue() {
let gen: RunningMax.Control = RunningMax.Control(input: 0.5)
#expect(gen.floatValue(graph: graph) == gen.previousOutputValue)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(gen.floatValue(graph: graph) == gen.previousOutputValue)
}
/// Fan-out: two calls same segment return identical first channel.
@Test func fanOut() {
let inputSignal: Closure = Closure { _, i in Double(i) * 0.01 }
let gen: RunningMax.Control = RunningMax.Control(input: inputSignal)
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
#expect(out1[0][i] == out2[0][i])
}
}
/// Sub-block bypass: second call in same segment is cache hit; state not re-advanced.
@Test func subBlockBypassCacheHit() {
let inputSignal: Closure = Closure { _, i in Double(i) * 0.01 }
let gen: RunningMax.Control = RunningMax.Control(input: inputSignal)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
let stateAfterFirst: Double = gen.previousOutputValue
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(gen.previousOutputValue == stateAfterFirst,
"second call must be a cache hit — state must not re-advance")
}
/// Cross-block continuity: extreme carries across audio blocks.
@Test func crossBlockContinuity() {
let firstSerial: UInt64 = engine.segmentSerial
// Block 1: input = 0.8, sets max to 0.8.
// Block 2: input = 0.1, max stays 0.8.
let inputSignal: Closure = Closure { graph, _ in
graph.engine.segmentSerial == firstSerial ? 0.8 : 0.1
}
let gen: RunningMax.Control = RunningMax.Control(input: inputSignal)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(abs(gen.previousOutputValue - 0.8) < 1e-12)
advanceBlock(engine)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(abs(gen.previousOutputValue - 0.8) < 1e-12,
"extreme 0.8 from block 1 should persist in block 2 (0.1 < 0.8)")
}
/// mul/add: output is original*2+1.
@Test func mulAdd() {
let inputSignal: Closure = Closure { _, i in Double(i) * 0.01 }
let genBase: RunningMax.Control = RunningMax.Control(input: inputSignal)
let genScaled: RunningMax.Control = RunningMax.Control(
input: inputSignal,
mul: 2.0,
add: 1.0
)
let base: [[Double]] = genBase.calculatedSamples(graph: graph, count: blockSize)
let scaled: [[Double]] = genScaled.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
let expected: Double = base[0][i] * 2.0 + 1.0
#expect(abs(scaled[0][i] - expected) < 1e-12,
"mulAdd sample \(i): expected \(expected) got \(scaled[0][i])")
}
}
}
@@ -0,0 +1,147 @@
// RunningMinAudioTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("RunningMin.Audio")
struct RunningMinAudioTests {
let engine: SynthesisEngine
var graph: SynthGraph { makeSynthGraph(engine: engine) }
let blockSize: Int = 64
let sampleRate: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func rateIsAudio() {
let gen: RunningMin.Audio = RunningMin.Audio(input: 0.0)
#expect(gen.rate == .audio)
}
/// Output count matches request.
@Test func outputCountMatchesRequest() {
let gen: RunningMin.Audio = RunningMin.Audio(input: 0.5)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(Array(out[0].prefix(blockSize)).count == blockSize)
}
/// First sample initializes extreme to the first input value.
@Test func firstSampleInitializesToFirstInput() {
let inputVal: Double = 0.7
let gen: RunningMin.Audio = RunningMin.Audio(input: inputVal)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(abs(out[0][0] - inputVal) < 1e-12,
"first sample should equal first input \(inputVal), got \(out[0][0])")
}
/// Tracks decreasing extreme over a varying input.
///
/// Input starts at 1.0 and decreases by 0.01 per sample.
/// The running minimum should track every new minimum.
@Test func tracksDecreasingExtreme() {
// Input: 1.0, 0.99, 0.98, ... → the minimum decreases each sample.
let inputSignal: Closure = Closure { _, i in 1.0 - Double(i) * 0.01 }
let gen: RunningMin.Audio = RunningMin.Audio(input: inputSignal)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
let expected: Double = 1.0 - Double(i) * 0.01
#expect(abs(out[0][i] - expected) < 1e-12,
"sample \(i): expected min \(expected), got \(out[0][i])")
}
}
/// Ignores values that are greater than the current minimum.
@Test func ignoresValuesGreaterThanCurrentMin() {
// Input: 0.5 at sample 0 (init), then alternating 1.0 and 0.5.
// The minimum should stay at 0.5 throughout.
let inputSignal: Closure = Closure { _, i in i == 0 ? 0.5 : (i % 2 == 0 ? 0.5 : 1.0) }
let gen: RunningMin.Audio = RunningMin.Audio(input: inputSignal)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
#expect(abs(out[0][i] - 0.5) < 1e-12,
"minimum should stay 0.5, got \(out[0][i]) at sample \(i)")
}
}
/// Rising trig edge resets extreme to the current input value at that frame.
@Test func trigRisingEdgeResetsToCurrentInput() {
// Input: starts at 0.1, trig rises at sample 32 while input is at 0.5.
// Before sample 32: running min of 0.1.
// At sample 32: reset to input value at frame 32.
let inputSignal: Closure = Closure { _, i in i < 32 ? 0.1 : 0.5 }
let trigSignal: Closure = Closure { _, i in i < 32 ? 0.0 : 1.0 }
let gen: RunningMin.Audio = RunningMin.Audio(input: inputSignal, trig: trigSignal)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
// Samples 0..31: running min from 0.1 initial = 0.1.
for i: Int in 0..<32 {
#expect(abs(out[0][i] - 0.1) < 1e-12,
"sample \(i): expected 0.1, got \(out[0][i])")
}
// Sample 32: reset to input at frame 32 = 0.5.
#expect(abs(out[0][32] - 0.5) < 1e-12,
"sample 32 after reset: expected 0.5, got \(out[0][32])")
// Samples 33+: running min of 0.5 (input stays at 0.5, no further reset).
for i: Int in 33..<blockSize {
#expect(abs(out[0][i] - 0.5) < 1e-12,
"sample \(i): expected 0.5 (no new minimum), got \(out[0][i])")
}
}
/// Cross-block continuity: extreme carries across audio blocks.
@Test func crossBlockContinuity() {
// Block 1: input is 0.3 (sets min to 0.3).
// Block 2: input is 0.5 (min stays 0.3 since 0.5 > 0.3).
let firstSerial: UInt64 = engine.segmentSerial
let inputSignal: Closure = Closure { graph, _ in
graph.engine.segmentSerial == firstSerial ? 0.3 : 0.5
}
let gen: RunningMin.Audio = RunningMin.Audio(input: inputSignal)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
advanceBlock(engine)
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
// The minimum from block 1 (0.3) should persist in block 2 since input is 0.5.
for i: Int in 0..<blockSize {
#expect(abs(out2[0][i] - 0.3) < 1e-12,
"block 2 sample \(i): expected min 0.3, got \(out2[0][i])")
}
}
/// Fan-out: two calls same segment return identical first channel.
@Test func fanOut() {
let inputSignal: Closure = Closure { _, i in Double(i) * 0.01 }
let gen: RunningMin.Audio = RunningMin.Audio(input: inputSignal)
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
#expect(out1[0][i] == out2[0][i])
}
}
/// mul/add: output is original*2+1.
@Test func mulAdd() {
// Decreasing input so min updates each sample.
let inputSignal: Closure = Closure { _, i in 1.0 - Double(i) * 0.01 }
let genBase: RunningMin.Audio = RunningMin.Audio(input: inputSignal)
let genScaled: RunningMin.Audio = RunningMin.Audio(
input: inputSignal,
mul: 2.0,
add: 1.0
)
let base: [[Double]] = genBase.calculatedSamples(graph: graph, count: blockSize)
let scaled: [[Double]] = genScaled.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
let expected: Double = base[0][i] * 2.0 + 1.0
#expect(abs(scaled[0][i] - expected) < 1e-12,
"mulAdd sample \(i): expected \(expected) got \(scaled[0][i])")
}
}
}
@@ -0,0 +1,140 @@
// RunningMinControlTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("RunningMin.Control")
struct RunningMinControlTests {
let engine: SynthesisEngine
var graph: SynthGraph { makeSynthGraph(engine: engine) }
let blockSize: Int = 64
let sampleRate: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func rateIsControl() {
let gen: RunningMin.Control = RunningMin.Control(input: 0.0)
#expect(gen.rate == .control)
}
/// Output count matches request.
@Test func outputCountMatchesRequest() {
let gen: RunningMin.Control = RunningMin.Control(input: 0.5)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(Array(out[0].prefix(blockSize)).count == blockSize)
}
/// Block-final extreme is flat (vDSP_vfillD): all samples equal the final min.
@Test func outputBlockIsFlat() {
// Decreasing input: the scan finds a new minimum on each audio sample in the block.
let inputSignal: Closure = Closure { _, i in 1.0 - Double(i) * 0.001 }
let gen: RunningMin.Control = RunningMin.Control(input: inputSignal)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let expected: Double = out[0][blockSize - 1]
for i: Int in 0..<blockSize {
#expect(out[0][i] == expected,
"expected flat block, sample \(i) = \(out[0][i]) differs from last = \(expected)")
}
}
/// Block-final value matches the running minimum of all audio samples in the block.
@Test func blockFinalValueIsRunningMinOfBlock() {
// Input descends 1.0 → 0.0 over the block. The minimum after scanning = 1 - (blockSize-1)*0.01.
let inputSignal: Closure = Closure { _, i in 1.0 - Double(i) * 0.01 }
let gen: RunningMin.Control = RunningMin.Control(input: inputSignal)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
let expectedMin: Double = 1.0 - Double(blockSize - 1) * 0.01
#expect(abs(gen.previousOutputValue - expectedMin) < 1e-12,
"block final value should be \(expectedMin), got \(gen.previousOutputValue)")
}
/// Trig rising edge in a block resets extreme to current input at that frame.
@Test func trigEdgeInBlockResetsExtreme() {
// Input is 0.1 for samples 0..31, then 0.8 for 32..63.
// Trig rises at sample 32. At reset, the current input is 0.8, so the
// new minimum after the block is 0.8 (input stays at 0.8 after reset).
let inputSignal: Closure = Closure { _, i in i < 32 ? 0.1 : 0.8 }
let trigSignal: Closure = Closure { _, i in i < 32 ? 0.0 : 1.0 }
let gen: RunningMin.Control = RunningMin.Control(input: inputSignal, trig: trigSignal)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
// After reset at sample 32 (input=0.8), remaining samples are also 0.8.
// Running min after reset = 0.8.
#expect(abs(gen.previousOutputValue - 0.8) < 1e-12,
"after trig reset at sample 32 (input=0.8), block min should be 0.8, got \(gen.previousOutputValue)")
}
/// floatValue returns previousOutputValue.
@Test func floatValueReturnsPreviousOutputValue() {
let gen: RunningMin.Control = RunningMin.Control(input: 0.5)
#expect(gen.floatValue(graph: graph) == gen.previousOutputValue)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(gen.floatValue(graph: graph) == gen.previousOutputValue)
}
/// Fan-out: two calls same segment return identical first channel.
@Test func fanOut() {
let inputSignal: Closure = Closure { _, i in 1.0 - Double(i) * 0.01 }
let gen: RunningMin.Control = RunningMin.Control(input: inputSignal)
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
#expect(out1[0][i] == out2[0][i])
}
}
/// Sub-block bypass: second call in same segment is cache hit; state not re-advanced.
@Test func subBlockBypassCacheHit() {
let inputSignal: Closure = Closure { _, i in 1.0 - Double(i) * 0.01 }
let gen: RunningMin.Control = RunningMin.Control(input: inputSignal)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
let stateAfterFirst: Double = gen.previousOutputValue
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(gen.previousOutputValue == stateAfterFirst,
"second call must be a cache hit — state must not re-advance")
}
/// Cross-block continuity: extreme carries across audio blocks.
@Test func crossBlockContinuity() {
let firstSerial: UInt64 = engine.segmentSerial
// Block 1: input = 0.2, sets min to 0.2.
// Block 2: input = 0.9, min stays 0.2.
let inputSignal: Closure = Closure { graph, _ in
graph.engine.segmentSerial == firstSerial ? 0.2 : 0.9
}
let gen: RunningMin.Control = RunningMin.Control(input: inputSignal)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(abs(gen.previousOutputValue - 0.2) < 1e-12)
advanceBlock(engine)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(abs(gen.previousOutputValue - 0.2) < 1e-12,
"extreme 0.2 from block 1 should persist in block 2 (0.9 > 0.2)")
}
/// mul/add: output is original*2+1.
@Test func mulAdd() {
let inputSignal: Closure = Closure { _, i in 1.0 - Double(i) * 0.01 }
let genBase: RunningMin.Control = RunningMin.Control(input: inputSignal)
let genScaled: RunningMin.Control = RunningMin.Control(
input: inputSignal,
mul: 2.0,
add: 1.0
)
let base: [[Double]] = genBase.calculatedSamples(graph: graph, count: blockSize)
let scaled: [[Double]] = genScaled.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
let expected: Double = base[0][i] * 2.0 + 1.0
#expect(abs(scaled[0][i] - expected) < 1e-12,
"mulAdd sample \(i): expected \(expected) got \(scaled[0][i])")
}
}
}
@@ -0,0 +1,117 @@
// SlopeAudioTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("Slope.Audio")
struct SlopeAudioTests {
let engine: SynthesisEngine
var graph: SynthGraph { makeSynthGraph(engine: engine) }
let blockSize: Int = 64
let sampleRate: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func rateIsAudio() {
let gen: Slope.Audio = Slope.Audio(input: 0.0)
#expect(gen.rate == .audio)
}
/// Output count matches request.
@Test func outputCountMatchesRequest() {
let gen: Slope.Audio = Slope.Audio(input: 0.5)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(Array(out[0].prefix(blockSize)).count == blockSize)
}
/// First sample outputs 0.0 (lazy-init — no spike on startup).
@Test func firstSampleOutputsZero() {
let gen: Slope.Audio = Slope.Audio(input: 5.0)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(abs(out[0][0] - 0.0) < 1e-12,
"first sample should be 0.0 (lazy-init), got \(out[0][0])")
}
/// Constant input produces slope 0 after the first sample.
@Test func constantInputSlopeIsZero() {
let gen: Slope.Audio = Slope.Audio(input: 3.0)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
// Sample 0 = 0 (init). Samples 1+ = (3.0 - 3.0) * sr = 0.
for i: Int in 0..<blockSize {
#expect(abs(out[0][i] - 0.0) < 1e-12,
"constant input: slope should be 0 at sample \(i), got \(out[0][i])")
}
}
/// Linear ramp input x[i] = i*k → slope = k * sampleRate for samples >= 1.
///
/// x[n] = n*k, x[n-1] = (n-1)*k → slope = (n*k - (n-1)*k)*sr = k*sr.
@Test func linearRampProducesConstantSlope() {
let k: Double = 0.001 // increment per sample
let expectedSlope: Double = k * sampleRate
let inputSignal: Closure = Closure { _, i in Double(i) * k }
let gen: Slope.Audio = Slope.Audio(input: inputSignal)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
// Sample 0: lazy-init (output 0).
#expect(abs(out[0][0] - 0.0) < 1e-12)
// Samples 1..blockSize-1: slope = k * sampleRate.
for i: Int in 1..<blockSize {
#expect(abs(out[0][i] - expectedSlope) < 1e-9,
"sample \(i): expected slope \(expectedSlope), got \(out[0][i])")
}
}
/// Cross-block continuity: prevSample carries across blocks.
@Test func crossBlockContinuity() {
// A step function: 0.0 in block 1, 1.0 in block 2.
let firstSerial: UInt64 = engine.segmentSerial
let inputSignal: Closure = Closure { graph, _ in
graph.engine.segmentSerial == firstSerial ? 0.0 : 1.0
}
let gen: Slope.Audio = Slope.Audio(input: inputSignal)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
advanceBlock(engine)
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
// First sample of block 2: prev = 0.0 (last sample of block 1), x = 1.0.
// slope = (1.0 - 0.0) * sampleRate.
let expectedSlope: Double = sampleRate
#expect(abs(out2[0][0] - expectedSlope) < 1e-9,
"block 2 sample 0: expected slope \(expectedSlope) (step from 0→1), got \(out2[0][0])")
}
/// Fan-out: two calls same segment return identical first channel.
@Test func fanOut() {
let inputSignal: Closure = Closure { _, i in Double(i) * 0.01 }
let gen: Slope.Audio = Slope.Audio(input: inputSignal)
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
#expect(out1[0][i] == out2[0][i])
}
}
/// mul/add: output is original*2+1.
@Test func mulAdd() {
let k: Double = 0.001
let inputSignal: Closure = Closure { _, i in Double(i) * k }
let genBase: Slope.Audio = Slope.Audio(input: inputSignal)
let genScaled: Slope.Audio = Slope.Audio(input: inputSignal, mul: 2.0, add: 1.0)
let base: [[Double]] = genBase.calculatedSamples(graph: graph, count: blockSize)
let scaled: [[Double]] = genScaled.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
let expected: Double = base[0][i] * 2.0 + 1.0
#expect(abs(scaled[0][i] - expected) < 1e-12,
"mulAdd sample \(i): expected \(expected) got \(scaled[0][i])")
}
}
}
@@ -0,0 +1,161 @@
// SlopeControlTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("Slope.Control")
struct SlopeControlTests {
let engine: SynthesisEngine
var graph: SynthGraph { makeSynthGraph(engine: engine) }
let blockSize: Int = 64
let sampleRate: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func rateIsControl() {
let gen: Slope.Control = Slope.Control(input: 0.0)
#expect(gen.rate == .control)
}
/// Output count matches request.
@Test func outputCountMatchesRequest() {
let gen: Slope.Control = Slope.Control(input: 0.5)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(Array(out[0].prefix(blockSize)).count == blockSize)
}
/// First block outputs 0.0 (lazy-init — no startup spike).
@Test func firstBlockOutputsZero() {
let gen: Slope.Control = Slope.Control(input: 5.0)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(abs(gen.previousOutputValue - 0.0) < 1e-12,
"first block should output 0.0 (lazy-init), got \(gen.previousOutputValue)")
}
/// Constant input produces slope 0 after initialization.
@Test func constantInputSlopeIsZero() {
let gen: Slope.Control = Slope.Control(input: 3.0)
// Block 1: lazy-init → output 0.
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(abs(gen.previousOutputValue - 0.0) < 1e-12,
"first block of constant input: slope = 0")
// Block 2: x stays at 3.0, prev = 3.0 → slope = 0.
advanceBlock(engine)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(abs(gen.previousOutputValue - 0.0) < 1e-12,
"second block of constant input: slope should still be 0")
}
/// Control-rate slope uses controlRate = sampleRate/blockSize.
///
/// If the input steps from 0 to 1 between blocks, the slope is
/// (1.0 - 0.0) * controlRate = sampleRate / blockSize.
@Test func stepInputProducesControlRateSlope() {
let controlRate: Double = sampleRate / Double(blockSize)
let firstSerial: UInt64 = engine.segmentSerial
let inputSignal: Closure = Closure { graph, _ in
graph.engine.segmentSerial == firstSerial ? 0.0 : 1.0
}
let gen: Slope.Control = Slope.Control(input: inputSignal)
// Block 1: lazy-init → output 0, prevSample becomes 0.0.
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(abs(gen.previousOutputValue - 0.0) < 1e-12)
// Block 2: x = 1.0, prev = 0.0 → slope = (1.0 - 0.0) * controlRate.
advanceBlock(engine)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
let expectedSlope: Double = controlRate
#expect(abs(gen.previousOutputValue - expectedSlope) < 1e-9,
"step slope: expected \(expectedSlope), got \(gen.previousOutputValue)")
}
/// Output block is flat (vDSP_vfillD): all samples equal the computed slope.
@Test func outputBlockIsFlat() {
let gen: Slope.Control = Slope.Control(input: 0.5)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let expected: Double = out[0][blockSize - 1]
for i: Int in 0..<blockSize {
#expect(out[0][i] == expected,
"expected flat block, sample \(i) = \(out[0][i]) differs from last = \(expected)")
}
}
/// floatValue returns previousOutputValue.
@Test func floatValueReturnsPreviousOutputValue() {
let gen: Slope.Control = Slope.Control(input: 0.0)
#expect(gen.floatValue(graph: graph) == gen.previousOutputValue)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(gen.floatValue(graph: graph) == gen.previousOutputValue)
}
/// Fan-out: two calls same segment return identical first channel.
@Test func fanOut() {
let gen: Slope.Control = Slope.Control(input: 0.3)
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
#expect(out1[0][i] == out2[0][i])
}
}
/// Sub-block bypass: second call in same segment is cache hit; state not re-advanced.
@Test func subBlockBypassCacheHit() {
let gen: Slope.Control = Slope.Control(input: 1.0)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
let stateAfterFirst: Double = gen.previousOutputValue
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(gen.previousOutputValue == stateAfterFirst,
"second call must be a cache hit — state must not re-advance")
}
/// Cross-block continuity: prevSample carries across blocks.
@Test func crossBlockContinuity() {
let controlRate: Double = sampleRate / Double(blockSize)
let firstSerial: UInt64 = engine.segmentSerial
// Block 1 input = 0.0, block 2+ = 0.5.
let inputSignal: Closure = Closure { graph, _ in
graph.engine.segmentSerial == firstSerial ? 0.0 : 0.5
}
let gen: Slope.Control = Slope.Control(input: inputSignal)
// Block 1: lazy-init, prevSample = 0.0, output = 0.
_ = gen.calculatedSamples(graph: graph, count: blockSize)
// Block 2: x = 0.5, prev = 0.0 → slope = 0.5 * controlRate.
advanceBlock(engine)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
let expectedSlope: Double = 0.5 * controlRate
#expect(abs(gen.previousOutputValue - expectedSlope) < 1e-9,
"cross-block slope: expected \(expectedSlope), got \(gen.previousOutputValue)")
}
/// mul/add: output is original*2+1.
@Test func mulAdd() {
let firstSerial: UInt64 = engine.segmentSerial
let inputSignal: Closure = Closure { graph, _ in
graph.engine.segmentSerial == firstSerial ? 0.0 : 1.0
}
let genBase: Slope.Control = Slope.Control(input: inputSignal)
let genScaled: Slope.Control = Slope.Control(input: inputSignal, mul: 2.0, add: 1.0)
// Block 1: both init to 0 → output 0 (base) and 1 (scaled: 0*2+1).
let base1: [[Double]] = genBase.calculatedSamples(graph: graph, count: blockSize)
let scaled1: [[Double]] = genScaled.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
let expected: Double = base1[0][i] * 2.0 + 1.0
#expect(abs(scaled1[0][i] - expected) < 1e-12,
"block 1 mulAdd sample \(i): expected \(expected) got \(scaled1[0][i])")
}
}
}
@@ -0,0 +1,194 @@
// ZeroCrossingAudioTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("ZeroCrossing.Audio")
struct ZeroCrossingAudioTests {
let engine: SynthesisEngine
var graph: SynthGraph { makeSynthGraph(engine: engine) }
let blockSize: Int = 64
let sampleRate: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func rateIsAudio() {
let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: 0.0)
#expect(gen.rate == .audio)
}
/// Output count matches request.
@Test func outputCountMatchesRequest() {
let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: 0.5)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(Array(out[0].prefix(blockSize)).count == blockSize)
}
/// Constant positive (DC) input produces no zero crossing and freq stays at `0.0`.
///
/// `_prevSample` is lazy-initialised to the first input sample (`+1`). Since `prevSample`
/// equals `x` on every subsequent sample, the rising-edge condition
/// `prevSample <= 0 && x > 0` is never satisfied. SuperCollider `ZeroCrossing`
/// exhibits identical behaviour (`m_previn = ZIN0(0)`).
@Test func constantPositiveDCInputYieldsZeroFreq() {
let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: 1.0)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
#expect(out[0][i] == 0.0,
"constant positive DC input: freq should be 0 (no crossing), got \(out[0][i]) at sample \(i)")
}
}
/// Constant negative input: no rising zero crossing from the initial state (prevSample=0,
/// x=-1 — condition prevSample<=0 && x>0 is false). Freq stays 0.
@Test func constantNegativeInputNoZeroCrossing() {
let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: -1.0)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
#expect(out[0][i] == 0.0,
"constant negative input should yield freq 0, got \(out[0][i]) at sample \(i)")
}
}
/// Square wave with period P samples yields freq = sampleRate / P after the second
/// measured rising zero crossing.
///
/// A square wave alternates every P/2 samples. The rising ZC (≤0 → >0) fires every P
/// samples from the second crossing onward. `_prevSample` is lazy-initialised to the
/// first input sample (-1), so no spurious crossing fires on sample 0. The first
/// crossing at sample 8 has a count of 9 (incremented for samples 0..8); the second
/// and subsequent crossings measure exactly P = 16.
@Test func squareWaveKnownPeriodYieldsExpectedFreq() {
// Period = 16 samples. Signal: -1 for samples 0..7, +1 for 8..15, -1 for 16..23, +1 for 24..31 ...
// Sample 0: lazy-init sets prevSample=-1. count=1. No crossing (x=-1).
// Sample 8: count=9 (>4). prevSample=-1<=0, x=+1>0 → crossing fires. freq=sr/9. count=0.
// Sample 24: count=16 (>4). prev=-1<=0, x=+1>0 → crossing. freq=sr/16.
// From sample 24 onward, freq is sr/16.
let period: Int = 16
let halfPeriod: Int = period / 2
let expectedFreq: Double = sampleRate / Double(period)
let inputSignal: Closure = Closure { _, i in
((i / halfPeriod) % 2 == 0) ? -1.0 : 1.0
}
let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: inputSignal)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
// The second rising crossing is at sample 24 (period=16, half=8: -1 @ 0..7, +1 @ 8..15,
// -1 @ 16..23, +1 @ 24..31). From sample 24 onward, freq should be sr/16.
let secondCrossingAt: Int = period + halfPeriod // 24
for i: Int in secondCrossingAt..<blockSize {
#expect(abs(out[0][i] - expectedFreq) < 1e-9,
"sample \(i): expected \(expectedFreq) (stable period after 2nd crossing), got \(out[0][i])")
}
}
/// Frequency is held between crossings (output stays constant between rising edges).
///
/// Uses a signal starting at -1 so that `_prevSample` is lazy-initialised to -1 on
/// sample 0 and no spurious crossing fires. Signal: -1 for samples 0..9, +1 for
/// 10..19, -1 for 20..29, +1 for 30..39 …
///
/// Sample 0: lazy-init sets prevSample=-1. count incremented to 1. No crossing (x=-1).
/// First rising crossing fires at sample 10 with count = halfPeriod+1 = 11 (samples
/// 0..10 each increment count, 11 > zeroCrossingMinCount). Freq = sr/11. Count resets.
/// Second rising crossing fires at sample 30 with count = halfPeriod*2 = 20. Freq = sr/20.
/// Between crossings the output holds the last measured freq.
@Test func freqHeldBetweenCrossings() {
let halfPeriod: Int = 10
// Start with -1 for first half-period so lazy-init sets prevSample=-1 (no crossing).
let inputSignal: Closure = Closure { _, i in
((i / halfPeriod) % 2 == 0) ? -1.0 : 1.0
}
let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: inputSignal)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
// Samples 0..9: no crossing yet (count stays below threshold or x never >0), freq = 0.
for i: Int in 0..<halfPeriod {
#expect(out[0][i] == 0.0,
"sample \(i): expected 0 (no crossing yet), got \(out[0][i])")
}
// Sample 10: first rising crossing. Count at crossing = halfPeriod+1 = 11 (>4). Freq = sr/11.
let firstCrossingCount: Int = halfPeriod + 1
let freqAfterFirstCrossing: Double = sampleRate / Double(firstCrossingCount)
// Samples 10..29: freq held at freqAfterFirstCrossing (next crossing not until sample 30).
for i: Int in halfPeriod..<(halfPeriod * 3) {
#expect(abs(out[0][i] - freqAfterFirstCrossing) < 1e-9,
"sample \(i): expected \(freqAfterFirstCrossing) (held after 1st crossing), got \(out[0][i])")
}
// Sample 30: second rising crossing. Count since reset = halfPeriod*2 = 20 (>4). Freq = sr/20.
let secondCrossingCount: Int = halfPeriod * 2
let freqAfterSecondCrossing: Double = sampleRate / Double(secondCrossingCount)
// Samples 30..49: freq held at freqAfterSecondCrossing.
for i: Int in (halfPeriod * 3)..<(halfPeriod * 5) {
#expect(abs(out[0][i] - freqAfterSecondCrossing) < 1e-9,
"sample \(i): expected \(freqAfterSecondCrossing) (held after 2nd crossing), got \(out[0][i])")
}
}
/// Cross-block continuity: state (counter) carries across audio blocks.
@Test func crossBlockContinuity() {
// Square wave with period 32: crossing happens at sample 16 and 32 (=0 of block 2).
// Block 1 measures 32 samples between crossings (at sample 16 the count includes samples
// from the previous block which starts at 0, so count = 16+prev if counter carried).
// This test verifies counter survives block boundary — non-zero freq in block 2.
let halfPeriod: Int = 16
let inputSignal: Closure = Closure { _, i in
((i / halfPeriod) % 2 == 0) ? 1.0 : -1.0
}
let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: inputSignal)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
advanceBlock(engine)
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
// Block 2 should still detect crossings and emit a non-zero freq.
var hasNonZero: Bool = false
for i: Int in 0..<blockSize {
if out2[0][i] > 0.0 {
hasNonZero = true
break
}
}
#expect(hasNonZero, "expected non-zero freq in block 2 (counter should carry across blocks)")
}
/// Fan-out: two calls same segment return identical first channel.
@Test func fanOut() {
let inputSignal: Closure = Closure { _, i in i % 8 < 4 ? 1.0 : -1.0 }
let gen: ZeroCrossing.Audio = ZeroCrossing.Audio(input: inputSignal)
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
#expect(out1[0][i] == out2[0][i])
}
}
/// mul/add: output is original*2+1.
@Test func mulAdd() {
let halfPeriod: Int = 8
let inputSignal: Closure = Closure { _, i in ((i / halfPeriod) % 2 == 0) ? -1.0 : 1.0 }
let genBase: ZeroCrossing.Audio = ZeroCrossing.Audio(input: inputSignal)
let genScaled: ZeroCrossing.Audio = ZeroCrossing.Audio(
input: inputSignal,
mul: 2.0,
add: 1.0
)
let base: [[Double]] = genBase.calculatedSamples(graph: graph, count: blockSize)
let scaled: [[Double]] = genScaled.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
let expected: Double = base[0][i] * 2.0 + 1.0
#expect(abs(scaled[0][i] - expected) < 1e-12,
"mulAdd sample \(i): expected \(expected) got \(scaled[0][i])")
}
}
}
@@ -0,0 +1,148 @@
// ZeroCrossingControlTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("ZeroCrossing.Control")
struct ZeroCrossingControlTests {
let engine: SynthesisEngine
var graph: SynthGraph { makeSynthGraph(engine: engine) }
let blockSize: Int = 64
let sampleRate: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func rateIsControl() {
let gen: ZeroCrossing.Control = ZeroCrossing.Control(input: 0.0)
#expect(gen.rate == .control)
}
/// Output count matches request.
@Test func outputCountMatchesRequest() {
let gen: ZeroCrossing.Control = ZeroCrossing.Control(input: 0.5)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(Array(out[0].prefix(blockSize)).count == blockSize)
}
/// Constant negative input: no rising crossing fires (prevSample=0 ≤ 0, x=-1 — condition
/// `prevSample<=0 && x>0` is false). Freq stays 0 throughout the block.
@Test func constantNegativeInputNoZeroCrossing() {
let gen: ZeroCrossing.Control = ZeroCrossing.Control(input: -1.0)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(gen.previousOutputValue == 0.0,
"constant negative input: freq should remain 0, got \(gen.previousOutputValue)")
}
/// Square wave with period P samples yields freq = sampleRate / P (measured
/// over the full audio block at audio rate, reported as flat block-final value).
///
/// Signal starts at -1, so lazy-init sets `_prevSample = -1` on sample 0 and no
/// spurious crossing fires. The first crossing fires at sample 8 (count=9>4, freq=sr/9);
/// subsequent crossings measure exactly P=16 (count=16>4, freq=sr/16). Block-final
/// value after 64 samples is sr/16.
@Test func squareWaveKnownPeriodYieldsExpectedFreq() {
// Period = 16 samples → expected freq = 44100 / 16 = 2756.25 Hz.
let period: Int = 16
let expectedFreq: Double = sampleRate / Double(period)
// -1 for first half, +1 for second half, repeating.
let inputSignal: Closure = Closure { _, i in
((i / (period / 2)) % 2 == 0) ? -1.0 : 1.0
}
let gen: ZeroCrossing.Control = ZeroCrossing.Control(input: inputSignal)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(abs(gen.previousOutputValue - expectedFreq) < 1e-9,
"expected freq \(expectedFreq), got \(gen.previousOutputValue)")
}
/// Output block is flat: all samples equal the block-final freq.
@Test func outputBlockIsFlat() {
let period: Int = 8
let inputSignal: Closure = Closure { _, i in
((i / (period / 2)) % 2 == 0) ? -1.0 : 1.0
}
let gen: ZeroCrossing.Control = ZeroCrossing.Control(input: inputSignal)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let expected: Double = out[0][blockSize - 1]
for i: Int in 0..<blockSize {
#expect(out[0][i] == expected,
"expected flat block, sample \(i) = \(out[0][i]) differs from last = \(expected)")
}
}
/// floatValue returns previousOutputValue.
@Test func floatValueReturnsPreviousOutputValue() {
let gen: ZeroCrossing.Control = ZeroCrossing.Control(input: 0.0)
#expect(gen.floatValue(graph: graph) == gen.previousOutputValue)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(gen.floatValue(graph: graph) == gen.previousOutputValue)
}
/// Fan-out: two calls same segment return identical first channel.
@Test func fanOut() {
let inputSignal: Closure = Closure { _, i in i % 8 < 4 ? 1.0 : -1.0 }
let gen: ZeroCrossing.Control = ZeroCrossing.Control(input: inputSignal)
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
#expect(out1[0][i] == out2[0][i])
}
}
/// Sub-block bypass: second call in same segment is a cache hit; state not re-advanced.
@Test func subBlockBypassCacheHit() {
let inputSignal: Closure = Closure { _, i in i % 8 < 4 ? 1.0 : -1.0 }
let gen: ZeroCrossing.Control = ZeroCrossing.Control(input: inputSignal)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
let stateAfterFirst: Double = gen.previousOutputValue
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(gen.previousOutputValue == stateAfterFirst,
"second call in same segment must be a cache hit — state must not re-advance")
}
/// Cross-block continuity: counter carries across audio blocks.
@Test func crossBlockContinuity() {
// Use a slow square wave (period = 128 samples) that spans two blocks.
// After block 1, the counter should be non-zero and the freq in block 2 should be valid.
let period: Int = 32
let inputSignal: Closure = Closure { _, i in ((i / (period / 2)) % 2 == 0) ? -1.0 : 1.0 }
let gen: ZeroCrossing.Control = ZeroCrossing.Control(input: inputSignal)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
advanceBlock(engine)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
// In block 2, crossings still detected — previousOutputValue should be non-zero.
#expect(gen.previousOutputValue > 0.0,
"freq should be non-zero in block 2 (state carries across blocks)")
}
/// mul/add: output is original*2+1.
@Test func mulAdd() {
let period: Int = 16
let inputSignal: Closure = Closure { _, i in
((i / (period / 2)) % 2 == 0) ? -1.0 : 1.0
}
let genBase: ZeroCrossing.Control = ZeroCrossing.Control(input: inputSignal)
let genScaled: ZeroCrossing.Control = ZeroCrossing.Control(
input: inputSignal,
mul: 2.0,
add: 1.0
)
let base: [[Double]] = genBase.calculatedSamples(graph: graph, count: blockSize)
let scaled: [[Double]] = genScaled.calculatedSamples(graph: graph, count: blockSize)
// Both should have a consistent relationship: scaled[i] = base[i]*2+1.
for i: Int in 0..<blockSize {
let expected: Double = base[0][i] * 2.0 + 1.0
#expect(abs(scaled[0][i] - expected) < 1e-12,
"mulAdd sample \(i): expected \(expected) got \(scaled[0][i])")
}
}
}
@@ -0,0 +1,38 @@
// ChaoticInterpolateTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - ChaoticInterpolateTests
@Suite("chaoticInterpolate")
struct ChaoticInterpolateTests {
let hM1: Double = -0.5
let h0: Double = 0.2
let h1: Double = 0.9
let h2: Double = -0.3
@Test func noneHoldsSegmentStart() {
#expect(chaoticInterpolate(.none, phase: 0.0, hM1: hM1, h0: h0, h1: h1, h2: h2) == h0)
#expect(chaoticInterpolate(.none, phase: 0.99, hM1: hM1, h0: h0, h1: h1, h2: h2) == h0)
}
@Test func linearEndpointsAndMidpoint() {
#expect(abs(chaoticInterpolate(.linear, phase: 0.0, hM1: hM1, h0: h0, h1: h1, h2: h2) - h0) < 1e-15)
#expect(abs(chaoticInterpolate(.linear, phase: 1.0, hM1: hM1, h0: h0, h1: h1, h2: h2) - h1) < 1e-15)
let mid: Double = chaoticInterpolate(.linear, phase: 0.5, hM1: hM1, h0: h0, h1: h1, h2: h2)
#expect(abs(mid - 0.5 * (h0 + h1)) < 1e-15)
}
@Test func cubicPassesThroughSegmentEndpoints() {
// The 4-point cubic kernel passes through h0 at t=0 and h1 at t=1.
#expect(abs(chaoticInterpolate(.cubic, phase: 0.0, hM1: hM1, h0: h0, h1: h1, h2: h2) - h0) < 1e-12)
#expect(abs(chaoticInterpolate(.cubic, phase: 1.0, hM1: hM1, h0: h0, h1: h1, h2: h2) - h1) < 1e-12)
}
}
@@ -0,0 +1,83 @@
// CuspSteppedAudioTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - CuspSteppedAudioTests
@MainActor
@Suite("CuspStepped.Audio")
struct CuspSteppedAudioTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func deterministicSteppedIterations() {
// freq == sampleRate, .none → held outputs are the warm-up iterates 2,3,…
let m: CuspStepped.Audio = CuspStepped.Audio(freq: sr, interpolation: .none)
let g: SynthGraph = makeSynthGraph(engine: engine)
let s: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
#expect(abs(s[0][0] - (-0.9)) < 1e-9)
#expect(abs(s[0][1] - (-0.8024982662959761)) < 1e-9)
}
@Test func freqZeroHoldsSecondIteration() {
let m: CuspStepped.Audio = CuspStepped.Audio(freq: 0.0)
let samples: [Double] = collectBlocks(m, engine: engine, blocks: 4)
#expect(samples.allSatisfy { abs($0 - (-0.9)) < 1e-9 })
}
@Test func chaoticOrbitStaysBounded() {
let m: CuspStepped.Audio = CuspStepped.Audio(freq: sr)
let samples: [Double] = collectBlocks(m, engine: engine, blocks: 50)
#expect(samples.allSatisfy { $0.isFinite })
#expect(samples.allSatisfy { abs($0) < 1.5 }) // x in ~[-0.9,1.0]
#expect(Set(samples.map { ($0 * 1e4).rounded() }).count > 10)
}
@Test func allInterpolationModesFinite() {
for mode: TableInterpolation in [.none, .linear, .cubic] {
let m: CuspStepped.Audio = CuspStepped.Audio(freq: 4000.0, interpolation: mode)
let samples: [Double] = collectBlocks(m, engine: engine, blocks: 20)
#expect(samples.allSatisfy { $0.isFinite }, "mode \(mode) non-finite")
}
}
@Test func twoInstancesProduceIdenticalOutput() throws {
let a1: CuspStepped.Audio = CuspStepped.Audio(freq: 8000.0)
let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 10)
let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
try engine2.start()
let a2: CuspStepped.Audio = CuspStepped.Audio(freq: 8000.0)
let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 10)
#expect(s1 == s2)
}
@Test func participatesInFanOutCache() {
let m: CuspStepped.Audio = CuspStepped.Audio(freq: 8000.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let r1: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
let r2: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
}
@Test func mulAddScalesAndOffsets() {
let plain: CuspStepped.Audio = CuspStepped.Audio(freq: 0.0)
let g1: SynthGraph = makeSynthGraph(engine: engine)
let p: Double = plain.calculatedSamples(graph: g1, count: engine.blockSize)[0][0]
let scaled: CuspStepped.Audio = CuspStepped.Audio(freq: 0.0, mul: 0.5, add: 1.0)
let g2: SynthGraph = makeSynthGraph(engine: engine)
let s: Double = scaled.calculatedSamples(graph: g2, count: engine.blockSize)[0][0]
#expect(abs(s - (p * 0.5 + 1.0)) < 1e-12)
}
}
@@ -0,0 +1,56 @@
// CuspSteppedControlTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - CuspSteppedControlTests
@MainActor
@Suite("CuspStepped.Control")
struct CuspSteppedControlTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func freqZeroRampsToPrimedValue() {
let m: CuspStepped.Control = CuspStepped.Control(freq: 0.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let s: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
#expect(abs(s[0][engine.blockSize - 1] - (-0.9)) < 1e-9)
}
@Test func finiteBoundedOutput() {
let m: CuspStepped.Control = CuspStepped.Control(freq: 200.0)
let samples: [Double] = collectBlocks(m, engine: engine, blocks: 40)
#expect(samples.allSatisfy { $0.isFinite })
#expect(samples.allSatisfy { abs($0) < 1.5 })
}
@Test func twoInstancesProduceIdenticalOutput() throws {
let a1: CuspStepped.Control = CuspStepped.Control(freq: 500.0)
let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 20)
let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
try engine2.start()
let a2: CuspStepped.Control = CuspStepped.Control(freq: 500.0)
let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 20)
#expect(s1 == s2)
}
@Test func participatesInFanOutCache() {
let m: CuspStepped.Control = CuspStepped.Control(freq: 500.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let r1: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
let r2: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
}
}
@@ -0,0 +1,83 @@
// FBSineSteppedAudioTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - FBSineSteppedAudioTests
@MainActor
@Suite("FBSineStepped.Audio")
struct FBSineSteppedAudioTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func deterministicSteppedIterations() {
// freq == sampleRate, .none → held outputs are the warm-up iterates 2,3,…
let m: FBSineStepped.Audio = FBSineStepped.Audio(freq: sr, interpolation: .none)
let g: SynthGraph = makeSynthGraph(engine: engine)
let s: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
#expect(abs(s[0][0] - (0.5818307174710479)) < 1e-9)
#expect(abs(s[0][1] - (0.9422154392244042)) < 1e-9)
}
@Test func freqZeroHoldsSecondIteration() {
let m: FBSineStepped.Audio = FBSineStepped.Audio(freq: 0.0)
let samples: [Double] = collectBlocks(m, engine: engine, blocks: 4)
#expect(samples.allSatisfy { abs($0 - (0.5818307174710479)) < 1e-9 })
}
@Test func chaoticOrbitStaysBounded() {
let m: FBSineStepped.Audio = FBSineStepped.Audio(freq: sr)
let samples: [Double] = collectBlocks(m, engine: engine, blocks: 50)
#expect(samples.allSatisfy { $0.isFinite })
#expect(samples.allSatisfy { abs($0) <= 1.0 + 1e-12 }) // x = sin in [-1,1]
#expect(Set(samples.map { ($0 * 1e4).rounded() }).count > 10)
}
@Test func allInterpolationModesFinite() {
for mode: TableInterpolation in [.none, .linear, .cubic] {
let m: FBSineStepped.Audio = FBSineStepped.Audio(freq: 4000.0, interpolation: mode)
let samples: [Double] = collectBlocks(m, engine: engine, blocks: 20)
#expect(samples.allSatisfy { $0.isFinite }, "mode \(mode) non-finite")
}
}
@Test func twoInstancesProduceIdenticalOutput() throws {
let a1: FBSineStepped.Audio = FBSineStepped.Audio(freq: 8000.0)
let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 10)
let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
try engine2.start()
let a2: FBSineStepped.Audio = FBSineStepped.Audio(freq: 8000.0)
let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 10)
#expect(s1 == s2)
}
@Test func participatesInFanOutCache() {
let m: FBSineStepped.Audio = FBSineStepped.Audio(freq: 8000.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let r1: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
let r2: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
}
@Test func mulAddScalesAndOffsets() {
let plain: FBSineStepped.Audio = FBSineStepped.Audio(freq: 0.0)
let g1: SynthGraph = makeSynthGraph(engine: engine)
let p: Double = plain.calculatedSamples(graph: g1, count: engine.blockSize)[0][0]
let scaled: FBSineStepped.Audio = FBSineStepped.Audio(freq: 0.0, mul: 0.5, add: 1.0)
let g2: SynthGraph = makeSynthGraph(engine: engine)
let s: Double = scaled.calculatedSamples(graph: g2, count: engine.blockSize)[0][0]
#expect(abs(s - (p * 0.5 + 1.0)) < 1e-12)
}
}
@@ -0,0 +1,56 @@
// FBSineSteppedControlTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - FBSineSteppedControlTests
@MainActor
@Suite("FBSineStepped.Control")
struct FBSineSteppedControlTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func freqZeroRampsToPrimedValue() {
let m: FBSineStepped.Control = FBSineStepped.Control(freq: 0.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let s: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
#expect(abs(s[0][engine.blockSize - 1] - (0.5818307174710479)) < 1e-9)
}
@Test func finiteBoundedOutput() {
let m: FBSineStepped.Control = FBSineStepped.Control(freq: 200.0)
let samples: [Double] = collectBlocks(m, engine: engine, blocks: 40)
#expect(samples.allSatisfy { $0.isFinite })
#expect(samples.allSatisfy { abs($0) <= 1.0 + 1e-12 })
}
@Test func twoInstancesProduceIdenticalOutput() throws {
let a1: FBSineStepped.Control = FBSineStepped.Control(freq: 500.0)
let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 20)
let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
try engine2.start()
let a2: FBSineStepped.Control = FBSineStepped.Control(freq: 500.0)
let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 20)
#expect(s1 == s2)
}
@Test func participatesInFanOutCache() {
let m: FBSineStepped.Control = FBSineStepped.Control(freq: 500.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let r1: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
let r2: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
}
}
@@ -0,0 +1,85 @@
// GbmanSteppedAudioTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - GbmanSteppedAudioTests
@MainActor
@Suite("GbmanStepped.Audio")
struct GbmanSteppedAudioTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func deterministicSteppedIterations() {
// freq == sampleRate, .none. xi=1.2, yi=2.1: iterates 0.1, -0.1, 1.0, 2.1, …
// → held outputs -0.1, 1.0, 2.1, …
let gb: GbmanStepped.Audio = GbmanStepped.Audio(freq: sr, interpolation: .none)
let g: SynthGraph = makeSynthGraph(engine: engine)
let s: [[Double]] = gb.calculatedSamples(graph: g, count: engine.blockSize)
#expect(abs(s[0][0] - (-0.1)) < 1e-9)
#expect(abs(s[0][1] - 1.0) < 1e-9)
#expect(abs(s[0][2] - 2.1) < 1e-9)
}
@Test func freqZeroHoldsSecondIteration() {
let gb: GbmanStepped.Audio = GbmanStepped.Audio(freq: 0.0)
let samples: [Double] = collectBlocks(gb, engine: engine, blocks: 4)
#expect(samples.allSatisfy { abs($0 - (-0.1)) < 1e-9 })
}
@Test func chaoticOrbitStaysBounded() {
let gb: GbmanStepped.Audio = GbmanStepped.Audio(freq: sr)
let samples: [Double] = collectBlocks(gb, engine: engine, blocks: 50)
#expect(samples.allSatisfy { $0.isFinite })
#expect(samples.allSatisfy { abs($0) < 10.0 })
#expect(Set(samples.map { ($0 * 1e4).rounded() }).count > 10)
}
@Test func allInterpolationModesFinite() {
for mode: TableInterpolation in [.none, .linear, .cubic] {
let gb: GbmanStepped.Audio = GbmanStepped.Audio(freq: 4000.0, interpolation: mode)
let samples: [Double] = collectBlocks(gb, engine: engine, blocks: 20)
#expect(samples.allSatisfy { $0.isFinite }, "mode \(mode) non-finite")
}
}
@Test func twoInstancesProduceIdenticalOutput() throws {
let a1: GbmanStepped.Audio = GbmanStepped.Audio(freq: 8000.0)
let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 10)
let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
try engine2.start()
let a2: GbmanStepped.Audio = GbmanStepped.Audio(freq: 8000.0)
let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 10)
#expect(s1 == s2)
}
@Test func participatesInFanOutCache() {
let gb: GbmanStepped.Audio = GbmanStepped.Audio(freq: 8000.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let r1: [[Double]] = gb.calculatedSamples(graph: g, count: engine.blockSize)
let r2: [[Double]] = gb.calculatedSamples(graph: g, count: engine.blockSize)
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
}
@Test func mulAddScalesAndOffsets() {
let plain: GbmanStepped.Audio = GbmanStepped.Audio(freq: 0.0)
let g1: SynthGraph = makeSynthGraph(engine: engine)
let p: Double = plain.calculatedSamples(graph: g1, count: engine.blockSize)[0][0]
let scaled: GbmanStepped.Audio = GbmanStepped.Audio(freq: 0.0, mul: 0.5, add: 1.0)
let g2: SynthGraph = makeSynthGraph(engine: engine)
let s: Double = scaled.calculatedSamples(graph: g2, count: engine.blockSize)[0][0]
#expect(abs(s - (p * 0.5 + 1.0)) < 1e-12)
}
}
@@ -0,0 +1,56 @@
// GbmanSteppedControlTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - GbmanSteppedControlTests
@MainActor
@Suite("GbmanStepped.Control")
struct GbmanSteppedControlTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func freqZeroRampsToPrimedValue() {
let gb: GbmanStepped.Control = GbmanStepped.Control(freq: 0.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let s: [[Double]] = gb.calculatedSamples(graph: g, count: engine.blockSize)
#expect(abs(s[0][engine.blockSize - 1] - (-0.1)) < 1e-9)
}
@Test func finiteBoundedOutput() {
let gb: GbmanStepped.Control = GbmanStepped.Control(freq: 200.0)
let samples: [Double] = collectBlocks(gb, engine: engine, blocks: 40)
#expect(samples.allSatisfy { $0.isFinite })
#expect(samples.allSatisfy { abs($0) < 10.0 })
}
@Test func twoInstancesProduceIdenticalOutput() throws {
let a1: GbmanStepped.Control = GbmanStepped.Control(freq: 500.0)
let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 20)
let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
try engine2.start()
let a2: GbmanStepped.Control = GbmanStepped.Control(freq: 500.0)
let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 20)
#expect(s1 == s2)
}
@Test func participatesInFanOutCache() {
let gb: GbmanStepped.Control = GbmanStepped.Control(freq: 500.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let r1: [[Double]] = gb.calculatedSamples(graph: g, count: engine.blockSize)
let r2: [[Double]] = gb.calculatedSamples(graph: g, count: engine.blockSize)
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
}
}
@@ -0,0 +1,94 @@
// HenonSteppedAudioTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - HenonSteppedAudioTests
@MainActor
@Suite("HenonStepped.Audio")
struct HenonSteppedAudioTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func deterministicSteppedIterations() {
// freq == sampleRate → dphase = 1, one iteration per sample, .none holds the
// segment start. With a=1.4, b=0.3, x0=x1=0 the warm-up iterations are
// 1, -0.4, 1.076, -0.7408864; after 4-iteration priming the held outputs are
// -0.4, 1.076, -0.7408864, ...
let henon: HenonStepped.Audio = HenonStepped.Audio(freq: sr, a: 1.4, b: 0.3,
x0: 0.0, x1: 0.0, interpolation: .none)
let g: SynthGraph = makeSynthGraph(engine: engine)
let s: [[Double]] = henon.calculatedSamples(graph: g, count: engine.blockSize)
#expect(abs(s[0][0] - (-0.4)) < 1e-9)
#expect(abs(s[0][1] - 1.076) < 1e-9)
#expect(abs(s[0][2] - (-0.7408864)) < 1e-9)
}
@Test func chaoticOrbitStaysBounded() {
let henon: HenonStepped.Audio = HenonStepped.Audio(freq: sr) // canonical a/b
let samples: [Double] = collectBlocks(henon, engine: engine, blocks: 50)
#expect(samples.allSatisfy { $0.isFinite })
#expect(samples.allSatisfy { abs($0) < 2.0 })
// Not a constant — the orbit visits distinct values.
#expect(Set(samples.map { ($0 * 1e6).rounded() }).count > 10)
}
@Test func allInterpolationModesFinite() {
for mode: TableInterpolation in [.none, .linear, .cubic] {
let henon: HenonStepped.Audio = HenonStepped.Audio(freq: 4000.0, interpolation: mode)
let samples: [Double] = collectBlocks(henon, engine: engine, blocks: 20)
#expect(samples.allSatisfy { $0.isFinite }, "mode \(mode) non-finite")
}
}
@Test func freqZeroHoldsConstant() {
// dphase = 0 → never iterates past priming → constant held output.
let henon: HenonStepped.Audio = HenonStepped.Audio(freq: 0.0, interpolation: .linear)
let samples: [Double] = collectBlocks(henon, engine: engine, blocks: 4)
let first: Double = samples.first ?? .nan
#expect(samples.allSatisfy { $0 == first })
}
@Test func twoInstancesProduceIdenticalOutput() throws {
let h1: HenonStepped.Audio = HenonStepped.Audio(freq: 8000.0)
let s1: [Double] = collectBlocks(h1, engine: engine, blocks: 10)
let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
try engine2.start()
let h2: HenonStepped.Audio = HenonStepped.Audio(freq: 8000.0)
let s2: [Double] = collectBlocks(h2, engine: engine2, blocks: 10)
#expect(s1 == s2)
}
@Test func participatesInFanOutCache() {
let henon: HenonStepped.Audio = HenonStepped.Audio(freq: 8000.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let r1: [[Double]] = henon.calculatedSamples(graph: g, count: engine.blockSize)
let r2: [[Double]] = henon.calculatedSamples(graph: g, count: engine.blockSize)
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
}
@Test func mulAddScalesAndOffsets() {
let plain: HenonStepped.Audio = HenonStepped.Audio(freq: sr, interpolation: .none)
let g1: SynthGraph = makeSynthGraph(engine: engine)
let p: Double = plain.calculatedSamples(graph: g1, count: engine.blockSize)[0][0]
let scaled: HenonStepped.Audio = HenonStepped.Audio(freq: sr, interpolation: .none,
mul: 2.0, add: 1.0)
let g2: SynthGraph = makeSynthGraph(engine: engine)
let s: Double = scaled.calculatedSamples(graph: g2, count: engine.blockSize)[0][0]
#expect(abs(s - (p * 2.0 + 1.0)) < 1e-12)
}
}
@@ -0,0 +1,60 @@
// HenonSteppedControlTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - HenonSteppedControlTests
@MainActor
@Suite("HenonStepped.Control")
struct HenonSteppedControlTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func finiteBoundedOutput() {
let henon: HenonStepped.Control = HenonStepped.Control(freq: 200.0)
let samples: [Double] = collectBlocks(henon, engine: engine, blocks: 40)
#expect(samples.allSatisfy { $0.isFinite })
#expect(samples.allSatisfy { abs($0) < 2.0 })
}
@Test func freqZeroRampsToPrimedValue() {
// dphase = 0 → no iteration past priming; .none holds h0 = -0.4 (2nd Hénon
// iterate for a=1.4, b=0.3, x0=x1=0). The block ramps 0 → -0.4, so the last
// sample equals the target exactly.
let henon: HenonStepped.Control = HenonStepped.Control(freq: 0.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let s: [[Double]] = henon.calculatedSamples(graph: g, count: engine.blockSize)
#expect(abs(s[0][engine.blockSize - 1] - (-0.4)) < 1e-12)
}
@Test func twoInstancesProduceIdenticalOutput() throws {
let h1: HenonStepped.Control = HenonStepped.Control(freq: 500.0)
let s1: [Double] = collectBlocks(h1, engine: engine, blocks: 20)
let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
try engine2.start()
let h2: HenonStepped.Control = HenonStepped.Control(freq: 500.0)
let s2: [Double] = collectBlocks(h2, engine: engine2, blocks: 20)
#expect(s1 == s2)
}
@Test func participatesInFanOutCache() {
let henon: HenonStepped.Control = HenonStepped.Control(freq: 500.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let r1: [[Double]] = henon.calculatedSamples(graph: g, count: engine.blockSize)
let r2: [[Double]] = henon.calculatedSamples(graph: g, count: engine.blockSize)
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
}
}
@@ -0,0 +1,83 @@
// LatoocarfianSteppedAudioTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - LatoocarfianSteppedAudioTests
@MainActor
@Suite("LatoocarfianStepped.Audio")
struct LatoocarfianSteppedAudioTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func deterministicSteppedIterations() {
// freq == sampleRate, .none → held outputs are the warm-up iterates 2,3,…
let m: LatoocarfianStepped.Audio = LatoocarfianStepped.Audio(freq: sr, interpolation: .none)
let g: SynthGraph = makeSynthGraph(engine: engine)
let s: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
#expect(abs(s[0][0] - (0.34527127964613574)) < 1e-9)
#expect(abs(s[0][1] - (-0.31328745455281626)) < 1e-9)
}
@Test func freqZeroHoldsSecondIteration() {
let m: LatoocarfianStepped.Audio = LatoocarfianStepped.Audio(freq: 0.0)
let samples: [Double] = collectBlocks(m, engine: engine, blocks: 4)
#expect(samples.allSatisfy { abs($0 - (0.34527127964613574)) < 1e-9 })
}
@Test func chaoticOrbitStaysBounded() {
let m: LatoocarfianStepped.Audio = LatoocarfianStepped.Audio(freq: sr)
let samples: [Double] = collectBlocks(m, engine: engine, blocks: 50)
#expect(samples.allSatisfy { $0.isFinite })
#expect(samples.allSatisfy { abs($0) < 2.0 }) // x in ~[-1.5,1.5]
#expect(Set(samples.map { ($0 * 1e4).rounded() }).count > 10)
}
@Test func allInterpolationModesFinite() {
for mode: TableInterpolation in [.none, .linear, .cubic] {
let m: LatoocarfianStepped.Audio = LatoocarfianStepped.Audio(freq: 4000.0, interpolation: mode)
let samples: [Double] = collectBlocks(m, engine: engine, blocks: 20)
#expect(samples.allSatisfy { $0.isFinite }, "mode \(mode) non-finite")
}
}
@Test func twoInstancesProduceIdenticalOutput() throws {
let a1: LatoocarfianStepped.Audio = LatoocarfianStepped.Audio(freq: 8000.0)
let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 10)
let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
try engine2.start()
let a2: LatoocarfianStepped.Audio = LatoocarfianStepped.Audio(freq: 8000.0)
let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 10)
#expect(s1 == s2)
}
@Test func participatesInFanOutCache() {
let m: LatoocarfianStepped.Audio = LatoocarfianStepped.Audio(freq: 8000.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let r1: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
let r2: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
}
@Test func mulAddScalesAndOffsets() {
let plain: LatoocarfianStepped.Audio = LatoocarfianStepped.Audio(freq: 0.0)
let g1: SynthGraph = makeSynthGraph(engine: engine)
let p: Double = plain.calculatedSamples(graph: g1, count: engine.blockSize)[0][0]
let scaled: LatoocarfianStepped.Audio = LatoocarfianStepped.Audio(freq: 0.0, mul: 0.5, add: 1.0)
let g2: SynthGraph = makeSynthGraph(engine: engine)
let s: Double = scaled.calculatedSamples(graph: g2, count: engine.blockSize)[0][0]
#expect(abs(s - (p * 0.5 + 1.0)) < 1e-12)
}
}
@@ -0,0 +1,56 @@
// LatoocarfianSteppedControlTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - LatoocarfianSteppedControlTests
@MainActor
@Suite("LatoocarfianStepped.Control")
struct LatoocarfianSteppedControlTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func freqZeroRampsToPrimedValue() {
let m: LatoocarfianStepped.Control = LatoocarfianStepped.Control(freq: 0.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let s: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
#expect(abs(s[0][engine.blockSize - 1] - (0.34527127964613574)) < 1e-9)
}
@Test func finiteBoundedOutput() {
let m: LatoocarfianStepped.Control = LatoocarfianStepped.Control(freq: 200.0)
let samples: [Double] = collectBlocks(m, engine: engine, blocks: 40)
#expect(samples.allSatisfy { $0.isFinite })
#expect(samples.allSatisfy { abs($0) < 2.0 })
}
@Test func twoInstancesProduceIdenticalOutput() throws {
let a1: LatoocarfianStepped.Control = LatoocarfianStepped.Control(freq: 500.0)
let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 20)
let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
try engine2.start()
let a2: LatoocarfianStepped.Control = LatoocarfianStepped.Control(freq: 500.0)
let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 20)
#expect(s1 == s2)
}
@Test func participatesInFanOutCache() {
let m: LatoocarfianStepped.Control = LatoocarfianStepped.Control(freq: 500.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let r1: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
let r2: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
}
}
@@ -0,0 +1,83 @@
// LinCongSteppedAudioTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - LinCongSteppedAudioTests
@MainActor
@Suite("LinCongStepped.Audio")
struct LinCongSteppedAudioTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func deterministicSteppedIterations() {
// freq == sampleRate, .none. a=1.1, c=0.13, m=1, xi=0: iterates
// 0.13, 0.273, 0.4303, … → held outputs 0.273, 0.4303, …
let lc: LinCongStepped.Audio = LinCongStepped.Audio(freq: sr, interpolation: .none)
let g: SynthGraph = makeSynthGraph(engine: engine)
let s: [[Double]] = lc.calculatedSamples(graph: g, count: engine.blockSize)
#expect(abs(s[0][0] - 0.273) < 1e-9)
#expect(abs(s[0][1] - 0.4303) < 1e-9)
}
@Test func freqZeroHoldsSecondIteration() {
let lc: LinCongStepped.Audio = LinCongStepped.Audio(freq: 0.0)
let samples: [Double] = collectBlocks(lc, engine: engine, blocks: 4)
#expect(samples.allSatisfy { abs($0 - 0.273) < 1e-12 })
}
@Test func staysInZeroToModulusRange() {
let lc: LinCongStepped.Audio = LinCongStepped.Audio(freq: sr)
let samples: [Double] = collectBlocks(lc, engine: engine, blocks: 60)
#expect(samples.allSatisfy { $0 >= 0.0 && $0 < 1.0 })
#expect(Set(samples.map { ($0 * 1e6).rounded() }).count > 10)
}
@Test func allInterpolationModesFinite() {
for mode: TableInterpolation in [.none, .linear, .cubic] {
let lc: LinCongStepped.Audio = LinCongStepped.Audio(freq: 4000.0, interpolation: mode)
let samples: [Double] = collectBlocks(lc, engine: engine, blocks: 20)
#expect(samples.allSatisfy { $0.isFinite }, "mode \(mode) non-finite")
}
}
@Test func twoInstancesProduceIdenticalOutput() throws {
let a1: LinCongStepped.Audio = LinCongStepped.Audio(freq: 8000.0)
let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 10)
let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
try engine2.start()
let a2: LinCongStepped.Audio = LinCongStepped.Audio(freq: 8000.0)
let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 10)
#expect(s1 == s2)
}
@Test func participatesInFanOutCache() {
let lc: LinCongStepped.Audio = LinCongStepped.Audio(freq: 8000.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let r1: [[Double]] = lc.calculatedSamples(graph: g, count: engine.blockSize)
let r2: [[Double]] = lc.calculatedSamples(graph: g, count: engine.blockSize)
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
}
@Test func mulAddScalesAndOffsets() {
let plain: LinCongStepped.Audio = LinCongStepped.Audio(freq: 0.0)
let g1: SynthGraph = makeSynthGraph(engine: engine)
let p: Double = plain.calculatedSamples(graph: g1, count: engine.blockSize)[0][0]
let scaled: LinCongStepped.Audio = LinCongStepped.Audio(freq: 0.0, mul: 2.0, add: -1.0)
let g2: SynthGraph = makeSynthGraph(engine: engine)
let s: Double = scaled.calculatedSamples(graph: g2, count: engine.blockSize)[0][0]
#expect(abs(s - (p * 2.0 - 1.0)) < 1e-12)
}
}
@@ -0,0 +1,56 @@
// LinCongSteppedControlTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - LinCongSteppedControlTests
@MainActor
@Suite("LinCongStepped.Control")
struct LinCongSteppedControlTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func freqZeroRampsToPrimedValue() {
let lc: LinCongStepped.Control = LinCongStepped.Control(freq: 0.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let s: [[Double]] = lc.calculatedSamples(graph: g, count: engine.blockSize)
#expect(abs(s[0][engine.blockSize - 1] - 0.273) < 1e-12)
}
@Test func finiteBoundedOutput() {
let lc: LinCongStepped.Control = LinCongStepped.Control(freq: 200.0)
let samples: [Double] = collectBlocks(lc, engine: engine, blocks: 40)
#expect(samples.allSatisfy { $0.isFinite })
#expect(samples.allSatisfy { $0 >= 0.0 && $0 < 1.0 })
}
@Test func twoInstancesProduceIdenticalOutput() throws {
let a1: LinCongStepped.Control = LinCongStepped.Control(freq: 500.0)
let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 20)
let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
try engine2.start()
let a2: LinCongStepped.Control = LinCongStepped.Control(freq: 500.0)
let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 20)
#expect(s1 == s2)
}
@Test func participatesInFanOutCache() {
let lc: LinCongStepped.Control = LinCongStepped.Control(freq: 500.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let r1: [[Double]] = lc.calculatedSamples(graph: g, count: engine.blockSize)
let r2: [[Double]] = lc.calculatedSamples(graph: g, count: engine.blockSize)
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
}
}
@@ -0,0 +1,80 @@
// LorenzLinearAudioTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - LorenzLinearAudioTests
@MainActor
@Suite("LorenzLinear.Audio")
struct LorenzLinearAudioTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func freqZeroHoldsSecondIterationValue() {
// dphase = 0 → output stays at the primed segment start h0 (= the 2nd Euler
// iteration). With s=10, r=28, b=2.667, h=0.02, xi=0.1: iterations are
// x1 = 0.08, x2 = 0.0752, so h0 = 0.0752.
let lorenz: LorenzLinear.Audio = LorenzLinear.Audio(freq: 0.0)
let samples: [Double] = collectBlocks(lorenz, engine: engine, blocks: 4)
#expect(samples.allSatisfy { abs($0 - 0.0752) < 1e-12 })
}
@Test func orbitFiniteAndEvolves() {
let lorenz: LorenzLinear.Audio = LorenzLinear.Audio(freq: sr)
let samples: [Double] = collectBlocks(lorenz, engine: engine, blocks: 200)
#expect(samples.allSatisfy { $0.isFinite })
// Canonical Lorenz x stays bounded to roughly ±25.
#expect(samples.allSatisfy { abs($0) < 30.0 })
#expect(Set(samples.map { ($0 * 1e4).rounded() }).count > 50)
}
@Test func allInterpolationModesFinite() {
for mode: TableInterpolation in [.none, .linear, .cubic] {
let lorenz: LorenzLinear.Audio = LorenzLinear.Audio(freq: 6000.0, interpolation: mode)
let samples: [Double] = collectBlocks(lorenz, engine: engine, blocks: 20)
#expect(samples.allSatisfy { $0.isFinite }, "mode \(mode) non-finite")
}
}
@Test func twoInstancesProduceIdenticalOutput() throws {
let l1: LorenzLinear.Audio = LorenzLinear.Audio(freq: 9000.0)
let s1: [Double] = collectBlocks(l1, engine: engine, blocks: 30)
let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
try engine2.start()
let l2: LorenzLinear.Audio = LorenzLinear.Audio(freq: 9000.0)
let s2: [Double] = collectBlocks(l2, engine: engine2, blocks: 30)
#expect(s1 == s2)
}
@Test func participatesInFanOutCache() {
let lorenz: LorenzLinear.Audio = LorenzLinear.Audio(freq: 9000.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let r1: [[Double]] = lorenz.calculatedSamples(graph: g, count: engine.blockSize)
let r2: [[Double]] = lorenz.calculatedSamples(graph: g, count: engine.blockSize)
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
}
@Test func mulAddScalesAndOffsets() {
let plain: LorenzLinear.Audio = LorenzLinear.Audio(freq: 0.0)
let g1: SynthGraph = makeSynthGraph(engine: engine)
let p: Double = plain.calculatedSamples(graph: g1, count: engine.blockSize)[0][0]
let scaled: LorenzLinear.Audio = LorenzLinear.Audio(freq: 0.0, mul: 0.05, add: 0.5)
let g2: SynthGraph = makeSynthGraph(engine: engine)
let s: Double = scaled.calculatedSamples(graph: g2, count: engine.blockSize)[0][0]
#expect(abs(s - (p * 0.05 + 0.5)) < 1e-12)
}
}
@@ -0,0 +1,60 @@
// LorenzLinearControlTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - LorenzLinearControlTests
@MainActor
@Suite("LorenzLinear.Control")
struct LorenzLinearControlTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func finiteBoundedOutput() {
let lorenz: LorenzLinear.Control = LorenzLinear.Control(freq: 200.0, mul: 0.05)
let samples: [Double] = collectBlocks(lorenz, engine: engine, blocks: 40)
#expect(samples.allSatisfy { $0.isFinite })
#expect(samples.allSatisfy { abs($0) < 2.0 })
}
@Test func freqZeroRampsToPrimedValue() {
// dphase = 0 → no iteration past priming. The block ramps from the initial
// _rampTarget (0) to h0 = 0.0752 (2nd Euler iterate, h=0.02), so the block's
// last sample equals the target exactly.
let lorenz: LorenzLinear.Control = LorenzLinear.Control(freq: 0.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let s: [[Double]] = lorenz.calculatedSamples(graph: g, count: engine.blockSize)
#expect(abs(s[0][engine.blockSize - 1] - 0.0752) < 1e-12)
}
@Test func twoInstancesProduceIdenticalOutput() throws {
let l1: LorenzLinear.Control = LorenzLinear.Control(freq: 600.0)
let s1: [Double] = collectBlocks(l1, engine: engine, blocks: 20)
let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
try engine2.start()
let l2: LorenzLinear.Control = LorenzLinear.Control(freq: 600.0)
let s2: [Double] = collectBlocks(l2, engine: engine2, blocks: 20)
#expect(s1 == s2)
}
@Test func participatesInFanOutCache() {
let lorenz: LorenzLinear.Control = LorenzLinear.Control(freq: 600.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let r1: [[Double]] = lorenz.calculatedSamples(graph: g, count: engine.blockSize)
let r2: [[Double]] = lorenz.calculatedSamples(graph: g, count: engine.blockSize)
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
}
}
@@ -0,0 +1,85 @@
// QuadSteppedAudioTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - QuadSteppedAudioTests
@MainActor
@Suite("QuadStepped.Audio")
struct QuadSteppedAudioTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func deterministicSteppedIterations() {
// freq == sampleRate → one iteration per sample, .none holds the segment start.
// a=1, b=-1, c=-0.75, xi=0: warm-up iterates -0.75, 0.5625, -0.99609375, …;
// after 4-iteration priming the held outputs are 0.5625, -0.99609375, …
let q: QuadStepped.Audio = QuadStepped.Audio(freq: sr, interpolation: .none)
let g: SynthGraph = makeSynthGraph(engine: engine)
let s: [[Double]] = q.calculatedSamples(graph: g, count: engine.blockSize)
#expect(abs(s[0][0] - 0.5625) < 1e-9)
#expect(abs(s[0][1] - (-0.99609375)) < 1e-9)
}
@Test func freqZeroHoldsSecondIteration() {
let q: QuadStepped.Audio = QuadStepped.Audio(freq: 0.0)
let samples: [Double] = collectBlocks(q, engine: engine, blocks: 4)
#expect(samples.allSatisfy { abs($0 - 0.5625) < 1e-12 })
}
@Test func chaoticOrbitStaysBounded() {
let q: QuadStepped.Audio = QuadStepped.Audio(freq: sr)
let samples: [Double] = collectBlocks(q, engine: engine, blocks: 50)
#expect(samples.allSatisfy { $0.isFinite })
#expect(samples.allSatisfy { abs($0) < 2.0 })
#expect(Set(samples.map { ($0 * 1e6).rounded() }).count > 10)
}
@Test func allInterpolationModesFinite() {
for mode: TableInterpolation in [.none, .linear, .cubic] {
let q: QuadStepped.Audio = QuadStepped.Audio(freq: 4000.0, interpolation: mode)
let samples: [Double] = collectBlocks(q, engine: engine, blocks: 20)
#expect(samples.allSatisfy { $0.isFinite }, "mode \(mode) non-finite")
}
}
@Test func twoInstancesProduceIdenticalOutput() throws {
let q1: QuadStepped.Audio = QuadStepped.Audio(freq: 8000.0)
let s1: [Double] = collectBlocks(q1, engine: engine, blocks: 10)
let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
try engine2.start()
let q2: QuadStepped.Audio = QuadStepped.Audio(freq: 8000.0)
let s2: [Double] = collectBlocks(q2, engine: engine2, blocks: 10)
#expect(s1 == s2)
}
@Test func participatesInFanOutCache() {
let q: QuadStepped.Audio = QuadStepped.Audio(freq: 8000.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let r1: [[Double]] = q.calculatedSamples(graph: g, count: engine.blockSize)
let r2: [[Double]] = q.calculatedSamples(graph: g, count: engine.blockSize)
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
}
@Test func mulAddScalesAndOffsets() {
let plain: QuadStepped.Audio = QuadStepped.Audio(freq: 0.0)
let g1: SynthGraph = makeSynthGraph(engine: engine)
let p: Double = plain.calculatedSamples(graph: g1, count: engine.blockSize)[0][0]
let scaled: QuadStepped.Audio = QuadStepped.Audio(freq: 0.0, mul: 2.0, add: 1.0)
let g2: SynthGraph = makeSynthGraph(engine: engine)
let s: Double = scaled.calculatedSamples(graph: g2, count: engine.blockSize)[0][0]
#expect(abs(s - (p * 2.0 + 1.0)) < 1e-12)
}
}
@@ -0,0 +1,56 @@
// QuadSteppedControlTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - QuadSteppedControlTests
@MainActor
@Suite("QuadStepped.Control")
struct QuadSteppedControlTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func freqZeroRampsToPrimedValue() {
let q: QuadStepped.Control = QuadStepped.Control(freq: 0.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let s: [[Double]] = q.calculatedSamples(graph: g, count: engine.blockSize)
#expect(abs(s[0][engine.blockSize - 1] - 0.5625) < 1e-12)
}
@Test func finiteBoundedOutput() {
let q: QuadStepped.Control = QuadStepped.Control(freq: 200.0)
let samples: [Double] = collectBlocks(q, engine: engine, blocks: 40)
#expect(samples.allSatisfy { $0.isFinite })
#expect(samples.allSatisfy { abs($0) < 2.0 })
}
@Test func twoInstancesProduceIdenticalOutput() throws {
let q1: QuadStepped.Control = QuadStepped.Control(freq: 500.0)
let s1: [Double] = collectBlocks(q1, engine: engine, blocks: 20)
let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
try engine2.start()
let q2: QuadStepped.Control = QuadStepped.Control(freq: 500.0)
let s2: [Double] = collectBlocks(q2, engine: engine2, blocks: 20)
#expect(s1 == s2)
}
@Test func participatesInFanOutCache() {
let q: QuadStepped.Control = QuadStepped.Control(freq: 500.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let r1: [[Double]] = q.calculatedSamples(graph: g, count: engine.blockSize)
let r2: [[Double]] = q.calculatedSamples(graph: g, count: engine.blockSize)
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
}
}
@@ -0,0 +1,83 @@
// StandardSteppedAudioTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - StandardSteppedAudioTests
@MainActor
@Suite("StandardStepped.Audio")
struct StandardSteppedAudioTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func deterministicSteppedIterations() {
// freq == sampleRate, .none → held outputs are the warm-up iterates 2,3,…
let m: StandardStepped.Audio = StandardStepped.Audio(freq: sr, interpolation: .none)
let g: SynthGraph = makeSynthGraph(engine: engine)
let s: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
#expect(abs(s[0][0] - (2.2890283227337602)) < 1e-9)
#expect(abs(s[0][1] - (4.351601455163474)) < 1e-9)
}
@Test func freqZeroHoldsSecondIteration() {
let m: StandardStepped.Audio = StandardStepped.Audio(freq: 0.0)
let samples: [Double] = collectBlocks(m, engine: engine, blocks: 4)
#expect(samples.allSatisfy { abs($0 - (2.2890283227337602)) < 1e-9 })
}
@Test func chaoticOrbitStaysBounded() {
let m: StandardStepped.Audio = StandardStepped.Audio(freq: sr)
let samples: [Double] = collectBlocks(m, engine: engine, blocks: 50)
#expect(samples.allSatisfy { $0.isFinite })
#expect(samples.allSatisfy { $0 >= 0.0 && $0 < lyrebirdTwoPi }) // x in [0, 2pi)
#expect(Set(samples.map { ($0 * 1e4).rounded() }).count > 10)
}
@Test func allInterpolationModesFinite() {
for mode: TableInterpolation in [.none, .linear, .cubic] {
let m: StandardStepped.Audio = StandardStepped.Audio(freq: 4000.0, interpolation: mode)
let samples: [Double] = collectBlocks(m, engine: engine, blocks: 20)
#expect(samples.allSatisfy { $0.isFinite }, "mode \(mode) non-finite")
}
}
@Test func twoInstancesProduceIdenticalOutput() throws {
let a1: StandardStepped.Audio = StandardStepped.Audio(freq: 8000.0)
let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 10)
let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
try engine2.start()
let a2: StandardStepped.Audio = StandardStepped.Audio(freq: 8000.0)
let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 10)
#expect(s1 == s2)
}
@Test func participatesInFanOutCache() {
let m: StandardStepped.Audio = StandardStepped.Audio(freq: 8000.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let r1: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
let r2: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
}
@Test func mulAddScalesAndOffsets() {
let plain: StandardStepped.Audio = StandardStepped.Audio(freq: 0.0)
let g1: SynthGraph = makeSynthGraph(engine: engine)
let p: Double = plain.calculatedSamples(graph: g1, count: engine.blockSize)[0][0]
let scaled: StandardStepped.Audio = StandardStepped.Audio(freq: 0.0, mul: 0.5, add: 1.0)
let g2: SynthGraph = makeSynthGraph(engine: engine)
let s: Double = scaled.calculatedSamples(graph: g2, count: engine.blockSize)[0][0]
#expect(abs(s - (p * 0.5 + 1.0)) < 1e-12)
}
}
@@ -0,0 +1,56 @@
// StandardSteppedControlTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - StandardSteppedControlTests
@MainActor
@Suite("StandardStepped.Control")
struct StandardSteppedControlTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func freqZeroRampsToPrimedValue() {
let m: StandardStepped.Control = StandardStepped.Control(freq: 0.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let s: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
#expect(abs(s[0][engine.blockSize - 1] - (2.2890283227337602)) < 1e-9)
}
@Test func finiteBoundedOutput() {
let m: StandardStepped.Control = StandardStepped.Control(freq: 200.0)
let samples: [Double] = collectBlocks(m, engine: engine, blocks: 40)
#expect(samples.allSatisfy { $0.isFinite })
#expect(samples.allSatisfy { $0 >= 0.0 && $0 < lyrebirdTwoPi })
}
@Test func twoInstancesProduceIdenticalOutput() throws {
let a1: StandardStepped.Control = StandardStepped.Control(freq: 500.0)
let s1: [Double] = collectBlocks(a1, engine: engine, blocks: 20)
let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
try engine2.start()
let a2: StandardStepped.Control = StandardStepped.Control(freq: 500.0)
let s2: [Double] = collectBlocks(a2, engine: engine2, blocks: 20)
#expect(s1 == s2)
}
@Test func participatesInFanOutCache() {
let m: StandardStepped.Control = StandardStepped.Control(freq: 500.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let r1: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
let r2: [[Double]] = m.calculatedSamples(graph: g, count: engine.blockSize)
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
}
}
@@ -0,0 +1,93 @@
// DelayLineCubicTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - DelayLineCubicTests
@MainActor
@Suite("DelayLine cubic")
struct DelayLineCubicTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
/// A unit impulse through a fractional pure delay reproduces the interpolation
/// kernel's impulse response directly (no feedback to entangle the math).
/// Delay = 3.5 samples → integer part 3, frac 0.5. The impulse is written at
/// buffer index 0 (frame 0); reads happen before writes, so it surfaces across
/// the four cubic taps at frames 2…5.
@Test func cubicImpulseResponseMatchesCatmullRomAtHalfSample() {
// catmullRomCubic basis at t = 0.5: pM1 → -0.0625, p0 → 0.5625,
// p1 → 0.5625, p2 → -0.0625. As the lone impulse passes through taps
// (i0,i1,i2,i3) = (writePos-intD+1 … -2), output[2..5] trace that basis.
let dl: DelayLine = DelayLine(input: Impulse.Audio(freq: 1.0),
maxDelay: 16.0 / sr, delay: 3.5 / sr,
sampleRate: sr, interpolation: .cubic)
let g: SynthGraph = makeSynthGraph(engine: engine)
let s: [Double] = dl.calculatedSamples(graph: g, count: engine.blockSize)[0]
#expect(abs(s[0]) < 1e-12)
#expect(abs(s[1]) < 1e-12)
#expect(abs(s[2] - (-0.0625)) < 1e-12)
#expect(abs(s[3] - 0.5625) < 1e-12)
#expect(abs(s[4] - 0.5625) < 1e-12)
#expect(abs(s[5] - (-0.0625)) < 1e-12)
for i: Int in 6..<engine.blockSize {
#expect(abs(s[i]) < 1e-12, "sample \(i) should be silent")
}
}
@Test func linearImpulseResponseAtHalfSample() {
// Linear interp of the same impulse: 0.5 at the two integer taps bracketing
// the 3.5-sample read (frames 3 and 4).
let dl: DelayLine = DelayLine(input: Impulse.Audio(freq: 1.0),
maxDelay: 16.0 / sr, delay: 3.5 / sr,
sampleRate: sr, interpolation: .linear)
let g: SynthGraph = makeSynthGraph(engine: engine)
let s: [Double] = dl.calculatedSamples(graph: g, count: engine.blockSize)[0]
#expect(abs(s[3] - 0.5) < 1e-12)
#expect(abs(s[4] - 0.5) < 1e-12)
#expect(abs(s[2]) < 1e-12)
#expect(abs(s[5]) < 1e-12)
}
@Test func cubicReproducesLinearRampExactly() throws {
// Catmull-Rom is exact on collinear data, so a unit-per-sample ramp delayed
// by a fractional amount yields the same output under .cubic and .linear.
let rampCubic: Phasor.Audio = Phasor.Audio(rate: 1.0, start: 0.0, end: 1.0e9)
let dlCubic: DelayLine = DelayLine(input: rampCubic, maxDelay: 16.0 / sr,
delay: 4.25 / sr, sampleRate: sr, interpolation: .cubic)
let sCubic: [Double] = collectBlocks(dlCubic, engine: engine, blocks: 4)
let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
try engine2.start()
let rampLinear: Phasor.Audio = Phasor.Audio(rate: 1.0, start: 0.0, end: 1.0e9)
let dlLinear: DelayLine = DelayLine(input: rampLinear, maxDelay: 16.0 / sr,
delay: 4.25 / sr, sampleRate: sr, interpolation: .linear)
let sLinear: [Double] = collectBlocks(dlLinear, engine: engine2, blocks: 4)
// Skip the warm-up edge (first ~6 samples) where the ramp history is incomplete.
for i: Int in 8..<sCubic.count {
#expect(abs(sCubic[i] - sLinear[i]) < 1e-9, "cubic vs linear differ at \(i)")
}
}
@Test func cubicFiniteUnderNoise() {
let dl: DelayLine = DelayLine(input: WhiteNoise.Audio(), maxDelay: 0.05,
delay: 0.013, sampleRate: sr, interpolation: .cubic)
let s: [Double] = collectBlocks(dl, engine: engine, blocks: 20)
#expect(s.allSatisfy { $0.isFinite })
}
}
@@ -0,0 +1,53 @@
// DelayLineFeedbackCubicTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - DelayLineFeedbackCubicTests
@MainActor
@Suite("DelayLineFeedback cubic")
struct DelayLineFeedbackCubicTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
/// The wet output of the feedback delay is the cubic-read delayed signal.
/// For a unit impulse and a 3.5-sample delay, the first two non-zero outputs
/// (frames 2 and 3) read only the original impulse — feedback has not yet
/// recirculated into those taps — so they equal the Catmull-Rom basis at
/// t = 0.5 (-0.0625, then 0.5625) regardless of the feedback coefficient.
@Test func cubicFirstEchoMatchesCatmullRomBeforeRecirculation() {
let dlf: DelayLineFeedback = DelayLineFeedback(input: Impulse.Audio(freq: 1.0),
maxDelay: 16.0 / sr, delay: 3.5 / sr,
decayTime: 1.0, sampleRate: sr,
interpolation: .cubic)
let g: SynthGraph = makeSynthGraph(engine: engine)
let s: [Double] = dlf.calculatedSamples(graph: g, count: engine.blockSize)[0]
#expect(abs(s[0]) < 1e-12)
#expect(abs(s[1]) < 1e-12)
#expect(abs(s[2] - (-0.0625)) < 1e-12)
#expect(abs(s[3] - 0.5625) < 1e-12)
#expect(s.allSatisfy { $0.isFinite })
}
@Test func cubicFiniteUnderNoise() {
let dlf: DelayLineFeedback = DelayLineFeedback(input: WhiteNoise.Audio(),
maxDelay: 0.05, delay: 0.013,
decayTime: 0.3, sampleRate: sr,
interpolation: .cubic)
let s: [Double] = collectBlocks(dlf, engine: engine, blocks: 20)
#expect(s.allSatisfy { $0.isFinite })
}
}
@@ -0,0 +1,227 @@
// BalanceTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("Balance")
struct BalanceTests {
let engine: SynthesisEngine
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func quietInMatchedUpToTestRMS() {
// in: quiet sine (amp 0.2); test: louder sine (amp 0.5). Output amplitude
// should rise to ~0.5 → RMS ≈ 0.5/√2 ≈ 0.354.
let quiet: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.2)
let loud: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.5)
let bal: Balance = Balance(in: quiet, test: loud)
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 300)
let tail: [Double] = Array(samples.suffix(engine.blockSize * 100))
let expected: Double = 0.5 / 2.0.squareRoot()
#expect(abs(rmsValue(tail) - expected) < 0.02)
}
@Test func loudInMatchedDownToTestRMS() {
let loud: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 1.0)
let quiet: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.3)
let bal: Balance = Balance(in: loud, test: quiet)
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 300)
let tail: [Double] = Array(samples.suffix(engine.blockSize * 100))
let expected: Double = 0.3 / 2.0.squareRoot()
#expect(abs(rmsValue(tail) - expected) < 0.02)
}
@Test func dcSteadyStateMatchesTestLevel() {
// in DC 0.25, test DC 0.5. ms_in → 0.0625, ms_test → 0.25,
// gain → sqrt(0.25/0.0625) = 2, out → 0.25·2 = 0.5 = test level.
let inDC: ConstantGeneratorInput = ConstantGeneratorInput(0.25)
let testDC: ConstantGeneratorInput = ConstantGeneratorInput(0.5)
let bal: Balance = Balance(in: inDC, test: testDC)
let all: [Double] = collectBlocks(bal, engine: engine, blocks: 400)
let tail: [Double] = Array(all.suffix(engine.blockSize * 50))
let avg: Double = tail.reduce(0.0, +) / Double(tail.count)
#expect(abs(avg - 0.5) < 0.01)
}
@Test func silenceStaysSilentAndFinite() {
let inSil: ConstantGeneratorInput = ConstantGeneratorInput(0.0)
let testSil: ConstantGeneratorInput = ConstantGeneratorInput(0.0)
let bal: Balance = Balance(in: inSil, test: testSil)
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 50)
#expect(samples.allSatisfy { $0.isFinite })
#expect(rmsValue(samples) < 1e-9)
}
@Test func silentTestDrivesInputDown() {
// test is silent → in should be scaled toward zero (can't match RMS of silence).
let sine: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.5)
let testSil: ConstantGeneratorInput = ConstantGeneratorInput(0.0)
let bal: Balance = Balance(in: sine, test: testSil)
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 200)
let tail: [Double] = Array(samples.suffix(engine.blockSize * 50))
#expect(rmsValue(tail) < 0.01)
#expect(samples.allSatisfy { $0.isFinite })
}
@Test func silentInputStaysSilent() {
// in is silent → output stays zero regardless of loud test (0 has no RMS to scale).
let inSil: ConstantGeneratorInput = ConstantGeneratorInput(0.0)
let loud: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.8)
let bal: Balance = Balance(in: inSil, test: loud)
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 100)
#expect(samples.allSatisfy { $0.isFinite })
#expect(rmsValue(samples) < 1e-9)
}
@Test func hpControlsTrackingWindow() {
// Both hp settings converge to the same steady-state DC level; just verify
// both are finite and matched (window length affects speed, not target).
let inDC: ConstantGeneratorInput = ConstantGeneratorInput(0.25)
let testDC: ConstantGeneratorInput = ConstantGeneratorInput(0.5)
let slow: Balance = Balance(in: inDC, test: testDC, hp: 2.0)
let fast: Balance = Balance(in: ConstantGeneratorInput(0.25),
test: ConstantGeneratorInput(0.5), hp: 50.0)
let slowTail: [Double] = Array(collectBlocks(slow, engine: engine, blocks: 600).suffix(engine.blockSize * 50))
let fastTail: [Double] = Array(collectBlocks(fast, engine: engine, blocks: 600).suffix(engine.blockSize * 50))
let slowAvg: Double = slowTail.reduce(0.0, +) / Double(slowTail.count)
let fastAvg: Double = fastTail.reduce(0.0, +) / Double(fastTail.count)
#expect(abs(slowAvg - 0.5) < 0.02)
#expect(abs(fastAvg - 0.5) < 0.02)
}
@Test func mulScalesOutput() {
let inDC: ConstantGeneratorInput = ConstantGeneratorInput(0.25)
let testDC: ConstantGeneratorInput = ConstantGeneratorInput(0.5)
let plain: Balance = Balance(in: ConstantGeneratorInput(0.25),
test: ConstantGeneratorInput(0.5))
let scaled: Balance = Balance(in: inDC, test: testDC, mul: 0.5)
let p: [Double] = Array(collectBlocks(plain, engine: engine, blocks: 400).suffix(engine.blockSize * 50))
let s: [Double] = Array(collectBlocks(scaled, engine: engine, blocks: 400).suffix(engine.blockSize * 50))
let pAvg: Double = p.reduce(0.0, +) / Double(p.count)
let sAvg: Double = s.reduce(0.0, +) / Double(s.count)
#expect(abs(sAvg - 0.5 * pAvg) < 0.01)
}
@Test func finiteWithNoise() {
let bal: Balance = Balance(in: WhiteNoise.Audio(mul: 0.1),
test: WhiteNoise.Audio(mul: 0.5))
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 200)
#expect(samples.allSatisfy { $0.isFinite })
}
// MARK: - smooth (decoupled gain lag)
@Test func smoothDefaultIsBackwardCompatible() {
// smooth == 0.0 (default) must reproduce the un-smoothed steady-state exactly.
let bal: Balance = Balance(in: ConstantGeneratorInput(0.25),
test: ConstantGeneratorInput(0.5), smooth: 0.0)
let all: [Double] = collectBlocks(bal, engine: engine, blocks: 400)
let tail: [Double] = Array(all.suffix(engine.blockSize * 50))
let avg: Double = tail.reduce(0.0, +) / Double(tail.count)
#expect(abs(avg - 0.5) < 0.01)
}
@Test func smoothPreservesSteadyLevel() {
// A gain lag must not change the converged level, only the path to it.
let bal: Balance = Balance(in: ConstantGeneratorInput(0.25),
test: ConstantGeneratorInput(0.5), smooth: 0.05)
let all: [Double] = collectBlocks(bal, engine: engine, blocks: 600)
let tail: [Double] = Array(all.suffix(engine.blockSize * 50))
let avg: Double = tail.reduce(0.0, +) / Double(tail.count)
#expect(abs(avg - 0.5) < 0.01)
}
@Test func largerSmoothSlowsInitialResponse() {
// From the unity-gain start, a quiet-in/loud-test pair needs gain > 1. With a gain
// lag the early output rises more slowly, so its early-window RMS is lower; both
// converge to the same tail level.
let unsmoothed: Balance = Balance(in: OscSin.Audio(freq: 200.0, mul: 0.2),
test: OscSin.Audio(freq: 200.0, mul: 0.5), smooth: 0.0)
let smoothed: Balance = Balance(in: OscSin.Audio(freq: 200.0, mul: 0.2),
test: OscSin.Audio(freq: 200.0, mul: 0.5), smooth: 0.1)
let u: [Double] = collectBlocks(unsmoothed, engine: engine, blocks: 300)
let s: [Double] = collectBlocks(smoothed, engine: engine, blocks: 300)
let earlyWin: Int = engine.blockSize * 15
#expect(rmsValue(Array(u.prefix(earlyWin))) > rmsValue(Array(s.prefix(earlyWin))))
let target: Double = 0.5 / 2.0.squareRoot()
#expect(abs(rmsValue(Array(u.suffix(engine.blockSize * 100))) - target) < 0.02)
#expect(abs(rmsValue(Array(s.suffix(engine.blockSize * 100))) - target) < 0.02)
}
// MARK: - logDomain (decibel-domain gain glide)
@Test func logDomainDCSteadyStateMatchesTestLevel() {
let bal: Balance = Balance(in: ConstantGeneratorInput(0.25),
test: ConstantGeneratorInput(0.5), smooth: 0.02, logDomain: true)
let all: [Double] = collectBlocks(bal, engine: engine, blocks: 500)
let tail: [Double] = Array(all.suffix(engine.blockSize * 50))
let avg: Double = tail.reduce(0.0, +) / Double(tail.count)
#expect(abs(avg - 0.5) < 0.01)
}
@Test func logDomainQuietSineMatchedUpToTestRMS() {
let quiet: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.2)
let loud: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.5)
let bal: Balance = Balance(in: quiet, test: loud, smooth: 0.02, logDomain: true)
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 500)
let tail: [Double] = Array(samples.suffix(engine.blockSize * 100))
let expected: Double = 0.5 / 2.0.squareRoot()
#expect(abs(rmsValue(tail) - expected) < 0.02)
}
@Test func logDomainSilenceStaysSilentAndFinite() {
let bal: Balance = Balance(in: ConstantGeneratorInput(0.0),
test: ConstantGeneratorInput(0.0), logDomain: true)
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 50)
#expect(samples.allSatisfy { $0.isFinite })
#expect(rmsValue(samples) < 1e-9)
}
@Test func logDomainSilentInputStaysSilent() {
let bal: Balance = Balance(in: ConstantGeneratorInput(0.0),
test: OscSin.Audio(freq: 200.0, mul: 0.8), logDomain: true)
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 100)
#expect(samples.allSatisfy { $0.isFinite })
#expect(rmsValue(samples) < 1e-9)
}
@Test func logDomainSilentTestDrivesInputDown() {
let bal: Balance = Balance(in: OscSin.Audio(freq: 200.0, mul: 0.5),
test: ConstantGeneratorInput(0.0), smooth: 0.02, logDomain: true)
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 300)
let tail: [Double] = Array(samples.suffix(engine.blockSize * 50))
#expect(rmsValue(tail) < 0.01)
#expect(samples.allSatisfy { $0.isFinite })
}
@Test func logDomainMulScalesOutput() {
let plain: Balance = Balance(in: ConstantGeneratorInput(0.25),
test: ConstantGeneratorInput(0.5), smooth: 0.02, logDomain: true)
let scaled: Balance = Balance(in: ConstantGeneratorInput(0.25),
test: ConstantGeneratorInput(0.5), smooth: 0.02, logDomain: true, mul: 0.5)
let p: [Double] = Array(collectBlocks(plain, engine: engine, blocks: 500).suffix(engine.blockSize * 50))
let s: [Double] = Array(collectBlocks(scaled, engine: engine, blocks: 500).suffix(engine.blockSize * 50))
let pAvg: Double = p.reduce(0.0, +) / Double(p.count)
let sAvg: Double = s.reduce(0.0, +) / Double(s.count)
#expect(abs(sAvg - 0.5 * pAvg) < 0.01)
}
@Test func logDomainFiniteWithNoise() {
let bal: Balance = Balance(in: WhiteNoise.Audio(mul: 0.1),
test: WhiteNoise.Audio(mul: 0.5), logDomain: true)
let samples: [Double] = collectBlocks(bal, engine: engine, blocks: 200)
#expect(samples.allSatisfy { $0.isFinite })
}
}
@@ -0,0 +1,136 @@
// NormalizerTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
private func peak(_ samples: [Double]) -> Double {
samples.map { abs($0) }.max() ?? 0
}
@MainActor
@Suite("Normalizer")
struct NormalizerTests {
let engine: SynthesisEngine
let sr: Double = 44100.0
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func quietSineNormalizedUpToLevel() {
// A sine well below `level` is scaled UP so its steady-state peak ≈ level.
let level: Double = 0.8
let sine: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.2)
let norm: Normalizer = Normalizer(in: sine, level: level, dur: 0.01, sampleRate: sr)
let samples: [Double] = collectBlocks(norm, engine: engine, blocks: 300)
let tail: [Double] = Array(samples.suffix(engine.blockSize * 100))
let p: Double = peak(tail)
#expect(p > level - 0.05)
#expect(p < level + 0.02)
}
@Test func loudSineNormalizedDownToLevel() {
// A sine above `level` is scaled DOWN; steady-state peak ≈ level, no overshoot.
let level: Double = 0.5
let sine: OscSin.Audio = OscSin.Audio(freq: 220.0, mul: 2.0)
let norm: Normalizer = Normalizer(in: sine, level: level, dur: 0.01, sampleRate: sr)
let samples: [Double] = collectBlocks(norm, engine: engine, blocks: 200)
let tail: [Double] = Array(samples.suffix(engine.blockSize * 100))
let p: Double = peak(tail)
#expect(p > level - 0.05)
#expect(p < level + 0.001)
}
@Test func peakNeverExceedsLevelOnTransient() {
// Look-ahead must pre-emptively reduce gain so a sudden loud burst never
// overshoots `level`.
let level: Double = 0.5
let sine: OscSin.Audio = OscSin.Audio(freq: 110.0, mul: 3.0)
let norm: Normalizer = Normalizer(in: sine, level: level, dur: 0.01, sampleRate: sr)
let samples: [Double] = collectBlocks(norm, engine: engine, blocks: 200)
let violators: [Double] = samples.filter { abs($0) > level + 0.001 }
#expect(violators.isEmpty)
}
@Test func delayedByDurSamples() {
// An impulse at sample 0 appears delayed by Int(dur·sr); the first dur·sr
// output samples are zero.
let dur: Double = 0.003
let delaySamples: Int = Int(dur * sr)
let impulse: Impulse.Audio = Impulse.Audio(freq: 0.0)
let norm: Normalizer = Normalizer(in: impulse, level: 1.0, dur: dur, sampleRate: sr)
let blocks: Int = (delaySamples / engine.blockSize) + 5
let samples: [Double] = collectBlocks(norm, engine: engine, blocks: blocks)
let prefix: [Double] = Array(samples.prefix(delaySamples))
#expect(prefix.allSatisfy { abs($0) < 0.001 })
}
@Test func levelParamScales() {
// Doubling `level` doubles the normalized steady-state peak.
let sine: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.3)
let low: Normalizer = Normalizer(in: sine, level: 0.3, dur: 0.01, sampleRate: sr)
let lowSamples: [Double] = collectBlocks(low, engine: engine, blocks: 300)
let sine2: OscSin.Audio = OscSin.Audio(freq: 200.0, mul: 0.3)
let high: Normalizer = Normalizer(in: sine2, level: 0.6, dur: 0.01, sampleRate: sr)
let highSamples: [Double] = collectBlocks(high, engine: engine, blocks: 300)
let pLow: Double = peak(Array(lowSamples.suffix(engine.blockSize * 100)))
let pHigh: Double = peak(Array(highSamples.suffix(engine.blockSize * 100)))
#expect(abs(pHigh - 2.0 * pLow) < 0.05)
}
@Test func silenceStaysSilentAndFinite() {
// Zero input must not blow up (no level/0 division producing NaN/Inf).
let silence: ConstantGeneratorInput = ConstantGeneratorInput(0.0)
let norm: Normalizer = Normalizer(in: silence, level: 1.0, dur: 0.01, sampleRate: sr)
let samples: [Double] = collectBlocks(norm, engine: engine, blocks: 50)
#expect(samples.allSatisfy { $0.isFinite })
#expect(peak(samples) < 1e-9)
}
@Test func dcConvergesToLevel() {
// Constant DC v with level L → gain converges to L/v, output → L.
let level: Double = 0.5
let dc: ConstantGeneratorInput = ConstantGeneratorInput(0.25)
let norm: Normalizer = Normalizer(in: dc, level: level, dur: 0.01, sampleRate: sr)
let all: [Double] = collectBlocks(norm, engine: engine, blocks: 300)
let tail: [Double] = Array(all.suffix(engine.blockSize * 50))
let avg: Double = tail.reduce(0.0, +) / Double(tail.count)
#expect(abs(avg - level) < 0.01)
}
@Test func zeroDelayNormalizesDownExactly() {
// dur == 0 fast path: releaseCoeff == 0, attackComp == 1 → gain reaches
// level/|x| within one sample. DC 2.0 at level 1.0 → every output == 1.0.
let dc: ConstantGeneratorInput = ConstantGeneratorInput(2.0)
let norm: Normalizer = Normalizer(in: dc, level: 1.0, dur: 0.0, sampleRate: sr)
let samples: [Double] = collectBlocks(norm, engine: engine, blocks: 2)
#expect(samples.allSatisfy { abs($0 - 1.0) < 1e-12 })
}
@Test func zeroDelayScalesUpExactly() {
// dur == 0 fast path scaling up: DC 0.25 at level 1.0 → gain 4, output 1.0.
let dc: ConstantGeneratorInput = ConstantGeneratorInput(0.25)
let norm: Normalizer = Normalizer(in: dc, level: 1.0, dur: 0.0, sampleRate: sr)
let samples: [Double] = collectBlocks(norm, engine: engine, blocks: 2)
#expect(samples.allSatisfy { abs($0 - 1.0) < 1e-12 })
}
@Test func finiteWithNoise() {
let norm: Normalizer = Normalizer(in: WhiteNoise.Audio(mul: 0.4),
level: 0.9, dur: 0.005, sampleRate: sr)
let samples: [Double] = collectBlocks(norm, engine: engine, blocks: 200)
#expect(samples.allSatisfy { $0.isFinite })
// Peak should be bounded near level once settled.
let tail: [Double] = Array(samples.suffix(engine.blockSize * 100))
#expect(peak(tail) < 0.9 + 0.01)
}
}
@@ -0,0 +1,144 @@
// FormletAudioTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - Local DFT helper
private func dftMag(samples: [Double], freq: Double, sampleRate: Double) -> Double {
let n: Int = samples.count
guard n > 0 else { return 0 }
var re: Double = 0.0, im: Double = 0.0
for i: Int in 0..<n {
let phase: Double = 2.0 * Double.pi * freq * Double(i) / sampleRate
re += samples[i] * cos(phase)
im -= samples[i] * sin(phase)
}
return sqrt(re * re + im * im) / Double(n)
}
// MARK: - FormletAudioTests
@MainActor
@Suite("Formlet.Audio")
struct FormletAudioTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func impulseRingsAtFreq() {
// Deterministic impulse excitation. The resonant decay rings at `freq`;
// energy there far exceeds a frequency well above the resonance.
let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0)
let formlet: Formlet.Audio = Formlet.Audio(input: impulse, freq: 880.0,
attackTime: 0.002, decayTime: 0.2)
let samples: [Double] = collectBlocks(formlet, engine: engine, blocks: 60)
let magAt: Double = dftMag(samples: samples, freq: 880, sampleRate: sr)
let magAbove: Double = dftMag(samples: samples, freq: 4000, sampleRate: sr)
#expect(magAt > magAbove)
#expect(samples.allSatisfy { $0.isFinite })
}
@Test func longerDecayTimeDecaysSlower() throws {
let impulse1: Impulse.Audio = Impulse.Audio(freq: 1.0)
let f1: Formlet.Audio = Formlet.Audio(input: impulse1, freq: 440.0,
attackTime: 0.002, decayTime: 0.05)
let s1: [Double] = collectBlocks(f1, engine: engine, blocks: 40)
let rms1: Double = rmsValue(Array(s1.suffix(10 * engine.blockSize)))
let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr)
try engine2.start()
let impulse2: Impulse.Audio = Impulse.Audio(freq: 1.0)
let f2: Formlet.Audio = Formlet.Audio(input: impulse2, freq: 440.0,
attackTime: 0.002, decayTime: 0.5)
let s2: [Double] = collectBlocks(f2, engine: engine2, blocks: 40)
let rms2: Double = rmsValue(Array(s2.suffix(10 * engine2.blockSize)))
#expect(rms2 > rms1)
}
@Test func dcInputDecaysFinite() {
let dc: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
let formlet: Formlet.Audio = Formlet.Audio(input: dc, freq: 440.0,
attackTime: 0.005, decayTime: 0.1)
let samples: [Double] = collectBlocks(formlet, engine: engine, blocks: 50)
#expect(samples.allSatisfy { $0.isFinite })
}
@Test func audioRateFreqModNoCrash() {
let lfo: OscSin.Audio = OscSin.Audio(freq: 2.0)
let freqGen: BinaryOpGenerator = lfo * 200.0 + 440.0
let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0)
let formlet: Formlet.Audio = Formlet.Audio(input: impulse, freq: freqGen,
attackTime: 0.002, decayTime: 0.2)
let samples: [Double] = collectBlocks(formlet, engine: engine, blocks: 20)
#expect(samples.allSatisfy { $0.isFinite })
}
@Test func audioRateTimeModNoCrash() {
let lfoA: OscSin.Audio = OscSin.Audio(freq: 0.7)
let attackGen: BinaryOpGenerator = lfoA * 0.001 + 0.003
let lfoD: OscSin.Audio = OscSin.Audio(freq: 0.5)
let decayGen: BinaryOpGenerator = lfoD * 0.1 + 0.2
let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0)
let formlet: Formlet.Audio = Formlet.Audio(input: impulse, freq: 440.0,
attackTime: attackGen, decayTime: decayGen)
let samples: [Double] = collectBlocks(formlet, engine: engine, blocks: 20)
#expect(samples.allSatisfy { $0.isFinite })
}
@Test func participatesInFanOutCache() {
let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0)
let formlet: Formlet.Audio = Formlet.Audio(input: impulse, freq: 440.0,
attackTime: 0.002, decayTime: 0.2)
let g: SynthGraph = makeSynthGraph(engine: engine)
let r1: [[Double]] = formlet.calculatedSamples(graph: g, count: engine.blockSize)
let r2: [[Double]] = formlet.calculatedSamples(graph: g, count: engine.blockSize)
#expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize)))
}
@Test func denormalsDoNotAccumulate() {
let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0)
let formlet: Formlet.Audio = Formlet.Audio(input: impulse, freq: 440.0,
attackTime: 0.001, decayTime: 0.01)
let samples: [Double] = collectBlocks(formlet, engine: engine, blocks: 200)
#expect(samples.allSatisfy { $0.isFinite })
#expect(samples.allSatisfy { !$0.isSubnormal })
}
@Test func deterministicFirstSampleMatchesFormula() {
// Step input, zero state: out[0] = (1−R_decay)·1 − (1−R_attack)·1 = R_attack − R_decay.
let attackTime: Double = 0.005
let decayTime: Double = 0.2
let log0001: Double = log(0.001)
let rDecay: Double = exp(log0001 / (decayTime * sr))
let rAttack: Double = exp(log0001 / (attackTime * sr))
let expectedFirstSample: Double = rAttack - rDecay
let input: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
let formlet: Formlet.Audio = Formlet.Audio(input: input, freq: 440.0,
attackTime: attackTime, decayTime: decayTime)
let g: SynthGraph = makeSynthGraph(engine: engine)
let samples: [[Double]] = formlet.calculatedSamples(graph: g, count: engine.blockSize)
#expect(abs(samples[0][0] - expectedFirstSample) < 1e-10)
}
@Test func equalAttackDecayCancelsToSilence() {
// attackTime == decayTime → the two Ringz are identical, difference is exactly zero.
let dc: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
let formlet: Formlet.Audio = Formlet.Audio(input: dc, freq: 440.0,
attackTime: 0.1, decayTime: 0.1)
let samples: [Double] = collectBlocks(formlet, engine: engine, blocks: 10)
#expect(samples.allSatisfy { abs($0) < 1e-12 })
}
}
@@ -0,0 +1,53 @@
// FormletControlTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - FormletControlTests
@MainActor
@Suite("Formlet.Control")
struct FormletControlTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func finiteOutput() {
let trig: Impulse.Control = Impulse.Control(freq: 4.0)
let formlet: Formlet.Control = Formlet.Control(input: trig, freq: 60.0,
attackTime: 0.01, decayTime: 0.3)
let samples: [Double] = collectBlocks(formlet, engine: engine, blocks: 40)
#expect(samples.allSatisfy { $0.isFinite })
}
@Test func deterministicFirstBlockMatchesFormula() {
// Control rate: resonators step once per block at sampleRate/blockSize.
// out = (1−R_decay)·x − (1−R_attack)·x = (R_attack − R_decay)·x, x=1, zero state.
let attackTime: Double = 0.05
let decayTime: Double = 0.5
let controlRate: Double = sr / Double(engine.blockSize)
let log0001: Double = log(0.001)
let rDecay: Double = exp(log0001 / (decayTime * controlRate))
let rAttack: Double = exp(log0001 / (attackTime * controlRate))
let expected: Double = rAttack - rDecay
let input: ConstantGeneratorInput = ConstantGeneratorInput(1.0)
let formlet: Formlet.Control = Formlet.Control(input: input, freq: 50.0,
attackTime: attackTime, decayTime: decayTime)
let g: SynthGraph = makeSynthGraph(engine: engine)
let samples: [[Double]] = formlet.calculatedSamples(graph: g, count: engine.blockSize)
// Constant fill across the block.
#expect(abs(samples[0][0] - expected) < 1e-10)
#expect(abs(samples[0][engine.blockSize - 1] - expected) < 1e-10)
}
}
@@ -0,0 +1,164 @@
// KlankTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - Local DFT helper
private func dftMag(samples: [Double], freq: Double, sampleRate: Double) -> Double {
let n: Int = samples.count
guard n > 0 else { return 0 }
var re: Double = 0.0
var im: Double = 0.0
for i: Int in 0..<n {
let phase: Double = 2.0 * Double.pi * freq * Double(i) / sampleRate
re += samples[i] * cos(phase)
im -= samples[i] * sin(phase)
}
return sqrt(re * re + im * im) / Double(n)
}
/// Build a `[freq, amp, decay]` spec buffer (Klank channel order).
private func makeSpec(_ triplets: [(Double, Double, Double)]) -> LyrebirdBuffer {
let buf: LyrebirdBuffer = LyrebirdBuffer(count: triplets.count, channelCount: klankSpecChannelCount)
for (i, t) in triplets.enumerated() {
buf.setValue(t.0, frame: i, channel: klankFreqChannel)
buf.setValue(t.1, frame: i, channel: klankAmpChannel)
buf.setValue(t.2, frame: i, channel: klankDecayChannel)
}
return buf
}
@MainActor
@Suite("Klank")
struct KlankTests {
let engine: SynthesisEngine
let sr: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func dftPeaksAtAllModes() {
let spec: LyrebirdBuffer = makeSpec([
(440.0, 1.0, 0.5),
(1320.0, 1.0, 0.5),
])
let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0)
let voice: Klank.Audio = Klank.Audio(input: impulse, buffer: spec)
let samples: [Double] = collectBlocks(voice, engine: engine, blocks: 200)
let tail: [Double] = Array(samples.suffix(100 * engine.blockSize))
let mag440: Double = dftMag(samples: tail, freq: 440, sampleRate: sr)
let mag1320: Double = dftMag(samples: tail, freq: 1320, sampleRate: sr)
let mag200: Double = dftMag(samples: tail, freq: 200, sampleRate: sr)
let mag800: Double = dftMag(samples: tail, freq: 800, sampleRate: sr)
#expect(mag440 > mag200)
#expect(mag440 > mag800)
#expect(mag1320 > mag200)
#expect(mag1320 > mag800)
#expect(samples.allSatisfy { $0.isFinite })
}
@Test func freqscaleShiftsAllModesUp() {
// With freqscale 2.0 the energy should move from 440 to 880 Hz.
let spec: LyrebirdBuffer = makeSpec([(440.0, 1.0, 0.5)])
let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0)
let voice: Klank.Audio = Klank.Audio(input: impulse, buffer: spec, freqscale: 2.0)
let samples: [Double] = collectBlocks(voice, engine: engine, blocks: 200)
let tail: [Double] = Array(samples.suffix(100 * engine.blockSize))
let mag440: Double = dftMag(samples: tail, freq: 440, sampleRate: sr)
let mag880: Double = dftMag(samples: tail, freq: 880, sampleRate: sr)
#expect(mag880 > mag440)
#expect(samples.allSatisfy { $0.isFinite })
}
@Test func freqoffsetShiftsMode() {
// 200 Hz mode + 600 Hz offset → resonance at 800 Hz.
let spec: LyrebirdBuffer = makeSpec([(200.0, 1.0, 0.5)])
let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0)
let voice: Klank.Audio = Klank.Audio(input: impulse, buffer: spec, freqoffset: 600.0)
let samples: [Double] = collectBlocks(voice, engine: engine, blocks: 200)
let tail: [Double] = Array(samples.suffix(100 * engine.blockSize))
let mag200: Double = dftMag(samples: tail, freq: 200, sampleRate: sr)
let mag800: Double = dftMag(samples: tail, freq: 800, sampleRate: sr)
#expect(mag800 > mag200)
}
@Test func decayscaleLengthensRing() {
// Same spec, two decayscale values: the longer ring keeps more late energy.
let triplet: [(Double, Double, Double)] = [(440.0, 1.0, 0.3)]
let shortVoice: Klank.Audio = Klank.Audio(
input: Impulse.Audio(freq: 0.0), buffer: makeSpec(triplet), decayscale: 0.3)
let longVoice: Klank.Audio = Klank.Audio(
input: Impulse.Audio(freq: 0.0), buffer: makeSpec(triplet), decayscale: 3.0)
// Each voice is a fresh instance; collectBlocks evaluates them independently
// (its own Impulse(freq: 0) fires at that voice's first-block sample 0).
let shortSamples: [Double] = collectBlocks(shortVoice, engine: engine, blocks: 120)
let longSamples: [Double] = collectBlocks(longVoice, engine: engine, blocks: 120)
// Compare energy in the late window (after the impulse fires at sample 0).
let lateWindow: Int = 80 * engine.blockSize
let shortLate: Double = rmsValue(Array(shortSamples.suffix(shortSamples.count - lateWindow)))
let longLate: Double = rmsValue(Array(longSamples.suffix(longSamples.count - lateWindow)))
#expect(longLate > shortLate)
}
@Test func setBufferNilSilencesBank() {
let spec: LyrebirdBuffer = makeSpec([(440.0, 1.0, 0.5)])
let voice: Klank.Audio = Klank.Audio(input: Impulse.Audio(freq: 200.0), buffer: spec)
_ = collectBlocks(voice, engine: engine, blocks: 4)
voice.setBuffer(nil, engine: engine)
let after: [Double] = collectBlocks(voice, engine: engine, blocks: 20)
// Filter state rings briefly, then with no spec the bank produces silence.
let tail: [Double] = Array(after.suffix(8 * engine.blockSize))
#expect(rmsValue(tail) < 1e-6)
}
@Test func mulScalesOutput() {
let spec: LyrebirdBuffer = makeSpec([(440.0, 1.0, 0.5)])
let plain: Klank.Audio = Klank.Audio(input: Impulse.Audio(freq: 0.0), buffer: makeSpec([(440.0, 1.0, 0.5)]))
let scaled: Klank.Audio = Klank.Audio(input: Impulse.Audio(freq: 0.0), buffer: spec, mul: 0.5)
let p: [Double] = collectBlocks(plain, engine: engine, blocks: 40)
let s: [Double] = collectBlocks(scaled, engine: engine, blocks: 40)
#expect(abs(rmsValue(s) - 0.5 * rmsValue(p)) < 1e-9 + 1e-3 * rmsValue(p))
#expect(s.allSatisfy { $0.isFinite })
}
@Test func finiteAndStable() {
let spec: LyrebirdBuffer = makeSpec([
(110.0, 1.0, 2.0),
(220.0, 0.5, 1.0),
(330.0, 0.25, 0.5),
])
let voice: Klank.Audio = Klank.Audio(input: WhiteNoise.Audio(mul: 0.1), buffer: spec)
let samples: [Double] = collectBlocks(voice, engine: engine, blocks: 100)
#expect(samples.allSatisfy { $0.isFinite })
}
@Test func deterministicFirstSampleMatchesRingzFormula() {
// With a DC-1 input and zeroed filter state, the first output sample of a
// single resonator equals b0 = (1 − R)·amp, R = exp(log(0.001)/(decay·sr)).
let freq: Double = 440.0
let amp: Double = 0.8
let decay: Double = 0.5
let spec: LyrebirdBuffer = makeSpec([(freq, amp, decay)])
let voice: Klank.Audio = Klank.Audio(input: 1.0, buffer: spec)
let samples: [Double] = collectBlocks(voice, engine: engine, blocks: 1)
let r: Double = exp(log(0.001) / (decay * sr))
let expected: Double = (1.0 - r) * amp
#expect(abs(samples[0] - expected) < 1e-10)
}
}
@@ -0,0 +1,180 @@
// SlewAudioTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("Slew.Audio")
struct SlewAudioTests {
let engine: SynthesisEngine
var graph: SynthGraph { makeSynthGraph(engine: engine) }
let blockSize: Int = 64
let sampleRate: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func rateIsAudio() {
let gen: Slew.Audio = Slew.Audio(input: 0.0)
#expect(gen.rate == .audio)
}
/// Output count correct.
@Test func outputCountMatchesRequest() {
let gen: Slew.Audio = Slew.Audio(input: 0.5)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(Array(out[0].prefix(blockSize)).count == blockSize)
}
/// First sample initializes to the first input value (no slew on sample 0).
@Test func firstSampleInitializesToInput() {
let inputVal: Double = 0.8
let gen: Slew.Audio = Slew.Audio(input: inputVal, up: 0.001, dn: 0.001)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(abs(out[0][0] - inputVal) < 1e-12,
"sample 0 should equal first input \(inputVal), got \(out[0][0])")
}
/// Step up clamped to up/sr per sample: input 0→1 with up=sr reaches 1.0 in one sample.
@Test func stepUpClampedToUpPerSampleReachesTargetInOneSample() {
// up = sampleRate → upStep = sampleRate / sampleRate = 1.0 per sample.
// Input goes to 1.0 at sample 1, state starts at 0.0 (init'd to sample 0 = 0).
// At sample 1: x=1.0, state=0.0+1.0=1.0 (exactly).
let upRate: Double = sampleRate
let inputSignal: Closure = Closure { _, i in i == 0 ? 0.0 : 1.0 }
let gen: Slew.Audio = Slew.Audio(input: inputSignal, up: upRate, dn: 0.001)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
// Sample 0: initialized to 0.0.
#expect(abs(out[0][0] - 0.0) < 1e-12)
// Sample 1: x=1.0, upStep=1.0 → state reaches 1.0 in one step.
#expect(abs(out[0][1] - 1.0) < 1e-12,
"with up=sampleRate, should reach 1.0 in one step, got \(out[0][1])")
// Samples 2+: stays at 1.0 (input stays at 1.0).
for i: Int in 2..<blockSize {
#expect(abs(out[0][i] - 1.0) < 1e-12)
}
}
/// Step up clamped: input 0→1 with up=sr/2 takes 2 samples to reach 1.0.
@Test func stepUpClampedTakesMultipleSamples() {
// up = sampleRate/2 → upStep = 0.5 per sample.
let upRate: Double = sampleRate / 2.0
let inputSignal: Closure = Closure { _, i in i == 0 ? 0.0 : 1.0 }
let gen: Slew.Audio = Slew.Audio(input: inputSignal, up: upRate, dn: 0.001)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
// Sample 0: init'd to 0.0.
#expect(abs(out[0][0] - 0.0) < 1e-12)
// Sample 1: x=1.0, state=0.0+0.5=0.5 (clamped to upStep).
#expect(abs(out[0][1] - 0.5) < 1e-12,
"first slew step: expected 0.5 got \(out[0][1])")
// Sample 2: x=1.0, state=0.5+0.5=1.0 (reaches target).
#expect(abs(out[0][2] - 1.0) < 1e-12,
"second slew step: expected 1.0 got \(out[0][2])")
}
/// Step down clamped to dn/sr per sample.
@Test func stepDownClamped() {
// dn = sampleRate/2 → dnStep = 0.5 per sample.
let dnRate: Double = sampleRate / 2.0
// Input: 1.0 on sample 0 (init), then drops to 0.0.
let inputSignal: Closure = Closure { _, i in i == 0 ? 1.0 : 0.0 }
let gen: Slew.Audio = Slew.Audio(input: inputSignal, up: 0.001, dn: dnRate)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
// Sample 0: init'd to 1.0.
#expect(abs(out[0][0] - 1.0) < 1e-12)
// Sample 1: x=0.0, state=1.0-0.5=0.5 (clamped to dnStep).
#expect(abs(out[0][1] - 0.5) < 1e-12,
"step down sample 1: expected 0.5 got \(out[0][1])")
// Sample 2: x=0.0, state=0.5-0.5=0.0.
#expect(abs(out[0][2] - 0.0) < 1e-12,
"step down sample 2: expected 0.0 got \(out[0][2])")
}
/// Tracks exactly when input change is within the step budget.
@Test func tracksExactlyWithinStepBudget() {
// up = sampleRate (1.0/sample), dn = sampleRate (1.0/sample).
// Input ramps by 0.01 per sample — well within budget, so output should track exactly.
let upRate: Double = sampleRate
let dnRate: Double = sampleRate
let inputSignal: Closure = Closure { _, i in Double(i) * 0.01 }
let gen: Slew.Audio = Slew.Audio(input: inputSignal, up: upRate, dn: dnRate)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
let expected: Double = Double(i) * 0.01
#expect(abs(out[0][i] - expected) < 1e-12,
"tracking sample \(i): expected \(expected) got \(out[0][i])")
}
}
/// Cross-block state continuity.
@Test func crossBlockStateContinuity() {
// Slow slew rate so state doesn't reach target within one block.
let upRate: Double = 10.0 // 10 units/sec → upStep = 10/44100 ≈ 0.000227 per sample.
// Input: 0.0 for block 1, then 1.0 for block 2.
let firstSerial: UInt64 = engine.segmentSerial
let inputSignal: Closure = Closure { graph, _ in
graph.engine.segmentSerial == firstSerial ? 0.0 : 1.0
}
let gen: Slew.Audio = Slew.Audio(input: inputSignal, up: upRate, dn: upRate)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
advanceBlock(engine)
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
// Block 2 sample 0 should be slightly above 0.0 (the slew is rising toward 1.0).
let upStep: Double = upRate / sampleRate
#expect(abs(out2[0][0] - upStep) < 1e-12,
"block 2 sample 0: expected \(upStep) got \(out2[0][0])")
}
/// Asymmetric up ≠ dn.
@Test func asymmetricUpDownRates() {
// up = sampleRate (1.0/sample), dn = sampleRate/4 (0.25/sample).
let upRate: Double = sampleRate
let dnRate: Double = sampleRate / 4.0
// Input: 1.0 for first 32 samples, then 0.0.
let inputSignal: Closure = Closure { _, i in i < 32 ? 1.0 : 0.0 }
let gen: Slew.Audio = Slew.Audio(input: inputSignal, up: upRate, dn: dnRate)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
// Sample 0: init'd to 1.0.
#expect(abs(out[0][0] - 1.0) < 1e-12)
// Samples 1..31: stay at 1.0 (input = 1.0, within upStep).
for i: Int in 1..<32 {
#expect(abs(out[0][i] - 1.0) < 1e-12)
}
// Sample 32: x=0.0, dnStep=0.25. state=1.0-0.25=0.75.
#expect(abs(out[0][32] - 0.75) < 1e-12,
"asymmetric down sample 32: expected 0.75 got \(out[0][32])")
}
/// Fan-out: two calls same segment return identical first channel.
@Test func fanOut() {
let gen: Slew.Audio = Slew.Audio(input: 0.5, up: 10.0, dn: 10.0)
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
#expect(out1[0][i] == out2[0][i])
}
}
/// mul/add: output is original*2+1.
@Test func mulAdd() {
// Use a slow input ramp so output = input (large up/dn budget).
let inputSignal: Closure = Closure { _, i in Double(i) * 0.001 }
let genBase: Slew.Audio = Slew.Audio(input: inputSignal, up: sampleRate, dn: sampleRate)
let genScaled: Slew.Audio = Slew.Audio(input: inputSignal, up: sampleRate, dn: sampleRate, mul: 2.0, add: 1.0)
let base: [[Double]] = genBase.calculatedSamples(graph: graph, count: blockSize)
let scaled: [[Double]] = genScaled.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
let expected: Double = base[0][i] * 2.0 + 1.0
#expect(abs(scaled[0][i] - expected) < 1e-12,
"mulAdd sample \(i): expected \(expected) got \(scaled[0][i])")
}
}
}
@@ -0,0 +1,153 @@
// SlewControlTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("Slew.Control")
struct SlewControlTests {
let engine: SynthesisEngine
var graph: SynthGraph { makeSynthGraph(engine: engine) }
let blockSize: Int = 64
let sampleRate: Double = 44100
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
@Test func rateIsControl() {
let gen: Slew.Control = Slew.Control(input: 0.0)
#expect(gen.rate == .control)
}
/// Output count correct.
@Test func outputCountMatchesRequest() {
let gen: Slew.Control = Slew.Control(input: 0.5)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(Array(out[0].prefix(blockSize)).count == blockSize)
}
/// Control-rate step: first block initializes state to input, no movement.
@Test func firstBlockInitializesToInput() {
let inputVal: Double = 0.7
// With very slow up/dn (0.001 units/sec), the first block just initializes.
let gen: Slew.Control = Slew.Control(input: inputVal, up: 0.001, dn: 0.001)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(abs(gen.previousOutputValue - inputVal) < 1e-12,
"first block should initialize to input \(inputVal), got \(gen.previousOutputValue)")
}
/// Control-rate step: upStep = up / controlRate. With input jumping from 0 to 1,
/// the output advances by upStep per block.
@Test func controlRateStepPerBlock() {
let upRate: Double = 100.0 // units/sec
let controlRate: Double = sampleRate / Double(blockSize) // 44100/64 ≈ 689.06 Hz
let upStep: Double = upRate / controlRate
// Block 1: input = 0.0 (initialize to 0.0).
let firstSerial: UInt64 = engine.segmentSerial
let inputSignal: Closure = Closure { graph, _ in
graph.engine.segmentSerial == firstSerial ? 0.0 : 1.0
}
let gen: Slew.Control = Slew.Control(input: inputSignal, up: upRate, dn: upRate)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(abs(gen.previousOutputValue - 0.0) < 1e-12)
// Block 2: input = 1.0. State should advance by upStep toward 1.0.
advanceBlock(engine)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(abs(gen.previousOutputValue - upStep) < 1e-12,
"after block 2: expected \(upStep) got \(gen.previousOutputValue)")
}
/// Output block is flat (vDSP_vfillD): all samples equal the slewed value.
@Test func outputBlockIsFlat() {
let gen: Slew.Control = Slew.Control(input: 0.5)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let expected: Double = out[0][0]
for i: Int in 1..<blockSize {
#expect(out[0][i] == expected,
"expected flat block, but sample \(i) = \(out[0][i]) differs from sample 0 = \(expected)")
}
}
/// Tracks toward target over successive blocks.
/// State converges toward a stepped target over successive blocks, advancing
/// by exactly one control-rate step (`up / controlRate`) per block.
@Test func tracksTowardTargetOverBlocks() {
let controlRate: Double = sampleRate / Double(blockSize)
// Choose up so the per-block step is exactly 0.25 → reaches 1.0 in 4 steps.
let stepPerBlock: Double = 0.25
let upRate: Double = controlRate * stepPerBlock
// Input is 0.0 on the first (init) block, then jumps to 1.0 thereafter.
let firstSerial: UInt64 = engine.segmentSerial
let input: Closure = Closure { graph, _ in
graph.engine.segmentSerial == firstSerial ? 0.0 : 1.0
}
let gen: Slew.Control = Slew.Control(input: input, up: upRate, dn: upRate)
// Block 1: initializes to first input value 0.0.
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(gen.previousOutputValue == 0.0)
// Blocks 2..5: input target 1.0, advancing 0.25 per block.
let expected: [Double] = [0.25, 0.5, 0.75, 1.0]
for step: Double in expected {
advanceBlock(engine)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(abs(gen.previousOutputValue - step) < 1e-12,
"expected \(step) got \(gen.previousOutputValue)")
}
}
/// floatValue returns previousOutputValue.
@Test func floatValueReturnsPreviousOutputValue() {
let gen: Slew.Control = Slew.Control(input: 0.5)
#expect(gen.floatValue(graph: graph) == gen.previousOutputValue)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
#expect(gen.floatValue(graph: graph) == gen.previousOutputValue)
}
/// Fan-out: two calls same segment return identical first channel.
@Test func fanOut() {
let gen: Slew.Control = Slew.Control(input: 0.3, up: 100.0, dn: 100.0)
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
for i: Int in 0..<blockSize {
#expect(out1[0][i] == out2[0][i])
}
}
/// Sub-block bypass: second call in same segment is cache hit, state not re-advanced.
@Test func subBlockBypassCacheHit() {
let gen: Slew.Control = Slew.Control(input: 0.5, up: 1000.0, dn: 1000.0)
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let stateAfterFirst: Double = gen.previousOutputValue
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
// State must not have advanced.
#expect(gen.previousOutputValue == stateAfterFirst)
for i: Int in 0..<blockSize {
#expect(out1[0][i] == out2[0][i])
}
}
/// mul/add: output is original*2+1.
@Test func mulAdd() {
// Use a constant input so base and scaled start from the same value.
let genBase: Slew.Control = Slew.Control(input: 0.25, up: 10000.0, dn: 10000.0)
let genScaled: Slew.Control = Slew.Control(input: 0.25, up: 10000.0, dn: 10000.0, mul: 2.0, add: 1.0)
let base: [[Double]] = genBase.calculatedSamples(graph: graph, count: blockSize)
let scaled: [[Double]] = genScaled.calculatedSamples(graph: graph, count: blockSize)
// Both init to 0.25, but scaled has mul/add applied.
let expectedSample0: Double = base[0][0] * 2.0 + 1.0
#expect(abs(scaled[0][0] - expectedSample0) < 1e-12,
"mulAdd sample 0: expected \(expectedSample0) got \(scaled[0][0])")
}
}

Some files were not shown because too many files have changed in this diff Show More